509 lines
32 KiB
Python
509 lines
32 KiB
Python
"""Isolated native70334->Classic character-create packet prototype.
|
||
|
||
No UI, authentication, network, session mutation or implicit appearance defaults.
|
||
This module requires complete source eligibility and exact pinned table data from
|
||
its caller. It is not yet the production C++ transport route.
|
||
"""
|
||
from dataclasses import dataclass, replace
|
||
from pathlib import Path
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import struct
|
||
|
||
NATIVE_CREATE=0x420070
|
||
SOURCE_CREATE=0x36
|
||
MAX_CUSTOMIZATIONS=250
|
||
MAX_SOLUTIONS=4096
|
||
|
||
|
||
class UnsupportedCreation(ValueError):
|
||
"""Well-formed request whose semantics cannot yet be preserved exactly."""
|
||
|
||
|
||
def integer(value,low,high,label):
|
||
if type(value) is not int or not low<=value<=high:
|
||
raise ValueError(label+' out of bounds')
|
||
return value
|
||
|
||
|
||
def indexed_source_section_rows(sections):
|
||
"""Apply the original Source CharSections flagged-color index contract."""
|
||
parsed=[];clear_counts={}
|
||
for row in sections:
|
||
if type(row) is not dict or set(row)!={'id','race','sex','section','variation','color','flags'}:
|
||
raise ValueError('typed source CharSections row required')
|
||
integer(row['id'],1,0xffffffff,'source section identity')
|
||
race=integer(row['race'],1,255,'source section race');sex=integer(row['sex'],0,1,'source section sex')
|
||
section=integer(row['section'],0,4,'source base section');variation=integer(row['variation'],0,255,'source variation')
|
||
color=integer(row['color'],0,255,'source color');flags=integer(row['flags'],0,0xffffffff,'source section flags')
|
||
group=(race,sex,section,variation);parsed.append((row,group,color,flags))
|
||
if not flags&1:clear_counts[group]=clear_counts.get(group,0)+1
|
||
return [(row,group,color+(clear_counts.get(group,0) if flags&1 else 0)) for row,group,color,flags in parsed]
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class NativeCreate:
|
||
name:str
|
||
surname:str
|
||
race:int
|
||
cls:int
|
||
sex:int
|
||
customizations:tuple
|
||
template_set:int|None
|
||
trial_boost:bool
|
||
use_npe:bool
|
||
hardcore_self_found:bool
|
||
unknown_bits:int
|
||
unknown_word:int
|
||
timerunning_season:int
|
||
padding_bits:int
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class SourceCreate:
|
||
opcode:int
|
||
body:bytes
|
||
appearance:tuple
|
||
native:NativeCreate
|
||
|
||
|
||
def parse_native(opcode,body):
|
||
if type(opcode) is not int or opcode!=NATIVE_CREATE:
|
||
raise ValueError('actual70334 character-create opcode required')
|
||
if type(body) is not bytes or not 18<=len(body)<=4096:
|
||
raise ValueError('bounded native character-create body required')
|
||
bits=int.from_bytes(body[:3],'big')
|
||
name_size=(bits>>18)&63;surname_size=(bits>>6)&63
|
||
has_template=bool(bits&(1<<17))
|
||
race,cls,sex,count,unknown_word,season=struct.unpack_from('<BBB I i i',body,3)
|
||
if not name_size or count>MAX_CUSTOMIZATIONS or not race or not cls or sex>1:
|
||
raise ValueError('native create identity/count bounds')
|
||
expected=18+name_size+surname_size+(4 if has_template else 0)+count*8
|
||
if len(body)!=expected:
|
||
raise ValueError('native create length/tail differs')
|
||
position=18
|
||
def text(size):
|
||
nonlocal position
|
||
raw=body[position:position+size];position+=size
|
||
if b'\0' in raw:
|
||
raise ValueError('embedded NUL in native create name')
|
||
try:return raw.decode('utf-8')
|
||
except UnicodeError as error:raise ValueError('native create name is not UTF8') from error
|
||
name=text(name_size);surname=text(surname_size)
|
||
template=struct.unpack_from('<i',body,position)[0] if has_template else None
|
||
if has_template:position+=4
|
||
customizations=[];seen=set()
|
||
for _ in range(count):
|
||
option,choice=struct.unpack_from('<II',body,position);position+=8
|
||
if not option or not choice or option in seen:
|
||
raise ValueError('native customization identity/duplicate option')
|
||
seen.add(option);customizations.append((option,choice))
|
||
return NativeCreate(name,surname,race,cls,sex,tuple(sorted(customizations)),template,
|
||
bool(bits&(1<<16)),bool(bits&(1<<15)),bool(bits&(1<<14)),
|
||
(bits>>12)&3,unknown_word,season,bits&63)
|
||
|
||
|
||
class AppearanceSchema:
|
||
"""Exact conversion relations and source geometry/texture domains.
|
||
|
||
Legacy field numbers1..5 are explicitly named by matching DBDefs:
|
||
skin,face,hairStyle,hairColor,features. No OrderIndex is used.
|
||
"""
|
||
def __init__(self,conversions,choices,sections,facial_hair,hair_geosets):
|
||
for rows in [conversions,choices,sections,facial_hair,hair_geosets]:
|
||
if type(rows) is not list or not 1<=len(rows)<=100000:
|
||
raise ValueError('complete bounded appearance table required')
|
||
self.choices={};self.relations={};self.held_conversion_rows=[];seen=set()
|
||
for row in choices:
|
||
if type(row) is not dict or set(row)!={'ID','ChrCustomizationOptionID'}:
|
||
raise ValueError('typed customization choice required')
|
||
choice=integer(row['ID'],1,0x7fffffff,'choice')
|
||
option=integer(row['ChrCustomizationOptionID'],1,0x7fffffff,'native option')
|
||
if choice in self.choices:raise ValueError('duplicate native choice')
|
||
self.choices[choice]=option
|
||
expected={'ID','ChrRacesID','Sex','OptionID','Data','ChrCustomizationChoiceID',
|
||
'DependentOptionID','DependentData','Field_3_4_0_45166_007'}
|
||
for row in conversions:
|
||
if type(row) is not dict or set(row)!=expected:
|
||
raise ValueError('typed conversion row required')
|
||
rid=integer(row['ID'],1,0x7fffffff,'conversion identity')
|
||
if rid in seen:raise ValueError('duplicate conversion identity')
|
||
seen.add(rid)
|
||
race=integer(row['ChrRacesID'],1,255,'conversion race')
|
||
sex=integer(row['Sex'],-1,1,'conversion sex')
|
||
field=integer(row['OptionID'],1,5,'legacy field')
|
||
value=integer(row['Data'],0,255,'legacy value')
|
||
choice=integer(row['ChrCustomizationChoiceID'],1,0x7fffffff,'conversion choice')
|
||
if choice not in self.choices:raise ValueError('missing native conversion choice parent')
|
||
dependent=integer(row['DependentOptionID'],0,1,'proven dependent legacy field')
|
||
dependent_value=integer(row['DependentData'],0,255,'dependent value')
|
||
if row['Field_3_4_0_45166_007']!=-1 or type(row['Field_3_4_0_45166_007']) is not int:
|
||
raise ValueError('unproven conversion discriminator')
|
||
if sex==-1:
|
||
self.held_conversion_rows.append({'id':rid,'reason':'unproven signed sex−1 semantics'})
|
||
continue
|
||
self.relations.setdefault((race,sex,choice),set()).add((field,value,dependent,dependent_value))
|
||
self.sections=set();self.facial=set();self.hair=set()
|
||
self.creator_skin_counts={}
|
||
for row,group,indexed_color in indexed_source_section_rows(sections):
|
||
if group[2:]==(0,0) and not row['flags']&1:
|
||
key=group[:2]
|
||
self.creator_skin_counts[key]=self.creator_skin_counts.get(key,0)+1
|
||
if indexed_color<=255:self.sections.add((*group,indexed_color))
|
||
for rows,dest in [(facial_hair,self.facial),(hair_geosets,self.hair)]:
|
||
for row in rows:
|
||
if type(row) is not dict or set(row)!={'race','sex','variation'}:
|
||
raise ValueError('typed source hair geometry row required')
|
||
dest.add((integer(row['race'],1,255,'source hair race'),integer(row['sex'],0,1,'source hair sex'),
|
||
integer(row['variation'],0,255,'source hair variation')))
|
||
|
||
def source_skin_face_texture_relationships(self,sections,identities,*,race):
|
||
"""Join Source skin/face rows to witnessed Source texture identities.
|
||
|
||
These relationships do not choose native materials or imply rendering.
|
||
Missing and ambiguous records or texture identities remain explicit holds.
|
||
"""
|
||
race=integer(race,1,255,'source race')
|
||
fields=('id','race','sex','section','variation','color','flags')
|
||
normalized=[]
|
||
for row in sections:
|
||
if type(row) is not dict or set(row)!=set(fields)|{'textures'} or type(row['textures']) is not list or len(row['textures'])!=3 or any(type(p) is not str for p in row['textures']):
|
||
raise ValueError('typed Source section texture row required')
|
||
normalized.append({k:row[k] for k in fields})
|
||
indexed=indexed_source_section_rows(normalized)
|
||
derived={(*group,color) for _,group,color in indexed if group[0]==race and group[2] in (0,1) and color<=255}
|
||
expected={entry for entry in self.sections if entry[0]==race and entry[2] in (0,1)}
|
||
if derived!=expected:raise ValueError('Source texture rows differ from appearance section index')
|
||
|
||
def path_key(path):return path.replace('\\','/').casefold()
|
||
by_path={}
|
||
for item in identities:
|
||
if type(item) is not dict or type(item.get('source_member')) is not str or not item['source_member']:
|
||
raise ValueError('typed current Source texture identity required')
|
||
status=item.get('status')
|
||
if status=='MISSING':continue
|
||
if status not in ('MATCH','MATCH_HISTORICAL','CHANGED','NEW'):
|
||
raise ValueError('unqualified Source texture identity status')
|
||
ckey=item.get('current_ckey');sha=item.get('current_sha256');size=item.get('current_bytes')
|
||
if type(ckey) is not str or not re.fullmatch('[0-9a-f]{32}',ckey) or type(sha) is not str or not re.fullmatch('[0-9a-f]{64}',sha):
|
||
raise ValueError('typed current Source texture keys required')
|
||
integer(size,1,0xffffffff,'source texture size')
|
||
by_path.setdefault(path_key(item['source_member']),set()).add((ckey,sha,size))
|
||
|
||
grouped={};out_of_range=[]
|
||
for row,(_,group,indexed_color) in zip(sections,indexed):
|
||
if group[0]!=race or group[2] not in (0,1):continue
|
||
if indexed_color>255:
|
||
out_of_range.append({'record_id':row['id'],'indexed_color':indexed_color,'flags':row['flags']});continue
|
||
grouped.setdefault((group[1],group[2],group[3],indexed_color),[]).append(row)
|
||
|
||
def detail(candidates,role,reasons):
|
||
if not candidates:
|
||
reasons.append('missing_'+role+'_row');return None
|
||
if len(candidates)!=1:
|
||
reasons.append('ambiguous_'+role+'_row')
|
||
return {'candidate_records':[{'id':r['id'],'flags':r['flags']} for r in candidates]}
|
||
row=candidates[0];textures=[]
|
||
for slot,path in enumerate(row['textures']):
|
||
if not path:
|
||
textures.append(None)
|
||
if slot < (1 if role=='body' else 2):reasons.append('missing_'+role+'_texture_slot_'+str(slot))
|
||
continue
|
||
matches=by_path.get(path_key(path),set())
|
||
texture={'source_member':path}
|
||
if len(matches)==1:
|
||
texture['content_key'],texture['sha256'],texture['bytes']=next(iter(matches))
|
||
else:
|
||
reasons.append(('unverified_' if not matches else 'ambiguous_')+role+'_texture_slot_'+str(slot))
|
||
textures.append(texture)
|
||
return {'record_id':row['id'],'raw_color':row['color'],'flags':row['flags'],'variation':row['variation'],'textures':textures}
|
||
|
||
result=[];domain_holds=[]
|
||
for sex in sorted({k[0] for k in grouped}):
|
||
skins=sorted({k[3] for k in grouped if k[0]==sex and ((k[1]==0 and k[2]==0) or k[1]==1)})
|
||
faces=sorted({k[2] for k in grouped if k[0]==sex and k[1]==1})
|
||
if not faces:domain_holds.append({'sex':sex,'reason':'missing_face_domain'})
|
||
for skin in skins:
|
||
for face in faces:
|
||
reasons=[];body=detail(grouped.get((sex,0,0,skin),[]),'body',reasons);head=detail(grouped.get((sex,1,face,skin),[]),'face',reasons)
|
||
result.append({'race':race,'sex':sex,'skin':skin,'face':face,'status':'held' if reasons else 'source_qualified','reasons':reasons,'body':body,'face_section':head})
|
||
return {'race':race,'relationships':result,'out_of_range_sections':out_of_range,'domain_holds':domain_holds,'native_material_selected':False,'runtime_accepted':False}
|
||
|
||
def source_skin_face_registered_associations(self, relationships, assets, sdk_rows, proof, *, candidate_root,
|
||
inherited_additive_lineage=None):
|
||
"""Bind witnessed Source body/face textures to private registered IDs.
|
||
|
||
This produces Source-only associations; it never chooses a native
|
||
model, material, actor customization or published client resource.
|
||
"""
|
||
if (type(candidate_root) is not str or not re.fullmatch('[0-9a-f]{32}',candidate_root)
|
||
or type(proof) is not dict or not str(proof.get('status','')).startswith('PASS_')
|
||
or type(proof.get('candidate_root')) is not str
|
||
or not re.fullmatch('[0-9a-f]{32}',proof['candidate_root']) or proof.get('mismatch_count')!=0):
|
||
raise ValueError('Pinned candidate SDK proof required')
|
||
if (not isinstance(assets,list) or not 1<=len(assets)<=16384
|
||
or not isinstance(sdk_rows,list) or len(sdk_rows)!=len(assets)
|
||
or proof.get('requested')!=len(assets) or proof.get('returned')!=len(assets)):
|
||
raise ValueError('Complete bounded Source asset and SDK batch required')
|
||
sdk={}
|
||
for row in sdk_rows:
|
||
ident=integer(row.get('file_data_id'),1,0xffffffff,'SDK file data ID')
|
||
if ident in sdk:raise ValueError('Duplicate SDK selector')
|
||
sdk[ident]=row
|
||
if proof['candidate_root']!=candidate_root:
|
||
if inherited_additive_lineage is None:
|
||
raise ValueError('Pinned candidate SDK proof required')
|
||
self._source_registered_additive_receipt(inherited_additive_lineage,proof,sdk_rows,candidate_root)
|
||
elif inherited_additive_lineage is not None:
|
||
raise ValueError('Unnecessary additive lineage is not accepted')
|
||
by_identity={};asset_ids=set()
|
||
for asset in assets:
|
||
ident=integer(asset.get('file_data_id'),1,0xffffffff,'Source file data ID')
|
||
if ident in asset_ids:raise ValueError('Duplicate registered Source selector')
|
||
asset_ids.add(ident)
|
||
ckey=asset.get('content_key');sha=asset.get('sha256');size=asset.get('bytes');members=asset.get('source_members')
|
||
if (type(ckey) is not str or not re.fullmatch('[0-9a-f]{32}',ckey)
|
||
or type(sha) is not str or not re.fullmatch('[0-9a-f]{64}',sha)
|
||
or type(size) is not int or size<=0 or not isinstance(members,list) or not members):
|
||
raise ValueError('Bound Source texture identity required')
|
||
witness=sdk.get(ident)
|
||
if (not witness or witness.get('known') is not True or witness.get('full_info_available') is not True
|
||
or witness.get('resolved_file_data_id')!=ident or witness.get('content_key')!=ckey
|
||
or witness.get('content_size')!=size):
|
||
raise ValueError('Registered Source texture SDK identity differs')
|
||
for member in members:
|
||
path=member.get('member') if isinstance(member,dict) else None
|
||
if type(path) is not str or not path:raise ValueError('Source member identity required')
|
||
key=(path.replace('\\','/').casefold(),ckey,sha,size)
|
||
by_identity.setdefault(key,set()).add(ident)
|
||
if asset_ids!=set(sdk):raise ValueError('Source asset and SDK selector sets differ')
|
||
if not isinstance(relationships,list) or not 1<=len(relationships)<=65536:
|
||
raise ValueError('Bounded Source relationships required')
|
||
result=[]
|
||
for source in relationships:
|
||
if not isinstance(source,dict):raise ValueError('Source relationship required')
|
||
row={'race':integer(source.get('race'),1,255,'source race'),
|
||
'sex':integer(source.get('sex'),0,1,'source sex'),
|
||
'skin':integer(source.get('skin'),0,255,'source skin'),
|
||
'face':integer(source.get('face'),0,255,'source face'),
|
||
'source_status':source.get('status'),'textures':[], 'reasons':[]}
|
||
if source.get('status')!='source_qualified':
|
||
row['reasons'].append('source_relationship_held')
|
||
else:
|
||
for role,field in (('body','body'),('face','face_section')):
|
||
part=source.get(field)
|
||
if not isinstance(part,dict) or not isinstance(part.get('textures'),list):
|
||
row['reasons'].append('missing_'+role+'_relationship');continue
|
||
required=1 if role=='body' else 2
|
||
if len(part['textures'])<required or any(not part['textures'][i] for i in range(required)):
|
||
row['reasons'].append('missing_'+role+'_required_texture')
|
||
for slot,texture in enumerate(part['textures']):
|
||
if texture is None:continue
|
||
if not isinstance(texture,dict) or not isinstance(texture.get('source_member'),str):
|
||
row['reasons'].append('invalid_'+role+'_texture');continue
|
||
key=(texture['source_member'].replace('\\','/').casefold(),texture.get('content_key'),texture.get('sha256'),texture.get('bytes'))
|
||
matches=by_identity.get(key,set())
|
||
if len(matches)!=1:
|
||
row['reasons'].append(('missing_' if not matches else 'ambiguous_')+role+'_registered_texture');continue
|
||
row['textures'].append({'role':role,'slot':slot,'source_member':texture['source_member'],
|
||
'content_key':texture['content_key'],'file_data_id':next(iter(matches))})
|
||
row['status']='held' if row['reasons'] else 'source_associated'
|
||
result.append(row)
|
||
return {'candidate_root':candidate_root,'sdk_proof_root':proof['candidate_root'],
|
||
'sdk_proof_inherited':proof['candidate_root']!=candidate_root,'relationships':result,
|
||
'native_material_selected':False,'actor_customization_selected':False,'runtime_accepted':False}
|
||
|
||
@staticmethod
|
||
def _source_registered_additive_lineage(lineage,parent_root,child_root,parent_ids):
|
||
"""Accept only one saved, selection-bound additive private COW step."""
|
||
if not isinstance(lineage,dict) or set(lineage)!={'root_delta','framing','cow','child_selection','parent_handoff'}:
|
||
raise ValueError('Complete additive Source lineage required')
|
||
d,f,c,s,p=(lineage[k] for k in ('root_delta','framing','cow','child_selection','parent_handoff'))
|
||
if any(not isinstance(x,dict) for x in (d,f,c,s,p)):
|
||
raise ValueError('Typed additive Source lineage required')
|
||
a=d.get('root_audit',{});added=d.get('assets');fr=f.get('root',{});tv=f.get('tvfs_child_audit',{})
|
||
en=f.get('encoding_audit',{});dl=f.get('download_audit',{});top=f.get('tvfs_parent_audit',{})
|
||
if (not str(d.get('status','')).startswith('PRIVATE_') or f.get('status')!='PASS_FRAMED_PRIVATE'
|
||
or c.get('kind')!='independent-cow-native-casc-candidate'
|
||
or d.get('parent_root')!=parent_root or d.get('candidate_root')!=child_root
|
||
or a.get('original_root_md5')!=parent_root or a.get('staged_root_md5')!=child_root
|
||
or a.get('original_groups_bit_identical') is not True or not isinstance(added,list)
|
||
or not added or a.get('new_records')!=len(added)
|
||
or f.get('parent_root')!=parent_root or fr.get('content_key')!=child_root
|
||
or f.get('new_asset_count')!=len(added) or f.get('new_physical_texture_frames')!=0
|
||
or en.get('original_entries_preserved') is not True
|
||
or en.get('all_original_content_key_encoding_bindings_preserved') is not True
|
||
or dl.get('original_entry_bytes_preserved') is not True or dl.get('original_tag_bits_preserved') is not True
|
||
or tv.get('all_original_path_offsets_preserved') is not True
|
||
or tv.get('CFT_VFS_ESpec_bytes_and_offsets_exact') is not True
|
||
or top.get('all_other_path_offsets_preserved') is not True):
|
||
raise ValueError('Additive ROOT and storage preservation proof required')
|
||
new_ids={integer(r.get('file_data_id'),1,0xffffffff,'additive file data ID') for r in added if isinstance(r,dict)}
|
||
aliases=tv.get('aliases')
|
||
root_keys={r.get('file_data_id'):r.get('content_key') for r in added if isinstance(r,dict)}
|
||
alias_keys={r.get('file_data_id'):r.get('content_key') for r in aliases if isinstance(r,dict)} if isinstance(aliases,list) else {}
|
||
if (len(new_ids)!=len(added) or parent_ids & new_ids or not isinstance(aliases,list)
|
||
or len(aliases)!=len(added) or alias_keys!=root_keys):
|
||
raise ValueError('Additive selectors must be distinct and disjoint')
|
||
parents=c.get('parent_index_files');indexes=c.get('new_index_generations')
|
||
if (c.get('logical_parent_root')!=parent_root or c.get('independent_cow_data') is not True
|
||
or c.get('existing_index_generations_preserved') is not True
|
||
or c.get('parent_index_preimages_preserved_independently_of_native_pruning') is not True
|
||
or c.get('new_objects_routed_by_exact_index_prefix_absence') is not True
|
||
or not isinstance(parents,list) or len(parents)!=16 or not isinstance(indexes,list)
|
||
or s.get('status')!='PASS_CHILD_STORE_BUILD_CONFIG_BINDS_SELECTED_ROOT'
|
||
or s.get('parent_root')!=parent_root or s.get('candidate_root')!=child_root
|
||
or s.get('candidate_build_key')!=c.get('new_build_config')
|
||
or s.get('parent_build_key')!=c.get('original_build_config')
|
||
or p.get('candidate_build_key')!=c.get('original_build_config')
|
||
or p.get('candidate_root')!=parent_root
|
||
or not all(isinstance(x,str) and x for x in (p.get('candidate_store'),c.get('parent_store'),s.get('parent_store')))
|
||
or Path(p['candidate_store']).resolve()!=Path(c['parent_store']).resolve()
|
||
or Path(s['parent_store']).resolve()!=Path(c['parent_store']).resolve()):
|
||
raise ValueError('Selection-bound private COW and parent indices required')
|
||
by_file={r.get('file'):r for r in parents if isinstance(r,dict)}
|
||
if len(by_file)!=16 or {r.get('bucket') for r in parents if isinstance(r,dict)}!=set(range(16)):
|
||
raise ValueError('Complete distinct parent index preimages required')
|
||
for name,row in by_file.items():
|
||
if (not isinstance(name,str) or not re.fullmatch('[0-9a-f]{10}\\.idx',name)
|
||
or row.get('bucket')!=int(name[:2],16) or row.get('generation')!=int(name[2:10],16)
|
||
or row.get('relative')!='Data/data/'+name or type(row.get('bytes')) is not int or row['bytes']<=0
|
||
or not isinstance(row.get('preserved_preimage'),str) or not row['preserved_preimage']
|
||
or not isinstance(row.get('sha256'),str) or not re.fullmatch('[0-9a-f]{64}',row['sha256'])):
|
||
raise ValueError('Pinned parent index preimage identity required')
|
||
seen_old=set()
|
||
for r in indexes:
|
||
if (not isinstance(r,dict) or r.get('original_entries_bit_identical') is not True
|
||
or r.get('old_file') not in by_file or r['old_file'] in seen_old
|
||
or r.get('original_sha256')!=by_file[r['old_file']].get('sha256')):
|
||
raise ValueError('Existing local index entries must be preserved')
|
||
seen_old.add(r['old_file'])
|
||
|
||
@staticmethod
|
||
def _source_evidence_sha(value):
|
||
return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
||
|
||
def prepare_source_registered_additive_receipt(self,lineage,proof,sdk_rows,*,candidate_root):
|
||
"""Qualify saved additive audits once; do not re-read ROOTs or indices."""
|
||
if (not isinstance(proof,dict) or not str(proof.get('status','')).startswith('PASS_')
|
||
or proof.get('mismatch_count')!=0 or not isinstance(sdk_rows,list)
|
||
or not sdk_rows or proof.get('requested')!=len(sdk_rows) or proof.get('returned')!=len(sdk_rows)):
|
||
raise ValueError('Complete parent SDK proof required')
|
||
parent=proof.get('candidate_root')
|
||
if (not isinstance(parent,str) or not re.fullmatch('[0-9a-f]{32}',parent)
|
||
or not isinstance(candidate_root,str) or not re.fullmatch('[0-9a-f]{32}',candidate_root)
|
||
or parent==candidate_root):
|
||
raise ValueError('Distinct pinned parent and child roots required')
|
||
ids={integer(r.get('file_data_id'),1,0xffffffff,'SDK file data ID') for r in sdk_rows if isinstance(r,dict)}
|
||
if len(ids)!=len(sdk_rows):raise ValueError('Distinct parent SDK selectors required')
|
||
self._source_registered_additive_lineage(lineage,parent,candidate_root,ids)
|
||
receipt={'status':'PASS_SOURCE_ADDITIVE_SDK_INHERITANCE_V1','parent_root':parent,'child_root':candidate_root,
|
||
'parent_proof_sha256':self._source_evidence_sha(proof),'sdk_rows_sha256':self._source_evidence_sha(sdk_rows),
|
||
'source_inputs_sha256':{k:self._source_evidence_sha(v) for k,v in lineage.items()},
|
||
'sdk_selector_count':len(ids),'native_material_selected':False,'runtime_accepted':False}
|
||
return {'receipt':receipt,'receipt_sha256':self._source_evidence_sha(receipt)}
|
||
|
||
def _source_registered_additive_receipt(self,wrapped,proof,sdk_rows,child_root):
|
||
if (not isinstance(wrapped,dict) or set(wrapped)!={'receipt','receipt_sha256'}
|
||
or not isinstance(wrapped['receipt'],dict)
|
||
or wrapped['receipt_sha256']!=self._source_evidence_sha(wrapped['receipt'])):
|
||
raise ValueError('Pinned additive Source receipt required')
|
||
r=wrapped['receipt'];pins=r.get('source_inputs_sha256')
|
||
if (r.get('status')!='PASS_SOURCE_ADDITIVE_SDK_INHERITANCE_V1' or r.get('parent_root')!=proof['candidate_root']
|
||
or r.get('child_root')!=child_root or r.get('parent_proof_sha256')!=self._source_evidence_sha(proof)
|
||
or r.get('sdk_rows_sha256')!=self._source_evidence_sha(sdk_rows) or r.get('sdk_selector_count')!=len(sdk_rows)
|
||
or not isinstance(pins,dict) or set(pins)!={'root_delta','framing','cow','child_selection','parent_handoff'}
|
||
or any(not isinstance(v,str) or not re.fullmatch('[0-9a-f]{64}',v) for v in pins.values())
|
||
or r.get('native_material_selected') is not False or r.get('runtime_accepted') is not False):
|
||
raise ValueError('Additive Source receipt inputs differ')
|
||
|
||
def creator_skin_allowed(self,race,sex,skin):
|
||
return 0<=skin<self.creator_skin_counts.get((race,sex),0)
|
||
|
||
def source_valid(self,race,sex,appearance):
|
||
skin,face,hair_style,hair_color,features=appearance
|
||
return ((race,sex,0,0,skin) in self.sections and
|
||
(race,sex,1,face,skin) in self.sections and
|
||
(race,sex,3,hair_style,hair_color) in self.sections and
|
||
(race,sex,hair_style) in self.hair and
|
||
(race,sex,features) in self.facial)
|
||
|
||
def resolve(self,request,*,new_character=False):
|
||
if not request.customizations:
|
||
raise UnsupportedCreation('missing explicit native customization choices')
|
||
states={(None,)*5}
|
||
for option,choice in request.customizations:
|
||
if self.choices.get(choice)!=option:
|
||
raise UnsupportedCreation('native option/choice parent differs')
|
||
relations=self.relations.get((request.race,request.sex,choice))
|
||
if not relations:
|
||
raise UnsupportedCreation('native choice has no exact race/sex legacy conversion')
|
||
new=set()
|
||
for state in states:
|
||
for field,value,dependent,dependent_value in relations:
|
||
updates={field-1:value}
|
||
if dependent:
|
||
if dependent-1 in updates and updates[dependent-1]!=dependent_value:continue
|
||
updates[dependent-1]=dependent_value
|
||
if any(state[index] is not None and state[index]!=value for index,value in updates.items()):continue
|
||
result=list(state)
|
||
for index,value in updates.items():result[index]=value
|
||
new.add(tuple(result))
|
||
if len(new)>MAX_SOLUTIONS:raise UnsupportedCreation('appearance inverse solution bound')
|
||
states=new
|
||
if not states:raise UnsupportedCreation('conflicting native legacy appearance constraints')
|
||
complete={state for state in states if None not in state and self.source_valid(request.race,request.sex,state)
|
||
and (not new_character or self.creator_skin_allowed(request.race,request.sex,state[0]))}
|
||
def forward_of(result):
|
||
forward={}
|
||
for (race,sex,choice),relations in self.relations.items():
|
||
if (race,sex)!=(request.race,request.sex):continue
|
||
if any(result[field-1]==value and (not dep or result[dep-1]==dep_value)
|
||
for field,value,dep,dep_value in relations):
|
||
option=self.choices[choice]
|
||
if option in forward and forward[option]!=choice:
|
||
raise UnsupportedCreation('source tuple has ambiguous native forward choices')
|
||
forward[option]=choice
|
||
return forward
|
||
canonical=False
|
||
# NEW creation only: exact native equivalence, not source visual aliases.
|
||
# Generic inverse callers keep their strict uniqueness requirement.
|
||
if new_character and (request.race,request.sex)==(6,0) and len(complete)==2:
|
||
zero,seven=sorted(complete)
|
||
if zero[4]==0 and seven[4]==7 and zero[:4]==seven[:4]:
|
||
canonical=forward_of(zero)==forward_of(seven)==dict(request.customizations)
|
||
if len(complete)!=1 and not canonical:
|
||
raise UnsupportedCreation('appearance inverse incomplete/ambiguous/source-domain')
|
||
result=min(complete) if canonical else next(iter(complete))
|
||
forward=forward_of(result)
|
||
if any(forward.get(option)!=choice for option,choice in request.customizations):
|
||
raise UnsupportedCreation('native choices fail exact legacy forward roundtrip')
|
||
return result
|
||
|
||
|
||
def translate_native(opcode,body,schema,source_pairs):
|
||
request=parse_native(opcode,body)
|
||
# Original regional validation accepts the Source UI's exact control
|
||
# surname. Classic creation carries only the first name.
|
||
if request.surname=='Control':
|
||
request=replace(request,surname='')
|
||
if type(source_pairs) not in (list,tuple,set,frozenset) or not source_pairs:
|
||
raise ValueError('complete source eligibility pairs required')
|
||
pairs=set()
|
||
for pair in source_pairs:
|
||
if type(pair) not in (list,tuple) or len(pair)!=2:
|
||
raise ValueError('typed source race/class pair required')
|
||
pairs.add((integer(pair[0],1,255,'source pair race'),integer(pair[1],1,255,'source pair class')))
|
||
if (request.race,request.cls) not in pairs:
|
||
raise UnsupportedCreation('race/class not present in actual source creation profile')
|
||
if (request.surname or request.template_set is not None or request.trial_boost or request.use_npe or
|
||
request.hardcore_self_found or request.unknown_bits or request.timerunning_season or request.unknown_word!=-1):
|
||
raise UnsupportedCreation('native creation feature has no proven Classic representation')
|
||
appearance=schema.resolve(request,new_character=True)
|
||
# Source CharacterCreation ignores outfitId after parsing; starting equipment
|
||
# is derived from real source race/class create info. Standard no-challenge
|
||
# request maps only to actual zero challengeMask, never a guessed mode.
|
||
payload=request.name.encode('utf-8')+b'\0'+bytes((request.race,request.cls,request.sex,*appearance,0))+bytes(4)
|
||
return SourceCreate(SOURCE_CREATE,payload,appearance,request)
|