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.
- bread_format/__init__.py +44 -0
- bread_format/_bytes.py +127 -0
- bread_format/_zstd.py +80 -0
- bread_format/container.py +84 -0
- bread_format/errors.py +41 -0
- bread_format/file.py +192 -0
- bread_format/mesh.py +375 -0
- bread_format/meshopt.py +253 -0
- bread_format/metadata.py +80 -0
- bread_format/scene.py +163 -0
- bread_format/slicer.py +136 -0
- bread_format-0.1.0.dist-info/METADATA +107 -0
- bread_format-0.1.0.dist-info/RECORD +16 -0
- bread_format-0.1.0.dist-info/WHEEL +5 -0
- bread_format-0.1.0.dist-info/licenses/LICENSE +201 -0
- bread_format-0.1.0.dist-info/top_level.txt +1 -0
bread_format/mesh.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 SynrgStudio
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""The mesh chunk, MESH, versions 1 and 2 (SPEC 6)."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import struct
|
|
9
|
+
from array import array
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from ._bytes import Bits, Fields, Meta
|
|
13
|
+
from .errors import Malformed, NoSuchVertex
|
|
14
|
+
from .meshopt import decode_attributes, decode_triangles
|
|
15
|
+
|
|
16
|
+
_MASK32 = 0xFFFFFFFF
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Mesh:
|
|
21
|
+
"""A triangle mesh, kept exactly (SPEC 6.1).
|
|
22
|
+
|
|
23
|
+
``vertices`` holds x, y and z of each vertex as the bits of their ``f32``,
|
|
24
|
+
so that every coordinate comes back bit for bit, NaN payloads included;
|
|
25
|
+
``vertex_bytes`` gives them as little-endian ``f32``s, and ``positions``
|
|
26
|
+
as Python floats. ``triangles`` holds the three vertex indices of each
|
|
27
|
+
triangle, first corner first.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
meta: Meta | None
|
|
31
|
+
vertices: array # 'I': 3 per vertex, the bits of each f32
|
|
32
|
+
triangles: array # 'I': 3 per triangle
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def vertex_count(self) -> int:
|
|
36
|
+
return len(self.vertices) // 3
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def triangle_count(self) -> int:
|
|
40
|
+
return len(self.triangles) // 3
|
|
41
|
+
|
|
42
|
+
def vertex_bytes(self) -> bytes:
|
|
43
|
+
"""The vertices as little-endian ``f32``s, ready for an array of
|
|
44
|
+
``float32``."""
|
|
45
|
+
return struct.pack(f"<{len(self.vertices)}I", *self.vertices)
|
|
46
|
+
|
|
47
|
+
def triangle_bytes(self) -> bytes:
|
|
48
|
+
"""The triangles as little-endian ``u32``s."""
|
|
49
|
+
return struct.pack(f"<{len(self.triangles)}I", *self.triangles)
|
|
50
|
+
|
|
51
|
+
def positions(self) -> list[tuple[float, float, float]]:
|
|
52
|
+
"""Each vertex as three floats. A signalling NaN may come out quiet:
|
|
53
|
+
use ``vertices`` or ``vertex_bytes`` to keep every bit."""
|
|
54
|
+
floats = struct.unpack(f"<{len(self.vertices)}f", self.vertex_bytes())
|
|
55
|
+
return [floats[i : i + 3] for i in range(0, len(floats), 3)]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read_mesh(version: int, payload: bytes | memoryview) -> Mesh:
|
|
59
|
+
"""Reads and checks a mesh payload of version 1 or 2."""
|
|
60
|
+
if version == 1:
|
|
61
|
+
return _read_v1(payload)
|
|
62
|
+
if version == 2:
|
|
63
|
+
return _read_v2(payload)
|
|
64
|
+
raise ValueError(f"no mesh version {version}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# --- Version 1 ----------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _read_v1(payload) -> Mesh:
|
|
71
|
+
f = Fields(payload)
|
|
72
|
+
meta = f.meta()
|
|
73
|
+
vertex_count = f.u32()
|
|
74
|
+
vertex_buffer = f.byte_string()
|
|
75
|
+
_check_vertex_bound(vertex_count, vertex_buffer)
|
|
76
|
+
triangle_count = f.u32()
|
|
77
|
+
index_buffer = f.byte_string()
|
|
78
|
+
rotations = [(f.u32(), f.u8()) for _ in range(f.count(5))]
|
|
79
|
+
f.end()
|
|
80
|
+
|
|
81
|
+
vertices = _vertex_bits(decode_attributes(vertex_buffer, vertex_count, 12))
|
|
82
|
+
triangles = decode_triangles(index_buffer, triangle_count)
|
|
83
|
+
|
|
84
|
+
# SPEC 6.5: each gap after the first is at least 1, and every rotation
|
|
85
|
+
# names a triangle that exists.
|
|
86
|
+
triangle = -1
|
|
87
|
+
for i, (gap, corner) in enumerate(rotations):
|
|
88
|
+
if i and gap == 0:
|
|
89
|
+
raise Malformed
|
|
90
|
+
triangle = gap if i == 0 else triangle + gap
|
|
91
|
+
if triangle >= triangle_count or corner not in (1, 2):
|
|
92
|
+
raise Malformed
|
|
93
|
+
_turn(triangles, triangle, corner)
|
|
94
|
+
|
|
95
|
+
_check_vertices(triangles, vertex_count)
|
|
96
|
+
return Mesh(meta, vertices, triangles)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _check_vertex_bound(vertex_count: int, buffer) -> None:
|
|
100
|
+
# Every block of up to 256 vertices starts with a 3-byte control header
|
|
101
|
+
# (SPEC 6.3), so L bytes hold fewer than 256 L / 3 vertices.
|
|
102
|
+
if 3 * vertex_count >= 256 * len(buffer):
|
|
103
|
+
raise Malformed
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _vertex_bits(raw: bytes) -> array:
|
|
107
|
+
bits = array("I")
|
|
108
|
+
bits.frombytes(raw)
|
|
109
|
+
if bits.itemsize != 4:
|
|
110
|
+
raise RuntimeError("array('I') is not 32 bits here")
|
|
111
|
+
if struct.pack("=I", 1) != struct.pack("<I", 1):
|
|
112
|
+
bits.byteswap()
|
|
113
|
+
return bits
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _turn(triangles: array, triangle: int, corner: int) -> None:
|
|
117
|
+
"""(s0, s1, s2) with corner c becomes (sc, sc+1, sc+2), modulo 3."""
|
|
118
|
+
at = 3 * triangle
|
|
119
|
+
s = triangles[at : at + 3]
|
|
120
|
+
triangles[at : at + 3] = array("I", (s[corner % 3], s[(corner + 1) % 3], s[(corner + 2) % 3]))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _check_vertices(triangles: array, vertex_count: int) -> None:
|
|
124
|
+
if triangles and max(triangles) >= vertex_count:
|
|
125
|
+
raise NoSuchVertex
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# --- Version 2 ----------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _read_v2(payload) -> Mesh:
|
|
132
|
+
f = Fields(payload)
|
|
133
|
+
meta = f.meta()
|
|
134
|
+
vertex_count = f.u32()
|
|
135
|
+
triangle_count = f.u32()
|
|
136
|
+
connectivity = f.u8()
|
|
137
|
+
coding = f.u8()
|
|
138
|
+
if connectivity not in (0, 1) or coding not in (0, 1, 2):
|
|
139
|
+
raise Malformed
|
|
140
|
+
index_buffer = f.byte_string()
|
|
141
|
+
permutation = f.byte_string() if connectivity == 1 else None
|
|
142
|
+
corners = f.byte_string()
|
|
143
|
+
vertex_parts = [f.byte_string() for _ in range(3 if coding == 1 else 1)]
|
|
144
|
+
f.end()
|
|
145
|
+
|
|
146
|
+
# SPEC 6.7: the triangles in decoding order, turned by their corners.
|
|
147
|
+
triangles = decode_triangles(index_buffer, triangle_count)
|
|
148
|
+
_check_vertices(triangles, vertex_count)
|
|
149
|
+
bits = Bits(corners)
|
|
150
|
+
for t in range(triangle_count):
|
|
151
|
+
corner = bits.read(2)
|
|
152
|
+
if corner == 3:
|
|
153
|
+
raise Malformed
|
|
154
|
+
if corner:
|
|
155
|
+
_turn(triangles, t, corner)
|
|
156
|
+
bits.end()
|
|
157
|
+
|
|
158
|
+
# SPEC 6.9: the vertices, in decoding numbering.
|
|
159
|
+
if coding == 0:
|
|
160
|
+
_check_vertex_bound(vertex_count, vertex_parts[0])
|
|
161
|
+
vertices = _vertex_bits(decode_attributes(vertex_parts[0], vertex_count, 12))
|
|
162
|
+
else:
|
|
163
|
+
if coding == 1:
|
|
164
|
+
if vertex_count > 3 * triangle_count:
|
|
165
|
+
raise Malformed
|
|
166
|
+
residuals = _rans(vertex_count, *vertex_parts)
|
|
167
|
+
else:
|
|
168
|
+
residuals = _planes(vertex_count, vertex_parts[0])
|
|
169
|
+
vertices = _unpredict(vertex_count, triangles, residuals)
|
|
170
|
+
|
|
171
|
+
if permutation is not None:
|
|
172
|
+
triangles, vertices = _restore_order(triangles, vertices, permutation, vertex_count)
|
|
173
|
+
return Mesh(meta, vertices, triangles)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _restore_order(decoded: array, vertices: array, permutation, vertex_count: int):
|
|
177
|
+
"""Connectivity B (SPEC 6.7): each decoded triangle back to its index,
|
|
178
|
+
then the vertices numbered by first use."""
|
|
179
|
+
t = len(decoded) // 3
|
|
180
|
+
width = (max(t, 2) - 1).bit_length()
|
|
181
|
+
bits = Bits(permutation)
|
|
182
|
+
triangles = array("I", bytes(4 * len(decoded)))
|
|
183
|
+
seen = bytearray(t)
|
|
184
|
+
for j in range(t):
|
|
185
|
+
p = bits.read(width)
|
|
186
|
+
if p >= t or seen[p]:
|
|
187
|
+
raise Malformed
|
|
188
|
+
seen[p] = 1
|
|
189
|
+
triangles[3 * p : 3 * p + 3] = decoded[3 * j : 3 * j + 3]
|
|
190
|
+
bits.end()
|
|
191
|
+
|
|
192
|
+
number = {}
|
|
193
|
+
for i, v in enumerate(triangles):
|
|
194
|
+
triangles[i] = number.setdefault(v, len(number))
|
|
195
|
+
if len(number) != vertex_count:
|
|
196
|
+
raise Malformed
|
|
197
|
+
renumbered = array("I", bytes(4 * len(vertices)))
|
|
198
|
+
for old, new in number.items():
|
|
199
|
+
renumbered[3 * new : 3 * new + 3] = vertices[3 * old : 3 * old + 3]
|
|
200
|
+
return triangles, renumbered
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _planes(vertex_count: int, part) -> list[int]:
|
|
204
|
+
"""Coding 2 (SPEC 6.9): 12 planes of one byte per vertex. Plane 4c + i
|
|
205
|
+
holds byte i of the residual of component c."""
|
|
206
|
+
if len(part) != 12 * vertex_count:
|
|
207
|
+
raise Malformed
|
|
208
|
+
n = vertex_count
|
|
209
|
+
residuals = []
|
|
210
|
+
for v in range(n):
|
|
211
|
+
for c in range(3):
|
|
212
|
+
residuals.append(sum(part[(4 * c + i) * n + v] << (8 * i) for i in range(4)))
|
|
213
|
+
return residuals
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _rans(vertex_count: int, tables_part, stream_part, raw_part) -> list[int]:
|
|
217
|
+
"""Coding 1 (SPEC 6.9): the residuals, x, y then z of each vertex."""
|
|
218
|
+
tables = _rans_tables(tables_part)
|
|
219
|
+
stream = bytes(stream_part)
|
|
220
|
+
raw = Bits(raw_part)
|
|
221
|
+
if len(stream) < 4:
|
|
222
|
+
raise Malformed
|
|
223
|
+
x = int.from_bytes(stream[:4], "big")
|
|
224
|
+
pos = 4
|
|
225
|
+
residuals = []
|
|
226
|
+
previous = 0 # the largest bit length among the residuals of the vertex before
|
|
227
|
+
for _ in range(vertex_count):
|
|
228
|
+
lengths = []
|
|
229
|
+
for c in range(3):
|
|
230
|
+
if c == 0:
|
|
231
|
+
context = previous
|
|
232
|
+
elif c == 1:
|
|
233
|
+
context = lengths[0]
|
|
234
|
+
else:
|
|
235
|
+
context = (lengths[0] + lengths[1] + 1) // 2
|
|
236
|
+
table = tables[34 * c + context]
|
|
237
|
+
if table is None:
|
|
238
|
+
raise Malformed
|
|
239
|
+
lookup, frequencies, starts = table
|
|
240
|
+
slot = x & 4095
|
|
241
|
+
s = lookup[slot]
|
|
242
|
+
x = frequencies[s] * (x >> 12) + slot - starts[s]
|
|
243
|
+
while x < 1 << 23:
|
|
244
|
+
if pos >= len(stream):
|
|
245
|
+
raise Malformed
|
|
246
|
+
x = (x << 8) | stream[pos]
|
|
247
|
+
pos += 1
|
|
248
|
+
r = _residual(s, raw)
|
|
249
|
+
residuals.append(r)
|
|
250
|
+
lengths.append(r.bit_length())
|
|
251
|
+
previous = max(lengths)
|
|
252
|
+
if pos != len(stream) or x != 1 << 23:
|
|
253
|
+
raise Malformed
|
|
254
|
+
raw.end()
|
|
255
|
+
return residuals
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _residual(s: int, raw: Bits) -> int:
|
|
259
|
+
big = s >> 2 # L, the residual's bit length
|
|
260
|
+
if big <= 1:
|
|
261
|
+
if s & 3:
|
|
262
|
+
raise Malformed
|
|
263
|
+
return big
|
|
264
|
+
n = big - 1
|
|
265
|
+
h = min(n, 2)
|
|
266
|
+
m = n - h
|
|
267
|
+
if (s & 3) & ((1 << (2 - h)) - 1):
|
|
268
|
+
raise Malformed
|
|
269
|
+
return (1 << n) + (((s & 3) >> (2 - h)) << m) + raw.read(m)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _rans_tables(part) -> list:
|
|
273
|
+
bits = Bits(part)
|
|
274
|
+
tables: list = []
|
|
275
|
+
for _ in range(102):
|
|
276
|
+
if not bits.read(1):
|
|
277
|
+
tables.append(None)
|
|
278
|
+
continue
|
|
279
|
+
frequencies = [bits.read(12) + 1 if bits.read(1) else 0 for _ in range(132)]
|
|
280
|
+
if sum(frequencies) != 4096:
|
|
281
|
+
raise Malformed
|
|
282
|
+
starts = []
|
|
283
|
+
lookup = bytearray(4096)
|
|
284
|
+
total = 0
|
|
285
|
+
for s, frequency in enumerate(frequencies):
|
|
286
|
+
starts.append(total)
|
|
287
|
+
lookup[total : total + frequency] = bytes([s]) * frequency
|
|
288
|
+
total += frequency
|
|
289
|
+
tables.append((lookup, frequencies, starts))
|
|
290
|
+
bits.end()
|
|
291
|
+
return tables
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# --- Vertex prediction (SPEC 6.8) ----------------------------------------
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _unpredict(vertex_count: int, triangles: array, residuals: list[int]) -> array:
|
|
298
|
+
t = len(triangles) // 3
|
|
299
|
+
tris = [tuple(triangles[3 * j : 3 * j + 3]) for j in range(t)]
|
|
300
|
+
# The triangles that have each vertex as a corner, and the triangles on
|
|
301
|
+
# each edge, in increasing order.
|
|
302
|
+
around: list[list[int]] = [[] for _ in range(vertex_count)]
|
|
303
|
+
edges: dict[tuple[int, int], list[int]] = {}
|
|
304
|
+
for j, tri in enumerate(tris):
|
|
305
|
+
for v in dict.fromkeys(tri):
|
|
306
|
+
around[v].append(j)
|
|
307
|
+
for k in range(3):
|
|
308
|
+
a, b = tri[k], tri[(k + 1) % 3]
|
|
309
|
+
on_edge = edges.setdefault((min(a, b), max(a, b)), [])
|
|
310
|
+
if not on_edge or on_edge[-1] != j:
|
|
311
|
+
on_edge.append(j)
|
|
312
|
+
|
|
313
|
+
bits = array("I", bytes(12 * vertex_count))
|
|
314
|
+
coords: list[tuple[float, float, float]] = []
|
|
315
|
+
for v in range(vertex_count):
|
|
316
|
+
prediction = _predict(v, tris, around[v], edges, coords, bits)
|
|
317
|
+
for c in range(3):
|
|
318
|
+
r = residuals[3 * v + c]
|
|
319
|
+
d = (r >> 1) ^ (_MASK32 if r & 1 else 0) # zigzag undone, as a u32
|
|
320
|
+
bits[3 * v + c] = _from_ord((_ord(prediction[c]) + d) & _MASK32)
|
|
321
|
+
coords.append(struct.unpack("<3f", struct.pack("<3I", *bits[3 * v : 3 * v + 3])))
|
|
322
|
+
return bits
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _predict(v, tris, around, edges, coords, bits) -> tuple[int, int, int]:
|
|
326
|
+
"""The prediction of vertex v, as the bits of three f32."""
|
|
327
|
+
sums = {"para": [0.0, 0.0, 0.0], "mid": [0.0, 0.0, 0.0], "near": [0.0, 0.0, 0.0]}
|
|
328
|
+
counts = {"para": 0, "mid": 0, "near": 0}
|
|
329
|
+
|
|
330
|
+
def add(name, value):
|
|
331
|
+
s = sums[name]
|
|
332
|
+
s[0], s[1], s[2] = s[0] + value[0], s[1] + value[1], s[2] + value[2]
|
|
333
|
+
counts[name] += 1
|
|
334
|
+
|
|
335
|
+
for j in around:
|
|
336
|
+
tri = tris[j]
|
|
337
|
+
k = tri.index(v)
|
|
338
|
+
a, b = tri[(k + 1) % 3], tri[(k + 2) % 3]
|
|
339
|
+
if a < v:
|
|
340
|
+
add("near", coords[a])
|
|
341
|
+
if b < v:
|
|
342
|
+
add("near", coords[b])
|
|
343
|
+
if a < v and b < v:
|
|
344
|
+
A, B = coords[a], coords[b]
|
|
345
|
+
add("mid", (0.5 * (A[0] + B[0]), 0.5 * (A[1] + B[1]), 0.5 * (A[2] + B[2])))
|
|
346
|
+
other = next((o for o in edges[(min(a, b), max(a, b))] if o != j), None)
|
|
347
|
+
if other is not None:
|
|
348
|
+
c = next((x for x in tris[other] if x != a and x != b), None)
|
|
349
|
+
if c is not None and c < v:
|
|
350
|
+
C = coords[c]
|
|
351
|
+
add("para", ((A[0] + B[0]) - C[0], (A[1] + B[1]) - C[1], (A[2] + B[2]) - C[2]))
|
|
352
|
+
|
|
353
|
+
for name in ("para", "mid", "near"):
|
|
354
|
+
if counts[name]:
|
|
355
|
+
return tuple(_to_f32_bits(s / counts[name]) for s in sums[name])
|
|
356
|
+
if v == 0:
|
|
357
|
+
return (0, 0, 0)
|
|
358
|
+
return tuple(b if b & 0x7F800000 != 0x7F800000 else 0 for b in bits[3 * v - 3 : 3 * v])
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _to_f32_bits(value: float) -> int:
|
|
362
|
+
"""Rounded to f32, to nearest, ties to even; not finite becomes +0.0."""
|
|
363
|
+
try:
|
|
364
|
+
(out,) = struct.unpack("<I", struct.pack("<f", value))
|
|
365
|
+
except OverflowError: # past the largest f32: rounds to infinity
|
|
366
|
+
return 0
|
|
367
|
+
return 0 if out & 0x7F800000 == 0x7F800000 else out
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _ord(u: int) -> int:
|
|
371
|
+
return (~u & _MASK32) if u >> 31 else u | 0x80000000
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _from_ord(o: int) -> int:
|
|
375
|
+
return o & 0x7FFFFFFF if o >> 31 else ~o & _MASK32
|
bread_format/meshopt.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 SynrgStudio
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""The two meshoptimizer codecs a MESH chunk uses (SPEC 6.3, 6.4), written
|
|
5
|
+
from their bitstream specification in Appendix A of the glTF extension
|
|
6
|
+
KHR_meshopt_compression: "Mode 0: attributes", version 1, and "Mode 1:
|
|
7
|
+
triangles"."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from array import array
|
|
12
|
+
|
|
13
|
+
from .errors import Malformed
|
|
14
|
+
|
|
15
|
+
_MASK32 = 0xFFFFFFFF
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _Cursor:
|
|
19
|
+
"""Reads bytes up to ``end``; reading past it is malformed."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, data: bytes, pos: int, end: int) -> None:
|
|
22
|
+
self.data = data
|
|
23
|
+
self.pos = pos
|
|
24
|
+
self.end = end
|
|
25
|
+
|
|
26
|
+
def take(self, n: int) -> bytes:
|
|
27
|
+
if n > self.end - self.pos:
|
|
28
|
+
raise Malformed
|
|
29
|
+
out = self.data[self.pos : self.pos + n]
|
|
30
|
+
self.pos += n
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
def byte(self) -> int:
|
|
34
|
+
if self.pos >= self.end:
|
|
35
|
+
raise Malformed
|
|
36
|
+
self.pos += 1
|
|
37
|
+
return self.data[self.pos - 1]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# --- Mode 0: attributes --------------------------------------------------
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def decode_attributes(data: bytes, count: int, stride: int) -> bytes:
|
|
44
|
+
"""``count`` elements of ``stride`` bytes, from a buffer of version 1 of
|
|
45
|
+
the attribute codec."""
|
|
46
|
+
data = bytes(data)
|
|
47
|
+
if not data or data[0] != 0xA1:
|
|
48
|
+
raise Malformed
|
|
49
|
+
channels = stride // 4
|
|
50
|
+
# The tail: zero padding, then the baseline element and the channel modes,
|
|
51
|
+
# together at least 24 bytes.
|
|
52
|
+
tail_size = max(stride + channels, 24)
|
|
53
|
+
if len(data) < 1 + tail_size:
|
|
54
|
+
raise Malformed
|
|
55
|
+
end = len(data) - tail_size
|
|
56
|
+
baseline = data[len(data) - stride - channels : len(data) - channels]
|
|
57
|
+
modes = data[len(data) - channels :]
|
|
58
|
+
for mode in modes:
|
|
59
|
+
if mode & 0x0F > 2 or (mode & 0x0F < 2 and mode >> 4):
|
|
60
|
+
raise Malformed
|
|
61
|
+
|
|
62
|
+
cursor = _Cursor(data, 1, end)
|
|
63
|
+
out = bytearray(count * stride)
|
|
64
|
+
previous = bytearray(baseline)
|
|
65
|
+
block_size = min((8192 // stride) & ~15, 256)
|
|
66
|
+
done = 0
|
|
67
|
+
while done < count:
|
|
68
|
+
elements = min(count - done, block_size)
|
|
69
|
+
groups = (elements + 15) // 16
|
|
70
|
+
control = cursor.take(channels)
|
|
71
|
+
# deltas[k][i]: byte k of the delta of element i of the block.
|
|
72
|
+
deltas = [
|
|
73
|
+
_data_block(cursor, (control[k >> 2] >> ((k & 3) * 2)) & 3, groups, elements) for k in range(stride)
|
|
74
|
+
]
|
|
75
|
+
for i in range(elements):
|
|
76
|
+
for c in range(channels):
|
|
77
|
+
_undelta(previous, 4 * c, [deltas[4 * c + j][i] for j in range(4)], modes[c])
|
|
78
|
+
out[(done + i) * stride : (done + i + 1) * stride] = previous
|
|
79
|
+
done += elements
|
|
80
|
+
if cursor.pos != end:
|
|
81
|
+
raise Malformed
|
|
82
|
+
return bytes(out)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# Bits per delta for each delta encoding mode, by control mode; 8 means the
|
|
86
|
+
# 16 deltas are stored as bytes.
|
|
87
|
+
_WIDTHS = {0: (0, 1, 2, 4), 1: (1, 2, 4, 8)}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _data_block(cursor: _Cursor, control: int, groups: int, elements: int) -> bytes:
|
|
91
|
+
"""One byte position's deltas, for every element of the block."""
|
|
92
|
+
if control == 2:
|
|
93
|
+
return bytes(16 * groups)
|
|
94
|
+
if control == 3:
|
|
95
|
+
# Literal: one delta byte per element, not rounded up to the group.
|
|
96
|
+
return cursor.take(elements)
|
|
97
|
+
header = cursor.take((groups + 3) // 4)
|
|
98
|
+
out = bytearray()
|
|
99
|
+
for g in range(groups):
|
|
100
|
+
width = _WIDTHS[control][(header[g >> 2] >> ((g & 3) * 2)) & 3]
|
|
101
|
+
if width == 0:
|
|
102
|
+
out += bytes(16)
|
|
103
|
+
elif width == 8:
|
|
104
|
+
out += cursor.take(16)
|
|
105
|
+
else:
|
|
106
|
+
out += bytes(_sentinel_group(cursor, width))
|
|
107
|
+
return bytes(out)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _sentinel_group(cursor: _Cursor, width: int) -> list[int]:
|
|
111
|
+
packed = cursor.take(2 * width)
|
|
112
|
+
per_byte = 8 // width
|
|
113
|
+
mask = (1 << width) - 1
|
|
114
|
+
values = []
|
|
115
|
+
for i in range(16):
|
|
116
|
+
byte = packed[i // per_byte]
|
|
117
|
+
slot = i % per_byte
|
|
118
|
+
# 1-bit deltas go from the least significant bit up; 2- and 4-bit
|
|
119
|
+
# deltas from the most significant bit down.
|
|
120
|
+
shift = slot if width == 1 else 8 - width * (slot + 1)
|
|
121
|
+
values.append((byte >> shift) & mask)
|
|
122
|
+
# A delta with every bit set is stored as a whole byte after the group.
|
|
123
|
+
return [cursor.byte() if v == mask else v for v in values]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _undelta(previous: bytearray, at: int, delta: list[int], mode: int) -> None:
|
|
127
|
+
"""Applies one channel's 4 delta bytes to the previous element, in place."""
|
|
128
|
+
kind = mode & 0x0F
|
|
129
|
+
if kind == 0: # byte deltas, zigzag-encoded
|
|
130
|
+
for j in range(4):
|
|
131
|
+
previous[at + j] = (previous[at + j] + _unzigzag(delta[j], 8)) & 0xFF
|
|
132
|
+
elif kind == 1: # 2-byte deltas, zigzag-encoded
|
|
133
|
+
for j in (0, 2):
|
|
134
|
+
old = previous[at + j] | previous[at + j + 1] << 8
|
|
135
|
+
new = (old + _unzigzag(delta[j] | delta[j + 1] << 8, 16)) & 0xFFFF
|
|
136
|
+
previous[at + j], previous[at + j + 1] = new & 0xFF, new >> 8
|
|
137
|
+
else: # 4-byte XOR deltas, rotated
|
|
138
|
+
rotation = mode >> 4
|
|
139
|
+
value = int.from_bytes(bytes(delta), "little")
|
|
140
|
+
xor = ((value >> rotation) | (value << ((32 - rotation) & 31))) & _MASK32
|
|
141
|
+
old = int.from_bytes(previous[at : at + 4], "little")
|
|
142
|
+
previous[at : at + 4] = (old ^ xor).to_bytes(4, "little")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _unzigzag(value: int, bits: int) -> int:
|
|
146
|
+
mask = (1 << bits) - 1
|
|
147
|
+
return (~(value >> 1) & mask) if value & 1 else value >> 1
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# --- Mode 1: triangles ---------------------------------------------------
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class _Fifo:
|
|
154
|
+
"""A 16-entry FIFO; reading an entry never written is malformed."""
|
|
155
|
+
|
|
156
|
+
def __init__(self) -> None:
|
|
157
|
+
self.entries: list = [None] * 16
|
|
158
|
+
self.written = 0
|
|
159
|
+
|
|
160
|
+
def push(self, value) -> None:
|
|
161
|
+
self.entries[self.written & 15] = value
|
|
162
|
+
self.written += 1
|
|
163
|
+
|
|
164
|
+
def get(self, index: int):
|
|
165
|
+
# 0 is the most recently added entry.
|
|
166
|
+
if index >= min(self.written, 16):
|
|
167
|
+
raise Malformed
|
|
168
|
+
return self.entries[(self.written - 1 - index) & 15]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def decode_triangles(data: bytes, triangle_count: int) -> array:
|
|
172
|
+
"""The ``3 * triangle_count`` indices of a buffer of the triangle codec,
|
|
173
|
+
version 1, as ``u32`` values."""
|
|
174
|
+
data = bytes(data)
|
|
175
|
+
if not data or data[0] != 0xE1:
|
|
176
|
+
raise Malformed
|
|
177
|
+
if triangle_count > len(data) - 17:
|
|
178
|
+
raise Malformed
|
|
179
|
+
codes = data[1 : 1 + triangle_count]
|
|
180
|
+
aux = data[len(data) - 16 :]
|
|
181
|
+
if aux[14] or aux[15] or any(b >> 4 == 0xF or b & 0x0F == 0xF for b in aux):
|
|
182
|
+
raise Malformed
|
|
183
|
+
extra = _Cursor(data, 1 + triangle_count, len(data) - 16)
|
|
184
|
+
|
|
185
|
+
edges = _Fifo()
|
|
186
|
+
vertices = _Fifo()
|
|
187
|
+
state = {"next": 0, "last": 0}
|
|
188
|
+
out = array("I")
|
|
189
|
+
|
|
190
|
+
def new() -> int:
|
|
191
|
+
value = state["next"]
|
|
192
|
+
state["next"] = (value + 1) & _MASK32
|
|
193
|
+
return value
|
|
194
|
+
|
|
195
|
+
def index() -> int:
|
|
196
|
+
# varint-7: 1 to 5 bytes, the high bit set on every byte but the last.
|
|
197
|
+
value = 0
|
|
198
|
+
for i in range(5):
|
|
199
|
+
byte = extra.byte()
|
|
200
|
+
value |= (byte & 0x7F) << (7 * i)
|
|
201
|
+
if not byte & 0x80:
|
|
202
|
+
break
|
|
203
|
+
else:
|
|
204
|
+
raise Malformed
|
|
205
|
+
value &= _MASK32
|
|
206
|
+
delta = (~(value >> 1) & _MASK32) if value & 1 else value >> 1
|
|
207
|
+
state["last"] = (state["last"] + delta) & _MASK32
|
|
208
|
+
return state["last"]
|
|
209
|
+
|
|
210
|
+
for code in codes:
|
|
211
|
+
high, low = code >> 4, code & 0x0F
|
|
212
|
+
if high < 0xF:
|
|
213
|
+
a, b = edges.get(high)
|
|
214
|
+
if low == 0:
|
|
215
|
+
c = new()
|
|
216
|
+
vertices.push(c)
|
|
217
|
+
elif low < 0xD:
|
|
218
|
+
c = vertices.get(low)
|
|
219
|
+
elif low < 0xF:
|
|
220
|
+
c = (state["last"] + (1 if low == 0xE else -1)) & _MASK32
|
|
221
|
+
state["last"] = c
|
|
222
|
+
vertices.push(c)
|
|
223
|
+
else:
|
|
224
|
+
c = index()
|
|
225
|
+
vertices.push(c)
|
|
226
|
+
edges.push((c, b))
|
|
227
|
+
edges.push((a, c))
|
|
228
|
+
else:
|
|
229
|
+
if low < 0xE:
|
|
230
|
+
z, w = aux[low] >> 4, aux[low] & 0x0F
|
|
231
|
+
a = new()
|
|
232
|
+
b = new() if z == 0 else vertices.get(z - 1)
|
|
233
|
+
c = new() if w == 0 else vertices.get(w - 1)
|
|
234
|
+
else:
|
|
235
|
+
zw = extra.byte()
|
|
236
|
+
if zw == 0:
|
|
237
|
+
state["next"] = 0
|
|
238
|
+
z, w = zw >> 4, zw & 0x0F
|
|
239
|
+
a = new() if low == 0xE else index()
|
|
240
|
+
b = new() if z == 0 else vertices.get(z - 1) if z < 0xF else index()
|
|
241
|
+
c = new() if w == 0 else vertices.get(w - 1) if w < 0xF else index()
|
|
242
|
+
edges.push((b, a))
|
|
243
|
+
edges.push((c, b))
|
|
244
|
+
edges.push((a, c))
|
|
245
|
+
vertices.push(a)
|
|
246
|
+
if z == 0 or z == 0xF:
|
|
247
|
+
vertices.push(b)
|
|
248
|
+
if w == 0 or w == 0xF:
|
|
249
|
+
vertices.push(c)
|
|
250
|
+
out.extend((a, b, c))
|
|
251
|
+
if extra.pos != extra.end:
|
|
252
|
+
raise Malformed
|
|
253
|
+
return out
|
bread_format/metadata.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 SynrgStudio
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""The META chunk: who made a file, how it may be used, and lasting ids for
|
|
5
|
+
its parts (SPEC 12). It never makes a file unreadable."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from ._bytes import Fields
|
|
13
|
+
from .errors import Malformed
|
|
14
|
+
|
|
15
|
+
#: The registered keys whose value is UTF-8 text (SPEC 12.1).
|
|
16
|
+
TEXT_KEYS = ("title", "description", "designer", "copyright", "license", "source", "created", "generator")
|
|
17
|
+
|
|
18
|
+
#: The subject that stands for the whole file in a payload.
|
|
19
|
+
FILE = 0xFFFFFFFF
|
|
20
|
+
|
|
21
|
+
_KEY = re.compile(rb"[a-z][a-z0-9._-]{0,63}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class MetaEntry:
|
|
26
|
+
"""A META entry. ``node`` is the node index it is about, or None for the
|
|
27
|
+
whole file."""
|
|
28
|
+
|
|
29
|
+
node: int | None
|
|
30
|
+
key: str
|
|
31
|
+
value: bytes
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def text(self) -> str | None:
|
|
35
|
+
"""The value of a registered text key."""
|
|
36
|
+
return self.value.decode("utf-8") if self.key in TEXT_KEYS else None
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def uuid(self) -> bytes | None:
|
|
40
|
+
"""The 16 bytes of a ``uuid``."""
|
|
41
|
+
return self.value if self.key == "uuid" else None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _fits(key: bytes, value: bytes) -> bool:
|
|
45
|
+
if not _KEY.fullmatch(key):
|
|
46
|
+
return False
|
|
47
|
+
if b"." in key:
|
|
48
|
+
return True # a program's own key: any value
|
|
49
|
+
if key == b"uuid":
|
|
50
|
+
return len(value) == 16
|
|
51
|
+
if key.decode() in TEXT_KEYS:
|
|
52
|
+
try:
|
|
53
|
+
value.decode("utf-8")
|
|
54
|
+
except UnicodeDecodeError:
|
|
55
|
+
return False
|
|
56
|
+
return True
|
|
57
|
+
return False # reserved
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read_metadata(payload: bytes, node_count: int) -> list[MetaEntry]:
|
|
61
|
+
"""The entries of a META payload of version 1 that a reader keeps: none
|
|
62
|
+
when the payload is malformed, and none that break a rule (SPEC 12.2)."""
|
|
63
|
+
try:
|
|
64
|
+
f = Fields(payload)
|
|
65
|
+
raw = [(f.u32(), bytes(f.byte_string()), bytes(f.byte_string())) for _ in range(f.count(12))]
|
|
66
|
+
f.end()
|
|
67
|
+
except Malformed:
|
|
68
|
+
return []
|
|
69
|
+
seen = set()
|
|
70
|
+
entries = []
|
|
71
|
+
for subject, key, value in raw:
|
|
72
|
+
if (subject, key) in seen:
|
|
73
|
+
continue # the second of two, whatever the first holds
|
|
74
|
+
seen.add((subject, key))
|
|
75
|
+
if subject != FILE and subject >= node_count:
|
|
76
|
+
continue
|
|
77
|
+
if not _fits(key, value):
|
|
78
|
+
continue
|
|
79
|
+
entries.append(MetaEntry(None if subject == FILE else subject, key.decode(), value))
|
|
80
|
+
return entries
|