bread-format 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Reads .bread files: triangle meshes, kept bit for bit, and the scene that
5
+ places them.
6
+
7
+ Written from the specification alone (SPEC.md), with the Python standard
8
+ library only, as a second reader of the format::
9
+
10
+ from bread_format import read_file
11
+
12
+ with open("model.bread", "rb") as f:
13
+ bread = read_file(f.read())
14
+ for leaf, mesh, transform in bread.placements():
15
+ ...
16
+ """
17
+
18
+ from ._bytes import Meta
19
+ from .errors import BreadError
20
+ from .file import BreadFile, read_file
21
+ from .mesh import Mesh, read_mesh
22
+ from .metadata import MetaEntry
23
+ from .scene import IDENTITY, Node, Scene, Transform, apply, compose
24
+ from .slicer import Entry, Paint, Role, fingerprint_of
25
+
26
+ __all__ = [
27
+ "IDENTITY",
28
+ "BreadError",
29
+ "BreadFile",
30
+ "Entry",
31
+ "Mesh",
32
+ "Meta",
33
+ "MetaEntry",
34
+ "Node",
35
+ "Paint",
36
+ "Role",
37
+ "Scene",
38
+ "Transform",
39
+ "apply",
40
+ "compose",
41
+ "fingerprint_of",
42
+ "read_file",
43
+ "read_mesh",
44
+ ]
bread_format/_bytes.py ADDED
@@ -0,0 +1,127 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Reading payload fields (SPEC 3.1 to 3.3) and bit streams (SPEC 6.6)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import struct
9
+ from dataclasses import dataclass
10
+
11
+ from .errors import Malformed
12
+
13
+ _U16 = struct.Struct("<H")
14
+ _U32 = struct.Struct("<I")
15
+ _U64 = struct.Struct("<Q")
16
+ _F64 = struct.Struct("<d")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Meta:
21
+ """A name and a comment, each a string or None (SPEC 5.1, 6.2)."""
22
+
23
+ name: str | None
24
+ comment: str | None
25
+
26
+
27
+ class Fields:
28
+ """Reads the fields of one payload, in order.
29
+
30
+ Every read past the end raises Malformed, and so does ``end`` when bytes
31
+ are left: a payload that is cut short or padded is malformed (SPEC 3.3).
32
+ """
33
+
34
+ def __init__(self, data: bytes | memoryview) -> None:
35
+ self._data = memoryview(data)
36
+ self._pos = 0
37
+
38
+ def left(self) -> int:
39
+ return len(self._data) - self._pos
40
+
41
+ def take(self, n: int) -> memoryview:
42
+ if n > self.left():
43
+ raise Malformed
44
+ out = self._data[self._pos : self._pos + n]
45
+ self._pos += n
46
+ return out
47
+
48
+ def u8(self) -> int:
49
+ return self.take(1)[0]
50
+
51
+ def u16(self) -> int:
52
+ return _U16.unpack(self.take(2))[0]
53
+
54
+ def u32(self) -> int:
55
+ return _U32.unpack(self.take(4))[0]
56
+
57
+ def u64(self) -> int:
58
+ return _U64.unpack(self.take(8))[0]
59
+
60
+ def f64(self) -> float:
61
+ return _F64.unpack(self.take(8))[0]
62
+
63
+ def flag(self) -> bool:
64
+ value = self.u8()
65
+ if value > 1:
66
+ raise Malformed
67
+ return value == 1
68
+
69
+ def count(self, at_least: int) -> int:
70
+ """A count of items that take at least ``at_least`` bytes each,
71
+ checked against the bytes left before anything is allocated for it."""
72
+ n = self.u32()
73
+ if n > self.left() // at_least:
74
+ raise Malformed
75
+ return n
76
+
77
+ def byte_string(self) -> memoryview:
78
+ return self.take(self.u32())
79
+
80
+ def text(self) -> str:
81
+ try:
82
+ return str(self.byte_string(), "utf-8")
83
+ except UnicodeDecodeError:
84
+ raise Malformed from None
85
+
86
+ def optional_text(self) -> str | None:
87
+ return self.text() if self.flag() else None
88
+
89
+ def meta(self) -> Meta | None:
90
+ """A *has metadata* flag, then a name and a comment when it is set."""
91
+ if not self.flag():
92
+ return None
93
+ return Meta(self.optional_text(), self.optional_text())
94
+
95
+ def end(self) -> None:
96
+ if self.left():
97
+ raise Malformed
98
+
99
+
100
+ class Bits:
101
+ """Reads a bit stream (SPEC 6.6): values packed least significant bit
102
+ first. ``end`` checks that the stream is exactly as long as the bits read
103
+ need, with the unused bits of its last byte at 0."""
104
+
105
+ def __init__(self, data: bytes | memoryview) -> None:
106
+ self._data = bytes(data)
107
+ self._pos = 0
108
+
109
+ def read(self, n: int) -> int:
110
+ value = 0
111
+ got = 0
112
+ while got < n:
113
+ index = self._pos >> 3
114
+ if index >= len(self._data):
115
+ raise Malformed
116
+ shift = self._pos & 7
117
+ width = min(8 - shift, n - got)
118
+ value |= ((self._data[index] >> shift) & ((1 << width) - 1)) << got
119
+ got += width
120
+ self._pos += width
121
+ return value
122
+
123
+ def end(self) -> None:
124
+ if len(self._data) != (self._pos + 7) >> 3:
125
+ raise Malformed
126
+ if self._pos & 7 and self._data[-1] >> (self._pos & 7):
127
+ raise Malformed
bread_format/_zstd.py ADDED
@@ -0,0 +1,80 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Zstandard decompression (SPEC 4.3): from the standard library on Python 3.14
5
+ and later (``compression.zstd``), and from the ``zstandard`` package before it.
6
+ Both decompress one frame as a stream that stops as soon as it passes a limit,
7
+ so memory grows with what a payload really holds, never with what it claims
8
+ (SPEC 4.5)."""
9
+
10
+ from __future__ import annotations
11
+
12
+ try:
13
+ from compression import zstd as _stdlib
14
+ except ImportError: # Python before 3.14
15
+ _stdlib = None
16
+
17
+ try:
18
+ import zstandard as _package
19
+ except ImportError: # not needed on Python 3.14 and later
20
+ _package = None
21
+
22
+ # How much the standard library decompresses at a time.
23
+ _STEP = 1 << 20
24
+
25
+ # How much compressed input the zstandard package is given at a time, since it
26
+ # cannot be told to stop after a number of bytes. A block holds at most 128 KiB
27
+ # and takes at least 4 bytes, so 256 bytes of input come out as 8 MiB at most:
28
+ # that bounds how far past the limit it can go.
29
+ _FEED = 256
30
+
31
+
32
+ class Failed(Exception):
33
+ """The data is not a Zstandard frame that can be decompressed."""
34
+
35
+
36
+ def inflate_stdlib(data: bytes, limit: int) -> tuple[bytes, bool]:
37
+ """``inflate`` with ``compression.zstd``."""
38
+ decompressor = _stdlib.ZstdDecompressor()
39
+ out = bytearray()
40
+ try:
41
+ while True:
42
+ want = min(limit + 1 - len(out), _STEP)
43
+ out += decompressor.decompress(data, max_length=want)
44
+ data = b""
45
+ if len(out) > limit or decompressor.eof or decompressor.needs_input:
46
+ break
47
+ except _stdlib.ZstdError:
48
+ raise Failed from None
49
+ return bytes(out), decompressor.eof and not decompressor.unused_data
50
+
51
+
52
+ def inflate_package(data: bytes, limit: int) -> tuple[bytes, bool]:
53
+ """``inflate`` with the ``zstandard`` package."""
54
+ decompressor = _package.ZstdDecompressor().decompressobj()
55
+ out = bytearray()
56
+ pos = 0
57
+ try:
58
+ while pos < len(data) and len(out) <= limit and not decompressor.eof:
59
+ out += decompressor.decompress(data[pos : pos + _FEED])
60
+ pos += _FEED
61
+ except _package.ZstdError:
62
+ raise Failed from None
63
+ whole = decompressor.eof and not decompressor.unused_data and pos >= len(data)
64
+ return bytes(out), whole
65
+
66
+
67
+ if _stdlib is not None:
68
+ _backend = inflate_stdlib
69
+ elif _package is not None:
70
+ _backend = inflate_package
71
+ else:
72
+ raise ImportError("bread-format needs Python 3.14 or later, or the zstandard package")
73
+
74
+
75
+ def inflate(data: bytes, limit: int) -> tuple[bytes, bool]:
76
+ """Decompresses the Zstandard frame that ``data`` starts with, and stops as
77
+ soon as more than ``limit`` bytes are out. Returns what came out, and
78
+ whether the frame ended, with nothing after it in ``data``. Raises
79
+ ``Failed`` when ``data`` is not a frame that decompresses."""
80
+ return _backend(data, limit)
@@ -0,0 +1,84 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The container (SPEC 4): the header, and chunks one after another."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import struct
9
+ import zlib
10
+ from dataclasses import dataclass
11
+
12
+ from ._zstd import Failed, inflate
13
+ from .errors import BreadError
14
+
15
+ MAGIC = b"BREAD\x00\r\n"
16
+ CONTAINER_VERSION = 1
17
+
18
+ _CHUNK_HEADER = struct.Struct("<4sHQQI") # tag, version, raw, stored, CRC: 26 bytes
19
+
20
+ # The first four bytes of a Zstandard frame that holds data (RFC 8878, 3.1.1).
21
+ _ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RawChunk:
26
+ """A chunk as the container holds it, before it is decompressed."""
27
+
28
+ tag: bytes
29
+ version: int
30
+ raw_length: int
31
+ stored: memoryview
32
+
33
+ @property
34
+ def name(self) -> str:
35
+ """The tag as text, for messages: four ASCII letters for any official tag."""
36
+ return self.tag.decode("latin-1")
37
+
38
+
39
+ def split_chunks(data: bytes | memoryview) -> list[RawChunk]:
40
+ """Checks the header and every chunk's CRC, and returns the chunks in file
41
+ order, still compressed (SPEC 4.1, 4.2, 4.4)."""
42
+ data = memoryview(data)
43
+ if len(data) < len(MAGIC) or data[: len(MAGIC)] != MAGIC:
44
+ raise BreadError("not-bread")
45
+ if len(data) < 10:
46
+ raise BreadError("cut-short")
47
+ (version,) = struct.unpack_from("<H", data, 8)
48
+ if version != CONTAINER_VERSION:
49
+ # Versions start at 1 (SPEC 3.4), so 0 is no version this reader knows
50
+ # either.
51
+ raise BreadError("version")
52
+ chunks = []
53
+ pos = 10
54
+ while pos < len(data):
55
+ if len(data) - pos < _CHUNK_HEADER.size:
56
+ raise BreadError("cut-short")
57
+ tag, chunk_version, raw_length, stored_length, crc = _CHUNK_HEADER.unpack_from(data, pos)
58
+ pos += _CHUNK_HEADER.size
59
+ # Checked against what is left of the file before it is read (SPEC 4.5).
60
+ if stored_length > len(data) - pos:
61
+ raise BreadError("cut-short")
62
+ stored = data[pos : pos + stored_length]
63
+ pos += stored_length
64
+ chunk = RawChunk(tag, chunk_version, raw_length, stored)
65
+ if zlib.crc32(stored) != crc:
66
+ raise BreadError("crc", chunk.name)
67
+ chunks.append(chunk)
68
+ return chunks
69
+
70
+
71
+ def decompress(chunk: RawChunk) -> bytes:
72
+ """The chunk's payload: one Zstandard frame that decompresses to exactly
73
+ the raw length (SPEC 4.3), decompressed as a stream that stops as soon as
74
+ it passes the raw length (SPEC 4.5)."""
75
+ if bytes(chunk.stored[:4]) != _ZSTD_MAGIC:
76
+ # A skippable frame is a valid frame that holds no payload.
77
+ raise BreadError("bad-payload", chunk.name)
78
+ try:
79
+ out, whole = inflate(bytes(chunk.stored), chunk.raw_length)
80
+ except Failed:
81
+ raise BreadError("bad-payload", chunk.name) from None
82
+ if len(out) != chunk.raw_length or not whole:
83
+ raise BreadError("bad-payload", chunk.name)
84
+ return out
bread_format/errors.py ADDED
@@ -0,0 +1,41 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Why a file is refused."""
5
+
6
+ from __future__ import annotations
7
+
8
+ #: What each reason code of conformance/README.md means.
9
+ MESSAGES = {
10
+ "not-bread": "not a .bread file",
11
+ "version": "written in a newer version of the format",
12
+ "cut-short": "the file is cut short",
13
+ "crc": "a chunk is damaged: its bytes do not match their checksum",
14
+ "bad-payload": "a chunk does not decompress to its recorded length",
15
+ "chunk-count": "a chunk is missing, or there are more of it than the format allows",
16
+ "malformed": "a chunk is malformed",
17
+ "no-such-vertex": "a triangle names a vertex its mesh does not have",
18
+ }
19
+
20
+
21
+ class BreadError(Exception):
22
+ """A file the reader refused.
23
+
24
+ ``reason`` is one of the reason codes of conformance/README.md, and
25
+ ``chunk`` the tag of the chunk it is about, such as ``"MESH"``, or None
26
+ when it is about the whole file.
27
+ """
28
+
29
+ def __init__(self, reason: str, chunk: str | None = None) -> None:
30
+ message = MESSAGES.get(reason, reason)
31
+ super().__init__(message if chunk is None else f"{message} ({chunk} chunk)")
32
+ self.reason = reason
33
+ self.chunk = chunk
34
+
35
+
36
+ class Malformed(Exception):
37
+ """A payload that is malformed (SPEC 3.3). The caller knows the chunk."""
38
+
39
+
40
+ class NoSuchVertex(Exception):
41
+ """A triangle that names a vertex its mesh does not have (SPEC 6.4)."""
bread_format/file.py ADDED
@@ -0,0 +1,192 @@
1
+ # SPDX-FileCopyrightText: 2026 SynrgStudio
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """A whole file: the container, then every chunk this reader knows, checked
5
+ against each other."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+ from .container import RawChunk, decompress, split_chunks
12
+ from .errors import BreadError, Malformed, NoSuchVertex
13
+ from .mesh import Mesh, read_mesh
14
+ from .metadata import MetaEntry, read_metadata
15
+ from .scene import Scene, read_scene
16
+ from .slicer import Entry, Paint, Role, read_entries, read_paint, read_previews, read_roles
17
+
18
+ #: The chunk versions this reader reads, by tag (SPEC 7.1).
19
+ VERSIONS = {
20
+ b"SCNE": (1,),
21
+ b"MESH": (1, 2),
22
+ b"THMB": (1,),
23
+ b"PROJ": (1,),
24
+ b"SUPP": (1, 2),
25
+ b"HOLW": (1, 2),
26
+ b"SPRV": (1,),
27
+ b"SURF": (1,),
28
+ b"ROLE": (1,),
29
+ b"META": (1,),
30
+ }
31
+
32
+ #: How many chunks of each tag a file holds: (at least, at most).
33
+ PER_FILE = {b"SCNE": (1, 1), b"MESH": (0, None)}
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class BreadFile:
38
+ """What a file holds.
39
+
40
+ ``settings`` is the PROJ payload, a TOML document, and ``thumbnail`` the
41
+ THMB payload, a PNG; each is None when the file has none. ``supports``
42
+ and ``hollows`` are the SUPP and HOLW entries, ``support_previews`` maps
43
+ each support leaf with a preview to its mesh, ``surface`` holds the SURF
44
+ entries, ``roles`` the ROLE entries: the leaves that are not models, and
45
+ ``metadata`` the META entries a reader keeps."""
46
+
47
+ scene: Scene
48
+ meshes: list[Mesh]
49
+ settings: bytes | None
50
+ thumbnail: bytes | None
51
+ supports: list[Entry]
52
+ hollows: list[Entry]
53
+ support_previews: dict[int, Mesh]
54
+ surface: list[Paint]
55
+ roles: list[Role]
56
+ metadata: list[MetaEntry]
57
+
58
+ def placements(self):
59
+ """Every mesh shown, with its world transform (SPEC 5.4)."""
60
+ for leaf, mesh, transform in self.scene.placements():
61
+ yield leaf, self.meshes[mesh], transform
62
+
63
+
64
+ def read_file(data: bytes) -> BreadFile:
65
+ """Reads a whole ``.bread`` file.
66
+
67
+ Raises BreadError, with its reason code, when the file is refused."""
68
+ chunks: dict[bytes, list[RawChunk]] = {}
69
+ for chunk in split_chunks(data):
70
+ versions = VERSIONS.get(chunk.tag)
71
+ if versions is None:
72
+ continue # a tag this reader does not know: skipped (SPEC 3.4)
73
+ if chunk.version > max(versions) or chunk.version < 1:
74
+ raise BreadError("version", chunk.name)
75
+ chunks.setdefault(chunk.tag, []).append(chunk)
76
+
77
+ for tag in VERSIONS:
78
+ least, most = PER_FILE.get(tag, (0, 1))
79
+ found = len(chunks.get(tag, []))
80
+ if found < least or (most is not None and found > most):
81
+ raise BreadError("chunk-count", tag.decode())
82
+
83
+ def payload(chunk: RawChunk) -> bytes:
84
+ return decompress(chunk)
85
+
86
+ def one(tag: bytes) -> RawChunk | None:
87
+ found = chunks.get(tag)
88
+ return found[0] if found else None
89
+
90
+ (scene_chunk,) = chunks[b"SCNE"]
91
+ scene = _guard("SCNE", read_scene, payload(scene_chunk))
92
+
93
+ meshes = [_guard("MESH", read_mesh, chunk.version, payload(chunk)) for chunk in chunks.get(b"MESH", [])]
94
+ if scene.mesh_count != len(meshes):
95
+ raise BreadError("malformed", "SCNE")
96
+
97
+ settings = payload(c) if (c := one(b"PROJ")) else None
98
+ thumbnail = payload(c) if (c := one(b"THMB")) else None
99
+
100
+ # SUPP and HOLW of version 1 were drafts: a reader may skip them (SPEC 7.3).
101
+ supports = _envelope("SUPP", payload(c)) if (c := one(b"SUPP")) and c.version == 2 else []
102
+ hollows = _envelope("HOLW", payload(c)) if (c := one(b"HOLW")) and c.version == 2 else []
103
+ _check_entries(scene, len(meshes), supports, hollows)
104
+
105
+ previews: dict[int, Mesh] = {}
106
+ if c := one(b"SPRV"):
107
+ support_leaves = {entry.part for entry in supports} if one(b"SUPP") else None
108
+ for preview in _guard("SPRV", read_previews, payload(c)):
109
+ mesh = _guard("SPRV", _preview_mesh, preview.mesh)
110
+ leaf = preview.leaf
111
+ if not _is_leaf(scene, leaf) or leaf in previews:
112
+ raise BreadError("malformed", "SPRV")
113
+ shown = meshes[scene.mesh_of(leaf)]
114
+ if shown.vertex_count or shown.triangle_count:
115
+ raise BreadError("malformed", "SPRV")
116
+ if support_leaves is not None and leaf not in support_leaves:
117
+ raise BreadError("malformed", "SPRV")
118
+ previews[leaf] = mesh
119
+
120
+ surface: list[Paint] = []
121
+ if c := one(b"SURF"):
122
+ surface = _guard("SURF", read_paint, payload(c))
123
+ seen = set()
124
+ for paint in surface:
125
+ if not _is_leaf(scene, paint.leaf) or (paint.leaf, paint.kind) in seen:
126
+ raise BreadError("malformed", "SURF")
127
+ seen.add((paint.leaf, paint.kind))
128
+
129
+ roles: list[Role] = []
130
+ if c := one(b"ROLE"):
131
+ roles = _guard("ROLE", read_roles, payload(c))
132
+ support_leaves = {entry.part for entry in supports}
133
+ models = {entry.model for entry in supports} | {entry.model for entry in hollows}
134
+ seen = set()
135
+ for role in roles:
136
+ if not _is_leaf(scene, role.leaf) or role.leaf in seen:
137
+ raise BreadError("malformed", "ROLE")
138
+ seen.add(role.leaf)
139
+ # A reserved role means a model, which contradicts nothing (SPEC 11.2).
140
+ if role.is_known and (role.leaf in models or (role.role == 2 and role.leaf in support_leaves)):
141
+ raise BreadError("malformed", "ROLE")
142
+
143
+ metadata = read_metadata(payload(c), len(scene.nodes)) if (c := one(b"META")) else []
144
+
145
+ return BreadFile(scene, meshes, settings, thumbnail, supports, hollows, previews, surface, roles, metadata)
146
+
147
+
148
+ def _guard(tag: str, read, *args):
149
+ """Runs a payload reader, turning what it finds into the file's refusal."""
150
+ try:
151
+ return read(*args)
152
+ except Malformed:
153
+ raise BreadError("malformed", tag) from None
154
+ except NoSuchVertex:
155
+ raise BreadError("no-such-vertex", tag) from None
156
+
157
+
158
+ def _preview_mesh(payload: bytes) -> Mesh:
159
+ # A preview's mesh is a MESH payload of version 1, refused as malformed
160
+ # whatever is wrong with it (SPEC 9.2).
161
+ try:
162
+ return read_mesh(1, payload)
163
+ except NoSuchVertex:
164
+ raise Malformed from None
165
+
166
+
167
+ def _envelope(tag: str, payload: bytes) -> list[Entry]:
168
+ return _guard(tag, read_entries, payload)
169
+
170
+
171
+ def _is_leaf(scene: Scene, node: int) -> bool:
172
+ return node < len(scene.nodes) and scene.nodes[node].is_leaf
173
+
174
+
175
+ def _check_entries(scene: Scene, mesh_count: int, supports: list[Entry], hollows: list[Entry]) -> None:
176
+ """SPEC 7.3: what SUPP and HOLW entries name."""
177
+ for tag, entries in (("SUPP", supports), ("HOLW", hollows)):
178
+ models = set()
179
+ for entry in entries:
180
+ if not _is_leaf(scene, entry.model) or entry.model in models:
181
+ raise BreadError("malformed", tag)
182
+ models.add(entry.model)
183
+ if tag == "SUPP" and not _is_leaf(scene, entry.part):
184
+ raise BreadError("malformed", tag)
185
+ if tag == "HOLW" and entry.part >= mesh_count:
186
+ raise BreadError("malformed", tag)
187
+ models = {entry.model for entry in supports} | {entry.model for entry in hollows}
188
+ support_leaves = set()
189
+ for entry in supports:
190
+ if entry.part in support_leaves or entry.part in models:
191
+ raise BreadError("malformed", "SUPP")
192
+ support_leaves.add(entry.part)