agent

+4:17
reasoning

Initial investigation focuses on tools/outfit.py, specifically lines 1267-1272. Further examination reveals additional files: tools/mobs.py and tools/gear.py, which appear relevant to the ongoing task.

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

    input

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

    result, 301 lines

    Showing lines 1-300 of 311
    1: """Common enemy units: one costume per class, built from gear.py on any base body. Generic but detailed:
    2: layered padding, mail and plate, riveted straps, an army colour on the cloth and shields (portrait
    3: guide, lesson 15). Pair each with a build and a face from gear.BUILDS / gear.FACES in the cast.
    4: """
    5: import numpy as np
    6: 
    7: import outfit as O
    8: import gear as G
    9: from fitting import Surface, merge_surfaces
    10: from vrm import bone_weight
    11: 
    12: 
    13: def _base(fit, shirt="padding", legs="cloth", boots="boot", gloves="glove", knee=None, shirt_subdiv=0, boot_top=None):
    14:     """Under layers every class shares: a shirt with sleeves to the wrist, trousers, boots to below
    15:     the knee (or to boot_top: above the knee, they take the thigh too), gloves. Returns the pieces and
    16:     the shirt (what coats are fitted over)."""
    17:     B = fit.bone
    18:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    19:     knee = B["J_Bip_L_LowerLeg"][1] if knee is None else knee
    20: 
    21:     def cuff(side):
    22:         a, h = B[f"J_Bip_{side}_LowerArm"], B[f"J_Bip_{side}_Hand"]
    23:         n = (h - a) / np.linalg.norm(h - a)
    24:         return n, n @ (h - n * 0.02)
    25:     torso = ("Spine", "Chest", "UpperChest", "Bust", "Shoulder", "UpperArm", "LowerArm", "Neck", "Hips")
    26:     # the neckline: a straight hem, lower at the throat than at the back of the neck (a level cut of
    27:     # whole triangles left a saw-tooth edge, and a big trapezius showed above it)
    28:     nh = np.array([0.0, 1.0, -0.3]) / np.linalg.norm([0.0, 1.0, -0.3])
    29:     neckline = (nh, float(nh @ (nk + np.array([0.0, 0.012, 0.0]))))
    30:     s = O.wrap(fit, "shirt", shirt, torso, offset=0.006, exclude=("UpperLeg",), y_min=hips[1] - 0.04,
    31:                y_max=nk[1] + 0.05, cut=neckline, hems=[cuff("L"), cuff("R"), neckline], subdiv=shirt_subdiv)
    32:     t = O.wrap(fit, "trousers", legs, ("Hips", "UpperLeg", "LowerLeg"), offset=0.007, y_max=hips[1] + 0.02, subdiv=1)
    33:     top = knee - 0.07 if boot_top is None else boot_top
    34:     b = O.wrap(fit, "boots", boots, ("LowerLeg", "Foot", "ToeBase") + (("UpperLeg",) if top > knee else ()), offset=0.015,
    35:                y_max=top, subdiv=1, hems=[((0, 1, 0), top - 0.005)])
    36:     g = O.wrap(fit, "gloves", gloves, ("Hand", "Thumb", "Index", "Middle", "Ring", "Little"), offset=0.003, min_w=0.3, smooth=4)
    37:     out = [p for p in (s, t, b, g) if p is not None]
    38:     for p, grp in zip(out, ("doublet", "trousers", "boots", "gloves")):
    39:         p["group"] = grp
    40:     return out, s, t, b
    41: 
    42: 
    43: def underwear(fit, band=False):
    44:     """Plain shorts (and a chest band with band=True) for inspecting bare bodies (the armory page, built
    45:     in the T-pose): hips to mid-thigh, close to the skin."""
    46:     B = fit.bone
    47:     hips, knee = B["J_Bip_C_Hips"][1], B["J_Bip_L_LowerLeg"][1]
    48:     lo, hi = (hips + knee) / 2 + 0.03, hips + 0.07
    49:     # all the skin between the hems but the arms' (they hang there in the fitting pose): taking only skin
    50:     # weighted to the hips, legs and spine left holes where MakeHuman weights it to the chest or elsewhere
    51:     out = [O.wrap(fit, "shorts", "cloth", ("J_",), offset=0.004, y_min=lo - 0.04, y_max=hi + 0.04, subdiv=1,
    52:                   exclude=("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little"),
    53:                   hems=[((0, 1, 0), hi - 0.005), ((0, -1, 0), -(lo + 0.005))], refloor=True, clamp=True)]
    54:     if band:
    55:         ch, uc = B["J_Bip_C_Chest"][1], B["J_Bip_C_UpperChest"][1]
    56:         blo, bhi = ch - 0.01, uc + 0.06
    57:         # like the shorts: triangles past the hems taken and clamped onto them (dropping them notched the
    58:         # top edge into steps on broad backs), every bone but the arms'
    59:         out.append(O.wrap(fit, "band", "cloth", ("J_",), offset=0.004, y_min=blo - 0.03, y_max=bhi + 0.03, subdiv=1,
    60:                           exclude=("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little"),
    61:                           hems=[((0, 1, 0), bhi - 0.005), ((0, -1, 0), -(blo + 0.005))], refloor=True, clamp=True))
    62:     out = [p for p in out if p is not None]
    63:     for p in out:
    64:         p["group"] = "underwear"
    65:     fit.keep_skin = ("J_",)                          # bare everywhere else: keep all the skin (VRoid 2 weights some to J_Sec_ bones)
    66:     # but not the skin well inside the shorts: on fitted bodies (tools/fit.py) it came through the waistband.
    67:     # Never the arms', which hang beside the hips in the fitting pose
    68:     arms = ("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little")
    69:     fit.drop_skin = lambda p: ((p["pos"][:, 1] > lo + 0.015) & (p["pos"][:, 1] < hi - 0.015)
    70:                                & (bone_weight(p, arms) < 0.05))
    71:     return out
    72: 
    73: 
    74: def underwear_f(fit):
    75:     return underwear(fit, band=True)
    76: 
    77: 
    78: def _under(shirt):
    79:     return Surface(*O.without(shirt, ("Shoulder", "UpperArm", "LowerArm", "Hand")))
    80: 
    81: 
    82: def _surf(pcs, *names, prefix=False):
    83:     sel = [p for p in pcs if (p["material"].startswith(tuple("OUTFIT_" + n for n in names)) if prefix
    84:                               else p["material"] in tuple("OUTFIT_" + n for n in names))]
    85:     return merge_surfaces(*[(p["pos"], p["tri"]) for p in sel])
    86: 
    87: 
    88: def soldier(fit, legs="breeches"):
    89:     """Halberd infantry, after the study's Soldier: a kettle hat, a doublet in the army colour with
    90:     full sleeves bagging into gauntlets that reach almost to the elbow, a short breastplate with a
    91:     plackart (full width to the armpits), a fauld of round scales to mid-thigh, a belt, a halberd
    92:     held in both hands (the cast's polearm stance, tools/clips.py). No puff or band on the upper arm:
    93:     the study's soldiers have neither, and on a real arm a puff read as a bicep.
    94:     legs: "breeches" (baggy, bagging over calf boots: the study's men) or "tights" (with boots to
    95:     above the knee: the study's women)."""
    96:     B = fit.bone
    97:     hips = B["J_Bip_C_Hips"]
    98:     knee = B["J_Bip_L_LowerLeg"][1]
    99:     gauntlet = 0.70                                         # of the forearm, from the wrist
    100:     y_hem = hips[1] - 0.20                                  # the fauld's
    101:     boot_top = knee + 0.08 if legs == "tights" else knee - 0.07
    102:     out, shirt, trousers, boots = _base(fit, shirt="signature", legs="cloth", boots="boot", shirt_subdiv=1,
    103:                                         boot_top=boot_top)
    104:     G.loose_sleeves(fit, shirt, cuff=gauntlet)
    105:     if legs == "breeches":
    106:         G.breeches(fit, trousers, boots, y_hem, boot_top - 0.005)
    107:     else:
    108:         G.flare_boots(fit, boots, boot_top - 0.005, ease=0.008)
    109:     under = _under(shirt)
    110:     out += G.breastplate(fit, under, arm=64.0)
    111:     plate = _surf(out, "breastplate", prefix=True)
    112:     # the guard's wide stance: the fauld follows the thighs closely and clears the seat
    113:     out += G.scale_skirt(fit, under, hips[1] + 0.06, y_hem, role="mail", share=0.15,
    114:                          clear=Surface(trousers["pos"], trousers["tri"]))
    115:     G.slim_under(fit, trousers, y_hem)                      # and what it hides can't come through it
    116:     belt, front = O.belt(fit, "belt", "leather", plate, hips[1] + 0.05, height=0.034, offset=0.004)
    117:     out.append(belt)
    118:     cuffs = G.cuffs(fit, length=gauntlet, flare=0.034)
    119:     G.tuck_sleeves(fit, shirt, cuffs)
    120:     out += cuffs
    121:     out += G.coif(fit, role="padding")
    122:     out += G.helmet(fit, "kettle")
    123:     out += G.halberd(fit, grip=0.50)                         # the rear hand near the butt, as the study holds it
    124:     return out
    125: 
    126: 
    127: def soldier_f(fit):
    128:     """The soldier as the study draws its women: tights and boots to above the knee."""
    129:     return soldier(fit, legs="tights")
    130: 
    131: 
    132: def fighter(fit):
    133:     """Sword and round shield, after the study's Fighter: a kettle hat worn low, a quilted gambeson with
    134:     full sleeves, a breastplate, lamed spaulders, a knife-pleated skirt in the army colour, greaves, a
    135:     wooden round shield, an arming sword."""
    136:     B = fit.bone
    137:     hips = B["J_Bip_C_Hips"]
    138:     knee = B["J_Bip_L_LowerLeg"][1]
    139:     out, shirt, trousers, boots = _base(fit, shirt="padding", legs="cloth", boots="boot")
    140:     under = _under(shirt)
    141:     out += G.quilted(fit, under, role="padding", y_hem=hips[1] - 0.02, flare=0.02, sleeve_end=0.95)
    142:     gam = _surf(out, "gambeson", "gambeson_skirt")
    143:     out += G.pleated_skirt(fit, gam, hips[1] + 0.05, hips[1] - 0.30, role="signature")
    144:     out += G.breastplate(fit, gam)
    145:     plate_body = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") in ("plate", "padding")], (fit.pos, fit.tri))
    146:     for side in ("L", "R"):
    147:         sp, rims = O.pauldron(fit, f"spaulder_{side}", "steel", plate_body, side=side,
    148:                               lames=((0, 56, 0.024, 0.032), (47, 73, 0.022, 0.030), (65, 91, 0.020, 0.028)), spread=105)
    149:         out += G._group(sp + [O.inherit(O.pipe(f"spaulder_{side}_roll{k}", "steel", r_, r=0.0028), pc)
    150:                               for k, (pc, r_) in enumerate(zip(sp, rims))], "plate")
    151:         ll, ft = B[f"J_Bip_{side}_LowerLeg"], B[f"J_Bip_{side}_Foot"]
    152:         top = (knee - 0.085 - ll[1]) / (ft[1] - ll[1])
    153:         gv, rims = O.limb_lames(fit, f"greave_{side}", "steel", O.side_of(boots, side), ll, ft, ((top, 0.80, 0.008, 0.011),),
    154:                                 rmax=0.11)
    155:         fit.bind(gv[0], rigid=f"J_Bip_{side}_LowerLeg")
    156:         out += G._group(gv + [O.inherit(O.pipe(f"greave_{side}_roll{k}", "steel", r_, r=0.0028), gv[0])
    157:                               for k, r_ in enumerate(rims[0])], "plate")
    158:     belt, front = O.belt(fit, "belt", "leather", _surf(out, "breastplate", prefix=True), hips[1] + 0.05, height=0.036,
    159:                          offset=0.004)
    160:     out.append(belt)
    161:     out += G.cuffs(fit, length=0.32)
    162:     out += G.coif(fit, role="padding")
    163:     out += G.helmet(fit, "kettle", lift=0.032)
    164:     out += G.round_shield(fit)
    165:     out += O.sword(fit, "R", blade_len=0.70, hilt="metal")
    166:     return out
    167: 
    168: 
    169: def housecarl(fit):
    170:     """An axeman in mail, after the study's Housecarl: a nasal helm over a mail coif, a mail hauberk to
    171:     mid-thigh over the gambeson, a short cape in the army colour, a wide belt, big cuffs, a long axe."""
    172:     B = fit.bone
    173:     hips = B["J_Bip_C_Hips"]
    174:     out, shirt, trousers, boots = _base(fit, shirt="padding", legs="cloth", boots="boot")
    175:     under = _under(shirt)
    176:     out += G.quilted(fit, under, role="padding", y_hem=hips[1] - 0.26, sleeve_end=0.95)
    177:     gam = _surf(out, "gambeson", "gambeson_skirt")
    178:     out += G.mail_shirt(fit, gam, y_hem=hips[1] - 0.16)
    179:     mail = _surf(out, "hauberk", prefix=True)
    180:     belt, front = O.belt(fit, "belt", "leather", mail, hips[1] + 0.04, height=0.05, offset=0.006)
    181:     out.append(belt)
    182:     body = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") in ("mail", "padding")], (fit.pos, fit.tri))
    183:     mt, grid, hood = O.mantle(fit, "cape", "signature", body)
    184:     out += G._group([mt], "mantle")
    185:     out += G.cuffs(fit, length=0.34, flare=0.036)
    186:     out += G.coif(fit, role="mail")
    187:     out += G.helmet(fit, "nasal")
    188:     out += G.axe(fit, haft=1.30, blade=0.26, grip=0.60)
    189:     return out
    190: 
    191: 
    192: def hoplite(fit):
    193:     """Heavy infantry: a close helm, plate over mail (riveted coat of plates, spaulders, greaves), a
    194:     tabard in the army colour, a tall tower shield and a spear."""
    195:     B = fit.bone
    196:     hips, nk = B["J_Bip_C_Hips"], B["J_Bip_C_Neck"]
    197:     knee = B["J_Bip_L_LowerLeg"][1]
    198:     out, shirt, trousers, boots = _base(fit, shirt="padding", legs="cloth", boots="boot")
    199:     under = Surface(*O.without(shirt, ("Shoulder", "UpperArm", "LowerArm", "Hand")))
    200:     out += G.quilted(fit, under, role="padding", y_hem=hips[1] - 0.20, sleeve_end=0.95)
    201:     gam = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p["material"] in ("OUTFIT_gambeson", "OUTFIT_gambeson_skirt")])
    202:     out += G.mail_shirt(fit, gam, y_hem=hips[1] - 0.20)
    203:     mail = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p["material"].startswith("OUTFIT_hauberk")])
    204:     out += G.riveted_vest(fit, mail, role="signature", rivet_role="steel")
    205:     plate_body = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") in ("plate", "mail", "padding")],
    206:                                 (fit.pos, fit.tri))
    207:     for side in ("L", "R"):
    208:         sp, rims = O.pauldron(fit, f"spaulder_{side}", "steel", plate_body, side=side,
    209:                               lames=((0, 56, 0.024, 0.032), (47, 73, 0.022, 0.030), (65, 91, 0.020, 0.028)), spread=110)
    210:         out += sp + [O.inherit(O.pipe(f"spaulder_{side}_roll{k}", "steel", r_, r=0.0028), pc) for k, (pc, r_) in enumerate(zip(sp, rims))]
    211:         ll, ft = B[f"J_Bip_{side}_LowerLeg"], B[f"J_Bip_{side}_Foot"]
    212:         top = (knee - 0.085 - ll[1]) / (ft[1] - ll[1])
    213:         gv, rims = O.limb_lames(fit, f"greave_{side}", "steel", O.side_of(boots, side), ll, ft, ((top, 0.80, 0.008, 0.011),),
    214:                                 rmax=0.11)
    215:         fit.bind(gv[0], rigid=f"J_Bip_{side}_LowerLeg")
    216:         out += gv + [O.inherit(O.pipe(f"greave_{side}_roll{k}", "steel", r_, r=0.0028), gv[0]) for k, r_ in enumerate(rims[0])]
    217:     for p in out:
    218:         if p["material"].startswith(("OUTFIT_spaulder", "OUTFIT_greave")):
    219:             p["group"] = "plate"
    220:     belt, front = O.belt(fit, "belt", "leather", merge_surfaces(*[(p["pos"], p["tri"]) for p in out
    221:                                                                    if p["material"].startswith("OUTFIT_brigandine_front")
    222:                                                                    or p["material"] == "OUTFIT_hauberk"]),
    223:                          hips[1] + 0.03, height=0.04, offset=0.008)
    224:     out.append(belt)
    225:     over = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") in ("plate", "mail")], (fit.pos, fit.tri))
    226:     mt, grid, hood = O.mantle(fit, "capelet", "signature", over)
    227:     out += G._group([mt, hood], "mantle")
    228:     out += G.cuffs(fit, role="steel", length=0.36, flare=0.026)
    229:     out += G.coif(fit, role="mail")
    230:     out += G.helmet(fit, "close")
    231:     emblem = [("poly", [(-0.09, 0.22), (0.09, 0.22), (0.09, -0.04), (0.0, -0.18), (-0.09, -0.04)], "paint"),
    232:               ("line", [(-0.13, 0.31), (0.13, 0.31)], 0.012, "paint")]
    233:     out += G.shield(fit, "heater", role="steel", width=0.56, height=0.92, curve=0.45, emblem=emblem)
    234:     out += G.spear(fit, length=2.2)
    235:     return out
    236: 
    237: 
    238: def berserker(fit):
    239:     """A huge axeman: bare arms, a fur mantle over a leather harness, wide belt, a two-bitted great axe."""
    240:     B = fit.bone
    241:     hips = B["J_Bip_C_Hips"]
    242:     out, shirt, trousers, boots = _base(fit, shirt="leather", legs="cloth", boots="fur")
    243:     # a sleeveless jerkin: the shirt's arms come off and the arms stay bare
    244:     shirt["tri"] = O.without(shirt, ("UpperArm", "LowerArm", "Hand"))[1]
    245:     fit.keep_skin = ("UpperArm", "LowerArm", "Shoulder")
    246:     under = Surface(*O.without(shirt, ("Shoulder", "UpperArm", "LowerArm", "Hand")))
    247:     out += G.riveted_vest(fit, under, role="leather", rivet_role="steel")
    248:     shoulders = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") in ("plate",)], (shirt["pos"], shirt["tri"]),
    249:                                (fit.pos, fit.tri))
    250:     mt, grid, hood = O.mantle(fit, "mantle", "fur", shoulders)
    251:     out += [mt]
    252:     belt, front = O.belt(fit, "belt", "leather", under, hips[1] + 0.04, height=0.06, offset=0.016)
    253:     out.append(belt)
    254:     out += G.axe(fit, haft=1.15, blade=0.30, double=True, grip=0.45)
    255:     return out
    256: 
    257: 
    258: def hunter(fit):
    259:     """A woodland archer: a cloth hood and short cape, a leather jerkin over a linen shirt, a bow in the
    260:     lowered hand, a quiver on the back."""
    261:     B = fit.bone
    262:     hips = B["J_Bip_C_Hips"]
    263:     out, shirt, trousers, boots = _base(fit, shirt="linen", legs="cloth", boots="boot")
    264:     under = Surface(*O.without(shirt, ("Shoulder", "UpperArm", "LowerArm", "Hand")))
    265:     out += G.riveted_vest(fit, under, name="jerkin", role="leather", rivet_role="leather", y_bottom=hips[1] - 0.06)
    266:     belt, front = O.belt(fit, "belt", "leather", under, hips[1] + 0.03, height=0.03, offset=0.020)
    267:     out.append(belt)
    268:     body = merge_surfaces(*[(p["pos"], p["tri"]) for p in out if p.get("group") == "plate"], (shirt["pos"], shirt["tri"]),
    269:                           (fit.pos, fit.tri))
    270:     mt, grid, _ = O.mantle(fit, "cape", "signature", body)
    271:     out.append(mt)
    272:     out += G.hood(fit, role="signature", lift=0.022)
    273:     out += G.bow(fit)
    274:     out += G.quiver(fit)
    275:     return out
    276: 
    277: 
    278: def thief(fit):
    279:     """A light skirmisher: a scarf over the lower face, a short leather jerkin, a sash, a dagger."""
    280:     B = fit.bone
    281:     hips = B["J_Bip_C_Hips"]
    282:     out, shirt, trousers, boots = _base(fit, shirt="cloth", legs="cloth", boots="boot")
    283:     under = Surface(*O.without(shirt, ("Shoulder", "UpperArm", "LowerArm", "Hand")))
    284:     out += G.riveted_vest(fit, under, name="jerkin", role="leather", rivet_role="steel", y_bottom=hips[1] - 0.02)
    285:     sash, front = O.belt(fit, "sash", "signature", under, hips[1] + 0.05, height=0.05, offset=0.022, tilt=0.02)
    286:     out.append(sash)
    287:     # no hood: her own bob shows (a hood over it either bulged or let it through); the scarf masks her face
    288:     ch = __import__("hair").head_chart(fit)               # a scarf over the nose and mouth
    289:     from plates import outline_plate
    290:     scarf, _ = outline_plate("scarf", "cloth", ch, -100, 100, lambda u: 150.0, lambda u: 104.0 - 6 * (abs(u) / 100) ** 2,
    291:                              offset=0.012, thickness=0.004, nu=40, nv=10, roll=0)
    292:     fit.bind(scarf, rigid="J_Bip_C_Head")
    293:     scarf["group"] = "hood"
    294:     out.append(scarf)
    295:     out += G.dagger(fit)
    296:     return out
    297: 
    298: 
    299: def witch(fit):
    300:     """A caster: a long robe with bell sleeves and a gold border, a sash, a tall pointed hat, a staff."""
  • read_file{"EndLine":300,"Path":"~/work/lowmarch/tools/gear.py","StartLine":1}

    input

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

    result, 301 lines

    Showing lines 1-300 of 984
    1: """Gear for generic units (the enemy soldiers): helmets, hoods and coifs, quilted coats, mail,
    2: riveted vests, shields and weapons, built on the plate kit (plates.py) and the head chart (hair.py).
    3: Each function returns pieces bound to the skeleton; a class costume (mobs.py) combines them.
    4: 
    5: Builds and faces for generic units are presets of the body's shape controls (BUILDS, FACES), so the
    6: same costume dresses a slim young soldier or a huge brute.
    7: """
    8: import math
    9: 
    10: import numpy as np
    11: 
    12: import outfit as O
    13: from fitting import Surface
    14: from plates import TorsoChart, LimbChart, ConeChart, outline_plate, stiffen, flat_piece, taper, Canvas
    15: from hair import head_chart
    16: 
    17: # ---- builds and faces: presets of vroid_portrait's shape controls ------------------------------------
    18: BUILDS = {
    19:     "slim": dict(chest=0.95, torso=0.94, arms=0.94, legs=0.94, neck=0.95),
    20:     "average": dict(),
    21:     "athletic": dict(chest=1.06, arms=1.07, legs=1.04, neck=1.08, shoulder_w=0.010),
    22:     "stocky": dict(chest=1.18, torso=1.24, arms=1.18, legs=1.16, neck=1.28, shoulder_w=0.018, leg_len=0.95, height=0.97),
    23:     "huge": dict(chest=1.34, torso=1.32, arms=1.40, legs=1.32, neck=1.55, hands=1.22, shoulder_w=0.042, height=1.12,
    24:                  head=0.92),
    25: }
    26: FACES = {   # 3D-strength values (the sculpt moves anatomical points by millimetres per unit)
    27:     "bare": dict(),     # no sculpt here: the head is sculpted in its own file (tools/heads.py, the armory)
    28:     "young": dict(face_len=-0.04, jaw=-0.4, chin_len=-0.5, eye=1.04),
    29:     "plain": dict(face_len=0.05, jaw=0.6, brow_ridge=0.6, eye=0.95, rest={"Fcl_BRW_Angry": 0.3}),
    30:     "veteran": dict(face_len=0.14, jaw=1.4, chin_w=1.2, chin_len=1.0, cheek=-1.0, brow_ridge=1.6, nose=1.4, eye=0.88,
    31:                     age_lines=0.8, iris=0.82, blush=0.0, mouth=1.1,
    32:                     rest={"Fcl_EYE_Angry": 0.6, "Fcl_EYE_Close": 0.12, "Fcl_EYE_Joy": 0.22, "Fcl_BRW_Angry": 0.65,
    33:                           "Fcl_MTH_Down": 0.35}),
    34:     "brute": dict(face_len=0.10, jaw=2.6, chin_w=2.2, chin_len=0.8, cheek=1.2, brow_ridge=2.4, nose=0.8, nose_w=2.2,
    35:                   eye=0.86, mouth=1.25, rest={"Fcl_EYE_Close": 0.28, "Fcl_BRW_Angry": 0.75}),
    36:     "gaunt": dict(face_len=0.18, jaw=0.3, chin_len=1.2, cheek=-1.6, nose=1.8, eye=0.88,
    37:                   rest={"Fcl_BRW_Angry": 0.5, "Fcl_EYE_Close": 0.25}),
    38:     "round": dict(face_len=-0.03, jaw=1.0, chin_w=1.2, cheek=1.6, eye=0.93, mouth=1.08),
    39:     "soft": dict(face_len=0.02, jaw=-0.2, cheek=0.4, eye=1.0),
    40:     "stern": dict(face_len=0.07, jaw=0.6, chin_len=0.5, brow_ridge=0.8, eye=0.92, rest={"Fcl_BRW_Angry": 0.55}),
    41: }
    42: 
    43: 
    44: def shape(build="average", face="plain", **extra):
    45:     """A shape dict for the cast: a build and a face combined (later keys win)."""
    46:     out = dict(BUILDS[build])
    47:     f = dict(FACES[face])
    48:     extra = dict(extra)
    49:     rest = {**out.pop("rest", {}), **f.pop("rest", {}), **extra.pop("rest", {})}
    50:     out.update(f)
    51:     out.update(extra)
    52:     if rest:
    53:         out["rest"] = rest
    54:     return out
    55: 
    56: 
    57: def _bind(fit, pcs, bone):
    58:     for pc in pcs:
    59:         fit.bind(pc, rigid=bone)
    60:     return pcs
    61: 
    62: 
    63: def _group(pcs, g):
    64:     for pc in pcs:
    65:         pc["group"] = g
    66:     return pcs
    67: 
    68: 
    69: # ---- heads: helmets, coifs and hoods on the chart over the skull ----------------------------------------
    70: def helmet(fit, kind="kettle", role="steel", lift=0.030, name="helmet", rivets=True, trim_role=None):
    71:     """A helmet on the skull chart.
    72:     kettle: a rounded bowl to just above the brows and ears, a wide brim sloping down.
    73:     nasal: a taller bowl with a band at the rim and a nose guard down to the nose's tip.
    74:     sallet: a bowl coming low over the forehead, sweeping into a long flared tail at the back.
    75:     close: a bowl to the jaw all round, a face plate with an eye slit and breaths (a bucket helm)."""
    76:     ch = head_chart(fit)
    77:     out = []
    78:     if kind == "kettle":
    79:         rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [74, 80, 86, 92]))
    80:     elif kind == "nasal":
    81:         rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [72, 82, 92, 100]))
    82:     elif kind == "sallet":
    83:         rim = lambda u: float(np.interp(abs(u), [0, 50, 90, 140, 180], [78, 86, 104, 124, 130]))
    84:     else:                                                  # close
    85:         rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [136, 134, 126, 122]))
    86:     fl = None
    87:     if kind == "sallet":                                   # the tail flares out over the nape
    88:         fl = lambda u, v, s, t: 0.030 * max(0.0, (abs(u) - 110) / 70) * (1 - t) ** 1.6
    89:     seams = []
    90:     if kind in ("nasal", "kettle"):                        # a raised comb from front to back
    91:         seams = [[(0, 4), (0, rim(0) - 4)], [(180, 4), (180, rim(180) - 4)]]
    92:     deco = []
    93:     if kind == "close":                                    # the eye slit and the breaths
    94:         deco.append(("line", [(-44, 97), (44, 97)], 0.008, "groove"))
    95:         for u in (-24, -16, -8, 8, 16, 24):
    96:             deco.append(("line", [(u, 112), (u, 122)], 0.003, "groove"))
    97:     bowl, ex = outline_plate(f"{name}", role, ch, -180, 180, rim, lambda u: 0.0, offset=lift,
    98:                              flare=fl, thickness=0.004, nu=72, nv=22, roll=0.003, roll_edges=("bottom",),
    99:                              roll_role=trim_role or role, seams=seams, groove=(0.006, -0.004), panel_crown=0.0,
    100:                              decal=deco, decal_px=1200)
    101:     out += [bowl] + ex
    102:     if kind == "kettle":                                   # the brim: out and down from the rim, all round
    103:         U = np.linspace(-180, 180, 73)
    104:         rimP = np.array([ch.point(u, rim(u), off=lift) for u in U])
    105:         d = rimP - ch.c
    106:         d[:, 1] = 0
    107:         d /= np.linalg.norm(d, axis=1, keepdims=True)
    108:         G = np.stack([rimP + d * 0.058 * t - np.array([0, 0.022 * t * t, 0]) for t in np.linspace(0, 1, 5)], 1)
    109:         pos, tri, outer = O.thick_grid(G, 0.004, outward_from=ch.c - np.array([0, 0.4, 0]))
    110:         brim = O.piece(f"{name}_brim", role, pos, tri)
    111:         out += [brim, O.pipe(f"{name}_brim_roll", trim_role or role, outer[:, -1], r=0.003, seg=6)]
    112:     if kind == "nasal":                                    # the nose guard and a riveted band
    113:         guard, gx = outline_plate(f"{name}_nasal", role, ch, -5, 5, lambda u: 104.0, lambda u: rim(0) - 8,
    114:                                   offset=lift + 0.006, thickness=0.004, nu=8, nv=12, roll=0)
    115:         out += [guard]
    116:         band, bx = outline_plate(f"{name}_band", role, ch, -180, 180, lambda u: rim(u), lambda u: rim(u) - 9,
    117:                                  offset=lift + 0.003, thickness=0.003, nu=72, nv=4, roll=0,
    118:                                  rivets=(0.035, 0.009, 0.0035) if rivets else None, rivet_role=role)
    119:         out += [band] + bx
    120:     _bind(fit, out, "J_Bip_C_Head")
    121:     return _group(out, "helmet")
    122: 
    123: 
    124: def coif(fit, role="mail", name="coif", lift=0.017, face=True):
    125:     """A hood worn under a helmet (padded or mail): over the skull and down to the jaw, the face left
    126:     open (face=False closes it to a slit-less cap), and a short cape over the shoulders."""
    127:     ch = head_chart(fit)
    128:     if face:
    129:         # down over the nape at the back: the study's soldiers show no hair there (a cut hair edge read
    130:         # as a sawtooth under the brim)
    131:         bottom = lambda u: float(np.interp(abs(u), [0, 34, 52, 80, 120, 180], [58, 64, 132, 142, 150, 156]))
    132:     else:
    133:         bottom = lambda u: 146.0
    134:     pc, _ = outline_plate(name, role, ch, -180, 180, bottom, lambda u: 0.0, offset=lift, thickness=0.004,
    135:                           nu=72, nv=24, roll=0)
    136:     _bind(fit, [pc], "J_Bip_C_Head")
    137:     return _group([pc], "helmet")
    138: 
    139: 
    140: def hood(fit, role="cloth", name="hood", lift=0.022, peak=0.03):
    141:     """A cloth hood: roomy over the head, open around the face, a peak at the back of the crown."""
    142:     ch = head_chart(fit)
    143:     bottom = lambda u: float(np.interp(abs(u), [0, 30, 50, 80, 180], [52, 58, 128, 142, 148]))
    144:     fl = lambda u, v, s, t: peak * math.exp(-((abs(u) - 180) / 40) ** 2) * math.exp(-((v - 30) / 25) ** 2)
    145:     pc, _ = outline_plate(name, role, ch, -180, 180, bottom, lambda u: 0.0, offset=lift, flare=fl, thickness=0.004,
    146:                           nu=72, nv=24, roll=0)
    147:     _bind(fit, [pc], "J_Bip_C_Head")
    148:     return _group([pc], "hood")
    149: 
    150: 
    151: def mail_pattern(w, h, ring_px=7, hem=None):
    152:     """A decal of mail rings (dark ring edges in the groove channel), rows offset like real mail."""
    153:     cv = Canvas(w, h, ss=2)
    154:     r = ring_px / 2
    155:     for j, yy in enumerate(np.arange(r, h, ring_px * 0.62)):
    156:         for xx in np.arange(r + (j % 2) * r, w, ring_px):
    157:             s, t = xx / w, 1 - yy / h
    158:             th = np.linspace(0, 2 * np.pi, 10)
    159:             cv.line(np.stack([s + np.cos(th) * r / w, t + np.sin(th) * r / h], 1), 0.9, "groove")
    160:     return cv.array()
    161: 
    162: 
    163: # ---- the torso: quilted coats, mail, riveted vests -------------------------------------------------------
    164: def quilted(fit, under, name="gambeson", role="padding", y_neck=None, y_hem=None, flare=0.08, split=10.0,
    165:             stitch=16.0, sleeves=True, sleeve_end=0.92):
    166:     """A padded coat quilted in vertical channels (each channel puffs between stitched seams): a body
    167:     from the neck to `y_hem` (below the hips it becomes a skirt over a cone, split at the front), and
    168:     sleeves quilted along the arm. `under`: the Surface it sits on (the shirt)."""
    169:     B = fit.bone
    170:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    171:     y_neck = nk[1] - 0.03 if y_neck is None else y_neck
    172:     y_hem = hips[1] - 0.22 if y_hem is None else y_hem
    173:     cz = float(hips[2])
    174:     y_waist = hips[1] + 0.06
    175:     tc = TorsoChart(under, y_waist - 0.04, y_neck + 0.03, cz=cz, du=3.0, dv=0.008)
    176:     out = []
    177:     us = np.arange(-180 + stitch, 180, stitch)
    178:     seams = [[(u, y_waist), (u, y_neck)] for u in us]
    179: 
    180:     def neck_top(u):                                        # lower at the front: a round neckline
    181:         return y_neck - 0.035 * max(0.0, 1 - abs(u) / 70) ** 1.5
    182:     body, _ = outline_plate(name, role, tc, -178, 178, lambda u: y_waist, neck_top, offset=0.008, thickness=0.006,
    183:                             nu=120, nv=26, roll=0.004, roll_edges=("top",), seams=seams, groove=(0.004, 0.004),
    184:                             panel_crown=0.006, decal_px=700)
    185:     fit.bind(body, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips", "Neck", "Shoulder"), fallback="J_Bip_C_Chest")
    186:     out.append(body)
    187:     # the skirt: a cone from the waist down, split at the front
    188:     r0 = lambda u: float(tc.radius(u, y_waist)) + 0.010
    189:     r0m = float(np.mean([r0(u) for u in range(-180, 180, 15)]))
    190:     cone = ConeChart(lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_waist - v) / (y_waist - y_hem), 0, 1.2) ** 1.2,
    191:                      cz=cz)
    192:     sk_seams = [[(u, y_hem), (u, y_waist)] for u in us if abs(u) > split + 4]
    193:     skirt, _ = outline_plate(f"{name}_skirt", role, cone, split, 360 - split, lambda u: y_hem, lambda u: y_waist + 0.012,
    194:                              offset=0.002, thickness=0.006, nu=110, nv=18, roll=0.004, roll_edges=("bottom", "left", "right"),
    195:                              seams=[[((u % 360), a), ((u % 360), b)] for (u, a), (_, b) in sk_seams],
    196:                              groove=(0.004, 0.004), panel_crown=0.006, decal_px=600)
    197:     fit.bind(skirt, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips")
    198:     stiffen(skirt, fit, share=0.55)
    199:     out.append(skirt)
    200:     if sleeves:
    201:         for side in ("L", "R"):
    202:             for seg, (a, b, v0, v1) in enumerate(((f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", -0.05, 1.02),
    203:                                                   (f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand", -0.02, sleeve_end))):
    204:                 arm = O.limb_surface(fit, (a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), side)
    205:                 lc = LimbChart(arm, B[a], B[b], front=(0, 0, -1))
    206:                 sl_seams = [[(u, v0), (u, v1)] for u in range(-150, 180, 30)]
    207:                 sl, _ = outline_plate(f"{name}_sleeve_{side}{seg}", role, lc, -180, 180, lambda u, v1=v1: v1,
    208:                                       lambda u, v0=v0: v0, offset=0.010, thickness=0.005, nu=48, nv=14, roll=0,
    209:                                       seams=sl_seams, groove=(0.005, 0.003), panel_crown=0.004, decal_px=700)
    210:                 fit.bind(sl, allow=(a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), fallback=a)
    211:                 out.append(sl)
    212:     return _group(out, "padding")
    213: 
    214: 
    215: def mail_shirt(fit, under, name="hauberk", role="mail", y_top=None, y_hem=None, sleeve=0.55, flare=0.05):
    216:     """A mail shirt over the coat: body to `y_hem`, short sleeves, rings painted as a decal, the hem
    217:     scalloped into a ragged edge."""
    218:     B = fit.bone
    219:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    220:     y_top = nk[1] - 0.05 if y_top is None else y_top
    221:     y_hem = hips[1] - 0.12 if y_hem is None else y_hem
    222:     cz = float(hips[2])
    223:     y_waist = hips[1] + 0.06
    224:     tc = TorsoChart(under, y_waist - 0.04, y_top + 0.03, cz=cz, du=3.0, dv=0.008)
    225:     rings = (mail_pattern(256, 128), 0.12)                   # one tile of rings covers 12 cm
    226:     body, _ = outline_plate(name, role, tc, -178, 178, lambda u: y_waist, lambda u: y_top - 0.02 * max(0, 1 - abs(u) / 60),
    227:                             offset=0.006, thickness=0.004, nu=96, nv=20, roll=0, pattern=rings)
    228:     out = [body]
    229:     r0 = lambda u: float(tc.radius(u, y_waist)) + 0.010
    230:     cone = ConeChart(lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_waist - v) / (y_waist - y_hem), 0, 1.2), cz=cz)
    231:     hem = lambda u: y_hem + 0.006 * abs(math.sin(math.radians(u) * 18))   # small scallops: a ragged mail edge
    232:     skirt, _ = outline_plate(f"{name}_skirt", role, cone, -178, 178, hem, lambda u: y_waist + 0.01, offset=0.004,
    233:                              thickness=0.004, nu=120, nv=10, roll=0, pattern=rings)
    234:     out.append(skirt)
    235:     fit.bind(body, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips", "Neck", "Shoulder"), fallback="J_Bip_C_Chest")
    236:     fit.bind(skirt, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips")
    237:     stiffen(skirt, fit, share=0.5)
    238:     for side in ("L", "R"):
    239:         a, b = f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm"
    240:         arm = O.limb_surface(fit, (f"{side}_UpperArm",), side)
    241:         lc = LimbChart(arm, B[a], B[b], front=(0, 0, -1))
    242:         sl, _ = outline_plate(f"{name}_sleeve_{side}", role, lc, -180, 180, lambda u: sleeve, lambda u: -0.08,
    243:                               offset=0.018, thickness=0.004, nu=40, nv=8, roll=0, pattern=rings)
    244:         fit.bind(sl, allow=(f"{side}_UpperArm", f"{side}_Shoulder"), fallback=a)
    245:         out.append(sl)
    246:     return _group(out, "mail")
    247: 
    248: 
    249: def riveted_vest(fit, under, name="brigandine", role="leather", rivet_role="steel", y_top=None, y_bottom=None):
    250:     """A coat of plates: cloth-covered plates held by rows of rivets, front and back, open at the sides."""
    251:     B = fit.bone
    252:     nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"]
    253:     y_top = nk[1] - 0.06 if y_top is None else y_top
    254:     y_bottom = hips[1] + 0.02 if y_bottom is None else y_bottom
    255:     cz = float(hips[2])
    256:     tc = TorsoChart(under, y_bottom - 0.03, y_top + 0.03, cz=cz, du=3.0, dv=0.008)
    257:     out = []
    258:     for nm, (u0, u1) in (("front", (-70, 70)), ("back", (110, 250))):
    259:         rows = [[(u, y_bottom + 0.02), (u, y_top - 0.02)] for u in np.arange(u0 + 14, u1 - 6, 14)]
    260:         top = (lambda u: y_top - 0.05 * max(0.0, 1 - abs(u) / 40)) if nm == "front" else (lambda u: y_top)
    261:         pc, ex = outline_plate(f"{name}_{nm}", role, tc, u0, u1, lambda u: y_bottom, top, offset=0.016, thickness=0.006,
    262:                                nu=48, nv=18, roll=0.003, roll_edges=("bottom", "top", "left", "right"),
    263:                                seams=rows, groove=(0.004, 0.002), panel_crown=0.003,
    264:                                rivets=(0.03, 0.012, 0.0035), rivet_role=rivet_role)
    265:         fit.bind(pc, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips"), fallback="J_Bip_C_Chest")
    266:         for q in ex:
    267:             O.inherit(q, pc)
    268:         out += [pc] + ex
    269:     return _group(out, "plate")
    270: 
    271: 
    272: # ---- shields -----------------------------------------------------------------------------------------------
    273: def shield(fit, shape="heater", side="L", role="signature", face_role="heraldry", width=0.46, height=0.62,
    274:            curve=0.55, emblem=None, name="shield"):
    275:     """A shield strapped to the forearm, cut from an outline and curved round its long axis.
    276:     heater: flat top, curved sides to a point; tower: tall, near-rectangular; kite: rounded top to a long point."""
    277:     E, H = fit.bone[f"J_Bip_{side}_LowerArm"], fit.bone[f"J_Bip_{side}_Hand"]
    278:     ax = (H - E) / np.linalg.norm(H - E)
    279:     lat = np.array([-1.0 if side == "L" else 1.0, 0, 0.0])
    280:     lat -= ax * (lat @ ax)
    281:     lat /= np.linalg.norm(lat)
    282:     up = -ax
    283:     fw = np.cross(lat, up)
    284:     if shape == "heater":
    285:         t = np.linspace(0, 1, 13)
    286:         right = [(width / 2 * (1 - t_ ** 2.2), -height * 0.25 - height * 0.75 * t_) for t_ in t]
    287:         outline = [(-width / 2, height * 0.25), (width / 2, height * 0.25)] + right[1:] + [(-x, y) for x, y in right[::-1][1:-1]]
    288:     elif shape == "tower":
    289:         outline = [(-width / 2, height / 2), (width / 2, height / 2), (width / 2, -height / 2), (-width / 2, -height / 2)]
    290:     else:                                                      # kite
    291:         a = np.linspace(0, np.pi, 12)
    292:         top = [(width / 2 * math.cos(x), height * 0.22 + width / 2 * 0.6 * math.sin(x)) for x in a]
    293:         outline = top + [(-width / 2 * 0.9, height * 0.0), (0.0, -height * 0.78), (width / 2 * 0.9, height * 0.0)]
    294:     centre = E + ax * np.linalg.norm(H - E) * 0.5 + lat * 0.07
    295:     deco = emblem or []
    296:     pc = flat_piece(name, role, outline, centre, fw, up, thickness=0.012, decal=deco, px=1200)
    297:     # curve round the long axis (the face bulges out)
    298:     P = pc["pos"]
    299:     x = (P - centre) @ fw
    300:     P += lat[None] * (-(x ** 2) / (2 * curve))[:, None]
  • read_file{"EndLine":300,"Path":"~/work/lowmarch/tools/hair.py","StartLine":1}

    input

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

    result, 301 lines

    Showing lines 1-300 of 318
    1: """The hair kit: hair built as locks combed over the skull, instead of borrowing a VRoid sample's hair
    2: cards (portrait guide, lesson 14).
    3: 
    4: HeadChart  u = degrees round the head (0 front, +90 the character's right), v = degrees down from the
    5:            crown (0 top, 90 level with the skull's centre, ~130 the jaw): rays from the skull's centre
    6:            onto the head skin, smoothed into a shell (as plates.TorsoChart does for the body).
    7: cap        the hair's base volume: a shell over the scalp down to a hairline given as v(u).
    8: lock       one lock: a path of (u, v, lift) points over the head (lift = metres off the scalp), smoothed
    9:            and sampled, then swept with a flat lens-shaped section whose flat side lies along the head,
    10:            width tapering to a point. Past the chart's lower edge a path just continues in 3D.
    11: Every piece gets UVs (around, along) and shares one strand texture, so the painted renderer draws
    12: strand highlights along each lock; every piece rides the head bone.
    13: """
    14: import math
    15: 
    16: import numpy as np
    17: 
    18: from plates import _Chart, _fill_nan
    19: from scipy.ndimage import gaussian_filter
    20: 
    21: 
    22: class HeadChart(_Chart):
    23:     def __init__(self, head, centre, du=4.0, dv=3.0, v_max=150.0, smooth=(1.0, 1.0)):
    24:         self.c = np.asarray(centre, float)
    25:         self.wrap = True
    26:         self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, 0.0, dv, 0.8
    27:         us = np.arange(-180.0, 180.0, du)
    28:         vs = np.arange(0.0, v_max + dv * 0.5, dv)
    29:         R = np.full((len(us), len(vs)), np.nan)
    30:         for i, u in enumerate(us):
    31:             for j, v in enumerate(vs):
    32:                 o, d = self.ray(u, v)
    33:                 R[i, j] = head.cast(o, d, rmax=0.3, far=True)
    34:         R = _fill_nan(R, True)
    35:         self.R = gaussian_filter(R, smooth, mode=("wrap", "nearest"))
    36: 
    37:     def ray(self, u, v):
    38:         u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))
    39:         ur, vr = np.radians(u), np.radians(v)
    40:         d = np.stack([np.sin(vr) * np.sin(ur), np.cos(vr), -np.sin(vr) * np.cos(ur)], -1)
    41:         return np.broadcast_to(self.c, d.shape).copy(), d
    42: 
    43:     def centre(self, v=None):
    44:         return self.c
    45: 
    46:     @property
    47:     def L(self):
    48:         """Metres per degree of v (decals and seams measure plates on this chart in metres)."""
    49:         return float(np.mean(self.R)) * np.pi / 180
    50: 
    51:     def metric(self, u, v):
    52:         """(arc across, arc down) in metres, for seams and decals on helmets."""
    53:         r = self.radius(u, v)
    54:         return np.stack([np.radians(u) * r * np.sin(np.radians(np.asarray(v, float))), np.radians(v) * r + 0 * np.asarray(u, float)], -1)
    55: 
    56: 
    57: # ---- the shared strand texture: fine light and dark lines running along each lock -----------------
    58: def strand_texture(n=256, seed=3):
    59:     rng = np.random.default_rng(seed)
    60:     x = np.arange(n)
    61:     stripes = np.zeros(n)
    62:     for f, a in ((3, 0.18), (7, 0.12), (17, 0.10), (41, 0.06)):
    63:         stripes += a * np.sin(2 * np.pi * (f * x / n + rng.random()))
    64:     stripes += 0.08 * gaussian_filter(rng.standard_normal(n), 1.2, mode="wrap")
    65:     col = np.clip(0.62 + stripes, 0.25, 0.95)
    66:     along = 1.0 - 0.10 * np.linspace(0, 1, n)[:, None]           # a touch darker toward the tip
    67:     img = (np.repeat(col[None, :], n, 0) * along * 255).astype(np.uint8)
    68:     return np.dstack([img, img, img, np.full((n, n), 255, np.uint8)])
    69: 
    70: 
    71: STRANDS = strand_texture()
    72: 
    73: 
    74: def _smooth_path(P, n):
    75:     """Catmull-Rom through control points P (k, 3), sampled at n points."""
    76:     P = np.asarray(P, float)
    77:     if len(P) == 2:
    78:         return P[0] + (P[1] - P[0]) * np.linspace(0, 1, n)[:, None]
    79:     Q = np.vstack([2 * P[0] - P[1], P, 2 * P[-1] - P[-2]])
    80:     seg = len(P) - 1
    81:     out = []
    82:     for t in np.linspace(0, seg, n):
    83:         i = min(int(t), seg - 1)
    84:         s = t - i
    85:         p0, p1, p2, p3 = Q[i], Q[i + 1], Q[i + 2], Q[i + 3]
    86:         out.append(0.5 * ((2 * p1) + (-p0 + p2) * s + (2 * p0 - 5 * p1 + 4 * p2 - p3) * s * s
    87:                           + (-p0 + 3 * p1 - 3 * p2 + p3) * s ** 3))
    88:     return np.array(out)
    89: 
    90: 
    91: def lock(name, chart, path, width, thick=0.006, n=28, seg=10, taper=(0.45, 1.0), tip=0.04, flat_to=None,
    92:          role="hair", root_width=None, profile=None):
    93:     """A lock along `path`: (u, v, lift) points on the chart, or 3D points (arrays of length 3 with
    94:     a flag), mixed freely as ("uv", u, v, lift) / ("xyz", x, y, z). Width tapers from
    95:     taper[0] of the way along to a point at the end (tip: the last fraction kept a hair's width).
    96:     The flat side faces `flat_to` (a point the section looks away from; default the skull's centre)."""
    97:     from outfit import piece
    98:     pts = []
    99:     for p in path:
    100:         if p[0] == "uv":
    101:             _, u, v, lift = p
    102:             pts.append(chart.point(u, v, off=lift))
    103:         else:
    104:             pts.append(np.array(p[1:], float))
    105:     C = _smooth_path(pts, n)
    106:     T = np.gradient(C, axis=0)
    107:     T /= np.maximum(np.linalg.norm(T, axis=1, keepdims=True), 1e-9)
    108:     away = C - np.asarray(flat_to if flat_to is not None else chart.c, float)
    109:     N = away - T * np.einsum("ij,ij->i", away, T)[:, None]
    110:     N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-9)
    111:     Bv = np.cross(T, N)
    112:     t = np.linspace(0, 1, n)
    113:     w0 = width if root_width is None else root_width
    114:     w = np.where(t < 0.12, w0 + (width - w0) * t / 0.12, width)
    115:     k = np.clip((t - taper[0]) / max(taper[1] - taper[0], 1e-6), 0, 1)
    116:     w = w * (1 - k ** 1.6) + tip * 0.01 * k
    117:     if profile is not None:                            # a clump: profile(t) = width as a fraction of `width`
    118:         w = width * np.array([profile(x) for x in t]) + 0.0004
    119:         k = np.clip((t - 0.6) / 0.4, 0, 1)
    120:     th = thick * np.maximum(1 - k ** 1.3, 0.15)
    121:     a = np.linspace(0, 2 * np.pi, seg + 1)
    122:     G = (C[:, None] + Bv[:, None] * (w[:, None] / 2 * np.cos(a)[None, :])[..., None]
    123:          + N[:, None] * (th[:, None] / 2 * np.sin(a)[None, :])[..., None])
    124:     from outfit import grid_mesh
    125:     pos, tri = grid_mesh(G)
    126:     pc = piece(name, role, pos, tri, outward_from=None)
    127:     from fitting import vertex_normals
    128:     fn = vertex_normals(pos, tri)
    129:     radial = (pos - np.repeat(C, seg + 1, 0))
    130:     if (np.einsum("ij,ij->i", fn, radial) < 0).mean() > 0.5:
    131:         pc["tri"] = tri[:, ::-1]
    132:         pc["nrm"] = -fn
    133:     uu, vv = np.meshgrid(a / (2 * np.pi), t, indexing="xy")
    134:     pc["uv"] = np.stack([uu.ravel(), vv.ravel()], 1)
    135:     pc["strands"] = True
    136:     pc["group"] = "hair"
    137:     return pc
    138: 
    139: 
    140: def cap(name, chart, hairline, lift=0.010, crown=0.006, nu=72, nv=26, role="hair"):
    141:     """The hair's base volume: a shell over the scalp from the crown down to hairline(u) (degrees of v),
    142:     lifted `lift` off the scalp plus `crown` more at the top."""
    143:     from outfit import piece, grid_mesh
    144:     U = np.linspace(-180, 180, nu)
    145:     G = np.zeros((nu, nv, 3))
    146:     UV = np.zeros((nu, nv, 2))
    147:     for i, u in enumerate(U):
    148:         vmax = hairline(u)
    149:         for j, s in enumerate(np.linspace(0, 1, nv)):
    150:             v = vmax * s                                    # from the crown itself (a gap there showed as a dot)
    151:             G[i, j] = chart.point(u, v, off=lift + crown * (1 - s) ** 2)
    152:             UV[i, j] = (i / (nu - 1) * 6, s)                # strands run from the crown down (u repeats)
    153:     pos, tri = grid_mesh(G)
    154:     pc = piece(name, role, pos, tri, outward_from=chart.c)
    155:     pc["uv"] = UV.reshape(-1, 2)
    156:     pc["strands"] = True
    157:     pc["group"] = "hair"
    158:     return pc
    159: 
    160: 
    161: # ---- hairstyles -----------------------------------------------------------------------------------
    162: def head_chart(fit, ear_x=None):
    163:     """The chart over this body's skull, centred in the head skin's bounding box. The ears are left
    164:     out (triangles further than ear_x to the side, by default 0.835 of the head's half width, 8.6 cm
    165:     on the VRoid heads): cast onto them, every lock passing the sides was pushed out past the ears and
    166:     the hair became a bowl."""
    167:     from fitting import Surface
    168:     head = fit.head_surface()
    169:     P = head.pos[np.unique(head.tri)]
    170:     centre = (P.min(0) + P.max(0)) / 2
    171:     if ear_x is None:
    172:         ear_x = min(0.086, 0.835 * float(P[:, 0].max() - centre[0]))
    173:     cx = head.pos[head.tri].mean(1)[:, 0]
    174:     skull = Surface(head.pos, head.tri[np.abs(cx - centre[0]) < ear_x])
    175:     return HeadChart(skull, centre)
    176: 
    177: 
    178: def clump(t, widest=0.55, root=0.42, point=1.6):
    179:     """A bang's width along it, as a fraction of its widest: it grows out of the hair mass, is widest
    180:     past its middle, then comes to a point."""
    181:     if t < widest:
    182:         return root + (1 - root) * math.sin(math.pi / 2 * t / widest)
    183:     return max(0.0, 1 - ((t - widest) / (1 - widest)) ** point) ** 0.9
    184: 
    185: 
    186: def elaine(fit):
    187:     """Elaine's hair: a short bob with side-swept bangs, side locks framing the face, the back down to
    188:     the nape; her bun, braid and ribbon (outfit.updo) sit on top, and one upright strand curls forward
    189:     from the crown.
    190:     The bangs follow a study of Unicorn Overlord's character art (lesson 14): a few clumps of clearly
    191:     different widths and lengths fanning from a part off the centre, widest past their middle, a thin
    192:     strand or two between them; not a row of matching points (the user found seven of them jarring)."""
    193:     ch = head_chart(fit)
    194:     # the hairline: low at the nape (about the earlobe's bottom), and down in front of the ear over the
    195:     # temple (the base's untextured temple skin showed as a white triangle there)
    196:     out = [cap("hair_cap", ch, lambda u: float(np.interp(abs(u), [0, 40, 60, 75, 90, 110, 130, 150, 180],
    197:                                                          [56, 62, 76, 100, 108, 110, 126, 140, 146])),
    198:                lift=0.007, crown=0.009)]
    199:     part = -24.0                                        # over her left eye
    200:     bangs = [  # name, path of (u, v, lift), widest width, (where widest, root fraction)
    201:         ("sweep", [(part + 4, 34, 0.006), (0, 60, 0.014), (20, 84, 0.017), (33, 96, 0.016)], 0.050, (0.50, 0.40)),
    202:         ("sweep_back", [(part + 12, 40, 0.005), (16, 64, 0.011), (40, 86, 0.013), (50, 95, 0.012)], 0.036, (0.55, 0.40)),
    203:         ("fall", [(part, 34, 0.006), (part - 1, 64, 0.016), (-10, 90, 0.019), (-5, 103, 0.018)], 0.030, (0.50, 0.45)),
    204:         ("left", [(part - 6, 36, 0.006), (part - 16, 64, 0.013), (-42, 88, 0.016), (-48, 97, 0.015)], 0.036, (0.55, 0.45)),
    205:         ("strand_r", [(part + 8, 42, 0.005), (8, 70, 0.018), (14, 99, 0.020)], 0.011, (0.35, 0.6)),
    206:         ("strand_l", [(-46, 48, 0.006), (-55, 76, 0.016), (-57, 98, 0.017)], 0.012, (0.35, 0.6)),
    207:     ]
    208:     for nm, path, w, (widest, root) in bangs:
    209:         out.append(lock(f"hair_bang_{nm}", ch, [("uv", *p) for p in path], width=w, thick=0.008, n=32,
    210:                         profile=lambda t, a=widest, b=root: clump(t, a, b)))
    211:     # side locks: one in front of the ear down to the jaw, one over the ear's top
    212:     for s, side in ((1, "R"), (-1, "L")):
    213:         out.append(lock(f"hair_side{side}0", ch, [("uv", s * 50, 24, 0.008), ("uv", s * 68, 68, 0.012),
    214:                                                    ("uv", s * 70, 108, 0.013), ("uv", s * 64, 140, 0.011)],
    215:                         width=0.030, thick=0.007, taper=(0.5, 1.0), root_width=0.013))
    216:         out.append(lock(f"hair_side{side}1", ch, [("uv", s * 84, 40, 0.005), ("uv", s * 100, 70, 0.012),
    217:                                                    ("uv", s * 108, 104, 0.012), ("uv", s * 112, 122, 0.010)],
    218:                         width=0.032, thick=0.008, taper=(0.55, 1.0), root_width=0.015))
    219:     # the back: locks from the crown down to the nape, overlapping
    220:     for k, u in enumerate((112, 132, 152, 172, 192, 212, 232, 252)):
    221:         side = abs(u - 180) / 68                      # 1 at the sides, 0 at the middle of the back
    222:         sw = (1 if u < 180 else -1) * 22 * side       # sweep toward the nape as they fall
    223:         out.append(lock(f"hair_back{k}", ch, [("uv", u, 30, 0.005), ("uv", u + sw * 0.2, 62, 0.010 + 0.006 * (1 - side)),
    224:                                               ("uv", u + sw * 0.6, 98, 0.010 + 0.004 * (1 - side)),
    225:                                               ("uv", u + sw, 146 - 14 * side, 0.008)],
    226:                         width=0.050, thick=0.009, taper=(0.75, 1.0), tip=0.3, root_width=0.020))
    227:     # the upright strand: from the crown, up and curling forward; flat side to the side
    228:     root = ch.point(0, 6, off=0.010)
    229:     up = np.array([0, 1.0, 0])
    230:     fwd = np.array([0, 0, -1.0])
    231:     out.append(lock("hair_ahoge", ch, [("xyz", *root), ("xyz", *(root + up * 0.030 - fwd * 0.004)),
    232:                                         ("xyz", *(root + up * 0.055 + fwd * 0.012)),
    233:                                         ("xyz", *(root + up * 0.050 + fwd * 0.040)),
    234:                                         ("xyz", *(root + up * 0.036 + fwd * 0.052))],
    235:                     width=0.016, thick=0.004, taper=(0.35, 1.0), flat_to=ch.c + np.array([-1.0, 0, 0]), n=24))
    236:     for pc in out:
    237:         fit.bind(pc, rigid="J_Bip_C_Head")
    238:     return out
    239: 
    240: 
    241: # ---- facial hair -----------------------------------------------------------------------------------------
    242: def _face_marks(ch, head, mouth=None):
    243:     """Chart angles of the chin (the front's lowest point) and the mouth: the mouth's own centre when
    244:     given (a long face puts it well over 13 degrees above the chin), else 13 degrees above the chin."""
    245:     P = head.pos[np.unique(head.tri)]
    246:     front = P[(np.abs(P[:, 0] - ch.c[0]) < 0.012) & (P[:, 2] < ch.c[2] - 0.04)]
    247:     chin = front[np.argmin(front[:, 1])]
    248: 
    249:     def angle(q):
    250:         d = q - ch.c
    251:         return float(np.degrees(np.arccos(np.clip(d[1] / np.linalg.norm(d), -1, 1))))
    252:     v_chin = angle(chin)
    253:     return v_chin, (angle(mouth) if mouth is not None else v_chin - 13.0)
    254: 
    255: 
    256: def beard(fit, style="full", role="hair", length=0.0):
    257:     """Facial hair on the head chart. style: 'full' (jaw, chin and cheeks, open round the mouth, with a
    258:     moustache), 'short' (close-cropped, the same outline), 'goatee' (chin and moustache), 'moustache'.
    259:     length: metres of beard hanging below the chin (locks)."""
    260:     from plates import outline_plate
    261:     ch = head_chart(fit)
    262:     head = fit.head_surface()
    263:     mouth = [p["pos"][np.unique(p["tri"])] for p, r in zip(fit._prims, fit._roles) if r == "mouth" and len(p["tri"])]
    264:     v_chin, v_mouth = _face_marks(ch, head, np.concatenate(mouth).mean(0) if mouth and getattr(fit, "cloth_hull", False) else None)
    265:     out = []
    266:     thick = 0.022 if style == "full" else 0.009
    267:     if style in ("full", "short"):
    268:         def top(u):
    269:             a = abs(u)
    270:             if a < 22:
    271:                 return v_mouth + 8.0
    272:             if a < 62:
    273:                 return v_mouth + 8.0 - (v_mouth + 8.0 - 110.0) * ((a - 22) / 40) ** 0.8
    274:             return 110.0 - 14.0 * min(1.0, (a - 62) / 30)
    275:         bottom = lambda u: min(149.0, v_chin + 7.0 - 3.0 * (abs(u) / 95))
    276:         fl = lambda u, v, s, t: thick * (1 - t) ** 0.7 * (0.6 + 0.4 * math.cos(math.radians(u)))
    277:         # solid: filled from its outer face down to the face (a shell standing off the jaw read as paper
    278:         # from below and from the side; the study draws beards as one mass)
    279:         pc, _ = outline_plate("beard", role, ch, -96, 96, bottom, top, offset=0.004, flare=fl,
    280:                               thickness=lambda u, v, s, t: 0.003 + fl(u, v, s, t), nu=48, nv=14, roll=0,
    281:                               pattern=(STRANDS, 0.03))
    282:         out.append(pc)
    283:     if style == "goatee":
    284:         pc, _ = outline_plate("beard", role, ch, -22, 22, lambda u: min(149.0, v_chin + 6.0), lambda u: v_mouth + 8.0,
    285:                               offset=0.004, flare=lambda u, v, s, t: 0.010 * (1 - t),
    286:                               thickness=lambda u, v, s, t: 0.003 + 0.010 * (1 - t), nu=20, nv=10, roll=0,
    287:                               pattern=(STRANDS, 0.03))
    288:         out.append(pc)
    289:     if style in ("full", "short", "goatee", "moustache"):          # the moustache: two locks from under the nose
    290:         for s in (-1, 1):
    291:             out.append(lock(f"moustache{(s + 1) // 2}", ch, [("uv", s * 2, v_mouth - 7, 0.006), ("uv", s * 14, v_mouth - 4, 0.010),
    292:                                                              ("uv", s * 26, v_mouth + 3, 0.009)],
    293:                             width=0.016 if style != "short" else 0.010, thick=0.006, n=16, taper=(0.5, 1.0)))
    294:     if length > 0 and style in ("full", "goatee"):                  # the beard's fall below the chin
    295:         # one solid mass, wide at the jaw and tapering to a point (three thin locks read as a ruff, and
    296:         # a mass that stayed wide read as a bib)
    297:         p0 = ch.point(0, v_chin + 4, off=0.015) + np.array([0.0, 0.006, -0.006])
    298:         full = style == "full"
    299:         out.append(lock("beard_fall", ch, [("xyz", *p0), ("xyz", *(p0 + np.array([0, -length * 0.55, -0.010]))),
    300:                                            ("xyz", *(p0 + np.array([0, -length, -0.004])))],