kcl-lib 0.2.186

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Standard library appearance.

use std::collections::HashSet;

use anyhow::Result;
use kcmc::ModelingCmd;
use kcmc::each_cmd as mcmd;
use kittycad_modeling_cmds::length_unit::LengthUnit;
use kittycad_modeling_cmds::ok_response::OkModelingCmdResponse;
use kittycad_modeling_cmds::output as mout;
use kittycad_modeling_cmds::shared::BodyType;
use kittycad_modeling_cmds::shared::FractionOfEdge;
use kittycad_modeling_cmds::shared::SurfaceEdgeReference;
use kittycad_modeling_cmds::websocket::OkWebSocketResponseData;
use kittycad_modeling_cmds::{self as kcmc};

use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::execution::BoundedEdge;
use crate::execution::ConsumedSolidOperation;
use crate::execution::ExecState;
use crate::execution::KclValue;
use crate::execution::ModelingCmdMeta;
use crate::execution::Solid;
use crate::execution::SolidCreator;
use crate::execution::types::ArrayLen;
use crate::execution::types::PrimitiveType;
use crate::execution::types::RuntimeType;
use crate::std::Args;
use crate::std::DEFAULT_TOLERANCE_MM;
use crate::std::args::TyF64;
use crate::std::edge;
use crate::std::sketch::FaceTag;
use crate::std::solid_consumption::record_consumed_solids;

/// Flips the orientation of a surface, swapping which side is the front and which is the reverse.
pub async fn flip_surface(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let surface = args.get_unlabeled_kw_arg("surface", &RuntimeType::solids(), exec_state)?;
    let out = inner_flip_surface(surface, exec_state, args).await?;
    Ok(out.into())
}

async fn inner_flip_surface(
    surfaces: Vec<Solid>,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Vec<Solid>, KclError> {
    for surface in &surfaces {
        exec_state
            .batch_modeling_cmd(
                ModelingCmdMeta::from_args(exec_state, &args),
                ModelingCmd::from(mcmd::Solid3dFlip::builder().object_id(surface.id).build()),
            )
            .await?;
    }

    Ok(surfaces)
}

/// Check if this object is a solid or not.
pub async fn is_solid(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let argument = args.get_unlabeled_kw_arg("body", &RuntimeType::solid(), exec_state)?;
    let meta = vec![crate::execution::Metadata {
        source_range: args.source_range,
    }];

    let res = inner_is_equal_body_type(argument, exec_state, args, BodyType::Solid).await?;
    Ok(KclValue::Bool { value: res, meta })
}

/// Check if this object is a surface or not.
pub async fn is_surface(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let argument = args.get_unlabeled_kw_arg("body", &RuntimeType::solid(), exec_state)?;
    let meta = vec![crate::execution::Metadata {
        source_range: args.source_range,
    }];

    let res = inner_is_equal_body_type(argument, exec_state, args, BodyType::Surface).await?;
    Ok(KclValue::Bool { value: res, meta })
}

async fn inner_is_equal_body_type(
    surface: Solid,
    exec_state: &mut ExecState,
    args: Args,
    expected: BodyType,
) -> Result<bool, KclError> {
    if args.ctx.no_engine_commands().await {
        // In mock execution, we can't query the surface type and know it for real.
        // So just give a best-effort attempt to figure out the surface/solid type.
        return if let Some(body_type) = surface.best_guess_body_type {
            Ok(expected == body_type)
        } else {
            // No body type known, so we don't know whether this is true or false.
            // Best effort guess is false.
            // Hopefully shouldn't matter to mock execution.
            Ok(false)
        };
    }

    Ok(expected == query_body_type(&surface, exec_state, &args).await?)
}

pub(crate) async fn query_body_type(
    surface: &Solid,
    exec_state: &mut ExecState,
    args: &Args,
) -> Result<BodyType, KclError> {
    let meta = ModelingCmdMeta::from_args(exec_state, args);
    let cmd = ModelingCmd::from(mcmd::Solid3dGetBodyType::builder().object_id(surface.id).build());

    let response = exec_state.send_modeling_cmd(meta, cmd).await?;

    let OkWebSocketResponseData::Modeling {
        modeling_response: OkModelingCmdResponse::Solid3dGetBodyType(body),
    } = response
    else {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            format!(
                "Engine returned invalid response, it should have returned Solid3dGetBodyType but it returned {response:#?}"
            ),
            vec![args.source_range],
        )));
    };

    Ok(body.body_type)
}

