reasoning

The shader and renderer upgrades need examination, specifically review/slice/index.html and tools/patch_lens_flattice.py, to understand the implementation of authored UV face shadow bias. This is indicated through a _PLATE attribute and a conditional check: vPlate.x > 1.5.

  • read_file{"EndLine":350,"Path":"~/work/lowmarch/review/slice/index.html","StartLine":1}

    input

    {
      "EndLine": 350,
      "Path": "~/work/lowmarch/review/slice/index.html",
      "StartLine": 1
    }

    result, 351 lines

    Showing lines 1-350 of 709
    1: <!doctype html>
    2: <html lang="en">
    3: <head>
    4: <meta charset="utf-8">
    5: <meta name="viewport" content="width=device-width, initial-scale=1">
    6: <title>Battle Slice · Lowmarch</title>
    7: <style>
    8:   html, body { margin: 0; height: 100%; background: #1e1d26; color: #ece8e0; font-family: system-ui, sans-serif; overflow: hidden; }
    9:   #stage { position: fixed; inset: 0; display: grid; place-items: center; }
    10:   canvas { max-width: 100%; max-height: 100%; display: block; }
    11:   #sheetOut { display: none; }
    12: </style>
    13: <script type="importmap">
    14: {
    15:   "imports": {
    16:     "three": "./three/build/three.module.js",
    17:     "three/addons/": "./three/examples/jsm/"
    18:   }
    19: }
    20: </script>
    21: </head>
    22: <body>
    23: <div id="stage"></div>
    24: <pre id="sheetOut"></pre>
    25: <script type="module">
    26: import * as THREE from "three";
    27: import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
    28: 
    29: const params = new URLSearchParams(location.search);
    30: const SHOT = params.has("shot");
    31: const SCENE = await (await fetch("scene.json")).json();
    32: 
    33: const stageEl = document.getElementById("stage");
    34: const R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: true });
    35: R.outputColorSpace = THREE.LinearSRGBColorSpace;
    36: R.setClearColor(0x000000, 0);
    37: stageEl.appendChild(R.domElement);
    38: 
    39: const hex = h => {
    40:   const n = parseInt(h.slice(1), 16);
    41:   return new THREE.Color().setRGB((n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255, THREE.LinearSRGBColorSpace);
    42: };
    43: const rawTex = t => { if (!t) return null; const c = t.clone(); c.colorSpace = THREE.NoColorSpace; c.needsUpdate = true; return c; };
    44: const white = (() => { const t = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1, THREE.RGBAFormat); t.needsUpdate = true; return t; })();
    45: 
    46: const 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 };
    47: const roleId = r => R_ID[r] || 10;
    48: 
    49: const scene = new THREE.Scene();
    50: const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 40);
    51: 
    52: const SKIN_HEAD = `#include <common>
    53:   #include <skinning_pars_vertex>`;
    54: const SKIN_BODY = `#include <beginnormal_vertex>
    55:     #include <skinbase_vertex>
    56:     #include <skinnormal_vertex>
    57:     #include <begin_vertex>
    58:     #include <skinning_vertex>`;
    59: 
    60: const PAINT_VS = `${SKIN_HEAD}
    61:   attribute float edge; attribute vec4 _plate; uniform float uLift;
    62:   varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying vec3 vWPos;
    63:   varying float vEdge; varying vec4 vPlate;
    64:   void main() {
    65:     ${SKIN_BODY}
    66:     vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate;
    67:     vec4 wp = modelMatrix * vec4(transformed, 1.0);
    68:     vWPos = wp.xyz;
    69:     vec4 mv = modelViewMatrix * vec4(transformed, 1.0); vView = -mv.xyz;
    70:     mv.z += uLift;
    71:     gl_Position = projectionMatrix * mv;
    72:   }`;
    73: 
    74: const HSV = `
    75:   vec3 rgb2hsv(vec3 c) {
    76:     vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    77:     vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    78:     vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
    79:     float d = q.x - min(q.w, q.y);
    80:     return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 1e-10)), d / (q.x + 1e-10), q.x);
    81:   }
    82:   vec3 hsv2rgb(vec3 c) {
    83:     vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    84:     vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    85:     return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
    86:   }`;
    87: 
    88: const PAINT_FS = `
    89:   uniform int uKind; uniform vec3 uBase; uniform vec3 uKey; uniform sampler2D uMap; uniform int uAlpha;
    90:   uniform int uPass; uniform vec4 uInfo; uniform vec3 uEye[3]; uniform vec3 uFlat; uniform vec3 uSkinRef;
    91:   uniform vec3 uGold; uniform vec3 uAmbient; uniform vec3 uKeyCol; uniform vec3 uRimCol; uniform float uGrain;
    92:   uniform int uFaceTex; uniform int uDecal; uniform vec3 uMotif; uniform vec3 uBand; uniform vec3 uSkinTone; uniform int uShadeOnly;
    93:   uniform int uSkinRamp; uniform vec3 uSkinL; uniform vec3 uSkinS; uniform vec3 uSkinC;
    94:   uniform float uCrownY;
    95:   uniform vec2 uFootA; uniform vec2 uFootB; uniform vec2 uFootC; uniform vec2 uFootD;
    96:   uniform sampler2D tCastInfo; uniform sampler2D tCastDepth; uniform vec2 uCastRes; uniform int uCastOn;
    97:   uniform float uCastNear; uniform float uCastFar; uniform float uCastPpm;
    98: 
    99:   float castShadow(int selfRole) {
    100:     vec2 uv = gl_FragCoord.xy / uCastRes, px = 1.0 / uCastRes;
    101:     float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);
    102:     float sxy = length(uKey.xy);
    103:     if (sxy < 0.05) return 0.0;
    104:     vec2 dir = uKey.xy / sxy;
    105:     float lz = uKey.z / sxy;
    106:     int steps = selfRole == 1 ? 8 : 15;
    107:     float stepM = selfRole == 1 ? 0.0026 : 0.0032;
    108:     for (int s = 1; s <= 15; s++) {
    109:       if (s > steps) break;
    110:       float dm = float(s) * stepM;
    111:       vec2 q = uv + dir * dm * uCastPpm * px;
    112:       vec4 ni = texture2D(tCastInfo, q);
    113:       if (ni.a < 0.5) continue;
    114:       int r = int(ni.r * 255.0 + 0.5);
    115:       if (selfRole == 1) {
    116:         if (r != 3 && r != 11 && r != 12) continue;
    117:       } else {
    118:         if (r != 1 && r != 3 && r != 11 && r != 12) continue;
    119:       }
    120:       float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);
    121:       float zr = z0 - lz * dm;
    122:       if (zq < zr - 0.004 && zq > zr - 0.22) return 1.0;
    123:     }
    124:     return 0.0;
    125:   }
    126: 
    127:   varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying vec3 vWPos;
    128:   varying float vEdge; varying vec4 vPlate;
    129:   ${HSV}
    130:   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)); }
    131:   float vnoise(vec3 x) {
    132:     vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);
    133:     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),
    134:                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);
    135:   }
    136:   float toward(float h, float target, float amt) { float d = target - h; d -= floor(d + 0.5); return fract(h + clamp(d, -amt, amt)); }
    137:   vec3 tone(vec3 base, float hue, float amt, float sMul, float vMul) {
    138:     vec3 h = rgb2hsv(base);
    139:     return hsv2rgb(vec3(toward(h.x, hue, amt), clamp(h.y * sMul, 0.0, 1.0), clamp(h.z * vMul, 0.0, 1.0)));
    140:   }
    141:   float st(float x, float t) { return smoothstep(t - 0.025, t + 0.025, x); }
    142: 
    143:   vec3 metal(bool gold, vec3 base, vec3 n, vec3 v, float lit, float hgt) {
    144:     vec3 r = reflect(-v, n);
    145:     vec3 s0, s1, s2, s3;
    146:     if (!gold) {
    147:       s0 = tone(base, 0.65, 0.09, 1.9, 0.40);
    148:       s1 = tone(base, 0.65, 0.05, 1.35, 0.72);
    149:       s2 = tone(base, 0.12, 0.0, 0.82, 0.94);
    150:       s3 = vec3(0.98, 0.97, 0.94);
    151:     } else {
    152:       s0 = vec3(0.32, 0.21, 0.16);
    153:       s1 = tone(base, 0.11, 0.03, 1.08, 0.72);
    154:       s2 = base;
    155:       s3 = tone(base, 0.13, 0.03, 0.50, 1.48);
    156:     }
    157:     // Clean painted cel metal: vertical sky-earth reflection + key light cel step + crisp specular
    158:     float sky = smoothstep(-0.45, 0.45, r.y);
    159:     float grad = hgt >= 0.0 ? clamp(sky * 0.45 + hgt * 0.65 - 0.06, 0.0, 1.0)
    160:                             : clamp(sky * 0.65 + n.y * 0.28 + 0.08, 0.0, 1.0);
    161:     vec3 body = mix(s1, s2, grad);
    162:     vec3 shaded = mix(s0, s1 * 0.94, grad * 0.75);
    163:     vec3 col = mix(shaded, body, st(lit, 0.42));
    164:     float hl = dot(n, normalize(uKey + v));
    165:     float specMask = hgt >= 0.0 ? smoothstep(0.25, 0.65, hgt) : 1.0;
    166:     col = mix(col, mix(s2, s3, 0.72), st(hl, 0.91) * specMask * st(lit, 0.50));
    167:     return col;
    168:   }
    169: 
    170:   void main() {
    171:     vec4 tex = texture2D(uMap, vUv);
    172:     if (uAlpha == 1 && tex.a < 0.5) discard;
    173:     if (uAlpha == 2 && (tex.a < 0.5 || dot(tex.rgb, vec3(1.0 / 3.0)) >= 0.42)) discard;
    174:     if (uPass == 1) { gl_FragColor = uInfo; return; }
    175: 
    176:     bool back = !gl_FrontFacing;
    177:     vec3 n = normalize(vN); if (back) n = -n;
    178:     vec3 v = normalize(vView);
    179:     float lit = dot(n, uKey) * 0.5 + 0.5;
    180:     int selfRole = int(uInfo.x * 255.0 + 0.5);
    181: 
    182:     if (uShadeOnly == 1) {
    183:       lit = 0.12;
    184:     } else if (uCastOn == 1 && uKind == 1 && (selfRole == 1 || selfRole == 2)) {
    185:       if (castShadow(selfRole) > 0.5) lit = min(lit, 0.34);
    186:     }
    187: 
    188:     float g1 = vnoise(vObj * 40.0), g2 = vnoise(vObj * 150.0);
    189:     vec3 col;
    190:     if (uKind == 0 || uKind == 5 || uKind == 6) {
    191:       vec3 hb = rgb2hsv(uBase);
    192:       bool cool = hb.x > 0.42 && hb.x < 0.86;
    193:       float sh = uKind == 5 ? 0.93 : (cool ? 0.68 : 0.96);
    194:       float li = cool ? 0.55 : 0.12;
    195:       vec3 c0 = tone(uBase, sh, 0.08, 1.12, 0.42), c1 = tone(uBase, sh, 0.05, 1.08, 0.66);
    196:       vec3 c3 = tone(uBase, li, 0.03, 0.82, 1.18);
    197:       float l = lit + (g1 - 0.5) * uGrain - (uKind == 6 ? 0.20 : 0.0);
    198:       if (uKind == 6) {
    199:         // Contact shadow on ground beneath planted feet
    200:         vec2 xz = vWPos.xz;
    201:         float da = length((xz - uFootA) * vec2(1.0, 1.35));
    202:         float db = length((xz - uFootB) * vec2(1.0, 1.35));
    203:         float dc = length((xz - uFootC) * vec2(1.0, 1.35));
    204:         float dd = length((xz - uFootD) * vec2(1.0, 1.35));
    205:         float dmin = min(min(da, db), min(dc, dd));
    206:         float contact = 1.0 - smoothstep(0.08, 0.30, dmin);
    207:         l -= 0.36 * contact;
    208:       }
    209:       col = mix(c0, c1, st(l, 0.32)); col = mix(col, uBase, st(l, 0.50)); col = mix(col, c3, st(l, 0.90));
    210:       if (uKind == 5) col *= 0.965 + 0.07 * vnoise(vObj * 22.0);
    211:     } else if (uKind == 1) {
    212:       // Skin: genuine 3/4 shadow plane (threshold 0.50 instead of 0.38) + warm hue-shifted ramp
    213:       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);
    214:       if (uSkinRamp == 1) { sL = uSkinL; sS = uSkinS; sC = uSkinC; }
    215:       col = mix(sC, sS, st(lit, 0.24)); col = mix(col, sL, st(lit, 0.50));
    216:       if (uFaceTex == 1) col *= clamp(tex.rgb / uSkinRef, 0.58, 1.04);
    217:       if (uFaceTex == 1 && vUv.x > 0.37 && vUv.x < 0.63 && vUv.y > 0.68 && vUv.y < 0.84) {
    218:         float d = 0.0, sl = dot(uSkinRef, vec3(1.0 / 3.0));
    219:         for (int k = -2; k <= 2; k++) for (int j = -2; j <= 2; j++) {
    220:           vec3 t = texture2D(uMap, vUv + vec2(float(j) * 1.1, float(k) * 0.9) / 512.0).rgb;
    221:           d = max(d, 1.0 - dot(t, vec3(1.0 / 3.0)) / sl);
    222:         }
    223:         float taper = 1.0 - 0.45 * smoothstep(0.038, 0.068, abs(vUv.x - 0.5));
    224:         vec3 lipInk = mix(sC * 0.68, vec3(0.32, 0.14, 0.15), 0.55);
    225:         col = mix(col, lipInk, smoothstep(0.09, 0.20, d) * taper);
    226:       }
    227:       if (uSkinRamp == 0) col *= uSkinTone;
    228:     } else if (uKind == 2) {
    229:       // Calm 2-tone cel hair + dark inner backfaces + one restrained crown halo band
    230:       float strand = dot(tex.rgb, vec3(1.0 / 3.0));
    231:       vec3 c0 = tone(uBase, 0.70, 0.06, 1.12, 0.38);
    232:       vec3 c1 = tone(uBase, 0.70, 0.04, 1.06, 0.66);
    233:       vec3 c2 = tone(uBase, 0.12, 0.02, 0.78, 1.24);
    234:       if (back || uShadeOnly == 1 || selfRole == 12) {
    235:         col = c0;
    236:       } else {
    237:         float l = lit + (strand - 0.58) * 0.035;
    238:         col = mix(c0, c1, st(l, 0.28));
    239:         col = mix(col, uBase, st(l, 0.48));
    240:         // Clean horizontal anime halo band around upper crown locks
    241:         float dy = (vWPos.y - uCrownY);
    242:         float bandMask = exp(-pow(dy / 0.028, 2.0)) * smoothstep(0.54, 0.68, lit);
    243:         float sp = dot(n, normalize(uKey + v)) + (strand - 0.58) * 0.04;
    244:         float halo = bandMask * smoothstep(0.76, 0.86, sp);
    245:         col = mix(col, c2, 0.62 * halo);
    246:       }
    247:     } else if (uKind == 3 || uKind == 4) {
    248:       bool plate = vPlate.x > 0.5;
    249:       float e = vPlate.y, w = vPlate.z;
    250:       bool gilt = uKind == 4 || (plate && w > 0.0 && e < w);
    251:       col = metal(gilt, gilt && uKind == 3 ? uGold : uBase, n, v, lit, plate ? vPlate.w : -1.0);
    252:       if (plate && w > 0.0) {
    253:         float aa = fwidth(e) * 1.2 + 1e-5;
    254:         float l1 = 1.0 - smoothstep(0.0010, 0.0010 + aa, abs(e - (w + 0.0050)));
    255:         float l2 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - w));
    256:         col = mix(col, col * 0.42, max(l1, l2 * 0.8));
    257:       }
    258:     } else if (uKind == 7) {
    259:       float l = dot(tex.rgb, vec3(1.0 / 3.0));
    260:       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));
    261:     } else if (uKind == 8) { col = tex.rgb; }
    262:     else if (uKind == 10) {
    263:       float lum = dot(tex.rgb, vec3(1.0 / 3.0));
    264:       col = mix(vec3(0.36, 0.11, 0.14), vec3(0.78, 0.38, 0.42), smoothstep(0.53, 0.58, tex.g));
    265:       col = mix(col, vec3(0.98, 0.96, 0.95), smoothstep(0.80, 0.86, lum));
    266:     } else { col = uFlat; }
    267: 
    268:     if (vPlate.x > 0.5 && vPlate.z > 0.0 && uKind != 3 && uKind != 4) {
    269:       float e = vPlate.y, w = vPlate.z, aa = fwidth(e) * 1.2 + 1e-5;
    270:       float band = 1.0 - smoothstep(w - aa, w, e);
    271:       float l1 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - (w + 0.0040)));
    272:       col = mix(col, metal(true, uGold, n, v, lit, -1.0), max(band, l1 * 0.9));
    273:     }
    274:     if (uDecal == 1) {
    275:       vec3 dm = tex.rgb;
    276:       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);
    277:       if (au > 0.0) col = mix(col, metal(true, uGold, n, v, lit, -1.0), au);
    278:       if (pm > 0.0) {
    279:         vec3 pc = mix(tone(uMotif, 0.70, 0.05, 1.10, 0.62), uMotif, st(lit, 0.42));
    280:         col = mix(col, mix(pc, tone(uMotif, 0.56, 0.03, 0.8, 1.25), st(lit, 0.92)), pm);
    281:       }
    282:       if (gm > 0.0) col = mix(col, col * 0.30, gm);
    283:     }
    284:     if (vEdge > 0.5) {
    285:       vec3 gd = tone(uBand, 0.20, 0.03, 1.0, 0.72);
    286:       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));
    287:     }
    288:     if (uKind <= 6) {
    289:       vec3 grade = mix(uAmbient, uKeyCol, st(lit, 0.52));
    290:       col *= uKind == 1 && uSkinRamp == 1 ? mix(vec3(1.0), grade, 0.25) : grade;
    291:       float fr = pow(1.0 - max(dot(n, v), 0.0), 4.2);
    292:       float rimBack = clamp(dot(n, normalize(vec3(0.55, 0.45, -0.35))), 0.0, 1.0);
    293:       col += uRimCol * fr * smoothstep(0.12, 0.55, rimBack) * (uKind == 1 ? 0.45 : 0.85);
    294:       if (uKind != 1 && uKind != 2) col *= 1.0 + (g2 - 0.5) * 0.05;
    295:     }
    296:     gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
    297:   }`;
    298: 
    299: const PAINT_COMP = `
    300:   uniform sampler2D tColor; uniform sampler2D tInfo; uniform sampler2D tDepth; uniform vec2 uRes;
    301:   uniform float uNear; uniform float uFar; uniform float uGap; uniform float uSil; uniform float uInner; uniform float uPpm;
    302:   ${HSV}
    303:   float z(vec2 p) { return uNear + texture2D(tDepth, p).x * (uFar - uNear); }
    304:   int rid(vec4 i) { return int(i.r * 255.0 + 0.5); }
    305:   float pid(vec4 i) { return floor(i.g * 255.0 + 0.5) + floor(i.b * 255.0 + 0.5) * 256.0; }
    306:   vec3 ink(vec3 c) { vec3 h = rgb2hsv(c); return hsv2rgb(vec3(h.x, clamp(h.y, 0.20, 0.45), 0.18)); }
    307: 
    308:   vec3 backdrop(vec2 uv) {
    309:     // Painted dusk-parchment SRPG stage backdrop (replaces pitch-black #0e0d12 void)
    310:     vec3 skyTop = vec3(0.22, 0.27, 0.36);
    311:     vec3 skyMid = vec3(0.46, 0.47, 0.52);
    312:     vec3 horizon = vec3(0.76, 0.69, 0.60);
    313:     vec3 lowMist = vec3(0.58, 0.54, 0.50);
    314:     vec3 underEarth = vec3(0.15, 0.14, 0.18);
    315: 
    316:     float y = uv.y;
    317:     vec3 bg = mix(horizon, skyMid, smoothstep(0.22, 0.62, y));
    318:     bg = mix(bg, skyTop, smoothstep(0.58, 0.98, y));
    319: 
    320:     // Distant painted ridge line above the turf horizon
    321:     float ridge1 = 0.215 + 0.024 * sin(uv.x * 5.2 + 0.8) + 0.012 * sin(uv.x * 13.0 + 2.1);
    322:     float ridge2 = 0.185 + 0.016 * sin(uv.x * 7.8 + 3.4) + 0.008 * cos(uv.x * 19.0);
    323:     vec3 rCol1 = vec3(0.38, 0.40, 0.46);
    324:     vec3 rCol2 = vec3(0.30, 0.33, 0.38);
    325:     bg = mix(bg, mix(rCol1, horizon, 0.38), 1.0 - smoothstep(ridge1 - 0.004, ridge1 + 0.004, y));
    326:     bg = mix(bg, mix(rCol2, lowMist, 0.25), 1.0 - smoothstep(ridge2 - 0.003, ridge2 + 0.003, y));
    327:     bg = mix(underEarth, bg, smoothstep(0.05, 0.13, y));
    328:     // Subtle vignette at extreme left/right corners
    329:     float vig = smoothstep(0.0, 0.35, 1.0 - length((uv - vec2(0.5, 0.52)) * vec2(0.85, 0.95)));
    330:     return bg * mix(0.86, 1.0, vig);
    331:   }
    332: 
    333:   void main() {
    334:     vec2 uv = gl_FragCoord.xy / uRes, px = 1.0 / uRes;
    335:     vec4 inf = texture2D(tInfo, uv);
    336:     if (inf.a < 0.5) {
    337:       vec4 best = vec4(0.0); vec2 bq = uv;
    338:       for (int k = 0; k < 12; k++) {
    339:         float a = float(k) * 0.5236;
    340:         for (int s = 1; s <= 2; s++) {
    341:           vec2 q = uv + vec2(cos(a), sin(a)) * uSil * float(s) * 0.5 * px;
    342:           vec4 ni = texture2D(tInfo, q);
    343:           if (ni.a > 0.5) { best = ni; bq = q; }
    344:         }
    345:       }
    346:       if (best.a > 0.5) {
    347:         int r = rid(best);
    348:         if (r >= 4 && r <= 7) { gl_FragColor = vec4(backdrop(uv), 1.0); return; }
    349:         gl_FragColor = vec4(ink(texture2D(tColor, bq).rgb), 1.0); return;
    350:       }
  • read_file{"EndLine":250,"Path":"~/work/lowmarch/tools/patch_lens_flattice.py","StartLine":1}

    input

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

    result, 116 lines

    Showing lines 1-115 of 115
    1: """Patch a scratch copy of the built armory page: tiles may take a close-up lens (`lens`, mm on a 36 mm wide frame)
    2: and Flattice (`flat`, 0..1), drawn by the page's own painted renderer.
    3: 
    4: Flattice is DillonGoo's add-on done in the vertex shader: every vertex is squashed toward a plane through the head
    5: bone's head, along the line from there to the camera, by `flat` times a weight that is 1 above the chin and fades to
    6: 0 over 5 cm below it (the add-on's MOD-Flattice group with the cursor at the chin). Normals are left as they were, as
    7: the Yin rig shades from normals stored before its lattice. Under a lens the outline pass reads perspective depth.
    8: At flat 1 every layer of the head lands on one plane and a depth buffer can't order them (hair, skin and mouth
    9: interior fight); 0.85 keeps enough depth, and the outline pass's depth step shrinks with the squash.
    10: 
    11:   python3 patch_lens_flattice.py SITE_DIR
    12: """
    13: import sys
    14: 
    15: path = sys.argv[1] + "/index.html"
    16: s = open(path, encoding="utf-8").read()
    17: 
    18: 
    19: def rep(old, new):
    20:     global s
    21:     assert s.count(old) == 1, old[:80]
    22:     s = s.replace(old, new)
    23: 
    24: 
    25: # vertex shader: the squash, in view space, after skinning
    26: rep("""  varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying float vEdge; varying vec4 vPlate;
    27:   void main() {
    28:     ${SKIN_BODY}
    29:     vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate;
    30:     vec4 mv = modelViewMatrix * vec4(transformed, 1.0); vView = -mv.xyz;""",
    31:     """  varying vec3 vN; varying vec2 vUv; varying vec3 vView; varying vec3 vObj; varying float vEdge; varying vec4 vPlate;
    32:   uniform float uFlattice; uniform float uFlChin; uniform float uFlFall; uniform vec3 uFlPivot;
    33:   void main() {
    34:     ${SKIN_BODY}
    35:     vN = normalize(normalMatrix * objectNormal); vUv = uv; vObj = position; vEdge = edge; vPlate = _plate;
    36:     vec4 mv = modelViewMatrix * vec4(transformed, 1.0);
    37:     if (uFlattice > 0.0) {                                   // Flattice: squash toward the pivot's plane, along pivot-to-camera
    38:       float w = clamp((position.y - (uFlChin - uFlFall)) / uFlFall, 0.0, 1.0);
    39:       vec3 u = normalize(-uFlPivot);
    40:       mv.xyz -= u * dot(mv.xyz - uFlPivot, u) * w * uFlattice;
    41:     }
    42:     vView = -mv.xyz;""")
    43: rep("""    uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },""",
    44:     """    uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },
    45:     uFlattice: { value: 0 }, uFlChin: { value: 0 }, uFlFall: { value: 0.05 }, uFlPivot: { value: new THREE.Vector3() },""")
    46: # outline pass: [redacted: secret] depth under a lens
    47: rep("""  float z(vec2 p) { return uNear + texture2D(tDepth, p).x * (uFar - uNear); }""",
    48:     """  uniform float uPersp;
    49:   float z(vec2 p) { float d = texture2D(tDepth, p).x;
    50:     return uPersp > 0.5 ? uNear * uFar / (uFar - d * (uFar - uNear)) : uNear + d * (uFar - uNear); }""")
    51: rep("""  uNear: { value: 0.1 }, uFar: { value: 40 },""", """  uNear: { value: 0.1 }, uFar: { value: 40 }, uPersp: { value: 0 },""")
    52: # tiles: after the page frames its orthographic view, a lens tile moves in and switches to a perspective projection
    53: rep("""      frameAt(centre, h, tw_, th_, pitch);
    54:       render();""",
    55:     """      frameAt(centre, h, tw_, th_, pitch);
    56:       lensAndFlat(tile, centre, h, tw_, th_, pitch);
    57:       render();""")
    58: rep("""async function runSheet(kind) {""",
    59:     """function lensAndFlat(tile, centre, h, tw, th, pitch) {
    60:   const pu = paint.mat.uniforms;
    61:   pu.uPersp.value = 0; camera.near = 0.1; camera.far = 40;
    62:   if (pu.uGap.userData === undefined) pu.uGap.userData = pu.uGap.value;
    63:   pu.uGap.value = pu.uGap.userData * (1 - (tile.flat || 0));   // depth steps shrink with the squash; so does the line test
    64:   const chr = active()[0];
    65:   if (tile.lens) {
    66:     const w = h * tw / th, d = w * tile.lens / 36, a = THREE.MathUtils.degToRad(pitch), n = 0.01;
    67:     camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(d));
    68:     camera.lookAt(centre); camera.updateMatrixWorld(true);
    69:     camera.near = n; camera.far = 40;
    70:     camera.projectionMatrix.makePerspective(-w / 2 * n / d, w / 2 * n / d, h / 2 * n / d, -h / 2 * n / d, n, 40);
    71:     camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
    72:     pu.uPersp.value = 1;
    73:   }
    74:   const face = chr.meshes.find(o => /Face_00_SKIN/.test(o.name + " " + (o.userData.material || "")));
    75:   face.geometry.computeBoundingBox();
    76:   let pivot = chr.root.getObjectByName("J_Bip_C_Head").getWorldPosition(new THREE.Vector3());
    77:   if (tile.pivot === "chin") {                      // the chin's front: the face's lowest points, the most forward of them
    78:     const P = face.geometry.attributes.position, low = face.geometry.boundingBox.min.y, v = new THREE.Vector3();
    79:     let best = null;
    80:     for (let i = 0; i < P.count; i++) {
    81:       v.fromBufferAttribute(P, i);
    82:       if (v.y < low + 0.006 && (!best || v.z > best.z)) best = v.clone();
    83:     }
    84:     pivot = best.applyMatrix4(face.matrixWorld);
    85:   }
    86:   pivot.applyMatrix4(camera.matrixWorldInverse);
    87:   for (const o of chr.meshes) {
    88:     const mu = o.material.uniforms;
    89:     if (!mu || !mu.uFlattice) continue;
    90:     mu.uFlattice.value = tile.flat || 0;
    91:     mu.uFlChin.value = tile.whole ? -100 : face.geometry.boundingBox.min.y + 0.01;   // whole: the body too
    92:     mu.uFlFall.value = 0.05; mu.uFlPivot.value.copy(pivot);
    93:   }
    94: }
    95: async function runSheet(kind) {""")
    96: # the rows: the armory camera, then a 24 mm close-up without and with Flattice
    97: i = s.index("const ARMORY_ROWS = [")
    98: j = s.index("const DUEL_YAWS")
    99: s = s[:i] + """const ARMORY_ROWS = [
    100:   { label: "Armory camera", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 4,
    101:       focus: "J_Bip_C_Head", dy: 0.05, size: 0.40, label: `${y}°` })) },
    102:   { label: "Close-up lens 24 mm, Flattice off", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({ clip: "ref", t: 0,
    103:       yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.05, size: 0.40, lens: 24, flat: 0, label: `${y}°` })) },
    104:   { label: "Close-up lens 24 mm, Flattice on (0.85: a little depth kept)", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({ clip: "ref", t: 0,
    105:       yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.05, size: 0.40, lens: 24, flat: 0.85, label: `${y}°` })) },
    106:   { label: "Close-up lens 24 mm, Flattice on, pivot at the chin", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({
    107:       clip: "ref", t: 0, yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.05, size: 0.40, lens: 24, flat: 0.85,
    108:       pivot: "chin", label: `${y}°` })) },
    109:   { label: "Close-up lens 24 mm, Flattice on the whole body", tw: 340, th: 340, tiles: [0, 35, 60, 90].map(y => ({
    110:       clip: "ref", t: 0, yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.05, size: 0.40, lens: 24, flat: 0.85,
    111:       whole: true, label: `${y}°` })) },
    112: ];
    113: """ + s[j:]
    114: open(path, "w", encoding="utf-8").write(s)
    115: print("patched", path)
  • read_file{"EndLine":709,"Path":"~/work/lowmarch/review/slice/index.html","StartLine":351}

    input

    {
      "EndLine": 709,
      "Path": "~/work/lowmarch/review/slice/index.html",
      "StartLine": 351
    }

    result, 360 lines

    Showing lines 351-709 of 709
    351:       gl_FragColor = vec4(backdrop(uv), 1.0); return;
    352:     }
    353: 
    354:     vec3 col = texture2D(tColor, uv).rgb; int r0 = rid(inf); float p0 = pid(inf); float z0 = z(uv);
    355:     bool feature = r0 >= 4 && r0 <= 9;
    356:     if (!feature) {
    357:       for (int k = 0; k < 4; k++) {
    358:         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)));
    359:         vec2 q = uv + d * px * uInner;
    360:         vec4 ni = texture2D(tInfo, q);
    361:         if (ni.a > 0.5 && z(q) > z0 + uGap && pid(ni) != p0) { col = ink(col); break; }
    362:       }
    363:       float acc = 0.0, rad = uSil * 2.8;
    364:       for (int k = 0; k < 8; k++) {
    365:         float a = float(k) * 0.785398 + 0.39;
    366:         vec2 q = uv + vec2(cos(a), sin(a)) * rad * px;
    367:         vec4 ni = texture2D(tInfo, q);
    368:         if (ni.a > 0.5) acc += clamp((z0 - z(q)) / 0.05, 0.0, 1.0);
    369:       }
    370:       col *= 1.0 - 0.18 * acc / 8.0;
    371:     }
    372:     gl_FragColor = vec4(col, 1.0);
    373:   }`;
    374: 
    375: const compCam = new THREE.Camera();
    376: function compPass(fs, uniforms) {
    377:   const mat = new THREE.ShaderMaterial({
    378:     uniforms,
    379:     vertexShader: `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`,
    380:     fragmentShader: fs, depthTest: false, depthWrite: false
    381:   });
    382:   const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);
    383:   const sc = new THREE.Scene(); sc.add(quad);
    384:   return { scene: sc, mat };
    385: }
    386: const paint = compPass(PAINT_COMP, {
    387:   tColor: { value: null }, tInfo: { value: null }, tDepth: { value: null },
    388:   uRes: { value: new THREE.Vector2() }, uNear: { value: 0.1 }, uFar: { value: 40 },
    389:   uGap: { value: 0.012 }, uSil: { value: 2.0 }, uInner: { value: 1.0 }, uPpm: { value: 1.0 }
    390: });
    391: 
    392: const targets = { rt: null, rtInfo: null, key: "" };
    393: function targetsFor(w, h) {
    394:   const key = `${w}x${h}`;
    395:   if (targets.key === key) return;
    396:   [targets.rt, targets.rtInfo].forEach(t => t && t.dispose());
    397:   const o = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter };
    398:   targets.rt = new THREE.WebGLRenderTarget(w, h, o);
    399:   targets.rtInfo = new THREE.WebGLRenderTarget(w, h, { ...o, depthTexture: new THREE.DepthTexture(w, h) });
    400:   targets.key = key;
    401: }
    402: 
    403: const _v = new THREE.Vector3(), _a = new THREE.Vector3(), _ab = new THREE.Vector3(), _cp = new THREE.Vector3();
    404: class Cloth {
    405:   constructor(skinned, U, V, trims, capsules, bone, closed = false, hemOnly = false) {
    406:     this.skinned = skinned; this.U = U; this.V = V; this.trims = trims; this.closed = closed;
    407:     this.n = skinned.geometry.attributes.position.count;
    408:     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);
    409:     this.x = new Float32Array(this.n * 3); this.prev = new Float32Array(this.n * 3);
    410:     const idx = (i, j) => i * V + j, links = [], bends = [], edge = new Float32Array(this.n);
    411:     for (let i = 0; i < U; i++) for (let j = 0; j < V; j++) {
    412:       if (i + 1 < U || closed) links.push([idx(i, j), idx((i + 1) % U, j)]);
    413:       if (j + 1 < V) links.push([idx(i, j), idx(i, j + 1)]);
    414:       if (i + 2 < U || closed) bends.push([idx(i, j), idx((i + 2) % U, j)]);
    415:       if (j + 2 < V) bends.push([idx(i, j), idx(i, j + 2)]);
    416:       edge[idx(i, j)] = ((j === 0 && !hemOnly) || j === V - 1 || (!closed && trims.length > 1 && (i === 0 || i === U - 1))) ? 1 : 0;
    417:     }
    418:     const r = skinned.geometry.attributes.position.array;
    419:     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]);
    420:     this.links = links.map(l => [l[0], l[1], len(l)]);
    421:     this.bends = bends.map(l => [l[0], l[1], len(l)]);
    422:     this.pinned = new Uint8Array(this.n); for (let i = 0; i < U; i++) this.pinned[idx(i, 0)] = 1;
    423:     const g = new THREE.BufferGeometry();
    424:     g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3).setUsage(THREE.DynamicDrawUsage));
    425:     g.setAttribute("normal", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3));
    426:     g.setAttribute("uv", skinned.geometry.attributes.uv || new THREE.BufferAttribute(new Float32Array(this.n * 2), 2));
    427:     g.setAttribute("edge", new THREE.BufferAttribute(edge, 1));
    428:     g.setIndex(skinned.geometry.index);
    429:     this.display = new THREE.Mesh(g, skinned.material);
    430:     this.display.userData = { ...skinned.userData, cloth: true };
    431:     this.display.frustumCulled = false;
    432:   }
    433:   rest(k, out) { this.skinned.getVertexPosition(k, out); return out.applyMatrix4(this.skinned.matrixWorld); }
    434:   reset() {
    435:     for (let k = 0; k < this.n; k++) {
    436:       this.rest(k, _v);
    437:       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;
    438:     }
    439:   }
    440:   step(dt, windX = 0) {
    441:     const x = this.x, pv = this.prev, pin = this.pinned;
    442:     const g = -9.8 * dt * dt, damp = 0.982;
    443:     for (let k = 0; k < this.n; k++) {
    444:       if (pin[k]) continue;
    445:       for (let c = 0; c < 3; c++) {
    446:         const i = 3*k + c, v = (x[i] - pv[i]) * damp;
    447:         pv[i] = x[i]; x[i] += v + (c === 1 ? g : 0) + (c === 0 ? windX * dt * dt : 0);
    448:       }
    449:     }
    450:     const pins = [];
    451:     for (let k = 0; k < this.n; k++) if (pin[k]) pins.push([k, this.rest(k, new THREE.Vector3())]);
    452:     const caps = this.caps.map(c => ({ a: c.a.getWorldPosition(new THREE.Vector3()), b: c.b.getWorldPosition(new THREE.Vector3()), r: c.r }));
    453:     const solve = (L, stiff) => {
    454:       for (const [ia, ib, R0] of L) {
    455:         const a = 3 * ia, b = 3 * ib;
    456:         const dx = x[b] - x[a], dy = x[b+1] - x[a+1], dz = x[b+2] - x[a+2];
    457:         const d = Math.hypot(dx, dy, dz) || 1e-9, f = (d - R0) / d * stiff;
    458:         const wa = pin[ia] ? 0 : 1, wb = pin[ib] ? 0 : 1, s = wa + wb;
    459:         if (!s) continue;
    460:         x[a] += dx * f * wa / s; x[a+1] += dy * f * wa / s; x[a+2] += dz * f * wa / s;
    461:         x[b] -= dx * f * wb / s; x[b+1] -= dy * f * wb / s; x[b+2] -= dz * f * wb / s;
    462:       }
    463:     };
    464:     for (let it = 0; it < 10; it++) {
    465:       for (const [k, w] of pins) { x[3*k] = w.x; x[3*k+1] = w.y; x[3*k+2] = w.z; }
    466:       solve(this.links, 1.0); solve(this.bends, 0.25);
    467:       for (let k = 0; k < this.n; k++) {
    468:         if (pin[k]) continue;
    469:         _v.set(x[3*k], x[3*k+1], x[3*k+2]);
    470:         for (const c of caps) {
    471:           _ab.subVectors(c.b, c.a);
    472:           const tt = THREE.MathUtils.clamp(_a.subVectors(_v, c.a).dot(_ab) / _ab.lengthSq(), 0, 1);
    473:           _cp.copy(c.a).addScaledVector(_ab, tt);
    474:           const d = _v.distanceTo(_cp);
    475:           if (d < c.r && d > 1e-6) _v.sub(_cp).multiplyScalar(c.r / d).add(_cp);
    476:         }
    477:         x[3*k] = _v.x; x[3*k+1] = _v.y; x[3*k+2] = _v.z;
    478:       }
    479:     }
    480:   }
    481:   write() {
    482:     const pos = this.display.geometry.attributes.position;
    483:     pos.array.set(this.x); pos.needsUpdate = true;
    484:     this.display.geometry.computeVertexNormals();
    485:   }
    486: }
    487: 
    488: const KEY = new THREE.Vector3(...(SCENE.key || [-0.62, 0.48, 0.62])).normalize();
    489: const GRADE = SCENE.grade || { ambient: [0.86, 0.88, 0.96], key: [1.04, 1.00, 0.94], rim: [0.28, 0.25, 0.20] };
    490: const KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };
    491: 
    492: function paintMaterial(V, role, map, index, infoRole = role, decal = false, crownY = 1.65) {
    493:   const Rl = V.roles[role] || { mode: "flat", color: "#ff00ff" }, P = (V.paint || {})[role];
    494:   const u = {
    495:     uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() },
    496:     uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 },
    497:     uInfo: { value: new THREE.Vector4(roleId(infoRole) / 255, (index % 256) / 255, Math.floor(index / 256) / 255, 1) },
    498:     uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() },
    499:     uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) },
    500:     uGold: { value: hex((V.paint && V.paint.gold && V.paint.gold.base) || "#c49a45") },
    501:     uAmbient: { value: new THREE.Vector3(...GRADE.ambient) },
    502:     uKeyCol: { value: new THREE.Vector3(...GRADE.key) },
    503:     uRimCol: { value: new THREE.Vector3(...GRADE.rim) },
    504:     uGrain: { value: 0.04 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null },
    505:     uSkinTone: { value: new THREE.Vector3(1, 1, 1) }, uShadeOnly: { value: 0 },
    506:     uSkinRamp: { value: 0 }, uSkinL: { value: new THREE.Color() }, uSkinS: { value: new THREE.Color() }, uSkinC: { value: new THREE.Color() },
    507:     uCrownY: { value: crownY },
    508:     uFootA: { value: new THREE.Vector2(99, 99) }, uFootB: { value: new THREE.Vector2(99, 99) },
    509:     uFootC: { value: new THREE.Vector2(99, 99) }, uFootD: { value: new THREE.Vector2(99, 99) },
    510:     tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 },
    511:     uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 },
    512:     uMotif: { value: hex((V.paint && V.paint.motif && V.paint.motif.base) || "#e8e3d5") }, uLift: { value: 0 }
    513:   };
    514:   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; }
    515:   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]); }
    516:   if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.11; }
    517:   if (P && P.shade) u.uShadeOnly.value = 1;
    518:   if (P && P.kind === "skin" && P.ramp) {
    519:     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]);
    520:   }
    521:   if (P && P.kind === "skin" && P.base) {
    522:     const c = hex(P.base); u.uSkinTone.value.set(c.r / 0.973, c.g / 0.882, c.b / 0.835);
    523:   }
    524:   if (role === "face" && map) u.uFaceTex.value = 1;
    525:   if ((role === "hair" || role === "hair_cap") && map) u.uAlpha.value = 1;
    526:   if (role === "iris") { u.uKind.value = 7; u.uAlpha.value = 1; }
    527:   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"); }
    528:   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; }
    529:   if (role === "mouth" && map) u.uKind.value = 10;
    530:   u.uBand.value = u.uGold.value.clone();
    531:   const m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: PAINT_VS, fragmentShader: PAINT_FS, side: THREE.DoubleSide,
    532:                                        extensions: { derivatives: true } });
    533:   m.defaultAttributeValues = { ...m.defaultAttributeValues, _plate: [0, 0, 0, 0], edge: [0] };
    534:   return m;
    535: }
    536: 
    537: const loader = new GLTFLoader();
    538: async function parseGlb(file) {
    539:   const j = await (await fetch(file)).json();
    540:   const bin = Uint8Array.from(atob(j.glb), c => c.charCodeAt(0));
    541:   return await new Promise((ok, bad) => loader.parse(bin.buffer, "", ok, bad));
    542: }
    543: 
    544: let meshIndex = 1;
    545: const allMeshes = [];
    546: const allCloths = [];
    547: const characters = [];
    548: 
    549: for (let ci = 0; ci < SCENE.characters.length; ci++) {
    550:   const def = SCENE.characters[ci], V = def.info;
    551:   const gltf = await parseGlb(`${def.name}.glb.json`);
    552:   const turn = new THREE.Group();
    553:   turn.add(gltf.scene);
    554:   turn.position.set(...def.place.pos);
    555:   turn.rotation.y = THREE.MathUtils.degToRad(def.place.yaw);
    556:   scene.add(turn);
    557: 
    558:   const meshes = [];
    559:   gltf.scene.traverse(o => {
    560:     if (!o.isMesh) return;
    561:     const m0 = o.material, role = o.userData.role || "body", raw = rawTex(m0.map);
    562:     const matName = o.userData.material || "";
    563:     const isInnerHair = role === "hair_cap" || matName.includes("HairBack");
    564:     const infoRole = isInnerHair ? "hair_cap" : (role === "hair" && ci > 0 ? "hair_b" : role === "shadow" ? "body" : role);
    565:     const decal = !!(m0.userData && m0.userData.decal);
    566:     const mat = paintMaterial(V, role, raw, meshIndex++, infoRole, decal, def.crown_y || 1.68);
    567:     if (isInnerHair) mat.uniforms.uShadeOnly.value = 1;
    568:     o.material = mat;
    569:     o.frustumCulled = false;
    570:     meshes.push(o);
    571:     allMeshes.push(o);
    572:   });
    573: 
    574:   const mixer = new THREE.AnimationMixer(gltf.scene);
    575:   const actions = Object.fromEntries(gltf.animations.map(c => [c.name, mixer.clipAction(c)]));
    576:   const clipName = def.clip || "idle";
    577:   if (actions[clipName]) {
    578:     actions[clipName].reset();
    579:     actions[clipName].setEffectiveWeight(1);
    580:     actions[clipName].play();
    581:     actions[clipName].time = def.clip_t || 0;
    582:     mixer.update(0);
    583:   }
    584:   scene.updateMatrixWorld(true);
    585: 
    586:   // Measure live crown height for the halo band after posing
    587:   const headBone = gltf.scene.getObjectByName("J_Bip_C_Head");
    588:   if (headBone) {
    589:     const hp = headBone.getWorldPosition(new THREE.Vector3());
    590:     const cy = hp.y + 0.145;
    591:     meshes.forEach(m => { m.material.uniforms.uCrownY.value = cy; });
    592:   }
    593: 
    594:   const bone = n => gltf.scene.getObjectByName(n);
    595:   const world = new THREE.Group();
    596:   scene.add(world);
    597:   for (const [cname, info] of Object.entries(V.cloth || {})) {
    598:     const skinned = meshes.find(m => m.userData.material === cname);
    599:     if (!skinned) continue;
    600:     const trims = meshes.filter(m => info.trims.includes(m.userData.material));
    601:     const caps = V.capsules.filter(c => !info.collide || info.collide.some(k => c.bones[0].includes(k)));
    602:     const cl = new Cloth(skinned, info.u, info.v, trims, caps, bone, info.closed, info.edges === "hem");
    603:     const PB = (V.paint || {})[info.band || "gold"];
    604:     if (PB && PB.base) cl.display.material.uniforms.uBand.value = hex(PB.base);
    605:     skinned.visible = false;
    606:     trims.forEach(t => { t.visible = false; });
    607:     world.add(cl.display);
    608:     allMeshes.push(cl.display);
    609:     allCloths.push({ cl, wind: def.wind || 0 });
    610:   }
    611:   characters.push({ def, root: gltf.scene, meshes });
    612: }
    613: 
    614: // Settle cloth drapes cleanly
    615: allCloths.forEach(({ cl }) => cl.reset());
    616: for (let s = 0; s < 160; s++) allCloths.forEach(({ cl, wind }) => cl.step(1 / 120, wind));
    617: allCloths.forEach(({ cl }) => cl.write());
    618: 
    619: // Load terrain and pass planted foot positions for contact shadows
    620: const groundGltf = await parseGlb("plains.glb.json");
    621: scene.add(groundGltf.scene);
    622: const footPts = [];
    623: for (const c of characters) {
    624:   for (const fn of ["J_Bip_L_Foot", "J_Bip_R_Foot"]) {
    625:     const b = c.root.getObjectByName(fn);
    626:     if (b) { const p = b.getWorldPosition(new THREE.Vector3()); footPts.push(new THREE.Vector2(p.x, p.z)); }
    627:   }
    628: }
    629: while (footPts.length < 4) footPts.push(new THREE.Vector2(99, 99));
    630: 
    631: const V0 = SCENE.characters[0].info;
    632: groundGltf.scene.traverse(o => {
    633:   if (!o.isMesh) return;
    634:   const role = o.userData.role || "grass";
    635:   const mat = paintMaterial(V0, role, rawTex(o.material.map), meshIndex++, role, false);
    636:   mat.uniforms.uFootA.value.copy(footPts[0]);
    637:   mat.uniforms.uFootB.value.copy(footPts[1]);
    638:   mat.uniforms.uFootC.value.copy(footPts[2]);
    639:   mat.uniforms.uFootD.value.copy(footPts[3]);
    640:   o.material = mat;
    641:   o.frustumCulled = false;
    642:   allMeshes.push(o);
    643: });
    644: 
    645: function setupCamera(aspect) {
    646:   const C = SCENE.camera;
    647:   const centre = new THREE.Vector3(...C.target);
    648:   const h = C.height, w = h * aspect;
    649:   camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2;
    650:   camera.zoom = 1;
    651:   camera.updateProjectionMatrix();
    652:   const a = THREE.MathUtils.degToRad(C.pitch);
    653:   camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(16));
    654:   camera.up.set(0, 1, 0);
    655:   camera.lookAt(centre);
    656: }
    657: 
    658: function renderFrame(w, h, ss = 1) {
    659:   const bw = w * ss, bh = h * ss;
    660:   R.setPixelRatio(1);
    661:   R.setSize(bw, bh, false);
    662:   setupCamera(w / h);
    663:   targetsFor(bw, bh);
    664: 
    665:   const visible = allMeshes.filter(o => o.visible);
    666:   visible.forEach(o => {
    667:     const mu = o.material.uniforms;
    668:     mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null;
    669:   });
    670:   R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera);
    671: 
    672:   const ppmBuf = bh / (camera.top - camera.bottom);
    673:   visible.forEach(o => {
    674:     const mu = o.material.uniforms;
    675:     mu.uPass.value = 0; mu.uCastOn.value = 1;
    676:     mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture;
    677:     mu.uCastRes.value.set(bw, bh); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf;
    678:   });
    679:   R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera);
    680: 
    681:   const u = paint.mat.uniforms;
    682:   u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture;
    683:   u.uRes.value.set(bw, bh); u.uNear.value = camera.near; u.uFar.value = camera.far;
    684:   u.uGap.value = 0.012;
    685:   u.uSil.value = THREE.MathUtils.clamp(1.75 * ppmBuf * 0.0040, ss, 2.5 * ss);
    686:   u.uInner.value = Math.max(ss * 0.78, u.uSil.value * 0.56);
    687:   u.uPpm.value = ppmBuf;
    688:   R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam);
    689: }
    690: 
    691: if (SHOT) {
    692:   const outW = +(params.get("w") || 1920), outH = +(params.get("h") || 1080), ss = +(params.get("ss") || 2);
    693:   renderFrame(outW, outH, ss);
    694:   const cv = document.createElement("canvas");
    695:   cv.width = outW; cv.height = outH;
    696:   const ctx = cv.getContext("2d");
    697:   ctx.imageSmoothingEnabled = true;
    698:   ctx.imageSmoothingQuality = "high";
    699:   ctx.drawImage(R.domElement, 0, 0, outW, outH);
    700:   document.getElementById("sheetOut").textContent = cv.toDataURL("image/png");
    701:   document.title = "slice ready";
    702: } else {
    703:   const fit = () => renderFrame(window.innerWidth, window.innerHeight, Math.min(2, window.devicePixelRatio || 1));
    704:   window.addEventListener("resize", fit);
    705:   fit();
    706: }
    707: </script>
    708: </body>
    709: </html>
