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>
1078 lines
50 KiB
Python
1078 lines
50 KiB
Python
"""GRASS CUTTER - the crew's eyes, lids and brows as parts that move. Called by gc_tripo_crew.py; not run on its own.
|
|
|
|
The Tripo shells have each face baked into one skin: two bulging white eyes with a black disc, a skin cap over the top of
|
|
each and a thinner one under it, and a thick dark bar above. Here, on the source shell as loaded:
|
|
measure() finds them from the paint: each eye's centre, radius and look, where the lids cut it, how thick the lids
|
|
stand off it, and each brow's line, height and colour, and the colour of the lids and the brows.
|
|
carve() pushes everything inside the lids' reach into a socket set back inside the eyeball, and planes the brows off
|
|
the forehead, before the shell is rebuilt, so the rebuilt skin is closed and smooth there.
|
|
repaint() paints the baked texture there over with the skin round it (called from carry, texel by texel).
|
|
build() makes the parts on the game model, rigid on the Head bone, origin at the pivot, world-aligned:
|
|
EyeBall_L/_R a sphere about its own centre, the pupil along the rest look. Turning it is looking.
|
|
Lid_L/_R the upper lid, a shell round the left-right axis through the eye's centre: turned about that
|
|
axis it slides down over the whole eye. Rest is no rotation; LIDS[name] has the closing angle.
|
|
LidLow_L/_R the lower lid, the same kind of shell under the eye, still; the upper lid closes over it.
|
|
Brow_L/_R the bar, sunk into the forehead, origin on the forehead at its middle.
|
|
One material per crew member, M_CrewFace_<Name>, its texture T_CrewFace_<Name>.png: the eye in an
|
|
equal-area disc round the pupil, and flat swatches of the lid, lid rim, lower lid and brow colours.
|
|
pictures() renders the close-ups Face_<name>_{rest,blink,look,brows}.png.
|
|
Blender axes as everywhere here: X the character's left, -Y its front, Z up. L is the character's own left (x > 0).
|
|
"""
|
|
import os, math
|
|
import bpy, bmesh
|
|
import numpy as np
|
|
from mathutils import Vector, Matrix
|
|
from mathutils.bvhtree import BVHTree
|
|
from mathutils.kdtree import KDTree
|
|
import common
|
|
|
|
FACE_MAP = 1024
|
|
SOCKET = 0.86 # the socket is pushed back to this share of the eyeball's radius
|
|
LID_IN = 1.015 # the lids' inside edge stands this far off the eyeball, in its radius
|
|
EYE_SEGS, EYE_RINGS = 18, 9
|
|
LID_X, LID_PHI, LOW_PHI = 9, 16, 6
|
|
BROW_RINGS, BROW_SEGS = 9, 10
|
|
MARGIN = math.radians(8)
|
|
CLOSE = math.radians(90) # the upper lid's closing turn, the same for all eight: the widest open eyes (Hank, Gus) need 81
|
|
EDGE_S = np.linspace(-1.0, 1.0, 41)
|
|
# where things lie on the face texture: the eye disc, and four flat swatches down the right
|
|
DISC_C, DISC_R = (0.375, 0.375), 0.365
|
|
SWATCH = {"lid": 0.02, "rim": 0.27, "low": 0.52, "brow": 0.77} # v of the bottom of each, u from 0.78, 0.2 square
|
|
IRIS_IN, IRIS_OUT, LIMBUS, PUPIL = (0.33, 0.19, 0.09), (0.19, 0.10, 0.05), (0.07, 0.045, 0.03), (0.015, 0.012, 0.012)
|
|
LIDS = {} # name -> what the game needs to know, for the report
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- reading the shell
|
|
|
|
STEP = 0.0008 # of the source unit, between the rays of the front photo: about a millimetre of the game's
|
|
|
|
|
|
def _tone(col):
|
|
mx, mn = col.max(1), col.min(1)
|
|
return mx, (mx - mn) / np.maximum(mx, 1e-6)
|
|
|
|
|
|
def _photo(o, x0, x1, z0, z1):
|
|
"""The face as seen from straight ahead: per ray, what it first meets (position, normal) and the painted colour there."""
|
|
me = o.data
|
|
me.calc_loop_triangles()
|
|
tris = me.loop_triangles
|
|
nt = len(tris)
|
|
tv = np.zeros(nt * 3, np.int32)
|
|
tris.foreach_get("vertices", tv)
|
|
tv = tv.reshape(-1, 3)
|
|
tl = np.zeros(nt * 3, np.int32)
|
|
tris.foreach_get("loops", tl)
|
|
tl = tl.reshape(-1, 3)
|
|
vco = np.zeros(len(me.vertices) * 3, np.float32)
|
|
me.vertices.foreach_get("co", vco)
|
|
vco = vco.reshape(-1, 3).astype(np.float64)
|
|
bvh = BVHTree.FromPolygons([Vector(p) for p in vco], [tuple(t) for t in tv], all_triangles=True)
|
|
uv = np.zeros(len(me.loops) * 2, np.float32)
|
|
me.uv_layers.active.data.foreach_get("uv", uv)
|
|
uv = uv.reshape(-1, 2).astype(np.float64)
|
|
img = me.materials[0].node_tree.nodes["Principled BSDF"].inputs["Base Color"].links[0].from_node.image
|
|
w, h = img.size
|
|
px = np.zeros(w * h * 4, np.float32)
|
|
img.pixels.foreach_get(px)
|
|
px = px.reshape(h, w, 4)[..., :3]
|
|
xs, zs = np.arange(x0, x1, STEP), np.arange(z0, z1, STEP)
|
|
H, W = len(zs), len(xs)
|
|
pos = np.zeros((H, W, 3))
|
|
tri = np.full((H, W), -1)
|
|
fwd = Vector((0, 1, 0))
|
|
for i, z in enumerate(zs):
|
|
for j, x in enumerate(xs):
|
|
hit = bvh.ray_cast(Vector((x, -1.0, z)), fwd, 2.0)
|
|
if hit[0] is not None:
|
|
pos[i, j] = hit[0]
|
|
tri[i, j] = hit[2]
|
|
ok = tri >= 0
|
|
t = tri[ok]
|
|
a, b, c = vco[tv[t, 0]], vco[tv[t, 1]], vco[tv[t, 2]]
|
|
p = pos[ok]
|
|
v0, v1, v2 = b - a, c - a, p - 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
|
|
q = (1 - bb - bc)[:, None] * uv[tl[t, 0]] + bb[:, None] * uv[tl[t, 1]] + bc[:, None] * uv[tl[t, 2]]
|
|
col = np.zeros((H, W, 3))
|
|
col[ok] = px[np.clip((q[:, 1] * h).astype(int), 0, h - 1), np.clip((q[:, 0] * w).astype(int), 0, w - 1)]
|
|
return dict(x=xs, z=zs, pos=pos, col=col, ok=ok, bvh=bvh)
|
|
|
|
|
|
def _components(mask):
|
|
"""4-connected pieces of a boolean grid, as arrays of (row, column)."""
|
|
H, W = mask.shape
|
|
lab = np.full(mask.shape, -1)
|
|
out = []
|
|
for i0, j0 in zip(*np.nonzero(mask)):
|
|
if lab[i0, j0] >= 0:
|
|
continue
|
|
lab[i0, j0] = len(out)
|
|
st, mem = [(i0, j0)], [(i0, j0)]
|
|
while st:
|
|
i, j = st.pop()
|
|
for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
|
|
if 0 <= a < H and 0 <= b < W and mask[a, b] and lab[a, b] < 0:
|
|
lab[a, b] = len(out)
|
|
st.append((a, b))
|
|
mem.append((a, b))
|
|
out.append(np.array(mem))
|
|
return out
|
|
|
|
|
|
def edge_at(k, s):
|
|
s = max(-0.85, min(0.85, s))
|
|
return k[0] * s * s + k[1] * s + k[2]
|
|
|
|
|
|
def edge(e, key, s):
|
|
"""The lid line actually built (key "up" or "lo"), at s eye radii across."""
|
|
return float(np.interp(s, EDGE_S, e[key]))
|
|
|
|
|
|
def lid_rho(a, w, x):
|
|
"""Lens profile of a lid: its distance from the left-right axis at x across, a in the middle, nothing at +-w."""
|
|
return a * math.sqrt(max(0.0, 1.0 - (x / w) ** 2))
|
|
|
|
|
|
def _edge_fit(S, Fv, lo, hi):
|
|
"""The lid line as a quadratic across the eye, bending no more than a lid does."""
|
|
if len(S) < 3:
|
|
f = float(np.median(Fv)) if Fv else (lo + hi) / 2
|
|
return (0.0, 0.0, float(np.clip(f, lo, hi)))
|
|
k = np.polyfit(S, Fv, 2)
|
|
k[0] = float(np.clip(k[0], -0.6, 0.6))
|
|
k[2] = float(np.clip(k[2], lo, hi))
|
|
return tuple(float(x) for x in k)
|
|
|
|
|
|
def measure(o):
|
|
"""Everything the face parts need, in the source's own units (one unit tall), read off a front photo of the face.
|
|
The painted eyes are flattened discs: each becomes the sphere with the same outline seen from the front and the same
|
|
front, so it stands out of the face as far and looks the same from ahead."""
|
|
Ph = _photo(o, -0.2, 0.2, 0.55, 0.97)
|
|
xs, zs, pos, col, ok = Ph["x"], Ph["z"], Ph["pos"], Ph["col"], Ph["ok"]
|
|
lum = col.max(2)
|
|
sat = (col.max(2) - col.min(2)) / np.maximum(lum, 1e-6)
|
|
white = ok & (lum > 0.6) & (sat < 0.3)
|
|
dark = ok & (lum < 0.2)
|
|
X, Z = np.meshgrid(xs, zs)
|
|
best = {}
|
|
for cp in _components(white):
|
|
if len(cp) < 40:
|
|
continue
|
|
cx, cz = X[cp[:, 0], cp[:, 1]], Z[cp[:, 0], cp[:, 1]]
|
|
sd = 1 if np.median(cx) > 0 else -1
|
|
if (np.sign(cx) != sd).mean() > 0.05 or not (0.02 < abs(cx.mean()) < 0.17 and 0.6 < cz.mean() < 0.95):
|
|
continue
|
|
if sd not in best or len(cp) > len(best[sd]):
|
|
best[sd] = cp
|
|
if set(best) != {1, -1}:
|
|
raise RuntimeError("face: eyes not found, sides %s" % sorted(best))
|
|
F = {"eyes": [], "brows": []}
|
|
bvh = Ph["bvh"]
|
|
for sd, side in ((1, "L"), (-1, "R")):
|
|
cp = best[sd]
|
|
# the eye seen: its white, and whatever lies between white on the same row (the pupil)
|
|
eye = np.zeros(white.shape, bool)
|
|
for i in np.unique(cp[:, 0]):
|
|
js = cp[cp[:, 0] == i, 1]
|
|
eye[i, js.min():js.max() + 1] = True
|
|
eye &= white | dark
|
|
rows = [i for i in range(eye.shape[0]) if eye[i].any()]
|
|
# a circle through the ends of every row: half-width squared = r^2 - (z - zc)^2
|
|
zr, hw, xm = [], [], []
|
|
for i in rows:
|
|
js = np.nonzero(eye[i])[0]
|
|
zr.append(zs[i])
|
|
hw.append((xs[js.max()] - xs[js.min()] + STEP) / 2)
|
|
xm.append((xs[js.max()] + xs[js.min()]) / 2)
|
|
zr, hw, xm = np.array(zr), np.array(hw), np.array(xm)
|
|
keep = np.ones(len(zr), bool)
|
|
for _ in range(3):
|
|
A = np.c_[2 * zr[keep], np.ones(keep.sum())]
|
|
sol = np.linalg.lstsq(A, hw[keep] ** 2 + zr[keep] ** 2, rcond=None)[0]
|
|
zc = sol[0]
|
|
r = math.sqrt(max(1e-8, sol[1] + zc * zc))
|
|
res = np.abs(np.sqrt(np.maximum(r * r - (zr - zc) ** 2, 0)) - hw)
|
|
keep = res <= max(np.percentile(res, 75), STEP)
|
|
r = min(max(r, hw.max()), 1.3 * hw.max())
|
|
mid = np.abs(zr - zc) < 0.5 * r
|
|
xc = float(np.median(xm[mid])) if mid.any() else float(np.median(xm))
|
|
yfront = np.percentile(pos[eye][:, 1], 3)
|
|
c = np.array([xc, yfront + r, zc])
|
|
# lid lines, column by column: the top and the bottom of the eye seen, as angles round the left-right axis
|
|
cols = [j for j in range(eye.shape[1]) if eye[:, j].any()]
|
|
S, Ft, Fb = [], [], []
|
|
for j in cols:
|
|
ii = np.nonzero(eye[:, j])[0]
|
|
dxj = xs[j] - xc
|
|
if abs(dxj) > 0.88 * r:
|
|
continue
|
|
rho = math.sqrt(r * r - dxj * dxj)
|
|
S.append(dxj / r)
|
|
Ft.append(math.asin(max(-1, min(1, (zs[ii.max()] - zc) / rho))))
|
|
Fb.append(math.asin(max(-1, min(1, (zs[ii.min()] - zc) / rho))))
|
|
k_up = _edge_fit(S, Ft, math.radians(-15), math.radians(80))
|
|
k_lo = _edge_fit(S, Fb, math.radians(-85), math.radians(-5))
|
|
# the pupil and iris as painted, one dark disc; a lid may cut it, then its centre is a radius in from the whole side
|
|
dd = eye & dark
|
|
dx, dz = X[dd] - xc, Z[dd] - zc
|
|
x5, x95, z5, z95 = np.percentile(dx, 4), np.percentile(dx, 96), np.percentile(dz, 4), np.percentile(dz, 96)
|
|
rp = (x95 - x5) / 2
|
|
px_, pz = (x5 + x95) / 2, (z5 + z95) / 2
|
|
if z95 - z5 < 1.85 * rp:
|
|
ztop = r * math.sin(edge_at(k_up, px_ / r))
|
|
zbot = r * math.sin(edge_at(k_lo, px_ / r))
|
|
pz = z5 + rp if abs(z95 - ztop) < abs(z5 - zbot) else z95 - rp
|
|
lx, lz = px_ / r, pz / r
|
|
look = Vector((lx, -math.sqrt(max(0.05, 1 - lx * lx - lz * lz)), lz)).normalized()
|
|
iris = math.asin(min(0.9, rp / (r * math.sqrt(max(0.2, 1 - lx * lx)))))
|
|
|
|
# how far the lids stand off the eye: rays from outside, in toward the centre, just past each lid line
|
|
def stand(k_edge, sg):
|
|
got = []
|
|
for s_ in (-0.5, -0.25, 0.0, 0.25, 0.5):
|
|
q = math.sqrt(1 - s_ * s_)
|
|
for dp in (7, 14, 21):
|
|
ph = edge_at(k_edge, s_) + sg * math.radians(dp)
|
|
d = Vector((s_, -q * math.cos(ph), q * math.sin(ph)))
|
|
h = bvh.ray_cast(Vector(c) + d * 1.6 * r, -d, 1.6 * r)
|
|
if h[0] is not None and 1.6 * r - h[3] > 1.01 * r:
|
|
got.append(1.6 * r - h[3])
|
|
if not got:
|
|
return 1.18 * r, 1.18 * r
|
|
return float(np.median(got)), float(np.percentile(got, 80))
|
|
a_up, _ = stand(k_up, 1)
|
|
a_lo, _ = stand(k_lo, -1)
|
|
# lens-shaped lids, as thick as the old ones in front and closing in to nothing at the eye's corners; the lower
|
|
# one a little the bigger, so the upper slides in under it, however far it is turned
|
|
a_up = min(max(a_up, 1.1 * r), 1.36 * r)
|
|
a_lo = min(max(a_lo, a_up + 0.05 * r), a_up + 0.12 * r)
|
|
w_up, w_lo = 1.03 * r, 1.045 * r
|
|
# the lid line seen from the front is the lid's own front edge, out at the lid's radius, not the eye's: the
|
|
# angles are read again for that radius
|
|
S, Ft, Fb = [], [], []
|
|
for j in cols:
|
|
ii = np.nonzero(eye[:, j])[0]
|
|
dxj = xs[j] - xc
|
|
if abs(dxj) > 0.88 * r:
|
|
continue
|
|
S.append(dxj / r)
|
|
Ft.append(math.asin(max(-1, min(1, (zs[ii.max()] - zc) / lid_rho(a_up, w_up, dxj)))))
|
|
Fb.append(math.asin(max(-1, min(1, (zs[ii.min()] - zc) / lid_rho(a_lo, w_lo, dxj)))))
|
|
k_up = _edge_fit(S, Ft, math.radians(-15), math.radians(80))
|
|
k_lo = _edge_fit(S, Fb, math.radians(-85), math.radians(-5))
|
|
# the lid lines, bent where they have to be for one closing angle to shut every eye from corner to corner
|
|
up_, lo_ = [], []
|
|
for s_ in EDGE_S:
|
|
u_, l_ = edge_at(k_up, s_), edge_at(k_lo, s_)
|
|
short = u_ - l_ - (CLOSE - MARGIN)
|
|
if short > 0:
|
|
u_, l_ = u_ - short / 2, l_ + short / 2
|
|
up_.append(u_)
|
|
lo_.append(l_)
|
|
# everything of the old eye and lids inside these goes back into the socket
|
|
env = (a_up * 1.03 + 0.0012, w_up * 1.03 + 0.0012, a_lo * 1.03 + 0.0012, w_lo * 1.03 + 0.0012)
|
|
# the lids' paint: a band of the front photo just over and just under the eye
|
|
lidm = np.zeros(eye.shape, bool)
|
|
lowm = np.zeros(eye.shape, bool)
|
|
nb = max(2, int(0.25 * r / STEP))
|
|
for j in cols:
|
|
ii = np.nonzero(eye[:, j])[0]
|
|
if abs(xs[j] - xc) > 0.6 * r:
|
|
continue
|
|
lidm[ii.max() + 3:ii.max() + 3 + nb, j] = True
|
|
lowm[max(0, ii.min() - 3 - nb // 2):max(0, ii.min() - 3), j] = True
|
|
lidm &= ok & ~dark & ~white
|
|
lowm &= ok & ~dark & ~white
|
|
e = dict(side=side, c=Vector(c), r=r, look=look, iris=iris, k_up=k_up, k_lo=k_lo, up=np.array(up_), lo=np.array(lo_),
|
|
a_up=a_up, a_lo=a_lo, w_up=w_up, w_lo=w_lo, env=env,
|
|
sclera=np.median(col[eye & white], 0), lid=np.median(col[lidm], 0) if lidm.any() else None,
|
|
low=np.median(col[lowm], 0) if lowm.any() else None)
|
|
F["eyes"].append(e)
|
|
print(f" eye {side}: centre {tuple(round(float(x), 4) for x in c)} r {r:.4f} (widest row {hw.max():.4f}) look {tuple(round(x, 2) for x in look)} iris {math.degrees(iris):.0f} deg"
|
|
f" | upper lid at {math.degrees(edge_at(k_up, 0)):.0f} deg, stands {a_up / r:.2f} r | lower at {math.degrees(edge_at(k_lo, 0)):.0f} deg, {a_lo / r:.2f} r"
|
|
f" | opening {math.degrees(edge_at(k_up, 0) - edge_at(k_lo, 0)):.0f} deg at the middle, {math.degrees(max(np.array(up_) - np.array(lo_))):.0f} at most once bent", flush=True)
|
|
skin = [e["lid"] for e in F["eyes"] if e["lid"] is not None]
|
|
for e in F["eyes"]:
|
|
e["lid"] = e["lid"] if e["lid"] is not None else (skin[0] if skin else np.array([0.75, 0.5, 0.33]))
|
|
e["low"] = e["low"] if e["low"] is not None else e["lid"]
|
|
F["grid"] = (xs[0], zs[0], len(zs), len(xs))
|
|
# the nose as each eye sees it (each reaches across the middle), together: one side's first fit may miss half of it
|
|
bms = [_brow_mask(Ph, white, dark, e) for e in F["eyes"]]
|
|
core = np.zeros(Ph["ok"].shape, bool)
|
|
for e, bm_ in zip(F["eyes"], bms):
|
|
core |= _face_base(Ph, white, dark, e, bm_)
|
|
for e, bm_ in zip(F["eyes"], bms):
|
|
_face_base(Ph, white, dark, e, bm_, core)
|
|
F["brows"].append(_brow(Ph, e, bm_))
|
|
return F
|
|
|
|
|
|
def _brow_mask(Ph, white, dark, e):
|
|
"""The brow's paint on the front photo: the dark bar over the eye, sheen and all."""
|
|
xs, zs, col, ok = Ph["x"], Ph["z"], Ph["col"], Ph["ok"]
|
|
X, Z = np.meshgrid(xs, zs)
|
|
c, r = np.array(e["c"]), e["r"]
|
|
near = dark & (Z > c[2] + 0.5 * r) & (Z < c[2] + 3.6 * r) & (np.abs(X - c[0]) < 2.4 * r)
|
|
best, score = None, 1e9
|
|
for cp in _components(near):
|
|
if len(cp) < 30:
|
|
continue
|
|
mx, mz = X[cp[:, 0], cp[:, 1]].mean(), Z[cp[:, 0], cp[:, 1]].mean()
|
|
if abs(mx - c[0]) > 1.7 * r or not (0.7 * r < mz - c[2] < 3.2 * r):
|
|
continue
|
|
sc_ = abs(mx - c[0]) + abs(mz - c[2] - 1.7 * r) - len(cp) * 1e-6
|
|
if sc_ < score:
|
|
best, score = cp, sc_
|
|
if best is None:
|
|
raise RuntimeError("face: no brow over eye " + e["side"])
|
|
bm_ = np.zeros(dark.shape, bool)
|
|
bm_[best[:, 0], best[:, 1]] = True
|
|
# a sheen on the bar can split its paint: everything darkish joined to it, in its box, belongs to it, and so does what
|
|
# lies between its top and bottom in each column
|
|
i0, i1 = best[:, 0].min(), best[:, 0].max()
|
|
j0, j1 = best[:, 1].min(), best[:, 1].max()
|
|
pad = int(0.004 / STEP)
|
|
loose = ok & (col.max(2) < 0.3)
|
|
box = np.zeros(dark.shape, bool)
|
|
box[max(0, i0 - pad):i1 + pad + 1, max(0, j0 - pad):j1 + pad + 1] = True
|
|
for cp in _components(loose & box):
|
|
if bm_[cp[:, 0], cp[:, 1]].any():
|
|
bm_[cp[:, 0], cp[:, 1]] = True
|
|
for j in range(j0, j1 + 1):
|
|
ii = np.nonzero(bm_[:, j])[0]
|
|
if len(ii):
|
|
bm_[ii.min():ii.max() + 1, j] = True
|
|
return bm_
|
|
|
|
|
|
def _grow(mask, n):
|
|
"""Steps (4-neighbour) from mask, up to n; n + 1 beyond."""
|
|
dist = np.where(mask, 0, n + 1)
|
|
cur = mask.copy()
|
|
for k in range(1, n + 1):
|
|
nb = cur.copy()
|
|
nb[1:] |= cur[:-1]
|
|
nb[:-1] |= cur[1:]
|
|
nb[:, 1:] |= cur[:, :-1]
|
|
nb[:, :-1] |= cur[:, 1:]
|
|
dist[nb & ~cur] = k
|
|
cur = nb
|
|
return dist
|
|
|
|
|
|
def _poly(x, z, o):
|
|
u, v = np.asarray(x, float) - o[0], np.asarray(z, float) - o[1]
|
|
return np.stack([np.ones_like(u), u, v, u * u, u * v, v * v, u ** 3, u * u * v, u * v * v, v ** 3], -1)
|
|
|
|
|
|
def face_y(e, x, z):
|
|
"""The plain face round an eye and its brow, without them: y over (x, z)."""
|
|
return _poly(x, z, e["bo"]) @ e["base"]
|
|
|
|
|
|
def _fit_base(P, o):
|
|
keep = np.ones(len(P), bool)
|
|
for _ in range(4):
|
|
coef = np.linalg.lstsq(_poly(P[keep, 0], P[keep, 2], o), P[keep, 1], rcond=None)[0]
|
|
res = P[:, 1] - _poly(P[:, 0], P[:, 2], o) @ coef
|
|
mad = np.median(np.abs(res[keep])) + 1e-5
|
|
# bumps in front (a nose, a cheek, a hat brim) go first; anything far off either way after them
|
|
keep = (res > -max(0.002, 2.5 * mad)) & (np.abs(res) < max(0.004, 4 * mad))
|
|
return coef
|
|
|
|
|
|
def _skin(m, col):
|
|
"""Of the pixels in m, those painted like most of them: the skin, not a hat brim or a sleeve of hair."""
|
|
med = np.median(col[m], 0)
|
|
return m & (np.linalg.norm(col - med, axis=2) < 0.14)
|
|
|
|
|
|
def _face_base(Ph, white, dark, e, bm_, core=None):
|
|
"""Where the eye, its lids and its brow sit on the face, on the front photo (e["foot"], steps from it in e["fdist"]),
|
|
and the plain face under them (face_y), fitted to the skin round about. Without core: only the nose as this eye
|
|
finds it (what stands well out of a first fit, medially and low), to be joined with the other eye's."""
|
|
xs, zs, pos, col, ok = Ph["x"], Ph["z"], Ph["pos"], Ph["col"], Ph["ok"]
|
|
X, Z = np.meshgrid(xs, zs)
|
|
c, r = np.array(e["c"]), e["r"]
|
|
sd = 1 if e["side"] == "L" else -1
|
|
dx, dz = X - c[0], Z - c[2]
|
|
lum = col.max(2)
|
|
# the new parts as seen from the front: the eye, and the two lenses round its left-right axis
|
|
ru = np.vectorize(lambda x: lid_rho(e["a_up"], e["w_up"], x))(dx)
|
|
rl = np.vectorize(lambda x: lid_rho(e["a_lo"], e["w_lo"], x))(dx)
|
|
parts = ((dx * dx + dz * dz) < r * r) | ((dz >= 0) & (dz < ru)) | ((dz < 0) & (-dz < rl))
|
|
mm = int(0.001 / STEP)
|
|
o = (c[0], c[2] + 0.8 * r)
|
|
# the nose, which stays: low and toward the middle, standing well out of the face (a first fit of it, whose trimming
|
|
# leaves bumps out), and a few millimetres of its foot
|
|
wide = np.vectorize(lambda x: lid_rho(1.05 * max(e["a_up"], e["a_lo"]), 1.35 * r, x))(dx)
|
|
near = (_grow(parts | (np.abs(dz) < wide), 14 * mm) <= 14 * mm) & (_grow(parts | (np.abs(dz) < wide), 3 * mm) >= 3 * mm)
|
|
g = _skin(ok & near & ~dark & ~white & (lum >= 0.25) & (dx * sd > -1.6 * r), col)
|
|
base0 = _fit_base(pos[g], o)
|
|
stand = (_poly(X, Z, o) @ base0) - pos[..., 1]
|
|
# the old eye and lids stand as far out: inside the new parts' outline only what lies in front of them counts
|
|
fy = np.full(X.shape, np.inf)
|
|
q = r * r - dx * dx - dz * dz
|
|
fy = np.where(q > 0, c[1] - np.sqrt(np.clip(q, 0, None)), fy)
|
|
for rr in (ru, rl):
|
|
q = rr * rr - dz * dz
|
|
fy = np.minimum(fy, np.where(q > 0, c[1] - np.sqrt(np.clip(q, 0, None)), np.inf))
|
|
free = ~parts | (pos[..., 1] < fy - 0.002)
|
|
nose = ok & free & (dz < 0.3 * r) & (dx * sd < -0.2 * r) & (stand > 0.22 * r) & (dx * dx + dz * dz < 6 * r * r)
|
|
if core is None:
|
|
return nose
|
|
nose = core & ok & free & (dz < 0.3 * r) & (dx * sd < -0.2 * r)
|
|
# the nose itself only, by the middle of the face: not a bulge of the old lower lid standing out of the first fit
|
|
# under the eye (those lie out toward the eye's centre)
|
|
cps = _components(nose)
|
|
nose = np.zeros_like(nose)
|
|
drop = []
|
|
for cp in cps:
|
|
if abs(xs[cp[:, 1]].mean()) < 0.6 * abs(c[0]):
|
|
nose[cp[:, 0], cp[:, 1]] = True
|
|
else:
|
|
drop.append(len(cp))
|
|
print(f" nose {e['side']}: {len(cps) - len(drop)} pieces kept, dropped", sorted(drop, reverse=True)[:5], flush=True)
|
|
# and everything between the eyes below their middles, outside the new parts: no part sits there, so nothing there
|
|
# needs planing, and a nose the colour of the skin that hardly stands out of the first fit stays whole
|
|
nose |= ok & ~parts & (np.abs(X) < abs(c[0]) - 0.85 * r) & (dz < 0) & (dz > -2 * r)
|
|
nose = (_grow(nose, mm) <= mm) & ok & free & (dz < 0.3 * r) & (dx * sd < -0.2 * r)
|
|
e["nose"] = nose
|
|
# the old lids reach out past the eye's sides, further than the new ones (wide): they are planed as far
|
|
init = (parts | (np.abs(dz) < wide) | (_grow(bm_, 3 * mm) <= 3 * mm)) & ~nose
|
|
|
|
def ring_of(foot):
|
|
d = _grow(foot, 14 * mm)
|
|
g = _skin(ok & (d >= 3 * mm) & (d <= 13 * mm) & ~dark & ~white & (lum >= 0.25) & ~nose & (dx * sd > -1.6 * r), col)
|
|
return pos[g]
|
|
base = _fit_base(ring_of(init), o)
|
|
# whatever stands out of that face near the parts belongs to the old eye, lids or brow, and is planed down too
|
|
ring_px = ok & (_grow(init, 14 * mm) >= 3 * mm) & (_grow(init, 14 * mm) <= 13 * mm) & ~dark & ~white & (lum >= 0.25) & ~nose
|
|
skin = np.median(col[_skin(ring_px, col)], 0)
|
|
over = ok & ((_poly(X, Z, o) @ base) - pos[..., 1] > 0.0016) & (_grow(init, int(0.3 * r / STEP)) <= int(0.3 * r / STEP)) & ~nose
|
|
# only skin (not a hat brim, hair or a beard), and not down toward the nose and mouth
|
|
lowlid = (np.linalg.norm(col - np.array(e["low"]), axis=2) < 0.1) & (np.linalg.norm(col - skin, axis=2) > 0.06)
|
|
over &= ((np.linalg.norm(col - skin, axis=2) < 0.2) & ((dz > -0.2 * r) | (dx * sd > 0))) | lowlid
|
|
touch = _grow(init, 2) <= 2
|
|
foot = init.copy()
|
|
for cp in _components(over & ~init):
|
|
if touch[cp[:, 0], cp[:, 1]].any():
|
|
foot[cp[:, 0], cp[:, 1]] = True
|
|
base = _fit_base(ring_of(foot), o)
|
|
e["base"], e["bo"], e["foot"] = base, o, foot
|
|
e["fdist"] = _grow(foot, 20 * mm) * STEP
|
|
e["ndist"] = _grow(nose, 20 * mm) * STEP
|
|
print(f" face round eye {e['side']}: {int(foot.sum())} px planed, {int(nose.sum())} px of nose kept; the eye stands "
|
|
f"{(face_y(e, c[0], c[2]) - (c[1] - r)) / r:.2f} r out of it", flush=True)
|
|
|
|
|
|
def _brow(Ph, e, bm_):
|
|
xs, zs, pos, col = Ph["x"], Ph["z"], Ph["pos"], Ph["col"]
|
|
D = pos[bm_]
|
|
m = D.mean(0)
|
|
Q = D[:, [0, 2]] - m[[0, 2]]
|
|
ev = np.linalg.eigh(Q.T @ Q)[1][:, -1]
|
|
a2 = ev if ev[0] > 0 else -ev
|
|
b2 = np.array([-a2[1], a2[0]])
|
|
t, v = Q @ a2, Q @ b2
|
|
t0, t1 = np.percentile(t, 0.5), np.percentile(t, 99.5)
|
|
ts = np.linspace(t0, t1, BROW_RINGS)
|
|
half = max((t1 - t0) / (BROW_RINGS - 1) * 0.5, 1.5 * STEP)
|
|
stand = face_y(e, D[:, 0], D[:, 2]) - D[:, 1]
|
|
vc, hh, ee = [], [], []
|
|
for ti in ts:
|
|
mm = np.abs(t - ti) < half
|
|
if mm.sum() < 3:
|
|
vc.append(np.nan); hh.append(np.nan); ee.append(np.nan)
|
|
continue
|
|
lo, hi = v[mm].min(), v[mm].max()
|
|
vc.append((lo + hi) / 2)
|
|
hh.append(hi - lo + STEP)
|
|
ee.append(float(np.percentile(stand[mm], 90)))
|
|
vc, hh, ee = (np.array(x, float) for x in (vc, hh, ee))
|
|
okk = ~np.isnan(vc)
|
|
for arr in (vc, hh, ee):
|
|
arr[~okk] = np.interp(ts[~okk], ts[okk], arr[okk])
|
|
vc = np.polyval(np.polyfit(ts, vc, 2), ts)
|
|
k3 = np.array([0.25, 0.5, 0.25])
|
|
hh = np.convolve(np.pad(hh, 1, mode="edge"), k3, "valid")
|
|
ee = np.convolve(np.pad(ee, 1, mode="edge"), k3, "valid")
|
|
ee = np.clip(ee, 0.3 * hh, 0.9 * hh)
|
|
colr = np.median(col[bm_], 0)
|
|
print(f" brow {e['side']}: length {t1 - t0:.4f} height {np.median(hh):.4f} stands {np.median(ee):.4f} colour {tuple(round(float(x), 2) for x in colr)}", flush=True)
|
|
return dict(side=e["side"], eye=e, m=m, a2=a2, b2=b2, ts=ts, vc=vc, h=hh, e=ee, col=colr)
|
|
|
|
|
|
def forehead(b, x, z):
|
|
return float(face_y(b["eye"], x, z))
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- the shell, changed
|
|
|
|
def _foot_weight(F, P, nose=None):
|
|
"""Per point: the eye it belongs to (by side), how far (source units) its front-view spot is from that eye's footprint,
|
|
and the plain face's y there."""
|
|
x0, z0, H, W = F["grid"]
|
|
j = np.clip(np.round((P[:, 0] - x0) / STEP).astype(int), 0, W - 1)
|
|
i = np.clip(np.round((P[:, 2] - z0) / STEP).astype(int), 0, H - 1)
|
|
inside = (P[:, 0] >= x0) & (P[:, 0] <= x0 + W * STEP) & (P[:, 2] >= z0) & (P[:, 2] <= z0 + H * STEP)
|
|
dist = np.full(len(P), 1.0)
|
|
fy = np.zeros(len(P))
|
|
for e in F["eyes"]:
|
|
m = inside & ((P[:, 0] > 0) == (e["side"] == "L"))
|
|
dist[m] = e["fdist"][i[m], j[m]]
|
|
if nose is not None:
|
|
nose[m] = e["ndist"][i[m], j[m]]
|
|
fy[m] = face_y(e, P[m, 0], P[m, 2])
|
|
return dist, fy
|
|
|
|
|
|
def carve(o, F):
|
|
"""Everything that stood out of the face where the eyes, lids and brows were is planed down onto the plain face
|
|
under them, before the shell is rebuilt: the parts then come out of a smooth face, and the eyeball and lids are
|
|
sunk into it."""
|
|
me = o.data
|
|
co = np.zeros(len(me.vertices) * 3, np.float32)
|
|
me.vertices.foreach_get("co", co)
|
|
co = co.reshape(-1, 3).astype(np.float64)
|
|
dist, fy = _foot_weight(F, co)
|
|
w = 1.0 - np.clip((dist - 0.0012) / 0.005, 0, 1)
|
|
w = w * w * (3 - 2 * w)
|
|
out = co[:, 1] < fy + 0.0008
|
|
m = (w > 0) & out & (fy - co[:, 1] < 0.09)
|
|
co[m, 1] += w[m] * (fy[m] + 0.0008 - co[m, 1])
|
|
me.vertices.foreach_set("co", co.astype(np.float32).ravel())
|
|
me.update()
|
|
print(" carved the face:", int(m.sum()), "vertices planed", flush=True)
|
|
|
|
|
|
def repaint(F, pos, out, hit):
|
|
"""Over the old eyes', lids' and brows' place, the colour of the skin round them, carried in from all sides
|
|
(inverse-distance from the ring just outside), so no painted eye or brow is left under the parts."""
|
|
ys, xs = np.nonzero(hit)
|
|
P = pos[ys, xs]
|
|
C = out[ys, xs].astype(np.float64)
|
|
lum, sat = _tone(C)
|
|
nd = np.ones(len(P))
|
|
dist, fy = _foot_weight(F, P, nd)
|
|
front = np.abs(P[:, 1] - fy) < 0.008
|
|
mask = front & (dist <= 0.0025)
|
|
band = front & (dist > 0.0035) & (dist < 0.012)
|
|
good = band & (lum > 0.18) & ~((lum > 0.72) & (sat < 0.25))
|
|
# skin only: not the nose, a lid's paint or a highlight baked into the source
|
|
if good.any():
|
|
med = np.median(C[good], 0)
|
|
good &= np.linalg.norm(C - med, axis=1) < 0.1
|
|
# stray specks of lighter paint lying on the face a little further out (the old lids' corners, bled with the
|
|
# nose's colour), kept clear of the nose itself
|
|
stray = (front & ~mask & (dist <= 0.012) & (nd > 0.004)
|
|
& (np.linalg.norm(C - med, axis=1) > 0.15) & (lum > med.max()))
|
|
# and specks of the old brows' paint just past the footprint, toward the middle (the temples' hair stays), on
|
|
# a fold of the old brow's end too
|
|
for bw in F["brows"]:
|
|
e = bw["eye"]
|
|
c, r = np.array(e["c"]), e["r"]
|
|
sd = 1 if e["side"] == "L" else -1
|
|
stray |= ((np.abs(P[:, 1] - fy) < 0.02) & ~mask & (dist <= 0.008) & ((P[:, 0] > 0) == (sd > 0)) & (P[:, 2] > c[2] + 0.6 * r)
|
|
& ((P[:, 0] - c[0]) * sd < 0) & (np.linalg.norm(C - bw["col"], axis=1) < 0.15))
|
|
mask |= stray
|
|
gi = np.nonzero(good)[0]
|
|
if len(gi) > 9000:
|
|
gi = np.random.default_rng(1).choice(gi, 9000, replace=False)
|
|
kd = KDTree(len(gi))
|
|
for j, i in enumerate(gi):
|
|
kd.insert(P[i], j)
|
|
kd.balance()
|
|
for i in np.nonzero(mask)[0]:
|
|
got = kd.find_n(P[i], 14)
|
|
wt = np.array([1.0 / max(d, 1e-4) ** 2 for _, _, d in got])
|
|
out[ys[i], xs[i]] = (C[gi[[j for _, j, _ in got]]] * wt[:, None]).sum(0) / wt.sum()
|
|
print(" repainted", int(mask.sum()), "texels from", len(gi), "round them,", int(stray.sum()) if good.any() else 0, "of them strays", flush=True)
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- the parts
|
|
|
|
def _mesh(name, verts, faces, uvs, smooth=True):
|
|
me = bpy.data.meshes.new(name)
|
|
me.from_pydata([tuple(v) for v in verts], [], faces)
|
|
uvl = me.uv_layers.new(name="UVMap")
|
|
k = 0
|
|
for p in me.polygons:
|
|
for li in p.loop_indices:
|
|
uvl.data[li].uv = uvs[k]
|
|
k += 1
|
|
for p in me.polygons:
|
|
p.use_smooth = smooth
|
|
o = bpy.data.objects.new(name, me)
|
|
common.link(o)
|
|
return o
|
|
|
|
|
|
def _orient(o, outward):
|
|
"""Turns every face of o to face outward(centre, normal) > 0."""
|
|
bm = bmesh.new()
|
|
bm.from_mesh(o.data)
|
|
bm.normal_update()
|
|
for f in bm.faces:
|
|
if outward(f.calc_center_median(), f) < 0:
|
|
f.normal_flip()
|
|
bm.to_mesh(o.data)
|
|
bm.free()
|
|
|
|
|
|
def _swatch(kind, a, b):
|
|
"""A point inside a flat swatch, a and b in 0..1."""
|
|
v0 = SWATCH[kind]
|
|
return (0.79 + 0.18 * a, v0 + 0.01 + 0.18 * b)
|
|
|
|
|
|
def _eye_frame(look):
|
|
up = Vector((0, 0, 1))
|
|
U = (up - look * up.dot(look)).normalized()
|
|
S = U.cross(look).normalized()
|
|
return U, S
|
|
|
|
|
|
def _disc_uv(d, look, U, S, psi_hint=None):
|
|
th = math.acos(max(-1.0, min(1.0, d.dot(look))))
|
|
q = d - look * d.dot(look)
|
|
psi = math.atan2(q.dot(U), q.dot(S)) if q.length > 1e-7 else (psi_hint or 0.0)
|
|
rho = DISC_R * math.sin(th / 2)
|
|
return (DISC_C[0] + rho * math.cos(psi), DISC_C[1] + rho * math.sin(psi)), psi
|
|
|
|
|
|
def eyeball(name, c, r, look):
|
|
U, S = _eye_frame(look)
|
|
th = [math.pi * (i / EYE_RINGS) ** 1.12 for i in range(EYE_RINGS + 1)]
|
|
V = [look * r]
|
|
for i in range(1, EYE_RINGS):
|
|
for j in range(EYE_SEGS):
|
|
ps = 2 * math.pi * j / EYE_SEGS
|
|
V.append((look * math.cos(th[i]) + (S * math.cos(ps) + U * math.sin(ps)) * math.sin(th[i])) * r)
|
|
V.append(-look * r)
|
|
back = len(V) - 1
|
|
ring = lambda i, j: 1 + (i - 1) * EYE_SEGS + j % EYE_SEGS
|
|
faces = []
|
|
for j in range(EYE_SEGS):
|
|
faces.append((0, ring(1, j), ring(1, j + 1)))
|
|
for i in range(1, EYE_RINGS - 1):
|
|
for j in range(EYE_SEGS):
|
|
faces.append((ring(i, j), ring(i + 1, j), ring(i + 1, j + 1), ring(i, j + 1)))
|
|
for j in range(EYE_SEGS):
|
|
faces.append((ring(EYE_RINGS - 1, j + 1), ring(EYE_RINGS - 1, j), back))
|
|
uvs = []
|
|
for f in faces:
|
|
hint = None
|
|
pts = []
|
|
for vi in f:
|
|
uv, psi = _disc_uv(V[vi].normalized(), look, U, S)
|
|
pts.append(uv)
|
|
if vi not in (0, back):
|
|
hint = psi if hint is None else hint
|
|
# the back pole takes the bearing of its own face, so the disc's rim is not dragged across the map
|
|
for k_, vi in enumerate(f):
|
|
if vi == back:
|
|
ps = [math.atan2(V[x].normalized().dot(U), V[x].normalized().dot(S)) for x in f if x != back]
|
|
ps = math.atan2(sum(math.sin(p) for p in ps), sum(math.cos(p) for p in ps))
|
|
pts[k_] = (DISC_C[0] + DISC_R * math.cos(ps), DISC_C[1] + DISC_R * math.sin(ps))
|
|
uvs += pts
|
|
o = _mesh(name, V, faces, uvs)
|
|
_orient(o, lambda p, f: p.dot(f.normal))
|
|
o.location = c
|
|
return o
|
|
|
|
|
|
def _rho(a, x):
|
|
return math.sqrt(max(0.0, a * a - x * x))
|
|
|
|
|
|
def lid(name, c, r, a, w, edge, span, upper):
|
|
"""A shell of revolution about the left-right axis through c, lens-shaped (lid_rho), the open edge at phi = edge(x),
|
|
running span(x) away from it (up and back for the upper lid, down and back for the lower), a rim from it in to the
|
|
eyeball. Turned about that axis it only slides over itself."""
|
|
sg = 1 if upper else -1
|
|
nphi = LID_PHI if upper else LOW_PHI
|
|
xs = [w * math.sin(math.radians(-90 + 180 * j / (LID_X - 1))) for j in range(LID_X)]
|
|
V, faces, uvs = [], [], []
|
|
grid = {}
|
|
pole = {}
|
|
for j, x in enumerate(xs):
|
|
if j in (0, LID_X - 1):
|
|
pole[j] = len(V)
|
|
V.append(Vector((x, 0, 0)))
|
|
continue
|
|
ro = lid_rho(a, w, x)
|
|
e, sp = edge(x), span(x)
|
|
for i in range(nphi + 1):
|
|
ph = e + sg * sp * i / nphi
|
|
grid[j, i] = len(V)
|
|
V.append(Vector((x, -ro * math.cos(ph), ro * math.sin(ph))))
|
|
rim = {}
|
|
for j, x in enumerate(xs):
|
|
if j in (0, LID_X - 1):
|
|
continue
|
|
ro = lid_rho(a, w, x)
|
|
ri = min(_rho(LID_IN * r, x), ro * 0.97)
|
|
ph = edge(x)
|
|
rim[j, 0] = len(V)
|
|
V.append(Vector((x, -ro * math.cos(ph), ro * math.sin(ph))))
|
|
rim[j, 1] = len(V)
|
|
V.append(Vector((x, -ri * math.cos(ph), ri * math.sin(ph))))
|
|
kind = "lid" if upper else "low"
|
|
|
|
def at(j, i):
|
|
return pole[j] if j in pole else grid[j, i]
|
|
for j in range(LID_X - 1):
|
|
for i in range(nphi):
|
|
q = [at(j, i), at(j + 1, i), at(j + 1, i + 1), at(j, i + 1)]
|
|
q = [x for k_, x in enumerate(q) if x not in q[:k_]]
|
|
faces.append(tuple(q))
|
|
uvs += [_swatch(kind, (j + (k_ in (1, 2))) / (LID_X - 1), (i + (k_ in (2, 3))) / nphi) for k_ in range(len(q))]
|
|
rk = lambda j, s_: rim[j, s_]
|
|
for j in range(LID_X - 1):
|
|
if j == 0:
|
|
q = [rk(1, 0), rk(1, 1), pole[0]]
|
|
elif j == LID_X - 2:
|
|
q = [rk(j, 0), pole[LID_X - 1], rk(j, 1)]
|
|
else:
|
|
q = [rk(j, 0), rk(j + 1, 0), rk(j + 1, 1), rk(j, 1)]
|
|
faces.append(tuple(q))
|
|
uvs += [_swatch("rim", (j + 0.5) / (LID_X - 1), 0.3 + 0.4 * k_ / 3) for k_ in range(len(q))]
|
|
o = _mesh(name, V, faces, uvs)
|
|
nrim = LID_X - 1
|
|
|
|
def outward(p, f):
|
|
if f.index >= len(faces) - nrim:
|
|
# the rim faces into the eye's opening: toward lower phi on the upper lid, higher on the lower one
|
|
ph = math.atan2(p.z, -p.y)
|
|
return f.normal.dot(Vector((0, math.sin(ph), math.cos(ph)))) * -sg
|
|
return f.normal.dot(Vector((0, p.y, p.z)))
|
|
_orient(o, outward)
|
|
# the rim stands at the edge's own vertices but on separate ones, so its shading breaks from the shell's
|
|
o.location = c
|
|
return o
|
|
|
|
|
|
def brow(name, b, k):
|
|
"""A chunky bar along the measured brow, standing off the forehead as far as the old one and sunk well into it."""
|
|
ts, vc, hh, ee = b["ts"], b["vc"], b["h"], b["e"]
|
|
m, a2, b2 = b["m"], b["a2"], b["b2"]
|
|
sink = max(0.5 * float(np.median(hh)), 0.009 / k)
|
|
|
|
def on(t, v):
|
|
xz = m[[0, 2]] + a2 * t + b2 * v
|
|
y = forehead(b, xz[0], xz[1])
|
|
return Vector((xz[0], y, xz[1]))
|
|
|
|
def normal(p):
|
|
h = 1e-4
|
|
fx = (forehead(b, p.x + h, p.z) - forehead(b, p.x - h, p.z)) / (2 * h)
|
|
fz = (forehead(b, p.x, p.z + h) - forehead(b, p.x, p.z - h)) / (2 * h)
|
|
return Vector((fx, -1, fz)).normalized()
|
|
rings, cen = [], []
|
|
n = len(ts)
|
|
for i in range(n):
|
|
p = on(ts[i], vc[i])
|
|
cen.append(p)
|
|
for i in range(n):
|
|
p = cen[i]
|
|
T = (cen[min(i + 1, n - 1)] - cen[max(i - 1, 0)]).normalized()
|
|
N = normal(p)
|
|
B = N.cross(T).normalized()
|
|
if B.z < 0:
|
|
B = -B
|
|
# the ends close in, rounded off
|
|
end = min(i, n - 1 - i)
|
|
tap = (0.72, 0.94)[end] if end < 2 else 1.0
|
|
h2, e_ = 1.12 * hh[i] / 2 * tap, ee[i] * (0.75 + 0.25 * tap)
|
|
ring = []
|
|
for kq in range(BROW_SEGS):
|
|
be = 2 * math.pi * kq / BROW_SEGS
|
|
cb, sb = math.cos(be), math.sin(be)
|
|
u_ = math.copysign(abs(cb) ** 0.65, cb)
|
|
w_ = math.copysign(abs(sb) ** 0.65, sb)
|
|
ring.append(p + B * (h2 * u_) + N * ((e_ - sink) / 2 + (e_ + sink) / 2 * w_))
|
|
rings.append(ring)
|
|
V = [v for ring in rings for v in ring]
|
|
for i, sgn in ((0, -1), (n - 1, 1)):
|
|
T = (cen[min(i + 1, n - 1)] - cen[max(i - 1, 0)]).normalized()
|
|
cc = sum(rings[i], Vector()) / BROW_SEGS
|
|
V.append(cc + T * sgn * hh[i] * 0.22)
|
|
faces = []
|
|
for i in range(n - 1):
|
|
for kq in range(BROW_SEGS):
|
|
a_, b_ = i * BROW_SEGS + kq, i * BROW_SEGS + (kq + 1) % BROW_SEGS
|
|
faces.append((a_, b_, b_ + BROW_SEGS, a_ + BROW_SEGS))
|
|
c0, c1 = len(V) - 2, len(V) - 1
|
|
for kq in range(BROW_SEGS):
|
|
faces.append((c0, (kq + 1) % BROW_SEGS, kq))
|
|
faces.append((c1, (n - 1) * BROW_SEGS + kq, (n - 1) * BROW_SEGS + (kq + 1) % BROW_SEGS))
|
|
centre = sum(cen, Vector()) / n
|
|
V = [(v - centre) * k for v in V]
|
|
uvs = []
|
|
for f in faces:
|
|
uvs += [_swatch("brow", 0.2 + 0.6 * (fi % 2), 0.2 + 0.6 * (fi // 2 % 2)) for fi in range(len(f))]
|
|
o = _mesh(name, V, faces, uvs)
|
|
bm = bmesh.new()
|
|
bm.from_mesh(o.data)
|
|
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
|
|
bm.to_mesh(o.data)
|
|
bm.free()
|
|
o.location = centre * k
|
|
return o
|
|
|
|
|
|
def _inside_test(body):
|
|
me = body.data
|
|
bvh = BVHTree.FromPolygons([v.co.copy() for v in me.vertices], [tuple(p.vertices) for p in me.polygons])
|
|
dirs = [Vector(d).normalized() for d in ((0.31, 0.17, 0.93), (-0.6, 0.35, -0.72), (0.23, 0.95, 0.2))]
|
|
|
|
def inside(p):
|
|
votes = 0
|
|
for d in dirs:
|
|
n, at = 0, p
|
|
for _ in range(80):
|
|
h = bvh.ray_cast(at + d * 1e-5, d)
|
|
if h[0] is None:
|
|
break
|
|
n += 1
|
|
at = h[0]
|
|
votes += n % 2
|
|
return votes >= 2
|
|
return inside
|
|
|
|
|
|
def _reach(inside, c, ro, x, start, step):
|
|
"""From phi = start, how far the circle of radius ro round the axis stays out in the open, going by step (radians)
|
|
at x; no further than 200 degrees."""
|
|
ph, last, miss = start, start, 0
|
|
for _ in range(int(math.radians(200) / abs(step))):
|
|
p = c + Vector((x, -ro * math.cos(ph), ro * math.sin(ph)))
|
|
if inside(p):
|
|
miss += 1
|
|
if miss > 3:
|
|
break
|
|
else:
|
|
miss, last = 0, ph
|
|
ph += step
|
|
return last
|
|
|
|
|
|
def _paint(name, F):
|
|
"""T_CrewFace_<Name>: the eye disc and the swatches."""
|
|
N = FACE_MAP
|
|
img = np.zeros((N, N, 3), np.float32)
|
|
eyes = F["eyes"]
|
|
sclera = np.clip(np.mean([e["sclera"] for e in eyes], 0) * 1.04, 0, 0.94)
|
|
iris = float(np.mean([e["iris"] for e in eyes]))
|
|
pupil = 0.58 * iris
|
|
gy, gx = np.mgrid[0:N, 0:N]
|
|
u, v = (gx + 0.5) / N - DISC_C[0], (gy + 0.5) / N - DISC_C[1]
|
|
rho = np.sqrt(u * u + v * v) / DISC_R
|
|
th = 2 * np.arcsin(np.clip(rho, 0, 1))
|
|
psi = np.arctan2(v, u)
|
|
px = 2 * math.pi / (DISC_R * N * math.pi) # radians of theta per texel near the front, roughly
|
|
soft = lambda edge_, x: np.clip((edge_ - x) / (1.5 * px) + 0.5, 0, 1)
|
|
col = np.broadcast_to(sclera, (N, N, 3)).copy()
|
|
# iris: lighter round the pupil, darker out to a ring at its edge
|
|
f = np.clip(th / iris, 0, 1)[..., None]
|
|
ir = np.array(IRIS_IN) * (1 - f) + np.array(IRIS_OUT) * f
|
|
lim = np.clip((th / iris - 0.84) / 0.12, 0, 1)[..., None]
|
|
ir = ir * (1 - lim) + np.array(LIMBUS) * lim
|
|
# a few faint streaks round the iris, so it is not a flat disc at close range
|
|
ir *= (1 + 0.08 * np.sin(psi * 23)[..., None] * (1 - f))
|
|
w = soft(iris, th)[..., None]
|
|
col = col * (1 - w) + ir * w
|
|
w = soft(pupil, th)[..., None]
|
|
col = col * (1 - w) + np.array(PUPIL) * w
|
|
# the highlight: up and toward the character's right, as the source paints it
|
|
dirs = np.stack([np.sin(th) * np.cos(psi), np.sin(th) * np.sin(psi), np.cos(th)], -1) # (S, U, look)
|
|
hx, hy = -0.62 * iris, 0.55 * iris # S is the character's left, so -S is its right
|
|
H = np.array([math.sin(hx), math.sin(hy), 1.0])
|
|
H /= np.linalg.norm(H)
|
|
ang = np.arccos(np.clip(dirs @ H, -1, 1))
|
|
w = soft(0.24 * iris, ang)[..., None]
|
|
col = col * (1 - w) + np.array([0.97, 0.97, 0.97]) * w
|
|
H2 = np.array([math.sin(0.45 * iris), math.sin(-0.5 * iris), 1.0])
|
|
H2 /= np.linalg.norm(H2)
|
|
w = 0.7 * soft(0.09 * iris, np.arccos(np.clip(dirs @ H2, -1, 1)))[..., None]
|
|
col = col * (1 - w) + np.array([0.9, 0.9, 0.9]) * w
|
|
img[:] = col
|
|
e0 = eyes[0]
|
|
sw = {"lid": e0["lid"], "rim": np.array(e0["lid"]) * 0.72, "low": e0["low"], "brow": np.mean([b["col"] for b in F["brows"]], 0)}
|
|
for kname, v0 in SWATCH.items():
|
|
y0, y1 = int((v0 - 0.02) * N), int((v0 + 0.22) * N)
|
|
img[max(0, y0):min(N, y1), int(0.76 * N):] = np.clip(sw[kname], 0, 1)
|
|
im = bpy.data.images.new("T_CrewFace_" + name.capitalize(), N, N, alpha=False)
|
|
im.pixels.foreach_set(np.dstack((img, np.ones((N, N), np.float32))).ravel())
|
|
im.filepath_raw = os.path.join(common.TEXTURES, im.name + ".png")
|
|
im.file_format = "PNG"
|
|
im.save()
|
|
m = bpy.data.materials.new("M_CrewFace_" + name.capitalize())
|
|
m.use_nodes = True
|
|
n = m.node_tree.nodes.new("ShaderNodeTexImage")
|
|
n.image = im
|
|
bsdf = m.node_tree.nodes["Principled BSDF"]
|
|
m.node_tree.links.new(n.outputs["Color"], bsdf.inputs["Base Color"])
|
|
bsdf.inputs["Roughness"].default_value = 0.6
|
|
m.node_tree.nodes.active = n
|
|
return m
|
|
|
|
|
|
def build(name, F, k, body, rig):
|
|
"""The parts on the game model, k metres to the source unit, hung on the Head bone."""
|
|
inside = _inside_test(body)
|
|
mat = _paint(name, F)
|
|
parts = {}
|
|
info = {}
|
|
for e in F["eyes"]:
|
|
sd = e["side"]
|
|
c, r = e["c"] * k, e["r"] * k
|
|
a_up, a_lo = e["a_up"] * k, e["a_lo"] * k
|
|
w_up, w_lo = e["w_up"] * k, e["w_lo"] * k
|
|
up = lambda x, e=e, r=r: edge(e, "up", x / r)
|
|
lo = lambda x, e=e, r=r: edge(e, "lo", x / r)
|
|
xs = [w_up * math.sin(math.radians(-90 + 180 * j / (LID_X - 1))) for j in range(1, LID_X - 1)]
|
|
theta = CLOSE
|
|
need = max(edge_at(e["k_up"], x / r) - edge_at(e["k_lo"], x / r) for x in xs if abs(x) < 0.3 * r) + MARGIN
|
|
# how far up and back the eye's dome is out in the open, and down and back under it
|
|
top = {x: _reach(inside, c, lid_rho(a_up, w_up, x), x, up(x), math.radians(2)) for x in xs if abs(x) < 0.9 * r}
|
|
bot = {x: _reach(inside, c, lid_rho(a_lo, w_lo, x), x, lo(x), -math.radians(2)) for x in xs if abs(x) < 0.9 * r}
|
|
top_all = max(top.values())
|
|
bot_all = min(bot.values())
|
|
|
|
# the upper lid goes all the way round but for the eye's opening: its far edge lies under the lower lid at rest,
|
|
# and turns down and back into the head as it closes, so no edge of it but the front one ever shows
|
|
def span_up(x, up=up, lo=lo):
|
|
return 2 * math.pi - (up(x) - lo(x)) - math.radians(3)
|
|
|
|
# the lower lid as far down and back as the dome is out in the open anywhere, and a little more: the closed upper
|
|
# lid's opening turns down behind it
|
|
def span_lo(x, lo=lo, bot_all=bot_all):
|
|
return max(lo(x) - (bot_all - MARGIN), math.radians(30))
|
|
# the lower lid's far edge must be under the skin
|
|
out = 0
|
|
for x in xs:
|
|
ph = lo(x) - span_lo(x)
|
|
ro = lid_rho(a_lo, w_lo, x)
|
|
out += not inside(c + Vector((x, -ro * math.cos(ph), ro * math.sin(ph))))
|
|
if out:
|
|
print(f" WARNING {sd}: {out} samples of the lower lid's far edge are out in the open", flush=True)
|
|
eb = eyeball("EyeBall_" + sd, c, r, e["look"])
|
|
ul = lid("Lid_" + sd, c, r, a_up, w_up, up, span_up, True)
|
|
ll = lid("LidLow_" + sd, c, r, a_lo, w_lo, lo, span_lo, False)
|
|
parts.update({eb.name: eb, ul.name: ul, ll.name: ll})
|
|
info[sd] = dict(theta=theta, rest=up(0), lower=lo(0), top=top_all, bottom=bot_all, r=r, a_up=a_up, a_lo=a_lo, look=e["look"], c=c)
|
|
print(f" {sd}: eye r {r * 1000:.1f} mm; lid edge {math.degrees(up(0)):.0f} deg over the eye, closes at +{math.degrees(theta):.0f} deg (needs {math.degrees(need):.0f}); "
|
|
f"dome open from {math.degrees(bot_all):.0f} to {math.degrees(top_all):.0f} deg", flush=True)
|
|
for b in F["brows"]:
|
|
o = brow("Brow_" + b["side"], b, k)
|
|
parts[o.name] = o
|
|
for o in parts.values():
|
|
o.data.materials.append(mat)
|
|
o.data.name = o.name
|
|
mw = Matrix.Translation(o.location)
|
|
o.parent = rig
|
|
o.parent_type = "BONE"
|
|
o.parent_bone = "Head"
|
|
bpy.context.view_layer.update()
|
|
o.matrix_world = mw
|
|
bpy.context.view_layer.update()
|
|
tris = sum(len(p.vertices) - 2 for o in parts.values() for p in o.data.polygons)
|
|
print(f" face parts: {sorted(parts)}, {tris} tris", flush=True)
|
|
LIDS[name] = dict(info=info, tris=tris)
|
|
log = os.environ.get("GC_FACE_LOG")
|
|
if log:
|
|
import json
|
|
with open(log, "a", encoding="utf-8") as f:
|
|
f.write(json.dumps({"name": name, "tris": tris, **{sd: {"theta": math.degrees(v["theta"]), "rest_edge": math.degrees(v["rest"]),
|
|
"lower_edge": math.degrees(v["lower"]), "r_mm": v["r"] * 1000, "look": tuple(round(x, 3) for x in v["look"]), "c": tuple(v["c"])} for sd, v in info.items()}}) + "\n")
|
|
return parts
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- pictures
|
|
|
|
def poses(name, theta=None):
|
|
"""Name -> {object: matrix applied in the object's own frame, after its rest}."""
|
|
th = theta or (LIDS[name]["info"]["L"]["theta"], LIDS[name]["info"]["R"]["theta"])
|
|
D = math.radians
|
|
R = lambda ax, a: Matrix.Rotation(a, 4, ax)
|
|
return {
|
|
"rest": {},
|
|
"blink": {"Lid_L": R("X", th[0]), "Lid_R": R("X", th[1])},
|
|
# 25 degrees to the character's right (Blender -X) and 15 up
|
|
"look": {"EyeBall_L": R("Z", D(-25)) @ R("X", D(-15)), "EyeBall_R": R("Z", D(-25)) @ R("X", D(-15))},
|
|
# 8 mm up, and the inner ends down 12 degrees: a frown
|
|
"brows": {"Brow_L": Matrix.Translation((0, 0, 0.008)) @ R("Y", D(-12)), "Brow_R": Matrix.Translation((0, 0, 0.008)) @ R("Y", D(12))},
|
|
}
|
|
|
|
|
|
def pictures(name, out=None, tag="Face_", theta=None, r=None, centre=None, only=None):
|
|
"""The close-ups, three views side by side: front, from the character's right and above, from its left and below.
|
|
theta, r and centre stand in for what build() knew, for a model read back from its FBX."""
|
|
sc = bpy.context.scene
|
|
out = out or common.PREVIEWS
|
|
parts = {o.name: o for o in sc.objects if o.name.split(".")[0] in ("EyeBall_L", "EyeBall_R", "Lid_L", "Lid_R", "LidLow_L", "LidLow_R", "Brow_L", "Brow_R")}
|
|
rest = {n: o.matrix_world.copy() for n, o in parts.items()}
|
|
if centre is None:
|
|
eL, eR = parts["EyeBall_L"].matrix_world.translation, parts["EyeBall_R"].matrix_world.translation
|
|
centre = (eL + eR) / 2
|
|
r = r or LIDS[name]["info"]["L"]["r"]
|
|
tgt = Vector(centre) + Vector((0, 0, 0.5 * r))
|
|
old = (sc.render.engine, sc.view_settings.view_transform, sc.render.resolution_x, sc.render.resolution_y, sc.camera)
|
|
sc.render.engine = "BLENDER_WORKBENCH"
|
|
sc.display.shading.light = "STUDIO"
|
|
sc.display.shading.color_type = "TEXTURE"
|
|
sc.display.shading.show_backface_culling = True
|
|
sc.display.shading.show_specular_highlight = True
|
|
sc.view_settings.view_transform = "Standard"
|
|
sc.render.resolution_x = sc.render.resolution_y = 560
|
|
if not sc.world:
|
|
sc.world = bpy.data.worlds.new("w")
|
|
sc.world.color = (0.32, 0.36, 0.34)
|
|
cd = bpy.data.cameras.new("FaceCam")
|
|
cd.type = "ORTHO"
|
|
cd.ortho_scale = 7.5 * r
|
|
cam = common.link(bpy.data.objects.new("FaceCam", cd))
|
|
cam["preview_only"] = True
|
|
sc.camera = cam
|
|
views = ((0, 3), (-38, 12), (28, -22))
|
|
for pose, rots in (poses(name, theta) if parts else {"rest": {}}).items():
|
|
if only and pose not in only:
|
|
continue
|
|
for n, o in parts.items():
|
|
o.matrix_world = rest[n] @ rots.get(n.split(".")[0], Matrix.Identity(4))
|
|
bpy.context.view_layer.update()
|
|
tiles = []
|
|
for az, el in views:
|
|
a, b = math.radians(az), math.radians(el)
|
|
cam.location = tgt + Vector((math.sin(a) * math.cos(b), -math.cos(a) * math.cos(b), math.sin(b))) * 2.0
|
|
cam.rotation_euler = (tgt - cam.location).to_track_quat("-Z", "Y").to_euler()
|
|
path = os.path.join(out, "_tile.png")
|
|
sc.render.filepath = path
|
|
bpy.ops.render.render(write_still=True)
|
|
im = bpy.data.images.load(path)
|
|
px = np.zeros(im.size[0] * im.size[1] * 4, np.float32)
|
|
im.pixels.foreach_get(px)
|
|
tiles.append(px.reshape(im.size[1], im.size[0], 4))
|
|
bpy.data.images.remove(im)
|
|
os.remove(path)
|
|
sheet = np.concatenate(tiles, 1)
|
|
im = bpy.data.images.new("sheet", sheet.shape[1], sheet.shape[0], alpha=False)
|
|
im.pixels.foreach_set(sheet.ravel())
|
|
im.filepath_raw = os.path.join(out, f"{tag}{name}_{pose}.png")
|
|
im.file_format = "PNG"
|
|
im.save()
|
|
bpy.data.images.remove(im)
|
|
for n, o in parts.items():
|
|
o.matrix_world = rest[n]
|
|
bpy.context.view_layer.update()
|
|
bpy.data.objects.remove(cam)
|
|
sc.render.engine, sc.view_settings.view_transform, sc.render.resolution_x, sc.render.resolution_y, sc.camera = old
|