Skip to main content

kcl_lib/execution/
geometry.rs

1use std::f64::consts::TAU;
2use std::ops::Add;
3use std::ops::AddAssign;
4use std::ops::Mul;
5use std::ops::Sub;
6use std::ops::SubAssign;
7use std::sync::Arc;
8
9use anyhow::Result;
10use indexmap::IndexMap;
11use kcl_error::SourceRange;
12use kittycad_modeling_cmds::ModelingCmd;
13use kittycad_modeling_cmds::each_cmd as mcmd;
14use kittycad_modeling_cmds::length_unit::LengthUnit;
15use kittycad_modeling_cmds::units::UnitLength;
16use kittycad_modeling_cmds::websocket::ModelingCmdReq;
17use kittycad_modeling_cmds::{self as kcmc};
18use parse_display::Display;
19use parse_display::FromStr;
20use serde::Deserialize;
21use serde::Serialize;
22use uuid::Uuid;
23
24use crate::NodePath;
25use crate::engine::DEFAULT_PLANE_INFO;
26use crate::engine::PlaneName;
27use crate::errors::KclError;
28use crate::errors::KclErrorDetails;
29use crate::exec::KclValue;
30use crate::execution::ArtifactId;
31use crate::execution::ExecState;
32use crate::execution::ExecutorContext;
33use crate::execution::Metadata;
34use crate::execution::TagEngineInfo;
35use crate::execution::TagIdentifier;
36use crate::execution::normalize_to_solver_distance_unit;
37use crate::execution::types::NumericType;
38use crate::execution::types::adjust_length;
39use crate::front::ArcCtor;
40use crate::front::CircleCtor;
41use crate::front::ControlPointSplineCtor;
42use crate::front::Freedom;
43use crate::front::LineCtor;
44use crate::front::Number;
45use crate::front::ObjectId;
46use crate::front::Point2d as ApiPoint2d;
47use crate::front::PointCtor;
48use crate::parsing::ast::types::Node;
49use crate::parsing::ast::types::NodeRef;
50use crate::parsing::ast::types::TagDeclarator;
51use crate::parsing::ast::types::TagNode;
52use crate::std::Args;
53use crate::std::args::TyF64;
54use crate::std::edge::UnresolvedEdgeSpecifier;
55use crate::std::sketch::FaceTag;
56use crate::std::sketch::PlaneData;
57use crate::util::MathExt;
58
59type Point3D = kcmc::shared::Point3d<f64>;
60
61/// A GD&T annotation.
62#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
63#[ts(export)]
64#[serde(tag = "type", rename_all = "camelCase")]
65pub struct GdtAnnotation {
66    /// The engine ID.
67    pub id: uuid::Uuid,
68    #[serde(skip)]
69    pub meta: Vec<Metadata>,
70}
71
72/// A geometry.
73#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
74#[ts(export)]
75#[serde(tag = "type")]
76#[allow(clippy::large_enum_variant)]
77pub enum Geometry {
78    Sketch(Sketch),
79    Solid(Solid),
80}
81
82impl Geometry {
83    pub fn id(&self) -> uuid::Uuid {
84        match self {
85            Geometry::Sketch(s) => s.id,
86            Geometry::Solid(e) => e.id,
87        }
88    }
89
90    /// If this geometry is the result of a pattern, then return the ID of
91    /// the original sketch which was patterned.
92    /// Equivalent to the `id()` method if this isn't a pattern.
93    pub fn original_id(&self) -> uuid::Uuid {
94        match self {
95            Geometry::Sketch(s) => s.original_id,
96            Geometry::Solid(e) => e.original_id(),
97        }
98    }
99}
100
101/// A geometry including an imported geometry.
102#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
103#[ts(export)]
104#[serde(tag = "type")]
105#[allow(clippy::large_enum_variant)]
106pub enum GeometryWithImportedGeometry {
107    Sketch(Sketch),
108    Solid(Solid),
109    ImportedGeometry(Box<ImportedGeometry>),
110}
111
112impl GeometryWithImportedGeometry {
113    pub async fn id(&mut self, ctx: &ExecutorContext) -> Result<uuid::Uuid, KclError> {
114        match self {
115            GeometryWithImportedGeometry::Sketch(s) => Ok(s.id),
116            GeometryWithImportedGeometry::Solid(e) => Ok(e.id),
117            GeometryWithImportedGeometry::ImportedGeometry(i) => {
118                let id = i.id(ctx).await?;
119                Ok(id)
120            }
121        }
122    }
123
124    pub fn into_solid(self) -> Option<Solid> {
125        match self {
126            GeometryWithImportedGeometry::Sketch(_) => None,
127            GeometryWithImportedGeometry::Solid(solid) => Some(solid),
128            GeometryWithImportedGeometry::ImportedGeometry(_) => None,
129        }
130    }
131}
132
133/// A set of geometry.
134#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
135#[ts(export)]
136#[serde(tag = "type")]
137#[allow(clippy::vec_box)]
138pub enum Geometries {
139    Sketches(Vec<Sketch>),
140    Solids(Vec<Solid>),
141}
142
143impl From<Geometry> for Geometries {
144    fn from(value: Geometry) -> Self {
145        match value {
146            Geometry::Sketch(x) => Self::Sketches(vec![x]),
147            Geometry::Solid(x) => Self::Solids(vec![x]),
148        }
149    }
150}
151
152/// Data for an imported geometry.
153#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
154#[ts(export)]
155#[serde(rename_all = "camelCase")]
156pub struct ImportedGeometry {
157    /// The ID of the imported geometry.
158    pub id: uuid::Uuid,
159    /// The original file paths.
160    pub value: Vec<String>,
161    #[serde(skip)]
162    pub meta: Vec<Metadata>,
163    /// If the imported geometry has completed.
164    #[serde(skip)]
165    completed: bool,
166}
167
168impl ImportedGeometry {
169    pub fn new(id: uuid::Uuid, value: Vec<String>, meta: Vec<Metadata>) -> Self {
170        Self {
171            id,
172            value,
173            meta,
174            completed: false,
175        }
176    }
177
178    async fn wait_for_finish(&mut self, ctx: &ExecutorContext) -> Result<(), KclError> {
179        if self.completed {
180            return Ok(());
181        }
182
183        ctx.engine
184            .ensure_async_command_completed(self.id, self.meta.first().map(|m| m.source_range))
185            .await?;
186
187        self.completed = true;
188
189        Ok(())
190    }
191
192    pub async fn id(&mut self, ctx: &ExecutorContext) -> Result<uuid::Uuid, KclError> {
193        if !self.completed {
194            self.wait_for_finish(ctx).await?;
195        }
196
197        Ok(self.id)
198    }
199}
200
201/// Data for geometry that can be hidden.
202#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
203#[ts(export)]
204#[serde(tag = "type", rename_all = "camelCase")]
205#[allow(clippy::vec_box)]
206pub enum HideableGeometry {
207    ImportedGeometry(Box<ImportedGeometry>),
208    SolidSet(Vec<Solid>),
209    PlaneSet(Vec<Plane>),
210    SketchSet(Vec<Sketch>),
211    HelixSet(Vec<Helix>),
212    GdtAnnotationSet(Vec<GdtAnnotation>),
213}
214
215impl From<HideableGeometry> for crate::execution::KclValue {
216    fn from(value: HideableGeometry) -> Self {
217        match value {
218            HideableGeometry::ImportedGeometry(s) => crate::execution::KclValue::ImportedGeometry(*s),
219            HideableGeometry::PlaneSet(mut s) => {
220                if s.len() == 1
221                    && let Some(s) = s.pop()
222                {
223                    crate::execution::KclValue::Plane { value: Box::new(s) }
224                } else {
225                    crate::execution::KclValue::HomArray {
226                        value: s
227                            .into_iter()
228                            .map(|s| crate::execution::KclValue::Plane { value: Box::new(s) })
229                            .collect(),
230                        ty: crate::execution::types::RuntimeType::plane(),
231                    }
232                }
233            }
234            HideableGeometry::SolidSet(mut s) => {
235                if s.len() == 1
236                    && let Some(s) = s.pop()
237                {
238                    crate::execution::KclValue::Solid { value: Box::new(s) }
239                } else {
240                    crate::execution::KclValue::HomArray {
241                        value: s
242                            .into_iter()
243                            .map(|s| crate::execution::KclValue::Solid { value: Box::new(s) })
244                            .collect(),
245                        ty: crate::execution::types::RuntimeType::solid(),
246                    }
247                }
248            }
249            HideableGeometry::GdtAnnotationSet(mut s) => {
250                if s.len() == 1
251                    && let Some(s) = s.pop()
252                {
253                    crate::execution::KclValue::GdtAnnotation { value: Box::new(s) }
254                } else {
255                    crate::execution::KclValue::HomArray {
256                        value: s
257                            .into_iter()
258                            .map(|s| crate::execution::KclValue::GdtAnnotation { value: Box::new(s) })
259                            .collect(),
260                        ty: crate::execution::types::RuntimeType::gdt(),
261                    }
262                }
263            }
264            HideableGeometry::SketchSet(mut s) => {
265                if s.len() == 1
266                    && let Some(s) = s.pop()
267                {
268                    crate::execution::KclValue::Sketch { value: Box::new(s) }
269                } else {
270                    crate::execution::KclValue::HomArray {
271                        value: s
272                            .into_iter()
273                            .map(|s| crate::execution::KclValue::Sketch { value: Box::new(s) })
274                            .collect(),
275                        ty: crate::execution::types::RuntimeType::sketch(),
276                    }
277                }
278            }
279            HideableGeometry::HelixSet(mut s) => {
280                if s.len() == 1
281                    && let Some(s) = s.pop()
282                {
283                    crate::execution::KclValue::Helix { value: Box::new(s) }
284                } else {
285                    crate::execution::KclValue::HomArray {
286                        value: s
287                            .into_iter()
288                            .map(|s| crate::execution::KclValue::Helix { value: Box::new(s) })
289                            .collect(),
290                        ty: crate::execution::types::RuntimeType::helices(),
291                    }
292                }
293            }
294        }
295    }
296}
297
298impl HideableGeometry {
299    pub(crate) async fn ids(&mut self, ctx: &ExecutorContext) -> Result<Vec<uuid::Uuid>, KclError> {
300        match self {
301            HideableGeometry::ImportedGeometry(s) => {
302                let id = s.id(ctx).await?;
303
304                Ok(vec![id])
305            }
306            HideableGeometry::PlaneSet(s) => Ok(s.iter().map(|s| s.id).collect()),
307            HideableGeometry::SolidSet(s) => Ok(s.iter().map(|s| s.id).collect()),
308            HideableGeometry::GdtAnnotationSet(s) => Ok(s.iter().map(|s| s.id).collect()),
309            HideableGeometry::SketchSet(s) => Ok(s.iter().map(|s| s.id).collect()),
310            HideableGeometry::HelixSet(s) => Ok(s.iter().map(|s| s.value).collect()),
311        }
312    }
313}
314
315/// Data for a solid, sketch, or an imported geometry.
316#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
317#[ts(export)]
318#[serde(tag = "type", rename_all = "camelCase")]
319#[allow(clippy::vec_box)]
320pub enum SolidOrSketchOrImportedGeometry {
321    ImportedGeometry(Box<ImportedGeometry>),
322    SolidSet(Vec<Solid>),
323    SketchSet(Vec<Sketch>),
324}
325
326impl From<SolidOrSketchOrImportedGeometry> for crate::execution::KclValue {
327    fn from(value: SolidOrSketchOrImportedGeometry) -> Self {
328        match value {
329            SolidOrSketchOrImportedGeometry::ImportedGeometry(s) => crate::execution::KclValue::ImportedGeometry(*s),
330            SolidOrSketchOrImportedGeometry::SolidSet(mut s) => {
331                if s.len() == 1
332                    && let Some(s) = s.pop()
333                {
334                    crate::execution::KclValue::Solid { value: Box::new(s) }
335                } else {
336                    crate::execution::KclValue::HomArray {
337                        value: s
338                            .into_iter()
339                            .map(|s| crate::execution::KclValue::Solid { value: Box::new(s) })
340                            .collect(),
341                        ty: crate::execution::types::RuntimeType::solid(),
342                    }
343                }
344            }
345            SolidOrSketchOrImportedGeometry::SketchSet(mut s) => {
346                if s.len() == 1
347                    && let Some(s) = s.pop()
348                {
349                    crate::execution::KclValue::Sketch { value: Box::new(s) }
350                } else {
351                    crate::execution::KclValue::HomArray {
352                        value: s
353                            .into_iter()
354                            .map(|s| crate::execution::KclValue::Sketch { value: Box::new(s) })
355                            .collect(),
356                        ty: crate::execution::types::RuntimeType::sketch(),
357                    }
358                }
359            }
360        }
361    }
362}
363
364impl SolidOrSketchOrImportedGeometry {
365    pub(crate) async fn ids(&mut self, ctx: &ExecutorContext) -> Result<Vec<uuid::Uuid>, KclError> {
366        match self {
367            SolidOrSketchOrImportedGeometry::ImportedGeometry(s) => {
368                let id = s.id(ctx).await?;
369
370                Ok(vec![id])
371            }
372            SolidOrSketchOrImportedGeometry::SolidSet(s) => Ok(s.iter().map(|s| s.id).collect()),
373            SolidOrSketchOrImportedGeometry::SketchSet(s) => Ok(s.iter().map(|s| s.id).collect()),
374        }
375    }
376}
377
378/// Data for a solid or an imported geometry.
379#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
380#[ts(export)]
381#[serde(tag = "type", rename_all = "camelCase")]
382#[allow(clippy::vec_box)]
383pub enum SolidOrImportedGeometry {
384    ImportedGeometry(Box<ImportedGeometry>),
385    SolidSet(Vec<Solid>),
386}
387
388impl From<SolidOrImportedGeometry> for crate::execution::KclValue {
389    fn from(value: SolidOrImportedGeometry) -> Self {
390        match value {
391            SolidOrImportedGeometry::ImportedGeometry(s) => crate::execution::KclValue::ImportedGeometry(*s),
392            SolidOrImportedGeometry::SolidSet(mut s) => {
393                if s.len() == 1
394                    && let Some(s) = s.pop()
395                {
396                    crate::execution::KclValue::Solid { value: Box::new(s) }
397                } else {
398                    crate::execution::KclValue::HomArray {
399                        value: s
400                            .into_iter()
401                            .map(|s| crate::execution::KclValue::Solid { value: Box::new(s) })
402                            .collect(),
403                        ty: crate::execution::types::RuntimeType::solid(),
404                    }
405                }
406            }
407        }
408    }
409}
410
411impl SolidOrImportedGeometry {
412    pub(crate) async fn ids(&mut self, ctx: &ExecutorContext) -> Result<Vec<uuid::Uuid>, KclError> {
413        match self {
414            SolidOrImportedGeometry::ImportedGeometry(s) => {
415                let id = s.id(ctx).await?;
416
417                Ok(vec![id])
418            }
419            SolidOrImportedGeometry::SolidSet(s) => Ok(s.iter().map(|s| s.id).collect()),
420        }
421    }
422}
423
424/// A helix.
425#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
426#[ts(export)]
427#[serde(rename_all = "camelCase")]
428pub struct Helix {
429    /// The id of the helix.
430    pub value: uuid::Uuid,
431    /// The artifact ID.
432    pub artifact_id: ArtifactId,
433    /// Number of revolutions.
434    pub revolutions: f64,
435    /// Start angle (in degrees).
436    pub angle_start: f64,
437    /// Is the helix rotation counter clockwise?
438    pub ccw: bool,
439    /// The cylinder the helix was created on.
440    pub cylinder_id: Option<uuid::Uuid>,
441    pub units: UnitLength,
442    #[serde(skip)]
443    pub meta: Vec<Metadata>,
444}
445
446#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
447#[ts(export)]
448#[serde(rename_all = "camelCase")]
449pub struct Plane {
450    /// The id of the plane.
451    pub id: uuid::Uuid,
452    /// The artifact ID.
453    pub artifact_id: ArtifactId,
454    /// The scene object ID. If this is None, then the plane has not been
455    /// sent to the engine yet. It must be sent before it is used.
456    #[serde(skip_serializing_if = "Option::is_none")]
457    pub object_id: Option<ObjectId>,
458    /// The kind of plane or custom.
459    pub kind: PlaneKind,
460    /// The information for the plane.
461    #[serde(flatten)]
462    pub info: PlaneInfo,
463    #[serde(skip)]
464    pub meta: Vec<Metadata>,
465}
466
467#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
468#[ts(export)]
469#[serde(rename_all = "camelCase")]
470pub struct PlaneInfo {
471    /// Origin of the plane.
472    pub origin: Point3d,
473    /// What should the plane's X axis be?
474    pub x_axis: Point3d,
475    /// What should the plane's Y axis be?
476    pub y_axis: Point3d,
477    /// What should the plane's Z axis be?
478    pub z_axis: Point3d,
479}
480
481impl PlaneInfo {
482    pub(crate) fn into_plane_data(self) -> PlaneData {
483        if self.origin.is_zero() {
484            match self {
485                Self {
486                    origin:
487                        Point3d {
488                            x: 0.0,
489                            y: 0.0,
490                            z: 0.0,
491                            units: Some(UnitLength::Millimeters),
492                        },
493                    x_axis:
494                        Point3d {
495                            x: 1.0,
496                            y: 0.0,
497                            z: 0.0,
498                            units: _,
499                        },
500                    y_axis:
501                        Point3d {
502                            x: 0.0,
503                            y: 1.0,
504                            z: 0.0,
505                            units: _,
506                        },
507                    z_axis: _,
508                } => return PlaneData::XY,
509                Self {
510                    origin:
511                        Point3d {
512                            x: 0.0,
513                            y: 0.0,
514                            z: 0.0,
515                            units: Some(UnitLength::Millimeters),
516                        },
517                    x_axis:
518                        Point3d {
519                            x: -1.0,
520                            y: 0.0,
521                            z: 0.0,
522                            units: _,
523                        },
524                    y_axis:
525                        Point3d {
526                            x: 0.0,
527                            y: 1.0,
528                            z: 0.0,
529                            units: _,
530                        },
531                    z_axis: _,
532                } => return PlaneData::NegXY,
533                Self {
534                    origin:
535                        Point3d {
536                            x: 0.0,
537                            y: 0.0,
538                            z: 0.0,
539                            units: Some(UnitLength::Millimeters),
540                        },
541                    x_axis:
542                        Point3d {
543                            x: 1.0,
544                            y: 0.0,
545                            z: 0.0,
546                            units: _,
547                        },
548                    y_axis:
549                        Point3d {
550                            x: 0.0,
551                            y: 0.0,
552                            z: 1.0,
553                            units: _,
554                        },
555                    z_axis: _,
556                } => return PlaneData::XZ,
557                Self {
558                    origin:
559                        Point3d {
560                            x: 0.0,
561                            y: 0.0,
562                            z: 0.0,
563                            units: Some(UnitLength::Millimeters),
564                        },
565                    x_axis:
566                        Point3d {
567                            x: -1.0,
568                            y: 0.0,
569                            z: 0.0,
570                            units: _,
571                        },
572                    y_axis:
573                        Point3d {
574                            x: 0.0,
575                            y: 0.0,
576                            z: 1.0,
577                            units: _,
578                        },
579                    z_axis: _,
580                } => return PlaneData::NegXZ,
581                Self {
582                    origin:
583                        Point3d {
584                            x: 0.0,
585                            y: 0.0,
586                            z: 0.0,
587                            units: Some(UnitLength::Millimeters),
588                        },
589                    x_axis:
590                        Point3d {
591                            x: 0.0,
592                            y: 1.0,
593                            z: 0.0,
594                            units: _,
595                        },
596                    y_axis:
597                        Point3d {
598                            x: 0.0,
599                            y: 0.0,
600                            z: 1.0,
601                            units: _,
602                        },
603                    z_axis: _,
604                } => return PlaneData::YZ,
605                Self {
606                    origin:
607                        Point3d {
608                            x: 0.0,
609                            y: 0.0,
610                            z: 0.0,
611                            units: Some(UnitLength::Millimeters),
612                        },
613                    x_axis:
614                        Point3d {
615                            x: 0.0,
616                            y: -1.0,
617                            z: 0.0,
618                            units: _,
619                        },
620                    y_axis:
621                        Point3d {
622                            x: 0.0,
623                            y: 0.0,
624                            z: 1.0,
625                            units: _,
626                        },
627                    z_axis: _,
628                } => return PlaneData::NegYZ,
629                _ => {}
630            }
631        }
632
633        PlaneData::Plane(Self {
634            origin: self.origin,
635            x_axis: self.x_axis,
636            y_axis: self.y_axis,
637            z_axis: self.z_axis,
638        })
639    }
640
641    pub(crate) fn is_right_handed(&self) -> bool {
642        // Katie's formula:
643        // dot(cross(x, y), z) ~= sqrt(dot(x, x) * dot(y, y) * dot(z, z))
644        let lhs = self
645            .x_axis
646            .axes_cross_product(&self.y_axis)
647            .axes_dot_product(&self.z_axis);
648        let rhs_x = self.x_axis.axes_dot_product(&self.x_axis);
649        let rhs_y = self.y_axis.axes_dot_product(&self.y_axis);
650        let rhs_z = self.z_axis.axes_dot_product(&self.z_axis);
651        let rhs = (rhs_x * rhs_y * rhs_z).sqrt();
652        // Check LHS ~= RHS
653        (lhs - rhs).abs() <= 0.0001
654    }
655
656    #[cfg(test)]
657    pub(crate) fn is_left_handed(&self) -> bool {
658        !self.is_right_handed()
659    }
660
661    pub(crate) fn make_right_handed(self) -> Self {
662        if self.is_right_handed() {
663            return self;
664        }
665        // To make it right-handed, negate X, i.e. rotate the plane 180 degrees.
666        Self {
667            origin: self.origin,
668            x_axis: self.x_axis.negated(),
669            y_axis: self.y_axis,
670            z_axis: self.z_axis,
671        }
672    }
673}
674
675impl TryFrom<PlaneData> for PlaneInfo {
676    type Error = KclError;
677
678    fn try_from(value: PlaneData) -> Result<Self, Self::Error> {
679        let name = match value {
680            PlaneData::XY => PlaneName::Xy,
681            PlaneData::NegXY => PlaneName::NegXy,
682            PlaneData::XZ => PlaneName::Xz,
683            PlaneData::NegXZ => PlaneName::NegXz,
684            PlaneData::YZ => PlaneName::Yz,
685            PlaneData::NegYZ => PlaneName::NegYz,
686            PlaneData::Plane(info) => {
687                return Ok(info);
688            }
689        };
690
691        let info = DEFAULT_PLANE_INFO.get(&name).ok_or_else(|| {
692            KclError::new_internal(KclErrorDetails::new(
693                format!("Plane {name} not found"),
694                Default::default(),
695            ))
696        })?;
697
698        Ok(info.clone())
699    }
700}
701
702impl From<&PlaneData> for PlaneKind {
703    fn from(value: &PlaneData) -> Self {
704        match value {
705            PlaneData::XY => PlaneKind::XY,
706            PlaneData::NegXY => PlaneKind::XY,
707            PlaneData::XZ => PlaneKind::XZ,
708            PlaneData::NegXZ => PlaneKind::XZ,
709            PlaneData::YZ => PlaneKind::YZ,
710            PlaneData::NegYZ => PlaneKind::YZ,
711            PlaneData::Plane(_) => PlaneKind::Custom,
712        }
713    }
714}
715
716impl From<&PlaneInfo> for PlaneKind {
717    fn from(value: &PlaneInfo) -> Self {
718        let data = PlaneData::Plane(value.clone());
719        PlaneKind::from(&data)
720    }
721}
722
723impl From<PlaneInfo> for PlaneKind {
724    fn from(value: PlaneInfo) -> Self {
725        let data = PlaneData::Plane(value);
726        PlaneKind::from(&data)
727    }
728}
729
730impl Plane {
731    #[cfg(test)]
732    pub(crate) fn from_plane_data_skipping_engine(
733        value: PlaneData,
734        exec_state: &mut ExecState,
735    ) -> Result<Self, KclError> {
736        let id = exec_state.next_uuid();
737        let kind = PlaneKind::from(&value);
738        Ok(Plane {
739            id,
740            artifact_id: id.into(),
741            info: PlaneInfo::try_from(value)?,
742            object_id: None,
743            kind,
744            meta: vec![],
745        })
746    }
747
748    /// Returns true if the plane has been sent to the engine.
749    pub fn is_initialized(&self) -> bool {
750        self.object_id.is_some()
751    }
752
753    /// Returns true if the plane has not been sent to the engine yet.
754    pub fn is_uninitialized(&self) -> bool {
755        !self.is_initialized()
756    }
757
758    /// The standard planes are XY, YZ and XZ (in both positive and negative)
759    pub fn is_standard(&self) -> bool {
760        match &self.kind {
761            PlaneKind::XY | PlaneKind::YZ | PlaneKind::XZ => true,
762            PlaneKind::Custom => false,
763        }
764    }
765
766    /// Project a point onto a plane by calculating how far away it is and moving it along the
767    /// normal of the plane so that it now lies on the plane.
768    pub fn project(&self, point: Point3d) -> Point3d {
769        let v = point - self.info.origin;
770        let dot = v.axes_dot_product(&self.info.z_axis);
771
772        point - self.info.z_axis * dot
773    }
774}
775
776/// A face.
777#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
778#[ts(export)]
779#[serde(rename_all = "camelCase")]
780pub struct Face {
781    /// The id of the face.
782    pub id: uuid::Uuid,
783    /// The artifact ID.
784    pub artifact_id: ArtifactId,
785    /// The scene object ID.
786    pub object_id: ObjectId,
787    /// The tag of the face.
788    pub value: String,
789    /// What should the face's X axis be?
790    pub x_axis: Point3d,
791    /// What should the face's Y axis be?
792    pub y_axis: Point3d,
793    /// The solid the face is on.
794    pub parent_solid: FaceParentSolid,
795    pub units: UnitLength,
796    #[serde(skip)]
797    pub meta: Vec<Metadata>,
798}
799
800/// The limited subset of a face's parent solid needed by face-backed sketches.
801#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
802#[ts(export)]
803#[serde(rename_all = "camelCase")]
804pub struct FaceParentSolid {
805    /// Which solid does this face belong to?
806    pub solid_id: Uuid,
807    /// ID of the sketch which created this solid, if any.
808    pub creator_sketch_id: Option<Uuid>,
809    /// Has the creator sketch been closed? This is only relevant if `creator_sketch_id` is Some, and we cannot infer the closed status otherwise.
810    pub creator_sketch_is_closed: Option<ProfileClosed>,
811    /// Pending edge cut IDs that may need to be flushed before referencing the face.
812    #[serde(default, skip_serializing_if = "Vec::is_empty")]
813    pub edge_cut_ids: Vec<Uuid>,
814}
815
816impl FaceParentSolid {
817    pub(crate) fn sketch_or_solid_id(&self) -> Uuid {
818        self.creator_sketch_id.unwrap_or(self.solid_id)
819    }
820}
821
822/// A bounded edge.
823/// Carries either `edge_id` (resolved) or `edge_specifier` (payload passed through for resolution in blend).
824#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
825#[ts(export)]
826#[serde(rename_all = "camelCase")]
827pub struct BoundedEdge {
828    /// The id of the face this edge belongs to.
829    pub face_id: uuid::Uuid,
830    /// The id of the edge (when resolved from a tag or UUID). Mutually exclusive with `edge_specifier`.
831    #[serde(skip_serializing_if = "Option::is_none")]
832    pub edge_id: Option<uuid::Uuid>,
833    /// Edge specifier payload (sideFaces, endFaces, index) when not resolved. Resolved in blend().
834    #[serde(skip_serializing_if = "Option::is_none")]
835    pub edge_specifier: Option<UnresolvedEdgeSpecifier>,
836    /// A percentage bound of the edge, used to restrict what portion of the edge will be used.
837    /// Range (0, 1)
838    pub lower_bound: f32,
839    /// A percentage bound of the edge, used to restrict what portion of the edge will be used.
840    /// Range (0, 1)
841    pub upper_bound: f32,
842}
843
844/// Kind of plane.
845#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, ts_rs::TS, FromStr, Display)]
846#[ts(export)]
847#[display(style = "camelCase")]
848pub enum PlaneKind {
849    #[serde(rename = "XY", alias = "xy")]
850    #[display("XY")]
851    XY,
852    #[serde(rename = "XZ", alias = "xz")]
853    #[display("XZ")]
854    XZ,
855    #[serde(rename = "YZ", alias = "yz")]
856    #[display("YZ")]
857    YZ,
858    /// A custom plane.
859    #[display("Custom")]
860    Custom,
861}
862
863#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
864#[ts(export)]
865#[serde(tag = "type", rename_all = "camelCase")]
866pub struct Sketch {
867    /// The id of the sketch (this will change when the engine's reference to it changes).
868    pub id: uuid::Uuid,
869    /// The paths in the sketch.
870    /// Only paths on the "outside" i.e. the perimeter.
871    /// Does not include paths "inside" the profile (for example, edges made by subtracting a profile)
872    pub paths: Vec<Path>,
873    /// Inner paths, resulting from subtract2d to carve profiles out of the sketch.
874    #[serde(default, skip_serializing_if = "Vec::is_empty")]
875    pub inner_paths: Vec<Path>,
876    /// What the sketch is on (can be a plane or a face).
877    pub on: SketchSurface,
878    /// The starting path.
879    pub start: BasePath,
880    /// Tag identifiers that have been declared in this sketch.
881    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
882    pub tags: IndexMap<String, TagIdentifier>,
883    /// The original id of the sketch. This stays the same even if the sketch is
884    /// is sketched on face etc.
885    pub artifact_id: ArtifactId,
886    #[ts(skip)]
887    pub original_id: uuid::Uuid,
888    /// If this sketch represents a region created from `region()`, the origin
889    /// sketch ID is the ID of the sketch block it was created from. None,
890    /// otherwise. This field corresponds to the `origin_path_id` of the `Path`
891    /// artifact.
892    #[serde(skip_serializing_if = "Option::is_none")]
893    #[ts(skip)]
894    pub origin_sketch_id: Option<uuid::Uuid>,
895    /// If the sketch includes a mirror.
896    #[serde(skip)]
897    pub mirror: Option<uuid::Uuid>,
898    /// If the sketch is a clone of another sketch.
899    #[serde(skip)]
900    pub clone: Option<uuid::Uuid>,
901    /// Synthetic pen-jump paths inserted to replay disconnected segment selections.
902    #[serde(skip)]
903    #[ts(skip)]
904    pub synthetic_jump_path_ids: Vec<uuid::Uuid>,
905    pub units: UnitLength,
906    /// Metadata.
907    #[serde(skip)]
908    pub meta: Vec<Metadata>,
909    /// Has the profile been closed?
910    /// If not given, defaults to yes, closed explicitly.
911    #[serde(
912        default = "ProfileClosed::explicitly",
913        skip_serializing_if = "ProfileClosed::is_explicitly"
914    )]
915    pub is_closed: ProfileClosed,
916}
917
918impl ProfileClosed {
919    #[expect(dead_code, reason = "it's not actually dead, it's called by serde")]
920    fn explicitly() -> Self {
921        Self::Explicitly
922    }
923
924    fn is_explicitly(&self) -> bool {
925        matches!(self, ProfileClosed::Explicitly)
926    }
927}
928
929/// Has the profile been closed?
930#[derive(Debug, Serialize, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd, ts_rs::TS)]
931#[serde(rename_all = "camelCase")]
932pub enum ProfileClosed {
933    /// It's definitely open.
934    No,
935    /// Unknown.
936    Maybe,
937    /// Yes, by adding a segment which loops back to the start.
938    Implicitly,
939    /// Yes, by calling `close()` or by making a closed shape (e.g. circle).
940    Explicitly,
941}
942
943impl Sketch {
944    // Tell the engine to enter sketch mode on the sketch.
945    // Run a specific command, then exit sketch mode.
946    pub(crate) fn build_sketch_mode_cmds(
947        &self,
948        exec_state: &mut ExecState,
949        inner_cmd: ModelingCmdReq,
950    ) -> Vec<ModelingCmdReq> {
951        vec![
952            // Before we extrude, we need to enable the sketch mode.
953            // We do this here in case extrude is called out of order.
954            ModelingCmdReq {
955                cmd: ModelingCmd::from(
956                    mcmd::EnableSketchMode::builder()
957                        .animated(false)
958                        .ortho(false)
959                        .entity_id(self.on.id())
960                        .adjust_camera(false)
961                        .maybe_planar_normal(if let SketchSurface::Plane(plane) = &self.on {
962                            // We pass in the normal for the plane here.
963                            let normal = plane.info.x_axis.axes_cross_product(&plane.info.y_axis);
964                            Some(normal.into())
965                        } else {
966                            None
967                        })
968                        .build(),
969                ),
970                cmd_id: exec_state.next_uuid().into(),
971            },
972            inner_cmd,
973            ModelingCmdReq {
974                cmd: ModelingCmd::SketchModeDisable(mcmd::SketchModeDisable::builder().build()),
975                cmd_id: exec_state.next_uuid().into(),
976            },
977        ]
978    }
979}
980
981/// A sketch type.
982#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
983#[ts(export)]
984#[serde(tag = "type", rename_all = "camelCase")]
985pub enum SketchSurface {
986    Plane(Box<Plane>),
987    Face(Box<Face>),
988}
989
990impl SketchSurface {
991    pub(crate) fn id(&self) -> uuid::Uuid {
992        match self {
993            SketchSurface::Plane(plane) => plane.id,
994            SketchSurface::Face(face) => face.id,
995        }
996    }
997    pub(crate) fn x_axis(&self) -> Point3d {
998        match self {
999            SketchSurface::Plane(plane) => plane.info.x_axis,
1000            SketchSurface::Face(face) => face.x_axis,
1001        }
1002    }
1003    pub(crate) fn y_axis(&self) -> Point3d {
1004        match self {
1005            SketchSurface::Plane(plane) => plane.info.y_axis,
1006            SketchSurface::Face(face) => face.y_axis,
1007        }
1008    }
1009
1010    pub(crate) fn object_id(&self) -> Option<ObjectId> {
1011        match self {
1012            SketchSurface::Plane(plane) => plane.object_id,
1013            SketchSurface::Face(face) => Some(face.object_id),
1014        }
1015    }
1016
1017    pub(crate) fn set_object_id(&mut self, object_id: ObjectId) {
1018        match self {
1019            SketchSurface::Plane(plane) => plane.object_id = Some(object_id),
1020            SketchSurface::Face(face) => face.object_id = object_id,
1021        }
1022    }
1023}
1024
1025/// A Sketch, Face, or TaggedFace.
1026#[derive(Debug, Clone, PartialEq)]
1027pub enum Extrudable {
1028    /// Sketch.
1029    Sketch(Box<Sketch>),
1030    /// Tagged Face.
1031    FaceTag(FaceTag),
1032    /// Face.
1033    Face(Box<Face>),
1034}
1035
1036impl Extrudable {
1037    /// Get the relevant id.
1038    pub async fn id_to_extrude(
1039        &self,
1040        exec_state: &mut ExecState,
1041        args: &Args,
1042        must_be_planar: bool,
1043    ) -> Result<uuid::Uuid, KclError> {
1044        match self {
1045            Extrudable::Sketch(sketch) => Ok(sketch.id),
1046            Extrudable::FaceTag(face_tag) => face_tag.get_face_id_from_tag(exec_state, args, must_be_planar).await,
1047            Extrudable::Face(face) => Ok(face.id),
1048        }
1049    }
1050
1051    pub fn as_sketch(&self) -> Option<Sketch> {
1052        match self {
1053            Extrudable::Sketch(sketch) => Some((**sketch).clone()),
1054            Extrudable::FaceTag(face) => match face.geometry() {
1055                Some(Geometry::Sketch(sketch)) => Some(sketch),
1056                Some(Geometry::Solid(solid)) => solid.sketch().cloned(),
1057                None => None,
1058            },
1059            Extrudable::Face(_) => None,
1060        }
1061    }
1062
1063    pub fn is_closed(&self) -> ProfileClosed {
1064        match self {
1065            Extrudable::Sketch(sketch) => sketch.is_closed,
1066            Extrudable::FaceTag(face_tag) => match face_tag.geometry() {
1067                Some(Geometry::Sketch(sketch)) => sketch.is_closed,
1068                Some(Geometry::Solid(solid)) => solid
1069                    .sketch()
1070                    .map(|sketch| sketch.is_closed)
1071                    .unwrap_or(ProfileClosed::Maybe),
1072                _ => ProfileClosed::Maybe,
1073            },
1074            Extrudable::Face(face) => match face.parent_solid.creator_sketch_is_closed {
1075                Some(is_closed) => is_closed,
1076                None => ProfileClosed::Maybe,
1077            },
1078        }
1079    }
1080}
1081
1082impl From<Sketch> for Extrudable {
1083    fn from(value: Sketch) -> Self {
1084        Extrudable::Sketch(Box::new(value))
1085    }
1086}
1087
1088#[derive(Debug, Clone)]
1089pub(crate) enum GetTangentialInfoFromPathsResult {
1090    PreviousPoint([f64; 2]),
1091    Arc {
1092        center: [f64; 2],
1093        ccw: bool,
1094    },
1095    Circle {
1096        center: [f64; 2],
1097        ccw: bool,
1098        radius: f64,
1099    },
1100    Ellipse {
1101        center: [f64; 2],
1102        ccw: bool,
1103        major_axis: [f64; 2],
1104        _minor_radius: f64,
1105    },
1106}
1107
1108impl GetTangentialInfoFromPathsResult {
1109    pub(crate) fn tan_previous_point(&self, last_arc_end: [f64; 2]) -> [f64; 2] {
1110        match self {
1111            GetTangentialInfoFromPathsResult::PreviousPoint(p) => *p,
1112            GetTangentialInfoFromPathsResult::Arc { center, ccw } => {
1113                crate::std::utils::get_tangent_point_from_previous_arc(*center, *ccw, last_arc_end)
1114            }
1115            // The circle always starts at 0 degrees, so a suitable tangent
1116            // point is either directly above or below.
1117            GetTangentialInfoFromPathsResult::Circle {
1118                center, radius, ccw, ..
1119            } => [center[0] + radius, center[1] + if *ccw { -1.0 } else { 1.0 }],
1120            GetTangentialInfoFromPathsResult::Ellipse {
1121                center,
1122                major_axis,
1123                ccw,
1124                ..
1125            } => [center[0] + major_axis[0], center[1] + if *ccw { -1.0 } else { 1.0 }],
1126        }
1127    }
1128}
1129
1130impl Sketch {
1131    pub(crate) fn add_tag(
1132        &mut self,
1133        tag: NodeRef<'_, TagDeclarator>,
1134        current_path: &Path,
1135        exec_state: &ExecState,
1136        surface: Option<&ExtrudeSurface>,
1137    ) {
1138        let mut tag_identifier: TagIdentifier = tag.into();
1139        let base = current_path.get_base();
1140        let mut sketch_copy = self.clone();
1141        sketch_copy.tags.clear();
1142        tag_identifier.info.push((
1143            exec_state.stack().current_epoch(),
1144            TagEngineInfo {
1145                id: base.geo_meta.id,
1146                geometry: Geometry::Sketch(sketch_copy),
1147                path: Some(current_path.clone()),
1148                surface: surface.cloned(),
1149            },
1150        ));
1151
1152        self.tags.insert(tag.name.to_string(), tag_identifier);
1153    }
1154
1155    pub(crate) fn merge_tags<'a>(&mut self, tags: impl Iterator<Item = &'a TagIdentifier>) {
1156        for t in tags {
1157            match self.tags.get_mut(&t.value) {
1158                Some(id) => {
1159                    id.merge_info(t);
1160                }
1161                None => {
1162                    self.tags.insert(t.value.clone(), t.clone());
1163                }
1164            }
1165        }
1166    }
1167
1168    /// Get the path most recently sketched.
1169    pub(crate) fn latest_path(&self) -> Option<&Path> {
1170        self.paths.last()
1171    }
1172
1173    /// The "pen" is an imaginary pen drawing the path.
1174    /// This gets the current point the pen is hovering over, i.e. the point
1175    /// where the last path segment ends, and the next path segment will begin.
1176    pub(crate) fn current_pen_position(&self) -> Result<Point2d, KclError> {
1177        let Some(path) = self.latest_path() else {
1178            return Ok(Point2d::new(self.start.to[0], self.start.to[1], self.start.units));
1179        };
1180
1181        let to = path.get_base().to;
1182        Ok(Point2d::new(to[0], to[1], path.get_base().units))
1183    }
1184
1185    pub(crate) fn get_tangential_info_from_paths(&self) -> GetTangentialInfoFromPathsResult {
1186        let Some(path) = self.latest_path() else {
1187            return GetTangentialInfoFromPathsResult::PreviousPoint(self.start.to);
1188        };
1189        path.get_tangential_info()
1190    }
1191}
1192
1193#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1194#[ts(export)]
1195#[serde(tag = "type", rename_all = "camelCase")]
1196pub struct Solid {
1197    /// The id of the solid.
1198    pub id: uuid::Uuid,
1199    /// Internal KCL value generation. The engine may reuse `id` for a new value.
1200    #[serde(skip)]
1201    #[ts(skip)]
1202    pub value_id: uuid::Uuid,
1203    /// The artifact ID of the solid.  Unlike `id`, this doesn't change.
1204    pub artifact_id: ArtifactId,
1205    /// The extrude surfaces.
1206    pub value: Vec<ExtrudeSurface>,
1207    /// How this solid was created.
1208    #[serde(rename = "sketch")]
1209    pub creator: SolidCreator,
1210    /// The id of the extrusion start cap
1211    pub start_cap_id: Option<uuid::Uuid>,
1212    /// The id of the extrusion end cap
1213    pub end_cap_id: Option<uuid::Uuid>,
1214    /// Chamfers or fillets on this solid.
1215    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1216    pub edge_cuts: Vec<EdgeCut>,
1217    /// Batch-end fillet/chamfer command ids that do not have concrete edge ids.
1218    #[serde(skip)]
1219    #[ts(skip)]
1220    pub pending_edge_cut_ids: Vec<uuid::Uuid>,
1221    /// The units of the solid.
1222    pub units: UnitLength,
1223    /// Is this a sectional solid?
1224    pub sectional: bool,
1225    /// Metadata.
1226    #[serde(skip)]
1227    pub meta: Vec<Metadata>,
1228}
1229
1230#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1231#[ts(export)]
1232pub struct CreatorFace {
1233    /// The face id that served as the base.
1234    pub face_id: uuid::Uuid,
1235    /// The solid id that owned the face.
1236    pub solid_id: uuid::Uuid,
1237    /// The sketch used for the operation.
1238    pub sketch: Sketch,
1239}
1240
1241/// How a solid was created.
1242#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1243#[ts(export)]
1244#[serde(tag = "creatorType", rename_all = "camelCase")]
1245pub enum SolidCreator {
1246    /// Created from a sketch.
1247    Sketch(Sketch),
1248    /// Created by extruding or modifying a face.
1249    Face(CreatorFace),
1250    /// Created procedurally without a sketch.
1251    Procedural,
1252}
1253
1254impl Solid {
1255    pub fn sketch(&self) -> Option<&Sketch> {
1256        match &self.creator {
1257            SolidCreator::Sketch(sketch) => Some(sketch),
1258            SolidCreator::Face(CreatorFace { sketch, .. }) => Some(sketch),
1259            SolidCreator::Procedural => None,
1260        }
1261    }
1262
1263    pub fn sketch_mut(&mut self) -> Option<&mut Sketch> {
1264        match &mut self.creator {
1265            SolidCreator::Sketch(sketch) => Some(sketch),
1266            SolidCreator::Face(CreatorFace { sketch, .. }) => Some(sketch),
1267            SolidCreator::Procedural => None,
1268        }
1269    }
1270
1271    pub fn sketch_id(&self) -> Option<uuid::Uuid> {
1272        self.sketch().map(|sketch| sketch.id)
1273    }
1274
1275    pub fn original_id(&self) -> uuid::Uuid {
1276        self.sketch().map(|sketch| sketch.original_id).unwrap_or(self.id)
1277    }
1278
1279    pub(crate) fn get_all_edge_cut_ids(&self) -> impl Iterator<Item = uuid::Uuid> + '_ {
1280        self.edge_cuts
1281            .iter()
1282            .map(|foc| foc.id())
1283            .chain(self.pending_edge_cut_ids.iter().copied())
1284    }
1285}
1286
1287impl From<&Solid> for FaceParentSolid {
1288    fn from(solid: &Solid) -> Self {
1289        Self {
1290            solid_id: solid.id,
1291            creator_sketch_id: solid.sketch_id(),
1292            creator_sketch_is_closed: solid.sketch().map(|sketch| sketch.is_closed),
1293            edge_cut_ids: solid.get_all_edge_cut_ids().collect(),
1294        }
1295    }
1296}
1297
1298/// A fillet or a chamfer.
1299#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1300#[ts(export)]
1301#[serde(tag = "type", rename_all = "camelCase")]
1302pub enum EdgeCut {
1303    /// A fillet.
1304    Fillet {
1305        /// The id of the engine command that called this fillet.
1306        id: uuid::Uuid,
1307        radius: TyF64,
1308        /// The engine id of the edge to fillet.
1309        #[serde(rename = "edgeId")]
1310        edge_id: uuid::Uuid,
1311        tag: Box<Option<TagNode>>,
1312    },
1313    /// A chamfer.
1314    Chamfer {
1315        /// The id of the engine command that called this chamfer.
1316        id: uuid::Uuid,
1317        length: TyF64,
1318        /// The engine id of the edge to chamfer.
1319        #[serde(rename = "edgeId")]
1320        edge_id: uuid::Uuid,
1321        tag: Box<Option<TagNode>>,
1322    },
1323}
1324
1325impl EdgeCut {
1326    pub fn id(&self) -> uuid::Uuid {
1327        match self {
1328            EdgeCut::Fillet { id, .. } => *id,
1329            EdgeCut::Chamfer { id, .. } => *id,
1330        }
1331    }
1332
1333    pub fn set_id(&mut self, id: uuid::Uuid) {
1334        match self {
1335            EdgeCut::Fillet { id: i, .. } => *i = id,
1336            EdgeCut::Chamfer { id: i, .. } => *i = id,
1337        }
1338    }
1339
1340    pub fn edge_id(&self) -> uuid::Uuid {
1341        match self {
1342            EdgeCut::Fillet { edge_id, .. } => *edge_id,
1343            EdgeCut::Chamfer { edge_id, .. } => *edge_id,
1344        }
1345    }
1346
1347    pub fn set_edge_id(&mut self, id: uuid::Uuid) {
1348        match self {
1349            EdgeCut::Fillet { edge_id: i, .. } => *i = id,
1350            EdgeCut::Chamfer { edge_id: i, .. } => *i = id,
1351        }
1352    }
1353
1354    pub fn tag(&self) -> Option<TagNode> {
1355        match self {
1356            EdgeCut::Fillet { tag, .. } => *tag.clone(),
1357            EdgeCut::Chamfer { tag, .. } => *tag.clone(),
1358        }
1359    }
1360}
1361
1362#[derive(Debug, Serialize, PartialEq, Clone, Copy, ts_rs::TS)]
1363#[ts(export)]
1364pub struct Point2d {
1365    pub x: f64,
1366    pub y: f64,
1367    pub units: UnitLength,
1368}
1369
1370impl Point2d {
1371    pub const ZERO: Self = Self {
1372        x: 0.0,
1373        y: 0.0,
1374        units: UnitLength::Millimeters,
1375    };
1376
1377    pub fn new(x: f64, y: f64, units: UnitLength) -> Self {
1378        Self { x, y, units }
1379    }
1380
1381    pub fn into_x(self) -> TyF64 {
1382        TyF64::new(self.x, self.units.into())
1383    }
1384
1385    pub fn into_y(self) -> TyF64 {
1386        TyF64::new(self.y, self.units.into())
1387    }
1388
1389    pub fn ignore_units(self) -> [f64; 2] {
1390        [self.x, self.y]
1391    }
1392}
1393
1394#[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, ts_rs::TS, Default)]
1395#[ts(export)]
1396pub struct Point3d {
1397    pub x: f64,
1398    pub y: f64,
1399    pub z: f64,
1400    pub units: Option<UnitLength>,
1401}
1402
1403impl Point3d {
1404    pub const ZERO: Self = Self {
1405        x: 0.0,
1406        y: 0.0,
1407        z: 0.0,
1408        units: Some(UnitLength::Millimeters),
1409    };
1410
1411    pub fn new(x: f64, y: f64, z: f64, units: Option<UnitLength>) -> Self {
1412        Self { x, y, z, units }
1413    }
1414
1415    pub const fn is_zero(&self) -> bool {
1416        self.x == 0.0 && self.y == 0.0 && self.z == 0.0
1417    }
1418
1419    /// Calculate the cross product of this vector with another.
1420    ///
1421    /// This should only be applied to axes or other vectors which represent only a direction (and
1422    /// no magnitude) since units are ignored.
1423    pub fn axes_cross_product(&self, other: &Self) -> Self {
1424        Self {
1425            x: self.y * other.z - self.z * other.y,
1426            y: self.z * other.x - self.x * other.z,
1427            z: self.x * other.y - self.y * other.x,
1428            units: None,
1429        }
1430    }
1431
1432    /// Normalize `-0.0` to `0.0` for cleaner serialized axis data.
1433    pub fn canonicalize_signed_zero(&mut self) {
1434        if self.x == 0.0 {
1435            self.x = 0.0;
1436        }
1437        if self.y == 0.0 {
1438            self.y = 0.0;
1439        }
1440        if self.z == 0.0 {
1441            self.z = 0.0;
1442        }
1443    }
1444
1445    /// Calculate the dot product of this vector with another.
1446    ///
1447    /// This should only be applied to axes or other vectors which represent only a direction (and
1448    /// no magnitude) since units are ignored.
1449    pub fn axes_dot_product(&self, other: &Self) -> f64 {
1450        let x = self.x * other.x;
1451        let y = self.y * other.y;
1452        let z = self.z * other.z;
1453        x + y + z
1454    }
1455
1456    pub fn normalize(&self) -> Self {
1457        let len = f64::sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
1458        Point3d {
1459            x: self.x / len,
1460            y: self.y / len,
1461            z: self.z / len,
1462            units: None,
1463        }
1464    }
1465
1466    pub fn as_3_dims(&self) -> ([f64; 3], Option<UnitLength>) {
1467        let p = [self.x, self.y, self.z];
1468        let u = self.units;
1469        (p, u)
1470    }
1471
1472    pub(crate) fn negated(self) -> Self {
1473        Self {
1474            x: -self.x,
1475            y: -self.y,
1476            z: -self.z,
1477            units: self.units,
1478        }
1479    }
1480}
1481
1482impl From<[TyF64; 3]> for Point3d {
1483    fn from(p: [TyF64; 3]) -> Self {
1484        Self {
1485            x: p[0].n,
1486            y: p[1].n,
1487            z: p[2].n,
1488            units: p[0].ty.as_length(),
1489        }
1490    }
1491}
1492
1493impl From<Point3d> for Point3D {
1494    fn from(p: Point3d) -> Self {
1495        Self { x: p.x, y: p.y, z: p.z }
1496    }
1497}
1498
1499impl From<Point3d> for kittycad_modeling_cmds::shared::Point3d<LengthUnit> {
1500    fn from(p: Point3d) -> Self {
1501        if let Some(units) = p.units {
1502            Self {
1503                x: LengthUnit(adjust_length(units, p.x, UnitLength::Millimeters).0),
1504                y: LengthUnit(adjust_length(units, p.y, UnitLength::Millimeters).0),
1505                z: LengthUnit(adjust_length(units, p.z, UnitLength::Millimeters).0),
1506            }
1507        } else {
1508            Self {
1509                x: LengthUnit(p.x),
1510                y: LengthUnit(p.y),
1511                z: LengthUnit(p.z),
1512            }
1513        }
1514    }
1515}
1516
1517impl Add for Point3d {
1518    type Output = Point3d;
1519
1520    fn add(self, rhs: Self) -> Self::Output {
1521        // TODO should assert that self and rhs the same units or coerce them
1522        Point3d {
1523            x: self.x + rhs.x,
1524            y: self.y + rhs.y,
1525            z: self.z + rhs.z,
1526            units: self.units,
1527        }
1528    }
1529}
1530
1531impl AddAssign for Point3d {
1532    fn add_assign(&mut self, rhs: Self) {
1533        *self = *self + rhs
1534    }
1535}
1536
1537impl Sub for Point3d {
1538    type Output = Point3d;
1539
1540    fn sub(self, rhs: Self) -> Self::Output {
1541        let (x, y, z) = if rhs.units != self.units
1542            && let Some(sunits) = self.units
1543            && let Some(runits) = rhs.units
1544        {
1545            (
1546                adjust_length(runits, rhs.x, sunits).0,
1547                adjust_length(runits, rhs.y, sunits).0,
1548                adjust_length(runits, rhs.z, sunits).0,
1549            )
1550        } else {
1551            (rhs.x, rhs.y, rhs.z)
1552        };
1553        Point3d {
1554            x: self.x - x,
1555            y: self.y - y,
1556            z: self.z - z,
1557            units: self.units,
1558        }
1559    }
1560}
1561
1562impl SubAssign for Point3d {
1563    fn sub_assign(&mut self, rhs: Self) {
1564        *self = *self - rhs
1565    }
1566}
1567
1568impl Mul<f64> for Point3d {
1569    type Output = Point3d;
1570
1571    fn mul(self, rhs: f64) -> Self::Output {
1572        Point3d {
1573            x: self.x * rhs,
1574            y: self.y * rhs,
1575            z: self.z * rhs,
1576            units: self.units,
1577        }
1578    }
1579}
1580
1581/// A base path.
1582#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1583#[ts(export)]
1584#[serde(rename_all = "camelCase")]
1585pub struct BasePath {
1586    /// The from point.
1587    #[ts(type = "[number, number]")]
1588    pub from: [f64; 2],
1589    /// The to point.
1590    #[ts(type = "[number, number]")]
1591    pub to: [f64; 2],
1592    pub units: UnitLength,
1593    /// The tag of the path.
1594    pub tag: Option<TagNode>,
1595    /// Metadata.
1596    #[serde(rename = "__geoMeta")]
1597    pub geo_meta: GeoMeta,
1598}
1599
1600impl BasePath {
1601    pub fn get_to(&self) -> [TyF64; 2] {
1602        let ty: NumericType = self.units.into();
1603        [TyF64::new(self.to[0], ty), TyF64::new(self.to[1], ty)]
1604    }
1605
1606    pub fn get_from(&self) -> [TyF64; 2] {
1607        let ty: NumericType = self.units.into();
1608        [TyF64::new(self.from[0], ty), TyF64::new(self.from[1], ty)]
1609    }
1610}
1611
1612/// Geometry metadata.
1613#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1614#[ts(export)]
1615#[serde(rename_all = "camelCase")]
1616pub struct GeoMeta {
1617    /// The id of the geometry.
1618    pub id: uuid::Uuid,
1619    /// Metadata.
1620    #[serde(flatten)]
1621    pub metadata: Metadata,
1622}
1623
1624/// A path.
1625#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1626#[ts(export)]
1627#[serde(tag = "type")]
1628pub enum Path {
1629    /// A straight line which ends at the given point.
1630    ToPoint {
1631        #[serde(flatten)]
1632        base: BasePath,
1633    },
1634    /// A arc that is tangential to the last path segment that goes to a point
1635    TangentialArcTo {
1636        #[serde(flatten)]
1637        base: BasePath,
1638        /// the arc's center
1639        #[ts(type = "[number, number]")]
1640        center: [f64; 2],
1641        /// arc's direction
1642        ccw: bool,
1643    },
1644    /// A arc that is tangential to the last path segment
1645    TangentialArc {
1646        #[serde(flatten)]
1647        base: BasePath,
1648        /// the arc's center
1649        #[ts(type = "[number, number]")]
1650        center: [f64; 2],
1651        /// arc's direction
1652        ccw: bool,
1653    },
1654    // TODO: consolidate segment enums, remove Circle. https://github.com/KittyCAD/modeling-app/issues/3940
1655    /// a complete arc
1656    Circle {
1657        #[serde(flatten)]
1658        base: BasePath,
1659        /// the arc's center
1660        #[ts(type = "[number, number]")]
1661        center: [f64; 2],
1662        /// the arc's radius
1663        radius: f64,
1664        /// arc's direction
1665        /// This is used to compute the tangential angle.
1666        ccw: bool,
1667    },
1668    CircleThreePoint {
1669        #[serde(flatten)]
1670        base: BasePath,
1671        /// Point 1 of the circle
1672        #[ts(type = "[number, number]")]
1673        p1: [f64; 2],
1674        /// Point 2 of the circle
1675        #[ts(type = "[number, number]")]
1676        p2: [f64; 2],
1677        /// Point 3 of the circle
1678        #[ts(type = "[number, number]")]
1679        p3: [f64; 2],
1680    },
1681    ArcThreePoint {
1682        #[serde(flatten)]
1683        base: BasePath,
1684        /// Point 1 of the arc (base on the end of previous segment)
1685        #[ts(type = "[number, number]")]
1686        p1: [f64; 2],
1687        /// Point 2 of the arc (interiorAbsolute kwarg)
1688        #[ts(type = "[number, number]")]
1689        p2: [f64; 2],
1690        /// Point 3 of the arc (endAbsolute kwarg)
1691        #[ts(type = "[number, number]")]
1692        p3: [f64; 2],
1693    },
1694    /// A path that is horizontal.
1695    Horizontal {
1696        #[serde(flatten)]
1697        base: BasePath,
1698        /// The x coordinate.
1699        x: f64,
1700    },
1701    /// An angled line to.
1702    AngledLineTo {
1703        #[serde(flatten)]
1704        base: BasePath,
1705        /// The x coordinate.
1706        x: Option<f64>,
1707        /// The y coordinate.
1708        y: Option<f64>,
1709    },
1710    /// A base path.
1711    Base {
1712        #[serde(flatten)]
1713        base: BasePath,
1714    },
1715    /// A circular arc, not necessarily tangential to the current point.
1716    Arc {
1717        #[serde(flatten)]
1718        base: BasePath,
1719        /// Center of the circle that this arc is drawn on.
1720        center: [f64; 2],
1721        /// Radius of the circle that this arc is drawn on.
1722        radius: f64,
1723        /// True if the arc is counterclockwise.
1724        ccw: bool,
1725    },
1726    Ellipse {
1727        #[serde(flatten)]
1728        base: BasePath,
1729        center: [f64; 2],
1730        major_axis: [f64; 2],
1731        minor_radius: f64,
1732        ccw: bool,
1733    },
1734    //TODO: (bc) figure this out
1735    Conic {
1736        #[serde(flatten)]
1737        base: BasePath,
1738    },
1739    /// A cubic Bezier curve.
1740    Bezier {
1741        #[serde(flatten)]
1742        base: BasePath,
1743        /// First control point (absolute coordinates).
1744        #[ts(type = "[number, number]")]
1745        control1: [f64; 2],
1746        /// Second control point (absolute coordinates).
1747        #[ts(type = "[number, number]")]
1748        control2: [f64; 2],
1749    },
1750}
1751
1752impl Path {
1753    pub fn get_id(&self) -> uuid::Uuid {
1754        match self {
1755            Path::ToPoint { base } => base.geo_meta.id,
1756            Path::Horizontal { base, .. } => base.geo_meta.id,
1757            Path::AngledLineTo { base, .. } => base.geo_meta.id,
1758            Path::Base { base } => base.geo_meta.id,
1759            Path::TangentialArcTo { base, .. } => base.geo_meta.id,
1760            Path::TangentialArc { base, .. } => base.geo_meta.id,
1761            Path::Circle { base, .. } => base.geo_meta.id,
1762            Path::CircleThreePoint { base, .. } => base.geo_meta.id,
1763            Path::Arc { base, .. } => base.geo_meta.id,
1764            Path::ArcThreePoint { base, .. } => base.geo_meta.id,
1765            Path::Ellipse { base, .. } => base.geo_meta.id,
1766            Path::Conic { base, .. } => base.geo_meta.id,
1767            Path::Bezier { base, .. } => base.geo_meta.id,
1768        }
1769    }
1770
1771    pub fn set_id(&mut self, id: uuid::Uuid) {
1772        match self {
1773            Path::ToPoint { base } => base.geo_meta.id = id,
1774            Path::Horizontal { base, .. } => base.geo_meta.id = id,
1775            Path::AngledLineTo { base, .. } => base.geo_meta.id = id,
1776            Path::Base { base } => base.geo_meta.id = id,
1777            Path::TangentialArcTo { base, .. } => base.geo_meta.id = id,
1778            Path::TangentialArc { base, .. } => base.geo_meta.id = id,
1779            Path::Circle { base, .. } => base.geo_meta.id = id,
1780            Path::CircleThreePoint { base, .. } => base.geo_meta.id = id,
1781            Path::Arc { base, .. } => base.geo_meta.id = id,
1782            Path::ArcThreePoint { base, .. } => base.geo_meta.id = id,
1783            Path::Ellipse { base, .. } => base.geo_meta.id = id,
1784            Path::Conic { base, .. } => base.geo_meta.id = id,
1785            Path::Bezier { base, .. } => base.geo_meta.id = id,
1786        }
1787    }
1788
1789    pub fn get_tag(&self) -> Option<TagNode> {
1790        match self {
1791            Path::ToPoint { base } => base.tag.clone(),
1792            Path::Horizontal { base, .. } => base.tag.clone(),
1793            Path::AngledLineTo { base, .. } => base.tag.clone(),
1794            Path::Base { base } => base.tag.clone(),
1795            Path::TangentialArcTo { base, .. } => base.tag.clone(),
1796            Path::TangentialArc { base, .. } => base.tag.clone(),
1797            Path::Circle { base, .. } => base.tag.clone(),
1798            Path::CircleThreePoint { base, .. } => base.tag.clone(),
1799            Path::Arc { base, .. } => base.tag.clone(),
1800            Path::ArcThreePoint { base, .. } => base.tag.clone(),
1801            Path::Ellipse { base, .. } => base.tag.clone(),
1802            Path::Conic { base, .. } => base.tag.clone(),
1803            Path::Bezier { base, .. } => base.tag.clone(),
1804        }
1805    }
1806
1807    pub fn get_base(&self) -> &BasePath {
1808        match self {
1809            Path::ToPoint { base } => base,
1810            Path::Horizontal { base, .. } => base,
1811            Path::AngledLineTo { base, .. } => base,
1812            Path::Base { base } => base,
1813            Path::TangentialArcTo { base, .. } => base,
1814            Path::TangentialArc { base, .. } => base,
1815            Path::Circle { base, .. } => base,
1816            Path::CircleThreePoint { base, .. } => base,
1817            Path::Arc { base, .. } => base,
1818            Path::ArcThreePoint { base, .. } => base,
1819            Path::Ellipse { base, .. } => base,
1820            Path::Conic { base, .. } => base,
1821            Path::Bezier { base, .. } => base,
1822        }
1823    }
1824
1825    /// Where does this path segment start?
1826    pub fn get_from(&self) -> [TyF64; 2] {
1827        let p = &self.get_base().from;
1828        let ty: NumericType = self.get_base().units.into();
1829        [TyF64::new(p[0], ty), TyF64::new(p[1], ty)]
1830    }
1831
1832    /// Where does this path segment end?
1833    pub fn get_to(&self) -> [TyF64; 2] {
1834        let p = &self.get_base().to;
1835        let ty: NumericType = self.get_base().units.into();
1836        [TyF64::new(p[0], ty), TyF64::new(p[1], ty)]
1837    }
1838
1839    /// The path segment start point and its type.
1840    pub fn start_point_components(&self) -> ([f64; 2], NumericType) {
1841        let p = &self.get_base().from;
1842        let ty: NumericType = self.get_base().units.into();
1843        (*p, ty)
1844    }
1845
1846    /// The path segment end point and its type.
1847    pub fn end_point_components(&self) -> ([f64; 2], NumericType) {
1848        let p = &self.get_base().to;
1849        let ty: NumericType = self.get_base().units.into();
1850        (*p, ty)
1851    }
1852
1853    /// Length of this path segment, in cartesian plane. Not all segment types
1854    /// are supported.
1855    pub fn length(&self) -> Option<TyF64> {
1856        let n = match self {
1857            Self::ToPoint { .. } | Self::Base { .. } | Self::Horizontal { .. } | Self::AngledLineTo { .. } => {
1858                Some(linear_distance(&self.get_base().from, &self.get_base().to))
1859            }
1860            Self::TangentialArc {
1861                base: _,
1862                center,
1863                ccw: _,
1864            }
1865            | Self::TangentialArcTo {
1866                base: _,
1867                center,
1868                ccw: _,
1869            } => {
1870                // The radius can be calculated as the linear distance between `to` and `center`,
1871                // or between `from` and `center`. They should be the same.
1872                let radius = linear_distance(&self.get_base().from, center);
1873                debug_assert_eq!(radius, linear_distance(&self.get_base().to, center));
1874                // TODO: Call engine utils to figure this out.
1875                Some(linear_distance(&self.get_base().from, &self.get_base().to))
1876            }
1877            Self::Circle { radius, .. } => Some(TAU * radius),
1878            Self::CircleThreePoint { .. } => {
1879                let circle_center = crate::std::utils::calculate_circle_from_3_points([
1880                    self.get_base().from,
1881                    self.get_base().to,
1882                    self.get_base().to,
1883                ]);
1884                let radius = linear_distance(
1885                    &[circle_center.center[0], circle_center.center[1]],
1886                    &self.get_base().from,
1887                );
1888                Some(TAU * radius)
1889            }
1890            Self::Arc { .. } => {
1891                // TODO: Call engine utils to figure this out.
1892                Some(linear_distance(&self.get_base().from, &self.get_base().to))
1893            }
1894            Self::ArcThreePoint { .. } => {
1895                // TODO: Call engine utils to figure this out.
1896                Some(linear_distance(&self.get_base().from, &self.get_base().to))
1897            }
1898            Self::Ellipse { .. } => {
1899                // Not supported.
1900                None
1901            }
1902            Self::Conic { .. } => {
1903                // Not supported.
1904                None
1905            }
1906            Self::Bezier { .. } => {
1907                // Not supported - Bezier curve length requires numerical integration.
1908                None
1909            }
1910        };
1911        n.map(|n| TyF64::new(n, self.get_base().units.into()))
1912    }
1913
1914    pub fn get_base_mut(&mut self) -> &mut BasePath {
1915        match self {
1916            Path::ToPoint { base } => base,
1917            Path::Horizontal { base, .. } => base,
1918            Path::AngledLineTo { base, .. } => base,
1919            Path::Base { base } => base,
1920            Path::TangentialArcTo { base, .. } => base,
1921            Path::TangentialArc { base, .. } => base,
1922            Path::Circle { base, .. } => base,
1923            Path::CircleThreePoint { base, .. } => base,
1924            Path::Arc { base, .. } => base,
1925            Path::ArcThreePoint { base, .. } => base,
1926            Path::Ellipse { base, .. } => base,
1927            Path::Conic { base, .. } => base,
1928            Path::Bezier { base, .. } => base,
1929        }
1930    }
1931
1932    pub(crate) fn get_tangential_info(&self) -> GetTangentialInfoFromPathsResult {
1933        match self {
1934            Path::TangentialArc { center, ccw, .. }
1935            | Path::TangentialArcTo { center, ccw, .. }
1936            | Path::Arc { center, ccw, .. } => GetTangentialInfoFromPathsResult::Arc {
1937                center: *center,
1938                ccw: *ccw,
1939            },
1940            Path::ArcThreePoint { p1, p2, p3, .. } => {
1941                let circle = crate::std::utils::calculate_circle_from_3_points([*p1, *p2, *p3]);
1942                GetTangentialInfoFromPathsResult::Arc {
1943                    center: circle.center,
1944                    ccw: crate::std::utils::is_points_ccw(&[*p1, *p2, *p3]) > 0,
1945                }
1946            }
1947            Path::Circle {
1948                center, ccw, radius, ..
1949            } => GetTangentialInfoFromPathsResult::Circle {
1950                center: *center,
1951                ccw: *ccw,
1952                radius: *radius,
1953            },
1954            Path::CircleThreePoint { p1, p2, p3, .. } => {
1955                let circle = crate::std::utils::calculate_circle_from_3_points([*p1, *p2, *p3]);
1956                let center_point = [circle.center[0], circle.center[1]];
1957                GetTangentialInfoFromPathsResult::Circle {
1958                    center: center_point,
1959                    // Note: a circle is always ccw regardless of the order of points
1960                    ccw: true,
1961                    radius: circle.radius,
1962                }
1963            }
1964            // TODO: (bc) fix me
1965            Path::Ellipse {
1966                center,
1967                major_axis,
1968                minor_radius,
1969                ccw,
1970                ..
1971            } => GetTangentialInfoFromPathsResult::Ellipse {
1972                center: *center,
1973                major_axis: *major_axis,
1974                _minor_radius: *minor_radius,
1975                ccw: *ccw,
1976            },
1977            Path::Conic { .. }
1978            | Path::ToPoint { .. }
1979            | Path::Horizontal { .. }
1980            | Path::AngledLineTo { .. }
1981            | Path::Base { .. }
1982            | Path::Bezier { .. } => {
1983                let base = self.get_base();
1984                GetTangentialInfoFromPathsResult::PreviousPoint(base.from)
1985            }
1986        }
1987    }
1988
1989    /// i.e. not a curve
1990    pub(crate) fn is_straight_line(&self) -> bool {
1991        matches!(self, Path::AngledLineTo { .. } | Path::ToPoint { .. })
1992    }
1993}
1994
1995/// Compute the straight-line distance between a pair of (2D) points.
1996#[rustfmt::skip]
1997fn linear_distance(
1998    [x0, y0]: &[f64; 2],
1999    [x1, y1]: &[f64; 2]
2000) -> f64 {
2001    let y_sq = (y1 - y0).squared();
2002    let x_sq = (x1 - x0).squared();
2003    (y_sq + x_sq).sqrt()
2004}
2005
2006/// An extrude surface.
2007#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2008#[ts(export)]
2009#[serde(tag = "type", rename_all = "camelCase")]
2010pub enum ExtrudeSurface {
2011    /// An extrude plane.
2012    ExtrudePlane(ExtrudePlane),
2013    ExtrudeArc(ExtrudeArc),
2014    Chamfer(ChamferSurface),
2015    Fillet(FilletSurface),
2016}
2017
2018// Chamfer surface.
2019#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2020#[ts(export)]
2021#[serde(rename_all = "camelCase")]
2022pub struct ChamferSurface {
2023    /// The id for the chamfer surface.
2024    pub face_id: uuid::Uuid,
2025    /// The tag.
2026    pub tag: Option<Node<TagDeclarator>>,
2027    /// Metadata.
2028    #[serde(flatten)]
2029    pub geo_meta: GeoMeta,
2030}
2031
2032// Fillet surface.
2033#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2034#[ts(export)]
2035#[serde(rename_all = "camelCase")]
2036pub struct FilletSurface {
2037    /// The id for the fillet surface.
2038    pub face_id: uuid::Uuid,
2039    /// The tag.
2040    pub tag: Option<Node<TagDeclarator>>,
2041    /// Metadata.
2042    #[serde(flatten)]
2043    pub geo_meta: GeoMeta,
2044}
2045
2046/// An extruded plane.
2047#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2048#[ts(export)]
2049#[serde(rename_all = "camelCase")]
2050pub struct ExtrudePlane {
2051    /// The face id for the extrude plane.
2052    pub face_id: uuid::Uuid,
2053    /// The tag.
2054    pub tag: Option<Node<TagDeclarator>>,
2055    /// Metadata.
2056    #[serde(flatten)]
2057    pub geo_meta: GeoMeta,
2058}
2059
2060/// An extruded arc.
2061#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2062#[ts(export)]
2063#[serde(rename_all = "camelCase")]
2064pub struct ExtrudeArc {
2065    /// The face id for the extrude plane.
2066    pub face_id: uuid::Uuid,
2067    /// The tag.
2068    pub tag: Option<Node<TagDeclarator>>,
2069    /// Metadata.
2070    #[serde(flatten)]
2071    pub geo_meta: GeoMeta,
2072}
2073
2074impl ExtrudeSurface {
2075    pub fn get_id(&self) -> uuid::Uuid {
2076        match self {
2077            ExtrudeSurface::ExtrudePlane(ep) => ep.geo_meta.id,
2078            ExtrudeSurface::ExtrudeArc(ea) => ea.geo_meta.id,
2079            ExtrudeSurface::Fillet(f) => f.geo_meta.id,
2080            ExtrudeSurface::Chamfer(c) => c.geo_meta.id,
2081        }
2082    }
2083
2084    pub fn face_id(&self) -> uuid::Uuid {
2085        match self {
2086            ExtrudeSurface::ExtrudePlane(ep) => ep.face_id,
2087            ExtrudeSurface::ExtrudeArc(ea) => ea.face_id,
2088            ExtrudeSurface::Fillet(f) => f.face_id,
2089            ExtrudeSurface::Chamfer(c) => c.face_id,
2090        }
2091    }
2092
2093    pub fn set_face_id(&mut self, face_id: uuid::Uuid) {
2094        match self {
2095            ExtrudeSurface::ExtrudePlane(ep) => ep.face_id = face_id,
2096            ExtrudeSurface::ExtrudeArc(ea) => ea.face_id = face_id,
2097            ExtrudeSurface::Fillet(f) => f.face_id = face_id,
2098            ExtrudeSurface::Chamfer(c) => c.face_id = face_id,
2099        }
2100    }
2101
2102    pub fn set_surface_tag(&mut self, tag: &TagNode) {
2103        match self {
2104            ExtrudeSurface::ExtrudePlane(extrude_plane) => extrude_plane.tag = Some(tag.clone()),
2105            ExtrudeSurface::ExtrudeArc(extrude_arc) => extrude_arc.tag = Some(tag.clone()),
2106            ExtrudeSurface::Chamfer(chamfer) => chamfer.tag = Some(tag.clone()),
2107            ExtrudeSurface::Fillet(fillet) => fillet.tag = Some(tag.clone()),
2108        }
2109    }
2110
2111    pub fn get_tag(&self) -> Option<Node<TagDeclarator>> {
2112        match self {
2113            ExtrudeSurface::ExtrudePlane(ep) => ep.tag.clone(),
2114            ExtrudeSurface::ExtrudeArc(ea) => ea.tag.clone(),
2115            ExtrudeSurface::Fillet(f) => f.tag.clone(),
2116            ExtrudeSurface::Chamfer(c) => c.tag.clone(),
2117        }
2118    }
2119}
2120
2121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, ts_rs::TS)]
2122pub struct SketchVarId(pub usize);
2123
2124impl SketchVarId {
2125    pub const INVALID: Self = Self(usize::MAX);
2126
2127    pub fn to_constraint_id(self, range: SourceRange) -> Result<ezpz::Id, KclError> {
2128        self.0.try_into().map_err(|_| {
2129            KclError::new_type(KclErrorDetails::new(
2130                "Cannot convert to constraint ID since the sketch variable ID is too large".to_owned(),
2131                vec![range],
2132            ))
2133        })
2134    }
2135}
2136
2137#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2138#[ts(export_to = "Geometry.ts")]
2139#[serde(rename_all = "camelCase")]
2140pub struct SketchVar {
2141    pub id: SketchVarId,
2142    pub initial_value: f64,
2143    pub ty: NumericType,
2144    /// Used for solver feedback to source.
2145    pub node_path: Option<NodePath>,
2146    #[serde(skip)]
2147    pub meta: Vec<Metadata>,
2148}
2149
2150impl SketchVar {
2151    pub fn initial_value_to_solver_units(
2152        &self,
2153        exec_state: &mut ExecState,
2154        source_range: SourceRange,
2155        description: &str,
2156    ) -> Result<TyF64, KclError> {
2157        let x_initial_value = KclValue::Number {
2158            value: self.initial_value,
2159            ty: self.ty,
2160            meta: vec![source_range.into()],
2161        };
2162        let normalized_value =
2163            normalize_to_solver_distance_unit(&x_initial_value, source_range, exec_state, description)?;
2164        normalized_value.as_ty_f64().ok_or_else(|| {
2165            let message = format!(
2166                "Expected number after coercion, but found {}",
2167                normalized_value.human_friendly_type()
2168            );
2169            debug_assert!(false, "{}", &message);
2170            KclError::new_internal(KclErrorDetails::new(message, vec![source_range]))
2171        })
2172    }
2173}
2174
2175#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2176#[ts(export_to = "Geometry.ts")]
2177#[serde(tag = "type")]
2178pub enum UnsolvedExpr {
2179    Known(TyF64),
2180    Unknown(SketchVarId),
2181}
2182
2183impl UnsolvedExpr {
2184    pub fn var(&self) -> Option<SketchVarId> {
2185        match self {
2186            UnsolvedExpr::Known(_) => None,
2187            UnsolvedExpr::Unknown(id) => Some(*id),
2188        }
2189    }
2190}
2191
2192pub type UnsolvedPoint2dExpr = [UnsolvedExpr; 2];
2193
2194#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2195#[ts(export_to = "Geometry.ts")]
2196#[serde(rename_all = "camelCase")]
2197pub struct ConstrainablePoint2d {
2198    pub vars: crate::front::Point2d<SketchVarId>,
2199    pub object_id: ObjectId,
2200}
2201
2202#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2203#[ts(export_to = "Geometry.ts")]
2204pub enum ConstrainablePoint2dOrOrigin {
2205    Point(ConstrainablePoint2d),
2206    Origin,
2207}
2208
2209#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2210#[ts(export_to = "Geometry.ts")]
2211#[serde(rename_all = "camelCase")]
2212pub struct ConstrainableLine2d {
2213    pub vars: [crate::front::Point2d<SketchVarId>; 2],
2214    pub object_id: ObjectId,
2215}
2216
2217#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2218#[ts(export_to = "Geometry.ts")]
2219#[serde(rename_all = "camelCase")]
2220pub struct UnsolvedSegment {
2221    /// The engine ID.
2222    pub id: Uuid,
2223    pub object_id: ObjectId,
2224    pub kind: UnsolvedSegmentKind,
2225    #[serde(skip_serializing_if = "Option::is_none")]
2226    pub tag: Option<TagIdentifier>,
2227    #[serde(skip)]
2228    pub node_path: Option<NodePath>,
2229    #[serde(skip)]
2230    pub meta: Vec<Metadata>,
2231}
2232
2233#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2234#[ts(export_to = "Geometry.ts")]
2235#[serde(rename_all = "camelCase")]
2236pub enum UnsolvedSegmentKind {
2237    Point {
2238        position: UnsolvedPoint2dExpr,
2239        ctor: Box<PointCtor>,
2240    },
2241    Line {
2242        start: UnsolvedPoint2dExpr,
2243        end: UnsolvedPoint2dExpr,
2244        ctor: Box<LineCtor>,
2245        start_object_id: ObjectId,
2246        end_object_id: ObjectId,
2247        construction: bool,
2248    },
2249    Arc {
2250        start: UnsolvedPoint2dExpr,
2251        end: UnsolvedPoint2dExpr,
2252        center: UnsolvedPoint2dExpr,
2253        ctor: Box<ArcCtor>,
2254        start_object_id: ObjectId,
2255        end_object_id: ObjectId,
2256        center_object_id: ObjectId,
2257        construction: bool,
2258    },
2259    Circle {
2260        start: UnsolvedPoint2dExpr,
2261        center: UnsolvedPoint2dExpr,
2262        ctor: Box<CircleCtor>,
2263        start_object_id: ObjectId,
2264        center_object_id: ObjectId,
2265        construction: bool,
2266    },
2267    ControlPointSpline {
2268        controls: Vec<UnsolvedPoint2dExpr>,
2269        ctor: Box<ControlPointSplineCtor>,
2270        control_object_ids: Vec<ObjectId>,
2271        control_polygon_edge_object_ids: Vec<ObjectId>,
2272        degree: u32,
2273        construction: bool,
2274    },
2275}
2276
2277impl UnsolvedSegmentKind {
2278    /// What kind of object is this (point, line, arc, etc)
2279    /// Suitable for use in user-facing messages.
2280    pub fn human_friendly_kind_with_article(&self) -> &'static str {
2281        match self {
2282            Self::Point { .. } => "a Point",
2283            Self::Line { .. } => "a Line",
2284            Self::Arc { .. } => "an Arc",
2285            Self::Circle { .. } => "a Circle",
2286            Self::ControlPointSpline { .. } => "a Control Point Spline",
2287        }
2288    }
2289}
2290
2291#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2292#[ts(export_to = "Geometry.ts")]
2293#[serde(rename_all = "camelCase")]
2294pub struct Segment {
2295    /// The engine ID.
2296    pub id: Uuid,
2297    pub object_id: ObjectId,
2298    pub kind: SegmentKind,
2299    pub surface: SketchSurface,
2300    /// The engine ID of the sketch that this is a part of.
2301    pub sketch_id: Uuid,
2302    #[serde(skip)]
2303    #[ts(skip)]
2304    pub sketch: Option<Arc<Sketch>>,
2305    #[serde(skip_serializing_if = "Option::is_none")]
2306    pub tag: Option<TagIdentifier>,
2307    #[serde(skip)]
2308    pub node_path: Option<NodePath>,
2309    #[serde(skip)]
2310    pub meta: Vec<Metadata>,
2311}
2312
2313impl Segment {
2314    pub fn is_construction(&self) -> bool {
2315        match &self.kind {
2316            SegmentKind::Point { .. } => true,
2317            SegmentKind::Line { construction, .. } => *construction,
2318            SegmentKind::Arc { construction, .. } => *construction,
2319            SegmentKind::Circle { construction, .. } => *construction,
2320            SegmentKind::ControlPointSpline { construction, .. } => *construction,
2321        }
2322    }
2323}
2324
2325#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2326#[ts(export_to = "Geometry.ts")]
2327#[serde(rename_all = "camelCase")]
2328pub enum SegmentKind {
2329    Point {
2330        position: [TyF64; 2],
2331        ctor: Box<PointCtor>,
2332        #[serde(skip_serializing_if = "Option::is_none")]
2333        freedom: Option<Freedom>,
2334    },
2335    Line {
2336        start: [TyF64; 2],
2337        end: [TyF64; 2],
2338        ctor: Box<LineCtor>,
2339        start_object_id: ObjectId,
2340        end_object_id: ObjectId,
2341        #[serde(skip_serializing_if = "Option::is_none")]
2342        start_freedom: Option<Freedom>,
2343        #[serde(skip_serializing_if = "Option::is_none")]
2344        end_freedom: Option<Freedom>,
2345        construction: bool,
2346    },
2347    Arc {
2348        start: [TyF64; 2],
2349        end: [TyF64; 2],
2350        center: [TyF64; 2],
2351        ctor: Box<ArcCtor>,
2352        start_object_id: ObjectId,
2353        end_object_id: ObjectId,
2354        center_object_id: ObjectId,
2355        #[serde(skip_serializing_if = "Option::is_none")]
2356        start_freedom: Option<Freedom>,
2357        #[serde(skip_serializing_if = "Option::is_none")]
2358        end_freedom: Option<Freedom>,
2359        #[serde(skip_serializing_if = "Option::is_none")]
2360        center_freedom: Option<Freedom>,
2361        construction: bool,
2362    },
2363    Circle {
2364        start: [TyF64; 2],
2365        center: [TyF64; 2],
2366        ctor: Box<CircleCtor>,
2367        start_object_id: ObjectId,
2368        center_object_id: ObjectId,
2369        #[serde(skip_serializing_if = "Option::is_none")]
2370        start_freedom: Option<Freedom>,
2371        #[serde(skip_serializing_if = "Option::is_none")]
2372        center_freedom: Option<Freedom>,
2373        construction: bool,
2374    },
2375    ControlPointSpline {
2376        controls: Vec<[TyF64; 2]>,
2377        ctor: Box<ControlPointSplineCtor>,
2378        control_object_ids: Vec<ObjectId>,
2379        control_polygon_edge_object_ids: Vec<ObjectId>,
2380        #[serde(skip_serializing_if = "Vec::is_empty")]
2381        control_freedoms: Vec<Option<Freedom>>,
2382        degree: u32,
2383        construction: bool,
2384    },
2385}
2386
2387#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2388#[ts(export_to = "Geometry.ts")]
2389#[serde(rename_all = "camelCase")]
2390pub struct AbstractSegment {
2391    pub repr: SegmentRepr,
2392    #[serde(skip)]
2393    pub meta: Vec<Metadata>,
2394}
2395
2396#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2397pub enum SegmentRepr {
2398    Unsolved { segment: Box<UnsolvedSegment> },
2399    Solved { segment: Box<Segment> },
2400}
2401
2402#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2403#[ts(export_to = "Geometry.ts")]
2404#[serde(rename_all = "camelCase")]
2405pub struct SketchConstraint {
2406    pub kind: SketchConstraintKind,
2407    #[serde(skip)]
2408    pub meta: Vec<Metadata>,
2409}
2410
2411#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2412#[ts(export_to = "Geometry.ts")]
2413#[serde(rename_all = "camelCase")]
2414pub enum SketchConstraintKind {
2415    Angle {
2416        line0: ConstrainableLine2d,
2417        line1: ConstrainableLine2d,
2418    },
2419    Distance {
2420        points: [ConstrainablePoint2dOrOrigin; 2],
2421        #[serde(rename = "labelPosition")]
2422        #[serde(skip_serializing_if = "Option::is_none")]
2423        #[ts(rename = "labelPosition")]
2424        #[ts(optional)]
2425        label_position: Option<ApiPoint2d<Number>>,
2426    },
2427    PointLineDistance {
2428        point: ConstrainablePoint2dOrOrigin,
2429        line: ConstrainableLine2d,
2430        input_object_ids: [Option<ObjectId>; 2],
2431        #[serde(rename = "labelPosition")]
2432        #[serde(skip_serializing_if = "Option::is_none")]
2433        #[ts(rename = "labelPosition")]
2434        #[ts(optional)]
2435        label_position: Option<ApiPoint2d<Number>>,
2436    },
2437    LineLineDistance {
2438        line0: ConstrainableLine2d,
2439        line1: ConstrainableLine2d,
2440        input_object_ids: [ObjectId; 2],
2441        #[serde(rename = "labelPosition")]
2442        #[serde(skip_serializing_if = "Option::is_none")]
2443        #[ts(rename = "labelPosition")]
2444        #[ts(optional)]
2445        label_position: Option<ApiPoint2d<Number>>,
2446    },
2447    PointCircularDistance {
2448        point: ConstrainablePoint2dOrOrigin,
2449        center: ConstrainablePoint2d,
2450        start: ConstrainablePoint2d,
2451        end: Option<ConstrainablePoint2d>,
2452        input_object_ids: [Option<ObjectId>; 2],
2453        #[serde(rename = "labelPosition")]
2454        #[serde(skip_serializing_if = "Option::is_none")]
2455        #[ts(rename = "labelPosition")]
2456        #[ts(optional)]
2457        label_position: Option<ApiPoint2d<Number>>,
2458    },
2459    LineCircularDistance {
2460        line: ConstrainableLine2d,
2461        center: ConstrainablePoint2d,
2462        start: ConstrainablePoint2d,
2463        end: Option<ConstrainablePoint2d>,
2464        input_object_ids: [ObjectId; 2],
2465        #[serde(rename = "labelPosition")]
2466        #[serde(skip_serializing_if = "Option::is_none")]
2467        #[ts(rename = "labelPosition")]
2468        #[ts(optional)]
2469        label_position: Option<ApiPoint2d<Number>>,
2470    },
2471    CircularCircularDistance {
2472        center0: ConstrainablePoint2d,
2473        start0: ConstrainablePoint2d,
2474        end0: Option<ConstrainablePoint2d>,
2475        center1: ConstrainablePoint2d,
2476        start1: ConstrainablePoint2d,
2477        end1: Option<ConstrainablePoint2d>,
2478        input_object_ids: [ObjectId; 2],
2479        #[serde(rename = "labelPosition")]
2480        #[serde(skip_serializing_if = "Option::is_none")]
2481        #[ts(rename = "labelPosition")]
2482        #[ts(optional)]
2483        label_position: Option<ApiPoint2d<Number>>,
2484    },
2485    Radius {
2486        points: [ConstrainablePoint2d; 2],
2487        #[serde(rename = "labelPosition")]
2488        #[serde(skip_serializing_if = "Option::is_none")]
2489        #[ts(rename = "labelPosition")]
2490        #[ts(optional)]
2491        label_position: Option<ApiPoint2d<Number>>,
2492    },
2493    Diameter {
2494        points: [ConstrainablePoint2d; 2],
2495        #[serde(rename = "labelPosition")]
2496        #[serde(skip_serializing_if = "Option::is_none")]
2497        #[ts(rename = "labelPosition")]
2498        #[ts(optional)]
2499        label_position: Option<ApiPoint2d<Number>>,
2500    },
2501    HorizontalDistance {
2502        points: [ConstrainablePoint2dOrOrigin; 2],
2503        #[serde(rename = "labelPosition")]
2504        #[serde(skip_serializing_if = "Option::is_none")]
2505        #[ts(rename = "labelPosition")]
2506        #[ts(optional)]
2507        label_position: Option<ApiPoint2d<Number>>,
2508    },
2509    VerticalDistance {
2510        points: [ConstrainablePoint2dOrOrigin; 2],
2511        #[serde(rename = "labelPosition")]
2512        #[serde(skip_serializing_if = "Option::is_none")]
2513        #[ts(rename = "labelPosition")]
2514        #[ts(optional)]
2515        label_position: Option<ApiPoint2d<Number>>,
2516    },
2517}
2518
2519impl SketchConstraintKind {
2520    pub fn name(&self) -> &'static str {
2521        match self {
2522            SketchConstraintKind::Angle { .. } => "angle",
2523            SketchConstraintKind::Distance { .. } => "distance",
2524            SketchConstraintKind::PointLineDistance { .. } => "distance",
2525            SketchConstraintKind::LineLineDistance { .. } => "distance",
2526            SketchConstraintKind::PointCircularDistance { .. } => "distance",
2527            SketchConstraintKind::LineCircularDistance { .. } => "distance",
2528            SketchConstraintKind::CircularCircularDistance { .. } => "distance",
2529            SketchConstraintKind::Radius { .. } => "radius",
2530            SketchConstraintKind::Diameter { .. } => "diameter",
2531            SketchConstraintKind::HorizontalDistance { .. } => "horizontalDistance",
2532            SketchConstraintKind::VerticalDistance { .. } => "verticalDistance",
2533        }
2534    }
2535}