Skip to main content

brep_kernel/feature_pipeline/features/
transform_face.rs

1//! TF — Transform Face.
2//!
3//! Carries the selected faces of a single solid by ONE RIGID MOTION — a rotation
4//! about a stated pivot followed by a translation — preserving each carrier's
5//! shape, and re-intersects the neighbours the motion moves the selection
6//! relative to. The motion is the `transform` parameter the transform gizmo
7//! edits: dragging an axis or the centre handle writes `position`, dragging a
8//! ring writes `rotationEuler`.
9//!
10//! # The motion
11//!
12//! `p ↦ pivot + position + R·(p − pivot)`, with `R` the intrinsic XYZ Euler
13//! rotation of `rotationEuler` (degrees) — exactly
14//! [`common::compose_trs_matrix`]`(position, rotationEuler, [1,1,1], pivot)`, the
15//! one feature-transform convention the Transform feature, the assembly pose and
16//! the gizmo already speak. The gizmo is drawn at `pivot + position`, which is
17//! where the pivot point lands, so a ring drag turns the faces about the handle
18//! the user is holding.
19//!
20//! `scale` has no meaning for a face edit — a scaled carrier is a different
21//! surface, not a moved one. The schema's `default_value` omits it, which hides
22//! it in the form and in the tool schema, and a document that carries a
23//! non-unit scale anyway is refused BY NAME rather than silently ignored.
24//!
25//! # A rotation is not a mode of a translation — and this feature does not pretend it is
26//!
27//! [`crate::move_faces`] moves a carrier's POSITION and leaves its normal alone;
28//! [`crate::rotate_faces`] moves the normal too, so the neighbour pairs are
29//! re-intersected differently and the invariants that let a corner ride rigidly
30//! are different invariants (a cone about its own axis is invariant under a
31//! rotation and not under a translation). The two primitives stay two roads, and
32//! this feature is a DISPATCHER over them, not a third solver:
33//!
34//! * a pure TRANSLATION (`rotationEuler` is the identity) goes to `move_faces`
35//!   with `position` — Move Face's road, unchanged;
36//! * a pure ROTATION (`position` is zero) goes to `rotate_faces` about the axis
37//!   LINE through `pivot` along the rotation's own axis, by its own angle —
38//!   Rotate Face's road, unchanged. `R` is converted to that axis and angle from
39//!   the same matrix the compose builds, so the stored Euler angles and the
40//!   kernel's Rodrigues rotation are one rotation;
41//! * a COMBINED motion goes through the rotation solver with the translation
42//!   composed into its affine before any corner is solved. The carrier normals
43//!   turn and their positions move together, and every edge inversion, winding
44//!   and soundness check sees the final geometry. A rotation-only intermediate
45//!   can invert a wall that the final translation extends safely; it is not a
46//!   shape the user requested and must not block the edit.
47//!
48//! The rigid regime requires the fixed carrier to be invariant under both
49//! parts: an in-plane spin does not leave a plane invariant when followed by a
50//! normal translation, and a cone cannot ride an axial translation. Cylinders
51//! still admit an axial slide. Other pairs use the existing re-intersection
52//! and re-trimming machinery against the final moved planes and ruled frames.
53//!
54//! # The pivot
55//!
56//! `pivot` is a stored vec3. When it is null the pivot is the SELECTION'S CENTRE,
57//! computed by [`selection_centre`] from the feature's INPUT solid: the centre of
58//! the axis-aligned bounds of every vertex on the selected faces' boundaries and
59//! of each boundary edge sampled at [`CENTRE_SAMPLES`] equal steps across its
60//! active parameter range (a face with no edge at all — a closed sphere —
61//! contributes its surface control points). Exact for straight-edged faces.
62//! Every run with a null `pivot` reports that value on its result
63//! ([`DEFAULT_PIVOT_KEY`]), and the app stores it into `pivot` when the run
64//! lands, so the rotation centre is a number in the document: re-running the history, dragging
65//! the gizmo, or editing a feature upstream never moves it. A null pivot in a
66//! hand-written document is resolved the same way on every run, from the same
67//! input, so it cannot drift either.
68//!
69//! # Reference resolution and behaviour mapping
70//!
71//! `faces` is a `reference_selection` of FACE names — the declaration Push Face
72//! and Delete Face use. A miss is an `unresolved` entry, never a panic. Every
73//! `transform` component and every `pivot` component may be a number or an
74//! expression.
75//!
76//! SOFT no-op (an empty result, no error) for an empty selection, names that all
77//! fail to resolve, faces spanning multiple solids, and the IDENTITY motion — a
78//! half-filled dialog must not shout. A kernel `Err` → `ctx.fail` (halt): the
79//! refusal names the offending entity, and neither primitive mutates its input,
80//! so the source solid is untouched.
81//!
82//! # Name preservation and the exit
83//!
84//! Both roads are pure geometry edits: no face, edge or vertex is created or
85//! destroyed, so every id and name survives. Names are COLLECTED, never
86//! re-stamped, and the result reuses the TARGET solid's name. The result goes
87//! through [`crate::accept_sound`] once, at the exit, as Move Face and Rotate
88//! Face each did.
89//!
90//! The acceptance is the one step that can change topology, and only on a
91//! BREAKOUT — a motion that carries the selection clean out of the faces it
92//! opened through, which both primitives build as a body passing through
93//! itself. Its crossing repair then splits the pair along their carriers' exact
94//! section, drops what ended up on the wrong side and RE-TRIMS the neighbour
95//! that is left holding an unanswered boundary, so edges and vertices move
96//! while every FACE name still survives. It says so in the result's `notes`
97//! rather than changing the answer silently.
98
99use crate::face_refusal_slugs::{PIVOT_GEOMETRY, RIGID_SCALE};
100use std::collections::HashSet;
101
102use crate::feature_pipeline::features::common;
103use crate::feature_pipeline::{AddedSolid, FeatureContext, FeatureRefusal, FeatureResult, SceneMap};
104use crate::{move_faces_unchecked, rotate_faces_unchecked, BrepSolid, KernelRefusal, KernelStage, Vec3};
105
106/// Stations per boundary edge in [`selection_centre`]. A power of two, so a
107/// rational circle split into quarter spans is sampled at its span ends — the
108/// points where an axis-aligned circle reaches its bounds.
109/// [`FeatureResult::refused_step`] of a Transform Face whose ROTATION refused
110/// (a turn alone, or a combined rigid motion through the rotation solver).
111pub const REFUSED_STEP_ROTATION: &str = "rotation";
112/// … whose pure TRANSLATION refused.
113pub const REFUSED_STEP_TRANSLATION: &str = "translation";
114
115pub const CENTRE_SAMPLES: usize = 64;
116
117pub fn execute(ctx: &FeatureContext) -> FeatureResult {
118    let mut result = match build(ctx) {
119        Ok(result) => result,
120        Err(error) => ctx.fail(error),
121    };
122    if let Some(report) = default_pivot_report(ctx) {
123        result.persistent_data = Some(report);
124    }
125    result
126}
127
128/// The key of the [`FeatureResult::persistent_data`] a Transform Face with a
129/// NULL `pivot` reports: `{"defaultPivot": {"pivot": [x, y, z], "faces": [...]}}`,
130/// the selection's centre over this run's input and the `faces` it was
131/// computed for. The app stores that value into `pivot` when the run lands
132/// (and only while `faces` still match), so the default reaches the document
133/// from the run that already resolved it — never from a second history replay
134/// on the app's own thread, which has no warm history cache and froze the UI
135/// for as long as a cold rebuild of the whole prefix. Reported on success AND
136/// on refusal: a refused motion still has a pivot for its gizmo.
137pub const DEFAULT_PIVOT_KEY: &str = "defaultPivot";
138
139fn default_pivot_report(ctx: &FeatureContext) -> Option<serde_json::Value> {
140    if !matches!(ctx.param("pivot"), None | Some(serde_json::Value::Null)) {
141        return None;
142    }
143    let names = common::reference_name_array(ctx.param("faces"));
144    if names.is_empty() {
145        return None;
146    }
147    let (handle, face_ids) = resolve_selection(ctx.scene, &names, &mut Vec::new())?;
148    let centre =
149        crate::with_registered_solid_str(handle, |solid| Ok(selection_centre(solid, &face_ids)))
150            .ok()??;
151    Some(serde_json::json!({
152        DEFAULT_PIVOT_KEY: { "pivot": [centre.x, centre.y, centre.z], "faces": names },
153    }))
154}
155
156/// The selection resolved against a scene: the one target solid's handle and
157/// the deduplicated face ids on it, or `None` for the soft no-ops (nothing
158/// resolved, or faces on more than one solid). Misses land in `unresolved`.
159fn resolve_selection(
160    scene: &SceneMap,
161    names: &[String],
162    unresolved: &mut Vec<String>,
163) -> Option<(u32, Vec<u64>)> {
164    let mut resolved: Vec<(u32, u64)> = Vec::new();
165    for name in names {
166        match scene.resolve_face(name) {
167            Some(face_ref) => resolved.push((face_ref.handle, face_ref.face_id)),
168            None => unresolved.push(name.clone()),
169        }
170    }
171    let &(target, _) = resolved.first()?;
172    if resolved.iter().any(|(handle, _)| *handle != target) {
173        return None;
174    }
175    let mut seen: HashSet<u64> = HashSet::new();
176    let face_ids = resolved
177        .iter()
178        .map(|(_, face_id)| *face_id)
179        .filter(|face_id| seen.insert(*face_id))
180        .collect();
181    Some((target, face_ids))
182}
183
184/// The centre of the selection's boundary bounds — the default pivot. See the
185/// module doc for exactly what is bounded. `None` only when the faces carry no
186/// geometry at all.
187pub fn selection_centre(solid: &BrepSolid, face_ids: &[u64]) -> Option<Vec3> {
188    let selected: HashSet<u64> = face_ids.iter().copied().collect();
189    let mut low = [f64::INFINITY; 3];
190    let mut high = [f64::NEG_INFINITY; 3];
191    let mut include = |point: Vec3| {
192        let point = [point.x, point.y, point.z];
193        if point.iter().all(|c| c.is_finite()) {
194            for axis in 0..3 {
195                low[axis] = low[axis].min(point[axis]);
196                high[axis] = high[axis].max(point[axis]);
197            }
198        }
199    };
200    let mut edge_ids: HashSet<u64> = HashSet::new();
201    let mut edgeless = Vec::new();
202    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
203        if !selected.contains(&face.id) {
204            continue;
205        }
206        let before = edge_ids.len();
207        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
208            edge_ids.insert(coedge.edge_id);
209        }
210        if edge_ids.len() == before && face.loops.iter().all(|l| l.coedges.is_empty()) {
211            edgeless.push(face);
212        }
213    }
214    let vertex_ids: HashSet<u64> = solid
215        .edges
216        .iter()
217        .filter(|edge| edge_ids.contains(&edge.id))
218        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
219        .collect();
220    for vertex in &solid.vertices {
221        if vertex_ids.contains(&vertex.id) {
222            include(vertex.point);
223        }
224    }
225    for edge in solid.edges.iter().filter(|edge| edge_ids.contains(&edge.id)) {
226        if edge.degenerate {
227            continue;
228        }
229        for station in 0..=CENTRE_SAMPLES {
230            let t = edge.t0 + (edge.t1 - edge.t0) * station as f64 / CENTRE_SAMPLES as f64;
231            if let Ok(point) = edge.curve.evaluate(t) {
232                include(point);
233            }
234        }
235    }
236    for face in edgeless {
237        for control in face.surface.control_points.iter().flatten() {
238            if let Ok(point) = control.point() {
239                include(point);
240            }
241        }
242    }
243    if !low[0].is_finite() {
244        return None;
245    }
246    Some(Vec3::new(
247        0.5 * (low[0] + high[0]),
248        0.5 * (low[1] + high[1]),
249        0.5 * (low[2] + high[2]),
250    ))
251}
252
253/// The pivot a Transform Face whose `faces` are `names` gets by default, read
254/// off the scene the results BEFORE it build — the value the app stores into
255/// `pivot` when the selection is committed, and the value `build` falls back to
256/// for a null `pivot`, because both go through `resolve_selection` and
257/// `selection_centre`. `None` when the selection does not resolve to faces on
258/// one solid.
259pub fn face_transform_pivot(prefix: &[FeatureResult], names: &[String]) -> Option<[f64; 3]> {
260    let mut scene = SceneMap::default();
261    for result in prefix {
262        scene.apply(result);
263    }
264    let (handle, face_ids) = resolve_selection(&scene, names, &mut Vec::new())?;
265    let centre =
266        crate::with_registered_solid_str(handle, |solid| Ok(selection_centre(solid, &face_ids)))
267            .ok()??;
268    Some([centre.x, centre.y, centre.z])
269}
270
271/// The point a PICKED entity puts the pivot on — what the dialog's pivot pick
272/// stores, resolved against the scene the feature runs against (`prefix`, the
273/// results before it), so the stored number is the entity as the user saw it:
274///
275/// - a vertex (`{solid}@x,y,z`, world coordinates) → that vertex, exactly;
276/// - a straight edge → its midpoint, a point ON the line a rotation about that
277///   edge needs; a circular edge → its centre; any other edge → the point at
278///   the middle of its parameter range;
279/// - a sphere face → its centre; an axis-bearing face (cylinder, cone, torus,
280///   revolution) → the point of its axis level with the face's `selection_centre`;
281///   any other face → that centre, the value a face SELECTION defaults to;
282/// - a datum frame → its origin.
283///
284/// `Err` names what failed: an empty name, a name not in that scene, or an
285/// entity whose geometry does not evaluate. Nothing is guessed.
286pub fn reference_point(prefix: &[FeatureResult], name: &str) -> Result<[f64; 3], String> {
287    use crate::feature_pipeline::pmi::resolve::resolve_reference;
288    use crate::{resolve_edge_selection, resolve_face_selection, SelectionGeometry};
289    let name = name.trim();
290    if name.is_empty() {
291        return Err("nothing was picked".into());
292    }
293    let mut scene = SceneMap::default();
294    for result in prefix {
295        scene.apply(result);
296    }
297    let point = if let Some(face) = scene.resolve_face(name) {
298        crate::with_registered_solid_str(face.handle, |solid| {
299            let centre = selection_centre(solid, &[face.face_id])
300                .ok_or_else(|| format!("face '{name}' has no geometry to place a point on"))?;
301            Ok(match resolve_face_selection(solid, face.face_id) {
302                Ok(SelectionGeometry::Sphere { center, .. }) => center,
303                Ok(SelectionGeometry::Axis { origin, direction, .. }) => {
304                    origin.add(direction.scale(centre.sub(origin).dot(direction)))
305                }
306                _ => centre,
307            })
308        })?
309    } else if let Some(edge) = scene.resolve_edge(name) {
310        crate::with_registered_solid_str(edge.handle, |solid| {
311            let record = solid
312                .edges
313                .iter()
314                .find(|record| record.id == edge.edge_id)
315                .ok_or_else(|| format!("edge '{name}' has no record"))?;
316            let at = |t: f64| record.curve.evaluate(t).map_err(|error| format!("edge '{name}': {error}"));
317            let (start, middle, end) = (at(record.t0)?, at(0.5 * (record.t0 + record.t1))?, at(record.t1)?);
318            // The analytic classifier's tolerances grow with the distance from
319            // the world origin; the point it names is taken only when the
320            // edge's own middle agrees with it to a fraction of the edge's own
321            // size, and otherwise the middle of the edge is the answer.
322            let size = start.sub(middle).length().max(end.sub(middle).length());
323            let reach = [start, middle, end].iter().map(|p| p.x.abs().max(p.y.abs()).max(p.z.abs())).fold(0.0, f64::max);
324            let agrees = |distance: f64| distance <= 1e-9 * size + 64.0 * f64::EPSILON * reach;
325            Ok(match resolve_edge_selection(solid, edge.edge_id) {
326                Ok(SelectionGeometry::Line { origin, .. })
327                    if agrees(middle.sub(start.add(end).scale(0.5)).length()) =>
328                {
329                    origin
330                }
331                Ok(SelectionGeometry::Circle { center, radius, .. })
332                    if [start, middle, end].iter().all(|p| agrees((p.sub(center).length() - radius).abs())) =>
333                {
334                    center
335                }
336                _ => middle,
337            })
338        })?
339    } else {
340        match resolve_reference(&scene, name)? {
341            SelectionGeometry::Point { position } => position,
342            SelectionGeometry::Plane { origin, .. } => origin,
343            SelectionGeometry::Sphere { center, .. } | SelectionGeometry::Circle { center, .. } => center,
344            SelectionGeometry::Line { origin, .. } | SelectionGeometry::Axis { origin, .. } => origin,
345        }
346    };
347    let point = [point.x, point.y, point.z];
348    if point.iter().any(|c| !c.is_finite()) {
349        return Err(format!("'{name}' did not evaluate to a finite point"));
350    }
351    Ok(point)
352}
353
354/// The rotation part of the motion as the axis and angle `rotate_faces` takes:
355/// `R` is built by the shared compose (so the Euler convention is single-sourced)
356/// and converted through its quaternion, choosing the numerically largest
357/// component first so a half turn keeps its axis. `None` for the identity.
358pub fn rotation_axis_angle(rotation_deg: [f64; 3]) -> Option<(Vec3, f64)> {
359    if rotation_deg == [0.0; 3] {
360        return None;
361    }
362    let radians = rotation_deg.map(f64::to_radians);
363    let m = common::compose_trs_matrix([0.0; 3], radians, [1.0; 3], [0.0; 3]);
364    let at = |row: usize, col: usize| m[row * 4 + col];
365    let (m00, m11, m22) = (at(0, 0), at(1, 1), at(2, 2));
366    let trace = m00 + m11 + m22;
367    // [x, y, z, w]
368    let q = if trace >= m00 && trace >= m11 && trace >= m22 {
369        let w = 0.5 * (1.0 + trace).max(0.0).sqrt();
370        let k = 0.25 / w;
371        [(at(2, 1) - at(1, 2)) * k, (at(0, 2) - at(2, 0)) * k, (at(1, 0) - at(0, 1)) * k, w]
372    } else if m00 >= m11 && m00 >= m22 {
373        let x = 0.5 * (1.0 + m00 - m11 - m22).max(0.0).sqrt();
374        let k = 0.25 / x;
375        [x, (at(0, 1) + at(1, 0)) * k, (at(0, 2) + at(2, 0)) * k, (at(2, 1) - at(1, 2)) * k]
376    } else if m11 >= m22 {
377        let y = 0.5 * (1.0 - m00 + m11 - m22).max(0.0).sqrt();
378        let k = 0.25 / y;
379        [(at(0, 1) + at(1, 0)) * k, y, (at(1, 2) + at(2, 1)) * k, (at(0, 2) - at(2, 0)) * k]
380    } else {
381        let z = 0.5 * (1.0 - m00 - m11 + m22).max(0.0).sqrt();
382        let k = 0.25 / z;
383        [(at(0, 2) + at(2, 0)) * k, (at(1, 2) + at(2, 1)) * k, z, (at(1, 0) - at(0, 1)) * k]
384    };
385    // One sign for the quaternion, so the angle lands in [0, π].
386    let sign = if q[3] < 0.0 { -1.0 } else { 1.0 };
387    let axis = Vec3::new(q[0] * sign, q[1] * sign, q[2] * sign);
388    let half_sine = axis.length();
389    let angle = 2.0 * half_sine.atan2(q[3] * sign);
390    if angle <= 1e-12 {
391        return None;
392    }
393    Some((axis.scale(1.0 / half_sine), angle))
394}
395
396/// A `transform` component, read through the shared vec3 reader under its
397/// dotted name so an expression error names `transform.position` and not a bare
398/// key.
399fn transform_vec3(ctx: &FeatureContext, key: &str, default: [f64; 3]) -> Result<[f64; 3], String> {
400    common::vec3_from_value(
401        ctx.env,
402        ctx.param("transform").and_then(|transform| transform.get(key)),
403        &format!("transform.{key}"),
404        default,
405    )
406}
407
408fn build(ctx: &FeatureContext) -> Result<FeatureResult, FeatureRefusal> {
409    let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
410
411    let names = common::reference_name_array(ctx.param("faces"));
412    if names.is_empty() {
413        return Ok(result); // Soft no-op — nothing selected.
414    }
415    let Some((target_handle, face_ids)) =
416        resolve_selection(ctx.scene, &names, &mut result.unresolved)
417    else {
418        return Ok(result); // Only unresolved names, or faces on several solids.
419    };
420    // The feature proceeds on the faces that resolved: a miss is reported as
421    // a typed partial fulfilment beside `unresolved`, never silently.
422    result.note_partial_resolution(&names);
423
424    // The motion. Scale first: a document that scales is refused before
425    // anything else is read, because no reading of the rest makes it rigid.
426    let scale = transform_vec3(ctx, "scale", [1.0; 3])?;
427    if scale != [1.0; 3] {
428        return Err(KernelRefusal::input(
429            KernelStage::Collect,
430            RIGID_SCALE,
431            format!(
432                "transformFace: `transform.scale` is {scale:?}, but a face transform is a RIGID \
433                 motion — a scaled carrier is a different surface, not a moved one — so scale must \
434                 be [1, 1, 1]; refusing"
435            ),
436        )
437        .into());
438    }
439    let position = transform_vec3(ctx, "position", [0.0; 3])?;
440    let rotation_deg = transform_vec3(ctx, "rotationEuler", [0.0; 3])?;
441    let translation = Vec3::new(position[0], position[1], position[2]);
442    let translates = translation.length() > 1e-12;
443    let rotation = rotation_axis_angle(rotation_deg);
444    if !translates && rotation.is_none() {
445        return Ok(result); // Soft no-op — the identity motion.
446    }
447
448    let target_name = ctx
449        .scene
450        .solids
451        .iter()
452        .find(|(_, handle)| **handle == target_handle)
453        .map(|(name, _)| name.clone())
454        .ok_or("transformFace: target solid has no scene-map name")?;
455    let solid = crate::with_registered_solid_str(target_handle, |solid| Ok(solid.clone()))?;
456
457    // The rotation as the re-cut road needs it too: axis point, axis, angle.
458    let turn = match rotation {
459        None => None,
460        Some((axis, angle)) => {
461            let pivot = match ctx.param("pivot") {
462                None | Some(serde_json::Value::Null) => selection_centre(&solid, &face_ids)
463                    .ok_or_else(|| {
464                        KernelRefusal::input(
465                            KernelStage::Collect,
466                            PIVOT_GEOMETRY,
467                            "transformFace: the selected faces carry no geometry to centre a pivot on",
468                        )
469                    })?,
470                Some(value) => {
471                    let [x, y, z] = common::vec3_from_value(ctx.env, Some(value), "pivot", [0.0; 3])?;
472                    Vec3::new(x, y, z)
473                }
474            };
475            Some((pivot, axis, angle))
476        }
477    };
478    // The motion records itself on refusal (`refused_step`), so the
479    // app names the motion the user asked for without reading this text.
480    let refused_at = |error: KernelRefusal, step: &str| {
481        let mut refused = ctx.fail(error);
482        refused.refused_step = Some(step.to_string());
483        refused
484    };
485    // A face beside a VARIABLE-RADIUS fillet has no road of its own: the band
486    // is a free-form carrier neither primitive re-intersects and the re-cut
487    // cannot bound a tool by — and where the re-cut is reached anyway (another
488    // fillet beside the face hands it the motion) it cuts the band where the
489    // moved plane crosses it and leaves it there, no longer tangent, under its
490    // name. The fillet is a derived face, so the motion is run on the body
491    // without it and the fillet is re-made on the edge the motion leaves,
492    // under its radius law (`edit/direct_edit/blend_rebuild.rs`). Offered
493    // first, and only where such a fillet borders the selection: without one
494    // it reads the selection's neighbours and steps aside.
495    let (moved, notes) = match move_faces_road(&solid, &face_ids, turn, translates, translation) {
496        Ok(solved) => solved,
497        Err((refusal, step)) => {
498            return match step {
499                Some(step) => Ok(refused_at(refusal, step)),
500                None => Err(refusal.into()),
501            };
502        }
503    };
504    result.notes.extend(notes);
505
506    // Both roads preserve every name — collect, never re-stamp.
507    let face_names = common::collect_face_names(&moved);
508    let edge_names = common::collect_edge_names(&moved);
509    let handle = crate::register_solid_value(moved);
510    result.added.push(AddedSolid {
511        handle,
512        name: target_name.clone(),
513        face_names,
514        edge_names,
515        ..AddedSolid::default()
516    });
517    result.removed.push(target_name);
518    Ok(result)
519}
520
521/// The motion's road with the variable-radius fillet rebuild offered first
522/// (see `build`), shared with the public [`crate::transform_faces`]: `Ok` is
523/// the edited body and its notes, `Err` the refusal (the rebuild's decline
524/// appended) and the motion's step it names.
525pub(crate) fn move_faces_road(
526    solid: &BrepSolid,
527    face_ids: &[u64],
528    turn: Option<(Vec3, Vec3, f64)>,
529    translates: bool,
530    translation: Vec3,
531) -> Result<(BrepSolid, Vec<String>), (KernelRefusal, Option<&'static str>)> {
532    let without = crate::rebuild_displaced_blends(solid, face_ids, "transformFace", |sharp| {
533        solve_motion(sharp, face_ids, turn, translates, translation).map_err(|(error, _)| error)
534    });
535    match without {
536        Some(Ok(solved)) => Ok(solved),
537        declined => solve_motion(solid, face_ids, turn, translates, translation).map_err(|(refusal, step)| {
538            let refusal = match &declined {
539                Some(Err(decline)) => crate::with_blend_rebuild_decline(refusal, decline),
540                _ => refusal,
541            };
542            (refusal, step)
543        }),
544    }
545}
546
547/// The motion's whole road on one body: the direct re-solve, its acceptance,
548/// and the re-cut where either hands the motion on. `Ok` is the edited body
549/// and the notes the road left; `Err` is the refusal and, for a refusal of
550/// the re-solve itself, the step of the motion it names (`refused_step`).
551fn solve_motion(
552    solid: &BrepSolid,
553    face_ids: &[u64],
554    turn: Option<(Vec3, Vec3, f64)>,
555    translates: bool,
556    translation: Vec3,
557) -> Result<(BrepSolid, Vec<String>), (KernelRefusal, Option<&'static str>)> {
558    let mut notes = Vec::new();
559    let moved = match turn {
560        None => match move_faces_unchecked(solid, face_ids, translation) {
561            Ok(moved) => moved,
562            // A straight edge the translation inverts or collapses on a face
563            // with an ISLAND is that face carried past the far end of the
564            // island's wall — a pocket floor pushed past the bottom of a hole
565            // through it — whose answer has that wall STOP EXISTING. No re-solve has such a body, so the
566            // re-cut is offered it, as it is offered an acceptance refusal
567            // below; the re-solve's refusal stays the primary one if it
568            // declines too.
569            Err(error) if is_straight_edge_inversion(&error) && has_island(solid, face_ids) => {
570                match recut_past_a_refusal(solid, face_ids, None, translation) {
571                    Ok((body, lost)) => {
572                        notes.push(format!(
573                            "transformFace: the moved carriers could not be re-solved ({error}), \
574                             so the selection was RE-CUT from the original body instead — the \
575                             result is the boolean this motion defines, and a face whose carrier \
576                             left the body is no longer on it"
577                        ));
578                        notes.extend(lost);
579                        return Ok((body, notes));
580                    }
581                    Err(reason) => {
582                        let error = error.with_message(|error| {
583                            format!("{error}. The re-cut road was offered it too and declined: {reason}")
584                        });
585                        return Err((with_declines_class(error, &[&reason]), Some(REFUSED_STEP_TRANSLATION)));
586                    }
587                }
588            }
589            Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, None, translation) {
590                Ok((body, note)) => {
591                    notes.push(format!("transformFace: the moved carriers could not be re-solved ({error}), {note}"));
592                    body
593                }
594                Err(reason) => {
595                    let error = error.with_message(|error| format!("{error}. {reason}"));
596                    return Err((error, Some(REFUSED_STEP_TRANSLATION)));
597                }
598            },
599            Err(error) => return Err((error, Some(REFUSED_STEP_TRANSLATION))),
600        },
601        Some((pivot, axis, angle)) => {
602            let solved = if !translates {
603                rotate_faces_unchecked(solid, face_ids, pivot, axis, angle)
604            } else {
605                crate::direct_edit::rotate_faces_rigid(
606                    solid, face_ids, pivot, axis, angle, translation,
607                )
608                .map_err(|error| {
609                    error.with_message(|error| {
610                        format!("transformFace: the combined rigid motion refused — {error}")
611                    })
612                })
613            };
614            match solved {
615                Ok(moved) => moved,
616                // A face tangent to a fillet beside it has no rim to re-solve:
617                // turned, it cuts that fillet in a different ruling or leaves
618                // it altogether, and either way the answer is a different
619                // topology. That is what the re-cut road below is for, so this
620                // one refusal is offered to it directly. Its body still passes
621                // the acceptance below.
622                Err(error) if is_ruling_refusal(&error) => {
623                    match crate::recut_moved_planes_rigid(solid, face_ids, turn, translation) {
624                        Ok(body) => {
625                            notes.push(format!(
626                                "transformFace: the turned face could not be re-solved against \
627                                 the fillet beside it ({error}), so the selection was RE-CUT \
628                                 from the original body instead"
629                            ));
630                            let (body, lost) = crate::reblend_lost_fillets(solid, face_ids, body);
631                            notes.extend(lost);
632                            body
633                        }
634                        Err(reason) => {
635                            let error = error.with_message(|error| {
636                                format!(
637                                    "{error}. The re-cut road was offered it too and declined: {reason}"
638                                )
639                            });
640                            return Err((with_declines_class(error, &[&reason]), Some(REFUSED_STEP_ROTATION)));
641                        }
642                    }
643                }
644                // A turned face whose neighbour has no route on this road — a
645                // plane's section of a cylinder or cone it cannot mint (a whole
646                // frustum's top turned past the generatrices), a slanted cap on a
647                // coaxial wall, a sphere, torus or quadric neighbour — still
648                // has an answer where the body is the intersection of its faces'
649                // own regions, or where the selection is a through bore
650                // (`by_regions`). The rotation road's refusal stays the primary
651                // one if both decline.
652                Err(error) if is_no_route_refusal(&error) => match by_regions(solid, face_ids, turn, translation) {
653                    Ok((body, note)) => {
654                        notes.push(format!(
655                            "transformFace: the turned face could not be re-solved ({error}), {note}"
656                        ));
657                        body
658                    }
659                    Err(reason) => {
660                        let error = error.with_message(|error| format!("{error}. {reason}"));
661                        return Err((error, Some(REFUSED_STEP_ROTATION)));
662                    }
663                },
664                Err(error) => return Err((error, Some(REFUSED_STEP_ROTATION))),
665            }
666        }
667    };
668    // Carrying a face past a neighbour's own extent leaves it crossing one it
669    // should have stopped at, and both roads are pure geometry edits that create
670    // no cell for `validate()` to catch. The acceptance Push Face takes: split and
671    // trim where that can be proved, refuse by name where it cannot. Where the
672    // motion carried the selection clean OUT of the faces it opened through —
673    // the breakout — that split also re-trims the neighbour left holding an
674    // unanswered boundary, which is the only way such a body closes.
675    //
676    // And where the acceptance refuses, the RE-CUT road is offered the same
677    // edit from the other end — the original body, the selection and the
678    // motion, cut as a boolean rather than re-solved — because a motion whose
679    // answer needs a face to STOP EXISTING has no body for a repair to reach.
680    // A plane moved rigidly is still a plane, so the road takes a
681    // rotate-then-translate as well as a translation (the 2026-09-22 slot
682    // document with its wall also TURNED 16.9° refused here while the same
683    // drag without the turn built). See `edit/direct_edit/face_move_recut.rs`.
684    // It runs only after an acceptance refusal; a motion refused by the
685    // direct re-intersection solver never reaches it.
686    let moved = match crate::accept_sound(moved, "transformFace") {
687        Ok(body) => body,
688        Err(refusal) => {
689            match recut_past_a_refusal(solid, face_ids, turn, translation) {
690                Ok((body, lost)) => {
691                    notes.push(format!(
692                        "transformFace: the moved carriers could not be re-solved onto the body \
693                         they left ({refusal}), so the selection was RE-CUT from the original \
694                         body instead — the result is the boolean this motion defines, and a \
695                         face whose carrier left the body is no longer on it"
696                    ));
697                    notes.extend(lost);
698                    body
699                }
700                // A through bore's wall: the RE-DRILL road — the body with
701                // the bore healed shut, less the moved carrier run the body's
702                // whole way through (`edit/direct_edit/face_move_redrill.rs`).
703                // It answers a mouth straddling a corner, whose two crossing
704                // pairs the acceptance's repair does not take. The re-cut
705                // declines every curved carrier, so this is the only road
706                // left for a bore wall.
707                Err(reason) => match redrill_past_a_refusal(solid, face_ids, turn, translation) {
708                    Ok(body) => {
709                        notes.push(format!(
710                            "transformFace: the moved bore could not be re-trimmed onto the body \
711                             ({refusal}), so the bore was RE-DRILLED instead — the body with the \
712                             hole filled, less the moved carrier run the body's whole way through"
713                        ));
714                        body
715                    }
716                    // The acceptance's refusal stays the primary one — its
717                    // class is what the boundary reports, unless a road's
718                    // decline names the input (`with_declines_class`) — and
719                    // the other roads' declines are appended as context.
720                    Err(redrill) => {
721                        let combined = refusal.with_message(|refusal| {
722                            format!(
723                                "{refusal}. The re-cut road was offered it too and declined: \
724                                 {reason}. The re-drill road declined: {redrill}"
725                            )
726                        });
727                        return Err((with_declines_class(combined, &[&reason, &redrill]), None))
728                    }
729                },
730            }
731        }
732    };
733    Ok((moved, notes))
734}
735
736/// A refusal whose other roads declined too, their declines appended to its
737/// message by the caller: where a decline names the INPUT (ill-posed or
738/// invalid: the re-cut finding the motion takes away all of the body's
739/// material, or splits it), that is the act's answer and its class is the
740/// refusal's; otherwise the primary refusal's class stands.
741pub(crate) fn with_declines_class(mut refusal: KernelRefusal, declines: &[&KernelRefusal]) -> KernelRefusal {
742    use crate::RefusalClass::{IllPosed, InvalidInput};
743    if let Some(decline) = declines.iter().find(|d| matches!(d.class, IllPosed { .. } | InvalidInput { .. })) {
744        refusal.class = decline.class.clone();
745    }
746    refusal
747}
748
749/// The re-cut offered after the acceptance refused the moved body.
750///
751/// The body passes the SAME acceptance the primitives' body did: a boolean's
752/// output is sound by construction, so this is a check and not a repair, and a
753/// body it refuses is refused by name rather than returned. Fillets the re-cut
754/// filled in are then re-made one by one, and the second value names any that
755/// could not be.
756pub(crate) fn recut_past_a_refusal(
757    solid: &BrepSolid,
758    face_ids: &[u64],
759    turn: Option<(Vec3, Vec3, f64)>,
760    translation: Vec3,
761) -> Result<(BrepSolid, Vec<String>), KernelRefusal> {
762    let body = crate::recut_moved_planes_rigid(solid, face_ids, turn, translation)?;
763    let body = crate::accept_sound(body, "transformFace").map_err(|reason| {
764        reason.with_message(|reason| format!("the re-cut built a body the acceptance refused — {reason}"))
765    })?;
766    Ok(crate::reblend_lost_fillets(solid, face_ids, body))
767}
768
769/// The re-drill offered after the acceptance and the re-cut refused: checked
770/// by the same acceptance, as the re-cut's body is.
771fn redrill_past_a_refusal(
772    solid: &BrepSolid,
773    face_ids: &[u64],
774    turn: Option<(Vec3, Vec3, f64)>,
775    translation: Vec3,
776) -> Result<BrepSolid, KernelRefusal> {
777    let body = crate::redrill_moved_bore(solid, face_ids, turn, translation)?;
778    crate::accept_sound(body, "transformFace").map_err(|reason| {
779        reason.with_message(|reason| format!("the re-drill built a body the acceptance refused — {reason}"))
780    })
781}
782
783/// The translation primitive's refusal for a straight edge it inverts or
784/// collapses (`face_move.rs`).
785fn is_straight_edge_inversion(error: &KernelRefusal) -> bool {
786    matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what }
787        if what == crate::face_refusal_slugs::EDGE_INVERSION || what == "edge_collapse")
788}
789
790/// Whether a selected face has an inner loop (an island: a hole through it or
791/// a boss standing on it).
792fn has_island(solid: &BrepSolid, face_ids: &[u64]) -> bool {
793    solid
794        .shells
795        .iter()
796        .flat_map(|shell| &shell.faces)
797        .any(|face| face_ids.contains(&face.id) && face.loops.len() > 1)
798}
799
800/// The rotation primitive's refusal for a face tangent to a ruled neighbour.
801fn is_ruling_refusal(error: &KernelRefusal) -> bool {
802    matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "ruling_edge")
803}
804
805/// A refusal of either primitive that says the neighbour or section has NO
806/// ROUTE on that road — not that the motion inverts, collapses or tears
807/// something, which stay refusals: a carrier kind it does not re-intersect, a
808/// curved edge it cannot rebuild, a plane's section of a ruled wall it cannot
809/// mint, a slanted chord off its wall, a sphere rim it does not model.
810fn is_no_route_refusal(error: &KernelRefusal) -> bool {
811    const NO_ROUTE: &[&str] = &[
812        "carrier_kind",
813        "curved_edge_rebuild",
814        "curved_fixed_edge_pair",
815        "ruled_section",
816        "chord_off_carrier",
817        "both_nappes",
818        "asymptotic_ruling",
819        "section_through_apex",
820        "cap_through_apex",
821        "sphere_oblique_rim",
822        "sphere_mixed_neighbours",
823        "sphere_open_rim",
824        "sphere_group",
825        // A moved ruled or revolved wall whose corner touches two fixed flats
826        // (no one image for the corner on the re-solve): a through bore slid
827        // across its plate, answered by the re-drill.
828        "mirror_corner_flats",
829    ];
830    matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if NO_ROUTE.contains(&what.as_str()))
831}
832
833/// The two roads that answer a motion from the body's own regions rather than
834/// by re-solving: the region re-cut for planar faces
835/// ([`crate::recut_convex_body`]: the body is the intersection of its faces'
836/// regions), the re-drill for a through bore ([`crate::redrill_moved_bore`]).
837/// `Ok` carries the body and the note naming the road; `Err` the declines.
838fn by_regions(
839    solid: &BrepSolid,
840    face_ids: &[u64],
841    turn: Option<(Vec3, Vec3, f64)>,
842    translation: Vec3,
843) -> Result<(BrepSolid, String), String> {
844    let recut = match crate::recut_convex_body(solid, face_ids, turn, translation) {
845        Ok(body) => {
846            return Ok((
847                body,
848                "so the body was RE-CUT as the intersection of its faces' own regions with the moved \
849                 planes' — the body this motion defines"
850                    .to_string(),
851            ))
852        }
853        Err(reason) => reason,
854    };
855    match crate::redrill_moved_bore(solid, face_ids, turn, translation) {
856        Ok(body) => Ok((
857            body,
858            "so the bore was RE-DRILLED — the body with the hole filled, less the moved carrier run \
859             the body's whole way through"
860                .to_string(),
861        )),
862        Err(redrill) => Err(format!(
863            "The region re-cut was offered it too and declined: {recut}. The re-drill road declined: {redrill}"
864        )),
865    }
866}
867
868/// Context-bar applicability ([`crate::feature_pipeline::context_offer`]):
869/// selected faces drive `faces`.
870pub fn context_applicable(probe: &crate::feature_pipeline::SelectionProbe) -> bool {
871    probe.faces > 0
872}
873
874pub fn schema() -> serde_json::Value {
875    serde_json::json!({
876    "type": "TF",
877    "shortName": "TF",
878    "longName": "Transform Face",
879    "ribbonPath": "Home/Synchronous Modeling/Transform Face",
880    "commandSize": "Compact",
881    "displayBuilder": false,
882    "inputParamsSchema": {
883        "id": {
884            "type": "string",
885            "default_value": null,
886            "hint": "Optional identifier for the transform face feature"
887        },
888        "faces": {
889            "type": "reference_selection",
890            "selectionFilter": [
891                "FACE"
892            ],
893            "timestampDependency": "parentSolid",
894            "multiple": true,
895            "default_value": [],
896            "hint": "Select one or more faces on a single solid to move and turn"
897        },
898        "pivot": {
899            "type": "vec3",
900            "label": "Pivot",
901            "default_value": null,
902            "selectionFilter": ["VERTEX", "EDGE", "FACE"],
903            "hint": "The point the rotation turns about, in world millimetres; set to the centre of the selection when the faces are picked, or picked from a vertex, edge or face"
904        },
905        "transform": {
906            "type": "transform",
907            "default_value": {
908                "position": [0, 0, 0],
909                "rotationEuler": [0, 0, 0]
910            },
911            "hint": "Rotate the faces about the pivot, then move them; drag the gizmo or type the values"
912        }
913    }
914})
915}
916