Skip to main content

kcl_lib/std/
extrude.rs

1//! Functions related to extruding.
2
3use std::collections::HashMap;
4
5use anyhow::Result;
6use indexmap::IndexMap;
7use kcmc::ModelingCmd;
8use kcmc::each_cmd as mcmd;
9use kcmc::length_unit::LengthUnit;
10use kcmc::ok_response::OkModelingCmdResponse;
11use kcmc::output::ExtrusionFaceInfo;
12use kcmc::shared::ExtrudeReference;
13use kcmc::shared::ExtrusionFaceCapType;
14use kcmc::shared::Opposite;
15use kcmc::shared::Point3d as KPoint3d; // Point3d is already defined in this pkg, to impl ts_rs traits.
16use kcmc::websocket::ModelingCmdReq;
17use kcmc::websocket::OkWebSocketResponseData;
18use kittycad_modeling_cmds::shared::Angle;
19use kittycad_modeling_cmds::shared::BodyType;
20use kittycad_modeling_cmds::shared::DirectionType;
21use kittycad_modeling_cmds::shared::EntityReference;
22use kittycad_modeling_cmds::shared::ExtrudeMethod;
23use kittycad_modeling_cmds::shared::Point2d;
24use kittycad_modeling_cmds::{self as kcmc};
25use uuid::Uuid;
26
27use super::DEFAULT_TOLERANCE_MM;
28use super::args::FromKclValue;
29use super::args::TyF64;
30use super::utils::point_to_mm;
31use crate::errors::KclError;
32use crate::errors::KclErrorDetails;
33use crate::execution::ArtifactId;
34use crate::execution::CreatorEdge;
35use crate::execution::CreatorFace;
36use crate::execution::ExecState;
37use crate::execution::ExecutorContext;
38use crate::execution::Extrudable;
39use crate::execution::ExtrudePlane;
40use crate::execution::ExtrudeSurface;
41use crate::execution::GeoMeta;
42use crate::execution::KclValue;
43use crate::execution::ModelingCmdMeta;
44use crate::execution::Path;
45use crate::execution::ProfileClosed;
46use crate::execution::Segment;
47use crate::execution::SegmentKind;
48use crate::execution::Sketch;
49use crate::execution::SketchSurface;
50use crate::execution::Solid;
51use crate::execution::SolidCreator;
52use crate::execution::annotations;
53use crate::execution::types::ArrayLen;
54use crate::execution::types::PrimitiveType;
55use crate::execution::types::RuntimeType;
56use crate::parsing::ast::types::TagDeclarator;
57use crate::parsing::ast::types::TagNode;
58use crate::std::Args;
59use crate::std::axis_or_reference::Point3dAxis3dOrGeometryReference;
60use crate::std::axis_or_reference::Point3dOrEdgeReference;
61use crate::std::edge::{self};
62use crate::std::solver::create_segments_in_engine;
63
64/// Extrudes by a given amount.
65pub async fn extrude(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
66    let sketch_values: Vec<KclValue> = args.get_unlabeled_kw_arg(
67        "sketches",
68        &RuntimeType::Array(
69            Box::new(RuntimeType::Primitive(PrimitiveType::Any)),
70            ArrayLen::Minimum(1),
71        ),
72        exec_state,
73    )?;
74
75    let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
76    let to_raw = args.get_kw_arg_opt(
77        "to",
78        &RuntimeType::Union(vec![
79            RuntimeType::point3d(),
80            RuntimeType::Primitive(PrimitiveType::Axis3d),
81            RuntimeType::Primitive(PrimitiveType::Edge),
82            RuntimeType::plane(),
83            RuntimeType::Primitive(PrimitiveType::Face),
84            RuntimeType::sketch(),
85            RuntimeType::Primitive(PrimitiveType::Solid),
86            RuntimeType::tagged_edge(),
87            RuntimeType::tagged_face(),
88            RuntimeType::Primitive(PrimitiveType::Any),
89        ]),
90        exec_state,
91    )?;
92    let to = match to_raw {
93        None => None,
94        Some(v) => {
95            let inner = if let KclValue::Object { value: ref obj, .. } = v {
96                if edge::is_edge_specifier_object(&v) {
97                    Point3dAxis3dOrGeometryReference::EdgeToReference(edge::parse_edge_specifier_object(obj, &args)?)
98                } else {
99                    Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
100                        KclError::new_type(KclErrorDetails::new(
101                            "Invalid value for `to`".to_owned(),
102                            vec![args.source_range],
103                        ))
104                    })?
105                }
106            } else {
107                Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
108                    KclError::new_type(KclErrorDetails::new(
109                        "Invalid value for `to`".to_owned(),
110                        vec![args.source_range],
111                    ))
112                })?
113            };
114            Some(inner)
115        }
116    };
117    let symmetric = args.get_kw_arg_opt("symmetric", &RuntimeType::bool(), exec_state)?;
118    let bidirectional_length: Option<TyF64> =
119        args.get_kw_arg_opt("bidirectionalLength", &RuntimeType::length(), exec_state)?;
120    let direction_raw = args.get_kw_arg_opt("direction", &RuntimeType::any(), exec_state)?;
121    let direction = match direction_raw {
122        None => None,
123        Some(v) => {
124            let inner = if edge::is_edge_specifier_object(&v) {
125                Point3dOrEdgeReference::EdgeSpecifier(edge::parse_edge_specifier_value(&v, &args)?)
126            } else {
127                Point3dOrEdgeReference::from_kcl_val(&v).ok_or_else(|| {
128                    KclError::new_type(KclErrorDetails::new(
129                        "Invalid value for `direction`".to_owned(),
130                        vec![args.source_range],
131                    ))
132                })?
133            };
134            Some(inner)
135        }
136    };
137    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
138    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
139    let draft_angle: Option<TyF64> = args.get_kw_arg_opt("draftAngle", &RuntimeType::degrees(), exec_state)?;
140    let twist_angle: Option<TyF64> = args.get_kw_arg_opt("twistAngle", &RuntimeType::degrees(), exec_state)?;
141    let twist_angle_step: Option<TyF64> = args.get_kw_arg_opt("twistAngleStep", &RuntimeType::degrees(), exec_state)?;
142    let twist_center: Option<[TyF64; 2]> = args.get_kw_arg_opt("twistCenter", &RuntimeType::point2d(), exec_state)?;
143    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
144    let method: Option<String> = args.get_kw_arg_opt("method", &RuntimeType::string(), exec_state)?;
145    let hide_seams: Option<bool> = args.get_kw_arg_opt("hideSeams", &RuntimeType::bool(), exec_state)?;
146    let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
147    let sketches = coerce_extrude_targets(
148        sketch_values,
149        body_type.unwrap_or_default(),
150        tag_start.as_ref(),
151        tag_end.as_ref(),
152        exec_state,
153        &args.ctx,
154        args.source_range,
155    )
156    .await?;
157
158    let result = inner_extrude(
159        sketches,
160        length,
161        to,
162        symmetric,
163        direction,
164        bidirectional_length,
165        tag_start,
166        tag_end,
167        draft_angle,
168        twist_angle,
169        twist_angle_step,
170        twist_center,
171        tolerance,
172        method,
173        hide_seams,
174        body_type,
175        exec_state,
176        args,
177    )
178    .await?;
179
180    Ok(result.into())
181}
182
183pub async fn coerce_extrude_targets(
184    sketch_values: Vec<KclValue>,
185    body_type: BodyType,
186    tag_start: Option<&TagNode>,
187    tag_end: Option<&TagNode>,
188    exec_state: &mut ExecState,
189    ctx: &ExecutorContext,
190    source_range: crate::SourceRange,
191) -> Result<Vec<Extrudable>, KclError> {
192    let mut extrudables = Vec::new();
193    let mut segments = Vec::new();
194
195    for value in sketch_values {
196        if let Some(segment) = value.clone().into_segment() {
197            segments.push(segment);
198            continue;
199        }
200
201        if edge::is_edge_specifier_object(&value) {
202            extrudables.push(Extrudable::EdgeSpecifier(edge::parse_edge_specifier_value_at(
203                &value,
204                source_range,
205            )?));
206            continue;
207        }
208
209        let Some(extrudable) = Extrudable::from_kcl_val(&value) else {
210            return Err(KclError::new_type(KclErrorDetails::new(
211                "Expected sketches, faces, tagged faces, or solved sketch segments for extrusion.".to_owned(),
212                vec![source_range],
213            )));
214        };
215        extrudables.push(extrudable);
216    }
217
218    if !segments.is_empty() && !extrudables.is_empty() {
219        return Err(KclError::new_semantic(KclErrorDetails::new(
220            "Cannot extrude sketch segments together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
221            vec![source_range],
222        )));
223    }
224
225    if !segments.is_empty() {
226        if !matches!(body_type, BodyType::Surface) {
227            let kind_of_extrude = match body_type {
228                BodyType::Solid => "solid extrude",
229                BodyType::Surface => "surface extrude",
230                _ => "non-surface extrude",
231            };
232            return Err(KclError::new_semantic(KclErrorDetails::new(
233                format!(
234                    "You're trying to perform a {kind_of_extrude} on an edge, but edges can only be extruded with surface extrudes. To do a solid extrude, select a closed sketch region instead. To extrude these edges, do a surface extrude by using `bodyType = SURFACE` instead."
235                ),
236                vec![source_range],
237            )));
238        }
239
240        if tag_start.is_some() || tag_end.is_some() {
241            return Err(KclError::new_semantic(KclErrorDetails::new(
242                "`tagStart` and `tagEnd` are not supported when extruding sketch segments. Segment surface extrudes do not create start or end caps."
243                    .to_owned(),
244                vec![source_range],
245            )));
246        }
247
248        let synthetic_sketch = build_segment_surface_sketch(segments, exec_state, ctx, source_range).await?;
249        return Ok(vec![Extrudable::from(synthetic_sketch)]);
250    }
251
252    // Edges behave like sketch segments: they can only be surface-extruded, they
253    // don't create caps, and they can't be mixed with sketches or faces. Enforce
254    // the same rules so these cases fail loudly instead of silently producing a
255    // surface (or silently ignoring `tagStart`/`tagEnd`).
256    let has_edge = extrudables.iter().any(|e| {
257        matches!(
258            e,
259            Extrudable::Edge(_) | Extrudable::EdgeTag(_) | Extrudable::EdgeSpecifier(_)
260        )
261    });
262    if has_edge {
263        let has_non_edge = extrudables.iter().any(|e| {
264            !matches!(
265                e,
266                Extrudable::Edge(_) | Extrudable::EdgeTag(_) | Extrudable::EdgeSpecifier(_)
267            )
268        });
269        if has_non_edge {
270            return Err(KclError::new_semantic(KclErrorDetails::new(
271                "Cannot extrude edges together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
272                vec![source_range],
273            )));
274        }
275
276        if !matches!(body_type, BodyType::Surface) {
277            let kind_of_extrude = match body_type {
278                BodyType::Solid => "solid extrude",
279                BodyType::Surface => "surface extrude",
280                _ => "non-surface extrude",
281            };
282            return Err(KclError::new_semantic(KclErrorDetails::new(
283                format!(
284                    "You're trying to perform a {kind_of_extrude} on an edge, but edges can only be extruded with surface extrudes. To do a solid extrude, select a closed sketch region instead. To extrude these edges, do a surface extrude by using `bodyType = SURFACE` instead."
285                ),
286                vec![source_range],
287            )));
288        }
289
290        if tag_start.is_some() || tag_end.is_some() {
291            return Err(KclError::new_semantic(KclErrorDetails::new(
292                "`tagStart` and `tagEnd` are not supported when extruding edges. Edge surface extrudes do not create start or end caps."
293                    .to_owned(),
294                vec![source_range],
295            )));
296        }
297    }
298
299    Ok(extrudables)
300}
301
302pub(crate) async fn build_segment_surface_sketch(
303    mut segments: Vec<Segment>,
304    exec_state: &mut ExecState,
305    ctx: &ExecutorContext,
306    source_range: crate::SourceRange,
307) -> Result<Sketch, KclError> {
308    let Some(first_segment) = segments.first() else {
309        return Err(KclError::new_semantic(KclErrorDetails::new(
310            "Expected at least one sketch segment.".to_owned(),
311            vec![source_range],
312        )));
313    };
314
315    let sketch_id = first_segment.sketch_id;
316    let sketch_surface = first_segment.surface.clone();
317    for segment in &segments {
318        if segment.sketch_id != sketch_id {
319            return Err(KclError::new_semantic(KclErrorDetails::new(
320                "All sketch segments passed to this operation must come from the same sketch.".to_owned(),
321                vec![source_range],
322            )));
323        }
324
325        if segment.surface != sketch_surface {
326            return Err(KclError::new_semantic(KclErrorDetails::new(
327                "All sketch segments passed to this operation must lie on the same sketch surface.".to_owned(),
328                vec![source_range],
329            )));
330        }
331
332        if matches!(segment.kind, SegmentKind::Point { .. }) {
333            return Err(KclError::new_semantic(KclErrorDetails::new(
334                "Point segments cannot be used here. Select line, arc, or circle segments instead.".to_owned(),
335                vec![source_range],
336            )));
337        }
338
339        if segment.is_construction() {
340            return Err(KclError::new_semantic(KclErrorDetails::new(
341                "Construction segments cannot be used here. Select non-construction sketch segments instead."
342                    .to_owned(),
343                vec![source_range],
344            )));
345        }
346    }
347
348    let synthetic_sketch_id = exec_state.next_uuid();
349    let segment_tags = IndexMap::from_iter(segments.iter().filter_map(|segment| {
350        segment
351            .tag
352            .as_ref()
353            .map(|tag| (segment.object_id, TagDeclarator::new(&tag.value)))
354    }));
355
356    for segment in &mut segments {
357        segment.id = exec_state.next_uuid();
358        segment.sketch_id = synthetic_sketch_id;
359        segment.sketch = None;
360    }
361
362    create_segments_in_engine(
363        &sketch_surface,
364        synthetic_sketch_id,
365        &mut segments,
366        &segment_tags,
367        ctx,
368        exec_state,
369        source_range,
370    )
371    .await?
372    .ok_or_else(|| {
373        KclError::new_semantic(KclErrorDetails::new(
374            "Expected at least one usable sketch segment.".to_owned(),
375            vec![source_range],
376        ))
377    })
378}
379
380#[allow(clippy::too_many_arguments)]
381async fn inner_extrude(
382    extrudables: Vec<Extrudable>,
383    length: Option<TyF64>,
384    to: Option<Point3dAxis3dOrGeometryReference>,
385    symmetric: Option<bool>,
386    direction: Option<Point3dOrEdgeReference>,
387    bidirectional_length: Option<TyF64>,
388    tag_start: Option<TagNode>,
389    tag_end: Option<TagNode>,
390    draft_angle: Option<TyF64>,
391    twist_angle: Option<TyF64>,
392    twist_angle_step: Option<TyF64>,
393    twist_center: Option<[TyF64; 2]>,
394    tolerance: Option<TyF64>,
395    method: Option<String>,
396    hide_seams: Option<bool>,
397    body_type: Option<BodyType>,
398    exec_state: &mut ExecState,
399    args: Args,
400) -> Result<Vec<Solid>, KclError> {
401    let body_type = body_type.unwrap_or_default();
402
403    if matches!(body_type, BodyType::Solid) && extrudables.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No))
404    {
405        return Err(KclError::new_semantic(KclErrorDetails::new(
406            "Cannot solid extrude an open profile. Either close the profile, or use a surface extrude.".to_owned(),
407            vec![args.source_range],
408        )));
409    }
410
411    if draft_angle.is_some() && twist_angle.is_some() {
412        return Err(KclError::new_semantic(KclErrorDetails::new(
413            "Zoo currently does not support adding both draft angle and twist angle to an extrude simultaneously"
414                .to_owned(),
415            vec![args.source_range],
416        )));
417    }
418
419    if direction.is_some() && twist_angle.is_some() {
420        return Err(KclError::new_semantic(KclErrorDetails::new(
421            "Zoo currently does not support adding both direction and twist angle to an extrude simultaneously"
422                .to_owned(),
423            vec![args.source_range],
424        )));
425    }
426
427    // Extrude the element(s).
428    let mut solids = Vec::new();
429    let tolerance = LengthUnit(tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM));
430
431    let extrude_method = match method.as_deref() {
432        Some("new" | "NEW") => ExtrudeMethod::New,
433        Some("merge" | "MERGE") => ExtrudeMethod::Merge,
434        None => ExtrudeMethod::default(),
435        Some(other) => {
436            return Err(KclError::new_semantic(KclErrorDetails::new(
437                format!("Unknown merge method {other}, try using `MERGE` or `NEW`"),
438                vec![args.source_range],
439            )));
440        }
441    };
442
443    if symmetric.unwrap_or(false) && bidirectional_length.is_some() {
444        return Err(KclError::new_semantic(KclErrorDetails::new(
445            "You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
446                .to_owned(),
447            vec![args.source_range],
448        )));
449    }
450
451    if (length.is_some() || twist_angle.is_some()) && to.is_some() {
452        return Err(KclError::new_semantic(KclErrorDetails::new(
453            "You cannot give `length` or `twist` params with the `to` param, you have to choose one or the other"
454                .to_owned(),
455            vec![args.source_range],
456        )));
457    }
458
459    let bidirection = bidirectional_length.map(|l| LengthUnit(l.to_mm()));
460
461    let opposite = match (symmetric, bidirection) {
462        (Some(true), _) => Opposite::Symmetric,
463        (None, None) => Opposite::None,
464        (Some(false), None) => Opposite::None,
465        (None, Some(length)) => Opposite::Other(length),
466        (Some(false), Some(length)) => Opposite::Other(length),
467    };
468
469    for extrudable in &extrudables {
470        let is_edge = match extrudable {
471            Extrudable::Sketch(..) => false,
472            Extrudable::FaceTag(_) => false,
473            Extrudable::Face(_) => false,
474            Extrudable::EdgeTag(_) => true,
475            Extrudable::Edge(_) => true,
476            Extrudable::EdgeSpecifier(_) => true,
477        };
478        let extrude_cmd_id = exec_state.next_uuid();
479        let (sketch_or_face_id, target_reference) = match extrudable {
480            Extrudable::EdgeSpecifier(spec) => (
481                None,
482                Some(edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?),
483            ),
484            _ => (Some(extrudable.id_to_extrude(exec_state, &args, false).await?), None),
485        };
486        if to.is_some() && sketch_or_face_id.is_none() {
487            return Err(KclError::new_semantic(KclErrorDetails::new(
488                "Edge specifiers cannot be extruded to a reference".to_owned(),
489                vec![args.source_range],
490            )));
491        }
492        let concrete_target = || {
493            sketch_or_face_id.ok_or_else(|| {
494                KclError::new_semantic(KclErrorDetails::new(
495                    "This extrusion requires a concrete target UUID".to_owned(),
496                    vec![args.source_range],
497                ))
498            })
499        };
500        if is_edge
501            && let Some(edge_id) = sketch_or_face_id
502            && let Some(target_source_range) = args.unlabeled_kw_arg_unconverted().map(|arg| arg.source_range)
503            && let Some(pending) = exec_state.pending_edge_refactor_meta(edge_id, target_source_range)
504            && let Ok(meta) =
505                edge::get_refactor_meta_for_edge(exec_state, edge_id, &args, pending.source_range, pending.stdlib_fn)
506                    .await
507        {
508            exec_state.record_edge_refactor_meta(meta);
509        }
510        let cmd = match (
511            &twist_angle,
512            &twist_angle_step,
513            &twist_center,
514            length.clone(),
515            &to,
516            &direction,
517        ) {
518            (Some(angle), angle_step, center, Some(length), None, None) => {
519                let center = center.clone().map(point_to_mm).map(Point2d::from).unwrap_or_default();
520                let total_rotation_angle = Angle::from_degrees(angle.to_degrees(exec_state, args.source_range));
521                let angle_step_size = Angle::from_degrees(
522                    angle_step
523                        .clone()
524                        .map(|a| a.to_degrees(exec_state, args.source_range))
525                        .unwrap_or(15.0),
526                );
527                ModelingCmd::from(
528                    mcmd::TwistExtrude::builder()
529                        .target(
530                            sketch_or_face_id
531                                .ok_or_else(|| {
532                                    KclError::new_semantic(KclErrorDetails::new(
533                                        "Edge specifiers cannot be used with twist extrusion".to_owned(),
534                                        vec![args.source_range],
535                                    ))
536                                })?
537                                .into(),
538                        )
539                        .distance(LengthUnit(length.to_mm()))
540                        .center_2d(center)
541                        .total_rotation_angle(total_rotation_angle)
542                        .angle_step_size(angle_step_size)
543                        .tolerance(tolerance)
544                        .body_type(body_type)
545                        .build(),
546                )
547            }
548            (None, None, None, Some(length), None, None) => ModelingCmd::from(
549                mcmd::Extrude::builder()
550                    .maybe_target(sketch_or_face_id.map(Into::into))
551                    .maybe_target_reference(target_reference.clone())
552                    .distance(LengthUnit(length.to_mm()))
553                    .opposite(opposite.clone())
554                    .maybe_draft_angle(
555                        draft_angle
556                            .clone()
557                            .map(|a| Angle::from_degrees(a.to_degrees(exec_state, args.source_range))),
558                    )
559                    .extrude_method(extrude_method)
560                    .body_type(body_type)
561                    .maybe_merge_coplanar_faces(hide_seams)
562                    .build(),
563            ),
564            (None, None, None, Some(length), None, Some(dir)) => {
565                let (direction3d, direction_edge_id) = match dir {
566                    Point3dOrEdgeReference::Point(p) => (
567                        Some(DirectionType::Axis {
568                            direction: KPoint3d {
569                                x: p[0].n,
570                                y: p[1].n,
571                                z: p[2].n,
572                            },
573                        }),
574                        None,
575                    ),
576                    Point3dOrEdgeReference::Edge(edge) => {
577                        let edge_id = match edge {
578                            crate::std::fillet::EdgeReference::Uuid(uuid) => *uuid,
579                            crate::std::fillet::EdgeReference::Tag(tag) => match tag.get_cur_info() {
580                                Some(info) => info.id,
581                                None => {
582                                    return Err(KclError::new_semantic(KclErrorDetails::new(
583                                        "Failed to get current info for tag".to_string(),
584                                        vec![args.source_range],
585                                    )));
586                                }
587                            },
588                        };
589                        (Some(DirectionType::Edge { id: edge_id }), Some(edge_id))
590                    }
591                    Point3dOrEdgeReference::EdgeSpecifier(_) => (None, None),
592                };
593                if let Some(edge_id) = direction_edge_id
594                    && let Some(direction_source_range) = args.labeled.get("direction").map(|arg| arg.source_range)
595                    && let Some(pending) = exec_state.pending_edge_refactor_meta(edge_id, direction_source_range)
596                    && let Ok(meta) = edge::get_refactor_meta_for_edge(
597                        exec_state,
598                        edge_id,
599                        &args,
600                        pending.source_range,
601                        pending.stdlib_fn,
602                    )
603                    .await
604                {
605                    exec_state.record_edge_refactor_meta(meta);
606                }
607                let direction_reference = match dir {
608                    Point3dOrEdgeReference::EdgeSpecifier(spec) => {
609                        Some(edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?)
610                    }
611                    _ => None,
612                };
613                ModelingCmd::from(
614                    mcmd::Extrude::builder()
615                        .maybe_target(sketch_or_face_id.map(Into::into))
616                        .maybe_target_reference(target_reference.clone())
617                        .distance(LengthUnit(length.to_mm()))
618                        .opposite(opposite.clone())
619                        .maybe_draft_angle(
620                            draft_angle
621                                .clone()
622                                .map(|a| Angle::from_degrees(a.to_degrees(exec_state, args.source_range))),
623                        )
624                        .extrude_method(extrude_method)
625                        .body_type(body_type)
626                        .maybe_merge_coplanar_faces(hide_seams)
627                        .maybe_direction(direction3d)
628                        .maybe_direction_reference(direction_reference)
629                        .build(),
630                )
631            }
632            (None, None, None, None, Some(to), None) => match to {
633                Point3dAxis3dOrGeometryReference::Point(point) => ModelingCmd::from(
634                    mcmd::ExtrudeToReference::builder()
635                        .target(concrete_target()?.into())
636                        .reference(ExtrudeReference::Point {
637                            point: KPoint3d {
638                                x: LengthUnit(point[0].to_mm()),
639                                y: LengthUnit(point[1].to_mm()),
640                                z: LengthUnit(point[2].to_mm()),
641                            },
642                        })
643                        .extrude_method(extrude_method)
644                        .body_type(body_type)
645                        .build(),
646                ),
647                Point3dAxis3dOrGeometryReference::Axis { direction, origin } => ModelingCmd::from(
648                    mcmd::ExtrudeToReference::builder()
649                        .target(concrete_target()?.into())
650                        .reference(ExtrudeReference::Axis {
651                            axis: KPoint3d {
652                                x: direction[0].to_mm(),
653                                y: direction[1].to_mm(),
654                                z: direction[2].to_mm(),
655                            },
656                            point: KPoint3d {
657                                x: LengthUnit(origin[0].to_mm()),
658                                y: LengthUnit(origin[1].to_mm()),
659                                z: LengthUnit(origin[2].to_mm()),
660                            },
661                        })
662                        .extrude_method(extrude_method)
663                        .body_type(body_type)
664                        .build(),
665                ),
666                Point3dAxis3dOrGeometryReference::Plane(plane) => {
667                    let plane_id = if plane.is_uninitialized() {
668                        if plane.info.origin.units.is_none() {
669                            return Err(KclError::new_semantic(KclErrorDetails::new(
670                                "Origin of plane has unknown units".to_string(),
671                                vec![args.source_range],
672                            )));
673                        }
674                        let sketch_plane = crate::std::sketch::make_sketch_plane_from_orientation(
675                            plane.clone().info.into_plane_data(),
676                            exec_state,
677                            &args,
678                        )
679                        .await?;
680                        sketch_plane.id
681                    } else {
682                        plane.id
683                    };
684                    ModelingCmd::from(
685                        mcmd::ExtrudeToReference::builder()
686                            .target(concrete_target()?.into())
687                            .reference(ExtrudeReference::EntityReference {
688                                entity_id: Some(plane_id),
689                                entity_reference: None,
690                            })
691                            .extrude_method(extrude_method)
692                            .body_type(body_type)
693                            .build(),
694                    )
695                }
696                Point3dAxis3dOrGeometryReference::Edge(edge_ref) => {
697                    let edge_id = edge_ref.get_engine_id(exec_state, &args)?;
698                    ModelingCmd::from(
699                        mcmd::ExtrudeToReference::builder()
700                            .target(concrete_target()?.into())
701                            .reference(ExtrudeReference::EntityReference {
702                                entity_id: Some(edge_id),
703                                entity_reference: None,
704                            })
705                            .extrude_method(extrude_method)
706                            .body_type(body_type)
707                            .build(),
708                    )
709                }
710                Point3dAxis3dOrGeometryReference::Face(face_tag) => {
711                    let face_id = face_tag.get_face_id_from_tag(exec_state, &args, false).await?;
712                    ModelingCmd::from(
713                        mcmd::ExtrudeToReference::builder()
714                            .target(concrete_target()?.into())
715                            .reference(ExtrudeReference::EntityReference {
716                                entity_id: Some(face_id),
717                                entity_reference: None,
718                            })
719                            .extrude_method(extrude_method)
720                            .body_type(body_type)
721                            .build(),
722                    )
723                }
724                Point3dAxis3dOrGeometryReference::Sketch(sketch_ref) => ModelingCmd::from(
725                    mcmd::ExtrudeToReference::builder()
726                        .target(concrete_target()?.into())
727                        .reference(ExtrudeReference::EntityReference {
728                            entity_id: Some(sketch_ref.id),
729                            entity_reference: None,
730                        })
731                        .extrude_method(extrude_method)
732                        .body_type(body_type)
733                        .build(),
734                ),
735                Point3dAxis3dOrGeometryReference::Solid(solid) => ModelingCmd::from(
736                    mcmd::ExtrudeToReference::builder()
737                        .target(concrete_target()?.into())
738                        .reference(ExtrudeReference::EntityReference {
739                            entity_id: Some(solid.id),
740                            entity_reference: None,
741                        })
742                        .extrude_method(extrude_method)
743                        .body_type(body_type)
744                        .build(),
745                ),
746                Point3dAxis3dOrGeometryReference::TaggedEdgeOrFace(tag) => {
747                    let tagged_edge_or_face = args.get_tag_engine_info(exec_state, tag)?;
748                    let tagged_edge_or_face_id = tagged_edge_or_face.id;
749                    ModelingCmd::from(
750                        mcmd::ExtrudeToReference::builder()
751                            .target(concrete_target()?.into())
752                            .reference(ExtrudeReference::EntityReference {
753                                entity_id: Some(tagged_edge_or_face_id),
754                                entity_reference: None,
755                            })
756                            .extrude_method(extrude_method)
757                            .body_type(body_type)
758                            .build(),
759                    )
760                }
761                Point3dAxis3dOrGeometryReference::EdgeToReference(spec) => {
762                    let inner = edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?;
763                    ModelingCmd::from(
764                        mcmd::ExtrudeToReference::builder()
765                            .target(concrete_target()?.into())
766                            .reference(ExtrudeReference::EntityReference {
767                                entity_id: None,
768                                entity_reference: Some(EntityReference::Edge {
769                                    inner,
770                                    topology_fallback: None,
771                                }),
772                            })
773                            .extrude_method(extrude_method)
774                            .body_type(body_type)
775                            .build(),
776                    )
777                }
778            },
779            (Some(_), _, _, None, None, None) => {
780                return Err(KclError::new_semantic(KclErrorDetails::new(
781                    "The `length` parameter must be provided when using twist angle for extrusion.".to_owned(),
782                    vec![args.source_range],
783                )));
784            }
785            (_, _, _, None, None, None) => {
786                return Err(KclError::new_semantic(KclErrorDetails::new(
787                    "Either `length` or `to` parameter must be provided for extrusion.".to_owned(),
788                    vec![args.source_range],
789                )));
790            }
791            (_, _, _, Some(_), Some(_), None) => {
792                return Err(KclError::new_semantic(KclErrorDetails::new(
793                    "You cannot give both `length` and `to` params, you have to choose one or the other".to_owned(),
794                    vec![args.source_range],
795                )));
796            }
797            (_, _, _, _, _, _) => {
798                return Err(KclError::new_semantic(KclErrorDetails::new(
799                    "Invalid combination of parameters for extrusion.".to_owned(),
800                    vec![args.source_range],
801                )));
802            }
803        };
804
805        let being_extruded = match extrudable {
806            Extrudable::Sketch(..) => BeingExtruded::Sketch,
807            Extrudable::FaceTag(face_tag) => {
808                let face_id = concrete_target()?;
809                let solid_id = match face_tag.geometry() {
810                    Some(crate::execution::Geometry::Solid(solid)) => solid.id,
811                    Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
812                        SketchSurface::Face(face) => face.parent_solid.solid_id,
813                        SketchSurface::Plane(_) => sketch.id,
814                    },
815                    None => face_id,
816                };
817                BeingExtruded::Face { face_id, solid_id }
818            }
819            Extrudable::Face(face) => BeingExtruded::Face {
820                face_id: face.id,
821                solid_id: face.parent_solid.solid_id,
822            },
823            Extrudable::EdgeTag(_) => BeingExtruded::Edge,
824            Extrudable::Edge(_) => BeingExtruded::Edge,
825            Extrudable::EdgeSpecifier(_) => BeingExtruded::Edge,
826        };
827        if let Some(post_extr_sketch) = extrudable.as_sketch() {
828            let cmds = post_extr_sketch.build_sketch_mode_cmds(
829                exec_state,
830                ModelingCmdReq {
831                    cmd_id: extrude_cmd_id.into(),
832                    cmd,
833                },
834            );
835            exec_state
836                .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), &cmds)
837                .await?;
838            solids.push(
839                do_post_extrude(
840                    &post_extr_sketch,
841                    extrude_cmd_id.into(),
842                    false,
843                    &NamedCapTags {
844                        start: tag_start.as_ref(),
845                        end: tag_end.as_ref(),
846                    },
847                    extrude_method,
848                    exec_state,
849                    &args,
850                    None,
851                    None,
852                    body_type,
853                    being_extruded,
854                )
855                .await?,
856            );
857        } else if is_edge {
858            // Ensure that edges do not use the MERGE method.
859            match extrude_method {
860                ExtrudeMethod::New => {
861                    // This is expected.
862                }
863                ExtrudeMethod::Merge => {
864                    return Err(KclError::new_semantic(KclErrorDetails::new(
865                        "Cannot use method MERGE with surface extrude of an edge".to_owned(),
866                        vec![args.source_range],
867                    )));
868                }
869                _ => {
870                    return Err(KclError::new_internal(KclErrorDetails::new(
871                        format!("Unknown extrude method: {extrude_method:?}"),
872                        vec![args.source_range],
873                    )));
874                }
875            }
876
877            // Surface-extrude an edge.
878            exec_state
879                .batch_modeling_cmd(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), cmd)
880                .await?;
881            // Extract the edge tag.
882            let edge_tag = match extrudable {
883                Extrudable::Sketch(_) => None,
884                Extrudable::FaceTag(_) => None,
885                Extrudable::Face(_) => None,
886                Extrudable::EdgeTag(tag) => Some(TagDeclarator::new(&tag.value)),
887                Extrudable::Edge(_) => None,
888                Extrudable::EdgeSpecifier(_) => None,
889            };
890            solids.push(after_surface_creation(extrude_cmd_id.into(), edge_tag, exec_state, &args).await?);
891        } else {
892            return Err(KclError::new_type(KclErrorDetails::new(
893                "Expected a sketch for extrusion".to_owned(),
894                vec![args.source_range],
895            )));
896        }
897    }
898
899    Ok(solids)
900}
901
902#[derive(Debug, Default)]
903pub(crate) struct NamedCapTags<'a> {
904    pub start: Option<&'a TagNode>,
905    pub end: Option<&'a TagNode>,
906}
907
908#[derive(Debug, Clone, Copy)]
909pub enum BeingExtruded {
910    Sketch,
911    Face { face_id: Uuid, solid_id: Uuid },
912    Edge,
913}
914
915/// Which edge should we use for querying Solid3dGetExtrusionInfo and GetAdjacencyInfo?
916/// It can be any edge of the body, but if our body is a clone, we should use an edge of
917/// the original body, not the new cloned body.
918fn get_extrusion_info_edge_id(
919    sketch: &Sketch,
920    any_edge_id: Uuid,
921    clone_id_map: Option<&HashMap<Uuid, Uuid>>,
922) -> Option<Uuid> {
923    // If this isn't a clone, there's no old/new body distinction.
924    // So just use the edge.
925    if sketch.clone.is_none() {
926        return Some(any_edge_id);
927    }
928    let Some(clone_map) = clone_id_map else {
929        return Some(any_edge_id);
930    };
931
932    // clone_map maps old IDs -> new IDs.
933    // If the `any_edge_id` is an ID of the OLD body
934    // (we know this if it's a _key_ of the map)
935    // we should use it (because that's the old body we're querying).
936    if clone_map.contains_key(&any_edge_id) {
937        return Some(any_edge_id);
938    }
939
940    // Otherwise, if the `any_edge_id` is an ID of the NEW body
941    // (we know this if it's a _value_ of the map),
942    // we should query the corresponding ID in the OLD body.
943    // i.e. if it's a hashmap value, find the corresponding key.
944    if let Some((old_edge_id, _)) = clone_map.iter().find(|(_, new_edge_id)| **new_edge_id == any_edge_id) {
945        return Some(*old_edge_id);
946    }
947
948    // Fall back to this if the clone_map doesn't have the data we expect.
949    // Engine will intuit an edge for the relevant calls, but it may mean the clone map was built wrong,
950    // or KCL and the engine disagree about what geometry exists.
951    None
952}
953
954/// This is similar to [`do_post_extrude()`], but for surfaces where a sketch
955/// isn't available.
956pub(crate) async fn after_surface_creation(
957    extrude_cmd_id: ArtifactId,
958    edge_tag: Option<crate::parsing::ast::types::Node<TagDeclarator>>,
959    exec_state: &mut ExecState,
960    args: &Args,
961) -> Result<Solid, KclError> {
962    let body_id = extrude_cmd_id.into();
963
964    // Bring the object to the front of the scene.
965    // See: https://github.com/KittyCAD/modeling-app/issues/806
966
967    exec_state
968        .batch_modeling_cmd(
969            ModelingCmdMeta::from_args(exec_state, args),
970            ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(body_id).build()),
971        )
972        .await?;
973
974    let (face_id, edge_id) = if args.ctx.no_engine_commands().await {
975        (exec_state.next_uuid(), exec_state.next_uuid())
976    } else {
977        // Get the body entity ids.
978        let response = exec_state
979            .send_modeling_cmd(
980                ModelingCmdMeta::from_args(exec_state, args),
981                ModelingCmd::from(mcmd::EntityGetAllChildUuids::builder().entity_id(body_id).build()),
982            )
983            .await?;
984        let OkWebSocketResponseData::Modeling {
985            modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(ref all_child_ids_resp),
986        } = response
987        else {
988            return Err(KclError::new_engine(KclErrorDetails::new(
989                format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
990                vec![args.source_range],
991            )));
992        };
993        let entity_ids = &all_child_ids_resp.entity_ids;
994        let Some(face_id) = entity_ids.first().copied() else {
995            return Err(KclError::new_internal(KclErrorDetails::new(
996                format!("Expected EntityGetAllChildUuids response to have at least 1 ID: {response:?}",),
997                vec![args.source_range],
998            )));
999        };
1000        let Some(edge_id) = entity_ids.get(1).copied() else {
1001            return Err(KclError::new_internal(KclErrorDetails::new(
1002                format!("Expected EntityGetAllChildUuids response to have at least 2 IDs: {response:?}"),
1003                vec![args.source_range],
1004            )));
1005        };
1006        (face_id, edge_id)
1007    };
1008
1009    // TODO: Do we need to use ExtrudeArc?
1010    let extrude_surface = ExtrudeSurface::ExtrudePlane(ExtrudePlane {
1011        face_id,
1012        tag: edge_tag,
1013        geo_meta: GeoMeta {
1014            id: face_id,
1015            metadata: args.source_range.into(),
1016        },
1017    });
1018    let new_value = vec![extrude_surface];
1019
1020    Ok(Solid {
1021        id: body_id,
1022        value_id: body_id,
1023        artifact_id: extrude_cmd_id,
1024        value: new_value,
1025        faces: Default::default(),
1026        meta: vec![args.source_range.into()],
1027        // Normally, we would propagate the units of the sketch. But an edge
1028        // doesn't have units. We also don't seem to use this field anywhere.
1029        units: kcl_api::UnitLength::Millimeters,
1030        sectional: false,
1031        creator: SolidCreator::Edge(CreatorEdge { edge_id, body_id }),
1032        start_cap_id: None,
1033        end_cap_id: None,
1034        edge_cuts: Vec::new(),
1035        pending_edge_cut_ids: Vec::new(),
1036    })
1037}
1038
1039#[allow(clippy::too_many_arguments)]
1040pub(crate) async fn do_post_extrude<'a>(
1041    sketch: &Sketch,
1042    extrude_cmd_id: ArtifactId,
1043    sectional: bool,
1044    named_cap_tags: &'a NamedCapTags<'a>,
1045    extrude_method: ExtrudeMethod,
1046    exec_state: &mut ExecState,
1047    args: &Args,
1048    edge_id: Option<Uuid>,
1049    clone_id_map: Option<&HashMap<Uuid, Uuid>>, // old sketch id -> new sketch id
1050    body_type: BodyType,
1051    being_extruded: BeingExtruded,
1052) -> Result<Solid, KclError> {
1053    // Bring the object to the front of the scene.
1054    // See: https://github.com/KittyCAD/modeling-app/issues/806
1055
1056    exec_state
1057        .batch_modeling_cmd(
1058            ModelingCmdMeta::from_args(exec_state, args),
1059            ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(sketch.id).build()),
1060        )
1061        .await?;
1062
1063    let any_edge_id = if let Some(edge_id) = sketch.mirror {
1064        edge_id
1065    } else if let Some(id) = edge_id {
1066        id
1067    } else {
1068        // The "get extrusion face info" API call requires *any* edge on the sketch being extruded.
1069        // So, let's just use the first one.
1070        let Some(any_edge_id) = sketch.paths.first().map(|edge| edge.get_base().geo_meta.id) else {
1071            return Err(KclError::new_type(KclErrorDetails::new(
1072                "Expected a non-empty sketch".to_owned(),
1073                vec![args.source_range],
1074            )));
1075        };
1076        any_edge_id
1077    };
1078
1079    // If the sketch is a clone, we will use the original info to get the extrusion face info.
1080    // So let's find an edge of the old body.
1081    let extrusion_info_edge_id = get_extrusion_info_edge_id(sketch, any_edge_id, clone_id_map);
1082
1083    let mut sketch = sketch.clone();
1084    match body_type {
1085        BodyType::Solid => {
1086            sketch.is_closed = ProfileClosed::Explicitly;
1087        }
1088        BodyType::Surface => {}
1089        _other => {
1090            // At some point in the future we'll add sheet metal or something.
1091            // Figure this out then.
1092        }
1093    }
1094
1095    match (extrude_method, being_extruded) {
1096        (ExtrudeMethod::Merge, BeingExtruded::Face { .. }) => {
1097            // Merge the IDs.
1098            // If we were sketching on a face, we need the original face id.
1099            if let SketchSurface::Face(ref face) = sketch.on {
1100                // If we're merging into an existing body, then assign the existing body's ID,
1101                // because the variable binding for this solid won't be its own object, it's just modifying the original one.
1102                sketch.id = face.parent_solid.sketch_or_solid_id();
1103            }
1104        }
1105        (ExtrudeMethod::New, BeingExtruded::Face { .. }) => {
1106            // We're creating a new solid, it's not based on any existing sketch (it's based on a face).
1107            // So we need a new ID, the extrude command ID.
1108            sketch.id = extrude_cmd_id.into();
1109        }
1110        (ExtrudeMethod::New, BeingExtruded::Sketch) => {
1111            // If we are creating a new body we need to preserve its new id.
1112            // The sketch's ID is already correct here, it should be the ID of the sketch.
1113        }
1114        (ExtrudeMethod::Merge, BeingExtruded::Sketch) => {
1115            if let SketchSurface::Face(ref face) = sketch.on {
1116                // If we're merging into an existing body, then assign the existing body's ID,
1117                // because the variable binding for this solid won't be its own object, it's just modifying the original one.
1118                sketch.id = face.parent_solid.sketch_or_solid_id();
1119            }
1120        }
1121        (other, _) => {
1122            // If you ever hit this, you should add a new arm to the match expression, and implement support for the new ExtrudeMethod variant.
1123            return Err(KclError::new_internal(KclErrorDetails::new(
1124                format!("Zoo does not yet support creating bodies via {other:?}"),
1125                vec![args.source_range],
1126            )));
1127        }
1128    }
1129
1130    // Similarly, if the sketch is a clone, we need to use the original sketch id to get the extrusion face info.
1131    let sketch_id = if let Some(cloned_from) = sketch.clone
1132        && clone_id_map.is_some()
1133    {
1134        cloned_from
1135    } else {
1136        sketch.id
1137    };
1138
1139    let solid3d_info = exec_state
1140        .send_modeling_cmd(
1141            ModelingCmdMeta::from_args(exec_state, args),
1142            ModelingCmd::from(
1143                mcmd::Solid3dGetExtrusionFaceInfo::builder()
1144                    .maybe_edge_id(extrusion_info_edge_id)
1145                    .object_id(sketch_id)
1146                    .build(),
1147            ),
1148        )
1149        .await?;
1150
1151    let face_infos = if let OkWebSocketResponseData::Modeling {
1152        modeling_response: OkModelingCmdResponse::Solid3dGetExtrusionFaceInfo(data),
1153    } = solid3d_info
1154    {
1155        data.faces
1156    } else {
1157        vec![]
1158    };
1159
1160    // Only do this if we need the artifact graph.
1161    if !args.ctx.settings.skip_artifact_graph {
1162        // Getting the ids of a sectional sweep does not work well and we cannot guarantee that
1163        // any of these call will not just fail.
1164        if !sectional {
1165            exec_state
1166                .batch_modeling_cmd(
1167                    ModelingCmdMeta::from_args(exec_state, args),
1168                    ModelingCmd::from(
1169                        mcmd::Solid3dGetAdjacencyInfo::builder()
1170                            .object_id(sketch_id)
1171                            .maybe_edge_id(extrusion_info_edge_id)
1172                            .build(),
1173                    ),
1174                )
1175                .await?;
1176        }
1177    }
1178
1179    let Faces {
1180        sides: mut face_id_map,
1181        mut start_cap_id,
1182        mut end_cap_id,
1183    } = analyze_faces(exec_state, args, face_infos).await;
1184
1185    // If this is a clone, we will use the clone_id_map to map the face info from the original sketch to the clone sketch.
1186    if sketch.clone.is_some()
1187        && let Some(clone_id_map) = clone_id_map
1188    {
1189        face_id_map = face_id_map
1190            .into_iter()
1191            .filter_map(|(k, v)| {
1192                let fe_key = clone_id_map.get(&k)?;
1193                let fe_value = clone_id_map.get(&(v?)).copied();
1194                Some((*fe_key, fe_value))
1195            })
1196            .collect::<HashMap<Uuid, Option<Uuid>>>();
1197        // The face info above was queried using the original solid's id, so
1198        // the cap ids belong to the original. Map them to the clone's ids.
1199        start_cap_id = start_cap_id.and_then(|id| clone_id_map.get(&id).copied());
1200        end_cap_id = end_cap_id.and_then(|id| clone_id_map.get(&id).copied());
1201    }
1202
1203    // Iterate over the sketch.value array and add face_id to GeoMeta
1204    let no_engine_commands = args.ctx.no_engine_commands().await;
1205    let mut new_value: Vec<ExtrudeSurface> = Vec::with_capacity(sketch.paths.len() + sketch.inner_paths.len() + 2);
1206    let outer_surfaces = sketch.paths.iter().flat_map(|path| {
1207        if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1208            surface_of(path, *actual_face_id)
1209        } else if no_engine_commands {
1210            crate::log::logln!(
1211                "No face ID found for path ID {:?}, but in no-engine-commands mode, so faking it",
1212                path.get_base().geo_meta.id
1213            );
1214            // Only pre-populate the extrude surface if we are in mock mode.
1215            fake_extrude_surface(exec_state, path)
1216        } else if sketch.clone.is_some()
1217            && let Some(clone_map) = clone_id_map
1218        {
1219            let new_path = clone_map.get(&(path.get_base().geo_meta.id));
1220
1221            if let Some(new_path) = new_path {
1222                match face_id_map.get(new_path) {
1223                    Some(Some(actual_face_id)) => clone_surface_of(path, *new_path, *actual_face_id),
1224                    _ => {
1225                        let actual_face_id = face_id_map.iter().find_map(|(key, value)| {
1226                            if let Some(value) = value {
1227                                if value == new_path { Some(key) } else { None }
1228                            } else {
1229                                None
1230                            }
1231                        });
1232                        match actual_face_id {
1233                            Some(actual_face_id) => clone_surface_of(path, *new_path, *actual_face_id),
1234                            None => {
1235                                crate::log::logln!("No face ID found for clone path ID {:?}, so skipping it", new_path);
1236                                None
1237                            }
1238                        }
1239                    }
1240                }
1241            } else {
1242                None
1243            }
1244        } else {
1245            crate::log::logln!(
1246                "No face ID found for path ID {:?}, and not in no-engine-commands mode, so skipping it",
1247                path.get_base().geo_meta.id
1248            );
1249            None
1250        }
1251    });
1252
1253    new_value.extend(outer_surfaces);
1254    let inner_surfaces = sketch.inner_paths.iter().flat_map(|path| {
1255        if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1256            surface_of(path, *actual_face_id)
1257        } else if no_engine_commands {
1258            // Only pre-populate the extrude surface if we are in mock mode.
1259            fake_extrude_surface(exec_state, path)
1260        } else {
1261            None
1262        }
1263    });
1264    new_value.extend(inner_surfaces);
1265
1266    // Add the tags for the start or end caps. A CSG can split or remove a
1267    // canonical cap before a body is cloned or mirrored, so reconstruction
1268    // cannot preserve that tag as one cap when the engine no longer reports it.
1269    if let Some(tag_start) = named_cap_tags.start {
1270        if let Some(start_cap_id) = start_cap_id {
1271            new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1272                face_id: start_cap_id,
1273                tag: Some(tag_start.clone()),
1274                geo_meta: GeoMeta {
1275                    id: start_cap_id,
1276                    metadata: args.source_range.into(),
1277                },
1278            }));
1279        } else if clone_id_map.is_none() {
1280            return Err(KclError::new_type(KclErrorDetails::new(
1281                format!(
1282                    "Expected a start cap ID for tag `{}` for extrusion of sketch {:?}",
1283                    tag_start.name, sketch.id
1284                ),
1285                vec![args.source_range],
1286            )));
1287        }
1288    }
1289    if let Some(tag_end) = named_cap_tags.end {
1290        if let Some(end_cap_id) = end_cap_id {
1291            new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1292                face_id: end_cap_id,
1293                tag: Some(tag_end.clone()),
1294                geo_meta: GeoMeta {
1295                    id: end_cap_id,
1296                    metadata: args.source_range.into(),
1297                },
1298            }));
1299        } else if clone_id_map.is_none() {
1300            return Err(KclError::new_type(KclErrorDetails::new(
1301                format!(
1302                    "Expected an end cap ID for tag `{}` for extrusion of sketch {:?}",
1303                    tag_end.name, sketch.id
1304                ),
1305                vec![args.source_range],
1306            )));
1307        }
1308    }
1309
1310    let meta = sketch.meta.clone();
1311    let units = sketch.units;
1312    let id = sketch.id;
1313    let creator = match being_extruded {
1314        BeingExtruded::Sketch => SolidCreator::Sketch(sketch),
1315        BeingExtruded::Face { face_id, solid_id } => SolidCreator::Face(CreatorFace {
1316            face_id,
1317            solid_id,
1318            sketch,
1319        }),
1320        BeingExtruded::Edge => {
1321            let message = "Expected an edge to have been extruded via another code path";
1322            debug_assert!(false, "{message}");
1323            return Err(KclError::new_internal(KclErrorDetails::new(
1324                message.to_owned(),
1325                vec![args.source_range],
1326            )));
1327        }
1328    };
1329
1330    Ok(Solid {
1331        id,
1332        value_id: extrude_cmd_id.into(),
1333        artifact_id: extrude_cmd_id,
1334        value: new_value,
1335        faces: Default::default(),
1336        meta,
1337        units,
1338        sectional,
1339        creator,
1340        start_cap_id,
1341        end_cap_id,
1342        edge_cuts: vec![],
1343        pending_edge_cut_ids: vec![],
1344    })
1345}
1346
1347#[derive(Debug, Default)]
1348struct Faces {
1349    /// Maps curve ID to face ID for each side.
1350    sides: HashMap<Uuid, Option<Uuid>>,
1351    /// Top face ID.
1352    end_cap_id: Option<Uuid>,
1353    /// Bottom face ID.
1354    start_cap_id: Option<Uuid>,
1355}
1356
1357async fn analyze_faces(exec_state: &mut ExecState, args: &Args, face_infos: Vec<ExtrusionFaceInfo>) -> Faces {
1358    let mut faces = Faces {
1359        sides: HashMap::with_capacity(face_infos.len()),
1360        ..Default::default()
1361    };
1362    if args.ctx.no_engine_commands().await {
1363        // Create fake IDs for start and end caps, to make extrudes mock-execute safe
1364        faces.start_cap_id = Some(exec_state.next_uuid());
1365        faces.end_cap_id = Some(exec_state.next_uuid());
1366    }
1367    for face_info in face_infos {
1368        match face_info.cap {
1369            ExtrusionFaceCapType::Bottom => faces.start_cap_id = face_info.face_id,
1370            ExtrusionFaceCapType::Top => faces.end_cap_id = face_info.face_id,
1371            ExtrusionFaceCapType::Both => {
1372                faces.end_cap_id = face_info.face_id;
1373                faces.start_cap_id = face_info.face_id;
1374            }
1375            ExtrusionFaceCapType::None => {
1376                if let Some(curve_id) = face_info.curve_id {
1377                    faces.sides.insert(curve_id, face_info.face_id);
1378                }
1379            }
1380            other => {
1381                exec_state.warn(
1382                    crate::CompilationIssue {
1383                        source_range: args.source_range,
1384                        message: format!("unknown extrusion face type {other:?}"),
1385                        suggestion: None,
1386                        severity: crate::errors::Severity::Warning,
1387                        tag: crate::errors::Tag::Unnecessary,
1388                    },
1389                    annotations::WARN_NOT_YET_SUPPORTED,
1390                );
1391            }
1392        }
1393    }
1394    faces
1395}
1396fn surface_of(path: &Path, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1397    match path {
1398        Path::Arc { .. }
1399        | Path::TangentialArc { .. }
1400        | Path::TangentialArcTo { .. }
1401        // TODO: (bc) fix me
1402        | Path::Ellipse { .. }
1403        | Path::Conic {.. }
1404        | Path::Circle { .. }
1405        | Path::CircleThreePoint { .. } => {
1406            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1407                face_id: actual_face_id,
1408                tag: path.get_base().tag.clone(),
1409                geo_meta: GeoMeta {
1410                    id: path.get_base().geo_meta.id,
1411                    metadata: path.get_base().geo_meta.metadata,
1412                },
1413            });
1414            Some(extrude_surface)
1415        }
1416        Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1417            let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1418                face_id: actual_face_id,
1419                tag: path.get_base().tag.clone(),
1420                geo_meta: GeoMeta {
1421                    id: path.get_base().geo_meta.id,
1422                    metadata: path.get_base().geo_meta.metadata,
1423                },
1424            });
1425            Some(extrude_surface)
1426        }
1427        Path::ArcThreePoint { .. } => {
1428            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1429                face_id: actual_face_id,
1430                tag: path.get_base().tag.clone(),
1431                geo_meta: GeoMeta {
1432                    id: path.get_base().geo_meta.id,
1433                    metadata: path.get_base().geo_meta.metadata,
1434                },
1435            });
1436            Some(extrude_surface)
1437        }
1438    }
1439}
1440
1441fn clone_surface_of(path: &Path, clone_path_id: Uuid, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1442    match path {
1443        Path::Arc { .. }
1444        | Path::TangentialArc { .. }
1445        | Path::TangentialArcTo { .. }
1446        // TODO: (gserena) fix me
1447        | Path::Ellipse { .. }
1448        | Path::Conic {.. }
1449        | Path::Circle { .. }
1450        | Path::CircleThreePoint { .. } => {
1451            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1452                face_id: actual_face_id,
1453                tag: path.get_base().tag.clone(),
1454                geo_meta: GeoMeta {
1455                    id: clone_path_id,
1456                    metadata: path.get_base().geo_meta.metadata,
1457                },
1458            });
1459            Some(extrude_surface)
1460        }
1461        Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1462            let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1463                face_id: actual_face_id,
1464                tag: path.get_base().tag.clone(),
1465                geo_meta: GeoMeta {
1466                    id: clone_path_id,
1467                    metadata: path.get_base().geo_meta.metadata,
1468                },
1469            });
1470            Some(extrude_surface)
1471        }
1472        Path::ArcThreePoint { .. } => {
1473            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1474                face_id: actual_face_id,
1475                tag: path.get_base().tag.clone(),
1476                geo_meta: GeoMeta {
1477                    id: clone_path_id,
1478                    metadata: path.get_base().geo_meta.metadata,
1479                },
1480            });
1481            Some(extrude_surface)
1482        }
1483    }
1484}
1485
1486/// Create a fake extrude surface to report for mock execution, when there's no engine response.
1487fn fake_extrude_surface(exec_state: &mut ExecState, path: &Path) -> Option<ExtrudeSurface> {
1488    let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1489        // pushing this values with a fake face_id to make extrudes mock-execute safe
1490        face_id: exec_state.next_uuid(),
1491        tag: path.get_base().tag.clone(),
1492        geo_meta: GeoMeta {
1493            id: path.get_base().geo_meta.id,
1494            metadata: path.get_base().geo_meta.metadata,
1495        },
1496    });
1497    Some(extrude_surface)
1498}
1499
1500#[cfg(test)]
1501mod tests {
1502    use kcl_api::UnitLength;
1503
1504    use super::*;
1505    use crate::execution::AbstractSegment;
1506    use crate::execution::Plane;
1507    use crate::execution::SegmentRepr;
1508    use crate::execution::parse_execute;
1509    use crate::execution::types::NumericType;
1510    use crate::execution::types::NumericTypeExt;
1511    use crate::front::Expr;
1512    use crate::front::Number;
1513    use crate::front::ObjectId;
1514    use crate::front::Point2d;
1515    use crate::front::PointCtor;
1516    use crate::std::sketch::PlaneData;
1517
1518    fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
1519        Point2d {
1520            x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
1521            y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
1522        }
1523    }
1524
1525    fn segment_value(exec_state: &mut ExecState) -> KclValue {
1526        let plane = Plane::from_plane_data_skipping_engine(PlaneData::XY, exec_state).unwrap();
1527        let segment = Segment {
1528            id: exec_state.next_uuid(),
1529            object_id: ObjectId(1),
1530            kind: SegmentKind::Point {
1531                position: [TyF64::new(0.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())],
1532                ctor: Box::new(PointCtor {
1533                    position: point_expr(0.0, 0.0),
1534                }),
1535                freedom: None,
1536            },
1537            surface: SketchSurface::Plane(Box::new(plane)),
1538            sketch_id: exec_state.next_uuid(),
1539            sketch: None,
1540            tag: None,
1541            node_path: None,
1542            meta: vec![],
1543        };
1544        KclValue::Segment {
1545            value: Box::new(AbstractSegment {
1546                repr: SegmentRepr::Solved {
1547                    segment: Box::new(segment),
1548                },
1549                meta: vec![],
1550            }),
1551        }
1552    }
1553
1554    #[tokio::test(flavor = "multi_thread")]
1555    async fn extrude_accepts_negative_bidirectional_length_in_mock_exec() {
1556        let code = r#"
1557profile001 = startSketchOn(XY)
1558  |> startProfile(at = [0, 0])
1559  |> line(end = [1, 0])
1560  |> line(end = [0, 1])
1561  |> close()
1562
1563extrude(profile001, length = 1, bidirectionalLength = -1)
1564"#;
1565
1566        let result = parse_execute(code).await.unwrap();
1567        let extrude = result
1568            .root_module_artifact_commands()
1569            .iter()
1570            .find_map(|artifact_command| match &artifact_command.command {
1571                ModelingCmd::Extrude(extrude) => Some(extrude),
1572                _ => None,
1573            })
1574            .expect("expected an extrude command");
1575
1576        assert_eq!(extrude.opposite, Opposite::Other(LengthUnit(-1.0)));
1577    }
1578
1579    #[tokio::test(flavor = "multi_thread")]
1580    async fn extrude_rejects_an_empty_target_array() {
1581        let err = parse_execute("nothing = extrude([], length = 5)").await.unwrap_err();
1582
1583        assert!(matches!(err, KclError::Argument { .. }), "{err:?}");
1584        assert!(err.message().contains("requires one or more"), "{err:?}");
1585    }
1586
1587    #[tokio::test(flavor = "multi_thread")]
1588    async fn edge_extrude_succeeds_in_mock_exec() {
1589        let code = r#"
1590@settings(kclVersion = 2.0)
1591
1592sketch001 = sketch(on = XZ) {
1593  line1 = line(start = [0mm, 0mm], end = [1mm, 0mm])
1594}
1595extrude001 = extrude(sketch001.line1, length = 5, bodyType = SURFACE)
1596extrude(
1597  getOppositeEdge(extrude001.sketch.tags.line1),
1598  length = 1,
1599  method = NEW,
1600  bodyType = SURFACE,
1601)
1602"#;
1603
1604        parse_execute(code).await.unwrap();
1605    }
1606
1607    #[tokio::test(flavor = "multi_thread")]
1608    async fn edge_specifier_target_cannot_be_extruded_to_a_reference() {
1609        let code = r#"
1610@settings(kclVersion = 2.0, experimentalFeatures = allow)
1611
1612profile = startSketchOn(XY)
1613  |> startProfile(at = [0, 0])
1614  |> line(end = [1, 0], tag = $sideFace)
1615  |> line(end = [0, 1])
1616  |> line(end = [-1, 0])
1617  |> close()
1618body = extrude(profile, length = 1, tagEnd = $endFace)
1619
1620extrude(
1621  { sideFaces = [sideFace, endFace] },
1622  to = offsetPlane(XY, offset = 10),
1623  bodyType = SURFACE,
1624  method = NEW,
1625)
1626"#;
1627
1628        let err = parse_execute(code).await.unwrap_err();
1629
1630        assert!(matches!(err, KclError::Semantic { .. }), "{err:?}");
1631        assert!(
1632            err.message()
1633                .contains("Edge specifiers cannot be extruded to a reference"),
1634            "{err:?}"
1635        );
1636    }
1637
1638    #[tokio::test(flavor = "multi_thread")]
1639    async fn segment_extrude_rejects_cap_tags() {
1640        let ctx = ExecutorContext::new_mock(None).await;
1641        let mut exec_state = ExecState::new(&ctx);
1642        let err = coerce_extrude_targets(
1643            vec![segment_value(&mut exec_state)],
1644            BodyType::Surface,
1645            Some(&TagDeclarator::new("cap_start")),
1646            None,
1647            &mut exec_state,
1648            &ctx,
1649            crate::SourceRange::default(),
1650        )
1651        .await
1652        .unwrap_err();
1653
1654        assert!(
1655            err.message()
1656                .contains("`tagStart` and `tagEnd` are not supported when extruding sketch segments"),
1657            "{err:?}"
1658        );
1659        ctx.close().await;
1660    }
1661
1662    /// `getOppositeEdge()` and the other edge getters return a raw edge as
1663    /// `KclValue::Uuid`, which coerces to `Extrudable::Edge`.
1664    fn edge_value(exec_state: &mut ExecState) -> KclValue {
1665        KclValue::Uuid {
1666            value: exec_state.next_uuid(),
1667            meta: vec![],
1668        }
1669    }
1670
1671    #[tokio::test(flavor = "multi_thread")]
1672    async fn edge_extrude_rejects_solid_body_type() {
1673        let ctx = ExecutorContext::new_mock(None).await;
1674        let mut exec_state = ExecState::new(&ctx);
1675        let edge = edge_value(&mut exec_state);
1676        let err = coerce_extrude_targets(
1677            vec![edge],
1678            BodyType::Solid,
1679            None,
1680            None,
1681            &mut exec_state,
1682            &ctx,
1683            crate::SourceRange::default(),
1684        )
1685        .await
1686        .unwrap_err();
1687
1688        assert!(
1689            err.message()
1690                .contains("edges can only be extruded with surface extrudes"),
1691            "{err:?}"
1692        );
1693        ctx.close().await;
1694    }
1695
1696    #[tokio::test(flavor = "multi_thread")]
1697    async fn edge_extrude_rejects_cap_tags() {
1698        let ctx = ExecutorContext::new_mock(None).await;
1699        let mut exec_state = ExecState::new(&ctx);
1700        let edge = edge_value(&mut exec_state);
1701        let err = coerce_extrude_targets(
1702            vec![edge],
1703            BodyType::Surface,
1704            Some(&TagDeclarator::new("cap_start")),
1705            None,
1706            &mut exec_state,
1707            &ctx,
1708            crate::SourceRange::default(),
1709        )
1710        .await
1711        .unwrap_err();
1712
1713        assert!(
1714            err.message()
1715                .contains("`tagStart` and `tagEnd` are not supported when extruding edges"),
1716            "{err:?}"
1717        );
1718        ctx.close().await;
1719    }
1720
1721    #[tokio::test(flavor = "multi_thread")]
1722    async fn edge_extrude_rejects_mixing_with_face() {
1723        let ctx = ExecutorContext::new_mock(None).await;
1724        let mut exec_state = ExecState::new(&ctx);
1725        let edge = edge_value(&mut exec_state);
1726        // The string "START" coerces to a `FaceTag`, i.e. a non-edge extrudable.
1727        let face = KclValue::String {
1728            value: "START".to_owned(),
1729            meta: vec![],
1730        };
1731        let err = coerce_extrude_targets(
1732            vec![edge, face],
1733            BodyType::Surface,
1734            None,
1735            None,
1736            &mut exec_state,
1737            &ctx,
1738            crate::SourceRange::default(),
1739        )
1740        .await
1741        .unwrap_err();
1742
1743        assert!(
1744            err.message()
1745                .contains("Cannot extrude edges together with sketches or faces"),
1746            "{err:?}"
1747        );
1748        ctx.close().await;
1749    }
1750}