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
use ahash::AHashSet;
use kcmc::ModelingCmd;
use kittycad_modeling_cmds::websocket::ModelingCmdReq;
use kittycad_modeling_cmds::websocket::OkWebSocketResponseData;
use kittycad_modeling_cmds::{self as kcmc};
use uuid::Uuid;

use crate::ExecState;
use crate::ExecutorContext;
use crate::KclError;
use crate::SourceRange;
use crate::errors::KclErrorDetails;
use crate::exec::ArtifactCommand;
use crate::exec::IdGenerator;
use crate::exec::KclValue;
use crate::execution::EntityCloneInfo;
use crate::execution::FaceParentSolid;
use crate::execution::Solid;
use crate::std::Args;

/// Developer toggle for the KCL 3.0 behavior where edge cuts (fillets and
/// chamfers) are sent to the engine immediately, in program order with other
/// modeling commands, instead of being deferred to the end of the batch.
///
/// Set this to `false` to restore the deferred behavior for every KCL version
/// while the immediate behavior is being evaluated. The KCL version gate in
/// [`ExecState::edge_cuts_are_immediate`] still applies when this is `true`.
pub(crate) const IMMEDIATE_EDGE_CUTS_IN_V3: bool = true;

/// Context and metadata needed to send a single modeling command.
///
/// Many functions consume Self so that the command ID isn't accidentally reused
/// among multiple modeling commands.
pub(crate) struct ModelingCmdMeta<'a> {
    /// The executor context, which contains the engine.
    pub ctx: &'a ExecutorContext,
    /// The source range of the command, used for error reporting.
    pub source_range: SourceRange,
    /// The id of the command, if it has been set by the caller or generated.
    id: Option<Uuid>,
}

impl<'a> ModelingCmdMeta<'a> {
    pub fn new(exec_state: &ExecState, ctx: &'a ExecutorContext, range: SourceRange) -> Self {
        ModelingCmdMeta {
            ctx,
            source_range: exec_state.mod_local.stdlib_entry_source_range.unwrap_or(range),
            id: None,
        }
    }

    pub fn with_id(exec_state: &ExecState, ctx: &'a ExecutorContext, range: SourceRange, id: Uuid) -> Self {
        ModelingCmdMeta {
            ctx,
            source_range: exec_state.mod_local.stdlib_entry_source_range.unwrap_or(range),
            id: Some(id),
        }
    }

    pub fn from_args(exec_state: &ExecState, args: &'a Args) -> Self {
        ModelingCmdMeta {
            ctx: &args.ctx,
            source_range: exec_state
                .mod_local
                .stdlib_entry_source_range
                .unwrap_or(args.source_range),
            id: None,
        }
    }

    pub fn from_args_id(exec_state: &ExecState, args: &'a Args, id: Uuid) -> Self {
        ModelingCmdMeta {
            ctx: &args.ctx,
            source_range: exec_state
                .mod_local
                .stdlib_entry_source_range
                .unwrap_or(args.source_range),
            id: Some(id),
        }
    }

    pub fn id(&mut self, id_generator: &mut IdGenerator) -> Uuid {
        if let Some(id) = self.id {
            return id;
        }
        let id = id_generator.next_uuid();
        self.id = Some(id);
        id
    }
}

impl ExecState {
    /// Add a modeling command to the batch but don't fire it right away.
    pub(crate) async fn batch_modeling_cmd(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        cmd: ModelingCmd,
    ) -> Result<(), KclError> {
        self.batch_modeling_cmd_with_entity_clone_info(meta, cmd, None).await
    }

