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