1
No files matched your search
@@ -0,0 +1,150 @@
|
||||
import bpy, math, os
|
||||
from mathutils import Vector
|
||||
OUT=os.path.dirname(os.path.abspath(__file__))
|
||||
bpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete(use_global=False)
|
||||
for c in list(bpy.data.collections):
|
||||
if c.name != 'Collection': bpy.data.collections.remove(c)
|
||||
base=bpy.data.collections.get('Collection'); base.name='Christmas Train Set'
|
||||
def mat(name,color,metal=0,rough=.35,emit=0):
|
||||
m=bpy.data.materials.new(name); m.diffuse_color=(*color,1); m.use_nodes=True
|
||||
p=next(n for n in m.node_tree.nodes if n.type=='BSDF_PRINCIPLED'); p.inputs['Base Color'].default_value=(*color,1); p.inputs['Metallic'].default_value=metal; p.inputs['Roughness'].default_value=rough
|
||||
if emit: p.inputs['Emission Color'].default_value=(*color,1); p.inputs['Emission Strength'].default_value=emit
|
||||
return m
|
||||
red=mat('Ruby lacquer',(.55,.018,.027),.25); green=mat('Evergreen lacquer',(.015,.19,.095),.2)
|
||||
gold=mat('Warm brass',(.85,.48,.075),.72); steel=mat('Rail steel',(.19,.25,.3),.8)
|
||||
dark=mat('Wheel iron',(.025,.035,.045),.5); wood=mat('Walnut sleepers',(.19,.075,.035))
|
||||
snow=mat('Soft snow',(.88,.95,1),0,.65); light=mat('Warm lantern glass',(1,.65,.17),.1,.22,3)
|
||||
blue=mat('Gift teal',(.015,.4,.5),.2)
|
||||
def finish(o,name,m,parent=None):
|
||||
o.name=name; o.data.materials.append(m)
|
||||
if parent:o.parent=parent
|
||||
return o
|
||||
def box(name,loc,scale,m,parent=None,bevel=.06):
|
||||
bpy.ops.mesh.primitive_cube_add(size=1,location=loc); o=bpy.context.object; o.dimensions=scale; bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
|
||||
finish(o,name,m,parent)
|
||||
if bevel:
|
||||
mod=o.modifiers.new('Rounded toy edges','BEVEL');mod.width=bevel;mod.segments=3
|
||||
o.modifiers.new('Weighted normals','WEIGHTED_NORMAL')
|
||||
return o
|
||||
def cyl(name,loc,r,depth,m,parent=None,axis='Z',verts=32):
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=verts,radius=r,depth=depth,location=loc);o=bpy.context.object
|
||||
if axis=='X':o.rotation_euler[1]=math.pi/2
|
||||
if axis=='Y':o.rotation_euler[0]=math.pi/2
|
||||
finish(o,name,m,parent);mod=o.modifiers.new('Machined edge','BEVEL');mod.width=.025;mod.segments=2;o.modifiers.new('Normals','WEIGHTED_NORMAL');return o
|
||||
def ball(name,loc,scale,m,parent=None):
|
||||
bpy.ops.mesh.primitive_uv_sphere_add(segments=20,ring_count=12,location=loc);o=bpy.context.object;o.scale=scale;finish(o,name,m,parent)
|
||||
for p in o.data.polygons:p.use_smooth=True
|
||||
return o
|
||||
def empty(name):
|
||||
o=bpy.data.objects.new(name,None);base.objects.link(o);return o
|
||||
def line(name,pts,r,m,parent=None,cyclic=False):
|
||||
cu=bpy.data.curves.new(name,'CURVE');cu.dimensions='3D';cu.bevel_depth=r;cu.bevel_resolution=3
|
||||
s=cu.splines.new('POLY');s.points.add(len(pts)-1)
|
||||
for p,co in zip(s.points,pts):p.co=(*co,1)
|
||||
s.use_cyclic_u=cyclic;o=bpy.data.objects.new(name,cu);base.objects.link(o);finish(o,name,m,parent);return o
|
||||
R=5.5
|
||||
track=empty('TRACK — fixed 11m centerline diameter')
|
||||
for i in range(88):
|
||||
a=i*math.tau/88
|
||||
o=box('Sleeper_%02d'%i,(R*math.cos(a),R*math.sin(a),.12),(1.35,.22,.19),wood,track,.035);o.rotation_euler[2]=a
|
||||
for rr in (R-.44,R+.44):
|
||||
for t in (-.065,.065):
|
||||
cyl('Rail fastening',(rr*math.cos(a)-t*math.sin(a),rr*math.sin(a)+t*math.cos(a),.235),.045,.06,gold,track,verts=12)
|
||||
for rr in (R-.44,R+.44):
|
||||
# Continuous rectangular rail profile swept around the circle.
|
||||
vs=[];fs=[];N=192
|
||||
for i in range(N):
|
||||
a=i*math.tau/N
|
||||
for dr,z in [(-.055,.22),(.055,.22),(.055,.37),(-.055,.37)]:vs.append(((rr+dr)*math.cos(a),(rr+dr)*math.sin(a),z))
|
||||
for i in range(N):
|
||||
for j in range(4):fs.append((4*i+j,4*((i+1)%N)+j,4*((i+1)%N)+(j+1)%4,4*i+(j+1)%4))
|
||||
me=bpy.data.meshes.new('Rail mesh');me.from_pydata(vs,[],fs);me.update();o=bpy.data.objects.new('Continuous steel rail',me);base.objects.link(o);finish(o,o.name,steel,track)
|
||||
motion=empty('ANIMATION — one loop 480 frames')
|
||||
motion.rotation_euler.z=0;motion.keyframe_insert('rotation_euler',frame=1,index=2)
|
||||
motion.rotation_euler.z=math.tau;motion.keyframe_insert('rotation_euler',frame=481,index=2)
|
||||
try:
|
||||
for fc in motion.animation_data.action.fcurves:
|
||||
for k in fc.keyframe_points:k.interpolation='LINEAR'
|
||||
fc.modifiers.new('CYCLES')
|
||||
except Exception: pass
|
||||
def chassis(name,angle,length):
|
||||
root=empty(name);root.parent=motion
|
||||
box('Brass chassis',(0,0,.87),(length,1.08,.22),gold,root)
|
||||
box('Painted chassis',(0,0,1.02),(length-.08,1.02,.18),red,root)
|
||||
for x in (-length*.3,length*.3):
|
||||
cyl('Axle',(x,0,.64),.07,1.22,steel,root,'Y')
|
||||
for y in (-.47,.47):
|
||||
wheel=cyl('Wheel',(x,y,.64),.27,.20,dark,root,'Y')
|
||||
cyl('Red wheel center',(x,y+(.08 if y>0 else -.08),.64),.20,.025,red,root,'Y')
|
||||
cyl('Brass hub',(x,y+(.1 if y>0 else -.1),.64),.08,.045,gold,root,'Y')
|
||||
root.location=(R*math.cos(angle),R*math.sin(angle),0);root.rotation_euler.z=angle+math.pi/2
|
||||
return root
|
||||
engine=chassis('Locomotive',0,2.25)
|
||||
cyl('Green boiler',(.32,0,1.49),.39,1.35,green,engine,'X')
|
||||
for x in (-.23,.55,.96):cyl('Boiler brass band',(x,0,1.49),.405,.075,gold,engine,'X')
|
||||
cyl('Front smokebox',(1.03,0,1.49),.34,.08,dark,engine,'X')
|
||||
cyl('Headlamp casing',(1.13,0,1.67),.16,.16,gold,engine,'X');cyl('Headlamp glass',(1.225,0,1.67),.125,.025,light,engine,'X')
|
||||
cyl('Chimney',(.65,0,2.02),.14,.55,red,engine);cyl('Chimney flared rim',(.65,0,2.30),.23,.12,gold,engine)
|
||||
ball('Steam dome',(.05,0,1.92),(.18,.18,.19),gold,engine)
|
||||
box('Cab rear',(-.94,0,1.60),(.14,1.02,1.10),red,engine)
|
||||
for y in (-.47,.47):
|
||||
box('Cab lower side',(-.65,y,1.31),(.66,.12,.47),green,engine)
|
||||
for x in (-.94,-.34):box('Cab window post',(x,y,1.93),(.11,.11,.82),red,engine)
|
||||
box('Window lintel',(-.64,y,2.27),(.72,.13,.10),gold,engine)
|
||||
box('Cab roof',(-.65,0,2.35),(1.04,1.28,.17),red,engine,.09)
|
||||
ball('Smooth snowy cab roof',(-.65,0,2.45),(.52,.63,.13),snow,engine)
|
||||
for y in (-.69,.69):box('Cab step',(-.68,y,.96),(.55,.23,.12),dark,engine)
|
||||
box('Front bumper',(1.24,0,.91),(.16,1.3,.15),red,engine)
|
||||
for y in (-.40,.40):cyl('Buffer',(1.36,y,.96),.11,.16,gold,engine,'X')
|
||||
for side in (-1,1):
|
||||
line('Brass handrail',[(-.2,side*.43,1.65),(.86,side*.43,1.65)],.025,gold,engine)
|
||||
wagons=[]
|
||||
for idx,a in enumerate((-.48,-.94)):
|
||||
w=chassis('Gift wagon %d'%(idx+1),a,1.85);wagons.append(w)
|
||||
box('Wagon bed',(0,0,1.15),(1.72,.96,.15),wood,w)
|
||||
for y in (-.49,.49):
|
||||
box('Emerald wagon side',(0,y,1.40),(1.80,.10,.52),green,w)
|
||||
box('Golden rim',(0,y,1.69),(1.87,.12,.09),gold,w)
|
||||
for x in (-.76,0,.76):box('Side brass trim',(x,y*1.02,1.4),(.06,.12,.48),gold,w,.015)
|
||||
for x in (-.87,.87):box('Wagon end',(x,0,1.4),(.12,.98,.52),red,w)
|
||||
for j,(x,y,z,size,col) in enumerate([(-.42,-.06,1.75,.61,red),(.37,.15,1.77,.66,blue),(.12,-.21,2.13,.42,green)]):
|
||||
box('Wrapped gift',(x,y,z),(size,size,size),col,w)
|
||||
box('Gift ribbon A',(x,y,z),(size+.012,.095,size+.018),gold,w,.01)
|
||||
box('Gift ribbon B',(x,y,z),(.095,size+.018,size+.025),gold,w,.01)
|
||||
for s in (-1,1):
|
||||
o=ball('Bow loop',(x+s*.10,y,z+size/2+.045),(.13,.07,.065),gold,w);o.rotation_euler.z=s*.4
|
||||
for a,b in [(0,-.48),(-.48,-.94)]:
|
||||
mid=(a+b)/2
|
||||
back=1.125 if a==0 else .925
|
||||
front=.925
|
||||
p1=(R*math.cos(a)+back*math.sin(a),R*math.sin(a)-back*math.cos(a),.86)
|
||||
p2=(R*math.cos(b)-front*math.sin(b),R*math.sin(b)+front*math.cos(b),.86)
|
||||
line('Coupling drawbar',[p1,p2],.055,dark,motion)
|
||||
scene=bpy.context.scene;scene.frame_end=480;scene.render.fps=24;scene.frame_set(1)
|
||||
# Linear interpolation across modern layered Actions as well.
|
||||
for action in bpy.data.actions:
|
||||
for layer in action.layers:
|
||||
for strip in layer.strips:
|
||||
for slot in action.slots:
|
||||
try:
|
||||
for fc in strip.channelbag(slot).fcurves:
|
||||
for k in fc.keyframe_points:k.interpolation='LINEAR'
|
||||
except Exception:pass
|
||||
studio=empty('PRESENTATION — hide for export')
|
||||
floor=mat('Backdrop',(.055,.12,.18),0,.8)
|
||||
box('Studio floor',(0,0,-.10),(200,200,.10),floor,studio,.0)
|
||||
world=scene.world;world.use_nodes=True;next(n for n in world.node_tree.nodes if n.type=='BACKGROUND').inputs[0].default_value=(.12,.19,.3,1);next(n for n in world.node_tree.nodes if n.type=='BACKGROUND').inputs[1].default_value=.5
|
||||
def aim(o,p):o.rotation_euler=(Vector(p)-o.location).to_track_quat('-Z','Y').to_euler()
|
||||
for loc,power,size in [((1,-5,12),2100,8),((-8,2,9),1700,7),((7,8,10),2600,6)]:
|
||||
bpy.ops.object.light_add(type='AREA',location=loc);o=bpy.context.object;o.data.energy=power;o.data.shape='DISK';o.data.size=size;o.parent=studio;aim(o,(0,0,0))
|
||||
bpy.ops.object.camera_add(location=(15,-19,18));cam=bpy.context.object;cam.parent=studio;aim(cam,(0,0,.35));cam.data.type='ORTHO';cam.data.ortho_scale=16;scene.camera=cam
|
||||
scene.render.engine='CYCLES';scene.cycles.samples=32
|
||||
scene.render.resolution_x=1400;scene.render.resolution_y=1100;scene.render.resolution_percentage=100
|
||||
scene.view_settings.view_transform='AgX'
|
||||
scene.render.filepath=os.path.join(OUT,'christmas_train_preview.png')
|
||||
scene['README']='Train and two gift wagons rotate around empty center. Track centerline radius 5.5m. Loop: frames 1–480 at 24fps. Presentation objects are separate. No tree. Curve rails/couplers should be converted to meshes for Roblox export; Blender animation must be recreated in Roblox.'
|
||||
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT,'christmas_train.blend'))
|
||||
bpy.ops.render.render(write_still=True)
|
||||
print('TRAIN_BUILD_COMPLETE')
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 1.8 MiB |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
@@ -0,0 +1,123 @@
|
||||
import os
|
||||
helper=os.path.join(os.path.dirname(__file__),'..','christmas_train','build_train.py')
|
||||
exec(open(helper,encoding='utf-8-sig').read().split('R=5.5')[0])
|
||||
OUT=os.path.dirname(os.path.abspath(__file__))
|
||||
base.name='GINGERBREAD HOUSE — avatar height'
|
||||
cookie=mat('Baked honey gingerbread',(.43,.17,.055),0,.62)
|
||||
edge=mat('Toasted biscuit edges',(.23,.065,.018),0,.65)
|
||||
icing=mat('Vanilla royal icing',(1,.91,.73),0,.36)
|
||||
pink=mat('Raspberry gumdrop',(.8,.035,.13),0,.26)
|
||||
mint=mat('Pistachio candy',(.13,.55,.22),0,.3)
|
||||
root=empty('GingerbreadHouse — 5.5 units tall')
|
||||
def B(n,p,s,m,b=.04):return box(n,p,s,m,root,b)
|
||||
def L(n,pts,r,m):return line(n,pts,r,m,root)
|
||||
def S(n,p,s,m):return ball(n,p,s,m,root)
|
||||
# Model dimensions are in Roblox-friendly units: total height approximately 5.5 studs.
|
||||
B('Thick gingerbread foundation',(0,0,.14),(4.6,3.9,.28),cookie,.15)
|
||||
B('Smooth icing base',(0,0,.29),(4.65,3.95,.17),snow,.12)
|
||||
B('Gingerbread walls',(0,0,1.78),(3.9,3.1,2.9),cookie,.09)
|
||||
vs=[(-1.95,-1.55,3.17),(1.95,-1.55,3.17),(0,-1.55,4.85),(-1.95,1.55,3.17),(1.95,1.55,3.17),(0,1.55,4.85)]
|
||||
me=bpy.data.meshes.new('Solid cookie gables');me.from_pydata(vs,[],[(0,2,1),(3,4,5),(0,1,4,3),(1,2,5,4),(2,0,3,5)]);me.update()
|
||||
o=bpy.data.objects.new('Triangular gingerbread gables',me);base.objects.link(o);finish(o,o.name,cookie,root)
|
||||
ang=math.atan2(1.68,1.95)
|
||||
for side in (-1,1):
|
||||
o=B('Chocolate biscuit roof',(side*1.04,0,4.02),(2.89,3.65,.22),edge,.07);o.rotation_euler.y=side*ang
|
||||
# Smooth, contiguous icing sheet with a gently scalloped eave silhouette.
|
||||
verts=[];faces=[];NU=20;NV=32
|
||||
for i in range(NU+1):
|
||||
u=i/NU
|
||||
for j in range(NV+1):
|
||||
v=j/NV;y=-1.86+3.72*v
|
||||
x=side*(.015+2.15*u)
|
||||
z=5.17-1.86*u+.055*math.sin(v*math.pi*5)**2
|
||||
if u>.8:z-=.10*((u-.8)/.2)**2*(.5+.5*math.cos(v*math.pi*12))
|
||||
verts.append((x,y,z))
|
||||
for i in range(NU):
|
||||
for j in range(NV):
|
||||
a=i*(NV+1)+j;faces.append((a,a+NV+1,a+NV+2,a+1))
|
||||
mesh=bpy.data.meshes.new('Flowing icing sheet');mesh.from_pydata(verts,[],faces);mesh.update();ob=bpy.data.objects.new('Smooth flowing roof icing',mesh);base.objects.link(ob);finish(ob,ob.name,snow,root)
|
||||
sol=ob.modifiers.new('Icing thickness','SOLIDIFY');sol.thickness=.11
|
||||
sub=ob.modifiers.new('Soft icing edges','SUBSURF');sub.levels=2
|
||||
for p in mesh.polygons:p.use_smooth=True
|
||||
# Chocolate exposed edges outlined with icing, festive candies on slopes.
|
||||
for y in (-1.87,1.87):L('Piped gable icing',[(side*2.17*k/20,y,5.17-1.86*k/20) for k in range(21)],.075,icing)
|
||||
for row in range(2):
|
||||
u=.35+row*.34
|
||||
for j in range(5):
|
||||
y=-1.35+j*.67;x=side*2.15*u;z=5.22-1.86*u
|
||||
S('Roof gumdrop',(x,y,z),(.13,.13,.12),[red,mint,gold,pink,blue][(j+row)%5])
|
||||
L('Icing ridge',[(0,-1.9,5.17),(0,1.9,5.17)],.1,icing)
|
||||
# Four striped candy pillars.
|
||||
for x in (-1.88,1.88):
|
||||
for y in (-1.54,1.54):
|
||||
cyl('Candy cane corner',(x,y,1.79),.105,2.85,icing,root)
|
||||
pts=[]
|
||||
for i in range(181):
|
||||
t=i/180;pts.append((x+.108*math.cos(t*math.tau*7),y+.108*math.sin(t*math.tau*7),.39+2.8*t))
|
||||
L('Spiral red candy stripe',pts,.036,red)
|
||||
# Arched door, thick icing surround and paneling.
|
||||
doorpts=[(-.55,.4),(.55,.4),(.55,1.63)]+[(.55*math.cos(t*math.pi/20),1.63+.55*math.sin(t*math.pi/20)) for t in range(21)]+[(-.55,.4)]
|
||||
verts=[(x,y,z) for y in (-1.59,-1.71) for x,z in doorpts];n=len(doorpts)
|
||||
faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]+[(i,(i+1)%n,(i+1)%n+n,i+n) for i in range(n)]
|
||||
mesh=bpy.data.meshes.new('Arched door mesh');mesh.from_pydata(verts,[],faces);mesh.update();o=bpy.data.objects.new('Ruby candy door',mesh);base.objects.link(o);finish(o,o.name,red,root)
|
||||
L('Thick door icing border',[(x,-1.74,z) for x,z in doorpts],.075,icing)
|
||||
for x in (-.28,0,.28):L('Door embossed piping',[(x,-1.725,.55),(x,-1.725,1.69)],.018,gold)
|
||||
S('Golden doorknob',(.34,-1.80,1.15),(.075,.07,.075),gold)
|
||||
B('Cookie doorstep',(0,-1.92,.39),(1.35,.55,.18),cookie,.08)
|
||||
def window(x,y,z,side=False):
|
||||
w=empty('Window');w.parent=root;w.location=(x,y,z)
|
||||
if side:w.rotation_euler.z=math.pi/2
|
||||
box('Chocolate window backing',(0,0,0),(.86,.12,.92),edge,w,.10)
|
||||
box('Warm sugar glass',(0,-.075,0),(.67,.05,.72),light,w,.08)
|
||||
for dx in (-.43,.43):line('Window icing jamb',[(dx,-.13,-.46),(dx,-.13,.46)],.055,icing,w)
|
||||
for dz in (-.46,.46):line('Window icing lintel',[(-.43,-.13,dz),(.43,-.13,dz)],.055,icing,w)
|
||||
box('Window crossbar',(0,-.13,0),(.74,.05,.05),icing,w,.015);box('Window mullion',(0,-.13,0),(.05,.05,.8),icing,w,.015)
|
||||
ball('Snowy sill',(0,-.13,-.51),(.52,.15,.085),snow,w)
|
||||
for x in (-1.20,1.20):window(x,-1.60,1.65)
|
||||
for y in (-.65,.65):window(1.98,y,1.70,True)
|
||||
# Circular wreath and bow on front gable.
|
||||
L('Evergreen wreath',[(.49*math.cos(t*math.tau/64),-1.68,3.55+.49*math.sin(t*math.tau/64)) for t in range(65)],.105,green)
|
||||
for i in range(12):
|
||||
a=i*math.tau/12;S('Wreath foliage',(.49*math.cos(a),-1.70,3.55+.49*math.sin(a)),(.13,.07,.14),green)
|
||||
if i%2==0:S('Wreath berries',(.49*math.cos(a),-1.8,3.55+.49*math.sin(a)),(.055,.045,.055),red)
|
||||
for s in (-1,1):
|
||||
o=S('Red bow loop',(s*.16,-1.84,3.10),(.20,.08,.12),red);o.rotation_euler.y=s*.35
|
||||
o=B('Bow ribbon tail',(s*.10,-1.83,2.94),(.12,.06,.28),red,.025);o.rotation_euler.y=s*.22
|
||||
S('Bow knot',(0,-1.91,3.1),(.09,.06,.08),gold)
|
||||
# Front roof fairy lights.
|
||||
pts=[(-1.95+3.9*i/40,-1.91,3.12-.20*math.sin(math.pi*i/40)) for i in range(41)]
|
||||
L('Garland cable',pts,.018,green)
|
||||
for i in range(11):
|
||||
x=-1.9+3.8*i/10;z=3.12-.2*math.sin(math.pi*i/10)
|
||||
cyl('Lamp socket',(x,-1.91,z-.04),.032,.08,gold,root,verts=12)
|
||||
S('Fairy bulb',(x,-1.91,z-.12),(.065,.065,.09),light)
|
||||
# Chimney with icing rim and peppermint disk.
|
||||
B('Cookie chimney',(.85,.75,4.78),(.48,.55,.95),cookie,.05)
|
||||
B('Chocolate chimney rim',(.85,.75,5.27),(.62,.68,.15),edge,.06)
|
||||
for x in (.57,1.13):S('Chimney icing',(x,.75,5.36),(.095,.38,.10),snow)
|
||||
for y in (.44,1.06):S('Chimney icing',(.85,y,5.36),(.31,.09,.10),snow)
|
||||
B('Chimney dark opening',(.85,.75,5.36),(.39,.4,.03),dark,.02)
|
||||
for x in (-2.13,2.13):
|
||||
for j in range(6):S('Base gumdrop',(x,-1.45+j*.58,.48),(.14,.14,.17),[pink,mint,blue,red,gold,mint][j])
|
||||
for x in (-1.55,1.58):
|
||||
B('Gift box',(x,-1.98,.64),(.45,.45,.52),green if x<0 else red,.055)
|
||||
B('Gift ribbon',(x,-1.98,.65),(.08,.46,.54),gold,.01)
|
||||
B('Gift ribbon',(x,-1.98,.65),(.46,.08,.54),gold,.01)
|
||||
S('Gift bow',(x,-1.98,.94),(.18,.10,.07),gold)
|
||||
root['target_height_studs']=5.5;root['purpose']='Decorative avatar-height gingerbread house; no interior.'
|
||||
studio=empty('PRESENTATION — exclude from game export')
|
||||
floor=mat('Studio blue',(.065,.16,.23),0,.8);box('Studio floor',(0,0,-.09),(200,200,.12),floor,studio,0)
|
||||
scene=bpy.context.scene;scene.unit_settings.system='NONE'
|
||||
world=scene.world;world.use_nodes=True
|
||||
bg=next(n for n in world.node_tree.nodes if n.type=='BACKGROUND');bg.inputs[0].default_value=(.15,.22,.33,1);bg.inputs[1].default_value=.45
|
||||
def aim(o,p):o.rotation_euler=(Vector(p)-o.location).to_track_quat('-Z','Y').to_euler()
|
||||
for loc,power,size in [((2,-7,10),1500,6),((-6,-2,6),1100,5),((3,6,9),1800,5)]:
|
||||
bpy.ops.object.light_add(type='AREA',location=loc);o=bpy.context.object;o.parent=studio;o.data.energy=power;o.data.shape='DISK';o.data.size=size;aim(o,(0,0,2))
|
||||
bpy.ops.object.camera_add(location=(9,-13,8));cam=bpy.context.object;cam.parent=studio;aim(cam,(0,0,2.6));cam.data.type='ORTHO';cam.data.ortho_scale=8.2;scene.camera=cam
|
||||
scene.render.engine='CYCLES';scene.cycles.samples=48;scene.render.resolution_x=1300;scene.render.resolution_y=1300;scene.render.resolution_percentage=100
|
||||
scene.view_settings.view_transform='AgX';scene.render.filepath=os.path.join(OUT,'gingerbread_house_preview.png')
|
||||
# Save asset and render. Presentation rig is clearly separated by parent.
|
||||
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT,'gingerbread_house.blend'))
|
||||
bpy.ops.render.render(write_still=True)
|
||||
print('GINGERBREAD_HOUSE_COMPLETE')
|
||||
|
||||
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
|
After Width: | Height: | Size: 636 B |
@@ -0,0 +1,464 @@
|
||||
# Generator animation (left machine) for ornament_machine_new_bow_anim.blend.
|
||||
# Run AFTER animate_shredder.py:
|
||||
# blender -b ornament_machine_new_bow_anim.blend --python animate_generator.py [-- --video]
|
||||
#
|
||||
# Frames 200-340 (the shredder uses 1-180), timeline markers name every stage:
|
||||
# 200 Gen_Press star button pushed in, flashes
|
||||
# 204 Gen_Magic chamber rings + emitter flare, light beam, swirling sparkles
|
||||
# 228 Gen_Spawn ornament grows out of a point at Ornament_Spawn_Point, spins and hovers
|
||||
# 264 Gen_Drop ornament sinks through the chamber floor (floor ring flashes)
|
||||
# 280 Gen_Output ornament drops out of the chute onto the tray, bounces, rests at Ornament_Output_Point
|
||||
# The ornament is a placeholder ("Ornament_Placeholder*"): in the game the real ornament model is put at the
|
||||
# two empties, which carry the same motion.
|
||||
import bpy, math, os, random, sys
|
||||
from mathutils import Vector, Euler
|
||||
|
||||
random.seed(5)
|
||||
sc = bpy.context.scene
|
||||
T0 = 200
|
||||
sc.frame_end = max(sc.frame_end, T0 + 140)
|
||||
|
||||
def bbox(o):
|
||||
cs = [o.matrix_world @ Vector(c) for c in o.bound_box]
|
||||
lo = Vector(map(min, *cs)); hi = Vector(map(max, *cs))
|
||||
return (lo + hi) / 2, hi - lo
|
||||
|
||||
def fcurves_of(idb):
|
||||
act = idb.animation_data.action if idb.animation_data else None
|
||||
if act is None:
|
||||
return []
|
||||
try:
|
||||
return list(act.fcurves)
|
||||
except AttributeError:
|
||||
out = []
|
||||
for layer in act.layers:
|
||||
for strip in layer.strips:
|
||||
for bag in strip.channelbags:
|
||||
out += list(bag.fcurves)
|
||||
return out
|
||||
|
||||
def key(idb, path, frame, value=None, interp=None, easing=None):
|
||||
if value is not None:
|
||||
setattr(idb, path, value)
|
||||
idb.keyframe_insert(data_path=path, frame=frame)
|
||||
if interp:
|
||||
for c in fcurves_of(idb):
|
||||
if c.data_path == path:
|
||||
for kp in c.keyframe_points:
|
||||
if abs(kp.co.x - frame) < 0.01:
|
||||
kp.interpolation = interp
|
||||
if easing:
|
||||
kp.easing = easing
|
||||
|
||||
def key_input(sock, frame, value):
|
||||
sock.default_value = value
|
||||
sock.keyframe_insert("default_value", frame=frame)
|
||||
|
||||
for name, f in (("Gen_Press", T0), ("Gen_Magic", T0 + 4), ("Gen_Spawn", T0 + 28), ("Gen_Drop", T0 + 64), ("Gen_Output", T0 + 80)):
|
||||
m = sc.timeline_markers.get(name) or sc.timeline_markers.new(name, frame=f)
|
||||
m.frame = f
|
||||
for name, f in (("Shredder_Start", 1), ("Shredder_Stop", 120), ("Shredder_Pour", 128)):
|
||||
if not sc.timeline_markers.get(name):
|
||||
sc.timeline_markers.new(name, frame=f)
|
||||
|
||||
coll = bpy.data.collections.get("Generator_Anim") or bpy.data.collections.new("Generator_Anim")
|
||||
if coll.name not in sc.collection.children:
|
||||
sc.collection.children.link(coll)
|
||||
|
||||
# ------------------------------------------------------------------ geometry from the model
|
||||
glass_c, glass_s = bbox(bpy.data.objects["Chamber_Glass"])
|
||||
pad_c, pad_s = bbox(bpy.data.objects["Chamber_BasePad"])
|
||||
emit_c, _ = bbox(bpy.data.objects["Chamber_EmitterGlow"])
|
||||
tray_c, tray_s = bbox(bpy.data.objects["Gen_Tray_Floor"])
|
||||
ceil_c, _ = bbox(bpy.data.objects["Gen_Chute_Ceiling"])
|
||||
back_c, _ = bbox(bpy.data.objects["Gen_Chute_BackWall"])
|
||||
CX, CY = glass_c.x, glass_c.y
|
||||
PAD_TOP = pad_c.z + pad_s.z / 2
|
||||
EMIT_Z = emit_c.z
|
||||
SPAWN_Z = (PAD_TOP + EMIT_Z) / 2 + 0.2
|
||||
|
||||
# ------------------------------------------------------------------ 1) button press + flash
|
||||
press = Vector((0, 0.18, 0)) # pushes into the machine (+Y)
|
||||
for o in bpy.data.objects:
|
||||
if o.name.startswith(("Gen_Button_Face", "Gen_Button_Inner", "Gen_Button_Star")):
|
||||
rest = o.location.copy()
|
||||
key(o, "location", T0 - 1, rest)
|
||||
key(o, "location", T0 + 3, rest + press, "QUAD", "EASE_OUT")
|
||||
key(o, "location", T0 + 12, rest)
|
||||
star_glow = bpy.data.materials.get("Glow_Yellow")
|
||||
btn_mat = None
|
||||
face = bpy.data.objects.get("Gen_Button_Face")
|
||||
if face and face.data.materials and face.data.materials[0]:
|
||||
btn_mat = face.data.materials[0].copy(); btn_mat.name = "Gen_Button_Face_Anim"
|
||||
face.data.materials[0] = btn_mat
|
||||
b = next(n for n in btn_mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
|
||||
b.inputs["Emission Color"].default_value = (0.3, 1.0, 0.4, 1)
|
||||
for f, v in ((T0 - 1, 0.0), (T0 + 3, 3.0), (T0 + 16, 0.0)):
|
||||
key_input(b.inputs["Emission Strength"], f, v)
|
||||
|
||||
# ------------------------------------------------------------------ 2) chamber magic (own copy of the cyan glow)
|
||||
magic = bpy.data.materials["Glow_Cyan"].copy(); magic.name = "Gen_Chamber_Magic"
|
||||
for n in ("Chamber_GlowRing_Low", "Chamber_GlowRing_High", "Chamber_EmitterGlow"):
|
||||
o = bpy.data.objects[n]
|
||||
for i, m in enumerate(o.data.materials):
|
||||
if m and m.name.startswith("Glow_Cyan"):
|
||||
o.data.materials[i] = magic
|
||||
mb = next(n for n in magic.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
|
||||
base_e = mb.inputs["Emission Strength"].default_value
|
||||
for f, v in ((T0 + 3, base_e), (T0 + 14, base_e * 3.5), (T0 + 30, base_e * 5), (T0 + 56, base_e * 3), (T0 + 66, base_e)):
|
||||
key_input(mb.inputs["Emission Strength"], f, v)
|
||||
for c in fcurves_of(magic.node_tree):
|
||||
nm = c.modifiers.new("NOISE"); nm.scale = 2.5; nm.strength = base_e * 1.5
|
||||
nm.use_restricted_range = True; nm.frame_start, nm.frame_end = T0 + 10, T0 + 60
|
||||
|
||||
# light beam from the emitter down to the floor
|
||||
beam_mat = bpy.data.materials.new("Gen_Beam")
|
||||
try:
|
||||
beam_mat.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
bb = next(n for n in beam_mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
|
||||
bb.inputs["Base Color"].default_value = (0.5, 0.95, 1.0, 1)
|
||||
bb.inputs["Emission Color"].default_value = (0.35, 0.9, 1.0, 1)
|
||||
bb.inputs["Emission Strength"].default_value = 2.0
|
||||
bb.inputs["Alpha"].default_value = 0.12
|
||||
for a, v in (("surface_render_method", "BLENDED"), ("blend_method", "BLEND")):
|
||||
try:
|
||||
setattr(beam_mat, a, v)
|
||||
except Exception:
|
||||
pass
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=24, radius=1.0, depth=1.0, location=(CX, CY, (PAD_TOP + EMIT_Z) / 2))
|
||||
beam = bpy.context.active_object
|
||||
beam.name = "Gen_Magic_Beam"
|
||||
beam.data.materials.append(beam_mat)
|
||||
for c in list(beam.users_collection):
|
||||
c.objects.unlink(beam)
|
||||
coll.objects.link(beam)
|
||||
h = EMIT_Z - PAD_TOP
|
||||
for f, r in ((T0 + 6, 0.0), (T0 + 16, 0.3), (T0 + 30, 0.8), (T0 + 58, 0.55), (T0 + 66, 0.0)):
|
||||
key(beam, "scale", f, (r, r, h if r > 0 else h * 0.2), "QUAD", "EASE_IN_OUT")
|
||||
key(beam, "scale", 1, (0, 0, 0), "CONSTANT")
|
||||
|
||||
# swirling sparkles (children of a spinning, rising orbit empty)
|
||||
spark_mat = bpy.data.materials.new("Gen_Sparkle")
|
||||
try:
|
||||
spark_mat.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
sb = next(n for n in spark_mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
|
||||
sb.inputs["Base Color"].default_value = (1, 1, 1, 1)
|
||||
sb.inputs["Emission Color"].default_value = (0.75, 0.97, 1.0, 1)
|
||||
sb.inputs["Emission Strength"].default_value = 12.0
|
||||
orbit = bpy.data.objects.new("Gen_Sparkle_Orbit", None)
|
||||
orbit.location = (CX, CY, PAD_TOP + 0.6)
|
||||
coll.objects.link(orbit)
|
||||
key(orbit, "rotation_euler", T0 + 6, Euler((0, 0, 0)), "QUAD", "EASE_IN")
|
||||
key(orbit, "rotation_euler", T0 + 62, Euler((0, 0, math.radians(360 * 4))))
|
||||
key(orbit, "location", T0 + 6, orbit.location.copy())
|
||||
key(orbit, "location", T0 + 62, Vector((CX, CY, PAD_TOP + 2.0)))
|
||||
for k in range(16):
|
||||
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, radius=0.09)
|
||||
s = bpy.context.active_object
|
||||
s.name = "Gen_Sparkle_%02d" % k
|
||||
s.data.materials.append(spark_mat)
|
||||
for c in list(s.users_collection):
|
||||
c.objects.unlink(s)
|
||||
coll.objects.link(s)
|
||||
a = 2 * math.pi * k / 16
|
||||
r = random.uniform(1.4, 2.5)
|
||||
s.parent = orbit
|
||||
s.location = (r * math.cos(a), r * math.sin(a), random.uniform(-0.3, 3.2))
|
||||
sz = random.uniform(0.8, 1.6)
|
||||
t_in = T0 + 8 + random.randint(0, 10)
|
||||
key(s, "scale", 1, (0, 0, 0), "CONSTANT")
|
||||
key(s, "scale", t_in - 1, (0, 0, 0))
|
||||
key(s, "scale", t_in + 4, (sz, sz, sz))
|
||||
key(s, "scale", T0 + 54 + random.randint(0, 6), (sz, sz, sz))
|
||||
key(s, "scale", T0 + 64 + random.randint(0, 4), (0, 0, 0))
|
||||
|
||||
# chamber light flash
|
||||
bpy.ops.object.light_add(type="POINT", location=(CX, CY, SPAWN_Z))
|
||||
cl = bpy.context.active_object
|
||||
cl.name = "Gen_Chamber_Light"
|
||||
for c in list(cl.users_collection):
|
||||
c.objects.unlink(cl)
|
||||
coll.objects.link(cl)
|
||||
cl.data.color = (0.45, 0.9, 1.0)
|
||||
cl.data.shadow_soft_size = 1.0
|
||||
for f, e in ((T0 + 2, 0.0), (T0 + 20, 250.0), (T0 + 30, 600.0), (T0 + 40, 220.0), (T0 + 60, 180.0), (T0 + 70, 0.0)):
|
||||
cl.data.energy = e; cl.data.keyframe_insert("energy", frame=f)
|
||||
cl.data.energy = 0; cl.data.keyframe_insert("energy", frame=1)
|
||||
|
||||
# ------------------------------------------------------------------ 2b) lightning bolts flickering inside the chamber
|
||||
MAGIC_A, MAGIC_B = T0 + 12, T0 + 60 # window in which the chamber is "charged"
|
||||
R_IN = glass_s.x / 2 - 0.45 # stay just inside the glass
|
||||
bolt_mat = bpy.data.materials.new("Gen_Lightning")
|
||||
try:
|
||||
bolt_mat.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
lb = next(n for n in bolt_mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
|
||||
lb.inputs["Base Color"].default_value = (0.85, 0.97, 1.0, 1)
|
||||
lb.inputs["Emission Color"].default_value = (0.65, 0.92, 1.0, 1)
|
||||
lb.inputs["Emission Strength"].default_value = 18.0
|
||||
|
||||
def jagged(p0, p1, n, amp):
|
||||
pts = []
|
||||
for i in range(n + 1):
|
||||
t = i / n
|
||||
p = p0.lerp(p1, t)
|
||||
if 0 < i < n:
|
||||
p = p + Vector((random.uniform(-amp, amp), random.uniform(-amp, amp), random.uniform(-amp, amp) * 0.4))
|
||||
pts.append(p)
|
||||
return pts
|
||||
|
||||
def bolt_object(name, strokes, radius):
|
||||
cu = bpy.data.curves.new(name, "CURVE")
|
||||
cu.dimensions = "3D"; cu.bevel_depth = radius; cu.bevel_resolution = 1
|
||||
for pts in strokes:
|
||||
sp = cu.splines.new("POLY")
|
||||
sp.points.add(len(pts) - 1)
|
||||
for p, v in zip(sp.points, pts):
|
||||
p.co = (v.x, v.y, v.z, 1)
|
||||
cu.materials.append(bolt_mat)
|
||||
o = bpy.data.objects.new(name, cu)
|
||||
coll.objects.link(o)
|
||||
return o
|
||||
|
||||
def vis_key(o, frame, visible):
|
||||
o.hide_render = not visible; o.hide_viewport = not visible
|
||||
o.keyframe_insert("hide_render", frame=frame); o.keyframe_insert("hide_viewport", frame=frame)
|
||||
|
||||
N_BOLT_SLOTS, VARIANTS = 5, 4
|
||||
for slot in range(N_BOLT_SLOTS):
|
||||
variants = []
|
||||
for v in range(VARIANTS):
|
||||
a0 = random.uniform(0, 2 * math.pi)
|
||||
start = Vector((CX + 0.6 * math.cos(a0), CY + 0.6 * math.sin(a0), EMIT_Z - 0.2))
|
||||
if random.random() < 0.5: # down to the floor pad
|
||||
a1 = random.uniform(0, 2 * math.pi); r1 = random.uniform(0.6, 1.8)
|
||||
end = Vector((CX + r1 * math.cos(a1), CY + r1 * math.sin(a1), PAD_TOP + 0.1))
|
||||
else: # sideways into the glass wall / pillars
|
||||
a1 = a0 + random.uniform(-1.2, 1.2)
|
||||
end = Vector((CX + R_IN * math.cos(a1), CY + R_IN * math.sin(a1), random.uniform(PAD_TOP + 1.0, EMIT_Z - 1.0)))
|
||||
main = jagged(start, end, 9, 0.45)
|
||||
k = random.randint(3, 6) # a forked branch
|
||||
branch = jagged(main[k], main[k] + Vector((random.uniform(-1.2, 1.2), random.uniform(-1.2, 1.2), -random.uniform(0.4, 1.2))), 4, 0.3)
|
||||
variants.append(bolt_object("Gen_Lightning_%d_%d" % (slot, v), [main, branch], random.uniform(0.035, 0.06)))
|
||||
for o in variants:
|
||||
vis_key(o, 1, False)
|
||||
f = MAGIC_A + slot * 2
|
||||
while f < MAGIC_B:
|
||||
o = random.choice(variants)
|
||||
dur = random.randint(1, 3)
|
||||
vis_key(o, f, True); vis_key(o, f + dur, False)
|
||||
f += dur + random.randint(1, 5)
|
||||
for o in variants:
|
||||
for c in fcurves_of(o):
|
||||
for kp in c.keyframe_points:
|
||||
kp.interpolation = "CONSTANT"
|
||||
|
||||
# ------------------------------------------------------------------ 2c) glowing fog filling the chamber
|
||||
fog_mat = bpy.data.materials.new("Gen_Fog")
|
||||
try:
|
||||
fog_mat.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
FN, FL = fog_mat.node_tree.nodes, fog_mat.node_tree.links
|
||||
FN.clear()
|
||||
fout = FN.new("ShaderNodeOutputMaterial")
|
||||
vol = FN.new("ShaderNodeVolumePrincipled")
|
||||
vol.inputs["Color"].default_value = (0.75, 0.92, 1.0, 1)
|
||||
vol.inputs["Emission Color"].default_value = (0.35, 0.8, 1.0, 1)
|
||||
tco = FN.new("ShaderNodeTexCoord")
|
||||
mp = FN.new("ShaderNodeMapping")
|
||||
FL.new(tco.outputs["Object"], mp.inputs["Vector"])
|
||||
nz = FN.new("ShaderNodeTexNoise"); nz.noise_dimensions = "4D"
|
||||
nz.inputs["Scale"].default_value = 1.6; nz.inputs["Detail"].default_value = 3.0
|
||||
FL.new(mp.outputs["Vector"], nz.inputs["Vector"])
|
||||
ramp = FN.new("ShaderNodeMapRange")
|
||||
ramp.inputs["From Min"].default_value = 0.42; ramp.inputs["From Max"].default_value = 0.75
|
||||
FL.new(nz.outputs["Fac"], ramp.inputs["Value"])
|
||||
dens = FN.new("ShaderNodeMath"); dens.operation = "MULTIPLY"
|
||||
FL.new(ramp.outputs["Result"], dens.inputs[0])
|
||||
FL.new(dens.outputs["Value"], vol.inputs["Density"])
|
||||
emis = FN.new("ShaderNodeMath"); emis.operation = "MULTIPLY"
|
||||
FL.new(ramp.outputs["Result"], emis.inputs[0])
|
||||
FL.new(emis.outputs["Value"], vol.inputs["Emission Strength"])
|
||||
FL.new(vol.outputs["Volume"], fout.inputs["Volume"])
|
||||
for f, d, e in ((1, 0.0, 0.0), (MAGIC_A - 4, 0.0, 0.0), (MAGIC_A + 10, 0.55, 0.45), (MAGIC_B - 6, 0.55, 0.45), (MAGIC_B + 10, 0.0, 0.0)):
|
||||
key_input(dens.inputs[1], f, d)
|
||||
key_input(emis.inputs[1], f, e)
|
||||
for f, w in ((MAGIC_A - 4, 0.0), (MAGIC_B + 10, 3.0)): # swirling wisps
|
||||
key_input(nz.inputs["W"], f, w)
|
||||
for f, rz in ((MAGIC_A - 4, 0.0), (MAGIC_B + 10, 2.5)):
|
||||
key_input(mp.inputs["Rotation"], f, (0, 0, rz))
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=32, radius=R_IN + 0.25, depth=EMIT_Z - PAD_TOP - 0.2,
|
||||
location=(CX, CY, (EMIT_Z + PAD_TOP) / 2))
|
||||
fog = bpy.context.active_object
|
||||
fog.name = "Gen_Magic_Fog"
|
||||
fog.data.materials.append(fog_mat)
|
||||
for c in list(fog.users_collection):
|
||||
c.objects.unlink(fog)
|
||||
coll.objects.link(fog)
|
||||
try:
|
||||
sc.eevee.volumetric_tile_size = "4"
|
||||
sc.eevee.volumetric_samples = 64
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------ 2d) fast spark bursts where the bolts hit
|
||||
burst_mat = bpy.data.materials.new("Gen_SparkBurst")
|
||||
try:
|
||||
burst_mat.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
kb = next(n for n in burst_mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
|
||||
kb.inputs["Emission Color"].default_value = (1.0, 0.95, 0.7, 1)
|
||||
kb.inputs["Emission Strength"].default_value = 20.0
|
||||
for k in range(36):
|
||||
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, radius=0.05)
|
||||
s = bpy.context.active_object
|
||||
s.name = "Gen_SparkBurst_%02d" % k
|
||||
s.data.materials.append(burst_mat)
|
||||
for c in list(s.users_collection):
|
||||
c.objects.unlink(s)
|
||||
coll.objects.link(s)
|
||||
t = random.randint(MAGIC_A, MAGIC_B - 8)
|
||||
a = random.uniform(0, 2 * math.pi); r = random.uniform(0.3, R_IN - 0.2)
|
||||
p0 = Vector((CX + r * math.cos(a), CY + r * math.sin(a), random.uniform(PAD_TOP + 0.3, EMIT_Z - 0.4)))
|
||||
d = Vector((random.uniform(-1, 1), random.uniform(-1, 1), random.uniform(-0.2, 1.0))).normalized() * random.uniform(0.6, 1.4)
|
||||
key(s, "scale", 1, (0, 0, 0), "CONSTANT")
|
||||
key(s, "scale", t - 1, (0, 0, 0), "LINEAR")
|
||||
key(s, "scale", t, (1.6, 1.6, 1.6))
|
||||
key(s, "scale", t + random.randint(5, 9), (0, 0, 0))
|
||||
key(s, "location", t, p0, "QUAD", "EASE_OUT")
|
||||
key(s, "location", t + 8, p0 + d + Vector((0, 0, -0.3)))
|
||||
|
||||
# ------------------------------------------------------------------ 3) placeholder ornament + game anchor points
|
||||
spawn = bpy.data.objects.get("Ornament_Spawn_Point") or bpy.data.objects.new("Ornament_Spawn_Point", None)
|
||||
spawn.empty_display_type = "SPHERE"; spawn.empty_display_size = 1.2
|
||||
if spawn.name not in coll.objects:
|
||||
coll.objects.link(spawn)
|
||||
spawn.location = (CX, CY, SPAWN_Z)
|
||||
out_pt = bpy.data.objects.get("Ornament_Output_Point") or bpy.data.objects.new("Ornament_Output_Point", None)
|
||||
out_pt.empty_display_type = "SPHERE"; out_pt.empty_display_size = 0.8
|
||||
if out_pt.name not in coll.objects:
|
||||
coll.objects.link(out_pt)
|
||||
|
||||
def placeholder(name, parent):
|
||||
"""Simple red bauble with gold band + cap; replaced by the real ornament in the game."""
|
||||
red = bpy.data.materials.get("Machine_Red"); gold = bpy.data.materials.get("Machine_Gold")
|
||||
bpy.ops.mesh.primitive_uv_sphere_add(segments=24, ring_count=16, radius=1.0)
|
||||
body = bpy.context.active_object; body.name = name; body.data.materials.append(red)
|
||||
bpy.ops.object.shade_smooth()
|
||||
bpy.ops.mesh.primitive_torus_add(major_radius=1.0, minor_radius=0.13)
|
||||
band = bpy.context.active_object; band.name = name + "_Band"; band.data.materials.append(gold)
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=12, radius=0.28, depth=0.3, location=(0, 0, 1.05))
|
||||
cap = bpy.context.active_object; cap.name = name + "_Cap"; cap.data.materials.append(gold)
|
||||
bpy.ops.mesh.primitive_torus_add(major_radius=0.2, minor_radius=0.06, location=(0, 0, 1.32), rotation=(math.radians(90), 0, 0))
|
||||
loop = bpy.context.active_object; loop.name = name + "_Loop"; loop.data.materials.append(gold)
|
||||
for p in (body, band, cap, loop):
|
||||
for c in list(p.users_collection):
|
||||
c.objects.unlink(p)
|
||||
coll.objects.link(p)
|
||||
p.parent = parent
|
||||
return body
|
||||
|
||||
orn = bpy.data.objects.new("Ornament_Anchor_Chamber", None) # carries the chamber motion
|
||||
coll.objects.link(orn)
|
||||
orn.parent = spawn
|
||||
placeholder("Ornament_Placeholder", orn)
|
||||
S = 0.95 # placeholder size in the chamber
|
||||
key(orn, "scale", 1, (0, 0, 0), "CONSTANT")
|
||||
key(orn, "scale", T0 + 27, (0, 0, 0), "BACK", "EASE_OUT")
|
||||
key(orn, "scale", T0 + 40, (S, S, S))
|
||||
key(orn, "rotation_euler", T0 + 27, Euler((0, 0, 0)), "QUAD", "EASE_OUT")
|
||||
key(orn, "rotation_euler", T0 + 46, Euler((0, 0, math.radians(720))), "SINE", "EASE_IN_OUT")
|
||||
key(orn, "rotation_euler", T0 + 64, Euler((0, 0, math.radians(800))))
|
||||
for f, dz in ((T0 + 40, 0.0), (T0 + 48, 0.25), (T0 + 56, -0.1), (T0 + 63, 0.15)): # hover bob
|
||||
key(orn, "location", f, Vector((0, 0, dz)), "SINE", "EASE_IN_OUT")
|
||||
drop_dz = PAD_TOP - SPAWN_Z - 0.2
|
||||
key(orn, "location", T0 + 64, Vector((0, 0, 0.15)), "QUAD", "EASE_IN")
|
||||
key(orn, "location", T0 + 74, Vector((0, 0, drop_dz)))
|
||||
key(orn, "scale", T0 + 64, (S, S, S), "QUAD", "EASE_IN")
|
||||
key(orn, "scale", T0 + 70, (S, S, S * 0.8))
|
||||
key(orn, "scale", T0 + 76, (0, 0, 0))
|
||||
# floor ring flashes as it goes through
|
||||
low = bpy.data.objects["Chamber_GlowRing_Low"]
|
||||
# the ring mesh is built in world space with its origin at 0,0,0 -> scaling would slide it off-centre.
|
||||
# Move the origin to the ring's own centre first (looks identical, but now it pulses in place).
|
||||
ring_c, _ = bbox(low)
|
||||
local_c = low.matrix_world.inverted() @ ring_c
|
||||
if local_c.length > 0.001:
|
||||
if low.data.users > 1:
|
||||
low.data = low.data.copy()
|
||||
from mathutils import Matrix
|
||||
low.data.transform(Matrix.Translation(-local_c))
|
||||
low.matrix_world = low.matrix_world @ Matrix.Translation(local_c)
|
||||
for f, sz in ((T0 + 66, 1.0), (T0 + 72, 1.25), (T0 + 80, 1.0)):
|
||||
key(low, "scale", f, (sz, sz, 1.0), "SINE", "EASE_IN_OUT")
|
||||
|
||||
# ------------------------------------------------------------------ 4) drop out of the chute onto the tray
|
||||
tray_top = tray_c.z + tray_s.z / 2
|
||||
R_OUT = 0.75
|
||||
rest = Vector((tray_c.x, tray_c.y - tray_s.y * 0.12, tray_top + R_OUT * 0.9))
|
||||
out_pt.location = rest
|
||||
start = Vector((tray_c.x, back_c.y - 0.7, ceil_c.z - 0.9))
|
||||
orn2 = bpy.data.objects.new("Ornament_Anchor_Output", None)
|
||||
coll.objects.link(orn2)
|
||||
placeholder("Ornament_Placeholder_Out", orn2)
|
||||
orn2.location = start
|
||||
key(orn2, "scale", 1, (0, 0, 0), "CONSTANT")
|
||||
key(orn2, "scale", T0 + 79, (0, 0, 0), "LINEAR")
|
||||
key(orn2, "scale", T0 + 81, (R_OUT, R_OUT, R_OUT))
|
||||
key(orn2, "scale", T0 + 89, (R_OUT * 1.12, R_OUT * 1.12, R_OUT * 0.8), "QUAD", "EASE_OUT") # squash on landing
|
||||
key(orn2, "scale", T0 + 93, (R_OUT, R_OUT, R_OUT))
|
||||
key(orn2, "location", T0 + 80, start, "QUAD", "EASE_IN")
|
||||
key(orn2, "location", T0 + 89, rest + Vector((0, 0.4, -0.05)), "QUAD", "EASE_OUT")
|
||||
key(orn2, "location", T0 + 94, rest + Vector((0, 0.1, 0.55)), "QUAD", "EASE_IN") # bounce
|
||||
key(orn2, "location", T0 + 99, rest + Vector((0, -0.05, 0)), "QUAD", "EASE_OUT")
|
||||
key(orn2, "location", T0 + 102, rest + Vector((0, 0, 0.12)), "QUAD", "EASE_IN")
|
||||
key(orn2, "location", T0 + 105, rest)
|
||||
key(orn2, "rotation_euler", T0 + 80, Euler((0, 0, 0)))
|
||||
key(orn2, "rotation_euler", T0 + 105, Euler((math.radians(-35), 0, math.radians(25))), "SINE", "EASE_OUT")
|
||||
key(orn2, "rotation_euler", T0 + 118, Euler((math.radians(-10), 0, math.radians(20))))
|
||||
chute_light = bpy.data.objects.get("Gen_Chute_Light")
|
||||
if chute_light:
|
||||
e0 = chute_light.data.energy
|
||||
for f, e in ((T0 + 76, e0), (T0 + 82, e0 * 3), (T0 + 96, e0)):
|
||||
chute_light.data.energy = e; chute_light.data.keyframe_insert("energy", frame=f)
|
||||
|
||||
# ------------------------------------------------------------------ generator camera, save, renders
|
||||
cam = bpy.data.objects.get("Generator_Cam")
|
||||
if cam is None:
|
||||
cam = bpy.data.objects.new("Generator_Cam", bpy.data.cameras.new("Generator_Cam"))
|
||||
sc.collection.objects.link(cam)
|
||||
target = Vector((CX, CY - 2.0, (tray_c.z + EMIT_Z) / 2 + 0.5))
|
||||
cam.location = target + Vector((-6.0, -24.0, 4.0))
|
||||
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
cam.data.lens = 50
|
||||
bpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)
|
||||
|
||||
main_cam = sc.camera
|
||||
out_dir = os.path.join(os.path.dirname(bpy.data.filepath), "generator_anim")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
sc.camera = cam
|
||||
sc.render.resolution_x = sc.render.resolution_y = 900
|
||||
if "--video" in sys.argv:
|
||||
sc.render.resolution_x = sc.render.resolution_y = 720
|
||||
if hasattr(sc.render.image_settings, "media_type"):
|
||||
sc.render.image_settings.media_type = "VIDEO"
|
||||
sc.render.image_settings.file_format = "FFMPEG"
|
||||
sc.render.ffmpeg.format = "MPEG4"; sc.render.ffmpeg.codec = "H264"
|
||||
sc.render.ffmpeg.constant_rate_factor = "MEDIUM"
|
||||
sc.frame_start, sc.frame_end = T0 - 5, T0 + 125
|
||||
sc.render.filepath = os.path.join(out_dir, "generator_preview.mp4")
|
||||
bpy.ops.render.render(animation=True)
|
||||
else:
|
||||
for f in (T0 + 2, T0 + 24, T0 + 33, T0 + 44, T0 + 52, T0 + 70, T0 + 88, T0 + 118):
|
||||
sc.frame_set(f)
|
||||
sc.render.filepath = os.path.join(out_dir, "gen_frame_%03d.png" % f)
|
||||
bpy.ops.render.render(write_still=True)
|
||||
sc.camera = main_cam
|
||||
print("DONE generator animation", bpy.data.filepath)
|
||||
@@ -0,0 +1,249 @@
|
||||
# Shredder animation for ornament_machine_new_bow.blend.
|
||||
# Run: blender -b ornament_machine_new_bow.blend --python animate_shredder.py [-- --video]
|
||||
# Result is saved as ornament_machine_new_bow_anim.blend (the source file is not touched).
|
||||
#
|
||||
# Timeline (24 fps):
|
||||
# 1-14 drums spin up
|
||||
# 14-120 shards drop in from the hopper, get dragged down by the drums, shrink to grit that piles on the floor
|
||||
# 120-142 drums slow down and stop, grit drains away
|
||||
# 128-180 shards pour out of the output chute onto the tray, bounce and settle
|
||||
import bpy, math, os, random, sys
|
||||
from mathutils import Vector, Matrix, Euler
|
||||
|
||||
random.seed(12)
|
||||
sc = bpy.context.scene
|
||||
FPS = 24
|
||||
sc.render.fps = FPS
|
||||
sc.frame_start, sc.frame_end = 1, 180
|
||||
SPIN_UP, STOP_START, STOP_END = 14, 120, 142
|
||||
SPEED = 2 * math.pi * 1.1 / FPS # drum speed: 1.1 rev/s
|
||||
src_path = bpy.data.filepath
|
||||
out_path = os.path.splitext(src_path)[0] + "_anim.blend"
|
||||
|
||||
def bbox(o):
|
||||
cs = [o.matrix_world @ Vector(c) for c in o.bound_box]
|
||||
lo = Vector(map(min, *cs)); hi = Vector(map(max, *cs))
|
||||
return (lo + hi) / 2, hi - lo
|
||||
|
||||
def key(ob, path, frame, value=None, interp=None, easing=None):
|
||||
if value is not None:
|
||||
setattr(ob, path, value)
|
||||
ob.keyframe_insert(data_path=path, frame=frame)
|
||||
if interp:
|
||||
fc = ob.animation_data.action
|
||||
# newest keyframes on this path get the requested interpolation
|
||||
for c in fcurves_of(ob):
|
||||
if c.data_path == path:
|
||||
for kp in c.keyframe_points:
|
||||
if abs(kp.co.x - frame) < 0.01:
|
||||
kp.interpolation = interp
|
||||
if easing:
|
||||
kp.easing = easing
|
||||
|
||||
def fcurves_of(ob):
|
||||
act = ob.animation_data.action if ob.animation_data else None
|
||||
if act is None:
|
||||
return []
|
||||
try:
|
||||
return list(act.fcurves)
|
||||
except AttributeError: # Blender 5.x slotted/layered actions
|
||||
out = []
|
||||
for layer in act.layers:
|
||||
for strip in layer.strips:
|
||||
for bag in strip.channelbags:
|
||||
out += list(bag.fcurves)
|
||||
return out
|
||||
|
||||
# ------------------------------------------------------------------ chamber geometry from the model
|
||||
floor_c, _ = bbox(bpy.data.objects["Rec_Chamber_Floor"])
|
||||
ceil_c, _ = bbox(bpy.data.objects["Rec_Chamber_Ceiling"])
|
||||
glass_c, _ = bbox(bpy.data.objects["Rec_Window_Glass"])
|
||||
tray_c, tray_s = bbox(bpy.data.objects["Rec_Tray_Floor"])
|
||||
chute_ceil_c, _ = bbox(bpy.data.objects["Rec_Chute_Ceiling"])
|
||||
chute_back_c, _ = bbox(bpy.data.objects["Rec_Chute_BackWall"])
|
||||
FLOOR_Z = floor_c.z + 0.08
|
||||
CEIL_Z = ceil_c.z - 0.08
|
||||
FRONT_Y = glass_c.y + 0.2
|
||||
|
||||
# ------------------------------------------------------------------ drums: pivot empties on each drum axis
|
||||
drum_parts = [o for o in bpy.data.objects if o.type == "MESH" and o.name.startswith("Rec_Drum")]
|
||||
cores = sorted([o for o in drum_parts if o.name.startswith("Rec_Drum_Core")], key=lambda o: bbox(o)[0].x)
|
||||
pivots = []
|
||||
for i, core in enumerate(cores):
|
||||
c, s = bbox(core)
|
||||
e = bpy.data.objects.new("Rec_Drum_Pivot_%s" % ("L" if i == 0 else "R"), None)
|
||||
e.empty_display_type = "ARROWS"; e.empty_display_size = 0.8
|
||||
e.location = c
|
||||
sc.collection.objects.link(e)
|
||||
pivots.append((e, c, s))
|
||||
bpy.context.view_layer.update()
|
||||
DRUM_Y, DRUM_Z = pivots[0][1].y, pivots[0][1].z
|
||||
DRUM_R = max(bbox(o)[1].z for o in drum_parts) / 2
|
||||
for o in drum_parts:
|
||||
c, _ = bbox(o)
|
||||
e = min(pivots, key=lambda p: abs(p[1].x - c.x))[0]
|
||||
mw = o.matrix_world.copy()
|
||||
o.parent = e
|
||||
o.matrix_parent_inverse = e.matrix_world.inverted()
|
||||
o.matrix_world = mw
|
||||
DRUM_X = [p[1].x for p in pivots]
|
||||
DRUM_HALF = max(p[2].x for p in pivots) / 2
|
||||
|
||||
# spin: ease-in start, constant speed, ease-out stop (opposite directions so the pair reads as a crusher)
|
||||
for idx, (e, c, s) in enumerate(pivots):
|
||||
d = 1 if idx == 0 else -1
|
||||
spin_end = SPEED * (STOP_START - SPIN_UP) + SPEED * SPIN_UP / 2
|
||||
e.rotation_euler = (0, 0, 0)
|
||||
key(e, "rotation_euler", 1, (0, 0, 0), "QUAD", "EASE_IN")
|
||||
key(e, "rotation_euler", SPIN_UP, (d * SPEED * SPIN_UP / 2, 0, 0), "LINEAR")
|
||||
key(e, "rotation_euler", STOP_START, (d * spin_end, 0, 0), "QUAD", "EASE_OUT")
|
||||
key(e, "rotation_euler", STOP_END, (d * (spin_end + SPEED * (STOP_END - STOP_START) / 2), 0, 0))
|
||||
# a little vibration while grinding
|
||||
e.location = c
|
||||
key(e, "location", SPIN_UP, c.copy())
|
||||
key(e, "location", STOP_START, c.copy())
|
||||
for idx, (e, c, s) in enumerate(pivots):
|
||||
for fc in fcurves_of(e):
|
||||
if fc.data_path == "location" and fc.array_index == 2:
|
||||
nm = fc.modifiers.new("NOISE"); nm.scale = 2.0; nm.strength = 0.05
|
||||
nm.use_restricted_range = True; nm.frame_start, nm.frame_end = SPIN_UP, STOP_START
|
||||
nm.blend_in, nm.blend_out = 6, 10
|
||||
|
||||
# ------------------------------------------------------------------ crystal prototypes
|
||||
floor_crystals = [o for o in bpy.data.objects if o.name.startswith("Rec_CrusherCrystal")]
|
||||
proto = floor_crystals[0]
|
||||
coll = bpy.data.collections.get("Shredder_Anim") or bpy.data.collections.new("Shredder_Anim")
|
||||
if coll.name not in sc.collection.children:
|
||||
sc.collection.children.link(coll)
|
||||
|
||||
def new_crystal(name, scale):
|
||||
o = bpy.data.objects.new(name, proto.data)
|
||||
coll.objects.link(o)
|
||||
o.scale = (scale, scale, scale)
|
||||
return o
|
||||
|
||||
def hide_until(o, frame, full_scale):
|
||||
key(o, "scale", 1, (0, 0, 0), "CONSTANT")
|
||||
key(o, "scale", frame - 1, (0, 0, 0), "LINEAR")
|
||||
key(o, "scale", frame + 1, (full_scale,) * 3)
|
||||
|
||||
def set_origin_to_center(o):
|
||||
"""Crystals were built in world space with the origin at 0; re-centre so scale/rotation act on the crystal."""
|
||||
c, _ = bbox(o)
|
||||
if (o.location - c).length > 0.01 and o.data.users == 1:
|
||||
o.data.transform(Matrix.Translation(-(o.matrix_world.inverted() @ c)))
|
||||
o.location = c
|
||||
return c
|
||||
|
||||
# the original floor crystals become the grit that builds up while grinding, then drains away
|
||||
proto_center = set_origin_to_center(proto)
|
||||
grit = []
|
||||
for k, o in enumerate(floor_crystals):
|
||||
if o is not proto:
|
||||
if o.data.users > 1:
|
||||
o.data = o.data.copy()
|
||||
set_origin_to_center(o)
|
||||
grit.append(o)
|
||||
proto_size = bbox(proto)[1].length
|
||||
# from here on new crystals reuse the (now centred) proto mesh
|
||||
|
||||
# ------------------------------------------------------------------ shards dropping in and being ground
|
||||
N_SHARDS = 18
|
||||
for i in range(N_SHARDS):
|
||||
s = SPIN_UP + 4 + i * 5.6
|
||||
x = random.choice(DRUM_X) + random.uniform(-DRUM_HALF * 0.7, DRUM_HALF * 0.7)
|
||||
sc0 = random.uniform(1.1, 1.5)
|
||||
o = new_crystal("Shard_%02d" % i, sc0)
|
||||
o.location = (x, DRUM_Y + DRUM_R * 0.6, CEIL_Z - 0.15)
|
||||
hide_until(o, int(s), sc0)
|
||||
path = [ # frame offset, position, scale factor
|
||||
(0, (x, DRUM_Y + DRUM_R * 0.55, CEIL_Z - 0.15), 1.0),
|
||||
(5, (x, DRUM_Y - DRUM_R * 0.3, DRUM_Z + DRUM_R + 0.08), 0.95), # lands on top of the drum
|
||||
(11, (x + random.uniform(-0.1, 0.1), DRUM_Y - DRUM_R - 0.22, DRUM_Z + DRUM_R * 0.3), 0.6), # dragged over the front
|
||||
(16, (x, DRUM_Y - DRUM_R - 0.25, DRUM_Z - DRUM_R * 0.5), 0.3), # crushed
|
||||
(20, (x, DRUM_Y - DRUM_R * 0.6, FLOOR_Z + 0.1), 0.0), # gone to grit
|
||||
]
|
||||
for off, pos, f in path:
|
||||
key(o, "location", int(s) + off, Vector(pos))
|
||||
key(o, "scale", int(s) + off, (sc0 * f,) * 3)
|
||||
rot0 = Euler([random.uniform(0, 6.28) for _ in range(3)])
|
||||
key(o, "rotation_euler", int(s), rot0)
|
||||
key(o, "rotation_euler", int(s) + 20, Euler([a + random.uniform(4, 9) for a in rot0]))
|
||||
|
||||
# grit appears bit by bit on the floor, then drains away after the drums stop
|
||||
for k, o in enumerate(grit):
|
||||
full = o.scale[0]
|
||||
t = SPIN_UP + 28 + k * (STOP_START - SPIN_UP - 34) / max(1, len(grit))
|
||||
hide_until(o, int(t), full)
|
||||
key(o, "scale", STOP_END - 4, (full,) * 3)
|
||||
key(o, "scale", STOP_END + 4 + k % 4, (0, 0, 0))
|
||||
|
||||
# chamber light pulses while grinding
|
||||
lt = bpy.data.objects.get("Rec_Chamber_Light")
|
||||
if lt:
|
||||
base = lt.data.energy
|
||||
for f, e in ((1, base), (SPIN_UP, base * 1.8), (STOP_START, base * 1.8), (STOP_END, base)):
|
||||
lt.data.energy = e; lt.data.keyframe_insert("energy", frame=f)
|
||||
act = lt.data.animation_data.action
|
||||
for fc in fcurves_of(lt.data):
|
||||
nm = fc.modifiers.new("NOISE"); nm.scale = 3; nm.strength = base * 0.5
|
||||
nm.use_restricted_range = True; nm.frame_start, nm.frame_end = SPIN_UP, STOP_START
|
||||
|
||||
# ------------------------------------------------------------------ shards pour out onto the tray and settle
|
||||
N_OUT = 20
|
||||
tray_top = tray_c.z + tray_s.z / 2
|
||||
for i in range(N_OUT):
|
||||
t0 = 128 + i * 2.2
|
||||
sc0 = random.uniform(1.2, 1.7)
|
||||
o = new_crystal("Output_Shard_%02d" % i, sc0)
|
||||
start = Vector((tray_c.x + random.uniform(-1.0, 1.0), chute_back_c.y - 0.5, chute_ceil_c.z - 0.45))
|
||||
# pile: lower-front of the sloped tray first, then stacking up
|
||||
gx = tray_c.x + random.uniform(-tray_s.x * 0.36, tray_s.x * 0.36)
|
||||
gy = tray_c.y + random.uniform(-tray_s.y * 0.3, tray_s.y * 0.15)
|
||||
# tray slopes: lower toward the inside; follow the floor height at that y
|
||||
slope = (tray_s.z - 0.28) / max(tray_s.y, 0.01)
|
||||
gz = tray_top + 0.25 + (i // 7) * 0.22 + (gy - tray_c.y) * slope
|
||||
end = Vector((gx, gy, gz))
|
||||
o.location = start
|
||||
hide_until(o, int(t0), sc0)
|
||||
key(o, "location", int(t0), start, "QUAD", "EASE_IN") # free fall
|
||||
key(o, "location", int(t0) + 8, end, "QUAD", "EASE_OUT")
|
||||
key(o, "location", int(t0) + 11, end + Vector((random.uniform(-0.1, 0.1), -0.08, 0.3)), "QUAD", "EASE_IN") # bounce
|
||||
key(o, "location", int(t0) + 14, end)
|
||||
r0 = Euler([random.uniform(0, 6.28) for _ in range(3)])
|
||||
key(o, "rotation_euler", int(t0), r0)
|
||||
key(o, "rotation_euler", int(t0) + 14, Euler([a + random.uniform(2, 5) for a in r0]))
|
||||
|
||||
# ------------------------------------------------------------------ shredder close-up camera (main camera kept)
|
||||
cam_data = bpy.data.cameras.new("Shredder_Cam")
|
||||
cam = bpy.data.objects.new("Shredder_Cam", cam_data)
|
||||
sc.collection.objects.link(cam)
|
||||
target = Vector((tray_c.x, glass_c.y, (tray_c.z + ceil_c.z) / 2))
|
||||
cam.location = target + Vector((5.0, -17.0, 3.5))
|
||||
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
cam_data.lens = 50
|
||||
|
||||
main_cam = sc.camera
|
||||
bpy.ops.wm.save_as_mainfile(filepath=out_path)
|
||||
|
||||
# check frames (+ optional preview video) from the close-up camera
|
||||
render_dir = os.path.join(os.path.dirname(src_path), "shredder_anim")
|
||||
os.makedirs(render_dir, exist_ok=True)
|
||||
sc.camera = cam
|
||||
sc.render.resolution_x = sc.render.resolution_y = 900
|
||||
for f in (() if "--video" in sys.argv else (8, 45, 75, 130, 150, 178)):
|
||||
sc.frame_set(f)
|
||||
sc.render.filepath = os.path.join(render_dir, "frame_%03d.png" % f)
|
||||
bpy.ops.render.render(write_still=True)
|
||||
if "--video" in sys.argv:
|
||||
sc.render.resolution_x = sc.render.resolution_y = 720
|
||||
if hasattr(sc.render.image_settings, "media_type"): # Blender 5.x: pick video output first
|
||||
sc.render.image_settings.media_type = "VIDEO"
|
||||
sc.render.image_settings.file_format = "FFMPEG"
|
||||
sc.render.ffmpeg.format = "MPEG4"
|
||||
sc.render.ffmpeg.codec = "H264"
|
||||
sc.render.ffmpeg.constant_rate_factor = "MEDIUM"
|
||||
sc.render.filepath = os.path.join(render_dir, "shredder_preview.mp4")
|
||||
bpy.ops.render.render(animation=True)
|
||||
sc.camera = main_cam
|
||||
print("SAVED", out_path, "drums", len(drum_parts), "shards", N_SHARDS, "grit", len(grit), "out", N_OUT)
|
||||
@@ -0,0 +1,523 @@
|
||||
# Export the animated ornament machine for Roblox (local files only, nothing is uploaded).
|
||||
# Run: blender -b ornament_machine_new_bow_anim.blend --python export_roblox.py
|
||||
#
|
||||
# Output: machine/roblox_export/
|
||||
# textures/Machine_Palette_{Color,Metalness,Roughness,Emissive}.png
|
||||
# Every material of the machine is a flat colour, so they are packed into ONE 256x256 palette
|
||||
# (8x8 cells of 32 px); each face's UVs point at the centre of its material's cell.
|
||||
# OrnamentMachine.fbx / .glb full model in rest pose + rig (armature "MachineRig")
|
||||
# Body_XX static opaque geometry merged into chunks <= 18k triangles
|
||||
# Glow_<Colour> emissive geometry (set Material = Neon in Studio)
|
||||
# Glass_Chamber / Glass_Window, Chamber_GlowRing_Low, Rec_CrusherCrystal_XX
|
||||
# Drum_L / Drum_R / Gen_Button rigid parts skinned 100% to the bones of the same name
|
||||
# bones Ornament_Chamber / Ornament_Output: anchor points for the real ornament
|
||||
# OrnamentMachine_Shredder.fbx rig + animation, frames 1-180 -> 0-179
|
||||
# OrnamentMachine_Generator.fbx rig + animation, frames 200-325 -> 0-125
|
||||
# OrnamentMachine_FX.fbx FX prototypes: shard, lightning bolts, placeholder ornament
|
||||
# machine_timeline.json markers + everything Roblox bones can not play (visibility, scale,
|
||||
# light energy, emission strength, fog), sampled per frame
|
||||
import bpy, bmesh, json, math, os
|
||||
from mathutils import Matrix, Vector
|
||||
|
||||
sc = bpy.context.scene
|
||||
HERE = os.path.dirname(bpy.data.filepath)
|
||||
OUT = os.path.join(HERE, "roblox_export")
|
||||
TEXDIR = os.path.join(OUT, "textures")
|
||||
os.makedirs(TEXDIR, exist_ok=True)
|
||||
FPS = sc.render.fps
|
||||
CELL, GRID = 32, 8
|
||||
TEX = CELL * GRID
|
||||
MAX_TRIS = 18000
|
||||
CLIPS = {"Shredder": (1, 180), "Generator": (200, 325)}
|
||||
REST_FRAME = 0
|
||||
|
||||
FX_PREFIX = ("Gen_Lightning", "Gen_SparkBurst", "Gen_Sparkle", "Gen_Magic_Beam", "Gen_Magic_Fog",
|
||||
"Shard_", "Output_Shard_", "Ornament_Placeholder")
|
||||
GLASS = {"Chamber_Glass": "Glass_Chamber", "Rec_Window_Glass": "Glass_Window"}
|
||||
SINGLE = {"Chamber_GlowRing_Low": "Chamber_GlowRing_Low"}
|
||||
# bone name -> (source object whose world motion the bone copies, rest frame, mesh objects skinned to it)
|
||||
BONES = {
|
||||
"Drum_L": ("Rec_Drum_Pivot_L", 1, None),
|
||||
"Drum_R": ("Rec_Drum_Pivot_R", 1, None),
|
||||
"Gen_Button": ("Gen_Button_Face", 199, ["Gen_Button_Face", "Gen_Button_Inner", "Gen_Button_Star_Outline"]),
|
||||
# shredder button: not animated in Blender, but it must be its own part so Roblox can press it
|
||||
# (its glowing arrows stay the separate Glow_White part and are moved together with it)
|
||||
"Rec_Button": ("Rec_Button_Face", 0, ["Rec_Button_Face", "Rec_Button_Inner"]),
|
||||
"Ornament_Chamber": ("Ornament_Anchor_Chamber", 240, []),
|
||||
"Ornament_Output": ("Ornament_Anchor_Output", 325, []),
|
||||
}
|
||||
|
||||
def to_srgb(c):
|
||||
c = max(0.0, min(1.0, c))
|
||||
return 12.92 * c if c <= 0.0031308 else 1.055 * (c ** (1 / 2.4)) - 0.055
|
||||
|
||||
def principled(m):
|
||||
if not m or not m.node_tree:
|
||||
return None
|
||||
return next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
|
||||
|
||||
def is_glow(m):
|
||||
bs = principled(m)
|
||||
return bool(bs) and bs.inputs["Emission Strength"].default_value >= 1.0
|
||||
|
||||
# ------------------------------------------------------------------ palette
|
||||
sc.frame_set(REST_FRAME)
|
||||
palette = {} # material name -> cell index
|
||||
cell_info = []
|
||||
|
||||
def cell_of(m):
|
||||
name = m.name if m else "__none__"
|
||||
if name not in palette:
|
||||
bs = principled(m)
|
||||
if bs:
|
||||
bc = list(bs.inputs["Base Color"].default_value[:3])
|
||||
ec = list(bs.inputs["Emission Color"].default_value[:3])
|
||||
es = bs.inputs["Emission Strength"].default_value
|
||||
metal = bs.inputs["Metallic"].default_value
|
||||
rough = bs.inputs["Roughness"].default_value
|
||||
else:
|
||||
bc, ec, es, metal, rough = [0.7, 0.7, 0.7], [0, 0, 0], 0.0, 0.0, 0.5
|
||||
colour = ec if es >= 1.0 else bc # glow parts read as their light colour
|
||||
palette[name] = len(palette)
|
||||
cell_info.append({"material": name, "color": colour, "metal": metal, "rough": rough,
|
||||
"emissive": 1.0 if es >= 1.0 else min(1.0, es)})
|
||||
if len(palette) > GRID * GRID:
|
||||
raise RuntimeError("palette overflow")
|
||||
i = palette[name]
|
||||
return (((i % GRID) + 0.5) / GRID, ((i // GRID) + 0.5) / GRID)
|
||||
|
||||
def save_maps():
|
||||
maps = {"Color": lambda c: [to_srgb(v) for v in c["color"]],
|
||||
"Metalness": lambda c: [c["metal"]] * 3,
|
||||
"Roughness": lambda c: [c["rough"]] * 3,
|
||||
"Emissive": lambda c: [c["emissive"]] * 3}
|
||||
imgs = {}
|
||||
for kind, fn in maps.items():
|
||||
px = [0.0] * (TEX * TEX * 4)
|
||||
for i, c in enumerate(cell_info):
|
||||
r, g, b = fn(c)
|
||||
cx, cy = (i % GRID) * CELL, (i // GRID) * CELL
|
||||
for y in range(cy, cy + CELL):
|
||||
row = y * TEX
|
||||
for x in range(cx, cx + CELL):
|
||||
k = (row + x) * 4
|
||||
px[k:k + 4] = (r, g, b, 1.0)
|
||||
img = bpy.data.images.new("Machine_Palette_" + kind, TEX, TEX, alpha=False)
|
||||
if kind != "Color":
|
||||
img.colorspace_settings.name = "Non-Color"
|
||||
img.pixels = px
|
||||
img.filepath_raw = os.path.join(TEXDIR, img.name + ".png")
|
||||
img.file_format = "PNG"
|
||||
img.save()
|
||||
img.filepath = img.filepath_raw
|
||||
imgs[kind] = img
|
||||
return imgs
|
||||
|
||||
# ------------------------------------------------------------------ geometry helpers
|
||||
def world_bm(o):
|
||||
"""Evaluated world-space geometry of o with palette UVs; face.material_index = palette cell."""
|
||||
dg = bpy.context.evaluated_depsgraph_get()
|
||||
me = bpy.data.meshes.new_from_object(o.evaluated_get(dg))
|
||||
me.transform(o.matrix_world)
|
||||
if o.matrix_world.determinant() < 0:
|
||||
me.flip_normals()
|
||||
mats = [s.material for s in o.material_slots] or [None]
|
||||
real = [m for m in mats if m] or [None]
|
||||
bm = bmesh.new()
|
||||
bm.from_mesh(me)
|
||||
bpy.data.meshes.remove(me)
|
||||
for l in list(bm.loops.layers.uv):
|
||||
bm.loops.layers.uv.remove(l)
|
||||
uv = bm.loops.layers.uv.new("UVMap")
|
||||
for f in bm.faces:
|
||||
m = mats[f.material_index] if f.material_index < len(mats) else real[0]
|
||||
m = m or real[0]
|
||||
u = cell_of(m)
|
||||
f.material_index = palette[m.name if m else "__none__"]
|
||||
for lp in f.loops:
|
||||
lp[uv].uv = u
|
||||
return bm
|
||||
|
||||
def face_glow(bm):
|
||||
names = {v: k for k, v in palette.items()}
|
||||
return {f: is_glow(bpy.data.materials.get(names[f.material_index])) for f in bm.faces}
|
||||
|
||||
def bm_subset(bm, keep):
|
||||
c = bm.copy()
|
||||
kill = [f for f, src in zip(c.faces, bm.faces) if not keep(src)]
|
||||
bmesh.ops.delete(c, geom=kill, context="FACES")
|
||||
return c
|
||||
|
||||
def append_bm(dst, src):
|
||||
me = bpy.data.meshes.new("_tmp")
|
||||
src.to_mesh(me)
|
||||
dst.from_mesh(me)
|
||||
bpy.data.meshes.remove(me)
|
||||
|
||||
def tris(bm):
|
||||
return sum(len(f.verts) - 2 for f in bm.faces)
|
||||
|
||||
export_coll = bpy.data.collections.new("RobloxExport")
|
||||
sc.collection.children.link(export_coll)
|
||||
|
||||
def make_obj(name, bm, mat, origin=None):
|
||||
"""bm (world space) -> object named name with origin at its bbox centre (or origin)."""
|
||||
if origin is None:
|
||||
if not bm.verts:
|
||||
origin = Vector()
|
||||
else:
|
||||
lo = Vector(map(min, *[v.co for v in bm.verts])); hi = Vector(map(max, *[v.co for v in bm.verts]))
|
||||
origin = (lo + hi) / 2
|
||||
bmesh.ops.translate(bm, verts=bm.verts, vec=-origin)
|
||||
for f in bm.faces:
|
||||
f.material_index = 0
|
||||
me = bpy.data.meshes.new(name)
|
||||
bm.to_mesh(me)
|
||||
bm.free()
|
||||
for p in me.polygons:
|
||||
p.use_smooth = False
|
||||
me.materials.append(mat)
|
||||
ob = bpy.data.objects.new(name, me)
|
||||
ob.location = origin
|
||||
export_coll.objects.link(ob)
|
||||
return ob
|
||||
|
||||
# ------------------------------------------------------------------ classify the model
|
||||
objs = [o for o in bpy.data.objects if o.type in ("MESH", "CURVE", "FONT")]
|
||||
fx_objs = [o for o in objs if o.name.startswith(FX_PREFIX)]
|
||||
bone_mesh = {}
|
||||
for b, (src, _, meshes) in BONES.items():
|
||||
if meshes is None:
|
||||
meshes = [c.name for c in bpy.data.objects[src].children_recursive if c.type in ("MESH", "CURVE")]
|
||||
bone_mesh[b] = meshes
|
||||
skinned = {n for v in bone_mesh.values() for n in v}
|
||||
crystals = sorted(o.name for o in objs if o.name.startswith("Rec_CrusherCrystal"))
|
||||
static = [o for o in objs if o not in fx_objs and o.name not in skinned and o.name not in GLASS
|
||||
and o.name not in SINGLE and o.name not in crystals and (not o.hide_render or o.name in GLASS)]
|
||||
|
||||
body_parts, glow_parts = [], {}
|
||||
for o in sorted(static, key=lambda o: (o.matrix_world @ (sum((Vector(c) for c in o.bound_box), Vector()) / 8)).x):
|
||||
bm = world_bm(o)
|
||||
g = face_glow(bm)
|
||||
names = {v: k for k, v in palette.items()}
|
||||
opaque = bm_subset(bm, lambda f: not g[f])
|
||||
if opaque.faces:
|
||||
body_parts.append((o.name, opaque))
|
||||
else:
|
||||
opaque.free()
|
||||
for cell in {f.material_index for f in bm.faces if g[f]}:
|
||||
sub = bm_subset(bm, lambda f, c=cell: g[f] and f.material_index == c)
|
||||
glow_parts.setdefault(names[cell], []).append(sub)
|
||||
bm.free()
|
||||
|
||||
imgs = None # palette is complete only after every object is visited -> build materials afterwards
|
||||
pending = [] # (name, bm, kind, origin)
|
||||
|
||||
chunk, chunk_tris, chunk_i = bmesh.new(), 0, 1
|
||||
for name, bm in body_parts:
|
||||
t = tris(bm)
|
||||
if chunk_tris and chunk_tris + t > MAX_TRIS:
|
||||
pending.append(("Body_%02d" % chunk_i, chunk, "opaque", None)); chunk_i += 1
|
||||
chunk, chunk_tris = bmesh.new(), 0
|
||||
append_bm(chunk, bm); chunk_tris += t; bm.free()
|
||||
if chunk.faces:
|
||||
pending.append(("Body_%02d" % chunk_i, chunk, "opaque", None))
|
||||
|
||||
for mname, parts in glow_parts.items():
|
||||
bm = bmesh.new()
|
||||
for p in parts:
|
||||
append_bm(bm, p); p.free()
|
||||
pending.append(("Glow_" + mname.replace("Glow_", "").replace("Gen_", ""), bm, "glow", None))
|
||||
|
||||
for src, dst in GLASS.items():
|
||||
pending.append((dst, world_bm(bpy.data.objects[src]), "glass", None))
|
||||
for src, dst in SINGLE.items():
|
||||
pending.append((dst, world_bm(bpy.data.objects[src]), "glow", None))
|
||||
sc.frame_set(60) # crusher crystals are scaled to 0 at rest; take them at full size
|
||||
for i, n in enumerate(crystals):
|
||||
pending.append(("Rec_CrusherCrystal_%02d" % i, world_bm(bpy.data.objects[n]), "glow", None))
|
||||
sc.frame_set(REST_FRAME)
|
||||
|
||||
# bone rest matrices (scale removed)
|
||||
def clean(m):
|
||||
loc, rot, _ = m.decompose()
|
||||
return Matrix.Translation(loc) @ rot.to_matrix().to_4x4()
|
||||
|
||||
rest = {}
|
||||
for b, (src, rf, _) in BONES.items():
|
||||
sc.frame_set(rf)
|
||||
rest[b] = clean(bpy.data.objects[src].matrix_world)
|
||||
sc.frame_set(REST_FRAME)
|
||||
for b, meshes in bone_mesh.items():
|
||||
if not meshes:
|
||||
continue
|
||||
bm = bmesh.new()
|
||||
for n in meshes:
|
||||
part = world_bm(bpy.data.objects[n]); append_bm(bm, part); part.free()
|
||||
pending.append((b, bm, "glowmix", rest[b].translation.copy()))
|
||||
|
||||
# ------------------------------------------------------------------ materials
|
||||
imgs = save_maps()
|
||||
|
||||
def palette_mat(name, glow=False, glass=False):
|
||||
m = bpy.data.materials.new(name)
|
||||
try:
|
||||
m.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
nt = m.node_tree
|
||||
nt.nodes.clear()
|
||||
out = nt.nodes.new("ShaderNodeOutputMaterial")
|
||||
bs = nt.nodes.new("ShaderNodeBsdfPrincipled")
|
||||
nt.links.new(bs.outputs["BSDF"], out.inputs["Surface"])
|
||||
def tex(kind, sock):
|
||||
t = nt.nodes.new("ShaderNodeTexImage")
|
||||
t.image = imgs[kind]
|
||||
t.interpolation = "Closest"
|
||||
nt.links.new(t.outputs["Color"], bs.inputs[sock])
|
||||
return t
|
||||
tex("Color", "Base Color"); tex("Metalness", "Metallic"); tex("Roughness", "Roughness")
|
||||
if glow:
|
||||
tex("Color", "Emission Color")
|
||||
bs.inputs["Emission Strength"].default_value = 1.0
|
||||
if glass:
|
||||
bs.inputs["Alpha"].default_value = 0.3
|
||||
m.surface_render_method = "BLENDED"
|
||||
return m
|
||||
|
||||
MATS = {"opaque": palette_mat("Machine_Palette"), "glow": palette_mat("Machine_Palette_Glow", glow=True),
|
||||
"glass": palette_mat("Machine_Glass", glass=True)}
|
||||
MATS["glowmix"] = MATS["opaque"]
|
||||
|
||||
made = {}
|
||||
for name, bm, kind, origin in pending:
|
||||
made[name] = (make_obj(name, bm, MATS[kind], origin), kind)
|
||||
|
||||
# glow sub-parts of skinned groups (button star) stay in the same mesh; Studio can't split a MeshPart,
|
||||
# so mark the emissive cells via the Emissive map instead.
|
||||
|
||||
# ------------------------------------------------------------------ rig
|
||||
arm_data = bpy.data.armatures.new("MachineRig")
|
||||
rig = bpy.data.objects.new("MachineRig", arm_data)
|
||||
export_coll.objects.link(rig)
|
||||
bpy.context.view_layer.objects.active = rig
|
||||
for o in bpy.context.view_layer.objects:
|
||||
o.select_set(False)
|
||||
rig.select_set(True)
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
root = arm_data.edit_bones.new("Root")
|
||||
root.head, root.tail = (0, 0, 0), (0, 0, 1.0)
|
||||
for b in BONES:
|
||||
eb = arm_data.edit_bones.new(b)
|
||||
eb.head, eb.tail = (0, 0, 0), (0, 0.6, 0)
|
||||
eb.matrix = rest[b]
|
||||
eb.length = 0.6
|
||||
eb.parent = root
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
|
||||
for b, meshes in bone_mesh.items():
|
||||
if b not in made:
|
||||
continue
|
||||
ob = made[b][0]
|
||||
vg = ob.vertex_groups.new(name=b)
|
||||
vg.add(list(range(len(ob.data.vertices))), 1.0, "REPLACE")
|
||||
ob.parent = rig
|
||||
ob.matrix_parent_inverse = rig.matrix_world.inverted()
|
||||
mod = ob.modifiers.new("Armature", "ARMATURE")
|
||||
mod.object = rig
|
||||
for name, (ob, kind) in made.items():
|
||||
if ob.parent is None:
|
||||
ob.parent = rig
|
||||
ob.parent_type = "OBJECT"
|
||||
|
||||
def bake_clip(clip, a, b):
|
||||
act = bpy.data.actions.new("Machine_" + clip)
|
||||
rig.animation_data_create()
|
||||
rig.animation_data.action = act
|
||||
prev = {}
|
||||
for f in range(a, b + 1):
|
||||
sc.frame_set(f)
|
||||
for bn, (src, _, _) in BONES.items():
|
||||
pb = rig.pose.bones[bn]
|
||||
pb.rotation_mode = "QUATERNION"
|
||||
target = clean(bpy.data.objects[src].matrix_world)
|
||||
local = rest[bn].inverted() @ target # pose relative to rest (bone parent Root = identity)
|
||||
loc, q, _ = local.decompose()
|
||||
if bn in prev:
|
||||
q.make_compatible(prev[bn])
|
||||
prev[bn] = q.copy()
|
||||
pb.location = loc
|
||||
pb.rotation_quaternion = q
|
||||
pb.keyframe_insert("location", frame=f - a)
|
||||
pb.keyframe_insert("rotation_quaternion", frame=f - a)
|
||||
return act
|
||||
|
||||
actions = {clip: bake_clip(clip, a, b) for clip, (a, b) in CLIPS.items()}
|
||||
rig.animation_data.action = None
|
||||
for pb in rig.pose.bones:
|
||||
pb.location = (0, 0, 0); pb.rotation_quaternion = (1, 0, 0, 0)
|
||||
sc.frame_set(REST_FRAME)
|
||||
|
||||
# ------------------------------------------------------------------ export
|
||||
def select(objs_):
|
||||
for o in bpy.context.view_layer.objects:
|
||||
o.select_set(False)
|
||||
for o in objs_:
|
||||
o.select_set(True)
|
||||
bpy.context.view_layer.objects.active = objs_[0]
|
||||
|
||||
FBX = dict(use_selection=True, apply_unit_scale=True, apply_scale_options="FBX_SCALE_ALL",
|
||||
mesh_smooth_type="FACE", path_mode="COPY", embed_textures=True, add_leaf_bones=False,
|
||||
use_armature_deform_only=False, axis_forward="-Z", axis_up="Y")
|
||||
model_objs = [rig] + [ob for ob, _ in made.values()]
|
||||
select(model_objs)
|
||||
bpy.ops.export_scene.fbx(filepath=os.path.join(OUT, "OrnamentMachine.fbx"), bake_anim=False,
|
||||
object_types={"ARMATURE", "MESH"}, **FBX)
|
||||
|
||||
for clip, act in actions.items():
|
||||
a, b = CLIPS[clip]
|
||||
rig.animation_data.action = act
|
||||
sc.frame_start, sc.frame_end = 0, b - a
|
||||
select([rig])
|
||||
bpy.ops.export_scene.fbx(filepath=os.path.join(OUT, "OrnamentMachine_%s.fbx" % clip),
|
||||
object_types={"ARMATURE"}, bake_anim=True, bake_anim_use_all_actions=False,
|
||||
bake_anim_use_nla_strips=False, bake_anim_force_startend_keying=True,
|
||||
bake_anim_step=1.0, bake_anim_simplify_factor=0.0, **FBX)
|
||||
rig.animation_data.action = None
|
||||
|
||||
# GLB: same model, both clips as glTF animations (handy for previewing in any viewer)
|
||||
for act in actions.values():
|
||||
tr = rig.animation_data.nla_tracks.new()
|
||||
tr.name = act.name
|
||||
tr.strips.new(act.name, 0, act)
|
||||
select(model_objs)
|
||||
bpy.ops.export_scene.gltf(filepath=os.path.join(OUT, "OrnamentMachine.glb"), export_format="GLB",
|
||||
use_selection=True, export_yup=True, export_apply=False,
|
||||
export_animations=True, export_animation_mode="NLA_TRACKS")
|
||||
for tr in list(rig.animation_data.nla_tracks):
|
||||
rig.animation_data.nla_tracks.remove(tr)
|
||||
sc.frame_start, sc.frame_end = 1, 325
|
||||
sc.frame_set(REST_FRAME)
|
||||
|
||||
# FX prototypes
|
||||
fx_made = []
|
||||
proto_shard = next((o for o in fx_objs if o.name.startswith("Shard_")), None)
|
||||
if proto_shard:
|
||||
bm = world_bm(proto_shard); fx_made.append(make_obj("FX_Shard", bm, MATS["glow"]))
|
||||
for o in fx_objs:
|
||||
if o.name.startswith("Gen_Lightning"):
|
||||
bm = world_bm(o); fx_made.append(make_obj("FX_" + o.name.replace("Gen_", ""), bm, MATS["glow"]))
|
||||
ph = [o for o in fx_objs if o.name.startswith("Ornament_Placeholder") and "_Out" not in o.name]
|
||||
if ph:
|
||||
sc.frame_set(240)
|
||||
bm = bmesh.new()
|
||||
for o in ph:
|
||||
part = world_bm(o); append_bm(bm, part); part.free()
|
||||
fx_made.append(make_obj("FX_Ornament_Placeholder", bm, MATS["opaque"]))
|
||||
sc.frame_set(REST_FRAME)
|
||||
for o in fx_made:
|
||||
o.parent = None
|
||||
select(fx_made)
|
||||
bpy.ops.export_scene.fbx(filepath=os.path.join(OUT, "OrnamentMachine_FX.fbx"), bake_anim=False,
|
||||
object_types={"MESH"}, **FBX)
|
||||
|
||||
# ------------------------------------------------------------------ timeline JSON
|
||||
def r(v, n=3):
|
||||
return [round(x, n) for x in v]
|
||||
|
||||
tracks = {}
|
||||
track_objs = [o for o in fx_objs if not o.name.startswith("Ornament_Placeholder")]
|
||||
track_objs += [bpy.data.objects[n] for n in crystals]
|
||||
track_objs += [bpy.data.objects[n] for n in SINGLE]
|
||||
track_objs += [bpy.data.objects[s] for s, _, _ in BONES.values() if s.startswith("Ornament_Anchor")]
|
||||
lights = [o for o in bpy.data.objects if o.type == "LIGHT" and o.name.startswith(("Gen_", "Rec_"))]
|
||||
import re
|
||||
def mat_curves(m):
|
||||
act = m.node_tree.animation_data.action if m.node_tree and m.node_tree.animation_data else None
|
||||
if not act:
|
||||
return []
|
||||
out = []
|
||||
for layer in act.layers:
|
||||
for strip in layer.strips:
|
||||
for bag in strip.channelbags:
|
||||
for c in bag.fcurves:
|
||||
mm = re.match(r'nodes\["(.+)"\]\.inputs\[(\d+)\]', c.data_path)
|
||||
if mm:
|
||||
node = m.node_tree.nodes[mm.group(1)]
|
||||
sock = node.inputs[int(mm.group(2))]
|
||||
label = node.bl_idname.replace("ShaderNode", "") + ("_%d" % int(mm.group(2)))
|
||||
if node.bl_idname == "ShaderNodeMath":
|
||||
label = "Math(%s)_%d" % (node.operation, int(mm.group(2)))
|
||||
if node.bl_idname == "ShaderNodeBsdfPrincipled":
|
||||
label = sock.name
|
||||
label = node.name.encode("ascii", "ignore").decode() + ":" + label if label in [l for l, _ in out] else label
|
||||
out.append((label, c))
|
||||
return out
|
||||
anim_mats = [(m, mat_curves(m)) for m in bpy.data.materials if mat_curves(m)]
|
||||
timeline = {"fps": FPS, "units": "Blender units (Z up). FBX/GLB convert to Y up: roblox(x, y, z) = (x, z, -y) "
|
||||
"before the importer's own rotation; machine origin = (0,0,0).",
|
||||
"clips": {k: {"start": a, "end": b, "frames": b - a + 1} for k, (a, b) in CLIPS.items()},
|
||||
"markers": sorted(({"name": m.name, "frame": m.frame} for m in sc.timeline_markers), key=lambda m: m["frame"]),
|
||||
"objects": {}, "lights": {}, "materials": {}}
|
||||
for clip, (a, b) in CLIPS.items():
|
||||
for f in range(a, b + 1):
|
||||
sc.frame_set(f)
|
||||
for o in track_objs:
|
||||
vis = not o.hide_render
|
||||
loc, q, s = o.matrix_world.decompose()
|
||||
if s.length < 1e-4:
|
||||
vis = False
|
||||
t = timeline["objects"].setdefault(o.name, [])
|
||||
if vis:
|
||||
t.append([f, r(loc), r(q, 4), r(s)])
|
||||
elif t and t[-1][1] is not None:
|
||||
t.append([f, None, None, None]) # hidden from this frame on
|
||||
for l in lights:
|
||||
timeline["lights"].setdefault(l.name, {"color": r(l.data.color), "keys": []})["keys"].append(
|
||||
[f, round(l.data.energy, 2)])
|
||||
for m, curves in anim_mats:
|
||||
vals = {label: round(c.evaluate(f), 3) for label, c in curves}
|
||||
timeline["materials"].setdefault(m.name, []).append([f, vals])
|
||||
# drop constant light / material tracks
|
||||
for k in list(timeline["lights"]):
|
||||
if len({e for _, e in timeline["lights"][k]["keys"]}) == 1:
|
||||
del timeline["lights"][k]
|
||||
for k in list(timeline["materials"]):
|
||||
if len({json.dumps(v, sort_keys=True) for _, v in timeline["materials"][k]}) == 1:
|
||||
del timeline["materials"][k]
|
||||
timeline["bones"] = {b: {"source": s, "rest_position": r(rest[b].translation)} for b, (s, _, _) in BONES.items()}
|
||||
timeline["palette"] = [{"cell": i, **c, "color": r(c["color"])} for i, c in enumerate(cell_info)]
|
||||
with open(os.path.join(OUT, "machine_timeline.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(timeline, fh, separators=(",", ":"))
|
||||
|
||||
# ------------------------------------------------------------------ report
|
||||
for name, (ob, kind) in sorted(made.items()):
|
||||
ob.data.calc_loop_triangles()
|
||||
print("PART", name, kind, len(ob.data.loop_triangles), r(ob.dimensions, 2))
|
||||
print("PALETTE", len(cell_info), "cells")
|
||||
|
||||
# patch for a place that already has the first export (before Rec_Button was split out):
|
||||
# only the new Rec_Button part + the body chunk(s) whose geometry changed
|
||||
FIRST_EXPORT_TRIS = {"Body_01": 17876, "Body_02": 17908, "Body_03": 15152, "Body_04": 14412}
|
||||
patch = [made["Rec_Button"][0]]
|
||||
for name, (ob, kind) in made.items():
|
||||
if name in FIRST_EXPORT_TRIS and len(ob.data.loop_triangles) != FIRST_EXPORT_TRIS[name]:
|
||||
patch.append(ob)
|
||||
print("PATCH", [o.name for o in patch])
|
||||
saved_parent = {o: o.parent for o in patch}
|
||||
for o in patch:
|
||||
mw = o.matrix_world.copy()
|
||||
o.parent = None
|
||||
o.matrix_world = mw
|
||||
select(patch)
|
||||
bpy.ops.export_scene.gltf(filepath=os.path.join(OUT, "OrnamentMachine_RecButtonPatch.glb"), export_format="GLB",
|
||||
use_selection=True, export_yup=True, export_apply=True, export_animations=False,
|
||||
export_skins=False)
|
||||
for o, p in saved_parent.items():
|
||||
mw = o.matrix_world.copy()
|
||||
o.parent = p
|
||||
o.matrix_world = mw
|
||||
print("FX", [o.name for o in fx_made])
|
||||
print("TRACKS", len(timeline["objects"]), "lights", list(timeline["lights"]), "mats", list(timeline["materials"]))
|
||||
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "OrnamentMachine_export.blend"), copy=True)
|
||||
print("DONE")
|
||||
|
After Width: | Height: | Size: 1009 KiB |
|
After Width: | Height: | Size: 1019 KiB |
|
After Width: | Height: | Size: 1016 KiB |
|
After Width: | Height: | Size: 1022 KiB |
|
After Width: | Height: | Size: 1020 KiB |
|
After Width: | Height: | Size: 1020 KiB |
|
After Width: | Height: | Size: 1019 KiB |
|
After Width: | Height: | Size: 1014 KiB |
|
After Width: | Height: | Size: 1020 KiB |
|
After Width: | Height: | Size: 1019 KiB |
|
After Width: | Height: | Size: 1013 KiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,44 @@
|
||||
# Станок для игрушек: экспорт для Roblox
|
||||
|
||||
Файлы собирает скрипт `machine/export_roblox.py` из `ornament_machine_new_bow_anim.blend`. Чтобы пересобрать:
|
||||
|
||||
```
|
||||
blender -b ornament_machine_new_bow_anim.blend --python export_roblox.py
|
||||
```
|
||||
|
||||
## Файлы
|
||||
|
||||
| Файл | Что внутри |
|
||||
|---|---|
|
||||
| `OrnamentMachine.fbx` | Вся модель в исходной позе. Риг `MachineRig`, текстуры встроены. |
|
||||
| `OrnamentMachine.glb` | То же самое, плюс обе анимации, чтобы посмотреть их в любом просмотрщике. |
|
||||
| `OrnamentMachine_Shredder.fbx` | Анимация шредера для Animation Editor: 180 кадров. |
|
||||
| `OrnamentMachine_Generator.fbx` | Анимация генератора для Animation Editor: 126 кадров. |
|
||||
| `OrnamentMachine_FX.fbx` | Заготовки эффектов: осколок, 20 молний (5 позиций × 4 варианта) и игрушка-заглушка. |
|
||||
| `textures/Machine_Palette_*.png` | Палитра 256×256 и карты к ней: Color, Metalness, Roughness, Emissive. |
|
||||
| `machine_timeline.json` | Таймлайн для скриптов, частота 24 кадра в секунду. |
|
||||
|
||||
Что лежит в `machine_timeline.json`:
|
||||
- маркеры этапов;
|
||||
- покадровые позиции, повороты и масштабы осколков, кристаллов, молний, искр, кольца и якорей игрушки, а также кадры, когда они видимы;
|
||||
- яркость источников света;
|
||||
- свечение материалов и плотность тумана.
|
||||
|
||||
## Части модели
|
||||
|
||||
- **`Body_01..04`**: статичный корпус. Он разбит на 4 куска, в каждом не больше 18 тысяч треугольников.
|
||||
- **`Glow_*`**: светящиеся детали (Bulb, Cyan, Yellow, White, Chamber_Magic). В Studio им ставится `Material = Neon`.
|
||||
- **`Glass_Chamber`, `Glass_Window`**: стекло. В Studio им ставится `Material = Glass`, `Transparency` около 0.6.
|
||||
- **`Drum_L`, `Drum_R`, `Gen_Button`**: подвижные детали. Они привязаны к одноимённым костям рига.
|
||||
- **Кости `Ornament_Chamber` и `Ornament_Output`**: точки крепления настоящей игрушки, в колбе и на лотке. В Roblox кость (Bone) работает как Attachment.
|
||||
- **`Chamber_GlowRing_Low`, `Rec_CrusherCrystal_00..11`**: отдельные детали. Их масштаб и видимость задаются скриптом по таймлайну, потому что кости в Roblox не умеют масштабировать.
|
||||
|
||||
## Что не переносится костями
|
||||
|
||||
- молнии, искры, туман и луч;
|
||||
- вспышки свечения;
|
||||
- появление и исчезновение осколков.
|
||||
|
||||
В игре всё это делается через ParticleEmitter, Beam, PointLight и Tween. Тайминги берутся из `machine_timeline.json`.
|
||||
|
||||
Координаты в JSON заданы в осях Blender (Z вверх). Для Roblox они переводятся так: `(x, y, z) → (x, z, −y)`.
|
||||
|
After Width: | Height: | Size: 684 KiB |
@@ -0,0 +1 @@
|
||||
{"fps":24,"units":"Blender units (Z up). FBX/GLB convert to Y up: roblox(x, y, z) = (x, z, -y) before the importer's own rotation; machine origin = (0,0,0).","clips":{"Shredder":{"start":1,"end":180,"frames":180},"Generator":{"start":200,"end":325,"frames":126}},"markers":[{"name":"Shredder_Start","frame":1},{"name":"Shredder_Stop","frame":120},{"name":"Shredder_Pour","frame":128},{"name":"Gen_Press","frame":200},{"name":"Gen_Magic","frame":204},{"name":"Gen_Spawn","frame":228},{"name":"Gen_Drop","frame":264},{"name":"Gen_Output","frame":280}],"objects":{"Gen_Lightning_0_0":[[256,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[257,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[258,null,null,null]],"Gen_Lightning_0_1":[[226,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[227,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[228,null,null,null]],"Gen_Lightning_0_2":[[212,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[213,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[214,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[215,null,null,null],[244,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[245,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[246,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[247,null,null,null]],"Gen_Lightning_0_3":[[220,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[221,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[222,null,null,null],[231,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[232,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[233,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[234,null,null,null],[238,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[239,null,null,null],[250,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[251,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[252,null,null,null]],"Gen_Lightning_1_0":[[221,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[222,null,null,null],[231,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[232,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[233,null,null,null],[250,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[251,null,null,null]],"Gen_Lightning_1_1":[[214,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[215,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[216,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[217,null,null,null],[224,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[225,null,null,null],[253,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[254,null,null,null]],"Gen_Lightning_1_2":[[237,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[238,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[239,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[240,null,null,null],[244,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[245,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[246,null,null,null]],"Gen_Lightning_1_3":[[219,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[220,null,null,null],[226,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[227,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[228,null,null,null],[257,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[258,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[259,null,null,null]],"Gen_Lightning_2_0":[[216,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[217,null,null,null]],"Gen_Lightning_2_1":[[223,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[224,null,null,null],[225,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[226,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[227,null,null,null],[234,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[235,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[236,null,null,null],[257,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[258,null,null,null]],"Gen_Lightning_2_2":[[238,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[239,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[240,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[241,null,null,null],[246,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[247,null,null,null],[250,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[251,null,null,null]],"Gen_Lightning_2_3":[[219,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[220,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[221,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[222,null,null,null],[230,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[231,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[232,null,null,null],[252,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[253,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[254,null,null,null]],"Gen_Lightning_3_0":[[218,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[219,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[220,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[221,null,null,null],[227,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[228,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[229,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[230,null,null,null],[234,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[235,null,null,null],[255,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[256,null,null,null]],"Gen_Lightning_3_1":[[239,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],[1.0,1.0,1.0]],[240,[0.0,0.0,0.0],[1.0,0.0,0.0,0.0],Line truncated
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 994 KiB |
|
After Width: | Height: | Size: 997 KiB |
|
After Width: | Height: | Size: 1001 KiB |
|
After Width: | Height: | Size: 1002 KiB |
|
After Width: | Height: | Size: 1006 KiB |
|
After Width: | Height: | Size: 1001 KiB |
@@ -0,0 +1,823 @@
|
||||
# Floating snow-island hub map: terrain + fenced player zones (no trees / installations yet).
|
||||
# Run: blender -b --factory-startup --python build_map.py
|
||||
# Units: 1 Blender unit = 1 Roblox stud (avatar ~5 studs tall).
|
||||
import bpy, bmesh, math, os, random
|
||||
from mathutils import Matrix, Vector, noise
|
||||
|
||||
OUT_DIR = r"C:\roblox\Ornament Generator RNG\map"
|
||||
random.seed(11)
|
||||
|
||||
# ---------------------------------------------------------------- layout
|
||||
ISLAND_R = 158.0 # island top radius (room for trees around the zones)
|
||||
PLAZA_R = 60.0 # central plaza radius
|
||||
PLAZA_INNER_R = 38.0 # inner tiled circle
|
||||
ZONE_COUNT = 10
|
||||
ZONE_RING_R = 112.0 # distance from centre to each zone centre (zones close to the plaza)
|
||||
ZONE_A, ZONE_B, ZONE_CORNER = 21.0, 16.0, 7.0 # zone half-width (tangential), half-depth (radial), corner radius
|
||||
GATE_HALF = 4.6 # half opening of the gate (between gate-post centres)
|
||||
PATH_HALF = 5.0 # half width of the radial paths
|
||||
POST_STEP = 6.2 # fence post spacing
|
||||
POST_W, POST_H = 1.7, 6.0 # chunky square posts
|
||||
RAIL_T, RAIL_H = 0.8, 1.0 # rail thickness / height
|
||||
RAIL_Z = (2.0, 4.3) # rail centre heights
|
||||
SNOW_RES = 0.11 # metaball polygonisation step for the fence snow (smaller = smoother)
|
||||
SNOW_DECIMATE = 0.14 # keep this fraction of the snow triangles (smooth-shaded, stays soft)
|
||||
|
||||
def zone_frame(i):
|
||||
th = math.radians(90 + i * 360.0 / ZONE_COUNT)
|
||||
er = Vector((math.cos(th), math.sin(th), 0))
|
||||
et = Vector((-math.sin(th), math.cos(th), 0))
|
||||
return th, er, et, er * ZONE_RING_R
|
||||
|
||||
def zone_local(p, i):
|
||||
_, er, et, c = zone_frame(i)
|
||||
d = Vector((p.x, p.y, 0)) - c
|
||||
return d.dot(et), d.dot(er)
|
||||
|
||||
def in_rounded_rect(u, v, a, b, r):
|
||||
qx, qy = abs(u) - (a - r), abs(v) - (b - r)
|
||||
return math.hypot(max(qx, 0), max(qy, 0)) + min(max(qx, qy), 0) - r <= 0
|
||||
|
||||
def flat_area(x, y, pad=4.0):
|
||||
"""True where the ground must stay flat: plaza, paths and zones."""
|
||||
r = math.hypot(x, y)
|
||||
if r <= PLAZA_R + pad:
|
||||
return True
|
||||
for i in range(ZONE_COUNT):
|
||||
u, v = zone_local(Vector((x, y, 0)), i)
|
||||
if in_rounded_rect(u, v, ZONE_A + pad, ZONE_B + pad, ZONE_CORNER + pad):
|
||||
return True
|
||||
if abs(u) <= PATH_HALF + pad and -ZONE_B - pad <= v <= 0 and r <= ZONE_RING_R:
|
||||
return True
|
||||
th, er, et, c = zone_frame(i)
|
||||
p = Vector((x, y, 0))
|
||||
if abs(p.dot(et)) <= PATH_HALF + pad and 0 < p.dot(er) <= ZONE_RING_R - ZONE_B:
|
||||
return True
|
||||
return False
|
||||
|
||||
# ---------------------------------------------------------------- scene
|
||||
def setup_scene():
|
||||
sc = bpy.context.scene
|
||||
for o in list(bpy.data.objects):
|
||||
bpy.data.objects.remove(o, do_unlink=True)
|
||||
for c in list(bpy.data.collections):
|
||||
bpy.data.collections.remove(c)
|
||||
cols = {}
|
||||
for n in ("Terrain", "Fences", "Studio"):
|
||||
cols[n] = bpy.data.collections.new(n)
|
||||
sc.collection.children.link(cols[n])
|
||||
return sc, cols
|
||||
|
||||
# ---------------------------------------------------------------- shaders
|
||||
def new_mat(name):
|
||||
m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
|
||||
try:
|
||||
m.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
m.node_tree.nodes.clear()
|
||||
return m, m.node_tree.nodes, m.node_tree.links
|
||||
|
||||
def out(N, L, sock):
|
||||
o = N.new("ShaderNodeOutputMaterial")
|
||||
L.new(sock, o.inputs["Surface"])
|
||||
|
||||
def mat_snow():
|
||||
m, N, L = new_mat("Snow")
|
||||
tc = N.new("ShaderNodeTexCoord")
|
||||
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 0.08; nz.inputs["Detail"].default_value = 6
|
||||
L.new(tc.outputs["Object"], nz.inputs["Vector"])
|
||||
ramp = N.new("ShaderNodeValToRGB")
|
||||
ramp.color_ramp.elements[0].color = (0.84, 0.90, 1.0, 1) # faint cool shade in hollows
|
||||
ramp.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1)
|
||||
ramp.color_ramp.elements[0].position = 0.3
|
||||
L.new(nz.outputs["Fac"], ramp.inputs["Fac"])
|
||||
bs = N.new("ShaderNodeBsdfPrincipled")
|
||||
L.new(ramp.outputs["Color"], bs.inputs["Base Color"])
|
||||
bs.inputs["Roughness"].default_value = 0.55
|
||||
if "Subsurface Weight" in bs.inputs:
|
||||
bs.inputs["Subsurface Weight"].default_value = 0.15
|
||||
bs.inputs["Subsurface Radius"].default_value = (0.4, 0.6, 1.0)
|
||||
if "Coat Weight" in bs.inputs:
|
||||
bs.inputs["Coat Weight"].default_value = 0.15
|
||||
# fine sparkle bump
|
||||
fine = N.new("ShaderNodeTexNoise"); fine.inputs["Scale"].default_value = 1.8
|
||||
L.new(tc.outputs["Object"], fine.inputs["Vector"])
|
||||
bump = N.new("ShaderNodeBump"); bump.inputs["Strength"].default_value = 0.25
|
||||
L.new(fine.outputs["Fac"], bump.inputs["Height"])
|
||||
L.new(bump.outputs["Normal"], bs.inputs["Normal"])
|
||||
out(N, L, bs.outputs["BSDF"])
|
||||
m.diffuse_color = (0.95, 0.97, 1, 1)
|
||||
return m
|
||||
|
||||
def mat_snow_soft():
|
||||
"""Fence snow: bright, soft subsurface look with tiny glints (like the reference snow caps)."""
|
||||
m, N, L = new_mat("Snow_Soft")
|
||||
tc = N.new("ShaderNodeTexCoord")
|
||||
bs = N.new("ShaderNodeBsdfPrincipled")
|
||||
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 1.2
|
||||
L.new(tc.outputs["Object"], nz.inputs["Vector"])
|
||||
ramp = N.new("ShaderNodeValToRGB")
|
||||
# low-poly look: near-white flat colour, faint cool tint, no micro detail (the facets do the work)
|
||||
ramp.color_ramp.elements[0].color = (0.90, 0.94, 1.0, 1)
|
||||
ramp.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1)
|
||||
L.new(nz.outputs["Fac"], ramp.inputs["Fac"])
|
||||
L.new(ramp.outputs["Color"], bs.inputs["Base Color"])
|
||||
bs.inputs["Roughness"].default_value = 0.6
|
||||
if "Subsurface Weight" in bs.inputs:
|
||||
bs.inputs["Subsurface Weight"].default_value = 0.08
|
||||
bs.inputs["Subsurface Radius"].default_value = (0.7, 0.85, 1.0)
|
||||
bs.inputs["Subsurface Scale"].default_value = 0.1
|
||||
# a touch of self-light so shadowed facets stay white rather than grey-blue
|
||||
bs.inputs["Emission Color"].default_value = (0.92, 0.95, 1.0, 1)
|
||||
bs.inputs["Emission Strength"].default_value = 0.12
|
||||
out(N, L, bs.outputs["BSDF"])
|
||||
m.diffuse_color = (0.95, 0.97, 1, 1)
|
||||
return m
|
||||
|
||||
def mat_rock():
|
||||
m, N, L = new_mat("Cliff_Rock")
|
||||
tc = N.new("ShaderNodeTexCoord")
|
||||
wave = N.new("ShaderNodeTexWave"); wave.wave_type = "BANDS"; wave.bands_direction = "Z"
|
||||
wave.inputs["Scale"].default_value = 0.035; wave.inputs["Distortion"].default_value = 6; wave.inputs["Detail"].default_value = 4
|
||||
L.new(tc.outputs["Object"], wave.inputs["Vector"])
|
||||
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 0.12; nz.inputs["Detail"].default_value = 8
|
||||
L.new(tc.outputs["Object"], nz.inputs["Vector"])
|
||||
mix = N.new("ShaderNodeMix"); mix.data_type = "FLOAT"; mix.inputs["Factor"].default_value = 0.5
|
||||
L.new(wave.outputs["Fac"], mix.inputs["A"]); L.new(nz.outputs["Fac"], mix.inputs["B"])
|
||||
ramp = N.new("ShaderNodeValToRGB")
|
||||
ramp.color_ramp.elements[0].color = (0.10, 0.11, 0.16, 1)
|
||||
ramp.color_ramp.elements[1].color = (0.42, 0.44, 0.55, 1)
|
||||
L.new(mix.outputs["Result"], ramp.inputs["Fac"])
|
||||
bs = N.new("ShaderNodeBsdfPrincipled")
|
||||
L.new(ramp.outputs["Color"], bs.inputs["Base Color"])
|
||||
bs.inputs["Roughness"].default_value = 0.85
|
||||
bump = N.new("ShaderNodeBump"); bump.inputs["Strength"].default_value = 0.8
|
||||
L.new(mix.outputs["Result"], bump.inputs["Height"])
|
||||
L.new(bump.outputs["Normal"], bs.inputs["Normal"])
|
||||
out(N, L, bs.outputs["BSDF"])
|
||||
m.diffuse_color = (0.3, 0.32, 0.4, 1)
|
||||
return m
|
||||
|
||||
def mat_tiles(name, c1, c2, mortar, scale, radial=False):
|
||||
m, N, L = new_mat(name)
|
||||
tc = N.new("ShaderNodeTexCoord")
|
||||
vec = tc.outputs["Object"]
|
||||
if radial: # polar coordinates -> rings of tiles around the plaza centre
|
||||
sep = N.new("ShaderNodeSeparateXYZ"); L.new(vec, sep.inputs[0])
|
||||
at = N.new("ShaderNodeMath"); at.operation = "ARCTAN2"
|
||||
L.new(sep.outputs["Y"], at.inputs[0]); L.new(sep.outputs["X"], at.inputs[1])
|
||||
ln = N.new("ShaderNodeVectorMath"); ln.operation = "LENGTH"; L.new(vec, ln.inputs[0])
|
||||
sc_ = N.new("ShaderNodeMath"); sc_.operation = "MULTIPLY"; sc_.inputs[1].default_value = 6.0
|
||||
L.new(at.outputs["Value"], sc_.inputs[0])
|
||||
comb = N.new("ShaderNodeCombineXYZ")
|
||||
L.new(sc_.outputs["Value"], comb.inputs["X"]); L.new(ln.outputs["Value"], comb.inputs["Y"])
|
||||
vec = comb.outputs["Vector"]
|
||||
br = N.new("ShaderNodeTexBrick")
|
||||
br.inputs["Color1"].default_value = (*c1, 1); br.inputs["Color2"].default_value = (*c2, 1)
|
||||
br.inputs["Mortar"].default_value = (*mortar, 1)
|
||||
br.inputs["Scale"].default_value = scale
|
||||
br.inputs["Mortar Size"].default_value = 0.025
|
||||
br.inputs["Brick Width"].default_value = 0.5; br.inputs["Row Height"].default_value = 0.35
|
||||
br.offset = 0.5
|
||||
L.new(vec, br.inputs["Vector"])
|
||||
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 0.4
|
||||
L.new(tc.outputs["Object"], nz.inputs["Vector"])
|
||||
snowmix = N.new("ShaderNodeMix"); snowmix.data_type = "RGBA"
|
||||
pw = N.new("ShaderNodeMath"); pw.operation = "POWER"; pw.inputs[1].default_value = 6.0
|
||||
L.new(nz.outputs["Fac"], pw.inputs[0])
|
||||
L.new(pw.outputs["Value"], snowmix.inputs["Factor"])
|
||||
L.new(br.outputs["Color"], snowmix.inputs["A"])
|
||||
snowmix.inputs["B"].default_value = (0.92, 0.94, 1.0, 1) # light dusting of snow
|
||||
bs = N.new("ShaderNodeBsdfPrincipled")
|
||||
L.new(snowmix.outputs["Result"], bs.inputs["Base Color"])
|
||||
bs.inputs["Roughness"].default_value = 0.7
|
||||
bump = N.new("ShaderNodeBump"); bump.inputs["Strength"].default_value = 0.6
|
||||
inv = N.new("ShaderNodeMath"); inv.operation = "SUBTRACT"; inv.inputs[0].default_value = 1.0
|
||||
L.new(br.outputs["Fac"], inv.inputs[1]); L.new(inv.outputs["Value"], bump.inputs["Height"])
|
||||
L.new(bump.outputs["Normal"], bs.inputs["Normal"])
|
||||
out(N, L, bs.outputs["BSDF"])
|
||||
m.diffuse_color = (*c1, 1)
|
||||
return m
|
||||
|
||||
# stylised flat-colour wood (like the sample): warm tan boards with per-board tone, soft posterised
|
||||
# light/dark patches along the board, sparse thin outlined grain lines, a few outlined knots.
|
||||
WOOD_TOP = (0.74, 0.27, 0.09) # light orange at the top of a board
|
||||
WOOD_BOTTOM = (0.36, 0.10, 0.03) # darker brown at the bottom
|
||||
WOOD_LINE = (0.12, 0.025, 0.007) # thin dark grain lines / outlines
|
||||
WOOD_KNOT = (0.16, 0.035, 0.01)
|
||||
WOOD_HILITE = (0.90, 0.42, 0.18) # thin light edge next to grain lines
|
||||
|
||||
def mat_wood():
|
||||
m, N, L = new_mat("Fence_Wood")
|
||||
uvn = N.new("ShaderNodeUVMap"); uvn.uv_map = "UVMap"
|
||||
sep = N.new("ShaderNodeSeparateXYZ"); L.new(uvn.outputs["UV"], sep.inputs[0])
|
||||
def math_(op, a, b=None, val=None):
|
||||
n = N.new("ShaderNodeMath"); n.operation = op
|
||||
L.new(a, n.inputs[0])
|
||||
if b is not None:
|
||||
L.new(b, n.inputs[1])
|
||||
elif val is not None:
|
||||
n.inputs[1].default_value = val
|
||||
return n.outputs["Value"]
|
||||
def mix_col(fac, a, b):
|
||||
n = N.new("ShaderNodeMix"); n.data_type = "RGBA"
|
||||
L.new(fac, n.inputs["Factor"])
|
||||
if isinstance(a, tuple):
|
||||
n.inputs["A"].default_value = (*a, 1)
|
||||
else:
|
||||
L.new(a, n.inputs["A"])
|
||||
if isinstance(b, tuple):
|
||||
n.inputs["B"].default_value = (*b, 1)
|
||||
else:
|
||||
L.new(b, n.inputs["B"])
|
||||
return n.outputs["Result"]
|
||||
# inputs: per-face 0..1 coords, face size in studs, per-face seed
|
||||
dn = N.new("ShaderNodeUVMap"); dn.uv_map = "FaceDims"
|
||||
dsep = N.new("ShaderNodeSeparateXYZ"); L.new(dn.outputs["UV"], dsep.inputs[0])
|
||||
sn = N.new("ShaderNodeUVMap"); sn.uv_map = "FaceSeed"
|
||||
ssep = N.new("ShaderNodeSeparateXYZ"); L.new(sn.outputs["UV"], ssep.inputs[0])
|
||||
U, V = sep.outputs["X"], sep.outputs["Y"]
|
||||
Wd, Ln, S = dsep.outputs["X"], dsep.outputs["Y"], ssep.outputs["X"]
|
||||
u_st = math_("MULTIPLY", U, Wd) # studs across the face
|
||||
v_st = math_("MULTIPLY", V, Ln) # studs along the face
|
||||
seed10 = math_("MULTIPLY", S, val=37.0)
|
||||
|
||||
# 1) one board per face: light at the top, darker toward the bottom in soft stepped bands
|
||||
wob = N.new("ShaderNodeTexNoise"); wob.noise_dimensions = "2D"; wob.inputs["Scale"].default_value = 1.0
|
||||
wv = N.new("ShaderNodeCombineXYZ")
|
||||
L.new(math_("MULTIPLY", u_st, val=0.8), wv.inputs["X"]); L.new(math_("ADD", math_("MULTIPLY", v_st, val=0.5), seed10), wv.inputs["Y"])
|
||||
L.new(wv.outputs["Vector"], wob.inputs["Vector"])
|
||||
g = math_("ADD", V, math_("MULTIPLY", math_("SUBTRACT", wob.outputs["Fac"], val=0.5), val=0.18))
|
||||
steps = math_("DIVIDE", math_("FLOOR", math_("MULTIPLY", g, val=7.0)), val=7.0) # posterised bands
|
||||
grad = N.new("ShaderNodeValToRGB"); gcr = grad.color_ramp
|
||||
gcr.elements[0].color = (*WOOD_BOTTOM, 1)
|
||||
gcr.elements[1].color = (*WOOD_TOP, 1)
|
||||
L.new(steps, grad.inputs["Fac"])
|
||||
# slight per-face tone shift so neighbouring faces/boards differ
|
||||
tone = math_("ADD", math_("MULTIPLY", S, val=0.25), val=0.88)
|
||||
tn = N.new("ShaderNodeMix"); tn.data_type = "RGBA"; tn.blend_type = "MULTIPLY"; tn.inputs["Factor"].default_value = 1.0
|
||||
tcomb = N.new("ShaderNodeCombineColor")
|
||||
for ch in ("Red", "Green", "Blue"):
|
||||
L.new(tone, tcomb.inputs[ch])
|
||||
L.new(grad.outputs["Color"], tn.inputs["A"]); L.new(tcomb.outputs["Color"], tn.inputs["B"])
|
||||
col = tn.outputs["Result"]
|
||||
# darker strip along both long edges (bevelled-board look)
|
||||
edge_d = math_("MULTIPLY", math_("MINIMUM", U, math_("SUBTRACT", math_("MULTIPLY", U, val=-1.0), val=-1.0)), Wd)
|
||||
col = mix_col(math_("MULTIPLY", math_("LESS_THAN", edge_d, val=0.16), val=0.35), col, WOOD_BOTTOM)
|
||||
|
||||
# 2) 2-3 thin, partly-broken grain lines running along the board
|
||||
gv = N.new("ShaderNodeCombineXYZ")
|
||||
L.new(math_("ADD", u_st, seed10), gv.inputs["X"])
|
||||
L.new(math_("MULTIPLY", v_st, val=0.07), gv.inputs["Y"])
|
||||
wave = N.new("ShaderNodeTexWave"); wave.wave_type = "BANDS"; wave.bands_direction = "X"
|
||||
wave.wave_profile = "SAW"
|
||||
wave.inputs["Scale"].default_value = 1.4
|
||||
wave.inputs["Distortion"].default_value = 1.6
|
||||
wave.inputs["Detail"].default_value = 0.5
|
||||
L.new(gv.outputs["Vector"], wave.inputs["Vector"])
|
||||
brk = N.new("ShaderNodeTexNoise"); brk.noise_dimensions = "2D"; brk.inputs["Scale"].default_value = 1.0
|
||||
bv = N.new("ShaderNodeCombineXYZ")
|
||||
L.new(math_("MULTIPLY", u_st, val=2.0), bv.inputs["X"]); L.new(math_("ADD", math_("MULTIPLY", v_st, val=0.3), seed10), bv.inputs["Y"])
|
||||
L.new(bv.outputs["Vector"], brk.inputs["Vector"])
|
||||
keep = math_("GREATER_THAN", brk.outputs["Fac"], val=0.47)
|
||||
away = math_("GREATER_THAN", edge_d, val=0.2) # no grain lines on the edge strips
|
||||
line = math_("MULTIPLY", math_("MULTIPLY", math_("LESS_THAN", wave.outputs["Fac"], val=0.022), keep), away)
|
||||
hi = math_("MULTIPLY", math_("MULTIPLY", math_("GREATER_THAN", wave.outputs["Fac"], val=0.022),
|
||||
math_("LESS_THAN", wave.outputs["Fac"], val=0.045)), math_("MULTIPLY", keep, away))
|
||||
col = mix_col(math_("MULTIPLY", hi, val=0.5), col, WOOD_HILITE)
|
||||
col = mix_col(line, col, WOOD_LINE)
|
||||
|
||||
# 3) rare knots (outlined dark eye), only on some faces
|
||||
kv = N.new("ShaderNodeCombineXYZ")
|
||||
L.new(math_("MULTIPLY", u_st, val=1.2), kv.inputs["X"])
|
||||
L.new(math_("ADD", math_("MULTIPLY", v_st, val=0.3), seed10), kv.inputs["Y"])
|
||||
vor = N.new("ShaderNodeTexVoronoi"); vor.inputs["Scale"].default_value = 0.7
|
||||
L.new(kv.outputs["Vector"], vor.inputs["Vector"])
|
||||
sepc = N.new("ShaderNodeSeparateColor"); L.new(vor.outputs["Color"], sepc.inputs["Color"])
|
||||
pick = math_("MULTIPLY", math_("GREATER_THAN", sepc.outputs["Red"], val=0.86), away)
|
||||
d = vor.outputs["Distance"]
|
||||
core = math_("MULTIPLY", math_("LESS_THAN", d, val=0.07), pick)
|
||||
ring = math_("MULTIPLY", math_("MULTIPLY", math_("GREATER_THAN", d, val=0.095), math_("LESS_THAN", d, val=0.115)), pick)
|
||||
col = mix_col(ring, col, WOOD_LINE)
|
||||
col = mix_col(core, col, WOOD_KNOT)
|
||||
|
||||
# 4) thin dark outline on the long edges and the ends of every face
|
||||
end_d = math_("MULTIPLY", math_("MINIMUM", V, math_("SUBTRACT", math_("MULTIPLY", V, val=-1.0), val=-1.0)), Ln)
|
||||
outline = math_("MAXIMUM", math_("LESS_THAN", edge_d, val=0.045), math_("LESS_THAN", end_d, val=0.04))
|
||||
col = mix_col(outline, col, WOOD_LINE)
|
||||
bs = N.new("ShaderNodeBsdfPrincipled")
|
||||
L.new(col, bs.inputs["Base Color"])
|
||||
bs.inputs["Roughness"].default_value = 0.7
|
||||
if "Specular IOR Level" in bs.inputs:
|
||||
bs.inputs["Specular IOR Level"].default_value = 0.3
|
||||
out(N, L, bs.outputs["BSDF"])
|
||||
m.diffuse_color = (*WOOD_TOP, 1)
|
||||
return m
|
||||
|
||||
def mat_simple(name, col, rough=0.5, emit=0.0, metal=0.0):
|
||||
m, N, L = new_mat(name)
|
||||
bs = N.new("ShaderNodeBsdfPrincipled")
|
||||
bs.inputs["Base Color"].default_value = (*col, 1)
|
||||
bs.inputs["Roughness"].default_value = rough
|
||||
bs.inputs["Metallic"].default_value = metal
|
||||
bs.inputs["Emission Color"].default_value = (*col, 1)
|
||||
bs.inputs["Emission Strength"].default_value = emit
|
||||
out(N, L, bs.outputs["BSDF"])
|
||||
m.diffuse_color = (*col, 1)
|
||||
return m
|
||||
|
||||
# ---------------------------------------------------------------- terrain
|
||||
def build_island(coll, snow, rock):
|
||||
SEG = 256
|
||||
RINGS_TOP = 48
|
||||
bm = bmesh.new()
|
||||
def edge_r(a):
|
||||
return ISLAND_R * (1.0 + 0.035 * noise.noise(Vector((math.cos(a) * 3, math.sin(a) * 3, 0.5)))
|
||||
+ 0.015 * noise.noise(Vector((math.cos(a) * 11, math.sin(a) * 11, 2.0))))
|
||||
angles = [2 * math.pi * k / SEG for k in range(SEG)]
|
||||
er = [edge_r(a) for a in angles]
|
||||
centre = bm.verts.new((0, 0, 0))
|
||||
grid = []
|
||||
for ri in range(1, RINGS_TOP + 1):
|
||||
t = ri / RINGS_TOP
|
||||
row = []
|
||||
for k, a in enumerate(angles):
|
||||
r = er[k] * t
|
||||
x, y = r * math.cos(a), r * math.sin(a)
|
||||
z = 0.0
|
||||
if not flat_area(x, y):
|
||||
z = 2.6 * max(0.0, noise.noise(Vector((x * 0.035, y * 0.035, 7.0)))) + 0.3
|
||||
z *= min(1.0, (1 - t) * 6) # settle to 0 at the edge lip
|
||||
if ri == RINGS_TOP:
|
||||
z = 0.6 # snow lip slightly raised at the rim
|
||||
row.append(bm.verts.new((x, y, z)))
|
||||
grid.append(row)
|
||||
for k in range(SEG):
|
||||
bm.faces.new((centre, grid[0][k], grid[0][(k + 1) % SEG])).material_index = 0
|
||||
for ri in range(RINGS_TOP - 1):
|
||||
for k in range(SEG):
|
||||
k2 = (k + 1) % SEG
|
||||
bm.faces.new((grid[ri][k], grid[ri + 1][k], grid[ri + 1][k2], grid[ri][k2])).material_index = 0
|
||||
# side: snow skirt with drips, then a jagged rocky cone
|
||||
profile = [(1.012, -1.5, 0), (1.010, -4.0, 0), (0.995, -6.0, 1), (0.97, -14, 1), (0.93, -28, 1),
|
||||
(0.86, -46, 1), (0.74, -66, 1), (0.57, -88, 1), (0.36, -110, 1), (0.16, -128, 1)]
|
||||
prev = grid[-1]
|
||||
for pi_, (f, z, mi) in enumerate(profile):
|
||||
row = []
|
||||
for k, a in enumerate(angles):
|
||||
jag = 1.0
|
||||
zz = z
|
||||
if mi == 1:
|
||||
jag += 0.06 * noise.noise(Vector((math.cos(a) * 6, math.sin(a) * 6, z * 0.05)))
|
||||
jag += 0.03 * noise.noise(Vector((math.cos(a) * 25, math.sin(a) * 25, z * 0.2)))
|
||||
else:
|
||||
if pi_ == 1: # snow drips hanging over the cliff
|
||||
zz -= 2.5 * max(0.0, noise.noise(Vector((math.cos(a) * 30, math.sin(a) * 30, 1.0))))
|
||||
r = er[k] * f * jag
|
||||
row.append(bm.verts.new((r * math.cos(a), r * math.sin(a), zz)))
|
||||
for k in range(SEG):
|
||||
k2 = (k + 1) % SEG
|
||||
bm.faces.new((prev[k], row[k], row[k2], prev[k2])).material_index = mi
|
||||
prev = row
|
||||
tip = bm.verts.new((0, 0, -140))
|
||||
for k in range(SEG):
|
||||
bm.faces.new((prev[k], tip, prev[(k + 1) % SEG])).material_index = 1
|
||||
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
|
||||
me = bpy.data.meshes.new("Island")
|
||||
bm.to_mesh(me); bm.free()
|
||||
me.materials.append(snow); me.materials.append(rock)
|
||||
for p in me.polygons:
|
||||
p.use_smooth = True
|
||||
ob = bpy.data.objects.new("Island", me)
|
||||
coll.objects.link(ob)
|
||||
return ob
|
||||
|
||||
def cylinder(name, coll, mat, r, z0, z1, seg=128):
|
||||
bm = bmesh.new()
|
||||
bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=True, segments=seg, radius1=r, radius2=r, depth=z1 - z0,
|
||||
matrix=Matrix.Translation((0, 0, (z0 + z1) / 2)))
|
||||
me = bpy.data.meshes.new(name)
|
||||
bm.to_mesh(me); bm.free()
|
||||
me.materials.append(mat)
|
||||
ob = bpy.data.objects.new(name, me)
|
||||
bv = ob.modifiers.new("Bevel", "BEVEL"); bv.width = 0.15; bv.segments = 2; bv.limit_method = "ANGLE"
|
||||
coll.objects.link(ob)
|
||||
return ob
|
||||
|
||||
def build_plaza_and_paths(coll, tiles, tiles_inner, curb):
|
||||
cylinder("Plaza_Border", coll, curb, PLAZA_R + 2.5, -0.5, 0.35)
|
||||
cylinder("Plaza_Tiles", coll, tiles, PLAZA_R, -0.4, 0.45)
|
||||
cylinder("Plaza_Inner_Ring", coll, curb, PLAZA_INNER_R + 1.2, -0.3, 0.5)
|
||||
cylinder("Plaza_Inner_Tiles", coll, tiles_inner, PLAZA_INNER_R, -0.2, 0.55)
|
||||
bm = bmesh.new()
|
||||
def box(c, size, yaw, mi):
|
||||
M = Matrix.Translation(c) @ Matrix.Rotation(yaw, 4, "Z") @ Matrix.Diagonal((size[0], size[1], size[2], 1))
|
||||
ret = bmesh.ops.create_cube(bm, size=1.0, matrix=M)
|
||||
for f in {f for v in ret["verts"] for f in v.link_faces}:
|
||||
f.material_index = mi
|
||||
for i in range(ZONE_COUNT):
|
||||
th, er, et, c = zone_frame(i)
|
||||
r0, r1 = PLAZA_R - 1.0, ZONE_RING_R - ZONE_B + 2.0
|
||||
L_ = r1 - r0
|
||||
mid = er * ((r0 + r1) / 2)
|
||||
yaw = th
|
||||
box(Vector((mid.x, mid.y, 0.15)), (L_, PATH_HALF * 2, 0.6), yaw, 0) # path tiles
|
||||
for s in (-1, 1): # curbs
|
||||
cp = mid + et * s * (PATH_HALF + 0.45)
|
||||
box(Vector((cp.x, cp.y, 0.25)), (L_ - 3.0, 0.9, 0.8), yaw, 1)
|
||||
me = bpy.data.meshes.new("Paths")
|
||||
bm.to_mesh(me); bm.free()
|
||||
me.materials.append(tiles); me.materials.append(curb)
|
||||
ob = bpy.data.objects.new("Paths", me)
|
||||
bv = ob.modifiers.new("Bevel", "BEVEL"); bv.width = 0.12; bv.segments = 2; bv.limit_method = "ANGLE"
|
||||
coll.objects.link(ob)
|
||||
|
||||
# ---------------------------------------------------------------- fences
|
||||
def zone_perimeter(a, b, r):
|
||||
"""Dense CCW polyline of the rounded rectangle, from the right gate edge round to the left gate edge."""
|
||||
pts = [Vector((GATE_HALF, -b))]
|
||||
def arc(cx, cy, a0, a1, n=14):
|
||||
for k in range(1, n + 1):
|
||||
t = math.radians(a0 + (a1 - a0) * k / n)
|
||||
pts.append(Vector((cx + r * math.cos(t), cy + r * math.sin(t))))
|
||||
pts.append(Vector((a - r, -b)))
|
||||
arc(a - r, -b + r, -90, 0)
|
||||
pts.append(Vector((a, b - r)))
|
||||
arc(a - r, b - r, 0, 90)
|
||||
pts.append(Vector((-(a - r), b)))
|
||||
arc(-(a - r), b - r, 90, 180)
|
||||
pts.append(Vector((-a, -b + r)))
|
||||
arc(-(a - r), -b + r, 180, 270)
|
||||
pts.append(Vector((-GATE_HALF, -b)))
|
||||
return pts
|
||||
|
||||
def resample(poly, step):
|
||||
seglens = [(poly[i + 1] - poly[i]).length for i in range(len(poly) - 1)]
|
||||
total = sum(seglens)
|
||||
n = max(1, round(total / step))
|
||||
out_, targets = [], [total * k / n for k in range(n + 1)]
|
||||
acc, si = 0.0, 0
|
||||
for t in targets:
|
||||
while si < len(seglens) - 1 and acc + seglens[si] < t:
|
||||
acc += seglens[si]; si += 1
|
||||
f = 0.0 if seglens[si] == 0 else (t - acc) / seglens[si]
|
||||
out_.append(poly[si].lerp(poly[si + 1], min(1.0, f)))
|
||||
return out_
|
||||
|
||||
def uv_box(bm, uvl, center, size, yaw, mi=0, rot_y=0.0):
|
||||
"""Box where EVERY FACE is its own board (like one side of a beam in the reference):
|
||||
UVMap = 0..1 across (U) and along (V) the face; V runs along the box's long axis, V=1 at the top
|
||||
FaceDims = (face width, face length) in studs
|
||||
FaceSeed = (random seed per face, random)"""
|
||||
uv, dims, seed = uvl
|
||||
hs = [s / 2 for s in size]
|
||||
R = Matrix.Rotation(yaw, 4, "Z") @ Matrix.Rotation(rot_y, 4, "Y")
|
||||
verts = {}
|
||||
for sx in (-1, 1):
|
||||
for sy in (-1, 1):
|
||||
for sz in (-1, 1):
|
||||
verts[(sx, sy, sz)] = bm.verts.new(Vector(center) + R @ Vector((sx * hs[0], sy * hs[1], sz * hs[2])))
|
||||
long_ax = max(range(3), key=lambda a: size[a])
|
||||
for a in range(3):
|
||||
for s in (-1, 1):
|
||||
o = [k for k in range(3) if k != a]
|
||||
keys = []
|
||||
for cu, cv in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
|
||||
k = [0, 0, 0]; k[a] = s; k[o[0]] = cu; k[o[1]] = cv
|
||||
keys.append(tuple(k))
|
||||
f = bm.faces.new([verts[k] for k in keys])
|
||||
f.material_index = mi
|
||||
vax = long_ax if long_ax in o else max(o, key=lambda q: size[q])
|
||||
uax = o[0] if o[1] == vax else o[1]
|
||||
fs = (random.random(), random.random())
|
||||
for lp, k in zip(f.loops, keys):
|
||||
lp[uv].uv = ((k[uax] + 1) / 2, (k[vax] + 1) / 2)
|
||||
lp[dims].uv = (size[uax], size[vax])
|
||||
lp[seed].uv = fs
|
||||
|
||||
def finish_obj(name, bm, mats, coll, bevel, segs, angle=40):
|
||||
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
|
||||
me = bpy.data.meshes.new(name)
|
||||
bm.to_mesh(me); bm.free()
|
||||
for m in mats:
|
||||
me.materials.append(m)
|
||||
for p in me.polygons:
|
||||
p.use_smooth = True
|
||||
ob = bpy.data.objects.new(name, me)
|
||||
bv = ob.modifiers.new("Bevel", "BEVEL")
|
||||
bv.width, bv.segments, bv.limit_method = bevel, segs, "ANGLE"
|
||||
bv.angle_limit = math.radians(angle)
|
||||
bv.harden_normals = True
|
||||
bv.use_clamp_overlap = True
|
||||
coll.objects.link(ob)
|
||||
return ob
|
||||
|
||||
def build_fence(i, coll, wood, snow, wire, bulb, bulb2):
|
||||
th, er, et, c = zone_frame(i)
|
||||
def W(u, v, z=0.0):
|
||||
p = c + et * u + er * v
|
||||
return Vector((p.x, p.y, z))
|
||||
zone_name = "Zone_%02d" % (i + 1)
|
||||
bw = bmesh.new() # wood
|
||||
uvl = (bw.loops.layers.uv.new("UVMap"), bw.loops.layers.uv.new("FaceDims"), bw.loops.layers.uv.new("FaceSeed"))
|
||||
bl = bmesh.new() # lights
|
||||
# snow = metaballs: elements melt into each other -> soft, rounded caps with wavy, drooping edges
|
||||
mb = bpy.data.metaballs.new(zone_name + "_SnowMB")
|
||||
mb.resolution = mb.render_resolution = SNOW_RES
|
||||
mb.threshold = 0.6
|
||||
|
||||
def melem(kind, co, radius, size=None, yaw=0.0, vertical=False, stiff=2.0):
|
||||
e = mb.elements.new(type=kind)
|
||||
e.co = co
|
||||
e.radius = radius
|
||||
e.stiffness = stiff
|
||||
if size is not None:
|
||||
e.size_x, e.size_y, e.size_z = size
|
||||
q = Matrix.Rotation(yaw, 4, "Z").to_quaternion()
|
||||
if vertical: # capsules run along local X; stand them up for drips
|
||||
q = q @ Matrix.Rotation(math.radians(90), 4, "Y").to_quaternion()
|
||||
e.rotation = q
|
||||
return e
|
||||
|
||||
def drip(top_point, yaw, ln, r):
|
||||
"""Hanging icicle-like drip: a vertical capsule ending in a rounder bead."""
|
||||
melem("CAPSULE", top_point - Vector((0, 0, ln / 2)), r, size=(ln / 2, 1, 1), yaw=yaw, vertical=True)
|
||||
melem("BALL", top_point - Vector((0, 0, ln)), r * 1.25)
|
||||
|
||||
def lbox(center, size, yaw, mi):
|
||||
M = Matrix.Translation(center) @ Matrix.Rotation(yaw, 4, "Z") @ Matrix.Diagonal((size[0], size[1], size[2], 1))
|
||||
ret = bmesh.ops.create_cube(bl, size=1.0, matrix=M)
|
||||
for f in {f for v in ret["verts"] for f in v.link_faces}:
|
||||
f.material_index = mi
|
||||
|
||||
def lbulb(center, r, mi):
|
||||
M = Matrix.Translation(center) @ Matrix.Diagonal((r, r, r * 1.35, 1))
|
||||
ret = bmesh.ops.create_icosphere(bl, subdivisions=2, radius=1.0, matrix=M)
|
||||
for f in {f for v in ret["verts"] for f in v.link_faces}:
|
||||
f.material_index = mi
|
||||
|
||||
def snow_cap(base, w, h, yaw):
|
||||
"""Soft snow cap: rounded slab overhanging the post, a dome on top, a wavy drooping rim
|
||||
made of melted beads, and a couple of drips."""
|
||||
hw = w / 2
|
||||
# chunky: thick overhanging slab + tall dome
|
||||
melem("CUBE", base + Vector((0, 0, h + 0.45)), 0.75, size=(hw + 0.05, hw + 0.05, 0.28), yaw=yaw)
|
||||
melem("ELLIPSOID", base + Vector((0, 0, h + 1.0)), 1.0, size=(hw * 0.95, hw * 0.95, 0.75), yaw=yaw)
|
||||
rot = Matrix.Rotation(yaw, 4, "Z")
|
||||
edge = hw + 0.45
|
||||
for side in range(4):
|
||||
n = rot @ Vector((math.cos(side * math.pi / 2), math.sin(side * math.pi / 2), 0))
|
||||
t = Vector((-n.y, n.x, 0))
|
||||
steps = 3
|
||||
for s in range(steps + 1): # fat, wavy drooping rim
|
||||
u = -edge + 2 * edge * s / steps
|
||||
droop = random.uniform(0.0, 0.25)
|
||||
melem("BALL", base + n * (edge - 0.05) + t * u + Vector((0, 0, h + 0.12 - droop)),
|
||||
random.uniform(0.42, 0.55))
|
||||
# flowing snow: 1-2 soft tongues sliding down the side, each ending in a long drip
|
||||
for _ in range(random.choice((1, 1, 2))):
|
||||
u = random.uniform(-hw * 0.8, hw * 0.8)
|
||||
tl = random.uniform(0.45, 0.85) # tongue length
|
||||
pt = base + n * (edge - 0.22) + t * u + Vector((0, 0, h - tl / 2 + 0.1))
|
||||
melem("ELLIPSOID", pt, 1.0, size=(random.uniform(0.35, 0.5), 0.26, tl / 2 + 0.15),
|
||||
yaw=yaw + side * math.pi / 2)
|
||||
tip = base + n * (edge - 0.2) + t * (u + random.uniform(-0.15, 0.15)) + Vector((0, 0, h - tl + 0.15))
|
||||
drip(tip, yaw, random.uniform(0.35, 1.1), random.uniform(0.17, 0.24))
|
||||
for _ in range(random.choice((0, 1, 2))): # extra short drips along the rim
|
||||
p = base + n * (edge - 0.1) + t * random.uniform(-hw, hw) + Vector((0, 0, h))
|
||||
drip(p, yaw, random.uniform(0.3, 0.7), random.uniform(0.17, 0.23))
|
||||
|
||||
posts = resample(zone_perimeter(ZONE_A, ZONE_B, ZONE_CORNER), POST_STEP)
|
||||
n_posts = len(posts)
|
||||
GATE_W, GATE_POST_H = 2.4, 8.0
|
||||
for k, p in enumerate(posts):
|
||||
gate = k in (0, n_posts - 1)
|
||||
prev_p, next_p = posts[max(k - 1, 0)], posts[min(k + 1, n_posts - 1)]
|
||||
dl = W(next_p.x, next_p.y) - W(prev_p.x, prev_p.y)
|
||||
yaw = th if gate else math.atan2(dl.y, dl.x)
|
||||
base = W(p.x, p.y)
|
||||
w, h = (GATE_W, GATE_POST_H) if gate else (POST_W, POST_H)
|
||||
uv_box(bw, uvl, base + Vector((0, 0, h / 2)), (w, w, h), yaw)
|
||||
uv_box(bw, uvl, base + Vector((0, 0, h - 0.25)), (w + 0.35, w + 0.35, 0.5), yaw) # chunky top collar
|
||||
uv_box(bw, uvl, base + Vector((0, 0, 0.3)), (w + 0.3, w + 0.3, 0.6), yaw) # foot
|
||||
if gate:
|
||||
snow_cap(base, w + 0.35, h, yaw)
|
||||
lbox(base + Vector((0, 0, h + 1.35)), (0.5, 0.5, 0.5), yaw, 0) # lantern stem
|
||||
lbulb(base + Vector((0, 0, h + 2.05)), 0.62, 1) # glowing lantern
|
||||
else:
|
||||
snow_cap(base, w + 0.35, h, yaw)
|
||||
|
||||
for k in range(n_posts - 1):
|
||||
a_, b_ = W(posts[k].x, posts[k].y), W(posts[k + 1].x, posts[k + 1].y)
|
||||
d = b_ - a_
|
||||
yaw = math.atan2(d.y, d.x)
|
||||
mid = (a_ + b_) / 2
|
||||
L_ = d.length - POST_W + 0.3
|
||||
for z in RAIL_Z:
|
||||
uv_box(bw, uvl, mid + Vector((0, 0, z)), (L_, RAIL_T, RAIL_H), yaw) # thick rails
|
||||
top = RAIL_Z[1] + RAIL_H / 2
|
||||
low = RAIL_Z[0] + RAIL_H / 2
|
||||
tvec = d.normalized()
|
||||
nvec = Vector((-tvec.y, tvec.x, 0))
|
||||
# soft snow roll on the top rail: rounded slab + melted beads along both edges (wavy overhang)
|
||||
# chunky roll: thick rounded slab + fat beads along both edges
|
||||
melem("CUBE", mid + Vector((0, 0, top + 0.25)), 0.6, size=(L_ / 2 - 0.2, RAIL_T / 2 - 0.05, 0.16), yaw=yaw)
|
||||
nb = max(3, int(L_ / 0.9))
|
||||
for s_ in (-1, 1):
|
||||
for bi in range(nb + 1):
|
||||
u = -L_ / 2 + 0.3 + (L_ - 0.6) * bi / nb
|
||||
droop = random.uniform(0.0, 0.2)
|
||||
melem("BALL", mid + tvec * u + nvec * s_ * (RAIL_T / 2 + 0.12) + Vector((0, 0, top + 0.05 - droop)),
|
||||
random.uniform(0.34, 0.46))
|
||||
for _ in range(random.randint(2, 4)): # snow sliding over the rail edge + drips
|
||||
s_ = random.choice((-1, 1))
|
||||
u = random.uniform(-L_ / 2.6, L_ / 2.6)
|
||||
tl = random.uniform(0.35, 0.7)
|
||||
pt = mid + tvec * u + nvec * s_ * (RAIL_T / 2 + 0.1) + Vector((0, 0, top - tl / 2 + 0.1))
|
||||
melem("ELLIPSOID", pt, 1.0, size=(random.uniform(0.35, 0.6), 0.22, tl / 2 + 0.12), yaw=yaw)
|
||||
p = mid + tvec * (u + random.uniform(-0.2, 0.2)) + nvec * s_ * (RAIL_T / 2 + 0.12) + Vector((0, 0, top - tl + 0.1))
|
||||
drip(p, yaw, random.uniform(0.3, 0.9), random.uniform(0.16, 0.22))
|
||||
# lumpy snow on the lower rail
|
||||
melem("CUBE", mid + Vector((0, 0, low + 0.12)), 0.42, size=(L_ / 2 - 0.5, RAIL_T / 2 - 0.12, 0.06), yaw=yaw)
|
||||
for bi in range(nb):
|
||||
u = -L_ / 2 + 0.6 + (L_ - 1.2) * (bi + 0.5) / nb
|
||||
melem("BALL", mid + tvec * u + nvec * random.uniform(-0.15, 0.15) + Vector((0, 0, low + 0.15)),
|
||||
random.uniform(0.26, 0.36))
|
||||
# string lights on both faces of the fence, sagging between posts
|
||||
for s_ in (-1, 1):
|
||||
off = nvec * s_ * (RAIL_T / 2 + 0.55)
|
||||
n = 6
|
||||
prev = None
|
||||
for si in range(n + 1):
|
||||
t = si / n
|
||||
p = a_.lerp(b_, t) + off + Vector((0, 0, POST_H - 0.75 - 0.75 * math.sin(math.pi * t)))
|
||||
if prev is not None:
|
||||
seg = p - prev
|
||||
mid_w = (p + prev) / 2
|
||||
M = (Matrix.Translation(mid_w) @ Matrix.Rotation(yaw, 4, "Z")
|
||||
@ Matrix.Rotation(-math.atan2(seg.z, seg.xy.length), 4, "Y")
|
||||
@ Matrix.Diagonal((seg.length, 0.09, 0.09, 1)))
|
||||
bmesh.ops.create_cube(bl, size=1.0, matrix=M)
|
||||
if 0 < si < n:
|
||||
lbulb(p - Vector((0, 0, 0.42)), 0.24, 1 if si % 2 else 2)
|
||||
prev = p
|
||||
|
||||
# double gate: arched plank leaves with cross rails + diagonal brace, swung open into the zone
|
||||
leaf_w = GATE_HALF - GATE_W / 2 - 0.1
|
||||
for side in (-1, 1):
|
||||
hinge = W(side * (GATE_HALF - GATE_W / 2 - 0.05), -ZONE_B)
|
||||
open_yaw = th + side * math.radians(5) # ~95 deg open
|
||||
dir_ = Vector((math.cos(open_yaw), math.sin(open_yaw), 0))
|
||||
n_pl = 4
|
||||
pw = leaf_w / n_pl
|
||||
for pk in range(n_pl):
|
||||
off = pw * (pk + 0.5)
|
||||
closed_u = leaf_w - off # distance from the gate centre when closed
|
||||
h = 3.6 + 1.2 * math.cos(min(1.0, closed_u / GATE_HALF) * math.pi / 2)
|
||||
uv_box(bw, uvl, hinge + dir_ * off + Vector((0, 0, 0.3 + h / 2)), (pw - 0.06, 0.4, h), open_yaw)
|
||||
for z in (1.4, 3.3):
|
||||
uv_box(bw, uvl, hinge + dir_ * (leaf_w / 2) + Vector((0, 0, z)), (leaf_w, 0.7, 0.55), open_yaw)
|
||||
diag = math.atan2(1.9, leaf_w - 0.4)
|
||||
uv_box(bw, uvl, hinge + dir_ * (leaf_w / 2) + Vector((0, 0, 2.35)),
|
||||
(math.hypot(leaf_w - 0.4, 1.9), 0.6, 0.45), open_yaw, rot_y=diag) # Z-brace
|
||||
|
||||
wood_ob = finish_obj(zone_name + "_Fence", bw, [wood], coll, 0.12, 2)
|
||||
# polygonise the metaball snow into a regular smooth mesh
|
||||
mb_ob = bpy.data.objects.new(zone_name + "_SnowMB", mb)
|
||||
coll.objects.link(mb_ob)
|
||||
dg = bpy.context.evaluated_depsgraph_get()
|
||||
dg.update()
|
||||
sme = bpy.data.meshes.new_from_object(mb_ob.evaluated_get(dg))
|
||||
bpy.data.objects.remove(mb_ob, do_unlink=True)
|
||||
bpy.data.metaballs.remove(mb)
|
||||
sme.name = zone_name + "_FenceSnow"
|
||||
for p in sme.polygons:
|
||||
p.use_smooth = True
|
||||
sme.materials.clear()
|
||||
sme.materials.append(snow)
|
||||
snow_ob = bpy.data.objects.new(zone_name + "_FenceSnow", sme)
|
||||
coll.objects.link(snow_ob)
|
||||
# metaballs over-tessellate flat areas: bake a collapse-decimate into the mesh (keeps the soft shape)
|
||||
dec = snow_ob.modifiers.new("Decimate", "DECIMATE")
|
||||
dec.ratio = SNOW_DECIMATE
|
||||
dg = bpy.context.evaluated_depsgraph_get()
|
||||
dg.update()
|
||||
light_me = bpy.data.meshes.new_from_object(snow_ob.evaluated_get(dg))
|
||||
snow_ob.modifiers.clear()
|
||||
old = snow_ob.data
|
||||
snow_ob.data = light_me
|
||||
light_me.name = zone_name + "_FenceSnow"
|
||||
bpy.data.meshes.remove(old)
|
||||
for p in light_me.polygons:
|
||||
p.use_smooth = True # smooth, fluffy snow
|
||||
lights_ob = finish_obj(zone_name + "_Lights", bl, [wire, bulb, bulb2], coll, 0.02, 1, angle=60)
|
||||
return wood_ob, n_posts
|
||||
|
||||
# ---------------------------------------------------------------- studio
|
||||
def setup_studio(sc, coll):
|
||||
w = bpy.data.worlds.new("Sky")
|
||||
try:
|
||||
w.use_nodes = True
|
||||
except Exception:
|
||||
pass
|
||||
N, L = w.node_tree.nodes, w.node_tree.links
|
||||
N.clear()
|
||||
tc = N.new("ShaderNodeTexCoord"); sep = N.new("ShaderNodeSeparateXYZ")
|
||||
L.new(tc.outputs["Window"], sep.inputs[0])
|
||||
ramp = N.new("ShaderNodeValToRGB")
|
||||
ramp.color_ramp.elements[0].color = (0.32, 0.62, 1.0, 1)
|
||||
ramp.color_ramp.elements[1].color = (0.10, 0.36, 0.92, 1)
|
||||
L.new(sep.outputs["Y"], ramp.inputs["Fac"])
|
||||
bg_cam = N.new("ShaderNodeBackground"); L.new(ramp.outputs["Color"], bg_cam.inputs["Color"])
|
||||
bg_env = N.new("ShaderNodeBackground")
|
||||
bg_env.inputs["Color"].default_value = (0.45, 0.62, 1.0, 1); bg_env.inputs["Strength"].default_value = 0.9
|
||||
lp = N.new("ShaderNodeLightPath"); mix = N.new("ShaderNodeMixShader")
|
||||
L.new(lp.outputs["Is Camera Ray"], mix.inputs["Fac"])
|
||||
L.new(bg_env.outputs["Background"], mix.inputs[1]); L.new(bg_cam.outputs["Background"], mix.inputs[2])
|
||||
L.new(mix.outputs["Shader"], N.new("ShaderNodeOutputWorld").inputs["Surface"])
|
||||
sc.world = w
|
||||
|
||||
sun = bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN"))
|
||||
sun.data.energy = 3.2
|
||||
sun.data.color = (1.0, 0.93, 0.82)
|
||||
sun.data.angle = math.radians(4)
|
||||
sun.rotation_euler = (math.radians(58), 0, math.radians(-40))
|
||||
coll.objects.link(sun)
|
||||
|
||||
cam = bpy.data.objects.new("Map_Camera", bpy.data.cameras.new("Map_Camera"))
|
||||
cam.data.lens = 35
|
||||
cam.data.clip_end = 5000
|
||||
target = Vector((0, 0, -32))
|
||||
dist, el = 500.0, math.radians(36)
|
||||
cam.location = target + Vector((0, -dist * math.cos(el), dist * math.sin(el)))
|
||||
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
coll.objects.link(cam)
|
||||
sc.camera = cam
|
||||
|
||||
sc.render.engine = "BLENDER_EEVEE"
|
||||
try:
|
||||
sc.eevee.use_raytracing = True
|
||||
except Exception:
|
||||
pass
|
||||
sc.render.resolution_x, sc.render.resolution_y = 1920, 1080
|
||||
try:
|
||||
sc.view_settings.view_transform = "AgX"
|
||||
sc.view_settings.look = "AgX - Medium High Contrast"
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
tree = bpy.data.node_groups.new("Map_Compositor", "CompositorNodeTree")
|
||||
sc.compositing_node_group = tree
|
||||
rl, gl, go = tree.nodes.new("CompositorNodeRLayers"), tree.nodes.new("CompositorNodeGlare"), tree.nodes.new("NodeGroupOutput")
|
||||
tree.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")
|
||||
try:
|
||||
gl.glare_type = "BLOOM"
|
||||
except Exception:
|
||||
if "Type" in gl.inputs:
|
||||
gl.inputs["Type"].default_value = "Bloom"
|
||||
for k, v in (("Threshold", 1.0), ("Strength", 0.4), ("Size", 0.4)):
|
||||
if k in gl.inputs:
|
||||
gl.inputs[k].default_value = v
|
||||
tree.links.new(rl.outputs["Image"], gl.inputs["Image"])
|
||||
tree.links.new(gl.outputs["Image"], go.inputs[0])
|
||||
except Exception as ex:
|
||||
print("bloom unavailable:", ex)
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
def main():
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
sc, cols = setup_scene()
|
||||
snow, rock = mat_snow(), mat_rock()
|
||||
snow_soft = mat_snow_soft()
|
||||
tiles = mat_tiles("Path_Tiles", (0.30, 0.20, 0.13), (0.24, 0.155, 0.10), (0.11, 0.09, 0.08), 0.13)
|
||||
tiles_inner = mat_tiles("Plaza_Tiles_Radial", (0.36, 0.25, 0.17), (0.29, 0.19, 0.13), (0.12, 0.10, 0.09), 0.16, radial=True)
|
||||
curb = mat_simple("Stone_Curb", (0.15, 0.14, 0.16), 0.75)
|
||||
wood = mat_wood()
|
||||
wire = mat_simple("Light_Wire", (0.03, 0.04, 0.03), 0.6)
|
||||
bulb = mat_simple("Light_Bulb", (1.0, 0.72, 0.30), 0.2, emit=14.0)
|
||||
bulb2 = mat_simple("Light_Bulb_Gold", (1.0, 0.50, 0.12), 0.2, emit=12.0)
|
||||
build_island(cols["Terrain"], snow, rock)
|
||||
build_plaza_and_paths(cols["Terrain"], tiles, tiles_inner, curb)
|
||||
posts = 0
|
||||
for i in range(ZONE_COUNT):
|
||||
_, n = build_fence(i, cols["Fences"], wood, snow_soft, wire, bulb, bulb2)
|
||||
posts += n
|
||||
setup_studio(sc, cols["Studio"])
|
||||
sc.render.filepath = os.path.join(OUT_DIR, "map_preview.png")
|
||||
bpy.ops.render.render(write_still=True)
|
||||
# close-up of the bottom zone's gate to show fence detail and string lights
|
||||
cam = sc.camera
|
||||
_, er, et, c = zone_frame(7) # zone at 270 deg (front, nearest the camera)
|
||||
gate = c - er * ZONE_B
|
||||
tgt = Vector((gate.x, gate.y, 4.0)) + er * 6
|
||||
cam.location = Vector((gate.x, gate.y, 0)) - er * 30 + et * 16 + Vector((0, 0, 13))
|
||||
cam.rotation_euler = (tgt - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
sc.render.filepath = os.path.join(OUT_DIR, "map_closeup.png")
|
||||
bpy.ops.render.render(write_still=True)
|
||||
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT_DIR, "map_terrain.blend"))
|
||||
tris = sum(sum(len(p.vertices) - 2 for p in o.data.polygons) for o in bpy.data.objects if o.type == "MESH")
|
||||
return {"posts": posts, "tris_base": tris}
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("RESULT", main())
|
||||