use std::collections::HashSet;
use crate::feature_pipeline::features::common;
use crate::feature_pipeline::{AddedSolid, FeatureContext, FeatureRefusal, FeatureResult};
use crate::{move_faces_unchecked, AnalyticSurface, BrepSolid, Vec3};
pub fn execute(ctx: &FeatureContext) -> FeatureResult {
match build(ctx) {
Ok(result) => result,
Err(error) => ctx.fail(error),
}
}
fn build(ctx: &FeatureContext) -> Result<FeatureResult, FeatureRefusal> {
let mut result = FeatureResult::empty(ctx.id.clone(), ctx.feature_type.clone());
let names = common::reference_name_array(ctx.param("faces"));
if names.is_empty() {
return Ok(result); }
let mut resolved: Vec<(u32, u64)> = Vec::new();
for name in &names {
match ctx.scene.resolve_face(name) {
Some(face_ref) => resolved.push((face_ref.handle, face_ref.face_id)),
None => result.unresolved.push(name.clone()),
}
}
if resolved.is_empty() {
return Ok(result); }
let handles: HashSet<u32> = resolved.iter().map(|(handle, _)| *handle).collect();
if handles.len() > 1 {
return Ok(result); }
let target_handle = resolved[0].0;
let distance = match ctx.param("distance") {
None | Some(serde_json::Value::Null) => return Ok(result),
Some(_) => ctx.number("distance")?,
};
if !distance.is_finite() || distance.abs() <= 1e-12 {
return Ok(result);
}
result.note_partial_resolution(&names);
let mut seen: HashSet<u64> = HashSet::new();
let face_ids: Vec<u64> = resolved
.iter()
.map(|(_, face_id)| *face_id)
.filter(|face_id| seen.insert(*face_id))
.collect();
let target_name = ctx
.scene
.solids
.iter()
.find(|(_, handle)| **handle == target_handle)
.map(|(name, _)| name.clone())
.ok_or("push_face: target solid has no scene-map name")?;
let solid = crate::with_registered_solid_str(target_handle, |solid| Ok(solid.clone()))?;
let solid = push_faces(solid, &face_ids, distance, &mut result.notes, true)?;
let face_names = common::collect_face_names(&solid);
let edge_names = common::collect_edge_names(&solid);
let handle = crate::register_solid_value(solid);
result.added.push(AddedSolid {
handle,
name: target_name.clone(),
face_names,
edge_names,
..AddedSolid::default()
});
result.removed.push(target_name);
Ok(result)
}
pub(crate) fn push_faces(
mut solid: BrepSolid,
face_ids: &[u64],
distance: f64,
notes_out: &mut Vec<String>,
past_neighbours: bool,
) -> Result<BrepSolid, FeatureRefusal> {
let mut face_ids = merge_selected_ruled_pieces(&mut solid, face_ids)?;
for index in 0..face_ids.len() {
let id = face_ids[index];
let face_id = &id;
let mut followed: Option<Vec<u64>> = None;
match face_carrier(&solid, *face_id)? {
FaceCarrier::Planar => {
let normal = planar_face_normal(&solid, *face_id)?;
solid = match move_faces_unchecked(&solid, &[*face_id], normal.scale(distance)) {
Ok(pushed) => pushed,
Err(refusal) if !past_neighbours && is_inversion(&refusal) => {
return Err(crate::KernelRefusal::ill_posed(
crate::KernelStage::Refine,
"pushed_past_a_neighbour",
format!("offset_faces: the face is carried past a neighbour it was to meet ({refusal})"),
)
.into())
}
Err(refusal)
if !past_neighbours
&& is_collapse_or_inversion(&refusal)
&& passes_a_neighbour_short_of(&solid, *face_id, normal, distance) =>
{
return Err(crate::KernelRefusal::ill_posed(
crate::KernelStage::Refine,
"pushed_past_a_neighbour",
format!("offset_faces: the face is carried past a neighbour it was to meet, landing on another ({refusal})"),
)
.into())
}
Err(refusal) if is_collapse_or_inversion(&refusal) => {
match super::transform_face::recut_past_a_refusal(&solid, &[*face_id], None, normal.scale(distance)) {
Ok((body, lost)) => {
notes_out.push(format!(
"pushFace: the pushed face could not be re-solved ({refusal}), so it was \
RE-CUT from the body instead: the boolean this push defines"
));
notes_out.extend(lost);
followed = Some(follow_by_name(&solid, &body, &face_ids[index + 1..])?);
body
}
Err(reason) => {
let combined = refusal
.with_message(|refusal| format!("{refusal}. The re-cut road was offered it too and declined: {reason}"));
return Err(super::transform_face::with_declines_class(combined, &[&reason]).into())
}
}
}
Err(refusal) => {
let without = crate::rebuild_displaced_blends(&solid, &[*face_id], "pushFace", |sharp| {
let pushed = move_faces_unchecked(sharp, &[*face_id], normal.scale(distance))?;
Ok((crate::accept_sound(pushed, "pushFace")?, Vec::new()))
});
match without {
None => return Err(refusal.into()),
Some(Err(decline)) => {
return Err(crate::with_blend_rebuild_decline(refusal, &decline).into())
}
Some(Ok((pushed, notes))) => {
notes_out.extend(notes);
pushed
}
}
}
};
}
FaceCarrier::Ruled => {
solid = match crate::offset_ruled_face_unchecked(&solid, *face_id, distance) {
Ok(pushed) => pushed,
Err(refusal) => return Err(name_unselected_sibling(&solid, *face_id, refusal).into()),
};
}
FaceCarrier::Sphere => {
solid = crate::offset_sphere_face_unchecked(&solid, *face_id, distance)?;
}
FaceCarrier::Torus => {
solid = crate::offset_torus_face_unchecked(&solid, *face_id, distance)?;
}
FaceCarrier::Revolution => {
solid = crate::offset_revolution_face_unchecked(&solid, *face_id, distance)?;
}
FaceCarrier::Freeform => {
solid = crate::offset_freeform_face_unchecked(&solid, *face_id, distance)?;
}
}
if let Some(rest) = followed {
face_ids.truncate(index + 1);
face_ids.extend(rest);
}
}
let solid = crate::accept_sound(solid, "pushFace")?;
Ok(solid)
}
fn follow_by_name(before: &BrepSolid, after: &BrepSolid, ids: &[u64]) -> Result<Vec<u64>, crate::KernelRefusal> {
fn faces(solid: &BrepSolid) -> Vec<&crate::FaceRecord> {
solid.shells.iter().flat_map(|shell| &shell.faces).collect()
}
let (old, new) = (faces(before), faces(after));
let scale = crate::solid_model_scale(before).max(1.0);
let lost = |id: u64| {
crate::KernelRefusal::unsupported(
crate::KernelStage::Collect,
"recut_lost_selection",
format!("pushFace: a push was re-cut, which numbers the body's faces afresh, and face {id} still to push cannot be found in it"),
)
};
let area = |face: &crate::FaceRecord| crate::face_area(face).ok();
let corners = |solid: &BrepSolid, face: &crate::FaceRecord| -> Vec<[f64; 3]> {
let mut ids: Vec<u64> = face
.loops
.iter()
.flat_map(|lp| &lp.coedges)
.filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
.flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
.collect();
ids.sort_unstable();
ids.dedup();
let mut points: Vec<[f64; 3]> = ids.iter().filter_map(|id| solid.vertices.iter().find(|v| v.id == *id)).map(|v| [v.point.x, v.point.y, v.point.z]).collect();
points.sort_by(|a, b| a.iter().zip(b).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal));
points
};
let same_corners = |a: &[[f64; 3]], b: &[[f64; 3]]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (0..3).all(|k| (p[k] - q[k]).abs() <= 1e-9 * scale));
ids.iter()
.map(|&id| {
let face = old.iter().find(|face| face.id == id).ok_or_else(|| lost(id))?;
let was = corners(before, face);
let kept = |other: &crate::FaceRecord| same_corners(&was, &corners(after, other));
if let Some(name) = face.name.as_deref() {
let named_old: Vec<&crate::FaceRecord> = old.iter().filter(|f| f.name.as_deref() == Some(name)).copied().collect();
let named_new: Vec<&crate::FaceRecord> = new.iter().filter(|f| f.name.as_deref() == Some(name)).copied().collect();
if let ([_], [found]) = (named_old.as_slice(), named_new.as_slice()) {
if kept(found) {
return Ok(found.id);
}
}
}
let (Ok([u0, u1]), Ok([v0, v1])) = (face.surface.domain_u(), face.surface.domain_v()) else { return Err(lost(id)) };
let probes: Vec<crate::Vec3> = [(0.25, 0.25), (0.75, 0.3), (0.4, 0.8)]
.iter()
.filter_map(|&(a, b)| face.surface.evaluate(u0 + a * (u1 - u0), v0 + b * (v1 - v0)).ok())
.collect();
let want = area(face).ok_or_else(|| lost(id))?;
let matches: Vec<u64> = new
.iter()
.filter(|other| other.same_sense == face.same_sense)
.filter(|other| probes.len() == 3 && probes.iter().all(|&p| crate::project_point_to_surface(&other.surface, p).map_or(false, |hit| hit.distance <= 1e-9 * scale)))
.filter(|other| area(other).is_some_and(|got| (got - want).abs() <= 1e-9 * want.abs().max(1e-300)))
.filter(|other| kept(other))
.map(|other| other.id)
.collect();
match matches.as_slice() {
[found] => Ok(*found),
_ => Err(lost(id)),
}
})
.collect()
}
fn passes_a_neighbour_short_of(solid: &BrepSolid, face_id: u64, normal: Vec3, distance: f64) -> bool {
let step = 2.0 * (crate::solid_model_scale(solid) * 1e-7).max(1e-9);
let mut short = distance;
for _ in 0..16 {
short -= step.copysign(distance);
if short * distance <= 0.0 {
return false;
}
match move_faces_unchecked(solid, &[face_id], normal.scale(short)) {
Err(refusal) if is_inversion(&refusal) => return true,
Err(refusal) if is_collapse_or_inversion(&refusal) => continue,
_ => return false,
}
}
false
}
fn is_inversion(refusal: &crate::KernelRefusal) -> bool {
matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == crate::face_refusal_slugs::EDGE_INVERSION)
}
fn is_collapse_or_inversion(refusal: &crate::KernelRefusal) -> bool {
matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what }
if what == "edge_collapse" || what == crate::face_refusal_slugs::EDGE_INVERSION)
}
fn merge_selected_ruled_pieces(solid: &mut BrepSolid, face_ids: &[u64]) -> Result<Vec<u64>, crate::KernelRefusal> {
let ruled: Vec<u64> = face_ids
.iter()
.copied()
.filter(|id| matches!(face_carrier(solid, *id), Ok(FaceCarrier::Ruled)))
.collect();
if ruled.len() < 2 {
return Ok(face_ids.to_vec());
}
let (merged, carried_by) = crate::merge_faces_within(solid, PIECE_MERGE_TOLERANCE, &ruled)?;
*solid = merged;
let mut seen: HashSet<u64> = HashSet::new();
Ok(face_ids
.iter()
.map(|id| {
carried_by
.iter()
.find(|(face, _)| face == id)
.map(|(_, carrier)| *carrier)
.unwrap_or(*id)
})
.filter(|id| seen.insert(*id))
.collect())
}
const PIECE_MERGE_TOLERANCE: f64 = 1e-7;
fn name_unselected_sibling(solid: &BrepSolid, face_id: u64, refusal: crate::KernelRefusal) -> crate::KernelRefusal {
let edges_of = |id: u64| -> HashSet<u64> {
solid
.shells
.iter()
.flat_map(|shell| &shell.faces)
.filter(|face| face.id == id)
.flat_map(|face| &face.loops)
.flat_map(|loop_record| &loop_record.coedges)
.map(|coedge| coedge.edge_id)
.collect()
};
let own = edges_of(face_id);
let siblings: Vec<&crate::FaceRecord> = solid
.shells
.iter()
.flat_map(|shell| &shell.faces)
.filter(|face| {
face.id != face_id
&& matches!(face.surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. }))
&& !edges_of(face.id).is_disjoint(&own)
})
.collect();
for sibling in siblings {
let Ok((_, carried_by)) = crate::merge_faces_within(solid, PIECE_MERGE_TOLERANCE, &[face_id, sibling.id]) else {
continue;
};
if carried_by.iter().all(|(_, carrier)| *carrier == carried_by[0].1) {
let name = sibling.name.clone().unwrap_or_else(|| format!("face {}", sibling.id));
return crate::KernelRefusal::input(
crate::KernelStage::Collect,
"split_carrier_piece",
format!(
"push_face: face {face_id} is one piece of a cylinder/cone split into several faces; \
select its sibling `{name}` too so the whole carrier is pushed ({})",
refusal.message
),
);
}
}
refusal
}
enum FaceCarrier {
Planar,
Ruled,
Sphere,
Torus,
Revolution,
Freeform,
}
fn face_carrier(solid: &BrepSolid, face_id: u64) -> Result<FaceCarrier, String> {
for shell in &solid.shells {
for face in &shell.faces {
if face.id != face_id {
continue;
}
return match face.surface.analytic() {
Some(AnalyticSurface::Plane { .. }) => Ok(FaceCarrier::Planar),
Some(AnalyticSurface::RuledRevolution { .. }) => Ok(FaceCarrier::Ruled),
Some(AnalyticSurface::Sphere { .. }) => Ok(FaceCarrier::Sphere),
Some(AnalyticSurface::Torus { .. }) => Ok(FaceCarrier::Torus),
Some(AnalyticSurface::Revolution { .. }) => Ok(FaceCarrier::Revolution),
None => Ok(FaceCarrier::Freeform),
};
}
}
Err(format!("push_face: face id {face_id} not found"))
}
fn planar_face_normal(solid: &BrepSolid, face_id: u64) -> Result<Vec3, 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 { .. })) {
return Err(
"push_face: only planar faces are migrated (cylindrical radius-delta \
and other curved carriers are deferred)"
.into(),
);
}
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 mut normal = face.surface.normal(um, vm)?;
if !face.same_sense {
normal = normal.scale(-1.0);
}
return Ok(normal);
}
}
Err(format!("push_face: face id {face_id} not found"))
}
pub fn context_applicable(probe: &crate::feature_pipeline::SelectionProbe) -> bool {
probe.faces > 0
}
pub fn schema() -> serde_json::Value {
serde_json::json!({
"type": "PF",
"shortName": "PF",
"longName": "Push Face",
"ribbonPath": "Home/Synchronous Modeling/Push Face",
"commandSize": "Compact",
"displayBuilder": false,
"inputParamsSchema": {
"id": {
"type": "string",
"default_value": null,
"hint": "Optional identifier for the push face feature"
},
"faces": {
"type": "reference_selection",
"selectionFilter": [
"FACE"
],
"timestampDependency": "parentSolid",
"multiple": true,
"default_value": [],
"hint": "Select one or more faces on a single solid to push"
},
"distance": {
"type": "number",
"default_value": 1,
"hint": "Signed distance to push the selected faces along their normals"
}
}
})
}