agent

+11:25
reasoning

The code's clarity and expressiveness, across several key files, are notable. Time remaining is approximately one hour and nineteen minutes, having completed the required document review and reached a point of exact understanding.

Considering a high-resolution PNG for the visual, potentially offering superior clarity and detail compared to video for inspection and web use. The visual will be a side-view tactics battle frame in the style of Unicorn Overlord, rendered at 1920x1080 resolution. This frame aims to provide a clear, detailed representation of the battle scene.

The scene is set on stone-edged plains with a warm, dusk-colored sky. Two original characters are being introduced, built using contrasting VRoid bodies. The first, a Vanguard Captain, utilizes a "strong-woman" VRoid body and features warm peach skin, espresso-auburn hair, and slate-indigo attire accented by burnished steel armor with antique-gold detailing.

Focusing on the character details, the Vanguard Captain's stance is described with specific facial expressions and precise leg IK, emphasizing a confident gaze. The Housecarl/Lancer's physical build is detailed, including specific MakeHuman parameters and coloration details derived from a cast skin definition, along with outfit elements for the two characters.

Verifying the facing direction in the 3D scene, initial calculations indicate a potential mismatch in yaw angles. The goal is for both characters to face each other and angle slightly towards the camera. Further examination of the rotation calculations is necessary to ensure the characters are correctly oriented. The current setup seems to have a sign issue regarding the facing direction, requiring correction.

The yaw angle analysis revealed a critical sign convention error; a fighter on the right with a negative yaw faces left and towards the camera. Further investigation of the light key shows both fighters receive consistent three-quarter lighting when correctly oriented relative to the key light direction, which resolves the facing ambiguity. The clean build/render must now be fully checked for all updates.

The focus shifts to creating a clean build process, emphasizing the importance of not modifying core files to leverage pre-built assets. This approach aims to minimize build time and prevent unintentional alterations. A new script, tools/battle_slice.py, will be built to handle loading cached models and rendering the battle frame, ensuring a rapid and reliable workflow.

Examining the low-march costume, the script builds dark inner hair caps to prevent scalp skin from being visible and shifts head proxy normals for refined lighting. Subtle battle expressions are set to create a focused gaze for each character, alongside custom original costumes. The process relies on read-only bodies, ensuring an efficient build pipeline.

Detailed costume elements are defined for both characters, specifying attire such as surcoats, armor, and accessories, including their respective material and color palettes. The terrain description includes parameters for the plains scene, with adjustments to the width and depth for the widescreen frame.

The battle frame's renderer is being designed to be self-contained and efficient, using local resources to avoid external dependencies. Shader issues identified earlier are addressed through precise light angle adjustments, shadow threshold changes, and enabling screen-space shadows for specific model parts. Hair shading is refined by modifying backface rendering and per-strand specular effects.

The hair rendering approach has been refactored, replacing the original style with a 2-band cel shading approach, adding strand texture and a crown highlight. Eyebrow rendering is being adjusted to correct for depth issues caused by bangs, ensuring a natural appearance. Background rendering has also been changed to a painted atmospheric backdrop, replacing the prior black void. Crucially, all updates are achieved using the Lowmarch's own resources, models, and tools.

