ifc_lite_processing/
result_fingerprint.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! A complete, ordered fingerprint of a [`ProcessingResult`]: every field,
6//! including the `#[serde(skip)]` in-memory ones (`instance`, `local_bounds`,
7//! `local_to_world`, `presentation`), text metadata, UVs, texture bytes and
8//! which meshes share one texture allocation, instances, the frame, transforms,
9//! metadata and diagnostics. Floats feed their exact IEEE bits, so `-0.0` and
10//! NaN payloads count. Every struct is destructured in full, so a new field is
11//! a compile error here until it is classified.
12//!
13//! It exists to check the result cache's replay, so it is written separately
14//! from the cache codec and never calls it: a field the codec drops still
15//! changes this digest. `perf_probe --result-fingerprint` prints it.
16//!
17//! Diagnostics are walked field by field too, never through serde, whose
18//! JSON form cannot tell NaN payloads or infinities apart.
19//!
20//! Two kinds of field are left out, stated rather than hidden:
21//! [`ProcessingStats::from_cache`] (a replay sets it; that is its job) and,
22//! unless `include_timings`, the wall-clock `*_time_ms` fields, which differ
23//! between any two cold runs.
24
25use crate::types::mesh::{InstanceRecord, MeshData, MeshTextureData};
26use crate::types::presentation::{
27    MeshPresentationProvenance, NormalProvenance, PaletteAbsence, PaletteBinding, TextureBinding, UvAuthority,
28};
29use crate::{MeshFrame, ProcessingResult};
30use ifc_lite_geometry::InstanceMeta;
31use sha2::{Digest, Sha256};
32use std::collections::HashMap;
33
34#[path = "result_fingerprint_stats.rs"]
35mod stats;
36use stats::{metadata_fp, stats_fp};
37
38struct Fp(Sha256);
39
40impl Fp {
41    fn raw(&mut self, bytes: &[u8]) {
42        self.0.update(bytes);
43    }
44    fn len(&mut self, n: usize) {
45        self.raw(&(n as u64).to_le_bytes());
46    }
47    fn u8(&mut self, v: u8) {
48        self.raw(&[v]);
49    }
50    fn bool(&mut self, v: bool) {
51        self.u8(u8::from(v));
52    }
53    fn u32(&mut self, v: u32) {
54        self.raw(&v.to_le_bytes());
55    }
56    fn u64(&mut self, v: u64) {
57        self.raw(&v.to_le_bytes());
58    }
59    fn f32s(&mut self, v: &[f32]) {
60        self.len(v.len());
61        v.iter().for_each(|x| self.raw(&x.to_bits().to_le_bytes()));
62    }
63    fn f64s(&mut self, v: &[f64]) {
64        self.len(v.len());
65        v.iter().for_each(|x| self.raw(&x.to_bits().to_le_bytes()));
66    }
67    fn str(&mut self, s: &str) {
68        self.len(s.len());
69        self.raw(s.as_bytes());
70    }
71    fn opt<T>(&mut self, v: Option<T>, f: impl FnOnce(&mut Self, T)) {
72        self.bool(v.is_some());
73        if let Some(v) = v {
74            f(self, v);
75        }
76    }
77    fn opt_str(&mut self, v: &Option<String>) {
78        self.opt(v.as_deref(), |h, s| h.str(s));
79    }
80}
81
82/// Lowercase hex SHA-256 over the whole result (see the module docs for the
83/// two excluded field kinds).
84pub fn result_fingerprint(result: &ProcessingResult, include_timings: bool) -> String {
85    let ProcessingResult {
86        meshes,
87        instances,
88        mesh_coordinate_space,
89        frame,
90        site_transform,
91        building_transform,
92        metadata,
93        stats,
94    } = result;
95    let mut h = Fp(Sha256::new());
96    h.raw(b"ifc-lite-result-fingerprint-v1");
97    h.len(meshes.len());
98    let mut texture_owner: HashMap<*const Vec<u8>, usize> = HashMap::new();
99    for (index, mesh) in meshes.iter().enumerate() {
100        mesh_fp(&mut h, mesh, index, &mut texture_owner);
101    }
102    h.len(instances.len());
103    instances.iter().for_each(|r| instance_record_fp(&mut h, r));
104    h.u8(*mesh_coordinate_space as u8);
105    frame_fp(&mut h, frame);
106    h.opt(site_transform.as_deref(), |h, v| h.f64s(v));
107    h.opt(building_transform.as_deref(), |h, v| h.f64s(v));
108    metadata_fp(&mut h, metadata);
109    stats_fp(&mut h, stats, include_timings);
110    h.0.finalize().iter().map(|b| format!("{b:02x}")).collect()
111}
112
113fn mesh_fp(h: &mut Fp, mesh: &MeshData, index: usize, owners: &mut HashMap<*const Vec<u8>, usize>) {
114    let MeshData {
115        express_id,
116        ifc_type,
117        global_id,
118        name,
119        presentation_layer,
120        positions,
121        normals,
122        indices,
123        color,
124        material_name,
125        geometry_item_id,
126        material_id,
127        properties,
128        uvs,
129        texture,
130        geometry_class,
131        origin,
132        instance,
133        local_bounds,
134        local_to_world,
135        presentation,
136    } = mesh;
137    h.u32(*express_id);
138    h.str(ifc_type);
139    h.opt_str(global_id);
140    h.opt_str(name);
141    h.opt_str(presentation_layer);
142    h.f32s(positions);
143    h.f32s(normals);
144    h.len(indices.len());
145    indices.iter().for_each(|i| h.u32(*i));
146    h.f32s(color);
147    h.opt_str(material_name);
148    h.opt(*geometry_item_id, |h, v| h.u32(v));
149    h.opt(*material_id, |h, v| h.u32(v));
150    h.opt(properties.as_ref(), |h, map| {
151        h.len(map.len());
152        for (k, v) in map {
153            h.str(k);
154            h.str(v);
155        }
156    });
157    h.opt(uvs.as_deref(), |h, v| h.f32s(v));
158    h.opt(texture.as_ref(), |h, t| texture_fp(h, t, index, owners));
159    h.u8(*geometry_class);
160    h.f64s(origin);
161    h.opt(instance.as_ref(), instance_meta_fp);
162    h.opt(local_bounds.as_ref(), |h, v| h.f32s(v));
163    h.opt(local_to_world.as_ref(), |h, v| h.f64s(v));
164    h.opt(presentation.as_deref(), presentation_fp);
165}
166
167fn texture_fp(h: &mut Fp, t: &MeshTextureData, index: usize, owners: &mut HashMap<*const Vec<u8>, usize>) {
168    let MeshTextureData { texture_id, rgba, width, height, url, repeat_s, repeat_t } = t;
169    h.u32(*texture_id);
170    h.opt(rgba.as_ref(), |h, rgba| {
171        // The allocation's first owner, so a replay that duplicates (or merges)
172        // shared pixels differs even when the bytes agree.
173        let owner = *owners.entry(std::sync::Arc::as_ptr(rgba)).or_insert(index);
174        h.len(owner);
175        h.len(rgba.len());
176        h.raw(rgba);
177    });
178    h.u32(*width);
179    h.u32(*height);
180    h.opt_str(url);
181    h.bool(*repeat_s);
182    h.bool(*repeat_t);
183}
184
185fn instance_meta_fp(h: &mut Fp, m: &InstanceMeta) {
186    let InstanceMeta { transform, local_transform, canonical_transform, rep_identity, instanceable } = m;
187    h.f64s(transform);
188    h.opt(local_transform.as_ref(), |h, v| h.f64s(v));
189    h.opt(canonical_transform.as_ref(), |h, v| h.f64s(v));
190    h.raw(&rep_identity.to_le_bytes());
191    h.bool(*instanceable);
192}
193
194fn presentation_fp(h: &mut Fp, p: &MeshPresentationProvenance) {
195    let MeshPresentationProvenance { normals, palette, texture } = p;
196    h.u8(match normals {
197        NormalProvenance::Producer => 0,
198        NormalProvenance::RecomputedAfterWindingRepair => 1,
199        NormalProvenance::RecomputedMissing => 2,
200    });
201    h.opt(palette.as_ref(), |h, p| match *p {
202        PaletteBinding::Bound { map_id, face_set_id, palette_index } => {
203            h.u8(0);
204            [map_id, face_set_id, palette_index].iter().for_each(|v| h.u32(*v));
205        }
206        PaletteBinding::Absent { map_id, reason } => {
207            h.u8(1);
208            h.u32(map_id);
209            h.u8(match reason {
210                PaletteAbsence::Malformed => 0,
211                PaletteAbsence::Retopologized => 1,
212                PaletteAbsence::Unproven => 2,
213                PaletteAbsence::StyleOverride => 3,
214                PaletteAbsence::SupersededByTexture => 4,
215                PaletteAbsence::FixedDisplayColour => 5,
216            });
217        }
218    });
219    h.opt(texture.as_ref(), |h, t| {
220        let TextureBinding { texture_id, face_set_id, uv_authority } = t;
221        h.u32(*texture_id);
222        h.opt(*face_set_id, |h, v| h.u32(v));
223        h.u8(match uv_authority {
224            UvAuthority::Authored => 0,
225            UvAuthority::CoordinatePaired => 1,
226            UvAuthority::Fabricated => 2,
227            UvAuthority::UnknownMap => 3,
228            UvAuthority::Dropped => 4,
229        });
230    });
231}
232
233fn instance_record_fp(h: &mut Fp, r: &InstanceRecord) {
234    let InstanceRecord {
235        express_id,
236        ifc_type,
237        global_id,
238        name,
239        presentation_layer,
240        color,
241        template_express_id,
242        rep_identity,
243        transform,
244        geometry_item_id,
245    } = r;
246    h.u32(*express_id);
247    h.str(ifc_type);
248    h.opt_str(global_id);
249    h.opt_str(name);
250    h.opt_str(presentation_layer);
251    h.f32s(color);
252    h.u32(*template_express_id);
253    h.raw(&rep_identity.to_le_bytes());
254    h.f32s(transform);
255    h.opt(*geometry_item_id, |h, v| h.u32(v));
256}
257
258fn frame_fp(h: &mut Fp, frame: &MeshFrame) {
259    match frame {
260        MeshFrame::SiteLocal { placement } => {
261            h.u8(0);
262            h.f64s(placement);
263        }
264        MeshFrame::ModelRtc { anchor } => {
265            h.u8(1);
266            h.f64s(&[anchor.0, anchor.1, anchor.2]);
267        }
268        MeshFrame::RawIfc => h.u8(2),
269    }
270}
271