From 771e19e1d032bb734bcf29ee5d7fbbaffe3eafa6 Mon Sep 17 00:00:00 2001 From: Rachel Date: Fri, 3 Nov 2023 22:25:03 -0700 Subject: [PATCH] Add json2bin support for different processing modes for optional fields --- tools/json2bin/json2bin.py | 20 +++++++++++++++----- tools/json2bin/pokemon_wotbl_data.py | 6 +++++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/tools/json2bin/json2bin.py b/tools/json2bin/json2bin.py index c04ab8a16f..a5e6523a69 100644 --- a/tools/json2bin/json2bin.py +++ b/tools/json2bin/json2bin.py @@ -3,7 +3,7 @@ import subprocess from argparse import ArgumentParser -from enum import Enum, Flag +from enum import Enum, Flag, auto from types import FunctionType, LambdaType @@ -21,6 +21,12 @@ help='Output directory where generated files will be written') +class OptionalBehavior(Enum): + DISALLOW = 0 + SKIP = auto() + PAD = auto() + + class Parser(): __slots__ = ('registry', 'padding_index', 'field_index', 'alignment_index') @@ -52,7 +58,7 @@ def register(self, size: int | tuple[int,int], func: FunctionType | LambdaType, const_type: type[Enum] | None = None, - optional: bool = False) -> 'Parser': + optional: OptionalBehavior = OptionalBehavior.DISALLOW) -> 'Parser': ''' Register a function for processing a given key within the JSON structure, along with a size of the field in bytes and any @@ -114,10 +120,14 @@ def parse(self, data: dict) -> bytes: data_key = key[5:] # first 4 characters are a key-prefix data_val = self._walk(data, data_key.split('.')) if data_val == {} or data_val is None: - if optional: + if optional == OptionalBehavior.DISALLOW: + print(json.dumps(data, indent=4)) + raise KeyError(data_key) + elif optional == OptionalBehavior.SKIP: + continue + elif optional == OptionalBehavior.PAD: + binary.extend((0).to_bytes(size, 'little')) continue - print(json.dumps(data, indent=4)) - raise KeyError(data_key) binary.extend(parse_func(data_val, size, const_type)) return binary diff --git a/tools/json2bin/pokemon_wotbl_data.py b/tools/json2bin/pokemon_wotbl_data.py index 4d58d44ac4..9b6b84c4a4 100644 --- a/tools/json2bin/pokemon_wotbl_data.py +++ b/tools/json2bin/pokemon_wotbl_data.py @@ -11,9 +11,11 @@ species ) + def table_line(move_id: int, level: int) -> bytes: return ((move_id & 0x01FF) | ((level & 0x7F) << 9)).to_bytes(2, 'little', signed=False) + def parse_level_up_moves(table: dict, _size: int, _enum: None): out = [] for key, value in table.items(): @@ -31,7 +33,7 @@ def parse_level_up_moves(table: dict, _size: int, _enum: None): SCHEMA = j2b.Parser() \ .register_name(lambda s: s) \ - .register('learnset.level_up', 0, parse_level_up_moves, optional=True) \ + .register('learnset.level_up', 0, parse_level_up_moves, optional=j2b.OptionalBehavior.SKIP) \ .pad(2, 0xff) \ .align(4) @@ -60,6 +62,8 @@ def parse_level_up_moves(table: dict, _size: int, _enum: None): 'MOW': 507, }, } + + def indexer(file_path: pathlib.Path) -> int: name = file_path.parent.stem.upper() if name == '000': return 0