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 Some(angle) = angle {
116        // Return an error if the angle is zero.
117        // We don't use validate() here because we want to return a specific error message that is
118        // nice and we use the other data in the docs, so we still need use the derive above for the json schema.
119        if !(-360.0..=360.0).contains(&angle) || angle == 0.0 {
120            return Err(KclError::new_semantic(KclErrorDetails::new(
121                format!("Expected angle to be between -360 and 360 and not 0, found `{angle}`"),
122                vec![args.source_range],
123            )));
124        }
125    }
126
127    if let Some(bidirectional_angle) = bidirectional_angle {
128        // Return an error if the angle is zero.
129        // We don't use validate() here because we want to return a specific error message that is
130        // nice and we use the other data in the docs, so we still need use the derive above for the json schema.
131        if !(-360.0..=360.0).contains(&bidirectional_angle) || bidirectional_angle == 0.0 {
132            return Err(KclError::new_semantic(KclErrorDetails::new(
133                format!(
134                    "Expected bidirectional angle to be between -360 and 360 and not 0, found `{bidirectional_angle}`"
135                ),
136                vec![args.source_range],
137            )));
138        }
139
140        if let Some(angle) = angle {
141            let ang = angle.signum() * bidirectional_angle + angle;
142            if !(-360.0..=360.0).contains(&ang) {
143                return Err(KclError::new_semantic(KclErrorDetails::new(
144                    format!("Combined angle and bidirectional must be between -360 and 360, found '{ang}'"),
145                    vec![args.source_range],
146                )));
147            }
148        }
149    }
150
151    if symmetric.unwrap_or(false) && bidirectional_angle.is_some() {
152        return Err(KclError::new_semantic(KclErrorDetails::new(
153            "You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
154                .to_owned(),
155            vec![args.source_range],
156        )));
157    }
158
159    let angle = Angle::from_degrees(angle.unwrap_or(360.0));
160
161    let bidirectional_angle = bidirectional_angle.map(Angle::from_degrees);
162
163    let opposite = match (symmetric, bidirectional_angle) {
164        (Some(true), _) => Opposite::Symmetric,
165        (None, None) => Opposite::None,
166        (Some(false), None) => Opposite::None,
167        (None, Some(angle)) => Opposite::Other(angle),
168        (Some(false), Some(angle)) => Opposite::Other(angle),
169    };
170
171    let mut solids = Vec::new();
172    for sketch in &sketches {
173        let new_solid_id = exec_state.next_uuid();
174        let tolerance = tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM);
175
176        let direction = match &axis {
177            Axis2dOrEdgeReference::Axis { direction, origin } => {
178                exec_state
179                    .batch_modeling_cmd(
180                        ModelingCmdMeta::from_args_id(exec_state, &args, new_solid_id),
181                        ModelingCmd::from(
182                            mcmd::Revolve::builder()
183                                .angle(angle)
184                                .target(sketch.id.into())
185                                .axis(Point3d {
186                                    x: direction[0].to_mm(),
187                                    y: direction[1].to_mm(),
188                                    z: 0.0,
189                                })
190                                .origin(Point3d {
191                                    x: LengthUnit(origin[0].to_mm()),
192                                    y: LengthUnit(origin[1].to_mm()),
193                                    z: LengthUnit(0.0),
194                                })
195                                .tolerance(LengthUnit(tolerance))
196                                .axis_is_2d(true)
197                                .opposite(opposite.clone())
198                                .body_type(body_type)
199                                .build(),
200                        ),
201                    )
202                    .await?;
203                glm::DVec2::new(direction[0].to_mm(), direction[1].to_mm())
204            }
205            Axis2dOrEdgeReference::Edge(edge) => {
206                let edge_id = edge.get_engine_id(exec_state, &args)?;
207                exec_state
208                    .batch_modeling_cmd(
209                        ModelingCmdMeta::from_args_id(exec_state, &args, new_solid_id),
210                        ModelingCmd::from(
211                            mcmd::RevolveAboutEdge::builder()
212                                .angle(angle)
213                                .target(sketch.id.into())
214                                .edge_id(edge_id)
215                                .tolerance(LengthUnit(tolerance))
216                                .opposite(opposite.clone())
217                                .body_type(body_type)
218                                .build(),
219                        ),
220                    )
221                    .await?;
222                //TODO: fix me! Need to be able to calculate this to ensure the path isn't colinear
223                glm::DVec2::new(0.0, 1.0)
224            }
225            Axis2dOrEdgeReference::EdgeSpecifier(edge_ref) => {
226                // New API: use EdgeReference directly
227                exec_state
228                    .batch_modeling_cmd(
229                        ModelingCmdMeta::from_args_id(exec_state, &args, new_solid_id),
230                        ModelingCmd::from(
231                            mcmd::RevolveAboutEdge::builder()
232                                .angle(angle)
233                                .target(sketch.id.into())
234                                .edge_reference(edge_ref.clone())
235                                .tolerance(LengthUnit(tolerance))
236                                .opposite(opposite.clone())
237                                .body_type(body_type)
238                                .build(),
239                        ),
240                    )
241                    .await?;
242                //TODO: fix me! Need to be able to calculate this to ensure the path isn't colinear
243                glm::DVec2::new(0.0, 1.0)
244            }
245        };
246
247        let mut edge_id = None;
248        // If an edge lies on the axis of revolution it will not exist after the revolve, so
249        // it cannot be used to retrieve data about the solid
250        for path in sketch.paths.clone() {
251            if sketch.synthetic_jump_path_ids.contains(&path.get_id()) {
252                continue;
253            }
254
255            if !path.is_straight_line() {
256                edge_id = Some(path.get_id());
257                break;
258            }
259
260            let from = path.get_from();
261            let to = path.get_to();
262
263            let dir = glm::DVec2::new(to[0].n - from[0].n, to[1].n - from[1].n);
264            if glm::are_collinear2d(&dir, &direction, tolerance) {
265                continue;
266            }
267            edge_id = Some(path.get_id());
268            break;
269        }
270
271        solids.push(
272            do_post_extrude(
273                sketch,
274                new_solid_id.into(),
275                false,
276                &super::extrude::NamedCapTags {
277                    start: tag_start.as_ref(),
278                    end: tag_end.as_ref(),
279                },
280                kittycad_modeling_cmds::shared::ExtrudeMethod::New,
281                exec_state,
282                &args,
283                edge_id,
284                None,
285                body_type,
286                crate::std::extrude::BeingExtruded::Sketch,
287            )
288            .await?,
289        );
290    }
291
292    Ok(solids)
293}
294
295pub async fn coerce_revolve_targets(
296    sketch_values: Vec<KclValue>,
297    body_type: BodyType,
298    tag_start: Option<&TagNode>,
299    tag_end: Option<&TagNode>,
300    exec_state: &mut ExecState,
301    ctx: &ExecutorContext,
302    source_range: crate::SourceRange,
303) -> Result<Vec<Sketch>, KclError> {
304    let mut sketches = Vec::new();
305    let mut segments = Vec::new();
306
307    for value in sketch_values {
308        if let Some(segment) = value.clone().into_segment() {
309            segments.push(segment);
310            continue;
311        }
312
313        let Some(sketch) = Sketch::from_kcl_val(&value) else {
314            return Err(KclError::new_type(KclErrorDetails::new(
315                "Expected sketches or solved sketch segments for revolve.".to_owned(),
316                vec![source_range],
317            )));
318        };
319        sketches.push(sketch);
320    }
321
322    if !segments.is_empty() && !sketches.is_empty() {
323        return Err(KclError::new_semantic(KclErrorDetails::new(
324            "Cannot revolve sketch segments together with sketches in the same call. Use separate `revolve()` calls."
325                .to_owned(),
326            vec![source_range],
327        )));
328    }
329
330    if !segments.is_empty() {
331        if !matches!(body_type, BodyType::Surface) {
332            return Err(KclError::new_semantic(KclErrorDetails::new(
333                "Revolving sketch segments is only supported for surface revolves. Set `bodyType = SURFACE`."
334                    .to_owned(),
335                vec![source_range],
336            )));
337        }
338
339        if tag_start.is_some() || tag_end.is_some() {
340            return Err(KclError::new_semantic(KclErrorDetails::new(
341                "`tagStart` and `tagEnd` are not supported when revolving sketch segments. Segment surface revolves do not create start or end caps."
342                    .to_owned(),
343                vec![source_range],
344            )));
345        }
346
347        let synthetic_sketch = build_segment_surface_sketch(segments, exec_state, ctx, source_range).await?;
348        return Ok(vec![synthetic_sketch]);
349    }
350
351    Ok(sketches)
352}
353
354#[cfg(test)]
355mod tests {
356    use kcl_api::UnitLength;
357
358    use super::*;
359    use crate::execution::AbstractSegment;
360    use crate::execution::Plane;
361    use crate::execution::Segment;
362    use crate::execution::SegmentKind;
363    use crate::execution::SegmentRepr;
364    use crate::execution::SketchSurface;
365    use crate::execution::types::NumericType;
366    use crate::execution::types::NumericTypeExt;
367    use crate::front::Expr;
368    use crate::front::Number;
369    use crate::front::ObjectId;
370    use crate::front::Point2d;
371    use crate::front::PointCtor;
372    use crate::parsing::ast::types::TagDeclarator;
373    use crate::std::sketch::PlaneData;
374
375    fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
376        Point2d {
377            x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
378            y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
379        }
380    }
381
382    fn segment_value(exec_state: &mut ExecState) -> KclValue {
383        let plane = Plane::from_plane_data_skipping_engine(PlaneData::XY, exec_state).unwrap();
384        let segment = Segment {
385            id: exec_state.next_uuid(),
386            object_id: ObjectId(1),
387            kind: SegmentKind::Point {
388                position: [TyF64::new(0.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())],
389                ctor: Box::new(PointCtor {
390                    position: point_expr(0.0, 0.0),
391                }),
392                freedom: None,
393            },
394            surface: SketchSurface::Plane(Box::new(plane)),
395            sketch_id: exec_state.next_uuid(),
396            sketch: None,
397            tag: None,
398            node_path: None,
399            meta: vec![],
400        };
401        KclValue::Segment {
402            value: Box::new(AbstractSegment {
403                repr: SegmentRepr::Solved {
404                    segment: Box::new(segment),
405                },
406                meta: vec![],
407            }),
408        }
409    }
410
411    #[tokio::test(flavor = "multi_thread")]
412    async fn segment_revolve_rejects_cap_tags() {
413        let ctx = ExecutorContext::new_mock(None).await;
414        let mut exec_state = ExecState::new(&ctx);
415        let err = coerce_revolve_targets(
416            vec![segment_value(&mut exec_state)],
417            BodyType::Surface,
418            Some(&TagDeclarator::new("cap_start")),
419            None,
420            &mut exec_state,
421            &ctx,
422            crate::SourceRange::default(),
423        )
424        .await
425        .unwrap_err();
426
427        assert!(
428            err.message()
429                .contains("`tagStart` and `tagEnd` are not supported when revolving sketch segments"),
430            "{err:?}"
431        );
432        ctx.close().await;
433    }
434}