Game: - Assistant and Director portraits: GPT backgrounds and a holographic appear/disappear shader (Talk/TalkHolo) instead of on/off - Phone redesigned (HaulOS home, address bar, dock, error/loading states) and the browser link made sturdier - Settings > Graphics > Lighting: Classic / Enhanced (runtime volume, no project assets changed); Enhanced SSAO uses the smooth interleaved-gradient method at high samples so flat panels don't speckle - Painted board textures (T_HullPanel, T_BarnRed) keep only edge wear: the big bare-wood patches read as dirty smudges - The head leans into a sidestep smoothly instead of snapping with A / D - New keys in all 11 languages Review only (nothing swapped into the game yet): ArtSource/Blender/remaster (v1 paint pass of our own models, Synty-built ones left out), remaster/crew (crew repaint with arm, colour-edge and face fixes), remaster_v2 (smooth-geometry pilot). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
518 lines
23 KiB
Python
518 lines
23 KiB
Python
"""GRASS CUTTER crew remaster, stage 2: the repaint. Reads <scratch>/<name>_maps.npz from crew_rebake.py and writes
|
|
ArtSource/Blender/remaster/crew/textures/T_Crew_<Name>.png (2048, sRGB, every texel filled).
|
|
|
|
* the carried colour is split into the character's own paints (k-means in Lab with lightness down-weighted, so a lit
|
|
and a shadowed side of the same cloth stay one paint), and each texel is labelled with its paint;
|
|
* the labels are cleaned: a 3x3 plurality vote (twice) files off single-texel specks and stair steps, and any patch of a
|
|
paint smaller than MIN_PATCH texels is taken over by the paint round it (stray flecks of a neighbour's colour);
|
|
* each paint becomes one flat colour (its median) with soft shading: the texel's own lightness, blurred within the
|
|
paint and squeezed toward the median, so the cartoon reads clean while the folds still show;
|
|
* a consistent painted look for the whole crew: a little rest-pose ambient occlusion and a top light;
|
|
* per-character fixes (CFG): paints merged into another (Marcus's denim smudges), areas kept as painted (badges), a
|
|
team logo on Marcus's cap;
|
|
* the borders between paints are anti-aliased, and the empty map is filled outward from the charts (no black seams).
|
|
Run:
|
|
blender -b --factory-startup --python crew_repaint.py --python-exit-code 1 -- <scratch dir> [hank lin ...]
|
|
"""
|
|
import sys, os, math, time
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
OUT = os.path.normpath(os.path.join(HERE, "..", "textures"))
|
|
import bpy
|
|
import numpy as np
|
|
|
|
CREW = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji")
|
|
DIRECTOR = ("boss", "assistant")
|
|
K = 16 # starting paints
|
|
L_WEIGHT = 0.45 # lightness weight in the paint distance
|
|
MERGE = 9.0 # paints closer than this are one
|
|
MERGE_AB = 7.0 # ... or this close in hue/chroma and within MERGE_L in lightness (lit and shaded cloth)
|
|
MERGE_L = 24.0
|
|
MIN_PATCH = 80 # texels: smaller patches of a paint are flecks...
|
|
MIN_DETAIL = 24 # ...unless at least this big and this far (Lab) from the paint round them: a painted detail
|
|
DETAIL_DE = 45.0
|
|
BORDER_SIGMA = 2.5 # px: the wide vote that smooths paint borders
|
|
BIG_PATCH = 4000 # texels: a patch this big is an area of paint, not a detail
|
|
DISSOLVE_DE = 8.0 # a "dissolve" colour names a paint only if one lies this close to it (Lab)
|
|
SHADE_KEEP = 0.7 # how much of the painted lightness variation survives
|
|
SHADE_SIGMA = 5.0 # px
|
|
SHADE_CLIP = (-20.0, 14.0)
|
|
AO_STRENGTH = 0.32
|
|
TOP_LIGHT = 0.06
|
|
|
|
# per character: "merge": [(from sRGB, to sRGB)] paints whose median is nearest `from` become the paint nearest `to`;
|
|
# "protect": [(centre xyz in source units, radius)] where the carried paint is kept (badges, logos); "logo": cap logo
|
|
CFG = {
|
|
"assistant": {
|
|
# the G.R.A.S.S.A. badge, the ID card with its clip and the pen, the belt buckle
|
|
"protect_front": [(-0.138, 0.683, 0.078), (0.149, 0.664, 0.105), (-0.004, 0.588, 0.042)],
|
|
},
|
|
"wade": {
|
|
# the star badge on the hat band and the star buckle: kept as carried (read from the front)
|
|
"protect_front": [(-0.01, 1.262, 0.055), (0.0, 0.53, 0.07)],
|
|
# the overall's blue picked up at the ends of his sleeves (bare arms, red sleeves: no blue belongs there)
|
|
"dissolve": [((0.153, 0.286, 0.488), lambda d: d["armw"] > 0.6),
|
|
((0.074, 0.253, 0.55), lambda d: d["armw"] > 0.6),
|
|
# ... and the sleeve hem's grey
|
|
((0.251, 0.228, 0.231), lambda d: d["armw"] > 0.6)],
|
|
},
|
|
"boss": {
|
|
# the G.R.A.S.S.A. badge, the ID card with its clip and the pen, the tie, the belt buckle
|
|
"protect_front": [(-0.159, 0.658, 0.085), (0.171, 0.647, 0.115), (0.0, 0.66, 0.1), (0.0, 0.575, 0.06), (0.0, 0.541, 0.05)],
|
|
},
|
|
"marcus": {
|
|
# the grey distress smudges on the jeans (and the odd one on his arms), and the old logo's pale leftovers on the cap
|
|
"dissolve": [((0.353, 0.322, 0.328), None),
|
|
# (when the smudges come out brown instead: on the jeans only, below the belt, off the arms)
|
|
((0.433, 0.252, 0.151), lambda d: (d["gpos"][..., 2] < 0.62) & (d["armw"] < 0.3)),
|
|
((0.19, 0.11, 0.088), lambda d: (d["gpos"][..., 2] > 0.12) & (d["gpos"][..., 2] < 0.62) & (d["armw"] < 0.3)),
|
|
((0.854, 0.722, 0.644), lambda d: d["gpos"][..., 2] > 1.12),
|
|
# the overall's denim and the cap's navy that the source painted onto his bare upper arms
|
|
((0.239, 0.26, 0.371), lambda d: d["armw"] > 0.6),
|
|
((0.197, 0.169, 0.227), lambda d: d["armw"] > 0.6)],
|
|
"logo": dict(cap=(0.197, 0.169, 0.227), dir=(-0.45, 0.9, 0.0), band=(0.865, 0.935), r=0.042,
|
|
face=(0.93, 0.9, 0.8), rim=(0.95, 0.7, 0.13), mark=(0.24, 0.58, 0.2)),
|
|
},
|
|
}
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ colour
|
|
|
|
def srgb_to_lin(c):
|
|
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
|
|
|
|
|
|
def lin_to_srgb(c):
|
|
c = np.clip(c, 0, 1)
|
|
return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)
|
|
|
|
|
|
M_XYZ = np.array([[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]])
|
|
WHITE = np.array([0.95047, 1.0, 1.08883])
|
|
|
|
|
|
def lab(srgb):
|
|
xyz = srgb_to_lin(srgb) @ M_XYZ.T / WHITE
|
|
f = np.where(xyz > 216 / 24389, np.cbrt(xyz), (24389 / 27 * xyz + 16) / 116)
|
|
return np.stack([116 * f[..., 1] - 16, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])], -1)
|
|
|
|
|
|
def unlab(L):
|
|
fy = (L[..., 0] + 16) / 116
|
|
fx = fy + L[..., 1] / 500
|
|
fz = fy - L[..., 2] / 200
|
|
f = np.stack([fx, fy, fz], -1)
|
|
xyz = np.where(f ** 3 > 216 / 24389, f ** 3, (116 * f - 16) / (24389 / 27)) * WHITE
|
|
return lin_to_srgb(xyz @ np.linalg.inv(M_XYZ).T)
|
|
|
|
|
|
def feat(L):
|
|
return L * np.array([L_WEIGHT, 1.0, 1.0])
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ image helpers
|
|
|
|
def box(a, r, axis):
|
|
if r < 1:
|
|
return a
|
|
c = np.cumsum(a, axis=axis, dtype=np.float64)
|
|
n = a.shape[axis]
|
|
idx = np.arange(n)
|
|
hi = np.clip(idx + r, 0, n - 1)
|
|
lo = idx - r - 1
|
|
take_hi = np.take(c, hi, axis=axis)
|
|
take_lo = np.where((lo >= 0).reshape([-1 if i == axis else 1 for i in range(a.ndim)]),
|
|
np.take(c, np.clip(lo, 0, n - 1), axis=axis), 0)
|
|
return ((take_hi - take_lo) / (2 * r + 1)).astype(np.float32)
|
|
|
|
|
|
def blur(a, sigma):
|
|
"""Gaussian-ish blur, three box passes on each axis."""
|
|
r = max(1, int(round(-0.5 + math.sqrt(0.25 + sigma * sigma)))) # three passes of radius r: sigma^2 = r(r+1)
|
|
for _ in range(3):
|
|
a = box(box(a, r, 0), r, 1)
|
|
return a
|
|
|
|
|
|
def shifts(a, fill):
|
|
"""The 8 neighbours of every texel (array of shape (8,) + a.shape), `fill` off the edges."""
|
|
out = []
|
|
H, W = a.shape[:2]
|
|
for dy in (-1, 0, 1):
|
|
for dx in (-1, 0, 1):
|
|
if not dy and not dx:
|
|
continue
|
|
s = np.full_like(a, fill)
|
|
ys0, ys1 = max(0, dy), H + min(0, dy)
|
|
xs0, xs1 = max(0, dx), W + min(0, dx)
|
|
s[ys0 - dy:ys1 - dy, xs0 - dx:xs1 - dx] = a[ys0:ys1, xs0:xs1]
|
|
out.append(s)
|
|
return np.stack(out)
|
|
|
|
|
|
def plurality(lab_, hit, nlab, keep_self=1):
|
|
"""Each texel takes the paint most of its 3x3 has (itself counted keep_self+1 times)."""
|
|
nb = shifts(lab_, -1)
|
|
cnt = np.zeros((nlab,) + lab_.shape, np.int16)
|
|
for s in nb:
|
|
for l in range(nlab):
|
|
cnt[l] += (s == l)
|
|
for l in range(nlab):
|
|
cnt[l] += (lab_ == l) * (1 + keep_self)
|
|
new = cnt.argmax(0).astype(lab_.dtype)
|
|
return np.where(hit, new, lab_)
|
|
|
|
|
|
def vote_fill(lab_, loose, n):
|
|
"""The loose texels take the paint of the texels round them, ring by ring inward; loose ones do not vote."""
|
|
lab_ = lab_.copy()
|
|
left = loose.copy()
|
|
for _ in range(400):
|
|
if not left.any():
|
|
break
|
|
nb = shifts(np.where(left, -1, lab_), -1)
|
|
cnt = np.zeros((n,) + lab_.shape, np.int16)
|
|
for s in nb:
|
|
for l in range(n):
|
|
cnt[l] += (s == l)
|
|
upd = left & (cnt.max(0) > 0)
|
|
if not upd.any():
|
|
break # what is left is a whole chart of its own: it keeps its paint
|
|
lab_ = np.where(upd, cnt.argmax(0).astype(np.int16), lab_)
|
|
left &= ~upd
|
|
return lab_
|
|
|
|
|
|
def smooth_labels(lab_, hit, n, sigma=1.4):
|
|
"""Each texel takes the paint with the most weight round it (blurred one-hot): round, even borders, no stair steps."""
|
|
best = np.full(hit.shape, -1.0, np.float32)
|
|
out = lab_.copy()
|
|
for l in range(n):
|
|
w = blur(((lab_ == l) & hit).astype(np.float32), sigma)
|
|
m = hit & (w > best)
|
|
out[m] = l
|
|
best = np.where(m, w, best)
|
|
return out
|
|
|
|
|
|
def components(lab_, hit):
|
|
"""Connected patches of one paint (4-neighbour): returns a patch id per texel (-1 off the charts)."""
|
|
H, W = lab_.shape
|
|
ids = np.where(hit, np.arange(H * W).reshape(H, W), -1).astype(np.int64)
|
|
big = H * W + 1
|
|
for it in range(4000):
|
|
cur = np.where(hit, ids, big)
|
|
m = cur.copy()
|
|
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
|
|
s = np.roll(cur, (dy, dx), (0, 1))
|
|
sl = np.roll(lab_, (dy, dx), (0, 1))
|
|
sh = np.roll(hit, (dy, dx), (0, 1))
|
|
ok = sh & (sl == lab_)
|
|
m = np.where(ok & (s < m), s, m)
|
|
m = np.where(hit, m, -1)
|
|
flat = m.ravel()
|
|
# pointer jumping
|
|
for _ in range(3):
|
|
v = flat >= 0
|
|
flat = np.where(v, flat[np.maximum(flat, 0)], -1)
|
|
m = flat.reshape(H, W)
|
|
if np.array_equal(m, ids):
|
|
break
|
|
ids = m
|
|
return ids
|
|
|
|
|
|
def fill(rgb, known, max_iter=600):
|
|
"""Every unknown texel takes the average of its known neighbours, ring by ring outward, until the map is full."""
|
|
out = rgb.copy()
|
|
known = known.copy()
|
|
for _ in range(max_iter):
|
|
if known.all():
|
|
break
|
|
k = known.astype(np.float32)
|
|
tot = np.zeros_like(out)
|
|
cnt = np.zeros(known.shape, np.float32)
|
|
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)):
|
|
tot += np.roll(out * k[..., None], (dy, dx), (0, 1))
|
|
cnt += np.roll(k, (dy, dx), (0, 1))
|
|
new = ~known & (cnt > 0)
|
|
out[new] = tot[new] / cnt[new][:, None]
|
|
known |= new
|
|
return out
|
|
|
|
|
|
def save_png(rgb, path):
|
|
h, w = rgb.shape[:2]
|
|
img = bpy.data.images.new(os.path.splitext(os.path.basename(path))[0], w, h, alpha=False)
|
|
px = np.dstack([np.clip(rgb, 0, 1), np.ones((h, w))]).astype(np.float32)
|
|
img.pixels.foreach_set(px.ravel())
|
|
img.filepath_raw = path
|
|
img.file_format = "PNG"
|
|
img.save()
|
|
bpy.data.images.remove(img)
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ paints
|
|
|
|
def kmeans(X, k, iters=30, seed=3):
|
|
rng = np.random.default_rng(seed)
|
|
C = [X[rng.integers(len(X))]]
|
|
for _ in range(k - 1):
|
|
d = np.min(((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1), 1)
|
|
C.append(X[rng.choice(len(X), p=d / d.sum())])
|
|
C = np.array(C)
|
|
for _ in range(iters):
|
|
a = ((X[:, None, :] - C[None]) ** 2).sum(-1).argmin(1)
|
|
for j in range(k):
|
|
if (a == j).any():
|
|
C[j] = X[a == j].mean(0)
|
|
return C, a
|
|
|
|
|
|
def paints(Lab, hit):
|
|
ys, xs = np.nonzero(hit)
|
|
rng = np.random.default_rng(7)
|
|
pick = rng.choice(len(ys), min(len(ys), 160000), replace=False)
|
|
S = Lab[ys[pick], xs[pick]]
|
|
C, a = kmeans(feat(S), K)
|
|
C = C / np.array([L_WEIGHT, 1, 1]) # back to Lab
|
|
w = np.bincount(a, minlength=K).astype(float)
|
|
C, w = list(C), list(w)
|
|
while True:
|
|
best = None
|
|
for i in range(len(C)):
|
|
for j in range(i + 1, len(C)):
|
|
d = np.linalg.norm(feat(C[i]) - feat(C[j]))
|
|
dab = np.linalg.norm(C[i][1:] - C[j][1:])
|
|
dl = abs(C[i][0] - C[j][0])
|
|
if d < MERGE or (dab < MERGE_AB and dl < MERGE_L):
|
|
if best is None or d < best[0]:
|
|
best = (d, i, j)
|
|
if best is None:
|
|
break
|
|
_, i, j = best
|
|
C[i] = (C[i] * w[i] + C[j] * w[j]) / (w[i] + w[j])
|
|
w[i] += w[j]
|
|
del C[j], w[j]
|
|
# drop paints nothing much uses
|
|
C = np.array([c for c, n in zip(C, w) if n > 40])
|
|
return C
|
|
|
|
|
|
def assign(Lab, hit, C):
|
|
lab_ = np.full(hit.shape, -1, np.int16)
|
|
ys, xs = np.nonzero(hit)
|
|
F = feat(Lab[ys, xs])
|
|
FC = feat(C)
|
|
out = np.empty(len(ys), np.int16)
|
|
for s in range(0, len(ys), 400000):
|
|
out[s:s + 400000] = ((F[s:s + 400000, None, :] - FC[None]) ** 2).sum(-1).argmin(1)
|
|
lab_[ys, xs] = out
|
|
return lab_
|
|
|
|
|
|
def srgb_of(L):
|
|
return tuple(round(float(x), 3) for x in unlab(np.array(L)))
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ the repaint
|
|
|
|
def repaint(name, d):
|
|
t0 = time.time()
|
|
cfg = CFG.get(name, {})
|
|
hit = d["hit"]
|
|
col = d["col"].astype(np.float64)
|
|
Lab = lab(col)
|
|
C = paints(Lab, hit)
|
|
lab_ = assign(Lab, hit, C)
|
|
print(f" {len(C)} paints:", ", ".join(f"{i}:{srgb_of(c)}~{(lab_ == i).mean() * 100 / hit.mean():.1f}%" for i, c in enumerate(C)), flush=True)
|
|
n = len(C)
|
|
gpos = d["gpos"].astype(np.float64)
|
|
# specks and stair steps
|
|
for _ in range(2):
|
|
lab_ = plurality(lab_, hit, n)
|
|
lab_ = smooth_labels(lab_, hit, n)
|
|
ids = components(lab_, hit)
|
|
sizes = np.bincount(ids[hit].ravel(), minlength=ids.size)
|
|
loose = hit & (sizes[np.maximum(ids, 0)] < MIN_PATCH)
|
|
# ... but a small patch that stands out strongly from the paint round it, and is not a crumb, is a painted detail
|
|
# (a stitch, a rivet, a mole), not a fleck picked up from a neighbour: it stays
|
|
guess = vote_fill(lab_, loose, n)
|
|
dE = np.linalg.norm(C[np.maximum(lab_, 0)] - C[np.maximum(guess, 0)], axis=-1)
|
|
pid = np.where(loose, ids, 0)
|
|
tot = np.bincount(pid[loose].ravel(), weights=dE[loose].ravel(), minlength=ids.size)
|
|
cnt = np.bincount(pid[loose].ravel(), minlength=ids.size)
|
|
mean_dE = tot / np.maximum(cnt, 1)
|
|
detail = loose & (sizes[np.maximum(ids, 0)] >= MIN_DETAIL) & (mean_dE[np.maximum(ids, 0)] > DETAIL_DE)
|
|
loose &= ~detail
|
|
print(f" {int(loose.sum())} texels in patches under {MIN_PATCH} texels re-painted from round them;"
|
|
f" {int(detail.sum())} kept as painted details", flush=True)
|
|
# character fixes: a paint dissolved (where `where` says, in game metres) into whatever paint surrounds it
|
|
for colr, where in cfg.get("dissolve", []):
|
|
dc = np.linalg.norm(C - lab(np.array(colr)), axis=1)
|
|
i = int(np.argmin(dc))
|
|
if dc[i] > DISSOLVE_DE:
|
|
# the map has no such paint this time (it went into a neighbour): nothing to dissolve
|
|
print(f" no paint near {colr} (nearest {srgb_of(C[i])}, dE {dc[i]:.1f}): nothing dissolved", flush=True)
|
|
continue
|
|
m = hit & (lab_ == i)
|
|
if where is not None:
|
|
m &= where(d)
|
|
loose |= m
|
|
print(f" paint {i} {srgb_of(C[i])} dissolved: {int(m.sum())} texels", flush=True)
|
|
# on the arms, texels no ray reached (crew_rebake took the nearest point of the source, which next to a sleeve's
|
|
# end is the sleeve's inside or the torso) are not trusted either
|
|
if "how" in d:
|
|
guessw = hit & (d["how"] == 2) & (d["armw"] > 0.3)
|
|
loose |= guessw
|
|
print(f" arm texels with no ray hit, painted from round them: {int(guessw.sum())}", flush=True)
|
|
# loose texels are taken by the paint round them, ring by ring, the loose ones not voting
|
|
lab_ = vote_fill(lab_, loose, n)
|
|
lab_ = smooth_labels(lab_, hit, n)
|
|
# the borders between paints as smooth curves: a wide vote (blurred one-hot, ~+-9 px, only over chart texels, so
|
|
# nothing reaches across the 15 px gaps between charts) files off torn edges and blotches; small painted details
|
|
# (stitches, stars, buttons, rivets) it would swallow are put back, unless they lie against a big area of their own
|
|
# paint (then they are a blotch of it bleeding over the border)
|
|
wide = smooth_labels(lab_, hit, n, sigma=BORDER_SIGMA)
|
|
ids2 = components(lab_, hit)
|
|
size2 = np.bincount(ids2[hit].ravel(), minlength=ids2.size)
|
|
sz = size2[np.maximum(ids2, 0)]
|
|
lost = hit & (wide != lab_)
|
|
dE2 = np.linalg.norm(C[np.maximum(lab_, 0)] - C[np.maximum(wide, 0)], axis=-1)
|
|
near_big = np.zeros(hit.shape, bool)
|
|
for l in range(n):
|
|
big = (lab_ == l) & (sz >= BIG_PATCH)
|
|
if big.any():
|
|
near_big |= (lab_ == l) & (blur(big.astype(np.float32), 0.6) > 0.01) & ~big
|
|
pid = np.where(hit, ids2, 0)
|
|
against = np.bincount(pid[near_big].ravel(), minlength=ids2.size) > 0
|
|
keep = lost & (sz >= MIN_DETAIL) & (sz < BIG_PATCH) & (dE2 > DETAIL_DE) & ~against[np.maximum(ids2, 0)]
|
|
keep_ids = np.bincount(pid[keep].ravel(), minlength=ids2.size) > 0
|
|
back = hit & keep_ids[np.maximum(ids2, 0)]
|
|
print(f" borders smoothed: {int(lost.sum())} texels changed paint, {int((back & lost).sum())} of them put back as details", flush=True)
|
|
lab_ = np.where(back, lab_, wide)
|
|
lab_ = smooth_labels(lab_, hit, n) # one more fine pass over the joins
|
|
# the paint's own colour, and its lightness blurred within it (loose texels' own lightness is not trusted)
|
|
med = np.zeros((n, 3))
|
|
for l in range(n):
|
|
m = (lab_ == l) & ~loose
|
|
if m.any():
|
|
med[l] = np.median(Lab[m], 0)
|
|
dL = Lab[..., 0] - med[np.maximum(lab_, 0), 0]
|
|
sh = np.zeros(hit.shape, np.float32)
|
|
for l in range(n):
|
|
m = ((lab_ == l) & ~loose).astype(np.float32)
|
|
inl = lab_ == l
|
|
if not inl.any():
|
|
continue
|
|
num = blur((dL * m).astype(np.float32), SHADE_SIGMA)
|
|
den = blur(m, SHADE_SIGMA)
|
|
num2 = blur((dL * m).astype(np.float32), SHADE_SIGMA * 4)
|
|
den2 = blur(m, SHADE_SIGMA * 4)
|
|
far = num2 / np.maximum(den2, 1e-4) * (den2 > 1e-3)
|
|
sh = np.where(inl, np.where(den > 0.05, num / np.maximum(den, 1e-4), far), sh)
|
|
out = med[np.maximum(lab_, 0)].copy()
|
|
out[..., 0] += np.clip(SHADE_KEEP * sh, *SHADE_CLIP)
|
|
rgb = unlab(out)
|
|
# areas kept exactly as carried
|
|
pos = d["pos"].astype(np.float64)
|
|
keep = np.zeros(hit.shape, np.float32)
|
|
for c, r in cfg.get("protect", []):
|
|
dist = np.linalg.norm(pos - np.array(c), axis=-1)
|
|
keep = np.maximum(keep, np.clip((r - dist) / (0.25 * r), 0, 1))
|
|
# ... and front-facing areas given as discs (x, z, r) in game metres seen from the front: badges, ID cards, buckles
|
|
for x, z, r in cfg.get("protect_front", []):
|
|
dist = np.hypot(gpos[..., 0] - x, gpos[..., 2] - z)
|
|
front = (gpos[..., 1] < 0.02) & (d["ngame"][..., 1] < 0.35)
|
|
keep = np.maximum(keep, np.clip((r - dist) / (0.2 * r), 0, 1) * front)
|
|
keep *= hit
|
|
if keep.any():
|
|
k3 = col.astype(np.float32)
|
|
rgb = rgb * (1 - keep[..., None]) + k3 * keep[..., None]
|
|
print(f" kept as painted: {int((keep > 0.5).sum())} texels", flush=True)
|
|
# the cap logo
|
|
if "logo" in cfg:
|
|
rgb = logo(rgb, pos, d["nor"].astype(np.float64), lab_, hit, cfg["logo"], C)
|
|
# anti-aliased borders between paints
|
|
edge = np.zeros(hit.shape, bool)
|
|
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
|
|
edge |= (np.roll(lab_, (dy, dx), (0, 1)) != lab_) & np.roll(hit, (dy, dx), (0, 1))
|
|
edge &= hit
|
|
hf = hit.astype(np.float32)
|
|
soft = blur((rgb * hf[..., None]).astype(np.float32), 0.6) / np.maximum(blur(hf, 0.6), 1e-4)[..., None]
|
|
ring = (blur(edge.astype(np.float32), 0.6) > 0.02) & hit & ~edge
|
|
rgb = np.where(edge[..., None], 0.35 * rgb + 0.65 * soft, np.where(ring[..., None], 0.7 * rgb + 0.3 * soft, rgb))
|
|
# the crew's common light: a little occlusion and a top light, in linear
|
|
lin = srgb_to_lin(rgb)
|
|
ao = np.clip(d["ao"], 0, 1)
|
|
hf1 = hit.astype(np.float32)
|
|
ao = blur((ao * hf1).astype(np.float32), 1.0) / np.maximum(blur(hf1, 1.0), 1e-4)
|
|
ao = np.where(hit, ao, 1)
|
|
shade = (1 - AO_STRENGTH * (1 - ao)) * (1 + TOP_LIGHT * d["ngame"][..., 2])
|
|
rgb = lin_to_srgb(lin * shade[..., None])
|
|
rgb = fill(rgb.astype(np.float32), hit)
|
|
print(f" repainted in {time.time() - t0:.0f}s", flush=True)
|
|
return rgb, lab_, med
|
|
|
|
|
|
def logo(rgb, pos, nor, lab_, hit, L, C):
|
|
"""A neat team badge on Marcus's cap (worn back to front, so the badge looks back over his shoulder): a cream disc
|
|
with a gold rim and a green three-blade grass tuft, the crew's mark. Drawn in the plane facing L['dir'] (source
|
|
units), centred on the cap where its surface faces that way in the height band L['band']; on the cap paint only."""
|
|
dr = np.array(L["dir"], float)
|
|
dr /= np.linalg.norm(dr)
|
|
cap = int(np.argmin(np.linalg.norm(C - lab(np.array(L["cap"])), axis=1)))
|
|
on_cap = hit & (lab_ == cap)
|
|
z0, z1 = L["band"]
|
|
facing = on_cap & ((nor @ dr) > 0.85) & (pos[..., 2] > z0) & (pos[..., 2] < z1)
|
|
c = np.median(pos[facing], 0)
|
|
c[2] = (z0 + z1) / 2
|
|
R = L["r"]
|
|
ux = np.array([dr[1], -dr[0], 0.0])
|
|
ux /= np.linalg.norm(ux)
|
|
rel = pos - c
|
|
u = (rel @ ux) / R
|
|
v = rel[..., 2] / R
|
|
on = on_cap & ((nor @ dr) > 0.3) & (np.abs(rel @ dr) < 2.5 * R)
|
|
rr = np.sqrt(u * u + v * v)
|
|
aa = 0.05
|
|
ss = lambda x: np.clip(x / aa + 0.5, 0, 1)
|
|
disc = ss(1.0 - rr)
|
|
inner = ss(0.80 - rr)
|
|
tuft = np.zeros_like(u)
|
|
for (bx, by), (tx, ty), wd in (((0.0, -0.45), (0.0, 0.58), 0.17), ((-0.08, -0.45), (-0.5, 0.3), 0.14),
|
|
((0.08, -0.45), (0.5, 0.3), 0.14), ((-0.2, -0.45), (-0.62, -0.05), 0.1),
|
|
((0.2, -0.45), (0.62, -0.05), 0.1)):
|
|
ax = np.array([tx - bx, ty - by])
|
|
ln = np.linalg.norm(ax)
|
|
ax /= ln
|
|
t = ((u - bx) * ax[0] + (v - by) * ax[1]) / ln
|
|
perp = np.abs(-(u - bx) * ax[1] + (v - by) * ax[0])
|
|
half = wd * np.clip(1 - t, 0, 1) ** 0.9
|
|
tuft = np.maximum(tuft, ss(half - perp) * (t > -0.05) * ss(1 - t))
|
|
ground = ss(0.07 - np.abs(v + 0.47)) * ss(0.6 - np.abs(u))
|
|
tuft = np.maximum(tuft, ground) * inner
|
|
out = rgb.copy()
|
|
for mask, colr in ((disc, L["rim"]), (inner, L["face"]), (tuft, L["mark"])):
|
|
m = (mask * on)[..., None]
|
|
out = out * (1 - m) + np.array(colr) * m
|
|
print(f" cap logo at {np.round(c, 3)} facing {np.round(dr, 2)}: {int((disc * on > 0.5).sum())} texels", flush=True)
|
|
return out
|
|
|
|
def run(name, scratch):
|
|
print(f"=== {name}", flush=True)
|
|
d = dict(np.load(os.path.join(scratch, name + "_maps.npz")))
|
|
rgb, lab_, med = repaint(name, d)
|
|
os.makedirs(OUT, exist_ok=True)
|
|
save_png(rgb, os.path.join(OUT, "T_Crew_" + name.capitalize() + ".png"))
|
|
# the paint map, for checking
|
|
vis = unlab(med[np.maximum(lab_, 0)])
|
|
vis[lab_ < 0] = 0
|
|
save_png(vis, os.path.join(scratch, name + "_paints.png"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
args = sys.argv[sys.argv.index("--") + 1:]
|
|
scratch = args[0]
|
|
for nm in (args[1:] or CREW + DIRECTOR):
|
|
run(nm, scratch)
|