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::KclVersion;
17use crate::errors::KclError;
18use crate::errors::KclErrorDetails;
19use crate::execution::ExecState;
20use crate::execution::Extrudable;
21use crate::execution::Helix;
22use crate::execution::KclValue;
23use crate::execution::ModelingCmdMeta;
24use crate::execution::ProfileClosed;
25use crate::execution::Segment;
26use crate::execution::Sketch;
27use crate::execution::SketchSurface;
28use crate::execution::Solid;
29use crate::execution::types::ArrayLen;
30use crate::execution::types::RuntimeType;
31use crate::parsing::ast::types::TagNode;
32use crate::std::Args;
33use crate::std::extrude::BeingExtruded;
34use crate::std::extrude::build_segment_surface_sketch;
35use crate::std::extrude::coerce_extrude_targets;
36use crate::std::extrude::do_post_extrude;
37
38/// A path to sweep along.
39#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
40#[ts(export)]
41#[serde(untagged)]
42#[allow(clippy::large_enum_variant)]
43pub enum SweepPath {
44    Sketch(Sketch),
45    Helix(Box<Helix>),
46    Segments(Vec<Segment>),
47}
48
49/// The outer (typical) sweep path gets converted to this, losing some of its variants in the conversion.
50#[allow(clippy::large_enum_variant)]
51enum InnerSweepPath {
52    Sketch(Sketch),
53    Helix(Box<Helix>),
54}
55
56/// Create a 3D surface or solid by sweeping a sketch along a path.
57pub async fn sweep(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
58    let sketch_values = args.get_unlabeled_kw_arg(
59        "sketches",
60        &RuntimeType::Array(
61            Box::new(RuntimeType::Union(vec![
62                RuntimeType::sketch(),
63                RuntimeType::segment(),
64                RuntimeType::face(),
65                RuntimeType::tagged_face(),
66            ])),
67            ArrayLen::Minimum(1),
68        ),
69        exec_state,
70    )?;
71    let path: SweepPath = args.get_kw_arg(
72        "path",
73        &RuntimeType::Union(vec![
74            RuntimeType::sketch(),
75            RuntimeType::helix(),
76            RuntimeType::Array(Box::new(RuntimeType::segment()), ArrayLen::Minimum(1)),
77        ]),
78        exec_state,
79    )?;
80    let sectional = args.get_kw_arg_opt("sectional", &RuntimeType::bool(), exec_state)?;
81    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
82    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
83    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
84    let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
85    // KCL 3.0 removes the version parameter (`removed_in` in sketch.kcl),
86    // so from 3.0 on this is always None, and the newest algorithm is used.
87    let version: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
88    // Replaced by 2 args below.
89    let relative_to: Option<String> = args.get_kw_arg_opt("relativeTo", &RuntimeType::string(), exec_state)?;
90    // Replaces `relative_to`.
91    let translate_profile_to_path: Option<bool> =
92        args.get_kw_arg_opt("translateProfileToPath", &RuntimeType::bool(), exec_state)?;
93    let orient_profile_perpendicular: Option<bool> =
94        args.get_kw_arg_opt("orientProfilePerpendicular", &RuntimeType::bool(), exec_state)?;
95
96    let path = match path {
97        SweepPath::Segments(segments) => InnerSweepPath::Sketch(
98            build_segment_surface_sketch(segments, exec_state, &args.ctx, args.source_range).await?,
99        ),
100        SweepPath::Sketch(sketch) => InnerSweepPath::Sketch(sketch),
101        SweepPath::Helix(helix) => InnerSweepPath::Helix(helix),
102    };
103
104    let sketches = coerce_extrude_targets(
105        sketch_values,
106        body_type.unwrap_or_default(),
107        tag_start.as_ref(),
108        tag_end.as_ref(),
109        exec_state,
110        &args.ctx,
111        args.source_range,
112    )
113    .await?;
114
115    let value = inner_sweep(
116        sketches,
117        path,
118        sectional,
119        tolerance,
120        relative_to,
121        translate_profile_to_path,
122        orient_profile_perpendicular,
123        tag_start,
124        tag_end,
125        body_type,
126        version,
127        exec_state,
128        args,
129    )
130    .await?;
131    Ok(value.into())
132}
133
134enum ProfileTransform {
135    RelativeTo(RelativeTo),
136    SeparateFlags {
137        translate_profile_to_path: bool,
138        orient_profile_perpendicular: bool,
139    },
140}
141
142impl ProfileTransform {
143    fn relative_to(&self) -> Option<RelativeTo> {
144        match self {
145            ProfileTransform::RelativeTo(relative_to) => Some(*relative_to),
146            ProfileTransform::SeparateFlags { .. } => None,
147        }
148    }
149
150    fn translate_profile_to_path(&self) -> Option<bool> {
151        match self {
152            ProfileTransform::RelativeTo(..) => None,
153            ProfileTransform::SeparateFlags {
154                translate_profile_to_path,
155                ..
156            } => Some(*translate_profile_to_path),
157        }
158    }
159    fn orient_profile_perpendicular(&self) -> Option<bool> {
160        match self {
161            ProfileTransform::RelativeTo(..) => None,
162            ProfileTransform::SeparateFlags {
163                orient_profile_perpendicular,
164                ..
165            } => Some(*orient_profile_perpendicular),
166        }
167    }
168}
169
170/// The sweep algorithm version to send when the user does not set `version`.
171/// KCL 3.0 removes the version parameter (`removed_in` in sketch.kcl), so
172/// from 3.0 on this is always what is sent.
173fn default_sweep_version(kcl_version: KclVersion) -> Option<u8> {
174    if kcl_version <= KclVersion::V2 {
175        // Unspecified, so the engine chooses. It currently chooses version 1.
176        None
177    } else {
178        // KCL 3.0 and later always use the newest algorithm.
179        Some(2)
180    }
181}
182
183/// The value of `orientProfilePerpendicular` when the user does not set it.
184fn default_orient_profile_perpendicular(kcl_version: KclVersion, translate_profile_to_path: bool) -> bool {
185    if kcl_version <= KclVersion::V2 {
186        false
187    } else {
188        // From a mechanical engineer on what is intuitive:
189        // - `translateProfileToPath` should default to false.
190        // - `orientProfilePerpendicular` should default to false,
191        //   unless `translateProfileToPath` is true, in which case both should be true.
192        translate_profile_to_path
193    }
194}
195
196#[allow(clippy::too_many_arguments)]
197async fn inner_sweep(
198    sketches: Vec<Extrudable>,
199    path: InnerSweepPath,
200    sectional: Option<bool>,
201    tolerance: Option<TyF64>,
202    relative_to: Option<String>,
203    translate_profile_to_path: Option<bool>,
204    orient_profile_perpendicular: Option<bool>,
205    tag_start: Option<TagNode>,
206    tag_end: Option<TagNode>,
207    body_type: Option<BodyType>,
208    version: Option<u32>,
209    exec_state: &mut ExecState,
210    args: Args,
211) -> Result<Vec<Solid>, KclError> {
212    let body_type = body_type.unwrap_or_default();
213    if matches!(body_type, BodyType::Solid) && sketches.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No)) {
214        return Err(KclError::new_semantic(KclErrorDetails::new(
215            "Cannot solid sweep an open profile. Either close the profile, or use a surface sweep.".to_owned(),
216            vec![args.source_range],
217        )));
218    }
219
220    let kcl_version = exec_state.kcl_version();
221    let version = version
222        .map(|v| {
223            u8::try_from(v).map_err(|_e| {
224                KclError::new_argument(KclErrorDetails::new(
225                    format!("Invalid version {}", v),
226                    vec![args.source_range],
227                ))
228            })
229        })
230        .transpose()?
231        .or_else(|| default_sweep_version(kcl_version));
232
233    let trajectory = ModelingCmdId::from(match path {
234        InnerSweepPath::Sketch(sketch) => sketch.id,
235        InnerSweepPath::Helix(helix) => helix.value,
236    });
237
238    let profile_transform = match (relative_to, translate_profile_to_path, orient_profile_perpendicular) {
239        // Before KCL 3.0, when the user doesn't give any flags at all, the
240        // legacy `relativeTo` behavior is implied by the algorithm version.
241        (None, None, None) if kcl_version <= KclVersion::V2 => ProfileTransform::RelativeTo(match version {
242            // We default to algorithm v1 if no choice was made.
243            None | Some(1) => RelativeTo::TrajectoryCurve,
244            // 0 means "let engine choose". Engine currently chooses version 1.
245            Some(0) => RelativeTo::TrajectoryCurve,
246            // Algorithm version 2 defaults to SketchPlane.
247            Some(2) => RelativeTo::SketchPlane,
248            // Error on unknown algorithm.
249            Some(other) => {
250                return Err(KclError::new_argument(KclErrorDetails::new(
251                    format!("Invalid version {}", other),
252                    vec![args.source_range],
253                )));
254            }
255        }),
256
257        // If the "new" profile transformation args are set. KCL 3.0 removed
258        // `relativeTo` (see `removed_in` in sketch.kcl), so from 3.0 on,
259        // this is also the case when no flags are set at all.
260        (None, translate, orient) => {
261            let translate_profile_to_path = translate.unwrap_or_default();
262            ProfileTransform::SeparateFlags {
263                translate_profile_to_path,
264                orient_profile_perpendicular: orient
265                    .unwrap_or_else(|| default_orient_profile_perpendicular(kcl_version, translate_profile_to_path)),
266            }
267        }
268
269        // RelativeTo was set, but none of its replacements were.
270        (Some(relative_to), None, None) => ProfileTransform::RelativeTo(match relative_to.as_str() {
271            "sketchPlane" => RelativeTo::SketchPlane,
272            "trajectoryCurve" => RelativeTo::TrajectoryCurve,
273            _ => {
274                return Err(KclError::new_syntax(crate::errors::KclErrorDetails::new(
275                    "If you provide relativeTo, it must either be 'sketchPlane' or 'trajectoryCurve'".to_owned(),
276                    vec![args.source_range],
277                )));
278            }
279        }),
280
281        // RelativeTo was set, but also one of its replacements was.
282        // This is an error.
283        (Some(_relative_to), _, _) => {
284            return Err(KclError::new_argument(crate::errors::KclErrorDetails::new(
285                    "If you provide 'relativeTo', you cannot provide 'translateProfileToPath' or 'orientProfilePerpendicular'. Those arguments replace 'relativeTo', please use them instead.".to_owned(),
286                    vec![args.source_range],
287                )));
288        }
289    };
290
291    let mut solids = Vec::new();
292    for sketch in &sketches {
293        let sweep_cmd_id = exec_state.next_uuid();
294        let sketch_or_face_id = sketch.id_to_extrude(exec_state, &args, false).await?;
295        let cmd = ModelingCmd::from(
296            mcmd::Sweep::builder()
297                .target(sketch_or_face_id.into())
298                .trajectory(trajectory)
299                .sectional(sectional.unwrap_or(false))
300                .tolerance(LengthUnit(
301                    tolerance
302                        .as_ref()
303                        .map(|t| t.unwrap_to_mm())
304                        .unwrap_or(DEFAULT_TOLERANCE_MM),
305                ))
306                .maybe_relative_to(profile_transform.relative_to())
307                .maybe_orient_profile_perpendicular(profile_transform.orient_profile_perpendicular())
308                .maybe_translate_profile_to_path(profile_transform.translate_profile_to_path())
309                .body_type(body_type)
310                .maybe_version(version)
311                .build(),
312        );
313
314        let being_extruded = match sketch {
315            Extrudable::Sketch(..) => BeingExtruded::Sketch,
316            Extrudable::FaceTag(face_tag) => {
317                let face_id = sketch_or_face_id;
318                let solid_id = match face_tag.geometry() {
319                    Some(crate::execution::Geometry::Solid(solid)) => solid.id,
320                    Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
321                        SketchSurface::Face(face) => face.parent_solid.solid_id,
322                        SketchSurface::Plane(_) => sketch.id,
323                    },
324                    None => face_id,
325                };
326                BeingExtruded::Face { face_id, solid_id }
327            }
328            Extrudable::Face(face) => BeingExtruded::Face {
329                face_id: face.id,
330                solid_id: face.parent_solid.solid_id,
331            },
332            Extrudable::EdgeTag(_) => BeingExtruded::Edge,
333            Extrudable::Edge(_) => BeingExtruded::Edge,
334            Extrudable::EdgeSpecifier(_) => BeingExtruded::Edge,
335        };
336
337        if let Some(post_extr_sketch) = sketch.as_sketch() {
338            let cmds = post_extr_sketch.build_sketch_mode_cmds(
339                exec_state,
340                ModelingCmdReq {
341                    cmd_id: sweep_cmd_id.into(),
342                    cmd,
343                },
344            );
345            exec_state
346                .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, sweep_cmd_id), &cmds)
347                .await?;
348            solids.push(
349                do_post_extrude(
350                    &post_extr_sketch,
351                    sweep_cmd_id.into(),
352                    sectional.unwrap_or(false),
353                    &super::extrude::NamedCapTags {
354                        start: tag_start.as_ref(),
355                        end: tag_end.as_ref(),
356                    },
357                    kittycad_modeling_cmds::shared::ExtrudeMethod::New,
358                    exec_state,
359                    &args,
360                    None,
361                    None,
362                    body_type,
363                    being_extruded,
364                )
365                .await?,
366            );
367        } else {
368            return Err(KclError::new_type(KclErrorDetails::new(
369                "Expected a sketch for sweeping".to_owned(),
370                vec![args.source_range],
371            )));
372        }
373    }
374
375    // Hide the artifact from the sketch or helix.
376    exec_state
377        .batch_modeling_cmd(
378            ModelingCmdMeta::from_args(exec_state, &args),
379            ModelingCmd::from(
380                mcmd::ObjectVisible::builder()
381                    .object_id(trajectory.into())
382                    .hidden(true)
383                    .build(),
384            ),
385        )
386        .await?;
387
388    Ok(solids)
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use crate::execution::ExecTestResults;
395    use crate::execution::parse_execute;
396
397    /// What each KCL version sends to the engine when the user leaves out
398    /// `translateProfileToPath`, `orientProfilePerpendicular`, and `version`.
399    #[tokio::test(flavor = "multi_thread")]
400    async fn sweep_defaults_depend_on_kcl_version() {
401        // Before KCL 3.0, the legacy `relative_to` field is sent instead of
402        // the two flags, and the algorithm version is left to the engine.
403        let cmd = emitted_sweep("2.0", "").await;
404        assert_eq!(cmd.relative_to, Some(RelativeTo::TrajectoryCurve));
405        assert_eq!(cmd.translate_profile_to_path, None);
406        assert_eq!(cmd.orient_profile_perpendicular, None);
407        assert_eq!(cmd.version, None);
408
409        // From KCL 3.0, the two flags are always sent, both false by default,
410        // and the algorithm is always version 2.
411        let cmd = emitted_sweep("\"3.0-preview\"", "").await;
412        assert_eq!(cmd.relative_to, None);
413        assert_eq!(cmd.translate_profile_to_path, Some(false));
414        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
415        assert_eq!(cmd.version, Some(2));
416    }
417
418    /// From KCL 3.0, `orientProfilePerpendicular` defaults to the value of
419    /// `translateProfileToPath`. Before that, the two flags are independent.
420    #[tokio::test(flavor = "multi_thread")]
421    async fn orient_profile_perpendicular_follows_translate_in_kcl_3() {
422        let cmd = emitted_sweep("\"3.0-preview\"", ", translateProfileToPath = true").await;
423        assert_eq!(cmd.translate_profile_to_path, Some(true));
424        assert_eq!(cmd.orient_profile_perpendicular, Some(true));
425
426        let cmd = emitted_sweep("\"3.0-preview\"", ", translateProfileToPath = false").await;
427        assert_eq!(cmd.translate_profile_to_path, Some(false));
428        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
429
430        let cmd = emitted_sweep("2.0", ", translateProfileToPath = true").await;
431        assert_eq!(cmd.translate_profile_to_path, Some(true));
432        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
433    }
434
435    /// An explicit `orientProfilePerpendicular` wins over the default,
436    /// whatever `translateProfileToPath` is.
437    #[tokio::test(flavor = "multi_thread")]
438    async fn explicit_orient_profile_perpendicular_overrides_kcl_default() {
439        let cmd = emitted_sweep(
440            "\"3.0-preview\"",
441            ", translateProfileToPath = true, orientProfilePerpendicular = false",
442        )
443        .await;
444        assert_eq!(cmd.translate_profile_to_path, Some(true));
445        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
446
447        let cmd = emitted_sweep("\"3.0-preview\"", ", orientProfilePerpendicular = true").await;
448        assert_eq!(cmd.translate_profile_to_path, Some(false));
449        assert_eq!(cmd.orient_profile_perpendicular, Some(true));
450    }
451
452    /// If the user chooses a sweep algorithm version, KCL should respect it,
453    /// and not use that KCL version's default sweep algorithm version.
454    #[tokio::test(flavor = "multi_thread")]
455    async fn explicit_sweep_version_overrides_kcl_default() {
456        assert_eq!(emitted_sweep("2.0", ", version = 2").await.version, Some(2));
457        assert_eq!(emitted_sweep("2.0", ", version = 0").await.version, Some(0));
458    }
459
460    /// KCL 3.0 removed `sweep(version = )`. Passing it is reported like any
461    /// other unknown argument, and the newest algorithm is used.
462    #[tokio::test(flavor = "multi_thread")]
463    async fn sweep_version_is_removed_in_kcl_3() {
464        let result = run_sweep("\"3.0-preview\"", ", version = 1").await;
465        assert!(
466            result
467                .issues()
468                .iter()
469                .any(|issue| {
470                    issue.message
471                        == "`version` is not an argument of `sweep`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
472                }),
473            "issues: {:#?}",
474            result.issues()
475        );
476        assert_eq!(emitted_sweep_cmd(&result).version, Some(2));
477    }
478
479    /// Sweep a circle along a line under the given KCL version, passing
480    /// `extra_args` to `sweep`, and return the `Sweep` command sent to the
481    /// engine.
482    async fn emitted_sweep(kcl_version: &str, extra_args: &str) -> mcmd::Sweep {
483        emitted_sweep_cmd(&run_sweep(kcl_version, extra_args).await)
484    }
485
486    /// Sweep a circle along a line under the given KCL version, passing
487    /// `extra_args` to `sweep`.
488    async fn run_sweep(kcl_version: &str, extra_args: &str) -> ExecTestResults {
489        let code = format!(
490            r#"@settings(defaultLengthUnit = mm, kclVersion = {kcl_version})
491
492profileSketch = sketch(on = XY) {{
493  c = circle(start = [var 10mm, var 0mm], center = [var 0mm, var 0mm])
494}}
495profile = region(segments = [profileSketch.c])
496
497pathSketch = sketch(on = XZ) {{
498  path = line(start = [var 0mm, var 0mm], end = [var 0mm, var 100mm])
499}}
500
501sweep(profile, path = pathSketch{extra_args})
502"#
503        );
504        parse_execute(&code).await.unwrap()
505    }
506
507    /// The `Sweep` command the run sent to the engine.
508    fn emitted_sweep_cmd(result: &ExecTestResults) -> mcmd::Sweep {
509        result
510            .root_module_artifact_commands()
511            .iter()
512            .find_map(|artifact_command| match &artifact_command.command {
513                ModelingCmd::Sweep(cmd) => Some(cmd.clone()),
514                _ => None,
515            })
516            .expect("sweep should emit a Sweep command")
517    }
518}