"""Encode an RBF0 tree document back to bytes, and check that decoding and encoding give the original resource. `rbf0_tree.parse_resource` turns one RBF0 resource into a tree document (docs/rbf0.md section 9). `encode(doc)` writes that tree back as an RBF0 record stream with the grammar of docs/rbf0.md section 3: the `FB FF 01 00` prologue and 8-byte values for the wide layout, no prologue and 4-byte values for the narrow one; each descriptor name at its first use, in index order; an element's three header words `0, 0, attribute count`; its attributes, then its content in tree order; text and strings with the bytes and terminating NUL the tree records. The encoder fails closed. When the tree cannot hold the original bytes it raises EncodeError with a short reason instead of writing something else: status the parse was not complete (bad, truncated, or bytes after the root closed) utf8 a descriptor name, string or text had invalid UTF-8, which the decoder replaced with U+FFFD nan a float or vec3 component was NaN, whose bits the tree renders as text (infinities are exact) order a value counted as an attribute came after the element's content started descriptor a descriptor index outside the table, or a first use out of order length a string or text no longer has its recorded byte length value a value the record cannot hold (an integer out of range, an unknown type) Usage: python -I rbf0_encode.py --check [--limit N] Decode every RBF0 resource (joining 64 KiB continuations as rbf0_tree.py does), encode it, and compare the result with the original bytes. Prints counts only: exact, different, and refused by reason. Exit 1 when a resource encodes to different bytes. python -I rbf0_encode.py Write each resource of an rbf0_tree.py JSON report (possibly edited) as .rbf. The directory must be new or empty. Everything written is game data: keep it in your work folder, out of git, issues and pull requests. """ import argparse import json import math import os import struct import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import rbf0_tree # noqa: E402 MAGIC = rbf0_tree.MAGIC PROLOGUE = rbf0_tree.PROLOGUE REASONS = ("status", "utf8", "nan", "order", "descriptor", "length", "value") class EncodeError(ValueError): """The tree cannot be written back byte for byte; `reason` is one of REASONS.""" def __init__(self, reason, message): super().__init__(f"{reason}: {message}") self.reason = reason class _Writer: def __init__(self, doc): self.wide = doc.get("layout") == "wide-64" self.out = bytearray(MAGIC + (PROLOGUE if self.wide else b"")) self.names = [d.get("name") for d in doc.get("descriptors") or []] self.bad_names = {d["index"] for d in doc.get("descriptors") or [] if d.get("utf8_valid") is False} self.emitted = 0 def record(self, node, kind): index = node.get("descriptor") if not isinstance(index, int) or not 0 <= index < 0xFD: raise EncodeError("descriptor", f"descriptor index {index!r} cannot be written") if index > self.emitted: raise EncodeError("descriptor", f"descriptor {index} is used before descriptor {self.emitted}") self.out += bytes((index, kind)) if index == self.emitted: name = node.get("name", "") if index in self.bad_names: raise EncodeError("utf8", f"descriptor {index} name had invalid UTF-8") if index < len(self.names) and self.names[index] not in (None, name): raise EncodeError("descriptor", f"descriptor {index} is named both {self.names[index]!r} and {name!r}") raw = name.encode("utf-8") if len(raw) > 0xFFFF: raise EncodeError("length", f"descriptor {index} name is {len(raw)} bytes") self.out += struct.pack(" 0xFFFF or ("byte_length" in node and len(raw) != node["byte_length"]): raise EncodeError("length", f"string of {len(raw)} bytes, recorded {node.get('byte_length')}") self.record(node, 0x60) self.out += struct.pack("