1use crate::edit;
27use crate::model::{Instructions, Style, Target, ToolUse};
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, HashMap};
30
31pub const TEMPLATE: &str = include_str!("../player/player.html");
33
34pub const DATA_SCHEMA: u32 = 2;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(rename_all = "lowercase")]
40pub enum Mode {
41 #[default]
43 Shop,
44 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 pub steps: Vec<PlayerStep>,
75 #[serde(default)]
77 pub tools: Vec<ToolUse>,
78 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
90 pub assembly: Vec<PlayerComponent>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub motion: Option<Motion>,
96 #[serde(default = "Style::saved_before_styles")]
100 pub style: Style,
101}
102
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108#[serde(rename_all = "camelCase")]
109pub struct Motion {
110 pub fps: u32,
111 pub duration: f64,
113 pub frames: Vec<MotionFrame>,
114}
115
116#[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 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 pub number: usize,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub parent: Option<String>,
154 #[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 #[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 pub placed: Vec<usize>,
173 pub adding: Vec<usize>,
175 #[serde(default)]
177 pub insertion: Vec<Insertion>,
178 #[serde(default, skip_serializing_if = "Vec::is_empty")]
181 pub poses: Vec<Pose>,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub pmi: Option<PlayerPmi>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub image: Option<String>,
189 #[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 pub part: String,
201 #[serde(default)]
203 pub name: String,
204 #[serde(default)]
205 pub find_number: String,
206 pub quantity: usize,
207 pub occurrences: Vec<String>,
209 #[serde(default)]
210 pub serial_tracked: bool,
211 #[serde(default)]
212 pub subassembly: bool,
213 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub fov_deg: Option<f64>,
234 #[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 #[serde(default)]
248 pub arrow: usize,
249}
250
251#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
265#[serde(rename_all = "camelCase")]
266pub struct PlayerPmi {
267 pub lines: String,
270 #[serde(default, skip_serializing_if = "String::is_empty")]
272 pub arrows: String,
273 pub annotations: usize,
275 #[serde(default, skip_serializing_if = "Vec::is_empty")]
278 pub texts: Vec<String>,
279}
280
281impl PlayerPmi {
282 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
308#[serde(rename_all = "camelCase")]
309pub struct PlayerComponent {
310 pub path: String,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
315 pub parent: Option<String>,
316 #[serde(default)]
318 pub depth: usize,
319 pub name: String,
321 pub part: String,
323 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
340 pub attributes: Vec<(String, String)>,
341 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub thumbnail: Option<String>,
345}
346
347impl PlayerComponent {
348 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
383#[serde(rename_all = "camelCase")]
384pub struct PlayerMesh {
385 pub id: String,
386 pub positions: String,
388 pub normals: String,
390 pub indices: String,
392 #[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 fn localise(&mut self, placement: &[f64; 16]) {
410 let m = placement;
411 let r = |p: [f32; 3]| -> [f32; 3] {
412 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
448#[serde(rename_all = "camelCase")]
449pub struct PlayerNode {
450 pub occurrence: String,
452 pub mesh: usize,
454 pub matrix: [f64; 16],
456 pub color: [f32; 3],
458}
459
460#[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 pub poses: HashMap<String, Vec<Pose>>,
471 pub pmi: HashMap<String, PlayerPmi>,
473 pub arrows: HashMap<String, Vec<crate::model::Arrow>>,
477 pub assembly: Vec<PlayerComponent>,
480 pub wrapper: String,
484}
485
486const RIGID_FIT_TOLERANCE: f64 = 1e-4;
488
489impl Scene {
490 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
567fn 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 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 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 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
659fn 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Serialize)]
851#[serde(rename_all = "camelCase")]
852struct Config<'a> {
853 mode: &'a str,
854 #[serde(skip_serializing_if = "Option::is_none")]
856 data_url: Option<&'a str>,
857 #[serde(skip_serializing_if = "Option::is_none")]
859 job: Option<&'a str>,
860}
861
862pub fn offline_html(data: &PlayerData, mode: Mode) -> String {
865 let config = Config { mode: mode.as_str(), data_url: None, job: None };
866 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
877pub const TOOL_PICTURE_MAX_BYTES: usize = 1024 * 1024;
879
880pub 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
903pub 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
922pub 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
936pub 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
958pub 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
972pub fn png_data_url(png: &[u8]) -> String {
974 format!("data:image/png;base64,{}", base64(png))
975}
976