Files
Bonchellon 52619d8952 Hologram calls, HaulOS phone, Enhanced lighting, smoother camera; Blender remaster review files
Game:
- Assistant and Director portraits: GPT backgrounds and a holographic appear/disappear shader (Talk/TalkHolo) instead of on/off
- Phone redesigned (HaulOS home, address bar, dock, error/loading states) and the browser link made sturdier
- Settings > Graphics > Lighting: Classic / Enhanced (runtime volume, no project assets changed); Enhanced SSAO uses the
  smooth interleaved-gradient method at high samples so flat panels don't speckle
- Painted board textures (T_HullPanel, T_BarnRed) keep only edge wear: the big bare-wood patches read as dirty smudges
- The head leans into a sidestep smoothly instead of snapping with A / D
- New keys in all 11 languages

Review only (nothing swapped into the game yet): ArtSource/Blender/remaster (v1 paint pass of our own models, Synty-built
ones left out), remaster/crew (crew repaint with arm, colour-edge and face fixes), remaster_v2 (smooth-geometry pilot).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:28:47 +03:00

1311 lines
51 KiB
Python

"""GRASS CUTTER - remaster pass over our own models (review copies, nothing in Assets/ is touched).
For every model in MODELS below:
1. import the game FBX (Assets/Art/Models/<name>.fbx) and give its slots the game's colours (ArtSource/materials*.json,
the Synty atlas for M_Pack, the tiling textures from Assets/Art/Textures, all read-only)
2. geometry polish on the paintable objects: smooth shading + sharp by angle, a bevel by angle with harden normals,
recessed riveted panels on the largest flat hard-surface faces (machines / vehicles / robots / train / scene)
3. a new UV set (smart project + pack with margins) and a Cycles EMIT bake of a stylised paint layer into one atlas:
slot colour or texture, top-lit gradient, cool AO in crevices, edge highlights on convex edges, edge wear and
scratches on metal, mud and grass stains low on machines and tools; plus a metallic/roughness map
4. one painted material per model (M_Paint_<short>); glowing, glass, runtime-swapped and decal slots stay their own
untextured/original slots; objects the game drives by material or UV (Lamp, Fill, Glow, Glass, Screen, Display,
Sign, Belt, ...) are left exactly as they were
5. save <OUT>/<name>.blend, textures/T_<short>_Paint.png + T_<short>_MS.png, fbx/<name>.fbx (common.py export
settings), previews/<name>.png, and for a few key models previews/compare/<name>_before_after.png (left before)
Every object keeps its name, parent, transform and origin. Resumable: a model with stats/<name>.json is skipped
(pass --force to redo).
Run: blender -b --factory-startup --python remaster.py --python-exit-code 1 -- [names...] [--force] [--nopreview]
"""
import bpy, bmesh, json, math, os, sys, time, random, traceback
from mathutils import Vector, Matrix
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", ".."))
MODELS_DIR = os.path.join(ROOT, "Assets", "Art", "Models")
TEXSRC = os.path.join(ROOT, "Assets", "Art", "Textures")
OUT = os.environ.get("RM_OUT") or os.path.join(ROOT, "ArtSource", "Blender", "remaster")
DEBUG = os.environ.get("RM_DEBUG", "")
TEXOUT = os.path.join(OUT, "textures")
FBXOUT = os.path.join(OUT, "fbx")
PREVOUT = os.path.join(OUT, "previews")
CMPOUT = os.path.join(PREVOUT, "compare")
STATS = os.path.join(OUT, "stats")
CATEGORIES = {
"Tools": ["SM_Tool_NailScissors", "SM_Tool_GardenShears", "SM_Tool_Sickle", "SM_Tool_Scythe", "SM_Tool_LongScythe",
"SM_Tool_WideScythe", "SM_Tool_Hammer", "SM_Tool_LawnMower"],
# left out, the Synty pack is not ours to touch: SM_PushMower and SM_RiderMower (POLYGON Farm TractorOld, gc_pack_vehicles),
# SM_HaulTractor / SM_WideMulcher / SM_BalerTractor (pack tractors and attachments) and SM_GarageDoor (the pack garage's own
# door), all from gc_stage17
"Vehicles": ["SM_GarageOutlet", "SM_MowerBar"],
"Train": ["SM_TrainLoco", "SM_TrainWagon", "SM_TrainStation"],
"Robots": ["SM_RobotMower", "SM_RobotDock", "SM_Reaper", "SM_BundleCatcher", "SM_Drone", "SM_DronePad"],
"Machines": ["SM_CryoPress", "SM_Binder", "SM_BeltSplitter", "SM_BeltMerger", "SM_BatteryRack", "SM_BatteryBank",
"SM_SolarPost", "SM_SolarPair", "SM_SolarTracker", "SM_Belt", "SM_Windmill", "SM_UnloadBay",
"SM_BaseIntake", "SM_Hopper"],
"Building": ["SM_Wall", "SM_WallDoor", "SM_WallWindow", "SM_Floor", "SM_FlatRoof", "SM_Roof", "SM_Stairs", "SM_Steps",
"SM_Pillar", "SM_Railing", "SM_Fence", "SM_Planter", "SM_Lamppost", "SM_Bench", "SM_Crate", "SM_Flagpole",
"SM_Deck_Square", "SM_Deck_Hex", "SM_Foundation_Square", "SM_Foundation_Hex"],
"Scene": ["SM_DeckTile", "SM_Dock", "SM_Ladder", "SM_CrewCabin", "SM_Terminal", "SM_SupplyWall", "SM_Decor_Lamp",
"SM_Decor_Dish"],
"Props": ["SM_VendBeer", "SM_VendSmoke", "SM_BeerCan", "SM_BeerCanCrushed", "SM_Cigar", "SM_HandCan", "SM_HandCigar",
"SM_Phone"],
"World": ["SM_Spire_A", "SM_Spire_B", "SM_Spire_C", "SM_SurveyStake", "SM_SurveyPoint", "SM_Ufo", "SM_Bug",
"SM_Grasshopper", "SM_Hemp"],
}
CAT_OF = {n: c for c, ns in CATEGORIES.items() for n in ns}
ALL = [n for ns in CATEGORIES.values() for n in ns]
COMPARE = {"SM_Tool_Scythe", "SM_RobotMower", "SM_Drone", "SM_Windmill", "SM_VendBeer",
"SM_VendSmoke", "SM_CrewCabin"}
# models left as they are, with the reason (reported)
SKIP = {"SM_Hemp": "alpha-cutout leaf cards (M_HempCard): nothing to bevel, an opaque paint bake would lose the cutout"}
# per category: dirt (mud/grass low down), wear (edge chips/scratches), panels (riveted panels, max count), panel mats
CAT_LOOK = {
"Tools": dict(dirt=0.45, wear=1.0, panels=0, tool=True),
"Vehicles": dict(dirt=1.0, wear=1.0, panels=8),
"Train": dict(dirt=0.8, wear=0.9, panels=10),
"Robots": dict(dirt=0.6, wear=0.7, panels=6),
"Machines": dict(dirt=0.6, wear=0.8, panels=8),
"Building": dict(dirt=0.45, wear=0.6, panels=4),
"Scene": dict(dirt=0.45, wear=0.6, panels=6),
"Props": dict(dirt=0.0, wear=0.5, panels=0),
"World": dict(dirt=0.0, wear=0.3, panels=0),
}
# objects the game drives by material / UV / emission, or that are pure glow/glass: left untouched
UNTOUCHED_OBJ = {"Lamp", "Fill", "Grass", "Glow", "Glass", "Bulb", "Bulbs", "Dome", "Emitter", "Ember", "Screen", "Display",
"Sign", "Belt", "BlinkEye_L", "BlinkEye_R"}
# slots that stay their own material (decals, fills, runtime-looked-up)
KEEP_MATS = {"M_Clippings", "M_GrassFill", "M_Logo", "M_GaugeFace", "M_Screen", "M_PhoneGlow", "M_PhoneIdle", "M_HempCard",
"M_SlatBelt", "M_ConveyorBelt", "M_WindowGlass", "M_Pupil"}
# hard-surface slots that may get riveted panels
PANEL_MATS = {"M_Steel", "M_HullWhite", "M_BarnRed", "M_PaintRed", "M_PaintGreen", "M_PaintDarkGreen",
"M_PaintYellow", "M_PaintCream", "M_PaintWhite", "M_Soot", "M_Teal", "M_Navy", "M_Pack"}
PANEL_CATS_PACK = {"Vehicles", "Robots", "Machines", "Train", "Scene"}
NO_DETAIL_OBJ = ("Wheel", "Rotor", "Reel", "SpinBlade", "Claw", "Blade", "Tab", "Hand", "Paddle", "Gauge", "Knob", "Button")
METALLIC_NAMES = {"M_Steel", "M_Brass", "M_Gold", "M_Tin", "M_TinOld", "M_PhoneBand", "M_PhoneShell"}
MATDEFS = {}
for _fn in sorted(os.listdir(os.path.join(ROOT, "ArtSource"))):
if _fn.startswith("materials") and _fn.endswith(".json"):
with open(os.path.join(ROOT, "ArtSource", _fn), "r", encoding="utf-8") as f:
MATDEFS.update({m["name"]: m for m in json.load(f)})
def log(*a):
print("[remaster]", *a, flush=True)
def short(name):
return name[3:] if name.startswith("SM_") else name
def base_name(n):
return n.split(".")[0] if n else n
def hex2lin(h):
h = h.lstrip("#")
c = [int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4)]
return [((x + 0.055) / 1.055) ** 2.4 if x > 0.04045 else x / 12.92 for x in c]
def mdef(n):
d = dict(MATDEFS.get(base_name(n), {}))
d.setdefault("color", "#BBBBBB")
if d.get("metallic") is None:
d["metallic"] = 0.8 if base_name(n) in METALLIC_NAMES else 0.0
if d.get("smoothness") is None:
d["smoothness"] = 0.3
if not d.get("tiling"):
d["tiling"] = [1, 1]
return d
def is_special(n):
n = base_name(n)
d = MATDEFS.get(n, {})
return bool(d.get("emission")) or bool(d.get("transparent")) or n in KEEP_MATS or "Glass" in n or n.startswith("M_Light")
def load_tex(fn):
p = os.path.join(TEXSRC, fn)
if not os.path.exists(p):
return None
return bpy.data.images.load(p, check_existing=True)
# ---------------------------------------------------------------- scene / setup
def reset():
bpy.ops.wm.read_factory_settings(use_empty=True)
for c in (bpy.data.meshes, bpy.data.materials, bpy.data.objects, bpy.data.images, bpy.data.curves):
for d in list(c):
c.remove(d)
def gpu(sc):
sc.render.engine = "CYCLES"
try:
p = bpy.context.preferences.addons["cycles"].preferences
for t in ("OPTIX", "CUDA"):
try:
p.compute_device_type = t
p.get_devices()
devs = [d for d in p.devices if d.type == t]
if devs:
for d in p.devices:
d.use = d.type == t
sc.cycles.device = "GPU"
return t
except Exception:
continue
except Exception:
pass
sc.cycles.device = "CPU"
return "CPU"
def orig_material(n):
"""The game's look of slot n (as common.mat builds it), named n."""
nb = base_name(n)
d = mdef(nb)
m = bpy.data.materials.new(nb)
nt = m.node_tree
bsdf = next(x for x in nt.nodes if x.type == "BSDF_PRINCIPLED")
col = hex2lin(d["color"]) + [1.0]
bsdf.inputs["Base Color"].default_value = col
bsdf.inputs["Metallic"].default_value = d["metallic"]
bsdf.inputs["Roughness"].default_value = 1.0 - d["smoothness"]
if d.get("emission"):
bsdf.inputs["Emission Color"].default_value = hex2lin(d["emission"]) + [1.0]
bsdf.inputs["Emission Strength"].default_value = 2.0
if d.get("transparent"):
bsdf.inputs["Alpha"].default_value = d.get("alpha", 0.5)
try:
m.surface_render_method = "BLENDED"
except Exception:
pass
tex = d.get("texture")
img = load_tex(tex) if tex else None
if img:
tn = nt.nodes.new("ShaderNodeTexImage")
tn.image = img
mp = nt.nodes.new("ShaderNodeMapping")
tc = nt.nodes.new("ShaderNodeTexCoord")
t = d["tiling"]
mp.inputs["Scale"].default_value = (t[0], t[1], 1)
nt.links.new(tc.outputs["UV"], mp.inputs["Vector"])
nt.links.new(mp.outputs["Vector"], tn.inputs["Vector"])
if d["color"].upper() != "#FFFFFF":
mix = nt.nodes.new("ShaderNodeMix")
mix.data_type = "RGBA"
mix.blend_type = "MULTIPLY"
mix.inputs["Factor"].default_value = 1.0
nt.links.new(tn.outputs["Color"], mix.inputs[6])
mix.inputs[7].default_value = col
nt.links.new(mix.outputs[2], bsdf.inputs["Base Color"])
else:
nt.links.new(tn.outputs["Color"], bsdf.inputs["Base Color"])
return m
def import_model(name):
"""Import the game FBX; slots get the game's materials (same names). Returns (meshes, empties)."""
before = set(bpy.data.objects)
bpy.ops.import_scene.fbx(filepath=os.path.join(MODELS_DIR, name + ".fbx"))
objs = [o for o in bpy.data.objects if o not in before]
for o in objs:
if o.type == "MESH" and o.data.users > 1:
o.data = o.data.copy()
imported = [m for m in bpy.data.materials]
for m in imported:
m.name = "__imp_" + m.name
built = {}
for o in objs:
if o.type != "MESH":
continue
for i, ms in enumerate(o.data.materials):
if ms is None:
continue
nb = base_name(ms.name[6:])
if nb not in built:
built[nb] = orig_material(nb)
o.data.materials[i] = built[nb]
for m in imported:
if m.users == 0:
bpy.data.materials.remove(m)
return objs
def tris_of(objs, evaluated=True):
dg = bpy.context.evaluated_depsgraph_get()
n = 0
for o in objs:
if o.type != "MESH":
continue
me = o.evaluated_get(dg).data if evaluated else o.data
n += sum(len(p.vertices) - 2 for p in me.polygons)
return n
def bbox(objs):
bpy.context.view_layer.update()
mn = Vector((1e9,) * 3)
mx = Vector((-1e9,) * 3)
for o in objs:
if o.type != "MESH":
continue
for c in o.bound_box:
w = o.matrix_world @ Vector(c)
mn = Vector(map(min, mn, w))
mx = Vector(map(max, mx, w))
return mn, mx
def apply_mods(o):
dg = bpy.context.evaluated_depsgraph_get()
me = bpy.data.meshes.new_from_object(o.evaluated_get(dg), preserve_all_data_layers=True, depsgraph=dg)
old = o.data
o.modifiers.clear()
o.data = me
me.name = old.name
if old.users == 0:
bpy.data.meshes.remove(old)
def clear_custom_normals(o):
me = o.data
try:
if "custom_normal" in me.attributes:
me.attributes.remove(me.attributes["custom_normal"])
return
except Exception:
pass
try:
with bpy.context.temp_override(object=o, active_object=o, selected_objects=[o], selected_editable_objects=[o]):
bpy.ops.mesh.customdata_custom_splitnormals_clear()
except Exception:
pass
def smooth_by_angle(o, ang=35):
me = o.data
for p in me.polygons:
p.use_smooth = True
try:
me.set_sharp_from_angle(angle=math.radians(ang))
except Exception:
pass
# ---------------------------------------------------------------- geometry polish
def panel_candidates(paint_objs, cat, diag, look):
"""Largest clear flat rectangular hard-surface quads across the model, world area order."""
if look["panels"] <= 0:
return {}
amin = max((0.10 * diag) ** 2, 0.012)
dg = bpy.context.evaluated_depsgraph_get()
sc = bpy.context.scene
cands = []
for o in paint_objs:
if o.name.startswith(NO_DETAIL_OBJ):
continue
mw = o.matrix_world
n3 = mw.to_3x3().inverted().transposed()
mats = [base_name(m.name) if m else "" for m in o.data.materials]
for p in o.data.polygons:
if p.loop_total != 4:
continue
mn = mats[p.material_index] if p.material_index < len(mats) else ""
if mn not in PANEL_MATS:
continue
if mn == "M_Pack" and cat not in PANEL_CATS_PACK:
continue
nw = (n3 @ p.normal).normalized()
if nw.z < -0.3:
continue
vs = [mw @ o.data.vertices[i].co for i in p.vertices]
area = ((vs[1] - vs[0]).cross(vs[3] - vs[0]).length + (vs[1] - vs[2]).cross(vs[3] - vs[2]).length) / 2
if area < amin:
continue
ok = True
lens = []
for k in range(4):
a, b, c = vs[k - 1], vs[k], vs[(k + 1) % 4]
e1, e2 = (a - b), (c - b)
lens.append(e2.length)
if e1.length < 1e-6 or e2.length < 1e-6 or abs(e1.normalized().dot(e2.normalized())) > 0.17:
ok = False
break
if abs((b - vs[0]).dot(nw)) > 0.002 * diag:
ok = False
break
if not ok or max(lens) / max(min(lens), 1e-6) > 4.5:
continue
ctr = sum(vs, Vector()) / 4
hit, loc, nrm, idx, ho, mx = sc.ray_cast(dg, ctr + nw * 0.002 * diag, nw, distance=0.06 * diag)
if hit:
continue
cands.append((area, o.name, p.index, mn))
cands.sort(reverse=True)
out = {}
for area, on, pi, mn in cands[:look["panels"]]:
out.setdefault(on, []).append((pi, area))
return out
def inset_panels(o, faces, diag):
"""Recess each face as a panel; returns rivet spots [(co, normal, mat_index, uv)] in object space."""
me = o.data
bm = bmesh.new()
bm.from_mesh(me)
bm.faces.ensure_lookup_table()
uvl = bm.loops.layers.uv[0] if bm.loops.layers.uv else None
spots = []
for f, area in [(bm.faces[pi], a) for pi, a in faces]:
if not f.is_valid or len(f.verts) != 4:
continue
side = math.sqrt(area)
t = min(max(0.06 * side, 0.004), 0.035)
d = 0.22 * t
outer = [v.co.copy() for v in f.verts]
uvc = None
if uvl:
us = [l[uvl].uv.copy() for l in f.loops]
uvc = sum(us, us[0] * 0) / len(us)
mi = f.material_index
r = bmesh.ops.inset_individual(bm, faces=[f], thickness=t, depth=-d, use_even_offset=True)
nrm = f.normal.copy()
inner = [v.co.copy() for v in f.verts]
ctr = sum(inner, Vector()) / 4
for oc in outer:
# frame corner: half way between the outer corner and the nearest inner corner
ic = min(inner, key=lambda q: (q - oc).length)
p = oc + (ic + nrm * d - oc) * 0.5
spots.append((p, nrm.copy(), mi, uvc, 0.3 * t))
bm.to_mesh(me)
bm.free()
return spots
def add_rivets(o, spots):
me = o.data
bm = bmesh.new()
bm.from_mesh(me)
uvl = bm.loops.layers.uv[0] if bm.loops.layers.uv else None
n = 0
for p, nrm, mi, uvc, r in spots:
tmp = bmesh.new()
bmesh.ops.create_uvsphere(tmp, u_segments=8, v_segments=4, radius=r)
for v in [v for v in tmp.verts if v.co.z < -1e-5]:
tmp.verts.remove(v)
for v in tmp.verts:
v.co.z = v.co.z * 0.55 - 0.15 * r
rot = nrm.to_track_quat("Z", "Y").to_matrix().to_4x4()
bmesh.ops.transform(tmp, matrix=Matrix.Translation(p) @ rot, verts=tmp.verts)
tme = bpy.data.meshes.new("tmp")
tmp.to_mesh(tme)
tmp.free()
before = set(bm.faces)
bm.from_mesh(tme)
bpy.data.meshes.remove(tme)
for f in bm.faces:
if f in before:
continue
f.material_index = mi
f.smooth = True
if uvl and uvc is not None:
for l in f.loops:
l[uvl].uv = uvc
n += 1
bm.to_mesh(me)
bm.free()
return n
def _set_bevel(o, cfg):
o.modifiers.clear()
if cfg is None:
return
cname, segs, ang, width = cfg
b = o.modifiers.new("rm_bevel", "BEVEL")
b.width = width
b.segments = segs
b.limit_method = "ANGLE"
b.angle_limit = math.radians(ang)
b.harden_normals = True
b.use_clamp_overlap = True
b.miter_outer = "MITER_ARC"
b.profile = 0.5
def _spiky(part, tree, kd, w):
"""True when the bevelled part has a vertex off its original surface or far from every original vertex."""
dg = bpy.context.evaluated_depsgraph_get()
me = part.evaluated_get(dg).data
for v in me.vertices:
if tree.find_nearest(v.co, 0.6 * w)[0] is None:
return True
if kd.find(v.co)[2] > 5.0 * w:
return True
return False
def _split_loose(o):
dup = o.copy()
dup.data = o.data.copy()
dup.parent = None
dup.matrix_world = o.matrix_world.copy()
dup.modifiers.clear()
bpy.context.scene.collection.objects.link(dup)
bpy.ops.object.select_all(action="DESELECT")
dup.select_set(True)
bpy.context.view_layer.objects.active = dup
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
try:
bpy.ops.mesh.separate(type="LOOSE")
except Exception:
pass
bpy.ops.object.mode_set(mode="OBJECT")
return [x for x in bpy.context.selected_objects]
def _join_back(o, parts):
bpy.ops.object.select_all(action="DESELECT")
for x in parts:
x.select_set(True)
bpy.context.view_layer.objects.active = parts[0]
if len(parts) > 1:
bpy.ops.object.join()
j = bpy.context.view_layer.objects.active
old = o.data
newme = j.data
j.data = old # keep the joined mesh alive while the helper object goes
bpy.data.objects.remove(j)
nm = old.name
o.data = newme
if old.users == 0:
bpy.data.meshes.remove(old)
newme.name = nm
def bevel_all(objs, diag, budget, notes):
"""Bevel by angle with harden normals, loose part by loose part: every part takes the strongest config that does
not blow it out (vertices must stay on the part's original surface and near its original vertices); the whole
model backs off a level until it fits the triangle budget. Parts are joined back into their object."""
from mathutils.bvhtree import BVHTree
from mathutils.kdtree import KDTree
w = min(max(0.0065 * diag, 0.0006), 0.022)
configs = [("2seg/48deg", 2, 48, w), ("1seg/48deg", 1, 48, w), ("1seg/65deg", 1, 65, w * 0.6)]
split = {}
table = [] # (part, [tris or None per config], orig tris)
for o in objs:
parts = _split_loose(o)
split[o.name] = parts
for pt in parts:
dg = bpy.context.evaluated_depsgraph_get()
tree = BVHTree.FromObject(pt, dg, deform=False)
me = pt.data
kd = KDTree(len(me.vertices))
for i, v in enumerate(me.vertices):
kd.insert(v.co, i)
kd.balance()
t0 = sum(len(p.vertices) - 2 for p in me.polygons)
res = []
for cfg in configs:
_set_bevel(pt, cfg)
res.append(None if _spiky(pt, tree, kd, w) else tris_of([pt]))
pt.modifiers.clear()
table.append((pt, res, t0, pt.dimensions.length))
blown = sum(1 for _, r, _, _ in table if all(x is None for x in r))
gentler = sum(1 for _, r, _, _ in table if r[0] is None and any(x is not None for x in r))
if blown:
notes.append("%d loose part(s) would blow out under any bevel: left unbevelled" % blown)
if gentler:
notes.append("%d loose part(s) took a gentler bevel" % gentler)
chosen = None
for level in range(len(configs)):
tot = 0
pick = []
for pt, r, t0, sz in table:
k = next((k for k in range(level, len(configs)) if r[k] is not None), None)
pick.append(k)
tot += t0 if k is None else r[k]
if tot <= budget:
chosen = (level, pick)
break
if chosen is None:
# gentlest clean bevel everywhere, then the smallest parts lose theirs until the model fits
pick = [max((k for k in range(len(configs)) if r[k] is not None), default=None) for _, r, _, _ in table]
tot = sum(t0 if k is None else r[k] for (_, r, t0, _), k in zip(table, pick))
dropped = 0
for i in sorted(range(len(table)), key=lambda i: table[i][3]):
if tot <= budget:
break
k = pick[i]
if k is None:
continue
tot -= table[i][1][k] - table[i][2]
pick[i] = None
dropped += 1
notes.append("budget: bevel left off the %d smallest of %d loose parts" % (dropped, len(table)))
chosen = (len(configs), pick)
used = set()
if chosen is not None:
for (pt, r, t0, sz), k in zip(table, chosen[1]):
if k is not None:
_set_bevel(pt, configs[k])
apply_mods(pt)
used.add(k)
for o in objs:
_join_back(o, split[o.name])
if chosen is None:
return "none (budget)"
return "/".join(configs[k][0] for k in sorted(used)) if used else "none"
def mesh_sane(objs):
bad = 0
for o in objs:
for v in o.data.vertices:
if any(math.isnan(c) or abs(c) > 1e5 for c in v.co):
bad += 1
return bad == 0
# ---------------------------------------------------------------- paint (bake)
def nodes_paint(nt, d, info, look, mode):
"""Build the emission tree. mode 'paint' or 'ms' (metallic, roughness)."""
N = nt.nodes
L = nt.links
for x in list(N):
N.remove(x)
out = N.new("ShaderNodeOutputMaterial")
em = N.new("ShaderNodeEmission")
L.new(em.outputs[0], out.inputs["Surface"])
timg = N.new("ShaderNodeTexImage")
timg.name = "BAKE_TARGET"
timg.image = info["img_ms"] if mode == "ms" else info["img"]
N.active = timg
timg.select = True
if mode == "ms":
met = d["metallic"]
em.inputs["Color"].default_value = (met, 1.0 - d["smoothness"], 0.0, 1.0)
return
if mode == "null":
em.inputs["Color"].default_value = (0, 0, 0, 1)
return
def mr(x, a, b, c, e, clamp=True):
n = N.new("ShaderNodeMapRange")
n.clamp = clamp
L.new(x, n.inputs[0])
n.inputs[1].default_value = a
n.inputs[2].default_value = b
n.inputs[3].default_value = c
n.inputs[4].default_value = e
return n.outputs[0]
def math_(op, a, b=None, clamp=False):
n = N.new("ShaderNodeMath")
n.operation = op
n.use_clamp = clamp
for i, v in enumerate((a, b)):
if v is None:
continue
if isinstance(v, (int, float)):
n.inputs[i].default_value = v
else:
L.new(v, n.inputs[i])
return n.outputs[0]
def mix(fac, a, b, blend="MIX"):
n = N.new("ShaderNodeMix")
n.data_type = "RGBA"
n.blend_type = blend
n.clamp_result = True
for sock, v in ((n.inputs[0], fac), (n.inputs[6], a), (n.inputs[7], b)):
if isinstance(v, (int, float)):
sock.default_value = v
elif isinstance(v, (tuple, list)):
sock.default_value = tuple(v) + ((1.0,) if len(v) == 3 else ())
else:
L.new(v, sock)
return n.outputs[2]
def noise(scale, detail=3.0, rough=0.55, vec=None, stretch=None):
n = N.new("ShaderNodeTexNoise")
n.inputs["Scale"].default_value = scale
n.inputs["Detail"].default_value = detail
n.inputs["Roughness"].default_value = rough
v = vec if vec is not None else geo.outputs["Position"]
if stretch:
mp = N.new("ShaderNodeMapping")
mp.inputs["Scale"].default_value = stretch
L.new(v, mp.inputs["Vector"])
v = mp.outputs[0]
L.new(v, n.inputs["Vector"])
return n.outputs["Fac"]
diag = info["diag"]
zmin, zmax = info["zmin"], info["zmax"]
geo = N.new("ShaderNodeNewGeometry")
# base colour
col = hex2lin(d["color"])
tex = d.get("texture")
img = load_tex(tex) if tex else None
if img:
uvn = N.new("ShaderNodeUVMap")
uvn.uv_map = "OrigUV"
mp = N.new("ShaderNodeMapping")
t = d["tiling"]
mp.inputs["Scale"].default_value = (t[0], t[1], 1)
L.new(uvn.outputs[0], mp.inputs["Vector"])
tn = N.new("ShaderNodeTexImage")
tn.image = img
tn.interpolation = "Closest" if base_name(d.get("name", "")) == "M_Pack" else "Linear"
L.new(mp.outputs[0], tn.inputs["Vector"])
basec = tn.outputs["Color"]
if d["color"].upper() != "#FFFFFF":
basec = mix(1.0, basec, col, "MULTIPLY")
else:
rgb = N.new("ShaderNodeRGB")
rgb.outputs[0].default_value = tuple(col) + (1.0,)
basec = rgb.outputs[0]
metal = d["metallic"] >= 0.5
nm = base_name(d.get("name", ""))
painted = nm.startswith("M_Paint") or nm in ("M_BarnRed", "M_HullWhite", "M_Pack", "M_Teal", "M_Navy", "M_Hazard")
wood = nm in ("M_Timber", "M_Deck", "M_DeckDark", "M_DeckWorn", "M_WoodDeck", "M_Bark")
if DEBUG.startswith("base"):
L.new(basec, em.inputs["Color"])
return
# soft top light and height gradient
sep = N.new("ShaderNodeSeparateXYZ")
L.new(geo.outputs["Normal"], sep.inputs[0])
top = mr(sep.outputs[2], -1.0, 1.0, 0.68, 1.13)
sepp = N.new("ShaderNodeSeparateXYZ")
L.new(geo.outputs["Position"], sepp.inputs[0])
hgt = mr(sepp.outputs[2], zmin, zmax, 0.86, 1.05)
shade = math_("MULTIPLY", top, hgt)
# hand-painted value wobble + warm/cool drift
nA = noise(2.2 / diag, 4.0, 0.6)
wob = mr(nA, 0.3, 0.7, 0.90, 1.10)
shade = math_("MULTIPLY", shade, wob)
sh = N.new("ShaderNodeCombineColor")
for i in range(3):
L.new(shade, sh.inputs[i])
c = mix(1.0, basec, sh.outputs[0], "MULTIPLY")
nB = noise(0.9 / diag, 2.0, 0.5)
c = mix(mr(nB, 0.4, 0.7, 0.0, 0.10), c, (0.95, 0.80, 0.62), "OVERLAY")
# brush strokes: stretched noise, tiny value steps
nS = noise(9.0 / diag, 1.0, 0.4, stretch=(1.0, 1.0, 6.0))
c = mix(mr(nS, 0.42, 0.78, 0.0, 0.14), c, (1, 1, 1), "SOFT_LIGHT")
nS2 = noise(16.0 / diag, 1.0, 0.4, stretch=(6.0, 1.0, 1.0))
c = mix(mr(nS2, 0.5, 0.8, 0.0, 0.06), c, (0, 0, 0), "SOFT_LIGHT")
# ambient occlusion: cool tinted crevices
ao = N.new("ShaderNodeAmbientOcclusion")
ao.samples = 16
ao.inputs["Distance"].default_value = info["ao_dist"]
aof = ao.outputs["AO"]
aom = mr(aof, 0.05, 0.95, 0.0, 1.0)
aom = math_("POWER", aom, 0.85)
shadow = mix(1.0, c, (0.36, 0.33, 0.50), "MULTIPLY")
c = mix(aom, shadow, c)
# tight crease AO: dark painted lines in the seams
ao2 = N.new("ShaderNodeAmbientOcclusion")
ao2.samples = 8
ao2.inputs["Distance"].default_value = info["edge_r"] * 2.5
crease = mr(ao2.outputs["AO"], 0.2, 0.85, 0.45, 1.0)
cr = N.new("ShaderNodeCombineColor")
for i in range(3):
L.new(crease, cr.inputs[i])
c = mix(1.0, c, cr.outputs[0], "MULTIPLY")
# convex edges: bevel normal vs true normal, only where open (AO high)
bev = N.new("ShaderNodeBevel")
bev.samples = 8
bev.inputs["Radius"].default_value = info["edge_r"]
dot = N.new("ShaderNodeVectorMath")
dot.operation = "DOT_PRODUCT"
L.new(bev.outputs[0], dot.inputs[0])
L.new(geo.outputs["Normal"], dot.inputs[1])
edge = mr(dot.outputs["Value"], 0.995, 0.86, 0.0, 1.0)
convex = mr(aof, 0.72, 0.93, 0.0, 1.0)
eh = math_("MULTIPLY", edge, convex, clamp=True)
hl = mix(1.0, c, (1.55, 1.5, 1.4), "MULTIPLY")
hl = mix(0.25, hl, (1.0, 0.97, 0.9), "SCREEN")
c = mix(math_("MULTIPLY", eh, 0.65), c, hl)
wear = look["wear"]
if wear > 0 and (metal or painted):
nW = noise(14.0 / diag, 5.0, 0.7)
chip = math_("MULTIPLY", eh, mr(nW, 0.55, 0.66, 0.0, 1.0), clamp=True)
if metal:
c = mix(math_("MULTIPLY", chip, 0.75 * wear), c, (0.92, 0.90, 0.84))
else:
c = mix(math_("MULTIPLY", chip, 0.22 * wear), c, hl)
if wear > 0 and metal:
# fine scratches: stretched noise bands, patchy
wv = N.new("ShaderNodeTexWave")
wv.inputs["Scale"].default_value = 26.0 / diag
wv.inputs["Distortion"].default_value = 9.0
wv.inputs["Detail"].default_value = 3.0
L.new(geo.outputs["Position"], wv.inputs["Vector"])
lines = mr(wv.outputs["Fac"], 0.90, 0.99, 0.0, 1.0)
patch = mr(noise(3.0 / diag, 2.0, 0.5), 0.5, 0.65, 0.0, 1.0)
scr = math_("MULTIPLY", lines, patch, clamp=True)
c = mix(math_("MULTIPLY", scr, 0.6 * wear), c, (0.95, 0.95, 0.92))
if wood:
# gentle sun-bleached tops on timber
c = mix(math_("MULTIPLY", mr(sep.outputs[2], 0.6, 1.0, 0.0, 1.0), 0.18), c, (0.95, 0.86, 0.70))
dirt = look["dirt"]
if dirt > 0:
h = max(zmax - zmin, 1e-3)
dh = min(max(0.28 * h, 0.06), 0.55) if not look.get("tool") else h
low = mr(sepp.outputs[2], zmin, zmin + dh, 1.0, 0.0)
low = math_("POWER", low, 1.4)
nD = noise(5.0 / diag, 6.0, 0.65)
dm = math_("MULTIPLY", low, mr(nD, 0.42, 0.62, 0.0, 1.0), clamp=True)
if look.get("tool"):
dm = math_("MULTIPLY", mr(nD, 0.55, 0.68, 0.0, 1.0), 1.0 if metal else 0.35)
c = mix(math_("MULTIPLY", dm, 0.55 * dirt), c, (0.20, 0.12, 0.055))
nG = noise(7.0 / diag, 4.0, 0.6, stretch=(1, 1, 3))
gm = math_("MULTIPLY", low if not look.get("tool") else mr(nG, 0, 1, 1, 1), mr(nG, 0.58, 0.72, 0.0, 1.0), clamp=True)
c = mix(math_("MULTIPLY", gm, 0.45 * dirt), c, (0.10, 0.30, 0.03))
hs = N.new("ShaderNodeHueSaturation")
hs.inputs["Saturation"].default_value = 1.08
L.new(c, hs.inputs["Color"])
L.new(hs.outputs[0], em.inputs["Color"])
em.inputs["Strength"].default_value = 1.0
def build_bake_mats(names, info, look, mode):
mats = {}
for n in names:
m = bpy.data.materials.new("BK_%s_%s" % (mode, n))
d = mdef(n)
d["name"] = n
nodes_paint(m.node_tree, d, info, look, "null" if (is_special(n) and mode == "paint") else mode)
mats[n] = m
return mats
def smart_uv(objs, margin):
bpy.ops.object.select_all(action="DESELECT")
for o in objs:
o.select_set(True)
bpy.context.view_layer.objects.active = objs[0]
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_mode(type="FACE")
bpy.ops.mesh.select_all(action="DESELECT")
for o in objs:
mats = [base_name(m.name) if m else "" for m in o.data.materials]
bm = bmesh.from_edit_mesh(o.data)
for f in bm.faces:
if not is_special(mats[f.material_index] if f.material_index < len(mats) else ""):
f.select_set(True)
bm.select_flush_mode()
bmesh.update_edit_mesh(o.data)
bpy.ops.uv.smart_project(angle_limit=math.radians(60), island_margin=margin * 0.5, area_weight=0.0,
correct_aspect=True, scale_to_bounds=False)
bpy.ops.object.mode_set(mode="OBJECT")
tree = world_bvh()
mn, mx = bbox(list(bpy.context.scene.objects))
reach = max((mx - mn).length * 0.4, 0.05)
for o in objs:
weight_islands(o, tree, reach)
bpy.ops.object.mode_set(mode="EDIT")
try:
bpy.ops.uv.select_all(action="SELECT")
except Exception:
pass
try:
bpy.ops.uv.pack_islands(udim_source="CLOSEST_UDIM", rotate=True, margin_method="FRACTION", margin=margin)
except TypeError:
bpy.ops.uv.pack_islands(rotate=True, margin=margin)
bpy.ops.object.mode_set(mode="OBJECT")
def face_weight(mn, nz):
"""Texel density weight: fine tiling textures get more room, flat colours less, undersides little."""
d = mdef(mn)
tex = d.get("texture")
w = 1.0 if mn == "M_Pack" else (1.5 if tex else 0.8)
if nz < -0.6:
w *= 0.4
return w
def world_bvh():
from mathutils.bvhtree import BVHTree
dg = bpy.context.evaluated_depsgraph_get()
verts, polys = [], []
for o in bpy.context.scene.objects:
if o.type != "MESH":
continue
me = o.evaluated_get(dg).data
mw = o.matrix_world
b = len(verts)
verts.extend(mw @ v.co for v in me.vertices)
polys.extend([b + i for i in p.vertices] for p in me.polygons)
return BVHTree.FromPolygons(verts, polys, epsilon=0.0)
def openness(tree, c, n, reach):
"""0..1: share of 7 hemisphere rays from the face that escape within reach (1 = in the open)."""
t1 = n.orthogonal().normalized()
t2 = n.cross(t1)
dirs = [n] + [(n * 0.55 + (t1 * math.cos(a) + t2 * math.sin(a)) * 0.85).normalized() for a in
[i * math.tau / 6 for i in range(6)]]
o = c + n * reach * 0.002
free = sum(1 for d in dirs if tree.ray_cast(o, d, reach)[0] is None)
return free / len(dirs)
def weight_islands(o, tree=None, reach=1.0):
"""Find the PaintUV islands (faces joined by edges whose UVs match) and scale each about its centre by its weight."""
me = o.data
mats = [base_name(m.name) if m else "" for m in me.materials]
n3 = o.matrix_world.to_3x3().inverted().transposed()
bm = bmesh.new()
bm.from_mesh(me)
uvl = bm.loops.layers.uv["PaintUV"]
bm.faces.ensure_lookup_table()
par = list(range(len(bm.faces)))
def find(i):
while par[i] != i:
par[i] = par[par[i]]
i = par[i]
return i
def special(f):
return is_special(mats[f.material_index] if f.material_index < len(mats) else "")
for e in bm.edges:
ls = e.link_loops
if len(ls) != 2:
continue
l1, l2 = ls
if special(l1.face) or special(l2.face):
continue
a1, b1 = l1[uvl].uv, l1.link_loop_next[uvl].uv
if l1.vert == l2.vert:
a2, b2 = l2[uvl].uv, l2.link_loop_next[uvl].uv
else:
a2, b2 = l2.link_loop_next[uvl].uv, l2[uvl].uv
if (a1 - a2).length < 1e-6 and (b1 - b2).length < 1e-6:
par[find(l1.face.index)] = find(l2.face.index)
groups = {}
for f in bm.faces:
if special(f):
continue
groups.setdefault(find(f.index), []).append(f)
for fs in groups.values():
tw = ta = 0.0
for f in fs:
a = max(f.calc_area(), 1e-9)
nz = (n3 @ f.normal).normalized().z
fw = face_weight(mats[f.material_index] if f.material_index < len(mats) else "", nz)
if tree is not None:
op = openness(tree, o.matrix_world @ f.calc_center_median(), (n3 @ f.normal).normalized(), reach)
fw *= 0.25 + 0.75 * min(1.0, op * 1.6)
tw += fw * a
ta += a
w = tw / max(ta, 1e-12)
if abs(w - 1.0) < 1e-3:
continue
us = [l[uvl].uv for f in fs for l in f.loops]
c = Vector(((min(u.x for u in us) + max(u.x for u in us)) / 2, (min(u.y for u in us) + max(u.y for u in us)) / 2))
for f in fs:
for l in f.loops:
l[uvl].uv = c + (l[uvl].uv - c) * w
bm.to_mesh(me)
bm.free()
def special_loops(o):
mats = [base_name(m.name) if m else "" for m in o.data.materials]
return [li for p in o.data.polygons if is_special(mats[p.material_index] if p.material_index < len(mats) else "")
for li in p.loop_indices]
# ---------------------------------------------------------------- preview
def make_camera(objs, elev=25, azim=-35, res=768):
sc = bpy.context.scene
mn, mx = bbox(objs)
ctr = (mn + mx) / 2
rad = (mx - mn).length / 2
d = rad / math.tan(math.radians(18)) * 1.05
el, az = math.radians(elev), math.radians(azim)
return dict(loc=ctr + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) * d,
ctr=ctr, d=d, zmin=mn.z, rad=rad, res=res)
def render(path, cam):
sc = bpy.context.scene
helpers = []
cd = bpy.data.cameras.new("PrevCam")
cd.lens = 50
co = bpy.data.objects.new("PrevCam", cd)
sc.collection.objects.link(co)
helpers.append(co)
co.location = cam["loc"]
co.rotation_euler = (cam["ctr"] - cam["loc"]).to_track_quat("-Z", "Y").to_euler()
cd.clip_start = cam["d"] * 0.01
cd.clip_end = cam["d"] * 6 + 100
sc.camera = co
for nm, en, rot, ang in (("Key", 3.2, (48, 8, -42), 10), ("Fill", 0.9, (62, 0, 125), 30), ("Rim", 1.8, (28, 0, 172), 6)):
ld = bpy.data.lights.new(nm, "SUN")
ld.energy = en
ld.angle = math.radians(ang)
lo = bpy.data.objects.new(nm, ld)
sc.collection.objects.link(lo)
lo.rotation_euler = [math.radians(a) for a in rot]
helpers.append(lo)
# soft ground
gm = bpy.data.meshes.new("PrevGround")
s = cam["rad"] * 30 + 5
z = cam["zmin"] - 0.001
gm.from_pydata([(-s, -s, z), (s, -s, z), (s, s, z), (-s, s, z)], [], [(0, 1, 2, 3)])
go = bpy.data.objects.new("PrevGround", gm)
sc.collection.objects.link(go)
helpers.append(go)
gmat = bpy.data.materials.new("PrevGroundMat")
bs = gmat.node_tree.nodes.get("Principled BSDF")
bs.inputs["Base Color"].default_value = (0.50, 0.52, 0.55, 1)
bs.inputs["Roughness"].default_value = 1.0
gm.materials.append(gmat)
w = bpy.data.worlds.get("PrevWorld") or bpy.data.worlds.new("PrevWorld")
sc.world = w
bg = w.node_tree.nodes.get("Background")
bg.inputs[0].default_value = (0.50, 0.53, 0.58, 1)
bg.inputs[1].default_value = 0.65
sc.render.engine = "BLENDER_EEVEE"
try:
sc.eevee.taa_render_samples = 48
except Exception:
pass
sc.render.resolution_x = sc.render.resolution_y = cam["res"]
sc.render.film_transparent = False
try:
sc.view_settings.view_transform = "AgX"
sc.view_settings.look = "AgX - Punchy"
except Exception:
pass
sc.render.image_settings.file_format = "PNG"
sc.render.filepath = path
bpy.ops.render.render(write_still=True)
for h in helpers:
d = h.data
bpy.data.objects.remove(h)
if isinstance(d, bpy.types.Mesh):
bpy.data.meshes.remove(d)
elif isinstance(d, bpy.types.Light):
bpy.data.lights.remove(d)
elif isinstance(d, bpy.types.Camera):
bpy.data.cameras.remove(d)
bpy.data.materials.remove(gmat)
def side_by_side(a, b, out):
ia = bpy.data.images.load(a)
ib = bpy.data.images.load(b)
w, h = ia.size
import numpy as np
pa = np.empty(w * h * 4, dtype=np.float32)
pb = np.empty(w * h * 4, dtype=np.float32)
ia.pixels.foreach_get(pa)
ib.pixels.foreach_get(pb)
pa = pa.reshape(h, w, 4)
pb = pb.reshape(h, w, 4)
gap = np.ones((h, 8, 4), dtype=np.float32)
gap[..., :3] = 0.15
pc = np.concatenate([pa, gap, pb], axis=1)
im = bpy.data.images.new("cmp", pc.shape[1], h, alpha=True)
im.pixels.foreach_set(pc.ravel())
im.filepath_raw = out
im.file_format = "PNG"
im.save()
for i in (ia, ib, im):
bpy.data.images.remove(i)
# ---------------------------------------------------------------- one model
def process(name, do_preview=True):
t0 = time.time()
st = {"name": name, "category": CAT_OF.get(name), "notes": []}
reset()
sc = bpy.context.scene
objs = import_model(name)
meshes = [o for o in objs if o.type == "MESH"]
st["tris_before"] = tris_of(meshes, evaluated=False)
st["objects"] = sorted(o.name for o in objs)
xf_before = {o.name: ([round(x, 5) for x in o.matrix_world.translation], o.parent.name if o.parent else None) for o in objs}
cat = CAT_OF.get(name, "Props")
look = CAT_LOOK[cat]
mn, mx = bbox(meshes)
diag = max((mx - mn).length, 0.02)
cam = make_camera(meshes)
if do_preview and name in COMPARE:
render(os.path.join(CMPOUT, name + "_before.png"), cam)
paint = []
for o in meshes:
if o.name in UNTOUCHED_OBJ:
continue
mats = [base_name(m.name) if m else "" for m in o.data.materials]
if not mats or all(is_special(m) for m in mats):
continue
paint.append(o)
st["untouched"] = sorted(o.name for o in meshes if o not in paint)
if not paint:
raise RuntimeError("nothing paintable")
# ~3x the original at most, big machines capped well under 30k; untouched objects count against it
budget = min(3 * st["tris_before"], 25000) - tris_of([o for o in meshes if o not in paint], evaluated=False)
budget_geo = budget
# 0. the original UVs under a fixed name before any geometry work (Unity reads the first set)
for o in paint:
me = o.data
if len(me.uv_layers) == 0:
me.uv_layers.new(name="OrigUV")
st["notes"].append("%s: had no UVs" % o.name)
me.uv_layers[0].name = "OrigUV"
for l in list(me.uv_layers)[1:]:
me.uv_layers.remove(l)
# 1. normals: keep the authored split normals (FBX custom normals); only meshes without any get smoothed by angle
for o in paint:
if not o.data.has_custom_normals:
smooth_by_angle(o, 40)
# 2. panels (inset before the bevel so the bevel rounds the panel lines)
bpy.context.view_layer.update()
cands = panel_candidates(paint, cat, diag, look) if ("nogeo" not in DEBUG and "nopanel" not in DEBUG) else {}
spots = {}
npan = 0
for o in paint:
if o.name in cands:
spots[o.name] = inset_panels(o, cands[o.name], diag)
npan += len(cands[o.name])
# 3. bevel (leave room for rivets)
nriv_want = sum(len(v) for v in spots.values())
cfg = bevel_all(paint, diag, budget_geo - min(nriv_want * 24, int(0.12 * budget)), st["notes"]) if "nogeo" not in DEBUG else "none (debug)"
st["bevel"] = cfg
if "bbox moved" in cfg:
st["notes"].append("bevel moved the bounds")
# 4. rivets, inside what is left of the budget
left = budget - tris_of(paint)
nriv = 0
for o in paint:
sp = spots.get(o.name, [])
if not sp:
continue
k = min(len(sp), max(0, left // 24))
if k <= 0:
continue
nriv += add_rivets(o, sp[:k])
left -= k * 24
st["panels"] = npan
st["rivets"] = nriv
if not mesh_sane(paint):
st["notes"].append("NaN vertices after polish")
# 5. UVs
for o in paint:
me = o.data
if "OrigUV" not in me.uv_layers:
me.uv_layers.new(name="OrigUV", do_init=False)
st["notes"].append("%s: original UVs lost in polish, slot colours only" % o.name)
for l in [l for l in me.uv_layers if l.name != "OrigUV"]:
me.uv_layers.remove(l)
pu = me.uv_layers.new(name="PaintUV", do_init=True)
me.uv_layers.active = pu
area = 0.0
for o in paint:
mats = [base_name(m.name) if m else "" for m in o.data.materials]
sc3 = o.matrix_world.to_3x3()
s = abs(sc3.determinant()) ** (2 / 3)
area += sum(p.area for p in o.data.polygons if not is_special(mats[p.material_index] if p.material_index < len(mats) else "")) * s
saved = {}
for o in paint:
me = o.data
lo = special_loops(o)
ouv = me.uv_layers["OrigUV"].data
puv = me.uv_layers["PaintUV"].data
saved[o.name] = [(li, ouv[li].uv.copy()) for li in lo]
for li in lo:
puv[li].uv = (-3.0, -3.0) # out of the way of the packer; a point bakes nothing
res = 2048 if (area > 5.0 or diag > 3.5 or st["tris_before"] > 9000) else 1024
st["texture"] = res
st["paint_area_m2"] = round(area, 2)
margin = 0.006 if res == 2048 else 0.009
smart_uv(paint, margin)
# 6. bake
img = bpy.data.images.new("T_%s_Paint" % short(name), res, res, alpha=False)
img.colorspace_settings.name = "sRGB"
img_ms = bpy.data.images.new("T_%s_MS" % short(name), res // 2, res // 2, alpha=False)
img_ms.colorspace_settings.name = "Non-Color"
info = dict(img=img, img_ms=img_ms, diag=diag, zmin=mn.z, zmax=mx.z,
ao_dist=min(max(0.06 * diag, 0.025), 0.45),
edge_r=min(max(0.0045 * diag, 0.0015), 0.012))
slotnames = sorted({base_name(m.name) for o in paint for m in o.data.materials if m})
orig_slots = {o.name: [m for m in o.data.materials] for o in paint}
dev = gpu(sc)
st["device"] = dev
sc.cycles.samples = 64
sc.cycles.use_denoising = False
sc.render.bake.margin = 16
sc.render.bake.margin_type = "EXTEND"
sc.render.bake.use_clear = True
sc.render.bake.target = "IMAGE_TEXTURES"
bpy.ops.object.select_all(action="DESELECT")
for o in paint:
o.select_set(True)
bpy.context.view_layer.objects.active = paint[0]
tb = time.time()
for mode, target, samples, mg in (("paint", img, 64, 16), ("ms", img_ms, 1, 8)):
bk = build_bake_mats(slotnames, info, look, mode)
for o in paint:
for i, m in enumerate(orig_slots[o.name]):
if m:
o.data.materials[i] = bk[base_name(m.name)]
sc.cycles.samples = samples
sc.render.bake.margin = mg
bpy.ops.object.bake(type="EMIT", margin=mg, use_clear=True)
for m in bk.values():
bpy.data.materials.remove(m)
st["bake_s"] = round(time.time() - tb, 1)
for o in paint:
for i, m in enumerate(orig_slots[o.name]):
o.data.materials[i] = m
os.makedirs(TEXOUT, exist_ok=True)
for im in (img, img_ms):
im.filepath_raw = os.path.join(TEXOUT, im.name + ".png")
im.file_format = "PNG"
im.save()
im.filepath = os.path.join(TEXOUT, im.name + ".png")
im.source = "FILE"
im.reload()
# 7. final material + UVs + slots
pm = bpy.data.materials.new("M_Paint_%s" % short(name))
nt = pm.node_tree
bs = nt.nodes.get("Principled BSDF")
ti = nt.nodes.new("ShaderNodeTexImage")
ti.image = img
ti.location = (-600, 200)
tm = nt.nodes.new("ShaderNodeTexImage")
tm.image = img_ms
tm.location = (-600, -150)
sp = nt.nodes.new("ShaderNodeSeparateColor")
sp.location = (-300, -150)
nt.links.new(ti.outputs["Color"], bs.inputs["Base Color"])
nt.links.new(tm.outputs["Color"], sp.inputs[0])
nt.links.new(sp.outputs[0], bs.inputs["Metallic"])
nt.links.new(sp.outputs[1], bs.inputs["Roughness"])
for o in paint:
me = o.data
puv = me.uv_layers["PaintUV"].data
for li, uv in saved[o.name]:
puv[li].uv = uv
me.uv_layers.remove(me.uv_layers["OrigUV"])
me.uv_layers["PaintUV"].name = "UVMap"
old = [m for m in me.materials]
newl = []
remap = []
for m in old:
tgt = m if (m is not None and is_special(m.name)) else pm
if tgt not in newl:
newl.append(tgt)
remap.append(newl.index(tgt))
idx = [0] * len(me.polygons)
me.polygons.foreach_get("material_index", idx)
idx = [remap[i] if i < len(remap) else 0 for i in idx]
me.materials.clear()
for m in newl:
me.materials.append(m)
me.polygons.foreach_set("material_index", idx)
me.update()
for m in list(bpy.data.materials):
if m.users == 0:
bpy.data.materials.remove(m)
st["tris_after"] = tris_of(meshes, evaluated=False)
# contract check
for o in objs:
t, p = xf_before[o.name]
if [round(x, 5) for x in o.matrix_world.translation] != t or (o.parent.name if o.parent else None) != p:
st["notes"].append("transform changed: " + o.name)
# 8. outputs
os.makedirs(FBXOUT, exist_ok=True)
for o in sc.objects:
o.select_set(o.type in ("MESH", "EMPTY"))
bpy.ops.export_scene.fbx(filepath=os.path.join(FBXOUT, name + ".fbx"), use_selection=True, axis_forward="-Z", axis_up="Y",
apply_scale_options="FBX_SCALE_ALL", bake_space_transform=False,
use_mesh_modifiers=True, mesh_smooth_type="FACE", add_leaf_bones=False,
object_types={"MESH", "EMPTY"}, path_mode="STRIP", use_custom_props=False)
sc.render.engine = "BLENDER_EEVEE"
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, name + ".blend"), check_existing=False, relative_remap=True,
compress=True)
if do_preview:
render(os.path.join(PREVOUT, name + ".png"), cam)
if name in COMPARE:
render(os.path.join(CMPOUT, name + "_after.png"), cam)
side_by_side(os.path.join(CMPOUT, name + "_before.png"), os.path.join(CMPOUT, name + "_after.png"),
os.path.join(CMPOUT, name + "_before_after.png"))
st["seconds"] = round(time.time() - t0, 1)
return st
def main():
args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
force = "--force" in args
nopv = "--nopreview" in args
names = [a for a in args if not a.startswith("--")] or ALL
for d in (OUT, TEXOUT, FBXOUT, PREVOUT, CMPOUT, STATS):
os.makedirs(d, exist_ok=True)
for n in names:
sp = os.path.join(STATS, n + ".json")
if os.path.exists(sp) and not force:
log("skip (done)", n)
continue
if not os.path.exists(os.path.join(MODELS_DIR, n + ".fbx")):
log("missing", n)
continue
if n in SKIP:
with open(sp, "w") as f:
json.dump({"name": n, "category": CAT_OF.get(n), "skipped": SKIP[n]}, f, indent=1)
log("skipped", n, SKIP[n])
continue
log("start", n)
try:
st = process(n, do_preview=not nopv)
with open(sp, "w") as f:
json.dump(st, f, indent=1)
log("done", n, "tris %d -> %d" % (st["tris_before"], st["tris_after"]), st["bevel"], "%.0fs" % st["seconds"])
except Exception:
traceback.print_exc()
with open(os.path.join(STATS, n + ".error.txt"), "w") as f:
f.write(traceback.format_exc())
log("FAILED", n)
if __name__ == "__main__":
main()