Skip to main content

brep_instructions/
player.rs

1//! The interactive HTML player: a trusted template and its data format, kept
2//! apart.
3//!
4//! * [`TEMPLATE`] (`player/player.html`) is code: one script block, one style
5//!   block, no inline event handlers, and it never puts data into the page as
6//!   markup (text goes in as text, pictures only as `data:image/…` or same-site
7//!   `/api/tools/…` URLs). A server serves it under its own content security
8//!   policy with a per-response nonce ([`served_html`]).
9//! * [`PlayerData`] is data: the steps flat in reading order, each with its
10//!   parent's id and depth, the meshes deduplicated per part, a node per
11//!   occurrence with its matrix, and per step what is placed, what is being
12//!   added, the insertion offsets and the camera. A server stores it per
13//!   instructions revision and the template fetches it. Data written before
14//!   the step tree (schema 1: chapters of steps) reads as a flat list.
15//! * Beside the steps the data carries the assembly's occurrence tree
16//!   ([`PlayerComponent`], one row per placed component with its thumbnail
17//!   and details), which the page's Model tab shows as an expandable tree
18//!   over the model with every part's visibility its own, and its Parts tab
19//!   as one card per part with the steps that use it; and per step the PMI
20//!   its view shows ([`PlayerPmi`]: dimensions, notes, balloons, leaders,
21//!   laid out by the same `pmi_present` the viewport, the sheets and the 3D
22//!   PDF use), drawn over the parts.
23//! * The offline copy is the same template with the data inlined
24//!   ([`offline_html`]): one self-contained `.html`.
25
26use crate::edit;
27use crate::model::{Instructions, Style, Target, ToolUse};
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, HashMap};
30
31/// The player template.
32pub const TEMPLATE: &str = include_str!("../player/player.html");
33
34/// The player data's schema version.
35pub const DATA_SCHEMA: u32 = 2;
36
37/// The two player modes.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(rename_all = "lowercase")]
40pub enum Mode {
41    /// Touch-first, with a step checklist and per-step sign-off.
42    #[default]
43    Shop,
44    /// Pictures first, minimal text.
45    Customer,
46}
47
48impl Mode {
49    pub fn parse(text: &str) -> Option<Self> {
50        match text {
51            "shop" => Some(Self::Shop),
52            "customer" => Some(Self::Customer),
53            _ => None,
54        }
55    }
56
57    pub fn as_str(self) -> &'static str {
58        match self {
59            Self::Shop => "shop",
60            Self::Customer => "customer",
61        }
62    }
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67pub struct PlayerData {
68    pub schema: u32,
69    pub title: String,
70    #[serde(default)]
71    pub subtitle: String,
72    pub target: Target,
73    /// Every step in reading order (a step's children before it).
74    pub steps: Vec<PlayerStep>,
75    /// Distinct tools, in first-use order.
76    #[serde(default)]
77    pub tools: Vec<ToolUse>,
78    /// A picture per tool of the library (by `toolId`): the server's own
79    /// `/api/tools/<id>/picture` as built, which the page the PLM serves
80    /// loads same-site; the offline page carries only `data:image` pictures
81    /// ([`PlayerData::inline_tool_pictures`]), the rest dropped.
82    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
83    pub tool_pictures: BTreeMap<String, String>,
84    pub meshes: Vec<PlayerMesh>,
85    pub nodes: Vec<PlayerNode>,
86    /// The assembly's occurrence tree, depth first (a component before its
87    /// children): the Model tab's tree and the Parts tab's cards. Absent from
88    /// data made before the tree was carried, and from a motion study's.
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub assembly: Vec<PlayerComponent>,
91    /// A motion study's baked frames: with no chapters the page is the study's
92    /// player (a timeline over the frames); a step may carry one too (its
93    /// motion). Absent from instructions made before motion existed.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub motion: Option<Motion>,
96    /// How the page draws the steps: the document's style. Data made before
97    /// styles existed reads as Shaded, as it was drawn; a motion study is
98    /// Shaded.
99    #[serde(default = "Style::saved_before_styles")]
100    pub style: Style,
101    /// What an offline page keys a build's record by in the browser's
102    /// storage ([`record_key`]): the instructions' content, so two documents,
103    /// or two revisions of one, never share values. Absent from data made
104    /// before the record was kept, and from a motion study's.
105    #[serde(default, skip_serializing_if = "String::is_empty")]
106    pub record_key: String,
107}
108
109/// The identity an offline page keeps a build's record under: a digest of
110/// everything the author wrote (the target revision, the steps, their
111/// fields), the same on every machine and in every build. Any edit, and any
112/// new revision of the assembly, is a new key.
113pub fn record_key(block: &Instructions) -> String {
114    // FNV-1a, 64 bit, over the block's JSON in the model's own field order: stable by construction (a
115    // hasher from the standard library may change between releases).
116    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
117    for byte in serde_json::to_string(block).unwrap_or_default().bytes() {
118        hash ^= u64::from(byte);
119        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
120    }
121    format!("{hash:016x}")
122}
123
124/// A motion study baked for the player: every frame's poses, in the order
125/// they play. Keyed by OCCURRENCE id (a node's `occurrence` is its solid's
126/// scene name, `ACOMP2:Part`, under the occurrence), so the same JSON is also
127/// what a document keeps as a study's published `motion`.
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct Motion {
131    pub fps: u32,
132    /// Seconds.
133    pub duration: f64,
134    pub frames: Vec<MotionFrame>,
135}
136
137/// One frame: the occurrences whose pose differs from the document, each as
138/// the delta over its document pose (column-major 4×4, applied over the
139/// node's own matrix: `model = pose × node.matrix`); the occurrences a
140/// visibility clip hides; opacities (0..1) a transparency clip sets; the
141/// camera when a camera clip drives it (absolute: eye, target, up, and the
142/// projection); whether parts interfere, and which.
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
144#[serde(rename_all = "camelCase")]
145pub struct MotionFrame {
146    pub time: f64,
147    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
148    pub poses: std::collections::BTreeMap<String, [f64; 16]>,
149    #[serde(default, skip_serializing_if = "Vec::is_empty")]
150    pub hidden: Vec<String>,
151    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
152    pub opacity: std::collections::BTreeMap<String, f64>,
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub camera: Option<Camera>,
155    #[serde(default, skip_serializing_if = "Vec::is_empty")]
156    pub clashing: Vec<String>,
157}
158
159impl MotionFrame {
160    /// Whether parts interfere at this frame.
161    pub fn clash(&self) -> bool {
162        !self.clashing.is_empty()
163    }
164}
165
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
167#[serde(rename_all = "camelCase")]
168pub struct PlayerStep {
169    pub id: String,
170    /// 1-based, in reading order.
171    pub number: usize,
172    /// The parent step's id; none at the top level.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub parent: Option<String>,
175    /// 0 at the top level.
176    #[serde(default)]
177    pub depth: usize,
178    pub title: String,
179    #[serde(default)]
180    pub notes: String,
181    pub adds: Vec<PlayerAdd>,
182    #[serde(default)]
183    pub tools: Vec<ToolUse>,
184    /// `12 N·m`.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub torque: Option<String>,
187    #[serde(default)]
188    pub callouts: Vec<PlayerCallout>,
189    pub signoff: bool,
190    /// What the person doing the work records at the step (shop mode).
191    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192    pub fields: Vec<crate::fields::StepField>,
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub camera: Option<Camera>,
195    /// Node indices drawn ghosted.
196    pub placed: Vec<usize>,
197    /// Node indices highlighted.
198    pub adding: Vec<usize>,
199    /// Where an adding node starts its insertion motion.
200    #[serde(default)]
201    pub insertion: Vec<Insertion>,
202    /// The step view's explode poses: a matrix per posed node, applied after
203    /// the node's own matrix (world space), as the step's pictures pose it.
204    #[serde(default, skip_serializing_if = "Vec::is_empty")]
205    pub poses: Vec<Pose>,
206    /// The PMI the step's view shows, drawn over the parts.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub pmi: Option<PlayerPmi>,
209    /// A rendered picture of the step (PNG data URL), for customer mode and
210    /// for viewers without WebGL.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub image: Option<String>,
213    /// A motion study's published motion attached to the step: played in
214    /// place of the insertion animation, keyed by the scene's occurrences
215    /// (the study's keys under the wrapper).
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub motion: Option<Motion>,
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
221#[serde(rename_all = "camelCase")]
222pub struct PlayerAdd {
223    /// The PLM part id, or the name ([`crate::model::Add::part`]).
224    pub part: String,
225    /// The display name (what the page shows; `part` when absent).
226    #[serde(default)]
227    pub name: String,
228    #[serde(default)]
229    pub find_number: String,
230    pub quantity: usize,
231    /// The occurrences, so shop mode can ask for one serial per unit.
232    pub occurrences: Vec<String>,
233    #[serde(default)]
234    pub serial_tracked: bool,
235    #[serde(default)]
236    pub subassembly: bool,
237    /// The part's thumbnail (PNG data URL).
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub thumbnail: Option<String>,
240}
241
242#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct PlayerCallout {
245    pub kind: crate::model::CalloutKind,
246    pub text: String,
247}
248
249#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
250#[serde(rename_all = "camelCase")]
251pub struct Camera {
252    pub eye: [f64; 3],
253    pub target: [f64; 3],
254    pub up: [f64; 3],
255    /// Perspective field of view in degrees; `None` = orthographic.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub fov_deg: Option<f64>,
258    /// Orthographic half height, in model units.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub half_height: Option<f64>,
261}
262
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265pub struct Insertion {
266    pub node: usize,
267    pub offset: [f64; 3],
268    /// Which of the step's arrows moves the node: the nodes of one arrow (a
269    /// part's solids, a sub-assembly's parts) share one drawn arrow. Data
270    /// made before it reads 0.
271    #[serde(default)]
272    pub arrow: usize,
273}
274
275/// A posed node of a step: its view's explode pose as a column-major 4×4.
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct Pose {
279    pub node: usize,
280    pub matrix: [f64; 16],
281}
282
283/// A step view's PMI as the page draws it: every enabled, resolved
284/// annotation of the view (not its explode or hide rows) laid out in world
285/// space, sized as the viewport sized it when the view was saved. Text is
286/// stroked with the PMI font, so the page needs no font of its own. Arrays
287/// are little-endian base64 like a mesh's.
288#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
289#[serde(rename_all = "camelCase")]
290pub struct PlayerPmi {
291    /// f32 xyz pairs: dimension, extension and leader lines, frames and the
292    /// stroked text, as line segments.
293    pub lines: String,
294    /// f32 xyz triples: the filled arrowheads, as triangles.
295    #[serde(default, skip_serializing_if = "String::is_empty")]
296    pub arrows: String,
297    /// How many annotations are drawn.
298    pub annotations: usize,
299    /// Each drawn annotation's text, in the view's order (for a reader
300    /// without WebGL and for automation).
301    #[serde(default, skip_serializing_if = "Vec::is_empty")]
302    pub texts: Vec<String>,
303}
304
305impl PlayerPmi {
306    /// The drawing of `annotations` annotations from their polylines (each
307    /// at least two points; every polyline becomes its consecutive segments)
308    /// and arrowhead triangles. `None` when there is nothing to draw.
309    pub fn new(polylines: &[Vec<[f64; 3]>], arrows: &[[[f64; 3]; 3]], annotations: usize, texts: Vec<String>) -> Option<Self> {
310        let mut segments: Vec<f32> = Vec::new();
311        for line in polylines {
312            for pair in line.windows(2) {
313                segments.extend(pair[0].iter().chain(&pair[1]).map(|&v| v as f32));
314            }
315        }
316        let triangles: Vec<f32> = arrows.iter().flatten().flatten().map(|&v| v as f32).collect();
317        if segments.is_empty() && triangles.is_empty() {
318            return None;
319        }
320        Some(Self {
321            lines: encode_f32(&segments),
322            arrows: if triangles.is_empty() { String::new() } else { encode_f32(&triangles) },
323            annotations,
324            texts,
325        })
326    }
327}
328
329/// One placed component of the assembly: a row of the Model tab's tree and,
330/// with the other rows of its part, a card of the Parts tab.
331#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332#[serde(rename_all = "camelCase")]
333pub struct PlayerComponent {
334    /// The occurrence path (`ACOMP1:ACOMP3`): a node belongs to the deepest
335    /// component whose path its occurrence starts with (then `:`).
336    pub path: String,
337    /// The parent component's path; none at the top of the assembly.
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub parent: Option<String>,
340    /// 0 at the top of the assembly.
341    #[serde(default)]
342    pub depth: usize,
343    /// The part's name.
344    pub name: String,
345    /// What a step's add names the part by: its PLM id, or its name.
346    pub part: String,
347    /// The PLM part id when the part was placed from a PLM revision.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub part_id: Option<String>,
350    #[serde(default)]
351    pub find_number: String,
352    #[serde(default)]
353    pub subassembly: bool,
354    #[serde(default)]
355    pub fastener: bool,
356    #[serde(default)]
357    pub serial_tracked: bool,
358    #[serde(default)]
359    pub grounded: bool,
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub torque: Option<String>,
362    /// The part's attributes as `[name, value]` text pairs.
363    #[serde(default, skip_serializing_if = "Vec::is_empty")]
364    pub attributes: Vec<(String, String)>,
365    /// The part's thumbnail (PNG data URL); every row of one part carries
366    /// the same.
367    #[serde(default, skip_serializing_if = "Option::is_none")]
368    pub thumbnail: Option<String>,
369}
370
371impl PlayerComponent {
372    /// One row per component of `root` and its sub-assemblies, depth first.
373    /// Thumbnails are filled by [`PlayerData::build`] from the scene's.
374    pub fn rows(root: &crate::wizard::Level) -> Vec<Self> {
375        let mut out = Vec::new();
376        fn walk(level: &crate::wizard::Level, parent: Option<&str>, depth: usize, out: &mut Vec<PlayerComponent>) {
377            for c in &level.components {
378                out.push(PlayerComponent {
379                    path: c.path.clone(),
380                    parent: parent.map(str::to_string),
381                    depth,
382                    name: c.part.clone(),
383                    part: c.part_key().to_string(),
384                    part_id: c.part_id.clone(),
385                    find_number: c.find_number.clone(),
386                    subassembly: c.children.is_some(),
387                    fastener: c.fastener,
388                    serial_tracked: c.serial_tracked,
389                    grounded: c.grounded,
390                    torque: c.torque.clone(),
391                    attributes: c.attributes.clone(),
392                    thumbnail: None,
393                });
394                if let Some(children) = &c.children {
395                    walk(children, Some(&c.path), depth + 1, out);
396                }
397            }
398        }
399        walk(root, None, 0, &mut out);
400        out
401    }
402}
403
404/// One triangle mesh, shared by every node of the same part. Arrays are
405/// little-endian and base64-encoded.
406#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
407#[serde(rename_all = "camelCase")]
408pub struct PlayerMesh {
409    pub id: String,
410    /// f32 xyz.
411    pub positions: String,
412    /// f32 xyz, one per position.
413    pub normals: String,
414    /// u32 triangle indices.
415    pub indices: String,
416    /// f32 xyz pairs: the solid's display edges as line segments, drawn over
417    /// the faces as the viewport draws them. Absent from data written before
418    /// edges were carried.
419    #[serde(default, skip_serializing_if = "String::is_empty")]
420    pub edges: String,
421}
422
423impl PlayerMesh {
424    pub fn new(id: &str, positions: &[f32], normals: &[f32], indices: &[u32]) -> Self {
425        Self { id: id.into(), positions: encode_f32(positions), normals: encode_f32(normals), indices: encode_u32(indices), edges: String::new() }
426    }
427
428    /// The same mesh with its edges, given as polylines (each at least two
429    /// points): every polyline becomes its consecutive segments.
430    /// Take the mesh back through `placement` (a rigid column-major 4×4): the
431    /// vertices through its inverse, the normals and edges through the
432    /// rotation's transpose, so the mesh reads in the part's own frame.
433    fn localise(&mut self, placement: &[f64; 16]) {
434        let m = placement;
435        let r = |p: [f32; 3]| -> [f32; 3] {
436            // Rᵀ · p: rows of R are the matrix's columns' first three entries.
437            let p = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])];
438            [
439                (m[0] * p[0] + m[1] * p[1] + m[2] * p[2]) as f32,
440                (m[4] * p[0] + m[5] * p[1] + m[6] * p[2]) as f32,
441                (m[8] * p[0] + m[9] * p[1] + m[10] * p[2]) as f32,
442            ]
443        };
444        let back = |p: [f32; 3]| -> [f32; 3] { r([p[0] - m[12] as f32, p[1] - m[13] as f32, p[2] - m[14] as f32]) };
445        let map = |text: &str, f: &dyn Fn([f32; 3]) -> [f32; 3]| -> String {
446            let values = decode_f32(text);
447            let mapped: Vec<f32> = values.chunks_exact(3).flat_map(|p| f([p[0], p[1], p[2]])).collect();
448            encode_f32(&mapped)
449        };
450        self.positions = map(&self.positions, &back);
451        self.normals = map(&self.normals, &r);
452        if !self.edges.is_empty() {
453            self.edges = map(&self.edges, &back);
454        }
455    }
456
457    pub fn with_edges(mut self, polylines: &[Vec<[f32; 3]>]) -> Self {
458        let mut segments: Vec<f32> = Vec::new();
459        for line in polylines {
460            for pair in line.windows(2) {
461                segments.extend_from_slice(&pair[0]);
462                segments.extend_from_slice(&pair[1]);
463            }
464        }
465        self.edges = if segments.is_empty() { String::new() } else { encode_f32(&segments) };
466        self
467    }
468}
469
470/// One drawn solid of one occurrence.
471#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
472#[serde(rename_all = "camelCase")]
473pub struct PlayerNode {
474    /// The occurrence path the solid belongs to.
475    pub occurrence: String,
476    /// Index into `meshes`.
477    pub mesh: usize,
478    /// Column-major 4 × 4 placement.
479    pub matrix: [f64; 16],
480    /// sRGB colour, 0..1.
481    pub color: [f32; 3],
482}
483
484/// What the caller supplies beside the block: the meshes and nodes of the
485/// assembly as placed, each step's camera and picture, and part thumbnails.
486#[derive(Debug, Clone, Default)]
487pub struct Scene {
488    pub meshes: Vec<PlayerMesh>,
489    pub nodes: Vec<PlayerNode>,
490    pub cameras: HashMap<String, Camera>,
491    pub step_images: HashMap<String, String>,
492    pub thumbnails: HashMap<String, String>,
493    /// Each step's explode poses, by step id.
494    pub poses: HashMap<String, Vec<Pose>>,
495    /// Each step's view PMI, by step id.
496    pub pmi: HashMap<String, PlayerPmi>,
497    /// The arrows a step's parts come home along when they are not the
498    /// step's own (a Line art step without arrows gets one per part from the
499    /// engine), by step id; a step not listed uses its own `arrows`.
500    pub arrows: HashMap<String, Vec<crate::model::Arrow>>,
501    /// The assembly's occurrence tree ([`PlayerComponent::rows`]); each
502    /// row's thumbnail is taken from `thumbnails` by its part.
503    pub assembly: Vec<PlayerComponent>,
504    /// The wrapper occurrence the instructions place the assembly under
505    /// (`ACOMP1`): a step's motion, keyed by the assembly's own occurrences,
506    /// is re-keyed under it. Empty when the nodes are the assembly's own.
507    pub wrapper: String,
508}
509
510/// The tolerance of a rigid fit, as a share of the mesh's extent.
511const RIGID_FIT_TOLERANCE: f64 = 1e-4;
512
513impl Scene {
514    /// One mesh per part. `keys` is one key per node (its part and member)
515    /// and `placements` one optional placement per node (column-major, the
516    /// engine's pose of the occurrence in the world). Among the nodes of one
517    /// key, the first is the reference:
518    ///
519    /// * with placements, its mesh is made part-local (its vertices taken back
520    ///   through its placement, normals through the rotation) and every placed
521    ///   node of the key shares it, each carrying its own placement as its
522    ///   matrix, whatever that copy's own tessellation was;
523    /// * without, a node whose mesh is the same tessellation as the reference's
524    ///   moved rigidly shares it and carries the rigid move, decided by the
525    ///   vertices themselves (the same index order and count, every vertex
526    ///   within `RIGID_FIT_TOLERANCE` of the fit), so a mirrored or
527    ///   re-tessellated copy keeps its own.
528    ///
529    /// Meshes left unreferenced are dropped and the rest renumbered.
530    pub fn share_meshes(&mut self, keys: &[String], placements: &[Option<[f64; 16]>]) {
531        let decoded: Vec<Vec<[f64; 3]>> = self.meshes.iter().map(|mesh| decode_f32(&mesh.positions).chunks(3).map(|p| [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]).collect()).collect();
532        let placement = |i: usize| placements.get(i).copied().flatten();
533        let mut first_by_key: HashMap<&str, usize> = HashMap::new();
534        let mut shared: Vec<Option<(usize, [f64; 16])>> = vec![None; self.nodes.len()];
535        let mut localised: Vec<Option<[f64; 16]>> = vec![None; self.nodes.len()];
536        for (i, node) in self.nodes.iter().enumerate() {
537            let Some(key) = keys.get(i) else { continue };
538            match first_by_key.get(key.as_str()) {
539                None => {
540                    first_by_key.insert(key, i);
541                    if let Some(at) = placement(i) {
542                        localised[i] = Some(at);
543                    }
544                }
545                Some(&reference) => {
546                    let rm = self.nodes[reference].mesh;
547                    match (placement(reference), placement(i)) {
548                        (Some(_), Some(at)) => shared[i] = Some((rm, at)),
549                        _ => {
550                            let cm = node.mesh;
551                            if rm != cm && self.meshes[rm].indices == self.meshes[cm].indices {
552                                if let Some(matrix) = rigid_fit(&decoded[rm], &decoded[cm]) {
553                                    shared[i] = Some((rm, matrix));
554                                }
555                            }
556                        }
557                    }
558                }
559            }
560        }
561        for (i, at) in localised.iter().enumerate() {
562            if let Some(at) = at {
563                let mesh = self.nodes[i].mesh;
564                self.meshes[mesh].localise(at);
565                self.nodes[i].matrix = *at;
566            }
567        }
568        for (i, found) in shared.iter().enumerate() {
569            if let Some((mesh, matrix)) = found {
570                self.nodes[i].mesh = *mesh;
571                self.nodes[i].matrix = *matrix;
572            }
573        }
574        let used: Vec<bool> = (0..self.meshes.len()).map(|m| self.nodes.iter().any(|n| n.mesh == m)).collect();
575        let mut renumbered = vec![0usize; self.meshes.len()];
576        let mut next = 0;
577        for (m, keep) in used.iter().enumerate() {
578            if *keep {
579                renumbered[m] = next;
580                next += 1;
581            }
582        }
583        let meshes = std::mem::take(&mut self.meshes);
584        self.meshes = meshes.into_iter().enumerate().filter(|(m, _)| used[*m]).map(|(_, mesh)| mesh).collect();
585        for node in &mut self.nodes {
586            node.mesh = renumbered[node.mesh];
587        }
588    }
589}
590
591/// The rigid move (a proper rotation and a translation, column-major 4×4)
592/// taking every point of `a` onto the point of `b` with the same index, or
593/// `None` when there is none within tolerance (a different shape, a mirror,
594/// or too few points to fix a frame).
595fn rigid_fit(a: &[[f64; 3]], b: &[[f64; 3]]) -> Option<[f64; 16]> {
596    if a.len() != b.len() || a.len() < 3 {
597        return None;
598    }
599    let sub = |p: [f64; 3], q: [f64; 3]| [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
600    let dot = |p: [f64; 3], q: [f64; 3]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
601    let cross = |p: [f64; 3], q: [f64; 3]| [p[1] * q[2] - p[2] * q[1], p[2] * q[0] - p[0] * q[2], p[0] * q[1] - p[1] * q[0]];
602    let norm = |p: [f64; 3]| dot(p, p).sqrt();
603    let scale = |p: [f64; 3], k: f64| [p[0] * k, p[1] * k, p[2] * k];
604    // Three points that fix a frame: the farthest from the first, then the
605    // farthest from that line.
606    let i0 = 0;
607    let i1 = (0..a.len()).max_by(|&i, &j| norm(sub(a[i], a[i0])).partial_cmp(&norm(sub(a[j], a[i0]))).unwrap_or(std::cmp::Ordering::Equal))?;
608    let axis = sub(a[i1], a[i0]);
609    let extent = norm(axis);
610    if extent <= 0.0 {
611        return None;
612    }
613    let off_line = |i: usize| norm(cross(axis, sub(a[i], a[i0]))) / extent;
614    let i2 = (0..a.len()).max_by(|&i, &j| off_line(i).partial_cmp(&off_line(j)).unwrap_or(std::cmp::Ordering::Equal))?;
615    let tolerance = RIGID_FIT_TOLERANCE * extent.max(1e-9);
616    if off_line(i2) <= tolerance {
617        return None;
618    }
619    let frame = |p: &[[f64; 3]]| -> Option<[[f64; 3]; 3]> {
620        let u = sub(p[i1], p[i0]);
621        let u = scale(u, 1.0 / norm(u));
622        let v0 = sub(p[i2], p[i0]);
623        let v = sub(v0, scale(u, dot(v0, u)));
624        let lv = norm(v);
625        if lv <= 0.0 {
626            return None;
627        }
628        let v = scale(v, 1.0 / lv);
629        Some([u, v, cross(u, v)])
630    };
631    let (fa, fb) = (frame(a)?, frame(b)?);
632    // R = Fb · Faᵀ: column k of R = Σ_j fb[j] * fa[j][k].
633    let mut r = [[0.0f64; 3]; 3];
634    for col in 0..3 {
635        for row in 0..3 {
636            r[col][row] = (0..3).map(|j| fb[j][row] * fa[j][col]).sum();
637        }
638    }
639    let apply = |p: [f64; 3]| [
640        r[0][0] * p[0] + r[1][0] * p[1] + r[2][0] * p[2],
641        r[0][1] * p[0] + r[1][1] * p[1] + r[2][1] * p[2],
642        r[0][2] * p[0] + r[1][2] * p[1] + r[2][2] * p[2],
643    ];
644    let t = sub(b[i0], apply(a[i0]));
645    for (p, q) in a.iter().zip(b) {
646        let moved = apply(*p);
647        if norm(sub([moved[0] + t[0], moved[1] + t[1], moved[2] + t[2]], *q)) > tolerance {
648            return None;
649        }
650    }
651    Some([
652        r[0][0], r[0][1], r[0][2], 0.0,
653        r[1][0], r[1][1], r[1][2], 0.0,
654        r[2][0], r[2][1], r[2][2], 0.0,
655        t[0], t[1], t[2], 1.0,
656    ])
657}
658
659impl Motion {
660    /// The same motion with every occurrence key put under `wrapper`
661    /// (`ACOMP2` → `ACOMP1:ACOMP2`); unchanged when `wrapper` is empty.
662    pub fn under(&self, wrapper: &str) -> Motion {
663        if wrapper.is_empty() {
664            return self.clone();
665        }
666        let key = |k: &str| format!("{wrapper}:{k}");
667        let frames = self
668            .frames
669            .iter()
670            .map(|frame| MotionFrame {
671                time: frame.time,
672                poses: frame.poses.iter().map(|(k, v)| (key(k), *v)).collect(),
673                hidden: frame.hidden.iter().map(|k| key(k)).collect(),
674                opacity: frame.opacity.iter().map(|(k, v)| (key(k), *v)).collect(),
675                camera: frame.camera.clone(),
676                clashing: frame.clashing.iter().map(|k| key(k)).collect(),
677            })
678            .collect();
679        Motion { fps: self.fps, duration: self.duration, frames }
680    }
681}
682
683/// A step's attached motion (the study's published JSON, `{study,
684/// assemblySignature}` beside the frames) re-keyed under the wrapper; a
685/// value that is not a motion is refused like a node naming a missing mesh.
686fn step_motion(step: &crate::model::Step, wrapper: &str) -> Result<Option<Motion>, String> {
687    let Some(value) = &step.motion else { return Ok(None) };
688    let motion: Motion = serde_json::from_value(value.clone()).map_err(|e| format!("step '{}': its motion is not a motion study's: {e}", step.id))?;
689    if motion.frames.is_empty() {
690        return Err(format!("step '{}': its motion has no frames", step.id));
691    }
692    Ok(Some(motion.under(wrapper)))
693}
694
695impl PlayerData {
696    /// The player data of `block` over `scene`.
697    pub fn build(block: &Instructions, scene: Scene) -> Result<Self, String> {
698        for (i, node) in scene.nodes.iter().enumerate() {
699            if node.mesh >= scene.meshes.len() {
700                return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
701            }
702        }
703        let occurrences: Vec<String> = scene.nodes.iter().map(|n| n.occurrence.clone()).collect();
704        let mut steps = Vec::new();
705        for (number, (depth, step)) in block.steps().enumerate() {
706            let number = number + 1;
707            let parent = block.parent_id(&step.id).flatten().map(str::to_string);
708            {
709                let presentation = edit::presentation(block, &step.id, &occurrences)?;
710                let index_of = |paths: &[String]| -> Vec<usize> {
711                    let set: std::collections::HashSet<&str> = paths.iter().map(String::as_str).collect();
712                    occurrences.iter().enumerate().filter(|(_, o)| set.contains(o.as_str())).map(|(i, _)| i).collect()
713                };
714                let adding = index_of(&presentation.adding);
715                let arrows = scene.arrows.get(&step.id).unwrap_or(&step.arrows);
716                let insertion = adding
717                    .iter()
718                    .filter_map(|&node| {
719                        let path = &occurrences[node];
720                        arrows
721                            .iter()
722                            .enumerate()
723                            .find(|(_, a)| path == &a.occurrence || (path.starts_with(&a.occurrence) && path[a.occurrence.len()..].starts_with(':')))
724                            .map(|(arrow, a)| Insertion { node, offset: a.start_offset(), arrow })
725                    })
726                    .collect();
727                steps.push(PlayerStep {
728                    id: step.id.clone(),
729                    number,
730                    parent,
731                    depth,
732                    title: step.title.clone(),
733                    notes: step.notes.clone(),
734                    adds: step
735                        .adds
736                        .iter()
737                        .map(|a| PlayerAdd {
738                            part: a.part.clone(),
739                            name: a.display_name().to_string(),
740                            find_number: a.find_number.clone(),
741                            quantity: a.quantity(),
742                            occurrences: a.occurrences.clone(),
743                            serial_tracked: a.serial_tracked,
744                            subassembly: a.subassembly,
745                            thumbnail: scene.thumbnails.get(&a.part).cloned(),
746                        })
747                        .collect(),
748                    tools: step.tools.clone(),
749                    torque: step.torque.as_ref().map(|t| t.text()),
750                    callouts: step.callouts.iter().map(|c| PlayerCallout { kind: c.kind, text: c.text.clone() }).collect(),
751                    signoff: step.signoff.required,
752                    fields: step.fields.clone(),
753                    camera: scene.cameras.get(&step.id).cloned(),
754                    placed: index_of(&presentation.placed),
755                    adding,
756                    insertion,
757                    poses: scene.poses.get(&step.id).cloned().unwrap_or_default(),
758                    pmi: scene.pmi.get(&step.id).cloned(),
759                    image: scene.step_images.get(&step.id).cloned(),
760                    motion: step_motion(step, &scene.wrapper)?,
761                });
762            }
763        }
764        let title = if block.front.title.is_empty() { block.target.name.clone() } else { block.front.title.clone() };
765        let mut assembly = scene.assembly;
766        for row in &mut assembly {
767            if row.thumbnail.is_none() {
768                row.thumbnail = scene.thumbnails.get(&row.part).cloned();
769            }
770        }
771        Ok(Self {
772            schema: DATA_SCHEMA,
773            title,
774            subtitle: block.front.subtitle.clone(),
775            target: block.target.clone(),
776            steps,
777            tool_pictures: block
778                .tools_list()
779                .iter()
780                .filter_map(|(tool, _)| tool.tool_id.as_deref())
781                .filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'))
782                .map(|id| (id.to_string(), format!("/api/tools/{id}/picture")))
783                .collect(),
784            tools: block.tools_list().into_iter().map(|(t, _)| t).collect(),
785            meshes: scene.meshes,
786            nodes: scene.nodes,
787            assembly,
788            motion: None,
789            style: block.template.style,
790            record_key: record_key(block),
791        })
792    }
793
794    /// Put the fetched tool pictures in: for each tool with a picture entry,
795    /// `fetched[id]` as `Some((media type, bytes))` becomes a `data:image`
796    /// URL when the type is one the page shows (PNG, JPEG, WebP) and the
797    /// bytes are within [`TOOL_PICTURE_MAX_BYTES`]; any other entry (not
798    /// fetched, no picture, another type, too large) is dropped, so an
799    /// offline page never carries a picture it cannot load. Returns how many
800    /// were put in.
801    pub fn inline_tool_pictures(&mut self, fetched: &BTreeMap<String, Option<(String, Vec<u8>)>>) -> usize {
802        let mut inlined = 0;
803        let pictures = std::mem::take(&mut self.tool_pictures);
804        for (id, url) in pictures {
805            if url.starts_with("data:image/") {
806                self.tool_pictures.insert(id, url);
807                inlined += 1;
808                continue;
809            }
810            let Some(Some((media, bytes))) = fetched.get(&id) else { continue };
811            let media = media.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
812            if !matches!(media.as_str(), "image/png" | "image/jpeg" | "image/webp") || bytes.len() > TOOL_PICTURE_MAX_BYTES {
813                continue;
814            }
815            self.tool_pictures.insert(id, format!("data:{media};base64,{}", base64(bytes)));
816            inlined += 1;
817        }
818        inlined
819    }
820
821    /// A motion study's player: no steps, the scene's meshes and nodes, and
822    /// the study's frames as `motion`. `title` is the study's name.
823    pub fn motion_study(title: &str, subtitle: &str, target: Target, scene: Scene, motion: Motion) -> Result<Self, String> {
824        for (i, node) in scene.nodes.iter().enumerate() {
825            if node.mesh >= scene.meshes.len() {
826                return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
827            }
828        }
829        if motion.frames.is_empty() {
830            return Err("a motion study's player needs at least one frame".into());
831        }
832        Ok(Self {
833            schema: DATA_SCHEMA,
834            title: title.to_string(),
835            subtitle: subtitle.to_string(),
836            target,
837            steps: Vec::new(),
838            tools: Vec::new(),
839            tool_pictures: BTreeMap::new(),
840            meshes: scene.meshes,
841            nodes: scene.nodes,
842            assembly: Vec::new(),
843            motion: Some(motion),
844            style: Style::Shaded,
845            record_key: String::new(),
846        })
847    }
848
849    pub fn to_json(&self) -> String {
850        serde_json::to_string(self).expect("player data serializes")
851    }
852
853    /// Read the data, schema 1 (chapters of steps) included: its steps become
854    /// one flat list, every step at the top.
855    pub fn from_json(text: &str) -> Result<Self, String> {
856        let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("player data: {e}"))?;
857        let schema = value.get("schema").and_then(serde_json::Value::as_u64).unwrap_or(0);
858        if schema == 0 || schema > u64::from(DATA_SCHEMA) {
859            return Err(format!("player data schema {schema} is not supported"));
860        }
861        if schema == 1 {
862            if let Some(object) = value.as_object_mut() {
863                let chapters = object.remove("chapters").and_then(|c| c.as_array().cloned()).unwrap_or_default();
864                if !object.contains_key("steps") {
865                    let steps: Vec<serde_json::Value> =
866                        chapters.into_iter().flat_map(|c| c.get("steps").and_then(|s| s.as_array().cloned()).unwrap_or_default()).collect();
867                    object.insert("steps".into(), serde_json::Value::Array(steps));
868                }
869                object.insert("schema".into(), serde_json::Value::from(DATA_SCHEMA));
870            }
871        }
872        serde_json::from_value(value).map_err(|e| format!("player data: {e}"))
873    }
874}
875
876/// How the template finds its data and what it may do.
877#[derive(Debug, Clone, PartialEq, Serialize)]
878#[serde(rename_all = "camelCase")]
879struct Config<'a> {
880    mode: &'a str,
881    /// Where to fetch the data; `None` = inlined.
882    #[serde(skip_serializing_if = "Option::is_none")]
883    data_url: Option<&'a str>,
884    /// The job whose steps shop mode signs off; `None` = a local checklist.
885    #[serde(skip_serializing_if = "Option::is_none")]
886    job: Option<&'a str>,
887}
888
889/// The self-contained offline copy: the template with `data` inlined. Shop
890/// mode keeps a local checklist (no server to sign off to).
891pub fn offline_html(data: &PlayerData, mode: Mode) -> String {
892    let config = Config { mode: mode.as_str(), data_url: None, job: None };
893    // An offline page loads no `/api/tools/…` picture: only the inlined ones go.
894    let json = if data.tool_pictures.values().all(|url| url.starts_with("data:image/")) {
895        data.to_json()
896    } else {
897        let mut data = data.clone();
898        data.tool_pictures.retain(|_, url| url.starts_with("data:image/"));
899        data.to_json()
900    };
901    fill(None, &serde_json::to_string(&config).unwrap(), &json)
902}
903
904/// The largest tool picture an offline page inlines, in bytes.
905pub const TOOL_PICTURE_MAX_BYTES: usize = 1024 * 1024;
906
907/// The template as a server serves it: `nonce` goes on the script and style
908/// blocks, the page fetches its data from `data_url` (same origin), and in shop
909/// mode with a `job` its sign-offs go to that job.
910pub fn served_html(nonce: &str, data_url: &str, mode: Mode, job: Option<&str>) -> Result<String, String> {
911    if nonce.is_empty() || !nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b"+/=_-".contains(&b)) {
912        return Err("the nonce must be base64 or base64url text".into());
913    }
914    if !data_url.starts_with('/') || data_url.starts_with("//") {
915        return Err("the data URL must be a same-origin path".into());
916    }
917    let job = job.filter(|_| mode == Mode::Shop);
918    let config = Config { mode: mode.as_str(), data_url: Some(data_url), job };
919    Ok(fill(Some(nonce), &serde_json::to_string(&config).unwrap(), "null"))
920}
921
922fn fill(nonce: Option<&str>, config: &str, data: &str) -> String {
923    let nonce_attribute = nonce.map(|n| format!(" nonce=\"{n}\"")).unwrap_or_default();
924    TEMPLATE
925        .replace("{{NONCE}}", &nonce_attribute)
926        .replace("{{CONFIG}}", &script_json(config))
927        .replace("{{DATA}}", &script_json(data))
928}
929
930/// JSON made safe inside a `<script type="application/json">` block: no `<`,
931/// `>` or `&` (so no `</script>` and no comment openers), and no U+2028/9.
932pub fn script_json(json: &str) -> String {
933    let mut out = String::with_capacity(json.len());
934    for ch in json.chars() {
935        match ch {
936            '<' => out.push_str("\\u003c"),
937            '>' => out.push_str("\\u003e"),
938            '&' => out.push_str("\\u0026"),
939            '\u{2028}' => out.push_str("\\u2028"),
940            '\u{2029}' => out.push_str("\\u2029"),
941            _ => out.push(ch),
942        }
943    }
944    out
945}
946
947const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
948
949/// Standard base64 with padding.
950pub fn base64(bytes: &[u8]) -> String {
951    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
952    for chunk in bytes.chunks(3) {
953        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
954        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
955        out.push(BASE64[(n >> 18) as usize & 63] as char);
956        out.push(BASE64[(n >> 12) as usize & 63] as char);
957        out.push(if chunk.len() > 1 { BASE64[(n >> 6) as usize & 63] as char } else { '=' });
958        out.push(if chunk.len() > 2 { BASE64[n as usize & 63] as char } else { '=' });
959    }
960    out
961}
962
963/// Standard base64 back to bytes: padding (at most two `=`) only at the end.
964/// `None` for any other character, so a corrupt string is never read as the
965/// prefix before its first bad character.
966pub fn unbase64(text: &str) -> Option<Vec<u8>> {
967    let value = |c: u8| BASE64.iter().position(|&b| b == c);
968    let body = text.strip_suffix("==").or_else(|| text.strip_suffix('=')).unwrap_or(text);
969    let mut out = Vec::with_capacity(text.len() / 4 * 3);
970    let mut acc: u32 = 0;
971    let mut bits = 0;
972    for c in body.bytes() {
973        let v = value(c)?;
974        acc = (acc << 6) | v as u32;
975        bits += 6;
976        if bits >= 8 {
977            bits -= 8;
978            out.push((acc >> bits) as u8);
979            acc &= (1 << bits) - 1;
980        }
981    }
982    Some(out)
983}
984
985/// The f32 values an [`encode_f32`] string carries; none for a string that is
986/// not base64 (never a short read of its good prefix).
987pub fn decode_f32(text: &str) -> Vec<f32> {
988    unbase64(text).unwrap_or_default().chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
989}
990
991pub fn encode_f32(values: &[f32]) -> String {
992    base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
993}
994
995pub fn encode_u32(values: &[u32]) -> String {
996    base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
997}
998
999/// A PNG as a data URL, the only picture form the player shows from data.
1000pub fn png_data_url(png: &[u8]) -> String {
1001    format!("data:image/png;base64,{}", base64(png))
1002}
1003