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