Update
No files matched your search
@@ -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 |