# 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_ 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")