Files

164 lines
8.4 KiB
Python

"""#122 (2026-11-26): appearance catalogue, Octo 1.12 CharSections vs native Forever choices (skins + faces).
For every race/sex and every Turtle player-bytes value, report what Octo draws and what the current conversion
profile makes the Forever client draw:
skin v -> Octo skin row (Turtle order: flags-0 by colour, then flags-1 appended) and texture
-> profile conversion (field 1) -> HD choice C -> SD alt S -> native SD skin texture (element S, target 1)
face f on skin v -> Octo section-1 row (same flags/colour) -> conversion (field 2, skin-dependent) -> HD F -> SD alt
-> native SD face-lower texture (element (F_sd, S), target 4)
SD textures are compared by look (downscaled RGB mean abs difference, 0..255); HD is recorded only.
Pass a matched native table and texture export to audit a specific build.
Usage: catalogue.py <profile.hpp> <CharSections.octo.tsv> <out.json>"""
import argparse
import collections
import io
import json
import re
import struct
import sys
from pathlib import Path
H = Path(__file__).resolve().parent
sys.path.insert(0, str(H.parent / 'maps14-20261122'))
FIELDS = {1: 'skin', 2: 'face', 3: 'hair_style', 4: 'hair_color', 5: 'facial'}
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 look(raw, size=32):
from PIL import Image
if raw is None: return None
try: im = Image.open(io.BytesIO(raw)).convert('RGB')
except Exception: return None
return im.resize((size, size), Image.BILINEAR).tobytes()
def diff(a, b):
if a is None or b is None: return None
return round(sum(abs(x - y) for x, y in zip(a, b)) / len(a), 1)
def source_conversions(profile_text, choice_names):
"""Return unconditional choices and choices conditional on a particular skin."""
section = re.search(r'\bConversions\s*\{\{(.*?)\}\}\s*;', profile_text, re.S)
if not section:
raise ValueError('Missing Conversions in appearance profile')
direct = {}
by_skin = {}
names = {1: 'Skin Color', 2: 'Face'}
for record in re.findall(r'\{([^{}]*)\}', section[1]):
_, race, sex, field, value, choice, dependency, dep_value, _ = map(int, record.split(','))
if sex < 0 or field not in names or choice_names.get(choice) != names[field]:
continue
key = (race, sex, field, value)
if dependency == 0:
direct.setdefault(key, choice)
elif dependency == 1:
by_skin.setdefault((*key, dep_value), choice)
return direct, by_skin
def historical_texture_reader():
sys.path.insert(0, '/mnt/Games/@project/gateway/runtime/continuation-20261113/claude-lane/content/sdskins-d20a-20261126')
import frozen_store as fs
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
def read_texture(fd):
return st.read(root[idx[fd]:idx[fd] + 16].hex())[2] if fd in idx else None
return read_texture
def main(profile, octo_cs, out, native_dir=None, read_texture=None):
import octo_mpq
N = Path(native_dir) if native_dir else H / 'native'
if read_texture is None:
read_texture = historical_texture_reader()
cache = {}
def native(fd):
if fd not in cache: cache[fd] = look(read_texture(fd))
return cache[fd]
def octo(path):
k = 'o:' + path.lower()
if k not in cache:
raw = octo_mpq.read(path) if path else None
cache[k] = look(bytes(raw)) if raw is not None else None
return cache[k]
mat = {r['ID']: r for r in rows(N / 'ChrCustomizationMaterial.tsv')}
tfd = {}
for r in rows(N / 'TextureFileData.tsv'): tfd.setdefault(r['MaterialResourcesID'], int(r['FileDataID']))
el = collections.defaultdict(dict)
for r in rows(N / 'ChrCustomizationElement.tsv'):
m = mat.get(r['ChrCustomizationMaterialID'])
if m: el[(int(r['ChrCustomizationChoiceID']), int(r['RelatedChrCustomizationChoiceID']))].setdefault(
int(m['ChrModelTextureTargetID']), tfd.get(m['MaterialResourcesID']))
alt = {int(r['SourceChrCustomizationChoiceID']): int(r['VariantChrCustomizationChoiceID']) for r in rows(N / 'ChrModelAltVariantChoice.tsv')}
# A Turtle value converts to several choices (Human face -> Face option + skin-dependent Eye Color option): keep only
# choices on the option that field shows (field 1 Skin Color, field 2 Face), else the eye-colour row counts as the face.
opt_name = {int(r['ID']): r['Name_lang'] for r in rows(N / 'ChrCustomizationOption.tsv')}
ch_opt = {int(r['ID']): int(r['ChrCustomizationOptionID']) for r in rows(N / 'ChrCustomizationChoice.tsv')}
choice_names = {choice: opt_name.get(option) for choice, option in ch_opt.items()}
conv, dep = source_conversions(Path(profile).read_text(), choice_names)
cs = list(rows(octo_cs))
skins = collections.defaultdict(list)
for flag in ('0', '1'):
for r in sorted((r for r in cs if r['BaseSection'] == '0' and r['VariationIndex'] == '0' and r['Flags'] == flag), key=lambda r: int(r['ColorIndex'])):
skins[(int(r['RaceID']), int(r['SexID']))].append(r)
sec1 = {}
for r in cs:
if r['BaseSection'] == '1':
sec1[(int(r['RaceID']), int(r['SexID']), int(r['VariationIndex']), r['Flags'], r['ColorIndex'])] = r['TextureName'].split(',')[0]
report = []
for (race, sex), lst in sorted(skins.items()):
if race > 10: continue
octo_faces = sorted({k[2] for k in sec1 if k[:2] == (race, sex)})
for v, r in enumerate(lst):
tex = r['TextureName'].split(',')[0]
C = conv.get((race, sex, 1, v)); S = alt.get(C) if C else None
ntex = el.get((S, 0), {}).get(1) if S else None
d = diff(octo(tex), native(ntex)) if ntex else None
# best native SD skin for this race/sex by look (other SD skin choices of the same option)
entry = dict(race=race, sex=sex, value=v, flags=int(r['Flags']), color=int(r['ColorIndex']), octo=tex,
hd=C, sd=S, sd_tex=ntex, sd_diff=d, faces=[])
for f in octo_faces:
ft = sec1.get((race, sex, f, r['Flags'], r['ColorIndex']))
F = dep.get((race, sex, 2, f, v), conv.get((race, sex, 2, f))); Fs = alt.get(F) if F else None
nf = el.get((Fs, S), {}).get(4) if Fs and S else None
entry['faces'].append(dict(face=f, octo=ft, hd=F, sd=Fs, sd_tex=nf,
sd_diff=diff(octo(ft), native(nf)) if ft and nf else None,
state='octo-none' if not ft else 'no-native' if not nf else 'both'))
report.append(entry)
Path(out).write_text(json.dumps(report, indent=1))
bad = [e for e in report if e['sd_diff'] is None or e['sd_diff'] > 12]
print(f'skins {len(report)}; SD skin look differs (>12) or missing: {len(bad)}')
for e in bad:
print(f" race {e['race']} sex {e['sex']} v{e['value']:>2} flags{e['flags']} c{e['color']:>2} hd {e['hd']} sd {e['sd']} diff {e['sd_diff']} {e['octo'].rsplit(chr(92),1)[-1]}")
fc = collections.Counter(f['state'] for e in report for f in e['faces'])
fb = sum(1 for e in report for f in e['faces'] if f['state'] == 'both' and f['sd_diff'] is not None and f['sd_diff'] > 12)
print('faces', dict(fc), 'look differs', fb)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('profile', type=Path)
parser.add_argument('octo_sections', type=Path)
parser.add_argument('output', type=Path)
parser.add_argument('--native-dir', type=Path, help='Directory containing the six matching native DB2 dumps')
parser.add_argument('--texture-dir', type=Path, help='Decoded native texture files named <FileDataID>.blp')
args = parser.parse_args()
def from_directory(fdid):
path = args.texture_dir / f'{fdid}.blp'
return path.read_bytes() if path.is_file() else None
if bool(args.native_dir) != bool(args.texture_dir):
parser.error('supply both --native-dir and --texture-dir for a new build')
main(args.profile, args.octo_sections, args.output, args.native_dir,
from_directory if args.texture_dir else None)