Skip to main content

kcl_lib/std/
sweep.rs

1//! Standard library sweep.
2
3use anyhow::Result;
4use kcmc::ModelingCmd;
5use kcmc::each_cmd as mcmd;
6use kcmc::length_unit::LengthUnit;
7use kcmc::shared::BodyType;
8use kittycad_modeling_cmds::id::ModelingCmdId;
9use kittycad_modeling_cmds::shared::RelativeTo;
10use kittycad_modeling_cmds::websocket::ModelingCmdReq;
11use kittycad_modeling_cmds::{self as kcmc};
12use serde::Serialize;
13
14use super::DEFAULT_TOLERANCE_MM;
15use super::args::TyF64;
16use crate::errors::KclError;
17use crate::errors::KclErrorDetails;
18use crate::execution::ExecState;
19use crate::execution::Extrudable;
20use crate::execution::Helix;
21use crate::execution::KclValue;
22use crate::execution::ModelingCmdMeta;
23use crate::execution::ProfileClosed;
24use crate::execution::Segment;
25use crate::execution::Sketch;
26use crate::execution::SketchSurface;
27use crate::execution::Solid;
28use crate::execution::types::ArrayLen;
29use crate::execution::types::RuntimeType;
30use crate::parsing::ast::types::TagNode;
31use crate::std::Args;
32use crate::std::extrude::BeingExtruded;
33use crate::std::extrude::build_segment_surface_sketch;
34use crate::std::extrude::coerce_extrude_targets;
35use crate::std::extrude::do_post_extrude;
36
37/// A path to sweep along.
38#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
39#[ts(export)]
40#[serde(untagged)]
41#[allow(clippy::large_enum_variant)]
42pub enum SweepPath {
43    Sketch(Sketch),
44    Helix(Box<Helix>),
45    Segments(Vec<Segment>),
46}
47
48/// The outer (typical) sweep path gets converted to this, losing some of its variants in the conversion.
49#[allow(clippy::large_enum_variant)]
50enum InnerSweepPath {
51    Sketch(Sketch),
52    Helix(Box<Helix>),
53}
54
55/// Create a 3D surface or solid by sweeping a sketch along a path.
56pub async fn sweep(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
57    let sketch_values = args.get_unlabeled_kw_arg(
58        "sketches",
59        &RuntimeType::Array(
60            Box::new(RuntimeType::Union(vec![
61                RuntimeType::sketch(),
62                RuntimeType::segment(),
63                RuntimeType::face(),
64                RuntimeType::tagged_face(),
65            ])),
66            ArrayLen::Minimum(1),
67        ),
68        exec_state,
69    )?;
70    let path: SweepPath = args.get_kw_arg(
71        "path",
72        &RuntimeType::Union(vec![
73            RuntimeType::sketch(),
74            RuntimeType::helix(),
75            RuntimeType::Array(Box::new(RuntimeType::segment()), ArrayLen::Minimum(1)),
76        ]),
77        exec_state,
78    )?;
79    let sectional = args.get_kw_arg_opt("sectional", &RuntimeType::bool(), exec_state)?;
80    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
81    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
82    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
83    let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
84    let version: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
85    // Replaced by 2 args below.
86    let relative_to: Option<String> = args.get_kw_arg_opt("relativeTo", &RuntimeType::string(), exec_state)?;
87    // Replaces `relative_to`.
88    let translate_profile_to_path: Option<bool> =
89        args.get_kw_arg_opt("translateProfileToPath", &RuntimeType::bool(), exec_state)?;
90    let orient_profile_perpendicular: Option<bool> =
91        args.get_kw_arg_opt("orientProfilePerpendicular", &RuntimeType::bool(), exec_state)?;
92
93    let path = match path {
94        SweepPath::Segments(segments) => InnerSweepPath::Sketch(
95            build_segment_surface_sketch(segments, exec_state, &args.ctx, args.source_range).await?,
96        ),
97        SweepPath::Sketch(sketch) => InnerSweepPath::Sketch(sketch),
98        SweepPath::Helix(helix) => InnerSweepPath::Helix(helix),
99    };
100
101    let sketches = coerce_extrude_targets(
102        sketch_values,
103        body_type.unwrap_or_default(),
104        tag_start.as_ref(),
105        tag_end.as_ref(),
106        exec_state,
107        &args.ctx,
108        args.source_range,
109    )
110    .await?;
111
112    let value = inner_sweep(
113        sketches,
114        path,
115        sectional,
116        tolerance,
117        relative_to,
118        translate_profile_to_path,
119        orient_profile_perpendicular,
120        tag_start,
121        tag_end,
122        body_type,
123        version,
124        exec_state,
125        args,
126    )
127    .await?;
128    Ok(value.into())
129}
130
131enum ProfileTransform {
132    RelativeTo(RelativeTo),
133    SeparateFlags {
134        translate_profile_to_path: bool,
135        orient_profile_perpendicular: bool,
136    },
137}
138
139impl ProfileTransform {
140    fn relative_to(&self) -> Option<RelativeTo> {
141        match self {
142            ProfileTransform::RelativeTo(relative_to) => Some(*relative_to),
143            ProfileTransform::SeparateFlags { .. } => None,
144        }
145    }
146
147    fn translate_profile_to_path(&self) -> Option<bool> {
148        match self {
149            ProfileTransform::RelativeTo(..) => None,
150            ProfileTransform::SeparateFlags {
151                translate_profile_to_path,
152                ..
153            } => Some(*translate_profile_to_path),
154        }
155    }
156    fn orient_profile_perpendicular(&self) -> Option<bool> {
157        match self {
158            ProfileTransform::RelativeTo(..) => None,
159            ProfileTransform::SeparateFlags {
160                orient_profile_perpendicular,
161                ..
162            } => Some(*orient_profile_perpendicular),
163        }
164    }
165}
166
167#[allow(clippy::too_many_arguments)]
168async fn inner_sweep(
169    sketches: Vec<Extrudable>,
170    path: InnerSweepPath,
171    sectional: Option<bool>,
172    tolerance: Option<TyF64>,
173    relative_to: Option<String>,
174    translate_profile_to_path: Option<bool>,
175    orient_profile_perpendicular: Option<bool>,
176    tag_start: Option<TagNode>,
177    tag_end: Option<TagNode>,
178    body_type: Option<BodyType>,
179    version: Option<u32>,
180    exec_state: &mut ExecState,
181    args: Args,
182) -> Result<Vec<Solid>, KclError> {
183    let body_type = body_type.unwrap_or_default();
184    if matches!(body_type, BodyType::Solid) && sketches.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No)) {
185        return Err(KclError::new_semantic(KclErrorDetails::new(
186            "Cannot solid sweep an open profile. Either close the profile, or use a surface sweep.".to_owned(),
187            vec![args.source_range],
188        )));
189    }
190
191    let version = version
192        .map(|v| {
193            u8::try_from(v).map_err(|_e| {
194                KclError::new_argument(KclErrorDetails::new(
195                    format!("Invalid version {}", v),
196                    vec![args.source_range],
197                ))
198            })
199        })
200        .transpose()?;
201
202    let trajectory = ModelingCmdId::from(match path {
203        InnerSweepPath::Sketch(sketch) => sketch.id,
204        InnerSweepPath::Helix(helix) => helix.value,
205    });
206
207    let profile_transform = match (relative_to, translate_profile_to_path, orient_profile_perpendicular) {
208        // Default case when the user doesn't give any flags at all.
209        (None, None, None) => ProfileTransform::RelativeTo(match version {
210            // We default to algorithm v1 if no choice was made.
211            None | Some(1) => RelativeTo::TrajectoryCurve,
212            // 0 means "let engine choose". Engine currently chooses version 1.
213            Some(0) => RelativeTo::TrajectoryCurve,
214            // Algorithm version 2 defaults to SketchPlane.
215            Some(2) => RelativeTo::SketchPlane,
216            // Error on unknown algorithm.
217            Some(other) => {
218                return Err(KclError::new_argument(KclErrorDetails::new(
219                    format!("Invalid version {}", other),
220                    vec![args.source_range],
221                )));
222            }
223        }),
224
225        // If the "new" profile transformation args are set.
226        (None, translate, orient) => ProfileTransform::SeparateFlags {
227            translate_profile_to_path: translate.unwrap_or_default(),
228            orient_profile_perpendicular: orient.unwrap_or_default(),
229        },
230
231        // RelativeTo was set, but none of its replacements were.
232        (Some(relative_to), None, None) => ProfileTransform::RelativeTo(match relative_to.as_str() {
233            "sketchPlane" => RelativeTo::SketchPlane,
234            "trajectoryCurve" => RelativeTo::TrajectoryCurve,
235            _ => {
236                return Err(KclError::new_syntax(crate::errors::KclErrorDetails::new(
237                    "If you provide relativeTo, it must either be 'sketchPlane' or 'trajectoryCurve'".to_owned(),
238                    vec![args.source_range],
239                )));
240            }
241        }),
242
243        // RelativeTo was set, but also one of its replacements was.
244        // This is an error.
245        (Some(_relative_to), _, _) => {
246            return Err(KclError::new_argument(crate::errors::KclErrorDetails::new(
247                    "If you provide 'relativeTo', you cannot provide 'translateProfileToPath' or 'orientProfilePerpendicular'. Those arguments replace 'relativeTo', please use them instead.".to_owned(),
248                    vec![args.source_range],
249                )));
250        }
251    };
252
253    let mut solids = Vec::new();
254    for sketch in &sketches {
255        let sweep_cmd_id = exec_state.next_uuid();
256        let sketch_or_face_id = sketch.id_to_extrude(exec_state, &args, false).await?;
257        let cmd = ModelingCmd::from(
258            mcmd::Sweep::builder()
259                .target(sketch_or_face_id.into())
260                .trajectory(trajectory)
261                .sectional(sectional.unwrap_or(false))
262                .tolerance(LengthUnit(
263                    tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
264                ))
265                .maybe_relative_to(profile_transform.relative_to())
266                .maybe_orient_profile_perpendicular(profile_transform.orient_profile_perpendicular())
267                .maybe_translate_profile_to_path(profile_transform.translate_profile_to_path())
268                .body_type(body_type)
269                .maybe_version(version)
270                .build(),
271        );
272
273        let being_extruded = match sketch {
274            Extrudable::Sketch(..) => BeingExtruded::Sketch,
275            Extrudable::FaceTag(face_tag) => {
276                let face_id = sketch_or_face_id;
277                let solid_id = match face_tag.geometry() {
278                    Some(crate::execution::Geometry::Solid(solid)) => solid.id,
279                    Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
280                        SketchSurface::Face(face) => face.parent_solid.solid_id,
281                        SketchSurface::Plane(_) => sketch.id,
282                    },
283                    None => face_id,
284                };
285                BeingExtruded::Face { face_id, solid_id }
286            }
287            Extrudable::Face(face) => BeingExtruded::Face {
288                face_id: face.id,
289                solid_id: face.parent_solid.solid_id,
290            },
291            Extrudable::EdgeTag(_) => BeingExtruded::Edge,
292            Extrudable::Edge(_) => BeingExtruded::Edge,
293        };
294
295        if let Some(post_extr_sketch) = sketch.as_sketch() {
296            let cmds = post_extr_sketch.build_sketch_mode_cmds(
297                exec_state,
298                ModelingCmdReq {
299                    cmd_id: sweep_cmd_id.into(),
300                    cmd,
301                },
302            );
303            exec_state
304                .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, sweep_cmd_id), &cmds)
305                .await?;
306            solids.push(
307                do_post_extrude(
308                    &post_extr_sketch,
309                    sweep_cmd_id.into(),
310                    sectional.unwrap_or(false),
311                    &super::extrude::NamedCapTags {
312                        start: tag_start.as_ref(),
313                        end: tag_end.as_ref(),
314                    },
315                    kittycad_modeling_cmds::shared::ExtrudeMethod::New,
316                    exec_state,
317                    &args,
318                    None,
319                    None,
320                    body_type,
321                    being_extruded,
322                )
323                .await?,
324            );
325        } else {
326            return Err(KclError::new_type(KclErrorDetails::new(
327                "Expected a sketch for sweeping".to_owned(),
328                vec![args.source_range],
329            )));
330        }
331    }
332
333    // Hide the artifact from the sketch or helix.
334    exec_state
335        .batch_modeling_cmd(
336            ModelingCmdMeta::from_args(exec_state, &args),
337            ModelingCmd::from(
338                mcmd::ObjectVisible::builder()
339                    .object_id(trajectory.into())
340                    .hidden(true)
341                    .build(),
342            ),
343        )
344        .await?;
345
346    Ok(solids)
347}