bread-format 0.6.0

Reads and writes .bread files: tiny, lossless meshes and scenes, with room for slicer data such as editable supports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/*
 * SPDX-FileCopyrightText: 2026 SynrgStudio
 * SPDX-License-Identifier: Apache-2.0
 */

//! Checks that an edit changed only what the editor owns (`SPEC.md`, section
//! 7.4). Nothing in a file can stop a program from changing another
//! program's data, but a program that writes through this crate can call
//! [`check_edit`] before saving, and its tests can too.
//!
//! The scene, the meshes that leaves show, the metadata, the roles and the
//! thumbnail are shared. The settings, the supports, the hollows and the
//! support previews belong to Breadslicer ([`BREADSLICER`]). Each program
//! data, surface paint and volume entry belongs to the program it names, and
//! a mesh that no leaf shows to the owner of the entry that names it. Paint
//! read from surface chunk version 1 names no program, so anyone may change
//! it. The chunks this build does not know are kept as they were read,
//! unless the edit removes or renumbers nodes or meshes.

use std::collections::HashSet;
use std::fmt;

use crate::container::Chunk;
use crate::file::BreadFile;
use crate::scene::{NodeKind, Scene};

/// The program name that owns the application chunks (`PROJ`, `SUPP`,
/// `HOLW`) and the support preview (`SPRV`).
pub const BREADSLICER: &str = "breadslicer";

/// Who made an edit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Editor<'a> {
    /// A program, by its name, such as `nudl`: it may change what is shared
    /// and what it owns.
    Program(&'a str),
    /// A program that only repairs meshes: it may change the vertices and
    /// triangles of the meshes that leaves show, and the thumbnail.
    MeshRepair,
}

/// Where each node and each mesh of the original file went in the edited
/// one: `nodes[i]` is the new index of node `i`, or `None` if the edit
/// removed it, and the same for `meshes`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Remap {
    pub nodes: Vec<Option<usize>>,
    pub meshes: Vec<Option<usize>>,
}

impl Remap {
    /// Every node and mesh of `original` keeps its index.
    pub fn identity(original: &BreadFile) -> Self {
        Self {
            nodes: (0..original.scene.nodes.len()).map(Some).collect(),
            meshes: (0..original.scene.meshes.len()).map(Some).collect(),
        }
    }

    /// Whether every node and mesh keeps its index.
    pub fn is_identity(&self) -> bool {
        let same = |list: &[Option<usize>]| list.iter().enumerate().all(|(i, &to)| to == Some(i));
        same(&self.nodes) && same(&self.meshes)
    }

    fn node(&self, node: usize) -> Option<usize> {
        self.nodes.get(node).copied().flatten()
    }

    fn mesh(&self, mesh: usize) -> Option<usize> {
        self.meshes.get(mesh).copied().flatten()
    }
}

/// A part of a file, named by its indices in the original file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Data {
    /// The project settings (`PROJ`).
    Settings,
    /// The supports entry of a model (`SUPP`).
    Supports { model: usize },
    /// The hollows entry of a model (`HOLW`).
    Hollow { model: usize },
    /// The support preview of a support leaf (`SPRV`).
    SupportPreview { leaf: usize },
    /// A surface paint entry (`SURF`).
    Surface { leaf: usize, kind: u8 },
    /// A volume entry (`VOLM`).
    Volume { model: usize, kind: u8, mesh: usize },
    /// A program data entry (`PROG`), about a node or the whole file.
    ProgramData { node: Option<usize> },
    /// A mesh of the scene.
    Mesh { mesh: usize },
    /// The scene apart from what its meshes hold: its nodes, transforms and
    /// mesh resources, and how many meshes it has.
    Scene,
    /// The roles (`ROLE`).
    Roles,
    /// The metadata (`META`).
    Metadata,
    /// A chunk this build does not know, by its tag.
    Chunk { tag: [u8; 4] },
}

/// How data changed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
    /// It is in both files, but not the same.
    Changed,
    /// It is in the original only.
    Dropped,
    /// It is in the edited file only.
    Added,
}

