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::CutType;
9use kittycad_modeling_cmds as kcmc;
10use serde::Deserialize;
11use serde::Serialize;
12
13use super::DEFAULT_TOLERANCE_MM;
14use super::args::TyF64;
15use crate::SourceRange;
16use crate::errors::KclError;
17use crate::errors::KclErrorDetails;
18use crate::execution::EdgeCut;
19use crate::execution::ExecState;
20use crate::execution::ExtrudeSurface;
21use crate::execution::FilletSurface;
22use crate::execution::GeoMeta;
23use crate::execution::KclValue;
24use crate::execution::ModelingCmdMeta;
25use crate::execution::Solid;
26use crate::execution::TagIdentifier;
27use crate::execution::types::RuntimeType;
28use crate::parsing::ast::types::TagNode;
29use crate::std::Args;
30
31/// A tag or a uuid of an edge.
32#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]
33#[serde(untagged)]
34pub enum EdgeReference {
35    /// A uuid of an edge.
36    Uuid(uuid::Uuid),
37    /// A tag of an edge.
38    Tag(Box<TagIdentifier>),
39}
40
41impl EdgeReference {
42    pub fn get_engine_id(&self, exec_state: &mut ExecState, args: &Args) -> Result<uuid::Uuid, KclError> {
43        match self {
44            EdgeReference::Uuid(uuid) => Ok(*uuid),
45            EdgeReference::Tag(tag) => Ok(args.get_tag_engine_info(exec_state, tag)?.id),
46        }
47    }
48
49    /// Get all engine IDs for this edge reference.
50    /// For region-mapped tags, returns multiple IDs (one per region segment).
51    pub fn get_all_engine_ids(&self, exec_state: &mut ExecState, args: &Args) -> Result<Vec<uuid::Uuid>, KclError> {
52        match self {
53            EdgeReference::Uuid(uuid) => Ok(vec![*uuid]),
54            EdgeReference::Tag(tag) => {
55                let infos = tag.get_all_cur_info();
56                if infos.is_empty() {
57                    // Fallback to single ID lookup (checks the stack).
58                    Ok(vec![args.get_tag_engine_info(exec_state, tag)?.id])
59                } else {
60                    Ok(infos.iter().map(|i| i.id).collect())
61                }
62            }
63        }
64    }
65}
66
67pub(super) fn validate_unique<T: Eq + std::hash::Hash>(tags: &[(T, SourceRange)]) -> Result<(), KclError> {
68    // Check if tags contains any duplicate values.
69    let mut tag_counts: IndexMap<&T, Vec<SourceRange>> = Default::default();
70    for tag in tags {
71        tag_counts.entry(&tag.0).or_insert(Vec::new()).push(tag.1);
72    }
73    let mut duplicate_tags_source = Vec::new();
74    for (_tag, count) in tag_counts {
75        if count.len() > 1 {
76            duplicate_tags_source.extend(count)
77        }
78    }
79    if !duplicate_tags_source.is_empty() {
80        return Err(KclError::new_type(KclErrorDetails::new(
81            "The same edge ID is being referenced multiple times, which is not allowed. Please select a different edge"
82                .to_string(),
83            duplicate_tags_source,
84        )));
85    }
86    Ok(())
87}
88
89/// Create fillets on tagged paths.
90pub async fn fillet(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
91    let solid = args.get_unlabeled_kw_arg("solid", &RuntimeType::solid(), exec_state)?;
92    let radius: TyF64 = args.get_kw_arg("radius", &RuntimeType::length(), exec_state)?;
93    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
94    let tags = args.kw_arg_edge_array_and_source("tags")?;
95    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
96
97    // Run the function.
98    validate_unique(&tags)?;
99    let tags: Vec<EdgeReference> = tags.into_iter().map(|item| item.0).collect();
100    let value = inner_fillet(solid, radius, tags, tolerance, tag, exec_state, args).await?;
101    Ok(KclValue::Solid { value })
102}
103
104async fn inner_fillet(
105    solid: Box<Solid>,
106    radius: TyF64,
107    tags: Vec<EdgeReference>,
108    tolerance: Option<TyF64>,
109    tag: Option<TagNode>,
110    exec_state: &mut ExecState,
111    args: Args,
112) -> Result<Box<Solid>, KclError> {
113    // If you try and tag multiple edges with a tagged fillet, we want to return an
114    // error to the user that they can only tag one edge at a time.
115    if tag.is_some() && tags.len() > 1 {
116        return Err(KclError::new_type(KclErrorDetails {
117            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(),
118            source_ranges: vec![args.source_range],
119            backtrace: Default::default(),
120        }));
121    }
122    if tags.is_empty() {
123        return Err(KclError::new_semantic(KclErrorDetails {
124            source_ranges: vec![args.source_range],
125            message: "You must fillet at least one tag".to_owned(),
126            backtrace: Default::default(),
127        }));
128    }
129
130    let mut solid = solid.clone();
131    let edge_ids = tags
132        .into_iter()
133        .map(|edge_tag| edge_tag.get_all_engine_ids(exec_state, &args))
134        .try_fold(Vec::new(), |mut acc, item| match item {
135            Ok(ids) => {
136                acc.extend(ids);
137                Ok(acc)
138            }
139            Err(e) => Err(e),
140        })?;
141
142    let id = exec_state.next_uuid();
143    let mut extra_face_ids = Vec::new();
144    let num_extra_ids = edge_ids.len() - 1;
145    for _ in 0..num_extra_ids {
146        extra_face_ids.push(exec_state.next_uuid());
147    }
148    exec_state
149        .batch_end_cmd(
150            ModelingCmdMeta::from_args_id(exec_state, &args, id),
151            ModelingCmd::from(
152                mcmd::Solid3dFilletEdge::builder()
153                    .edge_ids(edge_ids.clone())
154                    .extra_face_ids(extra_face_ids)
155                    .strategy(Default::default())
156                    .object_id(solid.id)
157                    .radius(LengthUnit(radius.to_mm()))
158                    .tolerance(LengthUnit(
159                        tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
160                    ))
161                    .cut_type(CutType::Fillet)
162                    .build(),
163            ),
164        )
165        .await?;
166
167    let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Fillet {
168        id,
169        edge_id,
170        radius: radius.clone(),
171        tag: Box::new(tag.clone()),
172    });
173    solid.edge_cuts.extend(new_edge_cuts);
174
175    if let Some(ref tag) = tag {
176        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
177            face_id: id,
178            tag: Some(tag.clone()),
179            geo_meta: GeoMeta {
180                id,
181                metadata: args.source_range.into(),
182            },
183        }));
184    }
185
186    Ok(solid)
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn test_validate_unique() {
195        let dup_a = SourceRange::from([1, 3, 0]);
196        let dup_b = SourceRange::from([10, 30, 0]);
197        // Two entries are duplicates (abc) with different source ranges.
198        let tags = vec![("abc", dup_a), ("abc", dup_b), ("def", SourceRange::from([2, 4, 0]))];
199        let actual = validate_unique(&tags);
200        // Both the duplicates should show up as errors, with both of the
201        // source ranges they correspond to.
202        // But the unique source range 'def' should not.
203        let expected = vec![dup_a, dup_b];
204        assert_eq!(actual.err().unwrap().source_ranges(), expected);
205    }
206}