brep_kernel/feature_pipeline/features/sketch/loop_ids.rs
1//! Stable per-LOOP identity for a sketch's closed loops.
2//!
3//! # Why
4//!
5//! A profile-swept feature (extrude/sweep/revolve/loft/path-sweep) builds one
6//! prism per profile REGION and stamps names on the result. Sidewalls are safe:
7//! they are named from the source geometry's persistent `{sketchId}:G{gid}`. The
8//! CAPS were not — every region stamped the SAME `{cap_base}_START/_END`, so the
9//! post-union `ensure_unique_face_names` pass disambiguated them POSITIONALLY
10//! (`X[0]`, `X[1]`, …) in shell/face encounter order. Editing the sketch to add
11//! or remove a loop shifted those indices, and a fillet that referenced `X[1]`
12//! silently jumped to a different island on replay.
13//!
14//! The fix is to give every loop an identity of its own that the cap names embed.
15//! That identity must survive editing the loop itself, so it is PERSISTED: each
16//! sketch geometry carries a `loopId` in `persistentData.sketch`, written back by
17//! the editor on commit (`assign_sketch_loop_ids`).
18//!
19//! # The rule
20//!
21//! For each assembled closed loop:
22//! - if ANY member edge carries a stored `loopId`, the loop claims the LOWEST of
23//! them ("lowest number wins") and that value is written back onto every other
24//! member edge, so the loop keeps its identity as edges come and go;
25//! - otherwise the loop is new and SEEDS its id from the lowest geometry id
26//! among its edges.
27//!
28//! Both halves are computed the same way whether or not the document has ever
29//! been committed, so a sketch that has never been through the editor derives
30//! exactly the id it would have been assigned — reading and writing never
31//! disagree, and no document renames faces merely by being opened.
32//!
33//! # Resilience
34//!
35//! - ADDING an edge to a loop: the new edge carries no id and inherits the
36//! loop's — unchanged. (Minting also hands out ids above the current maximum,
37//! so a seed can only move down, never up.)
38//! - REMOVING a non-anchor edge: the id lives on the survivors — unchanged.
39//! - REMOVING the anchor edge (the one the id was seeded from): still unchanged,
40//! because the id was persisted onto the whole loop, not recomputed from the
41//! anchor. This is the case a derive-only scheme cannot handle, and the reason
42//! the id is stored at all.
43//! - Editing a DIFFERENT loop: never observed here — a loop's claim reads only
44//! its own edges. That is the reported bug, fixed.
45//!
46//! # Collisions
47//!
48//! Two loops can claim the same id: a loop that SPLIT in two (both halves carry
49//! the same stored id), or — because the editor mints `max(existing gid) + 1` and
50//! therefore REUSES the ids of deleted geometry — a freshly drawn loop whose
51//! seed collides with an older loop's stored id. Ties break in this order:
52//! 1. a loop that INHERITED the id (stored on its edges) beats one that merely
53//! seeded it from a gid, so a new loop can never steal a live loop's identity;
54//! 2. between two inheritors (the split case), the one holding the lower minimum
55//! gid keeps it — deterministic, and independent of loop order.
56//! The loser re-seeds from its own lowest gid, or, if that is taken too, from one
57//! above the highest id in play. A split therefore keeps the original id on one
58//! half and mints a fresh one for the other; if the halves are later rejoined,
59//! the survivor's id wins again.
60
61use super::geometry::Loop;
62
63/// Resolve every loop's [`Loop::loop_id`], in place.
64///
65/// `loops` is the fully assembled set (chained loops plus whole circles and
66/// ellipses) BEFORE region classification, so ids are decided over the sketch as
67/// a whole and never depend on how the loops later group into regions.
68pub(super) fn resolve(loops: &mut [Loop]) {
69 let claims: Vec<Claim> = loops.iter().map(Claim::of).collect();
70 for (loop_data, id) in loops.iter_mut().zip(settle(&claims)) {
71 loop_data.loop_id = id;
72 }
73}
74
75/// One loop's claim: the id it wants, whether it INHERITED that id from stored
76/// geometry (as opposed to seeding it from a gid), and its lowest gid — the
77/// tie-break and the re-seed source.
78struct Claim {
79 id: Option<u64>,
80 inherited: bool,
81 min_gid: Option<u64>,
82}
83
84impl Claim {
85 fn of(loop_data: &Loop) -> Self {
86 let stored = loop_data
87 .entries
88 .iter()
89 .filter_map(|(segment, _)| segment.ids.loop_id)
90 .min();
91 let min_gid = loop_data
92 .entries
93 .iter()
94 .filter_map(|(segment, _)| segment.ids.gid)
95 .min();
96 Self {
97 id: stored.or(min_gid),
98 inherited: stored.is_some(),
99 min_gid,
100 }
101 }
102}
103
104/// Award each claim a UNIQUE id, applying the tie-break rules in the module doc.
105/// Returns one id per claim, in input order.
106fn settle(claims: &[Claim]) -> Vec<Option<u64>> {
107 // Award order: inheritors first (they cannot be displaced by a seeder), then
108 // by ascending minimum gid, then by input position — a total order, so the
109 // outcome never depends on the order the loops happened to be assembled in.
110 let mut order: Vec<usize> = (0..claims.len()).collect();
111 order.sort_by_key(|&index| {
112 let claim = &claims[index];
113 (!claim.inherited, claim.min_gid.unwrap_or(u64::MAX), index)
114 });
115
116 let mut taken: Vec<u64> = Vec::with_capacity(claims.len());
117 let mut resolved = vec![None; claims.len()];
118 for index in order {
119 let claim = &claims[index];
120 let Some(wanted) = claim.id else { continue };
121 let id = if taken.contains(&wanted) {
122 // Displaced: fall back to this loop's own lowest gid, else to one
123 // above everything in play (ids are just numbers — a re-seed is free
124 // to leave the gid space).
125 let own = claim.min_gid.filter(|gid| !taken.contains(gid));
126 own.unwrap_or_else(|| next_free(claims, &taken))
127 } else {
128 wanted
129 };
130 taken.push(id);
131 resolved[index] = Some(id);
132 }
133 resolved
134}
135
136/// One above the highest id anywhere in play (awarded, claimed, or a gid) — the
137/// last-resort id for a loop displaced off both its stored id and its own gid.
138fn next_free(claims: &[Claim], taken: &[u64]) -> u64 {
139 let highest = taken
140 .iter()
141 .copied()
142 .chain(claims.iter().flat_map(|claim| claim.id.into_iter()))
143 .chain(claims.iter().flat_map(|claim| claim.min_gid.into_iter()))
144 .max()
145 .unwrap_or(0);
146 highest.saturating_add(1)
147}
148
149// BREP private tests: 836b0104a3a028ba
150
151// ===========================================================================
152// Write-back — the editor side
153// ===========================================================================
154
155/// Assign every closed loop's id onto the geometries of a SOLVED sketch document,
156/// in place, and report whether anything changed.
157///
158/// This is the persistence half of the scheme: the kernel DERIVES ids the same
159/// way every run (so a document that has never been through here still names its
160/// faces correctly), and this writes the derived ids down so they survive the one
161/// edit deriving cannot: deleting the edge an id was seeded from. The editor calls
162/// it when a sketch is committed.
163///
164/// `doc` is the `persistentData.sketch` object. Geometry that is construction-only
165/// or not part of a closed loop is left untouched — only a loop has an identity.
166pub fn assign_sketch_loop_ids(doc: &mut serde_json::Value) -> bool {
167 let Some(loops) = closed_loops(doc) else {
168 return false;
169 };
170 let mut changed = false;
171 let Some(geometries) = doc
172 .get_mut("geometries")
173 .and_then(serde_json::Value::as_array_mut)
174 else {
175 return false;
176 };
177 for geometry in geometries.iter_mut() {
178 let Some(gid) = geometry.get("id").and_then(numeric) else {
179 continue;
180 };
181 let Some(loop_id) = loops.get(&gid) else {
182 continue;
183 };
184 let already = geometry.get("loopId").and_then(numeric);
185 if already == Some(*loop_id) {
186 continue;
187 }
188 if let Some(object) = geometry.as_object_mut() {
189 object.insert("loopId".into(), serde_json::json!(loop_id));
190 changed = true;
191 }
192 }
193 changed
194}
195
196/// `geometry id -> loop id` for every geometry that belongs to a closed loop,
197/// derived exactly as the sketch feature derives it: chain the segments, settle
198/// the claims, then hand each loop's awarded id to ALL of its members ("lowest
199/// number wins and updates the rest of the edges in that loop to match").
200fn closed_loops(doc: &serde_json::Value) -> Option<std::collections::HashMap<u64, u64>> {
201 let members = loop_members(doc)?;
202 let claims: Vec<Claim> = members
203 .iter()
204 .map(|edges| {
205 let stored = edges.iter().filter_map(|(_, stored)| *stored).min();
206 let min_gid = edges.iter().map(|(gid, _)| *gid).min();
207 Claim {
208 id: stored.or(min_gid),
209 inherited: stored.is_some(),
210 min_gid,
211 }
212 })
213 .collect();
214 let mut assignment = std::collections::HashMap::new();
215 for (edges, id) in members.iter().zip(settle(&claims)) {
216 let Some(id) = id else { continue };
217 for (gid, _) in edges {
218 assignment.insert(*gid, id);
219 }
220 }
221 Some(assignment)
222}
223
224/// Group the document's model geometry into closed loops, as
225/// `(geometry id, stored loop id)` per member.
226///
227/// Whole circles and ellipses are loops on their own. The rest chain end-to-end
228/// through shared POINT ids — the same adjacency the profile chainer walks, read
229/// off the document's point references rather than solved coordinates, which is
230/// exact and needs no tolerance. A chain is closed when it returns to its start.
231///
232/// At a BRANCHING junction (three or more segments meeting at one point — not a
233/// well-formed profile) this walk takes the first candidate, which may group the
234/// edges differently than the profile chainer does. That degrades safely rather
235/// than corrupting anything: the kernel resolves each loop's id from the ids
236/// stored on ITS OWN edges, so a mis-grouped stamp at worst makes two loops claim
237/// the same id, which [`settle`] then breaks apart deterministically.
238fn loop_members(doc: &serde_json::Value) -> Option<Vec<Vec<(u64, Option<u64>)>>> {
239 let geometries = doc.get("geometries")?.as_array()?;
240 let mut loops: Vec<Vec<(u64, Option<u64>)>> = Vec::new();
241 // (gid, stored, endpoint a, endpoint b) for the chainable segments.
242 let mut segments: Vec<(u64, Option<u64>, u64, u64)> = Vec::new();
243 for geometry in geometries {
244 if geometry.get("construction").and_then(serde_json::Value::as_bool) == Some(true) {
245 continue;
246 }
247 let Some(gid) = geometry.get("id").and_then(numeric) else {
248 continue;
249 };
250 let stored = geometry.get("loopId").and_then(numeric);
251 let geom_type = geometry
252 .get("type")
253 .and_then(serde_json::Value::as_str)
254 .unwrap_or("");
255 let points: Vec<u64> = geometry
256 .get("points")
257 .and_then(serde_json::Value::as_array)
258 .map(|ids| ids.iter().filter_map(numeric).collect())
259 .unwrap_or_default();
260 match geom_type {
261 // Self-contained loops.
262 "circle" | "ellipse" => loops.push(vec![(gid, stored)]),
263 // `[start, end]`.
264 "line" if points.len() == 2 => segments.push((gid, stored, points[0], points[1])),
265 // `[center, start, end]`.
266 "arc" if points.len() == 3 => segments.push((gid, stored, points[1], points[2])),
267 // `[p0, …, pn]` — the spline's endpoints are its first and last.
268 "bezier" if points.len() >= 2 => {
269 segments.push((gid, stored, points[0], points[points.len() - 1]))
270 }
271 _ => {}
272 }
273 }
274
275 // Walk each connected component; keep it only if it closes.
276 let mut visited = vec![false; segments.len()];
277 for start in 0..segments.len() {
278 if visited[start] {
279 continue;
280 }
281 let (_, _, first_point, _) = segments[start];
282 let mut chain = vec![start];
283 visited[start] = true;
284 let mut tail = segments[start].3;
285 loop {
286 if tail == first_point {
287 // Closed: a chain of one segment closes only if it is a loop on
288 // its own (a full-circle arc), which the endpoints already say.
289 loops.push(
290 chain
291 .iter()
292 .map(|&index| (segments[index].0, segments[index].1))
293 .collect(),
294 );
295 break;
296 }
297 let next = (0..segments.len()).find(|&index| {
298 !visited[index] && (segments[index].2 == tail || segments[index].3 == tail)
299 });
300 let Some(next) = next else { break };
301 visited[next] = true;
302 chain.push(next);
303 tail = if segments[next].2 == tail {
304 segments[next].3
305 } else {
306 segments[next].2
307 };
308 }
309 }
310 Some(loops)
311}
312
313/// A JSON id as a number (a numeric string counts) — the write-back's copy of the
314/// sketch pipeline's `numeric_id`, so both halves read ids identically.
315fn numeric(value: &serde_json::Value) -> Option<u64> {
316 match value {
317 serde_json::Value::Number(number) => number.as_u64(),
318 serde_json::Value::String(text) => text.parse().ok(),
319 _ => None,
320 }
321}
322
323// BREP private tests: ef961a0422cc988b