Files

23 lines
1.2 KiB
Python

"""BLP2 DXT5 (8-bit alpha) with a full mip chain, same header layout as the native drake textures."""
import struct,subprocess,tempfile,os,sys
from PIL import Image
def write_blp5(img,path):
w,h=img.size;levels=[]
with tempfile.TemporaryDirectory() as t:
while True:
p=os.path.join(t,'l.png');d=os.path.join(t,'l.dds')
img.resize((w,h),Image.LANCZOS).convert('RGBA').save(p)
subprocess.run(['magick',p,'-define','dds:compression=dxt5','-define','dds:mipmaps=0',d],check=True)
raw=open(d,'rb').read()[128:];want=max(1,(w+3)//4)*max(1,(h+3)//4)*16;assert len(raw)==want,(len(raw),want)
levels.append(raw)
if (w==1 and h==1) or len(levels)==16:break
w,h=max(1,w//2),max(1,h//2)
offs,sizes,at=[],[],1172
for l in levels:offs.append(at);sizes.append(len(l));at+=len(l)
offs+=[0]*(16-len(offs));sizes+=[0]*(16-len(sizes))
hdr=b'BLP2'+struct.pack('<I',1)+bytes([2,8,7,1])+struct.pack('<II',*img.size)+struct.pack('<16I',*offs)+struct.pack('<16I',*sizes)+bytes(1024)
open(path,'wb').write(hdr+b''.join(levels))
if __name__=='__main__':
for a in sys.argv[1:]:
s,d=a.split(':');write_blp5(Image.open(s),d)