1use anyhow::Result;
4use indexmap::IndexMap;
5use kcl_derive_docs::stdlib;
6use kcmc::shared::Point2d as KPoint2d; use kcmc::{each_cmd as mcmd, length_unit::LengthUnit, shared::Angle, ModelingCmd};
8use kittycad_modeling_cmds as kcmc;
9use kittycad_modeling_cmds::shared::PathSegment;
10use parse_display::{Display, FromStr};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use crate::{
15 errors::{KclError, KclErrorDetails},
16 execution::{
17 Artifact, ArtifactId, BasePath, CodeRef, ExecState, Face, GeoMeta, KclValue, Path, Plane, Point2d, Point3d,
18 Sketch, SketchSet, SketchSurface, Solid, StartSketchOnFace, StartSketchOnPlane, TagEngineInfo, TagIdentifier,
19 },
20 parsing::ast::types::TagNode,
21 std::{
22 args::{Args, TyF64},
23 utils::{
24 arc_angles, arc_center_and_end, calculate_circle_center, get_tangential_arc_to_info, get_x_component,
25 get_y_component, intersection_with_parallel_line, TangentialArcInfoInput,
26 },
27 },
28};
29
30#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
32#[ts(export)]
33#[serde(rename_all = "snake_case", untagged)]
34pub enum FaceTag {
35 StartOrEnd(StartOrEnd),
36 Tag(Box<TagIdentifier>),
38}
39
40impl std::fmt::Display for FaceTag {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 FaceTag::Tag(t) => write!(f, "{}", t),
44 FaceTag::StartOrEnd(StartOrEnd::Start) => write!(f, "start"),
45 FaceTag::StartOrEnd(StartOrEnd::End) => write!(f, "end"),
46 }
47 }
48}
49
50impl FaceTag {
51 pub async fn get_face_id(
53 &self,
54 solid: &Solid,
55 exec_state: &mut ExecState,
56 args: &Args,
57 must_be_planar: bool,
58 ) -> Result<uuid::Uuid, KclError> {
59 match self {
60 FaceTag::Tag(ref t) => args.get_adjacent_face_to_tag(exec_state, t, must_be_planar).await,
61 FaceTag::StartOrEnd(StartOrEnd::Start) => solid.start_cap_id.ok_or_else(|| {
62 KclError::Type(KclErrorDetails {
63 message: "Expected a start face".to_string(),
64 source_ranges: vec![args.source_range],
65 })
66 }),
67 FaceTag::StartOrEnd(StartOrEnd::End) => solid.end_cap_id.ok_or_else(|| {
68 KclError::Type(KclErrorDetails {
69 message: "Expected an end face".to_string(),
70 source_ranges: vec![args.source_range],
71 })
72 }),
73 }
74 }
75}
76
77#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, FromStr, Display)]
78#[ts(export)]
79#[serde(rename_all = "snake_case")]
80#[display(style = "snake_case")]
81pub enum StartOrEnd {
82 #[serde(rename = "start", alias = "START")]
86 Start,
87 #[serde(rename = "end", alias = "END")]
91 End,
92}
93
94pub const NEW_TAG_KW: &str = "tag";
95
96pub async fn line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
98 let sketch = args.get_unlabeled_kw_arg("sketch")?;
100 let end = args.get_kw_arg_opt("end")?;
101 let end_absolute = args.get_kw_arg_opt("endAbsolute")?;
102 let tag = args.get_kw_arg_opt(NEW_TAG_KW)?;
103
104 let new_sketch = inner_line(sketch, end_absolute, end, tag, exec_state, args).await?;
105 Ok(KclValue::Sketch {
106 value: Box::new(new_sketch),
107 })
108}
109
110#[stdlib {
135 name = "line",
136 keywords = true,
137 unlabeled_first = true,
138 args = {
139 sketch = { docs = "Which sketch should this path be added to?"},
140 end_absolute = { docs = "Which absolute point should this line go to? Incompatible with `end`."},
141 end = { docs = "How far away (along the X and Y axes) should this line go? Incompatible with `endAbsolute`.", include_in_snippet = true},
142 tag = { docs = "Create a new tag which refers to this line"},
143 }
144}]
145async fn inner_line(
146 sketch: Sketch,
147 end_absolute: Option<[f64; 2]>,
148 end: Option<[f64; 2]>,
149 tag: Option<TagNode>,
150 exec_state: &mut ExecState,
151 args: Args,
152) -> Result<Sketch, KclError> {
153 straight_line(
154 StraightLineParams {
155 sketch,
156 end_absolute,
157 end,
158 tag,
159 },
160 exec_state,
161 args,
162 )
163 .await
164}
165
166struct StraightLineParams {
167 sketch: Sketch,
168 end_absolute: Option<[f64; 2]>,
169 end: Option<[f64; 2]>,
170 tag: Option<TagNode>,
171}
172
173impl StraightLineParams {
174 fn relative(p: [f64; 2], sketch: Sketch, tag: Option<TagNode>) -> Self {
175 Self {
176 sketch,
177 tag,
178 end: Some(p),
179 end_absolute: None,
180 }
181 }
182 fn absolute(p: [f64; 2], sketch: Sketch, tag: Option<TagNode>) -> Self {
183 Self {
184 sketch,
185 tag,
186 end: None,
187 end_absolute: Some(p),
188 }
189 }
190}
191
192async fn straight_line(
193 StraightLineParams {
194 sketch,
195 end,
196 end_absolute,
197 tag,
198 }: StraightLineParams,
199 exec_state: &mut ExecState,
200 args: Args,
201) -> Result<Sketch, KclError> {
202 let from = sketch.current_pen_position()?;
203 let (point, is_absolute) = match (end_absolute, end) {
204 (Some(_), Some(_)) => {
205 return Err(KclError::Semantic(KclErrorDetails {
206 source_ranges: vec![args.source_range],
207 message: "You cannot give both `end` and `endAbsolute` params, you have to choose one or the other"
208 .to_owned(),
209 }));
210 }
211 (Some(end_absolute), None) => (end_absolute, true),
212 (None, Some(end)) => (end, false),
213 (None, None) => {
214 return Err(KclError::Semantic(KclErrorDetails {
215 source_ranges: vec![args.source_range],
216 message: "You must supply either `end` or `endAbsolute` arguments".to_owned(),
217 }));
218 }
219 };
220
221 let id = exec_state.next_uuid();
222 args.batch_modeling_cmd(
223 id,
224 ModelingCmd::from(mcmd::ExtendPath {
225 path: sketch.id.into(),
226 segment: PathSegment::Line {
227 end: KPoint2d::from(point).with_z(0.0).map(LengthUnit),
228 relative: !is_absolute,
229 },
230 }),
231 )
232 .await?;
233 let end = if is_absolute {
234 point
235 } else {
236 let from = sketch.current_pen_position()?;
237 [from.x + point[0], from.y + point[1]]
238 };
239
240 let current_path = Path::ToPoint {
241 base: BasePath {
242 from: from.into(),
243 to: end,
244 tag: tag.clone(),
245 units: sketch.units,
246 geo_meta: GeoMeta {
247 id,
248 metadata: args.source_range.into(),
249 },
250 },
251 };
252
253 let mut new_sketch = sketch.clone();
254 if let Some(tag) = &tag {
255 new_sketch.add_tag(tag, ¤t_path);
256 }
257
258 new_sketch.paths.push(current_path);
259
260 Ok(new_sketch)
261}
262
263pub async fn x_line_to(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
265 let (to, sketch, tag): (f64, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
266
267 let new_sketch = inner_x_line_to(to, sketch, tag, exec_state, args).await?;
268 Ok(KclValue::Sketch {
269 value: Box::new(new_sketch),
270 })
271}
272
273#[stdlib {
297 name = "xLineTo",
298}]
299async fn inner_x_line_to(
300 to: f64,
301 sketch: Sketch,
302 tag: Option<TagNode>,
303 exec_state: &mut ExecState,
304 args: Args,
305) -> Result<Sketch, KclError> {
306 let from = sketch.current_pen_position()?;
307
308 let new_sketch = straight_line(
309 StraightLineParams::absolute([to, from.y], sketch, tag),
310 exec_state,
311 args,
312 )
313 .await?;
314
315 Ok(new_sketch)
316}
317
318pub async fn y_line_to(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
320 let (to, sketch, tag): (f64, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
321
322 let new_sketch = inner_y_line_to(to, sketch, tag, exec_state, args).await?;
323 Ok(KclValue::Sketch {
324 value: Box::new(new_sketch),
325 })
326}
327
328#[stdlib {
345 name = "yLineTo",
346}]
347async fn inner_y_line_to(
348 to: f64,
349 sketch: Sketch,
350 tag: Option<TagNode>,
351 exec_state: &mut ExecState,
352 args: Args,
353) -> Result<Sketch, KclError> {
354 let from = sketch.current_pen_position()?;
355
356 let new_sketch = straight_line(
357 StraightLineParams::absolute([from.x, to], sketch, tag),
358 exec_state,
359 args,
360 )
361 .await?;
362 Ok(new_sketch)
363}
364
365pub async fn x_line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
367 let (length, sketch, tag): (f64, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
368
369 let new_sketch = inner_x_line(length, sketch, tag, exec_state, args).await?;
370 Ok(KclValue::Sketch {
371 value: Box::new(new_sketch),
372 })
373}
374
375#[stdlib {
398 name = "xLine",
399}]
400async fn inner_x_line(
401 length: f64,
402 sketch: Sketch,
403 tag: Option<TagNode>,
404 exec_state: &mut ExecState,
405 args: Args,
406) -> Result<Sketch, KclError> {
407 straight_line(
408 StraightLineParams::relative([length, 0.0], sketch, tag),
409 exec_state,
410 args,
411 )
412 .await
413}
414
415pub async fn y_line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
417 let (length, sketch, tag): (f64, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
418
419 let new_sketch = inner_y_line(length, sketch, tag, exec_state, args).await?;
420 Ok(KclValue::Sketch {
421 value: Box::new(new_sketch),
422 })
423}
424
425#[stdlib {
443 name = "yLine",
444}]
445async fn inner_y_line(
446 length: f64,
447 sketch: Sketch,
448 tag: Option<TagNode>,
449 exec_state: &mut ExecState,
450 args: Args,
451) -> Result<Sketch, KclError> {
452 straight_line(
453 StraightLineParams::relative([0.0, length], sketch, tag),
454 exec_state,
455 args,
456 )
457 .await
458}
459
460#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
462#[ts(export)]
463#[serde(rename_all = "camelCase", untagged)]
464pub enum AngledLineData {
465 AngleAndLengthNamed {
467 angle: f64,
469 length: f64,
471 },
472 AngleAndLengthPair([f64; 2]),
474}
475
476pub async fn angled_line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
478 let (data, sketch, tag): (AngledLineData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
479
480 let new_sketch = inner_angled_line(data, sketch, tag, exec_state, args).await?;
481 Ok(KclValue::Sketch {
482 value: Box::new(new_sketch),
483 })
484}
485
486#[stdlib {
504 name = "angledLine",
505}]
506async fn inner_angled_line(
507 data: AngledLineData,
508 sketch: Sketch,
509 tag: Option<TagNode>,
510 exec_state: &mut ExecState,
511 args: Args,
512) -> Result<Sketch, KclError> {
513 let from = sketch.current_pen_position()?;
514 let (angle, length) = match data {
515 AngledLineData::AngleAndLengthNamed { angle, length } => (angle, length),
516 AngledLineData::AngleAndLengthPair(pair) => (pair[0], pair[1]),
517 };
518
519 let delta: [f64; 2] = [
521 length * f64::cos(angle.to_radians()),
522 length * f64::sin(angle.to_radians()),
523 ];
524 let relative = true;
525
526 let to: [f64; 2] = [from.x + delta[0], from.y + delta[1]];
527
528 let id = exec_state.next_uuid();
529
530 args.batch_modeling_cmd(
531 id,
532 ModelingCmd::from(mcmd::ExtendPath {
533 path: sketch.id.into(),
534 segment: PathSegment::Line {
535 end: KPoint2d::from(delta).with_z(0.0).map(LengthUnit),
536 relative,
537 },
538 }),
539 )
540 .await?;
541
542 let current_path = Path::ToPoint {
543 base: BasePath {
544 from: from.into(),
545 to,
546 tag: tag.clone(),
547 units: sketch.units,
548 geo_meta: GeoMeta {
549 id,
550 metadata: args.source_range.into(),
551 },
552 },
553 };
554
555 let mut new_sketch = sketch.clone();
556 if let Some(tag) = &tag {
557 new_sketch.add_tag(tag, ¤t_path);
558 }
559
560 new_sketch.paths.push(current_path);
561 Ok(new_sketch)
562}
563
564pub async fn angled_line_of_x_length(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
566 let (data, sketch, tag): (AngledLineData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
567
568 let new_sketch = inner_angled_line_of_x_length(data, sketch, tag, exec_state, args).await?;
569 Ok(KclValue::Sketch {
570 value: Box::new(new_sketch),
571 })
572}
573
574#[stdlib {
588 name = "angledLineOfXLength",
589}]
590async fn inner_angled_line_of_x_length(
591 data: AngledLineData,
592 sketch: Sketch,
593 tag: Option<TagNode>,
594 exec_state: &mut ExecState,
595 args: Args,
596) -> Result<Sketch, KclError> {
597 let (angle, length) = match data {
598 AngledLineData::AngleAndLengthNamed { angle, length } => (angle, length),
599 AngledLineData::AngleAndLengthPair(pair) => (pair[0], pair[1]),
600 };
601
602 if angle.abs() == 270.0 {
603 return Err(KclError::Type(KclErrorDetails {
604 message: "Cannot have an x constrained angle of 270 degrees".to_string(),
605 source_ranges: vec![args.source_range],
606 }));
607 }
608
609 if angle.abs() == 90.0 {
610 return Err(KclError::Type(KclErrorDetails {
611 message: "Cannot have an x constrained angle of 90 degrees".to_string(),
612 source_ranges: vec![args.source_range],
613 }));
614 }
615
616 let to = get_y_component(Angle::from_degrees(angle), length);
617
618 let new_sketch = straight_line(StraightLineParams::relative(to.into(), sketch, tag), exec_state, args).await?;
619
620 Ok(new_sketch)
621}
622
623#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
625#[ts(export)]
626#[serde(rename_all = "camelCase")]
627pub struct AngledLineToData {
628 pub angle: f64,
630 pub to: f64,
632}
633
634pub async fn angled_line_to_x(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
636 let (data, sketch, tag): (AngledLineToData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
637
638 let new_sketch = inner_angled_line_to_x(data, sketch, tag, exec_state, args).await?;
639 Ok(KclValue::Sketch {
640 value: Box::new(new_sketch),
641 })
642}
643
644#[stdlib {
659 name = "angledLineToX",
660}]
661async fn inner_angled_line_to_x(
662 data: AngledLineToData,
663 sketch: Sketch,
664 tag: Option<TagNode>,
665 exec_state: &mut ExecState,
666 args: Args,
667) -> Result<Sketch, KclError> {
668 let from = sketch.current_pen_position()?;
669 let AngledLineToData { angle, to: x_to } = data;
670
671 if angle.abs() == 270.0 {
672 return Err(KclError::Type(KclErrorDetails {
673 message: "Cannot have an x constrained angle of 270 degrees".to_string(),
674 source_ranges: vec![args.source_range],
675 }));
676 }
677
678 if angle.abs() == 90.0 {
679 return Err(KclError::Type(KclErrorDetails {
680 message: "Cannot have an x constrained angle of 90 degrees".to_string(),
681 source_ranges: vec![args.source_range],
682 }));
683 }
684
685 let x_component = x_to - from.x;
686 let y_component = x_component * f64::tan(angle.to_radians());
687 let y_to = from.y + y_component;
688
689 let new_sketch = straight_line(
690 StraightLineParams::absolute([x_to, y_to], sketch, tag),
691 exec_state,
692 args,
693 )
694 .await?;
695 Ok(new_sketch)
696}
697
698pub async fn angled_line_of_y_length(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
700 let (data, sketch, tag): (AngledLineData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
701
702 let new_sketch = inner_angled_line_of_y_length(data, sketch, tag, exec_state, args).await?;
703
704 Ok(KclValue::Sketch {
705 value: Box::new(new_sketch),
706 })
707}
708
709#[stdlib {
725 name = "angledLineOfYLength",
726}]
727async fn inner_angled_line_of_y_length(
728 data: AngledLineData,
729 sketch: Sketch,
730 tag: Option<TagNode>,
731 exec_state: &mut ExecState,
732 args: Args,
733) -> Result<Sketch, KclError> {
734 let (angle, length) = match data {
735 AngledLineData::AngleAndLengthNamed { angle, length } => (angle, length),
736 AngledLineData::AngleAndLengthPair(pair) => (pair[0], pair[1]),
737 };
738
739 if angle.abs() == 0.0 {
740 return Err(KclError::Type(KclErrorDetails {
741 message: "Cannot have a y constrained angle of 0 degrees".to_string(),
742 source_ranges: vec![args.source_range],
743 }));
744 }
745
746 if angle.abs() == 180.0 {
747 return Err(KclError::Type(KclErrorDetails {
748 message: "Cannot have a y constrained angle of 180 degrees".to_string(),
749 source_ranges: vec![args.source_range],
750 }));
751 }
752
753 let to = get_x_component(Angle::from_degrees(angle), length);
754
755 let new_sketch = straight_line(StraightLineParams::relative(to.into(), sketch, tag), exec_state, args).await?;
756
757 Ok(new_sketch)
758}
759
760pub async fn angled_line_to_y(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
762 let (data, sketch, tag): (AngledLineToData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
763
764 let new_sketch = inner_angled_line_to_y(data, sketch, tag, exec_state, args).await?;
765 Ok(KclValue::Sketch {
766 value: Box::new(new_sketch),
767 })
768}
769
770#[stdlib {
785 name = "angledLineToY",
786}]
787async fn inner_angled_line_to_y(
788 data: AngledLineToData,
789 sketch: Sketch,
790 tag: Option<TagNode>,
791 exec_state: &mut ExecState,
792 args: Args,
793) -> Result<Sketch, KclError> {
794 let from = sketch.current_pen_position()?;
795 let AngledLineToData { angle, to: y_to } = data;
796
797 if angle.abs() == 0.0 {
798 return Err(KclError::Type(KclErrorDetails {
799 message: "Cannot have a y constrained angle of 0 degrees".to_string(),
800 source_ranges: vec![args.source_range],
801 }));
802 }
803
804 if angle.abs() == 180.0 {
805 return Err(KclError::Type(KclErrorDetails {
806 message: "Cannot have a y constrained angle of 180 degrees".to_string(),
807 source_ranges: vec![args.source_range],
808 }));
809 }
810
811 let y_component = y_to - from.y;
812 let x_component = y_component / f64::tan(angle.to_radians());
813 let x_to = from.x + x_component;
814
815 let new_sketch = straight_line(
816 StraightLineParams::absolute([x_to, y_to], sketch, tag),
817 exec_state,
818 args,
819 )
820 .await?;
821 Ok(new_sketch)
822}
823
824#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
826#[ts(export)]
827#[serde(rename_all = "camelCase")]
828pub struct AngledLineThatIntersectsData {
830 pub angle: f64,
832 pub intersect_tag: TagIdentifier,
834 pub offset: Option<f64>,
836}
837
838pub async fn angled_line_that_intersects(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
840 let (data, sketch, tag): (AngledLineThatIntersectsData, Sketch, Option<TagNode>) =
841 args.get_data_and_sketch_and_tag()?;
842 let new_sketch = inner_angled_line_that_intersects(data, sketch, tag, exec_state, args).await?;
843 Ok(KclValue::Sketch {
844 value: Box::new(new_sketch),
845 })
846}
847
848#[stdlib {
868 name = "angledLineThatIntersects",
869}]
870async fn inner_angled_line_that_intersects(
871 data: AngledLineThatIntersectsData,
872 sketch: Sketch,
873 tag: Option<TagNode>,
874 exec_state: &mut ExecState,
875 args: Args,
876) -> Result<Sketch, KclError> {
877 let intersect_path = args.get_tag_engine_info(exec_state, &data.intersect_tag)?;
878 let path = intersect_path.path.clone().ok_or_else(|| {
879 KclError::Type(KclErrorDetails {
880 message: format!("Expected an intersect path with a path, found `{:?}`", intersect_path),
881 source_ranges: vec![args.source_range],
882 })
883 })?;
884
885 let from = sketch.current_pen_position()?;
886 let to = intersection_with_parallel_line(
887 &[path.get_from().into(), path.get_to().into()],
888 data.offset.unwrap_or_default(),
889 data.angle,
890 from,
891 );
892
893 let new_sketch = straight_line(StraightLineParams::absolute(to.into(), sketch, tag), exec_state, args).await?;
894 Ok(new_sketch)
895}
896
897#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
900#[ts(export)]
901#[serde(rename_all = "camelCase", untagged)]
902#[allow(clippy::large_enum_variant)]
903pub enum SketchData {
904 PlaneOrientation(PlaneData),
905 Plane(Box<Plane>),
906 Solid(Box<Solid>),
907}
908
909#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
911#[ts(export)]
912#[serde(rename_all = "camelCase")]
913#[allow(clippy::large_enum_variant)]
914pub enum PlaneData {
915 #[serde(rename = "XY", alias = "xy")]
917 XY,
918 #[serde(rename = "-XY", alias = "-xy")]
920 NegXY,
921 #[serde(rename = "XZ", alias = "xz")]
923 XZ,
924 #[serde(rename = "-XZ", alias = "-xz")]
926 NegXZ,
927 #[serde(rename = "YZ", alias = "yz")]
929 YZ,
930 #[serde(rename = "-YZ", alias = "-yz")]
932 NegYZ,
933 Plane {
935 origin: Point3d,
937 #[serde(rename = "xAxis")]
939 x_axis: Point3d,
940 #[serde(rename = "yAxis")]
942 y_axis: Point3d,
943 #[serde(rename = "zAxis")]
945 z_axis: Point3d,
946 },
947}
948
949pub async fn start_sketch_on(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
951 let (data, tag): (SketchData, Option<FaceTag>) = args.get_data_and_optional_tag()?;
952
953 match inner_start_sketch_on(data, tag, exec_state, &args).await? {
954 SketchSurface::Plane(value) => Ok(KclValue::Plane { value }),
955 SketchSurface::Face(value) => Ok(KclValue::Face { value }),
956 }
957}
958
959#[stdlib {
1079 name = "startSketchOn",
1080 feature_tree_operation = true,
1081}]
1082async fn inner_start_sketch_on(
1083 data: SketchData,
1084 tag: Option<FaceTag>,
1085 exec_state: &mut ExecState,
1086 args: &Args,
1087) -> Result<SketchSurface, KclError> {
1088 match data {
1089 SketchData::PlaneOrientation(plane_data) => {
1090 let plane = make_sketch_plane_from_orientation(plane_data, exec_state, args).await?;
1091 Ok(SketchSurface::Plane(plane))
1092 }
1093 SketchData::Plane(plane) => {
1094 if plane.value == crate::exec::PlaneType::Uninit {
1095 let plane = make_sketch_plane_from_orientation(plane.into_plane_data(), exec_state, args).await?;
1096 Ok(SketchSurface::Plane(plane))
1097 } else {
1098 let id = exec_state.next_uuid();
1100 exec_state.add_artifact(Artifact::StartSketchOnPlane(StartSketchOnPlane {
1101 id: ArtifactId::from(id),
1102 plane_id: plane.artifact_id,
1103 code_ref: CodeRef::placeholder(args.source_range),
1104 }));
1105
1106 Ok(SketchSurface::Plane(plane))
1107 }
1108 }
1109 SketchData::Solid(solid) => {
1110 let Some(tag) = tag else {
1111 return Err(KclError::Type(KclErrorDetails {
1112 message: "Expected a tag for the face to sketch on".to_string(),
1113 source_ranges: vec![args.source_range],
1114 }));
1115 };
1116 let face = start_sketch_on_face(solid, tag, exec_state, args).await?;
1117
1118 let id = exec_state.next_uuid();
1120 exec_state.add_artifact(Artifact::StartSketchOnFace(StartSketchOnFace {
1121 id: ArtifactId::from(id),
1122 face_id: face.artifact_id,
1123 code_ref: CodeRef::placeholder(args.source_range),
1124 }));
1125
1126 Ok(SketchSurface::Face(face))
1127 }
1128 }
1129}
1130
1131async fn start_sketch_on_face(
1132 solid: Box<Solid>,
1133 tag: FaceTag,
1134 exec_state: &mut ExecState,
1135 args: &Args,
1136) -> Result<Box<Face>, KclError> {
1137 let extrude_plane_id = tag.get_face_id(&solid, exec_state, args, true).await?;
1138
1139 Ok(Box::new(Face {
1140 id: extrude_plane_id,
1141 artifact_id: extrude_plane_id.into(),
1142 value: tag.to_string(),
1143 x_axis: solid.sketch.on.x_axis(),
1145 y_axis: solid.sketch.on.y_axis(),
1146 z_axis: solid.sketch.on.z_axis(),
1147 units: solid.units,
1148 solid,
1149 meta: vec![args.source_range.into()],
1150 }))
1151}
1152
1153async fn make_sketch_plane_from_orientation(
1154 data: PlaneData,
1155 exec_state: &mut ExecState,
1156 args: &Args,
1157) -> Result<Box<Plane>, KclError> {
1158 let plane = Plane::from_plane_data(data.clone(), exec_state);
1159
1160 let clobber = false;
1162 let size = LengthUnit(60.0);
1163 let hide = Some(true);
1164 match data {
1165 PlaneData::XY | PlaneData::NegXY | PlaneData::XZ | PlaneData::NegXZ | PlaneData::YZ | PlaneData::NegYZ => {
1166 let x_axis = match data {
1167 PlaneData::NegXY => Point3d::new(-1.0, 0.0, 0.0),
1168 PlaneData::NegXZ => Point3d::new(-1.0, 0.0, 0.0),
1169 PlaneData::NegYZ => Point3d::new(0.0, -1.0, 0.0),
1170 _ => plane.x_axis,
1171 };
1172 args.batch_modeling_cmd(
1173 plane.id,
1174 ModelingCmd::from(mcmd::MakePlane {
1175 clobber,
1176 origin: plane.origin.into(),
1177 size,
1178 x_axis: x_axis.into(),
1179 y_axis: plane.y_axis.into(),
1180 hide,
1181 }),
1182 )
1183 .await?;
1184 }
1185 PlaneData::Plane {
1186 origin,
1187 x_axis,
1188 y_axis,
1189 z_axis: _,
1190 } => {
1191 args.batch_modeling_cmd(
1192 plane.id,
1193 ModelingCmd::from(mcmd::MakePlane {
1194 clobber,
1195 origin: origin.into(),
1196 size,
1197 x_axis: x_axis.into(),
1198 y_axis: y_axis.into(),
1199 hide,
1200 }),
1201 )
1202 .await?;
1203 }
1204 }
1205
1206 Ok(Box::new(plane))
1207}
1208
1209pub async fn start_profile_at(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1211 let (start, sketch_surface, tag): ([f64; 2], SketchSurface, Option<TagNode>) =
1212 args.get_data_and_sketch_surface()?;
1213
1214 let sketch = inner_start_profile_at(start, sketch_surface, tag, exec_state, args).await?;
1215 Ok(KclValue::Sketch {
1216 value: Box::new(sketch),
1217 })
1218}
1219
1220#[stdlib {
1255 name = "startProfileAt",
1256}]
1257pub(crate) async fn inner_start_profile_at(
1258 to: [f64; 2],
1259 sketch_surface: SketchSurface,
1260 tag: Option<TagNode>,
1261 exec_state: &mut ExecState,
1262 args: Args,
1263) -> Result<Sketch, KclError> {
1264 match &sketch_surface {
1265 SketchSurface::Face(face) => {
1266 args.flush_batch_for_solid_set(exec_state, face.solid.clone().into())
1269 .await?;
1270 }
1271 SketchSurface::Plane(plane) if !plane.is_standard() => {
1272 args.batch_end_cmd(
1275 exec_state.next_uuid(),
1276 ModelingCmd::from(mcmd::ObjectVisible {
1277 object_id: plane.id,
1278 hidden: true,
1279 }),
1280 )
1281 .await?;
1282 }
1283 _ => {}
1284 }
1285
1286 let id = exec_state.next_uuid();
1289 args.batch_modeling_cmd(
1290 id,
1291 ModelingCmd::from(mcmd::EnableSketchMode {
1292 animated: false,
1293 ortho: false,
1294 entity_id: sketch_surface.id(),
1295 adjust_camera: false,
1296 planar_normal: if let SketchSurface::Plane(plane) = &sketch_surface {
1297 Some(plane.z_axis.into())
1299 } else {
1300 None
1301 },
1302 }),
1303 )
1304 .await?;
1305
1306 let id = exec_state.next_uuid();
1307 let path_id = exec_state.next_uuid();
1308
1309 args.batch_modeling_cmd(path_id, ModelingCmd::from(mcmd::StartPath::default()))
1310 .await?;
1311 args.batch_modeling_cmd(
1312 id,
1313 ModelingCmd::from(mcmd::MovePathPen {
1314 path: path_id.into(),
1315 to: KPoint2d::from(to).with_z(0.0).map(LengthUnit),
1316 }),
1317 )
1318 .await?;
1319
1320 let current_path = BasePath {
1321 from: to,
1322 to,
1323 tag: tag.clone(),
1324 units: sketch_surface.units(),
1325 geo_meta: GeoMeta {
1326 id,
1327 metadata: args.source_range.into(),
1328 },
1329 };
1330
1331 let sketch = Sketch {
1332 id: path_id,
1333 original_id: path_id,
1334 artifact_id: path_id.into(),
1335 on: sketch_surface.clone(),
1336 paths: vec![],
1337 units: sketch_surface.units(),
1338 meta: vec![args.source_range.into()],
1339 tags: if let Some(tag) = &tag {
1340 let mut tag_identifier: TagIdentifier = tag.into();
1341 tag_identifier.info = Some(TagEngineInfo {
1342 id: current_path.geo_meta.id,
1343 sketch: path_id,
1344 path: Some(Path::Base {
1345 base: current_path.clone(),
1346 }),
1347 surface: None,
1348 });
1349 IndexMap::from([(tag.name.to_string(), tag_identifier)])
1350 } else {
1351 Default::default()
1352 },
1353 start: current_path,
1354 };
1355 Ok(sketch)
1356}
1357
1358pub async fn profile_start_x(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1360 let sketch: Sketch = args.get_sketch()?;
1361 let ty = sketch.units.into();
1362 let x = inner_profile_start_x(sketch)?;
1363 Ok(args.make_user_val_from_f64_with_type(TyF64::new(x, ty)))
1364}
1365
1366#[stdlib {
1377 name = "profileStartX"
1378}]
1379pub(crate) fn inner_profile_start_x(sketch: Sketch) -> Result<f64, KclError> {
1380 Ok(sketch.start.to[0])
1381}
1382
1383pub async fn profile_start_y(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1385 let sketch: Sketch = args.get_sketch()?;
1386 let ty = sketch.units.into();
1387 let x = inner_profile_start_y(sketch)?;
1388 Ok(args.make_user_val_from_f64_with_type(TyF64::new(x, ty)))
1389}
1390
1391#[stdlib {
1401 name = "profileStartY"
1402}]
1403pub(crate) fn inner_profile_start_y(sketch: Sketch) -> Result<f64, KclError> {
1404 Ok(sketch.start.to[1])
1405}
1406
1407pub async fn profile_start(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1409 let sketch: Sketch = args.get_sketch()?;
1410 let ty = sketch.units.into();
1411 let point = inner_profile_start(sketch)?;
1412 Ok(KclValue::from_point2d(point, ty, args.into()))
1413}
1414
1415#[stdlib {
1428 name = "profileStart"
1429}]
1430pub(crate) fn inner_profile_start(sketch: Sketch) -> Result<[f64; 2], KclError> {
1431 Ok(sketch.start.to)
1432}
1433
1434pub async fn close(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1436 let sketch = args.get_unlabeled_kw_arg("sketch")?;
1437 let tag = args.get_kw_arg_opt(NEW_TAG_KW)?;
1438 let new_sketch = inner_close(sketch, tag, exec_state, args).await?;
1439 Ok(KclValue::Sketch {
1440 value: Box::new(new_sketch),
1441 })
1442}
1443
1444#[stdlib {
1466 name = "close",
1467 keywords = true,
1468 unlabeled_first = true,
1469 args = {
1470 sketch = { docs = "The sketch you want to close"},
1471 tag = { docs = "Create a new tag which refers to this line"},
1472 }
1473}]
1474pub(crate) async fn inner_close(
1475 sketch: Sketch,
1476 tag: Option<TagNode>,
1477 exec_state: &mut ExecState,
1478 args: Args,
1479) -> Result<Sketch, KclError> {
1480 let from = sketch.current_pen_position()?;
1481 let to: Point2d = sketch.start.from.into();
1482
1483 let id = exec_state.next_uuid();
1484
1485 args.batch_modeling_cmd(id, ModelingCmd::from(mcmd::ClosePath { path_id: sketch.id }))
1486 .await?;
1487
1488 if let SketchSurface::Plane(_) = sketch.on {
1490 args.batch_modeling_cmd(
1492 exec_state.next_uuid(),
1493 ModelingCmd::SketchModeDisable(mcmd::SketchModeDisable::default()),
1494 )
1495 .await?;
1496 }
1497
1498 let current_path = Path::ToPoint {
1499 base: BasePath {
1500 from: from.into(),
1501 to: to.into(),
1502 tag: tag.clone(),
1503 units: sketch.units,
1504 geo_meta: GeoMeta {
1505 id,
1506 metadata: args.source_range.into(),
1507 },
1508 },
1509 };
1510
1511 let mut new_sketch = sketch.clone();
1512 if let Some(tag) = &tag {
1513 new_sketch.add_tag(tag, ¤t_path);
1514 }
1515
1516 new_sketch.paths.push(current_path);
1517
1518 Ok(new_sketch)
1519}
1520
1521#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
1523#[ts(export)]
1524#[serde(rename_all = "camelCase", untagged)]
1525pub enum ArcData {
1526 AnglesAndRadius {
1528 #[serde(rename = "angleStart")]
1530 #[schemars(range(min = -360.0, max = 360.0))]
1531 angle_start: f64,
1532 #[serde(rename = "angleEnd")]
1534 #[schemars(range(min = -360.0, max = 360.0))]
1535 angle_end: f64,
1536 radius: f64,
1538 },
1539 CenterToRadius {
1541 center: [f64; 2],
1543 to: [f64; 2],
1545 radius: f64,
1547 },
1548}
1549
1550#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
1552#[ts(export)]
1553#[serde(rename_all = "camelCase")]
1554pub struct ArcToData {
1555 pub end: [f64; 2],
1557 pub interior: [f64; 2],
1559}
1560
1561pub async fn arc(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1563 let (data, sketch, tag): (ArcData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
1564
1565 let new_sketch = inner_arc(data, sketch, tag, exec_state, args).await?;
1566 Ok(KclValue::Sketch {
1567 value: Box::new(new_sketch),
1568 })
1569}
1570
1571#[stdlib {
1595 name = "arc",
1596}]
1597pub(crate) async fn inner_arc(
1598 data: ArcData,
1599 sketch: Sketch,
1600 tag: Option<TagNode>,
1601 exec_state: &mut ExecState,
1602 args: Args,
1603) -> Result<Sketch, KclError> {
1604 let from: Point2d = sketch.current_pen_position()?;
1605
1606 let (center, angle_start, angle_end, radius, end) = match &data {
1607 ArcData::AnglesAndRadius {
1608 angle_start,
1609 angle_end,
1610 radius,
1611 } => {
1612 let a_start = Angle::from_degrees(*angle_start);
1613 let a_end = Angle::from_degrees(*angle_end);
1614 let (center, end) = arc_center_and_end(from, a_start, a_end, *radius);
1615 (center, a_start, a_end, *radius, end)
1616 }
1617 ArcData::CenterToRadius { center, to, radius } => {
1618 let (angle_start, angle_end) = arc_angles(from, to.into(), center.into(), *radius, args.source_range)?;
1619 (center.into(), angle_start, angle_end, *radius, to.into())
1620 }
1621 };
1622
1623 if angle_start == angle_end {
1624 return Err(KclError::Type(KclErrorDetails {
1625 message: "Arc start and end angles must be different".to_string(),
1626 source_ranges: vec![args.source_range],
1627 }));
1628 }
1629 let ccw = angle_start < angle_end;
1630
1631 let id = exec_state.next_uuid();
1632
1633 args.batch_modeling_cmd(
1634 id,
1635 ModelingCmd::from(mcmd::ExtendPath {
1636 path: sketch.id.into(),
1637 segment: PathSegment::Arc {
1638 start: angle_start,
1639 end: angle_end,
1640 center: KPoint2d::from(center).map(LengthUnit),
1641 radius: LengthUnit(radius),
1642 relative: false,
1643 },
1644 }),
1645 )
1646 .await?;
1647
1648 let current_path = Path::Arc {
1649 base: BasePath {
1650 from: from.into(),
1651 to: end.into(),
1652 tag: tag.clone(),
1653 units: sketch.units,
1654 geo_meta: GeoMeta {
1655 id,
1656 metadata: args.source_range.into(),
1657 },
1658 },
1659 center: center.into(),
1660 radius,
1661 ccw,
1662 };
1663
1664 let mut new_sketch = sketch.clone();
1665 if let Some(tag) = &tag {
1666 new_sketch.add_tag(tag, ¤t_path);
1667 }
1668
1669 new_sketch.paths.push(current_path);
1670
1671 Ok(new_sketch)
1672}
1673
1674pub async fn arc_to(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1676 let (data, sketch, tag): (ArcToData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
1677
1678 let new_sketch = inner_arc_to(data, sketch, tag, exec_state, args).await?;
1679 Ok(KclValue::Sketch {
1680 value: Box::new(new_sketch),
1681 })
1682}
1683
1684#[stdlib {
1701 name = "arcTo",
1702}]
1703pub(crate) async fn inner_arc_to(
1704 data: ArcToData,
1705 sketch: Sketch,
1706 tag: Option<TagNode>,
1707 exec_state: &mut ExecState,
1708 args: Args,
1709) -> Result<Sketch, KclError> {
1710 let from: Point2d = sketch.current_pen_position()?;
1711 let id = exec_state.next_uuid();
1712
1713 args.batch_modeling_cmd(
1715 id,
1716 ModelingCmd::from(mcmd::ExtendPath {
1717 path: sketch.id.into(),
1718 segment: PathSegment::ArcTo {
1719 end: kcmc::shared::Point3d {
1720 x: LengthUnit(data.end[0]),
1721 y: LengthUnit(data.end[1]),
1722 z: LengthUnit(0.0),
1723 },
1724 interior: kcmc::shared::Point3d {
1725 x: LengthUnit(data.interior[0]),
1726 y: LengthUnit(data.interior[1]),
1727 z: LengthUnit(0.0),
1728 },
1729 relative: false,
1730 },
1731 }),
1732 )
1733 .await?;
1734
1735 let start = [from.x, from.y];
1736 let interior = data.interior;
1737 let end = data.end;
1738
1739 let center = calculate_circle_center(start, interior, end);
1741
1742 let sum_of_square_differences =
1745 (center[0] - start[0] * center[0] - start[0]) + (center[1] - start[1] * center[1] - start[1]);
1746 let radius = sum_of_square_differences.sqrt();
1747
1748 let ccw = is_ccw(start, interior, end);
1749
1750 let current_path = Path::Arc {
1751 base: BasePath {
1752 from: from.into(),
1753 to: data.end,
1754 tag: tag.clone(),
1755 units: sketch.units,
1756 geo_meta: GeoMeta {
1757 id,
1758 metadata: args.source_range.into(),
1759 },
1760 },
1761 center,
1762 radius,
1763 ccw,
1764 };
1765
1766 let mut new_sketch = sketch.clone();
1767 if let Some(tag) = &tag {
1768 new_sketch.add_tag(tag, ¤t_path);
1769 }
1770
1771 new_sketch.paths.push(current_path);
1772
1773 Ok(new_sketch)
1774}
1775
1776fn is_ccw(start: [f64; 2], interior: [f64; 2], end: [f64; 2]) -> bool {
1790 let t1 = (interior[0] - start[0]) * (end[1] - start[1]);
1791 let t2 = (end[0] - start[0]) * (interior[1] - start[1]);
1792 t1 > t2
1794}
1795
1796#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, ts_rs::TS)]
1798#[ts(export)]
1799#[serde(rename_all = "camelCase", untagged)]
1800pub enum TangentialArcData {
1801 RadiusAndOffset {
1802 radius: f64,
1805 offset: f64,
1807 },
1808}
1809
1810pub async fn tangential_arc(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1812 let (data, sketch, tag): (TangentialArcData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
1813
1814 let new_sketch = inner_tangential_arc(data, sketch, tag, exec_state, args).await?;
1815 Ok(KclValue::Sketch {
1816 value: Box::new(new_sketch),
1817 })
1818}
1819
1820#[stdlib {
1844 name = "tangentialArc",
1845}]
1846async fn inner_tangential_arc(
1847 data: TangentialArcData,
1848 sketch: Sketch,
1849 tag: Option<TagNode>,
1850 exec_state: &mut ExecState,
1851 args: Args,
1852) -> Result<Sketch, KclError> {
1853 let from: Point2d = sketch.current_pen_position()?;
1854 let tangent_info = sketch.get_tangential_info_from_paths(); let tan_previous_point = tangent_info.tan_previous_point(from.into());
1857
1858 let id = exec_state.next_uuid();
1859
1860 let (center, to, ccw) = match data {
1861 TangentialArcData::RadiusAndOffset { radius, offset } => {
1862 let offset = Angle::from_degrees(offset);
1864
1865 let previous_end_tangent = Angle::from_radians(f64::atan2(
1868 from.y - tan_previous_point[1],
1869 from.x - tan_previous_point[0],
1870 ));
1871 let ccw = offset.to_degrees() > 0.0;
1874 let tangent_to_arc_start_angle = if ccw {
1875 Angle::from_degrees(-90.0)
1877 } else {
1878 Angle::from_degrees(90.0)
1880 };
1881 let start_angle = previous_end_tangent + tangent_to_arc_start_angle;
1884 let end_angle = start_angle + offset;
1885 let (center, to) = arc_center_and_end(from, start_angle, end_angle, radius);
1886
1887 args.batch_modeling_cmd(
1888 id,
1889 ModelingCmd::from(mcmd::ExtendPath {
1890 path: sketch.id.into(),
1891 segment: PathSegment::TangentialArc {
1892 radius: LengthUnit(radius),
1893 offset,
1894 },
1895 }),
1896 )
1897 .await?;
1898 (center, to.into(), ccw)
1899 }
1900 };
1901
1902 let current_path = Path::TangentialArc {
1903 ccw,
1904 center: center.into(),
1905 base: BasePath {
1906 from: from.into(),
1907 to,
1908 tag: tag.clone(),
1909 units: sketch.units,
1910 geo_meta: GeoMeta {
1911 id,
1912 metadata: args.source_range.into(),
1913 },
1914 },
1915 };
1916
1917 let mut new_sketch = sketch.clone();
1918 if let Some(tag) = &tag {
1919 new_sketch.add_tag(tag, ¤t_path);
1920 }
1921
1922 new_sketch.paths.push(current_path);
1923
1924 Ok(new_sketch)
1925}
1926
1927fn tan_arc_to(sketch: &Sketch, to: &[f64; 2]) -> ModelingCmd {
1928 ModelingCmd::from(mcmd::ExtendPath {
1929 path: sketch.id.into(),
1930 segment: PathSegment::TangentialArcTo {
1931 angle_snap_increment: None,
1932 to: KPoint2d::from(*to).with_z(0.0).map(LengthUnit),
1933 },
1934 })
1935}
1936
1937pub async fn tangential_arc_to(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1939 let (to, sketch, tag): ([f64; 2], Sketch, Option<TagNode>) = super::args::FromArgs::from_args(&args, 0)?;
1940
1941 let new_sketch = inner_tangential_arc_to(to, sketch, tag, exec_state, args).await?;
1942 Ok(KclValue::Sketch {
1943 value: Box::new(new_sketch),
1944 })
1945}
1946
1947pub async fn tangential_arc_to_relative(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1949 let (delta, sketch, tag): ([f64; 2], Sketch, Option<TagNode>) = super::args::FromArgs::from_args(&args, 0)?;
1950
1951 let new_sketch = inner_tangential_arc_to_relative(delta, sketch, tag, exec_state, args).await?;
1952 Ok(KclValue::Sketch {
1953 value: Box::new(new_sketch),
1954 })
1955}
1956
1957#[stdlib {
1975 name = "tangentialArcTo",
1976}]
1977async fn inner_tangential_arc_to(
1978 to: [f64; 2],
1979 sketch: Sketch,
1980 tag: Option<TagNode>,
1981 exec_state: &mut ExecState,
1982 args: Args,
1983) -> Result<Sketch, KclError> {
1984 let from: Point2d = sketch.current_pen_position()?;
1985 let tangent_info = sketch.get_tangential_info_from_paths();
1986 let tan_previous_point = tangent_info.tan_previous_point(from.into());
1987 let [to_x, to_y] = to;
1988 let result = get_tangential_arc_to_info(TangentialArcInfoInput {
1989 arc_start_point: [from.x, from.y],
1990 arc_end_point: to,
1991 tan_previous_point,
1992 obtuse: true,
1993 });
1994
1995 let delta = [to_x - from.x, to_y - from.y];
1996 let id = exec_state.next_uuid();
1997 args.batch_modeling_cmd(id, tan_arc_to(&sketch, &delta)).await?;
1998
1999 let current_path = Path::TangentialArcTo {
2000 base: BasePath {
2001 from: from.into(),
2002 to,
2003 tag: tag.clone(),
2004 units: sketch.units,
2005 geo_meta: GeoMeta {
2006 id,
2007 metadata: args.source_range.into(),
2008 },
2009 },
2010 center: result.center,
2011 ccw: result.ccw > 0,
2012 };
2013
2014 let mut new_sketch = sketch.clone();
2015 if let Some(tag) = &tag {
2016 new_sketch.add_tag(tag, ¤t_path);
2017 }
2018
2019 new_sketch.paths.push(current_path);
2020
2021 Ok(new_sketch)
2022}
2023
2024#[stdlib {
2042 name = "tangentialArcToRelative",
2043}]
2044async fn inner_tangential_arc_to_relative(
2045 delta: [f64; 2],
2046 sketch: Sketch,
2047 tag: Option<TagNode>,
2048 exec_state: &mut ExecState,
2049 args: Args,
2050) -> Result<Sketch, KclError> {
2051 let from: Point2d = sketch.current_pen_position()?;
2052 let to = [from.x + delta[0], from.y + delta[1]];
2053 let tangent_info = sketch.get_tangential_info_from_paths();
2054 let tan_previous_point = tangent_info.tan_previous_point(from.into());
2055
2056 let [dx, dy] = delta;
2057 let result = get_tangential_arc_to_info(TangentialArcInfoInput {
2058 arc_start_point: [from.x, from.y],
2059 arc_end_point: [from.x + dx, from.y + dy],
2060 tan_previous_point,
2061 obtuse: true,
2062 });
2063
2064 if result.center[0].is_infinite() {
2065 return Err(KclError::Semantic(KclErrorDetails {
2066 source_ranges: vec![args.source_range],
2067 message:
2068 "could not sketch tangential arc, because its center would be infinitely far away in the X direction"
2069 .to_owned(),
2070 }));
2071 } else if result.center[1].is_infinite() {
2072 return Err(KclError::Semantic(KclErrorDetails {
2073 source_ranges: vec![args.source_range],
2074 message:
2075 "could not sketch tangential arc, because its center would be infinitely far away in the Y direction"
2076 .to_owned(),
2077 }));
2078 }
2079
2080 let id = exec_state.next_uuid();
2081 args.batch_modeling_cmd(id, tan_arc_to(&sketch, &delta)).await?;
2082
2083 let current_path = Path::TangentialArcTo {
2084 base: BasePath {
2085 from: from.into(),
2086 to,
2087 tag: tag.clone(),
2088 units: sketch.units,
2089 geo_meta: GeoMeta {
2090 id,
2091 metadata: args.source_range.into(),
2092 },
2093 },
2094 center: result.center,
2095 ccw: result.ccw > 0,
2096 };
2097
2098 let mut new_sketch = sketch.clone();
2099 if let Some(tag) = &tag {
2100 new_sketch.add_tag(tag, ¤t_path);
2101 }
2102
2103 new_sketch.paths.push(current_path);
2104
2105 Ok(new_sketch)
2106}
2107
2108#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
2110#[ts(export)]
2111#[serde(rename_all = "camelCase")]
2112pub struct BezierData {
2113 pub to: [f64; 2],
2115 pub control1: [f64; 2],
2117 pub control2: [f64; 2],
2119}
2120
2121pub async fn bezier_curve(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2123 let (data, sketch, tag): (BezierData, Sketch, Option<TagNode>) = args.get_data_and_sketch_and_tag()?;
2124
2125 let new_sketch = inner_bezier_curve(data, sketch, tag, exec_state, args).await?;
2126 Ok(KclValue::Sketch {
2127 value: Box::new(new_sketch),
2128 })
2129}
2130
2131#[stdlib {
2150 name = "bezierCurve",
2151}]
2152async fn inner_bezier_curve(
2153 data: BezierData,
2154 sketch: Sketch,
2155 tag: Option<TagNode>,
2156 exec_state: &mut ExecState,
2157 args: Args,
2158) -> Result<Sketch, KclError> {
2159 let from = sketch.current_pen_position()?;
2160
2161 let relative = true;
2162 let delta = data.to;
2163 let to = [from.x + data.to[0], from.y + data.to[1]];
2164
2165 let id = exec_state.next_uuid();
2166
2167 args.batch_modeling_cmd(
2168 id,
2169 ModelingCmd::from(mcmd::ExtendPath {
2170 path: sketch.id.into(),
2171 segment: PathSegment::Bezier {
2172 control1: KPoint2d::from(data.control1).with_z(0.0).map(LengthUnit),
2173 control2: KPoint2d::from(data.control2).with_z(0.0).map(LengthUnit),
2174 end: KPoint2d::from(delta).with_z(0.0).map(LengthUnit),
2175 relative,
2176 },
2177 }),
2178 )
2179 .await?;
2180
2181 let current_path = Path::ToPoint {
2182 base: BasePath {
2183 from: from.into(),
2184 to,
2185 tag: tag.clone(),
2186 units: sketch.units,
2187 geo_meta: GeoMeta {
2188 id,
2189 metadata: args.source_range.into(),
2190 },
2191 },
2192 };
2193
2194 let mut new_sketch = sketch.clone();
2195 if let Some(tag) = &tag {
2196 new_sketch.add_tag(tag, ¤t_path);
2197 }
2198
2199 new_sketch.paths.push(current_path);
2200
2201 Ok(new_sketch)
2202}
2203
2204pub async fn hole(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2206 let (hole_sketch, sketch): (SketchSet, Sketch) = args.get_sketches()?;
2207
2208 let new_sketch = inner_hole(hole_sketch, sketch, exec_state, args).await?;
2209 Ok(KclValue::Sketch {
2210 value: Box::new(new_sketch),
2211 })
2212}
2213
2214#[stdlib {
2246 name = "hole",
2247 feature_tree_operation = true,
2248}]
2249async fn inner_hole(
2250 hole_sketch: SketchSet,
2251 sketch: Sketch,
2252 exec_state: &mut ExecState,
2253 args: Args,
2254) -> Result<Sketch, KclError> {
2255 let hole_sketches: Vec<Sketch> = hole_sketch.into();
2256 for hole_sketch in hole_sketches {
2257 args.batch_modeling_cmd(
2258 exec_state.next_uuid(),
2259 ModelingCmd::from(mcmd::Solid2dAddHole {
2260 object_id: sketch.id,
2261 hole_id: hole_sketch.id,
2262 }),
2263 )
2264 .await?;
2265
2266 args.batch_modeling_cmd(
2269 exec_state.next_uuid(),
2270 ModelingCmd::from(mcmd::ObjectVisible {
2271 object_id: hole_sketch.id,
2272 hidden: true,
2273 }),
2274 )
2275 .await?;
2276 }
2277
2278 Ok(sketch)
2279}
2280
2281#[cfg(test)]
2282mod tests {
2283
2284 use pretty_assertions::assert_eq;
2285
2286 use crate::{
2287 execution::TagIdentifier,
2288 std::{sketch::PlaneData, utils::calculate_circle_center},
2289 };
2290
2291 #[test]
2292 fn test_deserialize_plane_data() {
2293 let data = PlaneData::XY;
2294 let mut str_json = serde_json::to_string(&data).unwrap();
2295 assert_eq!(str_json, "\"XY\"");
2296
2297 str_json = "\"YZ\"".to_string();
2298 let data: PlaneData = serde_json::from_str(&str_json).unwrap();
2299 assert_eq!(data, PlaneData::YZ);
2300
2301 str_json = "\"-YZ\"".to_string();
2302 let data: PlaneData = serde_json::from_str(&str_json).unwrap();
2303 assert_eq!(data, PlaneData::NegYZ);
2304
2305 str_json = "\"-xz\"".to_string();
2306 let data: PlaneData = serde_json::from_str(&str_json).unwrap();
2307 assert_eq!(data, PlaneData::NegXZ);
2308 }
2309
2310 #[test]
2311 fn test_deserialize_sketch_on_face_tag() {
2312 let data = "start";
2313 let mut str_json = serde_json::to_string(&data).unwrap();
2314 assert_eq!(str_json, "\"start\"");
2315
2316 str_json = "\"end\"".to_string();
2317 let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2318 assert_eq!(
2319 data,
2320 crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::End)
2321 );
2322
2323 str_json = serde_json::to_string(&TagIdentifier {
2324 value: "thing".to_string(),
2325 info: None,
2326 meta: Default::default(),
2327 })
2328 .unwrap();
2329 let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2330 assert_eq!(
2331 data,
2332 crate::std::sketch::FaceTag::Tag(Box::new(TagIdentifier {
2333 value: "thing".to_string(),
2334 info: None,
2335 meta: Default::default()
2336 }))
2337 );
2338
2339 str_json = "\"END\"".to_string();
2340 let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2341 assert_eq!(
2342 data,
2343 crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::End)
2344 );
2345
2346 str_json = "\"start\"".to_string();
2347 let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2348 assert_eq!(
2349 data,
2350 crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::Start)
2351 );
2352
2353 str_json = "\"START\"".to_string();
2354 let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2355 assert_eq!(
2356 data,
2357 crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::Start)
2358 );
2359 }
2360
2361 #[test]
2362 fn test_circle_center() {
2363 let actual = calculate_circle_center([0.0, 0.0], [5.0, 5.0], [10.0, 0.0]);
2364 assert_eq!(actual[0], 5.0);
2365 assert_eq!(actual[1], 0.0);
2366 }
2367}