/// A change the editor may not make.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Violation {
    /// The editor changed data that another program owns.
    NotOwned {
        data: Data,
        owner: String,
        change: Change,
    },
    /// A mesh repair changed something other than the meshes that leaves
    /// show and the thumbnail.
    NotARepair { data: Data },
    /// The remap does not fit the files: its lists are not as long as the
    /// original's nodes and meshes, or it names an index the edited file does
    /// not have, or it sends two nodes or two meshes to the same index.
    BadRemap,
}

impl fmt::Display for Data {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Settings => f.write_str("the project settings"),
            Self::Supports { model } => write!(f, "the supports of node {model}"),
            Self::Hollow { model } => write!(f, "the hollow of node {model}"),
            Self::SupportPreview { leaf } => write!(f, "the support preview of node {leaf}"),
            Self::Surface { leaf, kind } => write!(f, "the paint of kind {kind} on node {leaf}"),
            Self::Volume { model, kind, mesh } => {
                write!(f, "the volume of kind {kind} on node {model}, mesh {mesh}")
            }
            Self::ProgramData { node: Some(node) } => {
                write!(f, "the program data about node {node}")
            }
            Self::ProgramData { node: None } => {
                f.write_str("the program data about the whole file")
            }
            Self::Mesh { mesh } => write!(f, "mesh {mesh}"),
            Self::Scene => f.write_str("the scene"),
            Self::Roles => f.write_str("the roles"),
            Self::Metadata => f.write_str("the metadata"),
            Self::Chunk { tag } => write!(f, "the chunk {}", String::from_utf8_lossy(tag)),
        }
    }
}

impl fmt::Display for Violation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotOwned {
                data,
                owner,
                change,
            } => {
                let change = match change {
                    Change::Changed => "changed",
                    Change::Dropped => "dropped",
                    Change::Added => "added",
                };
                write!(f, "{data}, which belongs to {owner}, was {change}")
            }
            Self::NotARepair { data } => {
                write!(f, "{data} changed, which a mesh repair may not change")
            }
            Self::BadRemap => f.write_str("the remap does not fit the files"),
        }
    }
}

/// Checks that `edited` changes `original` only where `editor` may, with
/// every node and mesh keeping its index. Returns every change it may not
/// make.
pub fn check_edit(
    original: &BreadFile,
    edited: &BreadFile,
    editor: Editor<'_>,
) -> Result<(), Vec<Violation>> {
    check_edit_remapped(original, edited, editor, &Remap::identity(original))
}

/// Checks that `edited` changes `original` only where `editor` may, with
/// the nodes and meshes moved or removed as `remap` says. Entries about a
/// removed node may be gone, whoever owns them; an entry that names a moved
/// node or mesh must name its new index. A mesh repair keeps every index, so
/// for [`Editor::MeshRepair`] a remap other than the identity is a
/// violation.
pub fn check_edit_remapped(
    original: &BreadFile,
    edited: &BreadFile,
    editor: Editor<'_>,
    remap: &Remap,
) -> Result<(), Vec<Violation>> {
    let violations = match editor {
        Editor::Program(program) => {
            if !remap_fits(original, edited, remap) {
                return Err(vec![Violation::BadRemap]);
            }
            check_program(original, edited, program, remap)
        }
        Editor::MeshRepair => {
            if !remap_fits(original, edited, remap) || !remap.is_identity() {
                return Err(vec![Violation::BadRemap]);
            }
            check_repair(original, edited)
        }
    };
    if violations.is_empty() {
        Ok(())
    } else {
        Err(violations)
    }
}

fn remap_fits(original: &BreadFile, edited: &BreadFile, remap: &Remap) -> bool {
    let fits = |list: &[Option<usize>], from: usize, to: usize| {
        let mut seen = HashSet::new();
        list.len() == from && list.iter().flatten().all(|&i| i < to && seen.insert(i))
    };
    fits(
        &remap.nodes,
        original.scene.nodes.len(),
        edited.scene.nodes.len(),
    ) && fits(
        &remap.meshes,
        original.scene.meshes.len(),
        edited.scene.meshes.len(),
    )
}

