Grass Cutters Together: the project as of moon-sweepers f3666f0

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-06 18:44:40 +06:00
parent 0f0467cd0c
commit d1c3761e58
4190 changed files with 270757 additions and 1 deletions

206
Tools/Trailer/lipsync.py Normal file
View File

@ -0,0 +1,206 @@
"""Lip sync by casting, not by animation: the Director's and the assistant's filmed loops (ArtSource/Director/video) are
searched for the stretch whose mouth opens and shuts most like the line being spoken, and that stretch becomes a take.
The mouth is found by following the eyes (template matching against the first frame) and measuring how much of a box under
the nose is dark (an open mouth shows its inside). The line's loudness, frame by frame at the loop's 24 fps, is compared with
that, over every loop of the right mood, every start and a few speeds. A line is split at its pauses, and each part gets its
own stretch, so the cut between them is a cut on a pause.
Each part is written as a take of 1920x1080 frames at 60 fps (the figure keyed over the mission-control backdrop) into
Builds/Trailer/rolls_z/d_<line>_<part>, and lipsync.json says where the parts go: the edit reads it.
py -I lipsync.py
"""
import json
import os
import subprocess
import sys
import wave
import cv2
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.normpath(os.path.join(HERE, "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "Tools", "director"))
import talk_videos # noqa: E402
from talk_videos import frames, key # noqa: E402
VID = os.path.join(ROOT, "ArtSource", "Director", "video")
AUDIO = os.path.join(ROOT, "Assets", "Audio")
OUT = os.path.join(ROOT, "Builds", "Trailer", "rolls_z")
BG = os.path.join(ROOT, "Assets", "Art", "UI", "T_Dir_BgWide.png")
FPS, OFPS = 24, 60
W, H = 1920, 1080
# where the face is in each loop's first frame: the eyes to follow, the mouth to measure (x0, y0, x1, y1)
FACE = {
"boss": {"eyes": (230, 240, 560, 370), "mouth": (325, 398, 445, 455)},
"asst": {"eyes": (250, 250, 520, 350), "mouth": (300, 360, 430, 425)},
}
# the trailer's own takes of their lines (Eleven v4, trimmed to the voice): name: (file, from, to, loops to try)
LINE_DIR = os.path.join(ROOT, "ArtSource", "Trailer", "boss")
LINES = {
"earth": ("dir_earth", 0.0, None, ["boss_angry", "boss_stern"]),
"scissors": ("dir_scissors", 0.0, None, ["boss_angry", "boss_stern"]),
"did": ("dir_did", 0.0, None, ["boss_calm", "boss_stern"]),
"noted": ("asst_noted", 0.0, None, ["asst_fed", "asst_stern"]),
}
def mouth_track(loop):
"""Per frame: how open the mouth is, and where the face is (offset from the first frame)."""
who = loop.split("_")[0]
ex0, ey0, ex1, ey1 = FACE[who]["eyes"]
mx0, my0, mx1, my1 = FACE[who]["mouth"]
tmpl, opens, offs = None, [], []
for rgb in frames(os.path.join(VID, loop + "_src.webm")):
g = cv2.cvtColor(rgb[:700], cv2.COLOR_RGB2GRAY)
if tmpl is None:
tmpl = g[ey0:ey1, ex0:ex1].copy()
dx = dy = 0
else:
m = cv2.matchTemplate(g, tmpl, cv2.TM_CCOEFF_NORMED)
_, _, _, (bx, by) = cv2.minMaxLoc(m)
dx, dy = bx - ex0, by - ey0
box = rgb[my0 + dy:my1 + dy, mx0 + dx:mx1 + dx].astype(np.float32)
v = box.max(axis=2)
inside = (v < 120) & (box[..., 0] > box[..., 2]) # dark and reddish: the inside of a mouth
teeth = (box.min(axis=2) > 200)
opens.append(float(inside.mean() + 0.5 * teeth.mean()))
offs.append((dx, dy))
return np.array(opens), offs
def decode(path, a, b):
p = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", "16000", "-"], capture_output=True, check=True)
x = np.frombuffer(p.stdout, np.float32)
end = len(x) if b is None else int(b * 16000)
return x[int(a * 16000):end]
def envelope(x):
hop = 16000 // FPS
n = len(x) // hop
e = np.array([np.sqrt(np.mean(x[i * hop:(i + 1) * hop] ** 2)) for i in range(n)])
return np.convolve(e, np.ones(2) / 2, mode="same")
def parts(env, gap=0.18, quiet=0.1):
"""Stretches of speech, split where it is quiet for longer than `gap` seconds."""
loud = env > quiet * env.max()
runs, start, still = [], None, 0
for i, on in enumerate(loud):
if on:
if start is None:
start = i
still = 0
elif start is not None:
still += 1
if still > gap * FPS:
runs.append((start, i - still + 1))
start = None
if start is not None:
runs.append((start, len(loud)))
# glue scraps under a third of a second onto their neighbour
out = []
for r in runs:
if out and (r[1] - r[0] < FPS / 3 or out[-1][1] - out[-1][0] < FPS / 3):
out[-1] = (out[-1][0], r[1])
else:
out.append(r)
return out
def z(v):
s = v.std()
return (v - v.mean()) / s if s > 1e-6 else v * 0
def best(env, tracks, loops, used):
"""The loop, first frame and speed whose mouth follows this loudness best."""
want = z(env)
top = (-9, None, 0, 1.0)
for loop in loops:
o = tracks[loop][0]
for speed in (0.8, 0.9, 1.0, 1.1, 1.25):
span = (len(env) - 1) * speed
for s in range(0, int(len(o) - span - 1)):
if any(loop == u and abs(s - us) < FPS for u, us in used):
continue
idx = (s + np.arange(len(env)) * speed).astype(int)
seq = o[idx]
score = float(np.mean(z(seq) * want)) + 0.15 * min(1.0, seq.std() / 0.05)
if score > top[0]:
top = (score, loop, s, speed)
return top
def render(name, loop, first, speed, frames_out, offs):
"""The stretch of the loop as a take: the figure, keyed, over the backdrop, head and shoulders filling the frame."""
folder = os.path.join(OUT, name)
os.makedirs(folder, exist_ok=True)
for f in os.listdir(folder):
os.remove(os.path.join(folder, f))
bg = cv2.imread(BG, cv2.IMREAD_COLOR)
s = max(W / bg.shape[1], H / bg.shape[0])
bg = cv2.resize(bg, (int(bg.shape[1] * s) + 1, int(bg.shape[0] * s) + 1), interpolation=cv2.INTER_AREA)
y0, x0 = (bg.shape[0] - H) // 2, (bg.shape[1] - W) // 2
bg = (bg[y0:y0 + H, x0:x0 + W].astype(np.float32) * np.array([0.95, 0.86, 0.82])).astype(np.float32)
# her loops sit on a lighter black than his: flood up to just over it
talk_videos.FLOOD = 20 if loop.startswith("asst") else 9
talk_videos.SOLID = talk_videos.FLOOD + 15
need = sorted({int(first + i * FPS / OFPS * speed) for i in range(frames_out)})
keep = {}
for i, rgb in enumerate(frames(os.path.join(VID, loop + "_src.webm"))):
if i in need:
keep[i] = (rgb, key(rgb))
if i > need[-1]:
break
top, crop = 30, 560 # head to chest
sc = H / crop
fw = int(768 * sc)
for k in range(frames_out):
i = min(int(first + k * FPS / OFPS * speed), max(keep))
rgb, a = keep[i]
fig = cv2.resize(cv2.cvtColor(rgb[top:top + crop], cv2.COLOR_RGB2BGR), (fw, int(crop * sc)), interpolation=cv2.INTER_AREA).astype(np.float32)
al = cv2.resize(a[top:top + crop], (fw, int(crop * sc)), interpolation=cv2.INTER_AREA).astype(np.float32)[..., None] / 255
out = bg.copy()
fx = (W - fw) // 2
fh = min(H, fig.shape[0])
out[:fh, fx:fx + fw] = fig[:fh] * al[:fh] + out[:fh, fx:fx + fw] * (1 - al[:fh])
cv2.imwrite(os.path.join(folder, "%05d.jpg" % k), out.astype(np.uint8), [cv2.IMWRITE_JPEG_QUALITY, 93])
def main():
tracks = {}
plan = {}
for name, (clip, a, b, loops) in LINES.items():
for loop in loops:
if loop not in tracks:
tracks[loop] = mouth_track(loop)
o = tracks[loop][0]
print(f"{loop}: {len(o)} frames, open {o.min():.3f}..{o.max():.3f}")
x = decode(os.path.join(LINE_DIR, clip + ".wav"), a, b)
env = envelope(x)
used, out = [], []
runs = parts(env)
# the parts tile the whole line: each runs to where the next starts, the last just past the end
cuts = [0] + [max(0, r[0] - 2) for r in runs[1:]] + [len(env) + 2]
for k in range(len(runs)):
lo, hi = cuts[k], cuts[k + 1]
score, loop, first, speed = best(np.pad(env, (0, 6))[lo:hi], tracks, loops, used)
used.append((loop, first))
take = f"d_{name}_{k}"
secs = (hi - lo) / FPS
render(take, loop, first, speed, int(secs * OFPS) + 18, tracks[loop][1])
out.append({"take": take, "at": lo / FPS, "secs": secs, "loop": loop, "first": first, "speed": speed, "score": round(score, 3)})
print(f"{take}: {lo / FPS:5.2f}+{secs:4.2f}s {loop} from {first} x{speed} score {score:.2f}")
plan[name] = {"clip": os.path.relpath(os.path.join(LINE_DIR, clip + ".wav"), ROOT).replace(os.sep, "/"), "from": a, "to": b if b is not None else a + len(x) / 16000, "parts": out}
with open(os.path.join(HERE, "lipsync.json"), "w") as f:
json.dump(plan, f, indent=1)
if __name__ == "__main__":
main()