Files
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

425 lines
19 KiB
Python

"""GRASS CUTTER - the G.R.A.S.S.A. Director and his assistant in 3D: SM_Dir_Boss and SM_Dir_Assistant.
The user's two Tripo models (ArtSource/Director/boss.glb, assistant.glb) are T-posed shells like the crew's, so they go
through the crew's pipeline (gc_tripo_crew.py): the skin rebuilt and cut to budget, unwrapped afresh and its colour baked
over, skinned by rule with the arms brought down, and the eyes, lids and brows made parts that move.
On top of that the head is cut straight across at the mouth for the South Park talk: everything above the cut is rigid on
a bone of its own, Top, which the game tips up off one end of the cut and then the other; both cut faces are closed with
a dark void (M_MouthVoid), so what opens is just a dark gap. The face parts ride on Top.
Run (no Unity open):
blender -b --factory-startup --python ArtSource/Blender/scripts/gc_director.py -- [boss assistant]
"""
import sys, os, math
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy, bmesh
import numpy as np
from mathutils import Vector, Matrix
import gc_tripo_crew as TC
import gc_crew_face as FACE
import os_crew as OC
import common
from common import link, reset
TC.SOURCE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "Director")
TC.TRIS = 30000 # seen up close on the phone, never sixteen at once
# the cut, in the source's units: under the moustache (the Director) or under the nose (the assistant)
CUT = {"boss": 0.601, "assistant": 0.69}
HEAD_X = 0.21 # half the head's width, source units: the cut reaches no further out
VOID = "M_MouthVoid"
# where the eyes may be (z from, z to, |x| under): the Director's grey hair reads as white to the eye finder
EYES = {"boss": (0.64, 0.83, 0.165), "assistant": (0.71, 0.83, 0.165)}
# whose eyes become parts that look and blink: the assistant's painted lashes defeat the eye finder, so hers stay painted
MOVING_EYES = {"boss"}
# brown brows (z from, z to, |x| under), for the brow finder
BROWS = {"assistant": (0.795, 0.842, 0.135)}
_photo = FACE._photo
# whose eyes become parts that look and blink: the assistant's painted lashes defeat the eye finder, so hers stay painted
MOVING_EYES = {"boss"}
def _windowed(name):
def photo(o, x0, x1, z0, z1):
Ph = _photo(o, x0, x1, z0, z1)
lo, hi, xm = EYES[name]
X, Z = np.meshgrid(Ph["x"], Ph["z"])
col = Ph["col"]
lum = col.max(2)
sat = (col.max(2) - col.min(2)) / np.maximum(lum, 1e-6)
out = ((Z < lo) | (Z > hi) | (np.abs(X) > xm)) & (lum > 0.6) & (sat < 0.3)
col[out] = col[out] * 0.55 # grey, neither white nor dark
if name in BROWS:
# brown brows read as skin to the brow finder, which wants a dark bar: shaded down to dark where they are
b0, b1, bx = BROWS[name]
red = (col[..., 0] > col[..., 1]) & (col[..., 1] > col[..., 2]) & (lum < 0.5) & (sat > 0.3)
band = (Z > b0) & (Z < b1) & (np.abs(X) < bx) & red
col[band] = col[band] * 0.5
return Ph
return photo
# the Director's glasses (front frame, bridge and arms, as boxes round their pieces in the source): the eye sockets are
# carved where the frame sits, so the frame is put back as it was afterwards
GLASSES = {"boss": [((-0.128, 0.128), (-0.187, -0.174), (0.676, 0.777)), ((0.124, 0.149), (-0.17, 0.054), (0.719, 0.762)),
((-0.149, -0.124), (-0.17, 0.054), (0.719, 0.762))]}
def islands(me):
"""Connected pieces of a mesh as vertex index lists (by its edges, as loaded: split along the UV seams)."""
nb = [[] for _ in me.vertices]
for e in me.edges:
a, b = e.vertices
nb[a].append(b)
nb[b].append(a)
seen, out = [False] * len(nb), []
for i in range(len(nb)):
if seen[i]:
continue
seen[i], st, part = True, [i], [i]
while st:
for j in nb[st.pop()]:
if not seen[j]:
seen[j] = True
st.append(j)
part.append(j)
out.append(part)
return out
def keep_glasses(o, name):
boxes = GLASSES.get(name, [])
kept = {}
for part in islands(o.data):
cs = [o.data.vertices[i].co for i in part]
for (x0, x1), (y0, y1), (z0, z1) in boxes:
if all(x0 <= c.x <= x1 and y0 <= c.y <= y1 and z0 <= c.z <= z1 for c in cs):
kept.update({i: o.data.vertices[i].co.copy() for i in part})
break
print(" glasses kept:", len(kept), "vertices", flush=True)
return kept
def back_wall(rig, zc, xl, xr, yc, k):
"""A dark wall standing up across the middle of the head from the cut: whatever looks in through the open mouth
meets it, not the far side of the head. Hidden in the skull while the mouth is shut."""
h = 0.09 * k
inset = 0.98
xl, xr = xl * inset, xr * inset
verts = [(xl, yc, zc - 0.01), (xr, yc, zc - 0.01), (xr, yc, zc + h), (xl, yc, zc + h)]
me = bpy.data.meshes.new("MouthBack")
me.from_pydata(verts, [], [(0, 1, 2, 3)])
me.materials.append(common.mat(VOID))
ob = link(bpy.data.objects.new("MouthBack", me))
ob.parent = rig
ob.parent_type = "BONE"
ob.parent_bone = "Head"
bpy.context.view_layer.update()
ob.matrix_world = Matrix.Identity(4)
return ob
def headset(o, bm, zc, k):
"""The faces of the headset's microphone round the cut: dark and grey on the baked texture (hair is brown, skin warm),
in front of the face's middle height band. They are left out of the cut, so the mic goes up whole with the top."""
img = next(n.image for n in o.data.materials[0].node_tree.nodes if n.type == "TEX_IMAGE" and n.image)
w, h = img.size
px = np.zeros(w * h * 4, np.float32)
img.pixels.foreach_get(px)
px = px.reshape(h, w, 4)
uv = bm.loops.layers.uv.active
out = set()
for f in bm.faces:
c = f.calc_center_median()
if abs(c.z - zc) > 0.07 * k or abs(c.x) > HEAD_X * k:
continue
u = sum(l[uv].uv.x for l in f.loops) / len(f.loops)
v = sum(l[uv].uv.y for l in f.loops) / len(f.loops)
col = px[min(h - 1, int(v * h)), min(w - 1, int(u * w)), :3]
if col.max() < 0.3 and col.max() - col.min() < 0.08:
out.add(f)
# a speck here and there of dark paint is not the mic: keep only what hangs together in a fair piece
keep, left = set(), set(out)
while left:
f0 = left.pop()
grp, st = [f0], [f0]
while st:
for e in st.pop().edges:
for g in e.link_faces:
if g in left:
left.discard(g)
grp.append(g)
st.append(g)
if len(grp) >= 12:
keep.update(grp)
return keep
# whose headset mic reaches down past the cut (the Director's ends above it, and his dark jacket would read as one)
MIC_CROSSES_CUT = {"assistant"}
def flap(o, rig, zc, k, name):
"""Cuts the head straight across at height zc (under the moustache, so it all goes up with the top), closes both
sides dark, and hangs the top on a new bone, Top. The hinges are the outermost points of the top on either side:
tipped about one of them nothing of the top goes down past the cut, so it never sinks into the jaw."""
bm = bmesh.new()
bm.from_mesh(o.data)
dl = bm.verts.layers.deform.verify()
# only the head and neck of the main skin are cut, not the collar or the shoulders round them, and not a piece of its
# own like the headset's microphone: that goes up with the top whole
pieces = TC.parts(bm)
main = max(pieces, key=len)
gear = headset(o, bm, zc, k) if name in MIC_CROSSES_CUT else set()
near = [f for f in bm.faces if abs(f.calc_center_median().z - zc) < 0.06 * k and abs(f.calc_center_median().x) < HEAD_X * k
and f.verts[0] in main and f not in gear]
geom = list({v for f in near for v in f.verts}) + list({e for f in near for e in f.edges}) + near
res = bmesh.ops.bisect_plane(bm, geom=geom, plane_co=(0, 0, zc), plane_no=(0, 0, 1), dist=1e-6)
cut_edges = [e for e in res["geom_cut"] if isinstance(e, bmesh.types.BMEdge)]
ring = [v.co.copy() for e in cut_edges for v in e.verts]
print(" cut edges:", len(cut_edges), flush=True)
# where the headset's mic was fused to the cheek below the cut, it comes away from it
torn = set()
tear = [e for e in bm.edges if len(e.link_faces) == 2 and (e.link_faces[0] in gear) != (e.link_faces[1] in gear)
and min(f.calc_center_median().z for f in e.link_faces) < zc]
torn = {v for e in tear for v in e.verts}
print(" mic faces:", len(gear), "torn from the cheek along", len(tear), "edges", flush=True)
bmesh.ops.split_edges(bm, edges=cut_edges + tear)
# the top: everything reached from the crown without crossing the cut
crown = max(bm.verts, key=lambda v: v.co.z)
faces, st = set(crown.link_faces), list(crown.link_faces)
while st:
f = st.pop()
for e in f.edges:
for g in e.link_faces:
if g not in faces:
faces.add(g)
st.append(g)
top = {v for f in faces for v in f.verts}
gv = {v for f in gear for v in f.verts}
if gv:
print(" mic spans x %.3f..%.3f z %.3f..%.3f" % (min(v.co.x for v in gv), max(v.co.x for v in gv), min(v.co.z for v in gv), max(v.co.z for v in gv)), flush=True)
# the mic may hang below the cut; nothing else of the top may
low = min((v.co.z for v in top if v not in gv), default=zc)
loose = 0
for p in pieces:
if p is main:
continue
if max(v.co.z for v in p) > zc and all(abs(v.co.x) < HEAD_X * k * 1.6 for v in p):
top |= p
loose += 1
print(f" {loose} loose pieces go up with the top", flush=True)
print(f" top: {len(top)} verts of {len(bm.verts)}, lowest {low:.3f} (cut {zc:.3f})", flush=True)
if low < zc - 1e-3 or len(top) > len(bm.verts) * 0.5:
raise RuntimeError("the cut does not part the head from the body")
# close the cut strands of hair beside the face in their own colour; the mouth itself is left open: nothing there
bound = [e for e in bm.edges if e.is_boundary and ((abs(e.verts[0].co.z - zc) < 1e-4 and abs(e.verts[1].co.z - zc) < 1e-4)
or any(v in torn for v in e.verts))]
before = set(bm.faces)
bmesh.ops.holes_fill(bm, edges=bound, sides=0)
new = [f for f in bm.faces if f not in before]
bmesh.ops.triangulate(bm, faces=new)
new = [f for f in bm.faces if f not in before]
names = [m.name for m in o.data.materials]
if VOID not in names:
o.data.materials.append(common.mat(VOID))
names = [m.name for m in o.data.materials]
vi = names.index(VOID)
# each hole's cap on its own: the big one round the neck is the mouth, dark; the little ones are strands of hair
# cut through beside the face, which close in their own colour (each corner takes the colour of the skin next to it)
caps, left = [], set(new)
while left:
f0 = left.pop()
grp, st = [f0], [f0]
while st:
for e in st.pop().edges:
for g in e.link_faces:
if g in left:
left.discard(g)
grp.append(g)
st.append(g)
caps.append(grp)
caps.sort(key=lambda g: -sum(f.calc_area() for f in g))
uv = bm.loops.layers.uv.active
mouth, gone = 0, []
for n, grp in enumerate(caps):
# the mouth: the two biggest caps (one each side of the cut), anything near as big as them, and anything in the middle
cx = sum(f.calc_center_median().x for f in grp) / len(grp)
big = n < 2 or sum(f.calc_area() for f in grp) > 0.3 * sum(f.calc_area() for f in caps[0])
if (big or abs(cx) < 0.06 * k) and not any(v in torn for f in grp for v in f.verts):
gone.extend(grp)
mouth += len(grp)
continue
for f in grp:
f.material_index = 0
f.smooth = True
for l in f.loops:
# the UV of an old face at this corner
old = next((x for x in l.vert.link_loops if x.face not in new), None)
if old is not None:
l[uv].uv = old[uv].uv
bmesh.ops.delete(bm, geom=gone, context="FACES_ONLY")
print(" caps:", len(caps), "; left open in the mouth:", mouth, "faces", flush=True)
gi = o.vertex_groups.new(name="Top").index
for v in top:
v[dl].clear()
v[dl][gi] = 1.0
xl, xr = min(v.co.x for v in top), max(v.co.x for v in top)
bm.to_mesh(o.data)
bm.free()
yc = (min(c.y for c in ring) + max(c.y for c in ring)) / 2
bpy.context.view_layer.objects.active = rig
bpy.ops.object.mode_set(mode="EDIT")
b = rig.data.edit_bones.new("Top")
b.head, b.tail = Vector((0, yc, zc)), Vector((0, yc, zc + 0.15))
b.roll = 0
b.parent = rig.data.edit_bones["Head"]
b.use_connect = False
bpy.ops.object.mode_set(mode="OBJECT")
# the face parts ride on it
for x in list(bpy.context.scene.objects):
if x.parent == rig and x.parent_type == "BONE" and x.parent_bone == "Head":
mw = x.matrix_world.copy()
x.parent_bone = "Top"
bpy.context.view_layer.update()
x.matrix_world = mw
# the two hinges, for the game: empties on the Head bone at the cut's height, out at the top's widest
for nm, x in (("Hinge_R", xl), ("Hinge_L", xr)):
e = link(bpy.data.objects.new(nm, None))
e.empty_display_size = 0.03
e.parent = rig
e.parent_type = "BONE"
e.parent_bone = "Head"
bpy.context.view_layer.update()
e.matrix_world = Matrix.Translation((x, yc, zc))
bpy.context.view_layer.update()
rx = [c.x for c in ring]
print(f" Top at z {zc:.3f} y {yc:.3f}; cut spans x {min(rx):.3f}..{max(rx):.3f}; hinges at x {xl:.3f}, {xr:.3f}", flush=True)
return xl, xr
# the painted eyes where they don't become parts (source units: x of the left one, y of its front, z)
PAINTED_EYES = {"assistant": (0.058, -0.127, 0.77)}
def anchors(o, rig, name, F, k):
"""Empties on Top where the game puts its effects: Anchor_Forehead (the anger vein), Anchor_Ear_L/R (steam),
Anchor_Eye_L/R (tears), Anchor_Temple (sweat). Found on the mesh with rays, so they sit on the skin."""
from mathutils.bvhtree import BVHTree
bvh = BVHTree.FromPolygons([v.co for v in o.data.vertices], [tuple(p.vertices) for p in o.data.polygons])
if F:
e = next(e for e in F["eyes"] if e["side"] == "L")
ex, ey, ez = abs(e["c"][0]) * k, (e["c"][1] - e["r"]) * k, e["c"][2] * k
else:
ex, ey, ez = (c * k for c in PAINTED_EYES[name])
def front(x, z):
h = bvh.ray_cast(Vector((x, -3.0, z)), Vector((0, 1, 0)), 6.0)
return h[0] if h[0] is not None else Vector((x, ey, z))
def side(sx, z):
h = bvh.ray_cast(Vector((sx * 3.0, 0.0, z)), Vector((-sx, 0, 0)), 6.0)
return h[0] if h[0] is not None else Vector((sx * 0.25 * k, 0, z))
pts = {"Anchor_Forehead": front(0.0, ez + 0.075 * k), "Anchor_Temple": front(0.115 * k, ez + 0.045 * k),
"Anchor_Eye_L": Vector((ex, ey, ez)), "Anchor_Eye_R": Vector((-ex, ey, ez)),
"Anchor_Ear_L": side(1, ez - 0.02 * k), "Anchor_Ear_R": side(-1, ez - 0.02 * k)}
for nm, at in pts.items():
x = link(bpy.data.objects.new(nm, None))
x.empty_display_size = 0.02
x.parent = rig
x.parent_type = "BONE"
x.parent_bone = "Top"
bpy.context.view_layer.update()
x.matrix_world = Matrix.Translation(at)
print(f" {nm} at {tuple(round(c, 3) for c in at)}", flush=True)
bpy.context.view_layer.update()
def director(name):
o = TC.load(name)
F = None
if name in MOVING_EYES:
FACE._photo = _windowed(name)
F = FACE.measure(o)
FACE._photo = _photo
kept = keep_glasses(o, name)
FACE.carve(o, F)
for i, c in kept.items():
o.data.vertices[i].co = c
full = TC.thin(o)
TC.bake(name, o, full, (lambda pos, out, hit: FACE.repaint(F, pos, out, hit)) if F else None)
J = TC.measure(full)
bpy.data.objects.remove(full)
k = TC.SHOULDER / J["arm_z"]
W = TC.soften(o, TC.weights(o, J))
TC.lower_arms(o, W, J)
o.data.transform(Matrix.Scale(k, 4))
rig = TC.rig_it(o, W, J, k)
if F:
FACE.build(name, F, k, o, rig)
l, r = flap(o, rig, CUT[name] * k, k, name)
anchors(o, rig, name, F, k)
o.name = o.data.name = "DirBody"
print(name, "joints", {a: round(b, 3) for a, b in J.items()}, "k", round(k, 3), "tris", len(o.data.polygons),
"hinge x", round(l, 3), round(r, 3), flush=True)
return o, rig, (l, r, CUT[name] * k)
def hinge_pose(rig, l, r, side, ang):
"""Top tipped up by ang degrees about the end of the cut on `side` (-1 its right end, at x l; +1 its left, at x r)."""
pb = rig.pose.bones["Top"]
if not side:
pb.matrix_basis = Matrix.Identity(4)
return
bone = rig.data.bones["Top"]
pivot = Vector((l if side < 0 else r, bone.head_local.y, bone.head_local.z))
# a turn about +Y takes +x down: hinged at the low-x end the rest goes up by a turn about -Y, and the other way round
R = Matrix.Rotation(math.radians(ang) * (-1 if side < 0 else 1), 4, "Y")
rel = Matrix.Translation(pivot) @ R @ Matrix.Translation(-pivot)
pb.matrix_basis = bone.matrix_local.inverted() @ rel @ bone.matrix_local
bpy.context.view_layer.update()
def shots(name, rig, hinge):
"""Front close-ups: at rest, the top tipped off one end, then off the other, and the whole figure."""
l, r, zc = hinge
sc = bpy.context.scene
engines = [e.identifier for e in bpy.types.RenderSettings.bl_rna.properties["engine"].enum_items]
sc.render.engine = "BLENDER_EEVEE_NEXT" if "BLENDER_EEVEE_NEXT" in engines else "BLENDER_EEVEE"
sc.render.resolution_x = sc.render.resolution_y = 700
w = bpy.data.worlds.new("w")
sc.world = w
w.use_nodes = True
w.node_tree.nodes["Background"].inputs[0].default_value = (0.2, 0.26, 0.36, 1)
sun = link(bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN")))
sun.rotation_euler = (math.radians(55), 0, math.radians(25))
sun.data.energy = 3.5
d = bpy.data.cameras.new("c")
d.lens = 85
cam = link(bpy.data.objects.new("c", d))
sc.camera = cam
head = rig.matrix_world @ rig.data.bones["Top"].head_local
look = Vector((0, 0, head.z + 0.06))
cam.location = look + Vector((0.25, -2.6, 0.05))
cam.rotation_euler = (look - cam.location).to_track_quat("-Z", "Y").to_euler()
out = common.PREVIEWS
for tag, side, ang in (("rest", 0, 0), ("open_a", -1, 16), ("open_b", 1, 16)):
hinge_pose(rig, l, r, side, ang)
sc.render.filepath = os.path.join(out, f"Dir_{name}_{tag}.png")
bpy.ops.render.render(write_still=True)
hinge_pose(rig, l, r, 0, 0)
cam.location = Vector((0.7, -4.6, 0.85))
cam.rotation_euler = (Vector((0, 0, 0.75)) - cam.location).to_track_quat("-Z", "Y").to_euler()
sc.render.filepath = os.path.join(out, f"Dir_{name}_full.png")
bpy.ops.render.render(write_still=True)
if __name__ == "__main__":
args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
common.PREVIEWS = os.environ.get("GC_PREVIEWS", common.PREVIEWS)
for nm in (args or ("boss", "assistant")):
reset()
o, rig, hinge = director(nm)
OC.pose(rig, {})
OC.export_rigged("SM_Dir_" + nm.capitalize())
shots(nm, rig, hinge)