agent

+14:49
reasoning

Initial assessment: The code structure appears highly modular, with clear separation of concerns across multiple Python modules. This modularity suggests potential ease of integration and extension. Proceeding to construct the HTML and Python scripts for the review slice and battle slice, respectively.

Reviewing the HTML structure for the review slice, focusing on ensuring the plain ES module JavaScript loads necessary JSON files and handles cloth physics. The fragment shaders for painting require thorough examination. Noted role IDs for painting are crucial, specifically the hair cap and inner outline adjustments within the composition shader. The cloth simulation components, particularly springs, must be thoroughly inspected for correct integration.

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

    input

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

    result, 107 lines

    Showing lines 630-735 of 1737
    630: const targets = { rt: null, rtInfo: null, key: "" };
    631: function targetsFor(w, h) {
    632:   const key = `${w}x${h}`;
    633:   if (targets.key === key) return;
    634:   [targets.rt, targets.rtInfo].forEach(t => t && t.dispose());
    635:   const o = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter };
    636:   targets.rt = new THREE.WebGLRenderTarget(w, h, o);
    637:   targets.rtInfo = new THREE.WebGLRenderTarget(w, h, { ...o, depthTexture: new THREE.DepthTexture(w, h) });
    638:   targets.key = key;
    639: }
    640: 
    641: // ---- cloth -------------------------------------------------------------------------------------------------------
    642: // The skinned cape/tails stay hidden and provide the pinned row (they follow the animated body);
    643: // a plain display mesh in world space shows the simulated cloth. Colliders ride the bones.
    644: const _v = new THREE.Vector3(), _a = new THREE.Vector3(), _ab = new THREE.Vector3(), _cp = new THREE.Vector3();
    645: const _A = new THREE.Vector3(), _B = new THREE.Vector3();
    646: class Cloth {
    647:   constructor(skinned, U, V, trims, capsules, bone, closed = false, hemOnly = false) {
    648:     this.skinned = skinned; this.U = U; this.V = V; this.trims = trims; this.closed = closed; this.hemOnly = hemOnly;
    649:     this.n = skinned.geometry.attributes.position.count;
    650:     this.caps = capsules.map(c => ({ a: bone(c.bones[0]), b: bone(c.bones[1]), r: c.r + 0.006 })).filter(c => c.a && c.b);
    651:     this.x = new Float32Array(this.n * 3); this.prev = new Float32Array(this.n * 3);
    652:     const idx = (i, j) => i * V + j, links = [], bends = [], edge = new Float32Array(this.n);
    653:     for (let i = 0; i < U; i++) for (let j = 0; j < V; j++) {
    654:       // a closed cloth (a skirt) wraps around: the last column links back to the first
    655:       if (i + 1 < U || closed) links.push([idx(i, j), idx((i + 1) % U, j)]);
    656:       if (j + 1 < V) links.push([idx(i, j), idx(i, j + 1)]);
    657:       if (i + 2 < U || closed) bends.push([idx(i, j), idx((i + 2) % U, j)]);
    658:       if (j + 2 < V) bends.push([idx(i, j), idx(i, j + 2)]);
    659:       edge[idx(i, j)] = ((j === 0 && !hemOnly) || j === V - 1 || (!closed && trims.length > 1 && (i === 0 || i === U - 1))) ? 1 : 0;
    660:     }
    661:     const src = skinned.geometry.attributes.position, r = src.array;
    662:     const len = ([a, b]) => Math.hypot(r[3*a] - r[3*b], r[3*a+1] - r[3*b+1], r[3*a+2] - r[3*b+2]);
    663:     this.links = links.map(l => [l[0], l[1], len(l)]);
    664:     this.bends = bends.map(l => [l[0], l[1], len(l)]);
    665:     this.pinned = new Uint8Array(this.n); for (let i = 0; i < U; i++) this.pinned[idx(i, 0)] = 1;
    666:     const g = new THREE.BufferGeometry();
    667:     g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3).setUsage(THREE.DynamicDrawUsage));
    668:     g.setAttribute("normal", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3));
    669:     g.setAttribute("uv", skinned.geometry.attributes.uv || new THREE.BufferAttribute(new Float32Array(this.n * 2), 2));
    670:     g.setAttribute("edge", new THREE.BufferAttribute(edge, 1));
    671:     g.setIndex(skinned.geometry.index);
    672:     this.display = new THREE.Mesh(g, skinned.material);
    673:     this.display.userData = { ...skinned.userData, cloth: true };
    674:     this.display.frustumCulled = false;
    675:     this.lines = new THREE.LineSegments(new THREE.BufferGeometry(), null);
    676:     this.lines.frustumCulled = false;
    677:   }
    678:   rest(k, out) { this.skinned.getVertexPosition(k, out); return out.applyMatrix4(this.skinned.matrixWorld); }
    679:   reset(lift) {
    680:     for (let k = 0; k < this.n; k++) {
    681:       this.rest(k, _v);
    682:       if (lift && !this.pinned[k]) { const j = k % this.V; _v.y += 0.0035 * j * j; }
    683:       this.x[3*k] = this.prev[3*k] = _v.x; this.x[3*k+1] = this.prev[3*k+1] = _v.y; this.x[3*k+2] = this.prev[3*k+2] = _v.z;
    684:     }
    685:   }
    686:   step(dt, t) {
    687:     const x = this.x, pv = this.prev, pin = this.pinned;
    688:     const g = -9.8 * dt * dt, damp = 0.985;
    689:     const gust = state.wind ? (0.9 + 0.6 * Math.sin(t * 1.7) + 0.3 * Math.sin(t * 4.3)) * dt * dt * 4.0 : 0;
    690:     for (let k = 0; k < this.n; k++) {
    691:       if (pin[k]) continue;
    692:       for (let c = 0; c < 3; c++) {
    693:         const i = 3*k + c, v = (x[i] - pv[i]) * damp;
    694:         pv[i] = x[i]; x[i] += v + (c === 1 ? g : 0) + (c === 0 ? gust : 0) + (c === 2 ? gust * 0.4 : 0);
    695:       }
    696:     }
    697:     const pins = [];
    698:     for (let k = 0; k < this.n; k++) if (pin[k]) pins.push([k, this.rest(k, new THREE.Vector3())]);
    699:     const caps = this.caps.map(c => ({ a: c.a.getWorldPosition(new THREE.Vector3()), b: c.b.getWorldPosition(new THREE.Vector3()), r: c.r }));
    700:     // a closed skirt's axis: the middle of its pinned waist row. Inside a leg collider, its cloth is
    701:     // always pushed away from this axis; pushed to the nearest side, a leg stepping wide drags the
    702:     // fabric in between the legs
    703:     const axis = new THREE.Vector3();
    704:     if (this.closed) { for (const [, w] of pins) axis.add(w); axis.multiplyScalar(1 / Math.max(1, pins.length)); }
    705:     const solve = (L, stiff) => {
    706:       for (const [ia, ib, R] of L) {
    707:         const a = 3 * ia, b = 3 * ib;
    708:         const dx = x[b] - x[a], dy = x[b+1] - x[a+1], dz = x[b+2] - x[a+2];
    709:         const d = Math.hypot(dx, dy, dz) || 1e-9, f = (d - R) / d * stiff;
    710:         const wa = pin[ia] ? 0 : 1, wb = pin[ib] ? 0 : 1, s = wa + wb;
    711:         if (!s) continue;
    712:         const ka = f * wa / s, kb = f * wb / s;
    713:         x[a] += dx * ka; x[a+1] += dy * ka; x[a+2] += dz * ka;
    714:         x[b] -= dx * kb; x[b+1] -= dy * kb; x[b+2] -= dz * kb;
    715:       }
    716:     };
    717:     const touch = this.touch || (this.touch = new Uint8Array(this.n)); touch.fill(0);
    718:     for (let it = 0; it < 10; it++) {
    719:       for (const [k, w] of pins) { x[3*k] = w.x; x[3*k+1] = w.y; x[3*k+2] = w.z; }
    720:       solve(this.links, 1.0);
    721:       solve(this.bends, 0.2);
    722:       for (let k = 0; k < this.n; k++) {
    723:         if (pin[k]) continue;
    724:         _v.set(x[3*k], x[3*k+1], x[3*k+2]);
    725:         let jumped = false;
    726:         for (const c of caps) {
    727:           _ab.subVectors(c.b, c.a);
    728:           const tt = THREE.MathUtils.clamp(_a.subVectors(_v, c.a).dot(_ab) / _ab.lengthSq(), 0, 1);
    729:           _cp.copy(c.a).addScaledVector(_ab, tt);
    730:           const d = _v.distanceTo(_cp);
    731:           if (d < c.r && d > 1e-6) {
    732:             if (this.closed) {
    733:               _A.set(_v.x - axis.x, 0, _v.z - axis.z);                     // outward, horizontally
    734:               _B.set(_v.x - _cp.x, 0, _v.z - _cp.z);
    735:               if (_A.lengthSq() > 1e-8 && _B.dot(_A) < 0) {                 // the nearest way out is inward: go round
  • read_file{"EndLine":350,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":250}

    input

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

    result, 102 lines

    Showing lines 250-350 of 1737
    250: const charDef = name => CAM.characters.find(c => c.name === name);
    251: // a workshop page (camera.json "page"): its own title and notes, and no duel
    252: const PAGE = CAM.page || null;
    253: const NO_DUEL = PAGE?.duel === false;
    254: if (PAGE) {
    255:   document.title = `${PAGE.title} · Lowmarch`;
    256:   document.querySelector(".brand .eyebrow").textContent = PAGE.eyebrow || "Lowmarch";
    257:   document.querySelector(".brand h1").textContent = PAGE.title;
    258:   if (PAGE.notes) document.querySelector("#panel section ul").innerHTML = PAGE.notes;
    259: }
    260: // the armory: bodies compared side by side (the Compare view) in three poses, instead of clips and a lineup
    261: const ARMORY_PAGE = !!PAGE?.armory;
    262: const MAX_COMPARE = 6;
    263: if (ARMORY_PAGE) {
    264:   $("compareBtn").hidden = false; $("poseSeg").hidden = false; $("clipSeg").hidden = true; $("lineupBtn").hidden = true;
    265:   $("motionSeg").hidden = false;
    266:   if (PAGE.skins && PAGE.skins.length) {             // skin picker: try any tone of the range on the bodies shown
    267:     const sel = $("skinSel");
    268:     sel.append(new Option("Skin: as built", ""));
    269:     for (const g of [...new Set(PAGE.skins.map(s => s.group))]) {
    270:       const og = document.createElement("optgroup"); og.label = g;
    271:       PAGE.skins.filter(s => s.group === g).forEach(s => og.append(new Option(s.label, s.name)));
    272:       sel.append(og);
    273:     }
    274:     if (PAGE.skins.some(s => s.name === params.get("skin"))) state.skin = params.get("skin");    // ?skin=<tone>
    275:     sel.value = state.skin || "";
    276:     sel.hidden = false;
    277:     sel.addEventListener("change", () => { state.skin = sel.value; });
    278:   }
    279:   if (["still", "bounce", "twist"].includes(params.get("motion"))) state.motion = params.get("motion");
    280:   state.compare = (params.get("compare") || "").split(",").filter(n => charDef(n)).slice(0, MAX_COMPARE);
    281:   if (!state.compare.length) state.compare = CAM.characters.slice(0, 2).map(c => c.name);
    282:   if (["up", "out", "down"].includes(params.get("pose"))) state.pose = params.get("pose");
    283: }
    284: if (NO_DUEL) {
    285:   document.querySelector('[data-view="duel"]').hidden = true;
    286:   document.querySelector('[data-clip="clash"]').hidden = true;
    287:   state.clip = "idle";
    288: }
    289: 
    290: const hex = h => {                                     // raw palette value, no colour-space conversion
    291:   const n = parseInt(h.slice(1), 16);
    292:   return new THREE.Color().setRGB((n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255, THREE.LinearSRGBColorSpace);
    293: };
    294: const rawTex = t => { if (!t) return null; const c = t.clone(); c.colorSpace = THREE.NoColorSpace; c.needsUpdate = true; return c; };
    295: const gradient = (() => {
    296:   const d = new Uint8Array([70, 70, 70, 255, 140, 140, 140, 255, 205, 205, 205, 255, 255, 255, 255, 255]);
    297:   const t = new THREE.DataTexture(d, 4, 1, THREE.RGBAFormat); t.minFilter = t.magFilter = THREE.NearestFilter; t.needsUpdate = true; return t;
    298: })();
    299: const white = (() => { const t = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1, THREE.RGBAFormat); t.needsUpdate = true; return t; })();
    300: 
    301: // ---- scene and camera -----------------------------------------------------------------------------------------------
    302: const scene = new THREE.Scene();
    303: const hemi = new THREE.HemisphereLight(0xfff6ee, 0x3a3450, 1.35);
    304: const sun = new THREE.DirectionalLight(0xffffff, 1.6);
    305: scene.add(hemi, sun);
    306: const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 40);
    307: 
    308: // ---- shaders --------------------------------------------------------------------------------------------------------
    309: const SKIN_HEAD = `#include <common>
    310:   #include <skinning_pars_vertex>`;
    311: const SKIN_BODY = `#include <beginnormal_vertex>
    312:     #include <skinbase_vertex>
    313:     #include <skinnormal_vertex>
    314:     #include <begin_vertex>
    315:     #include <skinning_vertex>`;
    316: const PAINT_VS = `${SKIN_HEAD}
    317:   attribute float edge; attribute vec4 _plate; uniform float uLift;
    318:   varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying float vEdge; varying vec4 vPlate;
    319:   void main() {
    320:     ${SKIN_BODY}
    321:     vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate;
    322:     vec4 mv = modelViewMatrix * vec4(transformed, 1.0); vView = -mv.xyz;
    323:     mv.z += uLift;                                              // brows: drawn over the bangs (depth lift toward the camera)
    324:     gl_Position = projectionMatrix * mv;
    325:   }`;
    326: const HSV = `
    327:   vec3 rgb2hsv(vec3 c) {
    328:     vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    329:     vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    330:     vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
    331:     float d = q.x - min(q.w, q.y);
    332:     return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 1e-10)), d / (q.x + 1e-10), q.x);
    333:   }
    334:   vec3 hsv2rgb(vec3 c) {
    335:     vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    336:     vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    337:     return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
    338:   }`;
    339: // painted renderer, after the Unicorn Overlord study: tight terminators, hue-shifted ramps built from
    340: // one base colour per material, hard reflection bands on steel, strand highlights on hair, a stage
    341: // grade and a back rim
    342: const PAINT_FS = `
    343:   uniform int uKind; uniform vec3 uBase; uniform vec3 uKey; uniform sampler2D uMap; uniform int uAlpha;
    344:   uniform int uPass; uniform vec4 uInfo; uniform vec3 uEye[3]; uniform vec3 uFlat; uniform vec3 uSkinRef;
    345:   uniform vec3 uGold; uniform vec3 uAmbient; uniform vec3 uKeyCol; uniform vec3 uRimCol; uniform float uGrain;
    346:   uniform int uFaceTex; uniform int uDecal; uniform vec3 uMotif; uniform vec3 uBand; uniform vec3 uSkinTone; uniform int uShadeOnly;
    347:   uniform int uSkinRamp; uniform vec3 uSkinL; uniform vec3 uSkinS; uniform vec3 uSkinC;
    348:   uniform sampler2D tCastInfo; uniform sampler2D tCastDepth; uniform vec2 uCastRes; uniform int uCastOn;
    349:   uniform float uCastNear; uniform float uCastFar; uniform float uCastPpm;
    350:   // Cast shadows on skin, in screen space (the "depth offset" shadows of anime toon shaders): walk from this pixel
  • read_file{"EndLine":905,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":840}

    input

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

    result, 67 lines

    Showing lines 840-905 of 1737
    840:         X[3 * k] = q.x; X[3 * k + 1] = q.y; X[3 * k + 2] = q.z;
    841:         pr = r; ph = h; pt = tt;
    842:       }
    843:     }
    844:     this.prev.set(X);
    845:   }
    846:   reset() { this.push.fill(0); this.pose(0, true); }
    847:   step(dt) { this.pose(dt, false); }
    848: }
    849: 
    850: // ---- materials per mesh ----------------------------------------------------------------------------------------------
    851: const KEY = new THREE.Vector3(-0.45, 0.55, 0.70).normalize();
    852: // stage grades: ambient multiply, key colour, back rim (characters and stage share them)
    853: const GRADE = { battle: { ambient: [0.84, 0.87, 0.98], key: [1.05, 1.0, 0.92], rim: [0.38, 0.34, 0.26] },
    854:                 bust: { ambient: [0.90, 0.90, 0.98], key: [1.03, 1.0, 0.96], rim: [0.24, 0.24, 0.34] } };
    855: // Brows draw over the bangs: they are lifted this far (m) toward the camera, more than the bangs stand off the
    856: // forehead and much less than the head is deep, so a brow still hides behind the skull when the head turns away.
    857: const BROW_LIFT = 0.04;
    858: const KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };
    859: function paintMaterial(V, role, map, index, infoRole = role, decal = false) {
    860:   const Rl = V.roles[role] || { mode: "flat", color: "#ff00ff" }, P = (V.paint || {})[role];
    861:   const u = { uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() },
    862:     uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },
    863:     uInfo: { value: new THREE.Vector4(roleId(infoRole) / 255, (index % 256) / 255, Math.floor(index / 256) / 255, 1) },
    864:     uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() }, uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) },
    865:     uGold: { value: hex((V.paint && V.paint.gold && V.paint.gold.base) || "#b08b3f") },
    866:     uAmbient: { value: new THREE.Vector3(1, 1, 1) }, uKeyCol: { value: new THREE.Vector3(1, 1, 1) }, uRimCol: { value: new THREE.Vector3() },
    867:     uGrain: { value: 0.05 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null },
    868:     uSkinTone: { value: new THREE.Vector3(1, 1, 1) }, uShadeOnly: { value: 0 },
    869:     uSkinRamp: { value: 0 }, uSkinL: { value: new THREE.Color() }, uSkinS: { value: new THREE.Color() }, uSkinC: { value: new THREE.Color() },
    870:     tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 },
    871:     uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 },
    872:     uMotif: { value: hex((V.paint && V.paint.motif && V.paint.motif.base) || "#3a44a0") }, uLift: { value: 0 } };
    873:   if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; }
    874:   else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); }
    875:   if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; }
    876:   if (P && P.shade) u.uShadeOnly.value = 1;         // shadow cards: skin, always in its shade tone
    877:   if (P && P.kind === "skin" && P.ramp) {           // a designed ramp: lit, shade, deep shade
    878:     u.uSkinRamp.value = 1; u.uSkinL.value = hex(P.ramp[0]); u.uSkinS.value = hex(P.ramp[1]); u.uSkinC.value = hex(P.ramp[2]);
    879:   }
    880:   if (P && P.kind === "skin" && P.base) {           // skin tone: the base colour against the default light skin
    881:     const c = hex(P.base); u.uSkinTone.value.set(c.r / 0.973, c.g / 0.882, c.b / 0.835);
    882:   }
    883:   if (role === "face" && map) u.uFaceTex.value = 1;
    884:   if (role === "hair" && map) u.uAlpha.value = 1;
    885:   if (role === "iris") { u.uKind.value = 7; u.uAlpha.value = 1; }
    886:   else if (role === "white" || role === "highlight") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); }
    887:   else if (!P && Rl.mode === "flat") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; }
    888:   if (role === "brow") u.uLift.value = BROW_LIFT;
    889:   if (role === "mouth" && map) u.uKind.value = 10;
    890:   u.uBand.value = u.uGold.value.clone();
    891:   const m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: PAINT_VS, fragmentShader: PAINT_FS, side: THREE.DoubleSide,
    892:                                        extensions: { derivatives: true } });
    893:   // meshes without plate data or a cloth edge read zeros, not whatever another program left in that slot
    894:   m.defaultAttributeValues = { ...m.defaultAttributeValues, _plate: [0, 0, 0, 0], edge: [0] };
    895:   return m;
    896: }
    897: 
    898: // ---- models ------------------------------------------------------------------------------------------------------
    899: const loader = new GLTFLoader();
    900: const chars = new Map();          // name -> loaded character
    901: let ground = null;
    902: const stage = new THREE.Group();  // the duel: both fighters stand on it; the turn slider rotates it
    903: scene.add(stage);
    904: // the lineup: every enemy model standing in a row (camera.json's lineup), each turning in place
    905: const LINEUP = CAM.lineup || { order: [], spacing: 0.9 };

agent

+15:29
reasoning

The brow lift value is the root cause. The code assigns a non-zero lift value specifically to brow elements, making them float above their intended depth. Setting this lift to zero resolves the unnatural layering, correctly placing the brows behind the hair. This clarifies why brows were floating above the bangs.

  • write_file{"Content":"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Battle Slice · Lowmarch</title>\n<style>\n html, body { margin: 0; height: 100%; background: #1e1d26; color: #ece8e0; font-family: system-ui, sans-serif; overflow: hidden; }\n #stage { position: fixed; inset: 0; display: grid; place-items: center; }\n canvas { max-width: 100%; max-height: 100%; display: block; }\n #sheetOut { display: none; }\n</style>\n<script type=\"importmap\">\n{\n \"imports\": {\n \"three\": \"./three/build/three.module.js\",\n \"three/addons/\": \"./three/examples/jsm/\"\n }\n}\n</script>\n</head>\n<body>\n<div id=\"stage\"></div>\n<pre id=\"sheetOut\"></pre>\n<script type=\"module\">\nimport * as THREE from \"three\";\nimport { GLTFLoader } from \"three/addons/loaders/GLTFLoader.js\";\n\nconst params = new URLSearchParams(location.search);\nconst SHOT = params.has(\"shot\");\nconst SCENE = await (await fetch(\"scene.json\")).json();\n\nconst stageEl = document.getElementById(\"stage\");\nconst R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: true });\nR.outputColorSpace = THREE.LinearSRGBColorSpace;\nR.setClearColor(0x000000, 0);\nstageEl.appendChild(R.domElement);\n\nconst hex = h => {\n const n = parseInt(h.slice(1), 16);\n return new THREE.Color().setRGB((n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255, THREE.LinearSRGBColorSpace);\n};\nconst rawTex = t => { if (!t) return null; const c = t.clone(); c.colorSpace = THREE.NoColorSpace; c.needsUpdate = true; return c; };\nconst white = (() => { const t = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1, THREE.RGBAFormat); t.needsUpdate = true; return t; })();\n\nconst R_ID = { face: 1, body: 2, hair: 3, iris: 4, white: 5, highlight: 6, line: 7, brow: 8, mouth: 9, hair_b: 11, hair_cap: 12, grass: 20, dirt: 21, stone: 22 };\nconst roleId = r => R_ID[r] || 10;\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 40);\n\nconst SKIN_HEAD = `#include <common>\n #include <skinning_pars_vertex>`;\nconst SKIN_BODY = `#include <beginnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <begin_vertex>\n #include <skinning_vertex>`;\n\nconst PAINT_VS = `${SKIN_HEAD}\n attribute float edge; attribute vec4 _plate; uniform float uLift;\n varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying vec3 vWPos;\n varying float vEdge; varying vec4 vPlate;\n void main() {\n ${SKIN_BODY}\n vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate;\n vec4 wp = modelMatrix * vec4(transformed, 1.0);\n vWPos = wp.xyz;\n vec4 mv = modelViewMatrix * vec4(transformed, 1.0); vView = -mv.xyz;\n mv.z += uLift;\n gl_Position = projectionMatrix * mv;\n }`;\n\nconst HSV = `\n vec3 rgb2hsv(vec3 c) {\n vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n float d = q.x - min(q.w, q.y);\n return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 1e-10)), d / (q.x + 1e-10), q.x);\n }\n vec3 hsv2rgb(vec3 c) {\n vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n }`;\n\nconst PAINT_FS = `\n uniform int uKind; uniform vec3 uBase; uniform vec3 uKey; uniform sampler2D uMap; uniform int uAlpha;\n uniform int uPass; uniform vec4 uInfo; uniform vec3 uEye[3]; uniform vec3 uFlat; uniform vec3 uSkinRef;\n uniform vec3 uGold; uniform vec3 uAmbient; uniform vec3 uKeyCol; uniform vec3 uRimCol; uniform float uGrain;\n uniform int uFaceTex; uniform int uDecal; uniform vec3 uMotif; uniform vec3 uBand; uniform vec3 uSkinTone; uniform int uShadeOnly;\n uniform int uSkinRamp; uniform vec3 uSkinL; uniform vec3 uSkinS; uniform vec3 uSkinC;\n uniform float uCrownY;\n uniform vec2 uFootA; uniform vec2 uFootB; uniform vec2 uFootC; uniform vec2 uFootD;\n uniform sampler2D tCastInfo; uniform sampler2D tCastDepth; uniform vec2 uCastRes; uniform int uCastOn;\n uniform float uCastNear; uniform float uCastFar; uniform float uCastPpm;\n\n float castShadow(int selfRole) {\n vec2 uv = gl_FragCoord.xy / uCastRes, px = 1.0 / uCastRes;\n float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);\n float sxy = length(uKey.xy);\n if (sxy < 0.05) return 0.0;\n vec2 dir = uKey.xy / sxy;\n float lz = uKey.z / sxy;\n int steps = selfRole == 1 ? 8 : 15;\n float stepM = selfRole == 1 ? 0.0026 : 0.0032;\n for (int s = 1; s <= 15; s++) {\n if (s > steps) break;\n float dm = float(s) * stepM;\n vec2 q = uv + dir * dm * uCastPpm * px;\n vec4 ni = texture2D(tCastInfo, q);\n if (ni.a < 0.5) continue;\n int r = int(ni.r * 255.0 + 0.5);\n if (selfRole == 1) {\n if (r != 3 && r != 11 && r != 12) continue;\n } else {\n if (r != 1 && r != 3 && r != 11 && r != 12) continue;\n }\n float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);\n float zr = z0 - lz * dm;\n if (zq < zr - 0.004 && zq > zr - 0.22) return 1.0;\n }\n return 0.0;\n }\n\n varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying vec3 vWPos;\n varying float vEdge; varying vec4 vPlate;\n ${HSV}\n float hash(vec3 p) { p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }\n float vnoise(vec3 x) {\n vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix(hash(i), hash(i + vec3(1,0,0)), f.x), mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y),\n mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x), mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z);\n }\n float toward(float h, float target, float amt) { float d = target - h; d -= floor(d + 0.5); return fract(h + clamp(d, -amt, amt)); }\n vec3 tone(vec3 base, float hue, float amt, float sMul, float vMul) {\n vec3 h = rgb2hsv(base);\n return hsv2rgb(vec3(toward(h.x, hue, amt), clamp(h.y * sMul, 0.0, 1.0), clamp(h.z * vMul, 0.0, 1.0)));\n }\n float st(float x, float t) { return smoothstep(t - 0.025, t + 0.025, x); }\n\n vec3 metal(bool gold, vec3 base, vec3 n, vec3 v, float lit, float hgt) {\n vec3 r = reflect(-v, n);\n float ry = r.y + (vnoise(vObj * vec3(3.0, 14.0, 3.0)) - 0.5) * 0.12;\n float curv = length(fwidth(n)) / max(length(fwidth(vView)), 1e-5);\n float sharp = smoothstep(5.0, 14.0, curv);\n if (hgt >= 0.0) sharp *= 0.25; else sharp = max(sharp, 0.3);\n vec3 s0, s1, s2, s3;\n if (!gold) { s0 = tone(base, 0.66, 0.10, 2.1, 0.34); s1 = tone(base, 0.66, 0.06, 1.5, 0.74);\n s2 = tone(base, 0.12, 0.0, 0.8, 0.90); s3 = vec3(0.97, 0.96, 0.93); }\n else { s0 = vec3(0.28, 0.19, 0.24); s1 = tone(base, 0.12, 0.03, 1.05, 0.72); s2 = base; s3 = tone(base, 0.14, 0.03, 0.52, 1.48); }\n vec3 hard = mix(s0, s1, st(ry, -0.42));\n hard = mix(hard, s2, st(ry, -0.08));\n hard = mix(hard, s0, st(ry, 0.36));\n hard = mix(hard, s3, st(ry, 0.47));\n hard = mix(hard, s2 * 1.05, st(ry, 0.70));\n float k = smoothstep(-0.55, 0.30, r.y);\n if (hgt >= 0.0) k = clamp(k * 0.45 + hgt * 0.80 - 0.18, 0.0, 1.0);\n else k = clamp(k * 0.6 + n.y * 0.35 + 0.05, 0.0, 1.0);\n vec3 soft = mix(s1 * 0.9, s2, k);\n float hl = dot(n, normalize(uKey + v));\n if (hgt >= 0.0) soft = mix(soft, mix(s2, s3, 0.62), st(hl, 0.95) * smoothstep(0.42, 0.8, hgt));\n vec3 col = mix(soft, hard, sharp);\n return mix(col * 0.70 + s0 * 0.30, col, st(lit, 0.34));\n }\n\n void main() {\n vec4 tex = texture2D(uMap, vUv);\n if (uAlpha == 1 && tex.a < 0.5) discard;\n if (uAlpha == 2 && (tex.a < 0.5 || dot(tex.rgb, vec3(1.0 / 3.0)) >= 0.42)) discard;\n if (uPass == 1) { gl_FragColor = uInfo; return; }\n\n bool back = !gl_FrontFacing;\n vec3 n = normalize(vN); if (back) n = -n;\n vec3 v = normalize(vView);\n float lit = dot(n, uKey) * 0.5 + 0.5;\n int selfRole = int(uInfo.x * 255.0 + 0.5);\n\n if (uShadeOnly == 1) {\n lit = 0.12;\n } else if (uCastOn == 1 && uKind == 1 && (selfRole == 1 || selfRole == 2)) {\n if (castShadow(selfRole) > 0.5) lit = min(lit, 0.34);\n }\n\n float g1 = vnoise(vObj * 40.0), g2 = vnoise(vObj * 150.0);\n vec3 col;\n if (uKind == 0 || uKind == 5 || uKind == 6) {\n vec3 hb = rgb2hsv(uBase);\n bool cool = hb.x > 0.42 && hb.x < 0.86;\n float sh = uKind == 5 ? 0.93 : (cool ? 0.68 : 0.96);\n float li = cool ? 0.55 : 0.12;\n vec3 c0 = tone(uBase, sh, 0.08, 1.12, 0.42), c1 = tone(uBase, sh, 0.05, 1.08, 0.66);\n vec3 c3 = tone(uBase, li, 0.03, 0.82, 1.18);\n float l = lit + (g1 - 0.5) * uGrain - (uKind == 6 ? 0.20 : 0.0);\n if (uKind == 6) {\n // Contact shadow on ground beneath planted feet\n vec2 xz = vWPos.xz;\n float da = length((xz - uFootA) * vec2(1.0, 1.35));\n float db = length((xz - uFootB) * vec2(1.0, 1.35));\n float dc = length((xz - uFootC) * vec2(1.0, 1.35));\n float dd = length((xz - uFootD) * vec2(1.0, 1.35));\n float dmin = min(min(da, db), min(dc, dd));\n float contact = 1.0 - smoothstep(0.08, 0.30, dmin);\n l -= 0.36 * contact;\n }\n col = mix(c0, c1, st(l, 0.32)); col = mix(col, uBase, st(l, 0.50)); col = mix(col, c3, st(l, 0.90));\n if (uKind == 5) col *= 0.965 + 0.07 * vnoise(vObj * 22.0);\n } else if (uKind == 1) {\n // Skin: genuine 3/4 shadow plane (threshold 0.50 instead of 0.38) + warm hue-shifted ramp\n vec3 sL = vec3(0.973, 0.882, 0.835), sS = vec3(0.776, 0.659, 0.608), sC = vec3(0.451, 0.322, 0.310);\n if (uSkinRamp == 1) { sL = uSkinL; sS = uSkinS; sC = uSkinC; }\n col = mix(sC, sS, st(lit, 0.24)); col = mix(col, sL, st(lit, 0.50));\n if (uFaceTex == 1) col *= clamp(tex.rgb / uSkinRef, 0.58, 1.04);\n if (uFaceTex == 1 && vUv.x > 0.37 && vUv.x < 0.63 && vUv.y > 0.68 && vUv.y < 0.84) {\n float d = 0.0, sl = dot(uSkinRef, vec3(1.0 / 3.0));\n for (int k = -2; k <= 2; k++) for (int j = -2; j <= 2; j++) {\n vec3 t = texture2D(uMap, vUv + vec2(float(j) * 1.1, float(k) * 0.9) / 512.0).rgb;\n d = max(d, 1.0 - dot(t, vec3(1.0 / 3.0)) / sl);\n }\n float taper = 1.0 - 0.45 * smoothstep(0.038, 0.068, abs(vUv.x - 0.5));\n vec3 lipInk = mix(sC * 0.68, vec3(0.32, 0.14, 0.15), 0.55);\n col = mix(col, lipInk, smoothstep(0.09, 0.20, d) * taper);\n }\n if (uSkinRamp == 0) col *= uSkinTone;\n } else if (uKind == 2) {\n // Calm 2-tone cel hair + dark inner backfaces + one restrained crown halo band\n float strand = dot(tex.rgb, vec3(1.0 / 3.0));\n vec3 c0 = tone(uBase, 0.70, 0.06, 1.12, 0.38);\n vec3 c1 = tone(uBase, 0.70, 0.04, 1.06, 0.66);\n vec3 c2 = tone(uBase, 0.12, 0.02, 0.78, 1.24);\n if (back || uShadeOnly == 1 || selfRole == 12) {\n col = c0;\n } else {\n float l = lit + (strand - 0.58) * 0.035;\n col = mix(c0, c1, st(l, 0.28));\n col = mix(col, uBase, st(l, 0.48));\n // Clean horizontal anime halo band around upper crown locks\n float dy = (vWPos.y - uCrownY);\n float bandMask = exp(-pow(dy / 0.028, 2.0)) * smoothstep(0.54, 0.68, lit);\n float sp = dot(n, normalize(uKey + v)) + (strand - 0.58) * 0.04;\n float halo = bandMask * smoothstep(0.76, 0.86, sp);\n col = mix(col, c2, 0.62 * halo);\n }\n } else if (uKind == 3 || uKind == 4) {\n bool plate = vPlate.x > 0.5;\n float e = vPlate.y, w = vPlate.z;\n bool gilt = uKind == 4 || (plate && w > 0.0 && e < w);\n col = metal(gilt, gilt && uKind == 3 ? uGold : uBase, n, v, lit, plate ? vPlate.w : -1.0);\n if (plate && w > 0.0) {\n float aa = fwidth(e) * 1.2 + 1e-5;\n float l1 = 1.0 - smoothstep(0.0010, 0.0010 + aa, abs(e - (w + 0.0050)));\n float l2 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - w));\n col = mix(col, col * 0.42, max(l1, l2 * 0.8));\n }\n } else if (uKind == 7) {\n float l = dot(tex.rgb, vec3(1.0 / 3.0));\n col = l < 0.3 ? mix(uEye[0], uEye[1], l / 0.3) : mix(uEye[1], uEye[2], clamp((l - 0.3) / 0.6, 0.0, 1.0));\n } else if (uKind == 8) { col = tex.rgb; }\n else if (uKind == 10) {\n float lum = dot(tex.rgb, vec3(1.0 / 3.0));\n col = mix(vec3(0.36, 0.11, 0.14), vec3(0.78, 0.38, 0.42), smoothstep(0.53, 0.58, tex.g));\n col = mix(col, vec3(0.98, 0.96, 0.95), smoothstep(0.80, 0.86, lum));\n } else { col = uFlat; }\n\n if (vPlate.x > 0.5 && vPlate.z > 0.0 && uKind != 3 && uKind != 4) {\n float e = vPlate.y, w = vPlate.z, aa = fwidth(e) * 1.2 + 1e-5;\n float band = 1.0 - smoothstep(w - aa, w, e);\n float l1 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - (w + 0.0040)));\n col = mix(col, metal(true, uGold, n, v, lit, -1.0), max(band, l1 * 0.9));\n }\n if (uDecal == 1) {\n vec3 dm = tex.rgb;\n float pm = smoothstep(0.3, 0.7, dm.r), gm = smoothstep(0.3, 0.7, dm.g), au = smoothstep(0.3, 0.7, dm.b);\n if (au > 0.0) col = mix(col, metal(true, uGold, n, v, lit, -1.0), au);\n if (pm > 0.0) {\n vec3 pc = mix(tone(uMotif, 0.70, 0.05, 1.10, 0.62), uMotif, st(lit, 0.42));\n col = mix(col, mix(pc, tone(uMotif, 0.56, 0.03, 0.8, 1.25), st(lit, 0.92)), pm);\n }\n if (gm > 0.0) col = mix(col, col * 0.30, gm);\n }\n if (vEdge > 0.5) {\n vec3 gd = tone(uBand, 0.20, 0.03, 1.0, 0.72);\n col = mix(gd, uBand, st(lit, 0.45)); col = mix(col, tone(uBand, 0.16, 0.03, 0.5, 1.45), st(lit, 0.85));\n }\n if (uKind <= 6) {\n vec3 grade = mix(uAmbient, uKeyCol, st(lit, 0.52));\n col *= uKind == 1 && uSkinRamp == 1 ? mix(vec3(1.0), grade, 0.25) : grade;\n float fr = pow(1.0 - max(dot(n, v), 0.0), 4.2);\n float rimBack = clamp(dot(n, normalize(vec3(0.55, 0.45, -0.35))), 0.0, 1.0);\n col += uRimCol * fr * smoothstep(0.12, 0.55, rimBack) * (uKind == 1 ? 0.45 : 0.85);\n if (uKind != 1 && uKind != 2) col *= 1.0 + (g2 - 0.5) * 0.05;\n }\n gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);\n }`;\n\nconst PAINT_COMP = `\n uniform sampler2D tColor; uniform sampler2D tInfo; uniform sampler2D tDepth; uniform vec2 uRes;\n uniform float uNear; uniform float uFar; uniform float uGap; uniform float uSil; uniform float uInner; uniform float uPpm;\n ${HSV}\n float z(vec2 p) { return uNear + texture2D(tDepth, p).x * (uFar - uNear); }\n int rid(vec4 i) { return int(i.r * 255.0 + 0.5); }\n float pid(vec4 i) { return floor(i.g * 255.0 + 0.5) + floor(i.b * 255.0 + 0.5) * 256.0; }\n vec3 ink(vec3 c) { vec3 h = rgb2hsv(c); return hsv2rgb(vec3(h.x, clamp(h.y, 0.20, 0.45), 0.18)); }\n\n vec3 backdrop(vec2 uv) {\n // Painted dusk-parchment SRPG stage backdrop (replaces pitch-black #0e0d12 void)\n vec3 skyTop = vec3(0.22, 0.27, 0.36);\n vec3 skyMid = vec3(0.46, 0.47, 0.52);\n vec3 horizon = vec3(0.76, 0.69, 0.60);\n vec3 lowMist = vec3(0.58, 0.54, 0.50);\n vec3 underEarth = vec3(0.15, 0.14, 0.18);\n\n float y = uv.y;\n vec3 bg = mix(horizon, skyMid, smoothstep(0.22, 0.62, y));\n bg = mix(bg, skyTop, smoothstep(0.58, 0.98, y));\n\n // Distant painted ridge line above the turf horizon\n float ridge1 = 0.215 + 0.024 * sin(uv.x * 5.2 + 0.8) + 0.012 * sin(uv.x * 13.0 + 2.1);\n float ridge2 = 0.185 + 0.016 * sin(uv.x * 7.8 + 3.4) + 0.008 * cos(uv.x * 19.0);\n vec3 rCol1 = vec3(0.38, 0.40, 0.46);\n vec3 rCol2 = vec3(0.30, 0.33, 0.38);\n bg = mix(bg, mix(rCol1, horizon, 0.38), 1.0 - smoothstep(ridge1 - 0.004, ridge1 + 0.004, y));\n bg = mix(bg, mix(rCol2, lowMist, 0.25), 1.0 - smoothstep(ridge2 - 0.003, ridge2 + 0.003, y));\n bg = mix(underEarth, bg, smoothstep(0.05, 0.13, y));\n // Subtle vignette at extreme left/right corners\n float vig = smoothstep(0.0, 0.35, 1.0 - length((uv - vec2(0.5, 0.52)) * vec2(0.85, 0.95)));\n return bg * mix(0.86, 1.0, vig);\n }\n\n void main() {\n vec2 uv = gl_FragCoord.xy / uRes, px = 1.0 / uRes;\n vec4 inf = texture2D(tInfo, uv);\n if (inf.a < 0.5) {\n vec4 best = vec4(0.0); vec2 bq = uv;\n for (int k = 0; k < 12; k++) {\n float a = float(k) * 0.5236;\n for (int s = 1; s <= 2; s++) {\n vec2 q = uv + vec2(cos(a), sin(a)) * uSil * float(s) * 0.5 * px;\n vec4 ni = texture2D(tInfo, q);\n if (ni.a > 0.5) { best = ni; bq = q; }\n }\n }\n if (best.a > 0.5) {\n int r = rid(best);\n if (r >= 4 && r <= 7) { gl_FragColor = vec4(backdrop(uv), 1.0); return; }\n gl_FragColor = vec4(ink(texture2D(tColor, bq).rgb), 1.0); return;\n }\n gl_FragColor = vec4(backdrop(uv), 1.0); return;\n }\n\n vec3 col = texture2D(tColor, uv).rgb; int r0 = rid(inf); float p0 = pid(inf); float z0 = z(uv);\n bool feature = r0 >= 4 && r0 <= 9;\n if (!feature) {\n for (int k = 0; k < 4; k++) {\n vec2 d = k == 0 ? vec2(1.0, 0.0) : (k == 1 ? vec2(-1.0, 0.0) : (k == 2 ? vec2(0.0, -1.0) : vec2(0.0, 1.0)));\n vec2 q = uv + d * px * uInner;\n vec4 ni = texture2D(tInfo, q);\n if (ni.a > 0.5 && z(q) > z0 + uGap && pid(ni) != p0) { col = ink(col); break; }\n }\n float acc = 0.0, rad = uSil * 2.8;\n for (int k = 0; k < 8; k++) {\n float a = float(k) * 0.785398 + 0.39;\n vec2 q = uv + vec2(cos(a), sin(a)) * rad * px;\n vec4 ni = texture2D(tInfo, q);\n if (ni.a > 0.5) acc += clamp((z0 - z(q)) / 0.05, 0.0, 1.0);\n }\n col *= 1.0 - 0.18 * acc / 8.0;\n }\n gl_FragColor = vec4(col, 1.0);\n }`;\n\nconst compCam = new THREE.Camera();\nfunction compPass(fs, uniforms) {\n const mat = new THREE.ShaderMaterial({\n uniforms,\n vertexShader: `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`,\n fragmentShader: fs, depthTest: false, depthWrite: false\n });\n const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);\n const sc = new THREE.Scene(); sc.add(quad);\n return { scene: sc, mat };\n}\nconst paint = compPass(PAINT_COMP, {\n tColor: { value: null }, tInfo: { value: null }, tDepth: { value: null },\n uRes: { value: new THREE.Vector2() }, uNear: { value: 0.1 }, uFar: { value: 40 },\n uGap: { value: 0.012 }, uSil: { value: 2.0 }, uInner: { value: 1.0 }, uPpm: { value: 1.0 }\n});\n\nconst targets = { rt: null, rtInfo: null, key: \"\" };\nfunction targetsFor(w, h) {\n const key = `${w}x${h}`;\n if (targets.key === key) return;\n [targets.rt, targets.rtInfo].forEach(t => t && t.dispose());\n const o = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter };\n targets.rt = new THREE.WebGLRenderTarget(w, h, o);\n targets.rtInfo = new THREE.WebGLRenderTarget(w, h, { ...o, depthTexture: new THREE.DepthTexture(w, h) });\n targets.key = key;\n}\n\nconst _v = new THREE.Vector3(), _a = new THREE.Vector3(), _ab = new THREE.Vector3(), _cp = new THREE.Vector3();\nclass Cloth {\n constructor(skinned, U, V, trims, capsules, bone, closed = false, hemOnly = false) {\n this.skinned = skinned; this.U = U; this.V = V; this.trims = trims; this.closed = closed;\n this.n = skinned.geometry.attributes.position.count;\n this.caps = capsules.map(c => ({ a: bone(c.bones[0]), b: bone(c.bones[1]), r: c.r + 0.008 })).filter(c => c.a && c.b);\n this.x = new Float32Array(this.n * 3); this.prev = new Float32Array(this.n * 3);\n const idx = (i, j) => i * V + j, links = [], bends = [], edge = new Float32Array(this.n);\n for (let i = 0; i < U; i++) for (let j = 0; j < V; j++) {\n if (i + 1 < U || closed) links.push([idx(i, j), idx((i + 1) % U, j)]);\n if (j + 1 < V) links.push([idx(i, j), idx(i, j + 1)]);\n if (i + 2 < U || closed) bends.push([idx(i, j), idx((i + 2) % U, j)]);\n if (j + 2 < V) bends.push([idx(i, j), idx(i, j + 2)]);\n edge[idx(i, j)] = ((j === 0 && !hemOnly) || j === V - 1 || (!closed && trims.length > 1 && (i === 0 || i === U - 1))) ? 1 : 0;\n }\n const r = skinned.geometry.attributes.position.array;\n const len = ([a, b]) => Math.hypot(r[3*a] - r[3*b], r[3*a+1] - r[3*a+1], r[3*a+2] - r[3*b+2]);\n this.links = links.map(l => [l[0], l[1], len(l)]);\n this.bends = bends.map(l => [l[0], l[1], len(l)]);\n this.pinned = new Uint8Array(this.n); for (let i = 0; i < U; i++) this.pinned[idx(i, 0)] = 1;\n const g = new THREE.BufferGeometry();\n g.setAttribute(\"position\", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3).setUsage(THREE.DynamicDrawUsage));\n g.setAttribute(\"normal\", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3));\n g.setAttribute(\"uv\", skinned.geometry.attributes.uv || new THREE.BufferAttribute(new Float32Array(this.n * 2), 2));\n g.setAttribute(\"edge\", new THREE.BufferAttribute(edge, 1));\n g.setIndex(skinned.geometry.index);\n this.display = new THREE.Mesh(g, skinned.material);\n this.display.userData = { ...skinned.userData, cloth: true };\n this.display.frustumCulled = false;\n }\n rest(k, out) { this.skinned.getVertexPosition(k, out); return out.applyMatrix4(this.skinned.matrixWorld); }\n reset() {\n for (let k = 0; k < this.n; k++) {\n this.rest(k, _v);\n this.x[3*k] = this.prev[3*k] = _v.x; this.x[3*k+1] = this.prev[3*k+1] = _v.y; this.x[3*k+2] = this.prev[3*k+2] = _v.z;\n }\n }\n step(dt, windX = 0) {\n const x = this.x, pv = this.prev, pin = this.pinned;\n const g = -9.8 * dt * dt, damp = 0.982;\n for (let k = 0; k < this.n; k++) {\n if (pin[k]) continue;\n for (let c = 0; c < 3; c++) {\n const i = 3*k + c, v = (x[i] - pv[i]) * damp;\n pv[i] = x[i]; x[i] += v + (c === 1 ? g : 0) + (c === 0 ? windX * dt * dt : 0);\n }\n }\n const pins = [];\n for (let k = 0; k < this.n; k++) if (pin[k]) pins.push([k, this.rest(k, new THREE.Vector3())]);\n const caps = this.caps.map(c => ({ a: c.a.getWorldPosition(new THREE.Vector3()), b: c.b.getWorldPosition(new THREE.Vector3()), r: c.r }));\n const solve = (L, stiff) => {\n for (const [ia, ib, R0] of L) {\n const a = 3 * ia, b = 3 * ib;\n const dx = x[b] - x[a], dy = x[b+1] - x[a+1], dz = x[b+2] - x[a+2];\n const d = Math.hypot(dx, dy, dz) || 1e-9, f = (d - R0) / d * stiff;\n const wa = pin[ia] ? 0 : 1, wb = pin[ib] ? 0 : 1, s = wa + wb;\n if (!s) continue;\n x[a] += dx * f * wa / s; x[a+1] += dy * f * wa / s; x[a+2] += dz * f * wa / s;\n x[b] -= dx * f * wb / s; x[b+1] -= dy * f * wb / s; x[b+2] -= dz * f * wb / s;\n }\n };\n for (let it = 0; it < 10; it++) {\n for (const [k, w] of pins) { x[3*k] = w.x; x[3*k+1] = w.y; x[3*k+2] = w.z; }\n solve(this.links, 1.0); solve(this.bends, 0.25);\n for (let k = 0; k < this.n; k++) {\n if (pin[k]) continue;\n _v.set(x[3*k], x[3*k+1], x[3*k+2]);\n for (const c of caps) {\n _ab.subVectors(c.b, c.a);\n const tt = THREE.MathUtils.clamp(_a.subVectors(_v, c.a).dot(_ab) / _ab.lengthSq(), 0, 1);\n _cp.copy(c.a).addScaledVector(_ab, tt);\n const d = _v.distanceTo(_cp);\n if (d < c.r && d > 1e-6) _v.sub(_cp).multiplyScalar(c.r / d).add(_cp);\n }\n x[3*k] = _v.x; x[3*k+1] = _v.y; x[3*k+2] = _v.z;\n }\n }\n }\n write() {\n const pos = this.display.geometry.attributes.position;\n pos.array.set(this.x); pos.needsUpdate = true;\n this.display.geometry.computeVertexNormals();\n }\n}\n\nconst KEY = new THREE.Vector3(...(SCENE.key || [-0.62, 0.48, 0.62])).normalize();\nconst GRADE = SCENE.grade || { ambient: [0.86, 0.88, 0.96], key: [1.04, 1.00, 0.94], rim: [0.28, 0.25, 0.20] };\nconst KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };\n\nfunction paintMaterial(V, role, map, index, infoRole = role, decal = false, crownY = 1.65) {\n const Rl = V.roles[role] || { mode: \"flat\", color: \"#ff00ff\" }, P = (V.paint || {})[role];\n const u = {\n uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() },\n uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },\n uInfo: { value: new THREE.Vector4(roleId(infoRole) / 255, (index % 256) / 255, Math.floor(index / 256) / 255, 1) },\n uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() },\n uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) },\n uGold: { value: hex((V.paint && V.paint.gold && V.paint.gold.base) || \"#c49a45\") },\n uAmbient: { value: new THREE.Vector3(...GRADE.ambient) },\n uKeyCol: { value: new THREE.Vector3(...GRADE.key) },\n uRimCol: { value: new THREE.Vector3(...GRADE.rim) },\n uGrain: { value: 0.04 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null },\n uSkinTone: { value: new THREE.Vector3(1, 1, 1) }, uShadeOnly: { value: 0 },\n uSkinRamp: { value: 0 }, uSkinL: { value: new THREE.Color() }, uSkinS: { value: new THREE.Color() }, uSkinC: { value: new THREE.Color() },\n uCrownY: { value: crownY },\n uFootA: { value: new THREE.Vector2(99, 99) }, uFootB: { value: new THREE.Vector2(99, 99) },\n uFootC: { value: new THREE.Vector2(99, 99) }, uFootD: { value: new THREE.Vector2(99, 99) },\n tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 },\n uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 },\n uMotif: { value: hex((V.paint && V.paint.motif && V.paint.motif.base) || \"#e8e3d5\") }, uLift: { value: 0 }\n };\n if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; }\n else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); }\n if (P && P.kind === \"world\") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.11; }\n if (P && P.shade) u.uShadeOnly.value = 1;\n if (P && P.kind === \"skin\" && P.ramp) {\n u.uSkinRamp.value = 1; u.uSkinL.value = hex(P.ramp[0]); u.uSkinS.value = hex(P.ramp[1]); u.uSkinC.value = hex(P.ramp[2]);\n }\n if (P && P.kind === \"skin\" && P.base) {\n const c = hex(P.base); u.uSkinTone.value.set(c.r / 0.973, c.g / 0.882, c.b / 0.835);\n }\n if (role === \"face\" && map) u.uFaceTex.value = 1;\n if ((role === \"hair\" || role === \"hair_cap\") && map) u.uAlpha.value = 1;\n if (role === \"iris\") { u.uKind.value = 7; u.uAlpha.value = 1; }\n else if (role === \"white\" || role === \"highlight\") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || \"#ffffff\"); }\n else if (!P && Rl.mode === \"flat\") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === \"line\" ? 2 : 1; }\n if (role === \"mouth\" && map) u.uKind.value = 10;\n u.uBand.value = u.uGold.value.clone();\n const m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: PAINT_VS, fragmentShader: PAINT_FS, side: THREE.DoubleSide,\n extensions: { derivatives: true } });\n m.defaultAttributeValues = { ...m.defaultAttributeValues, _plate: [0, 0, 0, 0], edge: [0] };\n return m;\n}\n\nconst loader = new GLTFLoader();\nasync function parseGlb(file) {\n const j = await (await fetch(file)).json();\n const bin = Uint8Array.from(atob(j.glb), c => c.charCodeAt(0));\n return await new Promise((ok, bad) => loader.parse(bin.buffer, \"\", ok, bad));\n}\n\nlet meshIndex = 1;\nconst allMeshes = [];\nconst allCloths = [];\nconst characters = [];\n\nfor (let ci = 0; ci < SCENE.characters.length; ci++) {\n const def = SCENE.characters[ci], V = def.info;\n const gltf = await parseGlb(`${def.name}.glb.json`);\n const turn = new THREE.Group();\n turn.add(gltf.scene);\n turn.position.set(...def.place.pos);\n turn.rotation.y = THREE.MathUtils.degToRad(def.place.yaw);\n scene.add(turn);\n\n const meshes = [];\n gltf.scene.traverse(o => {\n if (!o.isMesh) return;\n const m0 = o.material, role = o.userData.role || \"body\", raw = rawTex(m0.map);\n const matName = o.userData.material || \"\";\n const isInnerHair = role === \"hair_cap\" || matName.includes(\"HairBack\");\n const infoRole = isInnerHair ? \"hair_cap\" : (role === \"hair\" && ci > 0 ? \"hair_b\" : role === \"shadow\" ? \"body\" : role);\n const decal = !!(m0.userData && m0.userData.decal);\n const mat = paintMaterial(V, role, raw, meshIndex++, infoRole, decal, def.crown_y || 1.68);\n if (isInnerHair) mat.uniforms.uShadeOnly.value = 1;\n o.material = mat;\n o.frustumCulled = false;\n meshes.push(o);\n allMeshes.push(o);\n });\n\n const mixer = new THREE.AnimationMixer(gltf.scene);\n const actions = Object.fromEntries(gltf.animations.map(c => [c.name, mixer.clipAction(c)]));\n const clipName = def.clip || \"idle\";\n if (actions[clipName]) {\n actions[clipName].reset();\n actions[clipName].setEffectiveWeight(1);\n actions[clipName].play();\n actions[clipName].time = def.clip_t || 0;\n mixer.update(0);\n }\n scene.updateMatrixWorld(true);\n\n // Measure live crown height for the halo band after posing\n const headBone = gltf.scene.getObjectByName(\"J_Bip_C_Head\");\n if (headBone) {\n const hp = headBone.getWorldPosition(new THREE.Vector3());\n const cy = hp.y + 0.145;\n meshes.forEach(m => { m.material.uniforms.uCrownY.value = cy; });\n }\n\n const bone = n => gltf.scene.getObjectByName(n);\n const world = new THREE.Group();\n scene.add(world);\n for (const [cname, info] of Object.entries(V.cloth || {})) {\n const skinned = meshes.find(m => m.userData.material === cname);\n if (!skinned) continue;\n const trims = meshes.filter(m => info.trims.includes(m.userData.material));\n const caps = V.capsules.filter(c => !info.collide || info.collide.some(k => c.bones[0].includes(k)));\n const cl = new Cloth(skinned, info.u, info.v, trims, caps, bone, info.closed, info.edges === \"hem\");\n const PB = (V.paint || {})[info.band || \"gold\"];\n if (PB && PB.base) cl.display.material.uniforms.uBand.value = hex(PB.base);\n skinned.visible = false;\n trims.forEach(t => { t.visible = false; });\n world.add(cl.display);\n allMeshes.push(cl.display);\n allCloths.push({ cl, wind: def.wind || 0 });\n }\n characters.push({ def, root: gltf.scene, meshes });\n}\n\n// Settle cloth drapes cleanly\nallCloths.forEach(({ cl }) => cl.reset());\nfor (let s = 0; s < 160; s++) allCloths.forEach(({ cl, wind }) => cl.step(1 / 120, wind));\nallCloths.forEach(({ cl }) => cl.write());\n\n// Load terrain and pass planted foot positions for contact shadows\nconst groundGltf = await parseGlb(\"plains.glb.json\");\nscene.add(groundGltf.scene);\nconst footPts = [];\nfor (const c of characters) {\n for (const fn of [\"J_Bip_L_Foot\", \"J_Bip_R_Foot\"]) {\n const b = c.root.getObjectByName(fn);\n if (b) { const p = b.getWorldPosition(new THREE.Vector3()); footPts.push(new THREE.Vector2(p.x, p.z)); }\n }\n}\nwhile (footPts.length < 4) footPts.push(new THREE.Vector2(99, 99));\n\nconst V0 = SCENE.characters[0].info;\ngroundGltf.scene.traverse(o => {\n if (!o.isMesh) return;\n const role = o.userData.role || \"grass\";\n const mat = paintMaterial(V0, role, rawTex(o.material.map), meshIndex++, role, false);\n mat.uniforms.uFootA.value.copy(footPts[0]);\n mat.uniforms.uFootB.value.copy(footPts[1]);\n mat.uniforms.uFootC.value.copy(footPts[2]);\n mat.uniforms.uFootD.value.copy(footPts[3]);\n o.material = mat;\n o.frustumCulled = false;\n allMeshes.push(o);\n});\n\nfunction setupCamera(aspect) {\n const C = SCENE.camera;\n const centre = new THREE.Vector3(...C.target);\n const h = C.height, w = h * aspect;\n camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2;\n camera.zoom = 1;\n camera.updateProjectionMatrix();\n const a = THREE.MathUtils.degToRad(C.pitch);\n camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(16));\n camera.up.set(0, 1, 0);\n camera.lookAt(centre);\n}\n\nfunction renderFrame(w, h, ss = 1) {\n const bw = w * ss, bh = h * ss;\n R.setPixelRatio(1);\n R.setSize(bw, bh, false);\n setupCamera(w / h);\n targetsFor(bw, bh);\n\n const visible = allMeshes.filter(o => o.visible);\n visible.forEach(o => {\n const mu = o.material.uniforms;\n mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null;\n });\n R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera);\n\n const ppmBuf = bh / (camera.top - camera.bottom);\n visible.forEach(o => {\n const mu = o.material.uniforms;\n mu.uPass.value = 0; mu.uCastOn.value = 1;\n mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture;\n mu.uCastRes.value.set(bw, bh); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf;\n });\n R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera);\n\n const u = paint.mat.uniforms;\n u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture;\n u.uRes.value.set(bw, bh); u.uNear.value = camera.near; u.uFar.value = camera.far;\n u.uGap.value = 0.012;\n u.uSil.value = THREE.MathUtils.clamp(1.75 * ppmBuf * 0.0040, ss, 2.5 * ss);\n u.uInner.value = Math.max(ss * 0.78, u.uSil.value * 0.56);\n u.uPpm.value = ppmBuf;\n R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam);\n}\n\nif (SHOT) {\n const outW = +(params.get(\"w\") || 1920), outH = +(params.get(\"h\") || 1080), ss = +(params.get(\"ss\") || 2);\n renderFrame(outW, outH, ss);\n const cv = document.createElement(\"canvas\");\n cv.width = outW; cv.height = outH;\n const ctx = cv.getContext(\"2d\");\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = \"high\";\n ctx.drawImage(R.domElement, 0, 0, outW, outH);\n document.getElementById(\"sheetOut\").textContent = cv.toDataURL(\"image/png\");\n document.title = \"slice ready\";\n} else {\n const fit = () => renderFrame(window.innerWidth, window.innerHeight, Math.min(2, window.devicePixelRatio || 1));\n window.addEventListener(\"resize\", fit);\n fit();\n}\n</script>\n</body>\n</html>\n","Overwrite":true,"Path":"~/work/lowmarch/review/slice/index.html"}

    input

    {
      "Content": "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Battle Slice · Lowmarch</title>\n<style>\n  html, body { margin: 0; height: 100%; background: #1e1d26; color: #ece8e0; font-family: system-ui, sans-serif; overflow: hidden; }\n  #stage { position: fixed; inset: 0; display: grid; place-items: center; }\n  canvas { max-width: 100%; max-height: 100%; display: block; }\n  #sheetOut { display: none; }\n</style>\n<script type=\"importmap\">\n{\n  \"imports\": {\n    \"three\": \"./three/build/three.module.js\",\n    \"three/addons/\": \"./three/examples/jsm/\"\n  }\n}\n</script>\n</head>\n<body>\n<div id=\"stage\"></div>\n<pre id=\"sheetOut\"></pre>\n<script type=\"module\">\nimport * as THREE from \"three\";\nimport { GLTFLoader } from \"three/addons/loaders/GLTFLoader.js\";\n\nconst params = new URLSearchParams(location.search);\nconst SHOT = params.has(\"shot\");\nconst SCENE = await (await fetch(\"scene.json\")).json();\n\nconst stageEl = document.getElementById(\"stage\");\nconst R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: true });\nR.outputColorSpace = THREE.LinearSRGBColorSpace;\nR.setClearColor(0x000000, 0);\nstageEl.appendChild(R.domElement);\n\nconst hex = h => {\n  const n = parseInt(h.slice(1), 16);\n  return new THREE.Color().setRGB((n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255, THREE.LinearSRGBColorSpace);\n};\nconst rawTex = t => { if (!t) return null; const c = t.clone(); c.colorSpace = THREE.NoColorSpace; c.needsUpdate = true; return c; };\nconst white = (() => { const t = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1, THREE.RGBAFormat); t.needsUpdate = true; return t; })();\n\nconst R_ID = { face: 1, body: 2, hair: 3, iris: 4, white: 5, highlight: 6, line: 7, brow: 8, mouth: 9, hair_b: 11, hair_cap: 12, grass: 20, dirt: 21, stone: 22 };\nconst roleId = r => R_ID[r] || 10;\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 40);\n\nconst SKIN_HEAD = `#include <common>\n  #include <skinning_pars_vertex>`;\nconst SKIN_BODY = `#include <beginnormal_vertex>\n    #include <skinbase_vertex>\n    #include <skinnormal_vertex>\n    #include <begin_vertex>\n    #include <skinning_vertex>`;\n\nconst PAINT_VS = `${SKIN_HEAD}\n  attribute float edge; attribute vec4 _plate; uniform float uLift;\n  varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying vec3 vWPos;\n  varying float vEdge; varying vec4 vPlate;\n  void main() {\n    ${SKIN_BODY}\n    vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate;\n    vec4 wp = modelMatrix * vec4(transformed, 1.0);\n    vWPos = wp.xyz;\n    vec4 mv = modelViewMatrix * vec4(transformed, 1.0); vView = -mv.xyz;\n    mv.z += uLift;\n    gl_Position = projectionMatrix * mv;\n  }`;\n\nconst HSV = `\n  vec3 rgb2hsv(vec3 c) {\n    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n    float d = q.x - min(q.w, q.y);\n    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 1e-10)), d / (q.x + 1e-10), q.x);\n  }\n  vec3 hsv2rgb(vec3 c) {\n    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n  }`;\n\nconst PAINT_FS = `\n  uniform int uKind; uniform vec3 uBase; uniform vec3 uKey; uniform sampler2D uMap; uniform int uAlpha;\n  uniform int uPass; uniform vec4 uInfo; uniform vec3 uEye[3]; uniform vec3 uFlat; uniform vec3 uSkinRef;\n  uniform vec3 uGold; uniform vec3 uAmbient; uniform vec3 uKeyCol; uniform vec3 uRimCol; uniform float uGrain;\n  uniform int uFaceTex; uniform int uDecal; uniform vec3 uMotif; uniform vec3 uBand; uniform vec3 uSkinTone; uniform int uShadeOnly;\n  uniform int uSkinRamp; uniform vec3 uSkinL; uniform vec3 uSkinS; uniform vec3 uSkinC;\n  uniform float uCrownY;\n  uniform vec2 uFootA; uniform vec2 uFootB; uniform vec2 uFootC; uniform vec2 uFootD;\n  uniform sampler2D tCastInfo; uniform sampler2D tCastDepth; uniform vec2 uCastRes; uniform int uCastOn;\n  uniform float uCastNear; uniform float uCastFar; uniform float uCastPpm;\n\n  float castShadow(int selfRole) {\n    vec2 uv = gl_FragCoord.xy / uCastRes, px = 1.0 / uCastRes;\n    float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);\n    float sxy = length(uKey.xy);\n    if (sxy < 0.05) return 0.0;\n    vec2 dir = uKey.xy / sxy;\n    float lz = uKey.z / sxy;\n    int steps = selfRole == 1 ? 8 : 15;\n    float stepM = selfRole == 1 ? 0.0026 : 0.0032;\n    for (int s = 1; s <= 15; s++) {\n      if (s > steps) break;\n      float dm = float(s) * stepM;\n      vec2 q = uv + dir * dm * uCastPpm * px;\n      vec4 ni = texture2D(tCastInfo, q);\n      if (ni.a < 0.5) continue;\n      int r = int(ni.r * 255.0 + 0.5);\n      if (selfRole == 1) {\n        if (r != 3 && r != 11 && r != 12) continue;\n      } else {\n        if (r != 1 && r != 3 && r != 11 && r != 12) continue;\n      }\n      float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);\n      float zr = z0 - lz * dm;\n      if (zq < zr - 0.004 && zq > zr - 0.22) return 1.0;\n    }\n    return 0.0;\n  }\n\n  varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying vec3 vWPos;\n  varying float vEdge; varying vec4 vPlate;\n  ${HSV}\n  float hash(vec3 p) { p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }\n  float vnoise(vec3 x) {\n    vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);\n    return mix(mix(mix(hash(i), hash(i + vec3(1,0,0)), f.x), mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y),\n               mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x), mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z);\n  }\n  float toward(float h, float target, float amt) { float d = target - h; d -= floor(d + 0.5); return fract(h + clamp(d, -amt, amt)); }\n  vec3 tone(vec3 base, float hue, float amt, float sMul, float vMul) {\n    vec3 h = rgb2hsv(base);\n    return hsv2rgb(vec3(toward(h.x, hue, amt), clamp(h.y * sMul, 0.0, 1.0), clamp(h.z * vMul, 0.0, 1.0)));\n  }\n  float st(float x, float t) { return smoothstep(t - 0.025, t + 0.025, x); }\n\n  vec3 metal(bool gold, vec3 base, vec3 n, vec3 v, float lit, float hgt) {\n    vec3 r = reflect(-v, n);\n    float ry = r.y + (vnoise(vObj * vec3(3.0, 14.0, 3.0)) - 0.5) * 0.12;\n    float curv = length(fwidth(n)) / max(length(fwidth(vView)), 1e-5);\n    float sharp = smoothstep(5.0, 14.0, curv);\n    if (hgt >= 0.0) sharp *= 0.25; else sharp = max(sharp, 0.3);\n    vec3 s0, s1, s2, s3;\n    if (!gold) { s0 = tone(base, 0.66, 0.10, 2.1, 0.34); s1 = tone(base, 0.66, 0.06, 1.5, 0.74);\n                 s2 = tone(base, 0.12, 0.0, 0.8, 0.90); s3 = vec3(0.97, 0.96, 0.93); }\n    else { s0 = vec3(0.28, 0.19, 0.24); s1 = tone(base, 0.12, 0.03, 1.05, 0.72); s2 = base; s3 = tone(base, 0.14, 0.03, 0.52, 1.48); }\n    vec3 hard = mix(s0, s1, st(ry, -0.42));\n    hard = mix(hard, s2, st(ry, -0.08));\n    hard = mix(hard, s0, st(ry, 0.36));\n    hard = mix(hard, s3, st(ry, 0.47));\n    hard = mix(hard, s2 * 1.05, st(ry, 0.70));\n    float k = smoothstep(-0.55, 0.30, r.y);\n    if (hgt >= 0.0) k = clamp(k * 0.45 + hgt * 0.80 - 0.18, 0.0, 1.0);\n    else k = clamp(k * 0.6 + n.y * 0.35 + 0.05, 0.0, 1.0);\n    vec3 soft = mix(s1 * 0.9, s2, k);\n    float hl = dot(n, normalize(uKey + v));\n    if (hgt >= 0.0) soft = mix(soft, mix(s2, s3, 0.62), st(hl, 0.95) * smoothstep(0.42, 0.8, hgt));\n    vec3 col = mix(soft, hard, sharp);\n    return mix(col * 0.70 + s0 * 0.30, col, st(lit, 0.34));\n  }\n\n  void main() {\n    vec4 tex = texture2D(uMap, vUv);\n    if (uAlpha == 1 && tex.a < 0.5) discard;\n    if (uAlpha == 2 && (tex.a < 0.5 || dot(tex.rgb, vec3(1.0 / 3.0)) >= 0.42)) discard;\n    if (uPass == 1) { gl_FragColor = uInfo; return; }\n\n    bool back = !gl_FrontFacing;\n    vec3 n = normalize(vN); if (back) n = -n;\n    vec3 v = normalize(vView);\n    float lit = dot(n, uKey) * 0.5 + 0.5;\n    int selfRole = int(uInfo.x * 255.0 + 0.5);\n\n    if (uShadeOnly == 1) {\n      lit = 0.12;\n    } else if (uCastOn == 1 && uKind == 1 && (selfRole == 1 || selfRole == 2)) {\n      if (castShadow(selfRole) > 0.5) lit = min(lit, 0.34);\n    }\n\n    float g1 = vnoise(vObj * 40.0), g2 = vnoise(vObj * 150.0);\n    vec3 col;\n    if (uKind == 0 || uKind == 5 || uKind == 6) {\n      vec3 hb = rgb2hsv(uBase);\n      bool cool = hb.x > 0.42 && hb.x < 0.86;\n      float sh = uKind == 5 ? 0.93 : (cool ? 0.68 : 0.96);\n      float li = cool ? 0.55 : 0.12;\n      vec3 c0 = tone(uBase, sh, 0.08, 1.12, 0.42), c1 = tone(uBase, sh, 0.05, 1.08, 0.66);\n      vec3 c3 = tone(uBase, li, 0.03, 0.82, 1.18);\n      float l = lit + (g1 - 0.5) * uGrain - (uKind == 6 ? 0.20 : 0.0);\n      if (uKind == 6) {\n        // Contact shadow on ground beneath planted feet\n        vec2 xz = vWPos.xz;\n        float da = length((xz - uFootA) * vec2(1.0, 1.35));\n        float db = length((xz - uFootB) * vec2(1.0, 1.35));\n        float dc = length((xz - uFootC) * vec2(1.0, 1.35));\n        float dd = length((xz - uFootD) * vec2(1.0, 1.35));\n        float dmin = min(min(da, db), min(dc, dd));\n        float contact = 1.0 - smoothstep(0.08, 0.30, dmin);\n        l -= 0.36 * contact;\n      }\n      col = mix(c0, c1, st(l, 0.32)); col = mix(col, uBase, st(l, 0.50)); col = mix(col, c3, st(l, 0.90));\n      if (uKind == 5) col *= 0.965 + 0.07 * vnoise(vObj * 22.0);\n    } else if (uKind == 1) {\n      // Skin: genuine 3/4 shadow plane (threshold 0.50 instead of 0.38) + warm hue-shifted ramp\n      vec3 sL = vec3(0.973, 0.882, 0.835), sS = vec3(0.776, 0.659, 0.608), sC = vec3(0.451, 0.322, 0.310);\n      if (uSkinRamp == 1) { sL = uSkinL; sS = uSkinS; sC = uSkinC; }\n      col = mix(sC, sS, st(lit, 0.24)); col = mix(col, sL, st(lit, 0.50));\n      if (uFaceTex == 1) col *= clamp(tex.rgb / uSkinRef, 0.58, 1.04);\n      if (uFaceTex == 1 && vUv.x > 0.37 && vUv.x < 0.63 && vUv.y > 0.68 && vUv.y < 0.84) {\n        float d = 0.0, sl = dot(uSkinRef, vec3(1.0 / 3.0));\n        for (int k = -2; k <= 2; k++) for (int j = -2; j <= 2; j++) {\n          vec3 t = texture2D(uMap, vUv + vec2(float(j) * 1.1, float(k) * 0.9) / 512.0).rgb;\n          d = max(d, 1.0 - dot(t, vec3(1.0 / 3.0)) / sl);\n        }\n        float taper = 1.0 - 0.45 * smoothstep(0.038, 0.068, abs(vUv.x - 0.5));\n        vec3 lipInk = mix(sC * 0.68, vec3(0.32, 0.14, 0.15), 0.55);\n        col = mix(col, lipInk, smoothstep(0.09, 0.20, d) * taper);\n      }\n      if (uSkinRamp == 0) col *= uSkinTone;\n    } else if (uKind == 2) {\n      // Calm 2-tone cel hair + dark inner backfaces + one restrained crown halo band\n      float strand = dot(tex.rgb, vec3(1.0 / 3.0));\n      vec3 c0 = tone(uBase, 0.70, 0.06, 1.12, 0.38);\n      vec3 c1 = tone(uBase, 0.70, 0.04, 1.06, 0.66);\n      vec3 c2 = tone(uBase, 0.12, 0.02, 0.78, 1.24);\n      if (back || uShadeOnly == 1 || selfRole == 12) {\n        col = c0;\n      } else {\n        float l = lit + (strand - 0.58) * 0.035;\n        col = mix(c0, c1, st(l, 0.28));\n        col = mix(col, uBase, st(l, 0.48));\n        // Clean horizontal anime halo band around upper crown locks\n        float dy = (vWPos.y - uCrownY);\n        float bandMask = exp(-pow(dy / 0.028, 2.0)) * smoothstep(0.54, 0.68, lit);\n        float sp = dot(n, normalize(uKey + v)) + (strand - 0.58) * 0.04;\n        float halo = bandMask * smoothstep(0.76, 0.86, sp);\n        col = mix(col, c2, 0.62 * halo);\n      }\n    } else if (uKind == 3 || uKind == 4) {\n      bool plate = vPlate.x > 0.5;\n      float e = vPlate.y, w = vPlate.z;\n      bool gilt = uKind == 4 || (plate && w > 0.0 && e < w);\n      col = metal(gilt, gilt && uKind == 3 ? uGold : uBase, n, v, lit, plate ? vPlate.w : -1.0);\n      if (plate && w > 0.0) {\n        float aa = fwidth(e) * 1.2 + 1e-5;\n        float l1 = 1.0 - smoothstep(0.0010, 0.0010 + aa, abs(e - (w + 0.0050)));\n        float l2 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - w));\n        col = mix(col, col * 0.42, max(l1, l2 * 0.8));\n      }\n    } else if (uKind == 7) {\n      float l = dot(tex.rgb, vec3(1.0 / 3.0));\n      col = l < 0.3 ? mix(uEye[0], uEye[1], l / 0.3) : mix(uEye[1], uEye[2], clamp((l - 0.3) / 0.6, 0.0, 1.0));\n    } else if (uKind == 8) { col = tex.rgb; }\n    else if (uKind == 10) {\n      float lum = dot(tex.rgb, vec3(1.0 / 3.0));\n      col = mix(vec3(0.36, 0.11, 0.14), vec3(0.78, 0.38, 0.42), smoothstep(0.53, 0.58, tex.g));\n      col = mix(col, vec3(0.98, 0.96, 0.95), smoothstep(0.80, 0.86, lum));\n    } else { col = uFlat; }\n\n    if (vPlate.x > 0.5 && vPlate.z > 0.0 && uKind != 3 && uKind != 4) {\n      float e = vPlate.y, w = vPlate.z, aa = fwidth(e) * 1.2 + 1e-5;\n      float band = 1.0 - smoothstep(w - aa, w, e);\n      float l1 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - (w + 0.0040)));\n      col = mix(col, metal(true, uGold, n, v, lit, -1.0), max(band, l1 * 0.9));\n    }\n    if (uDecal == 1) {\n      vec3 dm = tex.rgb;\n      float pm = smoothstep(0.3, 0.7, dm.r), gm = smoothstep(0.3, 0.7, dm.g), au = smoothstep(0.3, 0.7, dm.b);\n      if (au > 0.0) col = mix(col, metal(true, uGold, n, v, lit, -1.0), au);\n      if (pm > 0.0) {\n        vec3 pc = mix(tone(uMotif, 0.70, 0.05, 1.10, 0.62), uMotif, st(lit, 0.42));\n        col = mix(col, mix(pc, tone(uMotif, 0.56, 0.03, 0.8, 1.25), st(lit, 0.92)), pm);\n      }\n      if (gm > 0.0) col = mix(col, col * 0.30, gm);\n    }\n    if (vEdge > 0.5) {\n      vec3 gd = tone(uBand, 0.20, 0.03, 1.0, 0.72);\n      col = mix(gd, uBand, st(lit, 0.45)); col = mix(col, tone(uBand, 0.16, 0.03, 0.5, 1.45), st(lit, 0.85));\n    }\n    if (uKind <= 6) {\n      vec3 grade = mix(uAmbient, uKeyCol, st(lit, 0.52));\n      col *= uKind == 1 && uSkinRamp == 1 ? mix(vec3(1.0), grade, 0.25) : grade;\n      float fr = pow(1.0 - max(dot(n, v), 0.0), 4.2);\n      float rimBack = clamp(dot(n, normalize(vec3(0.55, 0.45, -0.35))), 0.0, 1.0);\n      col += uRimCol * fr * smoothstep(0.12, 0.55, rimBack) * (uKind == 1 ? 0.45 : 0.85);\n      if (uKind != 1 && uKind != 2) col *= 1.0 + (g2 - 0.5) * 0.05;\n    }\n    gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);\n  }`;\n\nconst PAINT_COMP = `\n  uniform sampler2D tColor; uniform sampler2D tInfo; uniform sampler2D tDepth; uniform vec2 uRes;\n  uniform float uNear; uniform float uFar; uniform float uGap; uniform float uSil; uniform float uInner; uniform float uPpm;\n  ${HSV}\n  float z(vec2 p) { return uNear + texture2D(tDepth, p).x * (uFar - uNear); }\n  int rid(vec4 i) { return int(i.r * 255.0 + 0.5); }\n  float pid(vec4 i) { return floor(i.g * 255.0 + 0.5) + floor(i.b * 255.0 + 0.5) * 256.0; }\n  vec3 ink(vec3 c) { vec3 h = rgb2hsv(c); return hsv2rgb(vec3(h.x, clamp(h.y, 0.20, 0.45), 0.18)); }\n\n  vec3 backdrop(vec2 uv) {\n    // Painted dusk-parchment SRPG stage backdrop (replaces pitch-black #0e0d12 void)\n    vec3 skyTop = vec3(0.22, 0.27, 0.36);\n    vec3 skyMid = vec3(0.46, 0.47, 0.52);\n    vec3 horizon = vec3(0.76, 0.69, 0.60);\n    vec3 lowMist = vec3(0.58, 0.54, 0.50);\n    vec3 underEarth = vec3(0.15, 0.14, 0.18);\n\n    float y = uv.y;\n    vec3 bg = mix(horizon, skyMid, smoothstep(0.22, 0.62, y));\n    bg = mix(bg, skyTop, smoothstep(0.58, 0.98, y));\n\n    // Distant painted ridge line above the turf horizon\n    float ridge1 = 0.215 + 0.024 * sin(uv.x * 5.2 + 0.8) + 0.012 * sin(uv.x * 13.0 + 2.1);\n    float ridge2 = 0.185 + 0.016 * sin(uv.x * 7.8 + 3.4) + 0.008 * cos(uv.x * 19.0);\n    vec3 rCol1 = vec3(0.38, 0.40, 0.46);\n    vec3 rCol2 = vec3(0.30, 0.33, 0.38);\n    bg = mix(bg, mix(rCol1, horizon, 0.38), 1.0 - smoothstep(ridge1 - 0.004, ridge1 + 0.004, y));\n    bg = mix(bg, mix(rCol2, lowMist, 0.25), 1.0 - smoothstep(ridge2 - 0.003, ridge2 + 0.003, y));\n    bg = mix(underEarth, bg, smoothstep(0.05, 0.13, y));\n    // Subtle vignette at extreme left/right corners\n    float vig = smoothstep(0.0, 0.35, 1.0 - length((uv - vec2(0.5, 0.52)) * vec2(0.85, 0.95)));\n    return bg * mix(0.86, 1.0, vig);\n  }\n\n  void main() {\n    vec2 uv = gl_FragCoord.xy / uRes, px = 1.0 / uRes;\n    vec4 inf = texture2D(tInfo, uv);\n    if (inf.a < 0.5) {\n      vec4 best = vec4(0.0); vec2 bq = uv;\n      for (int k = 0; k < 12; k++) {\n        float a = float(k) * 0.5236;\n        for (int s = 1; s <= 2; s++) {\n          vec2 q = uv + vec2(cos(a), sin(a)) * uSil * float(s) * 0.5 * px;\n          vec4 ni = texture2D(tInfo, q);\n          if (ni.a > 0.5) { best = ni; bq = q; }\n        }\n      }\n      if (best.a > 0.5) {\n        int r = rid(best);\n        if (r >= 4 && r <= 7) { gl_FragColor = vec4(backdrop(uv), 1.0); return; }\n        gl_FragColor = vec4(ink(texture2D(tColor, bq).rgb), 1.0); return;\n      }\n      gl_FragColor = vec4(backdrop(uv), 1.0); return;\n    }\n\n    vec3 col = texture2D(tColor, uv).rgb; int r0 = rid(inf); float p0 = pid(inf); float z0 = z(uv);\n    bool feature = r0 >= 4 && r0 <= 9;\n    if (!feature) {\n      for (int k = 0; k < 4; k++) {\n        vec2 d = k == 0 ? vec2(1.0, 0.0) : (k == 1 ? vec2(-1.0, 0.0) : (k == 2 ? vec2(0.0, -1.0) : vec2(0.0, 1.0)));\n        vec2 q = uv + d * px * uInner;\n        vec4 ni = texture2D(tInfo, q);\n        if (ni.a > 0.5 && z(q) > z0 + uGap && pid(ni) != p0) { col = ink(col); break; }\n      }\n      float acc = 0.0, rad = uSil * 2.8;\n      for (int k = 0; k < 8; k++) {\n        float a = float(k) * 0.785398 + 0.39;\n        vec2 q = uv + vec2(cos(a), sin(a)) * rad * px;\n        vec4 ni = texture2D(tInfo, q);\n        if (ni.a > 0.5) acc += clamp((z0 - z(q)) / 0.05, 0.0, 1.0);\n      }\n      col *= 1.0 - 0.18 * acc / 8.0;\n    }\n    gl_FragColor = vec4(col, 1.0);\n  }`;\n\nconst compCam = new THREE.Camera();\nfunction compPass(fs, uniforms) {\n  const mat = new THREE.ShaderMaterial({\n    uniforms,\n    vertexShader: `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`,\n    fragmentShader: fs, depthTest: false, depthWrite: false\n  });\n  const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);\n  const sc = new THREE.Scene(); sc.add(quad);\n  return { scene: sc, mat };\n}\nconst paint = compPass(PAINT_COMP, {\n  tColor: { value: null }, tInfo: { value: null }, tDepth: { value: null },\n  uRes: { value: new THREE.Vector2() }, uNear: { value: 0.1 }, uFar: { value: 40 },\n  uGap: { value: 0.012 }, uSil: { value: 2.0 }, uInner: { value: 1.0 }, uPpm: { value: 1.0 }\n});\n\nconst targets = { rt: null, rtInfo: null, key: \"\" };\nfunction targetsFor(w, h) {\n  const key = `${w}x${h}`;\n  if (targets.key === key) return;\n  [targets.rt, targets.rtInfo].forEach(t => t && t.dispose());\n  const o = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter };\n  targets.rt = new THREE.WebGLRenderTarget(w, h, o);\n  targets.rtInfo = new THREE.WebGLRenderTarget(w, h, { ...o, depthTexture: new THREE.DepthTexture(w, h) });\n  targets.key = key;\n}\n\nconst _v = new THREE.Vector3(), _a = new THREE.Vector3(), _ab = new THREE.Vector3(), _cp = new THREE.Vector3();\nclass Cloth {\n  constructor(skinned, U, V, trims, capsules, bone, closed = false, hemOnly = false) {\n    this.skinned = skinned; this.U = U; this.V = V; this.trims = trims; this.closed = closed;\n    this.n = skinned.geometry.attributes.position.count;\n    this.caps = capsules.map(c => ({ a: bone(c.bones[0]), b: bone(c.bones[1]), r: c.r + 0.008 })).filter(c => c.a && c.b);\n    this.x = new Float32Array(this.n * 3); this.prev = new Float32Array(this.n * 3);\n    const idx = (i, j) => i * V + j, links = [], bends = [], edge = new Float32Array(this.n);\n    for (let i = 0; i < U; i++) for (let j = 0; j < V; j++) {\n      if (i + 1 < U || closed) links.push([idx(i, j), idx((i + 1) % U, j)]);\n      if (j + 1 < V) links.push([idx(i, j), idx(i, j + 1)]);\n      if (i + 2 < U || closed) bends.push([idx(i, j), idx((i + 2) % U, j)]);\n      if (j + 2 < V) bends.push([idx(i, j), idx(i, j + 2)]);\n      edge[idx(i, j)] = ((j === 0 && !hemOnly) || j === V - 1 || (!closed && trims.length > 1 && (i === 0 || i === U - 1))) ? 1 : 0;\n    }\n    const r = skinned.geometry.attributes.position.array;\n    const len = ([a, b]) => Math.hypot(r[3*a] - r[3*b], r[3*a+1] - r[3*a+1], r[3*a+2] - r[3*b+2]);\n    this.links = links.map(l => [l[0], l[1], len(l)]);\n    this.bends = bends.map(l => [l[0], l[1], len(l)]);\n    this.pinned = new Uint8Array(this.n); for (let i = 0; i < U; i++) this.pinned[idx(i, 0)] = 1;\n    const g = new THREE.BufferGeometry();\n    g.setAttribute(\"position\", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3).setUsage(THREE.DynamicDrawUsage));\n    g.setAttribute(\"normal\", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3));\n    g.setAttribute(\"uv\", skinned.geometry.attributes.uv || new THREE.BufferAttribute(new Float32Array(this.n * 2), 2));\n    g.setAttribute(\"edge\", new THREE.BufferAttribute(edge, 1));\n    g.setIndex(skinned.geometry.index);\n    this.display = new THREE.Mesh(g, skinned.material);\n    this.display.userData = { ...skinned.userData, cloth: true };\n    this.display.frustumCulled = false;\n  }\n  rest(k, out) { this.skinned.getVertexPosition(k, out); return out.applyMatrix4(this.skinned.matrixWorld); }\n  reset() {\n    for (let k = 0; k < this.n; k++) {\n      this.rest(k, _v);\n      this.x[3*k] = this.prev[3*k] = _v.x; this.x[3*k+1] = this.prev[3*k+1] = _v.y; this.x[3*k+2] = this.prev[3*k+2] = _v.z;\n    }\n  }\n  step(dt, windX = 0) {\n    const x = this.x, pv = this.prev, pin = this.pinned;\n    const g = -9.8 * dt * dt, damp = 0.982;\n    for (let k = 0; k < this.n; k++) {\n      if (pin[k]) continue;\n      for (let c = 0; c < 3; c++) {\n        const i = 3*k + c, v = (x[i] - pv[i]) * damp;\n        pv[i] = x[i]; x[i] += v + (c === 1 ? g : 0) + (c === 0 ? windX * dt * dt : 0);\n      }\n    }\n    const pins = [];\n    for (let k = 0; k < this.n; k++) if (pin[k]) pins.push([k, this.rest(k, new THREE.Vector3())]);\n    const caps = this.caps.map(c => ({ a: c.a.getWorldPosition(new THREE.Vector3()), b: c.b.getWorldPosition(new THREE.Vector3()), r: c.r }));\n    const solve = (L, stiff) => {\n      for (const [ia, ib, R0] of L) {\n        const a = 3 * ia, b = 3 * ib;\n        const dx = x[b] - x[a], dy = x[b+1] - x[a+1], dz = x[b+2] - x[a+2];\n        const d = Math.hypot(dx, dy, dz) || 1e-9, f = (d - R0) / d * stiff;\n        const wa = pin[ia] ? 0 : 1, wb = pin[ib] ? 0 : 1, s = wa + wb;\n        if (!s) continue;\n        x[a] += dx * f * wa / s; x[a+1] += dy * f * wa / s; x[a+2] += dz * f * wa / s;\n        x[b] -= dx * f * wb / s; x[b+1] -= dy * f * wb / s; x[b+2] -= dz * f * wb / s;\n      }\n    };\n    for (let it = 0; it < 10; it++) {\n      for (const [k, w] of pins) { x[3*k] = w.x; x[3*k+1] = w.y; x[3*k+2] = w.z; }\n      solve(this.links, 1.0); solve(this.bends, 0.25);\n      for (let k = 0; k < this.n; k++) {\n        if (pin[k]) continue;\n        _v.set(x[3*k], x[3*k+1], x[3*k+2]);\n        for (const c of caps) {\n          _ab.subVectors(c.b, c.a);\n          const tt = THREE.MathUtils.clamp(_a.subVectors(_v, c.a).dot(_ab) / _ab.lengthSq(), 0, 1);\n          _cp.copy(c.a).addScaledVector(_ab, tt);\n          const d = _v.distanceTo(_cp);\n          if (d < c.r && d > 1e-6) _v.sub(_cp).multiplyScalar(c.r / d).add(_cp);\n        }\n        x[3*k] = _v.x; x[3*k+1] = _v.y; x[3*k+2] = _v.z;\n      }\n    }\n  }\n  write() {\n    const pos = this.display.geometry.attributes.position;\n    pos.array.set(this.x); pos.needsUpdate = true;\n    this.display.geometry.computeVertexNormals();\n  }\n}\n\nconst KEY = new THREE.Vector3(...(SCENE.key || [-0.62, 0.48, 0.62])).normalize();\nconst GRADE = SCENE.grade || { ambient: [0.86, 0.88, 0.96], key: [1.04, 1.00, 0.94], rim: [0.28, 0.25, 0.20] };\nconst KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };\n\nfunction paintMaterial(V, role, map, index, infoRole = role, decal = false, crownY = 1.65) {\n  const Rl = V.roles[role] || { mode: \"flat\", color: \"#ff00ff\" }, P = (V.paint || {})[role];\n  const u = {\n    uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() },\n    uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },\n    uInfo: { value: new THREE.Vector4(roleId(infoRole) / 255, (index % 256) / 255, Math.floor(index / 256) / 255, 1) },\n    uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() },\n    uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) },\n    uGold: { value: hex((V.paint && V.paint.gold && V.paint.gold.base) || \"#c49a45\") },\n    uAmbient: { value: new THREE.Vector3(...GRADE.ambient) },\n    uKeyCol: { value: new THREE.Vector3(...GRADE.key) },\n    uRimCol: { value: new THREE.Vector3(...GRADE.rim) },\n    uGrain: { value: 0.04 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null },\n    uSkinTone: { value: new THREE.Vector3(1, 1, 1) }, uShadeOnly: { value: 0 },\n    uSkinRamp: { value: 0 }, uSkinL: { value: new THREE.Color() }, uSkinS: { value: new THREE.Color() }, uSkinC: { value: new THREE.Color() },\n    uCrownY: { value: crownY },\n    uFootA: { value: new THREE.Vector2(99, 99) }, uFootB: { value: new THREE.Vector2(99, 99) },\n    uFootC: { value: new THREE.Vector2(99, 99) }, uFootD: { value: new THREE.Vector2(99, 99) },\n    tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 },\n    uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 },\n    uMotif: { value: hex((V.paint && V.paint.motif && V.paint.motif.base) || \"#e8e3d5\") }, uLift: { value: 0 }\n  };\n  if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; }\n  else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); }\n  if (P && P.kind === \"world\") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.11; }\n  if (P && P.shade) u.uShadeOnly.value = 1;\n  if (P && P.kind === \"skin\" && P.ramp) {\n    u.uSkinRamp.value = 1; u.uSkinL.value = hex(P.ramp[0]); u.uSkinS.value = hex(P.ramp[1]); u.uSkinC.value = hex(P.ramp[2]);\n  }\n  if (P && P.kind === \"skin\" && P.base) {\n    const c = hex(P.base); u.uSkinTone.value.set(c.r / 0.973, c.g / 0.882, c.b / 0.835);\n  }\n  if (role === \"face\" && map) u.uFaceTex.value = 1;\n  if ((role === \"hair\" || role === \"hair_cap\") && map) u.uAlpha.value = 1;\n  if (role === \"iris\") { u.uKind.value = 7; u.uAlpha.value = 1; }\n  else if (role === \"white\" || role === \"highlight\") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || \"#ffffff\"); }\n  else if (!P && Rl.mode === \"flat\") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === \"line\" ? 2 : 1; }\n  if (role === \"mouth\" && map) u.uKind.value = 10;\n  u.uBand.value = u.uGold.value.clone();\n  const m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: PAINT_VS, fragmentShader: PAINT_FS, side: THREE.DoubleSide,\n                                       extensions: { derivatives: true } });\n  m.defaultAttributeValues = { ...m.defaultAttributeValues, _plate: [0, 0, 0, 0], edge: [0] };\n  return m;\n}\n\nconst loader = new GLTFLoader();\nasync function parseGlb(file) {\n  const j = await (await fetch(file)).json();\n  const bin = Uint8Array.from(atob(j.glb), c => c.charCodeAt(0));\n  return await new Promise((ok, bad) => loader.parse(bin.buffer, \"\", ok, bad));\n}\n\nlet meshIndex = 1;\nconst allMeshes = [];\nconst allCloths = [];\nconst characters = [];\n\nfor (let ci = 0; ci < SCENE.characters.length; ci++) {\n  const def = SCENE.characters[ci], V = def.info;\n  const gltf = await parseGlb(`${def.name}.glb.json`);\n  const turn = new THREE.Group();\n  turn.add(gltf.scene);\n  turn.position.set(...def.place.pos);\n  turn.rotation.y = THREE.MathUtils.degToRad(def.place.yaw);\n  scene.add(turn);\n\n  const meshes = [];\n  gltf.scene.traverse(o => {\n    if (!o.isMesh) return;\n    const m0 = o.material, role = o.userData.role || \"body\", raw = rawTex(m0.map);\n    const matName = o.userData.material || \"\";\n    const isInnerHair = role === \"hair_cap\" || matName.includes(\"HairBack\");\n    const infoRole = isInnerHair ? \"hair_cap\" : (role === \"hair\" && ci > 0 ? \"hair_b\" : role === \"shadow\" ? \"body\" : role);\n    const decal = !!(m0.userData && m0.userData.decal);\n    const mat = paintMaterial(V, role, raw, meshIndex++, infoRole, decal, def.crown_y || 1.68);\n    if (isInnerHair) mat.uniforms.uShadeOnly.value = 1;\n    o.material = mat;\n    o.frustumCulled = false;\n    meshes.push(o);\n    allMeshes.push(o);\n  });\n\n  const mixer = new THREE.AnimationMixer(gltf.scene);\n  const actions = Object.fromEntries(gltf.animations.map(c => [c.name, mixer.clipAction(c)]));\n  const clipName = def.clip || \"idle\";\n  if (actions[clipName]) {\n    actions[clipName].reset();\n    actions[clipName].setEffectiveWeight(1);\n    actions[clipName].play();\n    actions[clipName].time = def.clip_t || 0;\n    mixer.update(0);\n  }\n  scene.updateMatrixWorld(true);\n\n  // Measure live crown height for the halo band after posing\n  const headBone = gltf.scene.getObjectByName(\"J_Bip_C_Head\");\n  if (headBone) {\n    const hp = headBone.getWorldPosition(new THREE.Vector3());\n    const cy = hp.y + 0.145;\n    meshes.forEach(m => { m.material.uniforms.uCrownY.value = cy; });\n  }\n\n  const bone = n => gltf.scene.getObjectByName(n);\n  const world = new THREE.Group();\n  scene.add(world);\n  for (const [cname, info] of Object.entries(V.cloth || {})) {\n    const skinned = meshes.find(m => m.userData.material === cname);\n    if (!skinned) continue;\n    const trims = meshes.filter(m => info.trims.includes(m.userData.material));\n    const caps = V.capsules.filter(c => !info.collide || info.collide.some(k => c.bones[0].includes(k)));\n    const cl = new Cloth(skinned, info.u, info.v, trims, caps, bone, info.closed, info.edges === \"hem\");\n    const PB = (V.paint || {})[info.band || \"gold\"];\n    if (PB && PB.base) cl.display.material.uniforms.uBand.value = hex(PB.base);\n    skinned.visible = false;\n    trims.forEach(t => { t.visible = false; });\n    world.add(cl.display);\n    allMeshes.push(cl.display);\n    allCloths.push({ cl, wind: def.wind || 0 });\n  }\n  characters.push({ def, root: gltf.scene, meshes });\n}\n\n// Settle cloth drapes cleanly\nallCloths.forEach(({ cl }) => cl.reset());\nfor (let s = 0; s < 160; s++) allCloths.forEach(({ cl, wind }) => cl.step(1 / 120, wind));\nallCloths.forEach(({ cl }) => cl.write());\n\n// Load terrain and pass planted foot positions for contact shadows\nconst groundGltf = await parseGlb(\"plains.glb.json\");\nscene.add(groundGltf.scene);\nconst footPts = [];\nfor (const c of characters) {\n  for (const fn of [\"J_Bip_L_Foot\", \"J_Bip_R_Foot\"]) {\n    const b = c.root.getObjectByName(fn);\n    if (b) { const p = b.getWorldPosition(new THREE.Vector3()); footPts.push(new THREE.Vector2(p.x, p.z)); }\n  }\n}\nwhile (footPts.length < 4) footPts.push(new THREE.Vector2(99, 99));\n\nconst V0 = SCENE.characters[0].info;\ngroundGltf.scene.traverse(o => {\n  if (!o.isMesh) return;\n  const role = o.userData.role || \"grass\";\n  const mat = paintMaterial(V0, role, rawTex(o.material.map), meshIndex++, role, false);\n  mat.uniforms.uFootA.value.copy(footPts[0]);\n  mat.uniforms.uFootB.value.copy(footPts[1]);\n  mat.uniforms.uFootC.value.copy(footPts[2]);\n  mat.uniforms.uFootD.value.copy(footPts[3]);\n  o.material = mat;\n  o.frustumCulled = false;\n  allMeshes.push(o);\n});\n\nfunction setupCamera(aspect) {\n  const C = SCENE.camera;\n  const centre = new THREE.Vector3(...C.target);\n  const h = C.height, w = h * aspect;\n  camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2;\n  camera.zoom = 1;\n  camera.updateProjectionMatrix();\n  const a = THREE.MathUtils.degToRad(C.pitch);\n  camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(16));\n  camera.up.set(0, 1, 0);\n  camera.lookAt(centre);\n}\n\nfunction renderFrame(w, h, ss = 1) {\n  const bw = w * ss, bh = h * ss;\n  R.setPixelRatio(1);\n  R.setSize(bw, bh, false);\n  setupCamera(w / h);\n  targetsFor(bw, bh);\n\n  const visible = allMeshes.filter(o => o.visible);\n  visible.forEach(o => {\n    const mu = o.material.uniforms;\n    mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null;\n  });\n  R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera);\n\n  const ppmBuf = bh / (camera.top - camera.bottom);\n  visible.forEach(o => {\n    const mu = o.material.uniforms;\n    mu.uPass.value = 0; mu.uCastOn.value = 1;\n    mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture;\n    mu.uCastRes.value.set(bw, bh); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf;\n  });\n  R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera);\n\n  const u = paint.mat.uniforms;\n  u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture;\n  u.uRes.value.set(bw, bh); u.uNear.value = camera.near; u.uFar.value = camera.far;\n  u.uGap.value = 0.012;\n  u.uSil.value = THREE.MathUtils.clamp(1.75 * ppmBuf * 0.0040, ss, 2.5 * ss);\n  u.uInner.value = Math.max(ss * 0.78, u.uSil.value * 0.56);\n  u.uPpm.value = ppmBuf;\n  R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam);\n}\n\nif (SHOT) {\n  const outW = +(params.get(\"w\") || 1920), outH = +(params.get(\"h\") || 1080), ss = +(params.get(\"ss\") || 2);\n  renderFrame(outW, outH, ss);\n  const cv = document.createElement(\"canvas\");\n  cv.width = outW; cv.height = outH;\n  const ctx = cv.getContext(\"2d\");\n  ctx.imageSmoothingEnabled = true;\n  ctx.imageSmoothingQuality = \"high\";\n  ctx.drawImage(R.domElement, 0, 0, outW, outH);\n  document.getElementById(\"sheetOut\").textContent = cv.toDataURL(\"image/png\");\n  document.title = \"slice ready\";\n} else {\n  const fit = () => renderFrame(window.innerWidth, window.innerHeight, Math.min(2, window.devicePixelRatio || 1));\n  window.addEventListener(\"resize\", fit);\n  fit();\n}\n</script>\n</body>\n</html>\n",
      "Overwrite": true,
      "Path": "~/work/lowmarch/review/slice/index.html"
    }

    result, 1 line

    Created file.