Files

118 lines
6.8 KiB
Python

"""#75 (2026-11-26): SD skins show Octo's textures for every Turtle skin value (Grimtotem and friends).
Turtle/Octo number player skins in their own order and repaint textures under Blizzard names; Turtle also appends its
flags-1 CharSections rows as shop skins (Tauren male 21 = TaurenMaleSkin00_21GrimTotem). The HD conversion profile maps
value v to native HD choice v, whose ChrModelAltVariantChoice gives one SD choice per value (checked 1:1). That SD choice
showed Blizzard's native texture v: only 15 of 285 base/extra textures were byte-identical to Octo's.
Rule (races 1-8; Goblin/High Elf SD rows come from sd_race_customization.py): for each Octo skin row
(BaseSection 0, variation 0; flags-0 rows by ColorIndex, then flags-1 rows appended) with a profile conversion, compare
Octo's base (target 1) and extra (target 2) texture bytes with the SD choice's current texture. Byte-identical stays
native; otherwise the Octo file is imported (new FDID; path prefixed octo_ when the name is taken) with new
TextureFileData + ChrCustomizationMaterial rows, and the SD choice's element for that target points at it (a new element
when the choice has none for that target). Every import is per file, so one Octo texture shared by several values is
imported once.
Usage: octo_sd_skin_import.py <dump dir> <CharSections.octo.tsv> <profile.hpp> <listfile> <root_fdids.txt> <out dir>"""
import collections, hashlib, json, re, struct, sys
from pathlib import Path
H = Path(__file__).resolve().parent
sys.path[:0] = [str(H), '/mnt/Games/@project/wt-master-merge/ops/maps14-20261122']
import frozen_store as fs, octo_mpq
FDID0, MR0, MAT0, ELEM0 = 8840200, 2201000, 301000, 402000
md5 = lambda b: hashlib.md5(b).hexdigest()
def rows(path):
for line in open(path, encoding='utf-8', errors='replace'):
f = line.rstrip('\n').split('\t')
yield dict(x.split('=', 1) for x in f[1:] if '=' in x)
def main(dump, octo_cs, profile, listfile, root_list, out):
d = Path(dump); out = Path(out); (out / 'textures').mkdir(parents=True, exist_ok=True)
names = set()
for line in open(listfile, encoding='utf-8', errors='replace'):
names.add(line.rstrip('\n').partition(';')[2].lower())
have = set(int(x) for x in open(root_list).read().split())
assert not any(f in have for f in range(FDID0, FDID0 + 400)), 'FDID block taken'
st = fs.Store(); root = st.root; idx = {}
for g in st.layout['groups']:
if not (g['locale'] & 2) or g.get('flags1'): continue
f = 0
for i, (x,) in enumerate(struct.iter_unpack('<I', memoryview(root)[g['ids_offset']:g['ckeys_offset']])):
f += x; idx.setdefault(f, g['ckeys_offset'] + i * 16); f += 1
native = lambda f: st.read(root[idx[f]:idx[f] + 16].hex())[2] if f in idx else None
mat = {int(r['ID']): r for r in rows(d / 'ChrCustomizationMaterial.tsv')}
assert max(mat) < MAT0
tfd = {}
for r in rows(d / 'TextureFileData.tsv'): tfd.setdefault(int(r['MaterialResourcesID']), int(r['FileDataID']))
assert max(tfd) < MR0
elems = list(rows(d / 'ChrCustomizationElement.tsv')); assert max(int(r['ID']) for r in elems) < ELEM0
el = collections.defaultdict(dict)
for r in elems:
m = int(r['ChrCustomizationMaterialID'])
if m in mat and r['RelatedChrCustomizationChoiceID'] == '0':
el[int(r['ChrCustomizationChoiceID'])].setdefault(mat[m]['ChrModelTextureTargetID'], (r, tfd.get(int(mat[m]['MaterialResourcesID']))))
alt = {int(r['SourceChrCustomizationChoiceID']): int(r['VariantChrCustomizationChoiceID']) for r in rows(d / 'ChrModelAltVariantChoice.tsv')}
conv = {}
for m in re.finditer(r'\{(\d+),(\d+),(\d+),1,(\d+),(\d+),', open(profile).read()):
_, r, s, v, c = map(int, m.groups()); conv.setdefault((r, s, v), c)
cs = [r for r in rows(octo_cs) if r.get('BaseSection') == '0' and r.get('VariationIndex') == '0']
seq = collections.defaultdict(list)
for flag in ('0', '1'):
for r in sorted((r for r in cs if r['Flags'] == flag), key=lambda r: int(r['ColorIndex'])):
seq[(int(r['RaceID']), int(r['SexID']))].append(r['TextureName'].split(',')[:2])
imported, mats, tfd_rows, set_el, add_el, report = {}, [], [], [], [], []
seen_sd = {}
nf, nmr, nmat, nel = FDID0, MR0, MAT0, ELEM0
def material(path, target):
nonlocal nf, nmr, nmat
key = (path.lower(), target)
if key in imported: return imported[key]
raw = bytes(octo_mpq.read(path))
p = path.lower().replace('\\', '/'); base = p.rsplit('/', 1)
if p in names: p = f'{base[0]}/octo_{base[1]}'
same = [k for k, v in imported.items() if k[0] == path.lower()]
if same:
fid, mr = imported[same[0]][1], imported[same[0]][2]
else:
fid, mr = nf, nmr; nf += 1; nmr += 1
(out / 'textures' / f'{fid}.blp').write_bytes(raw)
tfd_rows.append(dict(ID=fid, FileDataID=fid, UsageType=0, MaterialResourcesID=mr))
names.add(p); report.append(dict(fdid=fid, path=p, octo=path))
mats.append(dict(ID=nmat, ChrModelTextureTargetID=int(target), MaterialResourcesID=mr))
imported[key] = (nmat, fid, mr); nmat += 1
return imported[key]
counts = collections.Counter()
for (race, sex), lst in sorted(seq.items()):
if race > 8: continue
for v, tex in enumerate(lst):
hd = conv.get((race, sex, v)); sd = alt.get(hd)
if not sd: counts['no-conversion'] += 1; continue
assert sd not in seen_sd, (sd, seen_sd.get(sd), (race, sex, v)); seen_sd[sd] = (race, sex, v)
for target, path in zip(('1', '2'), tex):
if not path: continue
cur = el[sd].get(target)
if cur and native(cur[1]) is not None and md5(native(cur[1])) == md5(bytes(octo_mpq.read(path))):
counts['identical'] += 1; continue
m, fid, _ = material(path, target)
if cur:
set_el.append(dict(ID=int(cur[0]['ID']), ChrCustomizationMaterialID=m))
else:
nonlocal_el = nel
add_el.append(dict(ID=nonlocal_el, ChrCustomizationChoiceID=sd, ChrCustomizationMaterialID=m)); nel += 1
counts['import' if cur else 'import-new-element'] += 1
for name, data in (('set-ChrCustomizationElement', set_el), ('add-ChrCustomizationElement', add_el),
('add-ChrCustomizationMaterial', mats), ('add-TextureFileData', tfd_rows)):
(out / f'{name}.json').write_text(json.dumps(data, indent=1))
(out / 'imported-textures.json').write_text(json.dumps({str(r['fdid']): r['path'] for r in report}, indent=1))
(out / 'report.json').write_text(json.dumps(dict(counts=counts, files=len(report), choices=len(seen_sd)), indent=1))
print(dict(counts), 'files', len(report), 'materials', len(mats), file=sys.stderr)
if __name__ == '__main__': main(*sys.argv[1:7])