plugins/tools/plugin_resource_pack.py

155 lines
9.5 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
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,))
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 ref in strings_named(elements,'texture'): resolve(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}
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); 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 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={}; replacements=[]
for directory in (source_root/'legacy',ROOT/'network/resource-pack/shared',source_root/'overlay'):
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=set(); audit=Closure(files,vanilla)
for key in files:
if '/models/item/' in key and key.endswith('.json'):
textures,_=audit.model(key)
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)
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 original procedural source and assets. Existing DuneRealms card atlases, legacy item/entity artwork and MCGUI client transport preserved. One complete pack for every backend. No Xeindom/XAE assets.\n'
counts=Closure(files,vanilla).validate()
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,'inputs':lock,'replacedAssetPaths':sorted(set(replacements))}
output.with_suffix('.manifest.json').write_bytes(encoded(manifest));return manifest