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, SourceRange)>),
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            Ok(TaggedEdgeInputs::Tags(tags_with_source))
118        }
119        (None, None) => Err(KclError::new_semantic(KclErrorDetails::new(
120            missing_args_message.to_owned(),
121            vec![args.source_range],
122        ))),
123    }
124}
125
126/// Create fillets on tagged paths.
127pub async fn fillet(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
128    let solid: Box<Solid> = args.get_unlabeled_kw_arg("solid", &RuntimeType::solid(), exec_state)?;
129    let radius: TyF64 = args.get_kw_arg("radius", &RuntimeType::length(), exec_state)?;
130    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
131    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
132    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
133    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
134    let edge_cut_number: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
135    let edge_cut_version: EdgeCutVersion = edge_cut_number
136        .map(|num| {
137            num.try_into().map_err(|()| {
138                KclError::new_semantic(KclErrorDetails::new(
139                    format!("{} is not a version of the Zoo edge cut algorithm", num),
140                    vec![args.source_range],
141                ))
142            })
143        })
144        .transpose()?
145        .unwrap_or_default();
146
147    // Edge specifiers are object-shaped payloads, so there is no narrow RuntimeType for them yet.
148    // Keep this broad at the boundary and validate the shape in parse_tagged_edge_inputs.
149    let edge_refs: Option<Vec<KclValue>> = args.get_kw_arg_opt("edges", &RuntimeType::any_array(), exec_state)?;
150    let tags = args.kw_arg_edge_array_and_source_opt("tags")?;
151
152    let edge_inputs = parse_tagged_edge_inputs(
153        edge_refs,
154        tags,
155        Some(solid.as_ref()),
156        exec_state,
157        &args,
158        "You must provide either 'tags' or 'edges' to fillet edges",
159        "You must provide either 'tags' or 'edges' to fillet edges, not both",
160    )
161    .await?;
162
163    match edge_inputs {
164        TaggedEdgeInputs::EngineRefs(edge_refs) => {
165            let params = FilletEdgeRefParams {
166                radius,
167                tolerance,
168                csg_algorithm,
169                edge_cut_version,
170                tag,
171            };
172            let value = inner_fillet_with_engine_refs(solid, edge_refs, params, exec_state, args).await?;
173            Ok(KclValue::Solid { value })
174        }
175        TaggedEdgeInputs::Tags(tags) => {
176            let value = inner_fillet(
177                solid,
178                radius,
179                tags,
180                tolerance,
181                csg_algorithm,
182                tag,
183                edge_cut_version,
184                exec_state,
185                args,
186            )
187            .await?;
188            Ok(KclValue::Solid { value })
189        }
190    }
191}
192
193#[allow(clippy::too_many_arguments)]
194async fn inner_fillet(
195    solid: Box<Solid>,
196    radius: TyF64,
197    tags: Vec<(EdgeReference, SourceRange)>,
198    tolerance: Option<TyF64>,
199    csg_algorithm: CsgAlgorithm,
200    tag: Option<TagNode>,
201    edge_cut_version: EdgeCutVersion,
202    exec_state: &mut ExecState,
203    args: Args,
204) -> Result<Box<Solid>, KclError> {
205    // If you try and tag multiple edges with a tagged fillet, we want to return an
206    // error to the user that they can only tag one edge at a time.
207    if tag.is_some() && tags.len() > 1 {
208        return Err(KclError::new_type(KclErrorDetails {
209            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(),
210            source_ranges: vec![args.source_range],
211            backtrace: Default::default(),
212        }));
213    }
214    if tags.is_empty() {
215        return Err(KclError::new_semantic(KclErrorDetails {
216            source_ranges: vec![args.source_range],
217            message: "You must fillet at least one tag".to_owned(),
218            backtrace: Default::default(),
219        }));
220    }
221
222    let mut solid = solid.clone();
223    let mut edge_ids = Vec::new();
224    let mut tag_entries: Vec<crate::execution::DirectTagFilletTagEntry> = Vec::new();
225    for (edge_ref, source_range) in &tags {
226        let ids = edge_ref.get_all_engine_ids(exec_state, &args)?;
227        edge_ids.extend(ids.iter().copied());
228        let tag_identifier = match edge_ref {
229            EdgeReference::Tag(t) => t.value.clone(),
230            EdgeReference::Uuid(_) => String::new(),
231        };
232        for edge_id in ids {
233            if let Ok(face_ids) = super::edge::get_face_ids_for_edge(exec_state, solid.id, edge_id, &args).await
234                && let [a, b] = face_ids.as_slice()
235            {
236                if !tag_identifier.is_empty() {
237                    tag_entries.push(crate::execution::DirectTagFilletTagEntry {
238                        tag_identifier: tag_identifier.clone(),
239                        edge_id,
240                        face_ids: [*a, *b],
241                    });
242                } else {
243                    exec_state.record_edge_refactor_meta_from_pending(edge_id, *source_range, [*a, *b]);
244                }
245            }
246        }
247    }
248    if !tag_entries.is_empty() {
249        exec_state.record_direct_tag_fillet_meta(crate::execution::DirectTagFilletMeta {
250            call_source_range: args.source_range,
251            tags: tag_entries,
252        });
253    }
254
255    let id = exec_state.next_uuid();
256    let mut extra_face_ids = Vec::new();
257    let num_extra_ids = edge_ids.len() - 1;
258    for _ in 0..num_extra_ids {
259        extra_face_ids.push(exec_state.next_uuid());
260    }
261    exec_state
262        .batch_end_cmd(
263            ModelingCmdMeta::from_args_id(exec_state, &args, id),
264            ModelingCmd::from(
265                mcmd::Solid3dCutEdges::builder()
266                    .use_legacy(csg_algorithm.is_legacy())
267                    .edge_ids(edge_ids.clone())
268                    .extra_face_ids(extra_face_ids)
269                    .strategy(Default::default())
270                    .object_id(solid.id)
271                    .version(edge_cut_version)
272                    .tolerance(LengthUnit(
273                        tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
274                    ))
275                    .cut_type(CutTypeV2::Fillet {
276                        radius: LengthUnit(radius.to_mm()),
277                        second_length: None,
278                    })
279                    .build(),
280            ),
281        )
282        .await?;
283
284    let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Fillet {
285        id,
286        edge_id,
287        radius: radius.clone(),
288        tag: Box::new(tag.clone()),
289    });
290    solid.edge_cuts.extend(new_edge_cuts);
291
292    if let Some(ref tag) = tag {
293        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
294            face_id: id,
295            tag: Some(tag.clone()),
296            geo_meta: GeoMeta {
297                id,
298                metadata: args.source_range.into(),
299            },
300        }));
301    }
302
303    Ok(solid)
304}
305
306struct FilletEdgeRefParams {
307    radius: TyF64,
308    tolerance: Option<TyF64>,
309    csg_algorithm: CsgAlgorithm,
310    edge_cut_version: EdgeCutVersion,
311    tag: Option<TagNode>,
312}
313
314async fn inner_fillet_with_engine_refs(
315    solid: Box<Solid>,
316    edge_references: Vec<kcmc::shared::EdgeSpecifier>,
317    params: FilletEdgeRefParams,
318    exec_state: &mut ExecState,
319    args: Args,
320) -> Result<Box<Solid>, KclError> {
321    if edge_references.is_empty() {
322        return Err(KclError::new_semantic(KclErrorDetails {
323            source_ranges: vec![args.source_range],
324            message: "You must provide at least one edge".to_owned(),
325            backtrace: Default::default(),
326        }));
327    }
328
329    if params.tag.is_some() && edge_references.len() > 1 {
330        return Err(KclError::new_type(KclErrorDetails {
331            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(),
332            source_ranges: vec![args.source_range],
333            backtrace: Default::default(),
334        }));
335    }
336
337    let mut solid = solid.clone();
338
339    let id = exec_state.next_uuid();
340    let num_extra_ids = edge_references.len().saturating_sub(1);
341    let mut extra_face_ids = Vec::with_capacity(num_extra_ids);
342    for _ in 0..num_extra_ids {
343        extra_face_ids.push(exec_state.next_uuid());
344    }
345
346    exec_state
347        .batch_end_cmd(
348            ModelingCmdMeta::from_args_id(exec_state, &args, id),
349            ModelingCmd::from(
350                mcmd::Solid3dCutEdgeReferences::builder()
351                    .object_id(solid.id)
352                    .edges_references(edge_references.clone())
353                    .cut_type(CutTypeV2::Fillet {
354                        radius: LengthUnit(params.radius.to_mm()),
355                        second_length: None,
356                    })
357                    .tolerance(LengthUnit(
358                        params
359                            .tolerance
360                            .as_ref()
361                            .map(|t| t.to_mm())
362                            .unwrap_or(DEFAULT_TOLERANCE_MM),
363                    ))
364                    .strategy(Default::default())
365                    .extra_face_ids(extra_face_ids)
366                    .use_legacy(params.csg_algorithm.is_legacy())
367                    .version(params.edge_cut_version)
368                    .build(),
369            ),
370        )
371        .await?;
372
373    solid.pending_edge_cut_ids.push(id);
374
375    if let Some(ref tag) = params.tag {
376        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
377            face_id: id,
378            tag: Some(tag.clone()),
379            geo_meta: GeoMeta {
380                id,
381                metadata: args.source_range.into(),
382            },
383        }));
384    }
385
386    Ok(solid)
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    #[test]
394    fn test_validate_unique() {
395        let dup_a = SourceRange::from([1, 3, 0]);
396        let dup_b = SourceRange::from([10, 30, 0]);
397        // Two entries are duplicates (abc) with different source ranges.
398        let tags = vec![("abc", dup_a), ("abc", dup_b), ("def", SourceRange::from([2, 4, 0]))];
399        let actual = validate_unique(&tags);
400        // Both the duplicates should show up as errors, with both of the
401        // source ranges they correspond to.
402        // But the unique source range 'def' should not.
403        let expected = vec![dup_a, dup_b];
404        assert_eq!(actual.err().unwrap().source_ranges(), expected);
405    }
406}