Skip to main content

bread_format/
file.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! A whole `.bread` file: the thumbnail when there is one, the scene chunk,
7//! the metadata when there is any, the project settings, the supports, the
8//! hollows, the program data and the surface paint when there are any, the
9//! roles of leaves that are not models, the volumes that act on models when
10//! there are any, then one mesh chunk per mesh of the scene, in its order, the
11//! support previews when there are any, and last the chunks this build does
12//! not know.
13//!
14//! Reading keeps the chunks this build does not know, official or private, as
15//! they are, and writing writes them back at the end, in their order: a
16//! program that opens a file and saves it does not drop other programs'
17//! chunks. A program that changes the scene should drop them, since they may
18//! name nodes or meshes by an index that changed (section 7.2). Reading skips
19//! a chunk whose tag is not four ASCII letters or digits starting with a
20//! letter, which no writer may write. It also skips supports
21//! and hollows chunks of version 1, which only drafts of the format wrote, as
22//! section 7.3 allows: their models open without editable supports, and their
23//! hollows without the original. The support previews of draft supports are
24//! skipped with them, since they could not be checked against the supports.
25
26use std::fmt;
27use std::io::{self, Read, Write};
28
29use crate::app::{
30    DecodeDocumentsError, EncodeDocumentsError, HOLLOWS_TAG, HOLLOWS_VERSION, HollowEntry,
31    SETTINGS_TAG, SETTINGS_VERSION, SUPPORTS_TAG, SUPPORTS_VERSION, SupportEntry, decode_hollows,
32    decode_supports, encode_hollows, encode_supports,
33};
34use crate::container::{BreadReader, BreadWriter, Chunk, ChunkTag, ReadBreadError};
35use crate::mesh::{DecodeMeshError, EncodeMeshError, MESH_TAG, MESH_VERSION, Mesh, decode_mesh};
36use crate::mesh_v2::{decode_mesh_v2, encode_mesh_v2};
37use crate::metadata::{
38    EncodeMetadataError, METADATA_TAG, METADATA_VERSION, MetadataEntry, decode_metadata,
39    encode_metadata,
40};
41use crate::parallel;
42use crate::preview::{
43    DecodePreviewsError, EncodePreviewsError, SUPPORT_PREVIEW_TAG, SUPPORT_PREVIEW_VERSION,
44    SupportPreview, decode_previews, encode_previews,
45};
46use crate::program::{
47    DecodeProgramDataError, EncodeProgramDataError, PROGRAM_TAG, PROGRAM_VERSION, ProgramEntry,
48    decode_program_data, encode_program_data,
49};
50use crate::role::{
51    DecodeRolesError, EncodeRolesError, ROLE_RAFT, ROLE_TAG, ROLE_VERSION, RoleEntry, decode_roles,
52    encode_roles,
53};
54use crate::scene::{
55    DecodeSceneError, EncodeSceneError, SCENE_TAG, SCENE_VERSION, Scene, decode_scene, encode_scene,
56};
57use crate::surface::{
58    DecodeSurfaceError, EncodeSurfaceError, SURFACE_TAG, SURFACE_VERSION, SurfaceEntry,
59    decode_surface, decode_surface_v1, encode_surface,
60};
61use crate::volume::{
62    DecodeVolumesError, EncodeVolumesError, VOLUME_NEGATIVE, VOLUME_TAG, VOLUME_UNCUT,
63    VOLUME_VERSION, VolumeEntry, decode_volumes, encode_volumes,
64};
65
66/// The tag of the thumbnail chunk, whose payload is a PNG file. Section 8
67/// asks writers to put it first, so a program that only wants the picture
68/// reads one chunk.
69pub const THUMBNAIL_TAG: ChunkTag = ChunkTag(*b"THMB");
70
71/// The thumbnail chunk version this build writes and reads.
72pub const THUMBNAIL_VERSION: u16 = 1;
73
74/// What a `.bread` file holds.
75#[derive(Clone, Debug, Default, PartialEq)]
76pub struct BreadFile {
77    /// The scene and its meshes.
78    pub scene: Scene,
79    /// The project settings document, carried without being read.
80    pub settings: Option<Vec<u8>>,
81    /// Supports kept as data. Their support leaves show an empty mesh.
82    pub supports: Vec<SupportEntry>,
83    /// How hollowed models were made. Their leaves show the hollow.
84    pub hollows: Vec<HollowEntry>,
85    /// A small picture of the file: a PNG, at most 512 x 512 and best
86    /// 256 x 256, in sRGB. It is carried without being read: the PNG is
87    /// neither checked nor decoded.
88    pub thumbnail: Option<Vec<u8>>,
89    /// The mesh of the supports, for readers that do not rebuild them from
90    /// their documents. Each preview names the support leaf of an entry of
91    /// `supports`. A program that edits the supports writes new previews, or
92    /// none.
93    pub support_previews: Vec<SupportPreview>,
94    /// What was painted on the faces of leaves: one mask per program, leaf
95    /// and kind, each document carried without being read. A program changes
96    /// and drops only its own entries. Entries read from chunk version 1 name
97    /// no program, and must be given one before the file is written.
98    pub surface: Vec<SurfaceEntry>,
99    /// The leaves that are not models: supports or a raft. A support leaf of
100    /// `supports` is supports whether it is listed here or not.
101    pub roles: Vec<RoleEntry>,
102    /// Who made the file, how it may be used, and lasting ids for its parts.
103    /// Reading leaves out what breaks a rule of section 12, so metadata never
104    /// makes a file unreadable.
105    pub metadata: Vec<MetadataEntry>,
106    /// Meshes that act on a model without printing: support enforcers and
107    /// blockers, modifiers, and negative volumes with the model before the
108    /// cut. No leaf shows a volume's mesh.
109    pub volumes: Vec<VolumeEntry>,
110    /// Each program's own documents, about the whole file or one node, each
111    /// carried without being read (section 13).
112    pub program_data: Vec<ProgramEntry>,
113    /// The chunks this build does not know, official or private, as they
114    /// were read, in their order. Writing writes them back last. A program
115    /// keeps them, unless it removes or renumbers nodes or meshes: then it
116    /// may clear them, since they may name nodes or meshes by an index that
117    /// changed (section 7.4).
118    pub other_chunks: Vec<Chunk>,
119}
120
121/// Why a file could not be written.
122#[derive(Debug)]
123pub enum WriteFileError {
124    Io(io::Error),
125    Scene(EncodeSceneError),
126    Mesh(EncodeMeshError),
127    Supports(EncodeDocumentsError),
128    Hollows(EncodeDocumentsError),
129    Previews(EncodePreviewsError),
130    Surface(EncodeSurfaceError),
131    Roles(EncodeRolesError),
132    /// A role contradicts the supports or hollows: a support leaf given the
133    /// role of a raft, or a model of either given a role.
134    RoleConflict {
135        leaf: usize,
136    },
137    Metadata(EncodeMetadataError),
138    Volumes(EncodeVolumesError),
139    /// A volume belongs to a support leaf or a leaf with the role of
140    /// supports or a raft, or a hollowed model has a negative volume.
141    VolumeConflict {
142        model: usize,
143    },
144    ProgramData(EncodeProgramDataError),
145    /// One of `other_chunks` has a tag this build knows, which it writes
146    /// itself, or a tag that is not four ASCII letters or digits starting
147    /// with a letter.
148    OtherChunk {
149        tag: ChunkTag,
150    },
151    /// A support leaf shows a mesh with vertices or triangles: support
152    /// leaves are stored with an empty mesh.
153    SupportMeshNotEmpty {
154        leaf: usize,
155    },
156    /// A support leaf is also a hollowed model.
157    SupportIsHollowed {
158        leaf: usize,
159    },
160    /// A support preview names a leaf that no supports entry shows.
161    PreviewWithoutSupports {
162        leaf: usize,
163    },
164}
165
166impl fmt::Display for WriteFileError {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match self {
169            Self::Io(err) => write!(f, "{err}"),
170            Self::Scene(err) => write!(f, "{err}"),
171            Self::Mesh(err) => write!(f, "{err}"),
172            Self::Supports(err) | Self::Hollows(err) => write!(f, "{err}"),
173            Self::Previews(err) => write!(f, "{err}"),
174            Self::Surface(err) => write!(f, "{err}"),
175            Self::Roles(err) => write!(f, "{err}"),
176            Self::RoleConflict { leaf } => write!(f, "{}", RoleConflict(*leaf)),
177            Self::Metadata(err) => write!(f, "{err}"),
178            Self::Volumes(err) => write!(f, "{err}"),
179            Self::VolumeConflict { model } => write!(f, "{}", VolumeConflict(*model)),
180            Self::ProgramData(err) => write!(f, "{err}"),
181            Self::OtherChunk { tag } => write!(
182                f,
183                "the {tag} chunk cannot be carried: its tag is known or not a tag"
184            ),
185            Self::SupportMeshNotEmpty { leaf } => {
186                write!(
187                    f,
188                    "the support leaf {leaf} shows a mesh instead of an empty one"
189                )
190            }
191            Self::SupportIsHollowed { leaf } => write!(f, "{}", SupportIsHollowed(*leaf)),
192            Self::PreviewWithoutSupports { leaf } => {
193                write!(f, "{}", PreviewWithoutSupports(*leaf))
194            }
195        }
196    }
197}
198
199impl std::error::Error for WriteFileError {}
200
201impl From<io::Error> for WriteFileError {
202    fn from(err: io::Error) -> Self {
203        Self::Io(err)
204    }
205}
206
207/// Why a `.bread` file could not be read.
208#[derive(Debug)]
209pub enum ReadFileError {
210    File(ReadBreadError),
211    /// A chunk this build reads has a version it does not read: a newer one,
212    /// or 0, which no version is.
213    ChunkVersion {
214        tag: ChunkTag,
215        version: u16,
216    },
217    /// The file holds a number of chunks of one tag that the format does not
218    /// allow: no scene chunk, or two of a chunk that comes at most once.
219    ChunkCount {
220        tag: ChunkTag,
221        count: usize,
222    },
223    Mesh(DecodeMeshError),
224    Scene(DecodeSceneError),
225    Supports(DecodeDocumentsError),
226    Hollows(DecodeDocumentsError),
227    Previews(DecodePreviewsError),
228    Surface(DecodeSurfaceError),
229    Roles(DecodeRolesError),
230    ProgramData(DecodeProgramDataError),
231    /// A role contradicts the supports or hollows: a support leaf given the
232    /// role of a raft, or a model of either given a role.
233    RoleConflict {
234        leaf: usize,
235    },
236    /// A support leaf is also a hollowed model.
237    SupportIsHollowed {
238        leaf: usize,
239    },
240    /// A support preview names a leaf that no supports entry shows.
241    PreviewWithoutSupports {
242        leaf: usize,
243    },
244    Volumes(DecodeVolumesError),
245    /// A volume belongs to a support leaf or a leaf with the role of
246    /// supports or a raft, or a hollowed model has a negative volume.
247    VolumeConflict {
248        model: usize,
249    },
250}
251
252impl fmt::Display for ReadFileError {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        match self {
255            Self::File(err) => write!(f, "{err}"),
256            Self::ChunkVersion { tag, version: 0 } => {
257                write!(f, "the {tag} chunk has version 0, which does not exist")
258            }
259            Self::ChunkVersion { tag, version } => {
260                write!(
261                    f,
262                    "the {tag} chunk is written in a newer version ({version})"
263                )
264            }
265            Self::ChunkCount { tag, count } => write!(f, "the file holds {count} {tag} chunks"),
266            Self::Mesh(err) => write!(f, "{err}"),
267            Self::Scene(err) => write!(f, "{err}"),
268            Self::Supports(err) | Self::Hollows(err) => write!(f, "{err}"),
269            Self::Previews(err) => write!(f, "{err}"),
270            Self::Surface(err) => write!(f, "{err}"),
271            Self::Roles(err) => write!(f, "{err}"),
272            Self::ProgramData(err) => write!(f, "{err}"),
273            Self::RoleConflict { leaf } => write!(f, "{}", RoleConflict(*leaf)),
274            Self::SupportIsHollowed { leaf } => write!(f, "{}", SupportIsHollowed(*leaf)),
275            Self::PreviewWithoutSupports { leaf } => {
276                write!(f, "{}", PreviewWithoutSupports(*leaf))
277            }
278            Self::Volumes(err) => write!(f, "{err}"),
279            Self::VolumeConflict { model } => write!(f, "{}", VolumeConflict(*model)),
280        }
281    }
282}
283
284impl std::error::Error for ReadFileError {}
285
286/// The message of both `RoleConflict` errors.
287struct RoleConflict(usize);
288
289impl fmt::Display for RoleConflict {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        write!(
292            f,
293            "the role of leaf {} contradicts the supports or hollows",
294            self.0
295        )
296    }
297}
298
299/// The message of both `VolumeConflict` errors.
300struct VolumeConflict(usize);
301
302impl fmt::Display for VolumeConflict {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        write!(
305            f,
306            "the volumes of leaf {} contradict the supports, hollows or roles",
307            self.0
308        )
309    }
310}
311
312/// The message of both `SupportIsHollowed` errors.
313struct SupportIsHollowed(usize);
314
315impl fmt::Display for SupportIsHollowed {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        write!(f, "the support leaf {} is also a hollowed model", self.0)
318    }
319}
320
321/// The message of both `PreviewWithoutSupports` errors.
322struct PreviewWithoutSupports(usize);
323
324impl fmt::Display for PreviewWithoutSupports {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        write!(
327            f,
328            "the support preview of leaf {} has no supports entry",
329            self.0
330        )
331    }
332}
333
334impl From<ReadBreadError> for ReadFileError {
335    fn from(err: ReadBreadError) -> Self {
336        Self::File(err)
337    }
338}
339
340/// The newest version of the chunk `tag` this build reads, or `None` for a
341/// tag it does not know, which a reader skips. Every version from 1 up to it
342/// is read, though older supports and hollows chunks are skipped; any other
343/// version makes the file unreadable.
344pub fn supported_version(tag: ChunkTag) -> Option<u16> {
345    Some(match tag {
346        THUMBNAIL_TAG => THUMBNAIL_VERSION,
347        SCENE_TAG => SCENE_VERSION,
348        SETTINGS_TAG => SETTINGS_VERSION,
349        SUPPORTS_TAG => SUPPORTS_VERSION,
350        HOLLOWS_TAG => HOLLOWS_VERSION,
351        MESH_TAG => MESH_VERSION,
352        SUPPORT_PREVIEW_TAG => SUPPORT_PREVIEW_VERSION,
353        SURFACE_TAG => SURFACE_VERSION,
354        ROLE_TAG => ROLE_VERSION,
355        METADATA_TAG => METADATA_VERSION,
356        VOLUME_TAG => VOLUME_VERSION,
357        PROGRAM_TAG => PROGRAM_VERSION,
358        _ => return None,
359    })
360}
361
362/// Writes `file` as a `.bread` file to `out`, handing `out` back. When it
363/// fails, what it wrote to `out` is not a valid file.
364pub fn write_file<W: Write>(file: &BreadFile, out: W) -> Result<W, WriteFileError> {
365    let scene = &file.scene;
366    let scene_payload = encode_scene(scene).map_err(WriteFileError::Scene)?;
367    let supports = encode_supports(&file.supports, scene).map_err(WriteFileError::Supports)?;
368    let hollows = encode_hollows(&file.hollows, scene).map_err(WriteFileError::Hollows)?;
369    let previews =
370        encode_previews(&file.support_previews, scene).map_err(WriteFileError::Previews)?;
371    let surface = encode_surface(&file.surface, scene).map_err(WriteFileError::Surface)?;
372    let roles = encode_roles(&file.roles, scene).map_err(WriteFileError::Roles)?;
373    let metadata = encode_metadata(&file.metadata, scene).map_err(WriteFileError::Metadata)?;
374    let volumes = encode_volumes(&file.volumes, scene).map_err(WriteFileError::Volumes)?;
375    let program_data =
376        encode_program_data(&file.program_data, scene).map_err(WriteFileError::ProgramData)?;
377    if let Some(chunk) = file
378        .other_chunks
379        .iter()
380        .find(|chunk| !is_tag(chunk.tag) || supported_version(chunk.tag).is_some())
381    {
382        return Err(WriteFileError::OtherChunk { tag: chunk.tag });
383    }
384    for entry in &file.supports {
385        let leaf = entry.support;
386        if scene
387            .leaf_mesh(leaf)
388            .is_some_and(|mesh| !mesh.vertices.is_empty() || !mesh.triangles.is_empty())
389        {
390            return Err(WriteFileError::SupportMeshNotEmpty { leaf });
391        }
392    }
393    if let Some(leaf) = hollowed_support(&file.supports, &file.hollows) {
394        return Err(WriteFileError::SupportIsHollowed { leaf });
395    }
396    if let Some(leaf) = unsupported_preview(&file.support_previews, &file.supports) {
397        return Err(WriteFileError::PreviewWithoutSupports { leaf });
398    }
399    if let Some(leaf) = role_conflict(&file.roles, &file.supports, &file.hollows) {
400        return Err(WriteFileError::RoleConflict { leaf });
401    }
402    if let Some(model) = volume_conflict(&file.volumes, &file.supports, &file.hollows, &file.roles)
403    {
404        return Err(WriteFileError::VolumeConflict { model });
405    }
406    // Each mesh is encoded on its own, so they are encoded side by side.
407    let meshes: Vec<Vec<u8>> = parallel::map(&scene.meshes, encode_mesh_v2)
408        .into_iter()
409        .collect::<Result<_, _>>()
410        .map_err(WriteFileError::Mesh)?;
411
412    let mut writer = BreadWriter::new(out)?;
413    if let Some(thumbnail) = &file.thumbnail {
414        writer.chunk(THUMBNAIL_TAG, THUMBNAIL_VERSION, thumbnail)?;
415    }
416    writer.chunk(SCENE_TAG, SCENE_VERSION, &scene_payload)?;
417    if !file.metadata.is_empty() {
418        writer.chunk(METADATA_TAG, METADATA_VERSION, &metadata)?;
419    }
420    if let Some(settings) = &file.settings {
421        writer.chunk(SETTINGS_TAG, SETTINGS_VERSION, settings)?;
422    }
423    if !file.supports.is_empty() {
424        writer.chunk(SUPPORTS_TAG, SUPPORTS_VERSION, &supports)?;
425    }
426    if !file.hollows.is_empty() {
427        writer.chunk(HOLLOWS_TAG, HOLLOWS_VERSION, &hollows)?;
428    }
429    if !file.program_data.is_empty() {
430        writer.chunk(PROGRAM_TAG, PROGRAM_VERSION, &program_data)?;
431    }
432    if !file.surface.is_empty() {
433        writer.chunk(SURFACE_TAG, SURFACE_VERSION, &surface)?;
434    }
435    if !file.roles.is_empty() {
436        writer.chunk(ROLE_TAG, ROLE_VERSION, &roles)?;
437    }
438    if !file.volumes.is_empty() {
439        writer.chunk(VOLUME_TAG, VOLUME_VERSION, &volumes)?;
440    }
441    for payload in &meshes {
442        writer.chunk(MESH_TAG, MESH_VERSION, payload)?;
443    }
444    if !file.support_previews.is_empty() {
445        writer.chunk(SUPPORT_PREVIEW_TAG, SUPPORT_PREVIEW_VERSION, &previews)?;
446    }
447    for chunk in &file.other_chunks {
448        writer.chunk(chunk.tag, chunk.version, &chunk.payload)?;
449    }
450    Ok(writer.finish()?)
451}
452
453/// Whether `tag` is one a writer may write: four ASCII letters or digits,
454/// the first a letter (section 7).
455fn is_tag(tag: ChunkTag) -> bool {
456    tag.0[0].is_ascii_alphabetic() && tag.0.iter().all(u8::is_ascii_alphanumeric)
457}
458
459/// Mesh payloads smaller than this are decoded where they are read: a thread
460/// of their own would cost more than it saves.
461const MESH_ON_ITS_OWN_THREAD: usize = 1 << 16;
462
463/// A mesh chunk being decoded, or decoded already.
464enum PendingMesh<'scope> {
465    Done(Result<Mesh, DecodeMeshError>),
466    Running(std::thread::ScopedJoinHandle<'scope, Result<Mesh, DecodeMeshError>>),
467}
468
469impl PendingMesh<'_> {
470    fn finish(self) -> Result<Mesh, DecodeMeshError> {
471        match self {
472            Self::Done(mesh) => mesh,
473            Self::Running(handle) => handle
474                .join()
475                .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
476        }
477    }
478}
479
480fn decode_mesh_chunk(version: u16, payload: &[u8]) -> Result<Mesh, DecodeMeshError> {
481    match version {
482        1 => decode_mesh(payload),
483        _ => decode_mesh_v2(payload),
484    }
485}
486
487/// Reads the `.bread` file in `input`.
488///
489/// Large meshes are decoded on threads of their own while the rest of the
490/// file is read. A file is refused for the same reason as if every chunk
491/// were read in order: the first fault in file order.
492pub fn read_file<R: Read>(input: R) -> Result<BreadFile, ReadFileError> {
493    let mut reader = BreadReader::new(input)?;
494    std::thread::scope(|scope| read_chunks(&mut reader, scope))
495}
496
497fn read_chunks<'scope, R: Read>(
498    reader: &mut BreadReader<R>,
499    scope: &'scope std::thread::Scope<'scope, '_>,
500) -> Result<BreadFile, ReadFileError> {
501    let (mut thumbnails, mut scenes, mut settings, mut supports, mut hollows, mut previews) = (
502        Vec::new(),
503        Vec::new(),
504        Vec::new(),
505        Vec::new(),
506        Vec::new(),
507        Vec::new(),
508    );
509    let mut volumes = Vec::new();
510    let (mut surfaces, mut roles, mut metadata, mut programs) =
511        (Vec::new(), Vec::new(), Vec::new(), Vec::new());
512    let mut other_chunks = Vec::new();
513    let mut pending: Vec<PendingMesh<'scope>> = Vec::new();
514    let mut running = std::collections::VecDeque::new();
515    let threads = parallel::threads();
516    let mut read_all = || -> Result<(), ReadFileError> {
517        while let Some(chunk) = reader.next_chunk()? {
518            let Some(supported) = supported_version(chunk.tag) else {
519                if is_tag(chunk.tag) {
520                    other_chunks.push(chunk);
521                }
522                continue;
523            };
524            if chunk.version == 0 || chunk.version > supported {
525                return Err(ReadFileError::ChunkVersion {
526                    tag: chunk.tag,
527                    version: chunk.version,
528                });
529            }
530            // An older supports or hollows chunk is a draft one: it still counts
531            // as the one chunk of its tag, but its payload is not read.
532            let current = chunk.version == supported;
533            match chunk.tag {
534                THUMBNAIL_TAG => thumbnails.push(chunk.payload),
535                SCENE_TAG => scenes.push(chunk.payload),
536                SETTINGS_TAG => settings.push(chunk.payload),
537                SUPPORTS_TAG => supports.push(current.then_some(chunk.payload)),
538                HOLLOWS_TAG => hollows.push(current.then_some(chunk.payload)),
539                SUPPORT_PREVIEW_TAG => previews.push(chunk.payload),
540                SURFACE_TAG => surfaces.push((chunk.version, chunk.payload)),
541                ROLE_TAG => roles.push(chunk.payload),
542                METADATA_TAG => metadata.push(chunk.payload),
543                VOLUME_TAG => volumes.push(chunk.payload),
544                PROGRAM_TAG => programs.push(chunk.payload),
545                _ => {
546                    let (version, payload) = (chunk.version, chunk.payload);
547                    if threads < 2 || payload.len() < MESH_ON_ITS_OWN_THREAD {
548                        pending.push(PendingMesh::Done(decode_mesh_chunk(version, &payload)));
549                        continue;
550                    }
551                    // At most as many meshes at once as the machine runs threads.
552                    if running.len() >= threads {
553                        let oldest: usize = running.pop_front().expect("one is running");
554                        let mesh = std::mem::replace(
555                            &mut pending[oldest],
556                            PendingMesh::Done(Err(DecodeMeshError::Malformed)),
557                        );
558                        pending[oldest] = PendingMesh::Done(mesh.finish());
559                    }
560                    running.push_back(pending.len());
561                    pending.push(PendingMesh::Running(
562                        scope.spawn(move || decode_mesh_chunk(version, &payload)),
563                    ));
564                }
565            }
566        }
567        Ok(())
568    };
569    let read = read_all();
570    // A mesh refused comes before any fault found after it in the file, as
571    // when each mesh is decoded the moment it is read.
572    let meshes = pending
573        .into_iter()
574        .map(PendingMesh::finish)
575        .collect::<Result<Vec<_>, _>>()
576        .map_err(ReadFileError::Mesh)?;
577    read?;
578    let scene = single(SCENE_TAG, scenes)?.ok_or(ReadFileError::ChunkCount {
579        tag: SCENE_TAG,
580        count: 0,
581    })?;
582    let thumbnail = single(THUMBNAIL_TAG, thumbnails)?;
583    let settings = single(SETTINGS_TAG, settings)?;
584    let supports = single(SUPPORTS_TAG, supports)?;
585    let draft_supports = matches!(supports, Some(None));
586    let supports = supports.flatten();
587    let hollows = single(HOLLOWS_TAG, hollows)?.flatten();
588    let previews = single(SUPPORT_PREVIEW_TAG, previews)?;
589    let surface = single(SURFACE_TAG, surfaces)?;
590    let roles = single(ROLE_TAG, roles)?;
591    let metadata = single(METADATA_TAG, metadata)?;
592    let volumes = single(VOLUME_TAG, volumes)?;
593    let programs = single(PROGRAM_TAG, programs)?;
594
595    let scene = decode_scene(&scene, meshes).map_err(ReadFileError::Scene)?;
596    let supports = match supports {
597        None => Vec::new(),
598        Some(payload) => decode_supports(&payload, &scene).map_err(ReadFileError::Supports)?,
599    };
600    let hollows = match hollows {
601        None => Vec::new(),
602        Some(payload) => decode_hollows(&payload, &scene).map_err(ReadFileError::Hollows)?,
603    };
604    if let Some(leaf) = hollowed_support(&supports, &hollows) {
605        return Err(ReadFileError::SupportIsHollowed { leaf });
606    }
607    let support_previews = match previews {
608        Some(payload) if !draft_supports => {
609            decode_previews(&payload, &scene).map_err(ReadFileError::Previews)?
610        }
611        _ => Vec::new(),
612    };
613    if let Some(leaf) = unsupported_preview(&support_previews, &supports) {
614        return Err(ReadFileError::PreviewWithoutSupports { leaf });
615    }
616    let surface = match surface {
617        None => Vec::new(),
618        Some((1, payload)) => {
619            decode_surface_v1(&payload, &scene).map_err(ReadFileError::Surface)?
620        }
621        Some((_, payload)) => decode_surface(&payload, &scene).map_err(ReadFileError::Surface)?,
622    };
623    let roles = match roles {
624        None => Vec::new(),
625        Some(payload) => decode_roles(&payload, &scene).map_err(ReadFileError::Roles)?,
626    };
627    if let Some(leaf) = role_conflict(&roles, &supports, &hollows) {
628        return Err(ReadFileError::RoleConflict { leaf });
629    }
630    let volumes = match volumes {
631        None => Vec::new(),
632        Some(payload) => decode_volumes(&payload, &scene).map_err(ReadFileError::Volumes)?,
633    };
634    if let Some(model) = volume_conflict(&volumes, &supports, &hollows, &roles) {
635        return Err(ReadFileError::VolumeConflict { model });
636    }
637    let metadata = metadata.map_or_else(Vec::new, |payload| decode_metadata(&payload, &scene));
638    let program_data = match programs {
639        None => Vec::new(),
640        Some(payload) => {
641            decode_program_data(&payload, &scene).map_err(ReadFileError::ProgramData)?
642        }
643    };
644    Ok(BreadFile {
645        scene,
646        settings,
647        supports,
648        hollows,
649        thumbnail,
650        support_previews,
651        surface,
652        roles,
653        metadata,
654        volumes,
655        program_data,
656        other_chunks,
657    })
658}
659
660/// A leaf whose role contradicts the supports or hollows, which section 11
661/// forbids: a support leaf given the role of a raft, or the model of either
662/// given the role of supports or of a raft. Reserved roles mean a model, so
663/// they contradict nothing.
664fn role_conflict(
665    roles: &[RoleEntry],
666    supports: &[SupportEntry],
667    hollows: &[HollowEntry],
668) -> Option<usize> {
669    roles
670        .iter()
671        .filter(|entry| entry.is_known())
672        .find(|entry| {
673            let raft_on_support = entry.role == ROLE_RAFT
674                && supports.iter().any(|support| support.support == entry.leaf);
675            let model = supports.iter().any(|support| support.model == entry.leaf)
676                || hollows.iter().any(|hollow| hollow.model == entry.leaf);
677            raft_on_support || model
678        })
679        .map(|entry| entry.leaf)
680}
681
682/// The model of a volume entry that contradicts the supports, hollows or
683/// roles, which section 14 forbids: a support leaf, a leaf with the role of
684/// supports or of a raft, or a hollowed model with a negative volume or an
685/// uncut model. Reserved kinds mean nothing, so they contradict nothing.
686fn volume_conflict(
687    volumes: &[VolumeEntry],
688    supports: &[SupportEntry],
689    hollows: &[HollowEntry],
690    roles: &[RoleEntry],
691) -> Option<usize> {
692    volumes
693        .iter()
694        .filter(|entry| entry.is_known())
695        .find(|entry| {
696            let support = supports
697                .iter()
698                .any(|support| support.support == entry.model)
699                || roles
700                    .iter()
701                    .any(|role| role.is_known() && role.leaf == entry.model);
702            let cut = matches!(entry.kind, VOLUME_NEGATIVE | VOLUME_UNCUT)
703                && hollows.iter().any(|hollow| hollow.model == entry.model);
704            support || cut
705        })
706        .map(|entry| entry.model)
707}
708
709/// A support leaf that is also the model of a hollow, which section 7.3
710/// forbids across the two chunks.
711fn hollowed_support(supports: &[SupportEntry], hollows: &[HollowEntry]) -> Option<usize> {
712    supports
713        .iter()
714        .map(|entry| entry.support)
715        .find(|&leaf| hollows.iter().any(|hollow| hollow.model == leaf))
716}
717
718/// A preview's leaf that is not the support leaf of any supports entry,
719/// which section 9 forbids.
720fn unsupported_preview(previews: &[SupportPreview], supports: &[SupportEntry]) -> Option<usize> {
721    previews
722        .iter()
723        .map(|preview| preview.leaf)
724        .find(|&leaf| !supports.iter().any(|entry| entry.support == leaf))
725}
726
727/// The chunk of a tag that comes at most once.
728fn single<T>(tag: ChunkTag, chunks: Vec<T>) -> Result<Option<T>, ReadFileError> {
729    if chunks.len() > 1 {
730        return Err(ReadFileError::ChunkCount {
731            tag,
732            count: chunks.len(),
733        });
734    }
735    Ok(chunks.into_iter().next())
736}