Skip to main content

kcl_lib/std/
patterns.rs

1//! Standard library patterns.
2
3use std::cmp::Ordering;
4
5use anyhow::Result;
6use kcmc::{
7    ModelingCmd, each_cmd as mcmd, length_unit::LengthUnit, ok_response::OkModelingCmdResponse, shared::Transform,
8    websocket::OkWebSocketResponseData,
9};
10use kittycad_modeling_cmds::{
11    self as kcmc,
12    shared::{Angle, OriginType, Rotation},
13};
14use serde::Serialize;
15use uuid::Uuid;
16
17use super::axis_or_reference::Axis3dOrPoint3d;
18use crate::{
19    ExecutorContext, SourceRange,
20    errors::{KclError, KclErrorDetails},
21    execution::{
22        ControlFlowKind, ExecState, Geometries, Geometry, KclObjectFields, KclValue, ModelingCmdMeta, Sketch, Solid,
23        fn_call::{Arg, Args},
24        kcl_value::FunctionSource,
25        types::{NumericType, PrimitiveType, RuntimeType},
26    },
27    std::{
28        args::TyF64,
29        axis_or_reference::Axis2dOrPoint2d,
30        utils::{point_3d_to_mm, point_to_mm},
31    },
32};
33
34const MUST_HAVE_ONE_INSTANCE: &str = "There must be at least 1 instance of your geometry";
35
36/// Repeat some 3D solid, changing each repetition slightly.
37pub async fn pattern_transform(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
38    let solids = args.get_unlabeled_kw_arg("solids", &RuntimeType::solids(), exec_state)?;
39    let instances: u32 = args.get_kw_arg("instances", &RuntimeType::count(), exec_state)?;
40    let transform: FunctionSource = args.get_kw_arg("transform", &RuntimeType::function(), exec_state)?;
41    let use_original = args.get_kw_arg_opt("useOriginal", &RuntimeType::bool(), exec_state)?;
42
43    let solids = inner_pattern_transform(solids, instances, transform, use_original, exec_state, &args).await?;
44    Ok(solids.into())
45}
46
47/// Repeat some 2D sketch, changing each repetition slightly.
48pub async fn pattern_transform_2d(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
49    let sketches = args.get_unlabeled_kw_arg("sketches", &RuntimeType::sketches(), exec_state)?;
50    let instances: u32 = args.get_kw_arg("instances", &RuntimeType::count(), exec_state)?;
51    let transform: FunctionSource = args.get_kw_arg("transform", &RuntimeType::function(), exec_state)?;
52    let use_original = args.get_kw_arg_opt("useOriginal", &RuntimeType::bool(), exec_state)?;
53
54    let sketches = inner_pattern_transform_2d(sketches, instances, transform, use_original, exec_state, &args).await?;
55    Ok(sketches.into())
56}
57
58async fn inner_pattern_transform(
59    solids: Vec<Solid>,
60    instances: u32,
61    transform: FunctionSource,
62    use_original: Option<bool>,
63    exec_state: &mut ExecState,
64    args: &Args,
65) -> Result<Vec<Solid>, KclError> {
66    // Build the vec of transforms, one for each repetition.
67    let mut transform_vec = Vec::with_capacity(usize::try_from(instances).unwrap());
68    if instances < 1 {
69        return Err(KclError::new_semantic(KclErrorDetails::new(
70            MUST_HAVE_ONE_INSTANCE.to_owned(),
71            vec![args.source_range],
72        )));
73    }
74    for i in 1..instances {
75        let t = make_transform::<Solid>(i, &transform, args.source_range, exec_state, &args.ctx).await?;
76        transform_vec.push(t);
77    }
78    execute_pattern_transform(
79        transform_vec,
80        solids,
81        use_original.unwrap_or_default(),
82        exec_state,
83        args,
84    )
85    .await
86}
87
88async fn inner_pattern_transform_2d(
89    sketches: Vec<Sketch>,
90    instances: u32,
91    transform: FunctionSource,
92    use_original: Option<bool>,
93    exec_state: &mut ExecState,
94    args: &Args,
95) -> Result<Vec<Sketch>, KclError> {
96    // Build the vec of transforms, one for each repetition.
97    let mut transform_vec = Vec::with_capacity(usize::try_from(instances).unwrap());
98    if instances < 1 {
99        return Err(KclError::new_semantic(KclErrorDetails::new(
100            MUST_HAVE_ONE_INSTANCE.to_owned(),
101            vec![args.source_range],
102        )));
103    }
104    for i in 1..instances {
105        let t = make_transform::<Sketch>(i, &transform, args.source_range, exec_state, &args.ctx).await?;
106        transform_vec.push(t);
107    }
108    execute_pattern_transform(
109        transform_vec,
110        sketches,
111        use_original.unwrap_or_default(),
112        exec_state,
113        args,
114    )
115    .await
116}
117
118async fn execute_pattern_transform<T: GeometryTrait>(
119    transforms: Vec<Vec<Transform>>,
120    geo_set: T::Set,
121    use_original: bool,
122    exec_state: &mut ExecState,
123    args: &Args,
124) -> Result<Vec<T>, KclError> {
125    // Flush the batch for our fillets/chamfers if there are any.
126    // If we do not flush these, then you won't be able to pattern something with fillets.
127    // Flush just the fillets/chamfers that apply to these solids.
128    T::flush_batch(args, exec_state, &geo_set).await?;
129    let starting: Vec<T> = geo_set.into();
130
131    if args.ctx.context_type == crate::execution::ContextType::Mock {
132        return Ok(starting);
133    }
134
135    let mut output = Vec::new();
136    for geo in starting {
137        let new = send_pattern_transform(transforms.clone(), &geo, use_original, exec_state, args).await?;
138        output.extend(new)
139    }
140    Ok(output)
141}
142
143async fn send_pattern_transform<T: GeometryTrait>(
144    // This should be passed via reference, see
145    // https://github.com/KittyCAD/modeling-app/issues/2821
146    transforms: Vec<Vec<Transform>>,
147    solid: &T,
148    use_original: bool,
149    exec_state: &mut ExecState,
150    args: &Args,
151) -> Result<Vec<T>, KclError> {
152    let extra_instances = transforms.len();
153
154    let resp = exec_state
155        .send_modeling_cmd(
156            ModelingCmdMeta::from_args(exec_state, args),
157            ModelingCmd::from(
158                mcmd::EntityLinearPatternTransform::builder()
159                    .entity_id(if use_original { solid.original_id() } else { solid.id() })
160                    .transform(Default::default())
161                    .transforms(transforms)
162                    .build(),
163            ),
164        )
165        .await?;
166
167    let mut mock_ids = Vec::new();
168    let entity_ids = if let OkWebSocketResponseData::Modeling {
169        modeling_response: OkModelingCmdResponse::EntityLinearPatternTransform(pattern_info),
170    } = &resp
171    {
172        &pattern_info.entity_face_edge_ids.iter().map(|x| x.object_id).collect()
173    } else if args.ctx.no_engine_commands().await {
174        mock_ids.reserve(extra_instances);
175        for _ in 0..extra_instances {
176            mock_ids.push(exec_state.next_uuid());
177        }
178        &mock_ids
179    } else {
180        return Err(KclError::new_engine(KclErrorDetails::new(
181            format!("EntityLinearPattern response was not as expected: {resp:?}"),
182            vec![args.source_range],
183        )));
184    };
185
186    let mut geometries = vec![solid.clone()];
187    for id in entity_ids.iter().copied() {
188        let mut new_solid = solid.clone();
189        new_solid.set_id(id);
190        geometries.push(new_solid);
191    }
192    Ok(geometries)
193}
194
195async fn make_transform<T: GeometryTrait>(
196    i: u32,
197    transform: &FunctionSource,
198    source_range: SourceRange,
199    exec_state: &mut ExecState,
200    ctxt: &ExecutorContext,
201) -> Result<Vec<Transform>, KclError> {
202    // Call the transform fn for this repetition.
203    let repetition_num = KclValue::Number {
204        value: i.into(),
205        ty: NumericType::count(),
206        meta: vec![source_range.into()],
207    };
208    let transform_fn_args = Args::new(
209        Default::default(),
210        vec![(None, Arg::new(repetition_num, source_range))],
211        source_range,
212        exec_state,
213        ctxt.clone(),
214        Some("transform closure".to_owned()),
215    );
216    let transform_fn_return = transform
217        .call_kw(None, exec_state, ctxt, transform_fn_args, source_range)
218        .await?;
219
220    // Unpack the returned transform object.
221    let source_ranges = vec![source_range];
222    let transform_fn_return = transform_fn_return.ok_or_else(|| {
223        KclError::new_semantic(KclErrorDetails::new(
224            "Transform function must return a value".to_string(),
225            source_ranges.clone(),
226        ))
227    })?;
228
229    let transform_fn_return = match transform_fn_return.control {
230        ControlFlowKind::Continue => transform_fn_return.into_value(),
231        ControlFlowKind::Exit => {
232            let message = "Early return inside pattern transform function is currently not supported".to_owned();
233            debug_assert!(false, "{}", &message);
234            return Err(KclError::new_internal(KclErrorDetails::new(
235                message,
236                vec![source_range],
237            )));
238        }
239    };
240
241    let transforms = match transform_fn_return {
242        KclValue::Object { value, .. } => vec![value],
243        KclValue::Tuple { value, .. } | KclValue::HomArray { value, .. } => {
244            let transforms: Vec<_> = value
245                .into_iter()
246                .map(|val| {
247                    val.into_object().ok_or(KclError::new_semantic(KclErrorDetails::new(
248                        "Transform function must return a transform object".to_string(),
249                        source_ranges.clone(),
250                    )))
251                })
252                .collect::<Result<_, _>>()?;
253            transforms
254        }
255        _ => {
256            return Err(KclError::new_semantic(KclErrorDetails::new(
257                "Transform function must return a transform object".to_string(),
258                source_ranges,
259            )));
260        }
261    };
262
263    transforms
264        .into_iter()
265        .map(|obj| transform_from_obj_fields::<T>(obj, source_ranges.clone(), exec_state))
266        .collect()
267}
268
269fn transform_from_obj_fields<T: GeometryTrait>(
270    transform: KclObjectFields,
271    source_ranges: Vec<SourceRange>,
272    exec_state: &mut ExecState,
273) -> Result<Transform, KclError> {
274    // Apply defaults to the transform.
275    let replicate = match transform.get("replicate") {
276        Some(KclValue::Bool { value: true, .. }) => true,
277        Some(KclValue::Bool { value: false, .. }) => false,
278        Some(_) => {
279            return Err(KclError::new_semantic(KclErrorDetails::new(
280                "The 'replicate' key must be a bool".to_string(),
281                source_ranges,
282            )));
283        }
284        None => true,
285    };
286
287    let scale = match transform.get("scale") {
288        Some(x) => point_3d_to_mm(T::array_to_point3d(x, source_ranges.clone(), exec_state)?).into(),
289        None => kcmc::shared::Point3d { x: 1.0, y: 1.0, z: 1.0 },
290    };
291
292    for (dim, name) in [(scale.x, "x"), (scale.y, "y"), (scale.z, "z")] {
293        if dim == 0.0 {
294            return Err(KclError::new_semantic(KclErrorDetails::new(
295                format!("cannot set {name} = 0, scale factor must be nonzero"),
296                source_ranges,
297            )));
298        }
299    }
300    let translate = match transform.get("translate") {
301        Some(x) => {
302            let arr = point_3d_to_mm(T::array_to_point3d(x, source_ranges.clone(), exec_state)?);
303            kcmc::shared::Point3d::<LengthUnit> {
304                x: LengthUnit(arr[0]),
305                y: LengthUnit(arr[1]),
306                z: LengthUnit(arr[2]),
307            }
308        }
309        None => kcmc::shared::Point3d::<LengthUnit> {
310            x: LengthUnit(0.0),
311            y: LengthUnit(0.0),
312            z: LengthUnit(0.0),
313        },
314    };
315
316    let mut rotation = Rotation::default();
317    if let Some(rot) = transform.get("rotation") {
318        let KclValue::Object { value: rot, .. } = rot else {
319            return Err(KclError::new_semantic(KclErrorDetails::new(
320                "The 'rotation' key must be an object (with optional fields 'angle', 'axis' and 'origin')".to_owned(),
321                source_ranges,
322            )));
323        };
324        if let Some(axis) = rot.get("axis") {
325            rotation.axis = point_3d_to_mm(T::array_to_point3d(axis, source_ranges.clone(), exec_state)?).into();
326        }
327        if let Some(angle) = rot.get("angle") {
328            match angle {
329                KclValue::Number { value: number, .. } => {
330                    rotation.angle = Angle::from_degrees(*number);
331                }
332                _ => {
333                    return Err(KclError::new_semantic(KclErrorDetails::new(
334                        "The 'rotation.angle' key must be a number (of degrees)".to_owned(),
335                        source_ranges,
336                    )));
337                }
338            }
339        }
340        if let Some(origin) = rot.get("origin") {
341            rotation.origin = match origin {
342                KclValue::String { value: s, meta: _ } if s == "local" => OriginType::Local,
343                KclValue::String { value: s, meta: _ } if s == "global" => OriginType::Global,
344                other => {
345                    let origin = point_3d_to_mm(T::array_to_point3d(other, source_ranges, exec_state)?).into();
346                    OriginType::Custom { origin }
347                }
348            };
349        }
350    }
351
352    let transform = Transform::builder()
353        .replicate(replicate)
354        .scale(scale)
355        .translate(translate)
356        .rotation(rotation)
357        .build();
358    Ok(transform)
359}
360
361fn array_to_point3d(
362    val: &KclValue,
363    source_ranges: Vec<SourceRange>,
364    exec_state: &mut ExecState,
365) -> Result<[TyF64; 3], KclError> {
366    val.coerce(&RuntimeType::point3d(), true, exec_state)
367        .map_err(|e| {
368            KclError::new_semantic(KclErrorDetails::new(
369                format!(
370                    "Expected an array of 3 numbers (i.e., a 3D point), found {}",
371                    e.found
372                        .map(|t| t.human_friendly_type())
373                        .unwrap_or_else(|| val.human_friendly_type())
374                ),
375                source_ranges,
376            ))
377        })
378        .map(|val| val.as_point3d().unwrap())
379}
380
381fn array_to_point2d(
382    val: &KclValue,
383    source_ranges: Vec<SourceRange>,
384    exec_state: &mut ExecState,
385) -> Result<[TyF64; 2], KclError> {
386    val.coerce(&RuntimeType::point2d(), true, exec_state)
387        .map_err(|e| {
388            KclError::new_semantic(KclErrorDetails::new(
389                format!(
390                    "Expected an array of 2 numbers (i.e., a 2D point), found {}",
391                    e.found
392                        .map(|t| t.human_friendly_type())
393                        .unwrap_or_else(|| val.human_friendly_type())
394                ),
395                source_ranges,
396            ))
397        })
398        .map(|val| val.as_point2d().unwrap())
399}
400
401pub trait GeometryTrait: Clone {
402    type Set: Into<Vec<Self>> + Clone;
403    fn id(&self) -> Uuid;
404    fn original_id(&self) -> Uuid;
405    fn set_id(&mut self, id: Uuid);
406    fn array_to_point3d(
407        val: &KclValue,
408        source_ranges: Vec<SourceRange>,
409        exec_state: &mut ExecState,
410    ) -> Result<[TyF64; 3], KclError>;
411    #[allow(async_fn_in_trait)]
412    async fn flush_batch(args: &Args, exec_state: &mut ExecState, set: &Self::Set) -> Result<(), KclError>;
413}
414
415impl GeometryTrait for Sketch {
416    type Set = Vec<Sketch>;
417    fn set_id(&mut self, id: Uuid) {
418        self.id = id;
419    }
420    fn id(&self) -> Uuid {
421        self.id
422    }
423    fn original_id(&self) -> Uuid {
424        self.original_id
425    }
426    fn array_to_point3d(
427        val: &KclValue,
428        source_ranges: Vec<SourceRange>,
429        exec_state: &mut ExecState,
430    ) -> Result<[TyF64; 3], KclError> {
431        let [x, y] = array_to_point2d(val, source_ranges, exec_state)?;
432        let ty = x.ty;
433        Ok([x, y, TyF64::new(0.0, ty)])
434    }
435
436    async fn flush_batch(_: &Args, _: &mut ExecState, _: &Self::Set) -> Result<(), KclError> {
437        Ok(())
438    }
439}
440
441impl GeometryTrait for Solid {
442    type Set = Vec<Solid>;
443    fn set_id(&mut self, id: Uuid) {
444        self.id = id;
445        // We need this for in extrude.rs when you sketch on face.
446        self.sketch.id = id;
447    }
448
449    fn id(&self) -> Uuid {
450        self.id
451    }
452
453    fn original_id(&self) -> Uuid {
454        self.sketch.original_id
455    }
456
457    fn array_to_point3d(
458        val: &KclValue,
459        source_ranges: Vec<SourceRange>,
460        exec_state: &mut ExecState,
461    ) -> Result<[TyF64; 3], KclError> {
462        array_to_point3d(val, source_ranges, exec_state)
463    }
464
465    async fn flush_batch(args: &Args, exec_state: &mut ExecState, solid_set: &Self::Set) -> Result<(), KclError> {
466        exec_state
467            .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, args), solid_set)
468            .await
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use crate::execution::types::{NumericType, PrimitiveType};
476
477    #[tokio::test(flavor = "multi_thread")]
478    async fn test_array_to_point3d() {
479        let ctx = ExecutorContext::new_mock(None).await;
480        let mut exec_state = ExecState::new(&ctx);
481        let input = KclValue::HomArray {
482            value: vec![
483                KclValue::Number {
484                    value: 1.1,
485                    meta: Default::default(),
486                    ty: NumericType::mm(),
487                },
488                KclValue::Number {
489                    value: 2.2,
490                    meta: Default::default(),
491                    ty: NumericType::mm(),
492                },
493                KclValue::Number {
494                    value: 3.3,
495                    meta: Default::default(),
496                    ty: NumericType::mm(),
497                },
498            ],
499            ty: RuntimeType::Primitive(PrimitiveType::Number(NumericType::mm())),
500        };
501        let expected = [
502            TyF64::new(1.1, NumericType::mm()),
503            TyF64::new(2.2, NumericType::mm()),
504            TyF64::new(3.3, NumericType::mm()),
505        ];
506        let actual = array_to_point3d(&input, Vec::new(), &mut exec_state);
507        assert_eq!(actual.unwrap(), expected);
508        ctx.close().await;
509    }
510
511    #[tokio::test(flavor = "multi_thread")]
512    async fn test_tuple_to_point3d() {
513        let ctx = ExecutorContext::new_mock(None).await;
514        let mut exec_state = ExecState::new(&ctx);
515        let input = KclValue::Tuple {
516            value: vec![
517                KclValue::Number {
518                    value: 1.1,
519                    meta: Default::default(),
520                    ty: NumericType::mm(),
521                },
522                KclValue::Number {
523                    value: 2.2,
524                    meta: Default::default(),
525                    ty: NumericType::mm(),
526                },
527                KclValue::Number {
528                    value: 3.3,
529                    meta: Default::default(),
530                    ty: NumericType::mm(),
531                },
532            ],
533            meta: Default::default(),
534        };
535        let expected = [
536            TyF64::new(1.1, NumericType::mm()),
537            TyF64::new(2.2, NumericType::mm()),
538            TyF64::new(3.3, NumericType::mm()),
539        ];
540        let actual = array_to_point3d(&input, Vec::new(), &mut exec_state);
541        assert_eq!(actual.unwrap(), expected);
542        ctx.close().await;
543    }
544}
545
546/// A linear pattern on a 2D sketch.
547pub async fn pattern_linear_2d(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
548    let sketches = args.get_unlabeled_kw_arg("sketches", &RuntimeType::sketches(), exec_state)?;
549    let instances: u32 = args.get_kw_arg("instances", &RuntimeType::count(), exec_state)?;
550    let distance: TyF64 = args.get_kw_arg("distance", &RuntimeType::length(), exec_state)?;
551    let axis: Axis2dOrPoint2d = args.get_kw_arg(
552        "axis",
553        &RuntimeType::Union(vec![
554            RuntimeType::Primitive(PrimitiveType::Axis2d),
555            RuntimeType::point2d(),
556        ]),
557        exec_state,
558    )?;
559    let use_original = args.get_kw_arg_opt("useOriginal", &RuntimeType::bool(), exec_state)?;
560
561    let axis = axis.to_point2d();
562    if axis[0].n == 0.0 && axis[1].n == 0.0 {
563        return Err(KclError::new_semantic(KclErrorDetails::new(
564            "The axis of the linear pattern cannot be the zero vector. Otherwise they will just duplicate in place."
565                .to_owned(),
566            vec![args.source_range],
567        )));
568    }
569
570    let sketches = inner_pattern_linear_2d(sketches, instances, distance, axis, use_original, exec_state, args).await?;
571    Ok(sketches.into())
572}
573
574async fn inner_pattern_linear_2d(
575    sketches: Vec<Sketch>,
576    instances: u32,
577    distance: TyF64,
578    axis: [TyF64; 2],
579    use_original: Option<bool>,
580    exec_state: &mut ExecState,
581    args: Args,
582) -> Result<Vec<Sketch>, KclError> {
583    let [x, y] = point_to_mm(axis);
584    let axis_len = f64::sqrt(x * x + y * y);
585    let normalized_axis = kcmc::shared::Point2d::from([x / axis_len, y / axis_len]);
586    let transforms: Vec<_> = (1..instances)
587        .map(|i| {
588            let d = distance.to_mm() * (i as f64);
589            let translate = (normalized_axis * d).with_z(0.0).map(LengthUnit);
590            vec![Transform::builder().translate(translate).build()]
591        })
592        .collect();
593    execute_pattern_transform(
594        transforms,
595        sketches,
596        use_original.unwrap_or_default(),
597        exec_state,
598        &args,
599    )
600    .await
601}
602
603/// A linear pattern on a 3D model.
604pub async fn pattern_linear_3d(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
605    let solids = args.get_unlabeled_kw_arg("solids", &RuntimeType::solids(), exec_state)?;
606    let instances: u32 = args.get_kw_arg("instances", &RuntimeType::count(), exec_state)?;
607    let distance: TyF64 = args.get_kw_arg("distance", &RuntimeType::length(), exec_state)?;
608    let axis: Axis3dOrPoint3d = args.get_kw_arg(
609        "axis",
610        &RuntimeType::Union(vec![
611            RuntimeType::Primitive(PrimitiveType::Axis3d),
612            RuntimeType::point3d(),
613        ]),
614        exec_state,
615    )?;
616    let use_original = args.get_kw_arg_opt("useOriginal", &RuntimeType::bool(), exec_state)?;
617
618    let axis = axis.to_point3d();
619    if axis[0].n == 0.0 && axis[1].n == 0.0 && axis[2].n == 0.0 {
620        return Err(KclError::new_semantic(KclErrorDetails::new(
621            "The axis of the linear pattern cannot be the zero vector. Otherwise they will just duplicate in place."
622                .to_owned(),
623            vec![args.source_range],
624        )));
625    }
626
627    let solids = inner_pattern_linear_3d(solids, instances, distance, axis, use_original, exec_state, args).await?;
628    Ok(solids.into())
629}
630
631async fn inner_pattern_linear_3d(
632    solids: Vec<Solid>,
633    instances: u32,
634    distance: TyF64,
635    axis: [TyF64; 3],
636    use_original: Option<bool>,
637    exec_state: &mut ExecState,
638    args: Args,
639) -> Result<Vec<Solid>, KclError> {
640    let [x, y, z] = point_3d_to_mm(axis);
641    let axis_len = f64::sqrt(x * x + y * y + z * z);
642    let normalized_axis = kcmc::shared::Point3d::from([x / axis_len, y / axis_len, z / axis_len]);
643    let transforms: Vec<_> = (1..instances)
644        .map(|i| {
645            let d = distance.to_mm() * (i as f64);
646            let translate = (normalized_axis * d).map(LengthUnit);
647            vec![Transform::builder().translate(translate).build()]
648        })
649        .collect();
650    execute_pattern_transform(transforms, solids, use_original.unwrap_or_default(), exec_state, &args).await
651}
652
653/// Data for a circular pattern on a 2D sketch.
654#[derive(Debug, Clone, Serialize, PartialEq)]
655#[serde(rename_all = "camelCase")]
656struct CircularPattern2dData {
657    /// The number of total instances. Must be greater than or equal to 1.
658    /// This includes the original entity. For example, if instances is 2,
659    /// there will be two copies -- the original, and one new copy.
660    /// If instances is 1, this has no effect.
661    pub instances: u32,
662    /// The center about which to make the pattern. This is a 2D vector.
663    pub center: [TyF64; 2],
664    /// The arc angle (in degrees) to place the repetitions. Must be greater than 0.
665    pub arc_degrees: Option<f64>,
666    /// Whether or not to rotate the duplicates as they are copied.
667    pub rotate_duplicates: Option<bool>,
668    /// If the target being patterned is itself a pattern, then, should you use the original solid,
669    /// or the pattern?
670    #[serde(default)]
671    pub use_original: Option<bool>,
672}
673
674/// Data for a circular pattern on a 3D model.
675#[derive(Debug, Clone, Serialize, PartialEq)]
676#[serde(rename_all = "camelCase")]
677struct CircularPattern3dData {
678    /// The number of total instances. Must be greater than or equal to 1.
679    /// This includes the original entity. For example, if instances is 2,
680    /// there will be two copies -- the original, and one new copy.
681    /// If instances is 1, this has no effect.
682    pub instances: u32,
683    /// The axis around which to make the pattern. This is a 3D vector.
684    // Only the direction should matter, not the magnitude so don't adjust units to avoid normalisation issues.
685    pub axis: [f64; 3],
686    /// The center about which to make the pattern. This is a 3D vector.
687    pub center: [TyF64; 3],
688    /// The arc angle (in degrees) to place the repetitions. Must be greater than 0.
689    pub arc_degrees: Option<f64>,
690    /// Whether or not to rotate the duplicates as they are copied.
691    pub rotate_duplicates: Option<bool>,
692    /// If the target being patterned is itself a pattern, then, should you use the original solid,
693    /// or the pattern?
694    #[serde(default)]
695    pub use_original: Option<bool>,
696}
697
698#[allow(clippy::large_enum_variant)]
699enum CircularPattern {
700    ThreeD(CircularPattern3dData),
701    TwoD(CircularPattern2dData),
702}
703
704enum RepetitionsNeeded {
705    /// Add this number of repetitions
706    More(u32),
707    /// No repetitions needed
708    None,
709    /// Invalid number of total instances.
710    Invalid,
711}
712
713impl From<u32> for RepetitionsNeeded {
714    fn from(n: u32) -> Self {
715        match n.cmp(&1) {
716            Ordering::Less => Self::Invalid,
717            Ordering::Equal => Self::None,
718            Ordering::Greater => Self::More(n - 1),
719        }
720    }
721}
722
723impl CircularPattern {
724    pub fn axis(&self) -> [f64; 3] {
725        match self {
726            CircularPattern::TwoD(_lp) => [0.0, 0.0, 0.0],
727            CircularPattern::ThreeD(lp) => [lp.axis[0], lp.axis[1], lp.axis[2]],
728        }
729    }
730
731    pub fn center_mm(&self) -> [f64; 3] {
732        match self {
733            CircularPattern::TwoD(lp) => [lp.center[0].to_mm(), lp.center[1].to_mm(), 0.0],
734            CircularPattern::ThreeD(lp) => [lp.center[0].to_mm(), lp.center[1].to_mm(), lp.center[2].to_mm()],
735        }
736    }
737
738    fn repetitions(&self) -> RepetitionsNeeded {
739        let n = match self {
740            CircularPattern::TwoD(lp) => lp.instances,
741            CircularPattern::ThreeD(lp) => lp.instances,
742        };
743        RepetitionsNeeded::from(n)
744    }
745
746    pub fn arc_degrees(&self) -> Option<f64> {
747        match self {
748            CircularPattern::TwoD(lp) => lp.arc_degrees,
749            CircularPattern::ThreeD(lp) => lp.arc_degrees,
750        }
751    }
752
753    pub fn rotate_duplicates(&self) -> Option<bool> {
754        match self {
755            CircularPattern::TwoD(lp) => lp.rotate_duplicates,
756            CircularPattern::ThreeD(lp) => lp.rotate_duplicates,
757        }
758    }
759
760    pub fn use_original(&self) -> bool {
761        match self {
762            CircularPattern::TwoD(lp) => lp.use_original.unwrap_or_default(),
763            CircularPattern::ThreeD(lp) => lp.use_original.unwrap_or_default(),
764        }
765    }
766}
767
768/// A circular pattern on a 2D sketch.
769pub async fn pattern_circular_2d(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
770    let sketches = args.get_unlabeled_kw_arg("sketches", &RuntimeType::sketches(), exec_state)?;
771    let instances: u32 = args.get_kw_arg("instances", &RuntimeType::count(), exec_state)?;
772    let center: [TyF64; 2] = args.get_kw_arg("center", &RuntimeType::point2d(), exec_state)?;
773    let arc_degrees: Option<TyF64> = args.get_kw_arg_opt("arcDegrees", &RuntimeType::degrees(), exec_state)?;
774    let rotate_duplicates = args.get_kw_arg_opt("rotateDuplicates", &RuntimeType::bool(), exec_state)?;
775    let use_original = args.get_kw_arg_opt("useOriginal", &RuntimeType::bool(), exec_state)?;
776
777    let sketches = inner_pattern_circular_2d(
778        sketches,
779        instances,
780        center,
781        arc_degrees.map(|x| x.n),
782        rotate_duplicates,
783        use_original,
784        exec_state,
785        args,
786    )
787    .await?;
788    Ok(sketches.into())
789}
790
791#[allow(clippy::too_many_arguments)]
792async fn inner_pattern_circular_2d(
793    sketch_set: Vec<Sketch>,
794    instances: u32,
795    center: [TyF64; 2],
796    arc_degrees: Option<f64>,
797    rotate_duplicates: Option<bool>,
798    use_original: Option<bool>,
799    exec_state: &mut ExecState,
800    args: Args,
801) -> Result<Vec<Sketch>, KclError> {
802    let starting_sketches = sketch_set;
803
804    if args.ctx.context_type == crate::execution::ContextType::Mock {
805        return Ok(starting_sketches);
806    }
807    let data = CircularPattern2dData {
808        instances,
809        center,
810        arc_degrees,
811        rotate_duplicates,
812        use_original,
813    };
814
815    let mut sketches = Vec::new();
816    for sketch in starting_sketches.iter() {
817        let geometries = pattern_circular(
818            CircularPattern::TwoD(data.clone()),
819            Geometry::Sketch(sketch.clone()),
820            exec_state,
821            args.clone(),
822        )
823        .await?;
824
825        let Geometries::Sketches(new_sketches) = geometries else {
826            return Err(KclError::new_semantic(KclErrorDetails::new(
827                "Expected a vec of sketches".to_string(),
828                vec![args.source_range],
829            )));
830        };
831
832        sketches.extend(new_sketches);
833    }
834
835    Ok(sketches)
836}
837
838/// A circular pattern on a 3D model.
839pub async fn pattern_circular_3d(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
840    let solids = args.get_unlabeled_kw_arg("solids", &RuntimeType::solids(), exec_state)?;
841    // The number of total instances. Must be greater than or equal to 1.
842    // This includes the original entity. For example, if instances is 2,
843    // there will be two copies -- the original, and one new copy.
844    // If instances is 1, this has no effect.
845    let instances: u32 = args.get_kw_arg("instances", &RuntimeType::count(), exec_state)?;
846    // The axis around which to make the pattern. This is a 3D vector.
847    let axis: Axis3dOrPoint3d = args.get_kw_arg(
848        "axis",
849        &RuntimeType::Union(vec![
850            RuntimeType::Primitive(PrimitiveType::Axis3d),
851            RuntimeType::point3d(),
852        ]),
853        exec_state,
854    )?;
855    let axis = axis.to_point3d();
856
857    // The center about which to make the pattern. This is a 3D vector.
858    let center: [TyF64; 3] = args.get_kw_arg("center", &RuntimeType::point3d(), exec_state)?;
859    // The arc angle (in degrees) to place the repetitions. Must be greater than 0.
860    let arc_degrees: Option<TyF64> = args.get_kw_arg_opt("arcDegrees", &RuntimeType::degrees(), exec_state)?;
861    // Whether or not to rotate the duplicates as they are copied.
862    let rotate_duplicates = args.get_kw_arg_opt("rotateDuplicates", &RuntimeType::bool(), exec_state)?;
863    // If the target being patterned is itself a pattern, then, should you use the original solid,
864    // or the pattern?
865    let use_original = args.get_kw_arg_opt("useOriginal", &RuntimeType::bool(), exec_state)?;
866
867    let solids = inner_pattern_circular_3d(
868        solids,
869        instances,
870        [axis[0].n, axis[1].n, axis[2].n],
871        center,
872        arc_degrees.map(|x| x.n),
873        rotate_duplicates,
874        use_original,
875        exec_state,
876        args,
877    )
878    .await?;
879    Ok(solids.into())
880}
881
882#[allow(clippy::too_many_arguments)]
883async fn inner_pattern_circular_3d(
884    solids: Vec<Solid>,
885    instances: u32,
886    axis: [f64; 3],
887    center: [TyF64; 3],
888    arc_degrees: Option<f64>,
889    rotate_duplicates: Option<bool>,
890    use_original: Option<bool>,
891    exec_state: &mut ExecState,
892    args: Args,
893) -> Result<Vec<Solid>, KclError> {
894    // Flush the batch for our fillets/chamfers if there are any.
895    // If we do not flush these, then you won't be able to pattern something with fillets.
896    // Flush just the fillets/chamfers that apply to these solids.
897    exec_state
898        .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, &args), &solids)
899        .await?;
900
901    let starting_solids = solids;
902
903    if args.ctx.context_type == crate::execution::ContextType::Mock {
904        return Ok(starting_solids);
905    }
906
907    let mut solids = Vec::new();
908    let data = CircularPattern3dData {
909        instances,
910        axis,
911        center,
912        arc_degrees,
913        rotate_duplicates,
914        use_original,
915    };
916    for solid in starting_solids.iter() {
917        let geometries = pattern_circular(
918            CircularPattern::ThreeD(data.clone()),
919            Geometry::Solid(solid.clone()),
920            exec_state,
921            args.clone(),
922        )
923        .await?;
924
925        let Geometries::Solids(new_solids) = geometries else {
926            return Err(KclError::new_semantic(KclErrorDetails::new(
927                "Expected a vec of solids".to_string(),
928                vec![args.source_range],
929            )));
930        };
931
932        solids.extend(new_solids);
933    }
934
935    Ok(solids)
936}
937
938async fn pattern_circular(
939    data: CircularPattern,
940    geometry: Geometry,
941    exec_state: &mut ExecState,
942    args: Args,
943) -> Result<Geometries, KclError> {
944    let num_repetitions = match data.repetitions() {
945        RepetitionsNeeded::More(n) => n,
946        RepetitionsNeeded::None => {
947            return Ok(Geometries::from(geometry));
948        }
949        RepetitionsNeeded::Invalid => {
950            return Err(KclError::new_semantic(KclErrorDetails::new(
951                MUST_HAVE_ONE_INSTANCE.to_owned(),
952                vec![args.source_range],
953            )));
954        }
955    };
956
957    let center = data.center_mm();
958    let resp = exec_state
959        .send_modeling_cmd(
960            ModelingCmdMeta::from_args(exec_state, &args),
961            ModelingCmd::from(
962                mcmd::EntityCircularPattern::builder()
963                    .axis(kcmc::shared::Point3d::from(data.axis()))
964                    .entity_id(if data.use_original() {
965                        geometry.original_id()
966                    } else {
967                        geometry.id()
968                    })
969                    .center(kcmc::shared::Point3d {
970                        x: LengthUnit(center[0]),
971                        y: LengthUnit(center[1]),
972                        z: LengthUnit(center[2]),
973                    })
974                    .num_repetitions(num_repetitions)
975                    .arc_degrees(data.arc_degrees().unwrap_or(360.0))
976                    .rotate_duplicates(data.rotate_duplicates().unwrap_or(true))
977                    .build(),
978            ),
979        )
980        .await?;
981
982    // The common case is borrowing from the response.  Instead of cloning,
983    // create a Vec to borrow from in mock mode.
984    let mut mock_ids = Vec::new();
985    let entity_ids = if let OkWebSocketResponseData::Modeling {
986        modeling_response: OkModelingCmdResponse::EntityCircularPattern(pattern_info),
987    } = &resp
988    {
989        &pattern_info.entity_face_edge_ids.iter().map(|e| e.object_id).collect()
990    } else if args.ctx.no_engine_commands().await {
991        mock_ids.reserve(num_repetitions as usize);
992        for _ in 0..num_repetitions {
993            mock_ids.push(exec_state.next_uuid());
994        }
995        &mock_ids
996    } else {
997        return Err(KclError::new_engine(KclErrorDetails::new(
998            format!("EntityCircularPattern response was not as expected: {resp:?}"),
999            vec![args.source_range],
1000        )));
1001    };
1002
1003    let geometries = match geometry {
1004        Geometry::Sketch(sketch) => {
1005            let mut geometries = vec![sketch.clone()];
1006            for id in entity_ids.iter().copied() {
1007                let mut new_sketch = sketch.clone();
1008                new_sketch.id = id;
1009                geometries.push(new_sketch);
1010            }
1011            Geometries::Sketches(geometries)
1012        }
1013        Geometry::Solid(solid) => {
1014            let mut geometries = vec![solid.clone()];
1015            for id in entity_ids.iter().copied() {
1016                let mut new_solid = solid.clone();
1017                new_solid.id = id;
1018                geometries.push(new_solid);
1019            }
1020            Geometries::Solids(geometries)
1021        }
1022    };
1023
1024    Ok(geometries)
1025}