412 lines
17 KiB
Python
412 lines
17 KiB
Python
# Map -> Roblox GLBs with all textures embedded (same idea as the ornament machine export).
|
|
# Run on the saved copy: blender -b map/roblox/export_source.blend --python map/roblox/export_map_glb.py
|
|
#
|
|
# * flat-colour materials -> one palette atlas (32 px cells); every face points at its material's cell
|
|
# * procedural materials (fence wood, island snow, cliff, asphalt) -> baked into their own textures (Cycles)
|
|
# - the 10 zone fences share one bake: zone 1 is baked, the other fences get the same UVs (identical meshes)
|
|
# * snow meshes are decimated (they are the bulk of the 1.3M triangles)
|
|
# * everything is merged per texture into chunks of <= MAX_TRIS triangles (Roblox limit per MeshPart)
|
|
# * export: map_glb/Map_<Group>.glb (Zones / Plaza_Decor / Ground), each < 20 MB, + manifest.json
|
|
# * the zone name signs are left out (removed from the game earlier)
|
|
import bpy, bmesh, json, math, os
|
|
from collections import Counter, defaultdict
|
|
from mathutils import Vector, Matrix
|
|
|
|
SRC_DIR = os.path.dirname(bpy.data.filepath)
|
|
OUT = os.path.join(SRC_DIR, "map_glb")
|
|
os.makedirs(OUT, exist_ok=True)
|
|
MAX_TRIS = 18000
|
|
SNOW_RATIO = 0.35 # decimation of snow meshes (plaza, pines)
|
|
ZONE_SNOW_RATIO = 0.15 # snow draped on the 10 zone fences
|
|
BULB_RATIO = 0.22 # garland bulbs (smooth spheres)
|
|
WIRE_RATIO = 0.35 # garland wire
|
|
CELL, GRID = 32, 8 # palette atlas: 8x8 cells of 32 px
|
|
EXCLUDE = {"Studio"}
|
|
GROUND = {"Terrain", "Landscape_Snowdrifts", "Asphalt_Edge_Snowdrifts", "Continuous_Curb_Snow"}
|
|
ZONES = {"Fences", "Snow_Draped_Reference", "Snow_Organic_Domes",
|
|
"Festive_Nameplate_Details", "Sign_Fence_Style_Supports", "Zone_Player_Nameplates"}
|
|
# v2: no per-object bakes any more (their UVs came out wrong in Roblox): procedural materials are baked once,
|
|
# averaged to one colour and go into the palette like the flat ones; detail comes from the Roblox material.
|
|
BAKE_SIZE = {"Island__Snow": 2048}
|
|
DEFAULT_BAKE = 1024
|
|
FENCE_MAT = "Fence_Warm_Cedar_Subtle"
|
|
|
|
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 bsdf(m):
|
|
return next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) if m and m.node_tree else None
|
|
|
|
def is_procedural(m):
|
|
if not m or not m.node_tree:
|
|
return False
|
|
return any(n.type.startswith("TEX_") for n in m.node_tree.nodes)
|
|
|
|
def glow_of(m):
|
|
b = bsdf(m)
|
|
name = m.name.lower() if m else ""
|
|
return ("bulb" in name or "glass" in name) or (b is not None and b.inputs["Emission Strength"].default_value >= 0.5)
|
|
|
|
def coll_of(o):
|
|
return o.users_collection[0].name if o.users_collection else ""
|
|
|
|
# ------------------------------------------------------------------ scene objects to export
|
|
visible = [o for o in bpy.data.objects if o.type in ("MESH", "CURVE") and o.visible_get() and coll_of(o) not in EXCLUDE]
|
|
def group_of(o):
|
|
c = coll_of(o)
|
|
if c in GROUND:
|
|
return "Ground"
|
|
if c in ZONES:
|
|
# two files (upload limit 20 MB): zones on the +Y half of the island and on the -Y half
|
|
cs = [o.matrix_world @ Vector(v) for v in o.bound_box]
|
|
return "Zones_North" if sum(v.y for v in cs) >= 0 else "Zones_South"
|
|
return "Plaza_Decor"
|
|
print("OBJECTS", len(visible), dict(Counter(group_of(o) for o in visible)))
|
|
|
|
work = bpy.data.collections.new("RobloxExport") # merged export meshes live here (in the same scene)
|
|
bpy.context.scene.collection.children.link(work)
|
|
dg = bpy.context.evaluated_depsgraph_get()
|
|
|
|
def world_mesh(o):
|
|
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()
|
|
return me
|
|
|
|
# ------------------------------------------------------------------ palette for flat materials
|
|
palette, cells = {}, []
|
|
proc_color = {} # procedural material name -> averaged linear colour
|
|
def cell_uv(m):
|
|
key = m.name if m else "__none__"
|
|
if key not in palette:
|
|
b = bsdf(m)
|
|
col = list(b.inputs["Base Color"].default_value[:3]) if b else [0.8, 0.8, 0.8]
|
|
if m and m.name in proc_color:
|
|
col = proc_color[m.name]
|
|
if m and glow_of(m) and b:
|
|
ec = b.inputs["Emission Color"].default_value
|
|
if max(ec[:3]) > 0.05:
|
|
col = list(ec[:3])
|
|
palette[key] = len(cells)
|
|
cells.append(col)
|
|
if len(cells) > GRID * GRID:
|
|
raise RuntimeError("palette overflow")
|
|
i = palette[key]
|
|
return ((i % GRID) + 0.5) / GRID, ((i // GRID) + 0.5) / GRID
|
|
|
|
# ------------------------------------------------------------------ bake helpers
|
|
sc = bpy.context.scene
|
|
sc.render.engine = "CYCLES"
|
|
sc.cycles.samples = 4
|
|
sc.cycles.device = "CPU"
|
|
sc.render.bake.use_pass_direct = False
|
|
sc.render.bake.use_pass_indirect = False
|
|
sc.render.bake.use_pass_color = True
|
|
sc.render.bake.margin = 6
|
|
|
|
def bake_object_texture(name, me, mat, size):
|
|
"""me = world-space mesh using only `mat`; adds BakeUV, bakes the diffuse colour, returns the image."""
|
|
ob = bpy.data.objects.new("_bake_" + name, me)
|
|
sc.collection.objects.link(ob)
|
|
uv = me.uv_layers.new(name="BakeUV")
|
|
for l in me.uv_layers:
|
|
l.active_render = (l.name != "BakeUV") if len(me.uv_layers) > 1 else True
|
|
me.uv_layers.active = uv
|
|
bpy.ops.object.select_all(action="DESELECT")
|
|
ob.select_set(True)
|
|
bpy.context.view_layer.objects.active = ob
|
|
bpy.ops.object.mode_set(mode="EDIT")
|
|
bpy.ops.mesh.select_all(action="SELECT")
|
|
bpy.ops.uv.smart_project(angle_limit=math.radians(66), island_margin=0.003, scale_to_bounds=True)
|
|
bpy.ops.object.mode_set(mode="OBJECT")
|
|
img = bpy.data.images.new("Tex_" + name, size, size, alpha=False)
|
|
bm_ = mat.copy()
|
|
t = bm_.node_tree.nodes.new("ShaderNodeTexImage")
|
|
t.image = img
|
|
bm_.node_tree.nodes.active = t
|
|
me.materials.clear()
|
|
me.materials.append(bm_)
|
|
bpy.ops.object.bake(type="DIFFUSE", pass_filter={"COLOR"}, use_clear=True)
|
|
img.filepath_raw = os.path.join(OUT, img.name + ".png")
|
|
img.file_format = "PNG"
|
|
img.save()
|
|
sc.collection.objects.unlink(ob)
|
|
bpy.data.objects.remove(ob)
|
|
return img
|
|
|
|
# ------------------------------------------------------------------ build per-object pieces
|
|
# piece = (group, texture key, roblox material, bmesh in world space with a "UV" layer)
|
|
pieces = []
|
|
fence_bake = None # (image, uv list) from zone 1
|
|
fences = sorted([o for o in visible if any(s.material and s.material.name == FENCE_MAT for s in o.material_slots)
|
|
and coll_of(o) in ZONES], key=lambda o: o.name)
|
|
|
|
def split_faces(o, me):
|
|
"""-> {material: bmesh with only that material's faces}"""
|
|
names = [s.material for s in o.material_slots] or [None]
|
|
out = {}
|
|
used = {min(p.material_index, len(names) - 1) for p in me.polygons}
|
|
for idx in used:
|
|
m = names[idx]
|
|
bm = bmesh.new()
|
|
bm.from_mesh(me)
|
|
bmesh.ops.delete(bm, geom=[f for f in bm.faces if min(f.material_index, len(names) - 1) != idx], context="FACES")
|
|
if bm.faces:
|
|
key = m.name if m else "__none__"
|
|
if key in out:
|
|
tmp = bpy.data.meshes.new("_tmp"); bm.to_mesh(tmp); out[key][1].from_mesh(tmp); bpy.data.meshes.remove(tmp); bm.free()
|
|
else:
|
|
out[key] = (m, bm)
|
|
else:
|
|
bm.free()
|
|
return out
|
|
|
|
def decimate_bm(bm, ratio):
|
|
me = bpy.data.meshes.new("_dec")
|
|
bm.to_mesh(me)
|
|
bm.free()
|
|
ob = bpy.data.objects.new("_dec", me)
|
|
sc.collection.objects.link(ob)
|
|
mod = ob.modifiers.new("D", "DECIMATE")
|
|
mod.ratio = ratio
|
|
d2 = bpy.context.evaluated_depsgraph_get(); d2.update()
|
|
nm = bpy.data.meshes.new_from_object(ob.evaluated_get(d2))
|
|
out = bmesh.new()
|
|
out.from_mesh(nm)
|
|
sc.collection.objects.unlink(ob)
|
|
bpy.data.objects.remove(ob)
|
|
bpy.data.meshes.remove(me)
|
|
bpy.data.meshes.remove(nm)
|
|
return out
|
|
|
|
def set_uv_cell(bm, uv_xy):
|
|
for l in list(bm.loops.layers.uv):
|
|
bm.loops.layers.uv.remove(l)
|
|
uv = bm.loops.layers.uv.new("UV")
|
|
for f in bm.faces:
|
|
for lp in f.loops:
|
|
lp[uv].uv = uv_xy
|
|
|
|
def bm_from_mesh(me, keep_uv_name=None):
|
|
bm = bmesh.new()
|
|
bm.from_mesh(me)
|
|
if keep_uv_name:
|
|
keep = bm.loops.layers.uv.get(keep_uv_name)
|
|
for l in list(bm.loops.layers.uv):
|
|
if l != keep:
|
|
bm.loops.layers.uv.remove(l)
|
|
# rename to "UV"
|
|
uv = bm.loops.layers.uv.new("UV")
|
|
for f in bm.faces:
|
|
for lp in f.loops:
|
|
lp[uv].uv = lp[keep].uv
|
|
bm.loops.layers.uv.remove(keep)
|
|
return bm
|
|
|
|
def to_linear(c):
|
|
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
|
|
|
|
def mean_color(o, m):
|
|
me = world_mesh(o)
|
|
parts = split_faces(o, me)
|
|
bpy.data.meshes.remove(me)
|
|
if m.name not in parts:
|
|
return None
|
|
bm = parts.pop(m.name)[1]
|
|
for _, b2 in parts.values():
|
|
b2.free()
|
|
tmp = bpy.data.meshes.new("_mc"); bm.to_mesh(tmp); bm.free()
|
|
img = bake_object_texture("_mean_" + m.name, tmp, m, 128)
|
|
bpy.data.meshes.remove(tmp)
|
|
px = list(img.pixels)
|
|
acc, n = [0.0, 0.0, 0.0], 0
|
|
for k in range(0, len(px), 4):
|
|
if px[k] + px[k + 1] + px[k + 2] > 0.03: # skip the black background around UV islands
|
|
acc[0] += px[k]; acc[1] += px[k + 1]; acc[2] += px[k + 2]; n += 1
|
|
os.remove(img.filepath_raw)
|
|
bpy.data.images.remove(img)
|
|
return [to_linear(a / max(1, n)) for a in acc]
|
|
|
|
for o in visible:
|
|
for s in o.material_slots:
|
|
m = s.material
|
|
if m and is_procedural(m) and m.name not in proc_color:
|
|
c = mean_color(o, m)
|
|
if c:
|
|
proc_color[m.name] = c
|
|
print("MEAN", m.name, [round(to_srgb(v) * 255) for v in c])
|
|
|
|
fences = [] # fences now go through the palette path like everything else
|
|
if False:
|
|
z1 = fences[0]
|
|
me = world_mesh(z1)
|
|
img = bake_object_texture("Fence_Wood", me, bpy.data.materials[FENCE_MAT], DEFAULT_BAKE)
|
|
uvs = [d.uv.copy() for d in me.uv_layers["BakeUV"].data]
|
|
fence_bake = (img, uvs)
|
|
pieces.append((group_of(z1), img.name, "Wood", bm_from_mesh(me, "BakeUV")))
|
|
bpy.data.meshes.remove(me)
|
|
for o in fences[1:]:
|
|
me2 = world_mesh(o)
|
|
if len(me2.loops) == len(uvs):
|
|
lay = me2.uv_layers.new(name="BakeUV")
|
|
for k, d in enumerate(lay.data):
|
|
d.uv = uvs[k]
|
|
pieces.append((group_of(o), img.name, "Wood", bm_from_mesh(me2, "BakeUV")))
|
|
else:
|
|
print("WARNING fence topology differs, baking separately:", o.name)
|
|
im2 = bake_object_texture("Fence_" + o.name, me2, bpy.data.materials[FENCE_MAT], DEFAULT_BAKE)
|
|
pieces.append((group_of(o), im2.name, "Wood", bm_from_mesh(me2, "BakeUV")))
|
|
bpy.data.meshes.remove(me2)
|
|
|
|
fence_set = set(fences)
|
|
baked = Counter()
|
|
for o in visible:
|
|
if o in fence_set:
|
|
continue
|
|
grp = group_of(o)
|
|
me = world_mesh(o)
|
|
for key, (m, bm) in split_faces(o, me).items():
|
|
if False:
|
|
# bake this object's faces of the procedural material
|
|
tmp = bpy.data.meshes.new("_proc"); bm.to_mesh(tmp); bm.free()
|
|
img = bake_object_texture("%s_%s" % (o.name, m.name), tmp, m, BAKE_SIZE.get(o.name, DEFAULT_BAKE))
|
|
baked[m.name] += 1
|
|
pieces.append((grp, img.name, "Snow" if "snow" in m.name.lower() else ("Slate" if "rock" in m.name.lower() else "SmoothPlastic"),
|
|
bm_from_mesh(tmp, "BakeUV")))
|
|
bpy.data.meshes.remove(tmp)
|
|
else:
|
|
low_name = m.name.lower() if m else ""
|
|
ratio = None
|
|
if grp.startswith("Zones"): # 10 copies of everything: keep it light
|
|
if "snow" in low_name:
|
|
ratio = ZONE_SNOW_RATIO
|
|
elif "bulb" in low_name:
|
|
ratio = BULB_RATIO
|
|
elif "wire" in low_name:
|
|
ratio = WIRE_RATIO
|
|
elif "snow" in low_name and grp != "Ground":
|
|
ratio = SNOW_RATIO
|
|
if ratio:
|
|
bm = decimate_bm(bm, ratio)
|
|
set_uv_cell(bm, cell_uv(m))
|
|
low = (m.name.lower() if m else "")
|
|
rb = "Neon" if (m and glow_of(m)) else ("Snow" if "snow" in low else ("Wood" if "wood" in low or "trunk" in low
|
|
or "cedar" in low or "fence" in low or "timber" in low
|
|
else ("Slate" if "rock" in low or "cliff" in low else ("Asphalt" if "asphalt" in low
|
|
else ("Metal" if "bronze" in low or "gold" in low else "SmoothPlastic")))))
|
|
# one colour per mesh part: Roblox gets Part.Color from the cell, no texture sampling at all
|
|
pieces.append((grp, "C%02d" % palette[m.name if m else "__none__"], rb, bm))
|
|
bpy.data.meshes.remove(me)
|
|
print("BAKED", dict(baked), "PALETTE", len(cells))
|
|
|
|
# ------------------------------------------------------------------ palette image
|
|
TEX = CELL * GRID
|
|
pal = bpy.data.images.new("Tex_Palette", TEX, TEX, alpha=False)
|
|
px = [0.0] * (TEX * TEX * 4)
|
|
for i, c in enumerate(cells):
|
|
r, g, b = to_srgb(c[0]), to_srgb(c[1]), to_srgb(c[2])
|
|
cx, cy = (i % GRID) * CELL, (i // GRID) * CELL
|
|
for y in range(cy, cy + CELL):
|
|
for x in range(cx, cx + CELL):
|
|
k = (y * TEX + x) * 4
|
|
px[k:k + 4] = (r, g, b, 1.0)
|
|
pal.pixels = px
|
|
pal.filepath_raw = os.path.join(OUT, "Tex_Palette.png")
|
|
pal.file_format = "PNG"
|
|
pal.save()
|
|
|
|
# ------------------------------------------------------------------ export materials (one per texture)
|
|
mats = {}
|
|
def export_mat(tex_name, glow):
|
|
key = tex_name + ("_glow" if glow else "")
|
|
if key in mats:
|
|
return mats[key]
|
|
m = bpy.data.materials.new("M_" + key)
|
|
try:
|
|
m.use_nodes = True
|
|
except Exception:
|
|
pass
|
|
nt = m.node_tree
|
|
nt.nodes.clear()
|
|
out = nt.nodes.new("ShaderNodeOutputMaterial")
|
|
b = nt.nodes.new("ShaderNodeBsdfPrincipled")
|
|
b.inputs["Roughness"].default_value = 0.6
|
|
t = nt.nodes.new("ShaderNodeTexImage")
|
|
t.image = bpy.data.images["Tex_Palette" if tex_name.startswith("C") else tex_name]
|
|
t.interpolation = "Closest"
|
|
nt.links.new(t.outputs["Color"], b.inputs["Base Color"])
|
|
if glow:
|
|
nt.links.new(t.outputs["Color"], b.inputs["Emission Color"])
|
|
b.inputs["Emission Strength"].default_value = 1.0
|
|
nt.links.new(b.outputs["BSDF"], out.inputs["Surface"])
|
|
mats[key] = m
|
|
return m
|
|
|
|
# ------------------------------------------------------------------ merge into chunks and export
|
|
def tris(bm):
|
|
return sum(len(f.verts) - 2 for f in bm.faces)
|
|
|
|
buckets = defaultdict(list) # (group, texture, roblox material) -> [bm]
|
|
for grp, tex, rb, bm in pieces:
|
|
buckets[(grp, tex, rb)].append(bm)
|
|
|
|
manifest = []
|
|
group_objs = defaultdict(list)
|
|
for (grp, tex, rb), bms in sorted(buckets.items()):
|
|
# sort pieces around the island so chunks are spatially compact
|
|
def ang(bm):
|
|
c = sum((v.co for v in bm.verts), Vector()) / max(1, len(bm.verts))
|
|
return math.atan2(c.y, c.x)
|
|
bms.sort(key=ang)
|
|
chunk, n, k = bmesh.new(), 0, 0
|
|
def flush():
|
|
nonlocal_holder = None
|
|
out_chunks = []
|
|
for bm in bms:
|
|
t = tris(bm)
|
|
if n and n + t > MAX_TRIS:
|
|
out_chunks.append(chunk); chunk, n = bmesh.new(), 0
|
|
me = bpy.data.meshes.new("_m"); bm.to_mesh(me); chunk.from_mesh(me); bpy.data.meshes.remove(me); bm.free()
|
|
n += t
|
|
if n:
|
|
out_chunks.append(chunk)
|
|
for k, ch in enumerate(out_chunks):
|
|
bmesh.ops.triangulate(ch, faces=ch.faces[:])
|
|
if tris(ch) > MAX_TRIS: # a single huge piece: decimate the chunk
|
|
ch = decimate_bm(ch, MAX_TRIS / tris(ch) * 0.97)
|
|
name = "%s_%s_%s_%d" % (grp, rb, tex.replace("Tex_", ""), k)
|
|
name = name[:60]
|
|
me = bpy.data.meshes.new(name)
|
|
ch.to_mesh(me)
|
|
ch.free()
|
|
glow = rb == "Neon"
|
|
me.materials.append(export_mat(tex, glow))
|
|
for p in me.polygons:
|
|
p.use_smooth = rb == "Snow"
|
|
cs = [v.co for v in me.vertices]
|
|
lo = Vector((min(c.x for c in cs), min(c.y for c in cs), min(c.z for c in cs)))
|
|
hi = Vector((max(c.x for c in cs), max(c.y for c in cs), max(c.z for c in cs)))
|
|
ob = bpy.data.objects.new(name, me)
|
|
work.objects.link(ob)
|
|
group_objs[grp].append(ob)
|
|
manifest.append({"name": name, "group": grp, "material": rb, "texture": tex, "tris": len(me.polygons),
|
|
"center": [round(v, 3) for v in (lo + hi) / 2]})
|
|
|
|
# export one GLB per group (selection in the work scene)
|
|
for grp, objs in group_objs.items():
|
|
for o in bpy.context.view_layer.objects:
|
|
o.select_set(False)
|
|
for o in objs:
|
|
o.select_set(True)
|
|
path = os.path.join(OUT, "Map_%s.glb" % grp)
|
|
bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_yup=True,
|
|
export_apply=True, export_materials="EXPORT", export_image_format="AUTO")
|
|
print("GLB", grp, len(objs), "objects", round(os.path.getsize(path) / 1e6, 2), "MB",
|
|
sum(m["tris"] for m in manifest if m["group"] == grp), "tris")
|
|
|
|
json.dump({"parts": manifest, "palette": [[round(v, 4) for v in c] for c in cells]},
|
|
open(os.path.join(OUT, "manifest.json"), "w"), indent=1)
|
|
print("TOTAL", len(manifest), "meshes", sum(m["tris"] for m in manifest), "tris")
|