/// The meshes that a leaf of `scene` shows.
fn shown_meshes(scene: &Scene) -> HashSet<usize> {
    scene
        .nodes
        .iter()
        .filter_map(|node| match node.kind {
            NodeKind::Leaf { mesh } => Some(mesh),
            NodeKind::SharedLeaf { resource } => scene.mesh_resources.get(resource).copied(),
            NodeKind::Group { .. } | NodeKind::Reference { .. } => None,
        })
        .collect()
}

/// Compares the entries `before`, already remapped and without those about a
/// removed part, with `after`, as lists in any order, and reports each one
/// that changed, was dropped or was added. An entry of `before` with no equal
/// in `after` but one in the same place, as `same_place` says, changed.
fn compare<T: PartialEq>(
    before: &[(T, Data)],
    after: &[(T, Data)],
    same_place: impl Fn(&T, &T) -> bool,
    report: &mut impl FnMut(Data, Change),
) {
    let mut left: Vec<bool> = vec![true; after.len()];
    let mut unmatched = Vec::new();
    for (entry, data) in before {
        match (0..after.len()).find(|&i| left[i] && after[i].0 == *entry) {
            Some(i) => left[i] = false,
            None => unmatched.push((entry, data)),
        }
    }
    for (entry, data) in unmatched {
        match (0..after.len()).find(|&i| left[i] && same_place(&after[i].0, entry)) {
            Some(i) => {
                left[i] = false;
                report(data.clone(), Change::Changed);
            }
            None => report(data.clone(), Change::Dropped),
        }
    }
    for (i, (_, data)) in after.iter().enumerate() {
        if left[i] {
            report(data.clone(), Change::Added);
        }
    }
}