reasoning

Initial investigation focuses on the file review/slice/index.html and the script export_glb.py. The goal is to understand how custom textures, represented by p["custom_tex"], are handled within export_glb.py. Further examination is needed to confirm if the textures are correctly integrated into the HTML.

The code retrieves custom_tex and falls back to material_texture if unavailable, suggesting a direct override capability. The add_texture function then handles the texture integration based on whether custom_tex exists. This setup allows for custom texture painting, indicated by the specific texture data. This potentially enables applying detailed textures directly within the rendering pipeline controlled by the HTML and the GLB file.

The texture data directly affects the base color of the .glb file. A bias map for per-vertex anime face shadows (_PLATE on face) is present in the HTML. vPlate can be set to adjust the shadow bias. A -0.14 bias on the upper eye-socket under the brow ridge, enhances depth.

The shadow bias, defined in the HTML, is directly applied to the .glb file, affecting specific facial features. The biases range from negative values for shadows (e.g., nose and under-lip) to positive values for highlights (e.g., cheekbone and nose bridge). export_skinned integrates this per-vertex shadow data into the .glb file through _PLATE, preserving the authored anime face shading.

The HTML defines two-sided cloak lining using PAINT_FS. The back face of the cloak, when P.lining is present, uses a specified color, allowing for interior lining rendering. This enables the use of different colors to render different sides of the cape.

