Files
Diabolo/tools/build_iron_maiden.py

127 lines
6.3 KiB
Python

"""Prepare the approved Meshy cabinet with independently hinged, matching doors.
Blender 5: blender -b --python tools/build_iron_maiden.py
The closed source is the single source of truth for both door silhouettes.
"""
import bpy, bmesh, json, math
from pathlib import Path
from mathutils import Vector
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / 'tools/model_sources/iron_maiden_v01/source.glb'
OUT = ROOT / 'Demon_v0.19/art/equipment/iron_maiden_v01'
OUT.mkdir(parents=True, exist_ok=True)
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=str(SOURCE))
meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH']
bpy.ops.object.select_all(action='DESELECT')
for obj in meshes:
obj.select_set(True)
bpy.context.view_layer.objects.active = meshes[0]
bpy.ops.object.convert(target='MESH')
bpy.ops.object.join()
source = bpy.context.object
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
verts = [v.co for v in source.data.vertices]
lo = Vector(tuple(min(v[i] for v in verts) for i in range(3)))
hi = Vector(tuple(max(v[i] for v in verts) for i in range(3)))
factor = 3.10 / (hi.z - lo.z)
center = (lo + hi) * .5
for v in source.data.vertices:
v.co = Vector(((v.co.x-center.x)*factor, (v.co.y-center.y)*factor, (v.co.z-lo.z)*factor))
if len(source.data.polygons)>80000:
decimate=source.modifiers.new('Game triangle budget','DECIMATE')
decimate.ratio=80000/len(source.data.polygons)
bpy.ops.object.modifier_apply(modifier=decimate.name)
# Blender -Y is Godot +Z (the existing station approach direction).
# Cut the closed surface once. Each triangle then belongs to exactly one part.
bm = bmesh.new(); bm.from_mesh(source.data)
door_bottom, door_top, hinge_y = .25, 2.48, 0.0
for point, normal in [((0,0,door_bottom),(0,0,1)),((0,0,door_top),(0,0,1)),((0,hinge_y,0),(0,1,0)),((0,0,0),(1,0,0))]:
bmesh.ops.bisect_plane(bm, geom=list(bm.verts)+list(bm.edges)+list(bm.faces),
dist=1e-6, plane_co=point, plane_no=normal)
bm.to_mesh(source.data);bm.free()
def group_for(face):
c=face.calc_center_median()
if door_bottom+1e-5 < c.z < door_top-1e-5 and c.y < hinge_y-1e-5:
return 'LeftDoor' if c.x < 0 else 'RightDoor'
return 'Body'
parts={}
for name in ['Body','LeftDoor','RightDoor']:
mesh=source.data.copy();bm=bmesh.new();bm.from_mesh(mesh)
discard=[f for f in bm.faces if group_for(f)!=name]
bmesh.ops.delete(bm,geom=discard,context='FACES')
loose=[v for v in bm.verts if not v.link_faces]
bmesh.ops.delete(bm,geom=loose,context='VERTS')
bm.to_mesh(mesh);bm.free();mesh.update()
obj=bpy.data.objects.new(name+'Surface',mesh);bpy.context.collection.objects.link(obj)
parts[name]=obj
bpy.data.objects.remove(source,do_unlink=True)
# Separate smooth lining preserves the source exterior and central closing seam.
inner=bpy.data.materials.new('Smooth interior iron');inner.diffuse_color=(.055,.065,.075,1)
inner.use_nodes=True
inner.node_tree.nodes.clear()
principled=inner.node_tree.nodes.new('ShaderNodeBsdfPrincipled')
material_output=inner.node_tree.nodes.new('ShaderNodeOutputMaterial')
inner.node_tree.links.new(principled.outputs['BSDF'],material_output.inputs['Surface'])
principled.inputs['Base Color'].default_value=(.055,.065,.075,1)
principled.inputs['Metallic'].default_value=.78;principled.inputs['Roughness'].default_value=.50
for name,obj in parts.items():
custom=obj.data.attributes.get('custom_normal')
if custom:obj.data.attributes.remove(custom)
for polygon in obj.data.polygons:polygon.use_smooth=True
# Do not solidify the source's tiny rivets and decorative folds: inward offsets
# on those details produce self-intersections. A separate smooth lining defines
# the cavity, while the original outer surfaces stay untouched.
profile=[(.25,.73,.54),(.5,.75,.56),(1.0,.75,.56),(1.7,.75,.56),(2.15,.72,.54),(2.35,.55,.40),(2.43,.35,.25)]
liners={}
for name,start,end in [('Body',0,math.pi),('LeftDoor',math.pi,math.pi*1.5),('RightDoor',math.pi*1.5,math.pi*2)]:
count=48 if name=='Body' else 24
vertices=[];faces=[]
for z,rx,ry in profile:
for k in range(count+1):
a=start+(end-start)*k/count
vertices.append((math.cos(a)*rx*.86,math.sin(a)*ry*.70,z))
for j in range(len(profile)-1):
for k in range(count):
a=j*(count+1)+k;b=a+count+1
faces.append((a,b,b+1,a+1))
data=bpy.data.meshes.new(name+'Lining');data.from_pydata(vertices,[],faces);data.materials.append(inner)
liner=bpy.data.objects.new(name+'Lining',data);bpy.context.collection.objects.link(liner)
for p in data.polygons:p.use_smooth=True
liners[name]=liner
hinges={}
for name,sign in [('LeftDoor',-1),('RightDoor',1)]:
obj=parts[name]
edge=[v.co.x for v in obj.data.vertices if abs(v.co.y-hinge_y)<.045 and .45<v.co.z<2.20]
hx=(min(edge) if sign<0 else max(edge)) if edge else sign*.72
pivot=Vector((hx,hinge_y,0))
empty=bpy.data.objects.new(name,None);bpy.context.collection.objects.link(empty);empty.location=pivot
for v in obj.data.vertices:v.co-=pivot
obj.parent=empty;obj.location=(0,0,0)
liner=liners[name]
for v in liner.data.vertices:v.co-=pivot
liner.parent=empty
hinges[name]=list(pivot)
parts['Body'].name='Body'
# Embedded glTF images already have packed_file. Repacking those from their
# virtual filenames can discard the embedded bytes in Blender 5.
for image in bpy.data.images:
if image.source=='FILE' and not image.packed_file and image.size[0]>0:image.pack()
bpy.ops.wm.save_as_mainfile(filepath=str(ROOT/'tools/model_sources/iron_maiden_v01/iron_maiden.blend'))
bpy.ops.export_scene.gltf(filepath=str(OUT/'iron_maiden.glb'),export_format='GLB',export_yup=True,export_animations=False)
for obj in parts.values():obj.data.calc_loop_triangles()
manifest={'source_task':'01a1845b-d214-7150-8267-02bdbab6abd8','resource':'multi-image-to-3d',
'height_m':3.10,'hinges_blender':hinges,'door_height':[door_bottom,door_top],
'construction':'Closed source partitioned once; two front quadrants, separate smooth lining, recomputed normals.',
'triangles':sum(len(o.data.loop_triangles) for o in parts.values())+sum(len(o.data.polygons)*2 for o in liners.values())}
(OUT/'manifest.json').write_text(json.dumps(manifest,indent=2),encoding='utf-8')
print('IRON_MAIDEN_EXPORTED',json.dumps(manifest))