agent

+10:53
reasoning

The saber_study.py script appears to use a height calculation (y = lambda f: top - f * H) based on a head-height measurement (H) from a different dataset, specifically Elaine's 7.06-head body. This could lead to incorrect sizing or positioning if applied to the current target data. This discrepancy needs further investigation to ensure height scaling consistency.

  • read_file{"EndLine":650,"Path":"~/work/lowmarch/tools/gear.py","StartLine":300}

    input

    {
      "EndLine": 650,
      "Path": "~/work/lowmarch/tools/gear.py",
      "StartLine": 300
    }

    result, 352 lines

    Showing lines 300-650 of 984
    300:     P += lat[None] * (-(x ** 2) / (2 * curve))[:, None]
    301:     pc["nrm"] = O.vertex_normals(P, pc["tri"])
    302:     rim = O.pipe(f"{name}_rim", "steel", np.array([centre + fw * px_ + up * py_ + lat * (-(px_ ** 2) / (2 * curve) + 0.007)
    303:                                                     for px_, py_ in outline]), r=0.006, seg=6, closed=True)
    304:     boss, _ = O.dome(f"{name}_boss", "steel", centre + lat * 0.007, lat, up, 0.035, 0.022, rows=6)
    305:     out = [pc, rim, boss]
    306:     _bind(fit, out, f"J_Bip_{side}_LowerArm")
    307:     return _group(out, "shield")
    308: 
    309: 
    310: # ---- weapons (held like the sword: along the right hand's -z) ------------------------------------------------
    311: def _hand_frame(fit, hand="R"):
    312:     M = fit.world[f"J_Bip_{hand}_Hand"]
    313:     R, o = M[:3, :3], M[:3, 3]
    314:     R = R / np.linalg.norm(R, axis=0)
    315:     sx = 1 if hand == "R" else -1
    316:     g = getattr(fit, "grip", None)                     # the fist's measured hole (rig.grip_points)
    317:     fist = g[hand]["point"] if g else o + R @ np.array([sx * 0.045, -0.018, 0.0])
    318:     fwd = R @ np.array([0, 0, -1.0])
    319:     side = R @ np.array([sx * 1.0, 0, 0])
    320:     return fist, fwd, side, np.cross(fwd, side), R
    321: 
    322: 
    323: def spear(fit, length=2.0, grip=0.55, head=0.26, hand="R", shaft_role="wood", name="spear"):
    324:     """A spear held a little behind its middle: an ash shaft, a leaf blade with a socket, a butt cap."""
    325:     fist, fwd, side, flat, _ = _hand_frame(fit, hand)
    326:     start = fist - fwd * grip
    327:     out = [O.tube(f"{name}_shaft", shaft_role, start, fwd, length, 0.0135)]
    328:     tip0 = start + fwd * length
    329:     out.append(O.tube(f"{name}_socket", "steel", tip0 - fwd * 0.06, fwd, 0.08, 0.016, 0.012))
    330:     leaf = [(0.0, 0.0), (0.024, head * 0.30), (0.018, head * 0.65), (0.0, head), (-0.018, head * 0.65), (-0.024, head * 0.30)]
    331:     out.append(flat_piece(f"{name}_head", "steel", leaf, tip0 + fwd * 0.015, side, fwd, thickness=0.006))
    332:     out.append(O.ball(f"{name}_butt", "steel", start - fwd * 0.01, 0.016, squash=(1, 1, 1.6)))
    333:     _bind(fit, out, f"J_Bip_{hand}_Hand")
    334:     return _group(out, "weapon")
    335: 
    336: 
    337: def axe(fit, haft=0.85, blade=0.24, double=False, hand="R", shaft_role="wood", name="axe", grip=0.18):
    338:     """An axe: a haft with a bearded crescent blade (two for a great axe), a langet and a pommel."""
    339:     fist, fwd, side, flat, _ = _hand_frame(fit, hand)
    340:     start = fist - fwd * grip
    341:     out = [O.tube(f"{name}_haft", shaft_role, start, fwd, haft, 0.016, 0.018)]
    342:     top = start + fwd * (haft - 0.02)
    343:     a = np.linspace(-1, 1, 15)
    344:     edge = [(blade * (0.72 + 0.28 * math.cos(x * 1.25)), blade * 0.62 * x) for x in a]
    345:     beard = [(blade * 0.30, -blade * 0.62), (0.03, -blade * 0.16), (0.03, blade * 0.12), (blade * 0.30, blade * 0.58)]
    346:     cres = [(0.02, -0.05)] + [p_ for p_ in beard[:1]] + edge + [beard[-1]] + [(0.02, 0.05)]
    347:     for k, sg in enumerate((1, -1) if double else (1,)):
    348:         pts = [(sg * x, y) for x, y in cres]
    349:         out.append(flat_piece(f"{name}_blade{k}", "steel", pts, top, side, fwd, thickness=0.009))
    350:     out.append(O.box(f"{name}_eye", "steel", top, (side, flat, fwd), (0.026, 0.022, 0.06)))
    351:     out.append(O.ball(f"{name}_pommel", "steel", start, 0.022, squash=(1, 1, 0.8)))
    352:     _bind(fit, out, f"J_Bip_{hand}_Hand")
    353:     return _group(out, "weapon")
    354: 
    355: 
    356: def dagger(fit, blade=0.24, hand="R", name="dagger"):
    357:     fist, fwd, side, flat, _ = _hand_frame(fit, hand)
    358:     out = [O.tube(f"{name}_grip", "leather", fist - fwd * 0.06, fwd, 0.11, 0.011)]
    359:     g = fist + fwd * 0.055
    360:     out.append(O.box(f"{name}_guard", "steel", g, (side, flat, fwd), (0.040, 0.008, 0.007)))
    361:     out.append(flat_piece(f"{name}_blade", "steel", [(0.016, 0), (0.012, blade * 0.7), (0, blade), (-0.012, blade * 0.7), (-0.016, 0)],
    362:                           g + fwd * 0.006, side, fwd, thickness=0.005))
    363:     _bind(fit, out, f"J_Bip_{hand}_Hand")
    364:     return _group(out, "weapon")
    365: 
    366: 
    367: def staff(fit, length=1.65, hand="R", wood="wood", head_role="gold", name="staff", grip=0.75):
    368:     fist, fwd, side, flat, _ = _hand_frame(fit, hand)
    369:     start = fist - fwd * grip
    370:     out = [O.tube(f"{name}_shaft", wood, start, fwd, length, 0.014, 0.017)]
    371:     tip = start + fwd * length
    372:     out.append(O.ball(f"{name}_orb", head_role, tip + fwd * 0.04, 0.035))
    373:     for k in range(3):                                       # a cage of three prongs round the orb
    374:         ang = 2 * math.pi * k / 3
    375:         d = side * math.cos(ang) + flat * math.sin(ang)
    376:         pts = [tip - fwd * 0.02, tip + d * 0.03 + fwd * 0.02, tip + d * 0.042 + fwd * 0.05, tip + d * 0.02 + fwd * 0.085]
    377:         out.append(O.pipe(f"{name}_prong{k}", head_role, np.array(pts), r=0.004, seg=6))
    378:     _bind(fit, out, f"J_Bip_{hand}_Hand")
    379:     return _group(out, "weapon")
    380: 
    381: 
    382: def bow(fit, length=1.25, hand="L", name="bow", wood="wood"):
    383:     """A self bow in the lowered hand, hanging along the leg: limbs curving forward at the tips, a string."""
    384:     M = fit.world[f"J_Bip_{hand}_Hand"]
    385:     R, o = M[:3, :3], M[:3, 3]
    386:     R = R / np.linalg.norm(R, axis=0)
    387:     sx = 1 if hand == "R" else -1
    388:     grip = o + R @ np.array([sx * 0.045, -0.018, 0.0])
    389:     along = R @ np.array([sx * 1.0, 0, 0])                    # the fingers' direction: down a hanging arm
    390:     belly = R @ np.array([0, 0, -1.0])                        # the bow's back faces forward
    391:     t = np.linspace(-1, 1, 25)
    392:     curve = np.array([grip + along * (length / 2) * x + belly * (0.08 * (1 - x * x) - 0.02 * x ** 4) for x in t])
    393:     limb = O.pipe(f"{name}_limb", wood, curve, r=0.012, seg=7)
    394:     taper(limb, len(t), 8, 1.0 - 0.55 * np.abs(t) ** 1.4)
    395:     limb["nrm"] = O.vertex_normals(limb["pos"], limb["tri"])
    396:     string = O.pipe(f"{name}_string", "heraldry", np.array([curve[0], curve[-1]]), r=0.0014, seg=4)
    397:     wrap = O.tube(f"{name}_grip", "leather", grip - along * 0.05, along, 0.10, 0.016)
    398:     out = [limb, string, wrap]
    399:     _bind(fit, out, f"J_Bip_{hand}_Hand")
    400:     return _group(out, "weapon")
    401: 
    402: 
    403: def quiver(fit, name="quiver", role="leather"):
    404:     """A quiver slung on the back, arrows showing."""
    405:     B = fit.bone
    406:     sp = B["J_Bip_C_Chest"]
    407:     c = sp + np.array([0.06, 0.0, 0.11])
    408:     d = np.array([-0.35, 1.0, 0.1])
    409:     d /= np.linalg.norm(d)
    410:     out = [O.tube(f"{name}_case", role, c - d * 0.28, d, 0.5, 0.045, 0.05)]
    411:     for k in range(5):
    412:         off = np.array([math.cos(k * 1.3) * 0.02, 0, math.sin(k * 1.3) * 0.02])
    413:         out.append(O.tube(f"{name}_arrow{k}", "wood", c + d * 0.2 + off, d, 0.12, 0.004))
    414:         out.append(O.box(f"{name}_fletch{k}", "heraldry", c + d * 0.31 + off, (d, np.array([1.0, 0, 0]), np.cross(d, [1.0, 0, 0])),
    415:                          (0.03, 0.012, 0.002)))
    416:     _bind(fit, out, "J_Bip_C_Chest")
    417:     return _group(out, "weapon")
    418: 
    419: 
    420: # ---- casters: robes and hats --------------------------------------------------------------------------------
    421: def robe(fit, under, name="robe", role="signature", trim=0.012, y_hem=None, flare=0.16, split=0.0, sleeve_flare=0.07):
    422:     """A long robe: the body over the shirt, a skirt over a cone to the ankles (split at the front if
    423:     `split` degrees), bell sleeves widening to the wrist; gold-bordered edges."""
    424:     B = fit.bone
    425:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    426:     foot = B["J_Bip_L_Foot"][1]
    427:     y_hem = foot + 0.04 if y_hem is None else y_hem
    428:     cz = float(hips[2])
    429:     y_waist = hips[1] + 0.06
    430:     tc = TorsoChart(under, y_waist - 0.04, nk[1] + 0.02, cz=cz, du=3.0, dv=0.008)
    431:     out = []
    432:     body, _ = outline_plate(name, role, tc, -178, 178, lambda u: y_waist, lambda u: nk[1] - 0.025 - 0.03 * max(0.0, 1 - abs(u) / 60),
    433:                             offset=0.008, thickness=0.004, nu=96, nv=20, roll=0, trim=trim)
    434:     fit.bind(body, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips", "Neck", "Shoulder"), fallback="J_Bip_C_Chest")
    435:     out.append(body)
    436:     r0 = lambda u: float(tc.radius(u, y_waist)) + 0.010
    437:     cone = ConeChart(lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_waist - v) / (y_waist - y_hem), 0, 1.2) ** 1.4, cz=cz)
    438:     u0, u1 = (split, 360 - split) if split else (-178, 178)
    439:     skirt, _ = outline_plate(f"{name}_skirt", role, cone, u0, u1, lambda u: y_hem, lambda u: y_waist + 0.012, offset=0.002,
    440:                              thickness=0.004, nu=120, nv=22, roll=0, trim=trim)
    441:     fit.bind(skirt, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips")
    442:     stiffen(skirt, fit, share=0.6)
    443:     out.append(skirt)
    444:     for side in ("L", "R"):
    445:         for seg, (a, b, v0, v1, fl) in enumerate(((f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", -0.06, 1.02, 0.0),
    446:                                                   (f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand", -0.02, 0.86, sleeve_flare))):
    447:             arm = O.limb_surface(fit, (a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), side)
    448:             lc = LimbChart(arm, B[a], B[b], front=(0, 0, -1))
    449:             sl, _ = outline_plate(f"{name}_sleeve_{side}{seg}", role, lc, -180, 180, lambda u, v1=v1: v1, lambda u, v0=v0: v0,
    450:                                   offset=0.010, thickness=0.004, nu=48, nv=12, roll=0, trim=trim if seg else 0.0,
    451:                                   flare=(lambda u, v, s, t, fl=fl: fl * (1 - t) ** 1.8) if fl else None)
    452:             fit.bind(sl, allow=(a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), fallback=a)
    453:             out.append(sl)
    454:     return _group(out, "dress")
    455: 
    456: 
    457: def witch_hat(fit, name="hat", role="signature", band_role="gold", height=0.32, brim=0.12, lift=0.034):
    458:     """A tall pointed hat: a wide soft brim, a crown narrowing to a tip that bends back, a band."""
    459:     ch = head_chart(fit)
    460:     rim_v = lambda u: float(np.interp(abs(u), [0, 90, 180], [62, 74, 84]))
    461:     U = np.linspace(-180, 180, 49)
    462:     base = np.array([ch.point(u, rim_v(u), off=lift) for u in U])
    463:     c0 = base.mean(0)
    464:     rings = []
    465:     for k, t in enumerate(np.linspace(0, 1, 16)):
    466:         axis = c0 + np.array([0, height * t, 0.10 * t ** 2.2])            # the tip leans back
    467:         rings.append(axis + (base - c0) * (1 - t) ** 1.25 * (1 + 0.15 * math.sin(math.pi * t)))
    468:     G = np.stack(rings, 1)
    469:     pos, tri, outer = O.thick_grid(G, 0.004, outward_from=c0 + np.array([0, height * 0.3, 0]))
    470:     crown = O.piece(name, role, pos, tri)
    471:     d = base - ch.c
    472:     d[:, 1] = 0
    473:     d /= np.linalg.norm(d, axis=1, keepdims=True)
    474:     B_ = np.stack([base + d * brim * t - np.array([0, 0.03 * t ** 2, 0]) for t in np.linspace(0, 1, 6)], 1)
    475:     pos, tri, outer2 = O.thick_grid(B_, 0.004, outward_from=ch.c - np.array([0, 0.4, 0]))
    476:     brim_pc = O.piece(f"{name}_brim", role, pos, tri)
    477:     band = O.pipe(f"{name}_band", band_role, base + (base - c0) * 0.03 + np.array([0, 0.012, 0]), r=0.007, seg=6, closed=True)
    478:     out = [crown, brim_pc, band]
    479:     _bind(fit, out, "J_Bip_C_Head")
    480:     return _group(out, "helmet")
    481: 
    482: 
    483: # ---- the study's detail layer (lesson 15): puffed sleeves, breastplates, scale and pleated skirts ----------
    484: def puff(fit, side, role="signature", size=1.0, name=None, piping=None, gather=0.48, cap=None, under=None):
    485:     """A puffed upper sleeve: a rounded box on the shoulder and upper arm, gathered toward the elbow
    486:     (the generic units' most recognisable shape). size scales it; piping: a role for a seam pipe.
    487: 
    488:     cap (default: on MakeHuman bodies) is the shape after the Unicorn Overlord study and an art
    489:     review: a shoulder cap, widest at the top and fuller at the back, gathered hard into a band that
    490:     sits on the sleeve above the elbow, with folds converging on the band. Its size follows the arm's
    491:     length only (capped), and the sleeves in `under` are tucked inside it, so a thick arm can't poke
    492:     through. The older shape sat lower, bulged evenly in and out, and on a muscled arm read as a
    493:     swollen bicep."""
    494:     B = fit.bone
    495:     s = 1 if side == "R" else -1
    496:     sh, el = B[f"J_Bip_{side}_UpperArm"], B[f"J_Bip_{side}_LowerArm"]
    497:     L = float(np.linalg.norm(el - sh))
    498:     down = (el - sh) / L
    499:     outw = np.array([s * 1.0, 0, 0]) - down * (s * down[0])
    500:     outw /= np.linalg.norm(outw)
    501:     fwd = np.cross(down, outw)
    502:     fwd = -fwd if fwd[2] > 0 else fwd
    503:     up = -down
    504:     cap = getattr(fit, "cloth_hull", False) if cap is None else cap
    505:     if not cap:
    506:         # measured on a 23 cm upper arm; a thicker arm gets a bigger puff, or the arm pokes through it
    507:         w = fit.weight((f"{side}_UpperArm",))
    508:         sk = np.unique(fit.tri)
    509:         P = fit.pos[sk[w[sk] > 0.6]] - sh
    510:         r = np.linalg.norm(P - np.outer(P @ down, down), axis=1) if len(P) else np.zeros(1)
    511:         kl = L / 0.23
    512:         kr = max(float(np.percentile(r, 90)) / 0.0534, float(np.percentile(r, 50)) / 0.0391)
    513:         k = size * max(kl, kr + 0.06 * min(1.0, max(0.0, kr - kl) / 0.05))
    514:         c = sh + down * L * 0.32 + outw * 0.010 * k
    515:         ext = {"out": 0.058 * k, "in": 0.050 * k, "up": 0.082 * k, "down": 0.088 * k, "fwd": 0.056 * k, "back": 0.054 * k}
    516:         G, gexp, r_band = gather, 2.0, None
    517:     else:
    518:         k = size * min(1.15, L / 0.23)
    519:         # the arm's median radius: the puff must stand well clear of it to read as a puff at all
    520:         w = fit.weight((f"{side}_UpperArm",))
    521:         sk = np.unique(fit.tri)
    522:         P = fit.pos[sk[w[sk] > 0.6]] - sh
    523:         r_arm = float(np.median(np.linalg.norm(P - np.outer(P @ down, down), axis=1))) if len(P) else 0.04
    524:         lk = max(k, 1.35 * r_arm / 0.052)
    525:         c = sh + down * L * 0.17 + outw * 0.008 * lk
    526:         ext = {"out": 0.058 * lk, "in": 0.046 * lk, "up": 0.050 * k, "down": 0.110 * k, "fwd": 0.048 * lk, "back": 0.062 * lk}
    527:         # the band sits on the sleeve, round the bone: its radius where the puff gathers, measured on
    528:         # the sleeve itself
    529:         t_g = float((c - up * ext["down"] * 0.97 - sh) @ down)
    530:         cg = sh + down * t_g
    531:         r_band = r_arm + 0.008
    532:         band_r = None                                     # the band's radius by angle round the sleeve
    533:         cg0 = cg.copy()
    534: 
    535:         def measure(cg):
    536:             """The sleeve where the puff gathers: its centre, its 85th-percentile radius and its radius
    537:             by angle (None, None, None when there is no sleeve)."""
    538:             for pc_ in under or []:
    539:                 Q = pc_["pos"] - cg
    540:                 ax = Q @ down
    541:                 on_arm = (np.array([f"{side}_UpperArm" in n for n in pc_["jnames"]])[pc_["J"]] * pc_["W"]).sum(1) > 0.5
    542:                 near = (np.abs(ax) < 0.012) & on_arm
    543:                 if near.sum() <= 6:
    544:                     continue
    545:                 Qn = Q[near] - np.outer(ax[near], down)
    546:                 mid = Qn.mean(0)
    547:                 Qn = Qn - mid
    548:                 ang = np.arctan2(Qn @ fwd, Qn @ outw)
    549:                 rad = np.linalg.norm(Qn, axis=1)
    550:                 bins = (((ang + np.pi) / (2 * np.pi)) * 16).astype(int) % 16
    551:                 med = np.array([rad[bins == i].max() if (bins == i).any() else np.nan for i in range(16)])
    552:                 ok = ~np.isnan(med)
    553:                 cen = -np.pi + (np.arange(16) + 0.5) * 2 * np.pi / 16
    554:                 med = np.interp(cen, cen[ok], med[ok], period=2 * np.pi)
    555:                 med = (np.roll(med, 1) + 2 * med + np.roll(med, -1)) / 4
    556:                 return (cg + mid, float(np.percentile(rad, 85)) + 0.003,
    557:                         lambda f, cen=cen, med=med: float(np.interp(f, cen, med, period=2 * np.pi)) + 0.003)
    558:             return None, None, None
    559:         m_ = measure(cg0)
    560:         if m_[0] is not None:
    561:             cg, r_band, band_r = m_
    562:         lat = (ext["out"] + ext["in"] + ext["fwd"] + ext["back"]) / 4
    563:         G, gexp = float(np.clip(1 - r_band / lat, 0.3, 0.8)), 2.6
    564: 
    565:     def surf_many(D):
    566:         """Puff surface points (relative to c, in outw/up/fwd) along directions D (N,3)."""
    567:         D = D / np.linalg.norm(D, axis=1, keepdims=True)
    568:         A = np.stack([np.where(D[:, 0] >= 0, ext["out"], ext["in"]), np.where(D[:, 1] >= 0, ext["up"], ext["down"]),
    569:                       np.where(D[:, 2] >= 0, ext["fwd"], ext["back"])], 1)
    570:         r = (np.sum(np.abs(D / A) ** 3.0, axis=1)) ** (-1 / 3.0)
    571:         q = D * r[:, None]
    572:         g = np.where(q[:, 1] < 0, 1 - G * np.clip(-q[:, 1] / ext["down"], 0, 1) ** gexp, 1.0)
    573:         q[:, 0] *= g
    574:         q[:, 2] *= g
    575:         return q
    576: 
    577:     def surf(d):
    578:         q = surf_many(np.asarray(d, float)[None])[0]
    579:         return c + outw * q[0] + up * q[1] + fwd * q[2]
    580:     th = np.linspace(0, np.pi, 22)
    581:     ph = np.linspace(0, 2 * np.pi, 33)
    582:     Gd = np.array([[surf((math.sin(t) * math.cos(f), math.cos(t), math.sin(t) * math.sin(f))) for t in th] for f in ph])
    583:     pos, tri = O.grid_mesh(Gd)
    584:     pc = O.piece(name or f"puff_{side}", role, pos, tri, outward_from=c)
    585:     P = pc["pos"].reshape(33, 22, 3)
    586:     for i, f in enumerate(ph):
    587:         if not cap:                                       # puckered folds running down the sleeve
    588:             P[i] += (P[i] - c) * (0.05 * math.sin(f * 8))
    589:         else:                                             # five folds, deepening toward the band
    590:             hgt = ((P[i] - c) @ up) / ext["down"]
    591:             deep = np.clip(-hgt, 0, 1) ** 1.2
    592:             P[i] += (P[i] - c) * (0.07 * math.sin(f * 5)) * deep[:, None]
    593:     pc["pos"] = P.reshape(-1, 3)
    594:     pc["nrm"] = O.vertex_normals(pc["pos"], pc["tri"])
    595:     fit.bind(pc, blend={f"J_Bip_{side}_UpperArm": 0.8, f"J_Bip_{side}_Shoulder": 0.2})
    596:     out = [pc]
    597:     if cap:
    598:         # tuck the sleeves inside: anything of them within the puff's height that reaches past its skin
    599:         # is drawn back under it (the skin under a costume is culled, so only the sleeves can show)
    600:         for pc_ in under or []:
    601:             Q = pc_["pos"] - c
    602:             loc = np.stack([Q @ outw, Q @ up, Q @ fwd], 1)
    603:             span = (loc[:, 1] < ext["up"]) & (loc[:, 1] > -ext["down"] * 0.95)
    604:             arm = (np.array([f"{side}_UpperArm" in n or f"{side}_Shoulder" in n for n in pc_["jnames"]])[pc_["J"]]
    605:                    * pc_["W"]).sum(1) > 0.3
    606:             sel = span & arm
    607:             if not sel.any():
    608:                 continue
    609:             qs = surf_many(loc[sel])
    610:             lim = np.linalg.norm(qs, axis=1) - 0.005
    611:             dist = np.linalg.norm(loc[sel], axis=1)
    612:             over = dist > lim
    613:             idx = np.nonzero(sel)[0][over]
    614:             scale = (lim[over] / np.maximum(dist[over], 1e-9))[:, None]
    615:             pc_["pos"][idx] = c + (pc_["pos"][idx] - c) * scale
    616:             pc_["nrm"] = O.vertex_normals(pc_["pos"], pc_["tri"])
    617:         piping = piping or "leather"
    618:         m_ = measure(cg0)                                 # again, now the sleeve is tucked in
    619:         if m_[0] is not None:
    620:             cg, r_band, band_r = m_
    621:         band = np.array([cg + up * ext["down"] * 0.04 + (outw * math.cos(f) + fwd * math.sin(f))
    622:                          * ((band_r(math.atan2(math.sin(f), math.cos(f))) if band_r else r_band) + 0.002)
    623:                          for f in np.linspace(0, 2 * np.pi, 33)])
    624:         bd = O.pipe(f"{pc['material'][7:]}_band", piping, band, r=0.0055, seg=8, closed=True)
    625:         fit.bind(bd, rigid=f"J_Bip_{side}_UpperArm")       # it rides the sleeve, not the puff's shoulder blend
    626:         bd["group"] = pc.get("group")
    627:         out.append(bd)
    628:     elif piping:
    629:         band = np.array([surf((math.cos(f), -0.55, math.sin(f))) for f in np.linspace(0, 2 * np.pi, 33)])
    630:         out.append(O.inherit(O.pipe(f"{pc['material'][7:]}_band", piping, band, r=0.004 * k, seg=6, closed=True), pc))
    631:     return _group(out, "doublet")
    632: 
    633: 
    634: LIMBS = {"arm": ("UpperArm", "LowerArm", "Hand"), "leg": ("UpperLeg", "LowerLeg", "Foot")}
    635: 
    636: 
    637: def _limb_frame(fit, side, Q, limb="arm"):
    638:     """Points Q against one limb in the reference pose: the distance along it from the top joint (upper
    639:     segment 0..1, lower 1..2), the unit radial direction off the bone, its radius, its angle round the
    640:     limb (0 outward, +90 forward, 180 toward the body or the other leg), and the upper segment's length."""
    641:     B = fit.bone
    642:     j0, j1, j2 = (B[f"J_Bip_{side}_{n}"] for n in LIMBS[limb])
    643:     L1, L2 = float(np.linalg.norm(j1 - j0)), float(np.linalg.norm(j2 - j1))
    644:     d1, d2 = (j1 - j0) / L1, (j2 - j1) / L2
    645:     lower = (Q - j1) @ d2 > 0
    646:     t = np.where(lower, np.clip((Q - j1) @ d2, 0, L2), np.clip((Q - j0) @ d1, -0.3 * L1, L1))
    647:     ax = np.where(lower[:, None], d2, d1)
    648:     foot = np.where(lower[:, None], j1 + t[:, None] * d2, j0 + t[:, None] * d1)
    649:     R = Q - foot
    650:     R -= ax * (R * ax).sum(1, keepdims=True)
  • read_file{"EndLine":984,"Path":"~/work/lowmarch/tools/gear.py","StartLine":650}

    input

    {
      "EndLine": 984,
      "Path": "~/work/lowmarch/tools/gear.py",
      "StartLine": 650
    }

    result, 336 lines

    Showing lines 650-984 of 984
    650:     R -= ax * (R * ax).sum(1, keepdims=True)
    651:     r = np.linalg.norm(R, axis=1)
    652:     u = R / np.maximum(r, 1e-9)[:, None]
    653:     s = np.where(lower, 1 + t / L2, t / L1)
    654:     sx = 1.0 if side == "R" else -1.0
    655:     o = np.array([sx, 0, 0])[None] - ax * ax[:, :1] * sx
    656:     o /= np.linalg.norm(o, axis=1, keepdims=True)
    657:     f = np.cross(ax, o)
    658:     f = np.where((f[:, 2] > 0)[:, None], -f, f)                # forward is -z
    659:     phi = np.arctan2((u * f).sum(1), (u * o).sum(1))
    660:     return s, u, r, phi, L1
    661: 
    662: 
    663: def _let_out(fit, pc, limb, knots, prof, ease, folds=6, toward=0.72, behind=0.15, fold_amp=(0.18, 0.22),
    664:              fold_from=0.6, size=0.26):
    665:     """Let a wrapped garment out round a limb, both sides: radially off the bone by ease x prof (a
    666:     profile over the distance along the limb, see _limb_frame), less toward the body, a little more
    667:     behind, with `folds` soft folds that turn down the limb and deepen past `fold_from`. Weighted by
    668:     each point's share of the limb's two bones, so it fades into the body. Scaled by the upper segment's
    669:     length against `size`. Changes `pc` in place."""
    670:     P = pc["pos"]
    671:     for side in ("L", "R"):
    672:         hit = np.array([n in tuple(f"J_Bip_{side}_{b}" for b in LIMBS[limb][:2]) for n in pc["jnames"]])
    673:         w = (hit[pc["J"]] * pc["W"]).sum(1)
    674:         sel = np.nonzero(w > 0.02)[0]
    675:         if not len(sel):
    676:             continue
    677:         s, u, r, phi, L1 = _limb_frame(fit, side, P[sel], limb)
    678:         k = min(1.15, max(0.85, L1 / size))
    679:         base = ease * k * np.interp(s, knots, prof)
    680:         dirw = 1.0 - toward * np.clip(-np.cos(phi), 0, 1) ** 1.5 + behind * np.clip(-np.sin(phi), 0, 1)
    681:         fold = np.sin(folds * phi + 0.9 * s) * (fold_amp[0] + fold_amp[1] * np.clip((s - fold_from) / 0.7, 0, 1))
    682:         P[sel] += u * (base * dirw * (1 + fold) * np.clip(w[sel], 0, 1))[:, None]
    683:     pc["nrm"] = O.vertex_normals(P, pc["tri"])
    684:     return pc
    685: 
    686: 
    687: def _tuck(fit, pc, covers, limb, gap=0.003, both=False, span=None):
    688:     """Draw a garment inside what covers it on a limb (a gauntlet, a boot): any of it within a cover's
    689:     span that reaches past the cover's inner face (by angle round the limb and distance along it) is
    690:     pulled in under it. covers: pieces named for their side (cuff_L), or, with both=True, pieces over
    691:     both limbs (the boots), split by their skin weights. span: only the cover's points this far along
    692:     the limb (a boot's foot is not the leg's business)."""
    693:     P = pc["pos"]
    694:     for side in ("L", "R"):
    695:         if both:
    696:             hit = lambda c: np.array([f"_{side}_" in n for n in c["jnames"]])
    697:             pts = [c["pos"][(hit(c)[c["J"]] * c["W"]).sum(1) > 0.5] for c in covers]
    698:         else:
    699:             pts = [c["pos"] for c in covers if c["material"].endswith(f"_{side}")]
    700:         if not pts or not sum(len(q) for q in pts):
    701:             continue
    702:         cs, _, cr, cphi, _ = _limb_frame(fit, side, np.concatenate(pts), limb)
    703:         if span is not None:
    704:             keep = (cs > span[0]) & (cs < span[1])
    705:             cs, cr, cphi = cs[keep], cr[keep], cphi[keep]
    706:         sb = np.linspace(cs.min(), cs.max(), 14)
    707:         pb = np.linspace(-np.pi, np.pi, 25)
    708:         cen = (pb[:-1] + pb[1:]) / 2
    709:         i_s = np.clip(np.digitize(cs, sb) - 1, 0, len(sb) - 2)
    710:         i_p = np.clip(np.digitize(cphi, pb) - 1, 0, len(pb) - 2)
    711:         grid = np.full((len(sb) - 1, len(pb) - 1), np.inf)
    712:         np.minimum.at(grid, (i_s, i_p), cr)                     # the cover's inner face
    713:         for a in range(grid.shape[0]):                          # fill gaps round the limb
    714:             ok = np.isfinite(grid[a])
    715:             grid[a] = np.interp(cen, cen[ok], grid[a][ok], period=2 * np.pi) if ok.any() else np.inf
    716:         hit = np.array([n in tuple(f"J_Bip_{side}_{b}" for b in LIMBS[limb][1:]) for n in pc["jnames"]])
    717:         sel = np.nonzero((hit[pc["J"]] * pc["W"]).sum(1) > 0.3)[0]
    718:         s, u, r, phi, _ = _limb_frame(fit, side, P[sel], limb)
    719:         a = np.clip(np.digitize(s, sb) - 1, 0, len(sb) - 2)
    720:         b = np.clip(np.digitize(phi, pb) - 1, 0, len(pb) - 2)
    721:         lim = grid[a, b] - gap
    722:         over = (s > sb[0]) & (s < sb[-1]) & (r > lim)
    723:         P[sel[over]] -= u[over] * (r[over] - lim[over])[:, None]
    724:     pc["nrm"] = O.vertex_normals(P, pc["tri"])
    725:     return pc
    726: 
    727: 
    728: def loose_sleeves(fit, shirt, ease=0.030, cuff=0.70, folds=6):
    729:     """Full sleeves after the Unicorn Overlord study: the shirt's own sleeves let out, little at the
    730:     shoulder and fullest round the elbow and above the gauntlet (the opposite of a bicep's shape, so
    731:     the arm never reads as muscle), with soft folds down the arm that deepen where the sleeve bags
    732:     into the cuff. Less on the side toward the body (the hanging arm's room), more behind.
    733:     cuff: the gauntlet's length as a share of the forearm (cuffs()); below its top the sleeve goes
    734:     back to the arm, and tuck_sleeves() then draws it inside. Changes `shirt` in place."""
    735:     s_c = 2.0 - cuff                                      # the gauntlet's top on the arm
    736:     return _let_out(fit, shirt, "arm", [-0.3, 0.0, 0.35, 0.75, 1.0, s_c - 0.14, s_c - 0.02, s_c + 0.10, 2.2],
    737:                     [0.0, 0.10, 0.32, 0.72, 0.92, 1.0, 1.0, 0.0, 0.0], ease, folds)
    738: 
    739: 
    740: def tuck_sleeves(fit, shirt, cuff_pcs, gap=0.003):
    741:     """Draw a sleeve inside its gauntlet (see _tuck)."""
    742:     return _tuck(fit, shirt, cuff_pcs, "arm", gap)
    743: 
    744: 
    745: def _leg_s(fit, y):
    746:     """A height on the (left) leg as _limb_frame's distance along it: 0 at the hip joint, 1 at the knee,
    747:     2 at the ankle (the reference pose stands straight)."""
    748:     B = fit.bone
    749:     h, k, a = (float(B[f"J_Bip_L_{n}"][1]) for n in LIMBS["leg"])
    750:     return (h - y) / (h - k) if y > k else 1 + (k - y) / (k - a)
    751: 
    752: 
    753: def flare_boots(fit, boots, y_top, ease=0.010):
    754:     """Boot tops that stand a little off the leg (leather, not a stocking), easing back over a third of
    755:     the shin. Changes `boots` in place."""
    756:     s_b = _leg_s(fit, y_top)
    757:     return _let_out(fit, boots, "leg", [s_b - 0.05, s_b + 0.01, s_b + 0.30, 2.2], [1.0, 1.0, 0.0, 0.0], ease, folds=5,
    758:                     toward=0.5, behind=0.0, fold_amp=(0.12, 0.0), size=0.42)
    759: 
    760: 
    761: def breeches(fit, trousers, boots, y_hem, y_boot, ease=0.040, folds=7):
    762:     """Baggy breeches after the study's soldiers: the trousers let out below the fauld's hem (y_hem),
    763:     fullest just above the boot top (y_boot) where they bag over it, less on the inner thigh, with
    764:     folds down the leg; the boots' tops flare a little, and the breeches are drawn inside them.
    765:     Changes `trousers` and `boots` in place."""
    766:     s_f, s_b = _leg_s(fit, y_hem), _leg_s(fit, y_boot)
    767:     flare_boots(fit, boots, y_boot)
    768:     _let_out(fit, trousers, "leg", [-0.3, s_f - 0.02, s_f + 0.16, 0.85, s_b - 0.12, s_b - 0.02, s_b + 0.10, 2.2],
    769:              [0.0, 0.12, 0.6, 0.92, 1.0, 1.0, 0.0, 0.0], ease, folds, toward=0.6, behind=0.1, fold_amp=(0.15, 0.25),
    770:              fold_from=0.5, size=0.42)
    771:     _tuck(fit, trousers, [boots], "leg", gap=0.004, both=True, span=(1.0, 1.95))
    772:     return trousers, boots
    773: 
    774: 
    775: def slim_under(fit, trousers, y_hem, pull=0.018, ramp=0.05):
    776:     """Trousers drawn in toward the thigh bones where a skirt hides them (above y_hem, easing back to
    777:     full width over `ramp` above the hem). A stiff skirt follows the hips more than the thighs, and in
    778:     a wide stance or a lunge the thighs swing out through it; slimmer under it, they clear it. The
    779:     skin under the trousers is culled, so nothing else shows. Changes `trousers` in place."""
    780:     P = trousers["pos"]
    781:     for side in ("L", "R"):
    782:         hit = np.array([n == f"J_Bip_{side}_UpperLeg" for n in trousers["jnames"]])
    783:         w = (hit[trousers["J"]] * trousers["W"]).sum(1)
    784:         sel = np.nonzero(w > 0.05)[0]
    785:         if not len(sel):
    786:             continue
    787:         _, u, r, _, _ = _limb_frame(fit, side, P[sel], "leg")
    788:         k = np.clip((P[sel, 1] - y_hem) / ramp, 0, 1)
    789:         k = k * k * (3 - 2 * k)
    790:         d = np.minimum(pull * k * np.clip(w[sel], 0, 1), np.maximum(r - 0.03, 0))
    791:         P[sel] -= u * d[:, None]
    792:     trousers["nrm"] = O.vertex_normals(P, trousers["tri"])
    793:     return trousers
    794: 
    795: 
    796: def breastplate(fit, under, role="steel", name="breastplate", y_top=None, y_bottom=None, plackart=True, keel=0.008,
    797:                 back=True, arm=54.0):
    798:     """A breastplate (and backplate) as outline plates: a scooped neckline, armholes cut away at the
    799:     sides, a slight point at the waist, a central ridge, rolled edges; a plackart over the belly.
    800:     arm: where the armhole's scoop begins (degrees round the torso from the front); larger keeps the
    801:     plate's full width up to the armpits instead of a bib over the middle of the chest."""
    802:     B = fit.bone
    803:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    804:     y_top = nk[1] - 0.05 if y_top is None else y_top
    805:     y_bottom = hips[1] + 0.03 if y_bottom is None else y_bottom
    806:     cz = float(hips[2])
    807:     tc = TorsoChart(under, y_bottom - 0.04, y_top + 0.04, cz=cz, du=2.5, dv=0.007)
    808:     span = y_top - y_bottom
    809:     top = lambda u: y_top - 0.035 * max(0.0, 1 - abs(u) / 34) ** 1.4 - 0.11 * span * max(0.0, (abs(u) - arm) / 42) ** 1.3
    810:     bottom = lambda u: y_bottom - 0.018 * max(0.0, 1 - abs(u) / 40) ** 1.5
    811:     ridge = lambda u, v, s, t: keel * math.exp(-(u / 9.0) ** 2) * math.sin(math.pi * min(1.0, t * 1.15))
    812:     front, fx = outline_plate(name, role, tc, -96, 96, bottom, top, offset=0.014, crown=0.010, flare=ridge, thickness=0.004,
    813:                               nu=72, nv=26, roll=0.0034, roll_edges=("top", "bottom"))
    814:     fit.bind(front, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips"), fallback="J_Bip_C_Chest")
    815:     out = [front] + [O.inherit(p, front) for p in fx]
    816:     if back:
    817:         btop = lambda u: y_top - 0.01 - 0.11 * span * max(0.0, (abs(((u % 360) - 180)) - (arm - 4)) / 44) ** 1.3
    818:         bk, bx = outline_plate(f"{name}_back", role, tc, 96, 264, lambda u: y_bottom, btop, offset=0.014, crown=0.006,
    819:                                thickness=0.004, nu=60, nv=22, roll=0.0034, roll_edges=("top", "bottom"))
    820:         fit.bind(bk, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips"), fallback="J_Bip_C_Chest")
    821:         out += [bk] + [O.inherit(p, bk) for p in bx]
    822:     if plackart:                                            # over the belly, its top rounded up to a point
    823:         ptop = lambda u: y_bottom + 0.36 * span - 0.10 * span * (abs(u) / 50) ** 1.6
    824:         pl, px = outline_plate(f"{name}_plackart", role, tc, -50, 50, bottom, ptop, offset=0.020, crown=0.008, flare=ridge,
    825:                                thickness=0.004, nu=40, nv=12, roll=0.0034, roll_edges=("top",),
    826:                                rivets=(0.05, 0.010, 0.0035), rivet_role=role)
    827:         fit.bind(pl, allow=("Spine", "Chest", "Hips"), fallback="J_Bip_C_Spine")
    828:         out += [pl] + [O.inherit(p, pl) for p in px]
    829:     return _group(out, "plate")
    830: 
    831: 
    832: def scale_pattern(w=256, h=128, cols=8):
    833:     """Overlapping round scales (a fauld), rows offset: each scale's lower edge as a dark arc."""
    834:     cv = Canvas(w, h, ss=2)
    835:     sw = w / cols
    836:     rows = int(h / (sw * 0.55)) + 2
    837:     for j in range(rows):
    838:         yy = j * sw * 0.55
    839:         for i in range(cols + 1):
    840:             xx = i * sw + (j % 2) * sw / 2
    841:             th = np.linspace(math.pi * 1.05, math.pi * 1.95, 12)
    842:             pts = [((xx + sw / 2 * math.cos(t)) / w, 1 - (yy - sw * 0.45 * math.sin(t)) / h) for t in th]
    843:             cv.line(np.array(pts), 1.6, "groove")
    844:     return cv.array()
    845: 
    846: 
    847: def skirt_cone(fit, under, y_top, y_hem, flare, cz=None, clear=None, gap=0.012, side=0.0):
    848:     """A skirt's cone: the waist's radius at y_top, flaring by `flare` down to y_hem. clear: a Surface
    849:     it must also stand outside of below its top (the seat and thighs: sized from the waist alone, a
    850:     seat that sits further out than the waist showed through the back), never narrowing going down,
    851:     by `gap`, plus `side` more at the hips' sides (where a wide stance swings the thighs out)."""
    852:     B = fit.bone
    853:     cz = float(B["J_Bip_C_Hips"][2]) if cz is None else cz
    854:     tc = TorsoChart(under, y_top - 0.05, y_top + 0.03, cz=cz, du=3.0, dv=0.01)
    855:     r0 = lambda u: float(tc.radius(u, y_top)) + 0.012
    856:     cone = lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_top - v) / (y_top - y_hem), 0, 1.3) ** 1.2
    857:     if clear is None:
    858:         return ConeChart(cone, cz=cz)
    859:     lc = TorsoChart(clear, y_hem - 0.03, y_top, cz=cz, du=3.0, dv=0.01)
    860:     us = np.arange(-180.0, 180.0, 3.0)
    861:     vs = np.arange(y_top, y_hem - 0.031, -0.01)                  # top down
    862:     need = np.nan_to_num(lc.radius(us[:, None], vs[None, :]), nan=0.0) + gap + side * np.sin(np.radians(us))[:, None] ** 2
    863:     top_c = float(clear.pos[np.unique(clear.tri), 1].max())
    864:     need[:, vs > top_c] = 0.0                     # the chart fills rows above what it measured: not there
    865:     need = np.maximum(need, cone(us[:, None], vs[None, :]))
    866:     # hanging from the waist: the tightest outline that starts at the waist and clears everything below
    867:     # (the upper concave hull down each line of the skirt); a skirt that stepped straight out to the seat
    868:     # stood off the back like a shelf
    869:     d = y_top - vs
    870:     for i in range(len(us)):
    871:         hull = [0]
    872:         for j in range(1, len(vs)):
    873:             while len(hull) >= 2:
    874:                 a, b = hull[-2], hull[-1]
    875:                 if (need[i, b] - need[i, a]) * (d[j] - d[a]) <= (need[i, j] - need[i, a]) * (d[b] - d[a]):
    876:                     hull.pop()
    877:                 else:
    878:                     break
    879:             hull.append(j)
    880:         need[i] = np.interp(d, d[hull], need[i, hull])
    881:     need = np.maximum.accumulate(need, axis=1)                   # never narrowing going down
    882:     need = (np.roll(need, 1, 0) + 2 * need + np.roll(need, -1, 0)) / 4
    883: 
    884:     def r(u, v):
    885:         u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))
    886:         iu = ((u + 180.0) / 3.0) % len(us)
    887:         i0 = np.floor(iu).astype(int) % len(us)
    888:         f = iu - np.floor(iu)
    889:         jv = np.clip((y_top - v) / 0.01, 0, len(vs) - 1)
    890:         j0 = np.clip(np.floor(jv).astype(int), 0, len(vs) - 2)
    891:         g = jv - j0
    892:         n = ((need[i0, j0] * (1 - g) + need[i0, j0 + 1] * g) * (1 - f)
    893:              + (need[(i0 + 1) % len(us), j0] * (1 - g) + need[(i0 + 1) % len(us), j0 + 1] * g) * f)
    894:         return np.maximum(cone(u, v), n)
    895:     return ConeChart(r, cz=cz)
    896: 
    897: 
    898: def scale_skirt(fit, under, y_top, y_hem, role="mail", name="fauld", flare=0.05, split=0.0, share=0.55, clear=None,
    899:                 side=0.0):
    900:     """A fauld of round scales on a cone from y_top to y_hem. share: how much of it stays with the hips
    901:     rather than the thighs (a wide stance needs it lower, or a forward thigh comes through the front).
    902:     clear: what it must stand outside of (the trousers; see skirt_cone)."""
    903:     cone = skirt_cone(fit, under, y_top, y_hem, flare, clear=clear, side=side)
    904:     u0, u1 = (split, 360 - split) if split else (-180, 180)          # closed at the back (179 left a slit)
    905:     hem = lambda u: y_hem + 0.008 * abs(math.sin(math.radians(u) * 22))     # the scales' scalloped edge
    906:     pc, _ = outline_plate(name, role, cone, u0, u1, hem, lambda u: y_top, offset=0.0, thickness=0.004, nu=120, nv=12,
    907:                           roll=0, pattern=(scale_pattern(), 0.34))
    908:     fit.bind(pc, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips")
    909:     stiffen(pc, fit, share=share)
    910:     return _group([pc], "mail")
    911: 
    912: 
    913: def pleated_skirt(fit, under, y_top, y_hem, role="signature", name="skirt_pleats", flare=0.09, pleats=26, depth=0.012,
    914:                   split=0.0):
    915:     cone = skirt_cone(fit, under, y_top, y_hem, flare)
    916:     u0, u1 = (split, 360 - split) if split else (-179, 179)
    917:     tri = lambda u: abs(((u * pleats / 360.0) % 1.0) * 2 - 1)               # a triangle wave: knife pleats
    918:     fl = lambda u, v, s, t: depth * (1 - t) ** 0.6 * (tri(u) - 0.5)
    919:     pc, _ = outline_plate(name, role, cone, u0, u1, lambda u: y_hem, lambda u: y_top, offset=0.002, flare=fl,
    920:                           thickness=0.004, nu=pleats * 8, nv=14, roll=0, trim=0.0)
    921:     fit.bind(pc, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips")
    922:     stiffen(pc, fit, share=0.5)
    923:     return _group([pc], "dress")
    924: 
    925: 
    926: def cuffs(fit, role="glove", name="cuff", length=0.38, flare=0.030, lift=0.010):
    927:     """Big flared gauntlet cuffs over the lower forearm (oversized, as the study's units wear them)."""
    928:     B = fit.bone
    929:     out = []
    930:     for side in ("L", "R"):
    931:         la, hd = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"]
    932:         fore = O.limb_surface(fit, (f"{side}_LowerArm",), side)
    933:         lc = LimbChart(fore, la, hd, front=(0, 0, -1))
    934:         pc, ex = outline_plate(f"{name}_{side}", role, lc, -180, 180, lambda u: 1.04, lambda u: 1.0 - length, offset=lift,
    935:                                flare=lambda u, v, s, t: flare * t ** 1.5, thickness=0.005, nu=40, nv=10, roll=0.004,
    936:                                roll_edges=("top",))
    937:         fit.bind(pc, rigid=f"J_Bip_{side}_LowerArm")
    938:         for p in ex:
    939:             fit.bind(p, rigid=f"J_Bip_{side}_LowerArm")
    940:         out += [pc] + ex
    941:     return _group(out, "gloves")
    942: 
    943: 
    944: def round_shield(fit, side="L", radius=0.24, wood="wood", rim="steel", name="shield"):
    945:     """A round wooden shield: planks (grooves), an iron rim and boss, strapped to the forearm."""
    946:     E, H = fit.bone[f"J_Bip_{side}_LowerArm"], fit.bone[f"J_Bip_{side}_Hand"]
    947:     ax = (H - E) / np.linalg.norm(H - E)
    948:     lat = np.array([-1.0 if side == "L" else 1.0, 0, 0.0])
    949:     lat -= ax * (lat @ ax)
    950:     lat /= np.linalg.norm(lat)
    951:     up, fw = -ax, np.cross(lat, -ax)
    952:     centre = E + ax * np.linalg.norm(H - E) * 0.5 + lat * 0.07
    953:     a = np.linspace(0, 2 * np.pi, 40, endpoint=False)
    954:     outline = [(radius * math.cos(x), radius * math.sin(x)) for x in a]
    955:     planks = [("line", [(x, -radius), (x, radius)], 0.0025, "groove") for x in np.linspace(-radius, radius, 7)[1:-1]]
    956:     face = flat_piece(name, wood, outline, centre, fw, up, thickness=0.014, decal=planks, px=900)
    957:     P = face["pos"]
    958:     d2 = ((P - centre) @ fw) ** 2 + ((P - centre) @ up) ** 2
    959:     P += lat[None] * (0.03 * (1 - d2 / radius ** 2))[:, None]          # a shallow dome
    960:     face["nrm"] = O.vertex_normals(P, face["tri"])
    961:     ring = np.array([centre + fw * x + up * y + lat * 0.008 for x, y in outline])
    962:     out = [face, O.pipe(f"{name}_rim", rim, ring, r=0.008, seg=6, closed=True)]
    963:     boss, _ = O.dome(f"{name}_boss", rim, centre + lat * 0.036, lat, up, 0.05, 0.03, rows=6)
    964:     out.append(boss)
    965:     _bind(fit, out, f"J_Bip_{side}_LowerArm")
    966:     return _group(out, "shield")
    967: 
    968: 
    969: def halberd(fit, length=2.1, grip=0.80, hand="R", name="halberd"):
    970:     """A halberd: a long haft, an axe blade with a back hook, a spike, langets and a butt."""
    971:     fist, fwd, side, flat, _ = _hand_frame(fit, hand)
    972:     start = fist - fwd * grip
    973:     out = [O.tube(f"{name}_haft", "wood", start, fwd, length, 0.014)]
    974:     top = start + fwd * length
    975:     blade = [(0.02, -0.10), (0.15, -0.13), (0.17, -0.02), (0.15, 0.09), (0.02, 0.05)]
    976:     hook = [(-0.02, -0.06), (-0.10, -0.04), (-0.12, 0.02), (-0.02, 0.01)]
    977:     spike = [(0.0, 0.0), (0.016, 0.03), (0.0, 0.26), (-0.016, 0.03)]
    978:     out.append(flat_piece(f"{name}_blade", "steel", blade, top - fwd * 0.08, side, fwd, thickness=0.007))
    979:     out.append(flat_piece(f"{name}_hook", "steel", hook, top - fwd * 0.08, side, fwd, thickness=0.007))
    980:     out.append(flat_piece(f"{name}_spike", "steel", spike, top - fwd * 0.02, side, fwd, thickness=0.008))
    981:     out.append(O.tube(f"{name}_langet", "steel", top - fwd * 0.30, fwd, 0.30, 0.017))
    982:     out.append(O.ball(f"{name}_butt", "steel", start - fwd * 0.012, 0.017, squash=(1, 1, 1.6)))
    983:     _bind(fit, out, f"J_Bip_{hand}_Hand")
    984:     return _group(out, "weapon")

agent

+12:04
reasoning

Reviewing the current state, focusing on specific code sections in vroid_portrait.py related to neutral expressions, face normals, and shadow cards, as well as outfit.py with knight dress and lord outfits. These specific edits require a surgical approach. The goal is to make well-tested, clean edits.

  • read_file{"EndLine":470,"Path":"~/work/lowmarch/tools/vroid_portrait.py","StartLine":370}

    input

    {
      "EndLine": 470,
      "Path": "~/work/lowmarch/tools/vroid_portrait.py",
      "StartLine": 370
    }

    result, 102 lines

    Showing lines 370-470 of 1407
    370:     return None
    371: 
    372: 
    373: def strip_blush(prims, roles, v, keep):
    374:     """VRoid's faces are painted with blush on the cheeks and an orange shadow round the eyes: young.
    375:     keep = 1 leaves it, 0 takes it back to the plain skin (dark painted marks, the lip line and the
    376:     nose, are left alone)."""
    377:     if keep >= 1:
    378:         return
    379:     src = face_texture(prims, roles, v)
    380:     if src is None:
    381:         return
    382:     tex = v.image(src).astype(float)
    383:     rgb = tex[..., :3]
    384:     lum = rgb.mean(-1)
    385:     opaque = tex[..., 3] > 200
    386:     base = np.median(rgb[opaque & (lum > np.percentile(lum[opaque], 40))], axis=0)
    387:     warm = (rgb[..., 0] - rgb[..., 2]) - (base[0] - base[2])               # redder than the skin
    388:     w = np.clip(warm / 35.0, 0, 1) * (lum > 0.72 * base.mean()) * opaque * (1 - keep)
    389:     rgb[:] = rgb * (1 - w[..., None]) + base * w[..., None]
    390:     v._img[src] = np.clip(tex, 0, 255).astype(np.uint8)
    391: 
    392: 
    393: def face_normals(prims, roles, lm, amount, hair=0.0, forward=0.0, pull=0.5, neck=None):
    394:     """Shade the head as one simple rounded form instead of from its mesh (the "vertex skeleton normals" of
    395:     DillonGoo's Yin and Yang rigs): each normal points away from a short vertical line inside the head, pulled
    396:     halfway toward the line's middle, so cheeks, nose and jaw take clean shadow shapes that hold at every angle
    397:     instead of patches that jump as the head turns. The face, its brows, lines and mouth and the skull take it in
    398:     full (`amount`); the neck fades back to its own normals over 3 cm under the chin; hair takes `hair`, fading out
    399:     below the jaw. Then 5 rounds of smoothing over each mesh's neighbours, as the rig does. `forward`: where the
    400:     line sits, as a share of the head's depth in front of its middle. The rig's 0.13 shades too much of a VRoid face
    401:     (flatter than Yin's) under the armory's key; 0.0 keeps the front lit and shades the far jaw and the neck.
    402:     `pull`: how far toward the line's middle the normals point (0 = a capsule round the line, 1 = a sphere round its
    403:     middle). Hair is off by default: in the painted renderer it flattens the strands into one plastic sheen."""
    404:     if amount <= 0 and hair <= 0:
    405:         return
    406:     chin_y = lm["chin"][1]
    407:     skin = np.concatenate([p["pos"][np.unique(p["tri"])] for p, r in zip(prims, roles) if r in ("face", "body")])
    408:     mid = skin[(np.abs(skin[:, 0]) < 0.03) & (skin[:, 1] > lm["eye_y"])]
    409:     crown, front, back = mid[:, 1].max(), lm["nose"][2], mid[:, 2].max()     # the face looks toward -z
    410:     tall = crown - chin_y
    411:     line_z = (front + back) / 2 - forward * (back - front)
    412:     y0, y1 = chin_y - 0.31 * tall, crown - 0.02 * tall                          # from under the jaw to near the crown
    413:     frame = neck_frame(prims, roles, neck) if neck is not None else None
    414:     for p, r in zip(prims, roles):
    415:         y = p["pos"][:, 1]
    416:         wn = None
    417:         if r in ("face", "brow", "line", "mouth"):
    418:             w = np.full(len(y), amount)
    419:         elif r == "body":
    420:             w = amount * np.clip((y - (chin_y - 0.03)) / 0.03, 0, 1)
    421:             # the neck below: a smooth cylinder round its line (the rig's second skeleton), fading out at its base
    422:             if frame is not None:
    423:                 A, u, rad = frame
    424:                 rel = p["pos"] - A
    425:                 cyl = rel - np.outer(rel @ u, u)
    426:                 radial = np.linalg.norm(cyl, axis=1)
    427:                 wn = (amount - w) * np.clip((y - (A[1] - 0.01)) / 0.025, 0, 1) * \
    428:                     np.clip((1.6 * rad - radial) / (0.4 * rad), 0, 1)
    429:         elif r == "hair" and hair > 0:
    430:             w = hair * np.clip((y - (chin_y - 0.10)) / 0.10, 0, 1)
    431:         else:
    432:             continue
    433:         if not (w > 0).any() and (wn is None or not (wn > 0).any()):
    434:             continue
    435:         q = np.clip(y, y0, y1)
    436:         target = np.stack([np.zeros(len(y)), q + pull * ((y0 + y1) / 2 - q), np.full(len(y), line_z)], -1)
    437:         proxy = p["pos"] - target
    438:         proxy /= np.maximum(np.linalg.norm(proxy, axis=1, keepdims=True), 1e-9)
    439:         n = (1 - w[:, None]) * p["nrm"] + w[:, None] * proxy
    440:         if wn is not None:
    441:             cyl /= np.maximum(np.linalg.norm(cyl, axis=1, keepdims=True), 1e-9)
    442:             n += wn[:, None] * (cyl - p["nrm"])
    443:             w = w + wn
    444:         n /= np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-9)
    445:         t = p["tri"]
    446:         a = np.concatenate([t[:, 0], t[:, 1], t[:, 2], t[:, 1], t[:, 2], t[:, 0]])
    447:         b = np.concatenate([t[:, 1], t[:, 2], t[:, 0], t[:, 0], t[:, 1], t[:, 2]])
    448:         act = w > 0
    449:         for _ in range(5):
    450:             acc = n.copy()
    451:             np.add.at(acc, a, n[b])
    452:             acc /= np.maximum(np.linalg.norm(acc, axis=1, keepdims=True), 1e-9)
    453:             n = np.where(act[:, None], acc, n)
    454:         p["nrm"] = n
    455: 
    456: 
    457: def eye_closure(mo):
    458:     """How closed each eye is (0 open, 1 shut), from the expression shapes: {"L": c, "R": c}."""
    459:     both = sum(mo.get(k, 0.0) for k in ("Fcl_EYE_Close", "Fcl_EYE_Joy", "Fcl_ALL_Joy"))
    460:     return {s_: both + sum(mo.get(f"Fcl_EYE_{k}{s_}", 0.0) for k in ("Close_", "Joy_", "Close@", "Joy@"))
    461:             for s_ in ("L", "R")}
    462: 
    463: 
    464: def hide_closed_irises(mo, further=None):
    465:     """A closed eye hides its iris and highlight. On a blended face the iris can sit a little in front of where the
    466:     closing lids meet, so a strip of it shows through a closed (joy, wink) eye; VRoid's Iris_Hide and Highlight_Hide
    467:     shapes are added per eye as it closes past 70%. further: {side: extra close} for a shut eye whose lids stop short
    468:     of each other (measured by `lid_gap`)."""
    469:     out = dict(mo)
    470:     for side, c in eye_closure(mo).items():
  • read_file{"EndLine":700,"Path":"~/work/lowmarch/tools/vroid_portrait.py","StartLine":630}

    input

    {
      "EndLine": 700,
      "Path": "~/work/lowmarch/tools/vroid_portrait.py",
      "StartLine": 630
    }

    result, 72 lines

    Showing lines 630-700 of 1407
    630:         F = face["pos"][np.unique(face["tri"])]
    631:         ang = np.arctan2(F[:, 0] - cx, -(F[:, 2] - cz))                         # 0 = the front (-z)
    632:         far = np.hypot(F[:, 0] - cx, F[:, 2] - cz) > 0.6 * rad
    633:         ths = np.radians(np.linspace(-50, 50, 37))                              # stops short of the jaw's angle
    634:         jaw = np.array([F[far & (np.abs(ang - th) < np.radians(4)), 1].min()
    635:                         if (far & (np.abs(ang - th) < np.radians(4))).any() else np.nan for th in ths])
    636:         ok = ~np.isnan(jaw)
    637:         jaw = np.interp(ths, ths[ok], jaw[ok])
    638:         jaw = np.convolve(np.pad(jaw, 3, mode="edge"), np.ones(7) / 7, mode="valid")
    639:         cols = []
    640:         for th, jy in zip(ths, jaw):
    641:             d = np.array([np.sin(th), 0.0, -np.cos(th)])                      # outward
    642:             top = jy - 0.002                                                     # just under the jaw: hidden by it
    643:             bottom = top - span * (0.03 + 0.21 * (1 - (th / np.radians(50)) ** 2))   # deepest under the chin, ends in points
    644:             col = []
    645:             for k, y in enumerate(np.linspace(top, bottom, 8)):
    646:                 o = axis_at(A, u, y)
    647:                 t = neck.cast(o, d, rmax=0.2, far=False)
    648:                 if np.isnan(t):
    649:                     break
    650:                 col.append(o + d * (t + 0.0008 + 0.0025 * (1 - k / 7)))      # further off at the top: the jaw stays behind
    651:             if len(col) == 8:
    652:                 cols.append(col)
    653:         if len(cols) >= 3:
    654:             out.append((_shadow_card("chin", body, np.array(cols)), "shadow"))
    655:     if face is not None:                                    # under the nose tip: flat on top, rounded below
    656:         fs = Surface(face["pos"], face["tri"])
    657:         nose = lm["nose"]
    658:         w, h = 0.055 * span, 0.05 * span
    659:         y_t = nose[1] - 0.015 * span
    660:         zf = face["pos"][:, 2].min() - 0.05
    661:         cols = []
    662:         for x in np.linspace(-w, w, 15):
    663:             col = []
    664:             for t in np.linspace(0, 1, 4):
    665:                 o = np.array([nose[0] + x, y_t - t * h * np.sqrt(max(0.0, 1 - (x / w) ** 2)), zf])
    666:                 tt = fs.cast(o, np.array([0.0, 0.0, 1.0]), rmax=0.3, far=False)
    667:                 if np.isnan(tt):
    668:                     break
    669:                 col.append(o + np.array([0.0, 0.0, tt - 0.0005]))
    670:             if len(col) == 4:
    671:                 cols.append(col)
    672:         if len(cols) >= 3:
    673:             out.append((_shadow_card("nose", face, np.array(cols)), "shadow"))
    674:     return out
    675: 
    676: 
    677: def face_lines(prims, roles, v, amount):
    678:     """Age, drawn the way the study draws it on otherwise young anime faces: a few thin lines
    679:     (from the nose's wing round the mouth, under the eyes, crow's feet, a frown between the brows,
    680:     down from the mouth's corners), darker and more of them as `amount` (0..1) rises. Each stroke is
    681:     laid out in 3D from the face's landmarks, dropped onto the face from the front, and painted into a
    682:     copy of the face texture (which the renderers multiply into the skin)."""
    683:     if amount <= 0:
    684:         return
    685:     from PIL import Image, ImageDraw
    686:     from fitting import Surface
    687:     lm = landmarks(prims, roles)
    688:     face = [p for p, r in zip(prims, roles) if r == "face" and len(p["tri"])]
    689:     if not face:
    690:         return
    691:     off = np.cumsum([0] + [len(p["pos"]) for p in face])
    692:     pos = np.concatenate([p["pos"] for p in face])
    693:     uv = np.concatenate([p["uv"] for p in face])
    694:     tri = np.concatenate([p["tri"] + off[i] for i, p in enumerate(face)])
    695:     surf = Surface(pos, tri)
    696: 
    697:     def verts(*rs):
    698:         return np.concatenate([p["pos"][np.unique(p["tri"])] for p, r in zip(prims, roles) if r in rs])
    699:     iris = verts("iris")
    700:     mouth = verts("mouth")