The initial plan is to test the integration pipeline with a quick render, targeting visual inspection within 10-15 minutes to allow for artistic refinement. Reviewing the headless rendering process used for capturing images in existing scripts to ensure a reliable method, specifically examining arm_shoot.py and potentially frame.py for this capture. The license compliance is fully met, using only permitted assets and original creations.

  • read_file{"EndLine":120,"Path":"~/work/lowmarch/tools/shots/arm_shoot.py","StartLine":1}

    input

    {
      "EndLine": 120,
      "Path": "~/work/lowmarch/tools/shots/arm_shoot.py",
      "StartLine": 1
    }

    result, 40 lines

    Showing lines 1-39 of 39
    1: """Shoot armory sheets from a patched copy of the built page with headless Chromium (as review/vroid-02/sheets.py).
    2: 
    3:   python3 arm_shoot.py SITE_DIR OUT_DIR NAME [NAME...]
    4: """
    5: import base64
    6: import os
    7: import re
    8: import socket
    9: import subprocess
    10: import sys
    11: import time
    12: 
    13: site, out, names = sys.argv[1], sys.argv[2], sys.argv[3:]
    14: os.makedirs(out, exist_ok=True)
    15: s = socket.socket()
    16: s.bind(("127.0.0.1", 0))
    17: port = s.getsockname()[1]
    18: s.close()
    19: server = subprocess.Popen([sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", site],
    20:                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    21: try:
    22:     time.sleep(0.5)
    23:     for name in names:
    24:         t0 = time.time()
    25:         r = subprocess.run([os.environ.get("CHROMIUM", "/snap/bin/chromium"), *os.environ.get("CHROMIUM_FLAGS", "").split(),
    26:                             "--headless=new", "--use-angle=swiftshader", "--enable-unsafe-swiftshader",
    27:                             "--ignore-gpu-blocklist", "--window-size=1280,900", "--virtual-time-budget=600000",
    28:                             "--dump-dom", f"http://127.0.0.1:{port}/index.html?sheet={name}&rows={os.environ.get('ROWS', '0,1')}&scale=2{os.environ.get('EXTRA', '')}"],
    29:                            capture_output=True, text=True, timeout=900)
    30:         m = re.search(r'id="sheetOut"[^>]*>[redacted: data-URI prefix]([A-Za-z0-9+/=]+)<', r.stdout)
    31:         if not m:
    32:             err = re.search(r'id="sheetOut"[^>]*>([^<]*)<', r.stdout)
    33:             print(name, "FAILED", err.group(1)[:300] if err else r.stderr[-800:])
    34:             continue
    35:         p = os.path.join(out, f"painted_{name}.png")
    36:         open(p, "wb").write(base64.b64decode(m.group(1)))
    37:         print(name, p, f"{time.time() - t0:.0f}s")
    38: finally:
    39:     server.terminate()
  • read_file{"EndLine":420,"Path":"~/work/lowmarch/tools/session/frame.py","StartLine":330}

    input

    {
      "EndLine": 420,
      "Path": "~/work/lowmarch/tools/session/frame.py",
      "StartLine": 330
    }

    result, 2 lines

    Showing lines 77-77 of 77
    77:     main()

agent

+12:27
reasoning

The script utilizes a zero-dependency approach within arm_shoot.py, specifically lines 25-30, leveraging subprocess.run to execute Chromium in headless mode with Swiftshader. This technique avoids external dependencies and enables screen capture.

  • read_file{"EndLine":1737,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":1580}

    input

    {
      "EndLine": 1737,
      "Path": "~/work/lowmarch/review/vroid-02/index.html",
      "StartLine": 1580
    }

    result, 159 lines

    Showing lines 1580-1737 of 1737
    1580:       } else if (tile.focus) {
    1581:         centre = active()[0].root.getObjectByName(tile.focus).getWorldPosition(new THREE.Vector3()); centre.y += tile.dy; pitch = tile.pitch ?? 4;
    1582:       } else {
    1583:         // follow the hips across the ground (a lunge steps out of a fixed frame)
    1584:         const p = duel ? new THREE.Vector3(0, 0, 0) : active()[0].root.getObjectByName("J_Bip_C_Hips").getWorldPosition(new THREE.Vector3());
    1585:         centre = new THREE.Vector3(p.x, h / 2 - 0.06, p.z);
    1586:       }
    1587:       frameAt(centre, h, tw_, th_, pitch);
    1588:       render();
    1589:       const x = gap + k * (tw_ + gap);
    1590:       ctx.drawImage(R.domElement, x, y0, tw_, th_);
    1591:       ctx.fillStyle = "#9c98b5"; ctx.font = "14px sans-serif"; ctx.fillText(tile.label, x + 4, y0 + th_ + 16);
    1592:     });
    1593:     y0 += th_ + lab + gap;
    1594:   }
    1595:   $("sheetOut").textContent = cv.toDataURL("image/png");
    1596:   document.title = "sheet ready";
    1597: }
    1598: 
    1599: // ---- panel: checks and sheets ------------------------------------------------------------------------------------------
    1600: async function loadChecks() {
    1601:   const box = $("checks");
    1602:   try {
    1603:     const chk = await (await fetch("checks.json")).json();
    1604:     box.classList.remove("muted"); box.innerHTML = "";
    1605:     for (const c of CAM.characters) {
    1606:       const r = chk[c.name]; if (!r) continue;
    1607:       const d = document.createElement("div"); d.className = "check";
    1608:       const bad = r.through.length > 0 || (r.props || []).some(x => x.verdict === "FAIL");
    1609:       d.innerHTML = `<span class="sum ${bad ? "bad" : "ok"}"></span>`;
    1610:       d.querySelector(".sum").textContent = r.summary.replace(/^\w+:/, `${c.label}:`);
    1611:       const lay = r.layers;
    1612:       if (lay) {
    1613:         const ls = document.createElement("span"); ls.className = `sum ${lay.items.length ? "bad" : "ok"}`;
    1614:         ls.textContent = lay.summary.replace(/^\w+:/, `${c.label}:`); d.appendChild(ls);
    1615:       }
    1616:       // the armory's girths against real people of the body's height and waist (tools/anthro.py) list apart
    1617:       const props = (r.props || []).filter(x => x.verdict !== "real" && x.verdict !== "face"),
    1618:             real = (r.props || []).filter(x => x.verdict === "real"), face = (r.props || []).filter(x => x.verdict === "face");
    1619:       for (const [list, title] of [[r.through, "Arms through the body"], [r.touching, "Arms resting on the body"],
    1620:                                    [lay ? lay.items : [], "Garments through plate"], [props, "Proportions out of range"],
    1621:                                    [real, "Girths past most real people of this height and waist"],
    1622:                                    [face, "The face against the study's paintings (reported, not held)"]]) {
    1623:         if (!list.length) continue;
    1624:         const det = document.createElement("details");
    1625:         det.innerHTML = `<summary>${title} (${list.length})</summary><ul></ul>`;
    1626:         list.forEach(l => { const li = document.createElement("li"); li.textContent = l.text.replace(/^\w+, /, "").replace(/^Real bodies: /, ""); det.querySelector("ul").appendChild(li); });
    1627:         d.appendChild(det);
    1628:       }
    1629:       box.appendChild(d);
    1630:     }
    1631:   } catch (e) { box.textContent = "No checks in this build."; }
    1632:   try {
    1633:     const sh = await (await fetch("sheets.json")).json();
    1634:     const box2 = $("sheets");
    1635:     sh.forEach(s => {
    1636:       const a = document.createElement("a"); a.href = s.file; a.target = "_blank"; a.rel = "noopener";
    1637:       a.innerHTML = `<img alt="" loading="lazy"><span></span>`;
    1638:       a.querySelector("img").src = s.file; a.querySelector("img").alt = `Check sheet: ${s.label}.`;
    1639:       a.querySelector("span").textContent = s.label;
    1640:       box2.appendChild(a);
    1641:     });
    1642:   } catch (e) { $("sheets").textContent = "No sheets in this build."; }
    1643: }
    1644: 
    1645: // ---- wiring ------------------------------------------------------------------------------------------------------------
    1646: const panelEl = $("panel");
    1647: function setPanel(open) {
    1648:   panelEl.hidden = !open; $("panelBtn").setAttribute("aria-expanded", String(open));
    1649:   requestAnimationFrame(size);
    1650: }
    1651: $("panelBtn").addEventListener("click", () => setPanel(panelEl.hidden));
    1652: $("panelClose").addEventListener("click", () => setPanel(false));
    1653: document.addEventListener("keydown", e => { if (e.key === "Escape" && !panelEl.hidden && window.innerWidth <= 900) setPanel(false); });
    1654: document.querySelectorAll("[data-view]").forEach(b => b.addEventListener("click", () => setView(b.dataset.view)));
    1655: document.querySelectorAll("[data-pose]").forEach(b => {
    1656:   b.setAttribute("aria-pressed", String(b.dataset.pose === state.pose));
    1657:   b.addEventListener("click", () => {
    1658:     state.pose = b.dataset.pose;
    1659:     document.querySelectorAll("[data-pose]").forEach(x => x.setAttribute("aria-pressed", String(x === b)));
    1660:     if (state.view === "compare") { compareChanged(); }       // room and frame follow the pose
    1661:   });
    1662: });
    1663: document.querySelectorAll("[data-motion]").forEach(b => {
    1664:   b.setAttribute("aria-pressed", String(b.dataset.motion === state.motion));
    1665:   b.addEventListener("click", () => {
    1666:     state.motion = b.dataset.motion;
    1667:     document.querySelectorAll("[data-motion]").forEach(x => x.setAttribute("aria-pressed", String(x === b)));
    1668:   });
    1669: });
    1670: document.querySelectorAll("[data-mode]").forEach(b => b.addEventListener("click", () => {
    1671:   state.mode = b.dataset.mode;
    1672:   document.querySelectorAll("[data-mode]").forEach(x => x.setAttribute("aria-pressed", String(x === b)));
    1673: }));
    1674: document.querySelectorAll("[data-clip]").forEach(b => b.addEventListener("click", async () => {
    1675:   const want = b.dataset.clip, view = CLIP_VIEW[want];
    1676:   if (state.view === "lineup" && view === "battle") { setClip(want); return; }
    1677:   if (state.view !== view) await setView(view, want);
    1678:   else setClip(want, want === "clash" ? "idle" : null);
    1679: }));
    1680: const toggle = (id, key, after) => $(id).addEventListener("click", e => { state[key] = !state[key]; e.currentTarget.setAttribute("aria-pressed", String(state[key])); after && after(); });
    1681: toggle("cloth", "cloth", () => { applyMaterials(); active().forEach(c => c.cloths.forEach(cl => { cl.reset(false); cl.write(); })); });
    1682: toggle("wind", "wind");
    1683: toggle("physics", "physics");
    1684: toggle("xray", "xray", applyMaterials);
    1685: toggle("stepped", "stepped");
    1686: $("shade").addEventListener("click", e => { state.toon = !state.toon; e.currentTarget.setAttribute("aria-pressed", String(state.toon)); e.currentTarget.textContent = state.toon ? "3D: toon" : "3D: clay"; applyMaterials(); });
    1687: $("resetCloth").addEventListener("click", () => { state.cloth = true; $("cloth").setAttribute("aria-pressed", "true"); applyMaterials(); active().forEach(c => c.cloths.forEach(cl => cl.reset(true))); });
    1688: $("reset").addEventListener("click", matchCamera);
    1689: $("yaw").addEventListener("input", e => setYaw(+e.target.value));
    1690: $("play").addEventListener("click", e => { state.playing = !state.playing; e.currentTarget.setAttribute("aria-pressed", String(state.playing)); });
    1691: new ResizeObserver(() => size()).observe(stageEl);
    1692: 
    1693: let last = performance.now(), simT = 0;
    1694: const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    1695: function frame(now) {
    1696:   const dt = Math.min(0.05, Math.max(0.001, (now - last) / 1000)); last = now;
    1697:   ctl.update();
    1698:   const cs = active();
    1699:   if (cs.length) {
    1700:     if (state.playing) setYaw(state.yaw + dt * (reduceMotion ? 20 : 70));
    1701:     animate(dt);
    1702:     scene.updateMatrixWorld(true);
    1703:     if (state.physics && !SHEET) {                   // spring bones at a fixed 120 Hz, as the cloth
    1704:       const steps = Math.max(1, Math.round(dt / (1 / 120)));
    1705:       for (const c of cs) if (c.springs && c.springs.length) for (let s = 0; s < steps; s++) stepSprings(c, dt / steps);
    1706:     }
    1707:     const cloths = cs.flatMap(c => c.cloths);
    1708:     if (state.cloth && cloths.length) {
    1709:       const steps = Math.max(1, Math.round(dt / (1 / 120)));
    1710:       for (let s = 0; s < steps; s++) { simT += dt / steps; cloths.forEach(c => c.step(dt / steps, simT)); }
    1711:       cloths.forEach(c => c.write());
    1712:     }
    1713:     render();
    1714:     placeTags();
    1715:   }
    1716:   requestAnimationFrame(frame);
    1717: }
    1718: 
    1719: if (!LINEUP.order.length) $("lineupBtn").hidden = true;
    1720: // a check for scripts (?springprobe): after a few seconds of the motion, each body's widest spring-bone swing (degrees)
    1721: if (params.has("springprobe")) setTimeout(() => {
    1722:   document.title = "springs " + JSON.stringify(Object.fromEntries(active().map(c => [c.name, +(c.springMax || 0).toFixed(1)])));
    1723: }, 4000);
    1724: if (SHEET) {
    1725:   runSheet(SHEET).catch(e => { console.error(e); $("sheetOut").textContent = "error: " + e; document.title = "sheet failed"; });
    1726: } else {
    1727:   if (window.innerWidth > 1100) setPanel(true);
    1728:   loadChecks();
    1729:   const v0 = params.get("view"), w0 = params.get("who"), m0 = params.get("mode");
    1730:   if (w0 && charDef(w0)) state.who = w0;
    1731:   if (m0 === "3d") document.querySelector('[data-mode="3d"]').click();
    1732:   const views = ARMORY_PAGE ? ["battle", "bust", "compare"] : NO_DUEL ? ["battle", "bust", "lineup"] : ["duel", "battle", "bust", "lineup"];
    1733:   await setView(views.includes(v0) ? v0 : ARMORY_PAGE ? "compare" : NO_DUEL ? "lineup" : "duel", params.get("clip") || undefined);
    1734:   if (params.has("yaw")) setYaw(+params.get("yaw") || 0);      // ?yaw=180: open turned (the backs)
    1735:   requestAnimationFrame(frame);
    1736: }
    1737: </script>

