Files
IntoHole/assets/collections/storybook/source/build.py
T
Yanchen d1141b04c7 feat: 更新 IntoHole 的球体、滑槽和环境资产
- 为铁球、陶瓷球和木球制作风格化材质,归档 CC0 原始参考
- 更新方形球洞和实心滑槽,统一 90° 弯槽并兼容旧存档
- 用顺流泡沫表示水流方向,为冰块制作三种交错的裂纹
- 同步 Blender 源资产、Godot 加载、工坊和试玩预览
2026-11-19 16:18:41 +08:00

296 lines
15 KiB
Python

"""Blender-only authoring of a separate Railbound-inspired asset family.
Copies a stable source once; never writes to the baseline assets. To adopt a
later baseline, remove only this family's source_snapshot files explicitly.
"""
import bpy
import bmesh
import hashlib
import json
import math
import shutil
import time
import runpy
from pathlib import Path
from mathutils import Vector
ROOT = Path(__file__).resolve().parents[4]
SOURCE = Path(__file__).resolve().parent
SNAPSHOT = SOURCE / 'snapshot'
SNAPSHOT.mkdir(parents=True, exist_ok=True)
ONLY_ASSET = globals().get('ONLY_ASSET')
REPORTS = ROOT / 'playtest/artifacts/styled'
REPORTS.mkdir(parents=True, exist_ok=True)
OUT = SOURCE.parent
SOURCE.mkdir(parents=True, exist_ok=True)
snapshot = SNAPSHOT / 'source_snapshot.blend'
inputs = [ROOT/'assets/collections/baseline/source/collection.blend',
ROOT/'assets/collections/baseline/catalog.json', ROOT/'assets/collections/baseline/physics.json']
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
if not snapshot.exists():
before = [digest(p) for p in inputs]
time.sleep(3)
if before != [digest(p) for p in inputs]:
raise RuntimeError('Baseline is changing. Wait for its current build, then retry.')
copies = [snapshot, SNAPSHOT/'source_catalog.json', SNAPSHOT/'source_physics.json']
for src, dst in zip(inputs, copies):
shutil.copy2(src, dst)
if before != [digest(p) for p in inputs] or before != [digest(p) for p in copies]:
for p in copies: p.unlink(missing_ok=True)
raise RuntimeError('Baseline changed during copy. No snapshot was retained.')
(SNAPSHOT/'source_manifest.json').write_text(json.dumps({
'files': {str(p.relative_to(ROOT)): h for p,h in zip(inputs,before)},
'copiedAtUnix': time.time(), 'readOnlyBaseline': True}, indent=2))
bpy.ops.wm.open_mainfile(filepath=str(snapshot))
bpy.context.preferences.filepaths.save_version=0
catalog = json.loads((SNAPSHOT/'source_catalog.json').read_text())
physics = json.loads((SNAPSHOT/'source_physics.json').read_text())
palette = {'body':'B98A56', 'top':'E9C88B', 'groove':'FFF0C5',
'ink':'342E38', 'iron':'788A9E', 'iron_light':'C6DFE5',
'red':'CB6652', 'green':'799361'}
def mat(name, color, metallic=0.0, roughness=.85):
m = bpy.data.materials.new('Storybook / '+name)
rgba = tuple(int(color[i:i+2],16)/255 for i in (0,2,4))+(1,)
# Hex palette is sRGB; Blender's material values are linear.
rgba = tuple(((v+.055)/1.055)**2.4 if v>.04045 else v/12.92 for v in rgba[:3])+(1,)
m.diffuse_color = rgba
m.use_nodes = True
bsdf = m.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Base Color'].default_value = rgba
bsdf.inputs['Metallic'].default_value = metallic
bsdf.inputs['Roughness'].default_value = roughness
return m
mats={k:mat(k,v) for k,v in palette.items()}
mats['wall']=mat('wall stone','A29E8B')
mats['wall_top']=mat('wall stone top','D8D3B4')
def mesh_object(name,vertices,faces):
mesh=bpy.data.meshes.new(name)
mesh.from_pydata(vertices,[],faces);mesh.update()
bm=bmesh.new();bm.from_mesh(mesh)
bmesh.ops.recalc_face_normals(bm,faces=bm.faces);bm.to_mesh(mesh);bm.free()
obj=bpy.data.objects.new(name,mesh);bpy.context.collection.objects.link(obj)
return obj
def build_funnel():
bpy.data.objects.remove(bpy.data.objects['goal_hole'],do_unlink=True)
# A wall-sized cube around the original conical inlet and open throat.
# Matching square/circle rings form one closed manifold solid, with no
# hidden full-cube collider or overlapping shell blocking the ball.
sides=96
profile=[('circle',.46,0),('circle',.32,-.35),('circle',.32,-1),
('square',.5,-1),('square',.5,0)]
vertices=[]
for shape,size,z in profile:
for i in range(sides):
x,y=math.cos(i*math.tau/sides),math.sin(i*math.tau/sides)
radius=size/max(abs(x),abs(y)) if shape=='square' else size
vertices.append((radius*x,radius*y,z))
faces=[]
for ring in range(len(profile)):
next_ring=(ring+1)%len(profile)
for i in range(sides):
j=(i+1)%sides
faces.append((ring*sides+i,ring*sides+j,next_ring*sides+j,next_ring*sides+i))
return mesh_object('goal_hole',vertices,faces)
def build_wall(name='wall'):
vertices=[(x,y,z) for z in (0,1) for y in (-.5,.5) for x in (-.5,.5)]
faces=[(0,2,3,1),(4,5,7,6),(0,1,5,4),(2,6,7,3),(0,4,6,2),(1,3,7,5)]
return mesh_object(name,vertices,faces)
build_funnel();build_wall();build_wall('directional_boost');build_wall('water');build_wall('ice')
mats['water']=mat('water','74C7D8',roughness=.25)
mats['water_surface']=mat('water_surface','63B8C5',roughness=.25)
mats['ice']=mat('ice','A8DAE0',roughness=.12)
mats['ice_top']=mat('ice top','DBF5EE',roughness=.12)
for key, alpha in [('water',.22),('water_surface',.55),('ice',.86)]:
material=mats[key]
material.diffuse_color=(*material.diffuse_color[:3],alpha)
material.node_tree.nodes.get('Principled BSDF').inputs['Alpha'].default_value=material.diffuse_color[3]
material.surface_render_method='DITHERED'
for kind in ['water','ice']:
catalog['models'][kind]={'role':kind,'category':'nonInteractive' if kind=='water' else 'interactive',
'collisionShape':'none' if kind=='water' else 'box','cellFootprint':[1,1],
'boundsBlender':{'min':[-.5,-.5,0],'max':[.5,.5,1],'size':[1,1,1]},
'declaredSize':[1,1,1],'geometryOrigin':'authored'}
catalog['models']['water']['flowDirectionGodot']=[1,0,0]
catalog['models']['wall']={'role':'solid','category':'nonInteractive','collisionShape':'box',
'cellFootprint':[1,1],'boundsBlender':{'min':[-.5,-.5,0],'max':[.5,.5,1],'size':[1,1,1]},
'declaredSize':[1,1,1],'geometryOrigin':'authored'}
catalog['models']['directional_boost']={'role':'boost','category':'interactive','collisionShape':'box',
'cellFootprint':[1,1],'boundsBlender':{'min':[-.5,-.5,0],'max':[.5,.5,1],'size':[1,1,1]},
'declaredSize':[1,1,1],'geometryOrigin':'authored','arrowDirectionGodot':[1,0,0]}
catalog['models']['goal_hole']={'role':'goal','category':'nonInteractive','openingRadius':.32,
'entranceRadius':.46,'funnelDepth':.35,'depth':1.0,'cellFootprint':[1,1],
'boundsBlender':{'min':[-.5,-.5,-1],'max':[.5,.5,0],'size':[1,1,1]},
'declaredSize':[1,1,1],'geometryOrigin':'authored','outerShape':'cube'}
def export(objects, path):
if globals().get('EXPORT_KINDS') is not None and objects[0].name not in EXPORT_KINDS:
return
bpy.ops.object.select_all(action='DESELECT')
for obj in objects: obj.select_set(True)
bpy.context.view_layer.objects.active=objects[0]
path.parent.mkdir(parents=True,exist_ok=True)
bpy.ops.export_scene.gltf(filepath=str(path),export_format='GLB',
use_selection=True,export_yup=True,export_extras=True,export_apply=True)
def lines(name, segments, radius=.012):
curve=bpy.data.curves.new('ink_'+name,'CURVE')
curve.dimensions='3D'; curve.bevel_depth=radius; curve.bevel_resolution=0
curve.resolution_u=1
for points in segments:
spline=curve.splines.new('POLY'); spline.points.add(len(points)-1)
for point, value in zip(spline.points,points):point.co=(*value,1)
obj=bpy.data.objects.new('ink_'+name,curve)
bpy.context.collection.objects.link(obj); obj.data.materials.append(mats['ink'])
obj['visual_only']=True
return obj
def outline(obj):
bm=bmesh.new();bm.from_mesh(obj.data);bm.normal_update()
segments=[]
for edge in bm.edges:
if len(edge.link_faces)!=2 or edge.calc_face_angle(0)>math.radians(36):
segments.append([tuple(v.co) for v in edge.verts])
bm.free()
return lines(obj.name,segments)
def boost_arrow():
# Flat authored graphic above the top face; excluded from collision like ink outlines.
points=[(-.34,-.12),(.04,-.12),(.04,-.28),(.36,0),(.04,.28),(.04,.12),(-.34,.12)]
result=[]
for suffix,scale,z,color in [('border',1,1.002,'ink'),('fill',.82,1.003,'red')]:
arrow=mesh_object('ink_boost_arrow_'+suffix,[(x*scale,y*scale,z) for x,y in points],[tuple(range(7))])
arrow.data.materials.append(mats[color]);arrow['visual_only']=True
result.append(arrow)
return result
def asset_dir(kind):
category = 'balls' if kind == 'iron_ball' else 'goals' if kind == 'goal_hole' else 'blocks' if kind in ('wall','directional_boost','water','ice') else 'chutes'
return ROOT / 'assets' / category / kind
snapshot_turn='turn_90' if 'turn_90' in bpy.data.objects else 'turn_cw'
catalog['models']['turn_90']=dict(catalog['models'][snapshot_turn], geometrySource=snapshot_turn)
# Retire duplicate objects only in this working scene; never rewrite the snapshot.
for legacy in ('turn_cw','turn_ccw'):
if legacy!=snapshot_turn and legacy in bpy.data.objects:
bpy.data.objects.remove(bpy.data.objects[legacy],do_unlink=True)
kinds=['straight','turn_90','gentle','steep','y_merge']
groups=[];report=[]
all_kinds=kinds+['iron_ball','goal_hole','wall','directional_boost','water','ice']
if ONLY_ASSET is not None and ONLY_ASSET not in all_kinds:raise ValueError(ONLY_ASSET)
for kind in ([ONLY_ASSET] if ONLY_ASSET else all_kinds):
obj=bpy.data.objects[snapshot_turn if kind=='turn_90' else kind]
if kind=='turn_90':
obj.name=kind
obj['asset_id']=kind
obj.location=(0,0,0)
obj.data=obj.data.copy()
before_coords=[tuple(v.co) for v in obj.data.vertices]
old_indices=[p.material_index for p in obj.data.polygons]
obj.data.materials.clear()
if kind in kinds:
for key in ['body','groove','top']:obj.data.materials.append(mats[key])
for face,old in zip(obj.data.polygons,old_indices):
face.material_index=1 if old==1 else (2 if face.normal.z>.55 else 0)
group=[obj,outline(obj)]
category='chutes'
elif kind=='iron_ball':
ball_style=runpy.run_path(str(ROOT/'assets/balls/shared/source/material_style.py'))
ball_style['apply_material'](obj,kind)
catalog['models'][kind]['albedoTexture']='res://assets/balls/iron_ball/textures/albedo.png'
group=[obj]
category='balls'
elif kind=='goal_hole':
obj.data.materials.append(mats['wall'])
obj.data.materials.append(mats['wall_top'])
obj.data.materials.append(mats['ink'])
for face in obj.data.polygons:
inner=all(max(abs(obj.data.vertices[i].co.x),abs(obj.data.vertices[i].co.y))<.5-1e-6
for i in face.vertices)
face.material_index=2 if inner and face.normal.z<.01 else (1 if face.normal.z>0 else 0)
face.use_smooth=inner
group=[obj,outline(obj)]
category='environment'
elif kind in ('water','ice'):
obj.data.materials.append(mats[kind])
obj.data.materials.append(mats['ice_top' if kind=='ice' else 'water_surface'])
for face in obj.data.polygons:face.material_index=1 if face.normal.z>.5 else 0
group=[obj]
if kind=='ice':
ice_style=runpy.run_path(str(asset_dir(kind)/'source/material_style.py'))
ice_style['apply_ice_surface'](obj,mats['ice'],mats['ice_top'])
group.append(outline(obj))
category='entities'
else:
obj.data.materials.append(mats['wall']);obj.data.materials.append(mats['wall_top'])
for face in obj.data.polygons:face.material_index=1 if face.normal.z>.5 else 0
group=[obj,outline(obj)]
if kind=='directional_boost':group+=boost_arrow()
category='entities'
obj['style_family']='railbound_inspired'
obj['collision_source']='authored mesh' if kind in ('wall','goal_hole','directional_boost','water','ice') else 'unchanged source mesh'
export(group,asset_dir(kind)/'model.glb')
catalog['models'][kind]['path']='res://'+str((asset_dir(kind)/'model.glb').relative_to(ROOT))
catalog['models'][kind]['sourceBlend']=str((asset_dir(kind)/'source/model.blend').relative_to(ROOT))
for member in group:
if member.type=='CURVE':
bpy.ops.object.select_all(action='DESELECT');member.select_set(True)
bpy.context.view_layer.objects.active=member
bpy.ops.object.convert(target='MESH')
source_path=asset_dir(kind)/'source/model.blend'
source_path.parent.mkdir(parents=True,exist_ok=True)
# A separate editable source file contains only one asset family member.
report.append({'id':kind,'collisionGeometryUnchanged':kind not in ('wall','goal_hole','directional_boost','water','ice') and before_coords==[tuple(v.co) for v in obj.data.vertices],
'vertices':len(obj.data.vertices),'separateBlend':str(source_path.relative_to(ROOT))})
groups.append(group)
if ONLY_ASSET:
existing=json.loads((OUT/'catalog.json').read_text())
for legacy in ('turn_cw','turn_ccw'):existing['models'].pop(legacy,None)
existing['models'][ONLY_ASSET]=catalog['models'][ONLY_ASSET]
catalog=existing
else:
catalog['models']={k:catalog['models'][k] for k in all_kinds}
catalog['styleFamily']='railbound_inspired'
catalog['palette']=palette
(OUT/'catalog.json').write_text(json.dumps(catalog,ensure_ascii=False,indent=2))
if not ONLY_ASSET:
# Geometry rebuilds must not overwrite curated ball types or physics tuning.
if not (OUT/'physics.json').exists():
(OUT/'physics.json').write_text(json.dumps(physics,ensure_ascii=False,indent=2))
(OUT/'entities.json').write_text(json.dumps({'interactive':[{'id':'directional_boost','name':'定向加速','assetId':'directional_boost'},{'id':'ice','name':'易碎冰块','assetId':'ice'}],
'nonInteractive':[{'id':'wall','name':'标准墙壁','assetId':'wall'},
{'id':'goal_hole','name':'锥口球洞','assetId':'goal_hole'},{'id':'water','name':'水方块','assetId':'water'}]},ensure_ascii=False,indent=2))
if ONLY_ASSET:
names={member.name for member in groups[0]}
for obj in list(bpy.data.objects):
if obj.name not in names:bpy.data.objects.remove(obj,do_unlink=True)
bpy.ops.wm.save_as_mainfile(filepath=str(ROOT/report[0]['separateBlend']))
else:
for i,group in enumerate(groups):
for member in group:member.location=(i%4*2.6,i//4*3,0)
bpy.ops.wm.save_as_mainfile(filepath=str(SOURCE/'collection.blend'))
group_names=[[member.name for member in group] for group in groups]
for entry, names in zip(report,group_names):
if globals().get('EXPORT_KINDS') is not None and entry['id'] not in EXPORT_KINDS:
continue
bpy.ops.wm.open_mainfile(filepath=str(SOURCE/'collection.blend'))
for obj in list(bpy.data.objects):
if obj.name not in names:bpy.data.objects.remove(obj,do_unlink=True)
else:obj.location=(0,0,0)
bpy.ops.wm.save_as_mainfile(filepath=str(ROOT/entry['separateBlend']))
(REPORTS/(('asset_'+ONLY_ASSET+'.json') if ONLY_ASSET else 'assets.json')).write_text(json.dumps({
'sourceManifest':json.loads((SNAPSHOT/'source_manifest.json').read_text()),
'models':report,'radius':catalog['models']['iron_ball']['radius'],
'physicalMaterialUnchanged':True,'outlineGeometry':'visual only'},indent=2))
print('STYLE_ASSETS_READY')
if not ONLY_ASSET:
runpy.run_path(str(ROOT/'assets/balls/shared/source/build_materials.py'))