Skip to main content

kcl_lib/std/
revolve.rs

1//! Standard library revolution surfaces.
2
3use anyhow::Result;
4use kcmc::ModelingCmd;
5use kcmc::each_cmd as mcmd;
6use kcmc::length_unit::LengthUnit;
7use kcmc::shared::Angle;
8use kcmc::shared::Opposite;
9use kittycad_modeling_cmds::shared::BodyType;
10use kittycad_modeling_cmds::shared::Point3d;
11use kittycad_modeling_cmds::{self as kcmc};
12
13use super::DEFAULT_TOLERANCE_MM;
14use super::args::FromKclValue;
15use super::args::TyF64;
16use crate::errors::KclError;
17use crate::errors::KclErrorDetails;
18use crate::execution::ExecState;
19use crate::execution::ExecutorContext;
20use crate::execution::KclValue;
21use crate::execution::ModelingCmdMeta;
22use crate::execution::Sketch;
23use crate::execution::Solid;
24use crate::execution::types::ArrayLen;
25use crate::execution::types::RuntimeType;
26use crate::parsing::ast::types::TagNode;
27use crate::std::Args;
28use crate::std::axis_or_reference::Axis2dOrEdgeReference;
29use crate::std::edge;
30use crate::std::extrude::build_segment_surface_sketch;
31use crate::std::extrude::do_post_extrude;
32
33extern crate nalgebra_glm as glm;
34
35/// Revolve a sketch or set of sketches around an axis.
36pub async fn revolve(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
37    let sketch_values: Vec<KclValue> = args.get_unlabeled_kw_arg(
38        "sketches",
39        &RuntimeType::Array(
40            Box::new(RuntimeType::Union(vec![RuntimeType::sketch(), RuntimeType::segment()])),
41            ArrayLen::Minimum(1),
42        ),
43        exec_state,
44    )?;
45
46    // axis accepts: (1) Edge or Axis2d (legacy), or (2) an object with sideFaces (edge reference payload)
47    let axis_value: KclValue = args.get_kw_arg("axis", &RuntimeType::any(), exec_state)?;
48    let axis: Axis2dOrEdgeReference = if edge::is_edge_specifier_object(&axis_value) {
49        let spec = edge::parse_edge_specifier_value(&axis_value, &args)?;
50        let edge_reference =
51            edge::resolve_edge_specifier_with_adjacent_faces_or_tag_ids(&spec, exec_state, &args).await?;
52        Axis2dOrEdgeReference::EdgeSpecifier(edge_reference)
53    } else if let Some(axis_val) = Axis2dOrEdgeReference::from_kcl_val(&axis_value) {
54        axis_val
55    } else {
56        return Err(KclError::new_type(KclErrorDetails {
57            message: "axis must be an Edge, Axis2d, Segment, or an object with 'sideFaces' (edge reference)"
58                .to_string(),
59            source_ranges: vec![args.source_range],
60            backtrace: Default::default(),
61        }));
62    };
63    let angle: Option<TyF64> = args.get_kw_arg_opt("angle", &RuntimeType::degrees(), exec_state)?;
64    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
65    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
66    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
67    let symmetric = args.get_kw_arg_opt("symmetric", &RuntimeType::bool(), exec_state)?;
68    let bidirectional_angle: Option<TyF64> =
69        args.get_kw_arg_opt("bidirectionalAngle", &RuntimeType::angle(), exec_state)?;
70    let body_type: BodyType = args
71        .get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?
72        .unwrap_or_default();
73    let sketches = coerce_revolve_targets(
74        sketch_values,
75        body_type,
76        tag_start.as_ref(),
77        tag_end.as_ref(),
78        exec_state,
79        &args.ctx,
80        args.source_range,
81    )
82    .await?;
83
84    let value = inner_revolve(
85        sketches,
86        axis,
87        angle.map(|t| t.n),
88        tolerance,
89        tag_start,
90        tag_end,
91        symmetric,
92        bidirectional_angle.map(|t| t.n),
93        body_type,
94        exec_state,
95        args,
96    )
97    .await?;
98    Ok(value.into())
99}
100
101#[allow(clippy::too_many_arguments)]
102async fn inner_revolve(
103    sketches: Vec<Sketch>,
104    axis: Axis2dOrEdgeReference,
105    angle: Option<f64>,
106    tolerance: Option<TyF64>,
107    tag_start: Option<TagNode>,
108    tag_end: Option<TagNode>,
109    symmetric: Option<bool>,
110    bidirectional_angle: Option<f64>,
111    body_type: BodyType,
112    exec_state: &mut ExecState,
113    args: Args,
114) -> Result<Vec<Solid>, KclError> {
115    if let Axis2dOrEdgeReference::Axis { direction, .. } = &axis
116        && direction[0].to_mm() == 0.0
117        && direction[1].to_mm() == 0.0
118    {
119        return Err(KclError::new_semantic(KclErrorDetails::new(
120            "The axis of revolution cannot be the zero vector.".to_owned(),
121            vec![args.source_range],
122        )));
123    }
124
125    if let Some(angle) = angle {
126        // Return an error if the angle is zero.
127        // We don't use validate() here because we want to return a specific error message that is
128        // nice and we use the other data in the docs, so we still need use the derive above for the json schema.
129        if !(-360.0..=360.0).contains(&angle) || angle == 0.0 {
130            return Err(KclError::new_semantic(KclErrorDetails::new(
131                format!("Expected angle to be between -360 and 360 and not 0, found `{angle}`"),
132                vec![args.source_range],
133            )));
134        }
135    }
136
137    if let Some(bidirectional_angle) = bidirectional_angle {
138        // Return an error if the angle is zero.
139        // We don't use validate() here because we want to return a specific error message that is
140        // nice and we use the other data in the docs, so we still need use the derive above for the json schema.
141        if !(-360.0..=360.0).contains(&bidirectional_angle) || bidirectional_angle == 0.0 {
142            return Err(KclError::new_semantic(KclErrorDetails::new(
143                format!(
144                    "Expected bidirectional angle to be between -360 and 360 and not 0, found `{bidirectional_angle}`"
145                ),
146                vec![args.source_range],
147            )));
148        }
149
150        if let Some(angle) = angle {
151            let ang = angle.signum() * bidirectional_angle + angle;
152            if !(-360.0..=360.0).contains(&ang) {
153                return Err(KclError::new_semantic(KclErrorDetails::new(
154                    format!("Combined angle and bidirectional must be between -360 and 360, found '{ang}'"),
155                    vec![args.source_range],
156                )));
157            }
158        }
159    }
160
161    if symmetric.unwrap_or(false) && bidirectional_angle.is_some() {
162        return Err(KclError::new_semantic(KclErrorDetails::new(
163            "You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
164                .to_owned(),
165            vec![args.source_range],
166        )));
167    }
168
169    let angle = Angle::from_degrees(angle.unwrap_or(360.0));
170
171    let bidirectional_angle = bidirectional_angle.map(Angle::from_degrees);
172
173    let opposite = match (symmetric, bidirectional_angle) {
174        (Some(true), _) => Opposite::Symmetric,
175        (None, None) => Opposite::None,
176        (Some(false), None) => Opposite::None,
177        (None, Some(angle)) => Opposite::Other(angle),
178        (Some(false), Some(angle)) => Opposite::Other(angle),
179    };
180
181    let mut solids = Vec::new();
182    for sketch in &sketches {
183        let new_solid_id = exec_state.next_uuid();
184        let tolerance = tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM);
185
186        let direction = match &axis {
187            Axis2dOrEdgeReference::Axis { direction, origin } => {
188                exec_state
189                    .batch_modeling_cmd(
190                        ModelingCmdMeta::from_args_id(exec_state, &args, new_solid_id),
191                        ModelingCmd::from(
192                            mcmd::Revolve::builder()
193                                .angle(angle)
194                                .target(sketch.id.into())
195                                .axis(Point3d {
196                                    x: direction[0].to_mm(),
197                                    y: direction[1].to_mm(),
198                                    z: 0.0,
199                                })
200                                .origin(Point3d {
201                                    x: LengthUnit(origin[0].to_mm()),
202                                    y: LengthUnit(origin[1].to_mm()),
203                                    z: LengthUnit(0.0),
204                                })
205                                .tolerance(LengthUnit(tolerance))
206                                .axis_is_2d(true)
207                                .opposite(opposite.clone())
208                                .body_type(body_type)
209                                .build(),
210                        ),
211                    )
212                    .await?;
213                glm::DVec2::new(direction[0].to_mm(), direction[1].to_mm())
214            }
215            Axis2dOrEdgeReference::Edge(edge) => {
216                let edge_id = edge.get_engine_id(exec_state, &args)?;
217                let source_range = args
218                    .labeled
219                    .get("axis")
220                    .map(|arg| arg.source_range)
221                    .unwrap_or(args.source_range);
222                edge::record_refactor_meta_for_consumed_edge(exec_state, edge_id, source_range, &args).await;
223                exec_state
224                    .batch_modeling_cmd(
225                        ModelingCmdMeta::from_args_id(exec_state, &args, new_solid_id),
226                        ModelingCmd::from(
227                            mcmd::RevolveAboutEdge::builder()
228                                .angle(angle)
229                                .target(sketch.id.into())
230                                .edge_id(edge_id)
231                                .tolerance(LengthUnit(tolerance))
232                                .opposite(opposite.clone())
233                                .body_type(body_type)
234                                .build(),
235                        ),
236                    )
237                    .await?;
238                //TODO: fix me! Need to be able to calculate this to ensure the path isn't colinear
239                glm::DVec2::new(0.0, 1.0)
240            }
241            Axis2dOrEdgeReference::EdgeSpecifier(edge_ref) => {
242                // New API: use EdgeReference directly
243                exec_state
244                    .batch_modeling_cmd(
245                        ModelingCmdMeta::from_args_id(exec_state, &args, new_solid_id),
246                        ModelingCmd::from(
247                            mcmd::RevolveAboutEdge::builder()
248                                .angle(angle)
249                                .target(sketch.id.into())
250                                .edge_reference(edge_ref.clone())
251                                .tolerance(LengthUnit(tolerance))
252                                .opposite(opposite.clone())
253                                .body_type(body_type)
254                                .build(),
255                        ),
256                    )
257                    .await?;
258                //TODO: fix me! Need to be able to calculate this to ensure the path isn't colinear
259                glm::DVec2::new(0.0, 1.0)
260            }
261        };
262
263        let mut edge_id = None;
264        // If an edge lies on the axis of revolution it will not exist after the revolve, so
265        // it cannot be used to retrieve data about the solid
266        for path in sketch.paths.clone() {
267            if sketch.synthetic_jump_path_ids.contains(&path.get_id()) {
268                continue;
269            }
270
271            if !path.is_straight_line() {
272                edge_id = Some(path.get_id());
273                break;
274            }
275
276            let from = path.get_from();
277            let to = path.get_to();
278
279            let dir = glm::DVec2::new(to[0].n - from[0].n, to[1].n - from[1].n);
280            if glm::are_collinear2d(&dir, &direction, tolerance) {
281                continue;
282            }
283            edge_id = Some(path.get_id());
284            break;
285        }
286
287        solids.push(
288            do_post_extrude(
289                sketch,
290                new_solid_id.into(),
291                false,
292                &super::extrude::NamedCapTags {
293                    start: tag_start.as_ref(),
294                    end: tag_end.as_ref(),
295                },
296                kittycad_modeling_cmds::shared::ExtrudeMethod::New,
297                exec_state,
298                &args,
299                edge_id,
300                None,
301                body_type,
302                crate::std::extrude::BeingExtruded::Sketch,
303            )
304            .await?,
305        );
306    }
307
308    Ok(solids)
309}
310
311pub async fn coerce_revolve_targets(
312    sketch_values: Vec<KclValue>,
313    body_type: BodyType,
314    tag_start: Option<&TagNode>,
315    tag_end: Option<&TagNode>,
316    exec_state: &mut ExecState,
317    ctx: &ExecutorContext,
318    source_range: crate::SourceRange,
319) -> Result<Vec<Sketch>, KclError> {
320    let mut sketches = Vec::new();
321    let mut segments = Vec::new();
322
323    for value in sketch_values {
324        if let Some(segment) = value.clone().into_segment() {
325            segments.push(segment);
326            continue;
327        }
328
329        let Some(sketch) = Sketch::from_kcl_val(&value) else {
330            return Err(KclError::new_type(KclErrorDetails::new(
331                "Expected sketches or solved sketch segments for revolve.".to_owned(),
332                vec![source_range],
333            )));
334        };
335        sketches.push(sketch);
336    }
337
338    if !segments.is_empty() && !sketches.is_empty() {
339        return Err(KclError::new_semantic(KclErrorDetails::new(
340            "Cannot revolve sketch segments together with sketches in the same call. Use separate `revolve()` calls."
341                .to_owned(),
342            vec![source_range],
343        )));
344    }
345
346    if !segments.is_empty() {
347        if !matches!(body_type, BodyType::Surface) {
348            return Err(KclError::new_semantic(KclErrorDetails::new(
349                "Revolving sketch segments is only supported for surface revolves. Set `bodyType = SURFACE`."
350                    .to_owned(),
351                vec![source_range],
352            )));
353        }
354
355        if tag_start.is_some() || tag_end.is_some() {
356            return Err(KclError::new_semantic(KclErrorDetails::new(
357                "`tagStart` and `tagEnd` are not supported when revolving sketch segments. Segment surface revolves do not create start or end caps."
358                    .to_owned(),
359                vec![source_range],
360            )));
361        }
362
363        let synthetic_sketch = build_segment_surface_sketch(segments, exec_state, ctx, source_range).await?;
364        return Ok(vec![synthetic_sketch]);
365    }
366
367    Ok(sketches)
368}
369
370#[cfg(test)]
371mod tests {
372    use kcl_api::UnitLength;
373
374    use super::*;
375    use crate::execution::AbstractSegment;
376    use crate::execution::MockConfig;
377    use crate::execution::Plane;
378    use crate::execution::Segment;
379    use crate::execution::SegmentKind;
380    use crate::execution::SegmentRepr;
381    use crate::execution::SketchSurface;
382    use crate::execution::types::NumericType;
383    use crate::execution::types::NumericTypeExt;
384    use crate::front::Expr;
385    use crate::front::Number;
386    use crate::front::ObjectId;
387    use crate::front::Point2d;
388    use crate::front::PointCtor;
389    use crate::parsing::ast::types::TagDeclarator;
390    use crate::std::sketch::PlaneData;
391
392    fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
393        Point2d {
394            x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
395            y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
396        }
397    }
398
399    fn segment_value(exec_state: &mut ExecState) -> KclValue {
400        let plane = Plane::from_plane_data_skipping_engine(PlaneData::XY, exec_state).unwrap();
401        let segment = Segment {
402            id: exec_state.next_uuid(),
403            object_id: ObjectId(1),
404            kind: SegmentKind::Point {
405                position: [TyF64::new(0.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())],
406                ctor: Box::new(PointCtor {
407                    position: point_expr(0.0, 0.0),
408                }),
409                freedom: None,
410            },
411            surface: SketchSurface::Plane(Box::new(plane)),
412            sketch_id: exec_state.next_uuid(),
413            sketch: None,
414            tag: None,
415            node_path: None,
416            meta: vec![],
417        };
418        KclValue::Segment {
419            value: Box::new(AbstractSegment {
420                repr: SegmentRepr::Solved {
421                    segment: Box::new(segment),
422                },
423                meta: vec![],
424            }),
425        }
426    }
427
428    #[tokio::test(flavor = "multi_thread")]
429    async fn segment_revolve_rejects_cap_tags() {
430        let ctx = ExecutorContext::new_mock(None).await;
431        let mut exec_state = ExecState::new(&ctx);
432        let err = coerce_revolve_targets(
433            vec![segment_value(&mut exec_state)],
434            BodyType::Surface,
435            Some(&TagDeclarator::new("cap_start")),
436            None,
437            &mut exec_state,
438            &ctx,
439            crate::SourceRange::default(),
440        )
441        .await
442        .unwrap_err();
443
444        assert!(
445            err.message()
446                .contains("`tagStart` and `tagEnd` are not supported when revolving sketch segments"),
447            "{err:?}"
448        );
449        ctx.close().await;
450    }
451
452    #[tokio::test(flavor = "multi_thread")]
453    async fn mock_revolve_rejects_axis_that_collapses_to_zero_in_2d() {
454        let code = r#"
455profile = startSketchOn(XZ)
456  |> startProfile(at = [10, 0])
457  |> line(end = [0, 10])
458  |> line(end = [-10, 0])
459  |> close()
460
461body = revolve(profile, axis = Z, angle = 90deg)
462"#;
463        let program = crate::Program::parse_no_errs(code).unwrap();
464        let ctx = ExecutorContext::new_mock(None).await;
465        let err = ctx.run_mock(&program, &MockConfig::default()).await.unwrap_err();
466        ctx.close().await;
467
468        assert!(
469            err.error
470                .message()
471                .contains("axis of revolution cannot be the zero vector"),
472            "{err:?}"
473        );
474    }
475
476    #[tokio::test(flavor = "multi_thread")]
477    async fn mock_revolve_accepts_nonzero_2d_axis() {
478        let code = r#"
479profile = startSketchOn(XZ)
480  |> startProfile(at = [10, 0])
481  |> line(end = [0, 10])
482  |> line(end = [-10, 0])
483  |> close()
484
485body = revolve(profile, axis = Y, angle = 90deg)
486"#;
487        let program = crate::Program::parse_no_errs(code).unwrap();
488        let ctx = ExecutorContext::new_mock(None).await;
489        let outcome = ctx.run_mock(&program, &MockConfig::default()).await;
490        ctx.close().await;
491
492        outcome.unwrap();
493    }
494}