agent

+12:46
reasoning

The absence of requestAnimationFrame when the SHEET condition is met is immediately suspect, as this would prevent continuous animation. This suggests the simulation only runs one frame. Consequently, the visualization of the cloth and springs will appear static. Investigating the logic controlling SHEET is essential to correct the single-frame execution.

  • read_file{"EndLine":100,"Path":"~/work/lowmarch/.gitignore","StartLine":1}

    input

    {
      "EndLine": 100,
      "Path": "~/work/lowmarch/.gitignore",
      "StartLine": 1
    }

    result, 7 lines

    Showing lines 1-6 of 6
    1: # Study references (third-party art) never live in this repo; see docs/study.md
    2: refs/
    3: study/
    4: __pycache__/
    5: *.pyc
    6: review/out/

agent

+13:01
reasoning

The .gitignore file correctly excludes the review/out/ directory. The path ~/work/lowmarch/review/out/slice resides within the $HOME directory, allowing http.server to serve its contents to /snap/bin/chromium without any permission conflicts. This confirms a viable setup for serving the generated content.

Focusing on the first character, valen, starting with the body ensures proper arm clearance with the ribcage by computing an arm_out angle for the arm_f_strong body. The expression will be set with a blend of angry brow and eye morphs, with a closed mouth for a focused visual. This approach aims for a cohesive initial render.

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

    input

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

    result, 91 lines

    Showing lines 1-90 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:
  • read_file{"EndLine":150,"Path":"~/work/lowmarch/tools/hair.py","StartLine":91}

    input

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

    result, 61 lines

    Showing lines 91-150 of 318
    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)