reasoning

The script tools/export_glb.py utilizes material_texture to load material textures. Investigating lines 487-508 and 545-549 reveals how textures are handled. The function call src.material_texture is the likely point of manipulation for targeted texture replacements. Considering potential texture swaps. The iris and highlight textures could be candidates for substitution with a custom high-resolution sapphire texture.

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

    input

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

    result, 161 lines

    Showing lines 1-160 of 567
    1: """Export a composed character (VRoid base + our shapes, costume, props, scenery) to GLB for the
    2: browser 3D viewer.
    3: 
    4: Each primitive becomes a mesh named by its group (body, hair, costume pieces, sword, terrain) so
    5: the viewer can toggle and x-ray them. Face, eye, line, brow, mouth and hair keep VRoid's textures
    6: (downscaled) for alpha and detail; everything else gets the character's palette colour. The model
    7: is turned to face +z, the direction a default three.js camera looks from.
    8: """
    9: import io
    10: import math
    11: import json
    12: import struct
    13: 
    14: import numpy as np
    15: from PIL import Image
    16: 
    17: FLIP = np.array([-1.0, 1.0, -1.0])
    18: TEXTURED = ("face", "iris", "white", "highlight", "line", "brow", "mouth", "hair")
    19: ROLE_TONE = {"face": "5", "body": "4", "shadow": "3", "hair": "D", "brow": "B", "coat": "M", "cape": "W", "metal": "8",
    20:              "signature": "M", "doublet": "S", "heraldry": "N",
    21:              "steel": "8", "gold": "H", "leather": "v", "boot": "v", "glove": "x", "cloth": "M",
    22:              "grass": "c", "dirt": "f", "stone": "l", "mouth": "2", "line": "o", "iris": "s", "white": "w",
    23:              "highlight": "w"}
    24: 
    25: 
    26: def group_of(p, role):
    27:     if p.get("world"):
    28:         return "terrain"
    29:     if p.get("group"):
    30:         return p["group"]
    31:     if role in ("face", "body", "shadow", "iris", "white", "highlight", "line", "brow", "mouth"):
    32:         return "body"
    33:     if role == "hair":
    34:         return "hair"
    35:     name = p["material"].replace("OUTFIT_", "")
    36:     for key in ("trim", "edge", "hem", "placket", "buckle", "clasp"):
    37:         if key in name:
    38:             return "trim"
    39:     for key in ("pauldron", "cape", "collar", "tunic", "tails", "belt", "trousers", "boots", "gloves"):
    40:         if name.startswith(key):
    41:             return key
    42:     if name in ("blade", "guard", "grip", "pommel", "fuller"):
    43:         return "sword"
    44:     return "costume"
    45: 
    46: 
    47: def skin_ramp(h):
    48:     """A skin tone's lit, shade and deep-shade colours from its lit colour. The shade is darker and a little more
    49:     saturated, its hue nudged toward red on human tones (so deep skin stays rich and warm, not ashy) and toward
    50:     violet on the fantasy blues, greens and greys. Hex strings, light to dark."""
    51:     import colorsys
    52:     r, g, b = (int(h[i:i + 2], 16) / 255 for i in (1, 3, 5))
    53:     hue, sat, val = colorsys.rgb_to_hsv(r, g, b)
    54:     warm = hue < 0.17 or hue > 0.9
    55:     dh = -0.015 if warm else (0.025 if hue < 0.75 else -0.025)
    56: 
    57:     def tone(k, dv, ds):
    58:         rr, gg, bb = colorsys.hsv_to_rgb((hue + k * dh) % 1.0, min(1.0, sat + (1 - sat) * ds), val * dv)
    59:         return "#%02x%02x%02x" % tuple(int(round(c * 255)) for c in (rr, gg, bb))
    60:     return [h, tone(1, 0.80, 0.12), tone(2, 0.50, 0.22)]
    61: 
    62: 
    63: def hex_rgb(h):
    64:     h = h.lstrip("#")
    65:     return [int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)]
    66: 
    67: 
    68: def export(portrait, palette, path, max_tex=512, only_world=False):
    69:     """portrait: vroid_portrait.Portrait. palette: full char -> hex map. only_world: export just
    70:     the scenery (the character goes out skinned through export_skinned)."""
    71:     bin_ = bytearray()
    72:     views, accessors, meshes, nodes, materials, textures, images = [], [], [], [], [], [], []
    73:     tex_index = {}
    74: 
    75:     def add_view(data, target=None):
    76:         while len(bin_) % 4:
    77:             bin_.append(0)
    78:         off = len(bin_)
    79:         bin_.extend(data)
    80:         v = dict(buffer=0, byteOffset=off, byteLength=len(data))
    81:         if target:
    82:             v["target"] = target
    83:         views.append(v)
    84:         return len(views) - 1
    85: 
    86:     def add_acc(arr, kind, comp, target):
    87:         arr = np.ascontiguousarray(arr)
    88:         vi = add_view(arr.tobytes(), target)
    89:         a = dict(bufferView=vi, componentType=comp, count=int(arr.shape[0]), type=kind)
    90:         if kind == "VEC3" and comp == 5126:
    91:             a["min"] = arr.min(0).tolist()
    92:             a["max"] = arr.max(0).tolist()
    93:         accessors.append(a)
    94:         return len(accessors) - 1
    95: 
    96:     def add_texture(key, rgba):
    97:         if key in tex_index:
    98:             return tex_index[key]
    99:         im = Image.fromarray(rgba)
    100:         if max(im.size) > max_tex:
    101:             k = max_tex / max(im.size)
    102:             im = im.resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS)
    103:         b = io.BytesIO()
    104:         im.save(b, "PNG", optimize=True)
    105:         vi = add_view(b.getvalue())
    106:         images.append(dict(bufferView=vi, mimeType="image/png"))
    107:         textures.append(dict(source=len(images) - 1, sampler=0))
    108:         tex_index[key] = len(textures) - 1
    109:         return tex_index[key]
    110: 
    111:     for k, (p, role) in enumerate(zip(portrait.prims, portrait.roles)):
    112:         if role == "skip" or not len(p["tri"]) or (only_world and not p.get("world")):
    113:             continue
    114:         used, inv = np.unique(p["tri"], return_inverse=True)
    115:         pos = (p["pos"][used] * FLIP).astype(np.float32)
    116:         nrm = p["nrm"][used] * FLIP
    117:         nrm = (nrm / np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)).astype(np.float32)
    118:         tri = inv.reshape(-1, 3).astype(np.uint32)               # FLIP is a 180-degree turn: winding holds
    119:         attrs = dict(POSITION=add_acc(pos, "VEC3", 5126, 34962), NORMAL=add_acc(nrm, "VEC3", 5126, 34962))
    120:         mat = dict(name=f"{group_of(p, role)}:{role}", doubleSided=True,
    121:                    pbrMetallicRoughness=dict(metallicFactor=0.0, roughnessFactor=0.9))
    122:         tone = ROLE_TONE.get(role)
    123:         color = hex_rgb(palette[tone]) if tone in palette else [0.8, 0.8, 0.8]
    124:         tex = portrait.tex.get(k)
    125:         if role == "face":
    126:             tex = portrait.v.material_texture(p["mi"])
    127:         if role in TEXTURED and tex is not None:
    128:             uv = p["uv"][used].astype(np.float32)
    129:             attrs["TEXCOORD_0"] = add_acc(uv, "VEC2", 5126, 34962)
    130:             src = portrait._hair_v if role == "hair" and getattr(portrait, "_hair_v", None) is not None \
    131:                 and "_HAIR" in p["material"] else portrait.v
    132:             raw = src.material_texture(p["mi"])
    133:             mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture((id(src), p["mi"], role), raw))
    134:             if role == "hair":                        # strands are grey in the texture: tint them
    135:                 mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
    136:             if role in ("hair", "line", "brow", "iris", "highlight"):
    137:                 mat["alphaMode"] = "MASK"
    138:                 mat["alphaCutoff"] = 0.5
    139:         else:
    140:             mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
    141:         if role in ("metal", "steel", "gold"):
    142:             mat["pbrMetallicRoughness"].update(metallicFactor=0.6, roughnessFactor=0.35)
    143:         materials.append(mat)
    144:         meshes.append(dict(name=group_of(p, role), primitives=[dict(
    145:             attributes=attrs, indices=add_acc(tri.reshape(-1), "SCALAR", 5125, 34963), material=len(materials) - 1)]))
    146:         nodes.append(dict(name=f"{group_of(p, role)}/{p['material']}", mesh=len(meshes) - 1,
    147:                           extras=dict(group=group_of(p, role), role=role, world=bool(p.get("world")), material=p["material"])))
    148:     gltf = dict(asset=dict(version="2.0", generator="lowmarch export_glb"), scene=0,
    149:                 scenes=[dict(nodes=list(range(len(nodes))))], nodes=nodes, meshes=meshes, materials=materials,
    150:                 accessors=accessors, bufferViews=views, buffers=[dict(byteLength=len(bin_))],
    151:                 samplers=[dict(magFilter=9729, minFilter=9987)])
    152:     if textures:
    153:         gltf.update(textures=textures, images=images)
    154:     js = json.dumps(gltf, separators=(",", ":")).encode()
    155:     js += b" " * ((4 - len(js) % 4) % 4)
    156:     while len(bin_) % 4:
    157:         bin_.append(0)
    158:     out = struct.pack("<4sII", b"glTF", 2, 12 + 8 + len(js) + 8 + len(bin_))
    159:     out += struct.pack("<I4s", len(js), b"JSON") + js + struct.pack("<I4s", len(bin_), b"BIN\x00") + bytes(bin_)
    160:     open(path, "wb").write(out)
  • read_file{"EndLine":1150,"Path":"~/work/lowmarch/tools/blender_sculpt_cast.py","StartLine":701}

    input

    {
      "EndLine": 1150,
      "Path": "~/work/lowmarch/tools/blender_sculpt_cast.py",
      "StartLine": 701
    }

    result, 451 lines

    Showing lines 701-1150 of 1443
    701:     tun_g = np.zeros((nu_t, nv_t, 3))
    702:     for i, az in enumerate(az_t):
    703:         z_top = neck_z + 0.018 - 0.024 * math.cos(math.radians(az) * 0.5) ** 4 if abs(az) < 90 else neck_z + 0.022
    704:         for j, t in enumerate(np.linspace(0, 1, nv_t)):
    705:             zz = z_top * (1 - t) + (hips_z - 0.02) * t
    706:             pleat = 0.0018 * math.cos(math.radians(az * 12))
    707:             tun_g[i, j] = torso_ray(az, zz, lift=0.0055 + pleat)
    708:     add("arming_tunic", "doublet", _grid_shell_in_blender("Tunic", tun_g, 0.003, 1, cyclic_u=True), "torso_skin", "doublet")
    709: 
    710:     # Standing officer collar + gold braid rim
    711:     az_c = np.linspace(-152, 152, 34) + 180.0  # open slight V at front throat (0 deg)
    712:     col_g = np.zeros((34, 5, 3))
    713:     for i, a_raw in enumerate(np.linspace(26, 334, 34)):
    714:         az = ((a_raw + 180) % 360) - 180
    715:         h_col = 0.032 + 0.014 * (abs(az) / 180.0)
    716:         base_p = torso_ray(az, neck_z - 0.012, lift=0.010, default_r=0.062)
    717:         d_out = np.array([math.sin(math.radians(az)), math.cos(math.radians(az)), 0.0])
    718:         for j, s in enumerate(np.linspace(0, 1, 5)):
    719:             col_g[i, j] = base_p + d_out * (0.007 * s ** 1.3) + np.array([0.0, 0.0, h_col * s])
    720:     add("officer_collar", "signature", _grid_shell_in_blender("Collar", col_g, 0.0035, 1), "neck_blend", "collar")
    721:     add("officer_collar_gold", "gold", _curve_pipe_in_blender("CollarGold", col_g[:, -1], 0.0028), "neck_blend", "collar")
    722: 
    723:     # 2. Sculpted Steel Gorget + V-Keeled Gothic-Anime Cuirass + 3 Overlapping V-Fauld Lames
    724:     # 2a. Beveled Steel Gorget around collarbone
    725:     nu_g = 40
    726:     gor_g = np.zeros((nu_g, 6, 3))
    727:     for i, az in enumerate(np.linspace(-180, 180, nu_g, endpoint=False)):
    728:         p_in = torso_ray(az, neck_z - 0.018, lift=0.013, default_r=0.066)
    729:         z_out = uchest_z + 0.062 - 0.028 * max(0.0, math.cos(math.radians(az)))
    730:         p_out = torso_ray(az, z_out, lift=0.017, default_r=0.112)
    731:         for j, s in enumerate(np.linspace(0, 1, 6)):
    732:             gor_g[i, j] = p_in * (1 - s) + p_out * s + np.array([0, 0, 0.003 * math.sin(math.pi * s)])
    733:     add("gorget", "steel", _grid_shell_in_blender("Gorget", gor_g, 0.0045, 1, cyclic_u=True), "uchest_blend", "plate")
    734:     add("gorget_rim", "gold", _curve_pipe_in_blender("GorgetRim", gor_g[:, -1], 0.0032, cyclic=True), "uchest_blend", "plate")
    735: 
    736:     # 2b. V-Keeled Gothic Cuirass (nipping sharply into wasp-waist with central ridge keel & diagonal flutes!)
    737:     nu_c, nv_c = 48, 16
    738:     cuir_g = np.zeros((nu_c, nv_c, 3))
    739:     for i, az in enumerate(np.linspace(-180, 180, nu_c, endpoint=False)):
    740:         frontness = max(0.0, math.cos(math.radians(az)))
    741:         arm_dip = 0.048 * math.exp(-((abs(az) - 92.0) / 28.0) ** 2)
    742:         z_hi = uchest_z + 0.050 - 0.022 * frontness ** 2 - arm_dip
    743:         z_lo = waist_z - 0.022 * frontness ** 3  # sharp gothic V-point at front waist!
    744:         for j, t in enumerate(np.linspace(0, 1, nv_c)):
    745:             zz = z_hi * (1 - t) + z_lo * t
    746:             # Sharp central V-keel ridge down the front sternum + subtle gothic flutes!
    747:             keel = 0.014 * max(0.0, 1.0 - abs(az) / 28.0) ** 1.6 * math.sin(math.pi * np.clip(t * 1.1, 0.05, 0.95))
    748:             flute = 0.0026 * math.cos(math.radians((abs(az) - 22.0 * t) * 5.0)) * frontness * math.sin(math.pi * t)
    749:             cuir_g[i, j] = torso_ray(az, zz, lift=0.013 + keel + flute)
    750:     add("gothic_cuirass", "steel", _grid_shell_in_blender("Cuirass", cuir_g, 0.0055, 1, cyclic_u=True), "torso_plate", "plate")
    751:     add("cuirass_top_gold", "gold", _curve_pipe_in_blender("CuirTop", cuir_g[:, 0], 0.0032, cyclic=True), "torso_plate", "plate")
    752:     add("cuirass_waist_gold", "gold", _curve_pipe_in_blender("CuirBot", cuir_g[:, -1], 0.0034, cyclic=True), "torso_plate", "plate")
    753:     # Central raised gold sternum ridge spine!
    754:     keel_line = cuir_g[0, 1:-1] + np.array([0.0, 0.0055, 0.0])
    755:     add("cuirass_keel_gold", "gold", _curve_pipe_in_blender("CuirKeel", keel_line, 0.0028), "torso_plate", "plate")
    756: 
    757:     # 2c. Three Overlapping Articulated V-Fauld Lames below the waist
    758:     for k_lame in range(3):
    759:         nu_f = 44
    760:         fauld_g = np.zeros((nu_f, 4, 3))
    761:         z0 = waist_z - 0.008 - k_lame * 0.028
    762:         for i, az in enumerate(np.linspace(-180, 180, nu_f, endpoint=False)):
    763:             v_dip = 0.022 * max(0.0, math.cos(math.radians(az))) ** 2
    764:             flare = 0.016 + k_lame * 0.009
    765:             for j, s in enumerate(np.linspace(0, 1, 4)):
    766:                 zz = z0 - v_dip - s * 0.032
    767:                 fauld_g[i, j] = torso_ray(az, max(zz, hips_z - 0.06), lift=flare + s * 0.008)
    768:                 fauld_g[i, j, 2] = zz
    769:         add(f"fauld_lame_{k_lame}", "steel", _grid_shell_in_blender(f"Fauld{k_lame}", fauld_g, 0.004, 1, cyclic_u=True),
    770:             "hips_stiff", "plate")
    771:         if k_lame == 2:
    772:             add("fauld_hem_gold", "gold", _curve_pipe_in_blender("FauldGold", fauld_g[:, -1], 0.0028, cyclic=True),
    773:                 "hips_stiff", "plate")
    774: 
    775:     # 3. Split Swallowtail Royal-Indigo Surcoat + Ivory Pleated Under-Kirtle + Scalloped Steel Hip-Tassets
    776:     # 3a. Ivory pleated under-kirtle (gives luminous light-value contrast between dark indigo surcoat & dark cuisses!)
    777:     nu_k, nv_k = 56, 12
    778:     kirt_g = np.zeros((nu_k, nv_k, 3))
    779:     z_kirt_top = hips_z + 0.02
    780:     z_kirt_bot = 0.42 * hips_z + 0.58 * knee_z
    781:     for i, az in enumerate(np.linspace(-180, 180, nu_k, endpoint=False)):
    782:         base_w = torso_ray(az, hips_z + 0.01, lift=0.016, default_r=0.145)
    783:         d_out = np.array([math.sin(math.radians(az)), math.cos(math.radians(az)), 0.0])
    784:         pleat = 0.008 * math.cos(math.radians(az * 18.0))
    785:         side_room = 0.032 * math.sin(math.radians(az)) ** 2
    786:         for j, t in enumerate(np.linspace(0, 1, nv_k)):
    787:             zz = z_kirt_top * (1 - t) + z_kirt_bot * t
    788:             bell = (0.115 + side_room) * (t ** 1.12) + pleat * t
    789:             kirt_g[i, j] = np.array([base_w[0], base_w[1], zz]) + d_out * bell
    790:     add("ivory_underkirtle", "heraldry", _grid_shell_in_blender("Kirtle", kirt_g, 0.003, 1, cyclic_u=True),
    791:         "skirt_stiff", "skirt")
    792: 
    793:     # 3b. Split Royal-Indigo Swallowtail Surcoat Panels (open front V & side slits, gold piped border!)
    794:     for p_idx, (az0, az1) in enumerate(((22.0, 162.0), (-162.0, -22.0))):
    795:         nu_s, nv_s = 22, 14
    796:         sur_g = np.zeros((nu_s, nv_s, 3))
    797:         az_list = np.linspace(az0, az1, nu_s)
    798:         for i, az in enumerate(az_list):
    799:             u_norm = i / (nu_s - 1)
    800:             # Swallowtail V-point longer toward back-hip!
    801:             z_bot = (0.34 * hips_z + 0.66 * knee_z) - 0.065 * u_norm
    802:             base_w = torso_ray(az, hips_z + 0.015, lift=0.022, default_r=0.148)
    803:             d_out = np.array([math.sin(math.radians(az)), math.cos(math.radians(az)), 0.0])
    804:             fold = 0.009 * math.sin(u_norm * math.pi * 4.0)
    805:             side_room = 0.038 * math.sin(math.radians(az)) ** 2
    806:             for j, t in enumerate(np.linspace(0, 1, nv_s)):
    807:                 zz = (hips_z + 0.025) * (1 - t) + z_bot * t
    808:                 sur_g[i, j] = np.array([base_w[0], base_w[1], zz]) + d_out * ((0.130 + side_room) * (t ** 1.10) + fold * t)
    809:         add(f"surcoat_panel_{p_idx}", "signature", _grid_shell_in_blender(f"Surcoat{p_idx}", sur_g, 0.004, 1),
    810:             "skirt_stiff", "skirt")
    811:         # Gold border piping all along front split, bottom hem, and back slit!
    812:         border = np.vstack([sur_g[0, :], sur_g[1:, -1], sur_g[-1, -2::-1]])
    813:         add(f"surcoat_gold_{p_idx}", "gold", _curve_pipe_in_blender(f"SurGold{p_idx}", border, 0.0030),
    814:             "skirt_stiff", "skirt")
    815: 
    816:     # 3c. Articulated Fluted Steel Hip-Tassets (2 sculpted plates per hip over the surcoat!)
    817:     for side_nm, sx in (("R", 1.0), ("L", -1.0)):
    818:         for tl in range(2):
    819:             nu_ts, nv_ts = 14, 6
    820:             tas_g = np.zeros((nu_ts, nv_ts, 3))
    821:             az_seq = np.linspace(sx * 38.0, sx * 124.0, nu_ts)
    822:             if sx < 0:
    823:                 az_seq = az_seq[::-1]
    824:             z_t0 = hips_z + 0.015 - tl * 0.072
    825:             for i, az in enumerate(az_seq):
    826:                 u_mid = 1.0 - abs(i / (nu_ts - 1) * 2.0 - 1.0)
    827:                 z_t1 = z_t0 - (0.088 + 0.024 * u_mid)
    828:                 base_w = torso_ray(az, hips_z + 0.015, lift=0.028 + tl * 0.010, default_r=0.150)
    829:                 d_out = np.array([math.sin(math.radians(az)), math.cos(math.radians(az)), 0.0])
    830:                 flute = 0.004 * math.cos(i * 1.3)
    831:                 for j, s in enumerate(np.linspace(0, 1, nv_ts)):
    832:                     zz = z_t0 * (1 - s) + z_t1 * s
    833:                     tas_g[i, j] = np.array([base_w[0], base_w[1], zz]) + d_out * ((0.035 + tl * 0.032) + 0.042 * s + flute)
    834:             add(f"tasset_{side_nm}_{tl}", "steel", _grid_shell_in_blender(f"Tasset{side_nm}{tl}", tas_g, 0.0045, 1),
    835:                 "skirt_stiff", "plate")
    836:             rim_pts = np.vstack([tas_g[0, :], tas_g[1:, -1], tas_g[-1, -2::-1]])
    837:             add(f"tasset_gold_{side_nm}_{tl}", "gold", _curve_pipe_in_blender(f"TasGold{side_nm}{tl}", rim_pts, 0.0026),
    838:                 "skirt_stiff", "plate")
    839: 
    840:     # 4. Crossed Harness Sword-Belt + Sculpted Sunburst Ring Buckle + Hip Rondel Dagger
    841:     belt_pts = np.array([
    842:         torso_ray(az, waist_z - 0.018 - 0.018 * math.sin(math.radians(az)), lift=0.028)
    843:         for az in np.linspace(-180, 180, 48, endpoint=False)
    844:     ])
    845:     belt_g = np.stack([belt_pts + [0, 0, 0.018], belt_pts - [0, 0, 0.018]], axis=1)
    846:     add("sword_belt", "leather", _grid_shell_in_blender("SwordBelt", belt_g, 0.005, 1, cyclic_u=True), "hips_stiff", "belt")
    847: 
    848:     b_front = torso_ray(0.0, waist_z - 0.018, lift=0.035)
    849:     bpy.ops.mesh.primitive_torus_add(
    850:         major_radius=0.022, minor_radius=0.0055, major_segments=20, minor_segments=8,
    851:         location=tuple(b_front), rotation=(math.radians(90.0), 0.0, 0.0)
    852:     )
    853:     bk_ob = bpy.context.active_object
    854:     for poly in bk_ob.data.polygons:
    855:         poly.use_smooth = True
    856:     add("belt_ring_buckle", "gold", eval_mesh_data(bk_ob, True), "hips_stiff", "belt")
    857:     bpy.data.objects.remove(bk_ob, do_unlink=True)
    858: 
    859:     # Left-hip Gilded Rondel Misericorde Dagger in Scabbard
    860:     hip_L = torso_ray(-86.0, waist_z - 0.042, lift=0.048)
    861:     dag_dir = np.array([-0.12, -0.36, -0.92])
    862:     dag_dir /= np.linalg.norm(dag_dir)
    863:     scab_pts = [hip_L + dag_dir * s for s in np.linspace(0.0, 0.25, 8)]
    864:     add("dagger_scabbard", "leather", _curve_pipe_in_blender("DagScab", scab_pts, 0.011, seg=10), "hips_stiff", "belt")
    865:     add("dagger_chape", "gold", _curve_pipe_in_blender("DagChape", scab_pts[-3:], 0.0125, seg=10), "hips_stiff", "belt")
    866:     hilt_pts = [hip_L - dag_dir * s for s in np.linspace(0.0, 0.11, 6)]
    867:     add("dagger_grip", "gold", _curve_pipe_in_blender("DagGrip", hilt_pts, 0.009, seg=10), "hips_stiff", "belt")
    868: 
    869:     # 5. Asymmetric Winged Pauldrons + Gathered Lantern Sleeves + Articulated Vambraces, Couters & Gauntlets
    870:     for side_nm, sx in (("L", -1.0), ("R", 1.0)):
    871:         ua = B[f"J_Bip_{side_nm}_UpperArm"]
    872:         la = B[f"J_Bip_{side_nm}_LowerArm"]
    873:         hd = B[f"J_Bip_{side_nm}_Hand"]
    874:         ax_u = (la - ua) / np.linalg.norm(la - ua)
    875:         ax_l = (hd - la) / np.linalg.norm(hd - la)
    876: 
    877:         # Lantern cloth upper sleeve with sculpted pleats gathering at elbow
    878:         nu_sl, nv_sl = 24, 12
    879:         sl_g = np.zeros((nu_sl, nv_sl, 3))
    880:         up_u = np.array([0.0, 1.0, 0.0]) - ax_u * ax_u[1]
    881:         up_u /= np.linalg.norm(up_u)
    882:         lat_u = np.cross(ax_u, up_u)
    883:         len_u = np.linalg.norm(la - ua)
    884:         for i, ang in enumerate(np.linspace(0, 2 * math.pi, nu_sl, endpoint=False)):
    885:             d_r = math.cos(ang) * up_u + math.sin(ang) * lat_u
    886:             pleat = 0.005 * math.sin(ang * 7.0)
    887:             for j, t in enumerate(np.linspace(-0.04, 1.02, nv_sl)):
    888:                 puff = 0.046 + 0.022 * math.sin(math.pi * np.clip(t, 0, 1)) ** 0.8 + pleat * math.sin(math.pi * np.clip(t, 0, 1))
    889:                 sl_g[i, j] = ua + ax_u * (len_u * t) + d_r * puff
    890:         add(f"lantern_sleeve_{side_nm}", "signature",
    891:             _grid_shell_in_blender(f"Sleeve{side_nm}", sl_g, 0.003, 1, cyclic_u=True), f"uarm_{side_nm}", "doublet")
    892: 
    893:         # Asymmetric Winged Pauldrons: Left (shield side) has 4 grand fluted lames + haute-piece crest; Right has 3 sleek lames!
    894:         n_lames = 4 if side_nm == "L" else 3
    895:         out_sh = np.array([sx * 0.88, 0.0, 0.48])
    896:         out_sh /= np.linalg.norm(out_sh)
    897:         fwd_sh = np.array([0.0, 1.0, 0.0])
    898:         for kl in range(n_lames):
    899:             nu_p, nv_p = 18, 5
    900:             pl_g = np.zeros((nu_p, nv_p, 3))
    901:             span_deg = 128.0 - kl * 8.0
    902:             for i, u_ang in enumerate(np.linspace(-span_deg, span_deg, nu_p)):
    903:                 ur = math.radians(u_ang)
    904:                 dir_p = math.cos(ur) * out_sh + math.sin(ur) * fwd_sh
    905:                 dir_p /= np.linalg.norm(dir_p)
    906:                 crest = 0.022 * (1.0 - abs(u_ang) / span_deg) if (side_nm == "L" and kl == 0) else 0.008 * (1.0 - abs(u_ang) / span_deg)
    907:                 for j, s in enumerate(np.linspace(0, 1, nv_p)):
    908:                     c_p = ua + np.array([sx * 0.012, 0.0, 0.036 - kl * 0.030 - s * 0.042])
    909:                     r_p = (0.068 + kl * 0.005 + s * 0.012) * (1.0 + 0.12 * math.cos(ur))
    910:                     pl_g[i, j] = c_p + dir_p * r_p + np.array([0.0, 0.0, crest * (1 - s)])
    911:             if sx < 0:
    912:                 pl_g = pl_g[::-1]
    913:             add(f"pauldron_{side_nm}_{kl}", "steel", _grid_shell_in_blender(f"Pauld{side_nm}{kl}", pl_g, 0.0045, 1),
    914:                 f"pauldron_{side_nm}", "plate")
    915:             if kl in (0, n_lames - 1):
    916:                 add(f"pauldron_gold_{side_nm}_{kl}", "gold",
    917:                     _curve_pipe_in_blender(f"PauldGold{side_nm}{kl}", pl_g[:, -1], 0.0028), f"pauldron_{side_nm}", "plate")
    918: 
    919:         # Articulated Steel Vambrace + Gold Cuffs + Winged Elbow Couter
    920:         up_l = np.array([0.0, 1.0, 0.0]) - ax_l * ax_l[1]
    921:         up_l /= np.linalg.norm(up_l)
    922:         lat_l = np.cross(ax_l, up_l)
    923:         len_l = np.linalg.norm(hd - la)
    924:         nu_v, nv_v = 22, 8
    925:         vam_g = np.zeros((nu_v, nv_v, 3))
    926:         for i, ang in enumerate(np.linspace(0, 2 * math.pi, nu_v, endpoint=False)):
    927:             d_r = math.cos(ang) * up_l + math.sin(ang) * lat_l
    928:             flute = 0.0022 * math.cos(ang * 4.0)
    929:             for j, t in enumerate(np.linspace(0.08, 0.94, nv_v)):
    930:                 r_v = 0.046 * (1.0 - 0.22 * t) + 0.009 * max(0.0, 0.25 - t) * 3.0 + flute
    931:                 vam_g[i, j] = la + ax_l * (len_l * t) + d_r * r_v
    932:         add(f"vambrace_{side_nm}", "steel", _grid_shell_in_blender(f"Vam{side_nm}", vam_g, 0.004, 1, cyclic_u=True),
    933:             f"larm_{side_nm}", "plate")
    934:         add(f"vambrace_gold_top_{side_nm}", "gold", _curve_pipe_in_blender(f"VamGT{side_nm}", vam_g[:, 0], 0.0028, True),
    935:             f"larm_{side_nm}", "plate")
    936:         add(f"vambrace_gold_bot_{side_nm}", "gold", _curve_pipe_in_blender(f"VamGB{side_nm}", vam_g[:, -1], 0.0028, True),
    937:             f"larm_{side_nm}", "plate")
    938: 
    939:         # Sculpted Winged Elbow Couter
    940:         cout_g = np.zeros((13, 5, 3))
    941:         out_el = np.array([sx * 0.85, -0.52, 0.0])
    942:         out_el /= np.linalg.norm(out_el)
    943:         perp_el = np.cross(ax_l, out_el)
    944:         for i, u_a in enumerate(np.linspace(-95, 95, 13)):
    945:             ur = math.radians(u_a)
    946:             d_e = math.cos(ur) * out_el + math.sin(ur) * perp_el
    947:             wing = 1.0 + 0.45 * max(0.0, math.sin(ur * sx))
    948:             for j, s in enumerate(np.linspace(-1, 1, 5)):
    949:                 cout_g[i, j] = la + ax_l * (0.036 * s * wing) + d_e * (0.056 - 0.012 * s * s)
    950:         add(f"couter_{side_nm}", "steel", _grid_shell_in_blender(f"Couter{side_nm}", cout_g, 0.004, 1),
    951:             f"larm_{side_nm}", "plate")
    952: 
    953:         # Gauntlet dorsal hand plate over dark leather glove
    954:         gaunt_c = la + ax_l * (len_l + 0.035) + np.array([sx * 0.012, 0.0, 0.0])
    955:         bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=10, radius=1.0, location=(0, 0, 0))
    956:         gt_ob = bpy.context.active_object
    957:         gv = np.empty(len(gt_ob.data.vertices) * 3, dtype=np.float64)
    958:         gt_ob.data.vertices.foreach_get("co", gv)
    959:         gv = gv.reshape(-1, 3) * np.array([0.022, 0.038, 0.044]) + gaunt_c
    960:         gt_ob.data.vertices.foreach_set("co", gv.ravel())
    961:         gt_ob.data.update()
    962:         for poly in gt_ob.data.polygons:
    963:             poly.use_smooth = True
    964:         add(f"gauntlet_cuff_{side_nm}", "steel", eval_mesh_data(gt_ob, True), f"hand_{side_nm}", "plate")
    965:         bpy.data.objects.remove(gt_ob, do_unlink=True)
    966: 
    967:     # 6. Full Leg Harness: Breeches + Leather Thigh Cuisses + Winged Steel Poleyns + Fluted Shin-Greaves + 4-Lame Sabatons
    968:     for side_nm, sx in (("L", -1.0), ("R", 1.0)):
    969:         ul = B[f"J_Bip_{side_nm}_UpperLeg"]
    970:         ll = B[f"J_Bip_{side_nm}_LowerLeg"]
    971:         ft = B[f"J_Bip_{side_nm}_Foot"]
    972:         tb = B[f"J_Bip_{side_nm}_ToeBase"]
    973: 
    974:         def leg_ray(z_val, az_deg, lift=0.006, def_r=0.068):
    975:             az = math.radians(az_deg)
    976:             cx = float(np.interp(z_val, [ankle_z, knee_z, ul[2]], [ft[0], ll[0], ul[0]]))
    977:             cy = float(np.interp(z_val, [ankle_z, knee_z, ul[2]], [ft[1], ll[1], ul[1]]))
    978:             orig = Vector((cx, cy, z_val))
    979:             d = Vector((math.sin(az), math.cos(az), 0.0))
    980:             # Restrict ray length so it stays on this leg
    981:             hit, _, _, _ = bvh_body.ray_cast(orig + d * 0.14, -d, 0.135)
    982:             r = (hit - orig).length if hit is not None else def_r
    983:             r = np.clip(r, 0.036, 0.115)
    984:             return np.array([orig.x + d.x * (r + lift), orig.y + d.y * (r + lift), z_val])
    985: 
    986:         # Tailored dark breeches from hip to ankle
    987:         nu_lg, nv_lg = 26, 16
    988:         br_g = np.zeros((nu_lg, nv_lg, 3))
    989:         for i, az in enumerate(np.linspace(-180, 180, nu_lg, endpoint=False)):
    990:             for j, z_val in enumerate(np.linspace(ul[2] + 0.03, ankle_z + 0.02, nv_lg)):
    991:                 br_g[i, j] = leg_ray(z_val, az, lift=0.0045)
    992:         add(f"breeches_{side_nm}", "doublet",
    993:             _grid_shell_in_blender(f"Breech{side_nm}", br_g, 0.0025, 1, cyclic_u=True), f"leg_skin_{side_nm}", "trousers")
    994: 
    995:         # Dark Espresso Leather Cavalier Boot / Thigh Cuisse Cuff (knee + 9 cm down to ankle)
    996:         bt_g = np.zeros((26, 12, 3))
    997:         for i, az in enumerate(np.linspace(-180, 180, 26, endpoint=False)):
    998:             v_notch = 0.022 * max(0.0, math.cos(math.radians(az)))  # subtle cavalier V-peak at front thigh!
    999:             for j, t in enumerate(np.linspace(0, 1, 12)):
    1000:                 zz = (knee_z + 0.085 + v_notch) * (1 - t) + (ankle_z + 0.01) * t
    1001:                 cuff_flare = 0.012 * max(0.0, 0.25 - t) * 4.0
    1002:                 bt_g[i, j] = leg_ray(zz, az, lift=0.0085 + cuff_flare)
    1003:         add(f"cavalier_boot_{side_nm}", "boot",
    1004:             _grid_shell_in_blender(f"Boot{side_nm}", bt_g, 0.0035, 1, cyclic_u=True), f"leg_skin_{side_nm}", "boots")
    1005:         add(f"boot_top_gold_{side_nm}", "gold", _curve_pipe_in_blender(f"BootG{side_nm}", bt_g[:, 0], 0.0025, True),
    1006:             f"uleg_{side_nm}", "boots")
    1007: 
    1008:         # Sculpted Winged Steel Poleyn (faceted knee cop + swept outer side-wing!)
    1009:         pol_g = np.zeros((17, 7, 3))
    1010:         for i, az in enumerate(np.linspace(-112, 112, 17)):
    1011:             wing_ext = 0.032 * max(0.0, math.sin(math.radians(az * sx))) ** 1.5
    1012:             keel = 0.014 * max(0.0, 1.0 - abs(az) / 36.0) ** 1.5
    1013:             for j, s in enumerate(np.linspace(-1.0, 1.0, 7)):
    1014:                 zz = knee_z + 0.012 - s * (0.058 + 0.5 * wing_ext)
    1015:                 pol_g[i, j] = leg_ray(zz, az, lift=0.015 + keel * (1.0 - 0.6 * s * s) + wing_ext * (1.0 - 0.4 * s * s))
    1016:         add(f"poleyn_{side_nm}", "steel", _grid_shell_in_blender(f"Poleyn{side_nm}", pol_g, 0.0045, 1),
    1017:             f"lleg_{side_nm}", "plate")
    1018:         pol_rim = np.vstack([pol_g[:, 0], pol_g[-1, 1:], pol_g[::-1, -1], pol_g[0, -2::-1]])
    1019:         add(f"poleyn_gold_{side_nm}", "gold", _curve_pipe_in_blender(f"PolGold{side_nm}", pol_rim, 0.0025, True),
    1020:             f"lleg_{side_nm}", "plate")
    1021: 
    1022:         # Anatomically Contoured Fluted Steel Shin-Greave (front + outer calf shell with crisp shin keel!)
    1023:         grv_g = np.zeros((21, 10, 3))
    1024:         for i, az in enumerate(np.linspace(-118, 118, 21)):
    1025:             shin_keel = 0.010 * max(0.0, 1.0 - abs(az) / 26.0) ** 1.6
    1026:             for j, t in enumerate(np.linspace(0, 1, 10)):
    1027:                 zz = (knee_z - 0.048) * (1 - t) + (ankle_z + 0.042) * t
    1028:                 grv_g[i, j] = leg_ray(zz, az, lift=0.012 + shin_keel)
    1029:         add(f"fluted_greave_{side_nm}", "steel", _grid_shell_in_blender(f"Greave{side_nm}", grv_g, 0.0045, 1),
    1030:             f"lleg_{side_nm}", "plate")
    1031:         grv_rim = np.vstack([grv_g[:, 0], grv_g[-1, 1:], grv_g[::-1, -1], grv_g[0, -2::-1]])
    1032:         add(f"greave_gold_{side_nm}", "gold", _curve_pipe_in_blender(f"GrvGold{side_nm}", grv_rim, 0.0026, True),
    1033:             f"lleg_{side_nm}", "plate")
    1034: 
    1035:         # 4-Lame Articulated Pointed-Almond Steel Sabaton + Heeled Dark Leather Riding Boot Sole (100% enclosed!)
    1036:         heel_y = ft[1] - 0.048
    1037:         toe_y = tb[1] + 0.088
    1038:         foot_cx = ft[0]
    1039:         # Enclosed leather boot base + heel resting cleanly on Z = 0
    1040:         nu_f0, nv_f0 = 24, 10
    1041:         fbase_g = np.zeros((nu_f0, nv_f0, 3))
    1042:         for i, th in enumerate(np.linspace(0, 2 * math.pi, nu_f0, endpoint=False)):
    1043:             for j, s in enumerate(np.linspace(0, 1, nv_f0)):
    1044:                 yy = heel_y * (1 - s) + toe_y * s
    1045:                 taper_toe = (1.0 - 0.62 * max(0.0, (s - 0.55) / 0.45) ** 1.5)
    1046:                 hw = 0.048 * taper_toe
    1047:                 hz = 0.044 * (1.0 - 0.52 * s)
    1048:                 zc = 0.042 * (1.0 - 0.42 * s)
    1049:                 px = foot_cx + hw * math.cos(th)
    1050:                 pz = max(0.002, zc + hz * math.sin(th))
    1051:                 fbase_g[i, j] = [px, yy, pz]
    1052:         add(f"boot_foot_{side_nm}", "boot", _grid_shell_in_blender(f"BootFoot{side_nm}", fbase_g, 0.003, 1, cyclic_u=True),
    1053:             f"foot_{side_nm}", "boots")
    1054: 
    1055:         # 3 Overlapping Dorsal Steel Sabaton Lames over the instep!
    1056:         for sl_i in range(3):
    1057:             sab_g = np.zeros((15, 4, 3))
    1058:             s0 = 0.16 + sl_i * 0.24
    1059:             s1 = s0 + 0.28
    1060:             for i, u_a in enumerate(np.linspace(-85, 85, 15)):
    1061:                 ur = math.radians(u_a)
    1062:                 keel = 0.007 * max(0.0, 1.0 - abs(u_a) / 30.0)
    1063:                 for j, s in enumerate(np.linspace(s0, min(0.98, s1), 4)):
    1064:                     yy = heel_y * (1 - s) + toe_y * s
    1065:                     taper_toe = (1.0 - 0.58 * max(0.0, (s - 0.55) / 0.45) ** 1.5)
    1066:                     hw = (0.052 + sl_i * 0.0015) * taper_toe
    1067:                     hz = (0.049 + sl_i * 0.0015) * (1.0 - 0.48 * s)
    1068:                     zc = 0.042 * (1.0 - 0.42 * s)
    1069:                     sab_g[i, j] = [foot_cx + hw * math.sin(ur), yy, zc + hz * math.cos(ur) + keel]
    1070:             add(f"sabaton_lame_{side_nm}_{sl_i}", "steel",
    1071:                 _grid_shell_in_blender(f"Sab{side_nm}{sl_i}", sab_g, 0.0035, 1), f"foot_{side_nm}", "plate")
    1072: 
    1073:     # 7. Twin Sculpted Sunburst Gold Cloak Brooches + Draped Ceremonial Gold Aiguillette Chest-Chain
    1074:     brooch_pts = []
    1075:     for k_b, sx in enumerate((-1.0, 1.0)):
    1076:         bp_c = torso_ray(sx * 36.0, uchest_z + 0.055, lift=0.024)
    1077:         brooch_pts.append(bp_c)
    1078:         bpy.ops.mesh.primitive_cylinder_add(vertices=18, radius=0.020, depth=0.009,
    1079:                                             location=tuple(bp_c), rotation=(math.radians(78.0), 0.0, math.radians(-sx * 28.0)))
    1080:         br_ob = bpy.context.active_object
    1081:         add(f"sunburst_brooch_{k_b}", "gold", eval_mesh_data(br_ob, True), "uchest_blend", "trim")
    1082:         bpy.data.objects.remove(br_ob, do_unlink=True)
    1083: 
    1084:     for c_idx, sag in enumerate((0.026, 0.048)):
    1085:         c_pts = []
    1086:         for t in np.linspace(0, 1, 17):
    1087:             az = -36.0 * (1 - t) + 36.0 * t
    1088:             zz = (uchest_z + 0.052) - sag * math.sin(math.pi * t)
    1089:             c_pts.append(torso_ray(az, zz, lift=0.028 + 0.004 * c_idx))
    1090:         add(f"aiguillette_chain_{c_idx}", "gold", _curve_pipe_in_blender(f"Chain{c_idx}", np.array(c_pts), 0.0030),
    1091:             "uchest_blend", "trim")
    1092: 
    1093:     # 8. "Aurelia" Swept-Wing Silverwing Longsword (built in right-hand grip frame)
    1094:     M_rh = guard_arm_L_vrm["M_R_Hand"]
    1095:     R_rh = M_rh[:3, :3] / np.linalg.norm(M_rh[:3, :3], axis=0)
    1096:     fist_vrm = guard_arm_L_vrm["fist_R"]
    1097:     fwd_vrm = R_rh @ np.array([0.0, 0.0, -1.0])
    1098:     side_vrm = R_rh @ np.array([1.0, 0.0, 0.0])
    1099:     flat_vrm = np.cross(fwd_vrm, side_vrm)

    51 more lines not shown.

  • read_file{"EndLine":1443,"Path":"~/work/lowmarch/tools/blender_sculpt_cast.py","StartLine":1151}

    input

    {
      "EndLine": 1443,
      "Path": "~/work/lowmarch/tools/blender_sculpt_cast.py",
      "StartLine": 1151
    }

    result, 294 lines

    Showing lines 1151-1443 of 1443
    1151:     tip_idx = len(bl_verts)
    1152:     bl_verts.append(blade_base + fwd_bl * (blade_len + 0.018))
    1153:     for k in range(4):
    1154:         bl_faces.append([(rows_b - 1) * 4 + k, tip_idx, (rows_b - 1) * 4 + (k + 1) % 4])
    1155:     ob_blade = make_mesh_obj("AureliaBlade", np.array(bl_verts), np.array(bl_faces))
    1156:     # Sharp diamond-facet normals on the sword blade so steel cel planes catch razor highlights!
    1157:     add("aurelia_blade", "steel", eval_mesh_data(ob_blade, True), "rhand_rigid", "sword")
    1158:     bpy.data.objects.remove(ob_blade, do_unlink=True)
    1159: 
    1160:     ric_pts = [blade_base + fwd_bl * s for s in np.linspace(0.0, 0.088, 6)]
    1161:     add("aurelia_ricasso", "gold", _curve_pipe_in_blender("AuRicasso", ric_pts, 0.0082, seg=8), "rhand_rigid", "sword")
    1162: 
    1163:     # 9. "Lowmarch Aegis" Convex Winged Kite-Heater Shield with 3D Sculpted Gold Sunburst-and-Wings Crest!
    1164:     sc_bl = vrm_to_bl(guard_arm_L_vrm["shield_centre"])
    1165:     sout_bl = vrm_to_bl(guard_arm_L_vrm["shield_out"])
    1166:     sup_bl = vrm_to_bl(guard_arm_L_vrm["shield_up"])
    1167:     sfw_bl = np.cross(sout_bl, sup_bl)
    1168: 
    1169:     nu_sh, nv_sh = 25, 18
    1170:     sh_w, sh_h = 0.38, 0.56
    1171:     sh_g = np.zeros((nu_sh, nv_sh, 3))
    1172:     for j, v_t in enumerate(np.linspace(0, 1, nv_sh)):
    1173:         # Winged scalloped top edge, tapering gracefully to kite-heater point!
    1174:         py = sh_h * (0.34 - v_t)
    1175:         width_t = (1.0 - max(0.0, (v_t - 0.18) / 0.82) ** 1.85)
    1176:         for i, u_s in enumerate(np.linspace(-1.0, 1.0, nu_sh)):
    1177:             px = (sh_w * 0.5) * u_s * width_t
    1178:             top_wing = 0.018 * (u_s ** 2 - 0.35 * (1 - u_s ** 2)) * max(0.0, 1.0 - v_t * 3.5)
    1179:             bulge = 0.038 * (1.0 - 0.85 * (u_s ** 2) * (width_t ** 2)) * (1.0 - 0.25 * (v_t - 0.35) ** 2)
    1180:             sh_g[i, j] = sc_bl + sfw_bl * px + sup_bl * (py + top_wing) + sout_bl * bulge
    1181:     add("aegis_body", "signature", _grid_shell_in_blender("AegisBody", sh_g, 0.010, 1), "larm_rigid", "shield")
    1182: 
    1183:     # Stepped Gold Outer Rim around the entire shield perimeter!
    1184:     sh_perim = np.vstack([sh_g[:, 0], sh_g[-1, 1:], sh_g[::-1, -1], sh_g[0, -2::-1]]) + sout_bl * 0.008
    1185:     add("aegis_gold_rim", "gold", _curve_pipe_in_blender("AegisRim", sh_perim, 0.0068, cyclic=True, seg=10),
    1186:         "larm_rigid", "shield")
    1187: 
    1188:     # 3D Sculpted Gold Heraldic Winged-Sword & Sunburst Relief Crest on Shield Front!
    1189:     def sh_surf(ux, vy, lift=0.013):
    1190:         bulge = 0.038 * (1.0 - 0.85 * (ux / (sh_w * 0.5)) ** 2) * (1.0 - 0.25 * ((0.34 - vy / sh_h) - 0.35) ** 2)
    1191:         return sc_bl + sfw_bl * ux + sup_bl * vy + sout_bl * (bulge + lift)
    1192: 
    1193:     # Central vertical heraldic sword-spire + twin swept wings + sunburst boss!
    1194:     spire = np.array([sh_surf(0.0, vy, 0.015) for vy in np.linspace(-0.24, 0.14, 12)])
    1195:     add("aegis_crest_spire", "gold", _curve_pipe_in_blender("CrestSpire", spire, 0.0075, seg=8), "larm_rigid", "shield")
    1196:     for sx in (-1.0, 1.0):
    1197:         for w_tier, (y0, span_x, rise_y) in enumerate(((0.02, 0.135, 0.095), (-0.045, 0.105, 0.068), (-0.105, 0.072, 0.042))):
    1198:             w_pts = np.array([sh_surf(sx * span_x * t, y0 + rise_y * (t ** 1.3), 0.014) for t in np.linspace(0.08, 1.0, 9)])
    1199:             add(f"aegis_wing_{sx}_{w_tier}", "gold", _curve_pipe_in_blender(f"AWing{sx}{w_tier}", w_pts, 0.0058 - 0.0008 * w_tier, seg=8),
    1200:                 "larm_rigid", "shield")
    1201: 
    1202:     boss_c = sh_surf(0.0, 0.025, 0.018)
    1203:     bpy.ops.mesh.primitive_uv_sphere_add(segments=18, ring_count=10, radius=1.0, location=(0, 0, 0))
    1204:     bs_ob = bpy.context.active_object
    1205:     bv = np.empty(len(bs_ob.data.vertices) * 3, dtype=np.float64)
    1206:     bs_ob.data.vertices.foreach_get("co", bv)
    1207:     bv = bv.reshape(-1, 3)
    1208:     bv_w = boss_c + np.outer(bv[:, 0] * 0.032, sfw_bl) + np.outer(bv[:, 1] * 0.032, sup_bl) + np.outer(bv[:, 2] * 0.016, sout_bl)
    1209:     bs_ob.data.vertices.foreach_set("co", bv_w.ravel())
    1210:     bs_ob.data.update()
    1211:     add("aegis_boss", "steel", eval_mesh_data(bs_ob, True), "larm_rigid", "shield")
    1212:     bpy.data.objects.remove(bs_ob, do_unlink=True)
    1213: 
    1214:     # Interior leather forearm pad + double enarme straps on shield reverse
    1215:     for ey in (-0.06, 0.07):
    1216:         en_pts = np.array([
    1217:             sc_bl + sup_bl * ey + sfw_bl * (0.055 * math.sin(a)) - sout_bl * (0.012 + 0.042 * math.cos(a))
    1218:             for a in np.linspace(-math.pi * 0.48, math.pi * 0.48, 11)
    1219:         ])
    1220:         add(f"aegis_enarme_{ey}", "leather", _curve_pipe_in_blender(f"Enarme{ey}", en_pts, 0.0075, seg=8),
    1221:             "larm_rigid", "shield")
    1222: 
    1223:     return pieces
    1224: 
    1225: 
    1226: # ---------------------------------------------------------------------------
    1227: # 4. Korin Adversarial Upgrade: Blender 5.2 Spiky Wolf-Cut Hair + Northern Pauldrons & Fur Mantle
    1228: # ---------------------------------------------------------------------------
    1229: def build_korin_blender_upgrades(face_pos_vrm, face_tri, body_pos_vrm, body_tri, bones_vrm, lm_vrm):
    1230:     fp_bl = vrm_to_bl(face_pos_vrm)
    1231:     bp_bl = vrm_to_bl(body_pos_vrm)
    1232:     neck_z = bones_vrm["J_Bip_C_Neck"][1]
    1233:     uchest_z = bones_vrm["J_Bip_C_UpperChest"][1]
    1234:     eye_z = float(lm_vrm["eye_y"])
    1235:     fore_bl = vrm_to_bl(lm_vrm["forehead"])
    1236: 
    1237:     skull_mask = bp_bl[:, 2] > neck_z - 0.02
    1238:     skull_idx_map = np.where(skull_mask)[0]
    1239:     keep_bt = np.all(skull_mask[body_tri], axis=1)
    1240:     all_v = np.vstack([fp_bl, bp_bl[skull_mask]])
    1241:     remap = np.zeros(len(bp_bl), dtype=np.int32)
    1242:     remap[skull_idx_map] = np.arange(len(skull_idx_map)) + len(fp_bl)
    1243:     all_f = np.vstack([face_tri, remap[body_tri[keep_bt]]])
    1244:     bvh = BVHTree.FromPolygons(all_v.tolist(), all_f.tolist())
    1245:     hc = np.array([0.0, fore_bl[1] - 0.090, eye_z + 0.036])
    1246: 
    1247:     def skull_pt(az_deg, el_deg, lift=0.008):
    1248:         az, el = math.radians(az_deg), math.radians(el_deg)
    1249:         d = Vector((math.sin(el) * math.sin(az), math.sin(el) * math.cos(az), math.cos(el)))
    1250:         loc, _, _, _ = bvh.ray_cast(Vector(hc) + d * 0.34, -d, 0.32)
    1251:         if loc is None:
    1252:             return hc + np.array([d.x, d.y, d.z]) * (0.108 + lift)
    1253:         return np.array([loc.x, loc.y, loc.z]) + np.array([d.x, d.y, d.z]) * lift
    1254: 
    1255:     bev_lock, tap_lock = _make_chevron_bevel_and_taper("lock")
    1256:     hair_objs = []
    1257: 
    1258:     # Cranial hair volume shell
    1259:     nu, nv = 42, 18
    1260:     dome_g = np.zeros((nu, nv, 3))
    1261:     for i, az in enumerate(np.linspace(-180, 180, nu, endpoint=False)):
    1262:         hl = float(np.interp(abs(az), [0, 38, 72, 110, 150, 180], [48, 56, 78, 108, 134, 142]))
    1263:         for j, t in enumerate(np.linspace(0.03, 1.0, nv)):
    1264:             dome_g[i, j] = skull_pt(az, hl * t, lift=0.005 + 0.015 * math.sin(math.pi * min(1.0, t * 1.1)))
    1265:     c_top = skull_pt(0, 0, 0.017)
    1266:     dv = [c_top] + dome_g.reshape(-1, 3).tolist()
    1267:     df = []
    1268:     for i in range(nu):
    1269:         inext = (i + 1) % nu
    1270:         df.append([0, 1 + i * nv, 1 + inext * nv])
    1271:         for j in range(nv - 1):
    1272:             a, b, c, d = 1 + i * nv + j, 1 + inext * nv + j, 1 + inext * nv + j + 1, 1 + i * nv + j + 1
    1273:             df.extend([[a, b, c], [a, c, d]])
    1274:     d_ob = make_mesh_obj("KorinDome", np.array(dv), np.array(df))
    1275:     for poly in d_ob.data.polygons:
    1276:         poly.use_smooth = True
    1277:     hair_objs.append(d_ob)
    1278: 
    1279:     # Rugged Windswept Spiky Wolf-Cut Locks (32 bold 3D locks!)
    1280:     # Jagged parted brow spikes
    1281:     for k, (az0, az1, el_end, flare, wd) in enumerate([
    1282:         (14, -4, 78, 0.014, 0.021),
    1283:         (22, 10, 82, 0.016, 0.019),
    1284:         (-6, -22, 76, 0.016, 0.020),
    1285:         (-18, -38, 82, 0.018, 0.022),
    1286:         (28, 44, 86, 0.019, 0.021),
    1287:         (-32, -52, 88, 0.019, 0.020),
    1288:     ]):
    1289:         pts = [
    1290:             skull_pt(az0 * 0.4, 22, 0.018),
    1291:             skull_pt((az0 + az1) * 0.5, 46, 0.023),
    1292:             skull_pt(az1, 66, 0.022),
    1293:             skull_pt(az1, el_end, flare),
    1294:         ]
    1295:         hair_objs.append(_add_lock_curve(f"KBang_{k}", pts, wd, 0.48, hc, bev_lock, tap_lock))
    1296: 
    1297:     # Swept-back wild crown & lateral wolf-spikes!
    1298:     for k, az in enumerate(range(-165, 180, 22)):
    1299:         if abs(az) < 35:
    1300:             continue
    1301:         sgn = 1.0 if az >= 0 else -1.0
    1302:         pts = [
    1303:             skull_pt(az * 0.45, 20, 0.019),
    1304:             skull_pt(az * 0.85, 50, 0.028),
    1305:             skull_pt(az + sgn * 8, 82, 0.034),
    1306:             skull_pt(az + sgn * 14, 108, 0.046) + np.array([sgn * 0.016, -0.018, 0.008]),
    1307:         ]
    1308:         hair_objs.append(_add_lock_curve(f"KWolfSpike_{k}", pts, 0.025, 0.52, hc, bev_lock, tap_lock, twist=sgn * 0.2))
    1309: 
    1310:     # Shaggy collar-grazing nape spikes
    1311:     for k, az in enumerate((-135, -155, -172, 172, 155, 135)):
    1312:         pts = [
    1313:             skull_pt(az, 78, 0.022),
    1314:             skull_pt(az, 112, 0.028),
    1315:             skull_pt(az, 138, 0.034) + np.array([0.0, -0.022, -0.048]),
    1316:         ]
    1317:         hair_objs.append(_add_lock_curve(f"KNape_{k}", pts, 0.024, 0.50, hc, bev_lock, tap_lock))
    1318: 
    1319:     # Upper crown windswept spikes for jagged top silhouette!
    1320:     for k, (az, dx, dz) in enumerate(((-40, -0.028, 0.038), (15, 0.018, 0.044), (65, 0.032, 0.034), (145, 0.010, 0.036))):
    1321:         r0 = skull_pt(az, 28, 0.018)
    1322:         pts = [r0, r0 + np.array([dx * 0.5, -0.015, dz * 0.7]), r0 + np.array([dx, -0.042, dz])]
    1323:         hair_objs.append(_add_lock_curve(f"KCrownCrest_{k}", pts, 0.019, 0.50, hc, bev_lock, tap_lock))
    1324: 
    1325:     bpy.ops.object.select_all(action="DESELECT")
    1326:     for o in hair_objs:
    1327:         o.select_set(True)
    1328:     bpy.context.view_layer.objects.active = hair_objs[0]
    1329:     bpy.ops.object.join()
    1330:     joined = bpy.context.active_object
    1331: 
    1332:     bpy.ops.mesh.primitive_uv_sphere_add(segments=32, ring_count=20, radius=1.0, location=(0, 0, 0))
    1333:     prx = bpy.context.active_object
    1334:     pv = np.empty(len(prx.data.vertices) * 3, dtype=np.float64)
    1335:     prx.data.vertices.foreach_get("co", pv)
    1336:     pv = pv.reshape(-1, 3) * np.array([0.14, 0.15, 0.15]) + (hc + np.array([0, -0.01, 0.02]))
    1337:     prx.data.vertices.foreach_set("co", pv.ravel())
    1338:     prx.data.update()
    1339:     for poly in prx.data.polygons:
    1340:         poly.use_smooth = True
    1341:     dt = joined.modifiers.new("KDomeNrm", "DATA_TRANSFER")
    1342:     dt.object = prx
    1343:     dt.use_loop_data = True
    1344:     dt.data_types_loops = {"CUSTOM_NORMAL"}
    1345:     dt.loop_mapping = "POLYINTERP_NEAREST"
    1346:     dt.mix_factor = 0.46
    1347:     h_pos, h_nrm, h_tri = eval_mesh_data(joined, True)
    1348:     bpy.data.objects.remove(joined, do_unlink=True)
    1349:     bpy.data.objects.remove(prx, do_unlink=True)
    1350: 
    1351:     # Heavy Fluted Northern Steel Pauldrons + Sculpted Fur Shoulder Mantle!
    1352:     out = [("korin_wolf_hair", "hair", h_pos, h_nrm, h_tri, "head_rigid", "hair")]
    1353:     B = {k: vrm_to_bl(v) for k, v in bones_vrm.items()}
    1354:     for side_nm, sx in (("L", -1.0), ("R", 1.0)):
    1355:         ua = B[f"J_Bip_{side_nm}_UpperArm"]
    1356:         out_sh = np.array([sx * 0.88, 0.0, 0.48])
    1357:         out_sh /= np.linalg.norm(out_sh)
    1358:         fwd_sh = np.array([0.0, 1.0, 0.0])
    1359:         for kl in range(3):
    1360:             pl_g = np.zeros((16, 5, 3))
    1361:             span = 118.0 - kl * 8.0
    1362:             for i, ua_deg in enumerate(np.linspace(-span, span, 16)):
    1363:                 ur = math.radians(ua_deg)
    1364:                 dp = math.cos(ur) * out_sh + math.sin(ur) * fwd_sh
    1365:                 dp /= np.linalg.norm(dp)
    1366:                 for j, s in enumerate(np.linspace(0, 1, 5)):
    1367:                     cp = ua + np.array([sx * 0.015, 0.0, 0.040 - kl * 0.032 - s * 0.044])
    1368:                     rp = (0.082 + kl * 0.006 + s * 0.012) * (1.0 + 0.10 * math.cos(ur))
    1369:                     pl_g[i, j] = cp + dp * rp
    1370:             if sx < 0:
    1371:                 pl_g = pl_g[::-1]
    1372:             p_pos, p_nrm, p_tri = _grid_shell_in_blender(f"KPauld{side_nm}{kl}", pl_g, 0.005, 1)
    1373:             out.append((f"k_pauldron_{side_nm}_{kl}", "steel", p_pos, p_nrm, p_tri, f"pauldron_{side_nm}", "plate"))
    1374:             if kl == 0:
    1375:                 g_pos, g_nrm, g_tri = _curve_pipe_in_blender(f"KPGold{side_nm}", pl_g[:, -1], 0.0032)
    1376:                 out.append((f"k_pauldron_gold_{side_nm}", "gold", g_pos, g_nrm, g_tri, f"pauldron_{side_nm}", "plate"))
    1377: 
    1378:     # Sculpted Dark Fur Shoulder Mantle across upper back & shoulders!
    1379:     fur_objs = []
    1380:     nk_bl = B["J_Bip_C_Neck"]
    1381:     for i, az in enumerate(np.linspace(-132, 132, 26)):
    1382:         az_back = 180.0 + az
    1383:         ar = math.radians(az_back)
    1384:         d = np.array([math.sin(ar), math.cos(ar), 0.0])
    1385:         r0 = nk_bl + np.array([0.0, 0.0, -0.025]) + d * 0.105
    1386:         pts = [
    1387:             r0,
    1388:             r0 + d * 0.075 + np.array([0.0, 0.0, -0.018]),
    1389:             r0 + d * 0.145 + np.array([0.0, 0.0, -0.065 - 0.018 * (i % 2)]),
    1390:         ]
    1391:         fur_objs.append(_add_lock_curve(f"KFur_{i}", pts, 0.028, 0.65, nk_bl + np.array([0, 0, -0.10]), bev_lock, tap_lock))
    1392:     bpy.ops.object.select_all(action="DESELECT")
    1393:     for o in fur_objs:
    1394:         o.select_set(True)
    1395:     bpy.context.view_layer.objects.active = fur_objs[0]
    1396:     bpy.ops.object.join()
    1397:     fj = bpy.context.active_object
    1398:     f_pos, f_nrm, f_tri = eval_mesh_data(fj, True)
    1399:     bpy.data.objects.remove(fj, do_unlink=True)
    1400:     out.append(("korin_fur_mantle", "fur", f_pos, f_nrm, f_tri, "uchest_blend", "trim"))
    1401: 
    1402:     bpy.data.objects.remove(bev_lock, do_unlink=True)
    1403:     bpy.data.objects.remove(tap_lock, do_unlink=True)
    1404:     return out
    1405: 
    1406: 
    1407: def main():
    1408:     argv = sys.argv[sys.argv.index("--") + 1:]
    1409:     in_npz, out_npz, mode = argv[0], argv[1], argv[2]
    1410:     clear_scene()
    1411:     data = np.load(in_npz, allow_pickle=True)
    1412:     bones_vrm = data["bones"].item()
    1413:     lm_vrm = data["landmarks"].item()
    1414: 
    1415:     if mode == "valen":
    1416:         body_pos, body_nrm, face_pos, face_nrm = sculpt_valen_body_and_face(
    1417:             data["body_pos"], data["body_tri"], data["face_pos"], data["face_tri"], bones_vrm, lm_vrm
    1418:         )
    1419:         hair_pcs = build_valen_valkyrie_hair(
    1420:             face_pos, data["face_tri"], body_pos, data["body_tri"], bones_vrm, lm_vrm
    1421:         )
    1422:         guard_info = data["guard_info"].item()
    1423:         armour_pcs = build_valen_bespoke_armour(body_pos, data["body_tri"], bones_vrm, guard_info)
    1424:         all_pcs = [(nm, rl, p, n, t, bt, "hair") for (nm, rl, p, n, t, bt) in hair_pcs] + armour_pcs
    1425:         np.savez_compressed(
    1426:             out_npz,
    1427:             body_pos=body_pos,
    1428:             body_nrm=body_nrm,
    1429:             face_pos=face_pos,
    1430:             face_nrm=face_nrm,
    1431:             pieces=np.array(all_pcs, dtype=object),
    1432:         )
    1433:     elif mode == "korin":
    1434:         pcs = build_korin_blender_upgrades(
    1435:             data["face_pos"], data["face_tri"], data["body_pos"], data["body_tri"], bones_vrm, lm_vrm
    1436:         )
    1437:         np.savez_compressed(out_npz, pieces=np.array(pcs, dtype=object))
    1438:     else:
    1439:         raise ValueError(f"Unknown mode: {mode}")
    1440: 
    1441: 
    1442: if __name__ == "__main__":
    1443:     main()