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::ModelingCmdMeta;
26use crate::execution::Solid;
27use crate::execution::TagIdentifier;
28use crate::execution::types::RuntimeType;
29use crate::parsing::ast::types::TagNode;
30use crate::std::Args;
31use crate::std::csg::CsgAlgorithm;
32
33/// A tag or a uuid of an edge.
34#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]
35#[serde(untagged)]
36pub enum EdgeReference {
37    /// A uuid of an edge.
38    Uuid(uuid::Uuid),
39    /// A tag of an edge.
40    Tag(Box<TagIdentifier>),
41}
42
43impl EdgeReference {
44    pub fn get_engine_id(&self, exec_state: &mut ExecState, args: &Args) -> Result<uuid::Uuid, KclError> {
45        match self {
46            EdgeReference::Uuid(uuid) => Ok(*uuid),
47            EdgeReference::Tag(tag) => Ok(args.get_tag_engine_info(exec_state, tag)?.id),
48        }
49    }
50
51    /// Get all engine IDs for this edge reference.
52    /// For region-mapped tags, returns multiple IDs (one per region segment).
53    pub fn get_all_engine_ids(&self, exec_state: &mut ExecState, args: &Args) -> Result<Vec<uuid::Uuid>, KclError> {
54        match self {
55            EdgeReference::Uuid(uuid) => Ok(vec![*uuid]),
56            EdgeReference::Tag(tag) => {
57                let infos = tag.get_all_cur_info();
58                if infos.is_empty() {
59                    // Fallback to single ID lookup (checks the stack).
60                    Ok(vec![args.get_tag_engine_info(exec_state, tag)?.id])
61                } else {
62                    Ok(infos.iter().map(|i| i.id).collect())
63                }
64            }
65        }
66    }
67}
68
69pub(super) fn validate_unique<T: Eq + std::hash::Hash>(tags: &[(T, SourceRange)]) -> Result<(), KclError> {
70    // Check if tags contains any duplicate values.
71    let mut tag_counts: IndexMap<&T, Vec<SourceRange>> = Default::default();
72    for tag in tags {
73        tag_counts.entry(&tag.0).or_insert(Vec::new()).push(tag.1);
74    }
75    let mut duplicate_tags_source = Vec::new();
76    for (_tag, count) in tag_counts {
77        if count.len() > 1 {
78            duplicate_tags_source.extend(count)
79        }
80    }
81    if !duplicate_tags_source.is_empty() {
82        return Err(KclError::new_type(KclErrorDetails::new(
83            "The same edge ID is being referenced multiple times, which is not allowed. Please select a different edge"
84                .to_string(),
85            duplicate_tags_source,
86        )));
87    }
88    Ok(())
89}
90
91pub(super) enum TaggedEdgeInputs {
92    Tags(Vec<EdgeReference>),
93    EngineRefs(Vec<kcmc::shared::EdgeSpecifier>),
94}
95
96pub(super) async fn parse_tagged_edge_inputs(
97    edge_refs: Option<Vec<KclValue>>,
98    tags_with_source: Option<Vec<(EdgeReference, SourceRange)>>,
99    solid: Option<&Solid>,
100    exec_state: &mut ExecState,
101    args: &Args,
102    missing_args_message: &str,
103    both_args_message: &str,
104) -> Result<TaggedEdgeInputs, KclError> {
105    match (edge_refs, tags_with_source) {
106        (Some(_), Some(_)) => Err(KclError::new_semantic(KclErrorDetails::new(
107            both_args_message.to_owned(),
108            vec![args.source_range],
109        ))),
110        (Some(edge_refs), None) => {
111            let edge_refs_parsed =
112                super::edge::parse_edge_refs_to_references(edge_refs, solid, exec_state, args).await?;
113            Ok(TaggedEdgeInputs::EngineRefs(edge_refs_parsed))
114        }
115        (None, Some(tags_with_source)) => {
116            validate_unique(&tags_with_source)?;
117            let tags = tags_with_source.into_iter().map(|item| item.0).collect();
118            Ok(TaggedEdgeInputs::Tags(tags))
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_default();
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#[allow(clippy::too_many_arguments)]
195async fn inner_fillet(
196    solid: Box<Solid>,
197    radius: TyF64,
198    tags: Vec<EdgeReference>,
199    tolerance: Option<TyF64>,
200    csg_algorithm: CsgAlgorithm,
201    tag: Option<TagNode>,
202    edge_cut_version: EdgeCutVersion,
203    exec_state: &mut ExecState,
204    args: Args,
205) -> Result<Box<Solid>, KclError> {
206    // If you try and tag multiple edges with a tagged fillet, we want to return an
207    // error to the user that they can only tag one edge at a time.
208    if tag.is_some() && tags.len() > 1 {
209        return Err(KclError::new_type(KclErrorDetails {
210            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(),
211            source_ranges: vec![args.source_range],
212            backtrace: Default::default(),
213        }));
214    }
215    if tags.is_empty() {
216        return Err(KclError::new_semantic(KclErrorDetails {
217            source_ranges: vec![args.source_range],
218            message: "You must fillet at least one tag".to_owned(),
219            backtrace: Default::default(),
220        }));
221    }
222
223    let mut solid = solid.clone();
224    let edge_ids = tags
225        .into_iter()
226        .map(|edge_tag| edge_tag.get_all_engine_ids(exec_state, &args))
227        .try_fold(Vec::new(), |mut acc, item| match item {
228            Ok(ids) => {
229                acc.extend(ids);
230                Ok(acc)
231            }
232            Err(e) => Err(e),
233        })?;
234
235    let id = exec_state.next_uuid();
236    let mut extra_face_ids = Vec::new();
237    let num_extra_ids = edge_ids.len() - 1;
238    for _ in 0..num_extra_ids {
239        extra_face_ids.push(exec_state.next_uuid());
240    }
241    exec_state
242        .batch_end_cmd(
243            ModelingCmdMeta::from_args_id(exec_state, &args, id),
244            ModelingCmd::from(
245                mcmd::Solid3dCutEdges::builder()
246                    .use_legacy(csg_algorithm.is_legacy())
247                    .edge_ids(edge_ids.clone())
248                    .extra_face_ids(extra_face_ids)
249                    .strategy(Default::default())
250                    .object_id(solid.id)
251                    .version(edge_cut_version)
252                    .tolerance(LengthUnit(
253                        tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
254                    ))
255                    .cut_type(CutTypeV2::Fillet {
256                        radius: LengthUnit(radius.to_mm()),
257                        second_length: None,
258                    })
259                    .build(),
260            ),
261        )
262        .await?;
263
264    let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Fillet {
265        id,
266        edge_id,
267        radius: radius.clone(),
268        tag: Box::new(tag.clone()),
269    });
270    solid.edge_cuts.extend(new_edge_cuts);
271
272    if let Some(ref tag) = tag {
273        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
274            face_id: id,
275            tag: Some(tag.clone()),
276            geo_meta: GeoMeta {
277                id,
278                metadata: args.source_range.into(),
279            },
280        }));
281    }
282
283    Ok(solid)
284}
285
286struct FilletEdgeRefParams {
287    radius: TyF64,
288    tolerance: Option<TyF64>,
289    csg_algorithm: CsgAlgorithm,
290    edge_cut_version: EdgeCutVersion,
291    tag: Option<TagNode>,
292}
293
294async fn inner_fillet_with_engine_refs(
295    solid: Box<Solid>,
296    edge_references: Vec<kcmc::shared::EdgeSpecifier>,
297    params: FilletEdgeRefParams,
298    exec_state: &mut ExecState,
299    args: Args,
300) -> Result<Box<Solid>, KclError> {
301    if edge_references.is_empty() {
302        return Err(KclError::new_semantic(KclErrorDetails {
303            source_ranges: vec![args.source_range],
304            message: "You must provide at least one edge".to_owned(),
305            backtrace: Default::default(),
306        }));
307    }
308
309    if params.tag.is_some() && edge_references.len() > 1 {
310        return Err(KclError::new_type(KclErrorDetails {
311            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(),
312            source_ranges: vec![args.source_range],
313            backtrace: Default::default(),
314        }));
315    }
316
317    let mut solid = solid.clone();
318
319    let id = exec_state.next_uuid();
320    let num_extra_ids = edge_references.len().saturating_sub(1);
321    let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
322    for _ in 0..num_extra_ids {
323        extra_face_ids.push(exec_state.next_uuid());
324    }
325
326    exec_state
327        .batch_end_cmd(
328            ModelingCmdMeta::from_args_id(exec_state, &args, id),
329            ModelingCmd::from(
330                mcmd::Solid3dCutEdgeReferences::builder()
331                    .object_id(solid.id)
332                    .edges_references(edge_references.clone())
333                    .cut_type(CutTypeV2::Fillet {
334                        radius: LengthUnit(params.radius.to_mm()),
335                        second_length: None,
336                    })
337                    .tolerance(LengthUnit(
338                        params
339                            .tolerance
340                            .as_ref()
341                            .map(|t| t.to_mm())
342                            .unwrap_or(DEFAULT_TOLERANCE_MM),
343                    ))
344                    .strategy(Default::default())
345                    .extra_face_ids(extra_face_ids)
346                    .use_legacy(params.csg_algorithm.is_legacy())
347                    .version(params.edge_cut_version)
348                    .build(),
349            ),
350        )
351        .await?;
352
353    solid.pending_edge_cut_ids.push(id);
354
355    if let Some(ref tag) = params.tag {
356        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
357            face_id: id,
358            tag: Some(tag.clone()),
359            geo_meta: GeoMeta {
360                id,
361                metadata: args.source_range.into(),
362            },
363        }));
364    }
365
366    Ok(solid)
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_validate_unique() {
375        let dup_a = SourceRange::from([1, 3, 0]);
376        let dup_b = SourceRange::from([10, 30, 0]);
377        // Two entries are duplicates (abc) with different source ranges.
378        let tags = vec![("abc", dup_a), ("abc", dup_b), ("def", SourceRange::from([2, 4, 0]))];
379        let actual = validate_unique(&tags);
380        // Both the duplicates should show up as errors, with both of the
381        // source ranges they correspond to.
382        // But the unique source range 'def' should not.
383        let expected = vec![dup_a, dup_b];
384        assert_eq!(actual.err().unwrap().source_ranges(), expected);
385    }
386}