The shader code utilizes uHasLining and uLining to conditionally render the cloak lining based on its presence. The uFlattice, uFlChin, uFlFall, and uFlPivot uniforms within PAINT_VS suggest a flattice lens distortion effect is being implemented, likely for the perspective camera. The code aims to replicate the flattice lens calculations from patch_lens_flattice.py and apply them to the vertex positions.

The lens distortion calculations, implemented through uFlattice, uFlChin, uFlFall, and uFlPivot, modify vertex positions to create a flattice lens effect. wp.y represents the world height of the vertex after posing, while position.y represents the initial height. The code uses w = clamp((wp.y - (uFlChin - uFlFall)) / uFlFall, 0.0, 1.0) to apply a smooth squash and fade effect along the neck, based on the uFlChin position.

The code linearizes depth in castShadow within PAINT_FS, mirroring the z(vec2 p) function in PAINT_COMP when perspective rendering is enabled (uPersp > 0.5). This ensures accurate shadow casting, especially for hair-to-face shadows under a perspective camera lens. The uGap parameter in PAINT_COMP is also confirmed to be set to zero.

The flattice lens effect, derived from patch_lens_flattice.py, correctly applies a depth step calculation. This aligns with observed behaviors in the rendered output. The observed side-by-side rendering of different flattice settings in the image suggests a mechanism where both views are rendered simultaneously, potentially from the same GLB file, using the HTML script. Further investigation will determine if the rendering is indeed controlled by different HTML parameters.