pub async fn delete_face(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let body = args.get_unlabeled_kw_arg("body", &RuntimeType::solid(), exec_state)?;
    let faces: Option<Vec<FaceTag>> = args.get_kw_arg_opt(
        "faces",
        &RuntimeType::Array(Box::new(RuntimeType::tagged_face()), ArrayLen::Minimum(1)),
        exec_state,
    )?;
    let face_indices: Option<Vec<TyF64>> = args.get_kw_arg_opt(
        "faceIndices",
        &RuntimeType::Array(Box::new(RuntimeType::count()), ArrayLen::Minimum(1)),
        exec_state,
    )?;
    let face_indices = if let Some(face_indices) = face_indices {
        let faces = face_indices
            .into_iter()
            .map(|num| {
                crate::try_f64_to_u32(num.n).ok_or_else(|| {
                    KclError::new_semantic(KclErrorDetails::new(
                        format!("Face indices must be whole numbers, got {}", num.n),
                        vec![args.source_range],
                    ))
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Some(faces)
    } else {
        None
    };
    inner_delete_face(body, faces, face_indices, exec_state, args)
        .await
        .map(Box::new)
        .map(|value| KclValue::Solid { value })
}

async fn inner_delete_face(
    mut body: Solid,
    tagged_faces: Option<Vec<FaceTag>>,
    face_indices: Option<Vec<u32>>,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Solid, KclError> {
    // Validate args:
    // User has to give us SOMETHING to delete.
    if tagged_faces.is_none() && face_indices.is_none() {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            "You must use either the `faces` or the `faceIndices` parameter".to_string(),
            vec![args.source_range],
        )));
    }

    // Early return for mock response, just return the same solid.
    // If we tracked faces, we would remove some faces... but we don't really.
    let no_engine_commands = args.ctx.no_engine_commands().await;
    if no_engine_commands {
        return Ok(body);
    }

    // Chamfers and fillets are batched until the end of the file so they do not
    // invalidate source edge IDs too early. If deleteFace targets one of those
    // generated faces, the edge cut must be flushed before the delete command
    // references it.
    exec_state
        .flush_batch_for_solids(
            ModelingCmdMeta::from_args(exec_state, &args),
            std::slice::from_ref(&body),
        )
        .await?;

    // Combine the list of faces, both tagged and indexed.
    let tagged_faces = tagged_faces.unwrap_or_default();
    let face_indices = face_indices.unwrap_or_default();
    // Get the face's ID
    let mut face_ids = HashSet::with_capacity(face_indices.len() + tagged_faces.len());

    for tagged_face in tagged_faces {
        let face_id = tagged_face.get_face_id(&body, exec_state, &args, false).await?;
        face_ids.insert(face_id);
    }

    for face_index in face_indices {
        let face_uuid_response = exec_state
            .send_modeling_cmd(
                ModelingCmdMeta::from_args(exec_state, &args),
                ModelingCmd::from(
                    mcmd::Solid3dGetFaceUuid::builder()
                        .object_id(body.id)
                        .face_index(face_index)
                        .build(),
                ),
            )
            .await?;

        let OkWebSocketResponseData::Modeling {
            modeling_response: OkModelingCmdResponse::Solid3dGetFaceUuid(inner_resp),
        } = face_uuid_response
        else {
            return Err(KclError::new_semantic(KclErrorDetails::new(
                format!(
                    "Engine returned invalid response, it should have returned Solid3dGetFaceUuid but it returned {face_uuid_response:?}"
                ),
                vec![args.source_range],
            )));
        };
        face_ids.insert(inner_resp.face_id);
    }

    // Now that we've got all the faces, delete them all.
    let delete_face_response = exec_state
        .send_modeling_cmd(
            ModelingCmdMeta::from_args(exec_state, &args),
            ModelingCmd::from(
                mcmd::EntityDeleteChildren::builder()
                    .entity_id(body.id)
                    .child_entity_ids(face_ids)
                    .build(),
            ),
        )
        .await?;

    let OkWebSocketResponseData::Modeling {
        modeling_response: OkModelingCmdResponse::EntityDeleteChildren(mout::EntityDeleteChildren { .. }),
    } = delete_face_response
    else {
        return Err(KclError::new_semantic(KclErrorDetails::new(
            format!(
                "Engine returned invalid response, it should have returned EntityDeleteChildren but it returned {delete_face_response:?}"
            ),
            vec![args.source_range],
        )));
    };

    // Return the same body, it just has fewer faces.
    // And it's _probably_ a polysurface now, because if it was a solid before,
    // it's _probably_ a surface after some required face was deleted and the volume
    // is no longer closed. If it was a surface before, it's still a surface.
    body.best_guess_body_type = Some(BodyType::Surface);
    Ok(body)
}

/// Create a new surface that blends between two edges of separate surface bodies
pub async fn blend(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let edges: Vec<KclValue> = args.get_unlabeled_kw_arg(
        "edges",
        &RuntimeType::Array(
            Box::new(RuntimeType::Union(vec![
                RuntimeType::Primitive(PrimitiveType::BoundedEdge),
                RuntimeType::tagged_edge(),
                RuntimeType::Primitive(PrimitiveType::Any),
            ])),
            ArrayLen::Known(2),
        ),
        exec_state,
    )?;

    let mut bounded_edges = Vec::with_capacity(edges.len());
    for edge in edges {
        bounded_edges.push(resolve_blend_edge(edge, exec_state, &args).await?);
    }

    inner_blend(bounded_edges, exec_state, args.clone())
        .await
        .map(Box::new)
        .map(|value| KclValue::Solid { value })
}

/// When edge specifiers are used, the first face in `sideFaces` is used in the
/// [`BoundedEdge`] struct.
async fn resolve_blend_edge(edge: KclValue, exec_state: &mut ExecState, args: &Args) -> Result<BoundedEdge, KclError> {
    match edge {
        KclValue::BoundedEdge { value, .. } => Ok(value),
        KclValue::TagIdentifier(tag) => {
            let tagged_edge = args.get_tag_engine_info(exec_state, &tag)?;
            Ok(BoundedEdge {
                face_id: tagged_edge.geometry.id(),
                edge_id: Some(tagged_edge.id),
                edge_specifier: None,
                lower_bound: 0.0,
                upper_bound: 1.0,
            })
        }
        KclValue::Object { value: obj, .. } => {
            let spec = edge::parse_edge_specifier_object(&obj, args)?;
            let face_id = edge::face_id_from_first_side_face(&spec, exec_state, args)?;
            Ok(BoundedEdge {
                face_id,
                edge_id: None,
                edge_specifier: Some(spec),
                lower_bound: 0.0,
                upper_bound: 1.0,
            })
        }
        _ => Err(KclError::new_internal(KclErrorDetails::new(
            "Unexpected edge value while preparing blend edges. Expected BoundedEdge, tagged edge, or edge specifier object (e.g. { sideFaces = [...], endFaces = [...], index = 0 }).".to_owned(),
            vec![args.source_range],
        ))),
    }
}

async fn inner_blend(edges: Vec<BoundedEdge>, exec_state: &mut ExecState, args: Args) -> Result<Solid, KclError> {
    let id = exec_state.next_uuid();

    let mut surface_refs = Vec::with_capacity(edges.len());
    for edge in &edges {
        let fraction = if let Some(eid) = edge.edge_id {
            FractionOfEdge::builder()
                .edge_id(eid)
                .lower_bound(edge.lower_bound)
                .upper_bound(edge.upper_bound)
                .build()
        } else if let Some(ref spec) = edge.edge_specifier {
            let resolved = edge::resolve_unresolved_edge_specifier(edge.face_id, spec, exec_state, &args).await?;
            FractionOfEdge::builder()
                .edge_specifier(resolved)
                .lower_bound(edge.lower_bound)
                .upper_bound(edge.upper_bound)
                .build()
        } else {
            return Err(KclError::new_internal(KclErrorDetails::new(
                "BoundedEdge must have edge_id or edge_specifier".to_owned(),
                vec![args.source_range],
            )));
        };
        surface_refs.push(
            SurfaceEdgeReference::builder()
                .object_id(edge.face_id)
                .edges(vec![fraction])
                .build(),
        );
    }

    exec_state
        .batch_modeling_cmd(
            ModelingCmdMeta::from_args_id(exec_state, &args, id),
            ModelingCmd::from(mcmd::SurfaceBlend::builder().surfaces(surface_refs).build()),
        )
        .await?;

    let solid = Solid {
        id,
        value_id: id,
        topology_id: id,
        pattern_source_artifact_id: None,
        best_guess_body_type: Some(BodyType::Surface),
        artifact_id: id.into(),
        value: vec![],
        faces: Default::default(),
        creator: SolidCreator::Procedural,
        start_cap_id: None,
        end_cap_id: None,
        edge_cuts: vec![],
        pending_edge_cut_ids: vec![],
        units: exec_state.length_unit(),
        sectional: false,
        meta: vec![crate::execution::Metadata {
            source_range: args.source_range,
        }],
    };
    //TODO: How do we pass back the two new edge ids that were created?
    Ok(solid)
}

/// Stitch multiple surfaces together into one polysurface
pub async fn join(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
    let selection: Vec<Solid> = args.get_unlabeled_kw_arg("selection", &RuntimeType::solids(), exec_state)?;
    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;

    inner_join(selection, tolerance, exec_state, args)
        .await
        .map(Box::new)
        .map(|value| KclValue::Solid { value })
}

async fn inner_join(
    selection: Vec<Solid>,
    tolerance: Option<TyF64>,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Solid, KclError> {
    if selection.len() == 1 {
        let cmd = mcmd::Solid3dJoin::builder().object_id(selection[0].id).build();

        exec_state
            .batch_modeling_cmd(ModelingCmdMeta::from_args(exec_state, &args), ModelingCmd::from(cmd))
            .await?;

        Ok(selection[0].clone())
    } else {
        let body_out_id = exec_state.next_uuid();

        exec_state
            .flush_batch_for_solids(ModelingCmdMeta::from_args(exec_state, &args), &selection)
            .await?;

        let body_ids = selection.iter().map(|body| body.id).collect();
        let tolerance = tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM);
        let cmd = mcmd::Solid3dMultiJoin::builder()
            .object_ids(body_ids)
            .tolerance(LengthUnit(tolerance))
            .build();

        exec_state
            .batch_modeling_cmd(
                ModelingCmdMeta::from_args_id(exec_state, &args, body_out_id),
                ModelingCmd::from(cmd),
            )
            .await?;

        let solid = Solid {
            id: body_out_id,
            value_id: body_out_id,
            topology_id: body_out_id,
            pattern_source_artifact_id: None,
            best_guess_body_type: None,
            artifact_id: body_out_id.into(),
            value: vec![],
            faces: Default::default(),
            creator: SolidCreator::Procedural,
            start_cap_id: None,
            end_cap_id: None,
            edge_cuts: vec![],
            pending_edge_cut_ids: vec![],
            units: exec_state.length_unit(),
            sectional: false,
            meta: vec![args.source_range.into()],
        };
        record_consumed_solids(
            exec_state,
            &selection,
            ConsumedSolidOperation::JoinSurfaces,
            std::slice::from_ref(&solid),
        );
        Ok(solid)
    }
}

#[cfg(test)]
mod tests {
    use crate::execution::MockConfig;

    #[tokio::test(flavor = "multi_thread")]
    async fn mock_body_type_queries_use_locally_known_type() {
        let code = r#"
@settings(defaultLengthUnit = mm, kclVersion = 2.0)

solidSketch = sketch(on = XY) {
  profile = circle(
    start = [var 5mm, var 0mm],
    center = [var 0mm, var 0mm],
  )
}
solid = extrude(
  region(segments = [solidSketch.profile]),
  length = 5mm,
  bodyType = "solid",
)

surfaceSketch = sketch(on = XY) {
  profile = circle(
    start = [var 20mm, var 0mm],
    center = [var 15mm, var 0mm],
  )
}
surface = extrude(
  region(segments = [surfaceSketch.profile]),
  length = 5mm,
  bodyType = "surface",
)

assertIs(isSolid(solid))
assertIs(!isSurface(solid))
assertIs(isSurface(surface))
assertIs(!isSolid(surface))
"#;

        let program = crate::Program::parse_no_errs(code).unwrap();
        let ctx = crate::ExecutorContext::new_mock(None).await;
        let result = ctx.run_mock(&program, &MockConfig::default()).await;
        ctx.close().await;
        result.unwrap();
    }
}