Skip to main content

bread_format/
paint.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The documents of the surface paint chunk (`SPEC.md`, section 10.1): the
7//! masks themselves, which [`crate::surface`] carries without reading.
8//!
9//! Version 1 gives every triangle of a mesh one value, as runs. Version 2
10//! gives every painted triangle a tree that splits it into smaller pieces,
11//! each with its own value: what a support brush paints when it covers part
12//! of a triangle.
13//!
14//! ```text
15//! version 1   u32 triangle count, 48 bytes fingerprint,
16//!             u32 count, then per run: u32 length, u8 value
17//! version 2   u32 triangle count, 48 bytes fingerprint,
18//!             u32 count, then per painted triangle: u32 gap,
19//!             u32 length, the trees as a bit stream of 4-bit groups
20//! ```
21//!
22//! A document that breaks a rule never makes a file unreadable: a reader
23//! treats its entry as absent. [`SurfaceEntry::paint`] does that check, with
24//! the leaf's mesh, and gives the document only when it applies.
25
26use 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
34/// The kind of paint that marks details to keep: values 0 to 255.
35pub const PAINT_DETAIL: u8 = 0;
36/// The kind of paint that marks where supports must touch: values 0 to 255.
37pub const PAINT_SUPPORTS_MUST_TOUCH: u8 = 1;
38/// The kind of paint that marks where supports must not touch: values 0 to
39/// 255.
40pub const PAINT_SUPPORTS_MUST_NOT_TOUCH: u8 = 2;
41/// The kind of paint that marks both, as a support brush paints them: 0
42/// bare, 1 supports must touch, 2 supports must not touch.
43pub const PAINT_SUPPORTS_BOTH_WAYS: u8 = 3;
44
45/// The value of kind [`PAINT_SUPPORTS_BOTH_WAYS`] where supports must touch.
46pub const MUST_TOUCH: u8 = 1;
47/// The value of kind [`PAINT_SUPPORTS_BOTH_WAYS`] where supports must not
48/// touch.
49pub const MUST_NOT_TOUCH: u8 = 2;
50
51/// How deep a node of a version 2 tree may be: the root is at depth 0.
52pub const MAX_PAINT_DEPTH: usize = 32;
53
54/// The size of a mesh fingerprint, a SHA-384 digest.
55pub const FINGERPRINT_SIZE: usize = 48;
56
57/// A surface paint document.
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub enum PaintDocument {
60    /// Version 1: one value per triangle.
61    Runs(PaintRuns),
62    /// Version 2: a tree per painted triangle.
63    Trees(PaintTrees),
64}
65
66/// A version 1 document: the value of every triangle, as runs.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct PaintRuns {
69    /// How many triangles the painted mesh has.
70    pub triangle_count: u32,
71    /// The painted mesh's fingerprint ([`mesh_fingerprint`]).
72    pub fingerprint: [u8; FINGERPRINT_SIZE],
73    /// The runs, from the first triangle on.
74    pub runs: Vec<PaintRun>,
75}
76
77/// Triangles in a row that have the same value.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct PaintRun {
80    /// How many triangles the run covers.
81    pub length: u32,
82    /// Their value.
83    pub value: u8,
84}
85
86/// A version 2 document: the painted triangles and their trees.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct PaintTrees {
89    /// How many triangles the painted mesh has.
90    pub triangle_count: u32,
91    /// The painted mesh's fingerprint ([`mesh_fingerprint`]).
92    pub fingerprint: [u8; FINGERPRINT_SIZE],
93    /// The painted triangles, in increasing order. The others have the value
94    /// 0 all over.
95    pub triangles: Vec<PaintedTriangle>,
96}
97
98/// One painted triangle of a version 2 document.
99#[derive(Clone, Debug, PartialEq, Eq)]
100pub struct PaintedTriangle {
101    /// The triangle's index in its mesh.
102    pub triangle: u32,
103    /// How it is split, and the value of each piece.
104    pub tree: PaintNode,
105}
106
107/// A node of a version 2 tree.
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub enum PaintNode {
110    /// A piece of the triangle, with its value.
111    Leaf(u8),
112    /// A triangle split into 2, 3 or 4 children (1, 2 or 3 sides split),
113    /// named from its special corner, 0 to 2.
114    Split {
115        /// The corner the split is named from: see [`PaintNode::pieces`].
116        special: u8,
117        /// The children, first to last: 2, 3 or 4 of them.
118        children: Vec<PaintNode>,
119    },
120}
121
122/// A piece of a painted triangle, the leaf of its tree.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct PaintPiece {
125    /// The piece's three corners, in order, each as its weights over the
126    /// triangle's corners *A*0, *A*1 and *A*2. The weights are multiples of
127    /// a power of two, so they are exact.
128    pub corners: [[f64; 3]; 3],
129    /// The piece's value.
130    pub value: u8,
131}
132
133/// Why a document could not be decoded.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub enum DecodePaintError {
136    /// A document version this build does not know.
137    UnknownVersion(u32),
138    /// The document breaks a rule of section 10.1.
139    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/// Why a document could not be encoded.
159#[derive(Clone, Debug, PartialEq, Eq)]
160pub enum EncodePaintError {
161    /// The runs of a version 1 document do not add up to the triangle count.
162    RunsDoNotCover,
163    /// The painted triangles of a version 2 document are not in increasing
164    /// order, or one is past the mesh's last triangle.
165    NotInOrder,
166    /// A split node has fewer than 2 or more than 4 children, or a special
167    /// corner above 2.
168    BadSplit,
169    /// A node is deeper than [`MAX_PAINT_DEPTH`].
170    TooDeep,
171    /// The document has 2^32 or more runs or painted triangles, or its trees
172    /// take 4 GiB or more.
173    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    /// The document version: 1 for runs, 2 for trees.
192    #[must_use]
193    pub fn version(&self) -> u32 {
194        match self {
195            Self::Runs(_) => 1,
196            Self::Trees(_) => 2,
197        }
198    }
199
200    /// How many triangles the painted mesh has.
201    #[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    /// The painted mesh's fingerprint.
210    #[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    /// The largest value anywhere in the document, 0 when nothing is painted.
219    #[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    /// Whether the document's values are allowed for paint of `kind`: any
233    /// value for kinds 0 to 2, at most 2 for kind 3, and nothing for the
234    /// reserved kinds.
235    #[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    /// Whether the document was made on `mesh`, of `triangle_count`
245    /// triangles and with `fingerprint`, and covers it: version 1 runs that
246    /// add up to the triangle count. Version 2 documents are checked against
247    /// the triangle count when they are decoded.
248    #[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    /// How many triangles the runs cover, or `None` past `u64`.
264    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    /// The value of every triangle, from the first on.
271    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    /// The largest value in the tree.
280    #[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    /// The pieces of the triangle, depth first and each node's children
289    /// first to last, with their corners as weights over the triangle's
290    /// corners (section 10.1). A split node with corners C0, C1, C2 and
291    /// special corner s takes P0 = Cs, P1 = Cs+1, P2 = Cs+2, indices modulo 3,
292    /// and Mij the midpoint of Pi and Pj; its children are:
293    ///
294    /// ```text
295    /// 1 side split   (P0, P1, M12), (M12, P2, P0)
296    /// 2 sides split  (P0, M01, M20), (M01, P1, M20), (P1, P2, M20)
297    /// 3 sides split  (P0, M01, M20), (M01, P1, M12), (M12, P2, M20), (M01, M12, M20)
298    /// ```
299    ///
300    /// The pieces depend on the tree alone, never on neighbouring pieces or
301    /// triangles: they cover the triangle exactly once, each wound like it.
302    #[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                    // Pushed last to first, so the first child comes out first.
318                    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    /// Reads the tree of one triangle from the string of hex digits that
328    /// 3MF files of filament slicers hold for it: one digit per group of 4
329    /// bits, the last digit holding the first group. `None` when the string
330    /// is not exactly one tree that version 2 allows.
331    #[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    /// The tree as the string of hex digits a 3MF file holds for its
346    /// triangle (see [`PaintNode::from_3mf`]), in upper case. `None` for a
347    /// tree version 2 does not allow.
348    #[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    /// The piece's corners as points, given the triangle's corners in the
362    /// mesh's order, first corner first.
363    #[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
377/// The corners of the children of a node with `corners`, split from
378/// `special` into `count` children; `None` for a split the format does not
379/// have.
380fn 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
407/// Decodes a surface paint document of `version`.
408///
409/// # Errors
410///
411/// [`DecodePaintError::UnknownVersion`] for a version other than 1 or 2, and
412/// [`DecodePaintError::Malformed`] for a document that breaks a rule of
413/// section 10.1. Either way a reader treats the entry as absent.
414pub 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            // The stream ends with the last tree: at most the unused half of
465            // its last byte is left, and it is 0.
466            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
486/// Encodes a surface paint document, as the version [`PaintDocument::version`]
487/// gives.
488///
489/// # Errors
490///
491/// When the document breaks a rule of section 10.1: see [`EncodePaintError`].
492pub 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
546/// Where the groups of a tree come from: a bit stream, two groups a byte
547/// with the first in the low half, or a list of groups.
548enum GroupSource<'a> {
549    Bytes(&'a [u8]),
550    List(&'a [u8]),
551}
552
553/// Reads 4-bit groups one after the other.
554struct GroupReader<'a> {
555    groups: GroupSource<'a>,
556    /// The index of the next group.
557    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
578/// Reads one node at `depth`, and its children.
579fn 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    // The stream holds the last child first.
610    children.reverse();
611    Ok(PaintNode::Split {
612        special: high,
613        children,
614    })
615}
616
617/// Writes one node at `depth`, and its children, a group at a time.
618fn 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/// The fingerprint that names a mesh in a paint document (section 10.1): the
657/// SHA-384 digest of the vertex count as a `u64`, the bits of every
658/// coordinate as `u32`s, the triangle count as a `u64`, and every triangle's
659/// indices as `u32`s, all little-endian.
660#[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    /// The entry's document, when a reader keeps it for the leaf's `mesh`
683    /// (section 10.2): a kind and a document version this build knows, a
684    /// document that is not malformed, made on `mesh`, covering it, and with
685    /// values its kind allows. `None` means the entry is treated as absent.
686    #[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}