fn check_program(
    original: &BreadFile,
    edited: &BreadFile,
    program: &str,
    remap: &Remap,
) -> Vec<Violation> {
    let mut found: Vec<(Data, String, Change)> = Vec::new();

    if program != BREADSLICER {
        let mut push = |data, change| found.push((data, BREADSLICER.to_string(), change));
        if original.settings != edited.settings {
            push(Data::Settings, Change::Changed);
        }
        let supports = |file: &BreadFile, remapped: bool| {
            file.supports
                .iter()
                .filter_map(|entry| {
                    let mut entry = entry.clone();
                    let data = Data::Supports { model: entry.model };
                    if remapped {
                        entry.model = remap.node(entry.model)?;
                        entry.support = remap.node(entry.support)?;
                    }
                    Some((entry, data))
                })
                .collect::<Vec<_>>()
        };
        compare(
            &supports(original, true),
            &supports(edited, false),
            |a, b| a.model == b.model,
            &mut push,
        );
        let hollows = |file: &BreadFile, remapped: bool| {
            file.hollows
                .iter()
                .filter_map(|entry| {
                    let mut entry = entry.clone();
                    let data = Data::Hollow { model: entry.model };
                    if remapped {
                        entry.model = remap.node(entry.model)?;
                        entry.original = remap.mesh(entry.original)?;
                    }
                    Some((entry, data))
                })
                .collect::<Vec<_>>()
        };
        compare(
            &hollows(original, true),
            &hollows(edited, false),
            |a, b| a.model == b.model,
            &mut push,
        );
        let previews = |file: &BreadFile, remapped: bool| {
            file.support_previews
                .iter()
                .filter_map(|entry| {
                    let mut entry = entry.clone();
                    let data = Data::SupportPreview { leaf: entry.leaf };
                    if remapped {
                        entry.leaf = remap.node(entry.leaf)?;
                    }
                    Some((entry, data))
                })
                .collect::<Vec<_>>()
        };
        compare(
            &previews(original, true),
            &previews(edited, false),
            |a, b| a.leaf == b.leaf,
            &mut push,
        );
    }

    // Program data, paint and volumes of every other program, one owner at
    // a time.
    let mut owners: Vec<&str> = Vec::new();
    for file in [original, edited] {
        owners.extend(file.program_data.iter().map(|e| e.program.as_str()));
        owners.extend(file.surface.iter().filter_map(|e| e.program.as_deref()));
        owners.extend(file.volumes.iter().map(|e| e.program.as_str()));
    }
    owners.sort_unstable();
    owners.dedup();
    for owner in owners.into_iter().filter(|&owner| owner != program) {
        let mut push = |data, change| found.push((data, owner.to_string(), change));

        let entries = |file: &BreadFile, remapped: bool| {
            file.program_data
                .iter()
                .filter(|entry| entry.program == owner)
                .filter_map(|entry| {
                    let mut entry = entry.clone();
                    let data = Data::ProgramData { node: entry.node };
                    if remapped && let Some(node) = entry.node {
                        entry.node = Some(remap.node(node)?);
                    }
                    Some((entry, data))
                })
                .collect::<Vec<_>>()
        };
        compare(
            &entries(original, true),
            &entries(edited, false),
            |a, b| a.node == b.node,
            &mut push,
        );

        let paint = |file: &BreadFile, remapped: bool| {
            file.surface
                .iter()
                .filter(|entry| entry.program.as_deref() == Some(owner))
                .filter_map(|entry| {
                    let mut entry = entry.clone();
                    let data = Data::Surface {
                        leaf: entry.leaf,
                        kind: entry.kind,
                    };
                    if remapped {
                        entry.leaf = remap.node(entry.leaf)?;
                    }
                    Some((entry, data))
                })
                .collect::<Vec<_>>()
        };
        let mut after = paint(edited, false);
        // Paint read from chunk version 1 names no program: a program that
        // writes it back may name the program that painted it.
        let mut unowned: Vec<_> = original
            .surface
            .iter()
            .filter(|entry| entry.program.is_none())
            .filter_map(|entry| Some((remap.node(entry.leaf)?, entry)))
            .collect();
        after.retain(|(entry, _)| {
            let claimed = unowned.iter().position(|(leaf, old)| {
                *leaf == entry.leaf
                    && old.kind == entry.kind
                    && old.version == entry.version
                    && old.document == entry.document
            });
            claimed.map(|i| unowned.swap_remove(i)).is_none()
        });
        compare(
            &paint(original, true),
            &after,
            |a, b| a.leaf == b.leaf && a.kind == b.kind,
            &mut push,
        );

        let volumes = |file: &BreadFile, remapped: bool| {
            file.volumes
                .iter()
                .filter(|entry| entry.program == owner)
                .filter_map(|entry| {
                    let mut entry = entry.clone();
                    let data = Data::Volume {
                        model: entry.model,
                        kind: entry.kind,
                        mesh: entry.mesh,
                    };
                    if remapped {
                        entry.model = remap.node(entry.model)?;
                        entry.mesh = remap.mesh(entry.mesh)?;
                    }
                    Some((entry, data))
                })
                .collect::<Vec<_>>()
        };
        compare(
            &volumes(original, true),
            &volumes(edited, false),
            |a, b| a.model == b.model && a.kind == b.kind && a.mesh == b.mesh,
            &mut push,
        );
    }

    // A mesh that no leaf shows belongs to the owner of the entry that names
    // it: its contents stay, wherever it went.
    let shown = shown_meshes(&original.scene);
    let mut hidden: Vec<(usize, &str)> = Vec::new();
    if program != BREADSLICER {
        hidden.extend(original.hollows.iter().map(|e| (e.original, BREADSLICER)));
    }
    hidden.extend(
        original
            .volumes
            .iter()
            .filter(|e| e.program != program)
            .map(|e| (e.mesh, e.program.as_str())),
    );
    hidden.sort_unstable();
    hidden.dedup_by_key(|(mesh, _)| *mesh);
    for (mesh, owner) in hidden {
        if shown.contains(&mesh) {
            continue;
        }
        // A mesh dropped with the entries that named it is not reported: those
        // entries are reported if they should have stayed.
        let Some(to) = remap.mesh(mesh) else { continue };
        if original.scene.meshes.get(mesh) != edited.scene.meshes.get(to) {
            found.push((Data::Mesh { mesh }, owner.to_string(), Change::Changed));
        }
    }

    // Chunks this build does not know: kept as they were read, unless the
    // edit removed or renumbered nodes or meshes, when they may be dropped,
    // though not changed. Chunks the edited file adds are the editor's own.
    let mut left: Vec<&Chunk> = edited.other_chunks.iter().collect();
    for chunk in &original.other_chunks {
        match left.iter().position(|&c| c == chunk) {
            Some(i) => {
                left.remove(i);
            }
            None if remap.is_identity() => found.push((
                Data::Chunk { tag: chunk.tag.0 },
                "the program that wrote it".to_string(),
                Change::Dropped,
            )),
            None => {}
        }
    }

    found
        .into_iter()
        .map(|(data, owner, change)| Violation::NotOwned {
            data,
            owner,
            change,
        })
        .collect()
}