The script checks for custom_tex, falling back to material_texture if unavailable, enabling custom texture overrides. The texture cache key utilizes "custom_tex" if present. This ensures textures can be loaded from a custom data source, overriding the material texture. Adding custom texture support is unlikely to break anything as it defaults to the existing texture retrieval mechanism.

The extras dictionary within gnodes in export_skinned stores group, role, and material information for each mesh node. This data, when present, populates node.userData and the associated material information directly in the .glb file, eliminating the need for separate sidecar files for metadata. This data includes cel-paint ramps, skin ramps, eye colors, and cloth drape information, which is then accessible by any rendering pipeline that reads the .glb file. This means this extra data is harmless to other renderers.

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

    input

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

    result, 29 lines

    Showing lines 540-567 of 567
    540:             t0, q0, _ = _trs(local_ref[i])
    541:             if np.dot(Q[0], q0) < 0:
    542:                 q0 = -q0
    543:             # a channel whenever the clip leaves the reference pose, even if it then holds still
    544:             if np.abs(Q - q0).max() > 1e-5:
    545:                 samplers.append(dict(input=tacc, output=add_acc(Q, "VEC4", 5126), interpolation="LINEAR"))
    546:                 channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path="rotation")))
    547:             if np.abs(T - t0).max() > 1e-5:
    548:                 samplers.append(dict(input=tacc, output=add_acc(T, "VEC3", 5126), interpolation="LINEAR"))
    549:                 channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path="translation")))
    550:         anims.append(dict(name=name, samplers=samplers, channels=channels))
    551:     root = len(gnodes)
    552:     gnodes.append(dict(name="character", children=roots + mesh_nodes))
    553:     gltf = dict(asset=dict(version="2.0", generator="lowmarch export_skinned"), scene=0, scenes=[dict(nodes=[root])],
    554:                 nodes=gnodes, meshes=meshes, materials=materials, skins=[skin], accessors=accessors, bufferViews=views,
    555:                 buffers=[dict(byteLength=len(bin_))], samplers=[dict(magFilter=9729, minFilter=9987)])
    556:     if textures:
    557:         gltf.update(textures=textures, images=images)
    558:     if anims:
    559:         gltf["animations"] = anims
    560:     js = json.dumps(gltf, separators=(",", ":")).encode()
    561:     js += b" " * ((4 - len(js) % 4) % 4)
    562:     while len(bin_) % 4:
    563:         bin_.append(0)
    564:     out = struct.pack("<4sII", b"glTF", 2, 12 + 8 + len(js) + 8 + len(bin_))
    565:     out += struct.pack("<I4s", len(js), b"JSON") + js + struct.pack("<I4s", len(bin_), b"BIN\x00") + bytes(bin_)
    566:     open(path, "wb").write(out)
    567:     return len(out)
