Trailer: HUD takes showed the phone's screen; cut.py renders in parallel

- The trailer, BotCapture and PhoneScreen picked "any" UIDocument; since the phone has
  its own (drawn into its screen in the hand) the first-person takes captured the
  phone's home screen instead of the HUD. They take UIRoot's document now.
- cut.py renders a whole film in GC_CUT_WORKERS processes (20 by default), each a
  stretch of frames as near-lossless x264, joined and encoded once on NVENC with the
  sound. Shake and grain are seeded by frame, so the result does not depend on the
  split. Main trailer 57 -> 13 min.
- polden.py and story.py read the single rolls folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-12-01 21:31:02 +06:00
parent 9f6b749bad
commit dd0430048b
6 changed files with 62 additions and 14 deletions

View File

@ -27,7 +27,7 @@ namespace GrassCutter
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main; var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (cam) cam.targetTexture = _scene; if (cam) cam.targetTexture = _scene;
_cam = cam; _cam = cam;
var doc = Object.FindAnyObjectByType<UIDocument>(); var doc = UIRoot.I ? UIRoot.I.GetComponent<UIDocument>() : Object.FindAnyObjectByType<UIDocument>();
if (doc && doc.panelSettings) if (doc && doc.panelSettings)
{ {
doc.panelSettings.targetTexture = _ui; doc.panelSettings.targetTexture = _ui;

View File

@ -18,7 +18,8 @@ namespace GrassCutter
void Eyes(bool on) void Eyes(bool on)
{ {
var fx = _cam.GetComponent<CameraFx>(); var fx = _cam.GetComponent<CameraFx>();
var doc = FindAnyObjectByType<UIDocument>(); // the HUD's own document: the phone has one of its own, drawn into its screen in the hand
var doc = UIRoot.I ? UIRoot.I.GetComponent<UIDocument>() : null;
if (on) if (on)
{ {
_cam.transform.SetParent(Me.head, false); _cam.transform.SetParent(Me.head, false);

View File

@ -71,7 +71,7 @@ namespace GrassCutter
Tex.Create(); Tex.Create();
Web = new PhoneWeb((float)WebH / W, (float)H / W); Web = new PhoneWeb((float)WebH / W, (float)H / W);
var main = UnityEngine.Object.FindAnyObjectByType<UIDocument>(FindObjectsInactive.Include); var main = UIRoot.I ? UIRoot.I.GetComponent<UIDocument>() : UnityEngine.Object.FindAnyObjectByType<UIDocument>(FindObjectsInactive.Include);
var ps = UnityEngine.Object.Instantiate(main.panelSettings); var ps = UnityEngine.Object.Instantiate(main.panelSettings);
ps.targetTexture = Tex; ps.targetTexture = Tex;
ps.scaleMode = PanelScaleMode.ConstantPixelSize; ps.scaleMode = PanelScaleMode.ConstantPixelSize;

View File

@ -303,7 +303,8 @@ class Logo:
# ───────────────────────── the render ───────────────────────── # ───────────────────────── the render ─────────────────────────
def render(edl, out, span=None): def render(edl, out, span=None, part=None):
"""part=(first, last) renders just those output frames, picture only: what parallel() hands each worker."""
clock = Clock(edl.KEEP) clock = Clock(edl.KEEP)
song = decode(getattr(edl, "TRACK", TRACK)) * getattr(edl, "TRACK_GAIN", 1.0) song = decode(getattr(edl, "TRACK", TRACK)) * getattr(edl, "TRACK_GAIN", 1.0)
kick = pulse(song) kick = pulse(song)
@ -314,19 +315,23 @@ def render(edl, out, span=None):
for s in shots: for s in shots:
rolls.setdefault(s.take, Roll(os.path.join(edl.ROLLS, s.take))) rolls.setdefault(s.take, Roll(os.path.join(edl.ROLLS, s.take)))
wav = out + ".wav" wav = out + ".wav"
mix(song, clock, getattr(edl, "SFX", []), wav)
first, last = 0, int(clock.total * FPS) first, last = 0, int(clock.total * FPS)
if span: if span:
first, last = int(clock.out(span[0]) * FPS), int(clock.out(span[1]) * FPS) first, last = int(clock.out(span[0]) * FPS), int(clock.out(span[1]) * FPS)
cmd = ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-", enc = ["-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "20", "-b:v", "16M", "-maxrate", "30M", "-pix_fmt", "yuv420p"]
"-ss", f"{first / FPS:.3f}", "-t", f"{(last - first) / FPS:.3f}", "-i", wav, vin = ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-"]
"-map", "0:v", "-map", "1:a", "-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "20", "-b:v", "16M", "-maxrate", "30M", if part:
"-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "320k", "-shortest", out] # a part is an intermediate: near-lossless x264 on the CPU, since a GeForce opens only 8 NVENC sessions at once
first, last = part
cmd = vin + ["-c:v", "libx264", "-preset", "ultrafast", "-crf", "12", "-pix_fmt", "yuv420p", out]
else:
mix(song, clock, getattr(edl, "SFX", []), wav)
cmd = vin + ["-ss", f"{first / FPS:.3f}", "-t", f"{(last - first) / FPS:.3f}", "-i", wav,
"-map", "0:v", "-map", "1:a"] + enc + ["-c:a", "aac", "-b:a", "320k", "-shortest", out]
pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE) pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE)
hits = getattr(edl, "FLASH", []) hits = getattr(edl, "FLASH", [])
types = getattr(edl, "TYPE", []) types = getattr(edl, "TYPE", [])
pool = ThreadPoolExecutor(6) pool = ThreadPoolExecutor(6)
rng = random.Random(3)
idx = 0 idx = 0
def active(tt): def active(tt):
@ -357,6 +362,8 @@ def render(edl, out, span=None):
for n in range(first, last): for n in range(first, last):
t = n / FPS t = n / FPS
tt = clock.track(t) tt = clock.track(t)
# seeded by the frame, so any stretch renders the same on its own (the parallel parts rely on it)
rng = random.Random(n * 7919 + 3)
s = active(tt) s = active(tt)
if s is None: if s is None:
pipe.stdin.write(np.zeros((H, W, 3), np.uint8).tobytes()) pipe.stdin.write(np.zeros((H, W, 3), np.uint8).tobytes())
@ -398,7 +405,39 @@ def render(edl, out, span=None):
print(f"{idx}/{last - first}", flush=True) print(f"{idx}/{last - first}", flush=True)
pipe.stdin.close() pipe.stdin.close()
pipe.wait() pipe.wait()
os.remove(wav) if not part:
os.remove(wav)
def parallel(edl_path, edl, out, workers):
"""The whole film in `workers` processes at once, each a stretch of frames (picture only), then joined without
re-encoding and the mixed sound laid under it. Same frames as one long render, many times faster."""
import time
clock = Clock(edl.KEEP)
total = int(clock.total * FPS)
cuts = [round(total * k / workers) for k in range(workers + 1)]
parts = [f"{out}.part{k}.mp4" for k in range(workers)]
env = dict(os.environ, OPENCV_FOR_THREADS_NUM="3", OMP_NUM_THREADS="3")
t0 = time.time()
procs = [subprocess.Popen([sys.executable, "-I", os.path.abspath(__file__), edl_path, parts[k], "--part", str(cuts[k]), str(cuts[k + 1])], env=env)
for k in range(workers)]
song = decode(getattr(edl, "TRACK", TRACK)) * getattr(edl, "TRACK_GAIN", 1.0)
wav = out + ".wav"
mix(song, clock, getattr(edl, "SFX", []), wav)
bad = [k for k, p in enumerate(procs) if p.wait() != 0]
if bad:
raise SystemExit(f"parts failed: {bad}")
lst = out + ".parts.txt"
with open(lst, "w") as f:
for p in parts:
f.write("file '" + os.path.abspath(p).replace(os.sep, "/") + "'" + chr(10))
# one pass on the GPU makes the final film from the joined parts
subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", lst, "-i", wav, "-map", "0:v", "-map", "1:a",
"-c:v", "h264_nvenc", "-preset", "p6", "-rc", "vbr", "-cq", "20", "-b:v", "16M", "-maxrate", "30M", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "320k", "-shortest", out], check=True)
for p in parts + [lst, wav]:
os.remove(p)
print(f"{total} frames in {time.time() - t0:.0f} s with {workers} workers", flush=True)
if __name__ == "__main__": if __name__ == "__main__":
@ -410,4 +449,12 @@ if __name__ == "__main__":
sys.modules["cut"] = sys.modules["__main__"] sys.modules["cut"] = sys.modules["__main__"]
spec.loader.exec_module(edl) spec.loader.exec_module(edl)
setup(*getattr(edl, "SIZE", (1920, 1080))) setup(*getattr(edl, "SIZE", (1920, 1080)))
render(edl, sys.argv[2], (float(sys.argv[3]), float(sys.argv[4])) if len(sys.argv) > 4 else None) args = sys.argv[3:]
if args[:1] == ["--part"]:
cv2.setNumThreads(3)
render(edl, sys.argv[2], part=(int(args[1]), int(args[2])))
elif len(args) >= 2:
render(edl, sys.argv[2], (float(args[0]), float(args[1])))
else:
# the whole film: in parallel (GC_CUT_WORKERS, 20 by default on this 32-thread machine)
parallel(sys.argv[1], edl, sys.argv[2], int(os.environ.get("GC_CUT_WORKERS", "20")))

View File

@ -30,7 +30,7 @@ B = 60 / 129.2 # the music's beat
def roll(take): def roll(take):
base = take.split("@")[0] base = take.split("@")[0]
for d in ("rolls_z", "rolls3", "rolls_1105"): for d in ("rolls_z", "rolls"):
if os.path.isdir(os.path.join(TR, d, base)): if os.path.isdir(os.path.join(TR, d, base)):
return os.path.join(TR, d, take) return os.path.join(TR, d, take)
raise SystemExit("no take " + take) raise SystemExit("no take " + take)

View File

@ -16,7 +16,7 @@ import numpy as np
from cut import PROJECT, SR, Logo, Shot, Type, decode from cut import PROJECT, SR, Logo, Shot, Type, decode
from looks import AUDIO, GOLD, HOT, LOGO, NIGHT, PLAY, SPACE, clip # noqa: F401 from looks import AUDIO, GOLD, HOT, LOGO, NIGHT, PLAY, SPACE, clip # noqa: F401
ROLLS = os.path.join(PROJECT, r"Builds\Trailer\rolls3") ROLLS = os.path.join(PROJECT, r"Builds\Trailer\rolls")
OUT = os.path.join(PROJECT, r"Builds\Trailer\story") OUT = os.path.join(PROJECT, r"Builds\Trailer\story")
os.makedirs(OUT, exist_ok=True) os.makedirs(OUT, exist_ok=True)
PUNCH, SHAKE, ABERRATE = 0.006, 1.2, 0.6 PUNCH, SHAKE, ABERRATE = 0.006, 1.2, 0.6