fn check_repair(original: &BreadFile, edited: &BreadFile) -> Vec<Violation> {
    let mut violations = Vec::new();
    let mut push = |data| violations.push(Violation::NotARepair { data });
    let shown = shown_meshes(&original.scene);
    let (before, after) = (&original.scene, &edited.scene);
    if before.meshes.len() != after.meshes.len() {
        push(Data::Scene);
    }
    for (i, (old, new)) in before.meshes.iter().zip(&after.meshes).enumerate() {
        let changed = if shown.contains(&i) {
            old.meta != new.meta
        } else {
            old != new
        };
        if changed {
            push(Data::Mesh { mesh: i });
        }
    }
    let rest = |scene: &Scene| Scene {
        meshes: Vec::new(),
        ..scene.clone()
    };
    if rest(before) != rest(after) {
        push(Data::Scene);
    }
    if original.settings != edited.settings {
        push(Data::Settings);
    }
    for entry in diff(&original.supports, &edited.supports) {
        push(Data::Supports { model: entry.model });
    }
    for entry in diff(&original.hollows, &edited.hollows) {
        push(Data::Hollow { model: entry.model });
    }
    for entry in diff(&original.support_previews, &edited.support_previews) {
        push(Data::SupportPreview { leaf: entry.leaf });
    }
    for entry in diff(&original.surface, &edited.surface) {
        push(Data::Surface {
            leaf: entry.leaf,
            kind: entry.kind,
        });
    }
    for entry in diff(&original.volumes, &edited.volumes) {
        push(Data::Volume {
            model: entry.model,
            kind: entry.kind,
            mesh: entry.mesh,
        });
    }
    for entry in diff(&original.program_data, &edited.program_data) {
        push(Data::ProgramData { node: entry.node });
    }
    if !same_entries(&original.roles, &edited.roles) {
        push(Data::Roles);
    }
    if !same_entries(&original.metadata, &edited.metadata) {
        push(Data::Metadata);
    }
    for chunk in diff(&original.other_chunks, &edited.other_chunks) {
        push(Data::Chunk { tag: chunk.tag.0 });
    }
    // An entry that changed is in both lists of a diff: report it once.
    let mut once = Vec::new();
    for violation in violations {
        if !once.contains(&violation) {
            once.push(violation);
        }
    }
    once
}

/// Whether `a` and `b` hold the same entries, in any order.
fn same_entries<T: PartialEq>(a: &[T], b: &[T]) -> bool {
    a.len() == b.len() && diff(a, b).is_empty()
}

/// The entries of `a` that `b` lacks, and those of `b` that `a` lacks, each
/// entry matched once.
fn diff<'a, T: PartialEq>(a: &'a [T], b: &'a [T]) -> Vec<&'a T> {
    let mut left: Vec<&T> = b.iter().collect();
    let mut out = Vec::new();
    for entry in a {
        match left.iter().position(|&e| e == entry) {
            Some(i) => {
                left.remove(i);
            }
            None => out.push(entry),
        }
    }
    out.extend(left);
    out
}