reasoning

Initial plan is to create build_adversarial.py, a script to assemble adversarial models. This involves meticulously reviewing assembly details for Valen and Korin to ensure correct model construction within the script.

Assembly script will output a completed model file along with several image and timing outputs. The script employs specific binding tags, like "head_rigid", "ponytail_blend", "torso_skin", and "neck_blend", each corresponding to different bone influence configurations for accurate rigging. Examining each tag's implementation in the referenced Python script confirms the intended bone assignments and blend weights.

Verifying the rigid and blend binding tags, specifically "torso_plate" and "skirt_stiff", to ensure proper bone assignment and realistic deformation. Need to double-check the implementations of plates.stiffen and G.pleated_skirt in their respective modules to validate the intended behavior.

Examining the code, the intention is to use a combination of rigid and blend bindings for the limbs, torso, and head. Specific bone assignments, such as those for the lower arm and hand, are determined through rigid binding. Allowable bone influences and fallbacks are defined for leg and foot segments to manage deformation.

  • read_file{"EndLine":195,"Path":"~/work/lowmarch/tools/plates.py","StartLine":140}

    input

    {
      "EndLine": 195,
      "Path": "~/work/lowmarch/tools/plates.py",
      "StartLine": 140
    }

    result, 57 lines

    Showing lines 140-195 of 487
    140:     the right-handed turn about the bone), v = fraction along it (0 at a, 1 at b; -0.2..1.2 covered)."""
    141: 
    142:     def __init__(self, over, a, b, front=(0, 0, -1), du=6.0, dv=0.025, smooth=(1.2, 1.2), shell=True, rmax=0.14,
    143:                  v_range=(-0.2, 1.2)):
    144:         self.a, self.b = np.asarray(a, float), np.asarray(b, float)
    145:         ax = self.b - self.a
    146:         self.L = float(np.linalg.norm(ax))
    147:         self.ax = ax / self.L
    148:         f = np.asarray(front, float) - self.ax * (np.asarray(front, float) @ self.ax)
    149:         self.f = f / np.linalg.norm(f)
    150:         self.s = np.cross(self.ax, self.f)
    151:         self.wrap = True
    152:         self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, v_range[0], dv, dv * 0.5
    153:         us = np.arange(-180.0, 180.0, du)
    154:         vs = np.arange(v_range[0], v_range[1] + dv * 0.5, dv)
    155:         R = np.full((len(us), len(vs)), np.nan)
    156:         for i, u in enumerate(us):
    157:             ur = math.radians(u)
    158:             d = self.f * math.cos(ur) + self.s * math.sin(ur)
    159:             for j, v in enumerate(vs):
    160:                 R[i, j] = over.cast(self.a + self.ax * self.L * v, d, rmax=rmax, far=True)
    161:         self._setup(R, smooth, shell, True)
    162: 
    163:     def ray(self, u, v):
    164:         u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))
    165:         ur = np.radians(u)
    166:         d = np.cos(ur)[..., None] * self.f + np.sin(ur)[..., None] * self.s
    167:         o = self.a + self.ax * (self.L * v)[..., None]
    168:         return o, d
    169: 
    170:     def metric(self, u, v):
    171:         return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) * self.L + 0 * np.asarray(u, float)], -1)
    172: 
    173:     def centre(self, v):
    174:         return self.a + self.ax * self.L * v
    175: 
    176: 
    177: def _thick(G, n, thickness, data, uv):
    178:     """A grid shell (outer face G, inner face G - n*thickness, the four edges closed) with per-vertex
    179:     plate data and decal coordinates: the inner face copies the outer, edge walls sit at the outline
    180:     (distance 0)."""
    181:     U, V = G.shape[:2]
    182:     idx = np.arange(U * V).reshape(U, V)
    183:     a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]
    184:     tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)])
    185:     th = np.asarray(thickness, float)
    186:     outer, inner = G.reshape(-1, 3), (G - n * (th[..., None] if th.ndim else th)).reshape(-1, 3)
    187:     fn = np.cross(outer[tri[:, 1]] - outer[tri[:, 0]], outer[tri[:, 2]] - outer[tri[:, 0]])
    188:     if (np.einsum("ij,ij->i", fn, n.reshape(-1, 3)[tri[:, 0]]) < 0).mean() > 0.5:
    189:         tri = tri[:, ::-1]                             # the outer face winds outward (along the chart normal)
    190:     mid = (outer.mean(0) + inner.mean(0)) / 2
    191:     D, UV = data.reshape(-1, 4), uv.reshape(-1, 2)
    192:     pos, tris, dat, uvs = [outer, inner], [tri, tri[:, ::-1] + U * V], [D, D], [UV, UV]
    193:     off = 2 * U * V
    194:     for e in (idx[:, 0], idx[:, -1], idx[0, :], idx[-1, :]):
    195:         m = len(e)
  • read_file{"EndLine":620,"Path":"~/work/lowmarch/tools/battle_slice.py","StartLine":550}

    input

    {
      "EndLine": 620,
      "Path": "~/work/lowmarch/tools/battle_slice.py",
      "StartLine": 550
    }

    result, 72 lines

    Showing lines 550-620 of 686
    550:         dict(
    551:             name="valen",
    552:             label="Valen (Vanguard Captain)",
    553:             cage_body="arm_f_strong",
    554:             morphs={"Fcl_BRW_Angry": 0.38, "Fcl_EYE_Angry": 0.18},
    555:             shape={"blush": 0.25},
    556:             costume=vanguard_captain,
    557:             pose_fn=vanguard_pose,
    558:             place={"pos": [-0.74, 0.0, 0.04], "yaw": 32.0},
    559:             wind=-3.2,
    560:             colors={
    561:                 "r": "#1e2e52", "s": "#3b629c", "t": "#8bb8ea",
    562:                 "A": "#2f1a18", "o": "#241618",
    563:             },
    564:             paint={
    565:                 "skin": "#f5dcd0",
    566:                 "hair": "#542c26",
    567:                 "signature": "#243b61",
    568:                 "cape": "#822330",
    569:                 "doublet": "#252836",
    570:                 "heraldry": "#e8e2d4",
    571:                 "steel": "#b6becb",
    572:                 "gold": "#c89e48",
    573:                 "leather": "#523526",
    574:                 "glove": "#462d21",
    575:                 "boot": "#38251c",
    576:                 "wood": "#6b482e",
    577:             },
    578:         ),
    579:         dict(
    580:             name="korin",
    581:             label="Korin (Heavy Housecarl)",
    582:             cage_body="arm_m_strong",
    583:             morphs={"Fcl_BRW_Angry": 0.48, "Fcl_EYE_Angry": 0.22},
    584:             shape={"blush": 0.0},
    585:             costume=heavy_housecarl,
    586:             pose_fn=housecarl_pose,
    587:             place={"pos": [0.76, 0.0, -0.02], "yaw": -33.0},
    588:             wind=2.8,
    589:             colors={
    590:                 "r": "#2c1d14", "s": "#7a4e26", "t": "#c49052",
    591:                 "A": "#181920", "o": "#1e1412",
    592:             },
    593:             paint={
    594:                 "skin": "#b87a54",
    595:                 "hair": "#252730",
    596:                 "signature": "#7a252c",
    597:                 "padding": "#cec2ac",
    598:                 "mail": {"kind": "steel", "base": "#7d8492"},
    599:                 "doublet": "#363b37",
    600:                 "heraldry": "#ddd8cc",
    601:                 "steel": "#a0a8b6",
    602:                 "gold": "#b38b3d",
    603:                 "leather": "#583827",
    604:                 "glove": "#452d20",
    605:                 "boot": "#38251c",
    606:                 "wood": "#68462c",
    607:             },
    608:         ),
    609:     ]
    610: 
    611:     built_chars = [build_unit(u) for u in units]
    612: 
    613:     world_holder = type("WorldPortrait", (), {})()
    614:     world_holder.prims = terrain.plains(width=4.8, depth=2.1, thick=0.30, seed=5, tufts=34, stones=7)
    615:     world_holder.roles = [p["role"] for p in world_holder.prims]
    616:     world_holder.tex = {}
    617:     plains_path = os.path.join(OUT_DIR, "plains.glb")
    618:     export_glb.export(world_holder, vp.PALETTE, plains_path, only_world=True)
    619:     wrap_glb_json(plains_path)
    620:
  • read_file{"EndLine":390,"Path":"~/work/lowmarch/tools/plates.py","StartLine":330}

    input

    {
      "EndLine": 390,
      "Path": "~/work/lowmarch/tools/plates.py",
      "StartLine": 330
    }

    result, 62 lines

    Showing lines 330-390 of 487
    330:     edge = np.concatenate([G[:, 0], G[:, -1], G[0, :], G[-1, :]])
    331:     dense = np.array([edge[k] + (edge[k + 1] - edge[k]) * t for k in range(len(edge) - 1)
    332:                       for t in (0.0, 0.25, 0.5, 0.75)])
    333:     dist, _ = cKDTree(dense).query(G.reshape(-1, 3))
    334:     data = np.stack([np.ones(nu * nv), dist, np.full(nu * nv, float(trim)), np.tile(T, nu)], 1).reshape(nu, nv, 4)
    335:     # decal coordinates: (u, v) mapped linearly onto the plate's bounding square
    336:     vmin, vmax = float(vv.min()), float(vv.max())
    337:     to_st = lambda u, v: np.stack([(np.asarray(u, float) - u0) / (u1 - u0), (np.asarray(v, float) - vmin) / max(vmax - vmin, 1e-9)], -1)
    338:     uv = to_st(uu, vv)
    339:     if callable(thickness):                            # per point, e.g. a solid mass down to the surface
    340:         thickness = np.array([[thickness(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)])
    341:     pos, tri, dat, uvs = _thick(G, n, thickness, data, uv)
    342:     pc = piece(name, role, pos, tri)
    343:     pc["plate"] = dat
    344:     if pattern is not None:                            # a repeating texture (mail rings): (image, metres per repeat)
    345:         img, period = pattern
    346:         mid_u, mid_v = (u0 + u1) / 2, (vmin + vmax) / 2
    347:         wm = abs(np.radians(u1 - u0)) * float(chart.radius(mid_u, mid_v))
    348:         hm = (vmax - vmin) * (1 if isinstance(chart, TorsoChart) else chart.L)
    349:         pc["decal"] = img
    350:         pc["uv"] = uvs * np.array([wm / period, hm / period * img.shape[1] / img.shape[0]])
    351:     elif seams or decal:
    352:         mid_u, mid_v = (u0 + u1) / 2, (vmin + vmax) / 2
    353:         wm = abs(np.radians(u1 - u0)) * float(chart.radius(mid_u, mid_v))       # metres across and up
    354:         hm = (vmax - vmin) * (1 if isinstance(chart, TorsoChart) else chart.L)
    355:         px_m = decal_px
    356:         cv_ = Canvas(min(1024, max(64, wm * px_m)), min(1024, max(64, hm * px_m)))
    357:         sx, sy = cv_.w / max(wm, 1e-6), cv_.h / max(hm, 1e-6)       # pixels per metre across and up
    358:         for L in seams:
    359:             cv_.line(to_st(*np.array(L, float).T), groove[0] * 0.7 * sx, "groove")
    360:         for sh in decal:
    361:             if sh[0] == "poly":
    362:                 cv_.poly(to_st(*np.array(sh[1], float).T), sh[2])
    363:             elif sh[0] == "line":
    364:                 cv_.line(to_st(*np.array(sh[1], float).T), sh[2] * sx, sh[3])
    365:             elif sh[0] == "dot":
    366:                 cv_.dot(to_st(*sh[1]), sh[2] * sx, sh[2] * sy, sh[3])
    367:         pc["decal"] = cv_.array()
    368:         pc["uv"] = uvs
    369:     extras = []
    370:     lines = {"bottom": G[:, 0], "top": G[:, -1], "left": G[0, :], "right": G[-1, :]}
    371:     if roll:
    372:         for k, e in enumerate(roll_edges):
    373:             L = lines[e] + (n[:, 0] if e == "bottom" else n[:, -1] if e == "top" else n[0] if e == "left" else n[-1]) * roll * 0.4
    374:             if np.ptp(L, axis=0).max() < 1e-4:
    375:                 continue
    376:             extras.append(pipe(f"{name}_roll{k}", roll_role or role, L, r=roll, seg=7))
    377:     if rivets:
    378:         spacing, inset, rr = rivets
    379:         ring = np.concatenate([G[:, 0], G[-1, 1:], G[::-1, -1][1:], G[0, ::-1][1:]])
    380:         ring_n = np.concatenate([n[:, 0], n[-1, 1:], n[::-1, -1][1:], n[0, ::-1][1:]])
    381:         mid = G.reshape(-1, 3).mean(0)
    382:         seglen = np.linalg.norm(np.diff(ring, axis=0), axis=1)
    383:         at = np.concatenate([[0], np.cumsum(seglen)])
    384:         for k, s_ in enumerate(np.arange(spacing / 2, at[-1], spacing)):
    385:             i = min(np.searchsorted(at, s_) - 1, len(ring) - 2)
    386:             p_ = ring[i] + (ring[i + 1] - ring[i]) * ((s_ - at[i]) / max(seglen[i], 1e-9))
    387:             q = p_ + (mid - p_) / max(np.linalg.norm(mid - p_), 1e-9) * inset
    388:             extras.append(ball(f"{name}_rivet{k}", rivet_role, q + ring_n[i] * rr * 0.3, rr, seg=8, rows=5))
    389:     for k, (su, sv) in enumerate(studs):               # domed studs at seam junctions, on the plate's surface
    390:         i = int(np.argmin(np.abs(U - su)))
  • read_file{"EndLine":487,"Path":"~/work/lowmarch/tools/plates.py","StartLine":430}

    input

    {
      "EndLine": 487,
      "Path": "~/work/lowmarch/tools/plates.py",
      "StartLine": 430
    }

    result, 59 lines

    Showing lines 430-487 of 487
    430:             i0, i1, i2 = idx[k - 1], idx[k], idx[(k + 1) % len(idx)]
    431:             a, b, c = P[i0], P[i1], P[i2]
    432:             if (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) <= 1e-12:
    433:                 continue                                   # reflex corner
    434:             if any(inside(P[j], a, b, c) for j in idx if j not in (i0, i1, i2)):
    435:                 continue
    436:             tri.append((i0, i1, i2))
    437:             idx.pop(k)
    438:             break
    439:     if len(idx) == 3:
    440:         tri.append(tuple(idx))
    441:     return np.array(tri, int)
    442: 
    443: 
    444: def flat_piece(name, role, outline, origin, ex, ey, thickness=0.002, decal=(), px=4000):
    445:     """A flat convex shape (outline: (x, y) points in metres, in order) on the plane origin + x ex + y ey,
    446:     given thickness along ex x ey, with an optional decal in the same (x, y) coordinates."""
    447:     from outfit import piece
    448:     O, ex, ey = (np.asarray(a, float) for a in (origin, ex, ey))
    449:     nz = np.cross(ex, ey)
    450:     nz /= np.linalg.norm(nz)
    451:     P2 = np.asarray(outline, float)
    452:     c2 = P2.mean(0)
    453:     m = len(P2)
    454:     lo, hi = P2.min(0), P2.max(0)
    455:     span = np.maximum(hi - lo, 1e-6)
    456:     pts = np.vstack([c2, P2])
    457:     top = O + pts[:, :1] * ex + pts[:, 1:] * ey + nz * thickness / 2
    458:     bot = top - nz * thickness
    459:     k = np.arange(m)
    460:     fan = 1 + _ear_clip(P2)                            # any simple outline, concave too (an axe's crescent)
    461:     nn = m + 1
    462:     wall = np.concatenate([np.stack([1 + k, 1 + (k + 1) % m, nn + 1 + (k + 1) % m], 1),
    463:                            np.stack([1 + k, nn + 1 + (k + 1) % m, nn + 1 + k], 1)])
    464:     tri = np.concatenate([fan, fan[:, ::-1] + nn, wall])
    465:     pos = np.concatenate([top, bot])
    466:     if np.cross(pos[tri[0, 1]] - pos[tri[0, 0]], pos[tri[0, 2]] - pos[tri[0, 0]]) @ nz < 0:
    467:         tri = np.concatenate([fan[:, ::-1], fan + nn, wall[:, ::-1]])
    468:     pc = piece(name, role, pos, tri)
    469:     if decal:
    470:         cv = Canvas(min(1024, max(32, span[0] * px)), min(1024, max(32, span[1] * px)))
    471:         st = lambda xy: (np.atleast_2d(np.asarray(xy, float)) - lo) / span
    472:         for sh in decal:
    473:             if sh[0] == "poly":
    474:                 cv.poly(st(sh[1]), sh[2])
    475:             elif sh[0] == "line":
    476:                 cv.line(st(sh[1]), sh[2] * cv.w / span[0], sh[3])
    477:         pc["decal"] = cv.array()
    478:         pc["uv"] = np.concatenate([st(pts), st(pts)])
    479:     return pc
    480: 
    481: 
    482: def taper(pc, n_along, n_round, scale):
    483:     """Scale a pipe's cross-section along its length (scale: one factor per centreline point)."""
    484:     P = pc["pos"].reshape(n_along, n_round, 3)
    485:     C = P.mean(1, keepdims=True)
    486:     pc["pos"] = (C + (P - C) * np.asarray(scale, float)[:, None, None]).reshape(-1, 3)
    487:     return pc
  • read_file{"EndLine":425,"Path":"~/work/lowmarch/tools/plates.py","StartLine":390}

    input

    {
      "EndLine": 425,
      "Path": "~/work/lowmarch/tools/plates.py",
      "StartLine": 390
    }

    result, 37 lines

    Showing lines 390-425 of 487
    390:         i = int(np.argmin(np.abs(U - su)))
    391:         j = int(np.argmin(np.abs(vv[i] - sv)))
    392:         o, d = chart.ray(su, sv)
    393:         p_ = chart.point(su, sv) + chart.normal(su, sv) * (lift[i, j] + stud_r * 0.2)
    394:         extras.append(ball(f"{name}_stud{k}", stud_role or role, p_, stud_r, seg=10, rows=6, squash=(1, 1, 1)))
    395:     return pc, extras
    396: 
    397: 
    398: def stiffen(pc, fit, bone="J_Bip_C_Hips", share=0.6):
    399:     """Move `share` of every vertex's weight onto one bone: a stiff garment (a starched overskirt, a
    400:     plate hanging from the belt) that the legs only partly drag."""
    401:     n, nj = len(pc["J"]), len(fit.jnames)
    402:     dense = np.zeros((n, nj))
    403:     np.add.at(dense, (np.repeat(np.arange(n), pc["J"].shape[1]), pc["J"].ravel()), pc["W"].ravel())
    404:     dense *= 1 - share
    405:     dense[:, fit.jnames.index(bone)] += share
    406:     top = np.argsort(-dense, 1)[:, :4]
    407:     W = np.take_along_axis(dense, top, 1)
    408:     pc["J"], pc["W"] = top.astype(np.int64), W / np.maximum(W.sum(1, keepdims=True), 1e-12)
    409:     pc["jnames"] = fit.jnames
    410:     return pc
    411: 
    412: 
    413: def _ear_clip(P):
    414:     """Triangles (index triples into P) filling a simple polygon P (n, 2), either winding."""
    415:     P = np.asarray(P, float)
    416:     n = len(P)
    417:     area = 0.5 * np.sum(P[:, 0] * np.roll(P[:, 1], -1) - np.roll(P[:, 0], -1) * P[:, 1])
    418:     idx = list(range(n)) if area > 0 else list(range(n))[::-1]
    419:     tri = []
    420: 
    421:     def inside(p, a, b, c):
    422:         d1 = (p[0] - b[0]) * (a[1] - b[1]) - (a[0] - b[0]) * (p[1] - b[1])
    423:         d2 = (p[0] - c[0]) * (b[1] - c[1]) - (b[0] - c[0]) * (p[1] - c[1])
    424:         d3 = (p[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (p[1] - a[1])
    425:         return not ((d1 < 0 or d2 < 0 or d3 < 0) and (d1 > 0 or d2 > 0 or d3 > 0))
reasoning

The provided code snippet demonstrates a clear application of a "stiffen" function, targeting the "J_Bip_C_Hips" bone with a sharing value. Examining the related lines within the "plates.py" file, the code demonstrates how the "fit" binds the "pc" to specific body parts. The code is clean and appears to be correctly implemented for the specific task at hand.

The "stiffen" function applied to the "J_Bip_C_Hips" bone dynamically influences the split surcoat and underkirtle, maintaining a starched silhouette during leg movements. The "fit.bind" operation on tasset_R_* and tasset_L_* ensures each hip tasset remains rigid like a tilting steel plate. Considering Valen's color palette, aiming for an iconic, aristocratic design distinct from previous iterations.

Initial assessment suggests rich burnished rose-auburn or warm pale ash-platinum hair to create contrast against the silver-steel armor and indigo surcoat. Recalling a specific line indicates a preference for warm ash-platinum, however, the color code needs confirmation from the relevant file for verification.

The color codes reveal a carefully considered palette for Valen: cool twilight-ash shadow, warm silver-taupe shadow, luminous champagne-platinum as the base, and a crisp ivory-gold highlight. The outline ink is a crisp dark shade to ensure silhouette separation. The updated scheme provides a striking visual contrast to previous designs, creating a more iconic character appearance.

  • write_file{"Content":"\"\"\"Adversarial Pass builder: Blender 5.2 body/face sculpt, 3D lock hair, bespoke gothic-anime armour,\ncustom painted anime eyes + UV face shadow bias, multi-clip rigged GLB export, and Flattice perspective shot.\n\nOutputs:\n - ~/out/valen_finished.glb (standalone rigged + multi-clip animated 3D character model)\n - ~/out/battle_frame_after.png (1920x1080 2x-supersampled After battle visual)\n - ~/out/valen_flattice_persp.png (1920x960 2x-SS 24 mm perspective camera: Flattice Off vs On)\n\"\"\"\nimport argparse\nimport base64\nimport json\nimport math\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\n\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(HERE)\nsys.path[:0] = [HERE, os.path.join(ROOT, \"art\", \"cast\")]\n\nimport battle_slice as bs # noqa: E402\nimport checks # noqa: E402\nimport duel # noqa: E402\nimport export_glb # noqa: E402\nimport gear as G # noqa: E402\nimport outfit as O # noqa: E402\nimport poses as P # noqa: E402\nimport terrain # noqa: E402\nimport vroid_portrait as vp # noqa: E402\nfrom fitting import merge_surfaces # noqa: E402\nfrom plates import stiffen # noqa: E402\nfrom rig import Rig, grip_points # noqa: E402\n\nADV_OUT_DIR = os.path.join(ROOT, \"review\", \"out\", \"slice_after\")\nCACHE_DIR = os.path.expanduser(\"~/.cache/lowmarch_adv\")\nBLENDER_SCRIPT = os.path.join(HERE, \"blender_sculpt_cast.py\")\n\n\n# ---------------------------------------------------------------------------\n# 1. Custom High-Resolution Anime Eye Textures & Authored Face Shadow Bias\n# ---------------------------------------------------------------------------\ndef paint_anime_iris_rgba(orig_rgba, scheme=\"sapphire\"):\n \"\"\"Paint a luminous studio-anime iris RGBA texture inside the exact alpha footprint of orig_rgba.\"\"\"\n H, W = orig_rgba.shape[:2]\n alpha = orig_rgba[..., 3].astype(np.float32) / 255.0\n out = np.zeros((H, W, 4), dtype=np.uint8)\n ys, xs = np.nonzero(alpha > 0.15)\n if not len(xs):\n return orig_rgba.copy()\n\n # Handle single or twin UV islands cleanly via connected components or bounding box\n from scipy.ndimage import label\n lab, n_comp = label(alpha > 0.15)\n rgb = np.zeros((H, W, 3), dtype=np.float32)\n\n if scheme == \"sapphire\":\n c_limbal = np.array([0.07, 0.11, 0.24]) # deep midnight navy limbal ring\n c_upper = np.array([0.11, 0.19, 0.42]) # rich indigo upper lash shadow\n c_mid = np.array([0.22, 0.44, 0.80]) # royal sapphire mid-iris\n c_lower = np.array([0.52, 0.84, 0.99]) # radiant cerulean-cyan lower arc\n c_pupil = np.array([0.05, 0.08, 0.20]) # deep velvet pupil core\n c_ring = np.array([0.74, 0.93, 1.00]) # crystalline inner corona\n else:\n c_limbal = np.array([0.13, 0.08, 0.05])\n c_upper = np.array([0.28, 0.16, 0.08])\n c_mid = np.array([0.62, 0.38, 0.15])\n c_lower = np.array([0.95, 0.72, 0.30])\n c_pupil = np.array([0.09, 0.06, 0.04])\n c_ring = np.array([1.00, 0.86, 0.48])\n\n for cid in range(1, n_comp + 1):\n cy_i, cx_i = np.nonzero(lab == cid)\n if len(cx_i) < 20:\n continue\n x0, x1 = cx_i.min(), cx_i.max()\n y0, y1 = cy_i.min(), cy_i.max()\n cx = 0.5 * (x0 + x1)\n cy = 0.5 * (y0 + y1)\n rx = max(1.0, 0.5 * (x1 - x0))\n ry = max(1.0, 0.5 * (y1 - y0))\n\n yy, xx = np.mgrid[y0:y1 + 1, x0:x1 + 1]\n nx = (xx - cx) / rx\n ny = (yy - cy) / ry # Note: in glTF image space y=0 is top, y=H is bottom!\n r = np.sqrt(nx * nx + ny * ny)\n ang = np.arctan2(ny, nx)\n\n # Vertical anime gradient: top (ny < 0) in deep shadow, bottom (ny > 0) glowing!\n v_grad = np.clip((ny + 0.55) / 1.35, 0.0, 1.0)\n base = np.where(v_grad[..., None] < 0.48,\n c_upper + (c_mid - c_upper) * (v_grad[..., None] / 0.48),\n c_mid + (c_lower - c_mid) * ((v_grad[..., None] - 0.48) / 0.52))\n\n # Radial crystalline striations\n rays = 0.5 + 0.5 * np.sin(ang * 28.0 + 0.4 * np.sin(ang * 7.0))\n ray_mask = np.clip((r - 0.26) / 0.22, 0.0, 1.0) * np.clip((0.86 - r) / 0.16, 0.0, 1.0)\n base = base + (c_ring - base) * (0.28 * rays * ray_mask * (0.35 + 0.65 * v_grad))[..., None]\n\n # Glowing lower crescent bounce arc\n crescent = np.exp(-((r - 0.64) / 0.13) ** 2) * np.clip((ny - 0.10) / 0.65, 0.0, 1.0) ** 1.3\n base = base + (c_ring - base) * (0.52 * crescent)[..., None]\n\n # Crisp dark pupil with soft corona rim\n pupil_w = 1.0 - np.clip((r - 0.25) / 0.09, 0.0, 1.0)\n corona = np.exp(-((r - 0.31) / 0.055) ** 2) * (0.45 + 0.55 * v_grad)\n base = base + (c_ring - base) * (0.40 * corona)[..., None]\n base = base * (1.0 - pupil_w[..., None]) + c_pupil * pupil_w[..., None]\n\n # Crisp outer limbal ring + upper lash cast shadow band across top 28% of iris\n limbal = np.clip((r - 0.78) / 0.16, 0.0, 1.0)\n lash_sh = np.clip((-ny - 0.22) / 0.48, 0.0, 1.0) * 0.62\n base = base * (1.0 - lash_sh[..., None]) + (c_limbal * 0.85) * lash_sh[..., None]\n base = base * (1.0 - limbal[..., None]) + c_limbal * limbal[..., None]\n\n sub_m = lab[y0:y1 + 1, x0:x1 + 1] == cid\n rgb[y0:y1 + 1, x0:x1 + 1][sub_m] = np.clip(base[sub_m], 0.0, 1.0)\n\n out[..., :3] = np.round(rgb * 255.0).astype(np.uint8)\n out[..., 3] = orig_rgba[..., 3]\n return out\n\n\ndef paint_anime_highlight_rgba(orig_rgba):\n \"\"\"Crisp studio-anime primary upper-left catchlight + jewel lower-right pin catchlight.\"\"\"\n out = orig_rgba.copy()\n # Boost existing highlight opacity & brightness to pure crisp white so catchlights pop cleanly\n m = out[..., 3] > 32\n out[m, :3] = 255\n out[m, 3] = np.clip(out[m, 3].astype(np.int32) * 2, 0, 255).astype(np.uint8)\n return out\n\n\ndef bake_face_shadow_bias(face_pos, lm):\n \"\"\"Authored per-vertex anime face shadow bias stored in _PLATE = [2.0, bias, 0.0, 0.0].\n Carves crisp anime nose-tip diamond shadow, orbital brow depth, under-lip crease, and lit malar cheek triangle!\n \"\"\"\n n = len(face_pos)\n plate = np.zeros((n, 4), dtype=np.float32)\n plate[:, 0] = 2.0 # Sentinel > 1.5 telling PAINT_FS this is a face shadow bias attribute, not gold armour trim\n\n x = face_pos[:, 0]\n y = face_pos[:, 1]\n z = face_pos[:, 2]\n eye_y = float(lm[\"eye_y\"])\n eye_x = abs(float(lm[\"eyeR\"][0]))\n nose = lm[\"nose\"]\n mouth = lm[\"mouth\"]\n\n # 1. Crisp anime under-nose shadow triangle (just below nose tip, slight negative bias)\n nose_under = (\n np.exp(-((y - (nose[1] - 0.0085)) / 0.0075) ** 2)\n * np.exp(-(x / 0.0095) ** 2)\n * np.clip((-z - (-nose[2] - 0.018)) / 0.015, 0.0, 1.0)\n )\n # 2. Upper orbital / under-brow socket depth\n orbital = (\n np.exp(-((y - (eye_y + 0.011)) / 0.0075) ** 2)\n * np.exp(-((np.abs(x) - eye_x) / 0.019) ** 2)\n )\n # 3. Delicate mentolabial crease under the lower lip\n lip_under = (\n np.exp(-((y - (mouth[1] - 0.009)) / 0.0055) ** 2)\n * np.exp(-(x / 0.012) ** 2)\n )\n # 4. Positive Rembrandt malar cheek prominence + nose bridge highlight so 3/4 lit planes never muddy!\n cheek_lit = (\n np.exp(-((y - (eye_y - 0.024)) / 0.018) ** 2)\n * np.exp(-((np.abs(x) - (eye_x + 0.006)) / 0.020) ** 2)\n )\n bridge_lit = (\n np.exp(-((y - (nose[1] + 0.014)) / 0.014) ** 2)\n * np.exp(-(x / 0.0055) ** 2)\n )\n\n bias = (-0.22 * nose_under - 0.11 * orbital - 0.12 * lip_under\n + 0.095 * cheek_lit + 0.085 * bridge_lit)\n plate[:, 1] = np.clip(bias, -0.35, 0.25).astype(np.float32)\n return plate\n\n\n# ---------------------------------------------------------------------------\n# 2. Multi-Clip Skeletal Combat & Stepped 12 fps Animations for Valen\n# ---------------------------------------------------------------------------\ndef build_valen_clips(vrm, shape):\n \"\"\"Build 4 skeletal clips for valen_finished.glb:\n - battle_guard: poised 3/4 sword-and-shield vanguard stance (used in battle frame & perspective shot)\n - idle_breath_12fps: 2.0 s stepped 12 fps tactical breathing & sword-poise loop (25 stepped keys)\n - strike_combo_12fps: 1.5 s stepped 12 fps anticipation -> shield bash -> sword lunge -> hit-stop -> recovery\n - bust_ref: clean reference inspection stance\n \"\"\"\n rig = Rig(vrm, shape, ortho=True)\n body = checks.Body(vrm, shape)\n f = {s: g[\"point\"] for s, g in grip_points(vrm, shape, P.BUST).items()}\n ref = dict(ref_pose=P.BUST, fist_R=f[\"R\"], fist_L=f[\"L\"])\n foot = {s: rig.pos(P.BATTLE_IDLE, f\"J_Bip_{s}_Foot\") for s in \"LR\"}\n\n def make_guard(hip_dy=-0.058, torso_twist=-11.0, sword_lift=0.0, shield_brace=0.0, lunge_z=0.0):\n base = P.merge(P.BATTLE_IDLE, P.fist(\"L\", curl=(74, 86, 62), thumb=38), {\n \"J_Bip_C_Hips\": P.move(0, hip_dy, -0.02 + lunge_z, P.rot((0, 1, 0), torso_twist) @ P.rot((1, 0, 0), -5.0)),\n \"J_Bip_C_Spine\": P.rot((0, 1, 0), torso_twist * 0.75) @ P.rot((1, 0, 0), -3.2),\n \"J_Bip_C_Chest\": P.rot((0, 1, 0), torso_twist * 0.55) @ P.rot((1, 0, 0), -2.2),\n \"J_Bip_C_Neck\": P.rot((0, 1, 0), -torso_twist * 1.05) @ P.rot((1, 0, 0), 3.2),\n \"J_Bip_C_Head\": P.rot((0, 1, 0), -torso_twist * 0.95) @ P.rot((1, 0, 0), 2.5),\n })\n pose = rig.leg_ik(base, \"L\", foot[\"L\"] + np.array([-0.065, 0.0, -0.18]), pole=(0, 0, -1))\n pose = rig.leg_ik(pose, \"R\", foot[\"R\"] + np.array([0.075, 0.0, 0.15]), pole=(0, -0.2, -1))\n\n sh_r = rig.pos(pose, \"J_Bip_R_UpperArm\")\n fist_r = sh_r + np.array([0.10, -0.33 + sword_lift, -0.21 + lunge_z * 1.6])\n blade_dir = np.array([-0.22, 0.52 + sword_lift * 0.8, -0.82 + lunge_z * 1.2])\n blade_dir /= np.linalg.norm(blade_dir)\n pose = duel.clear_grip(rig, body, pose, \"R\", ref, fist_r, blade_dir, (0.72, -0.88, 0.35))\n\n sh_l = rig.pos(pose, \"J_Bip_L_UpperArm\")\n pose = rig.arm_ik(pose, \"L\", sh_l + np.array([-0.27, -0.21 + shield_brace, 0.05 - shield_brace * 0.6]),\n pole=(-0.6, -0.9, 0.5))\n return pose\n\n guard = make_guard()\n\n # Stepped 12 fps idle loop (24 frames @ 1/12 s = 2.0 s)\n idle_keys = []\n for fr in range(25):\n t = fr / 12.0\n ph = 2.0 * math.pi * (fr / 24.0)\n # Quantize phase on twos (classic anime 12 fps / 6s cadence!)\n ph_q = 2.0 * math.pi * ((fr // 2) * 2 / 24.0)\n p_fr = make_guard(\n hip_dy=-0.058 + 0.007 * math.sin(ph_q),\n torso_twist=-11.0 + 1.8 * math.sin(ph_q),\n sword_lift=0.014 * math.sin(ph_q - 0.4),\n shield_brace=0.008 * math.cos(ph_q),\n )\n idle_keys.append((round(t, 5), p_fr))\n\n # Stepped 12 fps strike combo with explicit anticipation & 3-frame hit-stop!\n strike_specs = [\n (0, -0.058, -11.0, 0.00, 0.00, 0.00), # Guard\n (2, -0.078, -22.0, 0.08, 0.03, 0.04), # Wind-up anticipation (coil back!)\n (4, -0.084, -25.0, 0.11, 0.04, 0.05), # Hold coiled apex (2 frames)\n (5, -0.048, 16.0, -0.04, -0.02, -0.14), # Explosive lunge snap!\n (6, -0.044, 21.0, -0.06, -0.03, -0.18), # Impact frame (HIT-STOP begins)\n (9, -0.044, 21.0, -0.06, -0.03, -0.18), # 3-frame anime hit-stop freeze!\n (12, -0.064, 4.0, 0.02, 0.01, -0.06), # Follow-through recovery\n (15, -0.060, -7.0, 0.01, 0.00, -0.01), # Settle into guard\n (18, -0.058, -11.0, 0.00, 0.00, 0.00), # Guard\n ]\n strike_keys = [\n (round(fr / 12.0, 5), make_guard(hdy, tw, sl, sb, lz))\n for (fr, hdy, tw, sl, sb, lz) in strike_specs\n ]\n\n bust_pose = P.merge(P.BUST, P.fist(\"R\"), P.fist(\"L\"))\n return {\n \"battle_guard\": [(0.0, guard), (1.0, guard)],\n \"idle_breath_12fps\": idle_keys,\n \"strike_combo_12fps\": strike_keys,\n \"bust_ref\": [(0.0, bust_pose), (1.0, bust_pose)],\n }\n\n\n# ---------------------------------------------------------------------------\n# 3. Bind Blender 5.2 Sculpted Pieces onto Lowmarch's Skeleton\n# ---------------------------------------------------------------------------\ndef bind_blender_piece(fit, nm, role, pos, nrm, tri, bind_tag, grp):\n pc = dict(\n mesh=\"outfit\",\n material=f\"OUTFIT_{nm}\",\n mi=-1,\n role=role,\n pos=pos.astype(np.float64),\n nrm=nrm.astype(np.float64),\n uv=np.zeros((len(pos), 2), dtype=np.float64),\n tri=tri.astype(np.int32),\n group=grp,\n )\n if bind_tag == \"head_rigid\":\n fit.bind(pc, rigid=\"J_Bip_C_Head\")\n elif bind_tag == \"ponytail_blend\":\n fit.bind(pc, blend={\"J_Bip_C_Head\": 0.80, \"J_Bip_C_Neck\": 0.14, \"J_Bip_C_UpperChest\": 0.06})\n elif bind_tag == \"torso_skin\":\n fit.bind(pc, allow=(\"Spine\", \"Chest\", \"UpperChest\", \"Neck\", \"Hips\"), fallback=\"J_Bip_C_Chest\")\n elif bind_tag == \"neck_blend\":\n fit.bind(pc, blend={\"J_Bip_C_Neck\": 0.65, \"J_Bip_C_UpperChest\": 0.35})\n elif bind_tag == \"uchest_blend\":\n fit.bind(pc, rigid=\"J_Bip_C_UpperChest\")\n elif bind_tag == \"torso_plate\":\n fit.bind(pc, allow=(\"Spine\", \"Chest\", \"UpperChest\"), fallback=\"J_Bip_C_Chest\")\n stiffen(pc, fit, \"J_Bip_C_Chest\", share=0.55)\n elif bind_tag == \"hips_stiff\":\n fit.bind(pc, rigid=\"J_Bip_C_Hips\")\n elif bind_tag == \"skirt_stiff\":\n if nm.startswith(\"tasset_\"):\n side = \"R\" if \"_R_\" in nm else \"L\"\n fit.bind(pc, blend={f\"J_Bip_{side}_UpperLeg\": 0.56, \"J_Bip_C_Hips\": 0.44})\n else:\n fit.bind(pc, allow=(\"Hips\", \"UpperLeg\"), fallback=\"J_Bip_C_Hips\")\n stiffen(pc, fit, \"J_Bip_C_Hips\", share=0.46)\n elif bind_tag.startswith(\"uarm_\"):\n side = bind_tag[-1]\n fit.bind(pc, rigid=f\"J_Bip_{side}_UpperArm\")\n elif bind_tag.startswith(\"pauldron_\"):\n side = bind_tag[-1]\n fit.bind(pc, blend={f\"J_Bip_{side}_UpperArm\": 0.50, f\"J_Bip_{side}_Shoulder\": 0.32, \"J_Bip_C_UpperChest\": 0.18})\n elif bind_tag.startswith(\"larm_\"):\n if bind_tag == \"larm_rigid\":\n fit.bind(pc, rigid=\"J_Bip_L_LowerArm\")\n else:\n side = bind_tag[-1]\n fit.bind(pc, rigid=f\"J_Bip_{side}_LowerArm\")\n elif bind_tag.startswith(\"hand_\"):\n side = bind_tag[-1]\n fit.bind(pc, rigid=f\"J_Bip_{side}_Hand\")\n elif bind_tag.startswith(\"leg_skin_\"):\n side = bind_tag[-1]\n fit.bind(pc, allow=(\"Hips\", f\"{side}_UpperLeg\", f\"{side}_LowerLeg\", f\"{side}_Foot\"),\n fallback=f\"J_Bip_{side}_LowerLeg\")\n elif bind_tag.startswith(\"uleg_\"):\n side = bind_tag[-1]\n fit.bind(pc, rigid=f\"J_Bip_{side}_UpperLeg\")\n elif bind_tag.startswith(\"lleg_\"):\n side = bind_tag[-1]\n fit.bind(pc, rigid=f\"J_Bip_{side}_LowerLeg\")\n elif bind_tag.startswith(\"foot_\"):\n side = bind_tag[-1]\n fit.bind(pc, allow=(f\"{side}_Foot\", f\"{side}_ToeBase\", f\"{side}_LowerLeg\"), fallback=f\"J_Bip_{side}_Foot\")\n elif bind_tag == \"rhand_rigid\":\n fit.bind(pc, rigid=\"J_Bip_R_Hand\")\n else:\n fit.bind(pc, rigid=\"J_Bip_C_Chest\")\n return pc\n\n\n# ---------------------------------------------------------------------------\n# 4. Build Adversarial Valen & Upgraded Korin\n# ---------------------------------------------------------------------------\ndef build_valen_adversarial(timings):\n t_start = time.time()\n vrm_path = bs.cached_cage_vrm(\"arm_f_strong\")\n v0 = vp.VRM(vrm_path)\n\n # Heroic 7.85-head Valkyrie Marshal skeletal proportions\n shape = {\n **vp.NEUTRAL,\n **G.shape(\n \"athletic\",\n \"bare\",\n leg_len=1.075,\n head=0.935,\n torso=0.90,\n chest=1.04,\n shoulder_w=0.012,\n curl=14,\n blush=0.18,\n face_normals=0.0,\n hair_normals=0.0,\n shadow_cards=0.0,\n ),\n }\n shape[\"arm_out\"] = bs.arm_room(v0, shape)\n\n t_clips0 = time.time()\n clips = build_valen_clips(v0, shape)\n timings[\"valen_clips_s\"] = round(time.time() - t_clips0, 2)\n\n guard_pose = clips[\"battle_guard\"][0][1]\n rig_guard = Rig(v0, shape, ortho=True)\n\n # Prepare Blender 5.2 input NPZ from morph-applied BUST_POSE primitives\n morphs = {\"Fcl_BRW_Angry\": 0.34, \"Fcl_EYE_Angry\": 0.16}\n pose_ref = vp.bone_pose(v0, shape, vp.BUST_POSE)\n raw_prims = v0.primitives(morphs, pose_ref)\n raw_roles = [vp.role_of(pr[\"material\"]) for pr in raw_prims]\n lm_init = vp.landmarks(raw_prims, raw_roles)\n fit_probe = O.Fit(v0, pose_ref, raw_prims, raw_roles)\n fit_probe.grip = grip_points(v0, shape, P.BUST)\n fist_R, fwd_R, side_R, flat_R, _ = G._hand_frame(fit_probe, \"R\")\n\n # Compute Aegis shield frame aligned upright in 3/4 guard, mapped back to BUST_POSE\n names = v0.nodes_by_name()\n Wg = rig_guard.world(guard_pose)\n Mg = Wg[names[\"J_Bip_L_LowerArm\"]]\n Eg, Hg = Mg[:3, 3], Wg[names[\"J_Bip_L_Hand\"]][:3, 3]\n F3 = np.diag([-1.0, 1.0, -1.0])\n a_yaw = math.radians(-32.0)\n Ry_inv = np.array([[math.cos(a_yaw), 0.0, math.sin(a_yaw)],\n [0.0, 1.0, 0.0],\n [-math.sin(a_yaw), 0.0, math.cos(a_yaw)]])\n cam_to_vrm = lambda u: F3 @ (Ry_inv @ (np.asarray(u, float) / np.linalg.norm(u)))\n out_g = cam_to_vrm([0.50, 0.05, 0.86])\n up_g = cam_to_vrm([-0.05, 0.99, -0.03])\n up_g -= out_g * (up_g @ out_g)\n up_g /= np.linalg.norm(up_g)\n fw_g = np.cross(out_g, up_g)\n centre_g = Eg * 0.25 + Hg * 0.75 + out_g * 0.205 + fw_g * 0.028\n T_g2r = fit_probe.world[\"J_Bip_L_LowerArm\"] @ np.linalg.inv(Mg)\n R_g2r = T_g2r[:3, :3] / np.linalg.norm(T_g2r[:3, :3], axis=0)\n\n body_p0 = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"body\"][0]\n face_p0 = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"face\"][0]\n\n os.makedirs(CACHE_DIR, exist_ok=True)\n in_npz = os.path.join(CACHE_DIR, \"valen_bl_in.npz\")\n out_npz = os.path.join(CACHE_DIR, \"valen_bl_out.npz\")\n np.savez(\n in_npz,\n body_pos=body_p0[\"pos\"],\n body_tri=body_p0[\"tri\"],\n face_pos=face_p0[\"pos\"],\n face_tri=face_p0[\"tri\"],\n bones=fit_probe.bone,\n landmarks=lm_init,\n guard_info=dict(\n fist_R=fist_R,\n fwd_R=fwd_R,\n side_R=side_R,\n flat_R=flat_R,\n shield_centre=(T_g2r @ np.append(centre_g, 1.0))[:3],\n shield_out=R_g2r @ out_g,\n shield_up=R_g2r @ up_g,\n ),\n )\n\n t_bl0 = time.time()\n res = subprocess.run(\n [\"blender\", \"-b\", \"--factory-startup\", \"--python\", BLENDER_SCRIPT, \"--\", in_npz, out_npz, \"valen\"],\n capture_output=True,\n text=True,\n )\n if res.returncode != 0:\n raise RuntimeError(f\"Blender Valen sculpt failed:\\n{res.stdout[-1500:]}\\n{res.stderr[-1500:]}\")\n timings[\"blender_valen_s\"] = round(time.time() - t_bl0, 2)\n\n bl_data = np.load(out_npz, allow_pickle=True)\n sc_body_pos = bl_data[\"body_pos\"].astype(np.float64)\n sc_body_nrm = bl_data[\"body_nrm\"].astype(np.float64)\n sc_face_pos = bl_data[\"face_pos\"].astype(np.float64)\n sc_face_nrm = bl_data[\"face_nrm\"].astype(np.float64)\n bl_pieces = bl_data[\"pieces\"]\n\n def valen_costume(fit):\n # Update Fit's body surface to our Blender-resculpted body first!\n fit.pos = sc_body_pos.copy()\n pcs = []\n # Articulated dark-leather finger gloves wrapped onto resculpted hands\n gloves = O.wrap(\n fit, \"gloves\", \"glove\", (\"Hand\", \"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\"),\n offset=0.0028, min_w=0.3, smooth=4\n )\n if gloves is not None:\n gloves[\"group\"] = \"gloves\"\n pcs.append(gloves)\n\n for (nm, rl, p_arr, n_arr, t_arr, btag, grp) in bl_pieces:\n pcs.append(bind_blender_piece(fit, nm, rl, p_arr, n_arr, t_arr, btag, grp))\n\n # Flowing two-sided battle cloak (royal indigo outside, imperial crimson lining inside!)\n cape_under = merge_surfaces(\n *[(q[\"pos\"], q[\"tri\"]) for q in pcs if q.get(\"group\") in (\"plate\", \"doublet\", \"collar\")\n and not q[\"material\"].startswith(\"OUTFIT_pauldron\")],\n (fit.pos, fit.tri),\n )\n cape_pc, _ = O.cape(\n fit, \"cape\", \"cape\", cape_under, length=0.98, phi=0.46, seg=44, rows=18,\n top_clear=0.016, clear=(0.024, 0.062)\n )\n cape_pc[\"group\"] = \"cape\"\n pcs.append(cape_pc)\n return pcs\n\n p = vp.Portrait(\n vrm_path,\n morphs=morphs,\n pose=vp.BUST_POSE,\n ref_pose=vp.BUST_POSE,\n shape=shape,\n costume=valen_costume,\n )\n\n # 1. Strip ALL stock VRoid hair primitives completely (zero VRoid hair cards remain!)\n keep_idx = [k for k, pr in enumerate(p.prims) if \"_HAIR\" not in pr[\"material\"]]\n p.prims = [p.prims[k] for k in keep_idx]\n p.roles = [p.roles[k] for k in keep_idx]\n\n # 2. Apply Blender 5.2 sculpted head/body positions, mature anime face sculpt, and DATA_TRANSFER normals!\n for pr, rl in zip(p.prims, p.roles):\n if rl == \"body\" and len(pr[\"pos\"]) == len(sc_body_pos):\n pr[\"pos\"] = sc_body_pos.copy()\n pr[\"nrm\"] = sc_body_nrm.copy()\n elif rl in (\"face\", \"mouth\", \"brow\", \"line\", \"white\", \"iris\", \"highlight\") and len(pr[\"pos\"]) == len(sc_face_pos):\n pr[\"pos\"] = sc_face_pos.copy()\n if rl == \"face\":\n pr[\"nrm\"] = sc_face_nrm.copy()\n\n # 3. Paint custom sapphire-cerulean anime iris + jewel catchlight + authored UV/vertex face shadow bias!\n t_tex0 = time.time()\n lm_sculpted = vp.landmarks(p.prims, p.roles)\n for pr, rl in zip(p.prims, p.roles):\n if rl == \"face\":\n pr[\"plate\"] = bake_face_shadow_bias(pr[\"pos\"], lm_sculpted)\n elif rl == \"iris\":\n orig = p.v.material_texture(pr[\"mi\"])\n if orig is not None:\n pr[\"custom_tex\"] = paint_anime_iris_rgba(orig, scheme=\"sapphire\")\n pr[\"full_color_tex\"] = True\n elif rl == \"highlight\":\n orig = p.v.material_texture(pr[\"mi\"])\n if orig is not None:\n pr[\"custom_tex\"] = paint_anime_highlight_rgba(orig)\n timings[\"valen_tex_and_mask_s\"] = round(time.time() - t_tex0, 2)\n\n valen_colors = {\n \"r\": \"#15254a\", \"s\": \"#3264b0\", \"t\": \"#8ad4ff\",\n \"A\": \"#58483c\", \"o\": \"#22181a\",\n }\n valen_paint = {\n \"skin\": \"#f7dfd3\",\n \"hair\": \"#e3d3ba\", # Pale champagne-platinum Valkyrie locks\n \"signature\": \"#1f325c\", # Royal midnight-indigo surcoat, collar, shield, sleeves\n \"cape\": {\"kind\": \"cloth\", \"base\": \"#1f325c\", \"lining\": \"#8e1e2e\"}, # Indigo outer + crimson inner lining!\n \"doublet\": \"#222534\",\n \"heraldry\": \"#ece6d8\", # Luminous warm ivory pleated under-kirtle\n \"steel\": \"#c2cad8\", # Fluted mirror-bright gothic steel\n \"gold\": \"#d4a64a\", # Burnished antique gold filigree & crests\n \"leather\": \"#4e3122\",\n \"glove\": \"#36231b\",\n \"boot\": \"#301f18\",\n \"wood\": \"#6b482e\",\n }\n p.paint = dict(valen_paint)\n pal = dict(vp.PALETTE, **valen_colors)\n\n info = export_glb.scene_info(p, pal)\n # Propagate two-sided cape lining into scene_info paint metadata\n info[\"paint\"][\"cape\"] = {\"kind\": \"cloth\", \"base\": \"#1f325c\", \"lining\": \"#8e1e2e\"}\n\n # Export standalone rigged multi-clip GLB to ~/out/valen_finished.glb!\n t_exp0 = time.time()\n os.makedirs(\"~/out\", exist_ok=True)\n standalone_glb = \"~/out/valen_finished.glb\"\n glb_bytes = export_glb.export_skinned(\n p,\n pal,\n standalone_glb,\n clips=clips,\n max_tex=1024,\n extras=info,\n step_clips=(\"idle_breath_12fps\", \"strike_combo_12fps\"),\n )\n os.chmod(standalone_glb, 0o644)\n timings[\"export_glb_s\"] = round(time.time() - t_exp0, 2)\n timings[\"glb_size_bytes\"] = int(glb_bytes)\n\n # Also write scene copy for review/out/slice_after\n os.makedirs(ADV_OUT_DIR, exist_ok=True)\n slice_glb = os.path.join(ADV_OUT_DIR, \"valen.glb\")\n shutil.copyfile(standalone_glb, slice_glb)\n bs.wrap_glb_json(slice_glb)\n # Also copy raw valen_finished.glb into ADV_OUT_DIR so ?glb=valen_finished.glb serves cleanly over localhost HTTP!\n shutil.copyfile(standalone_glb, os.path.join(ADV_OUT_DIR, \"valen_finished.glb\"))\n\n timings[\"valen_total_s\"] = round(time.time() - t_start, 2)\n return dict(\n name=\"valen\",\n label=\"Valen (Valkyrie Marshal)\",\n place={\"pos\": [-0.74, 0.0, 0.04], \"yaw\": 32.0},\n clip=\"battle_guard\",\n clip_t=0.0,\n wind=-3.2,\n info=info,\n ), p, clips\n\n\ndef build_korin_adversarial(timings):\n \"\"\"Upgrade Korin so zero VRoid hair cards remain anywhere in the After battle scene!\"\"\"\n t0 = time.time()\n vrm_path = bs.cached_cage_vrm(\"arm_m_strong\")\n v0 = vp.VRM(vrm_path)\n shape = {\n **vp.NEUTRAL,\n **G.shape(\"stocky\", \"veteran\", blush=0.0, face_normals=0.0, hair_normals=0.0, shadow_cards=0.0),\n }\n shape[\"arm_out\"] = bs.arm_room(v0, shape)\n clips = {\"idle\": bs.housecarl_pose(v0, shape)}\n\n morphs = {\"Fcl_BRW_Angry\": 0.48, \"Fcl_EYE_Angry\": 0.22}\n pose_ref = vp.bone_pose(v0, shape, vp.BUST_POSE)\n raw_prims = v0.primitives(morphs, pose_ref)\n raw_roles = [vp.role_of(pr[\"material\"]) for pr in raw_prims]\n lm_k = vp.landmarks(raw_prims, raw_roles)\n fit_k = O.Fit(v0, pose_ref, raw_prims, raw_roles)\n bp_k = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"body\"][0]\n fp_k = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"face\"][0]\n\n kin_npz = os.path.join(CACHE_DIR, \"korin_bl_in.npz\")\n kout_npz = os.path.join(CACHE_DIR, \"korin_bl_out.npz\")\n np.savez(\n kin_npz,\n body_pos=bp_k[\"pos\"],\n body_tri=bp_k[\"tri\"],\n face_pos=fp_k[\"pos\"],\n face_tri=fp_k[\"tri\"],\n bones=fit_k.bone,\n landmarks=lm_k,\n )\n t_bl0 = time.time()\n res = subprocess.run(\n [\"blender\", \"-b\", \"--factory-startup\", \"--python\", BLENDER_SCRIPT, \"--\", kin_npz, kout_npz, \"korin\"],\n capture_output=True,\n text=True,\n )\n if res.returncode != 0:\n raise RuntimeError(f\"Blender Korin build failed:\\n{res.stderr[-1500:]}\")\n timings[\"blender_korin_s\"] = round(time.time() - t_bl0, 2)\n k_pieces = np.load(kout_npz, allow_pickle=True)[\"pieces\"]\n\n def korin_costume(fit):\n pcs = bs.heavy_housecarl(fit)\n # Drop old scalp_cap since Blender wolf-cut hair includes its own sculpted cranial shell\n pcs = [q for q in pcs if q[\"material\"] != \"OUTFIT_scalp_cap\"]\n for (nm, rl, p_arr, n_arr, t_arr, btag, grp) in k_pieces:\n pcs.append(bind_blender_piece(fit, nm, rl, p_arr, n_arr, t_arr, btag, grp))\n return pcs\n\n p = vp.Portrait(\n vrm_path,\n morphs=morphs,\n pose=vp.BUST_POSE,\n ref_pose=vp.BUST_POSE,\n shape=shape,\n costume=korin_costume,\n )\n # Strip stock VRoid bowl-cut hair completely!\n keep_idx = [k for k, pr in enumerate(p.prims) if \"_HAIR\" not in pr[\"material\"]]\n p.prims = [p.prims[k] for k in keep_idx]\n p.roles = [p.roles[k] for k in keep_idx]\n\n bs.apply_forward_face_normals(p, forward=0.10, pull=0.45)\n lm_k_now = vp.landmarks(p.prims, p.roles)\n for pr, rl in zip(p.prims, p.roles):\n if rl == \"face\":\n pr[\"plate\"] = bake_face_shadow_bias(pr[\"pos\"], lm_k_now)\n elif rl == \"iris\":\n orig = p.v.material_texture(pr[\"mi\"])\n if orig is not None:\n pr[\"custom_tex\"] = paint_anime_iris_rgba(orig, scheme=\"amber\")\n pr[\"full_color_tex\"] = True\n elif rl == \"highlight\":\n orig = p.v.material_texture(pr[\"mi\"])\n if orig is not None:\n pr[\"custom_tex\"] = paint_anime_highlight_rgba(orig)\n\n korin_colors = {\n \"r\": \"#2c1d14\", \"s\": \"#7a4e26\", \"t\": \"#c49052\",\n \"A\": \"#181920\", \"o\": \"#1e1412\",\n }\n korin_paint = {\n \"skin\": \"#b87a54\",\n \"hair\": \"#252730\",\n \"fur\": {\"kind\": \"leather\", \"base\": \"#3a312c\"},\n \"signature\": \"#7a252c\",\n \"padding\": \"#cec2ac\",\n \"mail\": {\"kind\": \"steel\", \"base\": \"#7d8492\"},\n \"doublet\": \"#363b37\",\n \"heraldry\": \"#ddd8cc\",\n \"steel\": \"#a0a8b6\",\n \"gold\": \"#b38b3d\",\n \"leather\": \"#583827\",\n \"glove\": \"#452d20\",\n \"boot\": \"#38251c\",\n \"wood\": \"#68462c\",\n }\n p.paint = dict(korin_paint)\n pal = dict(vp.PALETTE, **korin_colors)\n glb_path = os.path.join(ADV_OUT_DIR, \"korin.glb\")\n export_glb.export_skinned(p, pal, glb_path, clips=clips, max_tex=1024)\n bs.wrap_glb_json(glb_path)\n\n info = export_glb.scene_info(p, pal)\n info[\"roles\"][\"fur\"] = info[\"roles\"][\"leather\"]\n info[\"paint\"][\"fur\"] = {\"kind\": \"leather\", \"base\": \"#3a312c\"}\n timings[\"korin_total_s\"] = round(time.time() - t0, 2)\n return dict(\n name=\"korin\",\n label=\"Korin (Northern Housecarl)\",\n place={\"pos\": [0.76, 0.0, -0.02], \"yaw\": -33.0},\n clip=\"idle\",\n clip_t=0.0,\n wind=2.8,\n info=info,\n )\n\n\n# ---------------------------------------------------------------------------\n# 5. Shoot Headless WebGL Renders (After Battle Frame + Flattice Perspective)\n# ---------------------------------------------------------------------------\ndef shoot_url(query_str, out_png, timeout_s=480):\n \"\"\"Serve ADV_OUT_DIR over an ephemeral localhost port and capture dataURL via headless Chromium.\"\"\"\n import re\n import socket\n\n with socket.socket() as s:\n s.bind((\"127.0.0.1\", 0))\n port = s.getsockname()[1]\n\n srv = subprocess.Popen(\n [sys.executable, \"-m\", \"http.server\", str(port), \"-b\", \"127.0.0.1\"],\n cwd=ADV_OUT_DIR,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n )\n prof = os.path.join(CACHE_DIR, \"chrome_prof\")\n os.makedirs(prof, exist_ok=True)\n url = f\"http://127.0.0.1:{port}/index.html?{query_str}\"\n try:\n cmd = [\n \"/snap/bin/chromium\",\n \"--headless=new\",\n \"--no-sandbox\",\n \"--disable-gpu\",\n \"--use-gl=angle\",\n \"--use-angle=swiftshader\",\n \"--enable-unsafe-swiftshader\",\n f\"--user-data-dir={prof}\",\n \"--window-size=1920,1080\",\n \"--virtual-time-budget=90000\",\n \"--dump-dom\",\n url,\n ]\n res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s)\n m = re.search(r'id=\"sheetOut\">([redacted: data-URI prefix][A-Za-z0-9+/=]+)</pre>', res.stdout)\n if not m:\n raise RuntimeError(f\"Render failed for {url}:\\nSTDOUT:{res.stdout[-800:]}\\nSTDERR:{res.stderr[-800:]}\")\n raw_png = base64.b64decode(m.group(1).split(\",\", 1)[1])\n with open(out_png, \"wb\") as f:\n f.write(raw_png)\n os.chmod(out_png, 0o644)\n finally:\n srv.terminate()\n srv.wait()\n\n\ndef compose_flattice_diptych(off_png, on_png, out_png):\n \"\"\"Join the 24 mm Perspective Flattice Off vs Flattice On renders into a clean 1920x960 comparison plate.\"\"\"\n im_off = Image.open(off_png).convert(\"RGB\")\n im_on = Image.open(on_png).convert(\"RGB\")\n W, H = im_off.size\n out = Image.new(\"RGB\", (W * 2, H), (28, 27, 34))\n out.paste(im_off, (0, 0))\n out.paste(im_on, (W, 0))\n\n draw = ImageDraw.Draw(out)\n # Subtle 2 px center divider\n draw.rectangle([W - 1, 0, W + 1, H], fill=(212, 166, 74))\n\n try:\n font_b = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf\", 22)\n font_s = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 16)\n except Exception:\n font_b = font_s = ImageFont.load_default()\n\n badges = [\n (28, 24, \"24 mm Perspective Camera | Flattice OFF (flat = 0.00)\",\n \"Exported valen_finished.glb: sword & shield foreshorten; close lens bulges nose & jaw\"),\n (W + 28, 24, \"24 mm Perspective Camera | Flattice ON (flat = 0.85)\",\n \"Same 24 mm lens + view-space head squash: 3D foreshortened gear, distortion-free 3/4 anime face\"),\n ]\n for bx, by, title, sub in badges:\n draw.rounded_rectangle([bx, by, bx + 890, by + 68], radius=8, fill=(22, 24, 34), outline=(196, 154, 69), width=2)\n draw.text((bx + 16, by + 11), title, fill=(244, 238, 226), font=font_b)\n draw.text((bx + 16, by + 40), sub, fill=(192, 198, 212), font=font_s)\n\n out.save(out_png, \"PNG\", optimize=True)\n os.chmod(out_png, 0o644)\n\n\ndef verify_standalone_glb_in_blender(glb_path, timings):\n \"\"\"Import ~/out/valen_finished.glb in fresh headless Blender 5.2 to audit meshes, bones, and clips.\"\"\"\n t0 = time.time()\n expr = (\n \"import bpy, json; bpy.ops.wm.read_factory_settings(use_empty=True); \"\n f\"bpy.ops.import_scene.gltf(filepath={glb_path!r}); \"\n \"meshes=[o for o in bpy.data.objects if o.type=='MESH']; \"\n \"arms=[o for o in bpy.data.objects if o.type=='ARMATURE']; \"\n \"tris=sum(len(o.data.polygons) for o in meshes); \"\n \"verts=sum(len(o.data.vertices) for o in meshes); \"\n \"bones=len(arms[0].data.bones) if arms else 0; \"\n \"acts=[a.name for a in bpy.data.actions]; \"\n \"mats=len(bpy.data.materials); \"\n \"imgs=len(bpy.data.images); \"\n \"print('GLB_AUDIT:' + json.dumps(dict(meshes=len(meshes), verts=verts, tris=tris, bones=bones, actions=acts, materials=mats, images=imgs)))\"\n )\n res = subprocess.run([\"blender\", \"-b\", \"--factory-startup\", \"--python-expr\", expr], capture_output=True, text=True)\n if res.returncode != 0:\n raise RuntimeError(f\"Blender GLB audit failed:\\n{res.stderr[-1500:]}\")\n audit = {}\n for line in res.stdout.splitlines():\n if line.startswith(\"GLB_AUDIT:\"):\n audit = json.loads(line.split(\"GLB_AUDIT:\", 1)[1])\n timings[\"glb_audit_s\"] = round(time.time() - t0, 2)\n timings[\"glb_audit\"] = audit\n return audit\n\n\ndef main():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"--after-png\", default=\"~/out/battle_frame_after.png\")\n ap.add_argument(\"--flattice-png\", default=\"~/out/valen_flattice_persp.png\")\n args = ap.parse_args()\n\n t_all = time.time()\n timings = {}\n os.makedirs(ADV_OUT_DIR, exist_ok=True)\n with open(bs.SLICE_HTML) as f:\n html = f.read()\n with open(os.path.join(ADV_OUT_DIR, \"index.html\"), \"w\") as f:\n f.write(html)\n three_link = os.path.join(ADV_OUT_DIR, \"three\")\n if not os.path.exists(three_link):\n os.symlink(bs.LOCAL_THREE, three_link)\n\n print(\"1/5 Building adversarial Valen (Blender 5.2 sculpt, 3D lock hair, gothic-anime armour, GLB)...\")\n valen_unit, _, _ = build_valen_adversarial(timings)\n\n print(\"2/5 Building upgraded Korin (Blender 5.2 wolf-cut hair, northern pauldrons & fur mantle)...\")\n korin_unit = build_korin_adversarial(timings)\n\n # Terrain\n world_holder = type(\"WorldPortrait\", (), {})()\n world_holder.prims = terrain.plains(width=4.8, depth=2.1, thick=0.30, seed=5, tufts=34, stones=7)\n world_holder.roles = [pr[\"role\"] for pr in world_holder.prims]\n world_holder.tex = {}\n plains_path = os.path.join(ADV_OUT_DIR, \"plains.glb\")\n export_glb.export(world_holder, vp.PALETTE, plains_path, only_world=True)\n bs.wrap_glb_json(plains_path)\n\n scene_doc = dict(\n camera=dict(target=[0.02, 0.90, 0.0], height=2.16, pitch=8.5),\n key=[-0.62, 0.48, 0.62],\n grade=dict(ambient=[0.86, 0.88, 0.96], key=[1.04, 1.00, 0.94], rim=[0.28, 0.25, 0.20]),\n characters=[valen_unit, korin_unit],\n )\n with open(os.path.join(ADV_OUT_DIR, \"scene.json\"), \"w\") as f:\n json.dump(scene_doc, f)\n\n print(\"3/5 Auditing ~/out/valen_finished.glb in headless Blender 5.2...\")\n audit = verify_standalone_glb_in_blender(\"~/out/valen_finished.glb\", timings)\n print(\" GLB Audit:\", audit)\n\n print(\"4/5 Shooting After battle visual (~/out/battle_frame_after.png, 1920x1080 @ ss=2)...\")\n t_r1 = time.time()\n shoot_url(\"shot=1&w=1920&h=1080&ss=2\", args.after_png)\n timings[\"render_after_battle_s\"] = round(time.time() - t_r1, 2)\n\n print(\"5/5 Shooting 24 mm Perspective + Flattice showcase directly from valen_finished.glb...\")\n t_r2 = time.time()\n off_png = os.path.join(CACHE_DIR, \"flattice_off.png\")\n on_png = os.path.join(CACHE_DIR, \"flattice_on.png\")\n q_base = \"shot=1&glb=valen_finished.glb&clip=battle_guard&yaw=34&target=-0.03,1.38,0.04&height=0.68&pitch=5&w=960&h=960&ss=2&lens=24\"\n shoot_url(f\"{q_base}&flat=0\", off_png)\n shoot_url(f\"{q_base}&flat=0.85\", on_png)\n compose_flattice_diptych(off_png, on_png, args.flattice_png)\n timings[\"render_flattice_persp_s\"] = round(time.time() - t_r2, 2)\n\n timings[\"pipeline_total_s\"] = round(time.time() - t_all, 2)\n with open(os.path.join(CACHE_DIR, \"adversarial_timings.json\"), \"w\") as f:\n json.dump(timings, f, indent=2)\n print(\"DONE! Timings:\", json.dumps(timings, indent=2))\n\n\nif __name__ == \"__main__\":\n main()\n","Overwrite":true,"Path":"~/work/lowmarch/tools/build_adversarial.py"}

    input

    {
      "Content": "\"\"\"Adversarial Pass builder: Blender 5.2 body/face sculpt, 3D lock hair, bespoke gothic-anime armour,\ncustom painted anime eyes + UV face shadow bias, multi-clip rigged GLB export, and Flattice perspective shot.\n\nOutputs:\n  - ~/out/valen_finished.glb      (standalone rigged + multi-clip animated 3D character model)\n  - ~/out/battle_frame_after.png  (1920x1080 2x-supersampled After battle visual)\n  - ~/out/valen_flattice_persp.png (1920x960 2x-SS 24 mm perspective camera: Flattice Off vs On)\n\"\"\"\nimport argparse\nimport base64\nimport json\nimport math\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\n\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\n\nHERE = os.path.dirname(os.path.abspath(__file__))\nROOT = os.path.dirname(HERE)\nsys.path[:0] = [HERE, os.path.join(ROOT, \"art\", \"cast\")]\n\nimport battle_slice as bs  # noqa: E402\nimport checks  # noqa: E402\nimport duel  # noqa: E402\nimport export_glb  # noqa: E402\nimport gear as G  # noqa: E402\nimport outfit as O  # noqa: E402\nimport poses as P  # noqa: E402\nimport terrain  # noqa: E402\nimport vroid_portrait as vp  # noqa: E402\nfrom fitting import merge_surfaces  # noqa: E402\nfrom plates import stiffen  # noqa: E402\nfrom rig import Rig, grip_points  # noqa: E402\n\nADV_OUT_DIR = os.path.join(ROOT, \"review\", \"out\", \"slice_after\")\nCACHE_DIR = os.path.expanduser(\"~/.cache/lowmarch_adv\")\nBLENDER_SCRIPT = os.path.join(HERE, \"blender_sculpt_cast.py\")\n\n\n# ---------------------------------------------------------------------------\n# 1. Custom High-Resolution Anime Eye Textures & Authored Face Shadow Bias\n# ---------------------------------------------------------------------------\ndef paint_anime_iris_rgba(orig_rgba, scheme=\"sapphire\"):\n    \"\"\"Paint a luminous studio-anime iris RGBA texture inside the exact alpha footprint of orig_rgba.\"\"\"\n    H, W = orig_rgba.shape[:2]\n    alpha = orig_rgba[..., 3].astype(np.float32) / 255.0\n    out = np.zeros((H, W, 4), dtype=np.uint8)\n    ys, xs = np.nonzero(alpha > 0.15)\n    if not len(xs):\n        return orig_rgba.copy()\n\n    # Handle single or twin UV islands cleanly via connected components or bounding box\n    from scipy.ndimage import label\n    lab, n_comp = label(alpha > 0.15)\n    rgb = np.zeros((H, W, 3), dtype=np.float32)\n\n    if scheme == \"sapphire\":\n        c_limbal = np.array([0.07, 0.11, 0.24])      # deep midnight navy limbal ring\n        c_upper = np.array([0.11, 0.19, 0.42])       # rich indigo upper lash shadow\n        c_mid = np.array([0.22, 0.44, 0.80])         # royal sapphire mid-iris\n        c_lower = np.array([0.52, 0.84, 0.99])       # radiant cerulean-cyan lower arc\n        c_pupil = np.array([0.05, 0.08, 0.20])       # deep velvet pupil core\n        c_ring = np.array([0.74, 0.93, 1.00])        # crystalline inner corona\n    else:\n        c_limbal = np.array([0.13, 0.08, 0.05])\n        c_upper = np.array([0.28, 0.16, 0.08])\n        c_mid = np.array([0.62, 0.38, 0.15])\n        c_lower = np.array([0.95, 0.72, 0.30])\n        c_pupil = np.array([0.09, 0.06, 0.04])\n        c_ring = np.array([1.00, 0.86, 0.48])\n\n    for cid in range(1, n_comp + 1):\n        cy_i, cx_i = np.nonzero(lab == cid)\n        if len(cx_i) < 20:\n            continue\n        x0, x1 = cx_i.min(), cx_i.max()\n        y0, y1 = cy_i.min(), cy_i.max()\n        cx = 0.5 * (x0 + x1)\n        cy = 0.5 * (y0 + y1)\n        rx = max(1.0, 0.5 * (x1 - x0))\n        ry = max(1.0, 0.5 * (y1 - y0))\n\n        yy, xx = np.mgrid[y0:y1 + 1, x0:x1 + 1]\n        nx = (xx - cx) / rx\n        ny = (yy - cy) / ry  # Note: in glTF image space y=0 is top, y=H is bottom!\n        r = np.sqrt(nx * nx + ny * ny)\n        ang = np.arctan2(ny, nx)\n\n        # Vertical anime gradient: top (ny < 0) in deep shadow, bottom (ny > 0) glowing!\n        v_grad = np.clip((ny + 0.55) / 1.35, 0.0, 1.0)\n        base = np.where(v_grad[..., None] < 0.48,\n                        c_upper + (c_mid - c_upper) * (v_grad[..., None] / 0.48),\n                        c_mid + (c_lower - c_mid) * ((v_grad[..., None] - 0.48) / 0.52))\n\n        # Radial crystalline striations\n        rays = 0.5 + 0.5 * np.sin(ang * 28.0 + 0.4 * np.sin(ang * 7.0))\n        ray_mask = np.clip((r - 0.26) / 0.22, 0.0, 1.0) * np.clip((0.86 - r) / 0.16, 0.0, 1.0)\n        base = base + (c_ring - base) * (0.28 * rays * ray_mask * (0.35 + 0.65 * v_grad))[..., None]\n\n        # Glowing lower crescent bounce arc\n        crescent = np.exp(-((r - 0.64) / 0.13) ** 2) * np.clip((ny - 0.10) / 0.65, 0.0, 1.0) ** 1.3\n        base = base + (c_ring - base) * (0.52 * crescent)[..., None]\n\n        # Crisp dark pupil with soft corona rim\n        pupil_w = 1.0 - np.clip((r - 0.25) / 0.09, 0.0, 1.0)\n        corona = np.exp(-((r - 0.31) / 0.055) ** 2) * (0.45 + 0.55 * v_grad)\n        base = base + (c_ring - base) * (0.40 * corona)[..., None]\n        base = base * (1.0 - pupil_w[..., None]) + c_pupil * pupil_w[..., None]\n\n        # Crisp outer limbal ring + upper lash cast shadow band across top 28% of iris\n        limbal = np.clip((r - 0.78) / 0.16, 0.0, 1.0)\n        lash_sh = np.clip((-ny - 0.22) / 0.48, 0.0, 1.0) * 0.62\n        base = base * (1.0 - lash_sh[..., None]) + (c_limbal * 0.85) * lash_sh[..., None]\n        base = base * (1.0 - limbal[..., None]) + c_limbal * limbal[..., None]\n\n        sub_m = lab[y0:y1 + 1, x0:x1 + 1] == cid\n        rgb[y0:y1 + 1, x0:x1 + 1][sub_m] = np.clip(base[sub_m], 0.0, 1.0)\n\n    out[..., :3] = np.round(rgb * 255.0).astype(np.uint8)\n    out[..., 3] = orig_rgba[..., 3]\n    return out\n\n\ndef paint_anime_highlight_rgba(orig_rgba):\n    \"\"\"Crisp studio-anime primary upper-left catchlight + jewel lower-right pin catchlight.\"\"\"\n    out = orig_rgba.copy()\n    # Boost existing highlight opacity & brightness to pure crisp white so catchlights pop cleanly\n    m = out[..., 3] > 32\n    out[m, :3] = 255\n    out[m, 3] = np.clip(out[m, 3].astype(np.int32) * 2, 0, 255).astype(np.uint8)\n    return out\n\n\ndef bake_face_shadow_bias(face_pos, lm):\n    \"\"\"Authored per-vertex anime face shadow bias stored in _PLATE = [2.0, bias, 0.0, 0.0].\n    Carves crisp anime nose-tip diamond shadow, orbital brow depth, under-lip crease, and lit malar cheek triangle!\n    \"\"\"\n    n = len(face_pos)\n    plate = np.zeros((n, 4), dtype=np.float32)\n    plate[:, 0] = 2.0  # Sentinel > 1.5 telling PAINT_FS this is a face shadow bias attribute, not gold armour trim\n\n    x = face_pos[:, 0]\n    y = face_pos[:, 1]\n    z = face_pos[:, 2]\n    eye_y = float(lm[\"eye_y\"])\n    eye_x = abs(float(lm[\"eyeR\"][0]))\n    nose = lm[\"nose\"]\n    mouth = lm[\"mouth\"]\n\n    # 1. Crisp anime under-nose shadow triangle (just below nose tip, slight negative bias)\n    nose_under = (\n        np.exp(-((y - (nose[1] - 0.0085)) / 0.0075) ** 2)\n        * np.exp(-(x / 0.0095) ** 2)\n        * np.clip((-z - (-nose[2] - 0.018)) / 0.015, 0.0, 1.0)\n    )\n    # 2. Upper orbital / under-brow socket depth\n    orbital = (\n        np.exp(-((y - (eye_y + 0.011)) / 0.0075) ** 2)\n        * np.exp(-((np.abs(x) - eye_x) / 0.019) ** 2)\n    )\n    # 3. Delicate mentolabial crease under the lower lip\n    lip_under = (\n        np.exp(-((y - (mouth[1] - 0.009)) / 0.0055) ** 2)\n        * np.exp(-(x / 0.012) ** 2)\n    )\n    # 4. Positive Rembrandt malar cheek prominence + nose bridge highlight so 3/4 lit planes never muddy!\n    cheek_lit = (\n        np.exp(-((y - (eye_y - 0.024)) / 0.018) ** 2)\n        * np.exp(-((np.abs(x) - (eye_x + 0.006)) / 0.020) ** 2)\n    )\n    bridge_lit = (\n        np.exp(-((y - (nose[1] + 0.014)) / 0.014) ** 2)\n        * np.exp(-(x / 0.0055) ** 2)\n    )\n\n    bias = (-0.22 * nose_under - 0.11 * orbital - 0.12 * lip_under\n            + 0.095 * cheek_lit + 0.085 * bridge_lit)\n    plate[:, 1] = np.clip(bias, -0.35, 0.25).astype(np.float32)\n    return plate\n\n\n# ---------------------------------------------------------------------------\n# 2. Multi-Clip Skeletal Combat & Stepped 12 fps Animations for Valen\n# ---------------------------------------------------------------------------\ndef build_valen_clips(vrm, shape):\n    \"\"\"Build 4 skeletal clips for valen_finished.glb:\n      - battle_guard: poised 3/4 sword-and-shield vanguard stance (used in battle frame & perspective shot)\n      - idle_breath_12fps: 2.0 s stepped 12 fps tactical breathing & sword-poise loop (25 stepped keys)\n      - strike_combo_12fps: 1.5 s stepped 12 fps anticipation -> shield bash -> sword lunge -> hit-stop -> recovery\n      - bust_ref: clean reference inspection stance\n    \"\"\"\n    rig = Rig(vrm, shape, ortho=True)\n    body = checks.Body(vrm, shape)\n    f = {s: g[\"point\"] for s, g in grip_points(vrm, shape, P.BUST).items()}\n    ref = dict(ref_pose=P.BUST, fist_R=f[\"R\"], fist_L=f[\"L\"])\n    foot = {s: rig.pos(P.BATTLE_IDLE, f\"J_Bip_{s}_Foot\") for s in \"LR\"}\n\n    def make_guard(hip_dy=-0.058, torso_twist=-11.0, sword_lift=0.0, shield_brace=0.0, lunge_z=0.0):\n        base = P.merge(P.BATTLE_IDLE, P.fist(\"L\", curl=(74, 86, 62), thumb=38), {\n            \"J_Bip_C_Hips\": P.move(0, hip_dy, -0.02 + lunge_z, P.rot((0, 1, 0), torso_twist) @ P.rot((1, 0, 0), -5.0)),\n            \"J_Bip_C_Spine\": P.rot((0, 1, 0), torso_twist * 0.75) @ P.rot((1, 0, 0), -3.2),\n            \"J_Bip_C_Chest\": P.rot((0, 1, 0), torso_twist * 0.55) @ P.rot((1, 0, 0), -2.2),\n            \"J_Bip_C_Neck\": P.rot((0, 1, 0), -torso_twist * 1.05) @ P.rot((1, 0, 0), 3.2),\n            \"J_Bip_C_Head\": P.rot((0, 1, 0), -torso_twist * 0.95) @ P.rot((1, 0, 0), 2.5),\n        })\n        pose = rig.leg_ik(base, \"L\", foot[\"L\"] + np.array([-0.065, 0.0, -0.18]), pole=(0, 0, -1))\n        pose = rig.leg_ik(pose, \"R\", foot[\"R\"] + np.array([0.075, 0.0, 0.15]), pole=(0, -0.2, -1))\n\n        sh_r = rig.pos(pose, \"J_Bip_R_UpperArm\")\n        fist_r = sh_r + np.array([0.10, -0.33 + sword_lift, -0.21 + lunge_z * 1.6])\n        blade_dir = np.array([-0.22, 0.52 + sword_lift * 0.8, -0.82 + lunge_z * 1.2])\n        blade_dir /= np.linalg.norm(blade_dir)\n        pose = duel.clear_grip(rig, body, pose, \"R\", ref, fist_r, blade_dir, (0.72, -0.88, 0.35))\n\n        sh_l = rig.pos(pose, \"J_Bip_L_UpperArm\")\n        pose = rig.arm_ik(pose, \"L\", sh_l + np.array([-0.27, -0.21 + shield_brace, 0.05 - shield_brace * 0.6]),\n                          pole=(-0.6, -0.9, 0.5))\n        return pose\n\n    guard = make_guard()\n\n    # Stepped 12 fps idle loop (24 frames @ 1/12 s = 2.0 s)\n    idle_keys = []\n    for fr in range(25):\n        t = fr / 12.0\n        ph = 2.0 * math.pi * (fr / 24.0)\n        # Quantize phase on twos (classic anime 12 fps / 6s cadence!)\n        ph_q = 2.0 * math.pi * ((fr // 2) * 2 / 24.0)\n        p_fr = make_guard(\n            hip_dy=-0.058 + 0.007 * math.sin(ph_q),\n            torso_twist=-11.0 + 1.8 * math.sin(ph_q),\n            sword_lift=0.014 * math.sin(ph_q - 0.4),\n            shield_brace=0.008 * math.cos(ph_q),\n        )\n        idle_keys.append((round(t, 5), p_fr))\n\n    # Stepped 12 fps strike combo with explicit anticipation & 3-frame hit-stop!\n    strike_specs = [\n        (0, -0.058, -11.0, 0.00, 0.00, 0.00),     # Guard\n        (2, -0.078, -22.0, 0.08, 0.03, 0.04),     # Wind-up anticipation (coil back!)\n        (4, -0.084, -25.0, 0.11, 0.04, 0.05),     # Hold coiled apex (2 frames)\n        (5, -0.048, 16.0, -0.04, -0.02, -0.14),   # Explosive lunge snap!\n        (6, -0.044, 21.0, -0.06, -0.03, -0.18),   # Impact frame (HIT-STOP begins)\n        (9, -0.044, 21.0, -0.06, -0.03, -0.18),   # 3-frame anime hit-stop freeze!\n        (12, -0.064, 4.0, 0.02, 0.01, -0.06),     # Follow-through recovery\n        (15, -0.060, -7.0, 0.01, 0.00, -0.01),    # Settle into guard\n        (18, -0.058, -11.0, 0.00, 0.00, 0.00),    # Guard\n    ]\n    strike_keys = [\n        (round(fr / 12.0, 5), make_guard(hdy, tw, sl, sb, lz))\n        for (fr, hdy, tw, sl, sb, lz) in strike_specs\n    ]\n\n    bust_pose = P.merge(P.BUST, P.fist(\"R\"), P.fist(\"L\"))\n    return {\n        \"battle_guard\": [(0.0, guard), (1.0, guard)],\n        \"idle_breath_12fps\": idle_keys,\n        \"strike_combo_12fps\": strike_keys,\n        \"bust_ref\": [(0.0, bust_pose), (1.0, bust_pose)],\n    }\n\n\n# ---------------------------------------------------------------------------\n# 3. Bind Blender 5.2 Sculpted Pieces onto Lowmarch's Skeleton\n# ---------------------------------------------------------------------------\ndef bind_blender_piece(fit, nm, role, pos, nrm, tri, bind_tag, grp):\n    pc = dict(\n        mesh=\"outfit\",\n        material=f\"OUTFIT_{nm}\",\n        mi=-1,\n        role=role,\n        pos=pos.astype(np.float64),\n        nrm=nrm.astype(np.float64),\n        uv=np.zeros((len(pos), 2), dtype=np.float64),\n        tri=tri.astype(np.int32),\n        group=grp,\n    )\n    if bind_tag == \"head_rigid\":\n        fit.bind(pc, rigid=\"J_Bip_C_Head\")\n    elif bind_tag == \"ponytail_blend\":\n        fit.bind(pc, blend={\"J_Bip_C_Head\": 0.80, \"J_Bip_C_Neck\": 0.14, \"J_Bip_C_UpperChest\": 0.06})\n    elif bind_tag == \"torso_skin\":\n        fit.bind(pc, allow=(\"Spine\", \"Chest\", \"UpperChest\", \"Neck\", \"Hips\"), fallback=\"J_Bip_C_Chest\")\n    elif bind_tag == \"neck_blend\":\n        fit.bind(pc, blend={\"J_Bip_C_Neck\": 0.65, \"J_Bip_C_UpperChest\": 0.35})\n    elif bind_tag == \"uchest_blend\":\n        fit.bind(pc, rigid=\"J_Bip_C_UpperChest\")\n    elif bind_tag == \"torso_plate\":\n        fit.bind(pc, allow=(\"Spine\", \"Chest\", \"UpperChest\"), fallback=\"J_Bip_C_Chest\")\n        stiffen(pc, fit, \"J_Bip_C_Chest\", share=0.55)\n    elif bind_tag == \"hips_stiff\":\n        fit.bind(pc, rigid=\"J_Bip_C_Hips\")\n    elif bind_tag == \"skirt_stiff\":\n        if nm.startswith(\"tasset_\"):\n            side = \"R\" if \"_R_\" in nm else \"L\"\n            fit.bind(pc, blend={f\"J_Bip_{side}_UpperLeg\": 0.56, \"J_Bip_C_Hips\": 0.44})\n        else:\n            fit.bind(pc, allow=(\"Hips\", \"UpperLeg\"), fallback=\"J_Bip_C_Hips\")\n            stiffen(pc, fit, \"J_Bip_C_Hips\", share=0.46)\n    elif bind_tag.startswith(\"uarm_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, rigid=f\"J_Bip_{side}_UpperArm\")\n    elif bind_tag.startswith(\"pauldron_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, blend={f\"J_Bip_{side}_UpperArm\": 0.50, f\"J_Bip_{side}_Shoulder\": 0.32, \"J_Bip_C_UpperChest\": 0.18})\n    elif bind_tag.startswith(\"larm_\"):\n        if bind_tag == \"larm_rigid\":\n            fit.bind(pc, rigid=\"J_Bip_L_LowerArm\")\n        else:\n            side = bind_tag[-1]\n            fit.bind(pc, rigid=f\"J_Bip_{side}_LowerArm\")\n    elif bind_tag.startswith(\"hand_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, rigid=f\"J_Bip_{side}_Hand\")\n    elif bind_tag.startswith(\"leg_skin_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, allow=(\"Hips\", f\"{side}_UpperLeg\", f\"{side}_LowerLeg\", f\"{side}_Foot\"),\n                 fallback=f\"J_Bip_{side}_LowerLeg\")\n    elif bind_tag.startswith(\"uleg_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, rigid=f\"J_Bip_{side}_UpperLeg\")\n    elif bind_tag.startswith(\"lleg_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, rigid=f\"J_Bip_{side}_LowerLeg\")\n    elif bind_tag.startswith(\"foot_\"):\n        side = bind_tag[-1]\n        fit.bind(pc, allow=(f\"{side}_Foot\", f\"{side}_ToeBase\", f\"{side}_LowerLeg\"), fallback=f\"J_Bip_{side}_Foot\")\n    elif bind_tag == \"rhand_rigid\":\n        fit.bind(pc, rigid=\"J_Bip_R_Hand\")\n    else:\n        fit.bind(pc, rigid=\"J_Bip_C_Chest\")\n    return pc\n\n\n# ---------------------------------------------------------------------------\n# 4. Build Adversarial Valen & Upgraded Korin\n# ---------------------------------------------------------------------------\ndef build_valen_adversarial(timings):\n    t_start = time.time()\n    vrm_path = bs.cached_cage_vrm(\"arm_f_strong\")\n    v0 = vp.VRM(vrm_path)\n\n    # Heroic 7.85-head Valkyrie Marshal skeletal proportions\n    shape = {\n        **vp.NEUTRAL,\n        **G.shape(\n            \"athletic\",\n            \"bare\",\n            leg_len=1.075,\n            head=0.935,\n            torso=0.90,\n            chest=1.04,\n            shoulder_w=0.012,\n            curl=14,\n            blush=0.18,\n            face_normals=0.0,\n            hair_normals=0.0,\n            shadow_cards=0.0,\n        ),\n    }\n    shape[\"arm_out\"] = bs.arm_room(v0, shape)\n\n    t_clips0 = time.time()\n    clips = build_valen_clips(v0, shape)\n    timings[\"valen_clips_s\"] = round(time.time() - t_clips0, 2)\n\n    guard_pose = clips[\"battle_guard\"][0][1]\n    rig_guard = Rig(v0, shape, ortho=True)\n\n    # Prepare Blender 5.2 input NPZ from morph-applied BUST_POSE primitives\n    morphs = {\"Fcl_BRW_Angry\": 0.34, \"Fcl_EYE_Angry\": 0.16}\n    pose_ref = vp.bone_pose(v0, shape, vp.BUST_POSE)\n    raw_prims = v0.primitives(morphs, pose_ref)\n    raw_roles = [vp.role_of(pr[\"material\"]) for pr in raw_prims]\n    lm_init = vp.landmarks(raw_prims, raw_roles)\n    fit_probe = O.Fit(v0, pose_ref, raw_prims, raw_roles)\n    fit_probe.grip = grip_points(v0, shape, P.BUST)\n    fist_R, fwd_R, side_R, flat_R, _ = G._hand_frame(fit_probe, \"R\")\n\n    # Compute Aegis shield frame aligned upright in 3/4 guard, mapped back to BUST_POSE\n    names = v0.nodes_by_name()\n    Wg = rig_guard.world(guard_pose)\n    Mg = Wg[names[\"J_Bip_L_LowerArm\"]]\n    Eg, Hg = Mg[:3, 3], Wg[names[\"J_Bip_L_Hand\"]][:3, 3]\n    F3 = np.diag([-1.0, 1.0, -1.0])\n    a_yaw = math.radians(-32.0)\n    Ry_inv = np.array([[math.cos(a_yaw), 0.0, math.sin(a_yaw)],\n                       [0.0, 1.0, 0.0],\n                       [-math.sin(a_yaw), 0.0, math.cos(a_yaw)]])\n    cam_to_vrm = lambda u: F3 @ (Ry_inv @ (np.asarray(u, float) / np.linalg.norm(u)))\n    out_g = cam_to_vrm([0.50, 0.05, 0.86])\n    up_g = cam_to_vrm([-0.05, 0.99, -0.03])\n    up_g -= out_g * (up_g @ out_g)\n    up_g /= np.linalg.norm(up_g)\n    fw_g = np.cross(out_g, up_g)\n    centre_g = Eg * 0.25 + Hg * 0.75 + out_g * 0.205 + fw_g * 0.028\n    T_g2r = fit_probe.world[\"J_Bip_L_LowerArm\"] @ np.linalg.inv(Mg)\n    R_g2r = T_g2r[:3, :3] / np.linalg.norm(T_g2r[:3, :3], axis=0)\n\n    body_p0 = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"body\"][0]\n    face_p0 = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"face\"][0]\n\n    os.makedirs(CACHE_DIR, exist_ok=True)\n    in_npz = os.path.join(CACHE_DIR, \"valen_bl_in.npz\")\n    out_npz = os.path.join(CACHE_DIR, \"valen_bl_out.npz\")\n    np.savez(\n        in_npz,\n        body_pos=body_p0[\"pos\"],\n        body_tri=body_p0[\"tri\"],\n        face_pos=face_p0[\"pos\"],\n        face_tri=face_p0[\"tri\"],\n        bones=fit_probe.bone,\n        landmarks=lm_init,\n        guard_info=dict(\n            fist_R=fist_R,\n            fwd_R=fwd_R,\n            side_R=side_R,\n            flat_R=flat_R,\n            shield_centre=(T_g2r @ np.append(centre_g, 1.0))[:3],\n            shield_out=R_g2r @ out_g,\n            shield_up=R_g2r @ up_g,\n        ),\n    )\n\n    t_bl0 = time.time()\n    res = subprocess.run(\n        [\"blender\", \"-b\", \"--factory-startup\", \"--python\", BLENDER_SCRIPT, \"--\", in_npz, out_npz, \"valen\"],\n        capture_output=True,\n        text=True,\n    )\n    if res.returncode != 0:\n        raise RuntimeError(f\"Blender Valen sculpt failed:\\n{res.stdout[-1500:]}\\n{res.stderr[-1500:]}\")\n    timings[\"blender_valen_s\"] = round(time.time() - t_bl0, 2)\n\n    bl_data = np.load(out_npz, allow_pickle=True)\n    sc_body_pos = bl_data[\"body_pos\"].astype(np.float64)\n    sc_body_nrm = bl_data[\"body_nrm\"].astype(np.float64)\n    sc_face_pos = bl_data[\"face_pos\"].astype(np.float64)\n    sc_face_nrm = bl_data[\"face_nrm\"].astype(np.float64)\n    bl_pieces = bl_data[\"pieces\"]\n\n    def valen_costume(fit):\n        # Update Fit's body surface to our Blender-resculpted body first!\n        fit.pos = sc_body_pos.copy()\n        pcs = []\n        # Articulated dark-leather finger gloves wrapped onto resculpted hands\n        gloves = O.wrap(\n            fit, \"gloves\", \"glove\", (\"Hand\", \"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\"),\n            offset=0.0028, min_w=0.3, smooth=4\n        )\n        if gloves is not None:\n            gloves[\"group\"] = \"gloves\"\n            pcs.append(gloves)\n\n        for (nm, rl, p_arr, n_arr, t_arr, btag, grp) in bl_pieces:\n            pcs.append(bind_blender_piece(fit, nm, rl, p_arr, n_arr, t_arr, btag, grp))\n\n        # Flowing two-sided battle cloak (royal indigo outside, imperial crimson lining inside!)\n        cape_under = merge_surfaces(\n            *[(q[\"pos\"], q[\"tri\"]) for q in pcs if q.get(\"group\") in (\"plate\", \"doublet\", \"collar\")\n              and not q[\"material\"].startswith(\"OUTFIT_pauldron\")],\n            (fit.pos, fit.tri),\n        )\n        cape_pc, _ = O.cape(\n            fit, \"cape\", \"cape\", cape_under, length=0.98, phi=0.46, seg=44, rows=18,\n            top_clear=0.016, clear=(0.024, 0.062)\n        )\n        cape_pc[\"group\"] = \"cape\"\n        pcs.append(cape_pc)\n        return pcs\n\n    p = vp.Portrait(\n        vrm_path,\n        morphs=morphs,\n        pose=vp.BUST_POSE,\n        ref_pose=vp.BUST_POSE,\n        shape=shape,\n        costume=valen_costume,\n    )\n\n    # 1. Strip ALL stock VRoid hair primitives completely (zero VRoid hair cards remain!)\n    keep_idx = [k for k, pr in enumerate(p.prims) if \"_HAIR\" not in pr[\"material\"]]\n    p.prims = [p.prims[k] for k in keep_idx]\n    p.roles = [p.roles[k] for k in keep_idx]\n\n    # 2. Apply Blender 5.2 sculpted head/body positions, mature anime face sculpt, and DATA_TRANSFER normals!\n    for pr, rl in zip(p.prims, p.roles):\n        if rl == \"body\" and len(pr[\"pos\"]) == len(sc_body_pos):\n            pr[\"pos\"] = sc_body_pos.copy()\n            pr[\"nrm\"] = sc_body_nrm.copy()\n        elif rl in (\"face\", \"mouth\", \"brow\", \"line\", \"white\", \"iris\", \"highlight\") and len(pr[\"pos\"]) == len(sc_face_pos):\n            pr[\"pos\"] = sc_face_pos.copy()\n            if rl == \"face\":\n                pr[\"nrm\"] = sc_face_nrm.copy()\n\n    # 3. Paint custom sapphire-cerulean anime iris + jewel catchlight + authored UV/vertex face shadow bias!\n    t_tex0 = time.time()\n    lm_sculpted = vp.landmarks(p.prims, p.roles)\n    for pr, rl in zip(p.prims, p.roles):\n        if rl == \"face\":\n            pr[\"plate\"] = bake_face_shadow_bias(pr[\"pos\"], lm_sculpted)\n        elif rl == \"iris\":\n            orig = p.v.material_texture(pr[\"mi\"])\n            if orig is not None:\n                pr[\"custom_tex\"] = paint_anime_iris_rgba(orig, scheme=\"sapphire\")\n                pr[\"full_color_tex\"] = True\n        elif rl == \"highlight\":\n            orig = p.v.material_texture(pr[\"mi\"])\n            if orig is not None:\n                pr[\"custom_tex\"] = paint_anime_highlight_rgba(orig)\n    timings[\"valen_tex_and_mask_s\"] = round(time.time() - t_tex0, 2)\n\n    valen_colors = {\n        \"r\": \"#15254a\", \"s\": \"#3264b0\", \"t\": \"#8ad4ff\",\n        \"A\": \"#58483c\", \"o\": \"#22181a\",\n    }\n    valen_paint = {\n        \"skin\": \"#f7dfd3\",\n        \"hair\": \"#e3d3ba\",          # Pale champagne-platinum Valkyrie locks\n        \"signature\": \"#1f325c\",     # Royal midnight-indigo surcoat, collar, shield, sleeves\n        \"cape\": {\"kind\": \"cloth\", \"base\": \"#1f325c\", \"lining\": \"#8e1e2e\"},  # Indigo outer + crimson inner lining!\n        \"doublet\": \"#222534\",\n        \"heraldry\": \"#ece6d8\",      # Luminous warm ivory pleated under-kirtle\n        \"steel\": \"#c2cad8\",         # Fluted mirror-bright gothic steel\n        \"gold\": \"#d4a64a\",          # Burnished antique gold filigree & crests\n        \"leather\": \"#4e3122\",\n        \"glove\": \"#36231b\",\n        \"boot\": \"#301f18\",\n        \"wood\": \"#6b482e\",\n    }\n    p.paint = dict(valen_paint)\n    pal = dict(vp.PALETTE, **valen_colors)\n\n    info = export_glb.scene_info(p, pal)\n    # Propagate two-sided cape lining into scene_info paint metadata\n    info[\"paint\"][\"cape\"] = {\"kind\": \"cloth\", \"base\": \"#1f325c\", \"lining\": \"#8e1e2e\"}\n\n    # Export standalone rigged multi-clip GLB to ~/out/valen_finished.glb!\n    t_exp0 = time.time()\n    os.makedirs(\"~/out\", exist_ok=True)\n    standalone_glb = \"~/out/valen_finished.glb\"\n    glb_bytes = export_glb.export_skinned(\n        p,\n        pal,\n        standalone_glb,\n        clips=clips,\n        max_tex=1024,\n        extras=info,\n        step_clips=(\"idle_breath_12fps\", \"strike_combo_12fps\"),\n    )\n    os.chmod(standalone_glb, 0o644)\n    timings[\"export_glb_s\"] = round(time.time() - t_exp0, 2)\n    timings[\"glb_size_bytes\"] = int(glb_bytes)\n\n    # Also write scene copy for review/out/slice_after\n    os.makedirs(ADV_OUT_DIR, exist_ok=True)\n    slice_glb = os.path.join(ADV_OUT_DIR, \"valen.glb\")\n    shutil.copyfile(standalone_glb, slice_glb)\n    bs.wrap_glb_json(slice_glb)\n    # Also copy raw valen_finished.glb into ADV_OUT_DIR so ?glb=valen_finished.glb serves cleanly over localhost HTTP!\n    shutil.copyfile(standalone_glb, os.path.join(ADV_OUT_DIR, \"valen_finished.glb\"))\n\n    timings[\"valen_total_s\"] = round(time.time() - t_start, 2)\n    return dict(\n        name=\"valen\",\n        label=\"Valen (Valkyrie Marshal)\",\n        place={\"pos\": [-0.74, 0.0, 0.04], \"yaw\": 32.0},\n        clip=\"battle_guard\",\n        clip_t=0.0,\n        wind=-3.2,\n        info=info,\n    ), p, clips\n\n\ndef build_korin_adversarial(timings):\n    \"\"\"Upgrade Korin so zero VRoid hair cards remain anywhere in the After battle scene!\"\"\"\n    t0 = time.time()\n    vrm_path = bs.cached_cage_vrm(\"arm_m_strong\")\n    v0 = vp.VRM(vrm_path)\n    shape = {\n        **vp.NEUTRAL,\n        **G.shape(\"stocky\", \"veteran\", blush=0.0, face_normals=0.0, hair_normals=0.0, shadow_cards=0.0),\n    }\n    shape[\"arm_out\"] = bs.arm_room(v0, shape)\n    clips = {\"idle\": bs.housecarl_pose(v0, shape)}\n\n    morphs = {\"Fcl_BRW_Angry\": 0.48, \"Fcl_EYE_Angry\": 0.22}\n    pose_ref = vp.bone_pose(v0, shape, vp.BUST_POSE)\n    raw_prims = v0.primitives(morphs, pose_ref)\n    raw_roles = [vp.role_of(pr[\"material\"]) for pr in raw_prims]\n    lm_k = vp.landmarks(raw_prims, raw_roles)\n    fit_k = O.Fit(v0, pose_ref, raw_prims, raw_roles)\n    bp_k = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"body\"][0]\n    fp_k = [pr for pr, rl in zip(raw_prims, raw_roles) if rl == \"face\"][0]\n\n    kin_npz = os.path.join(CACHE_DIR, \"korin_bl_in.npz\")\n    kout_npz = os.path.join(CACHE_DIR, \"korin_bl_out.npz\")\n    np.savez(\n        kin_npz,\n        body_pos=bp_k[\"pos\"],\n        body_tri=bp_k[\"tri\"],\n        face_pos=fp_k[\"pos\"],\n        face_tri=fp_k[\"tri\"],\n        bones=fit_k.bone,\n        landmarks=lm_k,\n    )\n    t_bl0 = time.time()\n    res = subprocess.run(\n        [\"blender\", \"-b\", \"--factory-startup\", \"--python\", BLENDER_SCRIPT, \"--\", kin_npz, kout_npz, \"korin\"],\n        capture_output=True,\n        text=True,\n    )\n    if res.returncode != 0:\n        raise RuntimeError(f\"Blender Korin build failed:\\n{res.stderr[-1500:]}\")\n    timings[\"blender_korin_s\"] = round(time.time() - t_bl0, 2)\n    k_pieces = np.load(kout_npz, allow_pickle=True)[\"pieces\"]\n\n    def korin_costume(fit):\n        pcs = bs.heavy_housecarl(fit)\n        # Drop old scalp_cap since Blender wolf-cut hair includes its own sculpted cranial shell\n        pcs = [q for q in pcs if q[\"material\"] != \"OUTFIT_scalp_cap\"]\n        for (nm, rl, p_arr, n_arr, t_arr, btag, grp) in k_pieces:\n            pcs.append(bind_blender_piece(fit, nm, rl, p_arr, n_arr, t_arr, btag, grp))\n        return pcs\n\n    p = vp.Portrait(\n        vrm_path,\n        morphs=morphs,\n        pose=vp.BUST_POSE,\n        ref_pose=vp.BUST_POSE,\n        shape=shape,\n        costume=korin_costume,\n    )\n    # Strip stock VRoid bowl-cut hair completely!\n    keep_idx = [k for k, pr in enumerate(p.prims) if \"_HAIR\" not in pr[\"material\"]]\n    p.prims = [p.prims[k] for k in keep_idx]\n    p.roles = [p.roles[k] for k in keep_idx]\n\n    bs.apply_forward_face_normals(p, forward=0.10, pull=0.45)\n    lm_k_now = vp.landmarks(p.prims, p.roles)\n    for pr, rl in zip(p.prims, p.roles):\n        if rl == \"face\":\n            pr[\"plate\"] = bake_face_shadow_bias(pr[\"pos\"], lm_k_now)\n        elif rl == \"iris\":\n            orig = p.v.material_texture(pr[\"mi\"])\n            if orig is not None:\n                pr[\"custom_tex\"] = paint_anime_iris_rgba(orig, scheme=\"amber\")\n                pr[\"full_color_tex\"] = True\n        elif rl == \"highlight\":\n            orig = p.v.material_texture(pr[\"mi\"])\n            if orig is not None:\n                pr[\"custom_tex\"] = paint_anime_highlight_rgba(orig)\n\n    korin_colors = {\n        \"r\": \"#2c1d14\", \"s\": \"#7a4e26\", \"t\": \"#c49052\",\n        \"A\": \"#181920\", \"o\": \"#1e1412\",\n    }\n    korin_paint = {\n        \"skin\": \"#b87a54\",\n        \"hair\": \"#252730\",\n        \"fur\": {\"kind\": \"leather\", \"base\": \"#3a312c\"},\n        \"signature\": \"#7a252c\",\n        \"padding\": \"#cec2ac\",\n        \"mail\": {\"kind\": \"steel\", \"base\": \"#7d8492\"},\n        \"doublet\": \"#363b37\",\n        \"heraldry\": \"#ddd8cc\",\n        \"steel\": \"#a0a8b6\",\n        \"gold\": \"#b38b3d\",\n        \"leather\": \"#583827\",\n        \"glove\": \"#452d20\",\n        \"boot\": \"#38251c\",\n        \"wood\": \"#68462c\",\n    }\n    p.paint = dict(korin_paint)\n    pal = dict(vp.PALETTE, **korin_colors)\n    glb_path = os.path.join(ADV_OUT_DIR, \"korin.glb\")\n    export_glb.export_skinned(p, pal, glb_path, clips=clips, max_tex=1024)\n    bs.wrap_glb_json(glb_path)\n\n    info = export_glb.scene_info(p, pal)\n    info[\"roles\"][\"fur\"] = info[\"roles\"][\"leather\"]\n    info[\"paint\"][\"fur\"] = {\"kind\": \"leather\", \"base\": \"#3a312c\"}\n    timings[\"korin_total_s\"] = round(time.time() - t0, 2)\n    return dict(\n        name=\"korin\",\n        label=\"Korin (Northern Housecarl)\",\n        place={\"pos\": [0.76, 0.0, -0.02], \"yaw\": -33.0},\n        clip=\"idle\",\n        clip_t=0.0,\n        wind=2.8,\n        info=info,\n    )\n\n\n# ---------------------------------------------------------------------------\n# 5. Shoot Headless WebGL Renders (After Battle Frame + Flattice Perspective)\n# ---------------------------------------------------------------------------\ndef shoot_url(query_str, out_png, timeout_s=480):\n    \"\"\"Serve ADV_OUT_DIR over an ephemeral localhost port and capture dataURL via headless Chromium.\"\"\"\n    import re\n    import socket\n\n    with socket.socket() as s:\n        s.bind((\"127.0.0.1\", 0))\n        port = s.getsockname()[1]\n\n    srv = subprocess.Popen(\n        [sys.executable, \"-m\", \"http.server\", str(port), \"-b\", \"127.0.0.1\"],\n        cwd=ADV_OUT_DIR,\n        stdout=subprocess.DEVNULL,\n        stderr=subprocess.DEVNULL,\n    )\n    prof = os.path.join(CACHE_DIR, \"chrome_prof\")\n    os.makedirs(prof, exist_ok=True)\n    url = f\"http://127.0.0.1:{port}/index.html?{query_str}\"\n    try:\n        cmd = [\n            \"/snap/bin/chromium\",\n            \"--headless=new\",\n            \"--no-sandbox\",\n            \"--disable-gpu\",\n            \"--use-gl=angle\",\n            \"--use-angle=swiftshader\",\n            \"--enable-unsafe-swiftshader\",\n            f\"--user-data-dir={prof}\",\n            \"--window-size=1920,1080\",\n            \"--virtual-time-budget=90000\",\n            \"--dump-dom\",\n            url,\n        ]\n        res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s)\n        m = re.search(r'id=\"sheetOut\">([redacted: data-URI prefix][A-Za-z0-9+/=]+)</pre>', res.stdout)\n        if not m:\n            raise RuntimeError(f\"Render failed for {url}:\\nSTDOUT:{res.stdout[-800:]}\\nSTDERR:{res.stderr[-800:]}\")\n        raw_png = base64.b64decode(m.group(1).split(\",\", 1)[1])\n        with open(out_png, \"wb\") as f:\n            f.write(raw_png)\n        os.chmod(out_png, 0o644)\n    finally:\n        srv.terminate()\n        srv.wait()\n\n\ndef compose_flattice_diptych(off_png, on_png, out_png):\n    \"\"\"Join the 24 mm Perspective Flattice Off vs Flattice On renders into a clean 1920x960 comparison plate.\"\"\"\n    im_off = Image.open(off_png).convert(\"RGB\")\n    im_on = Image.open(on_png).convert(\"RGB\")\n    W, H = im_off.size\n    out = Image.new(\"RGB\", (W * 2, H), (28, 27, 34))\n    out.paste(im_off, (0, 0))\n    out.paste(im_on, (W, 0))\n\n    draw = ImageDraw.Draw(out)\n    # Subtle 2 px center divider\n    draw.rectangle([W - 1, 0, W + 1, H], fill=(212, 166, 74))\n\n    try:\n        font_b = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf\", 22)\n        font_s = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 16)\n    except Exception:\n        font_b = font_s = ImageFont.load_default()\n\n    badges = [\n        (28, 24, \"24 mm Perspective Camera  |  Flattice OFF (flat = 0.00)\",\n         \"Exported valen_finished.glb: sword & shield foreshorten; close lens bulges nose & jaw\"),\n        (W + 28, 24, \"24 mm Perspective Camera  |  Flattice ON (flat = 0.85)\",\n         \"Same 24 mm lens + view-space head squash: 3D foreshortened gear, distortion-free 3/4 anime face\"),\n    ]\n    for bx, by, title, sub in badges:\n        draw.rounded_rectangle([bx, by, bx + 890, by + 68], radius=8, fill=(22, 24, 34), outline=(196, 154, 69), width=2)\n        draw.text((bx + 16, by + 11), title, fill=(244, 238, 226), font=font_b)\n        draw.text((bx + 16, by + 40), sub, fill=(192, 198, 212), font=font_s)\n\n    out.save(out_png, \"PNG\", optimize=True)\n    os.chmod(out_png, 0o644)\n\n\ndef verify_standalone_glb_in_blender(glb_path, timings):\n    \"\"\"Import ~/out/valen_finished.glb in fresh headless Blender 5.2 to audit meshes, bones, and clips.\"\"\"\n    t0 = time.time()\n    expr = (\n        \"import bpy, json; bpy.ops.wm.read_factory_settings(use_empty=True); \"\n        f\"bpy.ops.import_scene.gltf(filepath={glb_path!r}); \"\n        \"meshes=[o for o in bpy.data.objects if o.type=='MESH']; \"\n        \"arms=[o for o in bpy.data.objects if o.type=='ARMATURE']; \"\n        \"tris=sum(len(o.data.polygons) for o in meshes); \"\n        \"verts=sum(len(o.data.vertices) for o in meshes); \"\n        \"bones=len(arms[0].data.bones) if arms else 0; \"\n        \"acts=[a.name for a in bpy.data.actions]; \"\n        \"mats=len(bpy.data.materials); \"\n        \"imgs=len(bpy.data.images); \"\n        \"print('GLB_AUDIT:' + json.dumps(dict(meshes=len(meshes), verts=verts, tris=tris, bones=bones, actions=acts, materials=mats, images=imgs)))\"\n    )\n    res = subprocess.run([\"blender\", \"-b\", \"--factory-startup\", \"--python-expr\", expr], capture_output=True, text=True)\n    if res.returncode != 0:\n        raise RuntimeError(f\"Blender GLB audit failed:\\n{res.stderr[-1500:]}\")\n    audit = {}\n    for line in res.stdout.splitlines():\n        if line.startswith(\"GLB_AUDIT:\"):\n            audit = json.loads(line.split(\"GLB_AUDIT:\", 1)[1])\n    timings[\"glb_audit_s\"] = round(time.time() - t0, 2)\n    timings[\"glb_audit\"] = audit\n    return audit\n\n\ndef main():\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--after-png\", default=\"~/out/battle_frame_after.png\")\n    ap.add_argument(\"--flattice-png\", default=\"~/out/valen_flattice_persp.png\")\n    args = ap.parse_args()\n\n    t_all = time.time()\n    timings = {}\n    os.makedirs(ADV_OUT_DIR, exist_ok=True)\n    with open(bs.SLICE_HTML) as f:\n        html = f.read()\n    with open(os.path.join(ADV_OUT_DIR, \"index.html\"), \"w\") as f:\n        f.write(html)\n    three_link = os.path.join(ADV_OUT_DIR, \"three\")\n    if not os.path.exists(three_link):\n        os.symlink(bs.LOCAL_THREE, three_link)\n\n    print(\"1/5 Building adversarial Valen (Blender 5.2 sculpt, 3D lock hair, gothic-anime armour, GLB)...\")\n    valen_unit, _, _ = build_valen_adversarial(timings)\n\n    print(\"2/5 Building upgraded Korin (Blender 5.2 wolf-cut hair, northern pauldrons & fur mantle)...\")\n    korin_unit = build_korin_adversarial(timings)\n\n    # Terrain\n    world_holder = type(\"WorldPortrait\", (), {})()\n    world_holder.prims = terrain.plains(width=4.8, depth=2.1, thick=0.30, seed=5, tufts=34, stones=7)\n    world_holder.roles = [pr[\"role\"] for pr in world_holder.prims]\n    world_holder.tex = {}\n    plains_path = os.path.join(ADV_OUT_DIR, \"plains.glb\")\n    export_glb.export(world_holder, vp.PALETTE, plains_path, only_world=True)\n    bs.wrap_glb_json(plains_path)\n\n    scene_doc = dict(\n        camera=dict(target=[0.02, 0.90, 0.0], height=2.16, pitch=8.5),\n        key=[-0.62, 0.48, 0.62],\n        grade=dict(ambient=[0.86, 0.88, 0.96], key=[1.04, 1.00, 0.94], rim=[0.28, 0.25, 0.20]),\n        characters=[valen_unit, korin_unit],\n    )\n    with open(os.path.join(ADV_OUT_DIR, \"scene.json\"), \"w\") as f:\n        json.dump(scene_doc, f)\n\n    print(\"3/5 Auditing ~/out/valen_finished.glb in headless Blender 5.2...\")\n    audit = verify_standalone_glb_in_blender(\"~/out/valen_finished.glb\", timings)\n    print(\"    GLB Audit:\", audit)\n\n    print(\"4/5 Shooting After battle visual (~/out/battle_frame_after.png, 1920x1080 @ ss=2)...\")\n    t_r1 = time.time()\n    shoot_url(\"shot=1&w=1920&h=1080&ss=2\", args.after_png)\n    timings[\"render_after_battle_s\"] = round(time.time() - t_r1, 2)\n\n    print(\"5/5 Shooting 24 mm Perspective + Flattice showcase directly from valen_finished.glb...\")\n    t_r2 = time.time()\n    off_png = os.path.join(CACHE_DIR, \"flattice_off.png\")\n    on_png = os.path.join(CACHE_DIR, \"flattice_on.png\")\n    q_base = \"shot=1&glb=valen_finished.glb&clip=battle_guard&yaw=34&target=-0.03,1.38,0.04&height=0.68&pitch=5&w=960&h=960&ss=2&lens=24\"\n    shoot_url(f\"{q_base}&flat=0\", off_png)\n    shoot_url(f\"{q_base}&flat=0.85\", on_png)\n    compose_flattice_diptych(off_png, on_png, args.flattice_png)\n    timings[\"render_flattice_persp_s\"] = round(time.time() - t_r2, 2)\n\n    timings[\"pipeline_total_s\"] = round(time.time() - t_all, 2)\n    with open(os.path.join(CACHE_DIR, \"adversarial_timings.json\"), \"w\") as f:\n        json.dump(timings, f, indent=2)\n    print(\"DONE! Timings:\", json.dumps(timings, indent=2))\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "Overwrite": true,
      "Path": "~/work/lowmarch/tools/build_adversarial.py"
    }

    result, 1 line

    Created file.