1use std::fmt;
27
28use crate::bytes::{In, Out, fits_u32};
29#[cfg(feature = "fingerprint")]
30use crate::mesh::Mesh;
31#[cfg(feature = "fingerprint")]
32use crate::surface::SurfaceEntry;
33
34pub const PAINT_DETAIL: u8 = 0;
36pub const PAINT_SUPPORTS_MUST_TOUCH: u8 = 1;
38pub const PAINT_SUPPORTS_MUST_NOT_TOUCH: u8 = 2;
41pub const PAINT_SUPPORTS_BOTH_WAYS: u8 = 3;
44
45pub const MUST_TOUCH: u8 = 1;
47pub const MUST_NOT_TOUCH: u8 = 2;
50
51pub const MAX_PAINT_DEPTH: usize = 32;
53
54pub const FINGERPRINT_SIZE: usize = 48;
56
57#[derive(Clone, Debug, PartialEq, Eq)]
59pub enum PaintDocument {
60 Runs(PaintRuns),
62 Trees(PaintTrees),
64}
65
66#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct PaintRuns {
69 pub triangle_count: u32,
71 pub fingerprint: [u8; FINGERPRINT_SIZE],
73 pub runs: Vec<PaintRun>,
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct PaintRun {
80 pub length: u32,
82 pub value: u8,
84}
85
86#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct PaintTrees {
89 pub triangle_count: u32,
91 pub fingerprint: [u8; FINGERPRINT_SIZE],
93 pub triangles: Vec<PaintedTriangle>,
96}
97
98#[derive(Clone, Debug, PartialEq, Eq)]
100pub struct PaintedTriangle {
101 pub triangle: u32,
103 pub tree: PaintNode,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq)]
109pub enum PaintNode {
110 Leaf(u8),
112 Split {
115 special: u8,
117 children: Vec<PaintNode>,
119 },
120}
121
122#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct PaintPiece {
125 pub corners: [[f64; 3]; 3],
129 pub value: u8,
131}
132
133#[derive(Clone, Debug, PartialEq, Eq)]
135pub enum DecodePaintError {
136 UnknownVersion(u32),
138 Malformed,
140}
141
142impl fmt::Display for DecodePaintError {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 match self {
145 Self::UnknownVersion(version) => {
146 write!(
147 f,
148 "surface paint document version {version} is not supported"
149 )
150 }
151 Self::Malformed => f.write_str("the surface paint document is malformed"),
152 }
153 }
154}
155
156impl std::error::Error for DecodePaintError {}
157
158#[derive(Clone, Debug, PartialEq, Eq)]
160pub enum EncodePaintError {
161 RunsDoNotCover,
163 NotInOrder,
166 BadSplit,
169 TooDeep,
171 TooLarge,
174}
175
176impl fmt::Display for EncodePaintError {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.write_str(match self {
179 Self::RunsDoNotCover => "the paint runs do not cover exactly the mesh's triangles",
180 Self::NotInOrder => "the painted triangles are out of order, or past the mesh",
181 Self::BadSplit => "a paint tree splits a triangle in a way the format does not have",
182 Self::TooDeep => "a paint tree is deeper than the format allows",
183 Self::TooLarge => "the paint document is too large",
184 })
185 }
186}
187
188impl std::error::Error for EncodePaintError {}
189
190impl PaintDocument {
191 #[must_use]
193 pub fn version(&self) -> u32 {
194 match self {
195 Self::Runs(_) => 1,
196 Self::Trees(_) => 2,
197 }
198 }
199
200 #[must_use]
202 pub fn triangle_count(&self) -> u32 {
203 match self {
204 Self::Runs(runs) => runs.triangle_count,
205 Self::Trees(trees) => trees.triangle_count,
206 }
207 }
208
209 #[must_use]
211 pub fn fingerprint(&self) -> &[u8; FINGERPRINT_SIZE] {
212 match self {
213 Self::Runs(runs) => &runs.fingerprint,
214 Self::Trees(trees) => &trees.fingerprint,
215 }
216 }
217
218 #[must_use]
220 pub fn max_value(&self) -> u8 {
221 match self {
222 Self::Runs(runs) => runs.runs.iter().map(|run| run.value).max().unwrap_or(0),
223 Self::Trees(trees) => trees
224 .triangles
225 .iter()
226 .map(|painted| painted.tree.max_value())
227 .max()
228 .unwrap_or(0),
229 }
230 }
231
232 #[must_use]
236 pub fn allows_kind(&self, kind: u8) -> bool {
237 match kind {
238 PAINT_DETAIL | PAINT_SUPPORTS_MUST_TOUCH | PAINT_SUPPORTS_MUST_NOT_TOUCH => true,
239 PAINT_SUPPORTS_BOTH_WAYS => self.max_value() <= MUST_NOT_TOUCH,
240 _ => false,
241 }
242 }
243
244 #[must_use]
249 pub fn fits(&self, triangle_count: usize, fingerprint: &[u8; FINGERPRINT_SIZE]) -> bool {
250 if usize::try_from(self.triangle_count()).ok() != Some(triangle_count)
251 || self.fingerprint() != fingerprint
252 {
253 return false;
254 }
255 match self {
256 Self::Runs(runs) => runs.covered() == Some(u64::from(runs.triangle_count)),
257 Self::Trees(_) => true,
258 }
259 }
260}
261
262impl PaintRuns {
263 fn covered(&self) -> Option<u64> {
265 self.runs
266 .iter()
267 .try_fold(0u64, |sum, run| sum.checked_add(u64::from(run.length)))
268 }
269
270 pub fn values(&self) -> impl Iterator<Item = u8> + '_ {
272 self.runs
273 .iter()
274 .flat_map(|run| std::iter::repeat_n(run.value, run.length as usize))
275 }
276}
277
278impl PaintNode {
279 #[must_use]
281 pub fn max_value(&self) -> u8 {
282 match self {
283 Self::Leaf(value) => *value,
284 Self::Split { children, .. } => children.iter().map(Self::max_value).max().unwrap_or(0),
285 }
286 }
287
288 #[must_use]
303 pub fn pieces(&self) -> Vec<PaintPiece> {
304 const WHOLE: [[f64; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
305 let mut pieces = Vec::new();
306 let mut stack = vec![(self, WHOLE)];
307 while let Some((node, corners)) = stack.pop() {
308 match node {
309 Self::Leaf(value) => pieces.push(PaintPiece {
310 corners,
311 value: *value,
312 }),
313 Self::Split { special, children } => {
314 let Some(split) = split_corners(corners, *special, children.len()) else {
315 continue;
316 };
317 for (child, child_corners) in children.iter().zip(split).rev() {
319 stack.push((child, child_corners));
320 }
321 }
322 }
323 }
324 pieces
325 }
326
327 #[must_use]
332 pub fn from_3mf(digits: &str) -> Option<Self> {
333 let mut groups = Vec::with_capacity(digits.len());
334 for c in digits.chars().rev() {
335 groups.push(u8::try_from(c.to_digit(16)?).ok()?);
336 }
337 let mut reader = GroupReader {
338 groups: GroupSource::List(&groups),
339 next: 0,
340 };
341 let node = read_node(&mut reader, 0).ok()?;
342 (reader.next == groups.len()).then_some(node)
343 }
344
345 #[must_use]
349 pub fn to_3mf(&self) -> Option<String> {
350 let mut groups = Vec::new();
351 write_node(self, 0, &mut |group| groups.push(group)).ok()?;
352 groups
353 .iter()
354 .rev()
355 .map(|&group| char::from_digit(u32::from(group), 16).map(|c| c.to_ascii_uppercase()))
356 .collect()
357 }
358}
359
360impl PaintPiece {
361 #[must_use]
364 pub fn points(&self, triangle: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
365 self.corners.map(|weights| {
366 let mut point = [0.0; 3];
367 for (weight, corner) in weights.iter().zip(&triangle) {
368 for (p, c) in point.iter_mut().zip(corner) {
369 *p += weight * c;
370 }
371 }
372 point
373 })
374 }
375}
376
377fn split_corners(corners: [[f64; 3]; 3], special: u8, count: usize) -> Option<Vec<[[f64; 3]; 3]>> {
381 if special > 2 {
382 return None;
383 }
384 let s = usize::from(special);
385 let p = [corners[s], corners[(s + 1) % 3], corners[(s + 2) % 3]];
386 let mid = |a: [f64; 3], b: [f64; 3]| {
387 [
388 0.5 * (a[0] + b[0]),
389 0.5 * (a[1] + b[1]),
390 0.5 * (a[2] + b[2]),
391 ]
392 };
393 let (m01, m12, m20) = (mid(p[0], p[1]), mid(p[1], p[2]), mid(p[2], p[0]));
394 Some(match count {
395 2 => vec![[p[0], p[1], m12], [m12, p[2], p[0]]],
396 3 => vec![[p[0], m01, m20], [m01, p[1], m20], [p[1], p[2], m20]],
397 4 => vec![
398 [p[0], m01, m20],
399 [m01, p[1], m12],
400 [m12, p[2], m20],
401 [m01, m12, m20],
402 ],
403 _ => return None,
404 })
405}
406
407pub fn decode_paint(version: u32, document: &[u8]) -> Result<PaintDocument, DecodePaintError> {
415 let malformed = DecodePaintError::Malformed;
416 let mut input = In(document);
417 let triangle_count = input.u32().ok_or(malformed.clone())?;
418 let fingerprint: [u8; FINGERPRINT_SIZE] = input
419 .take(FINGERPRINT_SIZE)
420 .and_then(|bytes| bytes.try_into().ok())
421 .ok_or(malformed.clone())?;
422 let decoded = match version {
423 1 => {
424 let count = input.count(5).ok_or(malformed.clone())?;
425 let mut runs = Vec::with_capacity(count);
426 for _ in 0..count {
427 let length = input.u32().ok_or(malformed.clone())?;
428 let value = input.u8().ok_or(malformed.clone())?;
429 runs.push(PaintRun { length, value });
430 }
431 PaintDocument::Runs(PaintRuns {
432 triangle_count,
433 fingerprint,
434 runs,
435 })
436 }
437 2 => {
438 let count = input.count(4).ok_or(malformed.clone())?;
439 let mut indices = Vec::with_capacity(count);
440 let mut previous: Option<u32> = None;
441 for _ in 0..count {
442 let gap = input.u32().ok_or(malformed.clone())?;
443 let index = match previous {
444 None => gap,
445 Some(_) if gap == 0 => return Err(malformed),
446 Some(previous) => previous.checked_add(gap).ok_or(malformed.clone())?,
447 };
448 if index >= triangle_count {
449 return Err(malformed);
450 }
451 indices.push(index);
452 previous = Some(index);
453 }
454 let stream = input.bytes().ok_or(malformed.clone())?;
455 let mut reader = GroupReader {
456 groups: GroupSource::Bytes(stream),
457 next: 0,
458 };
459 let mut triangles = Vec::with_capacity(count);
460 for triangle in indices {
461 let tree = read_node(&mut reader, 0).map_err(|()| malformed.clone())?;
462 triangles.push(PaintedTriangle { triangle, tree });
463 }
464 let used_bytes = reader.next.div_ceil(2);
467 if used_bytes != stream.len()
468 || (reader.next % 2 == 1 && stream.last().is_some_and(|byte| byte >> 4 != 0))
469 {
470 return Err(malformed);
471 }
472 PaintDocument::Trees(PaintTrees {
473 triangle_count,
474 fingerprint,
475 triangles,
476 })
477 }
478 other => return Err(DecodePaintError::UnknownVersion(other)),
479 };
480 if !input.is_empty() {
481 return Err(malformed);
482 }
483 Ok(decoded)
484}
485
486pub fn encode_paint(document: &PaintDocument) -> Result<Vec<u8>, EncodePaintError> {
493 let mut out = Out::default();
494 out.u32(document.triangle_count());
495 out.0.extend_from_slice(document.fingerprint());
496 match document {
497 PaintDocument::Runs(runs) => {
498 if runs.covered() != Some(u64::from(runs.triangle_count)) {
499 return Err(EncodePaintError::RunsDoNotCover);
500 }
501 if !fits_u32(runs.runs.len()) {
502 return Err(EncodePaintError::TooLarge);
503 }
504 out.len(runs.runs.len());
505 for run in &runs.runs {
506 out.u32(run.length);
507 out.u8(run.value);
508 }
509 }
510 PaintDocument::Trees(trees) => {
511 if !fits_u32(trees.triangles.len()) {
512 return Err(EncodePaintError::TooLarge);
513 }
514 out.len(trees.triangles.len());
515 let mut previous: Option<u32> = None;
516 for painted in &trees.triangles {
517 if painted.triangle >= trees.triangle_count
518 || previous.is_some_and(|previous| painted.triangle <= previous)
519 {
520 return Err(EncodePaintError::NotInOrder);
521 }
522 out.u32(painted.triangle - previous.unwrap_or(0));
523 previous = Some(painted.triangle);
524 }
525 let mut stream = Vec::new();
526 let mut groups = 0usize;
527 for painted in &trees.triangles {
528 write_node(&painted.tree, 0, &mut |group| {
529 if groups.is_multiple_of(2) {
530 stream.push(group);
531 } else if let Some(last) = stream.last_mut() {
532 *last |= group << 4;
533 }
534 groups += 1;
535 })?;
536 }
537 if !fits_u32(stream.len()) {
538 return Err(EncodePaintError::TooLarge);
539 }
540 out.bytes(&stream);
541 }
542 }
543 Ok(out.0)
544}
545
546enum GroupSource<'a> {
549 Bytes(&'a [u8]),
550 List(&'a [u8]),
551}
552
553struct GroupReader<'a> {
555 groups: GroupSource<'a>,
556 next: usize,
558}
559
560impl GroupReader<'_> {
561 fn group(&mut self) -> Result<u8, ()> {
562 let group = match self.groups {
563 GroupSource::Bytes(bytes) => {
564 let byte = *bytes.get(self.next / 2).ok_or(())?;
565 if self.next.is_multiple_of(2) {
566 byte & 0x0f
567 } else {
568 byte >> 4
569 }
570 }
571 GroupSource::List(groups) => *groups.get(self.next).ok_or(())?,
572 };
573 self.next += 1;
574 Ok(group)
575 }
576}
577
578fn read_node(reader: &mut GroupReader<'_>, depth: usize) -> Result<PaintNode, ()> {
580 if depth > MAX_PAINT_DEPTH {
581 return Err(());
582 }
583 let group = reader.group()?;
584 let sides = group & 3;
585 let high = group >> 2;
586 if sides == 0 {
587 let mut value = u32::from(high);
588 if high == 3 {
589 loop {
590 let more = reader.group()?;
591 value += u32::from(more);
592 if value > 255 {
593 return Err(());
594 }
595 if more != 15 {
596 break;
597 }
598 }
599 }
600 return Ok(PaintNode::Leaf(u8::try_from(value).map_err(|_| ())?));
601 }
602 if high == 3 {
603 return Err(());
604 }
605 let mut children = Vec::with_capacity(usize::from(sides) + 1);
606 for _ in 0..=sides {
607 children.push(read_node(reader, depth + 1)?);
608 }
609 children.reverse();
611 Ok(PaintNode::Split {
612 special: high,
613 children,
614 })
615}
616
617fn write_node(
619 node: &PaintNode,
620 depth: usize,
621 out: &mut impl FnMut(u8),
622) -> Result<(), EncodePaintError> {
623 if depth > MAX_PAINT_DEPTH {
624 return Err(EncodePaintError::TooDeep);
625 }
626 match node {
627 PaintNode::Leaf(value) if *value < 3 => out(value << 2),
628 PaintNode::Leaf(value) => {
629 out(3 << 2);
630 let mut rest = value - 3;
631 while rest >= 15 {
632 out(15);
633 rest -= 15;
634 }
635 out(rest);
636 }
637 PaintNode::Split { special, children } => {
638 let sides = match children.len() {
639 2 => 1,
640 3 => 2,
641 4 => 3,
642 _ => return Err(EncodePaintError::BadSplit),
643 };
644 if *special > 2 {
645 return Err(EncodePaintError::BadSplit);
646 }
647 out(sides | (special << 2));
648 for child in children.iter().rev() {
649 write_node(child, depth + 1, out)?;
650 }
651 }
652 }
653 Ok(())
654}
655
656#[cfg(feature = "fingerprint")]
661#[must_use]
662pub fn mesh_fingerprint(mesh: &Mesh) -> [u8; FINGERPRINT_SIZE] {
663 use sha2::{Digest, Sha384};
664 let mut hasher = Sha384::new();
665 hasher.update((mesh.vertices.len() as u64).to_le_bytes());
666 for vertex in &mesh.vertices {
667 for coordinate in vertex {
668 hasher.update(coordinate.to_bits().to_le_bytes());
669 }
670 }
671 hasher.update((mesh.triangles.len() as u64).to_le_bytes());
672 for triangle in &mesh.triangles {
673 for index in triangle {
674 hasher.update(index.to_le_bytes());
675 }
676 }
677 hasher.finalize().into()
678}
679
680#[cfg(feature = "fingerprint")]
681impl SurfaceEntry {
682 #[must_use]
687 pub fn paint(&self, mesh: &Mesh) -> Option<PaintDocument> {
688 let document = decode_paint(self.version, &self.document).ok()?;
689 (document.allows_kind(self.kind)
690 && document.fits(mesh.triangles.len(), &mesh_fingerprint(mesh)))
691 .then_some(document)
692 }
693}