1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
//! Standard library fillets.
use anyhow::Result;
use derive_docs::stdlib;
use kcmc::{
each_cmd as mcmd, length_unit::LengthUnit, ok_response::OkModelingCmdResponse, shared::CutType,
websocket::OkWebSocketResponseData, ModelingCmd,
};
use kittycad_modeling_cmds as kcmc;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
ast::types::TagDeclarator,
errors::{KclError, KclErrorDetails},
executor::{
EdgeCut, ExecState, ExtrudeGroup, ExtrudeSurface, FilletSurface, GeoMeta, KclValue, TagIdentifier, UserVal,
},
settings::types::UnitLength,
std::Args,
};
/// Data for fillets.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct FilletData {
/// The radius of the fillet.
pub radius: f64,
/// The tags of the paths you want to fillet.
pub tags: Vec<EdgeReference>,
/// The tolerance for the fillet.
#[serde(default)]
pub tolerance: Option<f64>,
}
/// A tag or a uuid of an edge.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Eq, Ord, PartialOrd, Hash)]
#[ts(export)]
#[serde(untagged)]
pub enum EdgeReference {
/// A uuid of an edge.
Uuid(uuid::Uuid),
/// A tag of an edge.
Tag(Box<TagIdentifier>),
}
/// Create fillets on tagged paths.
pub async fn fillet(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let (data, extrude_group, tag): (FilletData, Box<ExtrudeGroup>, Option<TagDeclarator>) =
args.get_data_and_extrude_group_and_tag()?;
let extrude_group = inner_fillet(data, extrude_group, tag, exec_state, args).await?;
Ok(KclValue::ExtrudeGroup(extrude_group))
}
/// Blend a transitional edge along a tagged path, smoothing the sharp edge.
///
/// Fillet is similar in function and use to a chamfer, except
/// a chamfer will cut a sharp transition along an edge while fillet
/// will smoothly blend the transition.
///
/// ```no_run
/// const width = 20
/// const length = 10
/// const thickness = 1
/// const filletRadius = 2
///
/// const mountingPlateSketch = startSketchOn("XY")
/// |> startProfileAt([-width/2, -length/2], %)
/// |> lineTo([width/2, -length/2], %, $edge1)
/// |> lineTo([width/2, length/2], %, $edge2)
/// |> lineTo([-width/2, length/2], %, $edge3)
/// |> close(%, $edge4)
///
/// const mountingPlate = extrude(thickness, mountingPlateSketch)
/// |> fillet({
/// radius: filletRadius,
/// tags: [
/// getNextAdjacentEdge(edge1),
/// getNextAdjacentEdge(edge2),
/// getNextAdjacentEdge(edge3),
/// getNextAdjacentEdge(edge4)
/// ],
/// }, %)
/// ```
///
/// ```no_run
/// const width = 20
/// const length = 10
/// const thickness = 1
/// const filletRadius = 1
///
/// const mountingPlateSketch = startSketchOn("XY")
/// |> startProfileAt([-width/2, -length/2], %)
/// |> lineTo([width/2, -length/2], %, $edge1)
/// |> lineTo([width/2, length/2], %, $edge2)
/// |> lineTo([-width/2, length/2], %, $edge3)
/// |> close(%, $edge4)
///
/// const mountingPlate = extrude(thickness, mountingPlateSketch)
/// |> fillet({
/// radius: filletRadius,
/// tolerance: 0.000001,
/// tags: [
/// getNextAdjacentEdge(edge1),
/// getNextAdjacentEdge(edge2),
/// getNextAdjacentEdge(edge3),
/// getNextAdjacentEdge(edge4)
/// ],
/// }, %)
/// ```
#[stdlib {
name = "fillet",
}]
async fn inner_fillet(
data: FilletData,
extrude_group: Box<ExtrudeGroup>,
tag: Option<TagDeclarator>,
exec_state: &mut ExecState,
args: Args,
) -> Result<Box<ExtrudeGroup>, KclError> {
// Check if tags contains any duplicate values.
let mut tags = data.tags.clone();
tags.sort();
tags.dedup();
if tags.len() != data.tags.len() {
return Err(KclError::Type(KclErrorDetails {
message: "Duplicate tags are not allowed.".to_string(),
source_ranges: vec![args.source_range],
}));
}
let mut extrude_group = extrude_group.clone();
for edge_tag in data.tags {
let edge_id = match edge_tag {
EdgeReference::Uuid(uuid) => uuid,
EdgeReference::Tag(edge_tag) => args.get_tag_engine_info(exec_state, &edge_tag)?.id,
};
let id = uuid::Uuid::new_v4();
args.batch_end_cmd(
id,
ModelingCmd::from(mcmd::Solid3dFilletEdge {
edge_id,
object_id: extrude_group.id,
radius: LengthUnit(data.radius),
tolerance: LengthUnit(data.tolerance.unwrap_or(default_tolerance(&args.ctx.settings.units))),
cut_type: CutType::Fillet,
// We pass in the command id as the face id.
// So the resulting face of the fillet will be the same.
// This is because that's how most other endpoints work.
face_id: Some(id),
}),
)
.await?;
extrude_group.edge_cuts.push(EdgeCut::Fillet {
id,
edge_id,
radius: data.radius,
tag: Box::new(tag.clone()),
});
if let Some(ref tag) = tag {
extrude_group.value.push(ExtrudeSurface::Fillet(FilletSurface {
face_id: id,
tag: Some(tag.clone()),
geo_meta: GeoMeta {
id,
metadata: args.source_range.into(),
},
}));
}
}
Ok(extrude_group)
}
/// Get the opposite edge to the edge given.
pub async fn get_opposite_edge(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let tag: TagIdentifier = args.get_data()?;
let edge = inner_get_opposite_edge(tag, exec_state, args.clone()).await?;
Ok(KclValue::UserVal(UserVal {
value: serde_json::to_value(edge).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to convert Uuid to json: {}", e),
source_ranges: vec![args.source_range],
})
})?,
meta: vec![args.source_range.into()],
}))
}
/// Get the opposite edge to the edge given.
///
/// ```no_run
/// const exampleSketch = startSketchOn('XZ')
/// |> startProfileAt([0, 0], %)
/// |> line([10, 0], %)
/// |> angledLine({
/// angle: 60,
/// length: 10,
/// }, %)
/// |> angledLine({
/// angle: 120,
/// length: 10,
/// }, %)
/// |> line([-10, 0], %)
/// |> angledLine({
/// angle: 240,
/// length: 10,
/// }, %, $referenceEdge)
/// |> close(%)
///
/// const example = extrude(5, exampleSketch)
/// |> fillet({
/// radius: 3,
/// tags: [getOppositeEdge(referenceEdge)],
/// }, %)
/// ```
#[stdlib {
name = "getOppositeEdge",
}]
async fn inner_get_opposite_edge(tag: TagIdentifier, exec_state: &mut ExecState, args: Args) -> Result<Uuid, KclError> {
if args.ctx.is_mock {
return Ok(Uuid::new_v4());
}
let face_id = args.get_adjacent_face_to_tag(exec_state, &tag, false).await?;
let tagged_path = args.get_tag_engine_info(exec_state, &tag)?;
let resp = args
.send_modeling_cmd(
uuid::Uuid::new_v4(),
ModelingCmd::from(mcmd::Solid3dGetOppositeEdge {
edge_id: tagged_path.id,
object_id: tagged_path.sketch_group,
face_id,
}),
)
.await?;
let OkWebSocketResponseData::Modeling {
modeling_response: OkModelingCmdResponse::Solid3dGetOppositeEdge(opposite_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails {
message: format!("mcmd::Solid3dGetOppositeEdge response was not as expected: {:?}", resp),
source_ranges: vec![args.source_range],
}));
};
Ok(opposite_edge.edge)
}
/// Get the next adjacent edge to the edge given.
pub async fn get_next_adjacent_edge(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let tag: TagIdentifier = args.get_data()?;
let edge = inner_get_next_adjacent_edge(tag, exec_state, args.clone()).await?;
Ok(KclValue::UserVal(UserVal {
value: serde_json::to_value(edge).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to convert Uuid to json: {}", e),
source_ranges: vec![args.source_range],
})
})?,
meta: vec![args.source_range.into()],
}))
}
/// Get the next adjacent edge to the edge given.
///
/// ```no_run
/// const exampleSketch = startSketchOn('XZ')
/// |> startProfileAt([0, 0], %)
/// |> line([10, 0], %)
/// |> angledLine({
/// angle: 60,
/// length: 10,
/// }, %)
/// |> angledLine({
/// angle: 120,
/// length: 10,
/// }, %)
/// |> line([-10, 0], %)
/// |> angledLine({
/// angle: 240,
/// length: 10,
/// }, %, $referenceEdge)
/// |> close(%)
///
/// const example = extrude(5, exampleSketch)
/// |> fillet({
/// radius: 3,
/// tags: [getNextAdjacentEdge(referenceEdge)],
/// }, %)
/// ```
#[stdlib {
name = "getNextAdjacentEdge",
}]
async fn inner_get_next_adjacent_edge(
tag: TagIdentifier,
exec_state: &mut ExecState,
args: Args,
) -> Result<Uuid, KclError> {
if args.ctx.is_mock {
return Ok(Uuid::new_v4());
}
let face_id = args.get_adjacent_face_to_tag(exec_state, &tag, false).await?;
let tagged_path = args.get_tag_engine_info(exec_state, &tag)?;
let resp = args
.send_modeling_cmd(
uuid::Uuid::new_v4(),
ModelingCmd::from(mcmd::Solid3dGetNextAdjacentEdge {
edge_id: tagged_path.id,
object_id: tagged_path.sketch_group,
face_id,
}),
)
.await?;
let OkWebSocketResponseData::Modeling {
modeling_response: OkModelingCmdResponse::Solid3dGetNextAdjacentEdge(adjacent_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails {
message: format!(
"mcmd::Solid3dGetNextAdjacentEdge response was not as expected: {:?}",
resp
),
source_ranges: vec![args.source_range],
}));
};
adjacent_edge.edge.ok_or_else(|| {
KclError::Type(KclErrorDetails {
message: format!("No edge found next adjacent to tag: `{}`", tag.value),
source_ranges: vec![args.source_range],
})
})
}
/// Get the previous adjacent edge to the edge given.
pub async fn get_previous_adjacent_edge(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let tag: TagIdentifier = args.get_data()?;
let edge = inner_get_previous_adjacent_edge(tag, exec_state, args.clone()).await?;
Ok(KclValue::UserVal(UserVal {
value: serde_json::to_value(edge).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to convert Uuid to json: {}", e),
source_ranges: vec![args.source_range],
})
})?,
meta: vec![args.source_range.into()],
}))
}
/// Get the previous adjacent edge to the edge given.
///
/// ```no_run
/// const exampleSketch = startSketchOn('XZ')
/// |> startProfileAt([0, 0], %)
/// |> line([10, 0], %)
/// |> angledLine({
/// angle: 60,
/// length: 10,
/// }, %)
/// |> angledLine({
/// angle: 120,
/// length: 10,
/// }, %)
/// |> line([-10, 0], %)
/// |> angledLine({
/// angle: 240,
/// length: 10,
/// }, %, $referenceEdge)
/// |> close(%)
///
/// const example = extrude(5, exampleSketch)
/// |> fillet({
/// radius: 3,
/// tags: [getPreviousAdjacentEdge(referenceEdge)],
/// }, %)
/// ```
#[stdlib {
name = "getPreviousAdjacentEdge",
}]
async fn inner_get_previous_adjacent_edge(
tag: TagIdentifier,
exec_state: &mut ExecState,
args: Args,
) -> Result<Uuid, KclError> {
if args.ctx.is_mock {
return Ok(Uuid::new_v4());
}
let face_id = args.get_adjacent_face_to_tag(exec_state, &tag, false).await?;
let tagged_path = args.get_tag_engine_info(exec_state, &tag)?;
let resp = args
.send_modeling_cmd(
uuid::Uuid::new_v4(),
ModelingCmd::from(mcmd::Solid3dGetPrevAdjacentEdge {
edge_id: tagged_path.id,
object_id: tagged_path.sketch_group,
face_id,
}),
)
.await?;
let OkWebSocketResponseData::Modeling {
modeling_response: OkModelingCmdResponse::Solid3dGetPrevAdjacentEdge(adjacent_edge),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails {
message: format!(
"mcmd::Solid3dGetPrevAdjacentEdge response was not as expected: {:?}",
resp
),
source_ranges: vec![args.source_range],
}));
};
adjacent_edge.edge.ok_or_else(|| {
KclError::Type(KclErrorDetails {
message: format!("No edge found previous adjacent to tag: `{}`", tag.value),
source_ranges: vec![args.source_range],
})
})
}
pub(crate) fn default_tolerance(units: &UnitLength) -> f64 {
match units {
UnitLength::Mm => 0.0000001,
UnitLength::Cm => 0.0000001,
UnitLength::In => 0.0000001,
UnitLength::Ft => 0.0001,
UnitLength::Yd => 0.001,
UnitLength::M => 0.001,
}
}