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>
This commit is contained in:
433
ArtSource/Blender/remaster/crew/scripts/crew_assemble.py
Normal file
433
ArtSource/Blender/remaster/crew/scripts/crew_assemble.py
Normal file
@ -0,0 +1,433 @@
|
||||
"""GRASS CUTTER crew remaster, stage 3: puts it together. From <scratch>/<name>_stage1.blend (crew_rebake.py) and the
|
||||
repainted map (crew_repaint.py):
|
||||
ArtSource/Blender/remaster/crew/<SM>.blend the game model with the new map (old skin kept hidden in Originals)
|
||||
ArtSource/Blender/remaster/crew/fbx/<SM>.fbx same rig/weights/parts, new UVs on the skin (export as os_crew)
|
||||
ArtSource/Blender/remaster/crew/previews/<SM>_{front,34,back}.png, <SM>_compare.png (before/after), <SM>_maps.png
|
||||
and checks the new FBX against the game's: names, parents, transforms, bones, vertices and weights must all match.
|
||||
Run:
|
||||
blender -b --factory-startup --python crew_assemble.py --python-exit-code 1 -- <scratch dir> [hank lin ...]
|
||||
"""
|
||||
import sys, os, math
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BASE = os.path.normpath(os.path.join(HERE, ".."))
|
||||
ROOT = os.path.normpath(os.path.join(BASE, "..", "..", "..", ".."))
|
||||
import bpy
|
||||
import numpy as np
|
||||
from mathutils import Vector, Matrix
|
||||
|
||||
CREW = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji")
|
||||
DIRECTOR = ("boss", "assistant")
|
||||
GAME_TEX = os.path.join(ROOT, "Assets", "Art", "Textures")
|
||||
GAME_MODELS = os.path.join(ROOT, "Assets", "Art", "Models")
|
||||
RES = (600, 800)
|
||||
|
||||
|
||||
def sm_name(n):
|
||||
return ("SM_Dir_" if n in DIRECTOR else "SM_Crew_") + n.capitalize()
|
||||
|
||||
|
||||
def body_of(n):
|
||||
return bpy.data.objects["DirBody" if n in DIRECTOR else "CrewBody"]
|
||||
|
||||
|
||||
def relink_images():
|
||||
"""The FBX points its maps at Assets/Art/Models; they live in Assets/Art/Textures."""
|
||||
for im in bpy.data.images:
|
||||
if im.source != "FILE":
|
||||
continue
|
||||
fn = os.path.basename(im.filepath)
|
||||
p = os.path.join(GAME_TEX, fn)
|
||||
if os.path.exists(p):
|
||||
im.filepath = p
|
||||
im.reload()
|
||||
|
||||
|
||||
def tex_node(m):
|
||||
return next((n for n in m.node_tree.nodes if n.type == "TEX_IMAGE"), None)
|
||||
|
||||
|
||||
def soften_materials():
|
||||
for m in bpy.data.materials:
|
||||
if not m.node_tree:
|
||||
continue
|
||||
b = next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
|
||||
if b:
|
||||
b.inputs["Roughness"].default_value = 0.75
|
||||
if "Specular IOR Level" in b.inputs:
|
||||
b.inputs["Specular IOR Level"].default_value = 0.25
|
||||
b.inputs["Metallic"].default_value = 0.0 if m.name != "M_Brass" else 0.6
|
||||
|
||||
|
||||
def set_texture(m, path, uv):
|
||||
n = tex_node(m)
|
||||
if n is None:
|
||||
n = m.node_tree.nodes.new("ShaderNodeTexImage")
|
||||
b = next(x for x in m.node_tree.nodes if x.type == "BSDF_PRINCIPLED")
|
||||
m.node_tree.links.new(n.outputs["Color"], b.inputs["Base Color"])
|
||||
n.image = bpy.data.images.load(path, check_existing=True)
|
||||
n.interpolation = "Linear"
|
||||
uvn = next((x for x in m.node_tree.nodes if x.type == "UVMAP"), None)
|
||||
if uvn is None:
|
||||
uvn = m.node_tree.nodes.new("ShaderNodeUVMap")
|
||||
m.node_tree.links.new(uvn.outputs["UV"], n.inputs["Vector"])
|
||||
uvn.uv_map = uv
|
||||
|
||||
|
||||
def stage(scene_objs):
|
||||
"""Soft studio light and a world, shared by the previews."""
|
||||
sc = bpy.context.scene
|
||||
sc.render.engine = "BLENDER_EEVEE"
|
||||
sc.render.resolution_x, sc.render.resolution_y = RES
|
||||
sc.render.film_transparent = False
|
||||
sc.view_settings.view_transform = "Standard"
|
||||
sc.view_settings.look = "None"
|
||||
w = bpy.data.worlds.get("Studio") or bpy.data.worlds.new("Studio")
|
||||
sc.world = w
|
||||
w.use_nodes = True
|
||||
bg = w.node_tree.nodes["Background"]
|
||||
bg.inputs[0].default_value = (0.62, 0.68, 0.72, 1)
|
||||
bg.inputs[1].default_value = 0.9
|
||||
for nm, kind, en, rot, size in (("Key", "SUN", 2.6, (52, 8, -38), 18), ("Rim", "SUN", 1.4, (35, 0, 160), 10)):
|
||||
if nm in bpy.data.objects:
|
||||
continue
|
||||
ld = bpy.data.lights.new(nm, kind)
|
||||
ld.energy = en
|
||||
ld.angle = math.radians(size)
|
||||
lo = bpy.data.objects.new(nm, ld)
|
||||
sc.collection.objects.link(lo)
|
||||
lo.rotation_euler = [math.radians(a) for a in rot]
|
||||
if "Fill" not in bpy.data.objects:
|
||||
ld = bpy.data.lights.new("Fill", "AREA")
|
||||
ld.energy = 120
|
||||
ld.size = 3
|
||||
lo = bpy.data.objects.new("Fill", ld)
|
||||
sc.collection.objects.link(lo)
|
||||
lo.location = (-2.5, -2.5, 1.6)
|
||||
lo.rotation_euler = (Vector((0, 0, 0.7)) - lo.location).to_track_quat("-Z", "Y").to_euler()
|
||||
|
||||
|
||||
def bounds(objs):
|
||||
mn, mx = Vector((1e9,) * 3), Vector((-1e9,) * 3)
|
||||
for o in objs:
|
||||
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 camera(objs):
|
||||
sc = bpy.context.scene
|
||||
cam = bpy.data.objects.get("PreviewCam")
|
||||
if cam is None:
|
||||
cd = bpy.data.cameras.new("PreviewCam")
|
||||
cd.type = "ORTHO"
|
||||
cam = bpy.data.objects.new("PreviewCam", cd)
|
||||
sc.collection.objects.link(cam)
|
||||
mn, mx = bounds(objs)
|
||||
cam.data.ortho_scale = (mx.z - mn.z) * 1.1 # the taller side of the frame
|
||||
sc.camera = cam
|
||||
return cam, (mn + mx) / 2
|
||||
|
||||
|
||||
def aim(cam, ctr, az, el=8):
|
||||
a, e = math.radians(az), math.radians(el)
|
||||
cam.location = ctr + Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e))) * 6
|
||||
cam.rotation_euler = (ctr - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
cam.data.clip_end = 20
|
||||
|
||||
|
||||
VIEWS = (("front", 0), ("34", -35), ("back", 180))
|
||||
CLOSE = (("head", -20), ("legs", 25)) # close-ups in the comparison: the face and the trousers
|
||||
|
||||
|
||||
def render(path):
|
||||
bpy.context.scene.render.filepath = path
|
||||
bpy.ops.render.render(write_still=True)
|
||||
|
||||
|
||||
def read_png(path):
|
||||
im = bpy.data.images.load(path)
|
||||
w, h = im.size
|
||||
px = np.zeros(w * h * 4, np.float32)
|
||||
im.pixels.foreach_get(px)
|
||||
bpy.data.images.remove(im)
|
||||
return px.reshape(h, w, 4)
|
||||
|
||||
|
||||
def write_png(arr, path):
|
||||
h, w = arr.shape[:2]
|
||||
im = bpy.data.images.new("out", w, h, alpha=True)
|
||||
im.pixels.foreach_set(arr.astype(np.float32).ravel())
|
||||
im.filepath_raw = path
|
||||
im.file_format = "PNG"
|
||||
im.save()
|
||||
bpy.data.images.remove(im)
|
||||
|
||||
|
||||
def label(text, cam, at):
|
||||
cu = bpy.data.curves.new("lbl", "FONT")
|
||||
cu.body = text
|
||||
cu.size = cam.data.ortho_scale * 0.06
|
||||
cu.align_x = "LEFT"
|
||||
o = bpy.data.objects.new("lbl_" + text, cu)
|
||||
bpy.context.scene.collection.objects.link(o)
|
||||
m = bpy.data.materials.new("lbl")
|
||||
m.use_nodes = True
|
||||
e = m.node_tree.nodes.new("ShaderNodeEmission")
|
||||
e.inputs[0].default_value = (0.02, 0.02, 0.03, 1)
|
||||
m.node_tree.links.new(e.outputs[0], m.node_tree.nodes["Material Output"].inputs[0])
|
||||
o.data.materials.append(m)
|
||||
o.parent = cam
|
||||
o.location = (-cam.data.ortho_scale * 0.5 * RES[0] / RES[1] + cam.data.ortho_scale * 0.03,
|
||||
cam.data.ortho_scale * 0.5 - cam.data.ortho_scale * 0.09, -1)
|
||||
return o
|
||||
|
||||
|
||||
def build(name, scratch):
|
||||
sm = sm_name(name)
|
||||
bpy.ops.wm.open_mainfile(filepath=os.path.join(scratch, name + "_stage1.blend"))
|
||||
sc = bpy.context.scene
|
||||
relink_images()
|
||||
soften_materials()
|
||||
body = body_of(name)
|
||||
rig = next(o for o in sc.objects if o.type == "ARMATURE")
|
||||
mat = next(m for m in body.data.materials if m.name.startswith("M_Crew_"))
|
||||
old_tex = os.path.join(GAME_TEX, "T_Crew_" + name.capitalize() + ".png")
|
||||
new_tex = os.path.join(BASE, "textures", "T_Crew_" + name.capitalize() + ".png")
|
||||
# the game's own skin (kept by crew_rebake before any change: its positions, weights and map), hidden in Originals
|
||||
old = bpy.data.objects[body.name + "_Old"]
|
||||
om = mat.copy()
|
||||
om.name = mat.name + "_Old"
|
||||
set_texture(om, old_tex, "UVMap")
|
||||
old.data.materials[[m.name for m in old.data.materials].index(mat.name)] = om
|
||||
col = bpy.data.collections.new("Originals")
|
||||
sc.collection.children.link(col)
|
||||
for c_ in list(old.users_collection):
|
||||
c_.objects.unlink(old)
|
||||
col.objects.link(old)
|
||||
old.data.uv_layers["UVMap"].active_render = True
|
||||
# the new skin
|
||||
body.data.uv_layers.remove(body.data.uv_layers["UVOld"])
|
||||
body.data.uv_layers["UVMap"].active_render = True
|
||||
set_texture(mat, new_tex, "UVMap")
|
||||
# export, exactly as os_crew.export_rigged, without the old copy
|
||||
fbx = os.path.join(BASE, "fbx", sm + ".fbx")
|
||||
for o in sc.objects:
|
||||
o.select_set(o.type in ("MESH", "EMPTY", "ARMATURE") and o is not old)
|
||||
old.hide_set(False)
|
||||
bpy.ops.export_scene.fbx(filepath=fbx, use_selection=True, axis_forward="-Z", axis_up="Y",
|
||||
apply_scale_options="FBX_SCALE_ALL", bake_space_transform=False,
|
||||
use_mesh_modifiers=False, mesh_smooth_type="FACE", add_leaf_bones=False,
|
||||
object_types={"MESH", "EMPTY", "ARMATURE"}, use_armature_deform_only=False,
|
||||
armature_nodetype="NULL", primary_bone_axis="Y", secondary_bone_axis="X",
|
||||
bake_anim=False, path_mode="STRIP", use_custom_props=False)
|
||||
# previews
|
||||
stage(sc.objects)
|
||||
figure = [o for o in sc.objects if o.type == "MESH" and o is not old]
|
||||
cam, ctr = camera(figure)
|
||||
prv = os.path.join(BASE, "previews")
|
||||
os.makedirs(prv, exist_ok=True)
|
||||
old.hide_render = True
|
||||
for tag, az in VIEWS:
|
||||
aim(cam, ctr, az)
|
||||
render(os.path.join(prv, f"{sm}_{tag}.png"))
|
||||
# before / after: the same views with the old skin in place of the new
|
||||
tiles = {}
|
||||
mn, mx = bounds(figure)
|
||||
full = cam.data.ortho_scale
|
||||
shots = [(t, a, None) for t, a in VIEWS] + [(t, a, z) for (t, a), z in zip(CLOSE, ("head", "legs"))]
|
||||
for state in ("before", "after"):
|
||||
old.hide_render = state == "after"
|
||||
body.hide_render = state == "before"
|
||||
for tag, az, zoom in shots:
|
||||
if zoom == "head":
|
||||
cam.data.ortho_scale = (mx.z - mn.z) * 0.42
|
||||
aim(cam, Vector((ctr.x, ctr.y, mx.z - (mx.z - mn.z) * 0.2)), az)
|
||||
elif zoom == "legs":
|
||||
cam.data.ortho_scale = (mx.z - mn.z) * 0.5
|
||||
aim(cam, Vector((ctr.x, ctr.y, mn.z + (mx.z - mn.z) * 0.3)), az)
|
||||
else:
|
||||
cam.data.ortho_scale = full
|
||||
aim(cam, ctr, az)
|
||||
lb = label("BEFORE" if state == "before" else "AFTER", cam, None)
|
||||
p = os.path.join(scratch, f"{name}_{state}_{tag}.png")
|
||||
render(p)
|
||||
tiles[state, tag] = read_png(p)
|
||||
bpy.data.objects.remove(lb)
|
||||
cam.data.ortho_scale = full
|
||||
old.hide_render = False
|
||||
body.hide_render = False
|
||||
rows = [np.concatenate([tiles[s, t] for t, _, _ in shots], 1) for s in ("after", "before")] # images run bottom-up
|
||||
write_png(np.concatenate(rows, 0), os.path.join(prv, f"{sm}_compare.png"))
|
||||
closeups(name, sm, scratch, body, old, rig, cam)
|
||||
# the maps side by side (old | new), half size
|
||||
a = read_png(old_tex)[::2, ::2]
|
||||
b = read_png(new_tex)[::2, ::2]
|
||||
write_png(np.concatenate([a, np.ones((a.shape[0], 16, 4), np.float32), b], 1), os.path.join(prv, f"{sm}_maps.png"))
|
||||
# the blend: Material Preview in every 3D view, old skin hidden
|
||||
old.hide_set(True)
|
||||
old.hide_render = True
|
||||
col.hide_render = True
|
||||
lc = bpy.context.view_layer.layer_collection.children["Originals"]
|
||||
lc.hide_viewport = True
|
||||
for scr in bpy.data.screens:
|
||||
for area in scr.areas:
|
||||
if area.type == "VIEW_3D":
|
||||
for sp in area.spaces:
|
||||
if sp.type == "VIEW_3D":
|
||||
sp.shading.type = "MATERIAL"
|
||||
for im in bpy.data.images:
|
||||
if im.filepath and not im.packed_file:
|
||||
pass
|
||||
path = os.path.join(BASE, sm + ".blend")
|
||||
bpy.ops.wm.save_as_mainfile(filepath=path, check_existing=False, relative_remap=True)
|
||||
bpy.ops.file.make_paths_relative()
|
||||
bpy.ops.wm.save_mainfile()
|
||||
return fbx
|
||||
|
||||
|
||||
def closeups(name, sm, scratch, body, old, rig, cam):
|
||||
"""previews/arms/<SM>_arms.png and previews/faces/<SM>_face.png: before (top) and after (bottom), clay and painted."""
|
||||
sc = bpy.context.scene
|
||||
keep_res = (sc.render.resolution_x, sc.render.resolution_y)
|
||||
sc.render.resolution_x = sc.render.resolution_y = 600
|
||||
clay = bpy.data.materials.get("Clay") or bpy.data.materials.new("Clay")
|
||||
clay.use_nodes = True
|
||||
b = clay.node_tree.nodes["Principled BSDF"]
|
||||
b.inputs["Base Color"].default_value = (0.33, 0.33, 0.35, 1)
|
||||
b.inputs["Roughness"].default_value = 0.55
|
||||
vl = bpy.context.view_layer
|
||||
eyes = [o for o in sc.objects if o.name.startswith("EyeBall_")]
|
||||
anchor = [o for o in sc.objects if o.name.startswith("Anchor_Eye_")]
|
||||
if eyes or anchor:
|
||||
ez = sum((o.matrix_world.translation.z for o in (eyes or anchor))) / len(eyes or anchor)
|
||||
else:
|
||||
ez = rig.data.bones["Head"].head_local.z + 0.17
|
||||
sets = {
|
||||
"arms": [("clay", 0, Vector((0, 0, 0.64)), 0.78), ("clay", 90, Vector((0.2, 0, 0.64)), 0.62),
|
||||
("paint", -30, Vector((0.1, 0, 0.64)), 0.7)],
|
||||
"faces": [("clay", 0, Vector((0, 0, ez - 0.09)), 0.5), ("clay", -35, Vector((0, 0, ez - 0.09)), 0.5),
|
||||
("paint", -35, Vector((0, 0, ez - 0.09)), 0.5)],
|
||||
}
|
||||
for kind, shots in sets.items():
|
||||
rows = []
|
||||
for state in ("after", "before"):
|
||||
old.hide_render = state == "after"
|
||||
body.hide_render = state == "before"
|
||||
tiles = []
|
||||
for i, (look, az, at, scale) in enumerate(shots):
|
||||
vl.material_override = clay if look == "clay" else None
|
||||
cam.data.ortho_scale = scale
|
||||
aim(cam, at, az, el=6)
|
||||
lb = label("BEFORE" if state == "before" else "AFTER", cam, None)
|
||||
lb.location = (-scale * 0.47, scale * 0.41, -1)
|
||||
p = os.path.join(scratch, f"{name}_{kind}_{state}_{i}.png")
|
||||
render(p)
|
||||
tiles.append(read_png(p))
|
||||
bpy.data.objects.remove(lb)
|
||||
rows.append(np.concatenate(tiles, 1))
|
||||
vl.material_override = None
|
||||
d = os.path.join(BASE, "previews", kind)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
write_png(np.concatenate(rows, 0), os.path.join(d, f"{sm}_{'arms' if kind == 'arms' else 'face'}.png"))
|
||||
old.hide_render = False
|
||||
body.hide_render = False
|
||||
sc.render.resolution_x, sc.render.resolution_y = keep_res
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the check
|
||||
|
||||
def snapshot(path):
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
bpy.ops.import_scene.fbx(filepath=path)
|
||||
S = {}
|
||||
for o in bpy.context.scene.objects:
|
||||
e = dict(type=o.type, parent=o.parent.name if o.parent else None, ptype=o.parent_type, pbone=o.parent_bone,
|
||||
mw=np.array(o.matrix_world))
|
||||
if o.type == "MESH":
|
||||
me = o.data
|
||||
co = np.zeros(len(me.vertices) * 3)
|
||||
me.vertices.foreach_get("co", co)
|
||||
e["co"] = co.reshape(-1, 3)
|
||||
e["polys"] = len(me.polygons)
|
||||
e["mats"] = [m.name for m in me.materials]
|
||||
e["uvs"] = [u.name for u in me.uv_layers]
|
||||
gn = [g.name for g in o.vertex_groups]
|
||||
e["groups"] = gn
|
||||
W = np.zeros((len(me.vertices), max(1, len(gn))))
|
||||
for v in me.vertices:
|
||||
for g in v.groups:
|
||||
W[v.index, g.group] = g.weight
|
||||
e["w"] = W
|
||||
if o.type == "ARMATURE":
|
||||
e["bones"] = {b.name: (np.array(b.matrix_local), b.parent.name if b.parent else None) for b in o.data.bones}
|
||||
S[o.name] = e
|
||||
return S
|
||||
|
||||
|
||||
def check(name, fbx, scratch):
|
||||
A = snapshot(os.path.join(GAME_MODELS, sm_name(name) + ".fbx"))
|
||||
B = snapshot(fbx)
|
||||
bad = []
|
||||
# the skin vertices the shape fixes were allowed to move or re-weight (crew_rebake: arms, shoulders, lower face)
|
||||
edited = np.load(os.path.join(scratch, name + "_maps.npz"))["edited"]
|
||||
skin = "DirBody" if name in DIRECTOR else "CrewBody"
|
||||
note = ""
|
||||
if set(A) != set(B):
|
||||
bad.append(f"objects differ: {set(A) ^ set(B)}")
|
||||
for k in set(A) & set(B):
|
||||
a, b = A[k], B[k]
|
||||
for f in ("type", "parent", "ptype", "pbone"):
|
||||
if a[f] != b[f]:
|
||||
bad.append(f"{k}.{f}: {a[f]} vs {b[f]}")
|
||||
dm = np.abs(a["mw"] - b["mw"]).max()
|
||||
if dm > 1e-4:
|
||||
bad.append(f"{k} transform differs by {dm:.2e}")
|
||||
if a["type"] == "MESH":
|
||||
if a["co"].shape != b["co"].shape or a["polys"] != b["polys"]:
|
||||
bad.append(f"{k} topology {a['co'].shape}/{a['polys']} vs {b['co'].shape}/{b['polys']}")
|
||||
else:
|
||||
free = edited if (k == skin and len(edited) == len(a["co"])) else np.full(len(a["co"]), k.split(".")[0] == "Vest")
|
||||
dv = np.abs(a["co"] - b["co"])[~free].max(initial=0)
|
||||
if dv > 1e-5:
|
||||
bad.append(f"{k} vertices outside the edited arms/face move by {dv:.2e}")
|
||||
if free.any():
|
||||
mv = np.linalg.norm(a["co"] - b["co"], axis=1)[free]
|
||||
note += f" {k}: {int(free.sum())} arm/face vertices edited (moved up to {mv.max() * 100:.1f} cm, mean {mv.mean() * 1000:.1f} mm);"
|
||||
if a["mats"] != b["mats"]:
|
||||
bad.append(f"{k} materials {a['mats']} vs {b['mats']}")
|
||||
if a["groups"] != b["groups"]:
|
||||
bad.append(f"{k} groups {a['groups']} vs {b['groups']}")
|
||||
elif a["w"].shape == b["w"].shape:
|
||||
free = edited if (k == skin and len(edited) == len(a["w"])) else np.zeros(len(a["w"]), bool)
|
||||
dw = np.abs(a["w"] - b["w"])[~free].max(initial=0)
|
||||
if dw > 2e-4:
|
||||
bad.append(f"{k} weights outside the edited arms differ by {dw:.2e}")
|
||||
tot = b["w"].sum(1)
|
||||
if k == skin and np.abs(tot - 1).max() > 0.01:
|
||||
bad.append(f"{k} new weights do not sum to 1 ({tot.min():.3f}..{tot.max():.3f})")
|
||||
if a["type"] == "ARMATURE":
|
||||
if set(a["bones"]) != set(b["bones"]):
|
||||
bad.append(f"bones differ {set(a['bones']) ^ set(b['bones'])}")
|
||||
for bn in set(a["bones"]) & set(b["bones"]):
|
||||
d = np.abs(a["bones"][bn][0] - b["bones"][bn][0]).max()
|
||||
if d > 1e-4 or a["bones"][bn][1] != b["bones"][bn][1]:
|
||||
bad.append(f"bone {bn} differs by {d:.2e} / parent {a['bones'][bn][1]} vs {b['bones'][bn][1]}")
|
||||
print(f" CHECK {sm_name(name)}: {len(A)} objects;", "same names, parents, bones, part transforms, vertex counts; "
|
||||
"everything outside the edited skin identical." + note if not bad else "PROBLEMS:", flush=True)
|
||||
for x in bad:
|
||||
print(" ", x, flush=True)
|
||||
return not bad
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv[sys.argv.index("--") + 1:]
|
||||
scratch = args[0]
|
||||
ok = True
|
||||
for nm in (args[1:] or CREW + DIRECTOR):
|
||||
print(f"=== {nm}", flush=True)
|
||||
fbx = build(nm, scratch)
|
||||
ok &= check(nm, fbx, scratch)
|
||||
if not ok:
|
||||
sys.exit(1)
|
||||
837
ArtSource/Blender/remaster/crew/scripts/crew_rebake.py
Normal file
837
ArtSource/Blender/remaster/crew/scripts/crew_rebake.py
Normal file
@ -0,0 +1,837 @@
|
||||
"""GRASS CUTTER crew remaster, stage 1: a clean unwrap and a clean colour carry onto the game's own crew meshes.
|
||||
|
||||
The game's SM_Crew_<Name>.fbx (and SM_Dir_Boss / SM_Dir_Assistant) are imported as they are: rig, weights, part names and
|
||||
vertex positions are kept untouched. Only the body skin (CrewBody / DirBody) gets a new UV map:
|
||||
* smart-project charts, their saw-tooth edges smoothed and their crumbs merged into neighbours, then each chart opened
|
||||
out by minimum stretch along those seams, self-overlapping charts split in two, the head given more texels, and
|
||||
everything packed with a real margin (no strips of hundreds of fragments);
|
||||
The colour is then carried from the Tripo source shell (ArtSource/Crew/<name>.glb or ArtSource/Director/<name>.glb):
|
||||
* the arms are swung back up into the T-pose by inverting gc_tripo_crew.lower_arms with the mesh's own Arm/Fore weights,
|
||||
so every texel has its exact place on the source;
|
||||
* each texel looks along its own normal for the nearest FRONT-facing source surface within a few millimetres (never a
|
||||
neighbouring part, never extrapolated past its triangle's edge), and reads the source map at the nearest texel that is
|
||||
inside the source triangle (no bilinear pick-up of the source's own gutters);
|
||||
* the old eyes/brows are painted out as before (gc_crew_face.repaint).
|
||||
An ambient-occlusion map of the skin in its rest pose is baked as well, for stage 2 (crew_repaint.py).
|
||||
Output: <scratch>/<name>_stage1.blend and <scratch>/<name>_maps.npz.
|
||||
Run:
|
||||
blender -b --factory-startup --python crew_rebake.py --python-exit-code 1 -- <scratch dir> [hank lin ...]
|
||||
"""
|
||||
import sys, os, math, time
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.normpath(os.path.join(HERE, "..", "..", "..", "..", ".."))
|
||||
sys.path.insert(0, os.path.join(ROOT, "ArtSource", "Blender", "scripts"))
|
||||
sys.path.insert(0, HERE)
|
||||
import bpy, bmesh
|
||||
import numpy as np
|
||||
from mathutils import Vector, Matrix
|
||||
from mathutils.bvhtree import BVHTree
|
||||
import gc_tripo_crew as TC
|
||||
import gc_crew_face as FACE
|
||||
import common
|
||||
|
||||
CREW = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji")
|
||||
DIRECTOR = ("boss", "assistant")
|
||||
MAP = 2048
|
||||
ANGLE = 66 # smart-project angle limit
|
||||
MIN_FACES = 60 # charts smaller than this are merged into a neighbour
|
||||
HEAD_GAIN = 1.3 # linear texel-density gain for the head charts
|
||||
MARGIN = 0.0075 # pack margin (fraction of the map): ~15 px between charts
|
||||
EDGE_PX = 1.25 # texels up to this far outside a triangle still take its (edge-clamped) colour
|
||||
OUTER = 0.004 # source units a visible face may lie outside the game skin
|
||||
SEARCH = 0.012 # how far (source units) outside and inside the skin the source surface is looked for
|
||||
|
||||
|
||||
def sm_name(n):
|
||||
return ("SM_Dir_" if n in DIRECTOR else "SM_Crew_") + n.capitalize()
|
||||
|
||||
|
||||
def body_name(n):
|
||||
return "DirBody" if n in DIRECTOR else "CrewBody"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the source
|
||||
|
||||
def load_source(name):
|
||||
"""The carved source shell exactly as gc_tripo_crew / gc_director made it (before the remesh), and F, J."""
|
||||
if name in DIRECTOR:
|
||||
import gc_director as GD
|
||||
TC.SOURCE = os.path.join(ROOT, "ArtSource", "Director")
|
||||
o = TC.load(name)
|
||||
F = None
|
||||
if name in GD.MOVING_EYES:
|
||||
FACE._photo = GD._windowed(name)
|
||||
F = FACE.measure(o)
|
||||
FACE._photo = GD._photo
|
||||
kept = GD.keep_glasses(o, name)
|
||||
FACE.carve(o, F)
|
||||
for i, c in kept.items():
|
||||
o.data.vertices[i].co = c
|
||||
else:
|
||||
TC.SOURCE = os.path.join(ROOT, "ArtSource", "Crew")
|
||||
o = TC.load(name)
|
||||
F = FACE.measure(o)
|
||||
FACE.carve(o, F)
|
||||
bm = bmesh.new()
|
||||
bm.from_mesh(o.data)
|
||||
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)
|
||||
bm.to_mesh(o.data)
|
||||
bm.free()
|
||||
o.name = "Source"
|
||||
J = TC.measure(o)
|
||||
return o, F, J
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the game mesh
|
||||
|
||||
def import_game(name):
|
||||
path = os.path.join(ROOT, "Assets", "Art", "Models", sm_name(name) + ".fbx")
|
||||
before = set(bpy.data.objects)
|
||||
bpy.ops.import_scene.fbx(filepath=path)
|
||||
new = [o for o in bpy.data.objects if o not in before]
|
||||
body = next(o for o in new if o.type == "MESH" and o.name.startswith(body_name(name)))
|
||||
rig = next(o for o in new if o.type == "ARMATURE")
|
||||
return body, rig, new
|
||||
|
||||
|
||||
def tpose(body, rig, J):
|
||||
"""Source-unit T-pose position of every vertex of the game skin: lower_arms undone, the scale k taken off."""
|
||||
me = body.data
|
||||
n = len(me.vertices)
|
||||
co = np.zeros(n * 3, np.float32)
|
||||
me.vertices.foreach_get("co", co)
|
||||
co = co.reshape(-1, 3).astype(np.float64)
|
||||
co = (np.array(body.matrix_world) @ np.c_[co, np.ones(n)].T).T[:, :3]
|
||||
k_j = TC.SHOULDER / J["arm_z"]
|
||||
piv = {s: np.array(rig.matrix_world @ rig.data.bones["Arm_" + s].head_local) for s in "LR"}
|
||||
k = piv["L"][0] / 0.135
|
||||
print(f" k from the source {k_j:.4f}, from the rig {k:.4f}", flush=True)
|
||||
gi = {g.name: g.index for g in body.vertex_groups}
|
||||
w = {s: np.zeros(n) for s in "LR"}
|
||||
for v in me.vertices:
|
||||
for g in v.groups:
|
||||
for s in "LR":
|
||||
if g.group in (gi.get("Arm_" + s), gi.get("Fore_" + s)):
|
||||
w[s][v.index] += g.weight
|
||||
out = co.copy()
|
||||
for s, sx in (("L", 1), ("R", -1)):
|
||||
R = np.array(Matrix.Rotation(math.radians(sx * TC.HANG), 3, "Y"))
|
||||
m = w[s] > 1e-6
|
||||
for i in np.nonzero(m)[0]:
|
||||
M = (1 - w[s][i]) * np.eye(3) + w[s][i] * R
|
||||
out[i] = piv[s] + np.linalg.solve(M, co[i] - piv[s])
|
||||
return out / k, k, co, {s: piv[s] / k for s in "LR"}
|
||||
|
||||
|
||||
def normals_of(me, co):
|
||||
"""Vertex normals of me's faces laid on the positions co."""
|
||||
tmp = bpy.data.meshes.new("tmp")
|
||||
tmp.from_pydata([tuple(c) for c in co], [], [tuple(p.vertices) for p in me.polygons])
|
||||
tmp.update()
|
||||
nr = np.zeros(len(co) * 3, np.float32)
|
||||
tmp.vertex_normals.foreach_get("vector", nr)
|
||||
bpy.data.meshes.remove(tmp)
|
||||
return nr.reshape(-1, 3).astype(np.float64)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the unwrap
|
||||
|
||||
def uv_islands(bm, uvl, faces):
|
||||
"""Face -> island id, by shared edges whose two UV corners match on both sides."""
|
||||
lab, cur = {}, 0
|
||||
fs = set(faces)
|
||||
for f0 in faces:
|
||||
if f0 in lab:
|
||||
continue
|
||||
lab[f0] = cur
|
||||
st = [f0]
|
||||
while st:
|
||||
f = st.pop()
|
||||
for l in f.loops:
|
||||
e = l.edge
|
||||
for l2 in e.link_loops:
|
||||
g = l2.face
|
||||
if g is f or g in lab or g not in fs:
|
||||
continue
|
||||
# l: v0->v1 in f; l2 runs the other way in g
|
||||
a0, a1 = l[uvl].uv, l.link_loop_next[uvl].uv
|
||||
b0, b1 = l2.link_loop_next[uvl].uv, l2[uvl].uv
|
||||
if (a0 - b0).length < 1e-6 and (a1 - b1).length < 1e-6:
|
||||
lab[g] = cur
|
||||
st.append(g)
|
||||
cur += 1
|
||||
return lab
|
||||
|
||||
|
||||
def nbrs(f, fs):
|
||||
out = []
|
||||
for e in f.edges:
|
||||
for g in e.link_faces:
|
||||
if g is not f and g in fs:
|
||||
out.append(g)
|
||||
return out
|
||||
|
||||
|
||||
def tidy(lab, faces):
|
||||
"""Smooths chart borders (a face goes with two of its three neighbours) and merges crumbs into the neighbour they
|
||||
share most border with."""
|
||||
fs = set(faces)
|
||||
# every face against the faces round its corners: a face whose ring mostly belongs to another chart goes with it,
|
||||
# which files the saw teeth of the voxel skin off the chart borders
|
||||
ring = {f: [g for v in f.verts for g in v.link_faces if g is not f and g in fs] for f in faces}
|
||||
for _ in range(25):
|
||||
ch = 0
|
||||
for f in faces:
|
||||
nb = ring[f]
|
||||
if not nb:
|
||||
continue
|
||||
cnt = {}
|
||||
for g in nb:
|
||||
cnt[lab[g]] = cnt.get(lab[g], 0) + 1
|
||||
L = max(cnt, key=cnt.get)
|
||||
if L != lab[f] and cnt[L] > 0.5 * len(nb) and cnt[L] > cnt.get(lab[f], 0):
|
||||
lab[f] = L
|
||||
ch += 1
|
||||
if not ch:
|
||||
break
|
||||
frozen = set()
|
||||
for _ in range(400):
|
||||
members = {}
|
||||
for f in faces:
|
||||
members.setdefault(lab[f], []).append(f)
|
||||
small = sorted((len(m), L) for L, m in members.items() if len(m) < MIN_FACES and L not in frozen)
|
||||
if not small:
|
||||
break
|
||||
touched = set()
|
||||
for _s, L in small:
|
||||
if L in touched:
|
||||
continue
|
||||
border = {}
|
||||
for f in members[L]:
|
||||
for g in nbrs(f, fs):
|
||||
if lab[g] != L:
|
||||
border[lab[g]] = border.get(lab[g], 0) + 1
|
||||
if not border:
|
||||
frozen.add(L) # an isolated piece: kept as it is
|
||||
continue
|
||||
to = max(border, key=border.get)
|
||||
for f in members[L]:
|
||||
lab[f] = to
|
||||
members[to] = members.get(to, []) + members[L]
|
||||
touched.update((L, to))
|
||||
# charts must be connected pieces: split any that are not
|
||||
out, nid = {}, 0
|
||||
for f0 in faces:
|
||||
if f0 in out:
|
||||
continue
|
||||
out[f0] = nid
|
||||
st = [f0]
|
||||
while st:
|
||||
f = st.pop()
|
||||
for g in nbrs(f, fs):
|
||||
if g not in out and lab[g] == lab[f0]:
|
||||
out[g] = nid
|
||||
st.append(g)
|
||||
nid += 1
|
||||
return out
|
||||
|
||||
|
||||
def seams_from(bm, lab, void):
|
||||
for e in bm.edges:
|
||||
lf = e.link_faces
|
||||
e.seam = False
|
||||
if len(lf) != 2:
|
||||
continue
|
||||
a, b = lf
|
||||
if (a in void) != (b in void) or (a not in void and lab[a] != lab[b]):
|
||||
e.seam = True
|
||||
|
||||
|
||||
def raster(tri_uv, size, cb, edge_px=0.0):
|
||||
"""Calls cb(t, gy, gx, b(n,3), d) for every triangle with the texels it covers (d: signed px distance inside)."""
|
||||
for t in range(len(tri_uv)):
|
||||
u = tri_uv[t] * size - 0.5
|
||||
x0, y0 = np.floor(u.min(0) - edge_px).astype(int)
|
||||
x1, y1 = np.ceil(u.max(0) + edge_px).astype(int) + 1
|
||||
x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, size), min(y1, size)
|
||||
if x0 >= x1 or y0 >= y1:
|
||||
continue
|
||||
e0, e1 = u[1] - u[0], u[2] - u[0]
|
||||
det = e0[0] * e1[1] - e0[1] * e1[0]
|
||||
if abs(det) < 1e-12:
|
||||
continue
|
||||
gx, gy = np.meshgrid(np.arange(x0, x1), np.arange(y0, y1))
|
||||
dx, dy = gx - u[0, 0], gy - u[0, 1]
|
||||
b1 = (dx * e1[1] - dy * e1[0]) / det
|
||||
b2 = (dy * e0[0] - dx * e0[1]) / det
|
||||
b0 = 1 - b1 - b2
|
||||
# altitudes in px: distance of a texel inside each edge = b_i * h_i
|
||||
L = [np.linalg.norm(u[2] - u[1]), np.linalg.norm(u[2] - u[0]), np.linalg.norm(u[1] - u[0])]
|
||||
A = abs(det)
|
||||
h = [A / max(l, 1e-9) for l in L]
|
||||
d = np.minimum(np.minimum(b0 * h[0], b1 * h[1]), b2 * h[2])
|
||||
ok = d > -edge_px
|
||||
if not ok.any():
|
||||
continue
|
||||
b = np.stack([b0[ok], b1[ok], b2[ok]], 1)
|
||||
cb(t, gy[ok], gx[ok], b, d[ok])
|
||||
|
||||
|
||||
def tri_data(me, uvname):
|
||||
me.calc_loop_triangles()
|
||||
tris = me.loop_triangles
|
||||
n = len(tris)
|
||||
tl = np.zeros(n * 3, np.int32)
|
||||
tris.foreach_get("loops", tl)
|
||||
tv = np.zeros(n * 3, np.int32)
|
||||
tris.foreach_get("vertices", tv)
|
||||
tp = np.zeros(n, np.int32)
|
||||
tris.foreach_get("polygon_index", tp)
|
||||
luv = np.zeros(len(me.loops) * 2, np.float32)
|
||||
me.uv_layers[uvname].data.foreach_get("uv", luv)
|
||||
luv = luv.reshape(-1, 2).astype(np.float64)
|
||||
return tl.reshape(-1, 3), tv.reshape(-1, 3), tp, luv
|
||||
|
||||
|
||||
def overlapping(me, void_idx, size=1024):
|
||||
"""Polygon indices that share texels with another triangle (inside both)."""
|
||||
tl, tv, tp, luv = tri_data(me, "UVMap")
|
||||
mi = np.zeros(len(me.polygons), np.int32)
|
||||
me.polygons.foreach_get("material_index", mi)
|
||||
keep = mi[tp] != void_idx
|
||||
cnt = np.zeros((size, size), np.int32)
|
||||
owner = np.full((size, size), -1, np.int32)
|
||||
bad = set()
|
||||
tri_uv = luv[tl]
|
||||
|
||||
def cb(t, gy, gx, b, d):
|
||||
if not keep[t]:
|
||||
return
|
||||
m = d > 0.35
|
||||
gy, gx = gy[m], gx[m]
|
||||
cnt[gy, gx] += 1
|
||||
raster(tri_uv, size, cb)
|
||||
|
||||
def cb2(t, gy, gx, b, d):
|
||||
if not keep[t]:
|
||||
return
|
||||
m = d > 0.35
|
||||
if (cnt[gy[m], gx[m]] > 1).any():
|
||||
bad.add(int(tp[t]))
|
||||
raster(tri_uv, size, cb2)
|
||||
return bad
|
||||
|
||||
|
||||
def unwrap(body, void_idx, head_w):
|
||||
me = body.data
|
||||
old = me.uv_layers.active
|
||||
old.name = "UVOld"
|
||||
me.uv_layers.new(name="UVMap")
|
||||
me.uv_layers.active = me.uv_layers["UVMap"]
|
||||
for x in bpy.context.scene.objects:
|
||||
x.select_set(False)
|
||||
body.select_set(True)
|
||||
bpy.context.view_layer.objects.active = body
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
bpy.ops.mesh.select_mode(type="FACE")
|
||||
bm = bmesh.from_edit_mesh(me)
|
||||
bm.faces.ensure_lookup_table()
|
||||
void = {f for f in bm.faces if f.material_index == void_idx}
|
||||
for f in bm.faces:
|
||||
f.select_set(f not in void)
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.uv.smart_project(angle_limit=math.radians(ANGLE), island_margin=0.0, area_weight=0.0, scale_to_bounds=False)
|
||||
bm = bmesh.from_edit_mesh(me)
|
||||
bm.faces.ensure_lookup_table()
|
||||
uvl = bm.loops.layers.uv["UVMap"]
|
||||
faces = [f for f in bm.faces if f not in void]
|
||||
lab0 = uv_islands(bm, uvl, faces)
|
||||
lab = tidy(dict(lab0), faces)
|
||||
print(f" charts: smart project {len(set(lab0.values()))} -> tidied {len(set(lab.values()))}", flush=True)
|
||||
seams_from(bm, lab, void)
|
||||
bmesh.update_edit_mesh(me)
|
||||
|
||||
def open_out():
|
||||
bpy.ops.mesh.select_all(action="DESELECT")
|
||||
bm_ = bmesh.from_edit_mesh(me)
|
||||
for f in bm_.faces:
|
||||
f.select_set(f.material_index != void_idx)
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.uv.select_all(action="SELECT")
|
||||
bpy.ops.uv.unwrap(method="MINIMUM_STRETCH", margin=0.0)
|
||||
bm_ = bmesh.from_edit_mesh(me)
|
||||
uvl_ = bm_.loops.layers.uv["UVMap"]
|
||||
# charts the solver folded or squeezed (faces with next to no room on the map: every texel of such a face
|
||||
# takes one colour, a blotch): opened again by angles, then conformally if that squeezes them too
|
||||
for method in ("ANGLE_BASED", "CONFORMAL"):
|
||||
flat = _collapsed(bm_, uvl_, void_idx)
|
||||
if not flat:
|
||||
break
|
||||
bpy.ops.mesh.select_all(action="DESELECT")
|
||||
for f in flat:
|
||||
f.select_set(True)
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.mesh.select_linked(delimit={"SEAM"})
|
||||
bpy.ops.uv.select_all(action="SELECT")
|
||||
bpy.ops.uv.unwrap(method=method, margin=0.0)
|
||||
print(f" squeezed faces re-opened ({method.lower()}):", len(flat), flush=True)
|
||||
bm_ = bmesh.from_edit_mesh(me)
|
||||
uvl_ = bm_.loops.layers.uv["UVMap"]
|
||||
flat = _collapsed(bm_, uvl_, void_idx)
|
||||
if flat:
|
||||
fs_ = [f for f in bm_.faces if f.material_index != void_idx and f.calc_area() > 1e-9]
|
||||
ratio = float(np.median([abs(_uv_area(f, uvl_)) / f.calc_area() for f in fs_]))
|
||||
isl_ = uv_islands(bm_, uvl_, fs_)
|
||||
for L in {isl_[f] for f in flat}:
|
||||
_flatten(bm_, uvl_, [f for f, l in isl_.items() if l == L], ratio)
|
||||
bmesh.update_edit_mesh(me)
|
||||
print(" squeezed faces laid flat:", len(flat), flush=True)
|
||||
bpy.ops.mesh.select_all(action="DESELECT")
|
||||
bm_ = bmesh.from_edit_mesh(me)
|
||||
for f in bm_.faces:
|
||||
f.select_set(f.material_index != void_idx)
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.uv.select_all(action="SELECT")
|
||||
bpy.ops.uv.average_islands_scale()
|
||||
# the head gets more texels
|
||||
bm_ = bmesh.from_edit_mesh(me)
|
||||
uvl_ = bm_.loops.layers.uv["UVMap"]
|
||||
isl = uv_islands(bm_, uvl_, [f for f in bm_.faces if f.material_index != void_idx])
|
||||
groups = {}
|
||||
for f, L in isl.items():
|
||||
groups.setdefault(L, []).append(f)
|
||||
boosted = 0
|
||||
for L, fs in groups.items():
|
||||
hw = np.mean([head_w[v.index] for f in fs for v in f.verts])
|
||||
if hw > 0.5:
|
||||
c = sum((l[uvl_].uv for f in fs for l in f.loops), Vector((0, 0))) / sum(len(f.loops) for f in fs)
|
||||
done = set()
|
||||
for f in fs:
|
||||
for l in f.loops:
|
||||
if l.index in done:
|
||||
continue
|
||||
done.add(l.index)
|
||||
l[uvl_].uv = c + (l[uvl_].uv - c) * HEAD_GAIN
|
||||
boosted += 1
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.uv.select_all(action="SELECT")
|
||||
bpy.ops.uv.pack_islands(rotate=True, scale=True, margin_method="FRACTION", margin=MARGIN, shape_method="CONCAVE")
|
||||
return len(groups), boosted
|
||||
|
||||
n, boosted = open_out()
|
||||
print(f" {n} charts opened out, {boosted} of them head", flush=True)
|
||||
# charts that lie on themselves: cut in two across their longest extent, and the whole map opened and packed again
|
||||
for it in range(6):
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
bad = overlapping(me, void_idx)
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
print(f" pass {it}: faces lying on others: {len(bad)}", flush=True)
|
||||
if not bad:
|
||||
break
|
||||
bm = bmesh.from_edit_mesh(me)
|
||||
bm.faces.ensure_lookup_table()
|
||||
uvl = bm.loops.layers.uv["UVMap"]
|
||||
isl = uv_islands(bm, uvl, [f for f in bm.faces if f.material_index != void_idx])
|
||||
hit = {isl[bm.faces[i]] for i in bad if bm.faces[i] in isl}
|
||||
for L in hit:
|
||||
fs = [f for f, l in isl.items() if l == L]
|
||||
P = np.array([tuple(f.calc_center_median()) for f in fs])
|
||||
c = P.mean(0)
|
||||
_, _, vt = np.linalg.svd(P - c, full_matrices=False)
|
||||
ax = vt[0]
|
||||
side = {f: (np.dot(np.array(tuple(f.calc_center_median())) - c, ax) > 0) for f in fs}
|
||||
for f in fs:
|
||||
for e in f.edges:
|
||||
lf = [g for g in e.link_faces if g in side]
|
||||
if len(lf) == 2 and side[lf[0]] != side[lf[1]]:
|
||||
e.seam = True
|
||||
bmesh.update_edit_mesh(me)
|
||||
n, boosted = open_out()
|
||||
print(f" split {len(hit)} charts -> {n}", flush=True)
|
||||
# the mouth's void faces: one point in the corner
|
||||
bm = bmesh.from_edit_mesh(me)
|
||||
uvl = bm.loops.layers.uv["UVMap"]
|
||||
left = _collapsed(bm, uvl, void_idx)
|
||||
if left:
|
||||
# what no chart-wide solve opens: those faces cut out as charts of their own, at the map's texel density,
|
||||
# and the whole map packed again
|
||||
fs_ = [f for f in bm.faces if f.material_index != void_idx and f.calc_area() > 1e-9 and f not in set(left)]
|
||||
ratio = float(np.median([abs(_uv_area(f, uvl)) / f.calc_area() for f in fs_]))
|
||||
# each face laid out flat on its own plane, exactly its shape, at the map's density: a chart of its own
|
||||
for f in left:
|
||||
P = np.array([tuple(v.co) for v in f.verts])
|
||||
c3 = P.mean(0)
|
||||
nrm = np.array(tuple(f.normal))
|
||||
ax = P[1] - P[0]
|
||||
ax = ax - nrm * (ax @ nrm)
|
||||
ax /= max(np.linalg.norm(ax), 1e-12)
|
||||
ay = np.cross(nrm, ax)
|
||||
q = (P - c3) @ np.stack([ax, ay], 1) * np.sqrt(ratio)
|
||||
base = sum((l[uvl].uv for l in f.loops), Vector((0, 0))) / len(f.loops)
|
||||
for l, qq in zip(f.loops, q):
|
||||
l[uvl].uv = Vector((base[0] + qq[0] + 1e-4, base[1] + qq[1] + 1e-4))
|
||||
groups = left
|
||||
bmesh.update_edit_mesh(me)
|
||||
print(f" before packing: {len(_collapsed(bm, uvl, void_idx))} squeezed", flush=True)
|
||||
bpy.ops.mesh.select_all(action="DESELECT")
|
||||
for f in bm.faces:
|
||||
f.select_set(f.material_index != void_idx)
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.uv.select_all(action="SELECT")
|
||||
bpy.ops.uv.pack_islands(rotate=True, scale=True, margin_method="FRACTION", margin=MARGIN, shape_method="CONCAVE")
|
||||
bm = bmesh.from_edit_mesh(me)
|
||||
uvl = bm.loops.layers.uv["UVMap"]
|
||||
print(f" squeezed faces cut out as charts of their own: {len(left)} in {len(groups)} charts", flush=True)
|
||||
left = _collapsed(bm, uvl, void_idx)
|
||||
for f in left[:6]:
|
||||
print(f" left: {len(f.verts)}-gon, area {f.calc_area() * 1e4:.3f} cm2, map area {_uv_area(f, uvl):.2e}", flush=True)
|
||||
print(f" squeezed faces left: {len(left)} ({sum(f.calc_area() for f in left) * 1e4:.1f} cm2 source)", flush=True)
|
||||
for f in bm.faces:
|
||||
if f.material_index == void_idx:
|
||||
for l in f.loops:
|
||||
l[uvl].uv = (0.0005, 0.0005)
|
||||
bmesh.update_edit_mesh(me)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
|
||||
|
||||
def _collapsed(bm, uvl, void_idx, frac=0.08):
|
||||
"""Faces whose map area is under frac of their chart's usual map area per unit of surface."""
|
||||
fs = [f for f in bm.faces if f.material_index != void_idx and f.calc_area() > 1e-9]
|
||||
isl = uv_islands(bm, uvl, fs)
|
||||
r = {f: abs(_uv_area(f, uvl)) / f.calc_area() for f in fs}
|
||||
by = {}
|
||||
for f, L in isl.items():
|
||||
by.setdefault(L, []).append(r[f])
|
||||
med = {L: float(np.median(v)) for L, v in by.items()}
|
||||
# a chart squeezed as a whole (to a line or a point) has no usual area of its own: the map's is used
|
||||
glob_ = float(np.median(list(r.values())))
|
||||
return [f for f in fs if r[f] < frac * max(med[isl[f]], 0.25 * glob_)]
|
||||
|
||||
|
||||
def _flatten(bm, uvl, faces, ratio):
|
||||
"""Last resort for a chart no solver opens: its faces projected flat onto their best-fit plane, at the map's
|
||||
usual size, next to where they were."""
|
||||
vs = list({v for f in faces for v in f.verts})
|
||||
P = np.array([tuple(v.co) for v in vs])
|
||||
c = P.mean(0)
|
||||
_, _, vt = np.linalg.svd(P - c, full_matrices=False)
|
||||
q = (P - c) @ vt[:2].T * np.sqrt(ratio)
|
||||
at = {v: q[i] for i, v in enumerate(vs)}
|
||||
base = np.mean([tuple(l[uvl].uv) for f in faces for l in f.loops], 0)
|
||||
for f in faces:
|
||||
for l in f.loops:
|
||||
l[uvl].uv = Vector((base[0] + at[l.vert][0], base[1] + at[l.vert][1]))
|
||||
|
||||
|
||||
def _uv_area(f, uvl):
|
||||
p = [l[uvl].uv for l in f.loops]
|
||||
a = 0.0
|
||||
for i in range(1, len(p) - 1):
|
||||
a += (p[i].x - p[0].x) * (p[i + 1].y - p[0].y) - (p[i].y - p[0].y) * (p[i + 1].x - p[0].x)
|
||||
return a / 2
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the colour
|
||||
|
||||
def carry(name, body, src, T, NT, game_co, void_idx, arm_v=None, J=None):
|
||||
me = body.data
|
||||
tl, tv, tp, luv = tri_data(me, "UVMap")
|
||||
mi = np.zeros(len(me.polygons), np.int32)
|
||||
me.polygons.foreach_get("material_index", mi)
|
||||
NG = normals_of(me, game_co)
|
||||
pos = np.zeros((MAP, MAP, 3), np.float32)
|
||||
nor = np.zeros((MAP, MAP, 3), np.float32)
|
||||
ngm = np.zeros((MAP, MAP, 3), np.float32)
|
||||
gpos = np.zeros((MAP, MAP, 3), np.float32)
|
||||
best = np.full((MAP, MAP), -1e9, np.float32)
|
||||
inside = np.zeros((MAP, MAP), bool)
|
||||
tri = np.full((MAP, MAP), -1, np.int32)
|
||||
armw = np.zeros((MAP, MAP), np.float32)
|
||||
if arm_v is None:
|
||||
arm_v = np.zeros(len(T))
|
||||
tri_uv = luv[tl]
|
||||
|
||||
def cb(t, gy, gx, b, d):
|
||||
if mi[tp[t]] == void_idx:
|
||||
return
|
||||
ok = d > best[gy, gx]
|
||||
gy, gx, b, d = gy[ok], gx[ok], b[ok], d[ok]
|
||||
best[gy, gx] = d
|
||||
bc = np.clip(b, 0, None)
|
||||
bc /= bc.sum(1, keepdims=True)
|
||||
vs = tv[t]
|
||||
pos[gy, gx] = bc @ T[vs]
|
||||
gpos[gy, gx] = bc @ game_co[vs]
|
||||
n = bc @ NT[vs]
|
||||
nor[gy, gx] = n / np.maximum(np.linalg.norm(n, axis=1), 1e-9)[:, None]
|
||||
n = bc @ NG[vs]
|
||||
ngm[gy, gx] = n / np.maximum(np.linalg.norm(n, axis=1), 1e-9)[:, None]
|
||||
tri[gy, gx] = t
|
||||
armw[gy, gx] = bc @ arm_v[vs]
|
||||
inside[gy, gx] |= d >= 0
|
||||
t0 = time.time()
|
||||
raster(tri_uv, MAP, cb, EDGE_PX)
|
||||
hit = tri >= 0
|
||||
print(f" rasterised: {hit.mean() * 100:.1f}% of the map covered ({time.time() - t0:.1f}s)", flush=True)
|
||||
# the source as triangles
|
||||
hi = src.data
|
||||
hi.calc_loop_triangles()
|
||||
hv = [v.co.copy() for v in hi.vertices]
|
||||
htv = np.array([tuple(t.vertices) for t in hi.loop_triangles])
|
||||
htl = np.array([tuple(t.loops) for t in hi.loop_triangles])
|
||||
bvh = BVHTree.FromPolygons(hv, [tuple(t) for t in htv], all_triangles=True)
|
||||
hco = np.array([tuple(c) for c in hv])
|
||||
# the source without its arms (T-pose: out past the ribs, round the shoulder height): the torso's own skin, which
|
||||
# the torso reads from, so the side of the body under a lowered arm never takes the arm's colour
|
||||
tc_ = hco[htv].mean(1)
|
||||
if J is not None:
|
||||
is_arm = (np.abs(tc_[:, 0]) > J["ribs"] + 0.005) & (np.abs(tc_[:, 2] - J["arm_z"]) < 0.1)
|
||||
else:
|
||||
is_arm = np.zeros(len(htv), bool)
|
||||
keep_t = np.nonzero(~is_arm)[0]
|
||||
bvh_torso = BVHTree.FromPolygons(hv, [tuple(t) for t in htv[keep_t]], all_triangles=True)
|
||||
hn = np.cross(hco[htv[:, 1]] - hco[htv[:, 0]], hco[htv[:, 2]] - hco[htv[:, 0]])
|
||||
hn /= np.maximum(np.linalg.norm(hn, axis=1), 1e-12)[:, None]
|
||||
huv = np.zeros(len(hi.loops) * 2, np.float32)
|
||||
hi.uv_layers.active.data.foreach_get("uv", huv)
|
||||
huv = huv.reshape(-1, 2).astype(np.float64)
|
||||
img = hi.materials[0].node_tree.nodes["Principled BSDF"].inputs["Base Color"].links[0].from_node.image
|
||||
sw, sh = img.size
|
||||
sp = np.zeros(sw * sh * 4, np.float32)
|
||||
img.pixels.foreach_get(sp)
|
||||
sp = sp.reshape(sh, sw, 4)[..., :3].copy()
|
||||
ys, xs = np.nonzero(hit)
|
||||
P = pos[ys, xs].astype(np.float64)
|
||||
N = nor[ys, xs].astype(np.float64)
|
||||
near = np.zeros((len(P), 3))
|
||||
tri_s = np.zeros(len(P), np.int32)
|
||||
how = np.zeros(len(P), np.int8)
|
||||
AW = armw[ys, xs]
|
||||
# flat things worn on the front (badges, cards, buckles: crew_repaint.CFG "protect_front", discs in game metres seen
|
||||
# from the front) are read straight from the front, as the viewer sees them: the rebuilt skin smooths a buckle away
|
||||
G = gpos[ys, xs]
|
||||
NGt = ngm[ys, xs]
|
||||
flat = np.zeros(len(P), bool)
|
||||
for x, z, r in _front_discs(name):
|
||||
flat |= (np.hypot(G[:, 0] - x, G[:, 2] - z) < r) & (G[:, 1] < 0.02) & (NGt[:, 1] < 0.35)
|
||||
t0 = time.time()
|
||||
for i in range(len(P)):
|
||||
q = Vector(P[i])
|
||||
n = Vector(N[i])
|
||||
got = None
|
||||
torso_only = AW[i] < 0.3
|
||||
# on the arms the sleeve's hem (its rim, standing edge-on to the skin) does not count as looking this way
|
||||
face_min = 0.15 if torso_only else 0.5
|
||||
ray = bvh_torso.ray_cast if torso_only else bvh.ray_cast
|
||||
find = bvh_torso.find_nearest if torso_only else bvh.find_nearest
|
||||
if flat[i]:
|
||||
r = ray(q - Vector((0, 0.05, 0)), Vector((0, 1, 0)), 0.08)
|
||||
if r[0] is not None:
|
||||
got = r
|
||||
how[i] = 3
|
||||
if got is None and n.length > 0.5:
|
||||
# from outside in: the first source face that looks the same way as this texel, closest to the skin
|
||||
start = q + n * SEARCH
|
||||
at, left, cands = start, 2 * SEARCH, []
|
||||
for _ in range(4):
|
||||
r = ray(at, -n, left)
|
||||
if r[0] is None:
|
||||
break
|
||||
travelled = (r[0] - start).length
|
||||
# a face looking the other way is either the inside of something or one of the source's flipped
|
||||
# faces: it counts, but a face looking the right way within 4 mm wins over it
|
||||
facing = hn[keep_t[r[2]] if torso_only else r[2]] @ np.asarray(n)
|
||||
cands.append((abs(travelled - SEARCH) + (0.0 if facing > face_min else 0.004), r, travelled, facing > face_min))
|
||||
left = 2 * SEARCH - travelled - 1e-5
|
||||
at = r[0] - n * 1e-5
|
||||
if left <= 0:
|
||||
break
|
||||
if cands:
|
||||
# what is seen from outside: the outermost source face looking this way that lies no further than
|
||||
# OUTER outside the game skin (the rebuilt skin is an envelope; where it bridges a gap, between a
|
||||
# neckerchief's flap and the strap under it, the nearest face would be the hidden one); failing
|
||||
# that, the face nearest the skin
|
||||
outer = [c_ for c_ in cands if c_[3] and c_[2] >= SEARCH - OUTER]
|
||||
got = (min(outer, key=lambda c_: c_[2]) if outer else min(cands, key=lambda c_: c_[0]))[1]
|
||||
how[i] = 1
|
||||
if got is None and n.length > 0.5:
|
||||
# nothing within SEARCH (a smoothed elbow or shoulder lies further off the source's crumpled skin): the
|
||||
# source face looking this way nearest the skin along the normal, up to 3 x as far either side -- the
|
||||
# nearest point in space would be the inside of the sleeve or the torso next to it
|
||||
start = q + n * (3 * SEARCH)
|
||||
at, left, cands = start, 6 * SEARCH, []
|
||||
for _ in range(6):
|
||||
r = ray(at, -n, left)
|
||||
if r[0] is None:
|
||||
break
|
||||
travelled = (r[0] - start).length
|
||||
facing = hn[keep_t[r[2]] if torso_only else r[2]] @ np.asarray(n)
|
||||
if facing > face_min:
|
||||
cands.append((abs(travelled - 3 * SEARCH), r))
|
||||
left = 6 * SEARCH - travelled - 1e-5
|
||||
at = r[0] - n * 1e-5
|
||||
if left <= 0:
|
||||
break
|
||||
if cands:
|
||||
got = min(cands, key=lambda c_: c_[0])[1]
|
||||
how[i] = 4
|
||||
if got is None:
|
||||
got = find(q)
|
||||
how[i] = 2
|
||||
near[i] = got[0]
|
||||
tri_s[i] = keep_t[got[2]] if torso_only else got[2]
|
||||
print(f" carried {len(P)} texels in {time.time() - t0:.0f}s; by ray {np.mean(how == 1) * 100:.1f}%, nearest {np.mean(how == 2) * 100:.1f}%, from the front {int((how == 3).sum())}, by a longer ray {np.mean(how == 4) * 100:.1f}%", flush=True)
|
||||
a, b, c = hco[htv[tri_s, 0]], hco[htv[tri_s, 1]], hco[htv[tri_s, 2]]
|
||||
v0, v1, v2 = b - a, c - a, near - a
|
||||
d00, d01, d11 = (v0 * v0).sum(1), (v0 * v1).sum(1), (v1 * v1).sum(1)
|
||||
d20, d21 = (v2 * v0).sum(1), (v2 * v1).sum(1)
|
||||
den = np.maximum(d00 * d11 - d01 * d01, 1e-18)
|
||||
bb, bc = (d11 * d20 - d01 * d21) / den, (d00 * d21 - d01 * d20) / den
|
||||
ba = 1 - bb - bc
|
||||
B = np.clip(np.stack([ba, bb, bc], 1), 0, None)
|
||||
B /= np.maximum(B.sum(1, keepdims=True), 1e-12)
|
||||
U = htl[tri_s]
|
||||
uv = B[:, 0:1] * huv[U[:, 0]] + B[:, 1:2] * huv[U[:, 1]] + B[:, 2:3] * huv[U[:, 2]]
|
||||
# pulled toward the middle of its source triangle by up to a texel: never the source's own gutter
|
||||
cen = (huv[U[:, 0]] + huv[U[:, 1]] + huv[U[:, 2]]) / 3
|
||||
dv = (cen - uv) * np.array([sw, sh])
|
||||
dl = np.linalg.norm(dv, axis=1)
|
||||
uv += (dv / np.maximum(dl, 1e-9)[:, None] * np.minimum(dl, 0.9)[:, None]) / np.array([sw, sh])
|
||||
ix = np.clip((uv[:, 0] * sw).astype(int), 0, sw - 1)
|
||||
iy = np.clip((uv[:, 1] * sh).astype(int), 0, sh - 1)
|
||||
col = np.zeros((MAP, MAP, 3), np.float32)
|
||||
col[ys, xs] = sp[iy, ix]
|
||||
howm = np.zeros((MAP, MAP), np.int8)
|
||||
howm[ys, xs] = how
|
||||
return dict(pos=pos, nor=nor, ngame=ngm, gpos=gpos, col=col, hit=hit, inside=inside, tri=tri, how=howm, armw=armw,
|
||||
poly=np.where(hit, tp[np.maximum(tri, 0)], -1).astype(np.int32))
|
||||
|
||||
|
||||
def _front_discs(name):
|
||||
try:
|
||||
sys.path.insert(0, HERE)
|
||||
import crew_repaint
|
||||
return crew_repaint.CFG.get(name, {}).get("protect_front", [])
|
||||
except Exception as e:
|
||||
print(" (no front discs:", e, ")", flush=True)
|
||||
return []
|
||||
|
||||
|
||||
def bake_ao(body, others, void_idx):
|
||||
"""Rest-pose ambient occlusion of the skin on its own, into the new UV map."""
|
||||
sc = bpy.context.scene
|
||||
sc.render.engine = "CYCLES"
|
||||
sc.cycles.device = "CPU"
|
||||
sc.cycles.samples = 96
|
||||
w = bpy.data.worlds.new("AOWorld")
|
||||
sc.world = w
|
||||
w.light_settings.distance = 0.12
|
||||
for o in others:
|
||||
o.hide_render = True
|
||||
img = bpy.data.images.new("AO", MAP, MAP, alpha=False, float_buffer=True)
|
||||
added = []
|
||||
for m in body.data.materials:
|
||||
n = m.node_tree.nodes.new("ShaderNodeTexImage")
|
||||
n.image = img
|
||||
m.node_tree.nodes.active = n
|
||||
added.append((m, n))
|
||||
for x in sc.objects:
|
||||
x.select_set(False)
|
||||
body.select_set(True)
|
||||
bpy.context.view_layer.objects.active = body
|
||||
sc.render.bake.margin = 0
|
||||
sc.render.bake.use_clear = True
|
||||
t0 = time.time()
|
||||
bpy.ops.object.bake(type="AO", uv_layer="UVMap")
|
||||
print(f" AO baked in {time.time() - t0:.0f}s", flush=True)
|
||||
ao = np.zeros(MAP * MAP * 4, np.float32)
|
||||
img.pixels.foreach_get(ao)
|
||||
for m, n in added:
|
||||
m.node_tree.nodes.remove(n)
|
||||
bpy.data.images.remove(img)
|
||||
for o in others:
|
||||
o.hide_render = False
|
||||
return ao.reshape(MAP, MAP, 4)[..., 0].copy()
|
||||
|
||||
|
||||
def run(name, scratch):
|
||||
t0 = time.time()
|
||||
common.reset()
|
||||
print(f"=== {name}", flush=True)
|
||||
src, F, J = load_source(name)
|
||||
for x in list(bpy.data.objects):
|
||||
if x is not src:
|
||||
bpy.data.objects.remove(x)
|
||||
body, rig, objs = import_game(name)
|
||||
T, k, game_co, piv_src = tpose(body, rig, J)
|
||||
game_old = game_co.copy()
|
||||
# the game's own skin, kept for the before/after pictures
|
||||
old = body.copy()
|
||||
old.data = body.data.copy()
|
||||
old.name = old.data.name = body.name + "_Old"
|
||||
bpy.context.scene.collection.objects.link(old)
|
||||
# the shape fixes (crew_shape): a relaxed lower face, smoother arms that clear the torso and the strap
|
||||
import crew_shape as CS
|
||||
gnames, W = CS.read_weights(body)
|
||||
adj = CS.neighbours(body.data)
|
||||
parts = [o for o in objs if o.type == "MESH" and o.name.split(".")[0] in
|
||||
("EyeBall_L", "EyeBall_R", "Lid_L", "Lid_R", "LidLow_L", "LidLow_R", "Brow_L", "Brow_R")]
|
||||
eye_parts = None
|
||||
if parts:
|
||||
vs, fs = [], []
|
||||
for o in parts:
|
||||
base = len(vs)
|
||||
vs += [tuple(o.matrix_world @ v.co) for v in o.data.vertices]
|
||||
fs += [tuple(base + i for i in p.vertices) for p in o.data.polygons]
|
||||
eye_parts = (np.array(vs) / k, fs)
|
||||
T1, face_m = CS.fix_face(body, T, gnames, W, eye_parts, k, J, adj)
|
||||
T, P, Wn, out, arm_m = CS.fix_arms(body, gnames, W, T1, J, piv_src, k, TC.HANG, adj)
|
||||
faces = [tuple(p.vertices) for p in body.data.polygons]
|
||||
game_co, dented = CS.dent_torso(P * k, gnames, Wn, faces, T, adj)
|
||||
P = game_co / k # (the dented torso keeps its colour from where it was: T is not changed)
|
||||
vest = next((o for o in objs if o.name.split(".")[0] == "Vest"), None)
|
||||
if vest is not None:
|
||||
CS.regen_strap(vest, game_co, gnames, Wn, faces, J["arm_y"] * k)
|
||||
body.data.vertices.foreach_set("co", game_co.astype(np.float32).ravel())
|
||||
body.data.update()
|
||||
CS.write_weights(body, gnames, Wn)
|
||||
CS.smooth_normals(body)
|
||||
edited = (np.abs(Wn - W).max(1) > 1e-7) | (np.linalg.norm(P * k - game_old, axis=1) > 1e-6)
|
||||
# how well the game skin lies on the source in the T-pose (it was rebuilt over a thickened shell: a few mm)
|
||||
hv = [v.co.copy() for v in src.data.vertices]
|
||||
bvh = BVHTree.FromPolygons(hv, [tuple(p.vertices) for p in src.data.polygons])
|
||||
dist = np.array([(bvh.find_nearest(Vector(p))[0] - Vector(p)).length for p in T[::7]])
|
||||
print(f" game skin to source: median {np.median(dist):.4f}, 95% {np.percentile(dist, 95):.4f}, max {dist.max():.4f} (source units)", flush=True)
|
||||
names = [m.name for m in body.data.materials]
|
||||
void_idx = names.index("M_MouthVoid") if "M_MouthVoid" in names else -99
|
||||
NT = normals_of(body.data, T)
|
||||
gi = {g.name: g.index for g in body.vertex_groups}
|
||||
head_w = np.zeros(len(body.data.vertices))
|
||||
for v in body.data.vertices:
|
||||
for g in v.groups:
|
||||
if g.group in (gi.get("Head"), gi.get("Top")):
|
||||
head_w[v.index] += g.weight
|
||||
unwrap(body, void_idx, head_w)
|
||||
ixw = {nm_: i for i, nm_ in enumerate(gnames)}
|
||||
arm_v = sum(Wn[:, ixw[g]] for g in CS.ARM_GROUPS if g in ixw)
|
||||
maps = carry(name, body, src, T, NT, game_co, void_idx, arm_v, J)
|
||||
if F:
|
||||
col_ = maps["col"]
|
||||
FACE.repaint(F, maps["pos"].astype(np.float64), col_, maps["hit"])
|
||||
maps["col"] = col_
|
||||
bpy.data.objects.remove(src)
|
||||
maps["ao"] = bake_ao(body, [o for o in objs if o is not body and o.type == "MESH"] + [old], void_idx)
|
||||
maps["k"] = np.array(k)
|
||||
maps["edited"] = edited
|
||||
maps["arm_out"] = np.array(out * k)
|
||||
np.savez(os.path.join(scratch, name + "_maps.npz"), **maps)
|
||||
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(scratch, name + "_stage1.blend"), check_existing=False)
|
||||
print(f"=== {name} done in {time.time() - t0:.0f}s", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv[sys.argv.index("--") + 1:]
|
||||
scratch = args[0]
|
||||
os.makedirs(scratch, exist_ok=True)
|
||||
for nm in (args[1:] or CREW + DIRECTOR):
|
||||
run(nm, scratch)
|
||||
517
ArtSource/Blender/remaster/crew/scripts/crew_repaint.py
Normal file
517
ArtSource/Blender/remaster/crew/scripts/crew_repaint.py
Normal file
@ -0,0 +1,517 @@
|
||||
"""GRASS CUTTER crew remaster, stage 2: the repaint. Reads <scratch>/<name>_maps.npz from crew_rebake.py and writes
|
||||
ArtSource/Blender/remaster/crew/textures/T_Crew_<Name>.png (2048, sRGB, every texel filled).
|
||||
|
||||
* the carried colour is split into the character's own paints (k-means in Lab with lightness down-weighted, so a lit
|
||||
and a shadowed side of the same cloth stay one paint), and each texel is labelled with its paint;
|
||||
* the labels are cleaned: a 3x3 plurality vote (twice) files off single-texel specks and stair steps, and any patch of a
|
||||
paint smaller than MIN_PATCH texels is taken over by the paint round it (stray flecks of a neighbour's colour);
|
||||
* each paint becomes one flat colour (its median) with soft shading: the texel's own lightness, blurred within the
|
||||
paint and squeezed toward the median, so the cartoon reads clean while the folds still show;
|
||||
* a consistent painted look for the whole crew: a little rest-pose ambient occlusion and a top light;
|
||||
* per-character fixes (CFG): paints merged into another (Marcus's denim smudges), areas kept as painted (badges), a
|
||||
team logo on Marcus's cap;
|
||||
* the borders between paints are anti-aliased, and the empty map is filled outward from the charts (no black seams).
|
||||
Run:
|
||||
blender -b --factory-startup --python crew_repaint.py --python-exit-code 1 -- <scratch dir> [hank lin ...]
|
||||
"""
|
||||
import sys, os, math, time
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
OUT = os.path.normpath(os.path.join(HERE, "..", "textures"))
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
||||
CREW = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji")
|
||||
DIRECTOR = ("boss", "assistant")
|
||||
K = 16 # starting paints
|
||||
L_WEIGHT = 0.45 # lightness weight in the paint distance
|
||||
MERGE = 9.0 # paints closer than this are one
|
||||
MERGE_AB = 7.0 # ... or this close in hue/chroma and within MERGE_L in lightness (lit and shaded cloth)
|
||||
MERGE_L = 24.0
|
||||
MIN_PATCH = 80 # texels: smaller patches of a paint are flecks...
|
||||
MIN_DETAIL = 24 # ...unless at least this big and this far (Lab) from the paint round them: a painted detail
|
||||
DETAIL_DE = 45.0
|
||||
BORDER_SIGMA = 2.5 # px: the wide vote that smooths paint borders
|
||||
BIG_PATCH = 4000 # texels: a patch this big is an area of paint, not a detail
|
||||
DISSOLVE_DE = 8.0 # a "dissolve" colour names a paint only if one lies this close to it (Lab)
|
||||
SHADE_KEEP = 0.7 # how much of the painted lightness variation survives
|
||||
SHADE_SIGMA = 5.0 # px
|
||||
SHADE_CLIP = (-20.0, 14.0)
|
||||
AO_STRENGTH = 0.32
|
||||
TOP_LIGHT = 0.06
|
||||
|
||||
# per character: "merge": [(from sRGB, to sRGB)] paints whose median is nearest `from` become the paint nearest `to`;
|
||||
# "protect": [(centre xyz in source units, radius)] where the carried paint is kept (badges, logos); "logo": cap logo
|
||||
CFG = {
|
||||
"assistant": {
|
||||
# the G.R.A.S.S.A. badge, the ID card with its clip and the pen, the belt buckle
|
||||
"protect_front": [(-0.138, 0.683, 0.078), (0.149, 0.664, 0.105), (-0.004, 0.588, 0.042)],
|
||||
},
|
||||
"wade": {
|
||||
# the star badge on the hat band and the star buckle: kept as carried (read from the front)
|
||||
"protect_front": [(-0.01, 1.262, 0.055), (0.0, 0.53, 0.07)],
|
||||
# the overall's blue picked up at the ends of his sleeves (bare arms, red sleeves: no blue belongs there)
|
||||
"dissolve": [((0.153, 0.286, 0.488), lambda d: d["armw"] > 0.6),
|
||||
((0.074, 0.253, 0.55), lambda d: d["armw"] > 0.6),
|
||||
# ... and the sleeve hem's grey
|
||||
((0.251, 0.228, 0.231), lambda d: d["armw"] > 0.6)],
|
||||
},
|
||||
"boss": {
|
||||
# the G.R.A.S.S.A. badge, the ID card with its clip and the pen, the tie, the belt buckle
|
||||
"protect_front": [(-0.159, 0.658, 0.085), (0.171, 0.647, 0.115), (0.0, 0.66, 0.1), (0.0, 0.575, 0.06), (0.0, 0.541, 0.05)],
|
||||
},
|
||||
"marcus": {
|
||||
# the grey distress smudges on the jeans (and the odd one on his arms), and the old logo's pale leftovers on the cap
|
||||
"dissolve": [((0.353, 0.322, 0.328), None),
|
||||
# (when the smudges come out brown instead: on the jeans only, below the belt, off the arms)
|
||||
((0.433, 0.252, 0.151), lambda d: (d["gpos"][..., 2] < 0.62) & (d["armw"] < 0.3)),
|
||||
((0.19, 0.11, 0.088), lambda d: (d["gpos"][..., 2] > 0.12) & (d["gpos"][..., 2] < 0.62) & (d["armw"] < 0.3)),
|
||||
((0.854, 0.722, 0.644), lambda d: d["gpos"][..., 2] > 1.12),
|
||||
# the overall's denim and the cap's navy that the source painted onto his bare upper arms
|
||||
((0.239, 0.26, 0.371), lambda d: d["armw"] > 0.6),
|
||||
((0.197, 0.169, 0.227), lambda d: d["armw"] > 0.6)],
|
||||
"logo": dict(cap=(0.197, 0.169, 0.227), dir=(-0.45, 0.9, 0.0), band=(0.865, 0.935), r=0.042,
|
||||
face=(0.93, 0.9, 0.8), rim=(0.95, 0.7, 0.13), mark=(0.24, 0.58, 0.2)),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ colour
|
||||
|
||||
def srgb_to_lin(c):
|
||||
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
|
||||
|
||||
|
||||
def lin_to_srgb(c):
|
||||
c = np.clip(c, 0, 1)
|
||||
return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)
|
||||
|
||||
|
||||
M_XYZ = np.array([[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]])
|
||||
WHITE = np.array([0.95047, 1.0, 1.08883])
|
||||
|
||||
|
||||
def lab(srgb):
|
||||
xyz = srgb_to_lin(srgb) @ M_XYZ.T / WHITE
|
||||
f = np.where(xyz > 216 / 24389, np.cbrt(xyz), (24389 / 27 * xyz + 16) / 116)
|
||||
return np.stack([116 * f[..., 1] - 16, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])], -1)
|
||||
|
||||
|
||||
def unlab(L):
|
||||
fy = (L[..., 0] + 16) / 116
|
||||
fx = fy + L[..., 1] / 500
|
||||
fz = fy - L[..., 2] / 200
|
||||
f = np.stack([fx, fy, fz], -1)
|
||||
xyz = np.where(f ** 3 > 216 / 24389, f ** 3, (116 * f - 16) / (24389 / 27)) * WHITE
|
||||
return lin_to_srgb(xyz @ np.linalg.inv(M_XYZ).T)
|
||||
|
||||
|
||||
def feat(L):
|
||||
return L * np.array([L_WEIGHT, 1.0, 1.0])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ image helpers
|
||||
|
||||
def box(a, r, axis):
|
||||
if r < 1:
|
||||
return a
|
||||
c = np.cumsum(a, axis=axis, dtype=np.float64)
|
||||
n = a.shape[axis]
|
||||
idx = np.arange(n)
|
||||
hi = np.clip(idx + r, 0, n - 1)
|
||||
lo = idx - r - 1
|
||||
take_hi = np.take(c, hi, axis=axis)
|
||||
take_lo = np.where((lo >= 0).reshape([-1 if i == axis else 1 for i in range(a.ndim)]),
|
||||
np.take(c, np.clip(lo, 0, n - 1), axis=axis), 0)
|
||||
return ((take_hi - take_lo) / (2 * r + 1)).astype(np.float32)
|
||||
|
||||
|
||||
def blur(a, sigma):
|
||||
"""Gaussian-ish blur, three box passes on each axis."""
|
||||
r = max(1, int(round(-0.5 + math.sqrt(0.25 + sigma * sigma)))) # three passes of radius r: sigma^2 = r(r+1)
|
||||
for _ in range(3):
|
||||
a = box(box(a, r, 0), r, 1)
|
||||
return a
|
||||
|
||||
|
||||
def shifts(a, fill):
|
||||
"""The 8 neighbours of every texel (array of shape (8,) + a.shape), `fill` off the edges."""
|
||||
out = []
|
||||
H, W = a.shape[:2]
|
||||
for dy in (-1, 0, 1):
|
||||
for dx in (-1, 0, 1):
|
||||
if not dy and not dx:
|
||||
continue
|
||||
s = np.full_like(a, fill)
|
||||
ys0, ys1 = max(0, dy), H + min(0, dy)
|
||||
xs0, xs1 = max(0, dx), W + min(0, dx)
|
||||
s[ys0 - dy:ys1 - dy, xs0 - dx:xs1 - dx] = a[ys0:ys1, xs0:xs1]
|
||||
out.append(s)
|
||||
return np.stack(out)
|
||||
|
||||
|
||||
def plurality(lab_, hit, nlab, keep_self=1):
|
||||
"""Each texel takes the paint most of its 3x3 has (itself counted keep_self+1 times)."""
|
||||
nb = shifts(lab_, -1)
|
||||
cnt = np.zeros((nlab,) + lab_.shape, np.int16)
|
||||
for s in nb:
|
||||
for l in range(nlab):
|
||||
cnt[l] += (s == l)
|
||||
for l in range(nlab):
|
||||
cnt[l] += (lab_ == l) * (1 + keep_self)
|
||||
new = cnt.argmax(0).astype(lab_.dtype)
|
||||
return np.where(hit, new, lab_)
|
||||
|
||||
|
||||
def vote_fill(lab_, loose, n):
|
||||
"""The loose texels take the paint of the texels round them, ring by ring inward; loose ones do not vote."""
|
||||
lab_ = lab_.copy()
|
||||
left = loose.copy()
|
||||
for _ in range(400):
|
||||
if not left.any():
|
||||
break
|
||||
nb = shifts(np.where(left, -1, lab_), -1)
|
||||
cnt = np.zeros((n,) + lab_.shape, np.int16)
|
||||
for s in nb:
|
||||
for l in range(n):
|
||||
cnt[l] += (s == l)
|
||||
upd = left & (cnt.max(0) > 0)
|
||||
if not upd.any():
|
||||
break # what is left is a whole chart of its own: it keeps its paint
|
||||
lab_ = np.where(upd, cnt.argmax(0).astype(np.int16), lab_)
|
||||
left &= ~upd
|
||||
return lab_
|
||||
|
||||
|
||||
def smooth_labels(lab_, hit, n, sigma=1.4):
|
||||
"""Each texel takes the paint with the most weight round it (blurred one-hot): round, even borders, no stair steps."""
|
||||
best = np.full(hit.shape, -1.0, np.float32)
|
||||
out = lab_.copy()
|
||||
for l in range(n):
|
||||
w = blur(((lab_ == l) & hit).astype(np.float32), sigma)
|
||||
m = hit & (w > best)
|
||||
out[m] = l
|
||||
best = np.where(m, w, best)
|
||||
return out
|
||||
|
||||
|
||||
def components(lab_, hit):
|
||||
"""Connected patches of one paint (4-neighbour): returns a patch id per texel (-1 off the charts)."""
|
||||
H, W = lab_.shape
|
||||
ids = np.where(hit, np.arange(H * W).reshape(H, W), -1).astype(np.int64)
|
||||
big = H * W + 1
|
||||
for it in range(4000):
|
||||
cur = np.where(hit, ids, big)
|
||||
m = cur.copy()
|
||||
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
|
||||
s = np.roll(cur, (dy, dx), (0, 1))
|
||||
sl = np.roll(lab_, (dy, dx), (0, 1))
|
||||
sh = np.roll(hit, (dy, dx), (0, 1))
|
||||
ok = sh & (sl == lab_)
|
||||
m = np.where(ok & (s < m), s, m)
|
||||
m = np.where(hit, m, -1)
|
||||
flat = m.ravel()
|
||||
# pointer jumping
|
||||
for _ in range(3):
|
||||
v = flat >= 0
|
||||
flat = np.where(v, flat[np.maximum(flat, 0)], -1)
|
||||
m = flat.reshape(H, W)
|
||||
if np.array_equal(m, ids):
|
||||
break
|
||||
ids = m
|
||||
return ids
|
||||
|
||||
|
||||
def fill(rgb, known, max_iter=600):
|
||||
"""Every unknown texel takes the average of its known neighbours, ring by ring outward, until the map is full."""
|
||||
out = rgb.copy()
|
||||
known = known.copy()
|
||||
for _ in range(max_iter):
|
||||
if known.all():
|
||||
break
|
||||
k = known.astype(np.float32)
|
||||
tot = np.zeros_like(out)
|
||||
cnt = np.zeros(known.shape, np.float32)
|
||||
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)):
|
||||
tot += np.roll(out * k[..., None], (dy, dx), (0, 1))
|
||||
cnt += np.roll(k, (dy, dx), (0, 1))
|
||||
new = ~known & (cnt > 0)
|
||||
out[new] = tot[new] / cnt[new][:, None]
|
||||
known |= new
|
||||
return out
|
||||
|
||||
|
||||
def save_png(rgb, path):
|
||||
h, w = rgb.shape[:2]
|
||||
img = bpy.data.images.new(os.path.splitext(os.path.basename(path))[0], w, h, alpha=False)
|
||||
px = np.dstack([np.clip(rgb, 0, 1), np.ones((h, w))]).astype(np.float32)
|
||||
img.pixels.foreach_set(px.ravel())
|
||||
img.filepath_raw = path
|
||||
img.file_format = "PNG"
|
||||
img.save()
|
||||
bpy.data.images.remove(img)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ paints
|
||||
|
||||
def kmeans(X, k, iters=30, seed=3):
|
||||
rng = np.random.default_rng(seed)
|
||||
C = [X[rng.integers(len(X))]]
|
||||
for _ in range(k - 1):
|
||||
d = np.min(((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1), 1)
|
||||
C.append(X[rng.choice(len(X), p=d / d.sum())])
|
||||
C = np.array(C)
|
||||
for _ in range(iters):
|
||||
a = ((X[:, None, :] - C[None]) ** 2).sum(-1).argmin(1)
|
||||
for j in range(k):
|
||||
if (a == j).any():
|
||||
C[j] = X[a == j].mean(0)
|
||||
return C, a
|
||||
|
||||
|
||||
def paints(Lab, hit):
|
||||
ys, xs = np.nonzero(hit)
|
||||
rng = np.random.default_rng(7)
|
||||
pick = rng.choice(len(ys), min(len(ys), 160000), replace=False)
|
||||
S = Lab[ys[pick], xs[pick]]
|
||||
C, a = kmeans(feat(S), K)
|
||||
C = C / np.array([L_WEIGHT, 1, 1]) # back to Lab
|
||||
w = np.bincount(a, minlength=K).astype(float)
|
||||
C, w = list(C), list(w)
|
||||
while True:
|
||||
best = None
|
||||
for i in range(len(C)):
|
||||
for j in range(i + 1, len(C)):
|
||||
d = np.linalg.norm(feat(C[i]) - feat(C[j]))
|
||||
dab = np.linalg.norm(C[i][1:] - C[j][1:])
|
||||
dl = abs(C[i][0] - C[j][0])
|
||||
if d < MERGE or (dab < MERGE_AB and dl < MERGE_L):
|
||||
if best is None or d < best[0]:
|
||||
best = (d, i, j)
|
||||
if best is None:
|
||||
break
|
||||
_, i, j = best
|
||||
C[i] = (C[i] * w[i] + C[j] * w[j]) / (w[i] + w[j])
|
||||
w[i] += w[j]
|
||||
del C[j], w[j]
|
||||
# drop paints nothing much uses
|
||||
C = np.array([c for c, n in zip(C, w) if n > 40])
|
||||
return C
|
||||
|
||||
|
||||
def assign(Lab, hit, C):
|
||||
lab_ = np.full(hit.shape, -1, np.int16)
|
||||
ys, xs = np.nonzero(hit)
|
||||
F = feat(Lab[ys, xs])
|
||||
FC = feat(C)
|
||||
out = np.empty(len(ys), np.int16)
|
||||
for s in range(0, len(ys), 400000):
|
||||
out[s:s + 400000] = ((F[s:s + 400000, None, :] - FC[None]) ** 2).sum(-1).argmin(1)
|
||||
lab_[ys, xs] = out
|
||||
return lab_
|
||||
|
||||
|
||||
def srgb_of(L):
|
||||
return tuple(round(float(x), 3) for x in unlab(np.array(L)))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the repaint
|
||||
|
||||
def repaint(name, d):
|
||||
t0 = time.time()
|
||||
cfg = CFG.get(name, {})
|
||||
hit = d["hit"]
|
||||
col = d["col"].astype(np.float64)
|
||||
Lab = lab(col)
|
||||
C = paints(Lab, hit)
|
||||
lab_ = assign(Lab, hit, C)
|
||||
print(f" {len(C)} paints:", ", ".join(f"{i}:{srgb_of(c)}~{(lab_ == i).mean() * 100 / hit.mean():.1f}%" for i, c in enumerate(C)), flush=True)
|
||||
n = len(C)
|
||||
gpos = d["gpos"].astype(np.float64)
|
||||
# specks and stair steps
|
||||
for _ in range(2):
|
||||
lab_ = plurality(lab_, hit, n)
|
||||
lab_ = smooth_labels(lab_, hit, n)
|
||||
ids = components(lab_, hit)
|
||||
sizes = np.bincount(ids[hit].ravel(), minlength=ids.size)
|
||||
loose = hit & (sizes[np.maximum(ids, 0)] < MIN_PATCH)
|
||||
# ... but a small patch that stands out strongly from the paint round it, and is not a crumb, is a painted detail
|
||||
# (a stitch, a rivet, a mole), not a fleck picked up from a neighbour: it stays
|
||||
guess = vote_fill(lab_, loose, n)
|
||||
dE = np.linalg.norm(C[np.maximum(lab_, 0)] - C[np.maximum(guess, 0)], axis=-1)
|
||||
pid = np.where(loose, ids, 0)
|
||||
tot = np.bincount(pid[loose].ravel(), weights=dE[loose].ravel(), minlength=ids.size)
|
||||
cnt = np.bincount(pid[loose].ravel(), minlength=ids.size)
|
||||
mean_dE = tot / np.maximum(cnt, 1)
|
||||
detail = loose & (sizes[np.maximum(ids, 0)] >= MIN_DETAIL) & (mean_dE[np.maximum(ids, 0)] > DETAIL_DE)
|
||||
loose &= ~detail
|
||||
print(f" {int(loose.sum())} texels in patches under {MIN_PATCH} texels re-painted from round them;"
|
||||
f" {int(detail.sum())} kept as painted details", flush=True)
|
||||
# character fixes: a paint dissolved (where `where` says, in game metres) into whatever paint surrounds it
|
||||
for colr, where in cfg.get("dissolve", []):
|
||||
dc = np.linalg.norm(C - lab(np.array(colr)), axis=1)
|
||||
i = int(np.argmin(dc))
|
||||
if dc[i] > DISSOLVE_DE:
|
||||
# the map has no such paint this time (it went into a neighbour): nothing to dissolve
|
||||
print(f" no paint near {colr} (nearest {srgb_of(C[i])}, dE {dc[i]:.1f}): nothing dissolved", flush=True)
|
||||
continue
|
||||
m = hit & (lab_ == i)
|
||||
if where is not None:
|
||||
m &= where(d)
|
||||
loose |= m
|
||||
print(f" paint {i} {srgb_of(C[i])} dissolved: {int(m.sum())} texels", flush=True)
|
||||
# on the arms, texels no ray reached (crew_rebake took the nearest point of the source, which next to a sleeve's
|
||||
# end is the sleeve's inside or the torso) are not trusted either
|
||||
if "how" in d:
|
||||
guessw = hit & (d["how"] == 2) & (d["armw"] > 0.3)
|
||||
loose |= guessw
|
||||
print(f" arm texels with no ray hit, painted from round them: {int(guessw.sum())}", flush=True)
|
||||
# loose texels are taken by the paint round them, ring by ring, the loose ones not voting
|
||||
lab_ = vote_fill(lab_, loose, n)
|
||||
lab_ = smooth_labels(lab_, hit, n)
|
||||
# the borders between paints as smooth curves: a wide vote (blurred one-hot, ~+-9 px, only over chart texels, so
|
||||
# nothing reaches across the 15 px gaps between charts) files off torn edges and blotches; small painted details
|
||||
# (stitches, stars, buttons, rivets) it would swallow are put back, unless they lie against a big area of their own
|
||||
# paint (then they are a blotch of it bleeding over the border)
|
||||
wide = smooth_labels(lab_, hit, n, sigma=BORDER_SIGMA)
|
||||
ids2 = components(lab_, hit)
|
||||
size2 = np.bincount(ids2[hit].ravel(), minlength=ids2.size)
|
||||
sz = size2[np.maximum(ids2, 0)]
|
||||
lost = hit & (wide != lab_)
|
||||
dE2 = np.linalg.norm(C[np.maximum(lab_, 0)] - C[np.maximum(wide, 0)], axis=-1)
|
||||
near_big = np.zeros(hit.shape, bool)
|
||||
for l in range(n):
|
||||
big = (lab_ == l) & (sz >= BIG_PATCH)
|
||||
if big.any():
|
||||
near_big |= (lab_ == l) & (blur(big.astype(np.float32), 0.6) > 0.01) & ~big
|
||||
pid = np.where(hit, ids2, 0)
|
||||
against = np.bincount(pid[near_big].ravel(), minlength=ids2.size) > 0
|
||||
keep = lost & (sz >= MIN_DETAIL) & (sz < BIG_PATCH) & (dE2 > DETAIL_DE) & ~against[np.maximum(ids2, 0)]
|
||||
keep_ids = np.bincount(pid[keep].ravel(), minlength=ids2.size) > 0
|
||||
back = hit & keep_ids[np.maximum(ids2, 0)]
|
||||
print(f" borders smoothed: {int(lost.sum())} texels changed paint, {int((back & lost).sum())} of them put back as details", flush=True)
|
||||
lab_ = np.where(back, lab_, wide)
|
||||
lab_ = smooth_labels(lab_, hit, n) # one more fine pass over the joins
|
||||
# the paint's own colour, and its lightness blurred within it (loose texels' own lightness is not trusted)
|
||||
med = np.zeros((n, 3))
|
||||
for l in range(n):
|
||||
m = (lab_ == l) & ~loose
|
||||
if m.any():
|
||||
med[l] = np.median(Lab[m], 0)
|
||||
dL = Lab[..., 0] - med[np.maximum(lab_, 0), 0]
|
||||
sh = np.zeros(hit.shape, np.float32)
|
||||
for l in range(n):
|
||||
m = ((lab_ == l) & ~loose).astype(np.float32)
|
||||
inl = lab_ == l
|
||||
if not inl.any():
|
||||
continue
|
||||
num = blur((dL * m).astype(np.float32), SHADE_SIGMA)
|
||||
den = blur(m, SHADE_SIGMA)
|
||||
num2 = blur((dL * m).astype(np.float32), SHADE_SIGMA * 4)
|
||||
den2 = blur(m, SHADE_SIGMA * 4)
|
||||
far = num2 / np.maximum(den2, 1e-4) * (den2 > 1e-3)
|
||||
sh = np.where(inl, np.where(den > 0.05, num / np.maximum(den, 1e-4), far), sh)
|
||||
out = med[np.maximum(lab_, 0)].copy()
|
||||
out[..., 0] += np.clip(SHADE_KEEP * sh, *SHADE_CLIP)
|
||||
rgb = unlab(out)
|
||||
# areas kept exactly as carried
|
||||
pos = d["pos"].astype(np.float64)
|
||||
keep = np.zeros(hit.shape, np.float32)
|
||||
for c, r in cfg.get("protect", []):
|
||||
dist = np.linalg.norm(pos - np.array(c), axis=-1)
|
||||
keep = np.maximum(keep, np.clip((r - dist) / (0.25 * r), 0, 1))
|
||||
# ... and front-facing areas given as discs (x, z, r) in game metres seen from the front: badges, ID cards, buckles
|
||||
for x, z, r in cfg.get("protect_front", []):
|
||||
dist = np.hypot(gpos[..., 0] - x, gpos[..., 2] - z)
|
||||
front = (gpos[..., 1] < 0.02) & (d["ngame"][..., 1] < 0.35)
|
||||
keep = np.maximum(keep, np.clip((r - dist) / (0.2 * r), 0, 1) * front)
|
||||
keep *= hit
|
||||
if keep.any():
|
||||
k3 = col.astype(np.float32)
|
||||
rgb = rgb * (1 - keep[..., None]) + k3 * keep[..., None]
|
||||
print(f" kept as painted: {int((keep > 0.5).sum())} texels", flush=True)
|
||||
# the cap logo
|
||||
if "logo" in cfg:
|
||||
rgb = logo(rgb, pos, d["nor"].astype(np.float64), lab_, hit, cfg["logo"], C)
|
||||
# anti-aliased borders between paints
|
||||
edge = np.zeros(hit.shape, bool)
|
||||
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
|
||||
edge |= (np.roll(lab_, (dy, dx), (0, 1)) != lab_) & np.roll(hit, (dy, dx), (0, 1))
|
||||
edge &= hit
|
||||
hf = hit.astype(np.float32)
|
||||
soft = blur((rgb * hf[..., None]).astype(np.float32), 0.6) / np.maximum(blur(hf, 0.6), 1e-4)[..., None]
|
||||
ring = (blur(edge.astype(np.float32), 0.6) > 0.02) & hit & ~edge
|
||||
rgb = np.where(edge[..., None], 0.35 * rgb + 0.65 * soft, np.where(ring[..., None], 0.7 * rgb + 0.3 * soft, rgb))
|
||||
# the crew's common light: a little occlusion and a top light, in linear
|
||||
lin = srgb_to_lin(rgb)
|
||||
ao = np.clip(d["ao"], 0, 1)
|
||||
hf1 = hit.astype(np.float32)
|
||||
ao = blur((ao * hf1).astype(np.float32), 1.0) / np.maximum(blur(hf1, 1.0), 1e-4)
|
||||
ao = np.where(hit, ao, 1)
|
||||
shade = (1 - AO_STRENGTH * (1 - ao)) * (1 + TOP_LIGHT * d["ngame"][..., 2])
|
||||
rgb = lin_to_srgb(lin * shade[..., None])
|
||||
rgb = fill(rgb.astype(np.float32), hit)
|
||||
print(f" repainted in {time.time() - t0:.0f}s", flush=True)
|
||||
return rgb, lab_, med
|
||||
|
||||
|
||||
def logo(rgb, pos, nor, lab_, hit, L, C):
|
||||
"""A neat team badge on Marcus's cap (worn back to front, so the badge looks back over his shoulder): a cream disc
|
||||
with a gold rim and a green three-blade grass tuft, the crew's mark. Drawn in the plane facing L['dir'] (source
|
||||
units), centred on the cap where its surface faces that way in the height band L['band']; on the cap paint only."""
|
||||
dr = np.array(L["dir"], float)
|
||||
dr /= np.linalg.norm(dr)
|
||||
cap = int(np.argmin(np.linalg.norm(C - lab(np.array(L["cap"])), axis=1)))
|
||||
on_cap = hit & (lab_ == cap)
|
||||
z0, z1 = L["band"]
|
||||
facing = on_cap & ((nor @ dr) > 0.85) & (pos[..., 2] > z0) & (pos[..., 2] < z1)
|
||||
c = np.median(pos[facing], 0)
|
||||
c[2] = (z0 + z1) / 2
|
||||
R = L["r"]
|
||||
ux = np.array([dr[1], -dr[0], 0.0])
|
||||
ux /= np.linalg.norm(ux)
|
||||
rel = pos - c
|
||||
u = (rel @ ux) / R
|
||||
v = rel[..., 2] / R
|
||||
on = on_cap & ((nor @ dr) > 0.3) & (np.abs(rel @ dr) < 2.5 * R)
|
||||
rr = np.sqrt(u * u + v * v)
|
||||
aa = 0.05
|
||||
ss = lambda x: np.clip(x / aa + 0.5, 0, 1)
|
||||
disc = ss(1.0 - rr)
|
||||
inner = ss(0.80 - rr)
|
||||
tuft = np.zeros_like(u)
|
||||
for (bx, by), (tx, ty), wd in (((0.0, -0.45), (0.0, 0.58), 0.17), ((-0.08, -0.45), (-0.5, 0.3), 0.14),
|
||||
((0.08, -0.45), (0.5, 0.3), 0.14), ((-0.2, -0.45), (-0.62, -0.05), 0.1),
|
||||
((0.2, -0.45), (0.62, -0.05), 0.1)):
|
||||
ax = np.array([tx - bx, ty - by])
|
||||
ln = np.linalg.norm(ax)
|
||||
ax /= ln
|
||||
t = ((u - bx) * ax[0] + (v - by) * ax[1]) / ln
|
||||
perp = np.abs(-(u - bx) * ax[1] + (v - by) * ax[0])
|
||||
half = wd * np.clip(1 - t, 0, 1) ** 0.9
|
||||
tuft = np.maximum(tuft, ss(half - perp) * (t > -0.05) * ss(1 - t))
|
||||
ground = ss(0.07 - np.abs(v + 0.47)) * ss(0.6 - np.abs(u))
|
||||
tuft = np.maximum(tuft, ground) * inner
|
||||
out = rgb.copy()
|
||||
for mask, colr in ((disc, L["rim"]), (inner, L["face"]), (tuft, L["mark"])):
|
||||
m = (mask * on)[..., None]
|
||||
out = out * (1 - m) + np.array(colr) * m
|
||||
print(f" cap logo at {np.round(c, 3)} facing {np.round(dr, 2)}: {int((disc * on > 0.5).sum())} texels", flush=True)
|
||||
return out
|
||||
|
||||
def run(name, scratch):
|
||||
print(f"=== {name}", flush=True)
|
||||
d = dict(np.load(os.path.join(scratch, name + "_maps.npz")))
|
||||
rgb, lab_, med = repaint(name, d)
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
save_png(rgb, os.path.join(OUT, "T_Crew_" + name.capitalize() + ".png"))
|
||||
# the paint map, for checking
|
||||
vis = unlab(med[np.maximum(lab_, 0)])
|
||||
vis[lab_ < 0] = 0
|
||||
save_png(vis, os.path.join(scratch, name + "_paints.png"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv[sys.argv.index("--") + 1:]
|
||||
scratch = args[0]
|
||||
for nm in (args[1:] or CREW + DIRECTOR):
|
||||
run(nm, scratch)
|
||||
215
ArtSource/Blender/remaster/crew/scripts/crew_review.py
Normal file
215
ArtSource/Blender/remaster/crew/scripts/crew_review.py
Normal file
@ -0,0 +1,215 @@
|
||||
"""GRASS CUTTER crew remaster, stage 4: ArtSource/Blender/remaster/crew/Crew_Review.blend.
|
||||
|
||||
All ten remastered characters in a row (collection "Remastered", appended from the per-character .blends), each with its
|
||||
name on the floor; the game's current models, imported from Assets/Art/Models with their current maps, stand right behind
|
||||
each one in "Originals" (hidden: switch its eye on to compare). Soft studio light, a floor, a camera on the line-up, and
|
||||
every 3D view in Material Preview with the scene's lights.
|
||||
Run:
|
||||
blender -b --factory-startup --python crew_review.py --python-exit-code 1
|
||||
"""
|
||||
import sys, os, math
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BASE = os.path.normpath(os.path.join(HERE, ".."))
|
||||
ROOT = os.path.normpath(os.path.join(BASE, "..", "..", "..", ".."))
|
||||
import bpy
|
||||
from mathutils import Vector, Quaternion
|
||||
|
||||
ORDER = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji", "boss", "assistant")
|
||||
DIRECTOR = ("boss", "assistant")
|
||||
GAME_TEX = os.path.join(ROOT, "Assets", "Art", "Textures")
|
||||
STEP = 0.9 # metres between characters
|
||||
BEHIND = 1.1 # the original stands this far behind its remaster
|
||||
|
||||
|
||||
def sm_name(n):
|
||||
return ("SM_Dir_" if n in DIRECTOR else "SM_Crew_") + n.capitalize()
|
||||
|
||||
|
||||
def title(n):
|
||||
return {"boss": "The Director", "assistant": "Assistant"}.get(n, n.capitalize())
|
||||
|
||||
|
||||
def mat_flat(name, rgb, emit=False):
|
||||
m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
|
||||
m.use_nodes = True
|
||||
nt = m.node_tree
|
||||
b = nt.nodes.get("Principled BSDF")
|
||||
b.inputs["Base Color"].default_value = (*rgb, 1)
|
||||
b.inputs["Roughness"].default_value = 0.9
|
||||
if emit:
|
||||
b.inputs["Emission Color"].default_value = (*rgb, 1)
|
||||
b.inputs["Emission Strength"].default_value = 1.0
|
||||
return m
|
||||
|
||||
|
||||
def text(body, at, size, col, mat):
|
||||
cu = bpy.data.curves.new("Label_" + body, "FONT")
|
||||
cu.body = body
|
||||
cu.size = size
|
||||
cu.align_x = "CENTER"
|
||||
cu.extrude = 0.002
|
||||
o = bpy.data.objects.new("Label_" + body, cu)
|
||||
col.objects.link(o)
|
||||
o.location = at
|
||||
o.rotation_euler = (math.radians(90), 0, 0) # standing up, facing the camera
|
||||
o.data.materials.append(mat)
|
||||
return o
|
||||
|
||||
|
||||
def soften(mats):
|
||||
for m in mats:
|
||||
if not m or not m.node_tree:
|
||||
continue
|
||||
b = next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None)
|
||||
if b:
|
||||
b.inputs["Roughness"].default_value = 0.75
|
||||
if "Specular IOR Level" in b.inputs:
|
||||
b.inputs["Specular IOR Level"].default_value = 0.25
|
||||
|
||||
|
||||
def append_remaster(n, col):
|
||||
path = os.path.join(BASE, sm_name(n) + ".blend")
|
||||
with bpy.data.libraries.load(path, link=False) as (src, dst):
|
||||
dst.objects = list(src.objects)
|
||||
keep = []
|
||||
for o in dst.objects:
|
||||
if o is None:
|
||||
continue
|
||||
drop = (o.type in ("LIGHT", "CAMERA", "FONT") or o.name.endswith("_Old") or o.name.startswith("lbl"))
|
||||
if drop:
|
||||
bpy.data.objects.remove(o)
|
||||
continue
|
||||
col.objects.link(o)
|
||||
keep.append(o)
|
||||
rig = next(o for o in keep if o.type == "ARMATURE")
|
||||
for o in keep:
|
||||
o.name = o.name.split(".")[0] + "_" + n.capitalize()
|
||||
return rig, keep
|
||||
|
||||
|
||||
def import_original(n, col):
|
||||
before = set(bpy.data.objects)
|
||||
bpy.ops.import_scene.fbx(filepath=os.path.join(ROOT, "Assets", "Art", "Models", sm_name(n) + ".fbx"))
|
||||
new = [o for o in bpy.data.objects if o not in before]
|
||||
for o in new:
|
||||
for c in list(o.users_collection):
|
||||
c.objects.unlink(o)
|
||||
col.objects.link(o)
|
||||
o.name = o.name.split(".")[0] + "_" + n.capitalize() + "_Orig"
|
||||
for o in new:
|
||||
if o.type == "MESH":
|
||||
for m in o.data.materials:
|
||||
if m and m.node_tree:
|
||||
for nd in m.node_tree.nodes:
|
||||
if nd.type == "TEX_IMAGE" and nd.image:
|
||||
p = os.path.join(GAME_TEX, os.path.basename(nd.image.filepath))
|
||||
if os.path.exists(p):
|
||||
nd.image.filepath = p
|
||||
nd.image.reload()
|
||||
soften(o.data.materials)
|
||||
return next(o for o in new if o.type == "ARMATURE"), new
|
||||
|
||||
|
||||
def main():
|
||||
bpy.ops.wm.read_factory_settings(use_empty=False)
|
||||
for o in list(bpy.data.objects):
|
||||
bpy.data.objects.remove(o)
|
||||
sc = bpy.context.scene
|
||||
sc.name = "Crew Review"
|
||||
rem = bpy.data.collections.new("Remastered")
|
||||
org = bpy.data.collections.new("Originals")
|
||||
lab = bpy.data.collections.new("Labels")
|
||||
stg = bpy.data.collections.new("Stage")
|
||||
for c in (rem, org, lab, stg):
|
||||
sc.collection.children.link(c)
|
||||
ink = mat_flat("M_LabelInk", (0.03, 0.035, 0.05))
|
||||
ink2 = mat_flat("M_LabelInkOrig", (0.35, 0.12, 0.08))
|
||||
x0 = -STEP * (len(ORDER) - 1) / 2
|
||||
for i, n in enumerate(ORDER):
|
||||
x = x0 + i * STEP
|
||||
c = bpy.data.collections.new(sm_name(n))
|
||||
rem.children.link(c)
|
||||
rig, objs = append_remaster(n, c)
|
||||
rig.location = (x, 0, 0)
|
||||
co = bpy.data.collections.new(sm_name(n) + "_Original")
|
||||
org.children.link(co)
|
||||
rig_o, objs_o = import_original(n, co)
|
||||
rig_o.location = (x, BEHIND, 0)
|
||||
t = text(title(n), (x, -0.6, 0.015), 0.09, lab, ink)
|
||||
t2 = text(title(n) + " (game now)", (x, BEHIND - 0.6, 0.015), 0.06, org, ink2)
|
||||
print(" placed", n, flush=True)
|
||||
# the stage: a floor, soft light
|
||||
bpy.ops.mesh.primitive_circle_add(vertices=96, radius=STEP * len(ORDER) * 0.75, fill_type="NGON", location=(0, 0.4, 0))
|
||||
floor = bpy.context.active_object
|
||||
floor.name = "Floor"
|
||||
floor.scale.y = 0.45
|
||||
for c in list(floor.users_collection):
|
||||
c.objects.unlink(floor)
|
||||
stg.objects.link(floor)
|
||||
floor.data.materials.append(mat_flat("M_Floor", (0.3, 0.34, 0.33)))
|
||||
w = bpy.data.worlds.new("Studio")
|
||||
sc.world = w
|
||||
w.use_nodes = True
|
||||
w.node_tree.nodes["Background"].inputs[0].default_value = (0.62, 0.68, 0.74, 1)
|
||||
w.node_tree.nodes["Background"].inputs[1].default_value = 0.9
|
||||
for nm, kind, en, rot, ang in (("Key", "SUN", 2.6, (52, 8, -38), 18), ("Rim", "SUN", 1.3, (35, 0, 160), 10)):
|
||||
ld = bpy.data.lights.new(nm, kind)
|
||||
ld.energy = en
|
||||
ld.angle = math.radians(ang)
|
||||
lo = bpy.data.objects.new(nm, ld)
|
||||
stg.objects.link(lo)
|
||||
lo.rotation_euler = [math.radians(a) for a in rot]
|
||||
ld = bpy.data.lights.new("Fill", "AREA")
|
||||
ld.energy = 450
|
||||
ld.size = 6
|
||||
ld.shape = "RECTANGLE"
|
||||
ld.size_y = 2
|
||||
lo = bpy.data.objects.new("Fill", ld)
|
||||
stg.objects.link(lo)
|
||||
lo.location = (-1.5, -5, 2.5)
|
||||
lo.rotation_euler = (Vector((0, 0, 0.6)) - lo.location).to_track_quat("-Z", "Y").to_euler()
|
||||
# the camera on the line-up
|
||||
cd = bpy.data.cameras.new("ReviewCam")
|
||||
cd.lens = 38
|
||||
cam = bpy.data.objects.new("ReviewCam", cd)
|
||||
stg.objects.link(cam)
|
||||
cam.location = (0, -11.2, 1.55)
|
||||
cam.rotation_euler = (Vector((0, 0, 0.62)) - cam.location).to_track_quat("-Z", "Y").to_euler()
|
||||
sc.camera = cam
|
||||
sc.render.engine = "BLENDER_EEVEE"
|
||||
sc.render.resolution_x, sc.render.resolution_y = 2400, 900
|
||||
sc.view_settings.view_transform = "Standard"
|
||||
# Originals hidden by default (eye off), not rendered
|
||||
vl = bpy.context.view_layer
|
||||
vl.layer_collection.children["Originals"].hide_viewport = True
|
||||
org.hide_render = True
|
||||
# every 3D view: Material Preview with the scene's lights, looking at the line-up
|
||||
for scr in bpy.data.screens:
|
||||
for area in scr.areas:
|
||||
if area.type != "VIEW_3D":
|
||||
continue
|
||||
for sp in area.spaces:
|
||||
if sp.type != "VIEW_3D":
|
||||
continue
|
||||
sp.shading.type = "MATERIAL"
|
||||
sp.shading.use_scene_lights = True
|
||||
sp.shading.use_scene_world = True
|
||||
sp.overlay.show_relationship_lines = False
|
||||
sp.overlay.show_bones = False
|
||||
r3 = sp.region_3d
|
||||
r3.view_perspective = "PERSP"
|
||||
r3.view_location = (0, 0, 0.62)
|
||||
r3.view_rotation = cam.rotation_euler.to_quaternion()
|
||||
r3.view_distance = (cam.location - Vector((0, 0, 0.62))).length
|
||||
out = os.path.join(BASE, "Crew_Review.blend")
|
||||
bpy.ops.wm.save_as_mainfile(filepath=out, check_existing=False)
|
||||
bpy.ops.file.make_paths_relative()
|
||||
bpy.ops.wm.save_mainfile()
|
||||
# a still of the line-up, and one with the originals shown behind
|
||||
sc.render.filepath = os.path.join(BASE, "previews", "Crew_Review.png")
|
||||
bpy.ops.render.render(write_still=True)
|
||||
print("saved", out, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
322
ArtSource/Blender/remaster/crew/scripts/crew_shape.py
Normal file
322
ArtSource/Blender/remaster/crew/scripts/crew_shape.py
Normal file
@ -0,0 +1,322 @@
|
||||
"""GRASS CUTTER crew remaster: the shape fixes on the game skin, done in the source's T-pose (crew_rebake.tpose) before
|
||||
the arms are brought down again. Used by crew_rebake.py.
|
||||
|
||||
* ARMS. The arms are re-lowered from the T-pose by linear-blend skinning about the same shoulder pivots and by the same
|
||||
angle as gc_tripo_crew.lower_arms (so the Arm/Fore bones, their pivots and the Hand sockets still sit in the arm),
|
||||
but with weights smoothed further over the mesh (a wider, even blend Body<->Arm at the shoulder and Arm<->Fore at
|
||||
the elbow, normalised), the shoulder and elbow skin relaxed (Taubin smoothing: no crumpled fold, no shrinking), and
|
||||
the arm moved out from the body (weighted by its arm weight, so the shoulder stays attached) just as far as it takes
|
||||
to clear the torso, the belt and the chest strap (Vest), which used to cut through it.
|
||||
* FACE. The lower face (cheeks, jowls, jaw, down to the collar) is relaxed the same way, falling off to nothing round
|
||||
the eye, lid and brow parts (separate objects, which keep their place on the face), so the decimated skin's facets
|
||||
are gone while the nose, moustache and sockets keep their form. Normals are rebuilt smooth.
|
||||
Vertex count, topology, bone and part names, bones and part transforms are untouched.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
import bpy
|
||||
from mathutils import Vector, Matrix
|
||||
from mathutils.bvhtree import BVHTree
|
||||
|
||||
ARM_GROUPS = ("Arm_L", "Fore_L", "Arm_R", "Fore_R")
|
||||
STRAP_Z = 0.66 # game metres: the height of the chest strap (gc_tripo_crew.gear)
|
||||
STRAP_CLEAR = 0.017 # game metres the arm keeps off the torso skin round the strap (6 mm gap + 7 mm strap + air)
|
||||
BODY_CLEAR = 0.004 # ... and everywhere else
|
||||
MAX_OUT = 0.016 # source units: never further out than this (~2.4 cm in the game)
|
||||
FACE_CAP = 0.005 # game metres: the most the face relaxing moves a vertex
|
||||
DENT_MAX = 0.035 # game metres: the most the torso gives way under an arm
|
||||
ARM_CAP = 0.004 # ... and the shoulder/elbow relaxing
|
||||
|
||||
|
||||
def neighbours(me):
|
||||
n = len(me.vertices)
|
||||
ev = np.zeros(len(me.edges) * 2, np.int32)
|
||||
me.edges.foreach_get("vertices", ev)
|
||||
ev = ev.reshape(-1, 2)
|
||||
nb = [[] for _ in range(n)]
|
||||
for a, b in ev:
|
||||
nb[a].append(b)
|
||||
nb[b].append(a)
|
||||
# as a sparse averaging operator: rows, cols
|
||||
rows = np.concatenate([ev[:, 0], ev[:, 1]])
|
||||
cols = np.concatenate([ev[:, 1], ev[:, 0]])
|
||||
deg = np.bincount(rows, minlength=n).astype(np.float64)
|
||||
return rows, cols, deg
|
||||
|
||||
|
||||
def average(x, rows, cols, deg):
|
||||
acc = np.zeros_like(x)
|
||||
np.add.at(acc, rows, x[cols])
|
||||
d = np.maximum(deg, 1)
|
||||
return acc / (d[:, None] if x.ndim == 2 else d)
|
||||
|
||||
|
||||
def taubin(P, mask, adj, iters, lam=0.55, mu=-0.58):
|
||||
"""Taubin smoothing: Laplacian steps that take off the facets without shrinking the form. mask in [0, 1]."""
|
||||
rows, cols, deg = adj
|
||||
P = P.copy()
|
||||
m = mask[:, None]
|
||||
for _ in range(iters):
|
||||
P += lam * m * (average(P, rows, cols, deg) - P)
|
||||
P += mu * m * (average(P, rows, cols, deg) - P)
|
||||
return P
|
||||
|
||||
|
||||
def smoothstep(a, b, x):
|
||||
t = np.clip((x - a) / (b - a), 0, 1)
|
||||
return t * t * (3 - 2 * t)
|
||||
|
||||
|
||||
def read_weights(body):
|
||||
n = len(body.data.vertices)
|
||||
names = [g.name for g in body.vertex_groups]
|
||||
W = np.zeros((n, len(names)))
|
||||
for v in body.data.vertices:
|
||||
for g in v.groups:
|
||||
W[v.index, g.group] = g.weight
|
||||
return names, W
|
||||
|
||||
|
||||
def write_weights(body, names, W):
|
||||
for i, nm in enumerate(names):
|
||||
vg = body.vertex_groups[nm]
|
||||
idx = np.nonzero(W[:, i] > 0)[0] # (tiny weights pruned in the edited rows only, by the smoothing)
|
||||
vg.remove(list(range(len(body.data.vertices))))
|
||||
for j in idx:
|
||||
vg.add([int(j)], float(W[j, i]), "REPLACE")
|
||||
|
||||
|
||||
def smooth_arm_weights(names, W, T, adj, J):
|
||||
"""More blending in and round the arms: shoulder and elbow bands widened, everything normalised."""
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
arm = sum(W[:, ix[g]] for g in ARM_GROUPS if g in ix)
|
||||
ax = np.abs(T[:, 0])
|
||||
# where the weights may move: the arms and the shoulders round them (not the head, not the legs)
|
||||
# only where the arm already reached (gc_tripo_crew's rules keep it off the chest, the ribs and the neck): the
|
||||
# blend inside that band is evened out, it never spreads onto the chest or the back
|
||||
zone = (arm > 0.004).astype(float)
|
||||
rows, cols, deg = adj
|
||||
Wn = W.copy()
|
||||
for _ in range(10):
|
||||
Wn = Wn + 0.5 * zone[:, None] * (average(Wn, rows, cols, deg) - Wn)
|
||||
# a vertex never gains a bone it had nothing to do with nearby: the head keeps out of the arm and vice versa
|
||||
for g in ("Head", "Top", "Leg_L", "Leg_R", "Shin_L", "Shin_R"):
|
||||
if g in ix:
|
||||
Wn[:, ix[g]] = np.where(zone > 0, np.minimum(Wn[:, ix[g]], np.maximum(W[:, ix[g]], 0)), Wn[:, ix[g]])
|
||||
# an arm's weights stay on its own side
|
||||
for g in ARM_GROUPS:
|
||||
if g in ix:
|
||||
side = 1 if g.endswith("_L") else -1
|
||||
Wn[:, ix[g]] *= (T[:, 0] * side > 0)
|
||||
z = zone > 0
|
||||
Wz = Wn[z]
|
||||
Wz[Wz < 0.004] = 0
|
||||
Wn[z] = Wz / np.maximum(Wz.sum(1, keepdims=True), 1e-9)
|
||||
Wn[~z] = W[~z] # outside the arms nothing changes, not even by rounding
|
||||
return Wn, zone
|
||||
|
||||
|
||||
def lower(T, names, W, piv_src, hang, out):
|
||||
"""T-pose (source units) -> rest pose (source units), linear blend: Arm and Fore both turn by `hang` about the
|
||||
shoulder pivot and move out by `out` (source units) along x; Body/Head/legs stay."""
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
P = T.copy()
|
||||
for s, sx in (("L", 1), ("R", -1)):
|
||||
w = sum(W[:, ix[g]] for g in ("Arm_" + s, "Fore_" + s) if g in ix)
|
||||
R = np.array(Matrix.Rotation(math.radians(sx * hang), 3, "Y"))
|
||||
p = piv_src[s]
|
||||
moved = (T - p) @ R.T + p + np.array([sx * out, 0, 0])
|
||||
P += w[:, None] * (moved - T)
|
||||
return P
|
||||
|
||||
|
||||
def clearance(P, names, W, faces, k, T):
|
||||
"""How deep the arm lies inside the torso, and how close it comes round the strap, game metres. The arm: vertices
|
||||
all arm, past the shoulder (the shoulder itself joins the body, of course)."""
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
arm = sum(W[:, ix[g]] for g in ARM_GROUPS if g in ix)
|
||||
G = P * k
|
||||
torso_f = [f for f in faces if all(arm[v] < 0.05 for v in f)]
|
||||
bvh = BVHTree.FromPolygons([Vector(p) for p in G], torso_f)
|
||||
deep, strap = 0.0, 1.0
|
||||
hits = []
|
||||
for i in np.nonzero((arm > 0.97) & (np.abs(T[:, 0]) > 0.21))[0]:
|
||||
q = Vector(G[i])
|
||||
c, n, _, d = bvh.find_nearest(q)
|
||||
if c is None:
|
||||
continue
|
||||
inside = (q - c).dot(n) < 0
|
||||
depth = d if inside else -d
|
||||
hits.append(depth)
|
||||
if abs(q.z - STRAP_Z) < 0.03:
|
||||
strap = min(strap, -depth)
|
||||
# the deepest few vertices (98th percentile: a stray vertex of a fold does not set the whole arm)
|
||||
deep = float(np.percentile(hits, 98)) if hits else 0.0
|
||||
return deep, strap
|
||||
|
||||
|
||||
def fix_arms(body, names, W, T, J, piv_src, k, hang, adj):
|
||||
Wn, zone = smooth_arm_weights(names, W, T, adj, J)
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
arm_new = sum(Wn[:, ix[g]] for g in ARM_GROUPS if g in ix)
|
||||
# relax the shoulder and the elbow skin (T-pose): bands round the shoulder pivot and the elbow
|
||||
ax = np.abs(T[:, 0])
|
||||
elbow = 0.245
|
||||
sh_band = np.exp(-((ax - 0.15) / 0.035) ** 2) * (arm_new > 0.02)
|
||||
el_band = np.exp(-((ax - elbow) / 0.03) ** 2) * (arm_new > 0.5)
|
||||
mask = np.clip(np.maximum(sh_band, el_band), 0, 1) * 0.9
|
||||
T2 = taubin(T, mask, adj, 10)
|
||||
d = T2 - T
|
||||
ln = np.linalg.norm(d, axis=1, keepdims=True)
|
||||
T2 = T + d * np.minimum(1, (ARM_CAP / k) / np.maximum(ln, 1e-12))
|
||||
faces = [tuple(p.vertices) for p in body.data.polygons]
|
||||
out, best = 0.0, None
|
||||
while True:
|
||||
P = lower(T2, names, Wn, piv_src, hang, out)
|
||||
deep, strap = clearance(P, names, Wn, faces, k, T2)
|
||||
best = (out, deep, strap)
|
||||
if (deep <= BODY_CLEAR * 0.25 and strap >= STRAP_CLEAR) or out >= MAX_OUT:
|
||||
break
|
||||
out = min(MAX_OUT, out + 0.002)
|
||||
print(f" arms: weights smoothed over {int((zone > 0).sum())} vertices; out by {out * k * 100:.1f} cm; "
|
||||
f"deepest in the torso {best[1] * 100:.1f} cm, round the strap {best[2] * 100:.1f} cm clear", flush=True)
|
||||
return T2, P, Wn, out, mask > 0.01
|
||||
|
||||
|
||||
def face_mask(body, T, names, W, eye_parts, k, J):
|
||||
"""The lower face and the jaw down to the collar: Head-weighted skin below the brows, falling off round the eye
|
||||
parts and at the mesh's boundaries (the Director's mouth cut)."""
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
hw = sum(W[:, ix[g]] for g in ("Head", "Top") if g in ix)
|
||||
m = smoothstep(0.05, 0.4, hw)
|
||||
if eye_parts is not None and len(eye_parts):
|
||||
tree = BVHTree.FromPolygons([Vector(p) for p in eye_parts[0]], eye_parts[1])
|
||||
d = np.array([tree.find_nearest(Vector(p))[3] for p in T])
|
||||
eye_z = float(np.mean(eye_parts[0][:, 2]))
|
||||
m *= smoothstep(0.004, 0.022, d)
|
||||
# below the brows only (the hat and the hair keep their edges)
|
||||
m *= 1 - smoothstep(eye_z - 0.01, eye_z + 0.03, T[:, 2])
|
||||
else:
|
||||
m *= 1 - smoothstep(J["neck"] + 0.16, J["neck"] + 0.2, T[:, 2])
|
||||
# fixed: boundary vertices (the mouth cut) and the void faces
|
||||
me = body.data
|
||||
bound = np.zeros(len(me.vertices), bool)
|
||||
import bmesh
|
||||
bm = bmesh.new()
|
||||
bm.from_mesh(me)
|
||||
for v in bm.verts:
|
||||
if v.is_boundary:
|
||||
bound[v.index] = True
|
||||
void = [i for i, mt in enumerate(me.materials) if mt and mt.name.startswith("M_MouthVoid")]
|
||||
for f in bm.faces:
|
||||
if f.material_index in void:
|
||||
for v in f.verts:
|
||||
bound[v.index] = True
|
||||
bm.free()
|
||||
m[bound] = 0
|
||||
return m
|
||||
|
||||
|
||||
def fix_face(body, T, names, W, eye_parts, k, J, adj):
|
||||
m = face_mask(body, T, names, W, eye_parts, k, J)
|
||||
T2 = taubin(T, m * 0.9, adj, 20)
|
||||
# the facets are a millimetre or two deep: nothing moves further than that, so the features keep their form
|
||||
d = T2 - T
|
||||
ln = np.linalg.norm(d, axis=1, keepdims=True)
|
||||
cap = FACE_CAP / k
|
||||
T2 = T + d * np.minimum(1, cap / np.maximum(ln, 1e-12))
|
||||
moved = np.linalg.norm(T2 - T, axis=1) * k
|
||||
print(f" face: {int((m > 0.05).sum())} vertices relaxed, moved {moved.max() * 1000:.1f} mm at most "
|
||||
f"(mean {moved[m > 0.05].mean() * 1000:.1f} mm)", flush=True)
|
||||
return T2, m > 0.01
|
||||
|
||||
|
||||
def smooth_normals(body):
|
||||
me = body.data
|
||||
try:
|
||||
if me.has_custom_normals:
|
||||
with bpy.context.temp_override(object=body, active_object=body, selected_objects=[body]):
|
||||
bpy.ops.mesh.customdata_custom_splitnormals_clear()
|
||||
except Exception as e:
|
||||
print(" (custom normals not cleared:", e, ")", flush=True)
|
||||
for p in me.polygons:
|
||||
p.use_smooth = True
|
||||
for e in me.edges:
|
||||
e.use_edge_sharp = False
|
||||
me.update()
|
||||
|
||||
|
||||
def dent_torso(G, names, W, faces, T, adj):
|
||||
"""Where the hanging arm still comes too close to the torso (bulky chests and bellies), the torso gives way under it:
|
||||
its skin is pressed in, feathered, just far enough for the arm to clear it (and the strap round it). Game metres.
|
||||
Hidden under the arm in the rest pose."""
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
arm = sum(W[:, ix[g]] for g in ARM_GROUPS if g in ix)
|
||||
arm_f = [f for f in faces if all(arm[v] > 0.9 and abs(T[v, 0]) > 0.19 for v in f)]
|
||||
if not arm_f:
|
||||
return G, np.zeros(len(G), bool)
|
||||
tree = BVHTree.FromPolygons([Vector(p) for p in G], arm_f)
|
||||
# the torso's flanks only (skin facing sideways): the chest, the bib and the back keep their place
|
||||
tmp = bpy.data.meshes.new("tmp")
|
||||
tmp.from_pydata([tuple(p) for p in G], [], faces)
|
||||
tmp.update()
|
||||
vn = np.zeros(len(G) * 3, np.float32)
|
||||
tmp.vertex_normals.foreach_get("vector", vn)
|
||||
bpy.data.meshes.remove(tmp)
|
||||
vn = vn.reshape(-1, 3)
|
||||
side = (vn[:, 0] * np.sign(G[:, 0])) > 0.55
|
||||
torso = (arm < 0.05) & (np.abs(G[:, 0]) > 0.08) & (G[:, 2] > 0.3) & (G[:, 2] < 0.85) & side
|
||||
disp = np.zeros_like(G)
|
||||
for _ in range(3):
|
||||
more = 0
|
||||
for i in np.nonzero(torso)[0]:
|
||||
q = Vector(G[i] + disp[i])
|
||||
c, n, _, d = tree.find_nearest(q, 0.08)
|
||||
if c is None:
|
||||
continue
|
||||
# only the arm's inner side, facing the body across the gap, presses the torso (sideways)
|
||||
if abs(n.x) < 0.5 or np.sign(n.x) != -np.sign(G[i, 0]):
|
||||
continue
|
||||
dist = -d if (q - c).dot(n) < 0 else d
|
||||
need = STRAP_CLEAR if abs(q.z - STRAP_Z) < 0.045 else BODY_CLEAR
|
||||
if dist < need:
|
||||
disp[i, 0] -= np.sign(G[i, 0]) * min(need - dist + 0.001, DENT_MAX - abs(disp[i, 0]))
|
||||
more += 1
|
||||
# feathered: the dent spreads to the skin round it, never less than it needs where it needs it
|
||||
rows, cols, deg = adj
|
||||
sm = disp.copy()
|
||||
for _ in range(6):
|
||||
sm = sm + 0.5 * torso[:, None] * (average(sm, rows, cols, deg) - sm)
|
||||
disp = np.where(np.abs(disp) > np.abs(sm), disp, sm)
|
||||
disp = np.clip(disp, -DENT_MAX, DENT_MAX)
|
||||
if not more:
|
||||
break
|
||||
moved = np.linalg.norm(disp, axis=1)
|
||||
print(f" torso pressed in under the arms at {int((moved > 1e-4).sum())} vertices, {moved.max() * 100:.1f} cm at most", flush=True)
|
||||
return G + disp, moved > 1e-6
|
||||
|
||||
|
||||
def regen_strap(vest, G, names, W, faces, o_y):
|
||||
"""The chest strap (Vest) laid round the torso again as gc_tripo_crew.gear does it, on the torso only (game metres)."""
|
||||
import gc_tripo_crew as TC
|
||||
ix = {n: i for i, n in enumerate(names)}
|
||||
arm = sum(W[:, ix[g]] for g in ARM_GROUPS if g in ix)
|
||||
tf = [f for f in faces if all(arm[v] < 0.05 for v in f)]
|
||||
bvh = BVHTree.FromPolygons([Vector(p) for p in G], tf)
|
||||
z = STRAP_Z
|
||||
|
||||
def skin_at(z, a):
|
||||
d = Vector((math.sin(math.radians(a)), -math.cos(math.radians(a)), 0))
|
||||
c = Vector((0, o_y, z))
|
||||
hit = bvh.ray_cast(c, d, 0.6)
|
||||
return hit[0] + d * 0.006 if hit[0] else c + d * 0.2
|
||||
ring = [skin_at(z, a) for a in range(0, 360, 15)]
|
||||
V = [TC.tube("strap", ring + ring[:1], lambda s: (0.024, 0.007), "M_CrewVest", segs=6, per=1, ang=TC.FACET, cap=False)]
|
||||
new = TC.FT.done(V, "VestNew", uv=3.0, ang=TC.FACET)
|
||||
mw = vest.matrix_world.copy()
|
||||
new.data.transform(mw.inverted() @ new.matrix_world)
|
||||
old_me = vest.data
|
||||
vest.data = new.data
|
||||
vest.data.name = old_me.name
|
||||
bpy.data.objects.remove(new)
|
||||
print(f" chest strap laid again round the torso: {len(vest.data.vertices)} vertices (was {len(old_me.vertices)})", flush=True)
|
||||
12
ArtSource/Blender/remaster/crew/scripts/run_all.sh
Normal file
12
ArtSource/Blender/remaster/crew/scripts/run_all.sh
Normal file
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
# GRASS CUTTER crew remaster: the whole chain for the given characters (default: all ten).
|
||||
# sh run_all.sh <scratch dir> [hank lin ...]
|
||||
# stage 1 crew_rebake (shape fixes, unwrap, colour carry, AO) -> stage 2 crew_repaint (textures) ->
|
||||
# stage 3 crew_assemble (.blend, FBX, previews, FBX check). Then crew_review.py builds Crew_Review.blend.
|
||||
S="$1"; shift
|
||||
B="${BLENDER:-C:/Program Files (x86)/Steam/steamapps/common/Blender/blender.exe}"
|
||||
D="$(cd "$(dirname "$0")" && pwd)"
|
||||
for st in crew_rebake crew_repaint crew_assemble; do
|
||||
"$B" -b --factory-startup --python "$D/$st.py" --python-exit-code 1 -- "$S" "$@" > "$S/log_$st.log" 2>&1 || { echo "$st FAILED"; tail -30 "$S/log_$st.log"; exit 1; }
|
||||
done
|
||||
grep -aE "===|arms:|face:|torso pressed|strap laid|borders|dissolved|CHECK|^ " "$S"/log_crew_*.log
|
||||
Reference in New Issue
Block a user