A 3D model pipeline, pushed by GPT-6.2-Astra
agent (cont.)
+25:27exec_commandsed -n '1,245p' tools/hair.py && sed -n '155,174p;329,363p;982,1085p' tools/vroid_portrait.py (+3 more)
command
sed -n '1,245p' tools/hair.py && sed -n '155,174p;329,363p;982,1085p' tools/vroid_portrait.py cat ~/.local/share/lowmarch/trials/face-shading-2026-10-30/scripts/patch_lens_flattice.py sed -n '81,163p;178,222p;335,355p' ~/context/lowmarch.md sed -n '380,604p' tools/export_glb.py sed -n '350,411p' review/high-water/marsh.py && rg -n 'params.get|uFlatt|flattice|camera' ~/.local/share/lowmarch/trials/face-shading-2026-10-30/scripts/patch_lens_flattice.py head -155 tools/gear.py; sed -n '1,134p' tools/mobs.py; head -81 tools/outfit.py; sed -n '160,174p' tools/vroid_portrait.py
result, 748 lines
Script completed Wall time 0.2 seconds Output: Warning: truncated output (original token count: 12808) Total output lines: 925 Warning: truncated output (original token count: 5643) Total output lines: 404 """The hair kit: hair built as locks combed over the skull, instead of borrowing a VRoid sample's hair cards (portrait guide, lesson 14). HeadChart u = degrees round the head (0 front, +90 the character's right), v = degrees down from the crown (0 top, 90 level with the skull's centre, ~130 the jaw): rays from the skull's centre onto the head skin, smoothed into a shell (as plates.TorsoChart does for the body). cap the hair's base volume: a shell over the scalp down to a hairline given as v(u). lock one lock: a path of (u, v, lift) points over the head (lift = metres off the scalp), smoothed and sampled, then swept with a flat lens-shaped section whose flat side lies along the head, width tapering to a point. Past the chart's lower edge a path just continues in 3D. Every piece gets UVs (around, along) and shares one strand texture, so the painted renderer draws strand highlights along each lock; every piece rides the head bone. """ import math import numpy as np from plates import _Chart, _fill_nan from scipy.ndimage import gaussian_filter class HeadChart(_Chart): def __init__(self, head, centre, du=4.0, dv=3.0, v_max=150.0, smooth=(1.0, 1.0)): self.c = np.asarray(centre, float) self.wrap = True self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, 0.0, dv, 0.8 us = np.arange(-180.0, 180.0, du) vs = np.arange(0.0, v_max + dv * 0.5, dv) R = np.full((len(us), len(vs)), np.nan) for i, u in enumerate(us): for j, v in enumerate(vs): o, d = self.ray(u, v) R[i, j] = head.cast(o, d, rmax=0.3, far=True) R = _fill_nan(R, True) self.R = gaussian_filter(R, smooth, mode=("wrap", "nearest")) def ray(self, u, v): u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) ur, vr = np.radians(u), np.radians(v) d = np.stack([np.sin(vr) * np.sin(ur), np.cos(vr), -np.sin(vr) * np.cos(ur)], -1) return np.broadcast_to(self.c, d.shape).copy(), d def centre(self, v=None): return self.c @property def L(self): """Metres per degree of v (decals and seams measure plates on this chart in metres).""" return float(np.mean(self.R)) * np.pi / 180 def metric(self, u, v): """(arc across, arc down) in metres, for seams and decals on helmets.""" r = self.radius(u, v) 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) # ---- the shared strand texture: fine light and dark lines running along each lock ----------------- def strand_texture(n=256, seed=3): rng = np.random.default_rng(seed) x = np.arange(n) stripes = np.zeros(n) for f, a in ((3, 0.18), (7, 0.12), (17, 0.10), (41, 0.06)): stripes += a * np.sin(2 * np.pi * (f * x / n + rng.random())) stripes += 0.08 * gaussian_filter(rng.standard_normal(n), 1.2, mode="wrap") col = np.clip(0.62 + stripes, 0.25, 0.95) along = 1.0 - 0.10 * np.linspace(0, 1, n)[:, None] # a touch darker toward the tip img = (np.repeat(col[None, :], n, 0) * along * 255).astype(np.uint8) return np.dstack([img, img, img, np.full((n, n), 255, np.uint8)]) STRANDS = strand_texture() def _smooth_path(P, n): """Catmull-Rom through control points P (k, 3), sampled at n points.""" P = np.asarray(P, float) if len(P) == 2: return P[0] + (P[1] - P[0]) * np.linspace(0, 1, n)[:, None] Q = np.vstack([2 * P[0] - P[1], P, 2 * P[-1] - P[-2]]) seg = len(P) - 1 out = [] for t in np.linspace(0, seg, n): i = min(int(t), seg - 1) s = t - i p0, p1, p2, p3 = Q[i], Q[i + 1], Q[i + 2], Q[i + 3] out.append(0.5 * ((2 * p1) + (-p0 + p2) * s + (2 * p0 - 5 * p1 + 4 * p2 - p3) * s * s + (-p0 + 3 * p1 - 3 * p2 + p3) * s ** 3)) return np.array(out) def lock(name, chart, path, width, thick=0.006, n=28, seg=10, taper=(0.45, 1.0), tip=0.04, flat_to=None, role="hair", root_width=None, profile=None): """A lock along `path`: (u, v, lift) points on the chart, or 3D points (arrays of length 3 with a flag), mixed freely as ("uv", u, v, lift) / ("xyz", x, y, z). Width tapers from taper[0] of the way along to a point at the end (tip: the last fraction kept a hair's width). The flat side faces `flat_to` (a point the section looks away from; default the skull's centre).""" from outfit import piece pts = [] for p in path: if p[0] == "uv": _, u, v, lift = p pts.append(chart.point(u, v, off=lift)) else: pts.append(np.array(p[1:], float)) C = _smooth_path(pts, n) T = np.gradient(C, axis=0) T /= np.maximum(np.linalg.norm(T, axis=1, keepdims=True), 1e-9) away = C - np.asarray(flat_to if flat_to is not None else chart.c, float) N = away - T * np.einsum("ij,ij->i", away, T)[:, None] N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-9) Bv = np.cross(T, N) t = np.linspace(0, 1, n) w0 = width if root_width is None else root_width w = np.where(t < 0.12, w0 + (width - w0) * t / 0.12, width) k = np.clip((t - taper[0]) / max(taper[1] - taper[0], 1e-6), 0, 1) w = w * (1 - k ** 1.6) + tip * 0.01 * k if profile is not None: # a clump: profile(t) = width as a fraction of `width` w = width * np.array([profile(x) for x in t]) + 0.0004 k = np.clip((t - 0.6) / 0.4, 0, 1) th = thick * np.maximum(1 - k ** 1.3, 0.15) a = np.linspace(0, 2 * np.pi, seg + 1) G = (C[:, None] + Bv[:, None] * (w[:, None] / 2 * np.cos(a)[None, :])[..., None] + N[:, None] * (th[:, None] / 2 * np.sin(a)[None, :])[..., None]) from outfit import grid_mesh pos, tri = grid_mesh(G) pc = piece(name, role, pos, tri, outward_from=None) from fitting import vertex_normals fn = vertex_normals(pos, tri) radial = (pos - np.repeat(C, seg + 1, 0)) if (np.einsum("ij,ij->i", fn, radial) < 0).mean() > 0.5: pc["tri"] = tri[:, ::-1] pc["nrm"] = -fn uu, vv = np.meshgrid(a / (2 * np.pi), t, indexing="xy") pc["uv"] = np.stack([uu.ravel(), vv.ravel()], 1) pc["strands"] = True pc["group"] = "hair" return pc def cap(name, chart, hairline, lift=0.010, crown=0.006, nu=72, nv=26, role="hair"): """The hair's base volume: a shell over the scalp from the crown down to hairline(u) (degrees of v), lifted `lift` off the scalp plus `crown` more at the top.""" from outfit import piece, grid_mesh U = np.linspace(-180, 180, nu) G = np.zeros((nu, nv, 3)) UV = np.zeros((nu, nv, 2)) for i, u in enumerate(U): vmax = hairline(u) for j, s in enumerate(np.linspace(0, 1, nv)): v = vmax * s # from the crown itself (a gap there showed as a dot) G[i, j] = chart.point(u, v, off=lift + crown * (1 - s) ** 2) UV[i, j] = (i / (nu - 1) * 6, s) # strands run from the crown down (u repeats) pos, tri = grid_mesh(G) pc = piece(name, role, pos, tri, outward_from=chart.c) pc["uv"] = UV.reshape(-1, 2) pc["strands"] = True pc["group"] = "hair" return pc # ---- hairstyles ----…1943 tokens truncated… move("ridge" + sd, np.array([0, -0.0015, -0.004]) * sh["brow_ridge"]) move("wing" + sd, out * 0.004 * sh["nose_w"]) move("ear" + sd, 0); move("eye" + sd, 0) move("chin", np.array([0, -0.008, -0.003]) * sh["chin_len"]) move("nose", np.array([0, -0.002, -0.004]) * sh["nose"]) for name in ("crown", "occiput", "forehead", "neck_front", "neck_back", "mouth"): move(name, 0) C, D = np.array(ctrl), np.array(disp) if not np.abs(D).any(): return phi = lambda A, B: np.exp(-(np.linalg.norm(A[:, None] - B[None], axis=-1) / sigma) ** 2) Wt = np.linalg.solve(phi(C, C) + 1e-6 * np.eye(len(C)), D) centre = (lm["eyeL"] + lm["eyeR"]) / 2 for p, r in zip(prims, roles): if r not in SCULPT_ROLES: continue P = p["pos"] near = np.linalg.norm(P - centre, axis=1) < 0.16 if near.any(): P[near] += phi(P[near], C) @ Wt def face_texture(prims, roles, v): if r == "white" and len(p["tri"]): cx = p["pos"][p["tri"]].mean(1)[:, 0] p["tri"] = p["tri"][(cx < 0) != (side == "L")] self.lm = landmarks(self.prims, self.roles) if costume: # replace VRoid's clothes with ours import outfit fit = outfit.Fit(self.v, pose, self.prims, self.roles) import rig fit.grip = rig.grip_points(self.v, sh, ref_pose) # where each fist closes (weapons sit there) keep_ = [k for k, r in enumerate(self.roles) if r != "cloth"] self.prims = [self.prims[k] for k in keep_] self.roles = [self.roles[k] for k in keep_] costume = outfit.COSTUMES[costume] if isinstance(costume, str) else costume fit.keep_skin = () # a costume may leave skin bare (fit.keep_skin = bones) for pc in costume(fit): self.prims.append(pc) self.roles.append(pc["role"]) # body skin below the neck is always under clothes in a bust; drop it so it can't poke through cy = self.lm["chin"][1] from vrm import bone_weight for p, r in zip(self.prims, self.roles): if r != "body": continue if costume: # keep head, neck and upper chest (the throat shows in the collar opening) wv = bone_weight(p, ("Head", "Neck", "UpperChest") + tuple(getattr(fit, "keep_skin", ()))) p["tri"] = p["tri"][(wv[p["tri"]] >= 0.5).all(1)] if getattr(fit, "drop_skin", None) is not None: # a costume may hide the skin it covers p["tri"] = p["tri"][~fit.drop_skin(p)[p["tri"]].all(1)] else: T = p["pos"][p["tri"]] head = T[:, :, 1].min(1) > cy - 0.02 neck = (T[:, :, 1].min(1) > cy - 0.14) & (np.abs(T[:, :, 0]).max(1) < 0.055) p["tri"] = p["tri"][head | neck] for pc in world or []: # scenery: does not turn with the character self.prims.append(pc) self.roles.append(pc["role"]) # framing uses the unshaped face at the base head size, so head-size changes still show self.span = (self.lm["eye_y"] - self.lm["chin"][1]) / sh["head"] reshape(self.prims, self.roles, self.lm, sh) strip_blush(self.prims, self.roles, self.v, sh["blush"]) face_lines(self.prims, self.roles, self.v, sh["age_lines"]) lm_now = landmarks(self.prims, self.roles) # after the sculpt names, Wn = self.v.nodes_by_name(), self.v.node_world(pose) neck = (Wn[names["J_Bip_C_Neck"]][:3, 3], Wn[names["J_Bip_C_Head"]][:3, 3]) \ if "J_Bip_C_Neck" in names and "J_Bip_C_Head" in names else None face_normals(self.prims, self.roles, lm_now, sh["face_normals"], sh["hair_normals"], neck=neck) for pc, rl in shadow_cards(self.prims, self.roles, lm_now, sh["shadow_cards"], neck): self.prims.append(pc) self.roles.append(rl) if pose is not target_pose and any(not np.allclose(pose.get(k_, np.eye(4)), target_pose.get(k_, np.eye(4))) for k_ in set(pose) | set(target_pose)): repose(self.v, [p for p in self.prims if not p.get("world")], pose, target_pose) names = self.v.nodes_by_name() Wn = self.v.node_world() self.eye = (Wn[names["J_Adj_L_FaceEye"]][:3, 3] + Wn[names["J_Adj_R_FaceEye"]][:3, 3]) / 2 self.chin_y = self.lm["chin"][1] self.tex = {} for k, p in enumerate(self.prims): if self.roles[k] in ("line", "brow", "iris", "highlight", "white", "hair", "mouth"): src = self._hair_v if (hair_from and "_HAIR" in p["material"]) else self.v t = src.material_texture(p["mi"]) if t is not None and self.roles[k] == "line": # VRoid's upper lid is a thick graded band over the iris; keep its dark core only t = t.copy() t[..., 3] = np.where(t[..., :3].mean(-1) < LID_CORE, t[..., 3], 0) if t is not None: self.tex[k] = t # painted face marks (lip line, nose) from the face texture, grown so they survive the vote from scipy.ndimage import binary_dilation, label self.marks = {} self.mouth_pts = None self.mouth_curve = None for k, p in enumerate(self.prims): if self.roles[k] != "face": continue t = self.v.material_texture(p["mi"]) if t is None: continue th, tw = t.shape[:2] vv, uu = np.mgrid[0:th, 0:tw] vv, uu = (vv + 0.5) / th, (uu + 0.5) / tw win = ((uu > MARK_WINDOW["u"][0]) & (uu < MARK_WINDOW["u"][1]) & (vv > MARK_WINDOW["v"][0]) & (vv < MARK_WINDOW["v"][1])) raw = (t[..., :3].mean(-1) / 255 < FACE_MARK) & (t[..., 3] > 0) & win grown = binary_dilation(raw, iterations=MARK_GROW) & win # 2 = mouth (dark line), 1 = nose mark (one tone softer) self.marks[k] = np.where(grown, np.where(vv >= MARK_WINDOW["nose_below"], 2, 1), 0).astype(np.uint8) if self.mouth_pts is None and raw.any(): lab, n = label(raw) if n: widths = [np.ptp(np.nonzero(lab == i)[1]) for i in range(1, n + 1)] ys, xs = np.nonzero(lab == 1 + int(np.argmax(widths))) th, tw = raw.shape ends = [(xs.min() + 0.5, ys[xs == xs.min()].mean()), (xs.max() + 0.5, ys[xs == xs.max()].mean()), (xs.mean(), ys.mean())] face_prims = [q for q, r in zip(self.prims, self.roles) if r == "face"] pts = [uv_to_3d(face_prims, (ex / tw, ey / th)) for ex, ey in ends] if pts[0] is not None and pts[1] is not None: if pts[2] is None: pts[2] = (pts[0] + pts[1]) / 2 self.mouth_pts = pts # the painted line's centre, traced across: a 3D curve that hugs the lips lab_m = lab == 1 + int(np.argmax(widths)) curve = [] Warning: truncated output (original token count: 4304) Total output lines: 264 """Patch a scratch copy of the built armory page: tiles may take a close-up lens (`lens`, mm on a 36 mm wide frame) and Flattice (`flat`, 0..1), drawn by the page's own painted renderer. Flattice is DillonGoo's add-on done in the vertex shader: every vertex is squashed toward a plane through the head bone's head, along the line from there to the camera, by `flat` times a weight that is 1 above the chin and fades to 0 over 5 cm below it (the add-on's MOD-Flattice group with the cursor at the chin). Normals are left as they were, as the Yin rig shades from normals stored before its lattice. Under a lens the outline pass reads perspective depth. At flat 1 every layer of the head lands on one plane and a depth buffer can't order them (hair, skin and mouth interior fight); 0.85 keeps enough depth, and the outline pass's depth step shrinks with the squash. python3 patch_lens_flattice.py SITE_DIR """ import sys path = sys.argv[1] + "/index.html" s = open(path, encoding="utf-8").read() def rep(old, new): global s assert s.count(old) == 1, old[:80] s = s.replace(old, new) # vertex shader: the squash, in view space, after skinning rep(""" varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying float vEdge; varying vec4 vPlate; void main() { ${SKIN_BODY} vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate; vec4 mv = modelViewMatrix * vec4(transformed, 1.0); vView = -mv.xyz;""", """ varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying float vEdge; varying vec4 vPlate; uniform float uFlattice; uniform float uFlChin; uniform float uFlFall; uniform vec3 uFlPivot; void main() { ${SKIN_BODY} vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate; vec4 mv = modelViewMatrix * vec4(transformed, 1.0); if (uFlattice > 0.0) { // Flattice: squash toward the pivot's plane, along pivot-to-camera float w = clamp((position.y - (uFlChin - uFlFall)) / uFlFall, 0.0, 1.0); vec3 u = normalize(-uFlPivot); mv.xyz -= u * dot(mv.xyz - uFlPivot, u) * w * uFlattice; } vView = -mv.xyz;""") rep(""" uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },""", """ uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 }, uFlattice: { value: 0 }, uFlChin: { value: 0 }, uFlFall: { value: 0.05 }, uFlPivot: { value: new THREE.Vector3() },""") # outline pass: [redacted: secret] depth under a lens rep(""" float z(vec2 p) { return uNear + texture2D(tDepth, p).x * (uFar - uNear); }""", """ uniform float uPersp; float z(vec2 p) { float d = texture2D(tDepth, p).x; return uPersp > 0.5 ? uNear * uFar / (uFar - d * (uFar - uNear)) : uNear + d * (uFar - uNear); }""") rep(""" uNear: { value: 0.1 }, uFar: { value: 40 },""", """ uNear: { value: 0.1 }, uFar: { value: 40 }, uPersp: { value: 0 },""") # tiles: after the page frames its orthographic view, a lens tile moves in and switches to a perspective projection rep(""" frameAt(centre, h, tw_, th_, pitch); render();""", """ frameAt(centre, h, tw_, th_, pitch); lensAndFlat(tile, centre, h, tw_, th_, pitch); render();""") rep("""async function runSheet(kind) {""", """function lensAndFlat(tile, centre, h, tw, th, pitch) { const pu = paint.mat.uniforms; pu.uPersp.value = 0; camera.near = 0.1; camera.far = 40; if (pu.uGap.userData === undefined) pu.uGap.userData = pu.uGap.value; pu.uGap.value = pu.uGap.userData * (1 - (tile.flat || 0)); // depth steps shrink with the squash; so does the line test const chr = active()[0]; if (tile.lens) { const w = h * tw / th, d = w * tile.lens / 36, a = THREE.MathUtils.degToRad(pitch), n = 0.01; camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(d)); camera.lookAt(centre); camera.updateMatrixWorld(true); camera.near = n; camera.far = 40; camera.projectionMatrix.makePerspective(-w / 2 * n / d, w / 2 * n / d, h / 2 * n / d, -h / 2 * n / d, n, 40); camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); pu.uPersp.value = 1; } const face = chr.meshes.find(o => /Face_00_SKIN/.test(o.name + " " + (o.userData.material || ""))); face.geometry.computeBoundingBox(); let pivot = chr.root.getObjectByName("J_Bip_C_Head").getWorldPosition(new THREE.Vector3()); if (tile.pivot === "chin") { // the chin's front: the face's lowest points, the most forward of them const P = face.geometry.attributes.position, low = face.geometry.boundingBox.min.y, v = new THREE.Vector3(); let best = null; for (let i = 0; i < P.count; i++) { v.fromBufferAttribute(P, i); if (v.y < low + 0.006 && (!best || v.z > best.z)) best = v.clone(); } pivot = best.applyMatrix4(face.matrixWorld); } pivot.applyMatrix4(camera.matrixWorl…2808 tokens truncated…nd(data) vw = dict(buffer=0, byteOffset=off, byteLength=len(data)) if target: vw["target"] = target views.append(vw) return len(views) - 1 def add_acc(arr, kind, comp, target=None, minmax=False): arr = np.ascontiguousarray(arr) a = dict(bufferView=add_view(arr.tobytes(), target), componentType=comp, count=int(arr.shape[0]), type=kind) if minmax or (kind == "VEC3" and comp == 5126): a["min"] = np.atleast_1d(arr.min(0)).tolist() a["max"] = np.atleast_1d(arr.max(0)).tolist() accessors.append(a) return len(accessors) - 1348 more lines not shown.
exec_commandmkdir -p review/tide-keeper review/out/tide-keeper
command
mkdir -p review/tide-keeper review/out/tide-keeper cp ~/.local/share/lowmarch/trials/face-shading-2026-10-30/scripts/patch_lens_flattice.py review/tide-keeper/ cp review/vroid-02/index.html review/out/tide-keeper/index.html python3 review/tide-keeper/patch_lens_flattice.py review/out/tide-keeper sed -n '80,145p' review/tide-keeper/patch_lens_flattice.py sed -n '250,352p' tools/plates.py sed -n '23,72p' tools/mobs.py rg -n 'def material_texture|def node_world|def local_matrix' tools/vrm.py sed -n '231,271p' tools/export_glb.py rg -n 'camera.*getWorldPosition|frameAt\(' review/vroid-02/index.html | tail -10result, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"51ba3e","wall_time_seconds":0.00000669,"exit_code":0,"original_token_count":3918,"output":"Warning: truncated output (original token count: 3918)\nTotal output lines: 236\n\npatched review/out/tide-keeper/index.html\n for (let i = 0; i < P.count; i++) {\n v.fromBufferAttribute(P, i);\n if (v.y < low + 0.006 && (!best || v.z > best.z)) best = v.clone();\n }\n pivot = best.applyMatrix4(face.matrixWorld);\n }\n pivot.applyMatrix4(camera.matrixWorldInverse);\n for (const o of chr.meshes) {\n const mu = o.material.uniforms;\n if (!mu || !mu.uFlattice) continue;\n mu.uFlattice.value = tile.flat || 0;\n mu.uFlChin.value = tile.whole ? -100 : face.geometry.boundingBox.min.y + 0.01; // whole: the body too\n mu.uFlFall.value = 0.05; mu.uFlPivot.value.copy(pivot);\n }\n}\nasync function runSheet(kind) {\"\"\")\n# the rows: the armory camera, then a 24 mm close-up without and with Flattice\ni = s.index(\"const ARMORY_ROWS = [\")\nj = s.index(\"const DUEL_YAWS\")\ns = s[:i] + \"\"\"const ARMORY_ROWS = [\n { label: \"Armory camera\", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({ clip: \"ref\", t: 0, yaw: y, pitch: 4,\n focus: \"J_Bip_C_Head\", dy: 0.05, size: 0.40, label: `${y}°` })) },\n { label: \"Close-up lens 24 mm, Flattice off\", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({ clip: \"ref\", t: 0,\n yaw: y, pitch: 4, focus: \"J_Bip_C_Head\", dy: 0.05, size: 0.40, lens: 24, flat: 0, label: `${y}°` })) },\n { label: \"Close-up lens 24 mm, Flattice on (0.85: a little depth kept)\", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({ clip: \"ref\", t: 0,\n yaw: y, pitch: 4, focus: \"J_Bip_C_Head\", dy: 0.05, size: 0.40, lens: 24, flat: 0.85, label: `${y}°` })) },\n { label: \"Close-up lens 24 mm, Flattice on, pivot at the chin\", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({\n clip: \"ref\", t: 0, yaw: y, pitch: 4, focus: \"J_Bip_C_Head\", dy: 0.05, size: 0.40, lens: 24, flat: 0.85,\n pivot: \"chin\", label: `${y}°` })) },\n { label: \"Close-up lens 24 mm, Flattice on the whole body\", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({\n clip: \"ref\", t: 0, yaw: y, pitch: 4, focus: \"J_Bip_C_Head\", dy: 0.05, size: 0.40, lens: 24, flat: 0.85,\n whole: true, label: `${y}°` })) },\n];\n\"\"\" + s[j:]\nopen(path, \"w\", encoding=\"utf-8\").write(s)\nprint(\"patched\", path)\n return np.dstack(chans + [np.full((self.h, self.w), 255, np.uint8)]).astype(np.uint8)\n\n\ndef _seg_distance(P, A, B):\n \"\"\"Distance from points P (N,2) to segments A->B (M,2): (N,) minimum.\"\"\"\n d = B - A\n L2 = np.maximum((d * d).sum(1), 1e-18)\n t = np.clip(((P[:, None] - A[None]) * d[None]).sum(-1) / L2[None], 0, 1)\n Q = A[None] + t[..., None] * d[None]\n return np.linalg.norm(P[:, None] - Q, axis=-1).min(1)\n\n\ndef outline_plate(name, role, chart, u0, u1, bottom, top, offset=0.012, crown=0.0, flare=None, thickness=0.003,\n nu=48, nv=18, trim=0.0, roll=0.0026, roll_edges=(\"bottom\", \"top\", \"left\", \"right\"),\n roll_role=None, rivets=None, rivet_role=\"gold\", seams=(), groove=(0.004, 0.0025),\n panel_crown=0.0, studs=(), stud_r=0.004, stud_role=None, facets=None, decal=(), decal_px=1400,\n pattern=None):\n \"\"\"A plate between bottom(u) and top(u) over u in [u0, u1] on `chart`.\n offset: off the chart surface; crown: extra rise in the middle of the plate (0 at the outline);\n flare(u, v, s, t) -> extra offset (s across, t up, both 0..1), e.g. a cuff belling out at one end;\n thickness: metres, or thickness(u, v, s, t) per point (a beard filled down to the face);\n trim: gold border width painted by the renderer (0 = none); roll: rolled-edge tube radius along\n `roll_edges` (0 = none); rivets: (spacing, inset, radius) studs inside the outline (rivet_role).\n seams: polylines [(u, v), ...] dividing the plate into panels: each panel domes by panel_crown,\n the seams sink into grooves (width, depth) and are painted as dark grooves;\n studs: (u, v) points (seam junctions) given domed studs of radius stud_r;\n facets: u angles where the plate turns a corner: flat between them (a TorsoChart's horizontal rows);\n decal: shapes in chart coordinates painted on the plate (see Canvas):\n (\"poly\", [(u, v), ...], channel) / (\"line\", [(u, v), ...], width_m, channel) / (\"dot\", (u, v), r_m, channel)\n channels: \"paint\" (the character's motif colour), \"groove\", \"gold\".\n Returns (plate piece, [extra pieces: rolls, rivets, studs]); bind them all before export.\"\"\"\n from outfit import piece, pipe, ball\n U = np.linspace(u0, u1, nu)\n S = np.linspace(0, 1, nu)\n T = np.linspace(0, 1, nv)\n vb = np.array([bottom(u) for u in U])\n vt = np.array([top(u) for u in U])\n uu = np.repeat(U[:, None], nv, 1)\n vv = vb[:, None] + (vt - vb)[:, None] * T[None, :]\n n = chart.normal(uu, vv)\n lift = np.full(uu.shape, float(offset))\n if crown:\n lift += crown * np.sqrt(np.clip(np.sin(np.pi * S)[:, None] * np.sin(np.pi * T)[None, :], 0, 1))\n if flare is not None:\n lift += np.array([[flare(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)])\n if seams: # panels dome between seams that sink into grooves\n M = chart.metric(uu,…1368 tokens truncated… holes where MakeHuman weights it to the chest or elsewhere\n out = [O.wrap(fit, \"shorts\", \"cloth\", (\"J_\",), offset=0.004, y_min=lo - 0.04, y_max=hi + 0.04, subdiv=1,\n exclude=(\"Shoulder\", \"Arm\", \"Hand\", \"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\"),\n hems=[((0, 1, 0), hi - 0.005), ((0, -1, 0), -(lo + 0.005))], refloor=True, clamp=True)]\n if band:\n ch, uc = B[\"J_Bip_C_Chest\"][1], B[\"J_Bip_C_UpperChest\"][1]\n blo, bhi = ch - 0.01, uc + 0.06\n # like the shorts: triangles past the hems taken and clamped onto them (dropping them notched the\n # top edge into steps on broad backs), every bone but the arms'\n out.append(O.wrap(fit, \"band\", \"cloth\", (\"J_\",), offset=0.004, y_min=blo - 0.03, y_max=bhi + 0.03, subdiv=1,\n exclude=(\"Shoulder\", \"Arm\", \"Hand\", \"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\"),\n hems=[((0, 1, 0), bhi - 0.005), ((0, -1, 0), -(blo + 0.005))], refloor=True, clamp=True))\n out = [p for p in out if p is not None]\n for p in out:\n p[\"group\"] = \"underwear\"\n fit.keep_skin = (\"J_\",) # bare everywhere else: keep all the skin (VRoid 2 weights some to J_Sec_ bones)\n # but not the skin well inside the shorts: on fitted bodies (tools/fit.py) it came through the waistband.\n # Never the arms', which hang beside the hips in the fitting pose\n arms = (\"Shoulder\", \"Arm\", \"Hand\", \"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\")\n fit.drop_skin = lambda p: ((p[\"pos\"][:, 1] > lo + 0.015) & (p[\"pos\"][:, 1] < hi - 0.015)\n & (bone_weight(p, arms) < 0.05))\n return out\n\n60: def material_texture(self, mi):\n74: def local_matrix(self, i, pose=None):\n102: def node_world(self, pose=None):\n from scipy.spatial import cKDTree\n _, i = cKDTree(allp).query(portrait.mouth_curve)\n curve = ((portrait.mouth_curve + alln[i] * 0.0015) * FLIP).tolist()\n marks = None\n if getattr(portrait, \"marks\", None):\n m = next(iter(portrait.marks.values()))\n img = Image.fromarray(np.where(m == 1, 128, 0).astype(np.uint8), \"L\") # nose mark only; the mouth is a line\n b = io.BytesIO()\n img.save(b, \"PNG\", optimize=True)\n import base64\n marks = base64.b64encode(b.getvalue()).decode()\n # painted renderer: a material kind and one base colour per role; the shader builds the ramp\n pc = dict(signature=\"#7d1e2c\", doublet=\"#2a2d3d\", heraldry=\"#dfe2e8\", leather=\"#5f3e2b\", boot=\"#4a3326\", glove=\"#5f3e2b\",\n steel=\"#a6adbb\", gold=\"#b08b3f\", hair=hexp(\"C\"), trim=\"#b08b3f\")\n pc.update(getattr(portrait, \"paint\", None) or {})\n skin = dict(kind=\"skin\", base=pc.get(\"skin\") or \"#f8e1d5\") # light skin unless a tone is set\n skin[\"ramp\"] = skin_ramp(skin[\"base\"]) # its lit, shade and deep shade\n paint = {\"face\": dict(skin), \"body\": dict(skin), \"shadow\": dict(skin, shade=True), # shadow cards: skin in shade\n \"hair\": dict(kind=\"hair\", base=pc[\"hair\"]),\n \"coat\": dict(kind=\"cloth\", base=pc[\"signature\"]), \"cape\": dict(kind=\"cloth\", base=pc[\"signature\"]),\n \"signature\": dict(kind=\"cloth\", base=pc[\"signature\"]), \"doublet\": dict(kind=\"cloth\", base=pc[\"doublet\"]),\n \"cloth\": dict(kind=\"cloth\", base=pc[\"doublet\"]), \"heraldry\": dict(kind=\"cloth\", base=pc[\"heraldry\"]),\n \"leather\": dict(kind=\"leather\", base=pc[\"leather\"]), \"boot\": dict(kind=\"leather\", base=pc[\"boot\"]),\n \"glove\": dict(kind=\"leather\", base=pc[\"glove\"]), \"metal\": dict(kind=\"steel\", base=pc[\"steel\"]),\n \"steel\": dict(kind=\"steel\", base=pc[\"steel\"]), \"gold\": dict(kind=\"gold\", base=pc[\"gold\"]),\n \"grass\": dict(kind=\"world\", base=\"#5a7a3a\"), \"dirt\": dict(kind=\"world\", base=\"#6a4a32\"),\n \"stone\": dict(kind=\"world\", base=\"#7c7a86\"),\n \"motif\": dict(kind=\"cloth\", base=pc.get(\"motif\", \"#3a44a0\"))} # decal paint on steel (tools/plates.py)\n for role, val in pc.items(): # extra roles a cast entry names (cloth unless it says)\n if role not in paint and isinstance(val, str) and val.startswith(\"#\"):\n paint[role] = dict(kind=\"cloth\", base=val)\n elif role not in paint and isinstance(val, dict) and \"base\" in val:\n paint[role] = dict(kind=val.get(\"kind\", \"cloth\"), base=val[\"base\"])\n for role, g in (pc.get(\"grain\") or {}).items(): # optional per-role brush grain (big flat cloth mottles)\n if role in paint:\n paint[role][\"grain\"] = g\n return dict(roles=roles, light=vp.LIGHT.tolist(), sun=vp.SUN.tolist(), capsules=caps, cloth=cloth, face_marks=marks,\n paint=paint,\n mouth_curve=curve, mouth_bone=\"J_Bip_C_Head\", ink=dict(o=hexp(\"o\"), skin=hexp(\"1\"), hair=hexp(\"A\")),\n skin=[hexp(c) for c in \"12345\"], depth_gap=0.012)\n\n1503:function frameAt(centre, h, tw, th, pitch) {\n1587: frameAt(centre, h, tw_, th_, pitch);\n"}