plugins/tools/plugin_resource_pack.py
unimatrixgit c9944bb832
Some checks failed
DuneRealms Plugin CI / plugins (push) Failing after 8m59s
Supplied Dune Item Art Build / supplied-item-art (push) Successful in 30s
Keep supplied source text in canonical Git line endings
2026-12-03 20:52:03 +01:00

260 lines
18 KiB
Python

"""Deterministic resource-pack assembly and dependency closure; never runs plugin/game code."""
import hashlib
import json
from pathlib import Path
import re
import struct
import urllib.request
import zipfile
import plugin_vanilla_art
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / 'network/resource-pack/central'
PACK_ID = 'c24c7cf5-a292-539d-971f-a96d8b838162'
VALID = re.compile(r'[a-z0-9_.-]+:[a-z0-9_./-]+\Z')
def encoded(value): return (json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))+'\n').encode()
def resource(value):
value = value if ':' in value else 'minecraft:'+value
if not VALID.fullmatch(value) or '..' in value.split(':')[1].split('/'): raise ValueError('Invalid resource ID: '+value)
return value.split(':', 1)
def path_for(value, kind, suffix='.json'):
ns, path = resource(value); return f'assets/{ns}/{kind}/{path}{suffix}'
def read_zip(path):
files = {}
with zipfile.ZipFile(path) as archive:
for item in archive.infolist():
name = item.filename
if item.is_dir(): continue
if name in files or name.startswith('/') or '\\' in name or '..' in name.split('/'):
raise ValueError('Unsafe/duplicate archive entry: '+name)
files[name] = archive.read(item)
return files
def client_assets(cache, supplied=None):
lock = json.loads((SOURCE/'inputs.lock.json').read_text(encoding='utf-8'))['client']
path = Path(supplied) if supplied else Path(cache)/'minecraft-26.3-client.jar'
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(lock['url'], timeout=60) as response: payload=response.read(lock['size']+1)
if len(payload)!=lock['size'] or hashlib.sha1(payload).hexdigest()!=lock['sha1']: raise ValueError('Official client download differs')
path.write_bytes(payload)
if path.stat().st_size!=lock['size'] or hashlib.sha1(path.read_bytes()).hexdigest()!=lock['sha1']: raise ValueError('Pinned client assets differ')
return {key:value for key,value in read_zip(path).items() if key.startswith('assets/')}
def strings_named(value, name):
if isinstance(value, dict):
for key, child in value.items():
if key==name and isinstance(child, str): yield child
else: yield from strings_named(child, name)
elif isinstance(value, list):
for child in value: yield from strings_named(child, name)
class Closure:
def __init__(self, pack, vanilla):
self.pack=pack; self.files=dict(vanilla, **pack); self.cache={}
def model(self, key, chain=()):
if key in chain: raise ValueError('Model parent cycle: '+key)
if key not in self.files: raise ValueError('Missing model: '+key)
obj=json.loads(self.files[key]); textures={}; elements=[]
parent=obj.get('parent')
if parent and not parent.split(':')[-1].startswith('builtin/'):
inherited, elements=self.model(path_for(parent,'models'),chain+(key,)); textures.update(inherited)
textures.update(obj.get('textures',{})); elements=obj.get('elements',elements)
if chain:return textures,elements
def resolve(ref, seen=()):
if isinstance(ref,dict): ref=ref['sprite']
if ref.startswith('#'):
name=ref[1:]
if name in seen or name not in textures: raise ValueError('Unresolved model texture variable: '+key+' '+ref)
return resolve(textures[name],seen+(name,))
if key=='assets/minecraft/models/block/air.json' and ref in ('missingno','minecraft:missingno') and not elements:return ref
target=path_for(ref,'textures','.png')
if target not in self.files: raise ValueError('Missing texture: '+target+' in '+key)
png=self.files[target]
if not png.startswith(b'\x89PNG\r\n\x1a\n') or len(png)<24: raise ValueError('Invalid PNG: '+target)
return ref
for ref in textures.values(): resolve(ref)
for element in elements:
span=[abs(b-a) for a,b in zip(element.get('from',[0,0,0]),element.get('to',[16,16,16]))]
for side,face in element.get('faces',{}).items():
axes={'north':(0,1),'south':(0,1),'east':(1,2),'west':(1,2),'up':(0,2),'down':(0,2)}.get(side)
if axes and span[axes[0]]*span[axes[1]]==0:continue
if 'texture' in face:
ref=face['texture'];resolve('#'+ref if isinstance(ref,str) and ref in textures else ref)
return textures,elements
def font(self,key,chain=()):
if key in chain: raise ValueError('Font reference cycle: '+key)
if key not in self.files: raise ValueError('Missing font: '+key)
for provider in json.loads(self.files[key]).get('providers',[]):
kind=provider['type'].split(':')[-1]
if kind=='reference': self.font(path_for(provider['id'],'font'),chain+(key,))
elif 'file' in provider:
target=path_for(provider['file'],'textures' if kind=='bitmap' else 'font','')
if target not in self.files: raise ValueError('Missing font file: '+target)
if kind=='bitmap' and not self.files[target].startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid font bitmap: '+target)
def validate(self):
counts={'models':0,'fonts':0,'items':0,'blockstates':0}
parents={path_for(parent,'models') for key,payload in self.files.items() if '/models/' in key and key.endswith('.json') for parent in [json.loads(payload).get('parent')] if parent and not parent.split(':')[-1].startswith('builtin/')}
for key,payload in self.pack.items():
if key.startswith('assets/') and not re.fullmatch(r'assets/[a-z0-9_./-]+',key): raise ValueError('Invalid asset path: '+key)
if key.endswith('.png') and not payload.startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid PNG: '+key)
if not key.endswith('.json'): continue
value=json.loads(payload)
if '/models/' in key: self.model(key,('__template__',) if key in parents else ()); counts['models']+=1
elif '/font/' in key: self.font(key); counts['fonts']+=1
elif '/items/' in key or '/blockstates/' in key:
for ref in strings_named(value,'model'): self.model(path_for(ref,'models'))
counts['items' if '/items/' in key else 'blockstates']+=1
elif '/atlases/' in key:
seen=set()
for source in value.get('sources',[]):
if source['type'].split(':')[-1]=='single':
ref=source.get('sprite',source['resource'])
if ref in seen: raise ValueError('Duplicate atlas sprite: '+ref)
seen.add(ref)
if path_for(source['resource'],'textures','.png') not in self.files: raise ValueError('Missing atlas texture: '+ref)
return counts
def vanilla_catalog(files,vanilla):
"""Prove coverage of every concrete static texture referenced by vanilla item models.
Trim sprites are generated by the native paletted atlas, not separate PNG files.
Native special renderers/player-head skins retain their original model definitions.
"""
audit=Closure(files,vanilla);generated=set();static=set();definitions=0;references=0
atlas=json.loads(vanilla['assets/minecraft/atlases/items.json'])
for source in atlas['sources']:
if source['type'].split(':')[-1]!='paletted_permutations':continue
for base in source['textures']:
template=path_for(base,'textures','.png')
if template not in vanilla or template in files:raise ValueError('Native trim template must be preserved: '+template)
for suffix in source['permutations']:generated.add(path_for(base+'_'+suffix,'textures','.png'))
for ref in [source['palette_key'],*source['permutations'].values()]:
ns,path=resource(ref)
if f'assets/{ns}/textures/palettes/{path}.png' not in vanilla:raise ValueError('Missing native trim palette')
for key,payload in vanilla.items():
if not key.startswith('assets/minecraft/items/') or not key.endswith('.json'):continue
definitions+=1;value=json.loads(payload)
for ref in [*strings_named(value,'model'),*strings_named(value,'base')]:
references+=1;textures,_=audit.model(path_for(ref,'models'),('vanilla-catalog',))
for texture in textures.values():
if isinstance(texture,dict):texture=texture['sprite']
if texture.startswith('#'):continue
target=path_for(texture,'textures','.png')
if target in generated or target=='assets/minecraft/textures/missingno.png':continue
if target not in files:raise ValueError('Uncovered vanilla item texture: '+target)
static.add(target)
return {'definitions':definitions,'modelReferences':references,'staticTextureReferences':len(static),'nativeGeneratedTrimSprites':len(generated),'specialRendererModels':'preserved'}
def required_item_sprites(files, vanilla):
"""Modern item definitions may point at models/entity or any other model directory."""
sprites=set(); audit=Closure(files,vanilla)
for key,payload in files.items():
if '/items/' not in key or not key.endswith('.json'): continue
definition=json.loads(payload)
for model in [*strings_named(definition,'model'), *strings_named(definition,'base')]:
textures,elements=audit.model(path_for(model,'models'))
for ref in textures.values():
if isinstance(ref,dict):ref=ref['sprite']
if not ref.startswith('#'):
ns,leaf=resource(ref)
if ns!='minecraft' and not leaf.startswith(('item/','block/')):sprites.add(ns+':'+leaf)
return sprites
def validate_item_atlas(files, vanilla):
sources=json.loads(files.get('assets/minecraft/atlases/items.json',b'{"sources":[]}'))['sources']
published={source.get('sprite',source['resource']) for source in sources if source['type'].split(':')[-1]=='single'}
missing=required_item_sprites(files,vanilla)-published
if missing:raise ValueError('Item atlas missing custom sprites: '+', '.join(sorted(missing)))
def validate_block_layer(files, vanilla, paths):
atlas=json.loads(vanilla['assets/minecraft/atlases/blocks.json'])
if not any(s.get('type') in ('directory','minecraft:directory') and s.get('source')=='block' and s.get('prefix')=='block/' for s in atlas['sources']):raise ValueError('Native block sprite directory contract changed')
audit=Closure(files,vanilla);states=0;references=0
for key,payload in audit.files.items():
if '/blockstates/' in key and key.endswith('.json') and key in vanilla:
for model in strings_named(json.loads(payload),'model'):audit.model(path_for(model,'models'))
for key in paths:
if not key.startswith('assets/minecraft/blockstates/') or key not in vanilla:continue
states+=1
for model in strings_named(json.loads(files[key]),'model'):
textures,elements=audit.model(path_for(model,'models'))
for ref in textures.values():
if isinstance(ref,dict):ref=ref['sprite']
if ref.startswith('#'):continue
ns,leaf=resource(ref)
if ns=='minecraft' and leaf=='missingno' and not elements:continue
if ns!='minecraft' or not leaf.startswith('block/'):raise ValueError('Block sprite outside reviewed native atlas: '+ref)
target=path_for(ref,'textures','.png')
if target not in audit.files:raise ValueError('Missing block sprite: '+ref)
references+=1
entity_sprites=0
native_sources=[source for key,payload in vanilla.items() if key.startswith('assets/minecraft/atlases/') and key.endswith('.json') for source in json.loads(payload).get('sources',[])]
for key in paths:
if not key.startswith('assets/minecraft/textures/entity/') or not key.endswith('.png'):continue
leaf=key[len('assets/minecraft/textures/'):-4]
covered=any((source.get('type','').split(':')[-1]=='directory' and leaf.startswith(source.get('source','')+'/') and source.get('prefix')==source.get('source')+'/') or (source.get('type','').split(':')[-1]=='single' and tuple(resource(source.get('resource','')))==('minecraft',leaf)) for source in native_sources)
if not covered:raise ValueError('Block-entity sprite lacks a native atlas source: '+key)
entity_sprites+=1
return {'blockstates':states,'resolvedSpriteReferences':references,'blockEntitySprites':entity_sprites,'atlas':'native atlas sources; no atlas overrides'}
def build(output, source_commit, vanilla, source_root=SOURCE):
if not re.fullmatch('[a-f0-9]{40}',source_commit):raise ValueError('Exact source SHA required')
lock=json.loads((source_root/'inputs.lock.json').read_text(encoding='utf-8'))
files,vanilla_art=plugin_vanilla_art.load(vanilla)
owner_root=ROOT/'network/resource-pack/owner-items'
if (owner_root/'inputs.json').is_file():
approved=json.loads((owner_root/'inputs.json').read_text(encoding='utf-8'))['entries']
expected={r['path']:r['sha256'] for r in approved}
actual={p.relative_to(owner_root/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (owner_root/'overlay').rglob('*') if p.is_file()}
if actual!=expected or any(not n.startswith('assets/minecraft/textures/item/') or '..' in Path(n).parts or not n.endswith(('.png','.png.mcmeta')) for n in actual):raise ValueError('Owner item overlay differs from its reviewed boundary')
excal=ROOT/'network/resource-pack/excalibur'
if (excal/'inputs.json').is_file():
approved=json.loads((excal/'inputs.json').read_text(encoding='utf-8'))['entries']
expected={r['path']:r['sha256'] for r in approved}
actual={p.relative_to(excal/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (excal/'overlay').rglob('*') if p.is_file()}
if actual!=expected or any(not n.startswith(('assets/minecraft/textures/block/','assets/minecraft/models/block/','assets/minecraft/blockstates/','assets/minecraft/textures/entity/chest/','assets/minecraft/textures/entity/bed/','assets/minecraft/textures/entity/signs/','assets/minecraft/textures/entity/bell/','assets/minecraft/textures/entity/conduit/','assets/minecraft/textures/entity/decorated_pot/','assets/minecraft/textures/entity/enchantment/')) or '..' in Path(n).parts for n in actual):raise ValueError('Excalibur block layer differs from reviewed bytes/scope')
if set(actual)&plugin_vanilla_art.PROTECTED:raise ValueError('Excalibur replaces protected spice artwork')
replacements=[]
for directory in (ROOT/'network/resource-pack/excalibur/overlay',ROOT/'network/resource-pack/owner-items/overlay',ROOT/'network/resource-pack/dune-items/overlay',source_root/'legacy',ROOT/'network/resource-pack/shared',source_root/'overlay',ROOT/'network/resource-pack/dune-items/custom'):
for path in sorted(directory.rglob('*')):
if path.is_file():
key=path.relative_to(directory).as_posix();payload=path.read_bytes()
if key in files and files[key]!=payload:replacements.append(key)
files[key]=payload
# Compatibility alias removes the historical dangling default-font reference without replacing source artwork.
files['assets/dunerealms/font/imperial_menus.json']=encoded({'providers':[{'type':'reference','id':'dunerealms:card_art'},{'type':'reference','id':'dunerealms:lore_panels'}]})
# Item-only sprites outside the vanilla item directory need explicit registration; register in ONE atlas.
sprites=required_item_sprites(files,vanilla)
files['assets/minecraft/atlases/items.json']=encoded({'sources':[{'type':'minecraft:single','resource':ref,'sprite':ref} for ref in sorted(sprites)]})
transport_path=ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip'
if hashlib.sha256(transport_path.read_bytes()).hexdigest()!=lock['transportSha256']:raise ValueError('Transport input differs')
transport=read_zip(transport_path)
for key,value in transport.items():
if key=='pack.mcmeta':continue
if key in files and files[key]!=value:raise ValueError('Unexpected GUI transport collision: '+key)
files[key]=value
meta=json.loads(transport['pack.mcmeta']);meta['pack']={'description':'DuneRealms | One central network resource pack','min_format':88,'max_format':97}
files['pack.mcmeta']=encoded(meta)
files['CREDITS-DuneRealms.txt']=b'DuneRealms central artwork: owner-supplied procedural source and assets. Vanilla material layer extends that generator, retaining Minecraft/Mojang silhouettes and UV relief where noted; futuristic ore/metal icons and masonry/furniture materials by DuneRealms. Existing custom card atlases, legacy custom item/entity artwork and MCGUI transport preserved. No Xeindom/XAE assets.\n'
if (excal/'inputs.json').is_file():
files['CREDITS-Excalibur.txt']=(excal/'CREATOR-LICENSE.txt').read_bytes()+b'\nOfficial project: https://www.planetminecraft.com/texture-pack/excalibur/\nBlock-only network integration: Owner attested permission to merge on2026-11-29. Original licence retained; no general derivative permission claimed.\n'
counts=Closure(files,vanilla).validate()
validate_item_atlas(files,vanilla)
if (excal/'inputs.json').is_file():counts['excalibur']=validate_block_layer(files,vanilla,[r['path'] for r in approved])
vanilla_art['itemCatalog']=vanilla_catalog(files,vanilla)
output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(output,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=9) as zipout:
for key,value in sorted(files.items()):
info=zipfile.ZipInfo(key,(2026,11,29,0,0,0));info.create_system=0;info.compress_type=zipfile.ZIP_DEFLATED;zipout.writestr(info,value,compresslevel=9)
if read_zip(output)!=files:raise ValueError('Built ZIP differs from source assembly')
data=output.read_bytes();manifest={'filename':output.name,'sourceCommit':source_commit,'packId':PACK_ID,'delivery':'server','unified':True,'bytes':len(data),'sha1':hashlib.sha1(data).hexdigest(),'sha256':hashlib.sha256(data).hexdigest(),'entries':len(files),'validation':counts,'vanillaArtwork':vanilla_art,'inputs':lock,'replacedAssetPaths':sorted(set(replacements))}
output.with_suffix('.manifest.json').write_bytes(encoded(manifest));return manifest