A 3D model pipeline, pushed by Fable 5.2
agent
+1:03Read the brief, handbook, reflection and handoff. Now testing whether the old costume kit dresses the current slender body, aiming for one dressed, posed character in a battle frame.
Bashcd ~/Projects/lowmarch-fable52 && ls [redacted: private path]/vroid/lowmarch_bodies | head -40; python3 - <<'E'
command
cd ~/Projects/lowmarch-fable52 && ls [redacted: private path]/vroid/lowmarch_bodies | head -40; python3 - <<'E' import sys,os sys.path[:0]=["tools","art/cast","review/vroid-02"] from cast import CAST import cage c=CAST["arm_f_slender"] p=cage.path_for("arm_f_slender",c["cage"]); print(p, os.path.exists(p)) print({k:v for k,v in c.items() if k not in("cage",)}) Eresult, 12 lines
base_fem.vrm base_masc.vrm brute.vroid cage heads mass vroid_broad_v2.vrm vroid_brute.vrm vroid_stocky2.vrm vroid_stocky_v2.vrm [redacted: private path]/vroid/lowmarch_bodies/cage/arm_f_slender_81550a78f4ae4dbd.vrm True {'model': 'lowmarch_bodies/base_fem.vrm', 'hair': None, 'label': 'Woman, slender', 'costume': 'mob_underwear_f', 'shape': {'hands': 1.0}, 'colors': {'A': '#6b4a1e', 'B': '#a8782e', 'C': '#d4a648', 'D': '#ecd07a', 'E': '#fbf0c0', 'r': '#1a2a4a', 's': '#3a6ab0', 't': '#8ac0ec', 'K': '#3a1418', 'L': '#5e2026', 'M': '#7e2a30', 'P': '#a84848'}, 'paint': {'signature': '#7b3026', 'doublet': '#3a3330', 'heraldry': '#d8cfc0', 'leather': '#5a3e2a', 'boot': '#3e2c22', 'glove': '#4a3426', 'steel': '#9aa0aa', 'gold': '#a88a4a', 'hair': '#d4a648', 'motif': '#d8cfc0', 'padding': '#8a7a62', 'cloth': '#4a4038', 'wood': {'kind': 'leather', 'base': '#6a4a30'}, 'mail': {'kind': 'steel', 'base': '#8a909a'}, 'fur': {'kind': 'leather', 'base': '#6a5444'}, 'linen': '#b8ad94', 'grain': {'signature': 0.03, 'padding': 0.03, 'fur': 0.1}}, 'group': 'Women', 'archetype': 'young', 'sex': 'f', 'ranges': {}}Bashcd ~/Projects/lowmarch-fable52 && sed -n 942,1034p tools/outfit.py; cat tools/clips.py | sed -n 1,139p
command
cd ~/Projects/lowmarch-fable52 && sed -n 942,1034p tools/outfit.py; cat tools/clips.py | sed -n 1,139p
result, 232 lines
def knight_dress(fit): """A blonde knight-princess: a long blue dress with a white petticoat edge, a fitted steel breastplate, small spaulders, steel gauntlets and armoured boots, a two-handed sword with a gold hilt, and her hair up in a braided bun with a ribbon.""" B = fit.bone nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] knee = B["J_Bip_L_LowerLeg"][1] out = [] def grouped(pcs, g): for pc in pcs: if pc is not None: pc["group"] = g return [pc for pc in pcs if pc is not None] def rolled(name, pc, rims, r=0.0024, role="metal"): return [inherit(pipe(f"{name}_roll{k}", role, rim, r=r), pc) for k, rim in enumerate(rims)] def cuff_plane(side): a, hd = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"] n = (hd - a) / np.linalg.norm(hd - a) return n, n @ (hd - n * 0.035) torso = ("Spine", "Chest", "UpperChest", "Bust", "Shoulder", "UpperArm", "LowerArm", "Neck", "Hips") bodice = wrap(fit, "bodice", "signature", torso, offset=0.006, exclude=("UpperLeg",), y_min=hips[1] + 0.02, y_max=nk[1] + 0.012, hems=[cuff_plane("L"), cuff_plane("R")]) tights = wrap(fit, "tights", "doublet", ("Hips", "UpperLeg", "LowerLeg"), offset=0.004, y_max=hips[1] + 0.03, subdiv=1) boots = wrap(fit, "boots", "metal", ("LowerLeg", "Foot"), offset=0.014, y_max=knee - 0.06, exclude=("ToeBase",), subdiv=1, hems=[((0, 1, 0), knee - 0.065)]) gloves = wrap(fit, "gloves", "metal", ("Hand", "Thumb", "Index", "Middle", "Ring", "Little"), offset=0.0035, min_w=0.3, smooth=4) out += grouped([bodice], "dress") + grouped([tights], "trousers") + grouped([boots], "boots") + grouped([gloves], "gloves") out += grouped(sabaton(fit, "sabaton_L", "L") + sabaton(fit, "sabaton_R", "R"), "boots") col, rim, _ = collar(fit, "collar", "signature", height_back=0.034, height_front=0.022) out += grouped([col, inherit(pipe("collar_trim", "gold", rim, r=0.0022), col)], "dress") # steel breastplate, fitted, ending at the natural waist; gold line along the neckline cuirass = wrap(fit, "breastplate", "steel", ("Spine", "Chest", "UpperChest", "Bust"), offset=0.010, # the female # base weights the chest to its own Bust bones: leave them out and the plate has two holes exclude=("Shoulder", "UpperArm", "Neck"), y_min=hips[1] + 0.085, y_max=nk[1] - 0.065, base=Surface(bodice["pos"], bodice["tri"]), smooth=70, # a rigid shell, not a moulded bust hems=[((0, 1, 0), hips[1] + 0.095), ((0, 1, 0), nk[1] - 0.075)]) loops = sorted([cuirass["pos"][L] for L in cuirass["loops"] if len(L) > 12], key=lambda Lp: -Lp[:, 1].mean()) out += grouped([cuirass] + [inherit(pipe(f"breastplate_roll{k}", "gold" if k == 0 else "metal", Lp, r=0.003, closed=True), cuirass) for k, Lp in enumerate(loops)], "plate") # the skirt from the waist to the ankle, white petticoat edge (the viewer's border band) legs = merge_surfaces((tights["pos"], tights["tri"]), (boots["pos"], boots["tri"])) # the waist ring is cast onto the bodice without its sleeves: with them, the hanging arms beside # the hips held the ring out at the sides, a shelf the user saw once the arms moved waist = merge_surfaces(without(bodice, ("Shoulder", "UpperArm", "LowerArm", "Hand")), (tights["pos"], tights["tri"])) ytop = hips[1] + 0.08 sk, grid = skirt(fit, "skirt", "signature", waist, legs, ytop, ytop - 0.24, flare=0.17) # hem above the ankle sk["group"] = "dress" out.append(sk) out += grouped([inherit(ribbon("skirt_hem", "heraldry", np.concatenate([grid[:, -1], grid[:1, -1]]), width=0.03, lift=0.0015, normals=near_normals(sk, np.concatenate([grid[:, -1], grid[:1, -1]]))), sk)], "dress") out += grouped([inherit(pipe("waist_trim", "gold", grid[:, 0], r=0.0035, closed=True), sk)], "dress") plate_body = merge_surfaces((cuirass["pos"], cuirass["tri"]), (bodice["pos"], bodice["tri"]), (fit.pos, fit.tri)) for side in ("L", "R"): ll, ft = B[f"J_Bip_{side}_LowerLeg"], B[f"J_Bip_{side}_Foot"] la, hd = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"] sp, rims = pauldron(fit, f"spaulder_{side}", "steel", plate_body, side=side, lames=((0, 54, 0.016, 0.022), (46, 76, 0.014, 0.020)), spread=105) out += grouped(sp, "plate") + grouped(sum((rolled(f"spaulder_{side}{k}", pc, [r_]) for k, (pc, r_) in enumerate(zip(sp, rims))), []), "plate") fore = limb_surface(fit, (f"{side}_LowerArm",), side) vb, rims = limb_lames(fit, f"vambrace_{side}", "steel", fore, la, hd, ((0.10, 0.97, 0.014, 0.017),), rmax=0.11) fit.bind(vb[0], rigid=f"J_Bip_{side}_LowerArm") out += grouped(vb + rolled(f"vambrace_{side}", vb[0], rims[0]), "plate") arm = limb_surface(fit, (f"{side}_LowerArm", f"{side}_UpperArm"), side) jg, jr = joint_guard(fit, f"couter_{side}", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand", (0, 0, 1), side, arm, r=0.026, wing=0.042, depth=0.018) for pc in jg: fit.bind(pc, rigid=f"J_Bip_{side}_LowerArm") out += grouped(jg, "plate") shin = side_of(boots, side) # the greave starts below the boot's top: above it the casts find no boot and the knee bulges past it top = (knee - 0.075 - ll[1]) / (ft[1] - ll[1]) gv, rims = limb_lames(fit, f"greave_{side}", "steel", shin, ll, ft, ((top, 0.80, 0.006, 0.009),), rmax=0.11) fit.bind(gv[0], rigid=f"J_Bip_{side}_LowerLeg") out += grouped(gv + rolled(f"greave_{side}", gv[0], rims[0]), "plate") import hair out += [pc for pc in updo(fit) if pc["material"] != "OUTFIT_cowlick"] + hair.elaine(fit) out += sword(fit, "R", blade_len=0.84, blade_w=0.046, grip_len=0.21, hilt="gold", grip="signature") return [p for p in out if p is not None] # ---- costumes ------------------------------------------------------------------------- def lord_tunic(fit): """Battle animation clips, authored as a few key poses and finished with the rig tools (feet planted or stepped with leg IK, the sword aimed by direction rather than by wrist angles). clips(vrm, shape, stance) -> {name: [(time, pose), ...]} """ import numpy as np import poses as P from rig import Rig BLADE = (0, 0, -1) # the sword's blade in the right hand's frame (see outfit.sword) def clips(vrm, shape=None, stance="sword"): """stance: "sword" (one hand, the cast's default) or "polearm" (both hands, see polearm()).""" if stance == "polearm": return polearm(vrm, shape) rig = Rig(vrm, shape) idle = P.BATTLE_IDLE foot = {s: rig.pos(idle, f"J_Bip_{s}_Foot") for s in "LR"} step = np.array([0.0, 0.0, -0.36]) # the lead (left) foot steps forward def finish(pose, lead=0.0, blade=None): pose = rig.leg_ik(pose, "L", foot["L"] + step * lead) pose = rig.leg_ik(pose, "R", foot["R"]) if blade is not None: pose = rig.aim(pose, "J_Bip_R_Hand", BLADE, blade) return pose wind = finish(P.WIND_UP, 0.0, blade=(0.15, 0.55, 1.0)) # blade back over the shoulder slash = finish(P.SLASH, 1.0, blade=(0.1, -0.55, -1.0)) # forward and down through the target follow = finish(P.FOLLOW, 1.0, blade=(-0.45, -1.0, -0.15)) # carried down across the body breathe = finish(P.IDLE_BREATH, 0.0) return { "idle": [(0.0, idle), (0.9, breathe), (1.8, idle)], "attack": [(0.0, idle), (0.32, wind), (0.44, wind), (0.56, slash), (0.68, follow), (1.05, follow), (1.5, idle)], } def fists(rig): """Where each fist closes in the reference pose: the point a held weapon's shaft runs through, as gear._hand_frame places it (rig.grip_points: measured from the curled fingers).""" from rig import grip_points return {side: g["point"] for side, g in grip_points(rig.v, rig.shape, P.BUST).items()} # The polearm's keys: hips drop and forward shift, turn of the shoulders (- brings the left one # forward), forward lean, the lead foot's step; the right fist from the right shoulder in arm lengths # (x: the fighter's right, -z forward), the shaft's direction (head end), and the left arm's reach # (shoulder to fist, in arm lengths): the left fist holds the shaft where that reach meets it, so # every build gets bent elbows rather than a fixed hand spacing that some arms can't span. POLEARM = { "wind": dict(drop=0.075, turn=-26.0, lean=3.0, fwd=-0.03, lead=0.0, fist=(0.13, -0.52, -0.04), shaft=(-0.22, 0.30, -0.93), reach=0.78), "thrust": dict(drop=0.09, turn=-18.0, lean=14.0, fwd=0.17, lead=0.30, fist=(-0.10, -0.42, -0.50), shaft=(-0.28, 0.06, -0.96), reach=0.92), "follow": dict(drop=0.095, turn=-16.0, lean=16.0, fwd=0.19, lead=0.30, fist=(-0.12, -0.46, -0.52), shaft=(-0.28, 0.0, -0.96), reach=0.92), } # The guard's idle, after the study of Unicorn Overlord's idles (a mercenary's, tracked frame by frame): # a 2 s loop with the feet planted; the hips sink about 2% of the height and ease forward, the chest # sinks further (the lean deepens) and the head stays level; a slow rise, a short hold at the top, a # quicker sink and a longer settle; the weapon's head dips as the body sinks, a beat behind it. # GUARD_TOP and GUARD_LOW are the two ends; IDLE_SINK says how far sunk (0 top, 1 low) over the loop, # eased between its points; the loop is sampled every IDLE_STEP and each sample grips afresh. GUARD_TOP = dict(drop=0.050, turn=-14.0, lean=3.0, fwd=0.0, lead=0.0, fist=(0.04, -0.60, -0.26), shaft=(-0.32, 0.44, -0.84), reach=0.80) GUARD_LOW = dict(drop=0.092, turn=-16.0, lean=11.0, fwd=0.014, lead=0.0, fist=(0.04, -0.60, -0.26), shaft=(-0.32, 0.37, -0.87), reach=0.80) IDLE_LOOP, IDLE_STEP, SHAFT_LAG = 2.0, 0.1, 0.1 IDLE_SINK = [(0.0, 1.0), (0.15, 1.0), (0.85, 0.0), (1.15, 0.0), (1.55, 1.0), (2.0, 1.0)] def sink(t): """How far sunk the guard is at time t of the idle loop (0 top .. 1 low), eased between points.""" t = t % IDLE_LOOP for (t0, a), (t1, b) in zip(IDLE_SINK[:-1], IDLE_SINK[1:]): if t0 <= t <= t1: x = (t - t0) / max(t1 - t0, 1e-9) return a + (b - a) * x * x * (3 - 2 * x) return IDLE_SINK[-1][1] def guard_at(t): """The guard's parameters at time t of the idle loop.""" k, ks = sink(t), sink(t - SHAFT_LAG) out = {n: (GUARD_TOP[n] + (GUARD_LOW[n] - GUARD_TOP[n]) * k) if isinstance(GUARD_TOP[n], float) else GUARD_TOP[n] for n in GUARD_TOP} out["shaft"] = tuple(a + (b - a) * ks for a, b in zip(GUARD_TOP["shaft"], GUARD_LOW["shaft"])) return out def polearm(vrm, shape=None, keys=None): """A halberd in both hands (it is rigid on the right hand), after the study's soldiers: a wide, low guard, left foot forward, the shaft across the body with its head forward and up, the right fist by the hip and the left up the shaft at chest height, elbows bent and out of the body. The attack draws the shaft back and thrusts it forward on a lunge, both hands on it throughout. Each key grips with rig.grip so the left fist lands on the shaft where the right hand holds it.""" from checks import Body from duel import clear_grip rig = Rig(vrm, shape) body = Body(vrm, shape) f = fists(rig) ref = dict(ref_pose=P.BUST, fist_R=f["R"], fist_L=f["L"]) base = P.merge(P.BATTLE_IDLE, P.fist("L")) foot = {s: rig.pos(base, f"J_Bip_{s}_Foot") for s in "LR"} arm = {s: rig.pos(P.BUST, f"J_Bip_{s}_LowerArm") - rig.pos(P.BUST, f"J_Bip_{s}_UpperArm") for s in "LR"} span = {s: float(np.linalg.norm(arm[s]) + np.linalg.norm(f[s] - rig.pos(P.BUST, f"J_Bip_{s}_LowerArm"))) for s in "LR"} def guard(drop, turn, lean, fwd, lead, fist, shaft, reach): # the lean comes mostly from the hips: a bent spine pushed the breastplate's hem through the belt pose = P.merge(base, { "J_Bip_C_Hips": P.move(0, -drop, -fwd, P.rot((1, 0, 0), -lean * 0.65)), "J_Bip_C_Spine": P.rot((0, 1, 0), turn * 0.6) @ P.rot((1, 0, 0), -lean * 0.2), "J_Bip_C_Chest": P.rot((0, 1, 0), turn * 0.4) @ P.rot((1, 0, 0), -lean * 0.15), "J_Bip_C_Neck": P.rot((0, 1, 0), -turn * 0.5) @ P.rot((1, 0, 0), lean * 0.35), "J_Bip_C_Head": P.rot((0, 1, 0), -turn * 0.3) @ P.rot((1, 0, 0), lean * 0.35)}) # the gaze stays level pose = rig.leg_ik(pose, "L", foot["L"] + np.array([-0.07, 0, -0.14 - lead])) pose = rig.leg_ik(pose, "R", foot["R"] + np.array([0.06, 0, 0.12]), pole=(0, -0.2, -1)) D = np.asarray(shaft, float) / np.linalg.norm(shaft) fr = rig.pos(pose, "J_Bip_R_UpperArm") + span["R"] * np.asarray(fist, float) # the left fist: the point up the shaft at `reach` from the left shoulder q = fr - rig.pos(pose, "J_Bip_L_UpperArm") b, c = float(D @ q), float(q @ q) - (reach * span["L"]) ** 2 t = -b + np.sqrt(max(b * b - c, 0.0)) # (out of reach: the shaft's nearest point) t = float(np.clip(t, 0.22, 0.48)) pose = clear_grip(rig, body, pose, "R", ref, fr, D, (0.6, -0.4, 0.7)) return clear_grip(rig, body, pose, "L", ref, fr + D * t, D, (-0.8, -1.0, 0.1)) k = {n: guard(**v) for n, v in (keys or POLEARM).items()} n = int(round(IDLE_LOOP / IDLE_STEP)) idle = [(round(i * IDLE_STEP, 3), guard(**guard_at(i * IDLE_STEP))) for i in range(n)] idle.append((IDLE_LOOP, idle[0][1])) # the loop closes on its first pose rest = idle[0][1] return { "idle": idle, "attack": [(0.0, rest), (0.32, k["wind"]), (0.44, k["wind"]), (0.56, k["thrust"]), (0.68, k["follow"]), (1.05, k["follow"]), (1.5, rest)], }Bashmkdir -p ~/Projects/lowmarch-fable52/tools/whole && cd ~/Projects/lowmarch-fable52 && cat > tools/whole/build.py <<'E'
command
mkdir -p ~/Projects/lowmarch-fable52/tools/whole && cd ~/Projects/lowmarch-fable52 && cat > tools/whole/build.py <<'E' """One whole character on a current armory body: dressed by the old costume kit, rigged with the battle clips, built into a painted-renderer site of its own. python3 tools/whole/build.py -> review/out/whole/site/ (git-ignored) Reads the cached cage body; never rebuilds one. Nothing in cage's cache key is touched. """ import json import os import shutil import sys import time os.environ.setdefault("LOWMARCH_SITE", "whole") HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) sys.path.insert(0, os.path.join(ROOT, "review", "vroid-02")) import build # noqa: E402 (puts tools/ and art/cast on the path) import outfit # noqa: E402 import export_glb # noqa: E402 from cast import CAST # noqa: E402 NAME = "wren" BODY = sys.argv[1] if len(sys.argv) > 1 else "arm_f_slender" def dress(fit): """Elaine's knight dress, minus her kit hair: the body keeps the VRoid hair its head came with.""" out = [] for pc in outfit.knight_dress(fit): m = pc["material"] if pc.get("role") == "hair" or "bun" in m or "braid" in m or "ribbon" in m or "HAIR" in m.upper(): continue out.append(pc) return out outfit.COSTUMES["whole_knight"] = dress src, ela = CAST[BODY], CAST["elaine"] CAST[NAME] = dict(src, label="Wren", costume="whole_knight", stance="sword", shape=dict(src["shape"], rest={"Fcl_BRW_Angry": 0.3}), colors=dict(src["colors"], **{k: ela["colors"][k] for k in "KLMPQRST"}), paint=dict(ela["paint"], hair=src["paint"]["hair"])) build.LABELS = {NAME: "Wren"} if __name__ == "__main__": t0 = time.time() os.makedirs(build.OUT, exist_ok=True) r = build.character((NAME, None)) print(f"{NAME}.glb {r['size'] / 1e6:.1f} MB, {time.time() - t0:.0f}s") print(" " + r["checks"]["summary"]) if r["checks"]["layers"]: print(" " + r["checks"]["layers"]["summary"]) for item in r["checks"]["through"]: print(" ! " + item["text"]) build.scenery(NAME) cam = r["cams"]["battle"] out = dict(characters=[dict(name=NAME, label="Wren", info=r["info"], cams=r["cams"])], duel=dict(order={}, place={}, cam=dict(cam, pivot_px=[cam["w"] // 2, cam["pivot_px"][1]]), clip="clash"), lineup=dict(order=[], spacing=0.95), page=dict(title="Whole", eyebrow="Lowmarch · one whole character", notes="", duel=False, armory=False)) json.dump(out, open(f"{build.OUT}/camera.json", "w"), indent=1, default=build.as_list) json.dump({NAME: r["checks"]}, open(f"{build.OUT}/checks.json", "w"), indent=1) shutil.copy(os.path.join(ROOT, "review", "vroid-02", "index.html"), build.OUT) print(f"-> {build.OUT} {time.time() - t0:.0f}s") E time python3 tools/whole/build.py 2>&1 | tail -40result, 5 lines
wren: no cage body; run python3 -I tools/cage.py first real 0m0.800s user 0m0.888s sys 0m0.618s
Bashcd ~/Projects/lowmarch-fable52 && python3 - <<'E'
command
cd ~/Projects/lowmarch-fable52 && python3 - <<'E' import re p="tools/whole/build.py"; s=open(p).read() s=s.replace('build.LABELS = {NAME: "Wren"}\n','build.LABELS = {NAME: "Wren"}\n_model_path = build.model_path\nbuild.model_path = lambda name, c: _model_path(BODY if name == NAME else name, CAST[BODY] if name == NAME else c)\n') open(p,"w").write(s) E time python3 tools/whole/build.py 2>&1 | tail -40result, 10 lines
wren.glb 4.4 MB, 51s wren: 10 keyframes checked; 2 with an arm through the body, 7 with an arm resting on it wren: plate over garments: shows through in the reference pose, nothing new in 10 keyframes ! wren, attack at 0.68 s: right upper arm 2.7 cm inside the body ! wren, attack at 1.05 s: right upper arm 2.7 cm inside the body -> ~/Projects/lowmarch-fable52/review/out/whole/site 76s real 1m16.135s user 1m20.635s sys 5m38.814s
agent
+2:59The costume kit dressed the current slender body in 76 s on the first try. Now shooting it in the painted renderer to see how it looks.
Bashcd ~/Projects/lowmarch-fable52 && sed -n 1500,1600p review/vroid-02/index.html; sed -n 1700,1737p review/vroid-02/index.html
command
cd ~/Projects/lowmarch-fable52 && sed -n 1500,1600p review/vroid-02/index.html; sed -n 1700,1737p review/vroid-02/index.html
result, 139 lines
for (let s = 0; s < 150; s++) cs.forEach(c => c.cloths.forEach(cl => cl.step(1 / 120, s / 120))); cs.forEach(c => c.cloths.forEach(cl => cl.write())); } function frameAt(centre, h, tw, th, pitch) { const w = h * tw / th, a = THREE.MathUtils.degToRad(pitch); camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2; camera.zoom = 1; camera.updateProjectionMatrix(); camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(15)); camera.up.set(0, 1, 0); camera.lookAt(centre); ctl.target.copy(centre); } async function runSheet(kind) { document.body.classList.add("sheet"); const lineup = kind === "lineup", duel = kind === "duel" || lineup; if (!duel) state.who = kind; if (params.get("mode") === "3d") state.mode = "3d"; // ?mode=3d: the plain 3D renderer (tells a geometry fault from a shading one) await setView(lineup ? "lineup" : duel ? "duel" : "battle"); if ((!duel || lineup) && ground) { scene.remove(ground.root); } applyMaterials(); // ?rows=0,3 keeps some rows, ?scale=3 renders them larger (for side-by-sides against a reference) const keep = (params.get("rows") || "").split(",").filter(Boolean).map(Number); const scale = Math.max(1, Math.min(4, +(params.get("scale") || 1))); const rows = (lineup ? LINEUP_ROWS : duel ? DUEL_ROWS : PAGE && PAGE.armory ? ARMORY_ROWS : [...CHAR_ROWS]) .filter((r, i) => !keep.length || keep.includes(i)); if (!duel && !keep.length) { try { const chk = (await (await fetch("checks.json")).json())[kind]; const seen = new Set(), tiles = []; for (const it of chk.through) { const [limb] = it.hits[0], key = `${it.clip}@${it.t}`; if (seen.has(key) || tiles.length >= 6) continue; seen.add(key); for (const y of [60, 300]) tiles.push({ clip: it.clip, t: it.t, yaw: y, focus: `J_Bip_${limb.slice(0, 2)}LowerArm`, dy: 0, size: 0.75, label: `${it.clip} ${it.t} s, ${y}°` }); } // garments through plate: a close-up framed on the plate (two angles), reference pose first for (const it of (chk.layers ? chk.layers.items : [])) { const [, plate] = it.hits[0], key = `${it.clip}@${it.t}:${plate}`; if (seen.has(key) || tiles.length >= 10) continue; seen.add(key); const clip = it.clip === "reference pose" ? "ref" : it.clip; for (const y of [30, 330]) tiles.push({ clip, t: it.t, yaw: y, focusMesh: `OUTFIT_${plate}`, size: 0.5, label: `${plate}, ${it.clip === "reference pose" ? "as built" : it.clip + " " + it.t + " s"}, ${y}°` }); } if (tiles.length) rows.push({ label: "Flagged by the checks", tiles: tiles.slice(0, 6) }); if (tiles.length > 6) rows.push({ label: "Flagged by the checks (more)", tiles: tiles.slice(6, 12) }); } catch (e) { /* no checks: no row */ } } // the lineup's tiles shrink to stay under WebGL's largest drawing size (8192 here): past it they came out black const lw0 = Math.round(FIGURE.lineup.w / 2.5 * 480), lk = Math.min(1, 8000 / (lw0 * scale)), lw = Math.round(lw0 * lk); const tw = (lineup ? lw : duel ? 520 : 300) * scale, th = (duel ? 420 : lineup ? Math.round(520 * lk) : 520) * scale, lab = 22, rowHead = 30, gap = 6; const rw = r => (r.tw || tw / scale) * scale, rh = r => (r.th || th / scale) * scale; const cv = document.createElement("canvas"); cv.width = Math.max(...rows.map(r => r.tiles.length * (rw(r) + gap))) + gap; cv.height = rows.reduce((a, r) => a + rowHead + rh(r) + lab + gap, 0) + gap; const ctx = cv.getContext("2d"); ctx.fillStyle = "#100e18"; ctx.fillRect(0, 0, cv.width, cv.height); R.setPixelRatio(1); let y0 = gap; for (const row of rows) { const tw_ = rw(row), th_ = rh(row); R.setSize(tw_, th_, false); ctx.fillStyle = "#e9e6f2"; ctx.font = "bold 18px sans-serif"; ctx.fillText(`${lineup ? "Enemies" : duel ? "Duel" : charDef(kind).label} · ${row.label}`, gap + 2, y0 + 21); y0 += rowHead; row.tiles.forEach((tile, k) => { setYaw(tile.yaw); state.hidden = new Set(tile.hide || []); applyMaterials(); holdPose(tile.clip, tile.t); settleCloth(); let centre, h = tile.size || (lineup ? 2.5 : duel ? 2.3 : 2.05), pitch = tile.pitch ?? 8; if (tile.focusBind) { const hs = active().map(c => c.root.getObjectByName("J_Bip_R_Hand").getWorldPosition(new THREE.Vector3())); centre = hs[0].clone().add(hs[1]).multiplyScalar(0.5).add(new THREE.Vector3(0, 0.12, 0)); pitch = 4; } else if (tile.focusChar != null) { // one unit's head in the lineup centre = active()[tile.focusChar].root.getObjectByName("J_Bip_C_Head").getWorldPosition(new THREE.Vector3()); centre.y += 0.05; pitch = tile.pitch ?? 0; } else if (tile.focusMesh) { const m = active()[0].meshes.find(o => o.userData.material === tile.focusMesh); centre = m ? new THREE.Box3().setFromObject(m, true).getCenter(new THREE.Vector3()) : new THREE.Vector3(0, 1, 0); pitch = 4; } else if (tile.focus) { centre = active()[0].root.getObjectByName(tile.focus).getWorldPosition(new THREE.Vector3()); centre.y += tile.dy; pitch = tile.pitch ?? 4; } else { // follow the hips across the ground (a lunge steps out of a fixed frame) const p = duel ? new THREE.Vector3(0, 0, 0) : active()[0].root.getObjectByName("J_Bip_C_Hips").getWorldPosition(new THREE.Vector3()); centre = new THREE.Vector3(p.x, h / 2 - 0.06, p.z); } frameAt(centre, h, tw_, th_, pitch); render(); const x = gap + k * (tw_ + gap); ctx.drawImage(R.domElement, x, y0, tw_, th_); ctx.fillStyle = "#9c98b5"; ctx.font = "14px sans-serif"; ctx.fillText(tile.label, x + 4, y0 + th_ + 16); }); y0 += th_ + lab + gap; } $("sheetOut").textContent = cv.toDataURL("image/png"); document.title = "sheet ready"; } // ---- panel: checks and sheets ------------------------------------------------------------------------------------------ async function loadChecks() { if (state.playing) setYaw(state.yaw + dt * (reduceMotion ? 20 : 70)); animate(dt); scene.updateMatrixWorld(true); if (state.physics && !SHEET) { // spring bones at a fixed 120 Hz, as the cloth const steps = Math.max(1, Math.round(dt / (1 / 120))); for (const c of cs) if (c.springs && c.springs.length) for (let s = 0; s < steps; s++) stepSprings(c, dt / steps); } const cloths = cs.flatMap(c => c.cloths); if (state.cloth && cloths.length) { const steps = Math.max(1, Math.round(dt / (1 / 120))); for (let s = 0; s < steps; s++) { simT += dt / steps; cloths.forEach(c => c.step(dt / steps, simT)); } cloths.forEach(c => c.write()); } render(); placeTags(); } requestAnimationFrame(frame); } if (!LINEUP.order.length) $("lineupBtn").hidden = true; // a check for scripts (?springprobe): after a few seconds of the motion, each body's widest spring-bone swing (degrees) if (params.has("springprobe")) setTimeout(() => { document.title = "springs " + JSON.stringify(Object.fromEntries(active().map(c => [c.name, +(c.springMax || 0).toFixed(1)]))); }, 4000); if (SHEET) { runSheet(SHEET).catch(e => { console.error(e); $("sheetOut").textContent = "error: " + e; document.title = "sheet failed"; }); } else { if (window.innerWidth > 1100) setPanel(true); loadChecks(); const v0 = params.get("view"), w0 = params.get("who"), m0 = params.get("mode"); if (w0 && charDef(w0)) state.who = w0; if (m0 === "3d") document.querySelector('[data-mode="3d"]').click(); const views = ARMORY_PAGE ? ["battle", "bust", "compare"] : NO_DUEL ? ["battle", "bust", "lineup"] : ["duel", "battle", "bust", "lineup"]; await setView(views.includes(v0) ? v0 : ARMORY_PAGE ? "compare" : NO_DUEL ? "lineup" : "duel", params.get("clip") || undefined); if (params.has("yaw")) setYaw(+params.get("yaw") || 0); // ?yaw=180: open turned (the backs) requestAnimationFrame(frame); } </script>Bashcd ~/Projects/lowmarch-fable52 && grep -n "CHAR_ROWS\s*=\|DUEL_ROWS\s*=\|ARMORY_ROWS\s*=" -A 14 review/vroid-02/index.html | head -60; S=[redacted: private path]/scratchpad; mkdir -p $S/shots; time python3 tools/shots/arm_shoot.py review/out/whole/site $S/shots wren
command
cd ~/Projects/lowmarch-fable52 && grep -n "CHAR_ROWS\s*=\|DUEL_ROWS\s*=\|ARMORY_ROWS\s*=" -A 14 review/vroid-02/index.html | head -60; S=[redacted: private path]/scratchpad; mkdir -p $S/shots; time python3 tools/shots/arm_shoot.py review/out/whole/site $S/shots wrenresult, 52 lines
1433:const CHAR_ROWS = [ 1434- // arms down, as character design sheets are drawn: the row to compare against references 1435- { label: "Reference pose", tiles: [0, 30, 90, 180, 270, 330].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, hide: ["sword", "weapon"], label: `${y}°` })) }, 1436- { label: "Head", tiles: [0, 30, 90, 150, 180, 270].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.03, 1437- size: 0.42, hide: ["sword", "weapon"], label: `${y}°` })) }, 1438- { label: "Arms out", tiles: ARMS_YAWS.map(y => ({ clip: "apose", t: 0, yaw: y, label: `${y}°` })) }, 1439- { label: "Idle", tiles: ARMS_YAWS.map(y => ({ clip: "idle", t: 0, yaw: y, label: `${y}°` })) }, 1440- // the idle loop through time from one side (the camera holds still: the body's rise and sink shows) 1441- { label: "Idle loop", tiles: [0, 0.4, 0.8, 1.0, 1.3, 1.6].map(t => ({ clip: "idle", t, yaw: 300, label: `${t.toFixed(1)} s` })) }, 1442- { label: "Attack", tiles: [[0.32, "wind-up"], [0.56, "slash"], [0.68, "follow-through"]].flatMap(([t, n]) => 1443- [60, 300].map(y => ({ clip: "attack", t, yaw: y, label: `${n}, ${y}°` }))) }, 1444- { label: "Close-ups", tiles: [ 1445- { clip: "apose", t: 0, yaw: 0, focus: "J_Bip_C_Hips", dy: 0.10, size: 0.62, label: "waist, front" }, 1446- { clip: "apose", t: 0, yaw: 90, focus: "J_Bip_C_Hips", dy: 0.10, size: 0.62, label: "waist, side" }, 1447- { clip: "apose", t: 0, yaw: 180, focus: "J_Bip_C_Hips", dy: 0.10, size: 0.62, label: "waist, back" }, -- 1460:const ARMORY_ROWS = [ 1461- { label: "T-pose", tiles: [0, 45, 90, 135, 180, 270].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, label: `${y}°` })) }, 1462- { label: "Head", tiles: [0, 30, 90, 150, 180, 270].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.03, 1463- size: 0.42, label: `${y}°` })) }, 1464- { label: "Joins", tiles: [ 1465- ...[[0, -10, "neck, front"], [120, -4, "neck, behind the ear"]].map(([y, p, n]) => 1466- ({ clip: "ref", t: 0, yaw: y, pitch: p, focus: "J_Bip_C_Neck", dy: 0.03, size: 0.30, label: n })), 1467- { clip: "ref", t: 0, yaw: 0, focus: "J_Bip_L_UpperArm", dy: 0, size: 0.40, label: "shoulder, front" }, 1468- { clip: "ref", t: 0, yaw: 180, focus: "J_Bip_C_Hips", dy: -0.12, size: 0.55, label: "hips and thighs, back" }, 1469- { clip: "ref", t: 0, yaw: 0, focus: "J_Bip_C_Hips", dy: -0.12, size: 0.55, label: "hips and thighs, front" }, 1470- { clip: "ref", t: 0, yaw: 30, focus: "J_Bip_L_Foot", dy: 0.02, size: 0.5, label: "feet" }] }, 1471-]; 1472-const DUEL_YAWS = [0, 40, 90, 320]; 1473-const LINEUP_ROWS = [ 1474- { label: "Lineup", tiles: [0, 30].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, hide: ["sword", "weapon"], label: `${y}°, reference pose` })) }, -- 1484:const DUEL_ROWS = [0, 0.8, 1.6].map(t => ({ label: `Clash ${t.toFixed(1)} s`, tiles: DUEL_YAWS.map(y => ({ clip: "clash", t, yaw: y, label: `${y}°` })) })) 1485- .concat([{ label: "The bind, close", tiles: [0, 90, 180, 300].map(y => ({ clip: "clash", t: 0, yaw: y, focusBind: true, size: 0.95, label: `${y}°` })) }]); 1486- 1487-function holdPose(clip, t) { 1488- for (const c of active()) { 1489- if (c.skeleton) c.skeleton.pose(); 1490- c.mixer.stopAllAction(); c.blend = null; c.clip = clip; 1491- if (clip === "ref") continue; // the reference (bind) pose itself 1492- const a = c.actions[clip] || c.actions.idle; 1493- a.reset(); a.setEffectiveWeight(1); a.play(); a.time = t; c.mixer.update(0); 1494- } 1495- scene.updateMatrixWorld(true); 1496-} 1497-function settleCloth() { 1498- const cs = active(); wren [redacted: private path]/scratchpad/shots/painted_wren.png 23s real 0m23.669s user 0m1.914s sys 0m1.359sRead[redacted: private path]/scratchpad/shots/painted_wren.pngno result
input
{ "file_path": "[redacted: private path]/scratchpad/shots/painted_wren.png" }
agent
+3:32[redacted: image of a costume drawn after another studio character]
Bashcd ~/Projects/lowmarch-fable52 && S=[redacted: private path]/scratchpad; mkdir -p $S/shots2 && ROWS=3,5 python3 tools/shots/arm_shoot.py review/out/whole/site $S/shots2 wren
command
cd ~/Projects/lowmarch-fable52 && S=[redacted: private path]/scratchpad; mkdir -p $S/shots2 && ROWS=3,5 python3 tools/shots/arm_shoot.py review/out/whole/site $S/shots2 wrenresult, 1 line
wren [redacted: private path]/scratchpad/shots2/painted_wren.png 13s
agent
+4:02The dressed body renders. Checking her idle and attack poses next, then composing the frame.
Read[redacted: private path]/scratchpad/shots2/painted_wren.pngno result
input
{ "file_path": "[redacted: private path]/scratchpad/shots2/painted_wren.png" }
agent
+4:03[redacted: image of a costume drawn after another studio character]
Bashcd ~/Projects/lowmarch-fable52 && grep -n "DUEL\b\|DUEL\.\|place\[\|\.place\|ground\b.*=\|async function setView\|function setYaw\|function active\|stage\.\|KEY_DIR\|keyDir\|uKey\|background\|setClearColor" review/vroid-02/index.html | head -90
command
cd ~/Projects/lowmarch-fable52 && grep -n "DUEL\b\|DUEL\.\|place\[\|\.place\|ground\b.*=\|async function setView\|function setYaw\|function active\|stage\.\|KEY_DIR\|keyDir\|uKey\|background\|setClearColor" review/vroid-02/index.html | head -90
result, 41 lines
34:body { background: var(--screen); color: var(--fg); font: 16px/1.5 var(--f-body); overflow: hidden; } 39:.view { position: relative; min-width: 0; overflow: hidden; background: var(--screen-2); } 49:.hud.top { top: 0; background: linear-gradient(var(--hud), rgba(16, 14, 24, 0.55) 70%, transparent); padding-bottom: 18px; } 50:.hud.bottom { bottom: 0; background: linear-gradient(transparent, rgba(16, 14, 24, 0.55) 30%, var(--hud)); padding-top: 18px; } 56: background: rgba(16, 14, 24, 0.6); color: var(--screen-fg); border: 1px solid var(--screen-line); 60:.btn[aria-pressed="true"] { background: var(--screen-on); border-color: var(--screen-on-line); } 65:select.btn option, select.btn optgroup { background: var(--screen); color: var(--screen-fg); } 75:.panel { width: var(--panel-w); background: var(--panel); color: var(--fg); border-left: 1px solid var(--line); 83:.panel .close { font: 11px/1 var(--f-label); text-transform: uppercase; letter-spacing: 0.06em; background: none; color: var(--muted); 97:.sheets img { width: 100%; height: 120px; object-fit: cover; object-position: top; border: 1px solid var(--line); border-radius: 3px; background: var(--screen); } 112: text-transform: uppercase; text-align: center; color: var(--screen-fg); background: rgba(16, 14, 24, 0.72); 253:const NO_DUEL = PAGE?.duel === false; 284:if (NO_DUEL) { 343: uniform int uKind; uniform vec3 uBase; uniform vec3 uKey; uniform sampler2D uMap; uniform int uAlpha; 345: uniform vec3 uGold; uniform vec3 uAmbient; uniform vec3 uKeyCol; uniform vec3 uRimCol; uniform float uGrain; 356: float sxy = length(uKey.xy); 358: vec2 dir = uKey.xy / sxy; 359: float lz = uKey.z / sxy; // the ray's rise toward the camera per metre across 413: float hl = dot(n, normalize(uKey + v)); // the key's highlight, a hard-edged shape 425: float lit = dot(n, uKey) * 0.5 + 0.5; 464: float sp = dot(n, normalize(uKey + v)) + (strand - 0.6) * 0.18; 508: vec3 grade = mix(uAmbient, uKeyCol, st(lit, 0.55)); 619:R.setClearColor(0x000000, 0); 861: const u = { uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() }, 866: uAmbient: { value: new THREE.Vector3(1, 1, 1) }, uKeyCol: { value: new THREE.Vector3(1, 1, 1) }, uRimCol: { value: new THREE.Vector3() }, 875: if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; } 901:let ground = null; 987: ground = { root: gltf.scene, meshes }; 992: ...(ground && ground.root.parent && state.view !== "bust" ? ground.meshes : [])]; 1255:function setYaw(y) { 1259: if (state.view === "duel") stage.rotation.y = r; 1331:async function setView(view, clip) { 1345: stage.rotation.y = 0; 1351: stage.add(c.turn); 1354: stage.add(c.turn); c.holder.position.set(0, 0, 0); 1356: const pl = CAM.duel.place[c.name]; 1357: stage.add(c.turn); 1396: R.setRenderTarget(null); R.setClearColor(0x191626, 1); R.clear(); R.render(scene, camera); R.setClearColor(0x000000, 0); 1404: for (const o of meshes) { const mu = o.material.uniforms; mu.uAmbient.value.set(...G.ambient); mu.uKeyCol.value.set(...G.key); mu.uRimCol.value.set(...G.rim); } 1732: const views = ARMORY_PAGE ? ["battle", "bust", "compare"] : NO_DUEL ? ["battle", "bust", "lineup"] : ["duel", "battle", "bust", "lineup"]; 1733: await setView(views.includes(v0) ? v0 : ARMORY_PAGE ? "compare" : NO_DUEL ? "lineup" : "duel", params.get("clip") || undefined);Bashcd ~/Projects/lowmarch-fable52 && sed -n 1255,1262p review/vroid-02/index.html; sed -n 1325,1432p review/vroid-02/index.html; sed -n 596,625p review/vroid-02/index.html
command
cd ~/Projects/lowmarch-fable52 && sed -n 1255,1262p review/vroid-02/index.html; sed -n 1325,1432p review/vroid-02/index.html; sed -n 596,625p review/vroid-02/index.html
result, 146 lines
function setYaw(y) { state.yaw = ((y % 360) + 360) % 360; $("yaw").value = Math.round(state.yaw); $("yawOut").textContent = `${Math.round(state.yaw)}°`; const r = -THREE.MathUtils.degToRad(state.yaw); if (state.view === "duel") stage.rotation.y = r; else if (ROW_VIEW()) active().forEach(c => c.turn.rotation.y = r); else { const c = chars.get(state.who); if (c) c.turn.rotation.y = r; } } b.setAttribute("aria-pressed", String((state.view === "battle" || state.view === "bust") && state.who === c.name)); b.addEventListener("click", () => { state.who = c.name; setView(state.view === "duel" ? "battle" : state.view); }); box.appendChild(b); }); } async function setView(view, clip) { const changed = view !== state.view; state.view = view; document.querySelectorAll("[data-view]").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.view === view))); buildWho(); statusEl.hidden = false; statusEl.textContent = view === "duel" ? "Loading both fighters…" : "Loading the model…"; try { const cs = await Promise.all(activeNames().map(loadCharacter)); const g = view !== "bust" && !ROW_VIEW() ? await loadGround() : null; // a row of models stands on nothing for (const c of chars.values()) { c.turn.removeFromParent(); scene.remove(c.world); } if (ground) scene.remove(ground.root); if (g) scene.add(g.root); const v = CAM_VIEW(), lead = cs[0].info; paint.mat.uniforms.uGap.value = lead.depth_gap; stage.rotation.y = 0; for (const c of cs) { scene.add(c.world); c.turn.rotation.set(0, 0, 0); if (view === "lineup") { const i = LINEUP.order.indexOf(c.name); stage.add(c.turn); c.turn.position.set(lineupX(i), 0, 0); c.holder.position.set(0, 0, 0); } else if (view === "compare") { // placed by layoutCompare, once all are in stage.add(c.turn); c.holder.position.set(0, 0, 0); } else if (view === "duel") { const pl = CAM.duel.place[c.name]; stage.add(c.turn); c.turn.position.set(...pl.pos); c.turn.rotation.y = THREE.MathUtils.degToRad(pl.yaw); c.holder.position.set(0, 0, 0); } else { scene.add(c.turn); c.turn.position.set(v.pivot[0], 0, v.pivot[2]); c.holder.position.set(-v.pivot[0], 0, -v.pivot[2]); } } statusEl.hidden = true; if (view === "compare") layoutCompare(); buildParts(); applyMaterials(); size(); matchCamera(); setYaw(changed || view === "duel" ? VIEW_YAW[view] : state.yaw); const want = clip || (view === "duel" ? "clash" : (CLIP_VIEW[state.clip] === "battle" ? state.clip : "idle")); if (view === "duel") setClip("clash", SHEET ? null : "idle"); else if (view === "battle") setClip(want); else if (view === "lineup") setClip(clip && CLIP_VIEW[clip] === "battle" ? clip : "idle"); else setClip("idle"); animate(0); scene.updateMatrixWorld(true); cs.forEach(c => c.cloths.forEach(cl => { cl.reset(false); cl.write(); })); } catch (e) { console.error(e); statusEl.textContent = "The model didn't load."; } } // ---- rendering ------------------------------------------------------------------------------------------------------- function applySkin(meshes) { // the picked tone on every skin material (face, body, shadow cards); the built tone is kept to go back to const tone = state.skin && PAGE && PAGE.skins ? PAGE.skins.find(s => s.name === state.skin) : null; for (const o of meshes) { const m = o.userData.mats && o.userData.mats.painted, u = m && m.uniforms; if (!u || !u.uSkinRamp || u.uKind.value !== 1) continue; if (!o.userData.builtSkin) o.userData.builtSkin = [u.uSkinRamp.value, u.uSkinL.value.clone(), u.uSkinS.value.clone(), u.uSkinC.value.clone()]; if (tone) { u.uSkinRamp.value = 1; u.uSkinL.value.copy(hex(tone.ramp[0])); u.uSkinS.value.copy(hex(tone.ramp[1])); u.uSkinC.value.copy(hex(tone.ramp[2])); } else { const b = o.userData.builtSkin; u.uSkinRamp.value = b[0]; u.uSkinL.value.copy(b[1]); u.uSkinS.value.copy(b[2]); u.uSkinC.value.copy(b[3]); } } } function render() { const meshes = allMeshes(), cs = active(); applySkin(meshes); const cloths = cs.flatMap(c => c.cloths); if (state.mode === "3d") { meshes.forEach(o => o.material = o.userData.mat3d); cloths.forEach(c => c.lines3d.visible = trimsShown(c)); sun.position.copy(camera.position).add(new THREE.Vector3(-3, 4, 0)); sun.target.position.copy(ctl.target); sun.target.updateMatrixWorld(); R.setRenderTarget(null); R.setClearColor(0x191626, 1); R.clear(); R.render(scene, camera); R.setClearColor(0x000000, 0); return; } const buf = R.getDrawingBufferSize(new THREE.Vector2()); targetsFor(buf.x, buf.y); cloths.forEach(c => c.lines3d.visible = false); meshes.forEach(o => { o.material = o.userData.mats.painted; o.material.uniforms.uPass.value = 0; }); const G = GRADE[state.view === "bust" ? "bust" : "battle"]; // stage grade, shared by the characters and the stage for (const o of meshes) { const mu = o.material.uniforms; mu.uAmbient.value.set(...G.ambient); mu.uKeyCol.value.set(...G.key); mu.uRimCol.value.set(...G.rim); } // the info pass (roles, ids, depth) first: the colour pass reads it for cast shadows meshes.forEach(o => { // unbound while it is drawn: reading it now would be a feedback loop const mu = o.material.uniforms; mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null; }); R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera); const ppmBuf = buf.y / (camera.top - camera.bottom) * camera.zoom; for (const o of meshes) { const mu = o.material.uniforms; mu.uPass.value = 0; mu.uCastOn.value = 1; mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture; mu.uCastRes.value.set(buf.x, buf.y); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf; } R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera); const u = paint.mat.uniforms; u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture; u.uRes.value.set(buf.x, buf.y); u.uNear.value = camera.near; u.uFar.value = camera.far; // line weight follows the figure's size on screen (study: ~0.4% of its height) const ppm = buf.y / (camera.top - camera.bottom) * camera.zoom, dpr = R.getPixelRatio(); u.uSil.value = THREE.MathUtils.clamp(1.75 * ppm * 0.0042, dpr, 2.6 * dpr); u.uInner.value = Math.max(dpr * 0.75, u.uSil.value * 0.55); u.uPpm.value = ppm; R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam); } // ---- check sheets ---------------------------------------------------------------------------------------------------- // ?sheet=<name> poses one character through every check view; ?sheet=duel shows the bind. Each tile // is posed, its cloth settled at that angle, rendered by the same painted renderer as the page, and // drawn into one image, which lands in #sheetOut as a PNG data URL (a headless browser reads it). const ARMS_YAWS = [0, 45, 90, 135, 180, 270]; if (ni.a > 0.5) acc += clamp((z0 - z(q)) / 0.05, 0.0, 1.0); } col *= 1.0 - 0.22 * acc / 8.0; if (r0 == 1) { // the bangs shade the forehead float hair = 0.0; for (int s = 1; s <= 4; s++) { vec4 a = texture2D(tInfo, uv + vec2(0.0, float(s)) * uSil * px); int ra = rid(a); if (a.a > 0.5 && (ra == 3 || ra == 11)) hair = 1.0; } col = mix(col, col * vec3(0.84, 0.74, 0.76), 0.75 * hair); } } gl_FragColor = vec4(col, 1.0); }`; const compCam = new THREE.Camera(); function compPass(fs, uniforms) { const mat = new THREE.ShaderMaterial({ uniforms, vertexShader: `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`, fragmentShader: fs, transparent: true }); const s = new THREE.Scene(); s.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat)); return { mat, scene: s }; } // ---- the renderer --------------------------------------------------------------------------------------------------- const stageEl = $("stage"); const R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: !!SHEET }); R.setClearColor(0x000000, 0); R.outputColorSpace = THREE.LinearSRGBColorSpace; stageEl.appendChild(R.domElement); const paint = compPass(PAINT_COMP, { tColor: { value: null }, tInfo: { value: null }, tDepth: { value: null }, uRes: { value: new THREE.Vector2() }, uNear: { value: 0.1 }, uFar: { value: 40 }, uGap: { value: 0.012 }, uSil: { value: 2 }, uInner: { value: 1 }, uPpm: { value: 1000 } }); const ctl = new OrbitControls(camera, R.domElement); ctl.enableDamping = true; ctl.zoomToCursor = true; ctl.screenSpacePanning = true;Bashcd ~/Projects/lowmarch-fable52 && sed -n 251,303p tools/outfit.py; cat tools/terrain.py | sed -n 1,77p; grep -n "VIEW_YAW\|GRADE\s*=\|const KEY\b\|V.sun\|sun:" review/vroid-02/index.html | head; grep -n "sun\|def frame" -A3 tools/vroid_portrait.py | grep -n "sun\|def frame" | head
command
cd ~/Projects/lowmarch-fable52 && sed -n 251,303p tools/outfit.py; cat tools/terrain.py | sed -n 1,77p; grep -n "VIEW_YAW\|GRADE\s*=\|const KEY\b\|V.sun\|sun:" review/vroid-02/index.html | head; grep -n "sun\|def frame" -A3 tools/vroid_portrait.py | grep -n "sun\|def frame" | head
result, 136 lines
def wrap(fit, name, role, bones, offset, min_w=0.5, exclude=(), y_min=None, y_max=None, subdiv=0, base=None, hems=(), smooth=15, cut=None, refloor=False, clamp=False): """A garment shrink-wrapped onto the body region that follows `bones`. cut: (normal, d), keep only the skin below that plane (n.p < d, give or take a centimetre; pair it with a hem on the same plane). refloor: after the hems, push out whatever a hem pulled into the skin (a hem moves its edge straight along the plane's normal, which sinks it into a sloping hip; off by default so finished costumes don't drift). clamp: every vertex past a hem's plane goes onto it, not just the edge's (pass y_min and y_max a few centimetres past the hems: large skin triangles crossing a hem line otherwise leave notches as deep as a triangle).""" T = fit.tris_for(bones, min_w, exclude, y_min, y_max) if cut is not None: n_ = np.asarray(cut[0], float) / np.linalg.norm(cut[0]) T = T[(fit.pos[T] @ n_).max(1) < cut[1] + 0.01] if not len(T): return None pos, tri, used = compact(fit.pos, T) levels = [] for _ in range(subdiv): pos, tri, par = subdivide(pos, tri, with_parents=True) levels.append(par) out = shrink_wrap(pos, tri, base or fit.surf, offset, smooth=smooth) for n, d in hems: out = flatten_hem(out, tri, n, d) if clamp: n_ = np.asarray(n, float) / np.linalg.norm(n) over = out @ n_ - d out = out - np.outer(np.maximum(over, 0.0), n_) if refloor and hems: surf = base or fit.surf d2, cp2, ti2 = surf.query(out) low = d2 < offset * 0.75 out[low] = cp2[low] + surf.fn[ti2[low]] * offset * 0.75 pc = piece(name, role, out, tri) # weights come from the exact skin each vertex grew from: copying from the nearest skin instead # let the inside of one boot pick up the other leg's bones pc["J"], pc["W"] = blend_weights(fit.J[used], fit.W[used], int(fit.J.max()) + 1, levels) pc["jnames"] = fit.jnames if getattr(fit, "cloth_hull", False): # a body with muscle relief: sleeves span the hollows hw = lambda b: (np.array([b == n for n in fit.jnames])[pc["J"]] * pc["W"]).sum(1) axes = [] for sd in ("L", "R"): for b0, b1 in (("UpperArm", "LowerArm"), ("LowerArm", "Hand"), ("UpperLeg", "LowerLeg"), ("LowerLeg", "Foot"), ("Foot", "ToeBase")): # (boots over the foot: no toes showing) n0, n1 = f"J_Bip_{sd}_{b0}", f"J_Bip_{sd}_{b1}" if n0 in fit.bone and n1 in fit.bone: m = hw(n0) + (hw(n1) if b0 == "Foot" else 0.0) # the foot's segment takes the toes too axes.append((m >= 0.6, fit.bone[n0], fit.bone[n1], b0 == "Foot")) pc["pos"] = limb_hull(pc["pos"], tri, axes) pc["nrm"] = vertex_normals(pc["pos"], tri) pc["loops"] = boundary_loops(tri) return pc """Battle-scene terrain built in code: the ground a unit stands on in the side-view battle. Pieces use the same primitive dicts as outfit.py, with `world=True` so the renderer keeps them fixed while the character turns. Model coordinates: metres, y up, ground at y = 0. """ import math import numpy as np from outfit import grid_mesh, piece, ball def _noise(x, z, seed): rng = np.random.default_rng(seed) out = np.zeros_like(x) for k in range(5): fx, fz, ph = rng.uniform(1.5, 6.0), rng.uniform(1.5, 6.0), rng.uniform(0, 2 * math.pi, 2) out += np.sin(x * fx + ph[0]) * np.cos(z * fz + ph[1]) / (k + 1) return out def plains(width=4.2, depth=1.8, thick=0.25, seed=3, tufts=26, stones=5): """A raised plains platform: grassy top with gentle bumps, an earth bank on the sides, grass tufts and a few stones.""" out = [] nx, nz = 60, 26 xs = np.linspace(-width / 2, width / 2, nx) zs = np.linspace(-depth / 2, depth / 2, nz) X, Z = np.meshgrid(xs, zs, indexing="ij") Y = 0.012 * _noise(X, Z, seed) - 0.004 # keep it flat where the unit stands Y *= np.clip(np.hypot(X / 0.5, Z / 0.4) - 0.6, 0, 1) top = np.stack([X, Y, Z], -1) pos, tri = grid_mesh(top) out.append(piece("ground", "grass", pos, tri, outward_from=[0, -5, 0])) # earth bank on the four sides def bank(edge, name): lo = edge.copy() lo[:, 1] = -thick lo[:, 0] *= 1.02 lo[:, 2] *= 1.02 P = np.stack([edge, lo], 1) p_, t_ = grid_mesh(P) return piece(name, "dirt", p_, t_, outward_from=[0, -thick / 2, 0]) out.append(bank(top[:, 0], "bank_back")) out.append(bank(top[:, -1], "bank_front")) out.append(bank(top[0, :], "bank_left")) out.append(bank(top[-1, :], "bank_right")) rng = np.random.default_rng(seed + 1) for i in range(tufts): x, z = rng.uniform(-width / 2 * 0.95, width / 2 * 0.95), rng.uniform(-depth / 2 * 0.9, depth / 2 * 0.9) if abs(x) < 0.45 and abs(z) < 0.35: continue h = rng.uniform(0.04, 0.09) blades = [] for b in range(5): a = rng.uniform(0, 2 * math.pi) lean = np.array([math.cos(a), 0, math.sin(a)]) * rng.uniform(0.01, 0.03) base = np.array([x, 0.0, z]) + lean * 0.4 tip = base + np.array([0, h, 0]) + lean w = np.array([-math.sin(a), 0, math.cos(a)]) * 0.007 blades.append(np.array([base - w, base + w, tip])) pos = np.concatenate(blades) tri = np.arange(len(pos)).reshape(-1, 3) out.append(piece(f"tuft{i}", "grass", pos, tri, outward_from=[x, -1, z])) for i in range(stones): x, z = rng.uniform(-width / 2 * 0.9, width / 2 * 0.9), rng.uniform(-depth / 2 * 0.8, depth / 2 * 0.8) if abs(x) < 0.5 and abs(z) < 0.4: continue r = rng.uniform(0.04, 0.09) out.append(ball(f"stone{i}", "stone", [x, r * 0.35, z], r, squash=(1.0, 0.55, 0.8))) for p in out: p["world"] = True return out TERRAIN = {"plains": plains} 246:const VIEW_YAW = { duel: 0, battle: 60, bust: 30, lineup: 20, compare: 0 }; 851:const KEY = new THREE.Vector3(-0.45, 0.55, 0.70).normalize(); 853:const GRADE = { battle: { ambient: [0.84, 0.87, 0.98], key: [1.05, 1.0, 0.92], rim: [0.38, 0.34, 0.26] }, 875: if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; } 1367: setYaw(changed || view === "duel" ? VIEW_YAW[view] : state.yaw); 1:1094: def frame(self, view="bust", pitch=None, w=None, h=None):Bashcd ~/Projects/lowmarch-fable52 && grep -n "function activeNames" -A8 review/vroid-02/index.html; grep -n "function active()" -A3 review/vroid-02/index.html; grep -n "ORDER\b" review/vroid-02/index.html | head; grep -n "sun" tools/export_glb.py | head -5; sed -n 851,856p review/vroid-02/index.html; grep -n "mob_soldier\b\|def soldier" tools/mobs.py | head
command
cd ~/Projects/lowmarch-fable52 && grep -n "function activeNames" -A8 review/vroid-02/index.html; grep -n "function active()" -A3 review/vroid-02/index.html; grep -n "ORDER\b" review/vroid-02/index.html | head; grep -n "sun" tools/export_glb.py | head -5; sed -n 851,856p review/vroid-02/index.html; grep -n "mob_soldier\b\|def soldier" tools/mobs.py | head
result, 9 lines
267: return dict(roles=roles, light=vp.LIGHT.tolist(), sun=vp.SUN.tolist(), capsules=caps, cloth=cloth, face_marks=marks, const KEY = new THREE.Vector3(-0.45, 0.55, 0.70).normalize(); // stage grades: ambient multiply, key colour, back rim (characters and stage share them) const GRADE = { battle: { ambient: [0.84, 0.87, 0.98], key: [1.05, 1.0, 0.92], rim: [0.38, 0.34, 0.26] }, bust: { ambient: [0.90, 0.90, 0.98], key: [1.03, 1.0, 0.96], rim: [0.24, 0.24, 0.34] } }; // Brows draw over the bangs: they are lifted this far (m) toward the camera, more than the bangs stand off the // forehead and much less than the head is deep, so a brow still hides behind the skull when the head turns away. 88:def soldier(fit, legs="breeches"): 127:def soldier_f(fit):Bashcd ~/Projects/lowmarch-fable52 && grep -n "activeNames\|const active\b\|active = \|ROW_VIEW\s*=\|CAM_VIEW\s*=" review/vroid-02/index.html | head -12; grep -n "CAM.duel\|LINEUP\b" review/vroid-02/index.html | head -20
command
cd ~/Projects/lowmarch-fable52 && grep -n "activeNames\|const active\b\|active = \|ROW_VIEW\s*=\|CAM_VIEW\s*=" review/vroid-02/index.html | head -12; grep -n "CAM.duel\|LINEUP\b" review/vroid-02/index.html | head -20
result, 16 lines
906:const ROW_VIEW = () => state.view === "lineup" || state.view === "compare"; // several models in a row, each turning in place 907:const CAM_VIEW = () => state.view === "duel" || ROW_VIEW() ? CAM.duel.cam : charDef(state.who).cams[state.view]; 908:const activeNames = () => state.view === "duel" ? [CAM.duel.order.player, CAM.duel.order.opponent] 910:const active = () => activeNames().map(n => chars.get(n)).filter(Boolean); 1338: const cs = await Promise.all(activeNames().map(loadCharacter)); 905:const LINEUP = CAM.lineup || { order: [], spacing: 0.9 }; 907:const CAM_VIEW = () => state.view === "duel" || ROW_VIEW() ? CAM.duel.cam : charDef(state.who).cams[state.view]; 908:const activeNames = () => state.view === "duel" ? [CAM.duel.order.player, CAM.duel.order.opponent] 909: : state.view === "lineup" ? LINEUP.order : state.view === "compare" ? state.compare : [state.who]; 1010:const lineupX = i => (i - (LINEUP.order.length - 1) / 2) * LINEUP.spacing; 1227: get lineup() { return { w: Math.max(2.0, LINEUP.order.length * LINEUP.spacing + 0.4), top: 1.60, bottom: -1.16 }; }, 1350: const i = LINEUP.order.indexOf(c.name); 1356: const pl = CAM.duel.place[c.name]; 1478: { label: "Faces (helmets and hoods off)", tw: 300, th: 340, tiles: LINEUP.order.map((n, i) => ({ clip: "ref", t: 0, yaw: 20, 1481: { label: "Faces (helmets on)", tw: 300, th: 340, tiles: LINEUP.order.map((n, i) => ({ clip: "ref", t: 0, yaw: 20, 1719:if (!LINEUP.order.length) $("lineupBtn").hidden = true;