Skip to main content

kcl_lib/std/
fillet.rs

1//! Standard library fillets.
2
3use anyhow::Result;
4use indexmap::IndexMap;
5use kcmc::ModelingCmd;
6use kcmc::each_cmd as mcmd;
7use kcmc::length_unit::LengthUnit;
8use kcmc::shared::CutTypeV2;
9use kcmc::shared::EdgeCutVersion;
10use kittycad_modeling_cmds as kcmc;
11use serde::Deserialize;
12use serde::Serialize;
13
14use super::DEFAULT_TOLERANCE_MM;
15use super::args::TyF64;
16use crate::SourceRange;
17use crate::errors::KclError;
18use crate::errors::KclErrorDetails;
19use crate::execution::EdgeCut;
20use crate::execution::ExecState;
21use crate::execution::ExtrudeSurface;
22use crate::execution::FilletSurface;
23use crate::execution::GeoMeta;
24use crate::execution::KclValue;
25use crate::execution::KclVersion;
26use crate::execution::ModelingCmdMeta;
27use crate::execution::Solid;
28use crate::execution::TagIdentifier;
29use crate::execution::types::RuntimeType;
30use crate::parsing::ast::types::TagNode;
31use crate::std::Args;
32use crate::std::csg::CsgAlgorithm;
33
34/// A tag or a uuid of an edge.
35#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]
36#[serde(untagged)]
37pub enum EdgeReference {
38    /// A uuid of an edge.
39    Uuid(uuid::Uuid),
40    /// A tag of an edge.
41    Tag(Box<TagIdentifier>),
42}
43
44impl EdgeReference {
45    pub fn get_engine_id(&self, exec_state: &mut ExecState, args: &Args) -> Result<uuid::Uuid, KclError> {
46        match self {
47            EdgeReference::Uuid(uuid) => Ok(*uuid),
48            EdgeReference::Tag(tag) => Ok(args.get_tag_engine_info(exec_state, tag)?.id),
49        }
50    }
51
52    /// Get all engine IDs for this edge reference.
53    /// For region-mapped tags, returns multiple IDs (one per region segment).
54    pub fn get_all_engine_ids(&self, exec_state: &mut ExecState, args: &Args) -> Result<Vec<uuid::Uuid>, KclError> {
55        match self {
56            EdgeReference::Uuid(uuid) => Ok(vec![*uuid]),
57            EdgeReference::Tag(tag) => {
58                let infos = tag.get_all_cur_info();
59                if infos.is_empty() {
60                    // Fallback to single ID lookup (checks the stack).
61                    Ok(vec![args.get_tag_engine_info(exec_state, tag)?.id])
62                } else {
63                    Ok(infos.iter().map(|i| i.id).collect())
64                }
65            }
66        }
67    }
68}
69
70pub(super) fn validate_unique<T: Eq + std::hash::Hash>(tags: &[(T, SourceRange)]) -> Result<(), KclError> {
71    // Check if tags contains any duplicate values.
72    let mut tag_counts: IndexMap<&T, Vec<SourceRange>> = Default::default();
73    for tag in tags {
74        tag_counts.entry(&tag.0).or_insert(Vec::new()).push(tag.1);
75    }
76    let mut duplicate_tags_source = Vec::new();
77    for (_tag, count) in tag_counts {
78        if count.len() > 1 {
79            duplicate_tags_source.extend(count)
80        }
81    }
82    if !duplicate_tags_source.is_empty() {
83        return Err(KclError::new_type(KclErrorDetails::new(
84            "The same edge ID is being referenced multiple times, which is not allowed. Please select a different edge"
85                .to_string(),
86            duplicate_tags_source,
87        )));
88    }
89    Ok(())
90}
91
92pub(super) enum TaggedEdgeInputs {
93    Tags(Vec<(EdgeReference, SourceRange)>),
94    EngineRefs(Vec<kcmc::shared::EdgeSpecifier>),
95}
96
97pub(super) async fn parse_tagged_edge_inputs(
98    edge_refs: Option<Vec<KclValue>>,
99    tags_with_source: Option<Vec<(EdgeReference, SourceRange)>>,
100    solid: Option<&Solid>,
101    exec_state: &mut ExecState,
102    args: &Args,
103    missing_args_message: &str,
104    both_args_message: &str,
105) -> Result<TaggedEdgeInputs, KclError> {
106    match (edge_refs, tags_with_source) {
107        (Some(_), Some(_)) => Err(KclError::new_semantic(KclErrorDetails::new(
108            both_args_message.to_owned(),
109            vec![args.source_range],
110        ))),
111        (Some(edge_refs), None) => {
112            let edge_refs_parsed =
113                super::edge::parse_edge_refs_to_references(edge_refs, solid, exec_state, args).await?;
114            Ok(TaggedEdgeInputs::EngineRefs(edge_refs_parsed))
115        }
116        (None, Some(tags_with_source)) => {
117            validate_unique(&tags_with_source)?;
118            Ok(TaggedEdgeInputs::Tags(tags_with_source))
119        }
120        (None, None) => Err(KclError::new_semantic(KclErrorDetails::new(
121            missing_args_message.to_owned(),
122            vec![args.source_range],
123        ))),
124    }
125}
126
127/// Create fillets on tagged paths.
128pub async fn fillet(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
129    let solid: Box<Solid> = args.get_unlabeled_kw_arg("solid", &RuntimeType::solid(), exec_state)?;
130    let radius: TyF64 = args.get_kw_arg("radius", &RuntimeType::length(), exec_state)?;
131    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
132    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
133    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
134    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
135    let edge_cut_number: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
136    let edge_cut_version: EdgeCutVersion = edge_cut_number
137        .map(|num| {
138            num.try_into().map_err(|()| {
139                KclError::new_semantic(KclErrorDetails::new(
140                    format!("{} is not a version of the Zoo edge cut algorithm", num),
141                    vec![args.source_range],
142                ))
143            })
144        })
145        .transpose()?
146        .unwrap_or_else(|| default_edge_cut_version(exec_state.kcl_version()));
147
148    // Edge specifiers are object-shaped payloads, so there is no narrow RuntimeType for them yet.
149    // Keep this broad at the boundary and validate the shape in parse_tagged_edge_inputs.
150    let edge_refs: Option<Vec<KclValue>> = args.get_kw_arg_opt("edges", &RuntimeType::any_array(), exec_state)?;
151    let tags = args.kw_arg_edge_array_and_source_opt("tags")?;
152
153    let edge_inputs = parse_tagged_edge_inputs(
154        edge_refs,
155        tags,
156        Some(solid.as_ref()),
157        exec_state,
158        &args,
159        "You must provide either 'tags' or 'edges' to fillet edges",
160        "You must provide either 'tags' or 'edges' to fillet edges, not both",
161    )
162    .await?;
163
164    match edge_inputs {
165        TaggedEdgeInputs::EngineRefs(edge_refs) => {
166            let params = FilletEdgeRefParams {
167                radius,
168                tolerance,
169                csg_algorithm,
170                edge_cut_version,
171                tag,
172            };
173            let value = inner_fillet_with_engine_refs(solid, edge_refs, params, exec_state, args).await?;
174            Ok(KclValue::Solid { value })
175        }
176        TaggedEdgeInputs::Tags(tags) => {
177            let value = inner_fillet(
178                solid,
179                radius,
180                tags,
181                tolerance,
182                csg_algorithm,
183                tag,
184                edge_cut_version,
185                exec_state,
186                args,
187            )
188            .await?;
189            Ok(KclValue::Solid { value })
190        }
191    }
192}
193
194/// What version of the fillet/chamfer algorithm should this KCL version use?
195pub(super) fn default_edge_cut_version(kcl_version: KclVersion) -> EdgeCutVersion {
196    if kcl_version <= KclVersion::V2 {
197        EdgeCutVersion::V1
198    } else {
199        EdgeCutVersion::V2
200    }
201}
202
203#[allow(clippy::too_many_arguments)]
204async fn inner_fillet(
205    solid: Box<Solid>,
206    radius: TyF64,
207    tags: Vec<(EdgeReference, SourceRange)>,
208    tolerance: Option<TyF64>,
209    csg_algorithm: CsgAlgorithm,
210    tag: Option<TagNode>,
211    edge_cut_version: EdgeCutVersion,
212    exec_state: &mut ExecState,
213    args: Args,
214) -> Result<Box<Solid>, KclError> {
215    // If you try and tag multiple edges with a tagged fillet, we want to return an
216    // error to the user that they can only tag one edge at a time.
217    if tag.is_some() && tags.len() > 1 {
218        return Err(KclError::new_type(KclErrorDetails {
219            message: "You can only tag one edge at a time with a tagged fillet. Either delete the tag for the fillet fn if you don't need it OR separate into individual fillet functions for each tag.".to_string(),
220            source_ranges: vec![args.source_range],
221            backtrace: Default::default(),
222        }));
223    }
224    if tags.is_empty() {
225        return Err(KclError::new_semantic(KclErrorDetails {
226            source_ranges: vec![args.source_range],
227            message: "You must fillet at least one tag".to_owned(),
228            backtrace: Default::default(),
229        }));
230    }
231
232    let mut solid = solid.clone();
233    let mut edge_ids = Vec::new();
234    let mut tag_entries: Vec<crate::execution::DirectTagFilletTagEntry> = Vec::new();
235    for (edge_ref, source_range) in &tags {
236        let ids = edge_ref.get_all_engine_ids(exec_state, &args)?;
237        edge_ids.extend(ids.iter().copied());
238        let tag_identifier = match edge_ref {
239            EdgeReference::Tag(t) => t.value.clone(),
240            EdgeReference::Uuid(_) => String::new(),
241        };
242        for edge_id in ids {
243            if let Ok(face_ids) = super::edge::get_face_ids_for_edge(exec_state, solid.id, edge_id, &args).await
244                && let [a, b] = face_ids.as_slice()
245            {
246                if !tag_identifier.is_empty() {
247                    tag_entries.push(crate::execution::DirectTagFilletTagEntry {
248                        tag_identifier: tag_identifier.clone(),
249                        edge_id,
250                        face_ids: [*a, *b],
251                    });
252                } else {
253                    exec_state.record_edge_refactor_meta_from_pending(edge_id, *source_range, [*a, *b]);
254                }
255            }
256        }
257    }
258    if !tag_entries.is_empty() {
259        exec_state.record_direct_tag_fillet_meta(crate::execution::DirectTagFilletMeta {
260            call_source_range: args.source_range,
261            tags: tag_entries,
262        });
263    }
264
265    let id = exec_state.next_uuid();
266    let mut extra_face_ids = Vec::new();
267    let num_extra_ids = edge_ids.len() - 1;
268    for _ in 0..num_extra_ids {
269        extra_face_ids.push(exec_state.next_uuid());
270    }
271    exec_state
272        .batch_end_cmd(
273            ModelingCmdMeta::from_args_id(exec_state, &args, id),
274            ModelingCmd::from(
275                mcmd::Solid3dCutEdges::builder()
276                    .use_legacy(csg_algorithm.is_legacy())
277                    .edge_ids(edge_ids.clone())
278                    .extra_face_ids(extra_face_ids)
279                    .strategy(Default::default())
280                    .object_id(solid.id)
281                    .version(edge_cut_version)
282                    .tolerance(LengthUnit(
283                        tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
284                    ))
285                    .cut_type(CutTypeV2::Fillet {
286                        radius: LengthUnit(radius.to_mm()),
287                        second_length: None,
288                    })
289                    .build(),
290            ),
291        )
292        .await?;
293
294    let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Fillet {
295        id,
296        edge_id,
297        radius: radius.clone(),
298        tag: Box::new(tag.clone()),
299    });
300    solid.edge_cuts.extend(new_edge_cuts);
301
302    if let Some(ref tag) = tag {
303        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
304            face_id: id,
305            tag: Some(tag.clone()),
306            geo_meta: GeoMeta {
307                id,
308                metadata: args.source_range.into(),
309            },
310        }));
311    }
312
313    Ok(solid)
314}
315
316struct FilletEdgeRefParams {
317    radius: TyF64,
318    tolerance: Option<TyF64>,
319    csg_algorithm: CsgAlgorithm,
320    edge_cut_version: EdgeCutVersion,
321    tag: Option<TagNode>,
322}
323
324async fn inner_fillet_with_engine_refs(
325    solid: Box<Solid>,
326    edge_references: Vec<kcmc::shared::EdgeSpecifier>,
327    params: FilletEdgeRefParams,
328    exec_state: &mut ExecState,
329    args: Args,
330) -> Result<Box<Solid>, KclError> {
331    if edge_references.is_empty() {
332        return Err(KclError::new_semantic(KclErrorDetails {
333            source_ranges: vec![args.source_range],
334            message: "You must provide at least one edge".to_owned(),
335            backtrace: Default::default(),
336        }));
337    }
338
339    if params.tag.is_some() && edge_references.len() > 1 {
340        return Err(KclError::new_type(KclErrorDetails {
341            message: "You can only tag one edge at a time with a tagged fillet. Either delete the tag for the fillet fn if you don't need it OR separate into individual fillet functions for each edge.".to_string(),
342            source_ranges: vec![args.source_range],
343            backtrace: Default::default(),
344        }));
345    }
346
347    let mut solid = solid.clone();
348
349    let id = exec_state.next_uuid();
350    let num_extra_ids = edge_references.len().saturating_sub(1);
351    let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
352    for _ in 0..num_extra_ids {
353        extra_face_ids.push(exec_state.next_uuid());
354    }
355
356    exec_state
357        .batch_end_cmd(
358            ModelingCmdMeta::from_args_id(exec_state, &args, id),
359            ModelingCmd::from(
360                mcmd::Solid3dCutEdgeReferences::builder()
361                    .object_id(solid.id)
362                    .edges_references(edge_references.clone())
363                    .cut_type(CutTypeV2::Fillet {
364                        radius: LengthUnit(params.radius.to_mm()),
365                        second_length: None,
366                    })
367                    .tolerance(LengthUnit(
368                        params
369                            .tolerance
370                            .as_ref()
371                            .map(|t| t.to_mm())
372                            .unwrap_or(DEFAULT_TOLERANCE_MM),
373                    ))
374                    .strategy(Default::default())
375                    .extra_face_ids(extra_face_ids)
376                    .use_legacy(params.csg_algorithm.is_legacy())
377                    .version(params.edge_cut_version)
378                    .build(),
379            ),
380        )
381        .await?;
382
383    solid.pending_edge_cut_ids.push(id);
384
385    if let Some(ref tag) = params.tag {
386        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
387            face_id: id,
388            tag: Some(tag.clone()),
389            geo_meta: GeoMeta {
390                id,
391                metadata: args.source_range.into(),
392            },
393        }));
394    }
395
396    Ok(solid)
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use crate::execution::parse_execute;
403
404    /// Test what version of fillet each KCL version uses by default.
405    #[tokio::test(flavor = "multi_thread")]
406    async fn fillet_default_depends_on_kcl_version() {
407        assert_eq!(emitted_fillet_version("1.0", None).await, EdgeCutVersion::V1);
408        assert_eq!(emitted_fillet_version("2.0", None).await, EdgeCutVersion::V1);
409        assert_eq!(
410            emitted_fillet_version("\"3.0-preview\"", None).await,
411            EdgeCutVersion::V2
412        );
413    }
414
415    /// If the user chooses a fillet algorithm version, KCL should respect it,
416    /// and not use that KCL version's default fillet algorithm version.
417    #[tokio::test(flavor = "multi_thread")]
418    async fn explicit_fillet_version_overrides_kcl_default() {
419        assert_eq!(
420            emitted_fillet_version("\"3.0-preview\"", Some(1)).await,
421            EdgeCutVersion::V1
422        );
423    }
424
425    /// For a given KCL version, and optional `fillet(version = )` version,
426    /// show what fillet algorithm version the runtime sent to the engine.
427    async fn emitted_fillet_version(kcl_version: &str, explicit_version: Option<u32>) -> EdgeCutVersion {
428        let version_arg = explicit_version
429            .map(|version| format!(", version = {version}"))
430            .unwrap_or_default();
431        let code = format!(
432            r#"@settings(kclVersion = {kcl_version}, experimentalFeatures = allow)
433
434profile = startSketchOn(XY)
435  |> startProfile(at = [0, 0])
436  |> line(end = [10, 0], tag = $edge)
437  |> line(end = [0, 10])
438  |> line(end = [-10, 0])
439  |> close()
440solid = extrude(profile, length = 10)
441fillet(solid, tags = [edge], radius = 1{version_arg})
442"#
443        );
444
445        let result = parse_execute(&code).await.unwrap();
446        result
447            .root_module_artifact_commands()
448            .iter()
449            .find_map(|artifact_command| match &artifact_command.command {
450                ModelingCmd::Solid3dCutEdges(command) => Some(command.version),
451                _ => None,
452            })
453            .expect("fillet should emit a Solid3dCutEdges command")
454    }
455
456    #[test]
457    fn test_validate_unique() {
458        let dup_a = SourceRange::from([1, 3, 0]);
459        let dup_b = SourceRange::from([10, 30, 0]);
460        // Two entries are duplicates (abc) with different source ranges.
461        let tags = vec![("abc", dup_a), ("abc", dup_b), ("def", SourceRange::from([2, 4, 0]))];
462        let actual = validate_unique(&tags);
463        // Both the duplicates should show up as errors, with both of the
464        // source ranges they correspond to.
465        // But the unique source range 'def' should not.
466        let expected = vec![dup_a, dup_b];
467        assert_eq!(actual.err().unwrap().source_ranges(), expected);
468    }
469}