RacesOfValheim/scripts/render_obj.py
kanym b661fa6516 feat: Alfar chests get bodies of their own
Players mistook a plain Wood chest for the Eldividarkista, so neither
Alfar chest looks like a buildable vanilla chest any more.

Eldividarkista: the Mistlands dvergr crate stretched to 1.6 x 0.8 m,
blackened iron with a bronze frame and an iron grate on the front. The
grate glows and throws sparks only while the chest holds wood the drones
may burn.

Inngangskista: the dvergr town loot chest, navy steel with silver trim. A
cyan line in the lid shines while it holds anything but the sigil.

Both have new hammer icons, and their hover names say their role (input,
fuel) in English, Italian and Russian. If a borrowed vanilla model is
missing, the chest falls back to the old tinted wood chest.

scripts/paint_*_chest.py repaint the textures and render previews and
icons offline with scripts/render_obj.py.
2026-10-30 18:20:13 +01:00

88 lines
4.3 KiB
Python

"""Tiny software renderer: render(parts, out, size, yaw, pitch, bg)
parts: list of dicts {obj: path, tex: PIL image or None, color:(r,g,b), offset:(x,y,z), scale:(sx,sy,sz), emissive:bool}
OBJ x is mirrored vs Unity: we flip x back."""
import numpy as np
from PIL import Image
import math
def load_obj(path, groups=False):
v=[];vt=[];vn=[];faces=[];gid=[];g=0;gn=0;ids={}
for l in open(path):
p=l.split()
if not p: continue
if p[0]=='g': gn+=1; g=gn
elif p[0]=='v': v.append([float(x) for x in p[1:4]])
elif p[0]=='vt': vt.append([float(x) for x in p[1:3]])
elif p[0]=='f':
idx=[]
for k in p[1:]:
a=k.split('/'); idx.append((int(a[0])-1, int(a[1])-1 if len(a)>1 and a[1] else -1))
# a group counts as a submesh only once it has faces (the export starts with an empty one)
if g not in ids: ids[g]=len(ids)
for i in range(1,len(idx)-1): faces.append((idx[0],idx[i],idx[i+1])); gid.append(ids[g])
v=np.array(v); v[:,0]*=-1
if groups: return v, np.array(vt) if vt else None, faces, gid
return v, np.array(vt) if vt else None, faces
def render(parts, out, size=512, yaw=35, pitch=25, bg=(40,44,52,255), fit=None, light=(0.4,0.8,-0.5)):
tris=[]
for P in parts:
v,vt,faces,gid=load_obj(P['obj'],groups=True)
if 'rotx' in P:
a=math.radians(P['rotx']); c,s=math.cos(a),math.sin(a)
v=v@np.array([[1,0,0],[0,c,-s],[0,s,c]]).T
v=v*np.array(P.get('scale',(1,1,1)))+np.array(P.get('offset',(0,0,0)))
# 'texs'/'colors'/'emissives' per OBJ group (submesh) override 'tex'/'color'/'emissive'
def arr(t): return np.asarray(t.convert('RGBA'),dtype=np.float32)/255 if t is not None else None
texs=[arr(t) for t in P['texs']] if 'texs' in P else None
ta0=arr(P.get('tex'))
for f,gi in zip(faces,gid):
pv=np.array([v[i] for i,_ in f]); puv=np.array([vt[j] if (vt is not None and j>=0) else (0,0) for _,j in f])
ta=texs[min(gi,len(texs)-1)] if texs is not None else ta0
col=P['colors'][min(gi,len(P['colors'])-1)] if 'colors' in P else P.get('color',(1,1,1))
em=P['emissives'][min(gi,len(P['emissives'])-1)] if 'emissives' in P else P.get('emissive',False)
tris.append((pv,puv,ta,col,em))
ay=math.radians(yaw); ap=math.radians(pitch)
Ry=np.array([[math.cos(ay),0,math.sin(ay)],[0,1,0],[-math.sin(ay),0,math.cos(ay)]])
Rx=np.array([[1,0,0],[0,math.cos(ap),-math.sin(ap)],[0,math.sin(ap),math.cos(ap)]])
R=Rx@Ry
allv=np.concatenate([t[0] for t in tris])@R.T
if fit is None:
mn=allv.min(0); mx=allv.max(0); c=(mn+mx)/2; ext=max(mx[0]-mn[0],mx[1]-mn[1])*0.55
else: c,ext=fit
img=np.zeros((size,size,4),np.float32); img[:]=np.array(bg)/255
zb=np.full((size,size),-1e9)
L=np.array(light);L=L/np.linalg.norm(L)
for pv,puv,ta,col,em in tris:
q=pv@R.T
n=np.cross(pv[1]-pv[0],pv[2]-pv[0]); nl=np.linalg.norm(n)
if nl==0: continue
n=n/nl
nv=n@R.T
shade=1.0 if em else 0.35+0.65*abs(float(n@L))
sx=(q[:,0]-c[0])/ext*size/2+size/2; sy=size/2-(q[:,1]-c[1])/ext*size/2
x0=max(int(sx.min()),0);x1=min(int(sx.max())+1,size);y0=max(int(sy.min()),0);y1=min(int(sy.max())+1,size)
if x0>=x1 or y0>=y1: continue
xs,ys=np.meshgrid(np.arange(x0,x1)+0.5,np.arange(y0,y1)+0.5)
d=(sy[1]-sy[2])*(sx[0]-sx[2])+(sx[2]-sx[1])*(sy[0]-sy[2])
if abs(d)<1e-9: continue
w0=((sy[1]-sy[2])*(xs-sx[2])+(sx[2]-sx[1])*(ys-sy[2]))/d
w1=((sy[2]-sy[0])*(xs-sx[2])+(sx[0]-sx[2])*(ys-sy[2]))/d
w2=1-w0-w1
m=(w0>=0)&(w1>=0)&(w2>=0)
if not m.any(): continue
z=w0*q[0,2]+w1*q[1,2]+w2*q[2,2]
z=-z
sub=zb[y0:y1,x0:x1]; m&=z>sub
if not m.any(): continue
if ta is not None:
u=(w0*puv[0,0]+w1*puv[1,0]+w2*puv[2,0])%1; vv=(w0*puv[0,1]+w1*puv[1,1]+w2*puv[2,1])%1
th,tw=ta.shape[:2]
px=np.clip((u*tw).astype(int),0,tw-1); py=np.clip(((1-vv)*th).astype(int),0,th-1)
rgb=ta[py,px,:3]
else: rgb=np.ones(xs.shape+(3,))
rgb=rgb*np.array(col)*shade
sub[m]=z[m]
reg=img[y0:y1,x0:x1]
reg[m,:3]=np.clip(rgb[m],0,1); reg[m,3]=1
Image.fromarray((img*255).astype(np.uint8)).save(out)