    pub(crate) async fn batch_modeling_cmd_with_entity_clone_info(
        &mut self,
        mut meta: ModelingCmdMeta<'_>,
        cmd: ModelingCmd,
        entity_clone_info: Option<EntityCloneInfo>,
    ) -> Result<(), KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        let id = meta.id(self.id_generator());
        self.push_command(ArtifactCommand {
            cmd_id: id,
            range: meta.source_range,
            command: cmd.clone(),
            entity_clone_info,
            omit_from_graph: false,
        });
        meta.ctx
            .engine
            .batch_modeling_cmd(&meta.ctx.engine_batch, id, meta.source_range, &cmd)
            .await
    }

    /// Add multiple modeling commands to the batch but don't fire them right
    /// away.
    pub(crate) async fn batch_modeling_cmds(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        cmds: &[ModelingCmdReq],
    ) -> Result<(), KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        for cmd_req in cmds {
            self.push_command(ArtifactCommand {
                cmd_id: *cmd_req.cmd_id.as_ref(),
                range: meta.source_range,
                command: cmd_req.cmd.clone(),
                entity_clone_info: None,
                omit_from_graph: false,
            });
        }
        meta.ctx
            .engine
            .batch_modeling_cmds(&meta.ctx.engine_batch, meta.source_range, cmds)
            .await
    }

    /// Whether edge cuts (fillets and chamfers) are sent to the engine in
    /// program order, like any other modeling command.
    ///
    /// KCL 3.0: edge cuts execute immediately. Earlier versions defer them to
    /// the end of the batch; see [`Self::batch_end_cmd`]. This never varies
    /// within a single execution because it is keyed on the entry point's
    /// declared version.
    pub(crate) fn edge_cuts_are_immediate(&self) -> bool {
        IMMEDIATE_EDGE_CUTS_IN_V3 && self.entry_point_version_is_v3_or_higher()
    }

    /// Add an edge cut (fillet or chamfer) modeling command to the batch.
    ///
    /// KCL 3.0: the command is batched in order with other modeling commands,
    /// so it executes before whatever the program does next. The engine
    /// replaces a cut edge with a new face, so a later reference to that edge
    /// (for example `getOppositeEdge`) fails, matching the order the user
    /// wrote.
    ///
    /// Before KCL 3.0, the command is deferred to the end of the batch so that
    /// later references to the cut edge still resolve; see
    /// [`Self::batch_end_cmd`].
    pub(crate) async fn batch_edge_cut_cmd(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        cmd: ModelingCmd,
    ) -> Result<(), KclError> {
        if self.edge_cuts_are_immediate() {
            self.batch_modeling_cmd(meta, cmd).await
        } else {
            self.batch_end_cmd(meta, cmd).await
        }
    }

    /// Add a modeling command to the batch that gets executed at the end of the
    /// file. This is good for something like fillet or chamfer where the engine
    /// would eat the path id if we executed it right away.
    pub(crate) async fn batch_end_cmd(
        &mut self,
        mut meta: ModelingCmdMeta<'_>,
        cmd: ModelingCmd,
    ) -> Result<(), KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        let id = meta.id(self.id_generator());
        // TODO: The order of the tracking of these doesn't match the order that
        // they're sent to the engine.
        self.push_command(ArtifactCommand {
            cmd_id: id,
            range: meta.source_range,
            command: cmd.clone(),
            entity_clone_info: None,
            omit_from_graph: false,
        });
        meta.ctx
            .engine
            .batch_end_cmd(&meta.ctx.engine_batch, id, meta.source_range, &cmd)
            .await
    }

    /// Send the modeling cmd and wait for the response.
    pub(crate) async fn send_modeling_cmd(
        &mut self,
        mut meta: ModelingCmdMeta<'_>,
        cmd: ModelingCmd,
    ) -> Result<OkWebSocketResponseData, KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        let id = meta.id(self.id_generator());
        self.push_command(ArtifactCommand {
            cmd_id: id,
            range: meta.source_range,
            command: cmd.clone(),
            entity_clone_info: None,
            omit_from_graph: false,
        });
        meta.ctx
            .engine
            .send_modeling_cmd(&meta.ctx.engine_batch, id, meta.source_range, &cmd)
            .await
    }

    /// Send a query-only modeling command that is recorded in command snapshots
    /// but omitted from the semantic artifact graph.
    pub(crate) async fn send_untracked_modeling_cmd(
        &mut self,
        mut meta: ModelingCmdMeta<'_>,
        cmd: ModelingCmd,
    ) -> Result<OkWebSocketResponseData, KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        let id = meta.id(self.id_generator());
        self.push_command(ArtifactCommand {
            cmd_id: id,
            range: meta.source_range,
            command: cmd.clone(),
            entity_clone_info: None,
            omit_from_graph: true,
        });
        meta.ctx
            .engine
            .send_modeling_cmd(&meta.ctx.engine_batch, id, meta.source_range, &cmd)
            .await
    }

    /// Send the modeling cmd async and don't wait for the response.
    /// Add it to our list of async commands.
    pub(crate) async fn async_modeling_cmd(
        &mut self,
        mut meta: ModelingCmdMeta<'_>,
        cmd: &ModelingCmd,
    ) -> Result<(), KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        let id = meta.id(self.id_generator());
        let tracked_command = match cmd {
            ModelingCmd::ImportFiles(import_files) => {
                // Graph construction does not read imported file bytes. Retain the file paths
                // and format in execution state without duplicating the full input payload.
                let mut tracked_import = import_files.clone();
                for file in &mut tracked_import.files {
                    file.data.clear();
                }
                ModelingCmd::ImportFiles(tracked_import)
            }
            _ => cmd.clone(),
        };
        self.push_command(ArtifactCommand {
            cmd_id: id,
            range: meta.source_range,
            command: tracked_command,
            entity_clone_info: None,
            omit_from_graph: false,
        });
        meta.ctx.engine.async_modeling_cmd(id, meta.source_range, cmd).await
    }

    /// Force flush the batch queue.
    pub(crate) async fn flush_batch(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        // Whether or not to flush the end commands as well.
        // We only do this at the very end of the file.
        batch_end: bool,
    ) -> Result<OkWebSocketResponseData, KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        meta.ctx
            .engine
            .flush_batch(&meta.ctx.engine_batch, batch_end, meta.source_range)
            .await
    }

    /// Flush just the fillets and chamfers for this specific SolidSet.
    pub(crate) async fn flush_batch_for_solids(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        solids: &[Solid],
    ) -> Result<(), KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        // Make sure we don't traverse sketches more than once.
        let mut traversed_sketches = AHashSet::new();

        // Collect all the fillet/chamfer ids for the solids.
        let mut ids = Vec::new();
        for solid in solids {
            // We need to traverse the solids that share the same sketch.
            let sketch_id = solid.sketch_id().unwrap_or(solid.id);
            if !traversed_sketches.contains(&sketch_id) {
                // Find all the solids on the same shared sketch.
                ids.extend(
                    self.stack()
                        .walk_call_stack_with(|value| match value {
                            KclValue::Solid { value } if value.sketch_id().unwrap_or(value.id) == sketch_id => {
                                Some(value.get_all_edge_cut_ids().collect::<Vec<_>>())
                            }
                            _ => None,
                        })?
                        .into_iter()
                        .flatten(),
                );
                traversed_sketches.insert(sketch_id);
            }

            ids.extend(solid.get_all_edge_cut_ids());
        }

        self.flush_batch_for_edge_cut_ids(meta, ids).await
    }

    /// Flush just the fillets and chamfers for the parent solids of face-backed sketches.
    pub(crate) async fn flush_batch_for_face_parent_solids(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        solids: &[FaceParentSolid],
    ) -> Result<(), KclError> {
        if self.is_in_sketch_block() {
            return Err(no_modeling_in_sketch_block_error(meta.source_range));
        }
        // Make sure we don't traverse sketches more than once.
        let mut traversed_sketches = AHashSet::new();

        // Collect all the fillet/chamfer ids for the solids.
        let mut ids = Vec::new();
        for solid in solids {
            // We need to traverse the solids that share the same sketch.
            let sketch_id = solid.sketch_or_solid_id();
            if !traversed_sketches.contains(&sketch_id) {
                // Find all the solids on the same shared sketch.
                ids.extend(
                    self.stack()
                        .walk_call_stack_with(|value| match value {
                            KclValue::Solid { value } if value.sketch_id().unwrap_or(value.id) == sketch_id => {
                                Some(value.get_all_edge_cut_ids().collect::<Vec<_>>())
                            }
                            _ => None,
                        })?
                        .into_iter()
                        .flatten(),
                );
                traversed_sketches.insert(sketch_id);
            }

            ids.extend(solid.edge_cut_ids.iter().copied());
        }

        self.flush_batch_for_edge_cut_ids(meta, ids).await
    }

    async fn flush_batch_for_edge_cut_ids(
        &mut self,
        meta: ModelingCmdMeta<'_>,
        ids: Vec<Uuid>,
    ) -> Result<(), KclError> {
        // We can return early if there are no fillets or chamfers.
        if ids.is_empty() {
            return Ok(());
        }

        // We want to move these fillets and chamfers from batch_end to batch so they get executed
        // before whatever we call next.
        meta.ctx.engine_batch.move_batch_end_to_batch(ids).await;

        // Run flush.
        // Yes, we do need to actually flush the batch here, or references will fail later.
        self.flush_batch(meta, false).await?;

        Ok(())
    }
}

fn no_modeling_in_sketch_block_error(range: SourceRange) -> KclError {
    KclError::new_invalid_expression(KclErrorDetails::new(
        "Modeling commands communicating with the engine cannot be used inside a sketch block".to_owned(),
        vec![range],
    ))
}