1use crate::edit;
27use crate::model::{Instructions, 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}
97
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase")]
104pub struct Motion {
105 pub fps: u32,
106 pub duration: f64,
108 pub frames: Vec<MotionFrame>,
109}
110
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
118#[serde(rename_all = "camelCase")]
119pub struct MotionFrame {
120 pub time: f64,
121 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
122 pub poses: std::collections::BTreeMap<String, [f64; 16]>,
123 #[serde(default, skip_serializing_if = "Vec::is_empty")]
124 pub hidden: Vec<String>,
125 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
126 pub opacity: std::collections::BTreeMap<String, f64>,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub camera: Option<Camera>,
129 #[serde(default, skip_serializing_if = "Vec::is_empty")]
130 pub clashing: Vec<String>,
131}
132
133impl MotionFrame {
134 pub fn clash(&self) -> bool {
136 !self.clashing.is_empty()
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase")]
142pub struct PlayerStep {
143 pub id: String,
144 pub number: usize,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub parent: Option<String>,
149 #[serde(default)]
151 pub depth: usize,
152 pub title: String,
153 #[serde(default)]
154 pub notes: String,
155 pub adds: Vec<PlayerAdd>,
156 #[serde(default)]
157 pub tools: Vec<ToolUse>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub torque: Option<String>,
161 #[serde(default)]
162 pub callouts: Vec<PlayerCallout>,
163 pub signoff: bool,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub camera: Option<Camera>,
166 pub placed: Vec<usize>,
168 pub adding: Vec<usize>,
170 #[serde(default)]
172 pub insertion: Vec<Insertion>,
173 #[serde(default, skip_serializing_if = "Vec::is_empty")]
176 pub poses: Vec<Pose>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub pmi: Option<PlayerPmi>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub image: Option<String>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub motion: Option<Motion>,
189}
190
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
192#[serde(rename_all = "camelCase")]
193pub struct PlayerAdd {
194 pub part: String,
196 #[serde(default)]
198 pub name: String,
199 #[serde(default)]
200 pub find_number: String,
201 pub quantity: usize,
202 pub occurrences: Vec<String>,
204 #[serde(default)]
205 pub serial_tracked: bool,
206 #[serde(default)]
207 pub subassembly: bool,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub thumbnail: Option<String>,
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "camelCase")]
215pub struct PlayerCallout {
216 pub kind: crate::model::CalloutKind,
217 pub text: String,
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
221#[serde(rename_all = "camelCase")]
222pub struct Camera {
223 pub eye: [f64; 3],
224 pub target: [f64; 3],
225 pub up: [f64; 3],
226 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub fov_deg: Option<f64>,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub half_height: Option<f64>,
232}
233
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct Insertion {
237 pub node: usize,
238 pub offset: [f64; 3],
239}
240
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct Pose {
245 pub node: usize,
246 pub matrix: [f64; 16],
247}
248
249#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase")]
256pub struct PlayerPmi {
257 pub lines: String,
260 #[serde(default, skip_serializing_if = "String::is_empty")]
262 pub arrows: String,
263 pub annotations: usize,
265 #[serde(default, skip_serializing_if = "Vec::is_empty")]
268 pub texts: Vec<String>,
269}
270
271impl PlayerPmi {
272 pub fn new(polylines: &[Vec<[f64; 3]>], arrows: &[[[f64; 3]; 3]], annotations: usize, texts: Vec<String>) -> Option<Self> {
276 let mut segments: Vec<f32> = Vec::new();
277 for line in polylines {
278 for pair in line.windows(2) {
279 segments.extend(pair[0].iter().chain(&pair[1]).map(|&v| v as f32));
280 }
281 }
282 let triangles: Vec<f32> = arrows.iter().flatten().flatten().map(|&v| v as f32).collect();
283 if segments.is_empty() && triangles.is_empty() {
284 return None;
285 }
286 Some(Self {
287 lines: encode_f32(&segments),
288 arrows: if triangles.is_empty() { String::new() } else { encode_f32(&triangles) },
289 annotations,
290 texts,
291 })
292 }
293}
294
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct PlayerComponent {
300 pub path: String,
303 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub parent: Option<String>,
306 #[serde(default)]
308 pub depth: usize,
309 pub name: String,
311 pub part: String,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
315 pub part_id: Option<String>,
316 #[serde(default)]
317 pub find_number: String,
318 #[serde(default)]
319 pub subassembly: bool,
320 #[serde(default)]
321 pub fastener: bool,
322 #[serde(default)]
323 pub serial_tracked: bool,
324 #[serde(default)]
325 pub grounded: bool,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub torque: Option<String>,
328 #[serde(default, skip_serializing_if = "Vec::is_empty")]
330 pub attributes: Vec<(String, String)>,
331 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub thumbnail: Option<String>,
335}
336
337impl PlayerComponent {
338 pub fn rows(root: &crate::wizard::Level) -> Vec<Self> {
341 let mut out = Vec::new();
342 fn walk(level: &crate::wizard::Level, parent: Option<&str>, depth: usize, out: &mut Vec<PlayerComponent>) {
343 for c in &level.components {
344 out.push(PlayerComponent {
345 path: c.path.clone(),
346 parent: parent.map(str::to_string),
347 depth,
348 name: c.part.clone(),
349 part: c.part_key().to_string(),
350 part_id: c.part_id.clone(),
351 find_number: c.find_number.clone(),
352 subassembly: c.children.is_some(),
353 fastener: c.fastener,
354 serial_tracked: c.serial_tracked,
355 grounded: c.grounded,
356 torque: c.torque.clone(),
357 attributes: c.attributes.clone(),
358 thumbnail: None,
359 });
360 if let Some(children) = &c.children {
361 walk(children, Some(&c.path), depth + 1, out);
362 }
363 }
364 }
365 walk(root, None, 0, &mut out);
366 out
367 }
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
373#[serde(rename_all = "camelCase")]
374pub struct PlayerMesh {
375 pub id: String,
376 pub positions: String,
378 pub normals: String,
380 pub indices: String,
382 #[serde(default, skip_serializing_if = "String::is_empty")]
386 pub edges: String,
387}
388
389impl PlayerMesh {
390 pub fn new(id: &str, positions: &[f32], normals: &[f32], indices: &[u32]) -> Self {
391 Self { id: id.into(), positions: encode_f32(positions), normals: encode_f32(normals), indices: encode_u32(indices), edges: String::new() }
392 }
393
394 fn localise(&mut self, placement: &[f64; 16]) {
400 let m = placement;
401 let r = |p: [f32; 3]| -> [f32; 3] {
402 let p = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])];
404 [
405 (m[0] * p[0] + m[1] * p[1] + m[2] * p[2]) as f32,
406 (m[4] * p[0] + m[5] * p[1] + m[6] * p[2]) as f32,
407 (m[8] * p[0] + m[9] * p[1] + m[10] * p[2]) as f32,
408 ]
409 };
410 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]) };
411 let map = |text: &str, f: &dyn Fn([f32; 3]) -> [f32; 3]| -> String {
412 let values = decode_f32(text);
413 let mapped: Vec<f32> = values.chunks_exact(3).flat_map(|p| f([p[0], p[1], p[2]])).collect();
414 encode_f32(&mapped)
415 };
416 self.positions = map(&self.positions, &back);
417 self.normals = map(&self.normals, &r);
418 if !self.edges.is_empty() {
419 self.edges = map(&self.edges, &back);
420 }
421 }
422
423 pub fn with_edges(mut self, polylines: &[Vec<[f32; 3]>]) -> Self {
424 let mut segments: Vec<f32> = Vec::new();
425 for line in polylines {
426 for pair in line.windows(2) {
427 segments.extend_from_slice(&pair[0]);
428 segments.extend_from_slice(&pair[1]);
429 }
430 }
431 self.edges = if segments.is_empty() { String::new() } else { encode_f32(&segments) };
432 self
433 }
434}
435
436#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
438#[serde(rename_all = "camelCase")]
439pub struct PlayerNode {
440 pub occurrence: String,
442 pub mesh: usize,
444 pub matrix: [f64; 16],
446 pub color: [f32; 3],
448}
449
450#[derive(Debug, Clone, Default)]
453pub struct Scene {
454 pub meshes: Vec<PlayerMesh>,
455 pub nodes: Vec<PlayerNode>,
456 pub cameras: HashMap<String, Camera>,
457 pub step_images: HashMap<String, String>,
458 pub thumbnails: HashMap<String, String>,
459 pub poses: HashMap<String, Vec<Pose>>,
461 pub pmi: HashMap<String, PlayerPmi>,
463 pub assembly: Vec<PlayerComponent>,
466 pub wrapper: String,
470}
471
472const RIGID_FIT_TOLERANCE: f64 = 1e-4;
474
475impl Scene {
476 pub fn share_meshes(&mut self, keys: &[String], placements: &[Option<[f64; 16]>]) {
493 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();
494 let placement = |i: usize| placements.get(i).copied().flatten();
495 let mut first_by_key: HashMap<&str, usize> = HashMap::new();
496 let mut shared: Vec<Option<(usize, [f64; 16])>> = vec![None; self.nodes.len()];
497 let mut localised: Vec<Option<[f64; 16]>> = vec![None; self.nodes.len()];
498 for (i, node) in self.nodes.iter().enumerate() {
499 let Some(key) = keys.get(i) else { continue };
500 match first_by_key.get(key.as_str()) {
501 None => {
502 first_by_key.insert(key, i);
503 if let Some(at) = placement(i) {
504 localised[i] = Some(at);
505 }
506 }
507 Some(&reference) => {
508 let rm = self.nodes[reference].mesh;
509 match (placement(reference), placement(i)) {
510 (Some(_), Some(at)) => shared[i] = Some((rm, at)),
511 _ => {
512 let cm = node.mesh;
513 if rm != cm && self.meshes[rm].indices == self.meshes[cm].indices {
514 if let Some(matrix) = rigid_fit(&decoded[rm], &decoded[cm]) {
515 shared[i] = Some((rm, matrix));
516 }
517 }
518 }
519 }
520 }
521 }
522 }
523 for (i, at) in localised.iter().enumerate() {
524 if let Some(at) = at {
525 let mesh = self.nodes[i].mesh;
526 self.meshes[mesh].localise(at);
527 self.nodes[i].matrix = *at;
528 }
529 }
530 for (i, found) in shared.iter().enumerate() {
531 if let Some((mesh, matrix)) = found {
532 self.nodes[i].mesh = *mesh;
533 self.nodes[i].matrix = *matrix;
534 }
535 }
536 let used: Vec<bool> = (0..self.meshes.len()).map(|m| self.nodes.iter().any(|n| n.mesh == m)).collect();
537 let mut renumbered = vec![0usize; self.meshes.len()];
538 let mut next = 0;
539 for (m, keep) in used.iter().enumerate() {
540 if *keep {
541 renumbered[m] = next;
542 next += 1;
543 }
544 }
545 let meshes = std::mem::take(&mut self.meshes);
546 self.meshes = meshes.into_iter().enumerate().filter(|(m, _)| used[*m]).map(|(_, mesh)| mesh).collect();
547 for node in &mut self.nodes {
548 node.mesh = renumbered[node.mesh];
549 }
550 }
551}
552
553fn rigid_fit(a: &[[f64; 3]], b: &[[f64; 3]]) -> Option<[f64; 16]> {
558 if a.len() != b.len() || a.len() < 3 {
559 return None;
560 }
561 let sub = |p: [f64; 3], q: [f64; 3]| [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
562 let dot = |p: [f64; 3], q: [f64; 3]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
563 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]];
564 let norm = |p: [f64; 3]| dot(p, p).sqrt();
565 let scale = |p: [f64; 3], k: f64| [p[0] * k, p[1] * k, p[2] * k];
566 let i0 = 0;
569 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))?;
570 let axis = sub(a[i1], a[i0]);
571 let extent = norm(axis);
572 if extent <= 0.0 {
573 return None;
574 }
575 let off_line = |i: usize| norm(cross(axis, sub(a[i], a[i0]))) / extent;
576 let i2 = (0..a.len()).max_by(|&i, &j| off_line(i).partial_cmp(&off_line(j)).unwrap_or(std::cmp::Ordering::Equal))?;
577 let tolerance = RIGID_FIT_TOLERANCE * extent.max(1e-9);
578 if off_line(i2) <= tolerance {
579 return None;
580 }
581 let frame = |p: &[[f64; 3]]| -> Option<[[f64; 3]; 3]> {
582 let u = sub(p[i1], p[i0]);
583 let u = scale(u, 1.0 / norm(u));
584 let v0 = sub(p[i2], p[i0]);
585 let v = sub(v0, scale(u, dot(v0, u)));
586 let lv = norm(v);
587 if lv <= 0.0 {
588 return None;
589 }
590 let v = scale(v, 1.0 / lv);
591 Some([u, v, cross(u, v)])
592 };
593 let (fa, fb) = (frame(a)?, frame(b)?);
594 let mut r = [[0.0f64; 3]; 3];
596 for col in 0..3 {
597 for row in 0..3 {
598 r[col][row] = (0..3).map(|j| fb[j][row] * fa[j][col]).sum();
599 }
600 }
601 let apply = |p: [f64; 3]| [
602 r[0][0] * p[0] + r[1][0] * p[1] + r[2][0] * p[2],
603 r[0][1] * p[0] + r[1][1] * p[1] + r[2][1] * p[2],
604 r[0][2] * p[0] + r[1][2] * p[1] + r[2][2] * p[2],
605 ];
606 let t = sub(b[i0], apply(a[i0]));
607 for (p, q) in a.iter().zip(b) {
608 let moved = apply(*p);
609 if norm(sub([moved[0] + t[0], moved[1] + t[1], moved[2] + t[2]], *q)) > tolerance {
610 return None;
611 }
612 }
613 Some([
614 r[0][0], r[0][1], r[0][2], 0.0,
615 r[1][0], r[1][1], r[1][2], 0.0,
616 r[2][0], r[2][1], r[2][2], 0.0,
617 t[0], t[1], t[2], 1.0,
618 ])
619}
620
621impl Motion {
622 pub fn under(&self, wrapper: &str) -> Motion {
625 if wrapper.is_empty() {
626 return self.clone();
627 }
628 let key = |k: &str| format!("{wrapper}:{k}");
629 let frames = self
630 .frames
631 .iter()
632 .map(|frame| MotionFrame {
633 time: frame.time,
634 poses: frame.poses.iter().map(|(k, v)| (key(k), *v)).collect(),
635 hidden: frame.hidden.iter().map(|k| key(k)).collect(),
636 opacity: frame.opacity.iter().map(|(k, v)| (key(k), *v)).collect(),
637 camera: frame.camera.clone(),
638 clashing: frame.clashing.iter().map(|k| key(k)).collect(),
639 })
640 .collect();
641 Motion { fps: self.fps, duration: self.duration, frames }
642 }
643}
644
645fn step_motion(step: &crate::model::Step, wrapper: &str) -> Result<Option<Motion>, String> {
649 let Some(value) = &step.motion else { return Ok(None) };
650 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))?;
651 if motion.frames.is_empty() {
652 return Err(format!("step '{}': its motion has no frames", step.id));
653 }
654 Ok(Some(motion.under(wrapper)))
655}
656
657impl PlayerData {
658 pub fn build(block: &Instructions, scene: Scene) -> Result<Self, String> {
660 for (i, node) in scene.nodes.iter().enumerate() {
661 if node.mesh >= scene.meshes.len() {
662 return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
663 }
664 }
665 let occurrences: Vec<String> = scene.nodes.iter().map(|n| n.occurrence.clone()).collect();
666 let mut steps = Vec::new();
667 for (number, (depth, step)) in block.steps().enumerate() {
668 let number = number + 1;
669 let parent = block.parent_id(&step.id).flatten().map(str::to_string);
670 {
671 let presentation = edit::presentation(block, &step.id, &occurrences)?;
672 let index_of = |paths: &[String]| -> Vec<usize> {
673 let set: std::collections::HashSet<&str> = paths.iter().map(String::as_str).collect();
674 occurrences.iter().enumerate().filter(|(_, o)| set.contains(o.as_str())).map(|(i, _)| i).collect()
675 };
676 let adding = index_of(&presentation.adding);
677 let insertion = adding
678 .iter()
679 .filter_map(|&node| {
680 let path = &occurrences[node];
681 step.arrows
682 .iter()
683 .find(|a| path == &a.occurrence || (path.starts_with(&a.occurrence) && path[a.occurrence.len()..].starts_with(':')))
684 .map(|a| Insertion { node, offset: a.start_offset() })
685 })
686 .collect();
687 steps.push(PlayerStep {
688 id: step.id.clone(),
689 number,
690 parent,
691 depth,
692 title: step.title.clone(),
693 notes: step.notes.clone(),
694 adds: step
695 .adds
696 .iter()
697 .map(|a| PlayerAdd {
698 part: a.part.clone(),
699 name: a.display_name().to_string(),
700 find_number: a.find_number.clone(),
701 quantity: a.quantity(),
702 occurrences: a.occurrences.clone(),
703 serial_tracked: a.serial_tracked,
704 subassembly: a.subassembly,
705 thumbnail: scene.thumbnails.get(&a.part).cloned(),
706 })
707 .collect(),
708 tools: step.tools.clone(),
709 torque: step.torque.as_ref().map(|t| t.text()),
710 callouts: step.callouts.iter().map(|c| PlayerCallout { kind: c.kind, text: c.text.clone() }).collect(),
711 signoff: step.signoff.required,
712 camera: scene.cameras.get(&step.id).cloned(),
713 placed: index_of(&presentation.placed),
714 adding,
715 insertion,
716 poses: scene.poses.get(&step.id).cloned().unwrap_or_default(),
717 pmi: scene.pmi.get(&step.id).cloned(),
718 image: scene.step_images.get(&step.id).cloned(),
719 motion: step_motion(step, &scene.wrapper)?,
720 });
721 }
722 }
723 let title = if block.front.title.is_empty() { block.target.name.clone() } else { block.front.title.clone() };
724 let mut assembly = scene.assembly;
725 for row in &mut assembly {
726 if row.thumbnail.is_none() {
727 row.thumbnail = scene.thumbnails.get(&row.part).cloned();
728 }
729 }
730 Ok(Self {
731 schema: DATA_SCHEMA,
732 title,
733 subtitle: block.front.subtitle.clone(),
734 target: block.target.clone(),
735 steps,
736 tool_pictures: block
737 .tools_list()
738 .iter()
739 .filter_map(|(tool, _)| tool.tool_id.as_deref())
740 .filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'))
741 .map(|id| (id.to_string(), format!("/api/tools/{id}/picture")))
742 .collect(),
743 tools: block.tools_list().into_iter().map(|(t, _)| t).collect(),
744 meshes: scene.meshes,
745 nodes: scene.nodes,
746 assembly,
747 motion: None,
748 })
749 }
750
751 pub fn inline_tool_pictures(&mut self, fetched: &BTreeMap<String, Option<(String, Vec<u8>)>>) -> usize {
759 let mut inlined = 0;
760 let pictures = std::mem::take(&mut self.tool_pictures);
761 for (id, url) in pictures {
762 if url.starts_with("data:image/") {
763 self.tool_pictures.insert(id, url);
764 inlined += 1;
765 continue;
766 }
767 let Some(Some((media, bytes))) = fetched.get(&id) else { continue };
768 let media = media.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
769 if !matches!(media.as_str(), "image/png" | "image/jpeg" | "image/webp") || bytes.len() > TOOL_PICTURE_MAX_BYTES {
770 continue;
771 }
772 self.tool_pictures.insert(id, format!("data:{media};base64,{}", base64(bytes)));
773 inlined += 1;
774 }
775 inlined
776 }
777
778 pub fn motion_study(title: &str, subtitle: &str, target: Target, scene: Scene, motion: Motion) -> Result<Self, String> {
781 for (i, node) in scene.nodes.iter().enumerate() {
782 if node.mesh >= scene.meshes.len() {
783 return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
784 }
785 }
786 if motion.frames.is_empty() {
787 return Err("a motion study's player needs at least one frame".into());
788 }
789 Ok(Self {
790 schema: DATA_SCHEMA,
791 title: title.to_string(),
792 subtitle: subtitle.to_string(),
793 target,
794 steps: Vec::new(),
795 tools: Vec::new(),
796 tool_pictures: BTreeMap::new(),
797 meshes: scene.meshes,
798 nodes: scene.nodes,
799 assembly: Vec::new(),
800 motion: Some(motion),
801 })
802 }
803
804 pub fn to_json(&self) -> String {
805 serde_json::to_string(self).expect("player data serializes")
806 }
807
808 pub fn from_json(text: &str) -> Result<Self, String> {
811 let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("player data: {e}"))?;
812 let schema = value.get("schema").and_then(serde_json::Value::as_u64).unwrap_or(0);
813 if schema == 0 || schema > u64::from(DATA_SCHEMA) {
814 return Err(format!("player data schema {schema} is not supported"));
815 }
816 if schema == 1 {
817 if let Some(object) = value.as_object_mut() {
818 let chapters = object.remove("chapters").and_then(|c| c.as_array().cloned()).unwrap_or_default();
819 if !object.contains_key("steps") {
820 let steps: Vec<serde_json::Value> =
821 chapters.into_iter().flat_map(|c| c.get("steps").and_then(|s| s.as_array().cloned()).unwrap_or_default()).collect();
822 object.insert("steps".into(), serde_json::Value::Array(steps));
823 }
824 object.insert("schema".into(), serde_json::Value::from(DATA_SCHEMA));
825 }
826 }
827 serde_json::from_value(value).map_err(|e| format!("player data: {e}"))
828 }
829}
830
831#[derive(Debug, Clone, PartialEq, Serialize)]
833#[serde(rename_all = "camelCase")]
834struct Config<'a> {
835 mode: &'a str,
836 #[serde(skip_serializing_if = "Option::is_none")]
838 data_url: Option<&'a str>,
839 #[serde(skip_serializing_if = "Option::is_none")]
841 job: Option<&'a str>,
842}
843
844pub fn offline_html(data: &PlayerData, mode: Mode) -> String {
847 let config = Config { mode: mode.as_str(), data_url: None, job: None };
848 let json = if data.tool_pictures.values().all(|url| url.starts_with("data:image/")) {
850 data.to_json()
851 } else {
852 let mut data = data.clone();
853 data.tool_pictures.retain(|_, url| url.starts_with("data:image/"));
854 data.to_json()
855 };
856 fill(None, &serde_json::to_string(&config).unwrap(), &json)
857}
858
859pub const TOOL_PICTURE_MAX_BYTES: usize = 1024 * 1024;
861
862pub fn served_html(nonce: &str, data_url: &str, mode: Mode, job: Option<&str>) -> Result<String, String> {
866 if nonce.is_empty() || !nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b"+/=_-".contains(&b)) {
867 return Err("the nonce must be base64 or base64url text".into());
868 }
869 if !data_url.starts_with('/') || data_url.starts_with("//") {
870 return Err("the data URL must be a same-origin path".into());
871 }
872 let job = job.filter(|_| mode == Mode::Shop);
873 let config = Config { mode: mode.as_str(), data_url: Some(data_url), job };
874 Ok(fill(Some(nonce), &serde_json::to_string(&config).unwrap(), "null"))
875}
876
877fn fill(nonce: Option<&str>, config: &str, data: &str) -> String {
878 let nonce_attribute = nonce.map(|n| format!(" nonce=\"{n}\"")).unwrap_or_default();
879 TEMPLATE
880 .replace("{{NONCE}}", &nonce_attribute)
881 .replace("{{CONFIG}}", &script_json(config))
882 .replace("{{DATA}}", &script_json(data))
883}
884
885pub fn script_json(json: &str) -> String {
888 let mut out = String::with_capacity(json.len());
889 for ch in json.chars() {
890 match ch {
891 '<' => out.push_str("\\u003c"),
892 '>' => out.push_str("\\u003e"),
893 '&' => out.push_str("\\u0026"),
894 '\u{2028}' => out.push_str("\\u2028"),
895 '\u{2029}' => out.push_str("\\u2029"),
896 _ => out.push(ch),
897 }
898 }
899 out
900}
901
902const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
903
904pub fn base64(bytes: &[u8]) -> String {
906 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
907 for chunk in bytes.chunks(3) {
908 let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
909 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
910 out.push(BASE64[(n >> 18) as usize & 63] as char);
911 out.push(BASE64[(n >> 12) as usize & 63] as char);
912 out.push(if chunk.len() > 1 { BASE64[(n >> 6) as usize & 63] as char } else { '=' });
913 out.push(if chunk.len() > 2 { BASE64[n as usize & 63] as char } else { '=' });
914 }
915 out
916}
917
918pub fn unbase64(text: &str) -> Option<Vec<u8>> {
922 let value = |c: u8| BASE64.iter().position(|&b| b == c);
923 let body = text.strip_suffix("==").or_else(|| text.strip_suffix('=')).unwrap_or(text);
924 let mut out = Vec::with_capacity(text.len() / 4 * 3);
925 let mut acc: u32 = 0;
926 let mut bits = 0;
927 for c in body.bytes() {
928 let v = value(c)?;
929 acc = (acc << 6) | v as u32;
930 bits += 6;
931 if bits >= 8 {
932 bits -= 8;
933 out.push((acc >> bits) as u8);
934 acc &= (1 << bits) - 1;
935 }
936 }
937 Some(out)
938}
939
940pub fn decode_f32(text: &str) -> Vec<f32> {
943 unbase64(text).unwrap_or_default().chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
944}
945
946pub fn encode_f32(values: &[f32]) -> String {
947 base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
948}
949
950pub fn encode_u32(values: &[u32]) -> String {
951 base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
952}
953
954pub fn png_data_url(png: &[u8]) -> String {
956 format!("data:image/png;base64,{}", base64(png))
957}
958