1use std::num::NonZeroU32;
4
5use anyhow::Result;
6use kcmc::ModelingCmd;
7use kcmc::each_cmd as mcmd;
8use kcmc::length_unit::LengthUnit;
9use kcmc::shared::BodyType;
10use kittycad_modeling_cmds as kcmc;
11
12use super::DEFAULT_TOLERANCE_MM;
13use super::args::TyF64;
14use crate::errors::KclError;
15use crate::errors::KclErrorDetails;
16use crate::execution::ExecState;
17use crate::execution::ExecutorContext;
18use crate::execution::KclValue;
19use crate::execution::ModelingCmdMeta;
20use crate::execution::ProfileClosed;
21use crate::execution::Sketch;
22use crate::execution::Solid;
23use crate::execution::types::ArrayLen;
24use crate::execution::types::RuntimeType;
25use crate::parsing::ast::types::TagNode;
26use crate::std::Args;
27use crate::std::args::FromKclValue;
28use crate::std::extrude::build_segment_surface_sketch;
29use crate::std::extrude::do_post_extrude;
30
31const DEFAULT_V_DEGREE: u32 = 2;
32
33pub async fn loft(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
35 let sketch_values: Vec<KclValue> = args.get_unlabeled_kw_arg(
36 "sketches",
37 &RuntimeType::Array(
38 Box::new(RuntimeType::Union(vec![RuntimeType::sketch(), RuntimeType::segment()])),
39 ArrayLen::Minimum(2),
40 ),
41 exec_state,
42 )?;
43 let v_degree: NonZeroU32 = args
44 .get_kw_arg_opt("vDegree", &RuntimeType::count(), exec_state)?
45 .unwrap_or(NonZeroU32::new(DEFAULT_V_DEGREE).unwrap());
46 let bez_approximate_rational = args
50 .get_kw_arg_opt("bezApproximateRational", &RuntimeType::bool(), exec_state)?
51 .unwrap_or(false);
52 let base_curve_index: Option<u32> = args.get_kw_arg_opt("baseCurveIndex", &RuntimeType::count(), exec_state)?;
54 let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
56 let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
57 let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
58 let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
59
60 let sketches = coerce_loft_targets(
61 sketch_values,
62 body_type.unwrap_or_default(),
63 tag_start.as_ref(),
64 tag_end.as_ref(),
65 exec_state,
66 &args.ctx,
67 args.source_range,
68 )
69 .await?;
70 let value = inner_loft(
71 sketches,
72 v_degree,
73 bez_approximate_rational,
74 base_curve_index,
75 tolerance,
76 tag_start,
77 tag_end,
78 body_type,
79 exec_state,
80 args,
81 )
82 .await?;
83 Ok(KclValue::Solid { value })
84}
85
86async fn coerce_loft_targets(
87 sketch_values: Vec<KclValue>,
88 body_type: BodyType,
89 tag_start: Option<&TagNode>,
90 tag_end: Option<&TagNode>,
91 exec_state: &mut ExecState,
92 ctx: &ExecutorContext,
93 source_range: crate::SourceRange,
94) -> Result<Vec<Sketch>, KclError> {
95 let mut sketches = Vec::new();
96 let mut segments = Vec::new();
97
98 for value in sketch_values {
99 if let Some(segment) = value.clone().into_segment() {
100 segments.push(segment);
101 continue;
102 }
103
104 let Some(sketch) = Sketch::from_kcl_val(&value) else {
105 return Err(KclError::new_type(KclErrorDetails::new(
106 "Expected sketches or solved sketch segments for loft.".to_owned(),
107 vec![source_range],
108 )));
109 };
110 sketches.push(sketch);
111 }
112
113 if !segments.is_empty() && !sketches.is_empty() {
114 return Err(KclError::new_semantic(KclErrorDetails::new(
115 "Cannot loft sketch segments together with sketches in the same call. Use separate `loft()` calls."
116 .to_owned(),
117 vec![source_range],
118 )));
119 }
120
121 if !segments.is_empty() {
122 if !matches!(body_type, BodyType::Surface) {
123 return Err(KclError::new_semantic(KclErrorDetails::new(
124 "Lofting sketch segments is only supported for surface lofts. Set `bodyType = SURFACE`.".to_owned(),
125 vec![source_range],
126 )));
127 }
128
129 if tag_start.is_some() || tag_end.is_some() {
130 return Err(KclError::new_semantic(KclErrorDetails::new(
131 "`tagStart` and `tagEnd` are not supported when lofting sketch segments. Segment surface lofts do not create start or end caps."
132 .to_owned(),
133 vec![source_range],
134 )));
135 }
136
137 let mut loft_sections = Vec::with_capacity(segments.len());
138 for segment in segments {
139 loft_sections.push(build_segment_surface_sketch(vec![segment], exec_state, ctx, source_range).await?);
140 }
141 return Ok(loft_sections);
142 }
143
144 Ok(sketches)
145}
146
147#[allow(clippy::too_many_arguments)]
148async fn inner_loft(
149 sketches: Vec<Sketch>,
150 v_degree: NonZeroU32,
151 bez_approximate_rational: bool,
152 base_curve_index: Option<u32>,
153 tolerance: Option<TyF64>,
154 tag_start: Option<TagNode>,
155 tag_end: Option<TagNode>,
156 body_type: Option<BodyType>,
157 exec_state: &mut ExecState,
158 args: Args,
159) -> Result<Box<Solid>, KclError> {
160 let body_type = body_type.unwrap_or_default();
161 if matches!(body_type, BodyType::Solid) && sketches.iter().any(|sk| matches!(sk.is_closed, ProfileClosed::No)) {
162 return Err(KclError::new_semantic(KclErrorDetails::new(
163 "Cannot solid loft an open profile. Either close the profile, or use a surface loft.".to_owned(),
164 vec![args.source_range],
165 )));
166 }
167
168 if sketches.len() < 2 {
170 return Err(KclError::new_semantic(KclErrorDetails::new(
171 format!(
172 "Loft requires at least two sketches, but only {} were provided.",
173 sketches.len()
174 ),
175 vec![args.source_range],
176 )));
177 }
178
179 let id = exec_state.next_uuid();
180 exec_state
181 .batch_modeling_cmd(
182 ModelingCmdMeta::from_args_id(exec_state, &args, id),
183 ModelingCmd::from(if let Some(base_curve_index) = base_curve_index {
184 mcmd::Loft::builder()
185 .section_ids(sketches.iter().map(|group| group.id).collect())
186 .bez_approximate_rational(bez_approximate_rational)
187 .tolerance(LengthUnit(
188 tolerance
189 .as_ref()
190 .map(|t| t.unwrap_to_mm())
191 .unwrap_or(DEFAULT_TOLERANCE_MM),
192 ))
193 .v_degree(v_degree)
194 .body_type(body_type)
195 .base_curve_index(base_curve_index)
196 .build()
197 } else {
198 mcmd::Loft::builder()
199 .section_ids(sketches.iter().map(|group| group.id).collect())
200 .bez_approximate_rational(bez_approximate_rational)
201 .tolerance(LengthUnit(
202 tolerance
203 .as_ref()
204 .map(|t| t.unwrap_to_mm())
205 .unwrap_or(DEFAULT_TOLERANCE_MM),
206 ))
207 .v_degree(v_degree)
208 .body_type(body_type)
209 .build()
210 }),
211 )
212 .await?;
213
214 let mut sketch = sketches[0].clone();
216 sketch.id = id;
220 sketch.original_id = id;
221 Ok(Box::new(
222 do_post_extrude(
223 &sketch,
224 id.into(),
225 false,
226 &super::extrude::NamedCapTags {
227 start: tag_start.as_ref(),
228 end: tag_end.as_ref(),
229 },
230 kittycad_modeling_cmds::shared::ExtrudeMethod::New,
231 exec_state,
232 &args,
233 None,
234 None,
235 body_type,
236 crate::std::extrude::BeingExtruded::Sketch,
237 )
238 .await?,
239 ))
240}
241
242#[cfg(test)]
243mod tests {
244 use kcl_api::Expr;
245 use kcl_api::LineCtor;
246 use kcl_api::Number;
247 use kcl_api::ObjectId;
248 use kcl_api::Point2d;
249 use kcl_api::UnitLength;
250
251 use super::*;
252 use crate::execution::AbstractSegment;
253 use crate::execution::KclValue;
254 use crate::execution::Plane;
255 use crate::execution::Segment;
256 use crate::execution::SegmentKind;
257 use crate::execution::SegmentRepr;
258 use crate::execution::SketchSurface;
259 use crate::execution::parse_execute;
260 use crate::execution::types::NumericType;
261 use crate::execution::types::NumericTypeExt;
262 use crate::parsing::ast::types::TagDeclarator;
263 use crate::std::sketch::PlaneData;
264
265 fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
266 Point2d {
267 x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
268 y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
269 }
270 }
271
272 fn line_segment_value(exec_state: &mut ExecState, plane_data: PlaneData, object_id_seed: usize) -> KclValue {
273 let plane = Plane::from_plane_data_skipping_engine(plane_data, exec_state).unwrap();
274 let start = [TyF64::new(-2.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())];
275 let end = [TyF64::new(2.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())];
276 let segment = Segment {
277 id: exec_state.next_uuid(),
278 object_id: ObjectId(object_id_seed),
279 kind: SegmentKind::Line {
280 start,
281 end,
282 ctor: Box::new(LineCtor {
283 start: point_expr(-2.0, 0.0),
284 end: point_expr(2.0, 0.0),
285 construction: None,
286 }),
287 start_object_id: ObjectId(object_id_seed + 1),
288 end_object_id: ObjectId(object_id_seed + 2),
289 start_freedom: None,
290 end_freedom: None,
291 construction: false,
292 },
293 surface: SketchSurface::Plane(Box::new(plane)),
294 sketch_id: exec_state.next_uuid(),
295 sketch: None,
296 tag: None,
297 meta: vec![],
298 node_path: None,
299 };
300 KclValue::Segment {
301 value: Box::new(AbstractSegment {
302 repr: SegmentRepr::Solved {
303 segment: Box::new(segment),
304 },
305 meta: vec![],
306 }),
307 }
308 }
309
310 #[tokio::test(flavor = "multi_thread")]
311 async fn segment_loft_supports_sections_from_different_sketches() {
312 let ctx = ExecutorContext::new_mock(None).await;
313 let mut exec_state = ExecState::new(&ctx);
314 let sketches = coerce_loft_targets(
315 vec![
316 line_segment_value(&mut exec_state, PlaneData::XY, 1),
317 line_segment_value(&mut exec_state, PlaneData::NegXY, 10),
318 line_segment_value(&mut exec_state, PlaneData::XZ, 20),
319 ],
320 BodyType::Surface,
321 None,
322 None,
323 &mut exec_state,
324 &ctx,
325 crate::SourceRange::default(),
326 )
327 .await
328 .unwrap();
329
330 assert_eq!(sketches.len(), 3);
331 assert!(sketches.iter().all(|sketch| sketch.paths.len() == 1));
332 assert_ne!(sketches[0].id, sketches[1].id);
333 assert_ne!(sketches[1].id, sketches[2].id);
334 ctx.close().await;
335 }
336
337 #[tokio::test(flavor = "multi_thread")]
338 async fn segment_loft_rejects_cap_tags() {
339 let ctx = ExecutorContext::new_mock(None).await;
340 let mut exec_state = ExecState::new(&ctx);
341 let err = coerce_loft_targets(
342 vec![line_segment_value(&mut exec_state, PlaneData::XY, 1)],
343 BodyType::Surface,
344 Some(&TagDeclarator::new("cap_start")),
345 None,
346 &mut exec_state,
347 &ctx,
348 crate::SourceRange::default(),
349 )
350 .await
351 .unwrap_err();
352
353 assert!(
354 err.message()
355 .contains("`tagStart` and `tagEnd` are not supported when lofting sketch segments"),
356 "{err:?}"
357 );
358 ctx.close().await;
359 }
360
361 #[tokio::test(flavor = "multi_thread")]
362 async fn loft_uses_its_body_id_for_topology_queries() {
363 let result = parse_execute(
364 r#"@settings(kclVersion = 2.0)
365
366firstSketch = sketch(on = XY) {
367 circle1 = circle(start = [var 10, var 0], center = [var 0, var 0])
368}
369secondSketch = sketch(on = offsetPlane(XY, offset = 10)) {
370 circle1 = circle(start = [var 5, var 0], center = [var 0, var 0])
371}
372
373lofted = loft([
374 region(segments = [firstSketch.circle1]),
375 region(segments = [secondSketch.circle1]),
376])
377"#,
378 )
379 .await
380 .expect("loft executes");
381
382 let KclValue::Solid { value: solid } = result.variable("lofted") else {
383 panic!("`lofted` is not a solid");
384 };
385 assert_eq!(solid.id, solid.topology_id());
386 assert_eq!(
387 solid.sketch().expect("loft retains its base sketch").original_id,
388 solid.id
389 );
390 }
391}