reasoning

Examining tools/export_glb.py, lines 385-405 specify export_skinned's signature, and lines 545 & 548 define the interpolation. Suspecting a mismatch, checking how the clip tuple or dictionary handles stepped interpolation (e.g., 12 fps with "STEP"). If those have an interpolation other than "LINEAR"

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

    input

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

    result, 27 lines

    Showing lines 380-405 of 567
    380: def export_skinned(portrait, palette, path, clips=None, max_tex=512):
    381:     """The character in its reference pose as a skinned glTF: the VRoid skeleton (with our bone
    382:     scales) drives the body, face, hair and every costume piece through the weights they carry.
    383:     clips: {name: [(time, pose dict), ...]} -> glTF animations (rotation, plus translation where a
    384:     pose moves a bone). Scenery is left out (export it with export())."""
    385:     import vroid_portrait as vp
    386:     v = portrait.v
    387:     nodes_v = v.j["nodes"]
    388:     names = v.nodes_by_name()
    389:     parent = v.parents()
    390:     used = set()
    391:     for p in portrait.prims:
    392:         if "jnames" in p and not p.get("world"):
    393:             used.update(n for n in p["jnames"] if n in names)
    394:     joints = set()
    395:     for nm in used:                                   # every used bone plus its ancestors
    396:         i = names[nm]
    397:         while i is not None and i not in joints:
    398:             joints.add(i)
    399:             i = parent.get(i)
    400:     order = sorted(joints)
    401:     jidx = {nodes_v[i].get("name"): k for k, i in enumerate(order)}
    402:     ref = portrait.pose_ref
    403:     local_ref = {i: F4 @ v.local_matrix(i, ref) @ F4 for i in order}
    404:     world_ref = {}
    405: