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>
750 lines
34 KiB
Python
750 lines
34 KiB
Python
"""GRASS CUTTER - the eight crew members: SM_Crew_Hank and the others, made from the models in ArtSource/Crew.
|
|
|
|
Each source is one textured shell in a T-pose, one unit tall, with no bones, its texture shattered into thousands of tiny
|
|
islands that would bleed into each other in the mipmaps. Here it is cut down to a game budget, unwrapped afresh and baked
|
|
from the full model, skinned by rule from joints measured on the mesh itself, and its arms are brought down, so it stands
|
|
in the pose CrewAvatar expects. The rig keeps the names CrewAvatar looks up (Rig, Root, Body, Leg_L, Leg_R,
|
|
Arm_L, Arm_R), adding Head, Shin_L, Shin_R, Fore_L, Fore_R and the two sockets Hand_L and Hand_R. The eyes, lids and brows
|
|
are taken off the skin and put back as rigid parts on the Head bone (gc_crew_face.py): EyeBall_L/R, Lid_L/R, LidLow_L/R,
|
|
Brow_L/R, with close-ups in Face_<name>_{rest,blink,look,brows}.png.
|
|
Run:
|
|
blender -b --factory-startup --python ArtSource/Blender/scripts/gc_tripo_crew.py -- [hank otis ...]
|
|
"""
|
|
import sys, os, math
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
import bpy, bmesh
|
|
from mathutils import Vector, Matrix
|
|
from mathutils.bvhtree import BVHTree
|
|
import numpy as np
|
|
import os_crew as OC
|
|
import common
|
|
import gc_farm_tools as FT
|
|
import gc_crew_face as FACE
|
|
from gc_up_crew import * # noqa: F401,F403
|
|
|
|
ROSTER = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji")
|
|
SOURCE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "Crew")
|
|
TEXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "Assets", "Art", "Textures")
|
|
MAP = 2048
|
|
VOXEL = 0.0028 # of the source's one unit: under a centimetre of the game's, finer than a shirt button
|
|
TRIS = 18000 # each, with sixteen of them on a field
|
|
SHOULDER = 0.80 # metres from the ground: everyone's arms start here, whatever the hat adds on top
|
|
HANG = 78 # degrees the arms come down from the T
|
|
PEEL = 0.004 # how far outside the game skin the colour is looked for: more than the cut moves the surface
|
|
|
|
|
|
def smooth01(a, b, x):
|
|
t = max(0.0, min(1.0, (x - a) / (b - a)))
|
|
return t * t * (3 - 2 * t)
|
|
|
|
|
|
def load(name):
|
|
"""The shell, standing on the ground, one merged skin, cut down to budget. Saves its texture for Unity."""
|
|
bpy.ops.import_scene.gltf(filepath=os.path.join(SOURCE, name + ".glb"))
|
|
o = next(x for x in bpy.context.scene.objects if x.type == "MESH")
|
|
for x in list(bpy.context.scene.objects):
|
|
if x != o and x.type == "EMPTY":
|
|
bpy.data.objects.remove(x)
|
|
o.parent = None
|
|
o.data.transform(o.matrix_world)
|
|
o.matrix_world = Matrix.Identity(4)
|
|
o.name = o.data.name = "CrewBody"
|
|
# what the bake reads: the painted colour and nothing else
|
|
nt = o.data.materials[0].node_tree
|
|
bsdf = nt.nodes["Principled BSDF"]
|
|
tex = bsdf.inputs["Base Color"].links[0].from_node
|
|
fixed = os.path.join(SOURCE, name + "_basecolor.jpg")
|
|
if os.path.exists(fixed):
|
|
tex.image = bpy.data.images.load(fixed)
|
|
nt.links.new(tex.outputs["Color"], bsdf.inputs["Emission Color"])
|
|
bsdf.inputs["Emission Strength"].default_value = 1.0
|
|
return o
|
|
|
|
|
|
def parts(bm):
|
|
seen, out = set(), []
|
|
for v in bm.verts:
|
|
if v in seen:
|
|
continue
|
|
part, st = {v}, [v]
|
|
while st:
|
|
for e in st.pop().link_edges:
|
|
w = e.verts[1] if e.verts[0] in part else e.verts[0]
|
|
if w not in part:
|
|
part.add(w)
|
|
st.append(w)
|
|
seen |= part
|
|
out.append(part)
|
|
return out
|
|
|
|
|
|
def rebuild(o):
|
|
bpy.context.view_layer.objects.active = o
|
|
md = o.modifiers.new("skin", "REMESH")
|
|
md.mode = "VOXEL"
|
|
md.voxel_size = VOXEL
|
|
md.adaptivity = 0.0
|
|
bpy.ops.object.modifier_apply(modifier=md.name)
|
|
|
|
|
|
def cut(o, tris):
|
|
bpy.context.view_layer.objects.active = o
|
|
md = o.modifiers.new("thin", "DECIMATE")
|
|
md.ratio = min(1.0, tris / max(1, sum(len(p.vertices) - 2 for p in o.data.polygons)))
|
|
md.use_collapse_triangulate = True
|
|
bpy.ops.object.modifier_apply(modifier=md.name)
|
|
|
|
|
|
def enclosed(o):
|
|
"""Takes away what can't see out in any direction: the inside of a head or a body whose shell was open somewhere. It
|
|
would never show, and it would spend the polygons and the texture on nothing."""
|
|
dirs = [Vector((x, y, z)).normalized() for x in (-1, 0, 1) for y in (-1, 0, 1) for z in (-1, 0, 1) if x or y or z]
|
|
bm = bmesh.new()
|
|
bm.from_mesh(o.data)
|
|
bm.normal_update()
|
|
tree = BVHTree.FromBMesh(bm)
|
|
shut = set()
|
|
for v in bm.verts:
|
|
at = v.co + v.normal * 0.002
|
|
if all(tree.ray_cast(at, d)[0] is not None for d in dirs):
|
|
shut.add(v)
|
|
gone = [f for f in bm.faces if all(v in shut for v in f.verts)]
|
|
print(" faces that can't see out:", len(gone), "of", len(bm.faces), flush=True)
|
|
bmesh.ops.delete(bm, geom=gone, context="FACES")
|
|
bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context="VERTS")
|
|
bmesh.ops.holes_fill(bm, edges=[e for e in bm.edges if e.is_boundary], sides=0)
|
|
bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3])
|
|
for part in parts(bm):
|
|
if len(part) < 40:
|
|
bmesh.ops.delete(bm, geom=list(part), context="VERTS")
|
|
bm.to_mesh(o.data)
|
|
bm.free()
|
|
|
|
|
|
def hollow(o):
|
|
"""Removes every separate piece of the skin that lies inside another: an odd number of walls on the way out."""
|
|
bm = bmesh.new()
|
|
bm.from_mesh(o.data)
|
|
ps = parts(bm)
|
|
bm.verts.ensure_lookup_table()
|
|
bm.faces.ensure_lookup_table()
|
|
tree = BVHTree.FromBMesh(bm)
|
|
drop = []
|
|
for part in ps:
|
|
p = next(iter(part)).co + Vector((1e-4, 2e-4, 0))
|
|
d, n, at = Vector((0.31, 0.17, 0.93)).normalized(), 0, p
|
|
while True:
|
|
hit = tree.ray_cast(at + d * 1e-5, d)
|
|
if hit[0] is None:
|
|
break
|
|
at = hit[0]
|
|
if bm.faces[hit[2]].verts[0] not in part:
|
|
n += 1
|
|
if n % 2 or len(part) < 40:
|
|
drop.append(part)
|
|
print(" rebuilt skin:", len(ps), "pieces, dropped", len(drop), flush=True)
|
|
for part in drop:
|
|
bmesh.ops.delete(bm, geom=list(part), context="VERTS")
|
|
bm.to_mesh(o.data)
|
|
bm.free()
|
|
|
|
|
|
def thin(o):
|
|
"""Leaves o at the budget, and returns the full shell it was cut from."""
|
|
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()
|
|
full = o.copy()
|
|
full.data = o.data.copy()
|
|
full.name = "Full"
|
|
link(full)
|
|
bpy.context.view_layer.objects.active = o
|
|
# the shell has holes, flipped faces, loose pieces and bits inside: a skin rebuilt over it has none of that, and the
|
|
# colour comes across from the full shell afterwards, so nothing depends on the old surface. Voxels lose a thin open
|
|
# brim altogether, so the shell is thickened first; the hollow that leaves inside the body goes
|
|
md = o.modifiers.new("thick", "SOLIDIFY")
|
|
md.thickness = 0.0045
|
|
md.offset = 0.0
|
|
bpy.ops.object.modifier_apply(modifier=md.name)
|
|
rebuild(o)
|
|
hollow(o)
|
|
cut(o, 70000)
|
|
enclosed(o)
|
|
# the generator leaves a skin on the ground between the feet, and the thickening welds boots that nearly touch: either
|
|
# would stretch with every step, so the legs are parted down the middle, right down to the ground
|
|
bm = bmesh.new()
|
|
bm.from_mesh(o.data)
|
|
web = [f for f in bm.faces if f.calc_center_median().z < 0.14 and abs(f.calc_center_median().x) < 0.0045]
|
|
print(" parted the legs across", len(web), "faces of", len(bm.faces), flush=True)
|
|
bmesh.ops.delete(bm, geom=web, context="FACES")
|
|
bmesh.ops.holes_fill(bm, edges=[e for e in bm.edges if e.is_boundary], sides=0)
|
|
bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 4])
|
|
bm.to_mesh(o.data)
|
|
bm.free()
|
|
# an even skin gives its polygons to whatever is curved: the eyes and the mouth keep theirs without being told
|
|
cut(o, TRIS)
|
|
bm = bmesh.new()
|
|
bm.from_mesh(o.data)
|
|
# the cut leaves specks floating, and slivers with no area to shade
|
|
for part in parts(bm):
|
|
if len(part) < 40:
|
|
bmesh.ops.delete(bm, geom=list(part), context="VERTS")
|
|
bmesh.ops.dissolve_degenerate(bm, dist=1e-5, edges=bm.edges)
|
|
# an edge held by more than two faces is cut out and closed again
|
|
for _ in range(3):
|
|
wild = {f for e in bm.edges if len(e.link_faces) > 2 for f in e.link_faces}
|
|
if not wild:
|
|
break
|
|
bmesh.ops.delete(bm, geom=list(wild), context="FACES")
|
|
bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context="VERTS")
|
|
bmesh.ops.holes_fill(bm, edges=[e for e in bm.edges if e.is_boundary], sides=0)
|
|
bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3])
|
|
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
|
|
bm.to_mesh(o.data)
|
|
bm.free()
|
|
for p in o.data.polygons:
|
|
p.use_smooth = True
|
|
return full
|
|
|
|
|
|
def bake(name, o, full, fix=None):
|
|
"""A fresh unwrap for o, and the colour of the full shell carried over onto it along the surface."""
|
|
sc = bpy.context.scene
|
|
for x in sc.objects:
|
|
x.select_set(False)
|
|
o.select_set(True)
|
|
bpy.context.view_layer.objects.active = o
|
|
for u in list(o.data.uv_layers):
|
|
o.data.uv_layers.remove(u)
|
|
o.data.uv_layers.new(name="UVMap")
|
|
bpy.ops.object.mode_set(mode="EDIT")
|
|
bpy.ops.mesh.select_all(action="SELECT")
|
|
bpy.ops.uv.smart_project(angle_limit=math.radians(88), island_margin=0.0, area_weight=0.6, scale_to_bounds=True)
|
|
# a projection lays an eyelid and the eye under it on the same spot, and whichever is painted last wins both: the
|
|
# projection's islands are only cuts, each is opened out flat again
|
|
bpy.ops.uv.select_all(action="SELECT")
|
|
bpy.ops.uv.seams_from_islands(mark_seams=True)
|
|
bpy.ops.uv.unwrap(method="MINIMUM_STRETCH", margin=0.0)
|
|
bpy.ops.object.mode_set(mode="OBJECT")
|
|
# that solver now and then folds a whole island down to a line (it did a planed face): those islands are opened
|
|
# out again by angles
|
|
flat = collapsed(o)
|
|
print(" faces folded flat on the map:", len(flat), flush=True)
|
|
bpy.ops.object.mode_set(mode="EDIT")
|
|
if flat:
|
|
bm = bmesh.from_edit_mesh(o.data)
|
|
bm.faces.ensure_lookup_table()
|
|
for f in bm.faces:
|
|
f.select_set(False)
|
|
for i in flat:
|
|
bm.faces[i].select_set(True)
|
|
bm.select_flush(True)
|
|
bmesh.update_edit_mesh(o.data)
|
|
bpy.ops.mesh.select_linked(delimit={"SEAM"})
|
|
bpy.ops.uv.select_all(action="SELECT")
|
|
bpy.ops.uv.unwrap(method="ANGLE_BASED", margin=0.0)
|
|
bpy.ops.mesh.select_all(action="SELECT")
|
|
bpy.ops.uv.select_all(action="SELECT")
|
|
bpy.ops.uv.average_islands_scale()
|
|
bpy.ops.uv.pack_islands(rotate=True, margin_method="FRACTION", margin=0.003, shape_method="CONCAVE")
|
|
bpy.ops.object.mode_set(mode="OBJECT")
|
|
if flat:
|
|
print(" still folded after that:", len(collapsed(o)), flush=True)
|
|
# whatever still lies on top of something else is cut loose a face at a time and packed again
|
|
for _ in range(8):
|
|
crossed = overlaps(o)
|
|
print(" faces sharing the map:", len(crossed), flush=True)
|
|
if not crossed:
|
|
break
|
|
bpy.ops.object.mode_set(mode="EDIT")
|
|
bm = bmesh.from_edit_mesh(o.data)
|
|
bm.faces.ensure_lookup_table()
|
|
for f in bm.faces:
|
|
f.select_set(False)
|
|
for i in crossed:
|
|
bm.faces[i].select_set(True)
|
|
bm.select_flush(True)
|
|
bmesh.update_edit_mesh(o.data)
|
|
bpy.ops.mesh.mark_seam(clear=False)
|
|
bpy.ops.uv.select_all(action="SELECT")
|
|
bpy.ops.uv.unwrap(method="MINIMUM_STRETCH", margin=0.0)
|
|
bpy.ops.mesh.select_all(action="SELECT")
|
|
bpy.ops.uv.select_all(action="SELECT")
|
|
bpy.ops.uv.average_islands_scale()
|
|
bpy.ops.uv.pack_islands(rotate=True, margin_method="FRACTION", margin=0.003, shape_method="CONCAVE")
|
|
bpy.ops.object.mode_set(mode="OBJECT")
|
|
img = bpy.data.images.new("T_Crew_" + name.capitalize(), MAP, MAP, alpha=False)
|
|
m = bpy.data.materials.new("M_Crew_" + name.capitalize())
|
|
m.use_nodes = True
|
|
n = m.node_tree.nodes.new("ShaderNodeTexImage")
|
|
n.image = img
|
|
m.node_tree.links.new(n.outputs["Color"], m.node_tree.nodes["Principled BSDF"].inputs["Base Color"])
|
|
m.node_tree.nodes.active = n
|
|
o.data.materials.clear()
|
|
o.data.materials.append(m)
|
|
img.pixels.foreach_set(carry(o, full, fix).ravel())
|
|
img.filepath_raw = os.path.join(TEXTURES, img.name + ".png")
|
|
img.file_format = "PNG"
|
|
img.save()
|
|
for x in sc.objects:
|
|
x.select_set(False)
|
|
|
|
|
|
def texels(me):
|
|
"""Each triangle of me on the map: its index, the texels it reaches with a shade over each edge, their barycentric
|
|
weights and how far inside the triangle each one is (negative in the shade)."""
|
|
me.calc_loop_triangles()
|
|
tris = me.loop_triangles
|
|
luv = np.zeros(len(me.loops) * 2, np.float32)
|
|
me.uv_layers.active.data.foreach_get("uv", luv)
|
|
luv = luv.reshape(-1, 2).astype(np.float64) * MAP - 0.5
|
|
tl = np.zeros(len(tris) * 3, np.int32)
|
|
tris.foreach_get("loops", tl)
|
|
tl = tl.reshape(-1, 3)
|
|
for t in range(len(tl)):
|
|
u = luv[tl[t]]
|
|
x0, y0 = np.floor(u.min(0)).astype(int) - 1
|
|
x1, y1 = np.ceil(u.max(0)).astype(int) + 2
|
|
x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, MAP), min(y1, MAP)
|
|
if x0 >= x1 or y0 >= y1:
|
|
continue
|
|
gx, gy = np.meshgrid(np.arange(x0, x1), np.arange(y0, y1))
|
|
e0, e1 = u[1] - u[0], u[2] - u[0]
|
|
det = e0[0] * e1[1] - e0[1] * e1[0]
|
|
if abs(det) < 1e-9:
|
|
continue
|
|
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
|
|
ok = (b0 >= -0.03) & (b1 >= -0.03) & (b2 >= -0.03)
|
|
yield t, gy[ok], gx[ok], b0[ok], b1[ok], b2[ok], np.minimum(np.minimum(b0, b1), b2)[ok]
|
|
|
|
|
|
def collapsed(o):
|
|
"""Faces with a fair size on the model and next to none on the map."""
|
|
me = o.data
|
|
me.calc_loop_triangles()
|
|
uv = np.zeros(len(me.loops) * 2, np.float32)
|
|
me.uv_layers.active.data.foreach_get("uv", uv)
|
|
uv = uv.reshape(-1, 2)
|
|
out = set()
|
|
for t in me.loop_triangles:
|
|
a, b, c = (uv[l] for l in t.loops)
|
|
if abs((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) < 1e-10 and t.area > 1e-7:
|
|
out.add(t.polygon_index)
|
|
return sorted(out)
|
|
|
|
|
|
def overlaps(o):
|
|
"""The faces of o that share a texel of the map with another face, inside both of them."""
|
|
me = o.data
|
|
count = np.zeros((MAP, MAP), np.int32)
|
|
for t, gy, gx, b0, b1, b2, ins in texels(me):
|
|
count[gy[ins > 0], gx[ins > 0]] += 1
|
|
tris = me.loop_triangles
|
|
return {tris[t].polygon_index for t, gy, gx, b0, b1, b2, ins in texels(me) if (count[gy[ins > 0], gx[ins > 0]] > 1).any()}
|
|
|
|
|
|
def carry(o, full, fix=None):
|
|
"""Every texel of o takes the colour of the full shell where a ray from just outside o, straight in, first meets it, or
|
|
failing that of the nearest point on it."""
|
|
me = o.data
|
|
vco = np.zeros(len(me.vertices) * 3, np.float32)
|
|
me.vertices.foreach_get("co", vco)
|
|
vco = vco.reshape(-1, 3).astype(np.float64)
|
|
vno = np.zeros(len(me.vertices) * 3, np.float32)
|
|
me.vertex_normals.foreach_get("vector", vno)
|
|
vno = vno.reshape(-1, 3).astype(np.float64)
|
|
pos = np.zeros((MAP, MAP, 3), np.float64)
|
|
nor = np.zeros((MAP, MAP, 3), np.float64)
|
|
hit = np.zeros((MAP, MAP), bool)
|
|
best = np.full((MAP, MAP), -1.0)
|
|
for t, gy, gx, b0, b1, b2, ins in texels(me):
|
|
# the shade over each edge keeps anything from falling between two triangles, but never takes a texel that lies
|
|
# further inside another
|
|
ok = ins > best[gy, gx]
|
|
gy, gx = gy[ok], gx[ok]
|
|
best[gy, gx] = ins[ok]
|
|
vs = list(me.loop_triangles[t].vertices)
|
|
p, n = vco[vs], vno[vs]
|
|
pos[gy, gx] = b0[ok, None] * p[0] + b1[ok, None] * p[1] + b2[ok, None] * p[2]
|
|
w = b0[ok, None] * n[0] + b1[ok, None] * n[1] + b2[ok, None] * n[2]
|
|
nor[gy, gx] = w / np.maximum(np.linalg.norm(w, axis=1), 1e-9)[:, None]
|
|
hit[gy, gx] = True
|
|
# the full shell, as triangles
|
|
hi = full.data
|
|
hi.calc_loop_triangles()
|
|
hv = [v.co.copy() for v in hi.vertices]
|
|
bvh = BVHTree.FromPolygons(hv, [tuple(t.vertices) for t in hi.loop_triangles], all_triangles=True)
|
|
hco = np.array([tuple(c) for c in hv])
|
|
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)
|
|
htv = np.array([tuple(t.vertices) for t in hi.loop_triangles])
|
|
htl = np.array([tuple(t.loops) for t in hi.loop_triangles])
|
|
src = hi.materials[0].node_tree.nodes["Principled BSDF"].inputs["Base Color"].links[0].from_node.image
|
|
sw, sh = src.size
|
|
sp = np.zeros(sw * sh * 4, np.float32)
|
|
src.pixels.foreach_get(sp)
|
|
sp = sp.reshape(sh, sw, 4)[..., :3]
|
|
ys, xs = np.nonzero(hit)
|
|
pts = pos[ys, xs]
|
|
near = np.zeros((len(pts), 3))
|
|
tri = np.zeros(len(pts), np.int32)
|
|
find, ray = bvh.find_nearest, bvh.ray_cast
|
|
for i, q in enumerate(pts):
|
|
q = Vector(q)
|
|
n = Vector(nor[ys[i], xs[i]])
|
|
# what is seen from just outside, along the surface: the nearest point can be a layer under it, the eye under a
|
|
# highlight painted on a shell of its own
|
|
r = ray(q + n * PEEL, -n, PEEL * 2) if n.length > 0.5 else (None,)
|
|
if r[0] is None:
|
|
r = find(q)
|
|
near[i] = r[0]
|
|
tri[i] = r[2]
|
|
a, b, c = hco[htv[tri, 0]], hco[htv[tri, 1]], hco[htv[tri, 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
|
|
uv = ba[:, None] * huv[htl[tri, 0]] + bb[:, None] * huv[htl[tri, 1]] + bc[:, None] * huv[htl[tri, 2]]
|
|
fx, fy = uv[:, 0] * sw - 0.5, uv[:, 1] * sh - 0.5
|
|
ix, iy = np.clip(np.floor(fx).astype(int), 0, sw - 2), np.clip(np.floor(fy).astype(int), 0, sh - 2)
|
|
tx, ty = (fx - ix)[:, None], (fy - iy)[:, None]
|
|
col = (sp[iy, ix] * (1 - tx) + sp[iy, ix + 1] * tx) * (1 - ty) + (sp[iy + 1, ix] * (1 - tx) + sp[iy + 1, ix + 1] * tx) * ty
|
|
out = np.zeros((MAP, MAP, 3), np.float32)
|
|
out[ys, xs] = col
|
|
if fix:
|
|
fix(pos, out, hit)
|
|
# padding, so the mipmaps never reach the gaps between islands
|
|
known = hit.copy()
|
|
for _ in range(14):
|
|
k = known.astype(np.float32)
|
|
tot, cnt = np.zeros_like(out), np.zeros((MAP, MAP), np.float32)
|
|
for sy, sx in ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)):
|
|
tot += np.roll(out * k[..., None], (sy, sx), (0, 1))
|
|
cnt += np.roll(k, (sy, sx), (0, 1))
|
|
new = ~known & (cnt > 0)
|
|
out[new] = tot[new] / cnt[new][:, None]
|
|
known |= new
|
|
print(" carried", len(pts), "texels, surface used", round(100 * hit.mean()), "%", flush=True)
|
|
return np.dstack((out, np.ones((MAP, MAP), np.float32)))
|
|
|
|
|
|
def compare(name, o, full):
|
|
"""The same camera on the full model and the game one, in plain texture colour, for check_crew_pictures.py."""
|
|
sc = bpy.context.scene
|
|
sc.render.engine = "BLENDER_WORKBENCH"
|
|
sc.display.shading.light = "FLAT"
|
|
sc.display.shading.color_type = "TEXTURE"
|
|
sc.display.shading.show_backface_culling = True
|
|
sc.render.resolution_x, sc.render.resolution_y = 900, 1200
|
|
w = bpy.data.worlds.new("w")
|
|
sc.world = w
|
|
w.color = (0.35, 0.4, 0.38)
|
|
d = bpy.data.cameras.new("c")
|
|
d.type = "ORTHO"
|
|
d.ortho_scale = 1.1
|
|
cam = bpy.data.objects.new("c", d)
|
|
sc.collection.objects.link(cam)
|
|
sc.camera = cam
|
|
for az, tag in ((0, "front"), (65, "side"), (180, "back"), (295, "other")):
|
|
a = math.radians(az)
|
|
cam.location = Vector((3 * math.sin(a), -3 * math.cos(a), 0.5))
|
|
cam.rotation_euler = (Vector((0, 0, 0.5)) - cam.location).to_track_quat("-Z", "Y").to_euler()
|
|
for x, lab in ((full, "full"), (o, "game")):
|
|
full.hide_render, o.hide_render = x != full, x != o
|
|
sc.render.filepath = os.path.join(common.PREVIEWS, f"Cmp_{name}_{tag}_{lab}.png")
|
|
bpy.ops.render.render(write_still=True)
|
|
full.hide_render = o.hide_render = False
|
|
bpy.data.objects.remove(cam)
|
|
|
|
|
|
def measure(o):
|
|
"""Where the joints are, from the mesh. Everyone is near enough the same build for one set of rules."""
|
|
P = [v.co.copy() for v in o.data.vertices]
|
|
bvh = BVHTree.FromPolygons(P, [tuple(p.vertices) for p in o.data.polygons])
|
|
med = lambda s: sorted(s)[len(s) // 2]
|
|
J = {}
|
|
arm = [p for p in P if 0.22 < abs(p.x) < 0.3]
|
|
J["arm_z"], J["arm_y"] = med([p.z for p in arm]), med([p.y for p in arm])
|
|
knee = [p for p in P if 0.13 < p.z < 0.19]
|
|
J["leg_x"], J["leg_y"] = med([abs(p.x) for p in knee]), med([p.y for p in knee])
|
|
# up the gap between the legs until something is hit
|
|
hit = bvh.ray_cast(Vector((0, J["leg_y"], 0.01)), Vector((0, 0, 1)), 0.5)
|
|
J["crotch"] = hit[0].z if hit[0] else 0.25
|
|
# the narrowest slice between the shoulders and the brim of the head
|
|
def wide(z):
|
|
s = [abs(p.x) for p in P if z <= p.z < z + 0.012 and abs(p.x) < 0.19]
|
|
return max(s) if s else 1.0
|
|
neck = min((wide(0.595 + k * 0.006), 0.595 + k * 0.006) for k in range(10))
|
|
J["neck"] = neck[1]
|
|
# the ribs, under the arm: wider than the shoulder joint, so the arm has to keep off them
|
|
J["ribs"] = max(abs(p.x) for p in P if J["arm_z"] - 0.085 < p.z < J["arm_z"] - 0.06 and abs(p.x) < 0.2)
|
|
tip = [p for p in P if abs(p.x) > max(q.x for q in P) - 0.012]
|
|
J["reach"] = sum(abs(p.x) for p in tip) / len(tip)
|
|
return J
|
|
|
|
|
|
def weights(o, J):
|
|
"""Rules, in the T-pose. Returns name -> {vertex: weight}."""
|
|
W = {n: {} for n in ("Body", "Head", "Leg_L", "Leg_R", "Shin_L", "Shin_R", "Arm_L", "Arm_R", "Fore_L", "Fore_R")}
|
|
sh, elbow, reach = 0.135, 0.245, J["reach"]
|
|
hip, knee = J["crotch"] + 0.03, J["crotch"] * 0.56
|
|
for v in o.data.vertices:
|
|
i, p = v.index, v.co
|
|
ax, side = abs(p.x), "L" if p.x > 0 else "R"
|
|
# the arm: all there is out past the shoulder, between the waist and the head; level with the ribs, only what's above them
|
|
top = J["neck"] + 0.07 * smooth01(0.155, 0.195, ax) # a wide sleeve rises past the neck, out where there's no head
|
|
a = smooth01(sh - 0.015, sh + 0.03, ax) * (1 - smooth01(top - 0.02, top, p.z)) * smooth01(J["arm_z"] - 0.16, J["arm_z"] - 0.13, p.z)
|
|
a *= max(smooth01(J["ribs"], J["ribs"] + 0.02, ax), smooth01(J["arm_z"] - 0.055, J["arm_z"] - 0.03, p.z))
|
|
# the leg: below the hips, fading out toward the middle only right at the top
|
|
l = (1 - smooth01(J["crotch"] - 0.015, J["crotch"] + 0.05, p.z)) * max(smooth01(0.002, 0.03, ax), 1 - smooth01(J["crotch"] * 0.7, J["crotch"] * 0.9, p.z))
|
|
h = smooth01(J["neck"] - 0.012, J["neck"] + 0.022, p.z) * (1 - a)
|
|
b = max(0.0, 1 - a - l - h)
|
|
if a > 0.001:
|
|
f = smooth01(elbow - 0.022, elbow + 0.022, ax)
|
|
if f < 0.999:
|
|
W["Arm_" + side][i] = a * (1 - f)
|
|
if f > 0.001:
|
|
W["Fore_" + side][i] = a * f
|
|
if l > 0.001:
|
|
f = 1 - smooth01(knee - 0.022, knee + 0.022, p.z)
|
|
if f < 0.999:
|
|
W["Leg_" + side][i] = l * (1 - f)
|
|
if f > 0.001:
|
|
W["Shin_" + side][i] = l * f
|
|
if h > 0.001:
|
|
W["Head"][i] = h
|
|
if b > 0.001:
|
|
W["Body"][i] = b
|
|
return W
|
|
|
|
|
|
def soften(o, W, rounds=4):
|
|
"""Each vertex takes the average of its neighbours a few times: a hard step in the weights is a spike in the pose."""
|
|
nb = [[] for _ in o.data.vertices]
|
|
for e in o.data.edges:
|
|
a, b = e.vertices
|
|
nb[a].append(b)
|
|
nb[b].append(a)
|
|
A = {n: [m.get(i, 0.0) for i in range(len(nb))] for n, m in W.items()}
|
|
for _ in range(rounds):
|
|
for n, a in A.items():
|
|
A[n] = [(a[i] + sum(a[j] for j in q) / len(q)) / 2 if q else a[i] for i, q in enumerate(nb)]
|
|
return {n: {i: w for i, w in enumerate(a) if w > 0.004} for n, a in A.items()}
|
|
|
|
|
|
def lower_arms(o, W, J):
|
|
"""Bakes the arms down. They swing round the shoulder as one; a vertex goes as far as its weight on that arm says."""
|
|
for sx, side in ((1, "L"), (-1, "R")):
|
|
piv = Vector((sx * 0.135, J["arm_y"], J["arm_z"]))
|
|
R = Matrix.Rotation(math.radians(sx * HANG), 3, "Y")
|
|
for k in ("Arm_", "Fore_"):
|
|
for i, w in W[k + side].items():
|
|
v = o.data.vertices[i]
|
|
t = v.co - piv
|
|
v.co = v.co.lerp(piv + R @ t, w)
|
|
return
|
|
|
|
|
|
def rig_it(o, W, J, k):
|
|
"""The skeleton, on the arms as they now hang. Everything stands k metres to the source unit by now."""
|
|
rd = bpy.data.armatures.new("Rig")
|
|
rig = link(bpy.data.objects.new("Rig", rd))
|
|
bpy.context.view_layer.objects.active = rig
|
|
rig.select_set(True)
|
|
bpy.ops.object.mode_set(mode="EDIT")
|
|
eb = rd.edit_bones
|
|
|
|
def bone(name, h, t, parent=None):
|
|
b = eb.new(name)
|
|
b.head, b.tail = Vector(h) * k, Vector(t) * k
|
|
b.roll = 0.0
|
|
if parent:
|
|
b.parent = eb[parent]
|
|
b.use_connect = False
|
|
return b
|
|
c = math.cos(math.radians(HANG))
|
|
s = math.sin(math.radians(HANG))
|
|
hip = J["crotch"] + 0.03
|
|
knee = J["crotch"] * 0.56
|
|
y, ay = J["leg_y"], J["arm_y"]
|
|
bone("Root", (0, 0, 0), (0, 0, 0.12))
|
|
bone("Body", (0, ay, hip), (0, ay, J["neck"]), "Root")
|
|
bone("Head", (0, ay, J["neck"]), (0, ay, J["neck"] + 0.2), "Body")
|
|
sockets = {}
|
|
for side, sx in (("L", 1), ("R", -1)):
|
|
bone("Leg_" + side, (sx * J["leg_x"], y, hip), (sx * J["leg_x"], y, knee), "Body")
|
|
bone("Shin_" + side, (sx * J["leg_x"], y, knee), (sx * J["leg_x"], y, 0.02), "Leg_" + side)
|
|
# the arm hangs a little out from the body: along it from the shoulder, in the T's own lengths
|
|
at = lambda d: (sx * (0.135 + d * c), ay, J["arm_z"] - d * s)
|
|
elbow, wrist, fist = at(0.11), at(J["reach"] - 0.135 - 0.05), at(J["reach"] - 0.135 - 0.035)
|
|
bone("Arm_" + side, at(0), elbow, "Body")
|
|
bone("Fore_" + side, elbow, wrist, "Arm_" + side)
|
|
sockets["Hand_" + side] = ("Fore_" + side, Vector(fist) * k)
|
|
bpy.ops.object.mode_set(mode="OBJECT")
|
|
o.parent = rig
|
|
o.parent_type = "OBJECT"
|
|
for n, m in W.items():
|
|
vg = o.vertex_groups.new(name=n)
|
|
for i, w in m.items():
|
|
vg.add([i], w, "REPLACE")
|
|
o.modifiers.new("Armature", "ARMATURE").object = rig
|
|
bpy.context.view_layer.update()
|
|
for n, (b, at_) in sockets.items():
|
|
e = link(bpy.data.objects.new(n, None))
|
|
e.empty_display_size = 0.03
|
|
e.parent = rig
|
|
e.parent_type = "BONE"
|
|
e.parent_bone = b
|
|
bpy.context.view_layer.update()
|
|
e.matrix_world = Matrix.Translation(at_)
|
|
bpy.context.view_layer.update()
|
|
return rig
|
|
|
|
|
|
def gear(o, o_y):
|
|
"""The sack on the back with its fill window, the strap round the chest and the lantern on it: the parts of the old
|
|
crew member that still have a job. Vest, tinted per player, is the strap."""
|
|
bvh = BVHTree.FromPolygons([v.co.copy() for v in o.data.vertices], [tuple(p.vertices) for p in o.data.polygons])
|
|
|
|
def skin_at(z, a):
|
|
"""Round the body at height z, a degrees from the front. From inside out, so a hanging arm is never in the way."""
|
|
d = Vector((math.sin(DEG(a)), -math.cos(DEG(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
|
|
|
|
z = 0.66
|
|
back = skin_at(z, 180).y
|
|
# the sack is drawn at the old size and brought to fit: its front against the back, its seat at the waist
|
|
sc = 0.72
|
|
cy_, zb, zt = 0.43, 0.285, 0.75
|
|
M = Matrix.Translation((0, back - 0.005 - (cy_ - 0.135) * sc, 0.5 - zb * sc)) @ Matrix.Scale(sc, 4)
|
|
P = []
|
|
FB = Matrix.Translation((0, cy_, 0))
|
|
rx, ry = 0.205, 0.135
|
|
rings = [(0, 0, 0, 0, zb), (0, 0, rx * 0.72, ry * 0.7, zb + 0.004, 2.5), (0, 0, rx * 0.93, ry * 0.92, zb + 0.04, 2.5), (0, 0, rx * 1.04, ry * 1.02, zb + 0.13, 2.6), (0, 0, rx * 1.05, ry * 1.03, zb + 0.28, 2.6),
|
|
(0, 0, rx * 0.93, ry * 0.92, zt - 0.08, 2.4), (0, 0, rx * 0.66, ry * 0.68, zt - 0.02, 2.2), (0, 0, rx * 0.38, ry * 0.46, zt + 0.02, 2.0), (0, 0, rx * 0.21, ry * 0.28, zt + 0.045, 2.0),
|
|
(0, 0, rx * 0.2, ry * 0.27, zt + 0.06, 2.0), (0, 0, rx * 0.34, ry * 0.44, zt + 0.09, 2.0), (0, 0, rx * 0.4, ry * 0.5, zt + 0.115, 2.0), (0, 0, rx * 0.2, ry * 0.26, zt + 0.1, 2.0)]
|
|
sack = loft("sack", rings, segs=12, m="M_Burlap", frame=FB, smooth_ang=FACET + 8)
|
|
FT.pleats(sack, (0, cy_, 0), (0, 0, 1), n=6, amp=0.22, t0=zt - 0.08, t1=zt + 0.03)
|
|
wobble(sack, 0.012, 6.5, seed=3.0)
|
|
around(sack, (0, cy_, 0), (0, 0, 1), nu=4.5, s=4.6)
|
|
P.append(sack)
|
|
P.append(tube("twist", [(0.0, cy_, zt + 0.042), (0.0, cy_, zt + 0.07)], lambda s: 0.058, TWINE, segs=8, ang=FACET, cap=False))
|
|
rnd = random.Random(4)
|
|
for k in range(7):
|
|
a = TAU * k / 7 + rnd.uniform(-0.2, 0.2)
|
|
r_ = rnd.uniform(0.02, 0.062)
|
|
p0 = Vector((math.cos(a) * r_, cy_ + math.sin(a) * r_ * 0.8, zt + 0.08))
|
|
p1 = p0 + Vector((math.cos(a) * rnd.uniform(0.03, 0.07), math.sin(a) * rnd.uniform(0.02, 0.05), rnd.uniform(0.09, 0.14)))
|
|
P.append(tube("blade", [p0, p0.lerp(p1, 0.55) + Vector((0, 0, 0.012)), p1], lambda s: (0.024 * (1 - s) + 0.002, 0.008), rnd.choice(("M_Leaf", "M_LeafDark")), segs=4, per=1, ang=FACET))
|
|
# the fill window, a laced slit in the back of the sack
|
|
wz0, wz1, ww = 0.433, 0.767, 0.082
|
|
wc = (wz0 + wz1) / 2
|
|
F = frame_on((0, 0.566, wc), (0, 1, 0), up=(0, 0, 1))
|
|
P.append(ring_prism("wframe", rrect_pts(ww + 0.056, wz1 - wz0 + 0.056, 0.04, 2), rrect_pts(ww, wz1 - wz0, 0.03, 2), 0.022, F, LEA, bevel=0.0))
|
|
P.append(prism("wback", rrect_pts(ww + 0.006, wz1 - wz0 + 0.006, 0.03, 2), 0.003, F, HAIR))
|
|
for k in range(5):
|
|
y_ = wz0 + 0.035 + k * (wz1 - wz0 - 0.07) / 4
|
|
s_ = 1 if k % 2 else -1
|
|
P.append(tube("lace", [(-(ww / 2 + 0.018), 0.589, y_ + s_ * 0.014), (0, 0.593, y_), ((ww / 2 + 0.018), 0.589, y_ - s_ * 0.014)], lambda s: 0.0048, TWINE, segs=4, per=1, ang=FACET))
|
|
fill = prism("TankFill", rrect_pts(ww - 0.004, wz1 - wz0 - 0.004, 0.028, 2), 0.012, F @ Matrix.Translation((0, 0, 0.004)), "M_Clippings")
|
|
bp = FT.done(P, "Backpack", uv=4.0, ang=FACET)
|
|
uv_box(fill, 3.0)
|
|
# the strap, every centimetre of it on this body
|
|
ring = [skin_at(z, a) for a in range(0, 360, 15)]
|
|
V = [tube("strap", ring + ring[:1], lambda s: (0.024, 0.007), "M_CrewVest", segs=6, per=1, ang=FACET, cap=False)]
|
|
return bp, fill, V, skin_at(z, 28), M
|
|
|
|
|
|
def lantern(at):
|
|
"""Hangs off the strap at the front."""
|
|
lc = at + Vector((0, -0.03, -0.05))
|
|
P = []
|
|
L = Matrix.Translation(lc)
|
|
P.append(lathe("lbase", [(0.0, -0.05), (0.034, -0.05), (0.039, -0.04), (0.03, -0.028)], segs=8, m=BRASS, frame=L, smooth_ang=FACET))
|
|
P.append(lathe("ltop", [(0.03, 0.028), (0.037, 0.036), (0.02, 0.054), (0.0, 0.07)], segs=8, m=BRASS, frame=L, smooth_ang=FACET))
|
|
for k in range(4):
|
|
a = DEG(45 + 90 * k)
|
|
P.append(cyl("lrod", 0.0048, 0.06, lc + Vector((0.032 * math.cos(a), 0.032 * math.sin(a), 0)), verts=4, m=BRASS))
|
|
FT.ring_on(P, lc + Vector((0, 0, 0.082)), (0, 1, 0), 0.016, 0.0048, m=IRON, seg=8)
|
|
lamp = lathe("Lamp", [(0.0, -0.03), (0.024, -0.03), (0.029, -0.012), (0.029, 0.012), (0.024, 0.03), (0.0, 0.03)], segs=8, m="M_Emissive", frame=L, smooth_ang=FACET)
|
|
return P, lamp, lc
|
|
|
|
|
|
def ride(rig, *objs):
|
|
"""Rigid on the Body bone: plain renderers in Unity, so TankFill's scale and the lamp follow the bone."""
|
|
for o in objs:
|
|
mw = o.matrix_world.copy()
|
|
o.parent = rig
|
|
o.parent_type = "BONE"
|
|
o.parent_bone = "Body"
|
|
bpy.context.view_layer.update()
|
|
o.matrix_world = mw
|
|
bpy.context.view_layer.update()
|
|
|
|
|
|
def crew(name):
|
|
o = load(name)
|
|
# the eyes, lids and brows come off the skin: measured on the paint, pushed back into the head, painted over
|
|
F = FACE.measure(o)
|
|
FACE.carve(o, F)
|
|
full = thin(o)
|
|
bake(name, o, full, lambda pos, out, hit: FACE.repaint(F, pos, out, hit))
|
|
if CHECK:
|
|
compare(name, o, full)
|
|
# the joints from the full shell: decimation thins it unevenly, and the rules work on medians
|
|
J = measure(full)
|
|
bpy.data.objects.remove(full)
|
|
k = SHOULDER / J["arm_z"]
|
|
W = soften(o, weights(o, J))
|
|
lower_arms(o, W, J)
|
|
o.data.transform(Matrix.Scale(k, 4))
|
|
rig = rig_it(o, W, J, k)
|
|
bp, fill, V, hook, M = gear(o, J["arm_y"] * k)
|
|
for x in (bp, fill):
|
|
x.data.transform(M @ x.matrix_world)
|
|
x.matrix_world = Matrix.Identity(4)
|
|
set_origin(fill, M @ Vector((0, 0.57, 0.433)))
|
|
H, lamp, lc = lantern(hook)
|
|
P = FT.done(H, "Lantern", uv=4.0, ang=FACET)
|
|
vest = FT.done(V, "Vest", uv=3.0, ang=FACET)
|
|
set_origin(lamp, lc)
|
|
ride(rig, bp, fill, P, vest, lamp)
|
|
FACE.build(name, F, k, o, rig)
|
|
print(name, "joints", {a: round(b, 3) for a, b in J.items()}, "k", round(k, 3), "tris", len(o.data.polygons), flush=True)
|
|
return o, rig
|
|
|
|
|
|
def picture(name):
|
|
poses = [("rest", dict(elev=8, azim=-30), {}),
|
|
("walk", dict(elev=8, azim=-60), {"Leg_L": (DEG(-35), 0, 0), "Shin_L": (DEG(5), 0, 0), "Leg_R": (DEG(35), 0, 0), "Shin_R": (DEG(45), 0, 0), "Arm_L": (DEG(30), 0, 0), "Arm_R": (DEG(-30), 0, 0), "Fore_L": (DEG(-35), 0, 0), "Fore_R": (DEG(-25), 0, 0)}),
|
|
("back", dict(elev=12, azim=160), {}),
|
|
("sit", dict(elev=8, azim=-70), {"Leg_L": (DEG(-85), 0, 0), "Leg_R": (DEG(-85), 0, 0), "Shin_L": (DEG(85), 0, 0), "Shin_R": (DEG(85), 0, 0), "Arm_L": (DEG(-55), 0, 0), "Arm_R": (DEG(-55), 0, 0), "Fore_L": (DEG(-20), 0, 0), "Fore_R": (DEG(-20), 0, 0), "Head": (DEG(15), 0, 0)})]
|
|
return poses
|
|
|
|
|
|
CHECK = "GC_CHECK" in os.environ
|
|
|
|
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 ROSTER):
|
|
reset()
|
|
o, rig = crew(nm)
|
|
OC.pose(rig, {})
|
|
OC.export_rigged("SM_Crew_" + nm.capitalize())
|
|
for tag, view, rots in picture(nm):
|
|
OC.pose(rig, rots)
|
|
preview("Crew_" + nm + "_" + tag, res=520, bg=(0.45, 0.52, 0.48), **view)
|
|
OC.pose(rig, {})
|
|
FACE.pictures(nm)
|