203 lines
11 KiB
Python
203 lines
11 KiB
Python
"""Generate a host-only group profile from explicit pinned JSON inputs.
|
|
No runtime qualification, definition allocation, installation or publication.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
|
|
CLASSES = {3:8, 4:1, 5:9, 6:5, 7:11, 8:4, 9:3, 10:2, 11:7}
|
|
|
|
|
|
def _integer(value, low, high, label):
|
|
if type(value) is not int or not low <= value <= high:
|
|
raise ValueError(label)
|
|
return value
|
|
|
|
|
|
def _sha(value):
|
|
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
|
|
|
|
|
def _mask(row):
|
|
words = row.get('SpellClassMask')
|
|
if type(words) is not list or len(words) != 4:
|
|
raise ValueError('four native mask words required')
|
|
return sum((_integer(w, -0x80000000, 0xffffffff, 'native mask word') & 0xffffffff) << (32*i)
|
|
for i, w in enumerate(words))
|
|
|
|
|
|
def _members(values):
|
|
if type(values) is not list or not values:
|
|
raise ValueError('nonempty group membership required')
|
|
for value in values:
|
|
_integer(value, 1, 0x7fffffff, 'spell identity')
|
|
if values != sorted(set(values)):
|
|
raise ValueError('canonical unique group membership required')
|
|
return tuple(values)
|
|
|
|
|
|
def _allocation_bits(allocation):
|
|
rows = allocation['native_inventory']
|
|
by_id = {}; identities = set()
|
|
for row in rows:
|
|
ident = _integer(row['ID'], 1, 0x7fffffff, 'native row ID')
|
|
spell = _integer(row['SpellID'], 1, 0x7fffffff, 'native spell ID')
|
|
if ident in by_id or spell in identities:
|
|
raise ValueError('duplicate native identity')
|
|
by_id[ident] = row; identities.add(spell); _mask(row)
|
|
bits = {}; families = set()
|
|
for a in allocation['allocations']:
|
|
family = _integer(a['family'], 3, 11, 'family')
|
|
if family not in CLASSES or family in families:
|
|
raise ValueError('unsupported or duplicate allocation family')
|
|
families.add(family)
|
|
final = [r for r in rows if r['SpellClassSet'] == family]
|
|
replacements = {}
|
|
for change in a['record_replacements']:
|
|
rid = change['id']
|
|
if (change['table_name'] != 'SpellClassOptions' or rid in replacements or
|
|
change['record'] != by_id.get(rid) or change['record']['SpellClassSet'] != family or
|
|
change['before']['ID'] != rid):
|
|
raise ValueError('corrupt allocation replacement')
|
|
if ({k:v for k,v in change['before'].items() if k != 'SpellClassMask'} !=
|
|
{k:v for k,v in change['record'].items() if k != 'SpellClassMask'}):
|
|
raise ValueError('allocation changes nonmask fields')
|
|
replacements[rid] = change['before']
|
|
baseline = [replacements.get(r['ID'], r) for r in final]
|
|
if _sha(baseline) != a['baseline_native_inventory_sha256']:
|
|
raise ValueError('allocation baseline hash differs')
|
|
used = 0
|
|
for row in baseline: used |= _mask(row)
|
|
unused = [bit for bit in range(128) if not used & (1 << bit)]
|
|
witness = a['baseline_unused_native_bits']
|
|
if type(witness) is not list or any(type(b) is not int for b in witness) or witness != unused:
|
|
raise ValueError('unused-bit allocation witness differs')
|
|
family_bits = set(); group_ids = set(); additions = {}
|
|
for group in a['groups']:
|
|
bit = _integer(group['native_bit'], 0, 127, 'native group bit')
|
|
members = _members(group['spell_ids'])
|
|
if bit not in unused or bit in family_bits or group_ids.intersection(members):
|
|
raise ValueError('group bit reused, not unused, or overlapping membership')
|
|
family_bits.add(bit); group_ids.update(members)
|
|
actual = sorted(r['SpellID'] for r in final if _mask(r) & (1 << bit))
|
|
if actual != list(members):
|
|
raise ValueError('allocated bit membership differs or has collateral')
|
|
bits[(family, members)] = bit
|
|
additions.update({i:1 << bit for i in members})
|
|
for before, after in zip(baseline, final):
|
|
old, new = _mask(before), _mask(after)
|
|
if old & ~new or old ^ new != additions.get(before['SpellID'], 0):
|
|
raise ValueError('allocation mask preservation differs')
|
|
return bits
|
|
|
|
|
|
MIXED_HOLD = 'mixed-flat-percent-arithmetic-not-qualified'
|
|
|
|
|
|
def generate(routes, allocation):
|
|
"""Return (header_text, receipt) without writing files or mutating inputs."""
|
|
bits = _allocation_bits(allocation)
|
|
weights = []; rows = []; held = []; no_consumer = []
|
|
# Source ApplySpellMod: base*(1+P/100)+F. Native: (base+F')*(1+P/100).
|
|
# The runtime sends F'=F/(1+P/100) for a group whose partner is active, so a
|
|
# mixed pair is released when neither side carries any other hold.
|
|
def _other_holds(route):
|
|
return [h for h in route['holds'] if h != MIXED_HOLD]
|
|
partners = {}
|
|
for route in routes['routes']:
|
|
if type(route.get('holds')) is list:
|
|
partners.setdefault((route['family'], route['group_index'], route['source_operation']), []).append(route)
|
|
def _released(route):
|
|
if MIXED_HOLD not in route['holds'] or _other_holds(route):
|
|
return False
|
|
group = partners[(route['family'], route['group_index'], route['source_operation'])]
|
|
others = [r for r in group if r['kind'] != route['kind']]
|
|
return len(others) == 1 and not _other_holds(others[0]) and others[0].get('disposition', 'translate') == 'translate'
|
|
for route in routes['routes']:
|
|
family = _integer(route['family'], 3, 11, 'route family')
|
|
key = (family, _members(route['spell_ids']))
|
|
if key not in bits:
|
|
raise ValueError('route has no exact allocation family/membership')
|
|
bit = bits[key]
|
|
if type(route['holds']) is not list:
|
|
raise ValueError('explicit route holds required')
|
|
disposition = route.get('disposition', 'translate')
|
|
if disposition not in ('translate', 'source-no-consumer'):
|
|
raise ValueError('unknown route disposition')
|
|
if disposition == 'source-no-consumer':
|
|
operation = _integer(route['source_operation'], 0, 255, 'source operation')
|
|
if operation not in (21, 26, 31, 32):
|
|
raise ValueError('operation not qualified as source-no-consumer')
|
|
proof = route.get('source_consumer_proof')
|
|
if (type(proof) is not dict or type(proof.get('path')) is not str or not proof['path'] or
|
|
type(proof.get('sha256')) is not str or len(proof['sha256']) != 64 or
|
|
any(c not in '0123456789abcdef' for c in proof['sha256'])):
|
|
raise ValueError('explicit source consumer proof path/hash required')
|
|
try:
|
|
actual_hash = hashlib.sha256(Path(proof['path']).read_bytes()).hexdigest()
|
|
except OSError as exc:
|
|
raise ValueError('source consumer proof unavailable') from exc
|
|
if actual_hash != proof['sha256']:
|
|
raise ValueError('source consumer proof hash differs')
|
|
no_consumer.append(dict(route, native_bit=bit)); continue
|
|
if route['holds'] and not _released(route):
|
|
held.append(dict(route, native_bit=bit)); continue
|
|
if route.get('incomplete_spell_ids'):
|
|
raise ValueError('unheld route contains incomplete identities')
|
|
operation = _integer(route['source_operation'], 0, 255, 'source operation')
|
|
scale = route.get('flat_scale')
|
|
if type(scale) not in (int, float) or not math.isfinite(scale) or scale not in (1, 100, 1000):
|
|
raise ValueError('qualified flat_scale must be 1, 100 or 1000')
|
|
native = route['native_operations']
|
|
if type(native) is not list or len(native) != 1:
|
|
raise ValueError('one native operation required')
|
|
native_operation = _integer(native[0], 0, 255, 'native operation')
|
|
if route['kind'] not in ('flat', 'percent'):
|
|
raise ValueError('route kind')
|
|
source_weights = route['source_weights']
|
|
if type(source_weights) is not dict or not source_weights:
|
|
raise ValueError('nonempty exact source weights required')
|
|
parsed = {}; start = len(weights)
|
|
for rawbit, value in source_weights.items():
|
|
if type(rawbit) is not str or not rawbit.isascii() or not rawbit.isdecimal():
|
|
raise ValueError('source bit key')
|
|
sourcebit = _integer(int(rawbit), 0, 63, 'source weight bit')
|
|
if sourcebit in parsed or type(value) is not str or value not in ('1', '-1'):
|
|
raise ValueError('duplicate source bit or unsupported weight')
|
|
parsed[sourcebit] = int(value)
|
|
if start > 65535 or len(parsed) > 65535 or start + len(parsed) > 65535:
|
|
raise ValueError('uint16 weight offset/count extent')
|
|
weights.extend(sorted(parsed.items()))
|
|
rows.append((CLASSES[family], operation, route['kind']=='percent', native_operation,
|
|
bit, start, len(parsed), operation==14, int(scale)))
|
|
lines=['// Generated offline from pinned qualified Q106 routes. NOT a release approval.',
|
|
'#pragma once','#include "gateway/spell_modifier_group_values.hpp"','#include <array>',
|
|
'namespace gateway::spell_modifier::group_profile {',
|
|
'struct Route { uint8_t character_class, source_operation; bool percent; uint8_t native_operation, native_bit; uint16_t first_weight, weight_count; bool power_index_zero; double flat_scale; };',
|
|
f'inline constexpr std::array<SourceWeight,{len(weights)}> Weights{{{{']
|
|
lines += [f' {{{b},{w}}},' for b,w in weights]
|
|
lines += ['}};',f'inline constexpr std::array<Route,{len(rows)}> Routes{{{{']
|
|
lines += [' {'+','.join(str(v).lower() if isinstance(v,bool) else str(v) for v in row)+'},' for row in rows]
|
|
lines += ['}};','inline constexpr bool ReleaseQualified = false;','}']
|
|
header='\n'.join(lines)+'\n'
|
|
return header,dict(routes=len(rows),weights=len(weights),held_routes=len(held),release_qualified=False,
|
|
output_sha256=hashlib.sha256(header.encode()).hexdigest(),held=held,
|
|
source_no_consumer_routes=len(no_consumer),source_no_consumer=no_consumer)
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
for key in ('routes','allocation','output','receipt'):parser.add_argument('--'+key,type=Path,required=True)
|
|
args=parser.parse_args()
|
|
paths=[p.resolve() for p in (args.routes,args.allocation,args.output,args.receipt)]
|
|
if len(set(paths)) != 4:raise ValueError('input/output paths must be distinct')
|
|
raw_routes=args.routes.read_bytes();raw_allocation=args.allocation.read_bytes()
|
|
header,receipt=generate(json.loads(raw_routes),json.loads(raw_allocation))
|
|
receipt['pins']={str(args.routes):hashlib.sha256(raw_routes).hexdigest(),str(args.allocation):hashlib.sha256(raw_allocation).hexdigest()}
|
|
args.output.write_text(header)
|
|
args.receipt.write_text(json.dumps(receipt,indent=2)+'\n')
|
|
|
|
if __name__=='__main__':main()
|