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