Files
Ornament-Generator-RNG/map/roblox/split_by_material.py
T
2026-11-16 23:50:40 +03:00

52 lines
2.5 KiB
Python

# Split every object that uses several materials into one object per material, so Roblox (one
# material per MeshPart) keeps candy stripes, pine facet shades, wire vs bulbs, snow vs cliff.
# Saves a NEW file next to the source and exports FBX + GLB for Roblox.
# Run: blender -b map_reference_pines.blend --python split_by_material.py
import bpy, os
src = bpy.data.filepath
base = os.path.splitext(src)[0] + "_split"
def material_names(o):
return [s.material.name for s in o.material_slots if s.material]
targets = [o for o in bpy.data.objects if o.type == "MESH" and len(set(material_names(o))) > 1]
made = 0
for o in targets:
orig_name = o.name
before = set(bpy.data.objects)
bpy.ops.object.mode_set(mode="OBJECT") if bpy.context.object and bpy.context.object.mode != "OBJECT" else None
bpy.ops.object.select_all(action="DESELECT")
o.select_set(True)
bpy.context.view_layer.objects.active = o
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.mesh.separate(type="MATERIAL")
bpy.ops.object.mode_set(mode="OBJECT")
pieces = [o] + [x for x in set(bpy.data.objects) - before]
for p in pieces:
# each piece now only has faces of one material; drop unused slots and name it after that material
used = {f.material_index for f in p.data.polygons}
mats = [p.material_slots[i].material for i in sorted(used) if i < len(p.material_slots)]
mname = mats[0].name if mats else "None"
p.data.materials.clear()
for f in p.data.polygons:
f.material_index = 0
if mats:
p.data.materials.append(mats[0])
p.name = "%s__%s" % (orig_name, mname)
made += 1
bpy.ops.wm.save_as_mainfile(filepath=base + ".blend", copy=True)
bpy.ops.object.select_all(action="DESELECT")
export_objs = [o for o in bpy.data.objects if o.type in ("MESH", "CURVE", "FONT") and o.visible_get()]
for o in export_objs:
o.select_set(True)
bpy.ops.export_scene.fbx(filepath=base + ".fbx", use_selection=True, object_types={"MESH", "OTHER"},
apply_unit_scale=True, apply_scale_options="FBX_SCALE_ALL", use_mesh_modifiers=True,
mesh_smooth_type="FACE", path_mode="AUTO")
bpy.ops.export_scene.gltf(filepath=base + ".glb", export_format="GLB", use_selection=True,
export_yup=True, export_apply=True)
print("SPLIT objects:", len(targets), "-> pieces:", made, "| exported", len(export_objs), "objects")
print("FILES", base + ".blend", base + ".fbx", base + ".glb")