"""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, or an edit contains an unpaired surrogate 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, or an element short of its attribute count has a value in its content, which would decode as an attribute 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 (a non-string name, an integer out of range, a float that overflows the layout, an unknown type, more attribute records than the element's attribute count) 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 or was refused: only a run where every resource is exact exits 0. 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. Exit 1 if any resource is refused; valid resources are still written. 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 def _name_bytes(index, name): if not isinstance(name, str): raise EncodeError("value", f"descriptor {index} name must be a string, got {type(name).__name__}") try: return name.encode("utf-8") except UnicodeEncodeError: raise EncodeError("utf8", f"descriptor {index} name contains an unpaired Unicode surrogate") from None 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 isinstance(index, bool) 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)) name = node.get("name", "") if index == self.emitted: if index in self.bad_names: raise EncodeError("utf8", f"descriptor {index} name had invalid UTF-8") raw = _name_bytes(index, name) 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}") if index == len(self.names): self.names.append(name) else: self.names[index] = name 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(" 0xFFFFFFFF or ("length" in node and len(raw) != node["length"]): raise EncodeError("length", f"text of {len(raw)} bytes, recorded {node.get('length')}") self.out += b"\xfd\xff" + struct.pack(" attrs: raise EncodeError("value", f"element {node.get('name')!r} has {listed} attribute records, count {attrs}") if listed < attrs and any(c.get("kind") == "value" for c in node.get("content", [])): raise EncodeError("order", f"element {node.get('name')!r} is short of its {attrs} attributes and has a " "value in its content") self.record(node, 0x00) self.out += struct.pack("= 0 else i name = f"{file_offset:08x}.rbf" if os.path.exists(os.path.join(out_dir, name)): name = f"{file_offset:08x}-{i:04d}.rbf" target = os.path.join(out_dir, name) try: with open(target, "xb") as f: f.write(blob) except OSError as e: raise SystemExit(f"{target}: cannot write: {e.strerror or e}") from None written += 1 return written, refused def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--check", metavar="SOURCE", help="round-trip every resource of a carve directory or file") ap.add_argument("--limit", type=int, help="with --check, stop after N resources") ap.add_argument("report", nargs="?", help="an rbf0_tree.py JSON report to encode") ap.add_argument("out", nargs="?", help="a new or empty output directory") a = ap.parse_args(argv) if a.check: if a.report or a.out: ap.error("--check takes no report or output directory") if a.limit is not None and a.limit < 1: ap.error("--limit must be at least 1") if not os.path.exists(a.check): ap.error(f"{a.check}: no such file or directory") try: r = check(a.check, a.limit) except rbf0_tree.SelectionError as e: ap.error(str(e)) print(f"{r['resources']} resource(s): {r['exact']} exact, {r['different']} different, {r['refused']} refused") for reason, n in r["refused_by_reason"].items(): print(f" refused ({reason}): {n}") for layout, c in sorted(r["by_layout"].items()): print(f" {layout}: {c['exact']} of {c['resources']} exact") return 1 if r["different"] or r["refused"] else 0 if not a.report or not a.out: ap.error("give --check SOURCE, or a report and an output directory") if a.limit is not None: ap.error("--limit only applies to --check") if not os.path.isfile(a.report): ap.error(f"{a.report}: no such file") written, refused = write_all(a.report, a.out) print(f"{written} resource(s) written, {len(refused)} refused") for offset, why in refused: print(f" 0x{offset:x}: {why}" if isinstance(offset, int) else f" {offset}: {why}") return 1 if refused else 0 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())