Files
WoW-Hybrid-gateway/ops/spell_sound_compat.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

214 lines
13 KiB
Python

"""Source-owned sound definitions for simple, nonlooping spell visual kits.
29-column Vanilla SoundEntries splits into native SoundKit/SoundKitEntry. Reuse
positive native variation references only after exact path/stem/weight matching;
keep WAV→OGG conversion explicit. No audio bytes, playback or installation here.
"""
from copy import deepcopy
import hashlib
import math
import re
import struct
from collections import Counter
from types import SimpleNamespace
from octo_client_data import canonical_sha256
from spell_passive_compat import BUILD, SCHEMA, SUPPLEMENTAL_TABLES, encode, integer
POLICY = 'new-source-nonlooping-spell-sound-v1'
TABLES = ('SoundKit', 'SoundKitEntry')
def sound_inventory(dbc, native_names):
"""Compare every source row/file with exact native path/stem candidates.
This is the batch input to conversion, not a new converter or proof of
byte equivalence. Distinguish encoding variants and ambiguous file IDs.
Unsupported rows stay visible instead of narrowing the inventory silently.
"""
if dbc.fields != 29 or not 0 < len(dbc.rows) <= 100000:
raise ValueError('Reviewed bounded SoundEntries inventory required')
if not isinstance(native_names, dict) or len(native_names) > 2000000:
raise ValueError('Bounded native audio path inventory required')
native={};unreviewed_names=[]
for name,ids in native_names.items():
try:checked_name=path(name)
except ValueError:
if not isinstance(name,str)or len(name)>1024:raise ValueError('Native audio name bound')from None
unreviewed_names.append(name);continue
name=checked_name
if (not isinstance(ids,list) or not ids or len(ids)>64 or
any(type(i)is not int or not 0<i<=0xffffffff for i in ids)):
raise ValueError('Native audio file identities required')
native[name]=sorted(set(ids))
records=[];blocked=[];counts=Counter()
for raw in sorted(dbc.rows,key=lambda r:r[0]):
if raw[0] == 0:
blocked.append(dict(id=0,reason='zero-ID sentinel'));continue
try:source=source_sound(dbc,raw[0],inventory=True)
except ValueError as error:
blocked.append(dict(id=raw[0],reason=str(error)));continue
files=[]
for file in source['files']:
name=file['path'];stem=name.rsplit('.',1)[0]
candidates=[dict(path=n,file_data_ids=native[n],encoding_changed=n!=name)
for n in (stem+'.wav',stem+'.ogg')if n in native]
exact=next((c for c in candidates if c['path']==name),None)
status=('exact-path-candidate'if exact and len(exact['file_data_ids'])==1 else
'encoding-variant-candidate'if not exact and len(candidates)==1 and len(candidates[0]['file_data_ids'])==1 else
'ambiguous'if candidates else 'missing-native-path')
counts[status]+=1;files.append(dict(file,status=status,candidates=candidates))
reviewed=source['sound_type']==1 and source['flags']==0 and bool(files)and not source['unused_file_weights']
records.append(dict(id=source['id'],sound_type=source['sound_type'],flags=source['flags'],
files=files,unused_file_weights=source['unused_file_weights'],
reviewed_simple_spell_family=reviewed,
raw_row_sha256=hashlib.sha256(struct.pack('<29I',*raw)).hexdigest()))
return dict(kind='source-audio-batch-inventory',source_sha256=dbc.digest(),
source_records=len(dbc.rows),parsed_records=len(records),blocked=blocked,
unreviewed_native_paths=sorted(unreviewed_names),
file_status_counts=dict(sorted(counts.items())),records=records,
source_archive_precedence_verified=False,asset_bytes_verified=False,
converted=False,installed=False,playback_verified=False)
def path(value):
if not isinstance(value, str) or not 0 < len(value) <= 256 or not re.fullmatch(r'[A-Za-z0-9_./\\-]+', value):
raise ValueError('Bounded source/native sound path required')
value = value.replace('\\', '/').lower()
if not value.startswith('sound/') or any(p in ('', '.', '..') for p in value.split('/')):
raise ValueError('Sound path outside reviewed namespace')
if value.rsplit('.', 1)[-1] not in ('wav', 'ogg'): raise ValueError('Unreviewed audio encoding')
return value
def source_sound(dbc, ident, *, inventory=False):
integer(ident, 1, 0x7fffffff, 'source sound ID')
row = dbc.by_id.get(ident)
if dbc.fields != 29 or row is None or len(row) != 29:
raise ValueError('Reviewed29-column source sound row required')
def floating(index):
value = struct.unpack('<f', struct.pack('<I', row[index]))[0]
if not math.isfinite(value): raise ValueError('Finite source sound scalar required')
return value
files = []
directory = dbc.string(row[23])
for i in range(10):
if not row[3 + i]:
if row[13 + i] and not inventory: raise ValueError('Source sound weight without file')
continue
name = dbc.string(row[3 + i])
if '/' in name or '\\' in name: raise ValueError('Source sound file must be relative to its directory')
files.append(dict(slot=i, path=path(directory + '/' + name), frequency=row[13 + i]))
result=dict(id=ident, name=dbc.string(row[2]), sound_type=row[1], files=files,
volume=floating(24), flags=row[25], min_distance=floating(26),
distance_cutoff=floating(27), eax_def=row[28], source_row=list(row),
source_strings={str(row[i]): dbc.string(row[i]) for i in (2, 23, *range(3, 13))})
if inventory:
result['unused_file_weights']=[dict(slot=i,frequency=row[13+i])for i in range(10)if not row[3+i]and row[13+i]]
return result
def new_sound_candidate(source, native_kit, native_entries, names, schemas, maxima, registry, occupied):
"""Preserve simple source playback settings under a new destination-only ID."""
ident = integer(source.get('id'), 1, 0x7fffffff, 'source sound ID')
row = source.get('source_row'); texts = source.get('source_strings')
if (not isinstance(row, list) or len(row) != 29 or row[0] != ident or
any(type(v) is not int or not 0 <= v <= 0xffffffff for v in row) or not isinstance(texts, dict)):
raise ValueError('Complete captured sound row/strings required')
try:
checked = source_sound(SimpleNamespace(fields=29, by_id={ident: row},
string=lambda offset: texts[str(offset)]), ident)
except (KeyError, TypeError): raise ValueError('Source sound strings missing or invalid') from None
if checked != source: raise ValueError('Normalized source sound differs from captured words/strings')
if (not isinstance(source.get('name'), str) or not source['name'] or
source.get('sound_type') != 1 or type(source['sound_type']) is not int or
source.get('flags') != 0 or type(source['flags']) is not int):
raise ValueError('Only reviewed flag-free spell sounds supported')
integer(source.get('eax_def'), 0, 2, 'source EAX selection')
for key in ('volume', 'min_distance', 'distance_cutoff'):
value = source.get(key)
if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
raise ValueError('Finite nonnegative source sound scalar required')
if source['volume'] > 1 or (source['distance_cutoff'] and source['min_distance'] > source['distance_cutoff']):
raise ValueError('Source sound volume/distance bounds')
for t in TABLES:
if t not in schemas or canonical_sha256(schemas[t]) != SUPPLEMENTAL_TABLES[t][2]:
raise ValueError('Reviewed native sound schema required')
integer(maxima.get(t), 1, 0x7ffffffe, 'sound allocation floor')
if not isinstance(occupied.get(t), set): raise ValueError('Explicit occupied sound IDs required')
encode(native_kit, schemas['SoundKit'])
if (native_kit['ID'] != ident or native_kit['SoundType'] != source['sound_type'] or
native_kit['EAXDef'] != source['eax_def']):
raise ValueError('Positive matching native sound type/EAX required')
files = source.get('files')
if not isinstance(files, list) or not 1 <= len(files) <= 10 or not isinstance(native_entries, list) or len(native_entries) != len(files):
raise ValueError('Complete bounded source/native sound variations required')
targets = {}; entry_ids = set()
for entry in native_entries:
encode(entry, schemas['SoundKitEntry'])
fid = entry['FileDataID']; found = names.get(fid)
if (entry['ID'] in entry_ids or entry['SoundKitID'] != ident or entry['Volume'] != 1 or
entry['PlayerConditionID'] != 0 or not isinstance(found, list) or len(found) != 1):
raise ValueError('Unconditional native sound variation references required')
entry_ids.add(entry['ID']); name = path(found[0]); stem = name.rsplit('.', 1)[0]
if stem in targets: raise ValueError('Ambiguous native sound variation names')
targets[stem] = (entry, name)
matched = []; slots = set(); stems = set()
for row in sorted(files, key=lambda r: r['slot']):
slot = integer(row.get('slot'), 0, 9, 'source sound variation slot')
weight = integer(row.get('frequency'), 1, 255, 'source sound frequency')
name = path(row.get('path')); stem = name.rsplit('.', 1)[0]
if slot in slots or stem in stems or stem not in targets:
raise ValueError('Missing/duplicate source sound variation')
slots.add(slot); stems.add(stem); entry, target_name = targets[stem]
if entry['Frequency'] != weight: raise ValueError('Native/source sound frequency differs')
matched.append((slot, name, target_name, entry))
if stems != set(targets): raise ValueError('Additional native sound variations')
if (not isinstance(registry, dict) or set(registry) != {'schema_version', 'build', *TABLES} or
registry.get('schema_version') != 1 or registry.get('build') != BUILD):
raise ValueError('Explicit sound namespace registry required')
result = deepcopy(registry)
for t in TABLES:
entries = result[t]; seen = set()
if not isinstance(entries, dict) or len(entries) > 4096: raise ValueError('Bounded sound registry required')
for key, value in entries.items():
parts = key.split(':') if isinstance(key, str) else []
if (len(parts) != (1 if t == 'SoundKit' else 2) or
any(not p.isdecimal() or str(int(p)) != p for p in parts) or
int(parts[0]) <= 0 or (len(parts) == 2 and not 0 <= int(parts[1]) <= 9)):
raise ValueError('Source sound registry key differs')
integer(value, maxima[t] + 1, 0x7fffffff, 'new sound child ID')
if value in seen or value in occupied[t]: raise ValueError('Sound allocation collision')
seen.add(value)
def allocate(t, key):
if key not in result[t]:
value = integer(max([maxima[t], *result[t].values()]) + 1, 1, 0x7fffffff, 'new sound ID')
if value in occupied[t]: raise ValueError('Sound allocation collision')
result[t][key] = value
return result[t][key]
sound_id = allocate('SoundKit', str(ident))
kit = dict(ID=sound_id, SoundType=source['sound_type'], VolumeFloat=source['volume'], Flags=0,
MinDistance=source['min_distance'], DistanceCutoff=source['distance_cutoff'], EAXDef=source['eax_def'],
SoundKitAdvancedID=0, VolumeVariationPlus=0, VolumeVariationMinus=0,
PitchVariationPlus=0, PitchVariationMinus=0, DialogType=0, PitchAdjust=0,
BusOverwriteID=0, MaxInstances=0, SoundMixGroupID=0)
rows = [('SoundKit', kit)]; mappings = []
for slot, old, new, entry in matched:
rows.append(('SoundKitEntry', dict(entry, ID=allocate('SoundKitEntry', str(ident) + ':' + str(slot)), SoundKitID=sound_id)))
mappings.append(dict(source_slot=slot, source_path=old, native_path=new,
native_file_data_id=entry['FileDataID'], source_frequency=entry['Frequency']))
records = []
for t, row in rows:
wire = encode(row, schemas[t])
records.append(dict(table_name=t, table_hash=hex(SUPPLEMENTAL_TABLES[t][0]), id=row['ID'],
record=row, wire_hex=wire.hex(), sha256=hashlib.sha256(wire).hexdigest(), source_sound_id=ident,
baseline_record_sha256=None, allocation_policy='new-source-owned-spell-sound'))
return dict(kind='source-owned-spell-sound-candidates', definition_policy=POLICY,
build=BUILD, schema=SCHEMA, source_definition=deepcopy(source), native_sound_id=sound_id,
native_template_sha256=canonical_sha256(native_kit), records=records,
file_mappings=mappings, child_id_registry=result, existing_records_modified=False,
authoritative_ids_modified=False, audio_payload_equivalence_verified=False,
installable=False, installed=False, engine_accepted=False, gameplay_verified=False,
limits=['Only flag-free nonlooping spell sounds; unsupported flags/types and ambiguous files reject.',
'WAV/OGG naming and frequency correspondence is explicit; sample-byte/audio parity is not inferred.',
'A visual kit must be separately rebound to the new native sound ID; these rows alone change no runtime behavior.'])