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
//! Split solids with a base plane, planar face, or supported analytic face carrier.
//!
//! Pieces replace the source and retain surviving face names. Names use
//! `${featureID}:${solidName}:A` for above/outside and `:B` for below/inside;
//! keeping both emits A before B. Missing body or face references are reported
//! as unresolved. Unsupported carriers and nonintersecting cuts return errors.
use crate::feature_pipeline::features::common;
use crate::feature_pipeline::{AddedSolid, FeatureContext, FeatureResult};
use crate::{
split_solid_by_face_surface, split_solid_by_plane, AnalyticSurface, BrepSolid, NurbsSurface,
Vec3,
};
/// Base-plane normals through the world origin: the cut
/// plane is the named base plane, its normal the axis PERPENDICULAR to it.
fn plane_normal(key: &str) -> Vec3 {
match key {
"YZ" => Vec3::new(1.0, 0.0, 0.0),
"XZ" => Vec3::new(0.0, 1.0, 0.0),
_ => Vec3::new(0.0, 0.0, 1.0), // XY (default)
}
}
/// The resolved cut tool, shared across every solid being split.
enum CutTool {
/// A plane through `point` with unit `normal` → `split_solid_by_plane`.
Plane { point: Vec3, normal: Vec3 },
/// A non-planar analytic carrier → `split_solid_by_face_surface`.
Surface(NurbsSurface),
}
pub fn execute(ctx: &FeatureContext) -> FeatureResult {
match build(ctx) {
Ok(result) => result,
Err(error) => ctx.fail(error),
}
}
fn build(ctx: &FeatureContext) -> Result<FeatureResult, String> {
let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
// `solids` is a reference_selection of solid names (contract rule 1). No
// selection → no-op.
let names = common::reference_name_array(ctx.param("solids"));
if names.is_empty() {
return Ok(result);
}
let resolved = common::resolve_solid_names(ctx.scene, &names, &mut result.unresolved);
// Resolve the cut tool (may add its own `unresolved` entry for a missing
// planeRef face → no-op, per contract rule 1 / mirror's precedent).
let tool = match resolve_cut_tool(ctx, &mut result)? {
Some(tool) => tool,
None => return Ok(result),
};
if resolved.is_empty() {
return Ok(result);
}
let feature_id = if ctx.id.is_empty() { "SPLIT" } else { ctx.id.as_str() };
let keep = ctx
.string("keep")
.unwrap_or_default()
.to_uppercase();
let keep = if keep.is_empty() { "BOTH".to_string() } else { keep };
let keep_above = keep == "BOTH" || keep == "ABOVE";
let keep_below = keep == "BOTH" || keep == "BELOW";
for (solid_name, handle) in &resolved {
// Short registry borrow: run the split and hand back the owned pieces.
let pieces = crate::with_registered_solid_str(*handle, |solid| split(solid, &tool));
let pieces = match pieces {
Ok(pieces) => pieces,
Err(error) => {
// Handle hygiene: free any pieces already registered for earlier
// solids before halting (a leaked handle is a wasm32 OOM).
free_added(&result.added);
return Err(error);
}
};
let [below, above] = pieces;
// A(above/+n/outside) = pieces[1]; B(below/−n/inside) = pieces[0]. Keep
// selects; when BOTH, A is added before B.
if keep_above {
result.added.push(register_piece(
above,
&format!("{feature_id}:{solid_name}:A"),
&format!("{feature_id}:A"),
));
}
if keep_below {
result.added.push(register_piece(
below,
&format!("{feature_id}:{solid_name}:B"),
&format!("{feature_id}:B"),
));
}
// The cut consumes the original body.
result.removed.push(solid_name.clone());
}
if result.added.is_empty() {
// Every kept piece was excluded by `keep` yet a solid resolved — the caller
// throws "failed to process any selected solids".
return Err("split: `keep` excluded every piece".into());
}
Ok(result)
}
/// Run the split, normalizing both kernel entries to `[below, above]`.
fn split(solid: &BrepSolid, tool: &CutTool) -> Result<[BrepSolid; 2], String> {
match tool {
CutTool::Plane { point, normal } => {
let (below, above) = split_solid_by_plane(solid, *point, *normal)?;
Ok([below, above])
}
CutTool::Surface(surface) => {
let pieces = split_solid_by_face_surface(solid, surface)?;
let mut pieces = pieces.into_iter();
let below = pieces
.next()
.ok_or("split: surface cut produced no pieces")?;
let above = pieces
.next()
.ok_or("split: surface cut produced only one piece")?;
Ok([below, above])
}
}
}
/// Register a kept piece under `name`. A cut divides shared faces, so BOTH
/// halves would otherwise inherit the source's face/edge names verbatim (two
/// resident solids sharing a name — the exact collision the naming-contract
/// guard forbids). `namespace_copy_names` suffixes the piece's copy of those
/// names with the per-invocation `suffix` (`{feature_id}:A` / `:B`), keeping
/// them unique and mode-independent (the same piece is named the same whether
/// or not its sibling survives).
fn register_piece(mut piece: BrepSolid, name: &str, suffix: &str) -> AddedSolid {
common::namespace_copy_names(&mut piece, suffix);
let face_names = common::collect_face_names(&piece);
let edge_names = common::collect_edge_names(&piece);
let handle = crate::register_solid_value(piece);
AddedSolid {
handle,
name: name.to_string(),
face_names,
edge_names,
..AddedSolid::default()
}
}
/// Free already-registered pieces before a mid-loop error halt (no handle leak).
fn free_added(added: &[AddedSolid]) {
for piece in added {
crate::free_registered_solid(piece.handle);
}
}
/// Resolve the cut tool:
/// 1. a `planeRef` face NAME resolved against the scene-map:
/// - a PLANAR face → cut by its plane, shifted `normal·offset` (the caller
/// `resolvePlaneReference(refObj, offset)`);
/// - a non-planar analytic face → cut by its carrier surface (the caller ignores
/// `offset` on this path — matched, with the note below);
/// - a name that does not resolve → an `unresolved` no-op (contract rule 1).
/// 2. else the named base plane (`plane` param + `offset·normal`).
fn resolve_cut_tool(
ctx: &FeatureContext,
result: &mut FeatureResult,
) -> Result<Option<CutTool>, String> {
let offset = match ctx.param("offset") {
None | Some(serde_json::Value::Null) => 0.0,
Some(_) => ctx.number("offset")?,
};
if let Some(name) = plane_ref_name(ctx.param("planeRef")) {
return match common::resolve_plane_reference(ctx, &name) {
// A FACE keeps the curved-carrier path: a planar face → its offset
// plane, a curved analytic face → its carrier surface.
Some(common::PlaneLikeRef::Face(face_ref)) => {
let tool = crate::with_registered_solid_str(face_ref.handle, |solid| {
cut_tool_from_face(solid, face_ref.face_id, offset)
})?;
Ok(Some(tool))
}
// A datum / construction PLANE → an offset plane cut (its frame's
// origin + z-axis normal, shifted by `offset`).
Some(common::PlaneLikeRef::Frame(frame)) => Ok(Some(CutTool::Plane {
point: frame.origin.add(frame.z_axis.scale(offset)),
normal: frame.z_axis,
})),
None => {
result.unresolved.push(name);
Ok(None)
}
};
}
// Base plane: plane_point = origin + normal·offset.
let key = ctx
.string("plane")
.unwrap_or_default()
.to_uppercase();
let normal = plane_normal(&key);
Ok(Some(CutTool::Plane {
point: normal.scale(offset),
normal,
}))
}
/// Build a [`CutTool`] from a referenced face: a planar face → its offset plane;
/// any other analytic face → its carrier surface (offset ignored, as before).
fn cut_tool_from_face(
solid: &BrepSolid,
face_id: u64,
offset: f64,
) -> Result<CutTool, String> {
for shell in &solid.shells {
for face in &shell.faces {
if face.id != face_id {
continue;
}
if matches!(face.surface.analytic(), Some(AnalyticSurface::Plane { .. })) {
// Planar face → its plane, shifted along the face normal by
// `offset` (`resolvePlaneReference`). Point/normal from the
// surface midpoint, oriented by `same_sense` (mirror's pattern).
let [u0, u1] = face.surface.domain_u()?;
let [v0, v1] = face.surface.domain_v()?;
let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
let point = face.surface.evaluate(um, vm)?;
let mut normal = face.surface.normal(um, vm)?;
if !face.same_sense {
normal = normal.scale(-1.0);
}
return Ok(CutTool::Plane {
point: point.add(normal.scale(offset)),
normal,
});
}
// Non-planar analytic carrier: cut by the surface itself. The kernel
// recognizes cylinder/cone/sphere/torus and extends the carrier;
// general revolutions error there (deferred). `offset` has no
// meaning for a curved carrier — ignored here.
return Ok(CutTool::Surface(face.surface.clone()));
}
}
Err(format!("split: planeRef face id {face_id} not found"))
}
/// The `planeRef` reference name (`multiple: false`; a string, a `{ name }`
/// object, or the first entry of a saved singleton array). Empty → `None`.
fn plane_ref_name(value: Option<&serde_json::Value>) -> Option<String> {
let name = match value {
Some(serde_json::Value::String(text)) => Some(text.clone()),
Some(serde_json::Value::Array(array)) => array.iter().find_map(|entry| {
entry
.as_str()
.or_else(|| entry.get("name").and_then(|name| name.as_str()))
.map(str::to_string)
}),
Some(object @ serde_json::Value::Object(_)) => object
.get("name")
.and_then(|name| name.as_str())
.map(str::to_string),
_ => None,
}?;
let trimmed = name.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
}
/// Context-bar applicability ([`crate::feature_pipeline::context_offer`]):
/// selected solids drive `solids`, a face `planeRef`.
pub fn context_applicable(probe: &crate::feature_pipeline::SelectionProbe) -> bool {
probe.solids > 0 || probe.faces > 0
}
pub fn schema() -> serde_json::Value {
serde_json::json!({
"type": "SPL",
"shortName": "SPL",
"longName": "Split",
"ribbonPath": "Home/Modeling/Split",
"commandSize": "Compact",
"displayBuilder": false,
"inputParamsSchema": {
"id": {
"type": "string",
"default_value": null,
"hint": "unique identifier for the split feature"
},
"solids": {
"type": "reference_selection",
"selectionFilter": [
"SOLID"
],
"multiple": true,
"default_value": [],
"hint": "Select one or more solids to cut by the plane"
},
"plane": {
"type": "options",
"options": [
"XY",
"YZ",
"XZ"
],
"default_value": "XY",
"hint": "Base plane to cut with (through the world origin unless offset). Ignored when a plane reference is selected."
},
"offset": {
"type": "number",
"default_value": 0,
"hint": "Shift the cut plane along its normal (cut at origin + normal·offset)"
},
"planeRef": {
"type": "reference_selection",
"selectionFilter": [
"FACE",
"PLANE"
],
"multiple": false,
"default_value": null,
"hint": "Optional face or datum to cut with (overrides the base plane). A planar face cuts by its plane; a cylindrical / conical / spherical face cuts by that analytic surface (Golovanov §6.4)."
},
"keep": {
"type": "options",
"options": [
"BOTH",
"ABOVE",
"BELOW"
],
"default_value": "BOTH",
"hint": "Which piece(s) to keep: BOTH halves, only ABOVE (+normal side), or only BELOW (−normal side)"
}
}
})
}