A 3D model pipeline, pushed by Fable 5.2

agent

+58:37
reasoning

Both workers are almost finished, so I'm now writing the new renderer: a single page with a perspective camera, shadow mapping, cel shading, outlines, rim lighting, and a painted sky and ground.

  • Write~/Projects/lowmarch-fable52/tools/whole/stage/stage.html

    input

    ~/Projects/lowmarch-fable52/tools/whole/stage/stage.html
    
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>stage</title>
    <style>html, body { margin: 0; background: #14131a; } canvas { display: block; max-width: 100vw; height: auto; } #out { display: none; }</style>
    <script type="importmap">
    { "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
                   "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/" } }
    </script>
    </head>
    <body>
    <pre id="out"></pre>
    <script type="module">
    // Stage: a perspective cel renderer for one built character (and anyone beside her). Not the project's painted
    // page: light is designed here, not computed and patched.
    //   one key light with a real shadow map (the jaw on the neck, the arm on the plate, the figure on the ground);
    //   two tones per material with the shade's hue turned, a thin warm line where skin goes into shadow;
    //   hair as dark masses with one highlight band laid across the clumps;
    //   steel as a few flat shapes: a light, a plate tone, a shade, a hard streak;
    //   ink lines from depth, identity and creases, coloured by what they border, heavier on the outline;
    //   a rim light on the side away from the key; a painted sky, far hills and ground; bloom and a grade.
    // ?spec=<json>: see tools/whole/stage_shot.py.
    import * as THREE from "three";
    import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
    THREE.ColorManagement.enabled = false;                 // palette values are display values, as the project keeps them
    
    const $ = id => document.getElementById(id);
    const q = new URLSearchParams(location.search);
    const S = Object.assign({
      w: 1920, h: 1080, ss: 2, site: ".",
      chars: [{ name: "wren", clip: ["idle", 0], pos: [0, 0, 0], yaw: 60 }],
      cam: { lens: 50, pos: [0.4, 1.25, 4.2], target: [0, 1.0, 0] },
      key: [-0.55, 0.72, 0.42], rim: [0.75, 0.25, -0.6], flat: 0.0, wind: [0, 0, 0], sway: 0.0,
      sky: 1, ground: 1, bloom: 0.5, line: 1.0, debug: "",
    }, JSON.parse(q.get("spec") || "{}"));
    const W = Math.round(S.w * S.ss), H = Math.round(S.h * S.ss);
    
    const R = new THREE.WebGLRenderer({ antialias: false, alpha: false, preserveDrawingBuffer: true });
    R.setPixelRatio(1); R.setSize(S.w, S.h, false); R.outputColorSpace = THREE.LinearSRGBColorSpace; R.autoClear = true;
    document.body.appendChild(R.domElement);
    
    const hex = h => { const n = parseInt(h.slice(1), 16); return new THREE.Color().setRGB((n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255); };
    const hsv = c => { const o = {}; c.getHSL(o); const v = o.l + o.s * Math.min(o.l, 1 - o.l); return [o.h, v ? 2 * (1 - o.l / v) : 0, v]; };
    const fromHsv = (h, s, v) => { h = ((h % 1) + 1) % 1; s = Math.min(1, Math.max(0, s)); v = Math.min(1, Math.max(0, v));
      const l = v * (1 - s / 2), sl = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l); return new THREE.Color().setHSL(h, sl, l); };
    // a tone of a base colour: hue pulled toward `to` by at most `amt`, saturation and value scaled
    const tone = (c, to, amt, sMul, vMul) => { const [h, s, v] = hsv(c); let d = to - h; d -= Math.round(d);
      return fromHsv(h + Math.max(-amt, Math.min(amt, d)), s * sMul, v * vMul); };
    
    // ---- shaders --------------------------------------------------------------------------------------------------------
    const NOISE = `
      float hash1(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)); }
      float vnoise(vec3 x) {
        vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);
        return mix(mix(mix(hash1(i), hash1(i + vec3(1,0,0)), f.x), mix(hash1(i + vec3(0,1,0)), hash1(i + vec3(1,1,0)), f.x), f.y),
                   mix(mix(hash1(i + vec3(0,0,1)), hash1(i + vec3(1,0,1)), f.x), mix(hash1(i + vec3(0,1,1)), hash1(i + vec3(1,1,1)), f.x), f.y), f.z);
      }
      float fbm(vec3 p) { float a = 0.5, s = 0.0; for (int i = 0; i < 5; i++) { s += a * vnoise(p); p = p * 2.03 + 7.1; a *= 0.5; } return s; }`;
    
    const VS = `#include <common>
      #include <skinning_pars_vertex>
      attribute vec4 _plate;
      uniform int uPass; uniform float uLift; uniform int uSway; uniform vec3 uWind; uniform vec2 uSwaySpan;
      uniform float uFlatK; uniform float uFlatChin; uniform vec3 uFlatPivot;
      varying vec3 vN; varying vec2 vUv; varying vec3 vWorld; varying vec3 vObj; varying vec4 vPlate; varying vec3 vView;
      void main() {
        #include <beginnormal_vertex>
        #include <skinbase_vertex>
        #include <skinnormal_vertex>
        #include <begin_vertex>
        #include <skinning_vertex>
        vec4 wp = modelMatrix * vec4(transformed, 1.0);
        #ifdef USE_INSTANCING
          wp = modelMatrix * instanceMatrix * vec4(transformed, 1.0);
        #endif
        float sw = 0.0;
        if (uSway == 1) sw = _plate.y;                                  // hair: tied at the head, free at the tip
        else if (uSway == 2) sw = clamp((uSwaySpan.x - position.y) / uSwaySpan.y, 0.0, 1.0);   // a hanging panel, by height
        if (sw > 0.0) { float k = sw * sw; wp.xyz += uWind * k; wp.y += length(uWind) * k * 0.35 * sw; }
        vWorld = wp.xyz; vObj = position; vUv = uv; vPlate = _plate;
        vN = normalize(mat3(modelMatrix) * objectNormal);
        vec4 mv = viewMatrix * wp;
        if (uFlatK > 0.0 && uPass != 2) {                               // Flattice: squash the head toward the camera plane
          float w = clamp((position.y - (uFlatChin - 0.05)) / 0.05, 0.0, 1.0);
          vec3 u = normalize(-uFlatPivot);
          mv.xyz -= u * dot(mv.xyz - uFlatPivot, u) * w * uFlatK;
        }
        mv.z += uLift;
        vView = mv.xyz;
        gl_Position = projectionMatrix * mv;
      }`;
    
    const FS = `
      uniform int uPass; uniform int uKind; uniform int uAlpha; uniform int uRecv; uniform int uDecal; uniform int uFaceTex;
      uniform vec3 uBase; uniform vec3 uShade; uniform vec3 uDeep; uniform vec3 uLight; uniform vec3 uGold; uniform vec3 uGoldS;
      uniform vec3 uMotif; uniform vec3 uFlat; uniform vec3 uEye[3]; uniform vec3 uSkinRef; uniform vec3 uScatter;
      uniform sampler2D uMap; uniform vec3 uKey; uniform vec3 uCam; uniform vec4 uId;
      uniform sampler2D tShadow; uniform sampler2D tShadowFace; uniform mat4 uShadowMat; uniform float uShadowTexel;
      uniform vec3 uFog; uniform vec3 uSunCol; uniform vec3 uSkyAmb; uniform float uThresh; uniform float uSeed;
      varying vec3 vN; varying vec2 vUv; varying vec3 vWorld; varying vec3 vObj; varying vec4 vPlate; varying vec3 vView;
      ${NOISE}
      float st(float x, float t, float e) { return smoothstep(t - e, t + e, x); }
      float shadowAt(sampler2D t, vec3 wp, float bias) {
        vec4 sc = uShadowMat * vec4(wp, 1.0);
        vec3 p = sc.xyz * 0.5 + 0.5;
        if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z > 1.0) return 1.0;
        float s = 0.0;
        for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++)
          s += step(p.z - bias, texture2D(t, p.xy + vec2(float(i), float(j)) * uShadowTexel).x);
        return s / 9.0;
      }
      // steel and gold as a few flat shapes: shade, plate tone, light, and one hard streak toward the key
      vec3 metal(vec3 base, vec3 shade, vec3 deep, vec3 light, vec3 n, vec3 v, float lit, float hgt) {
        vec3 r = reflect(-v, n);
        float up = n.y * 0.5 + 0.5;
        vec3 col = mix(shade, base, lit);
        col = mix(col, deep, (1.0 - lit) * st(-r.y, 0.25, 0.04) * 0.75);            // the ground in the plate's shade
        col = mix(col, light, lit * st(up + (hgt >= 0.0 ? (hgt - 0.5) * 0.5 : 0.0), 0.70, 0.03) * 0.85);   // sky on what faces up
        float hl = dot(n, normalize(uKey + v));
        col = mix(col, vec3(1.0, 0.99, 0.95), lit * st(hl, 0.965, 0.006));          // the streak
        float fr = pow(1.0 - max(dot(n, v), 0.0), 3.0);
        col = mix(col, mix(deep, shade, 0.5), fr * 0.55 * (1.0 - lit * 0.6));        // edges turn away: darker
        return col;
      }
      void main() {
        vec4 tex = texture2D(uMap, vUv);
        if (uAlpha == 1 && tex.a < 0.5) discard;
        if (uAlpha == 2 && (tex.a < 0.5 || dot(tex.rgb, vec3(1.0 / 3.0)) >= 0.42)) discard;
        if (uPass == 2) { gl_FragColor = vec4(1.0); return; }                       // shadow [redacted: scan false positive] only
        vec3 n = normalize(vN); if (!gl_FrontFacing) n = -n;
        if (uPass == 1) {                                                           // line [redacted: scan false positive] normal, identity
          vec3 nv = normalize(mat3(viewMatrix) * n);
          gl_FragColor = vec4(nv.xy * 0.5 + 0.5, uId.x, uId.y); return;
        }
        vec3 v = normalize(uCam - vWorld);
        float ndl = dot(n, uKey);
        float sh = 1.0;
        if (uRecv == 1) sh = shadowAt(tShadow, vWorld + n * 0.012, 0.0016);
        else if (uRecv == 2) sh = shadowAt(tShadowFace, vWorld + n * 0.004, 0.0030);
        float lit = st(ndl, uThresh, 0.012) * st(sh, 0.5, 0.25);
        vec3 col;
        if (uKind == 0 || uKind == 5) {                                             // cloth, leather
          float g = vnoise(vObj * 34.0) - 0.5;
          float l2 = st(ndl + g * 0.05, uThresh, 0.012) * st(sh, 0.5, 0.25);
          col = mix(uShade, uBase, l2);
          col = mix(col, uDeep, (1.0 - l2) * st(-ndl, 0.55, 0.03) * 0.7);           // turned well away: a deeper core
          col = mix(col, uLight, l2 * st(ndl, 0.86, 0.02) * 0.55);
          if (uKind == 5) { float hl = dot(n, normalize(uKey + v)); col = mix(col, uLight, l2 * st(hl, 0.94, 0.02) * 0.5); }
          col *= 1.0 + (vnoise(vObj * 120.0) - 0.5) * 0.045;
        } else if (uKind == 1) {                                                    // skin
          col = mix(uShade, uBase, lit);
          float band = exp(-pow((ndl - uThresh) / 0.07, 2.0)) * st(sh, 0.5, 0.25);  // the warm line where it turns
          col = mix(col, uScatter, band * 0.35 * (1.0 - lit * 0.6));
          if (uFaceTex == 1) {
            col *= clamp(tex.rgb / uSkinRef, 0.55, 1.05);
            if (vUv.x > 0.38 && vUv.x < 0.62 && vUv.y > 0.68 && vUv.y < 0.84) {     // the closed mouth, inked from VRoid's painted line
              float d = 0.0, sl = dot(uSkinRef, vec3(1.0 / 3.0));
              for (int k = -2; k <= 2; k++) for (int j = -1; j <= 1; j++) {
                vec3 t = texture2D(uMap, vUv + vec2(float(j) * 1.2, float(k) * 0.8) / 512.0).rgb;
                d = max(d, 1.0 - dot(t, vec3(1.0 / 3.0)) / sl);
              }
              float taper = 1.0 - 0.55 * smoothstep(0.035, 0.065, abs(vUv.x - 0.5));
              col = mix(col, vec3(0.45, 0.20, 0.20), smoothstep(0.10, 0.22, d) * taper);
            }
          }
        } else if (uKind == 2) {                                                    // hair: masses, then one band of light
          col = mix(uShade, uBase, lit);
          col = mix(col, uDeep, (1.0 - lit) * st(-ndl, 0.45, 0.03) * 0.8);
          float u = vPlate.z, t = vPlate.w;
          vec3 dpx = dFdx(vWorld), dpy = dFdy(vWorld);
          float dux = dFdx(u), duy = dFdy(u), dtx = dFdx(t), dty = dFdy(t);
          float det = dtx * duy - dty * dux;
          vec3 T = abs(det) > 1e-9 ? normalize((dpx * duy - dpy * dux) / det) : normalize(vec3(0.0, 1.0, 0.0) - n * n.y);
          vec3 hv = normalize(uKey + v);
          float th = dot(T, hv);
          float jag = (vnoise(vec3(u * 9.0 + uSeed * 7.3, uSeed * 3.1, 0.0)) - 0.5) * 0.16 + (vnoise(vec3(u * 31.0, uSeed, 1.7)) - 0.5) * 0.06;
          float ring = 1.0 - smoothstep(0.045, 0.060, abs(th + jag - 0.06));       // where the strand runs across the light
          float face = st(dot(n, hv), 0.35, 0.10);
          col = mix(col, uLight, ring * face * lit * 0.92);
          col = mix(col, uBase * 1.12, lit * st(ndl, 0.80, 0.03) * 0.35);
        } else if (uKind == 3 || uKind == 4) {                                      // steel, gold
          bool plate = vPlate.x > 0.5;
          float e = vPlate.y, w = vPlate.z;
          bool gilt = uKind == 4 || (plate && w > 0.0 && e < w);
          float hgt = plate ? vPlate.w : -1.0;
          if (gilt && uKind == 3) col = metal(uGold, uGoldS, uGoldS * 0.6, mix(uGold, vec3(1.0, 0.95, 0.75), 0.6), n, v, lit, hgt);
          else col = metal(uBase, uShade, uDeep, uLight, n, v, lit, hgt);
          if (plate && w > 0.0) {                                                   // an engraved line inside the border
            float aa = fwidth(e) * 1.2 + 1e-5;
            float l1 = 1.0 - smoothstep(0.0009, 0.0009 + aa, abs(e - (w + 0.0050)));
            float l2 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - w));
            col = mix(col, col * 0.45, max(l1, l2 * 0.8));
          }
          if (uDecal == 1) {                                                        // R paint, G groove, B gold inlay
            float pm = smoothstep(0.3, 0.7, tex.r), gm = smoothstep(0.3, 0.7, tex.g), au = smoothstep(0.3, 0.7, tex.b);
            col = mix(col, metal(uGold, uGoldS, uGoldS * 0.6, uGold, n, v, lit, -1.0), au);
            col = mix(col, mix(uMotif * 0.62, uMotif, lit), pm);
            col = mix(col, col * 0.35, gm);
          }
        } else if (uKind == 6) {                                                    // ground: painted grass
          vec2 p = vWorld.xz;
          float d = length(uCam.xz - p);
          float a = fbm(vec3(p * 0.55, 0.0)), b = fbm(vec3(p * 2.6 + 9.0, 1.0)), c = vnoise(vec3(p.x * 26.0, p.y * 7.0, 2.0));
          vec3 g0 = vec3(0.26, 0.42, 0.25), g1 = vec3(0.40, 0.56, 0.28), g2 = vec3(0.60, 0.70, 0.36), g3 = vec3(0.50, 0.50, 0.30);
          col = mix(g0, g1, smoothstep(0.42, 0.50, a));
          col = mix(col, g2, smoothstep(0.52, 0.58, b) * 0.75);
          col = mix(col, g3, smoothstep(0.62, 0.66, fbm(vec3(p * 0.9 + 30.0, 4.0))) * 0.5);   // dry patches
          col *= 0.94 + 0.12 * c * smoothstep(9.0, 2.0, d);                         // blades, only near
          float s2 = shadowAt(tShadow, vWorld + vec3(0.0, 0.01, 0.0), 0.0012);
          col = mix(col * vec3(0.50, 0.58, 0.72), col, st(s2, 0.5, 0.35));
          col = mix(col, uFog, 1.0 - exp(-max(d - 6.0, 0.0) * 0.022));
        } else if (uKind == 7) {                                                    // iris
          float l = dot(tex.rgb, vec3(1.0 / 3.0));
          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));
          col *= mix(0.80, 1.0, st(sh, 0.5, 0.25));
        } else if (uKind == 8) { col = tex.rgb * mix(0.86, 1.0, st(sh, 0.5, 0.25)); }
        else if (uKind == 10) {                                                     // the open mouth
          float lum = dot(tex.rgb, vec3(1.0 / 3.0));
          col = mix(vec3(0.36, 0.11, 0.14), vec3(0.78, 0.38, 0.42), smoothstep(0.53, 0.58, tex.g));
          col = mix(col, vec3(0.98, 0.96, 0.95), smoothstep(0.80, 0.86, lum));
        } else { col = uFlat; }
        if (uKind <= 5) {                                                           // the scene's light on everything shaded
          col *= mix(uSkyAmb, uSunCol, lit);
          float d = length(uCam - vWorld);
          col = mix(col, uFog, (1.0 - exp(-max(d - 6.0, 0.0) * 0.022)) * 0.9);
        }
        gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
      }`;
    
    const QUAD_VS = `varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
    // the picture: sky where nothing is, ink lines, the rim light
    const COMP_FS = `
      uniform sampler2D tColor; uniform sampler2D tInfo; uniform sampler2D tDepth; uniform vec2 uRes; uniform float uNear; uniform float uFar;
      uniform mat4 uInvProj; uniform mat4 uCamWorld; uniform vec3 uKey; uniform vec2 uRimDir; uniform float uPx; uniform float uLine;
      uniform vec3 uZenith; uniform vec3 uHorizon; uniform vec3 uFog; uniform int uSky; uniform vec2 uKeyScr;
      varying vec2 vUv;
      ${NOISE}
      float lin(float d) { float z = d * 2.0 - 1.0; return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
      float zAt(vec2 p) { return lin(texture2D(tDepth, p).x); }
      vec3 rgb2hsv(vec3 c) { vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
        vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); float d = q.x - min(q.w, q.y);
        return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + 1e-10)), d / (q.x + 1e-10), q.x); }
      vec3 hsv2rgb(vec3 c) { vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); }
      vec3 ink(vec3 c) { vec3 h = rgb2hsv(c); return hsv2rgb(vec3(h.x + (h.x > 0.08 && h.x < 0.45 ? -0.03 : 0.0), clamp(h.y * 1.3 + 0.15, 0.25, 0.75), min(h.z * 0.34, 0.26))); }
      vec3 sky(vec3 d) {
        float e = max(d.y, 0.0);
        vec3 col = mix(uHorizon, uZenith, pow(e, 0.55));
        float sun = max(dot(d, uKey), 0.0);
        col += vec3(1.0, 0.85, 0.6) * (pow(sun, 60.0) * 0.5 + pow(sun, 6.0) * 0.12);
        if (d.y > 0.0) {                                                           // cumulus: a lit top, a cool underside, hard edges
          vec2 p = d.xz / (d.y + 0.12) * 1.1;
          float n = fbm(vec3(p * 0.9, 3.0)) + 0.35 * fbm(vec3(p * 3.1, 9.0));
          float cover = smoothstep(0.66, 0.70, n) * smoothstep(0.02, 0.16, d.y);
          float body = smoothstep(0.70, 0.90, n);
          float n2 = fbm(vec3((p + uKey.xz * 0.10) * 0.9, 3.0)) + 0.35 * fbm(vec3((p + uKey.xz * 0.10) * 3.1, 9.0));
          float lit = smoothstep(-0.02, 0.05, n - n2);
          vec3 cl = mix(vec3(0.70, 0.78, 0.90), vec3(1.0, 0.99, 0.96), max(lit, 1.0 - body) );
          cl = mix(cl, vec3(0.62, 0.70, 0.86), body * (1.0 - lit) * 0.6);
          col = mix(col, mix(cl, uHorizon, exp(-d.y * 9.0) * 0.6), cover);
        }
        // far hills: two ridges in haze
        float az = atan(d.x, -d.z);
        float h1 = 0.030 + 0.050 * fbm(vec3(az * 2.2, 0.0, 5.0)) + 0.012 * vnoise(vec3(az * 19.0, 1.0, 5.0));
        float h2 = 0.010 + 0.040 * fbm(vec3(az * 3.4 + 4.0, 0.0, 8.0)) + 0.008 * vnoise(vec3(az * 31.0, 2.0, 8.0));
        col = mix(col, mix(vec3(0.56, 0.66, 0.80), uHorizon, 0.45), smoothstep(0.004, -0.004, d.y - h1));
        col = mix(col, mix(vec3(0.36, 0.50, 0.50), uHorizon, 0.30), smoothstep(0.003, -0.003, d.y - h2));
        return col;
      }
      void main() {
        vec2 px = 1.0 / uRes;
        vec4 c = texture2D(tColor, vUv);
        vec4 inf = texture2D(tInfo, vUv);
        float d0 = texture2D(tDepth, vUv).x;
        bool bg = d0 >= 0.99999;
        float z0 = lin(d0);
        vec3 col = c.rgb;
        if (bg) {
          vec4 pv = uInvProj * vec4(vUv * 2.0 - 1.0, 1.0, 1.0);
          vec3 dir = normalize((uCamWorld * vec4(normalize(pv.xyz / pv.w), 0.0)).xyz);
          col = uSky == 1 ? sky(dir) : uHorizon;
        }
        bool isGround = inf.a > 0.90 && !bg;
        if (!bg && !isGround) {
          // rim: lit where the far side of the figure meets air or something well behind it
          float w = uPx * 3.2;
          float zr = zAt(vUv + uRimDir * px * w), zr2 = zAt(vUv + uRimDir * px * w * 0.5);
          float rim = max(smoothstep(0.10, 0.30, zr - z0), smoothstep(0.10, 0.30, zr2 - z0) * 0.6);
          vec3 nv = vec3(inf.rg * 2.0 - 1.0, 0.0);
          rim *= smoothstep(-0.2, 0.5, dot(nv.xy, uRimDir));
          col = mix(col, min(col * 1.25 + vec3(0.42, 0.38, 0.30), vec3(1.0)), rim * 0.85);
        }
        // ink: the outline (against air, against another thing well behind), then seams between parts, then creases
        float wOut = uPx * 1.25 * uLine, wIn = uPx * 0.8 * uLine;
        float edgeOut = 0.0, edgeIn = 0.0, crease = 0.0;
        vec3 nearCol = col; float nearZ = z0;
        for (int k = 0; k < 8; k++) {
          float a = float(k) * 0.7853982;
          vec2 o = vec2(cos(a), sin(a));
          vec2 p1 = vUv + o * px * wOut, p2 = vUv + o * px * wIn;
          float z1 = zAt(p1), z2 = zAt(p2);
          vec4 i2 = texture2D(tInfo, p2);
          float gap = 0.035 + 0.02 * min(z0, z1);
          if (z0 - z1 > gap) { edgeOut = 1.0; if (z1 < nearZ) { nearZ = z1; nearCol = texture2D(tColor, p1).rgb; } }   // something nearer beside us: its outline
          if (!bg && !isGround) {
            if (abs(i2.b - inf.b) > 0.002 && abs(z2 - z0) < gap) edgeIn = 1.0;      // another part, touching
            vec2 n0 = inf.rg * 2.0 - 1.0, n2 = i2.rg * 2.0 - 1.0;
            if (abs(i2.b - inf.b) <= 0.002 && dot(n0, n2) + sqrt(max(0.0, 1.0 - dot(n0, n0))) * sqrt(max(0.0, 1.0 - dot(n2, n2))) < 0.45) crease = 1.0;
          }
        }
        float lineW = inf.a;                                                        // 0 = this part takes no inner lines
        if (edgeOut > 0.0) col = ink(nearCol);
        else if (edgeIn > 0.0 && lineW > 0.05 && lineW < 0.90) col = mix(col, ink(col), 0.92);
        else if (crease > 0.0 && lineW > 0.05 && lineW < 0.90) col = mix(col, ink(col), 0.55);
        gl_FragColor = vec4(col, 1.0);
      }`;
    // bloom and the grade, at output size
    const FINAL_FS = `
      uniform sampler2D tPic; uniform sampler2D tBloom; uniform float uBloom; uniform vec2 uRes; varying vec2 vUv;
      float hash(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
      void main() {
        vec3 col = texture2D(tPic, vUv).rgb;
        col += texture2D(tBloom, vUv).rgb * uBloom;
        col = mix(col, col * col * (3.0 - 2.0 * col), 0.22);                        // a little contrast
        float l = dot(col, vec3(0.299, 0.587, 0.114));
        col = mix(col, col * vec3(1.03, 1.0, 0.95), smoothstep(0.5, 1.0, l));      // warm lights
        col = mix(col, col * vec3(0.94, 0.98, 1.06), smoothstep(0.45, 0.0, l));    // cool darks
        vec2 q = vUv - 0.5;
        col *= 1.0 - dot(q, q) * 0.38;
        col += (hash(vUv * uRes) - 0.5) * 0.012;
        gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
      }`;
    const BLUR_FS = `
      uniform sampler2D tSrc; uniform vec2 uDir; uniform int uThresh; varying vec2 vUv;
      void main() {
        vec3 s = vec3(0.0); float wsum = 0.0;
        for (int i = -6; i <= 6; i++) {
          float w = exp(-float(i * i) / 18.0);
          vec3 c = texture2D(tSrc, vUv + uDir * float(i)).rgb;
          if (uThresh == 1) c = max(c - 0.80, 0.0) * 3.0;
          s += c * w; wsum += w;
        }
        gl_FragColor = vec4(s / wsum, 1.0);
      }`;
    
    // ---- shared uniforms and materials -----------------------------------------------------------------------------------
    const key = new THREE.Vector3(...S.key).normalize();
    const white = (() => { const t = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1, THREE.RGBAFormat); t.needsUpdate = true; return t; })();
    const G = {                                            // one object per uniform, shared by every material
      uPass: { value: 0 }, uKey: { value: key }, uCam: { value: new THREE.Vector3() },
      tShadow: { value: null }, tShadowFace: { value: null }, uShadowMat: { value: new THREE.Matrix4() }, uShadowTexel: { value: 1 / 2048 },
      uWind: { value: new THREE.Vector3(...S.wind) }, uFlatK: { value: 0 }, uFlatChin: { value: 0 }, uFlatPivot: { value: new THREE.Vector3() },
      uFog: { value: new THREE.Color(0.78, 0.86, 0.92) }, uSunCol: { value: new THREE.Vector3(1.05, 1.0, 0.93) },
      uSkyAmb: { value: new THREE.Vector3(0.90, 0.93, 1.03) },
    };
    const KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 };
    let nextId = 1;
    function ramp(kind, base) {                            // the tones of one base colour: shade, deep shade, light
      const [h, s, v] = hsv(base);
      if (kind === 1) return { shade: tone(base, 0.01, 0.035, 2.05, 0.84), deep: tone(base, 0.99, 0.05, 2.4, 0.66), light: base.clone(),
                               scatter: fromHsv(0.015, 0.62, 0.93) };
      if (kind === 2) return { shade: tone(base, 0.95, 0.045, 1.12, 0.56), deep: tone(base, 0.90, 0.07, 1.10, 0.34), light: tone(base, 0.09, 0.05, 0.52, 1.75) };
      if (kind === 3) return { shade: tone(base, 0.66, 0.10, 3.2, 0.58), deep: tone(base, 0.72, 0.14, 4.0, 0.36), light: tone(base, 0.58, 0.02, 0.5, 1.14) };
      if (kind === 4) return { shade: tone(base, 0.05, 0.05, 1.15, 0.60), deep: tone(base, 0.98, 0.08, 1.2, 0.40), light: tone(base, 0.14, 0.03, 0.55, 1.35) };
      if (kind === 5) return { shade: tone(base, 0.97, 0.05, 1.15, 0.58), deep: tone(base, 0.92, 0.08, 1.2, 0.40), light: tone(base, 0.09, 0.03, 0.75, 1.30) };
      const cool = h > 0.40 && h < 0.86, dark = v < 0.30;
      return { shade: tone(base, cool ? 0.66 : 0.97, cool ? 0.07 : 0.05, 1.15, dark ? 0.55 : 0.60), deep: tone(base, cool ? 0.70 : 0.93, 0.10, 1.2, dark ? 0.32 : 0.40),
               light: tone(base, cool ? 0.50 : 0.12, 0.03, 0.80, dark ? 1.45 : 1.18) };
    }
    function material(V, mesh) {
      const role = mesh.userData.role || "body", m0 = mesh.material, name = mesh.userData.material || "";
      const Rl = V.roles[role] || { mode: "flat", color: "#ff00ff" }, P = (V.paint || {})[role];
      let map = m0.map || null;
      if (map) { map = map.clone(); map.colorSpace = THREE.NoColorSpace; map.needsUpdate = true; }
      const decal = !!(m0.userData && m0.userData.decal);
      const u = { ...G, uKind: { value: 9 }, uAlpha: { value: 0 }, uRecv: { value: 1 }, uDecal: { value: decal ? 1 : 0 }, uFaceTex: { value: 0 },
        uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uShade: { value: new THREE.Color() }, uDeep: { value: new THREE.Color() }, uLight: { value: new THREE.Color() },
        uGold: { value: hex((V.paint.gold && V.paint.gold.base) || "#b08b3f") }, uGoldS: { value: new THREE.Color() },
        uMotif: { value: hex((V.paint.motif && V.paint.motif.base) || "#3a44a0") }, uFlat: { value: new THREE.Color() },
        uEye: { value: V.roles.iris.colors.map(hex) }, uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) }, uScatter: { value: new THREE.Color() },
        uMap: { value: map || white }, uId: { value: new THREE.Vector4((nextId % 250 + 1) / 255, 0.5, 0, 0) }, uThresh: { value: 0.05 }, uSeed: { value: (nextId * 0.618) % 1 },
        uLift: { value: 0 }, uSway: { value: 0 }, uSwaySpan: { value: new THREE.Vector2(1, 1) } };
      nextId++;
      u.uGoldS.value = ramp(4, u.uGold.value).shade;
      let kind = 9;
      if (P) { kind = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); }
      else if (Rl.bands) { kind = 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); }
      if (role === "iris") { kind = 7; u.uAlpha.value = 1; u.uRecv.value = 2; u.uId.value.y = 0; }
      else if (role === "white" || role === "highlight") { kind = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); u.uRecv.value = role === "white" ? 2 : 0; u.uId.value.y = 0; }
      else if (!P && Rl.mode === "flat") { kind = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; u.uId.value.y = 0; }
      if (role === "line" || role === "brow") u.uFlat.value = tone(hex((V.paint.hair && V.paint.hair.base) || "#553322"), 0.97, 0.03, 1.0, role === "line" ? 0.30 : 0.42);
      if (role === "brow") u.uLift.value = 0.04;
      if (role === "mouth" && map) { kind = 10; u.uId.value.y = 0; }
      if (kind <= 5) { const r = ramp(kind, u.uBase.value); u.uShade.value = r.shade; u.uDeep.value = r.deep; u.uLight.value = r.light; if (r.scatter) u.uScatter.value = r.scatter; }
      if (kind === 1) { u.uThresh.value = role === "face" ? -0.02 : 0.02; if (role === "face") { u.uRecv.value = 2; u.uId.value.y = 0.3; if (map) u.uFaceTex.value = 1; } }
      if (role === "shadow") { u.uBase.value = u.uShade.value.clone(); u.uRecv.value = 0; u.uId.value.y = 0; }   // the nose's shadow card
      if (kind === 2) { u.uSway.value = 1; u.uThresh.value = 0.10; if (map && !mesh.geometry.attributes._plate) u.uAlpha.value = 1; }
      if (kind === 3 || kind === 4) u.uThresh.value = 0.12;
      if (/tabard/.test(name)) { u.uSway.value = 2; }
      u.uKind.value = kind;
      const mat = new THREE.ShaderMaterial({ uniforms: u, vertexShader: VS, fragmentShader: FS, side: THREE.DoubleSide, extensions: { derivatives: true } });
      mat.defaultAttributeValues = { ...mat.defaultAttributeValues, _plate: [0, 0, 0, 0] };
      mat.userData = { role, kind, name };
      return mat;
    }
    
    // ---- scene -----------------------------------------------------------------------------------------------------------
    const scene = new THREE.Scene();
    const loader = new GLTFLoader();
    async function loadGlb(file) {
      if (file.endsWith(".json")) {
        const j = await (await fetch(file)).json();
        const bin = Uint8Array.from(atob(j.glb), c => c.charCodeAt(0));
        return await new Promise((ok, bad) => loader.parse(bin.buffer, "", ok, bad));
      }
      return await loader.loadAsync(file);
    }
    const CAMJ = await (await fetch(`${S.site}/camera.json`)).json();
    const chars = [];
    for (const cs of S.chars) {
      const def = CAMJ.characters.find(c => c.name === cs.name), V = def.info;
      const gltf = await loadGlb(`${S.site}/${cs.file || cs.name + ".glb.json"}`);
      const turn = new THREE.Group();
      turn.position.set(...(cs.pos || [0, 0, 0])); turn.rotation.y = THREE.MathUtils.degToRad(cs.yaw || 0);
      turn.add(gltf.scene); scene.add(turn);
      const meshes = [];
      gltf.scene.traverse(o => { if (o.isMesh) { o.material = material(V, o); o.frustumCulled = false; meshes.push(o); } });
      const mixer = new THREE.AnimationMixer(gltf.scene);
      const [clip, t] = cs.clip || ["ref", 0];
      const src = gltf.animations.find(a => a.name === clip);
      if (src) { const a = mixer.clipAction(src); a.play(); a.time = t; mixer.update(0); }
      scene.updateMatrixWorld(true);
      // hanging panels sway from their top edge down
      for (const o of meshes) if (o.material.uniforms.uSway.value === 2) {
        o.geometry.computeBoundingBox(); const b = o.geometry.boundingBox;
        o.material.uniforms.uSwaySpan.value.set(b.max.y, Math.max(b.max.y - b.min.y, 0.05));
      }
      chars.push({ ...cs, gltf, turn, meshes, V });
    }
    let ground = null;
    if (S.ground) {
      const u = { ...G, uKind: { value: 6 }, uAlpha: { value: 0 }, uRecv: { value: 1 }, uDecal: { value: 0 }, uFaceTex: { value: 0 }, uMap: { value: white },
        uBase: { value: new THREE.Color() }, uShade: { value: new THREE.Color() }, uDeep: { value: new THREE.Color() }, uLight: { value: new THREE.Color() },
        uGold: { value: new THREE.Color() }, uGoldS: { value: new THREE.Color() }, uMotif: { value: new THREE.Color() }, uFlat: { value: new THREE.Color() },
        uEye: { value: [new THREE.Color(), new THREE.Color(), new THREE.Color()] }, uSkinRef: { value: new THREE.Vector3(1, 1, 1) }, uScatter: { value: new THREE.Color() },
        uId: { value: new THREE.Vector4(0, 1.0, 0, 0) }, uThresh: { value: 0 }, uSeed: { value: 0 }, uLift: { value: 0 }, uSway: { value: 0 }, uSwaySpan: { value: new THREE.Vector2(1, 1) } };
      const mat = new THREE.ShaderMaterial({ uniforms: u, vertexShader: VS, fragmentShader: FS, side: THREE.DoubleSide, extensions: { derivatives: true } });
      mat.defaultAttributeValues = { ...mat.defaultAttributeValues, _plate: [0, 0, 0, 0] };
      mat.userData = { role: "grass", kind: 6 };
      ground = new THREE.Mesh(new THREE.PlaneGeometry(600, 600, 1, 1).rotateX(-Math.PI / 2), mat);
      ground.frustumCulled = false; scene.add(ground);
    }
    
    // ---- camera and light -----------------------------------------------------------------------------------------------
    const aspect = S.w / S.h;
    const hfov = 2 * Math.atan(18 / S.cam.lens), vfov = 2 * Math.atan(Math.tan(hfov / 2) / aspect);
    const camera = new THREE.PerspectiveCamera(THREE.MathUtils.radToDeg(vfov), aspect, 0.3, 400);
    camera.position.set(...S.cam.pos); camera.lookAt(new THREE.Vector3(...S.cam.target)); camera.updateMatrixWorld(true);
    G.uCam.value.copy(camera.position);
    const allMeshes = () => [...chars.flatMap(c => c.meshes), ...(ground ? [ground] : [])];
    const box = new THREE.Box3();
    for (const c of chars) for (const o of c.meshes) { o.geometry.computeBoundingBox(); box.union(o.geometry.boundingBox.clone().applyMatrix4(c.turn.matrixWorld)); }
    box.expandByScalar(0.9);
    const ctr = box.getCenter(new THREE.Vector3()), rad = box.getSize(new THREE.Vector3()).length() / 2;
    const lcam = new THREE.OrthographicCamera(-rad, rad, rad, -rad, 0.1, rad * 4 + 10);
    lcam.position.copy(ctr).addScaledVector(key, rad * 2 + 2); lcam.lookAt(ctr); lcam.updateMatrixWorld(true);
    G.uShadowMat.value.multiplyMatrices(lcam.projectionMatrix, lcam.matrixWorldInverse);
    const SH = 4096;
    G.uShadowTexel.value = 1 / SH;
    const mkShadow = () => { const rt = new THREE.WebGLRenderTarget(SH, SH, { depthTexture: new THREE.DepthTexture(SH, SH, THREE.UnsignedIntType) });
      rt.depthTexture.minFilter = rt.depthTexture.magFilter = THREE.NearestFilter; return rt; };
    const rtShadow = mkShadow(), rtShadowFace = mkShadow();
    
    // Flattice: the head squashed toward a plane facing the camera, through the head bone; full above the chin
    if (S.flat > 0 && chars.length) {
      const c = chars[0], head = c.gltf.scene.getObjectByName("J_Bip_C_Head");
      const face = c.meshes.find(o => o.userData.role === "face");
      if (head && face) {
        face.geometry.computeBoundingBox();
        G.uFlatChin.value = face.geometry.boundingBox.min.y + 0.01;
        G.uFlatPivot.value.copy(head.getWorldPosition(new THREE.Vector3())).applyMatrix4(camera.matrixWorldInverse);
        // only her head's meshes take it: the weight is by bind-pose height, which would also catch a raised arm
        G.uFlatK.value = S.flat;
      }
    }
    
    // ---- passes ---------------------------------------------------------------------------------------------------------
    const FACE_PARTS = new Set(["iris", "white", "highlight", "line", "brow", "mouth", "shadow"]);
    const show = fn => allMeshes().forEach(o => { o.visible = fn(o); });
    function renderAll() {
      const g = R.getContext();
      // 1. shadows: everything but the ground and the face's flat parts; then, for the face, everything but the head's own skin
      G.uPass.value = 2;
      show(o => o !== ground && !FACE_PARTS.has(o.material.userData.role));
      R.setRenderTarget(rtShadow); R.clear(); R.render(scene, lcam);
      show(o => o !== ground && !FACE_PARTS.has(o.material.userData.role) && o.material.userData.role !== "face" && o.material.userData.role !== "body");
      R.setRenderTarget(rtShadowFace); R.clear(); R.render(scene, lcam);
      G.tShadow.value = rtShadow.depthTexture; G.tShadowFace.value = rtShadowFace.depthTexture;
      // 2. colour
      const mk = () => { const rt = new THREE.WebGLRenderTarget(W, H, { depthTexture: new THREE.DepthTexture(W, H, THREE.UnsignedIntType),
        minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter }); return rt; };
      const rtColor = mk(), rtInfo = mk();
      rtInfo.texture.minFilter = rtInfo.texture.magFilter = THREE.NearestFilter;
      G.uPass.value = 0; show(() => true);
      R.setClearColor(0x000000, 0);
      R.setRenderTarget(rtColor); R.clear(); R.render(scene, camera);
      // 3. line data: the face's painted parts are left out, so the skin under them answers for them
      G.uPass.value = 1; show(o => !FACE_PARTS.has(o.material.userData.role));
      R.setRenderTarget(rtInfo); R.clear(); R.render(scene, camera);
      show(() => true);
      // 4. the picture
      const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2)), qs = new THREE.Scene(), qc = new THREE.Camera(); qs.add(quad);
      const rimW = new THREE.Vector3(...S.rim).normalize().transformDirection(camera.matrixWorldInverse);
      const rimDir = new THREE.Vector2(rimW.x, rimW.y); if (rimDir.length() < 1e-3) rimDir.set(1, 0); rimDir.normalize();
      const keyV = key.clone().transformDirection(camera.matrixWorldInverse);
      quad.material = new THREE.ShaderMaterial({ vertexShader: QUAD_VS, fragmentShader: COMP_FS, uniforms: {
        tColor: { value: rtColor.texture }, tInfo: { value: rtInfo.texture }, tDepth: { value: rtColor.depthTexture }, uRes: { value: new THREE.Vector2(W, H) },
        uNear: { value: camera.near }, uFar: { value: camera.far }, uInvProj: { value: camera.projectionMatrixInverse }, uCamWorld: { value: camera.matrixWorld },
        uKey: { value: key }, uRimDir: { value: rimDir }, uPx: { value: H / 1080 }, uLine: { value: S.line }, uKeyScr: { value: new THREE.Vector2(keyV.x, keyV.y) },
        uZenith: { value: new THREE.Color(0.28, 0.50, 0.82) }, uHorizon: { value: new THREE.Color(0.80, 0.89, 0.94) }, uFog: G.uFog, uSky: { value: S.sky ? 1 : 0 } } });
      const rtPic = new THREE.WebGLRenderTarget(W, H, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });
      R.setRenderTarget(rtPic); R.render(qs, qc);
      // 5. bloom at a quarter size, then the grade at output size (the supersampled picture read with linear filtering)
      const bw = Math.round(S.w / 4), bh = Math.round(S.h / 4);
      const rtA = new THREE.WebGLRenderTarget(bw, bh, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter }), rtB = rtA.clone();
      const blur = (src, dst, dir, th) => { quad.material = new THREE.ShaderMaterial({ vertexShader: QUAD_VS, fragmentShader: BLUR_FS,
        uniforms: { tSrc: { value: src }, uDir: { value: dir }, uThresh: { value: th } } }); R.setRenderTarget(dst); R.render(qs, qc); };
      blur(rtPic.texture, rtA, new THREE.Vector2(1.6 / bw, 0), 1); blur(rtA.texture, rtB, new THREE.Vector2(0, 1.6 / bh), 0);
      blur(rtB.texture, rtA, new THREE.Vector2(3.0 / bw, 0), 0); blur(rtA.texture, rtB, new THREE.Vector2(0, 3.0 / bh), 0);
      quad.material = new THREE.ShaderMaterial({ vertexShader: QUAD_VS, fragmentShader: FINAL_FS, uniforms: {
        tPic: { value: rtPic.texture }, tBloom: { value: rtB.texture }, uBloom: { value: S.bloom }, uRes: { value: new THREE.Vector2(S.w, S.h) } } });
      R.setRenderTarget(null); R.render(qs, qc);
      void g;
    }
    try {
      renderAll();
      $("out").textContent = R.domElement.toDataURL("image/png");
      document.title = "stage ready";
    } catch (e) { $("out").textContent = "error: " + (e && e.stack || e); document.title = "stage failed"; }
    </script>
    </body>
    </html>
    

    result, 1 line

    File created successfully at: ~/Projects/lowmarch-fable52/tools/whole/stage/stage.html (file state is current in your context — no need to Read it back)
  • Bashcd ~/Projects/lowmarch-fable52 && python3 - <<'E'

    command

    cd ~/Projects/lowmarch-fable52 && python3 - <<'E'
    p="tools/whole/stage/stage.html"; s=open(p).read()
    old='''  gltf.scene.traverse(o => { if (o.isMesh) { o.material = material(V, o); o.frustumCulled = false; meshes.push(o); } });'''
    new='''  gltf.scene.traverse(o => { if (o.isMesh) { o.material = material(V, o); o.frustumCulled = false; meshes.push(o); } });
      if (chars.length) for (const o of meshes) o.material.uniforms.uFlatK = { value: 0 };     // Flattice is the first character's'''
    assert old in s; s=s.replace(old,new)
    s=s.replace("sky: 1, ground: 1, bloom: 0.5,","sky: 1, ground: 1, bloom: 0.35,")
    open(p,"w").write(s)
    E
    cat > tools/whole/stage_shot.py <<'E'
    """Shoot one picture with the stage renderer (tools/whole/stage/stage.html), headless.
    
      python3 tools/whole/stage_shot.py SITE_DIR SPEC.json OUT.png
    
    SITE_DIR: a built site (tools/whole/build.py): <name>.glb.json and camera.json. SPEC (all optional):
      w, h, ss (supersampling, 2)        chars [{name, clip [name, seconds], pos [x, y, z], yaw}]
      cam {lens (mm on a 36 mm frame), pos, target}        key [x, y, z] (toward the light), rim [x, y, z]
      flat (Flattice on the first character's head, 0..1)  wind [x, y, z] (metres of drift at a free tip)
      sky, ground (0 or 1), bloom, line (ink width scale)
    Yaw 0 faces +z (the GLB's front); 90 faces +x. The page is served from a scratch copy beside links to the site.
    """
    import base64
    import json
    import os
    import re
    import shutil
    import socket
    import subprocess
    import sys
    import tempfile
    import time
    import urllib.parse
    
    HERE = os.path.dirname(os.path.abspath(__file__))
    
    
    def shoot(site, spec, out):
        d = tempfile.mkdtemp(prefix="stage_", dir=os.path.dirname(os.path.abspath(out)))
        try:
            for f in os.listdir(site):
                if f.endswith((".json", ".glb")):
                    os.symlink(os.path.join(os.path.abspath(site), f), os.path.join(d, f))
            shutil.copy(os.path.join(HERE, "stage", "stage.html"), os.path.join(d, "stage.html"))
            s = socket.socket()
            s.bind(("127.0.0.1", 0))
            port = s.getsockname()[1]
            s.close()
            server = subprocess.Popen([sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", d],
                                      stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            try:
                time.sleep(0.5)
                url = f"http://127.0.0.1:{port}/stage.html?spec={urllib.parse.quote(json.dumps(spec))}"
                r = subprocess.run([os.environ.get("CHROMIUM", "/snap/bin/chromium"), "--headless=new", "--use-angle=swiftshader",
                                    "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "--window-size=1280,900",
                                    "--virtual-time-budget=600000", "--enable-logging=stderr", "--v=0", "--dump-dom", url],
                                   capture_output=True, text=True, timeout=1200)
                m = re.search(r'id="out"[^>]*>[redacted: data-URI prefix]([A-Za-z0-9+/=]+)<', r.stdout)
                if not m:
                    err = re.search(r'id="out"[^>]*>([^<]*)<', r.stdout)
                    logs = "\n".join(l for l in r.stderr.splitlines() if "CONSOLE" in l or "ERROR" in l.upper())[-3000:]
                    raise SystemExit("FAILED " + (err.group(1)[:1500] if err else "") + "\n" + logs)
                open(out, "wb").write(base64.b64decode(m.group(1)))
            finally:
                server.terminate()
        finally:
            shutil.rmtree(d, ignore_errors=True)
    
    
    if __name__ == "__main__":
        t0 = time.time()
        shoot(sys.argv[1], json.load(open(sys.argv[2])), sys.argv[3])
        print(sys.argv[3], f"{time.time() - t0:.0f}s")
    E
    mkdir -p review/out/stage && cd review/out/stage && cat > s1.json <<'E'
    {"w": 960, "h": 540, "ss": 2, "chars": [{"name": "wren", "clip": ["ref", 0], "pos": [0,0,0], "yaw": 25}],
     "cam": {"lens": 50, "pos": [0.3, 1.25, 4.6], "target": [0, 0.98, 0]}}
    E
    python3 ~/Projects/lowmarch-fable52/tools/whole/stage_shot.py ~/Projects/lowmarch-fable52/review/out/whole2/site s1.json s1.png 2>&1 | tail -30

    result, 1 line

    s1.png 19s

The new renderer ran on its first try. Looking at its first picture.

  • Read~/Projects/lowmarch-fable52/review/out/stage/s1.png

    input

    {
      "file_path": "~/Projects/lowmarch-fable52/review/out/stage/s1.png"
    }

    result

    no output

    s1.jpg
    s1.jpg
  • Bashcd ~/Projects/lowmarch-fable52 && python3 - <<'E'

    command

    cd ~/Projects/lowmarch-fable52 && python3 - <<'E'
    p="tools/whole/stage/stage.html"; s=open(p).read()
    R=[
    # metal: more form
    ('''    vec3 col = mix(shade, base, lit);
        col = mix(col, deep, (1.0 - lit) * st(-r.y, 0.25, 0.04) * 0.75);            // the ground in the plate's shade
        col = mix(col, light, lit * st(up + (hgt >= 0.0 ? (hgt - 0.5) * 0.5 : 0.0), 0.70, 0.03) * 0.85);   // sky on what faces up
        float hl = dot(n, normalize(uKey + v));
        col = mix(col, vec3(1.0, 0.99, 0.95), lit * st(hl, 0.965, 0.006));          // the streak''',
     '''    float ndl = dot(n, uKey);
        vec3 plate = base * 0.90;
        vec3 col = mix(shade, plate, lit);
        col = mix(col, deep, (1.0 - lit) * st(-r.y, 0.25, 0.04) * 0.75);            // the ground in the plate's shade
        col = mix(col, mix(plate, shade, 0.55), lit * st(-r.y, 0.30, 0.03) * 0.8);  // and, lighter, in its light
        col = mix(col, light, lit * st(ndl + up * 0.25, 0.86, 0.02));               // the light's own shape
        if (hgt >= 0.0) col *= mix(0.90, 1.05, hgt);                                // a plate darkens toward its foot
        float hl = dot(n, normalize(uKey + v));
        col = mix(col, vec3(1.0, 0.99, 0.95), lit * st(hl, 0.972, 0.005));          // the streak'''),
    # skin band softer
    ('''      col = mix(col, uScatter, band * 0.35 * (1.0 - lit * 0.6));''','''      col = mix(col, uScatter, band * 0.22 * (1.0 - lit * 0.5));'''),
    ('''  if (kind === 1) return { shade: tone(base, 0.01, 0.035, 2.05, 0.84), deep: tone(base, 0.99, 0.05, 2.4, 0.66), light: base.clone(),
                               scatter: fromHsv(0.015, 0.62, 0.93) };''','''  if (kind === 1) return { shade: tone(base, 0.02, 0.03, 1.55, 0.88), deep: tone(base, 0.99, 0.05, 2.2, 0.68), light: base.clone(),
                               scatter: fromHsv(0.02, 0.50, 0.95) };'''),
    ('''  if (kind === 1) { u.uThresh.value = role === "face" ? -0.02 : 0.02;''','''  if (kind === 1) { u.uThresh.value = role === "face" ? -0.32 : 0.02;       // a face stays lit until the light is well to its side'''),
    # ground calmer
    ('''      vec3 g0 = vec3(0.26, 0.42, 0.25), g1 = vec3(0.40, 0.56, 0.28), g2 = vec3(0.60, 0.70, 0.36), g3 = vec3(0.50, 0.50, 0.30);
          col = mix(g0, g1, smoothstep(0.42, 0.50, a));
          col = mix(col, g2, smoothstep(0.52, 0.58, b) * 0.75);
          col = mix(col, g3, smoothstep(0.62, 0.66, fbm(vec3(p * 0.9 + 30.0, 4.0))) * 0.5);   // dry patches''',
     '''      vec3 g0 = vec3(0.33, 0.50, 0.27), g1 = vec3(0.42, 0.58, 0.29), g2 = vec3(0.54, 0.67, 0.33), g3 = vec3(0.52, 0.56, 0.31);
          col = mix(g0, g1, smoothstep(0.44, 0.52, a));
          col = mix(col, g2, smoothstep(0.53, 0.57, b) * 0.6);
          col = mix(col, g3, smoothstep(0.60, 0.66, fbm(vec3(p * 0.35 + 30.0, 4.0))) * 0.45);  // dry patches'''),
    ('''      float a = fbm(vec3(p * 0.55, 0.0)), b = fbm(vec3(p * 2.6 + 9.0, 1.0)), c = vnoise(vec3(p.x * 26.0, p.y * 7.0, 2.0));''',
     '''      float a = fbm(vec3(p * 1.3, 0.0)), b = fbm(vec3(p * 5.0 + 9.0, 1.0)), c = vnoise(vec3(p.x * 26.0, p.y * 7.0, 2.0));'''),
    # horizon: no ink on ground edge
    ('''      if (z0 - z1 > gap) { edgeOut = 1.0; if (z1 < nearZ) { nearZ = z1; nearCol = texture2D(tColor, p1).rgb; } }   // something nearer beside us: its outline''',
     '''      if (z0 - z1 > gap && texture2D(tInfo, p1).a < 0.90) { edgeOut = 1.0; if (z1 < nearZ) { nearZ = z1; nearCol = texture2D(tColor, p1).rgb; } }   // something nearer beside us (not the ground): its outline'''),
    # hills
    ('''    col = mix(col, mix(vec3(0.56, 0.66, 0.80), uHorizon, 0.45), smoothstep(0.004, -0.004, d.y - h1));
        col = mix(col, mix(vec3(0.36, 0.50, 0.50), uHorizon, 0.30), smoothstep(0.003, -0.003, d.y - h2));''',
     '''    col = mix(col, mix(vec3(0.50, 0.62, 0.80), uHorizon, 0.55), smoothstep(0.003, -0.003, d.y - h1 * 1.5));
        col = mix(col, mix(vec3(0.38, 0.55, 0.52), uHorizon, 0.38), smoothstep(0.002, -0.002, d.y - h2 * 0.8));
        col = mix(col, uFog, smoothstep(0.02, -0.01, d.y) * 0.85);                  // the ground's far edge melts into haze'''),
    ]
    for a,b in R:
        assert a in s, a[:60]; s=s.replace(a,b,1)
    open(p,"w").write(s)
    E
    cd review/out/stage && cat > s2.json <<'E'
    {"w": 960, "h": 720, "ss": 2, "chars": [{"name": "wren", "clip": ["ref", 0], "pos": [0,0,0], "yaw": 30}],
     "cam": {"lens": 70, "pos": [0.25, 1.42, 2.3], "target": [0, 1.36, 0]}}
    E
    R=~/Projects/lowmarch-fable52; (python3 $R/tools/whole/stage_shot.py $R/review/out/whole2/site s1.json s1.png & python3 $R/tools/whole/stage_shot.py $R/review/out/whole2/site s2.json s2.png & wait) 2>&1 | tail -20

    result, 20 lines

    [2223:2459:1110/193543.390130:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2223:2223:1110/193543.476620:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2223:2459:1110/193543.483769:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2223:2223:1110/193543.577288:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2223:2223:1110/193544.259717:INFO:CONSOLE:423] "Uncaught SyntaxError: Unexpected reserved word", source: http://127.0.0.1:49459/stage.html?spec=%7B%22w%22%3A%20960%2C%20%22h%22%3A%20540%2C%20%22ss%22%3A%202%2C%20%22chars%22%3A%20%5B%7B%22name%22%3A%20%22wren%22%2C%20%22clip%22%3A%20%5B%22ref%22%2C%200%5D%2C%20%22pos%22%3A%20%5B0%2C%200%2C%200%5D%2C%20%22yaw%22%3A%2025%7D%5D%2C%20%22cam%22%3A%20%7B%22lens%22%3A%2050%2C%20%22pos%22%3A%20%5B0.3%2C%201.25%2C%204.6%5D%2C%20%22target%22%3A%20%5B0%2C%200.98%2C%200%5D%7D%7D (423)
    FAILED 
    1110/193543.127035:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2226:2226:1110/193543.155787:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2226:2481:1110/193543.160133:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2226:2226:1110/193543.212005:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2226:2481:1110/193543.212655:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2226:2226:1110/193543.219191:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2226:2226:1110/193543.252810:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.Properties.GetAll: object_path= /org/freedesktop/UPower/devices/DisplayDevice: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.UPower was not provided by any .service files
    [2226:2226:1110/193543.255269:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2226:2481:1110/193543.257751:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2226:2226:1110/193543.363941:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2226:2481:1110/193543.364160:ERROR:dbus/bus.cc:406] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
    [2226:2226:1110/193543.372651:ERROR:dbus/object_proxy.cc:572] Failed to call method: org.freedesktop.DBus.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: 
    [2226:2226:1110/193544.529869:INFO:CONSOLE:423] "Uncaught SyntaxError: Unexpected reserved word", source: http://127.0.0.1:50089/stage.html?spec=%7B%22w%22%3A%20960%2C%20%22h%22%3A%20720%2C%20%22ss%22%3A%202%2C%20%22chars%22%3A%20%5B%7B%22name%22%3A%20%22wren%22%2C%20%22clip%22%3A%20%5B%22ref%22%2C%200%5D%2C%20%22pos%22%3A%20%5B0%2C%200%2C%200%5D%2C%20%22yaw%22%3A%2030%7D%5D%2C%20%22cam%22%3A%20%7B%22lens%22%3A%2070%2C%20%22pos%22%3A%20%5B0.25%2C%201.42%2C%202.3%5D%2C%20%22target%22%3A%20%5B0%2C%201.36%2C%200%5D%7D%7D (423)
    [2226:2226:1110/193544.797050:ERROR:mojo/public/cpp/bindings/lib/interface_endpoint_client.cc:652] Message 88180291 rejected by interface blink.mojom.FrameWidgetHost
  • Bashcd ~/Projects/lowmarch-fable52 && sed -n 421,424p tools/whole/stage/stage.html | cut -c1-160; python3 - <<'E'

    command

    cd ~/Projects/lowmarch-fable52 && sed -n 421,424p tools/whole/stage/stage.html | cut -c1-160; python3 - <<'E'
    p="tools/whole/stage_shot.py"; s=open(p).read()
    s=s.replace('''logs = "\\n".join(l for l in r.stderr.splitlines() if "CONSOLE" in l or "ERROR" in l.upper())[-3000:]''','''logs = "\\n".join(l.split("source:")[0][-400:] for l in r.stderr.splitlines() if "CONSOLE" in l)[-3000:]''')
    open(p,"w").write(s)
    E

    result, 4 lines

      return await loader.loadAsync(file);
    }
    const CAMJ = await (await fetch(`${S.site}/camera.json`)).json();
    const chars = [];
  • Bashcd ~/Projects/lowmarch-fable52 && python3 - <<'E'

    command

    cd ~/Projects/lowmarch-fable52 && python3 - <<'E'
    p="tools/whole/stage/stage.html"; s=open(p).read()
    old='''? -0.32 : 0.02;       // a face stays lit until the light is well to its side'''
    assert old in s
    s=s.replace(old,'''? -0.32 : 0.02;   /* a face stays lit until the light is well to its side */''')
    open(p,"w").write(s)
    E
    cd review/out/stage && R=~/Projects/lowmarch-fable52; (python3 $R/tools/whole/stage_shot.py $R/review/out/whole2/site s1.json s1.png & python3 $R/tools/whole/stage_shot.py $R/review/out/whole2/site s2.json s2.png & wait) 2>&1 | tail -5

    result, 2 lines

    s1.png 28s
    s2.png 30s