776 lines
55 KiB
Python
776 lines
55 KiB
Python
#!/usr/bin/env python3
|
|
"""Bounded256 ->272 equipment assembly; standalone staging, never installation.
|
|
|
|
Reuses the paired-model parser and verified track converter. Limited to the
|
|
captured equipment feature family: basic one-texture draw batches and colors,
|
|
UV animation, lights, cameras, ribbons or particles. Unsupported features fail
|
|
explicitly; source geometry, material passes, attachments and events survive.
|
|
Registered SFID/TXID bindings must be supplied by a separate asset package.
|
|
"""
|
|
import hashlib
|
|
import argparse
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
from collections import Counter
|
|
import re
|
|
import struct
|
|
|
|
from m2_format_compare import model,skin,_extent
|
|
from m2_track_convert import convert_track,duplicate_native_sequence_slot
|
|
from model_blob import normalize_reversed_collision_bounds
|
|
|
|
|
|
def mark_generated_inline_sequences(body):
|
|
"""Mark generated272/274 in-body tracks as embedded, preserving other bits.
|
|
|
|
The converter appends every timestamp/key payload to this MD20 body.
|
|
Primary parseAnimTrack's 0x20 storage branch and55original70334 controls
|
|
ground this metadata. This does not modify published/native input models.
|
|
"""
|
|
if (not isinstance(body,bytes)or not 304<=len(body)<=67108864 or
|
|
body[:4]!=b'MD20'or struct.unpack_from('<I',body,4)[0]not in(272,274)):
|
|
raise ValueError('Generated bounded native MD20 body required')
|
|
count,offset=struct.unpack_from('<II',body,28)
|
|
if not 1<=count<=4096:raise ValueError('Generated animation sequence count')
|
|
_extent(body,offset,count,64,304)
|
|
output=bytearray(body);changed=0
|
|
for index in range(count):
|
|
at=offset+index*64+12;flags=struct.unpack_from('<I',body,at)[0]
|
|
native=flags|0x20;changed+=native!=flags;struct.pack_into('<I',output,at,native)
|
|
return bytes(output),dict(kind='generated-inline-animation-storage-metadata',
|
|
embedded_data_flag=0x20,sequences=count,changed_sequences=changed,
|
|
all_other_flag_bits_preserved=True,tracks_reconverted=False,
|
|
original_native_consumer_code_verified=False,native_acceptance=False)
|
|
|
|
|
|
def canonicalize_geometry_reversed_collision_bounds(raw):
|
|
"""Keep the recovered converter API, sharing the opt-in geometry helper."""
|
|
return normalize_reversed_collision_bounds(raw)
|
|
|
|
|
|
def source_playable_default0(raw):
|
|
"""Read the original256 precomputed default; do not guess fallback flags."""
|
|
if not isinstance(raw, bytes) or len(raw) < 324 or raw[:4] != b'MD20' or struct.unpack_from('<I',raw,4)[0] not in (256,257):
|
|
raise ValueError('Source256/257 playable-default input required')
|
|
count, offset = struct.unpack_from('<II', raw, 28)
|
|
lc, lo, pc, po = struct.unpack_from('<4I', raw, 36)
|
|
_extent(raw, offset, count, 68, 324)
|
|
lookup = _extent(raw, lo, lc, 2, 324)
|
|
if not pc:
|
|
raise ValueError('Exact precomputed Source playable0 required')
|
|
playable = _extent(raw, po, pc, 4, 324)
|
|
animation, flags = struct.unpack_from('<HH', playable)
|
|
if flags:
|
|
raise ValueError('Source default Reverse/Hold needs native consumer proof')
|
|
index = struct.unpack_from('<H', lookup, animation*2)[0] if animation < lc else 65535
|
|
if index == 65535 or index >= count:
|
|
raise ValueError('Source default has no selected sequence; initialization policy held')
|
|
return dict(animation_ID=animation, sequence_index=index, sequence_count=count,
|
|
playable_flags=flags, original_Source_playable0_hex=playable[:4].hex())
|
|
|
|
|
|
def materialize_source_playable_default0(raw, *, source_default,
|
|
world_model_bounds):
|
|
"""Represent Source playable[0] with an actual native ID0 and the same curve.
|
|
|
|
Native70334's observed default-bounds hash lookup checks the candidate
|
|
sequence ID, so a lookup-only alias cannot express the legacy relationship.
|
|
Keep every original sequence and payload; append only its default record
|
|
and matching inline track/event descriptors. This is not an alias flag.
|
|
"""
|
|
if (world_model_bounds is not True or
|
|
not isinstance(raw, bytes) or not 304 <= len(raw) <= 67108864 or
|
|
not isinstance(source_default, dict) or
|
|
any(type(source_default.get(k)) is not int for k in
|
|
('animation_ID','sequence_index','sequence_count','playable_flags')) or
|
|
source_default['playable_flags'] != 0):
|
|
raise ValueError('Exact Source playable default with no Reverse/Hold required')
|
|
base = 8 if raw[:4] == b'MD21' else 0
|
|
size = struct.unpack_from('<I', raw, 4)[0] if base else len(raw)
|
|
body = bytearray(raw[base:base+size])
|
|
if (len(body) != size or body[:4] != b'MD20' or
|
|
struct.unpack_from('<I', body, 4)[0] not in (272,274) or
|
|
struct.unpack_from('<I', body, 16)[0] != 0):
|
|
raise ValueError('Generated Source native body required')
|
|
count, offset = struct.unpack_from('<II', body, 28)
|
|
index = source_default['sequence_index']; animation = source_default['animation_ID']
|
|
if count != source_default['sequence_count'] or not 0 <= index < count < 4096:
|
|
raise ValueError('Exact existing Source sequence domain required')
|
|
sequences = bytes(_extent(body, offset, count, 64, 304))
|
|
target = sequences[index*64:(index+1)*64]
|
|
if struct.unpack_from('<H',target)[0] != animation:
|
|
raise ValueError('Source selected sequence identity differs')
|
|
ids = [struct.unpack_from('<H',sequences,i*64)[0] for i in range(count)]
|
|
if 0 in ids:
|
|
if animation == 0:
|
|
return raw,dict(kind='source-playable-default0-materialization-v1',changed=False,
|
|
reason='Source already has authored Stand0')
|
|
raise ValueError('Source overrides an existing Stand0; separate contract required')
|
|
if (struct.unpack_from('<h',target,60)[0] != -1 or
|
|
struct.unpack_from('<I',target,12)[0] & 0x40 or
|
|
not struct.unpack_from('<I',target,12)[0] & 0x20):
|
|
raise ValueError('Default multi-variation or alias storage held')
|
|
# Source5014 SetDoodadDefBounds -> GetBoundingBox/GetBoundingSphere reads
|
|
# the model header (+B4 box, +CC radius), not animation-record bounds.
|
|
# Native70334 initializes its World default bounds from the ID0 record.
|
|
# This explicit role projection leaves the authored sequence untouched.
|
|
bounds_bytes = bytes(body[160:188]) if world_model_bounds else target[32:60]
|
|
bounds = struct.unpack('<7f', bounds_bytes)
|
|
vertex_count = struct.unpack_from('<I',body,60)[0]
|
|
if (not all(math.isfinite(v) for v in bounds) or
|
|
any(bounds[k] > bounds[k+3] for k in range(3)) or
|
|
bounds[6] < 0 or vertex_count and
|
|
(bounds[6] == 0 or not any(bounds[k] < bounds[k+3] for k in range(3)))):
|
|
raise ValueError('Source selected bounds role empty/inverted/nonfinite; no fallback inferred')
|
|
lc, lo = struct.unpack_from('<II', body, 36)
|
|
lookup = bytes(_extent(body, lo, lc, 2, 304))
|
|
if not lc or struct.unpack_from('<H',lookup)[0] != 65535 or animation >= lc or struct.unpack_from('<H',lookup,animation*2)[0] != index:
|
|
raise ValueError('Exact missing-default and selected lookup relationship required')
|
|
for at in (96,264,272,280,288,296):
|
|
if struct.unpack_from('<I',body,at)[0]:
|
|
raise ValueError('Unreviewed generated animation feature')
|
|
globals_count = struct.unpack_from('<I',body,20)[0]
|
|
if globals_count > 4096:
|
|
raise ValueError('Global sequence count bound')
|
|
fields = [(28,36),(lo,lo+2)]; tracks=[]
|
|
def append(data):
|
|
body.extend(bytes((-len(body))%16)); at=len(body);body.extend(data)
|
|
if len(body)>67108864:raise ValueError('Default materialization body bound')
|
|
return at
|
|
default = bytearray(target);struct.pack_into('<H',default,0,0)
|
|
default[32:60] = bounds_bytes
|
|
struct.pack_into('<II',body,28,count+1,append(sequences+default))
|
|
struct.pack_into('<H',body,lo,count)
|
|
for header,stride,positions,time_only in ((44,88,(16,36,56),False),
|
|
(72,40,(0,20),False),(88,20,(0,),False),
|
|
(240,40,(20,),False),(256,36,(24,),True)):
|
|
n, at = struct.unpack_from('<II',body,header)
|
|
_extent(body,at,n,stride,304)
|
|
for i in range(n):
|
|
for relative in positions:
|
|
where=at+i*stride+relative
|
|
audit=duplicate_native_sequence_slot(body,where,count,index,append,
|
|
global_sequence_count=globals_count,timestamps_only=time_only)
|
|
tracks.append(audit)
|
|
if audit['changed']:fields.append((where+4,where+(12 if time_only else 20)))
|
|
# Check the existing body, not merely a list of intended changed fields.
|
|
before=bytearray(raw[base:base+size]);after=body[:size]
|
|
for a,z in fields:before[a:z]=bytes(z-a);after[a:z]=bytes(z-a)
|
|
if before != after:raise ValueError('Default materialization changed undeclared body bytes')
|
|
result=(raw[:4]+struct.pack('<I',len(body))+bytes(body)+raw[base+size:]) if base else bytes(body)
|
|
return result,dict(kind='source-playable-default0-materialization-v1',changed=True,
|
|
source_default=dict(source_default),source_sequence_index=index,
|
|
resolved_Source_record_bounds=dict(min=list(bounds[:3]),max=list(bounds[3:6]),radius=bounds[6]),
|
|
default_bounds_origin=('SOURCE_WORLD_MODEL_HEADER_6952A0_713640_713680'
|
|
if world_model_bounds else 'SOURCE_SELECTED_SEQUENCE'),
|
|
default_bounds_exact_hex=bounds_bytes.hex(),
|
|
default_sequence_index=count,old_sequence_count=count,new_sequence_count=count+1,
|
|
body_offset=base,old_body_bytes=size,new_body_bytes=len(body),
|
|
changed_original_body_fields=[list(v) for v in fields],tracks=tracks,
|
|
all_original_sequence_records_preserved=True,
|
|
default_record_except_ID_exact=not world_model_bounds,
|
|
default_record_except_ID_and_qualified_bounds_exact=True,
|
|
all_original_body_bytes_outside_declared_fields_preserved=True,
|
|
all_external_and_opaque_chunks_preserved=True,no_curve_keys_or_timestamps_generated=True,
|
|
global_sequence_semantics_preserved=True,alias_flags_added=False,native_acceptance=False)
|
|
|
|
|
|
def _qualified_cutout_shader16_batch(raw, source_skin, batch):
|
|
"""Exact Source cutout class paired to the retained native Durotar SKIN control.
|
|
|
|
Source shader helpers consume the selected lookup values and bone influence;
|
|
texture flags select sampler wrapping independently and remain unchanged.
|
|
The batch flags remain 24. Only the native shader word is canonicalized.
|
|
"""
|
|
if (len(batch) != 13 or tuple(batch[0:3]) != (24, 0, 0)
|
|
or batch[3] != batch[4] or batch[5] != 65535
|
|
or batch[7] != 0 or batch[8] != 1 or batch[11] != 0):
|
|
return False
|
|
def words(offset, stride):
|
|
count, at = struct.unpack_from('<II', raw, offset)
|
|
return count, _extent(raw, at, count, stride, 324)
|
|
material_count, materials = words(0x84, 4)
|
|
texture_count, textures = words(0x5C, 16)
|
|
tex_lookup_count, tex_lookup = words(0x94, 2)
|
|
coord_count, coord_lookup = words(0x9C, 2)
|
|
transform_count, transform_lookup = words(0xAC, 2)
|
|
# The original helpers select these records through each batch. Their
|
|
# values, not a zero index or a one-record table, determine this class.
|
|
if not 0 <= batch[6] < material_count or struct.unpack_from('<HH', materials, batch[6] * 4) != (4, 1):
|
|
return False
|
|
if not 0 <= batch[9] < tex_lookup_count:
|
|
return False
|
|
texture_index = struct.unpack_from('<H', tex_lookup, batch[9] * 2)[0]
|
|
if not 0 <= texture_index < texture_count or struct.unpack_from('<I', textures, texture_index * 16)[0] != 0:
|
|
return False
|
|
if struct.unpack_from('<I', textures, texture_index * 16 + 4)[0] & ~3:
|
|
return False
|
|
if not 0 <= batch[10] < coord_count or struct.unpack_from('<h', coord_lookup, batch[10] * 2)[0] != 0:
|
|
return False
|
|
if not 0 <= batch[12] < transform_count or struct.unpack_from('<H', transform_lookup, batch[12] * 2)[0] != 65535:
|
|
return False
|
|
if struct.unpack_from('<I', raw, 0x74)[0] != 0:
|
|
return False
|
|
return (0 <= batch[3] < source_skin['header'][6]
|
|
and struct.unpack_from('<H', source_skin['arrays'][3], batch[3] * 32 + 0x10)[0] == 1)
|
|
|
|
|
|
def native_particle_emitter(raw, at, track, append, bone_count, texture_count):
|
|
"""Source256 M2Particle (504 bytes) -> native272 M2Particle (492 bytes).
|
|
|
|
Field order is unchanged; ten float tracks and the enabled track shrink
|
|
from 28 to 20 bytes; the fixed three-point colour/alpha/scale table and
|
|
the head/tail cell words become native value-over-lifetime blocks at
|
|
(0, midpoint, 1); the head/tail selector word becomes flags 0x20000 /
|
|
0x40000. Every rule here is read off Blizzard's own conversion of
|
|
emitters present in both clients (claude-lane particle pair checks).
|
|
Flags bits 0..15 are copied: Blizzard changed lighting/world-space bits
|
|
on some of its own models, but not by any rule derivable from the file.
|
|
"""
|
|
r=_extent(raw,at,1,504,324)
|
|
flags,=struct.unpack_from('<I',r,4);bone,texture=struct.unpack_from('<HH',r,20)
|
|
blend,emitter,selector=struct.unpack_from('<HHH',r,40)
|
|
if flags>>16:raise ValueError('Unreviewed source particle flags')
|
|
if bone>=bone_count or texture>=texture_count:raise ValueError('Particle bone or texture outside source model')
|
|
if blend>7 or emitter not in(1,2,3)or selector not in(0,1,2):raise ValueError('Unreviewed source particle blend/emitter/head-tail value')
|
|
for name_offset in(24,32):
|
|
count,offset=struct.unpack_from('<II',r,name_offset);_extent(raw,offset,count,1,324)
|
|
points,point_offset=struct.unpack_from('<II',r,468);_extent(raw,point_offset,points,12,324)
|
|
midpoint,=struct.unpack_from('<f',r,332);colors=struct.unpack_from('<3I',r,336);scales=struct.unpack_from('<3f',r,348)
|
|
head=struct.unpack_from('<6H',r,360);tail=struct.unpack_from('<4h',r,372)
|
|
plain=struct.unpack_from('<3f',r,8)+scales+struct.unpack_from('<7f',r,380)+struct.unpack_from('<15f',r,408)
|
|
if not all(math.isfinite(v)for v in plain)or not 0<=midpoint<=1:raise ValueError('Nonfinite particle constant or midpoint outside lifetime')
|
|
if any(v<0 for v in tail):raise ValueError('Unreviewed particle cell animation words')
|
|
middle=round(midpoint*32767)
|
|
def block(times,fmt,values):
|
|
return struct.pack('<4I',len(times),append(struct.pack('<%dH'%len(times),*times)),len(values),append(b''.join(struct.pack(fmt,*v)for v in values)))
|
|
three=(0,middle,32767);four=(0,middle,middle,32767)
|
|
flags|=(0x20000 if selector in(0,2)else 0)|(0x40000 if selector in(1,2)else 0)
|
|
# As with ribbons, Blizzard's converted emitters carry an EMPTY enabled
|
|
# track where the Source track is the single always-on key (507 of 514
|
|
# paired emitters from the original archives); every other track is
|
|
# converted key for key.
|
|
interpolation,global_id,nr,ro,nt,to,nk,ko=struct.unpack_from('<Hh6I',r,476)
|
|
if global_id==-1 and nr==0 and nt==1 and nk==1 and _extent(raw,to,1,4,324)==bytes(4) and _extent(raw,ko,1,1,324)==b'\x01':
|
|
enabled=struct.pack('<Hh4I',interpolation,-1,0,0,0,0)
|
|
else:enabled=track(at+476,'visibility','enabled')
|
|
tracks=[track(at+52+28*i,'float32',name)for i,name in enumerate(('speed','variation','vertical','horizontal','gravity','lifespan','rate','length','width','source-z'))]
|
|
native=(r[:4]+struct.pack('<I',flags)+r[8:40]+struct.pack('<BBHBB',blend,emitter,0,0,0)+r[46:52]+
|
|
b''.join(tracks[:6])+bytes(4)+tracks[6]+bytes(4)+b''.join(tracks[7:])+
|
|
block(three,'<3f',[(float(c>>16&255),float(c>>8&255),float(c&255))for c in colors])+
|
|
block(three,'<H',[(round((c>>24)*32767/255),)for c in colors])+
|
|
block(three,'<2f',[(s,s)for s in scales])+bytes(8)+
|
|
block(four,'<H',[(head[0],),(head[1],),(head[3],),(head[4],)])+
|
|
block(four,'<H',[(v,)for v in tail])+
|
|
r[380:408]+bytes(8)+r[408:412]+bytes(4)+r[412:476]+enabled+bytes(16))
|
|
if len(native)!=492:raise ValueError('Native particle record width')
|
|
return native
|
|
|
|
|
|
def paired_single_texture_batch(batch, blend, environment_coordinates):
|
|
"""Native (flags, priority plane, shader word) for one single-texture Source256 batch.
|
|
|
|
Derived from Blizzard's own conversion: Source256 models that also exist in
|
|
the Forever client with identical triangles and index-aligned batch rows
|
|
(claude-lane/scripts/m2_pair_rule_check.py: 1421 of 1456 rows exact, the
|
|
rest are models whose materials Blizzard re-authored). Flags are retained.
|
|
The Source word after the flag pair is the priority plane unless it already
|
|
is the cutout shader word 16; the native shader word is 0x10 for every
|
|
non-opaque blend mode plus 0x80 for an environment-mapped coordinate set.
|
|
Two-texture batches are a different contract and are not covered.
|
|
"""
|
|
if len(batch) != 13 or batch[8] != 1:
|
|
return None
|
|
word = batch[2]
|
|
priority = batch[1] if (word == 16 or batch[1]) else (word - 65536 if word > 32767 else word)
|
|
if (batch[1] and word not in (0, 16)) or not -128 <= priority <= 127:
|
|
return None
|
|
return batch[0], priority, (0x80 if environment_coordinates else 0) | (0x10 if blend else 0)
|
|
|
|
|
|
def two_texture_batch(batch, blend0, blend1, env0, env1, second_set1):
|
|
"""Native (flags, priority plane, shader word) for one two-texture (op count 2) Source256 batch.
|
|
|
|
Source256 stores no shader word (the legacy client derived one at run time). Rule from the
|
|
Blizzard-converted native weapon/shield models of the 70334 store (claude-lane
|
|
item-displays-20261123/shader-two-texture-rule.md): opaque base + environment-mapped second
|
|
layer is a 0x8000 effect by the second layer's blend (alpha 2 -> 0x8000 Opaque_Mod2xNA_Alpha,
|
|
add 4 -> 0x8001 Opaque_AddAlpha) and 0xE (Opaque_Mod2xNA, T2 env) for opaque/mod2x/missing
|
|
second materials; a non-env second layer is the combiner nibble (0 opaque, 6 Mod2xNA) plus 0x4000
|
|
when it reads texture coordinate set 1. Uncovered combinations return None (still held).
|
|
"""
|
|
if len(batch) != 13 or batch[8] != 2 or env0:
|
|
return None
|
|
word = batch[2]
|
|
priority = batch[1] if (word == 16 or batch[1]) else (word - 65536 if word > 32767 else word)
|
|
if (batch[1] and word not in (0, 16, batch[1])) or not -128 <= priority <= 127:
|
|
return None
|
|
if blend0 == 0 and env1:
|
|
shader = {2: 0x8000, 4: 0x8001, 6: 0xE, 0: 0xE, None: 0xE}.get(blend1)
|
|
elif blend0 == 0:
|
|
shader = {0: 0x0, 6: 0x6, None: 0x0}.get(blend1)
|
|
if shader is not None and second_set1: shader |= 0x4000
|
|
elif blend0 == 2 and not env1 and not second_set1:
|
|
shader = {2: 0x11, None: 0x10}.get(blend1)
|
|
else:
|
|
shader = None
|
|
return None if shader is None else (batch[0], priority, shader)
|
|
|
|
|
|
def convert_equipment(raw, *, allow_qualified_cutout_shader16=False, paired_single_texture_rule=False, convert_ribbons=False, convert_particles=False, downgrade_hermite=False, creature=False, convert_uv_animation=False, convert_lights=False, resample_step_visibility=False, drop_unreachable_events=False, two_texture_rule=False, legacy_replaceable_types=False, character=False, editor_preview_resample_pre_window=False):
|
|
# character: opt-in for Source256 playable bodies (replaceable types 1 body, 2 cape, 6 hair, 8 skin extra; native
|
|
# character models use the same enum; cameras stripped by caller).
|
|
# creature: opt-in for Source256 creature/mount bodies. Allows global flag 0x1
|
|
# (tilt X, identical meaning in native, e.g. native drakemount 0x202081) and the
|
|
# monster skin replaceable types 11-13 (one declared texture each). Portrait
|
|
# cameras are not converted: the caller strips them (count 0) first.
|
|
if type(creature) is not bool:raise ValueError('Explicit creature opt-in required')
|
|
source=model(raw)
|
|
if not source['old']:raise ValueError('Source256/257 equipment required')
|
|
if len(source['vertices'])>65535:raise ValueError('Equipment needs explicit multi-skin vertex splitting')
|
|
def pair(offset):return struct.unpack_from('<II',raw,offset)
|
|
def source_array(offset,stride):
|
|
count,at=pair(offset);return count,_extent(raw,at,count,stride,324)
|
|
# Source256: extra lookup108, texture transforms116, replaceable lookup124.
|
|
# The old local renderer header skipped124 instead of108. Independent
|
|
# pywowlib M2Header's pre-WotLK layout plus actual source lookup values
|
|
# establish this order; do not copy that renderer's misplaced skip.
|
|
for name,offset in (('UV animation',116),('lights',284),('cameras',292),('camera lookup',300),('ribbons',308),('particles',316)):
|
|
if pair(offset)[0] and not (name=='ribbons' and convert_ribbons) and not (name=='particles' and convert_particles) and not (name=='UV animation' and convert_uv_animation) and not (name=='lights' and convert_lights):raise ValueError('Unsupported source equipment feature: '+name)
|
|
if struct.unpack_from('<I',raw,16)[0] & ~(1 if creature else 0):raise ValueError('Unreviewed source model global flags')
|
|
material_count,material_data=source_array(132,4)
|
|
if any(blend>6 for flags,blend in struct.iter_unpack('<HH',material_data)):
|
|
raise ValueError('Unreviewed source material blend mode')
|
|
texture_count,texture_data=source_array(92,16)
|
|
if texture_count>32768:raise ValueError('Native signed texture-index bound')
|
|
texture_lookup_count,texture_lookup_data=source_array(148,2)
|
|
if any(index>=texture_count for(index,)in struct.iter_unpack('<H',texture_lookup_data)):
|
|
raise ValueError('Invalid source texture lookup')
|
|
texture_types=[kind for kind,flags,length,offset in struct.iter_unpack('<4I',texture_data)]
|
|
# legacy_replaceable_types: Source256 equipment also declares type 1 (skin), 3 (weapon blade) and 4 (weapon handle)
|
|
# slots; native 70334 item models keep the same enum (e.g. polearm_2h_emeralddreamoutdoor_d_01 types 3/4,
|
|
# shield_epic_b_01 type 1), so they pass through unchanged.
|
|
allowed=(0,2,11,12,13)if creature else((0,1,2,6,8)if character else((0,1,2,3,4)if legacy_replaceable_types else(0,2)))
|
|
if any(kind not in allowed for kind in texture_types):raise ValueError('Unreviewed source replaceable texture type')
|
|
if creature and any(texture_types.count(kind)>1 for kind in(11,12,13)):raise ValueError('Multiple creature skin slots per type')
|
|
# Native controls map texture TYPE -> declared texture index. Legacy
|
|
# equipment often leaves this array empty; copying that empty header lets
|
|
# the mesh load but prevents item materials reaching replaceable type2.
|
|
used={index for(index,)in struct.iter_unpack('<H',texture_lookup_data)}
|
|
replacement_count,replacement_data=source_array(124,2)
|
|
if replacement_count>32767:raise ValueError('Native replaceable lookup bound')
|
|
source_replacement=list(struct.unpack('<'+'h'*replacement_count,replacement_data))
|
|
# Native controls index texture TYPE -> texture index. Source tables also
|
|
# contain entries for unused types (including non-native indices). Retain
|
|
# them in provenance, not in target engine memory. Keep the already tested
|
|
# declaration-derived mapping for empty/all-zero source lookup tables.
|
|
explicit_source_binding=bool(any(replacement_data))
|
|
replacement=[-1]*(max(texture_types)+1)if texture_types else []
|
|
for kind in set(texture_types):
|
|
candidates=[i for i,t in enumerate(texture_types)if t==kind]
|
|
active=[i for i in candidates if i in used]
|
|
if kind==2 and active and explicit_source_binding:
|
|
if len(source_replacement)<=kind or source_replacement[kind]not in active:
|
|
raise ValueError('Source active replaceable binding differs from declared textures')
|
|
replacement[kind]=source_replacement[kind]
|
|
else:
|
|
if kind==2 and len(active)>1:raise ValueError('Multiple active replaceable slots need material conversion')
|
|
replacement[kind]=active[0]if kind==2 and active else candidates[-1]
|
|
coord_count,coord_lookup_data=source_array(156,2)
|
|
transparency_count,_=source_array(164,2)
|
|
uv_count,_=source_array(172,2)
|
|
count,offset=pair(108);unknown=_extent(raw,offset,count,2,324)
|
|
if any(unknown):raise ValueError('Unreviewed nonzero legacy extra lookup')
|
|
count,offset=pair(28)
|
|
sequences=_extent(raw,offset,count,68,324)
|
|
if not 1<=count<=4096:raise ValueError('Actual equipment animation sequence required')
|
|
windows=[struct.unpack_from('<II',sequences,i*68+4)for i in range(count)]
|
|
if any(end<start for start,end in windows):raise ValueError('Invalid animation window')
|
|
out=bytearray(raw)
|
|
# Keep old payload addresses valid. Rewrite only the native304-byte header;
|
|
# twenty reserved bytes remain before the original body data starting324.
|
|
header=raw[:44]+raw[52:80]+raw[84:108]+raw[116:324]
|
|
if len(header)!=304:raise ValueError('Native header assembly width')
|
|
out[:304]=header;struct.pack_into('<I',out,4,272)
|
|
def append(data):
|
|
out.extend(bytes((-len(out))%16));offset=len(out);out.extend(data)
|
|
if len(out)>67108864:raise ValueError('Converted equipment size bound')
|
|
return offset
|
|
def array(header_offset,count,data):
|
|
struct.pack_into('<II',out,header_offset,count,append(data)if count else 0)
|
|
normalized_texture_names=[];native_texture_rows=[]
|
|
for i,(kind,flags,length,at)in enumerate(struct.iter_unpack('<4I',texture_data)):
|
|
if length and raw[at+length-1]!=0:
|
|
name=raw[at:at+length]+b'\0'
|
|
native_texture_rows.append(struct.pack('<4I',kind,flags,len(name),append(name)))
|
|
normalized_texture_names.append(i)
|
|
else:native_texture_rows.append(texture_data[i*16:(i+1)*16])
|
|
if normalized_texture_names:array(80,texture_count,b''.join(native_texture_rows))
|
|
array(104,len(replacement),struct.pack('<'+'h'*len(replacement),*replacement))
|
|
native_sequences=[]
|
|
repaired_alias_links = []
|
|
for i,(start,end)in enumerate(windows):
|
|
sequence=sequences[i*68:(i+1)*68]
|
|
variation_next, alias_next = struct.unpack_from('<hH', sequence, 64)
|
|
if not -1 <= variation_next < count:
|
|
raise ValueError(f'Sequence {i}: variationNext {variation_next} outside table of {count}')
|
|
if alias_next >= count:
|
|
flags = struct.unpack_from('<I', sequence, 16)[0]
|
|
if flags & 0x40:
|
|
raise ValueError(f'Alias sequence {i}: aliasNext {alias_next} outside table of {count}')
|
|
# The client can follow this field even on an ordinary sequence.
|
|
repaired_alias_links.append((i, alias_next))
|
|
sequence = sequence[:66] + struct.pack('<H', i)
|
|
native_sequences.append(sequence[:4]+struct.pack('<I',end-start)+sequence[12:])
|
|
array(28,count,b''.join(native_sequences))
|
|
global_count,global_offset=pair(20);_extent(raw,global_offset,global_count,4,324)
|
|
tracks=[]
|
|
def track(at,kind,label):
|
|
try:header,audit=convert_track(raw,at,kind,windows,out,global_sequence_count=global_count,downgrade_untangented_hermite=downgrade_hermite,resample_step_visibility=resample_step_visibility,editor_preview_resample_pre_window=editor_preview_resample_pre_window)
|
|
except ValueError as e:raise ValueError(f'{e} [{label}]') from None
|
|
tracks.append(dict(label=label,**audit));return header
|
|
# Source M2Color is vec3 + fixed16 tracks (28+28 bytes); native uses
|
|
# the same meanings in two20-byte array-of-array tracks. Reuse the exact
|
|
# timestamp/range/key conversion used by bones and opacity; never flatten
|
|
# an animated tint into a guessed constant or discard its alpha track.
|
|
color_count,color_offset=pair(84)
|
|
_extent(raw,color_offset,color_count,56,324)
|
|
if color_count>32767:raise ValueError('Native signed color-index bound')
|
|
array(72,color_count,b''.join(track(color_offset+i*56,'vec3',f'color:{i}:rgb')+
|
|
track(color_offset+i*56+28,'fixed16',f'color:{i}:alpha')for i in range(color_count)))
|
|
count,offset=pair(52);bones=_extent(raw,offset,count,108,324);native_bones=[]
|
|
if count>4096:raise ValueError('Equipment bone count bound')
|
|
for i in range(count):
|
|
at=offset+i*108;b= bones[i*108:(i+1)*108]
|
|
native_bones.append(b[:12]+bytes(4)+b''.join(track(at+12+j*28,kind,f'bone:{i}:{j}')for j,kind in enumerate(('vec3','quaternion','vec3')))+b[96:108])
|
|
array(44,count,b''.join(native_bones))
|
|
count,offset=pair(100);_extent(raw,offset,count,28,324)
|
|
array(88,count,b''.join(track(offset+i*28,'fixed16',f'opacity:{i}')for i in range(count)))
|
|
# Source256 M2TextureTransform: translation vec3, rotation float quaternion, scaling vec3 (3*28 bytes).
|
|
# Native272 keeps the same three tracks (3*20 bytes); texture-transform rotation stays a float C4Quaternion
|
|
# (only bone rotations are compressed).
|
|
count,offset=pair(116);_extent(raw,offset,count,84,324)
|
|
if count:array(96,count,b''.join(track(offset+i*84,'vec3',f'uv:{i}:translation')+track(offset+i*84+28,'quat32',f'uv:{i}:rotation')+
|
|
track(offset+i*84+56,'vec3',f'uv:{i}:scaling')for i in range(count)))
|
|
# Source256 M2Light (212 bytes): type u16, bone i16, position vec3, then ambient colour vec3, ambient intensity
|
|
# float, diffuse colour vec3, diffuse intensity float, attenuation start float, attenuation end float,
|
|
# visibility u8 tracks. Native272 keeps the same order with 20-byte tracks (156 bytes).
|
|
count,offset=pair(284);lights=_extent(raw,offset,count,212,324)
|
|
if count:array(264,count,b''.join(lights[i*212:i*212+16]+b''.join(track(offset+i*212+16+j*28,kind,f'light:{i}:{j}')for j,kind in
|
|
enumerate(('vec3','float32','vec3','float32','float32','float32','visibility')))for i in range(count)))
|
|
count,offset=pair(260);attachments=_extent(raw,offset,count,48,324)
|
|
array(240,count,b''.join(attachments[i*48:i*48+20]+track(offset+i*48+20,'visibility',f'attachment:{i}')for i in range(count)))
|
|
# Source256 M2Ribbon is 220 bytes: id, bone, position, texture-index array,
|
|
# material-index array (36), then colour vec3 / alpha fixed16 / height-above
|
|
# float / height-below float tracks (4*28), edges per second, edge lifetime,
|
|
# gravity, texture rows+columns (16), texture-slot uint16 and visibility
|
|
# tracks (2*28). Native272 keeps every field in the same order with 20-byte
|
|
# tracks and one trailing priority-plane pair (176 bytes). Index arrays keep
|
|
# their original body addresses. Verified against Blizzard's own conversion
|
|
# of ribbon models present in both clients (claude-lane ribbon pair check).
|
|
ribbon_count,ribbon_offset=pair(308);ribbons=_extent(raw,ribbon_offset,ribbon_count,220,324);native_ribbons=[]
|
|
def ribbon_visibility(at,i):
|
|
# Blizzard's converted ribbons carry an EMPTY visibility track wherever
|
|
# the Source track is the single always-visible key (121 of 121 paired
|
|
# ribbons); keep that representation, convert every other track fully.
|
|
interpolation,global_id,nr,ro,nt,to,nk,ko=struct.unpack_from('<Hh6I',raw,at)
|
|
if global_id==-1 and nr==0 and nt==1 and nk==1 and _extent(raw,to,1,4,324)==bytes(4) and _extent(raw,ko,1,1,324)==b'\x01':
|
|
tracks.append(dict(label=f'ribbon:{i}:visibility',kind='visibility',always_visible_as_empty_native_track=True))
|
|
return struct.pack('<Hh4I',interpolation,-1,0,0,0,0)
|
|
return track(at,'visibility',f'ribbon:{i}:visibility')
|
|
if ribbon_count>256:raise ValueError('Equipment ribbon count bound')
|
|
for i in range(ribbon_count):
|
|
at=ribbon_offset+i*220;r=ribbons[i*220:(i+1)*220]
|
|
if struct.unpack_from('<I',r,4)[0]>=pair(52)[0]:raise ValueError('Ribbon bone outside source skeleton')
|
|
tn,to=struct.unpack_from('<II',r,20);mn,mo=struct.unpack_from('<II',r,28)
|
|
if any(v>=texture_count for(v,)in struct.iter_unpack('<H',_extent(raw,to,tn,2,324))):raise ValueError('Ribbon texture outside source textures')
|
|
if any(v>=material_count for(v,)in struct.iter_unpack('<H',_extent(raw,mo,mn,2,324))):raise ValueError('Ribbon material outside source materials')
|
|
if not all(math.isfinite(v)for v in struct.unpack_from('<3f',r,8)+struct.unpack_from('<3f',r,148)):raise ValueError('Nonfinite ribbon constant')
|
|
native_ribbons.append(r[:36]+track(at+36,'vec3',f'ribbon:{i}:color')+track(at+64,'fixed16',f'ribbon:{i}:alpha')+
|
|
track(at+92,'float32',f'ribbon:{i}:above')+track(at+120,'float32',f'ribbon:{i}:below')+r[148:164]+
|
|
track(at+164,'uint16',f'ribbon:{i}:texture-slot')+ribbon_visibility(at+192,i)+bytes(4))
|
|
if ribbon_count:array(288,ribbon_count,b''.join(native_ribbons))
|
|
particle_count,particle_offset=pair(316);_extent(raw,particle_offset,particle_count,504,324)
|
|
if particle_count>256:raise ValueError('Equipment particle emitter count bound')
|
|
if particle_count:
|
|
array(296,particle_count,b''.join(native_particle_emitter(raw,particle_offset+i*504,
|
|
lambda at,kind,name,i=i:track(at,kind,f'particle:{i}:{name}'),append,pair(52)[0],texture_count)for i in range(particle_count)))
|
|
count,offset=pair(276);events=_extent(raw,offset,count,44,324);native_events=[];event_audits=[]
|
|
for i in range(count):
|
|
event=events[i*44:(i+1)*44]
|
|
interpolation,global_id,nr,ro,nt,to=struct.unpack_from('<Hh4I',event,24)
|
|
# Events are timestamp-only; character bodies carry one stray interpolation 1 ($CSD), written natively as 0.
|
|
if (interpolation and not character) or global_id!=-1:raise ValueError('Unreviewed equipment event timing contract')
|
|
ranges=list(struct.iter_unpack('<II',_extent(raw,ro,nr,8,324)))
|
|
unused_default_ranges=[]
|
|
# Original source7195dc..7195e9 indexes the range table with the
|
|
# active source animation index; it does not enumerate its count.
|
|
# Some source equipment retains one empty range after all sequences.
|
|
# This is an unreachable default, not another animation or a key.
|
|
if nr>len(windows) and all(r==(0,0) for r in ranges[len(windows):]):
|
|
unused_default_ranges=[list(r) for r in ranges[len(windows):]];del ranges[len(windows):]
|
|
if len(ranges)!=len(windows):raise ValueError('Unreviewed equipment event timing contract')
|
|
times=list(struct.unpack('<'+'I'*nt,_extent(raw,to,nt,4,324)))
|
|
arrays=[];policies=[]
|
|
for (begin,end),(start,stop)in zip(ranges,windows):
|
|
# Events use exclusive ends, distinct from bone/key inclusive ranges.
|
|
# Keyless events (nt 0) keep a stale (0,1) legacy range in some Source256 equipment; nothing is selectable.
|
|
if drop_unreachable_events and nt==0 and (begin,end)==(0,1):begin=end=0
|
|
if not 0<=begin<=end<=nt:raise ValueError('Invalid exclusive event range')
|
|
selected=times[begin:end]
|
|
if all(start<=v<=stop for v in selected):
|
|
selected=[v-start for v in selected];policies.append('absolute-window-to-relative')
|
|
elif all(0<=v<=stop-start for v in selected):policies.append('source-already-relative')
|
|
elif creature or drop_unreachable_events:
|
|
# Creature bodies (and opted-in equipment): keep keys inside this sequence's window (relative), drop strays
|
|
# that no sequence of this model can reach.
|
|
kept=[v-start for v in selected if start<=v<=stop]
|
|
policies.append(f'creature-window-filter:{len(selected)-len(kept)}-dropped');selected=kept
|
|
else:raise ValueError('Equipment event outside animation window/duration')
|
|
if any(a>b for a,b in zip(selected,selected[1:])):raise ValueError('Unordered event timestamps')
|
|
arrays.append(struct.pack('<II',len(selected),append(struct.pack('<'+'I'*len(selected),*selected))if selected else 0))
|
|
native_events.append(event[:24]+struct.pack('<HhII',0,-1,len(arrays),append(b''.join(arrays))))
|
|
audit=dict(event_id_hex=event[:4].hex(),timing=policies,engine_effect_verified=False)
|
|
if unused_default_ranges:audit['unused_default_ranges']=unused_default_ranges
|
|
event_audits.append(audit)
|
|
array(256,count,b''.join(native_events))
|
|
skins=[];skin_audits=[]
|
|
for view in range(source['view_count']):
|
|
source_skin=skin(source,view=view);values=source_skin['header'];arrays=source_skin['arrays']
|
|
# Native272/274 SKIN has an extra count/offset pair at48, not vertex
|
|
# bytes there. Keep its absent shadow-batch array explicitly zero.
|
|
native=bytearray(b'SKIN'+bytes(60))
|
|
def skin_array(at,count,data):
|
|
native.extend(bytes((-len(native))%16));offset=len(native)
|
|
struct.pack_into('<II',native,at,count,offset if count else 0);native.extend(data)
|
|
for at,k,data in ((4,0,arrays[0]),(12,2,arrays[1]),(20,4,arrays[2])):
|
|
skin_array(at,values[k],data)
|
|
vertices=source['vertices'];indices=[x[0]for x in struct.iter_unpack('<H',arrays[0])]
|
|
submeshes=[]
|
|
for i in range(values[6]):
|
|
row=arrays[3][i*32:(i+1)*32];fields=struct.unpack_from('<10H',row)
|
|
_,_,begin,nverts,first,ntris,*_=fields
|
|
if not nverts or begin+nverts>len(indices)or first+ntris>values[2]:raise ValueError('Invalid equipment submesh ranges')
|
|
points=[struct.unpack_from('<3f',vertices[j])for j in indices[begin:begin+nverts]]
|
|
center=tuple(struct.unpack('<f',struct.pack('<f',(min(p[k]for p in points)+max(p[k]for p in points))*.5))[0]for k in range(3))
|
|
radius=max(math.dist(center,p)for p in points)
|
|
if not math.isfinite(radius)or radius>3.4028234663852886e38:
|
|
raise ValueError('Unrepresentable equipment submesh sphere')
|
|
# A derived bounding sphere must enclose the actual vertices after
|
|
# float32 serialization; round radius upward rather than clipping.
|
|
radius=struct.unpack('<f',struct.pack('<f',radius))[0]
|
|
if any(math.dist(center,p)>radius for p in points):
|
|
radius=struct.unpack('<f',struct.pack('<I',struct.unpack('<I',struct.pack('<f',radius))[0]+1))[0]
|
|
submeshes.append(row+struct.pack('<4f',*center,radius))
|
|
skin_array(28,values[6],b''.join(submeshes))
|
|
native_batch_data = bytearray(arrays[4])
|
|
qualified_cutout_batches = 0
|
|
paired_rule_batches = 0
|
|
for batch_index, b in enumerate(source_skin['summary']['batch_rows']):
|
|
qualified_cutout = (allow_qualified_cutout_shader16
|
|
and _qualified_cutout_shader16_batch(raw, source_skin, b))
|
|
paired=None
|
|
if paired_single_texture_rule and not qualified_cutout and b[8]==1 and b[3]<values[6] and b[4]<values[6] and b[6]<material_count and b[10]<coord_count:
|
|
paired=paired_single_texture_batch(b,struct.unpack_from('<HH',material_data,b[6]*4)[1],
|
|
struct.unpack_from('<h',coord_lookup_data,b[10]*2)[0]==-1)
|
|
two=None
|
|
if two_texture_rule and paired is None and not qualified_cutout and b[8]==2 and b[3]<values[6] and b[4]<values[6] and b[6]<material_count and b[10]<coord_count:
|
|
cl=lambda k:struct.unpack_from('<h',coord_lookup_data,(b[10]+k)*2)[0] if b[10]+k<coord_count else None
|
|
bl=lambda k:struct.unpack_from('<HH',material_data,(b[6]+k)*4)[1] if b[6]+k<material_count else None
|
|
two=two_texture_batch(b,bl(0),bl(1),cl(0)==-1,cl(1)==-1,cl(1)==1)
|
|
if two is not None:paired=two
|
|
if paired is None and not qualified_cutout and (b[0]not in(0,16)or b[1]or b[2]or b[8]!=1 or b[3]>=values[6]or b[4]>=values[6]):
|
|
raise ValueError('Equipment batch requires unreviewed shader/material conversion')
|
|
if (b[5]!=65535 and b[5]>=color_count) or b[6]>=material_count or b[9]>=texture_lookup_count or b[10]>=coord_count or b[11]>=transparency_count or b[12]>=uv_count:
|
|
raise ValueError('Unresolved source batch material binding')
|
|
if qualified_cutout:
|
|
struct.pack_into('<H', native_batch_data, batch_index * 24 + 2, 16)
|
|
qualified_cutout_batches += 1
|
|
elif paired is not None:
|
|
struct.pack_into('<BbH', native_batch_data, batch_index * 24, *paired)
|
|
paired_rule_batches += 1
|
|
skin_array(36,values[8],bytes(native_batch_data))
|
|
# Modern272/274 field44 is the LOD vertex base. These legacy views all
|
|
# reference the original global buffer; copying old boneMax21 would
|
|
# incorrectly shift every vertex reference. Preserve boneMax in audit.
|
|
struct.pack_into('<I',native,44,0);skins.append(bytes(native))
|
|
checked=skin(model(bytes(out)),bytes(native))
|
|
if source_skin['faces']!=checked['faces']:raise ValueError('Equipment topology preservation failed')
|
|
skin_audits.append(dict(view=view,source_batches=values[8], qualified_cutout_shader16_batches=qualified_cutout_batches,paired_single_texture_rule_batches=paired_rule_batches,native_batches=values[8],
|
|
oriented_full_vertex_triangles_preserved=True,shader_pass_optimization=False,
|
|
native_header_bytes=64,native_lod_vertex_base=0,
|
|
legacy_bone_count_max=values[10],shadow_batches_converted=False,
|
|
material_engine_verified=False,sha256=hashlib.sha256(native).hexdigest()))
|
|
if not skins:raise ValueError('Equipment source has no skin views')
|
|
if model(bytes(out))['vertices']!=source['vertices']:raise ValueError('Equipment vertex preservation failed')
|
|
out,sequence_storage=mark_generated_inline_sequences(bytes(out))
|
|
out,collision_bounds=canonicalize_geometry_reversed_collision_bounds(out)
|
|
report=dict(kind='source-equipment-native-structure-stage',source_sha256=hashlib.sha256(raw).hexdigest(),
|
|
native_body_sha256=hashlib.sha256(out).hexdigest(),source_version=source['summary']['md20_version'],target_body_version=272,
|
|
repaired_alias_links=repaired_alias_links,
|
|
tracks=tracks,events=event_audits,skins=skin_audits,sequence_storage=sequence_storage,collision_bounds=collision_bounds,legacy_extra_lookup_zero_verified=True,
|
|
normalized_length_bounded_texture_names=normalized_texture_names,
|
|
source_replaceable_lookup=source_replacement,
|
|
source_replaceable_lookup_policy='active-type-binding-checked; unused-source-entries-provenance-only',
|
|
structural_conversion_complete=True,registered_dependencies_complete=False,
|
|
material_engine_verified=False,installed=False,engine_loaded=False)
|
|
return bytes(out),skins,report
|
|
|
|
|
|
def canonicalize_equivalent_rigid_views(raw, body, skins):
|
|
"""Reduce proved identical rigid hardware profiles to one native view.
|
|
|
|
This is opt-in and consumes already converted bodies/skins. It does not
|
|
turn legacy bone-cap profiles into modern spatial LODs. Each authored draw
|
|
must have the same full vertices, rigid weights, resolved bone palette,
|
|
material batch, mesh roles and oriented triangles in every source view.
|
|
"""
|
|
source=model(raw)
|
|
if not source['old'] or not 2<=source['view_count']<=4:
|
|
raise ValueError('Bounded legacy rigid hardware views required')
|
|
if len(skins)!=source['view_count'] or model(body)['view_count']!=source['view_count']:
|
|
raise ValueError('Passed complete native view conversion required')
|
|
if model(body)['vertices']!=source['vertices']:
|
|
raise ValueError('Converted rigid-view vertices differ')
|
|
count,at=struct.unpack_from('<II',raw,140)
|
|
lookup=list(struct.unpack('<'+'H'*count,_extent(raw,at,count,2,324)))
|
|
states=[];audits=[]
|
|
for view in range(source['view_count']):
|
|
parsed=skin(source,view=view)
|
|
indices=[r[0]for r in struct.iter_unpack('<H',parsed['arrays'][0])]
|
|
triangles=[r[0]for r in struct.iter_unpack('<H',parsed['arrays'][1])]
|
|
properties=list(struct.iter_unpack('<4B',parsed['arrays'][2]))
|
|
if len(properties)!=len(indices) or len(set(properties))!=1:
|
|
raise ValueError('Unproved rigid skin property mapping')
|
|
meshes=list(struct.iter_unpack('<10H3f',parsed['arrays'][3]));draws=[]
|
|
for batch in parsed['summary']['batch_rows']:
|
|
if batch[3]!=batch[4] or batch[3]>=len(meshes):
|
|
raise ValueError('Unproved rigid draw submesh mapping')
|
|
mesh=meshes[batch[3]]
|
|
if mesh[6]!=1 or mesh[8]!=1 or mesh[7]>=len(lookup):
|
|
raise ValueError('Rigid view requires a single resolved bone')
|
|
bone=lookup[mesh[7]]
|
|
if bone>=source['bone_count'] or mesh[9]>=source['bone_count']:
|
|
raise ValueError('Rigid view bone outside authored skeleton')
|
|
faces=[]
|
|
if mesh[5]%3 or mesh[4]+mesh[5]>len(triangles):
|
|
raise ValueError('Invalid rigid draw triangle extent')
|
|
for t in range(mesh[4],mesh[4]+mesh[5],3):
|
|
face=[]
|
|
for index in triangles[t:t+3]:
|
|
if not mesh[2]<=index<mesh[2]+mesh[3]:
|
|
raise ValueError('Rigid draw references another vertex partition')
|
|
vertex=source['vertices'][indices[index]]
|
|
weights=vertex[12:16];bones=vertex[16:20]
|
|
if sum(weights)!=255 or weights.count(255)!=1:
|
|
raise ValueError('Weighted skin cannot use rigid view canonicalization')
|
|
if any(weight and (bones[k] or properties[index][k])for k,weight in enumerate(weights)):
|
|
raise ValueError('Unproved rigid vertex bone mapping')
|
|
face.append((vertex.hex(),tuple(bone if weight else None for weight in weights),tuple(properties[index])))
|
|
face=tuple(face);faces.append(min(face,face[1:]+face[:1],face[2:]+face[:2]))
|
|
# Keep raw IDs/level, influences/center bone and all center float
|
|
# bits. Only index partition coordinates and palette offset vary.
|
|
start=batch[3]*32;mesh_raw=parsed['arrays'][3][start:start+32]
|
|
draws.append((tuple(batch),mesh_raw[:4].hex()+mesh_raw[16:32].hex(),bone,tuple(sorted(Counter(faces).items()))))
|
|
state=tuple(draws)
|
|
if states and state!=states[0]:raise ValueError('Authored rigid views have different rendered attributes')
|
|
states.append(state)
|
|
audits.append(dict(source_view=view,legacy_bone_cap=parsed['header'][10],draw_count=len(draws),
|
|
complete_render_state_sha256=hashlib.sha256(repr(state).encode()).hexdigest()))
|
|
output=bytearray(body);struct.pack_into('<I',output,68,1)
|
|
audit=dict(kind='complete-equivalent-rigid-hardware-view-canonicalization',authored_view_count=source['view_count'],
|
|
native_view_count=1,retained_source_view=0,authored_views=audits,
|
|
exact_single_lane_weight=255,uniform_skin_properties=True,
|
|
all_vertices_weights_resolved_bones_materials_and_oriented_draws_equal=True,
|
|
spatial_LOD_inferred=False,source_skeleton_animation_events_unchanged=True,
|
|
source_body_sha256=hashlib.sha256(body).hexdigest(),native_body_sha256=hashlib.sha256(output).hexdigest(),
|
|
native_resource_contract='existing single-view equipment; LodCount0, one SFID',engine_verified=False)
|
|
return bytes(output),[skins[0]],audit
|
|
|
|
|
|
def batch(manifest_path,output=None,*,canonicalize_rigid_views=False,allow_qualified_cutout_shader16=False,paired_single_texture_rule=False,convert_ribbons=False,convert_particles=False,downgrade_hermite=False,creature=False,convert_uv_animation=False,convert_lights=False,resample_step_visibility=False,drop_unreachable_events=False,two_texture_rule=False,legacy_replaceable_types=False,character=False):
|
|
"""Consume the existing source-asset extractor manifest, preserving candidates."""
|
|
if type(canonicalize_rigid_views)is not bool:raise ValueError('Explicit rigid-view policy required')
|
|
if manifest_path.is_symlink()or not manifest_path.is_file()or manifest_path.stat().st_size>8388608:
|
|
raise ValueError('Regular bounded source asset manifest required')
|
|
if type(allow_qualified_cutout_shader16) is not bool:raise ValueError('Explicit qualified cutout shader16 opt-in required')
|
|
if type(paired_single_texture_rule) is not bool:raise ValueError('Explicit paired single-texture rule opt-in required')
|
|
if type(convert_ribbons) is not bool:raise ValueError('Explicit ribbon conversion opt-in required')
|
|
if type(convert_particles) is not bool:raise ValueError('Explicit particle conversion opt-in required')
|
|
if type(downgrade_hermite) is not bool:raise ValueError('Explicit Hermite downgrade opt-in required')
|
|
manifest_raw=manifest_path.read_bytes();manifest=json.loads(manifest_raw)
|
|
matches=manifest.get('matches')
|
|
if not isinstance(matches,list)or not 1<=len(matches)<=4096:
|
|
raise ValueError('Bounded source asset candidates required')
|
|
jobs={};total_bytes=0
|
|
for row in matches:
|
|
if not isinstance(row,dict)or not isinstance(row.get('member'),str):raise ValueError('Source asset candidate required')
|
|
if not row['member'].endswith('.m2'):continue
|
|
sha=row.get('sha256');filename=row.get('file')
|
|
if not isinstance(sha,str)or not re.fullmatch('[0-9a-f]{64}',sha)or filename!=sha+'.m2':
|
|
raise ValueError('Pinned source model filename/hash required')
|
|
path=manifest_path.parent/filename
|
|
if path.is_symlink()or not path.is_file()or not 324<=path.stat().st_size<=67108864:
|
|
raise ValueError('Regular bounded source model required')
|
|
if sha not in jobs:
|
|
total_bytes+=path.stat().st_size
|
|
if total_bytes>268435456:raise ValueError('Source model batch byte bound')
|
|
raw=path.read_bytes()
|
|
if hashlib.sha256(raw).hexdigest()!=sha:raise ValueError('Source model bytes changed')
|
|
if sha not in jobs:jobs[sha]=dict(raw=raw,candidates=[])
|
|
jobs[sha]['candidates'].append(dict(member=row['member'],archive=row.get('archive')))
|
|
if not jobs:raise ValueError('No source model candidates')
|
|
if output is not None:output.mkdir(parents=True,exist_ok=False)
|
|
results=[]
|
|
for sha,job in sorted(jobs.items()):
|
|
try:
|
|
body,skins,report=convert_equipment(job['raw'],allow_qualified_cutout_shader16=allow_qualified_cutout_shader16,paired_single_texture_rule=paired_single_texture_rule,convert_ribbons=convert_ribbons,convert_particles=convert_particles,downgrade_hermite=downgrade_hermite,creature=creature,convert_uv_animation=convert_uv_animation,convert_lights=convert_lights,resample_step_visibility=resample_step_visibility,drop_unreachable_events=drop_unreachable_events,two_texture_rule=two_texture_rule,legacy_replaceable_types=legacy_replaceable_types,character=character)
|
|
if canonicalize_rigid_views and len(skins)>1:
|
|
body,skins,audit=canonicalize_equivalent_rigid_views(job['raw'],body,skins)
|
|
report['rigid_view_canonicalization']=audit
|
|
report['authored_skin_audits']=report['skins'];report['skins']=report['skins'][:1]
|
|
report['native_body_sha256']=hashlib.sha256(body).hexdigest()
|
|
payloads=[(sha+'.md20','native-body-needs-registered-container-bindings',body)]
|
|
payloads.extend((sha+f'-{i:02}.skin','native-skin',raw)for i,raw in enumerate(skins))
|
|
report['outputs']=[dict(file=name,role=role,bytes=len(data),sha256=hashlib.sha256(data).hexdigest())for name,role,data in payloads]
|
|
if output is not None:
|
|
for name,_,data in payloads:(output/name).write_bytes(data)
|
|
except ValueError as error:
|
|
report=dict(source_sha256=sha,blocked=str(error),structural_conversion_complete=False,installed=False)
|
|
report['source_candidates']=job['candidates'];results.append(report)
|
|
result=dict(kind='batch-equipment-native-structure-stage',
|
|
source_manifest_sha256=hashlib.sha256(manifest_raw).hexdigest(),
|
|
converter_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
|
track_converter_sha256=hashlib.sha256(Path(__file__).with_name('m2_track_convert.py').read_bytes()).hexdigest(),
|
|
records=results,converted_bodies=sum(r['structural_conversion_complete']for r in results),
|
|
blocked_bodies=sum(not r['structural_conversion_complete']for r in results),
|
|
installed=False,engine_loaded=False)
|
|
if output is not None:(output/'manifest.json').write_text(json.dumps(result,indent=2)+'\n')
|
|
return result
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--source-manifest',type=Path,required=True)
|
|
p.add_argument('--output',type=Path)
|
|
p.add_argument('--canonicalize-equivalent-rigid-views',action='store_true',help='Opt in to complete rigid draw equivalence before reducing legacy hardware profiles to the native single-view resource contract')
|
|
p.add_argument('--allow-qualified-cutout-shader16',action='store_true',help='Opt in to the proved Source cutout material class; retain all converter qualification checks')
|
|
p.add_argument('--paired-single-texture-rule',action='store_true',help='Opt in to the batch flag/priority/shader rule derived from Blizzard model pairs present in both clients')
|
|
p.add_argument('--convert-ribbons',action='store_true',help='Opt in to Source256 ribbon emitter conversion (220-byte records to native 176-byte records)')
|
|
p.add_argument('--convert-particles',action='store_true',help='Opt in to Source256 particle emitter conversion (504-byte records to native 492-byte records)')
|
|
p.add_argument('--downgrade-hermite',action='store_true',help='Represent tangent-free Hermite/Bezier tracks (nk==nt) with native linear interpolation')
|
|
p.add_argument('--creature',action='store_true',help='Opt in to Source256 creature/mount bodies (tilt flag, skin types 11-13; cameras stripped by caller)')
|
|
p.add_argument('--convert-uv-animation',action='store_true',help='Opt in to Source256 texture transforms (3x28-byte tracks to native 3x20)')
|
|
p.add_argument('--convert-lights',action='store_true',help='Opt in to Source256 lights (212-byte records to native 156-byte records)')
|
|
p.add_argument('--resample-step-visibility',action='store_true',help='Opt in to exact per-window resampling of step visibility tracks (particle enabled, ribbon visibility) whose ranges overlap or are absent')
|
|
p.add_argument('--drop-unreachable-events',action='store_true',help='Opt in to dropping equipment event keys outside every sequence window (creature rule)')
|
|
p.add_argument('--dry-run',action='store_true')
|
|
a=p.parse_args()
|
|
if a.dry_run==(a.output is not None):p.error('Select --dry-run or a new --output directory')
|
|
r=batch(a.source_manifest,a.output,canonicalize_rigid_views=a.canonicalize_equivalent_rigid_views,allow_qualified_cutout_shader16=a.allow_qualified_cutout_shader16,paired_single_texture_rule=a.paired_single_texture_rule,convert_ribbons=a.convert_ribbons,convert_particles=a.convert_particles,downgrade_hermite=a.downgrade_hermite,creature=a.creature,convert_uv_animation=a.convert_uv_animation,convert_lights=a.convert_lights,resample_step_visibility=a.resample_step_visibility,drop_unreachable_events=a.drop_unreachable_events)
|
|
print(json.dumps({k:r[k]for k in('converted_bodies','blocked_bodies','installed','engine_loaded')}))
|
|
|
|
|
|
if __name__=='__main__':main()
|