Skip to main content

draftwright/
geometry_ids.rs

1//! Geometry-backed ladder identity, spans and drawing order. No saved-Spec migration state.
2use crate::model::Analysis;
3use std::collections::BTreeMap;
4
5const AXES: [&str; 3] = ["x", "y", "z"];
6fn thousandths(v: f64) -> i64 {
7    (v * 1000.).round() as i64
8}
9
10/// Coordinate spelling retained for genuinely faceless evidence and captured drawing claims.
11/// This grammar is independent of the spec/1–2 reader's compatibility window.
12pub(crate) fn coordinate_word(v: f64) -> String {
13    let t = thousandths(v);
14    let (sign, t) = if t < 0 { ("m", -t) } else { ("", t) };
15    let frac = format!("{:03}", t % 1000);
16    let frac = frac.trim_end_matches('0');
17    if frac.is_empty() {
18        format!("{sign}{}", t / 1000)
19    } else {
20        format!("{sign}{}_{frac}", t / 1000)
21    }
22}
23
24/// Principal plane identities from either immutable Analysis representation.
25fn plane_sites(a: &Analysis) -> Vec<(usize, usize, f64)> {
26    let mut out: Vec<_> = a
27        .face_attachments
28        .iter()
29        .enumerate()
30        .filter_map(|(face, f)| {
31            (f.surface.as_deref() == Some("plane")).then_some(())?;
32            Some((face, f.axis?, *f.support.first()?))
33        })
34        .collect();
35    if let Some(ink) = &a.edge_ink {
36        use crate::model::dimension_geometry::Reference;
37        for r in ink.references.values().flatten() {
38            if let Reference::Plane {
39                membership,
40                origin,
41                normal,
42                ..
43            } = r
44                && let Some(axis) = normal.iter().position(|n| n.abs() > 1. - 1e-8)
45            {
46                out.extend(membership.faces.iter().map(|&f| (f, axis, origin[axis])));
47            }
48        }
49    }
50    out
51}
52
53#[derive(Default)]
54struct Index {
55    planes: BTreeMap<(usize, i64), usize>,
56    heights: BTreeMap<i64, String>,
57    zs: Vec<f64>,
58    positions: BTreeMap<(usize, i64), String>,
59    spans: BTreeMap<String, (usize, f64, f64)>,
60    presentation: BTreeMap<String, String>,
61    stations: BTreeMap<String, String>,
62}
63
64impl Index {
65    fn new(a: &Analysis) -> Self {
66        let sites = plane_sites(a);
67        let mut out = Self::default();
68        for &(face, k, at) in &sites {
69            out.planes
70                .entry((k, thousandths(at)))
71                .and_modify(|f| *f = (*f).min(face))
72                .or_insert(face);
73        }
74        let mut supports = BTreeMap::<i64, usize>::new();
75        for support in &a.level_supports {
76            if let Some(&face) = support.faces.iter().min() {
77                supports
78                    .entry(thousandths(support.z))
79                    .and_modify(|f| *f = (*f).min(face))
80                    .or_insert(face);
81            }
82        }
83        out.zs = raw_heights(a);
84        for &z in &out.zs {
85            let face = supports
86                .get(&thousandths(z))
87                .or_else(|| out.planes.get(&(2, thousandths(z))));
88            let parameter = face.map_or_else(
89                || {
90                    format!(
91                        "step_height.length.h{}",
92                        coordinate_word(z - a.envelope[0][2])
93                    )
94                },
95                |f| format!("step_height.length.f{f}"),
96            );
97            out.heights.insert(thousandths(z), parameter.clone());
98            out.spans
99                .entry(parameter)
100                .or_insert((2, a.envelope[0][2], z));
101        }
102        let mut stations = BTreeMap::<(usize, i64), (f64, Option<usize>)>::new();
103        for riser in &a.risers {
104            for (axis, values) in [
105                (&riser.axis, &riser.positions),
106                (&riser.other_axis, &riser.other_positions),
107            ] {
108                let Some(k) = AXES.iter().position(|x| x == axis) else {
109                    continue;
110                };
111                for &at in values {
112                    let face = riser
113                        .faces
114                        .iter()
115                        .min()
116                        .copied()
117                        .or_else(|| out.planes.get(&(k, thousandths(at))).copied());
118                    stations
119                        .entry((k, thousandths((at - a.envelope[0][k]).abs())))
120                        .and_modify(|(_, f)| *f = f.iter().chain(face.iter()).min().copied())
121                        .or_insert((at, face));
122                }
123            }
124        }
125        let mut groups = BTreeMap::<usize, Vec<(usize, i64)>>::new();
126        for (&site, (_, face)) in &stations {
127            if let Some(face) = face {
128                groups.entry(*face).or_default().push(site);
129            }
130        }
131        for (face, group) in groups {
132            let shared = group.len() > 1;
133            for (i, site) in group.into_iter().enumerate() {
134                out.positions.insert(
135                    site,
136                    format!(
137                        "step_position.length.f{face}{}",
138                        if shared {
139                            format!("_{i}")
140                        } else {
141                            String::new()
142                        }
143                    ),
144                );
145            }
146        }
147        for (&site @ (k, v), &(at, _)) in &stations {
148            let parameter = out
149                .positions
150                .entry(site)
151                .or_insert_with(|| {
152                    format!(
153                        "step_position.length.{}{}",
154                        AXES[k],
155                        coordinate_word(v as f64 / 1000.)
156                    )
157                })
158                .clone();
159            out.spans
160                .entry(parameter)
161                .or_insert((k, a.envelope[0][k], at));
162        }
163        // Keep the previous principal-plane fallback order and riser precedence.
164        for &(_, k, at) in &sites {
165            if k < 2 {
166                let parameter = out.position(a, k, at);
167                out.spans
168                    .entry(parameter)
169                    .or_insert((k, a.envelope[0][k], at));
170            }
171        }
172        let mut first_orders = BTreeMap::new();
173        for f in &a.features {
174            first_orders
175                .entry(f.id.as_str())
176                .or_insert(f.presentation_order);
177        }
178        let mut families = BTreeMap::<String, Vec<&crate::bridge::Feature>>::new();
179        for f in &a.features {
180            if let Some((prefix, _)) = f.id.rsplit_once(':') {
181                families.entry(prefix.into()).or_default().push(f);
182            }
183        }
184        for (prefix, mut fs) in families {
185            fs.sort_by(|a, b| a.faces.cmp(&b.faces));
186            for (n, f) in fs.into_iter().enumerate() {
187                if automatic(&f.id) {
188                    out.presentation.entry(f.id.clone()).or_insert_with(|| {
189                        format!("{prefix}:{}", first_orders[&f.id.as_str()].unwrap_or(n + 1))
190                    });
191                }
192            }
193        }
194        if let Some(r) = &a.recognition {
195            let mut first_orders = BTreeMap::new();
196            for p in &r.patterns {
197                first_orders
198                    .entry(p.id.as_str())
199                    .or_insert(p.presentation_order);
200            }
201            let mut ps: Vec<_> = r.patterns.iter().collect();
202            ps.sort_by(|a, b| a.faces.cmp(&b.faces));
203            for (n, p) in ps.into_iter().enumerate() {
204                if automatic(&p.id) {
205                    out.presentation.entry(p.id.clone()).or_insert_with(|| {
206                        format!(
207                            "f:hole_pattern:{}",
208                            first_orders[&p.id.as_str()].unwrap_or(n + 1)
209                        )
210                    });
211                }
212            }
213        }
214        let patterns = a
215            .recognition
216            .as_ref()
217            .map_or(&[][..], |r| r.patterns.as_slice());
218        // Canonical face identity survives spelling changes, independently of migration aliases.
219        let features: Vec<_> = a.features.iter().filter(|f| !f.faces.is_empty()).collect();
220        let patterns: Vec<_> = patterns.iter().filter(|p| !p.faces.is_empty()).collect();
221        if let Ok(names) = face_names(
222            features
223                .iter()
224                .map(|f| (f.kind.as_str(), f.faces.as_slice()))
225                .chain(
226                    patterns
227                        .iter()
228                        .map(|p| ("hole_pattern", p.faces.as_slice())),
229                )
230                .collect(),
231        ) {
232            out.stations.extend(
233                features
234                    .iter()
235                    .map(|f| f.id.clone())
236                    .chain(patterns.iter().map(|p| p.id.clone()))
237                    .zip(names),
238            );
239        }
240        out
241    }
242    fn position(&self, a: &Analysis, k: usize, at: f64) -> String {
243        self.positions
244            .get(&(k, thousandths((at - a.envelope[0][k]).abs())))
245            .cloned()
246            .unwrap_or_else(|| {
247                self.planes.get(&(k, thousandths(at))).map_or_else(
248                    || {
249                        format!(
250                            "step_position.length.{}{}",
251                            AXES[k],
252                            coordinate_word((at - a.envelope[0][k]).abs())
253                        )
254                    },
255                    |f| format!("step_position.length.f{f}"),
256                )
257            })
258    }
259}
260
261fn automatic(id: &str) -> bool {
262    id.rsplit_once(':').is_some_and(|(prefix, anchor)| {
263        prefix != "f:declared"
264            && anchor.strip_prefix('f').is_some_and(|s| {
265                !s.is_empty()
266                    && s.split('_')
267                        .all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
268            })
269    })
270}
271
272// Lexically scoped immutable preparation. No persistent address cache: mutating an
273// Analysis between calls cannot reuse stale evidence, and nested inputs restore on exit.
274type ActiveIndex = Option<(usize, Option<std::rc::Rc<Index>>)>;
275thread_local! {
276    static ACTIVE: std::cell::RefCell<ActiveIndex> = const {std::cell::RefCell::new(None)};
277}
278pub(crate) fn with<T>(a: &Analysis, run: impl FnOnce() -> T) -> T {
279    let identity = a as *const Analysis as usize;
280    if ACTIVE.with(|v| v.borrow().as_ref().is_some_and(|(p, _)| *p == identity)) {
281        return run();
282    }
283    struct Restore(ActiveIndex);
284    impl Drop for Restore {
285        fn drop(&mut self) {
286            ACTIVE.with(|v| *v.borrow_mut() = self.0.take());
287        }
288    }
289    let _restore = Restore(ACTIVE.with(|v| v.replace(Some((identity, None)))));
290    run()
291}
292fn index(a: &Analysis) -> std::rc::Rc<Index> {
293    let identity = a as *const Analysis as usize;
294    if let Some(found) = ACTIVE.with(|v| {
295        v.borrow()
296            .as_ref()
297            .filter(|(p, _)| *p == identity)
298            .and_then(|(_, i)| i.clone())
299    }) {
300        return found;
301    }
302    let found = std::rc::Rc::new(Index::new(a));
303    ACTIVE.with(|v| {
304        if let Some((p, i)) = &mut *v.borrow_mut()
305            && *p == identity
306        {
307            *i = Some(found.clone());
308        }
309    });
310    found
311}
312
313pub(crate) fn height_parameter(a: &Analysis, z: f64) -> String {
314    let i = index(a);
315    i.heights.get(&thousandths(z)).cloned().unwrap_or_else(|| {
316        i.planes.get(&(2, thousandths(z))).map_or_else(
317            || {
318                format!(
319                    "step_height.length.h{}",
320                    coordinate_word(z - a.envelope[0][2])
321                )
322            },
323            |f| format!("step_height.length.f{f}"),
324        )
325    })
326}
327pub(crate) fn position_parameter(a: &Analysis, k: usize, at: f64) -> String {
328    index(a).position(a, k, at)
329}
330pub(crate) fn heights(a: &Analysis) -> Vec<f64> {
331    index(a).zs.clone()
332}
333pub(crate) fn parameter_span(a: &Analysis, parameter: &str) -> Option<(usize, f64, f64)> {
334    if !parameter.starts_with("step_height.length.")
335        && !parameter.starts_with("step_position.length.")
336    {
337        return None;
338    }
339    index(a).spans.get(parameter).copied()
340}
341impl Analysis {
342    /// The part axis of a live ladder item, determined from its face/riser geometry.
343    pub fn ladder_axis(&self, parameter: &str) -> Option<usize> {
344        parameter_span(self, parameter).map(|(k, _, _)| k)
345    }
346}
347fn raw_heights(a: &Analysis) -> Vec<f64> {
348    let mut zs: Vec<_> = a
349        .levels
350        .iter()
351        .copied()
352        .chain(a.level_supports.iter().map(|s| s.z))
353        .collect();
354    zs.sort_by(f64::total_cmp);
355    zs.dedup_by_key(|z| thousandths(*z));
356    zs
357}
358
359/// Historical drawing claims have their own coordinate grammar. Reading these claims is
360/// independent of reading legacy Specs; internal current-item spans never use this parser.
361pub(crate) fn coordinate_claim(a: &Analysis, parameter: &str) -> Option<(usize, f64, f64)> {
362    let number = |word: &str| {
363        let word = word
364            .strip_prefix('m')
365            .map_or_else(|| word.to_string(), |s| format!("-{s}"));
366        word.replace('_', ".").parse::<f64>().ok()
367    };
368    if let Some(word) = parameter.strip_prefix("step_height.length.h") {
369        return number(word).map(|v| (2, a.envelope[0][2], a.envelope[0][2] + v));
370    }
371    let word = parameter.strip_prefix("step_position.length.")?;
372    let k = AXES.iter().position(|x| word.starts_with(x))?;
373    number(&word[1..]).map(|v| (k, a.envelope[0][k], a.envelope[0][k] + v))
374}
375pub(crate) fn claim_parameter(a: &Analysis, parameter: &str) -> Option<String> {
376    let (k, _, at) = coordinate_claim(a, parameter)?;
377    Some(if k == 2 && parameter.starts_with("step_height.") {
378        height_parameter(a, at)
379    } else {
380        position_parameter(a, k, at)
381    })
382}
383
384/// Keep the geometric enumeration before cavity reconciliation removes contradictory records.
385/// These ordinals serve drawing order, not saved identity or migration.
386pub(crate) fn assign_presentation_order(
387    features: &mut [crate::bridge::Feature],
388    patterns: &mut [crate::bridge::HolePattern],
389) {
390    let mut indices: Vec<_> = (0..features.len()).collect();
391    indices.sort_by(|&i, &j| {
392        (&features[i].kind, &features[i].faces).cmp(&(&features[j].kind, &features[j].faces))
393    });
394    let mut previous = None;
395    let mut n = 0;
396    for i in indices {
397        if previous.as_ref() == Some(&features[i].kind) {
398            n += 1;
399        } else {
400            n = 1;
401        }
402        previous = Some(features[i].kind.clone());
403        features[i].presentation_order = Some(n);
404    }
405    let mut indices: Vec<_> = (0..patterns.len()).collect();
406    indices.sort_by(|&i, &j| patterns[i].faces.cmp(&patterns[j].faces));
407    for (n, i) in indices.into_iter().enumerate() {
408        patterns[i].presentation_order = Some(n + 1);
409    }
410}
411
412/// Decimal enumeration order preserves established drawing ties (10 precedes 2), without
413/// consulting legacy_id. Authored and opaque synthetic identities retain their own ordering.
414pub(crate) fn presentation_key<'a>(a: &Analysis, id: &'a str) -> std::borrow::Cow<'a, str> {
415    index(a)
416        .presentation
417        .get(id)
418        .map_or(std::borrow::Cow::Borrowed(id), |key| {
419            std::borrow::Cow::Owned(key.clone())
420        })
421}
422
423/// Unsigned key with exactly f64::total_cmp ordering (including signed zero).
424pub(crate) fn coordinate_order(value: f64) -> u64 {
425    let bits = value.to_bits();
426    bits ^ if bits >> 63 == 0 {
427        1_u64 << 63
428    } else {
429        u64::MAX
430    }
431}
432
433pub(crate) fn feature_names(
434    features: &[crate::bridge::Feature],
435    patterns: &[crate::bridge::HolePattern],
436) -> Result<Vec<String>, String> {
437    let records: Vec<_> = features
438        .iter()
439        .map(|f| (f.kind.as_str(), f.faces.as_slice()))
440        .chain(
441            patterns
442                .iter()
443                .map(|p| ("hole_pattern", p.faces.as_slice())),
444        )
445        .collect();
446    face_names(records)
447}
448
449fn face_names(records: Vec<(&str, &[usize])>) -> Result<Vec<String>, String> {
450    type Anchors<'a> = BTreeMap<(&'a str, usize), Vec<(usize, &'a [usize])>>;
451    let mut groups: Anchors<'_> = BTreeMap::new();
452    for (i, (kind, faces)) in records.iter().enumerate() {
453        let face = faces
454            .iter()
455            .min()
456            .ok_or_else(|| format!("{kind} has no faces to anchor its ID"))?;
457        groups.entry((kind, *face)).or_default().push((i, faces));
458    }
459    let mut names = vec![String::new(); records.len()];
460    for ((kind, face), mut group) in groups {
461        group.sort_by(|a, b| a.1.cmp(b.1));
462        let shared = group.len() > 1;
463        for (n, (i, _)) in group.into_iter().enumerate() {
464            names[i] = format!(
465                "f:{kind}:f{face}{}",
466                if shared {
467                    format!("_{n}")
468                } else {
469                    String::new()
470                }
471            );
472        }
473    }
474    Ok(names)
475}
476
477/// A scheme's geometric station identity, independent of its current reference spelling.
478pub(crate) fn station_key(a: &Analysis, reference: &str) -> String {
479    let (role, id) = ["start:", "end:", "axis:"]
480        .into_iter()
481        .find_map(|role| reference.strip_prefix(role).map(|id| (role, id)))
482        .unwrap_or(("", reference));
483    let index = index(a);
484    format!(
485        "{role}{}",
486        index.stations.get(id).map_or(id, String::as_str)
487    )
488}
489
490#[cfg(test)]
491mod tests {
492    #[test]
493    fn index_is_shared_within_a_scope_and_rebuilt_after_mutation() {
494        let mut a: crate::model::Analysis = serde_json::from_str(include_str!(
495            "../tests/fixtures/identity/m10020.analysis7.json"
496        ))
497        .unwrap();
498        let prepared = super::with(&a, || {
499            let first = super::index(&a);
500            super::with(&a, || {
501                assert!(std::rc::Rc::ptr_eq(&first, &super::index(&a)))
502            });
503            first
504        });
505        a.levels.push(12345.);
506        super::with(&a, || {
507            let next = super::index(&a);
508            assert!(!std::rc::Rc::ptr_eq(&prepared, &next));
509            assert!(next.zs.contains(&12345.));
510            assert!(!prepared.zs.contains(&12345.));
511        });
512    }
513    #[test]
514    fn coordinate_keys_preserve_total_float_order() {
515        let mut values = [f64::NAN, -0., f64::NEG_INFINITY, 4., 0., -4., f64::INFINITY];
516        let mut expected = values;
517        values.sort_by_key(|&v| super::coordinate_order(v));
518        expected.sort_by(f64::total_cmp);
519        assert_eq!(values.map(f64::to_bits), expected.map(f64::to_bits));
520    }
521}