Subagent: Model export and lens shot

agent (cont.)

+5:45
  • Write~/Projects/lowmarch-fable52/tools/whole/export_model.py

    input

    ~/Projects/lowmarch-fable52/tools/whole/export_model.py
    
    """Export one built character as a standalone rigged model: a binary glTF 2.0 that a stock loader opens (three.js
    GLTFLoader, Blender's importer) with no knowledge of this project.
    
      python3 tools/whole/export_model.py SITE_DIR NAME OUT.glb [--check PNG [CLIP [SECONDS]]]
    
    Reads SITE_DIR/NAME.glb.json (tools/export_glb.py export_skinned, base64-wrapped by review/vroid-02/build.py) and the
    character's scene_info in SITE_DIR/camera.json. Geometry, skin weights, joints and clips pass through as built.
    Materials are rewritten per role (the node's extras.role) from the paint the painted page would use, as plain
    metallic-roughness materials: sRGB hex turned linear (export_skinned writes hex as is, so colours read pale),
    hair and iris textures recoloured to the character's own (the VRoid sample's textures are navy and blue), lashes and
    brows inked in their flat colour, the eye highlight blended (its alpha is mostly under 0.5, so a mask cut it all),
    shadow cards (the nose) a faint blend of the skin's shade, steel and gold half metallic, everything else 0.
    Duplicate materials are merged; textures nothing uses are dropped.
    Kept for the painted shader: each node's extras (group, role, material), each material's extras (role, kind, base,
    ramp), the _PLATE attribute, and the root node's extras.lowmarch: the whole scene_info (roles and their bands, paint,
    lights, capsules, cloth grids, mouth curve, face marks) plus a VRM humanoid map (VRoid's J_Bip names are fixed).
    Axes are glTF's: +Y up, metres, facing +Z, feet at y 0, in the reference pose the site was built in.
    --check: shoot the file in headless Chromium with three.js GLTFLoader, a PerspectiveCamera, its own materials and a
    plain light, posed at CLIP (default attack) and SECONDS (default its middle), beside the reference pose from the front.
    """
    import base64
    import colorsys
    import http.server
    import io
    import json
    import os
    import re
    import shutil
    import socket
    import struct
    import subprocess
    import sys
    import threading
    import time
    
    import numpy as np
    from PIL import Image
    
    ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    
    # VRM 0.x humanoid bone -> VRoid's joint name (the same on every VRoid export)
    HUMANOID = dict(hips="C_Hips", spine="C_Spine", chest="C_Chest", upperChest="C_UpperChest", neck="C_Neck", head="C_Head",
                    leftEye="L_FaceEye", rightEye="R_FaceEye")
    for s, side in (("L", "left"), ("R", "right")):
        HUMANOID.update({f"{side}Shoulder": f"{s}_Shoulder", f"{side}UpperArm": f"{s}_UpperArm", f"{side}LowerArm": f"{s}_LowerArm",
                         f"{side}Hand": f"{s}_Hand", f"{side}UpperLeg": f"{s}_UpperLeg", f"{side}LowerLeg": f"{s}_LowerLeg",
                         f"{side}Foot": f"{s}_Foot", f"{side}Toes": f"{s}_ToeBase"})
        for f in ("Thumb", "Index", "Middle", "Ring", "Little"):
            for k, part in enumerate(("Proximal", "Intermediate", "Distal")):
                HUMANOID[f"{side}{f}{part}"] = f"{s}_{f}{k + 1}"
    
    
    def joint_name(short):
        return ("J_Adj_" if short.endswith("FaceEye") else "J_Bip_") + short
    
    
    def lin(h):
        """sRGB hex -> linear RGB (glTF factors are linear)."""
        c = np.array([int(h.lstrip("#")[i:i + 2], 16) / 255 for i in (0, 2, 4)])
        return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4).round(4).tolist()
    
    
    def srgb(h):
        return np.array([int(h.lstrip("#")[i:i + 2], 16) for i in (0, 2, 4)], np.float64)
    
    
    def read_glb(b):
        magic, ver, _ = struct.unpack_from("<4sII", b, 0)
        assert magic == b"glTF" and ver == 2, "not a glTF 2 binary"
        n = struct.unpack_from("<I", b, 12)[0]
        j = json.loads(b[20:20 + n])
        m = struct.unpack_from("<I", b, 20 + n)[0]
        return j, b[28 + n:28 + n + m]
    
    
    def write_glb(j, bin_, path):
        js = json.dumps(j, separators=(",", ":")).encode()
        js += b" " * ((4 - len(js) % 4) % 4)
        bin_ = bytes(bin_) + b"\0" * ((4 - len(bin_) % 4) % 4)
        out = struct.pack("<4sII", b"glTF", 2, 28 + len(js) + len(bin_))
        out += struct.pack("<I4s", len(js), b"JSON") + js + struct.pack("<I4s", len(bin_), b"BIN\x00") + bin_
        open(path, "wb").write(out)
        return len(out)
    
    
    # ---- texture bakes (sRGB in, sRGB out) ---------------------------------------------------------------------------------
    def lum(rgb):
        return rgb @ np.array([0.299, 0.587, 0.114])
    
    
    def bake_hair(rgba, base):
        """The strands' light and dark kept as detail on the character's hair colour (the page's 3D view does this in its
        shader, against a fixed 0.5; this texture's own median is the reference, so a dark sample stays the right hue)."""
        rgb = rgba[..., :3].astype(np.float64)
        L, op = lum(rgb), rgba[..., 3] > 128
        ref = max(np.median(L[op]) if op.any() else 128.0, 8.0)
        d = 1 + (np.clip(L / ref, 0.45, 1.35) - 1) * 0.6
        out = rgba.copy()
        out[..., :3] = np.clip(srgb(base)[None, None] * d[..., None], 0, 255).round()
        return out
    
    
    def bake_tint(rgba, base):
        """The face texture moved so its skin (the median of its opaque texels) lands on the paint's skin."""
        rgb = rgba[..., :3].astype(np.float64)
        op = rgba[..., 3] > 128
        k = srgb(base) / np.maximum(np.median(rgb[op], 0), 1)
        out = rgba.copy()
        out[..., :3] = np.clip(rgb * k, 0, 255).round()
        return out
    
    
    def bake_iris(rgba, colors):
        """The iris by its light: dark rim to the middle colour to the light colour; the sample's own white glints kept."""
        rgb = rgba[..., :3].astype(np.float64)
        L, op = lum(rgb), rgba[..., 3] > 128
        lo, hi = np.percentile(L[op], [5, 92]) if op.any() else (0, 255)
        t = np.clip((L - lo) / max(hi - lo, 1), 0, 1)[..., None]
        c0, c1, c2 = (srgb(c)[None, None] for c in colors)
        col = np.where(t < 0.5, c0 + (c1 - c0) * (t / 0.5), c1 + (c2 - c1) * ((t - 0.5) / 0.5))
        glint = (L > hi) & (rgb.min(-1) > 200)
        col[glint] = rgb[glint]
        out = rgba.copy()
        out[..., :3] = col.round()
        return out
    
    
    def bake_ink(rgba, color):
        out = rgba.copy()
        out[..., :3] = srgb(color)
        return out
    
    
    # ---- materials ---------------------------------------------------------------------------------------------------------
    def material_for(role, old, info, tex_of):
        """A standard material for one piece. old: export_skinned's material. tex_of(old index, bake or None) -> new texture
        index. Returns the material dict."""
        paint, roles = info.get("paint", {}), info.get("roles", {})
        P, Rl = paint.get(role), roles.get(role, {})
        kind = P["kind"] if P else ("flat" if Rl.get("mode") == "flat" else role)
        pbr = old.get("pbrMetallicRoughness", {})
        tex = pbr.get("baseColorTexture", {}).get("index")
        decal = bool((old.get("extras") or {}).get("decal"))
        base = (P or {}).get("base") or Rl.get("color") or \
            (Rl["bands"][min(1, len(Rl["bands"]) - 1)][1] if Rl.get("bands") else None)
        m = dict(name=old.get("name", role), doubleSided=True,
                 pbrMetallicRoughness=dict(metallicFactor=0.0, roughnessFactor=0.85),
                 extras=dict(role=role, kind=kind, **({"base": base} if base else {})))
        if P and P.get("ramp"):
            m["extras"]["ramp"] = P["ramp"]
        if Rl.get("bands"):
            m["extras"]["bands"] = Rl["bands"]
        pm = m["pbrMetallicRoughness"]
    
        def colour(h, a=1.0):
            pm["baseColorFactor"] = lin(h) + [a]
    
        if tex is not None and decal:                         # a design mask (tools/plates.py), not a colour: kept aside
            m["extras"].update(decal=True, decal_texture=tex_of(tex, None))
            tex = None
        if role == "shadow":                                  # shade cards: the skin's shade, faint
            colour((P or {}).get("ramp", [None, base])[1] or base or "#c6a296", 0.35)
            m["alphaMode"] = "BLEND"
        elif tex is not None and role == "hair" and base:
            pm["baseColorTexture"] = dict(index=tex_of(tex, lambda a: bake_hair(a, base)))
            m["alphaMode"], m["alphaCutoff"] = "MASK", 0.5
        elif tex is not None and role == "face" and base:
            pm["baseColorTexture"] = dict(index=tex_of(tex, lambda a: bake_tint(a, base)))
        elif tex is not None and role == "iris" and Rl.get("colors"):
            pm["baseColorTexture"] = dict(index=tex_of(tex, lambda a: bake_iris(a, Rl["colors"])))
            m["alphaMode"], m["alphaCutoff"] = "MASK", 0.5
            pm["roughnessFactor"] = 0.4
        elif tex is not None and role in ("line", "brow") and Rl.get("color"):
            pm["baseColorTexture"] = dict(index=tex_of(tex, lambda a: bake_ink(a, Rl["color"])))
            m["alphaMode"], m["alphaCutoff"] = "MASK", 0.5 if role == "line" else 0.35
        elif tex is not None and role == "highlight":
            pm["baseColorTexture"] = dict(index=tex_of(tex, None))
            m["alphaMode"] = "BLEND"
            m["emissiveFactor"] = [0.6, 0.6, 0.6]
            m["emissiveTexture"] = dict(index=pm["baseColorTexture"]["index"])
        elif tex is not None:                                 # mouth, eye white, kit hair strands: the texture as painted
            pm["baseColorTexture"] = dict(index=tex_of(tex, None))
            if old.get("alphaMode"):
                m["alphaMode"], m["alphaCutoff"] = old["alphaMode"], old.get("alphaCutoff", 0.5)
            if "baseColorFactor" in pbr:                      # a tint export_skinned set: linear now
                pm["baseColorFactor"] = lin("#%02x%02x%02x" % tuple(round(c * 255) for c in pbr["baseColorFactor"][:3])) + [1.0]
        elif base:
            colour(base)
        elif "baseColorFactor" in pbr:
            pm["baseColorFactor"] = lin("#%02x%02x%02x" % tuple(round(c * 255) for c in pbr["baseColorFactor"][:3])) + [1.0]
        if kind in ("steel", "gold"):
            pm.update(metallicFactor=0.5, roughnessFactor=0.4)
        elif kind == "leather":
            pm["roughnessFactor"] = 0.7
        elif kind == "skin":
            pm["roughnessFactor"] = 0.75
        return m
    
    
    def export(site, name, out):
        j, bin_ = read_glb(base64.b64decode(json.load(open(os.path.join(site, f"{name}.glb.json")))["glb"]))
        cam = json.load(open(os.path.join(site, "camera.json")))
        entry = next((c for c in cam["characters"] if c["name"] == name), None)
        if entry is None:
            raise SystemExit(f"{name}: not in {site}/camera.json")
        info = entry["info"]
        view = lambda vi: bin_[j["bufferViews"][vi].get("byteOffset", 0):][:j["bufferViews"][vi]["byteLength"]]
        images = []                                           # (png bytes) of the new file
        textures, tex_key = [], {}
    
        def tex_of(old, bake):
            key = (old, bake.__code__.co_name if bake else None, id(bake) if bake else None)
            src = j["images"][j["textures"][old]["source"]]
            if bake is None:
                key = (old, None)
                if key not in tex_key:
                    images.append(bytes(view(src["bufferView"])))
                    textures.append(dict(source=len(images) - 1, sampler=0))
                    tex_key[key] = len(textures) - 1
                return tex_key[key]
            a = np.asarray(Image.open(io.BytesIO(view(src["bufferView"]))).convert("RGBA"))
            b = io.BytesIO()
            Image.fromarray(bake(a).astype(np.uint8)).save(b, "PNG", optimize=True)
            png = b.getvalue()
            for k, im in enumerate(images):                  # the same bake twice (two hair pieces on one map): one image
                if im == png:
                    textures.append(dict(source=k, sampler=0))
                    return len(textures) - 1
            images.append(png)
            textures.append(dict(source=len(images) - 1, sampler=0))
            return len(textures) - 1
    
        mats, mat_key = [], {}
        for nd in j["nodes"]:
            if "mesh" not in nd:
                continue
            role = (nd.get("extras") or {}).get("role", "body")
            for pr in j["meshes"][nd["mesh"]]["primitives"]:
                m = material_for(role, j["materials"][pr["material"]], info, tex_of)
                k = json.dumps(m, sort_keys=True)
                if k not in mat_key:
                    mat_key[k] = len(mats)
                    mats.append(m)
                pr["material"] = mat_key[k]
        # repack the buffer: the accessors' views as they were, then the images
        nb, views, remap = bytearray(), [], {}
    
        def put(data, target=None):
            while len(nb) % 4:
                nb.append(0)
            v = dict(buffer=0, byteOffset=len(nb), byteLength=len(data))
            if target:
                v["target"] = target
            nb.extend(data)
            views.append(v)
            return len(views) - 1
    
        for a in j["accessors"]:
            vi = a["bufferView"]
            if vi not in remap:
                remap[vi] = put(view(vi), j["bufferViews"][vi].get("target"))
                if "byteStride" in j["bufferViews"][vi]:
                    views[-1]["byteStride"] = j["bufferViews"][vi]["byteStride"]
            a["bufferView"] = remap[vi]
        j["images"] = [dict(bufferView=put(png), mimeType="image/png") for png in images]
        j["textures"], j["materials"], j["bufferViews"] = textures, mats, views
        j["buffers"] = [dict(byteLength=len(nb))]
        j["samplers"] = [dict(magFilter=9729, minFilter=9987, wrapS=10497, wrapT=10497)]
        if not textures:
            for k in ("textures", "images", "samplers"):
                j.pop(k)
        joints = {j["nodes"][k]["name"] for k in j["skins"][0]["joints"]}
        root = j["scenes"][j.get("scene", 0)]["nodes"][0]
        j["nodes"][root]["name"] = name
        j["nodes"][root]["extras"] = dict(lowmarch=dict(
            name=name, label=entry.get("label", name), source=f"{name}.glb.json", units="metres", up="+Y", front="+Z",
            humanoid={h: joint_name(s) for h, s in HUMANOID.items() if joint_name(s) in joints},
            scene_info=info))
        j["asset"] = dict(version="2.0", generator="lowmarch tools/whole/export_model.py (from export_skinned)")
        return write_glb(j, nb, out)
    
    
    # ---- the report: the file read back on its own --------------------------------------------------------------------------
    COMP = {5120: "b", 5121: "B", 5122: "h", 5123: "H", 5125: "I", 5126: "f"}
    NCOMP = dict(SCALAR=1, VEC2=2, VEC3=3, VEC4=4, MAT4=16)
    
    
    def report(path):
        b = open(path, "rb").read()
        j, bin_ = read_glb(b)
    
        def acc(i):
            a = j["accessors"][i]
            v = j["bufferViews"][a["bufferView"]]
            assert v.get("byteOffset", 0) + v["byteLength"] <= len(bin_), f"view {a['bufferView']} past the buffer"
            dt = np.dtype("<" + COMP[a["componentType"]])
            n = NCOMP[a["type"]]
            assert a.get("byteOffset", 0) + a["count"] * n * dt.itemsize <= v["byteLength"], f"accessor {i} past its view"
            arr = np.frombuffer(bin_, dt, a["count"] * n, v.get("byteOffset", 0) + a.get("byteOffset", 0))
            return arr.reshape(a["count"], n) if n > 1 else arr
    
        skin = j["skins"][0]
        nj = len(skin["joints"])
        tris, prims, lo, hi, bad = 0, 0, np.full(3, 1e9), np.full(3, -1e9), []
        for mi, me in enumerate(j["meshes"]):
            for pr in me["primitives"]:
                prims += 1
                P = acc(pr["attributes"]["POSITION"])
                I = acc(pr["indices"])
                tris += len(I) // 3
                lo, hi = np.minimum(lo, P.min(0)), np.maximum(hi, P.max(0))
                if I.max() >= len(P):
                    bad.append(f"mesh {mi}: index past its vertices")
                if "JOINTS_0" in pr["attributes"]:
                    if acc(pr["attributes"]["JOINTS_0"]).max() >= nj:
                        bad.append(f"mesh {mi}: joint index past the skin")
                    w = acc(pr["attributes"]["WEIGHTS_0"]).sum(1)
                    if np.abs(w - 1).max() > 2e-3:
                        bad.append(f"mesh {mi}: weights sum {w.min():.3f}..{w.max():.3f}")
        # rest pose against the bind matrices: each joint's world matrix times its inverse bind should be the identity
        nodes = j["nodes"]
        parent = {c: i for i, nd in enumerate(nodes) for c in nd.get("children", [])}
    
        def local(i):
            nd = nodes[i]
            x, y, z, w = nd.get("rotation", [0, 0, 0, 1])
            R = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
                          [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
                          [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
            M = np.eye(4)
            M[:3, :3] = R * np.array(nd.get("scale", [1, 1, 1]))
            M[:3, 3] = nd.get("translation", [0, 0, 0])
            return M
    
        def world(i):
            return world(parent[i]) @ local(i) if i in parent else local(i)
    
        ibm = acc(skin["inverseBindMatrices"]).reshape(-1, 4, 4).transpose(0, 2, 1)
        off = max(np.abs(world(k) @ ibm[n] - np.eye(4)).max() for n, k in enumerate(skin["joints"]))
        names = {nd.get("name"): i for i, nd in enumerate(nodes)}
        head = world(names["J_Bip_C_Head"])[:3, 3] if "J_Bip_C_Head" in names else None
        face = [k for k, nd in enumerate(nodes) if (nd.get("extras") or {}).get("role") == "face"]
        front = None
        if face and head is not None:
            fp = acc(j["meshes"][nodes[face[0]]["mesh"]]["primitives"][0]["attributes"]["POSITION"])
            front = "+Z" if fp[:, 2].max() - head[2] > head[2] - fp[:, 2].min() else "-Z"
        anims = []
        for a in j.get("animations", []):
            d = max(float(acc(s["input"]).max()) for s in a["samplers"]) if a["samplers"] else 0.0
            anims.append(f"{a['name']} {d:.2f} s ({len(a['channels'])} channels)")
        ext = (nodes[j["scenes"][0]["nodes"][0]].get("extras") or {}).get("lowmarch", {})
        blend = sum(m.get("alphaMode") == "BLEND" for m in j["materials"])
        mask = sum(m.get("alphaMode") == "MASK" for m in j["materials"])
        metal = sum(m["pbrMetallicRoughness"].get("metallicFactor", 1) > 0.2 for m in j["materials"])
        print(f"{path}: {len(b) / 1e6:.2f} MB (JSON {len(b) - len(bin_) - 28} B, binary {len(bin_)} B)")
        print(f"  meshes {len(j['meshes'])}, primitives {prims}, triangles {tris}, nodes {len(nodes)}")
        print(f"  materials {len(j['materials'])} ({mask} mask, {blend} blend, {metal} metallic), textures "
              f"{len(j.get('textures', []))}, images {len(j.get('images', []))}")
        print(f"  skin: {nj} joints, skeleton root {nodes[skin['skeleton']]['name']}, rest pose against bind matrices: "
              f"{off:.1e} off")
        print(f"  humanoid map in extras: {len(ext.get('humanoid', {}))} bones")
        print(f"  animations: {', '.join(anims) or 'none'}")
        print(f"  bounds (m): x {lo[0]:.3f}..{hi[0]:.3f}  y {lo[1]:.3f}..{hi[1]:.3f}  z {lo[2]:.3f}..{hi[2]:.3f}; "
              f"height {hi[1] - lo[1]:.3f}; face toward {front}")
        for x in bad:
            print("  ! " + x)
        return not bad and off < 1e-3
    
    
    # ---- the check: three.js GLTFLoader, perspective, its own materials --------------------------------------------------
    CHECK_PAGE = """<!doctype html><html><head><meta charset="utf-8"><title>model check</title>
    <style>body { margin: 0; background: #222; }</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">
    import * as THREE from "three";
    import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
    const q = new URLSearchParams(location.search), W = 960, H = 1080, out = document.getElementById("out");
    try {
      const R = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
      R.setSize(2 * W, H); R.setScissorTest(true);
      const gltf = await new Promise((ok, bad) => new GLTFLoader().load(q.get("file"), ok, null, bad));
      const scene = new THREE.Scene(); scene.background = new THREE.Color(0x8a93a3);
      scene.add(new THREE.HemisphereLight(0xffffff, 0x50505a, 1.6));
      const sun = new THREE.DirectionalLight(0xffffff, 2.2); sun.position.set(1.5, 3, 4); scene.add(sun);
      scene.add(gltf.scene);
      const floor = new THREE.Mesh(new THREE.CircleGeometry(1.2, 48), new THREE.MeshStandardMaterial({ color: 0x55604a }));
      floor.rotation.x = -Math.PI / 2; scene.add(floor);
      const mixer = new THREE.AnimationMixer(gltf.scene), clip = THREE.AnimationClip.findByName(gltf.animations, q.get("clip"));
      const t = q.get("t") !== null && q.get("t") !== "" ? +q.get("t") : clip.duration / 2;
      const box = new THREE.Box3().setFromObject(gltf.scene, true), h = box.max.y - box.min.y;
      const cam = new THREE.PerspectiveCamera(30, W / H, 0.05, 50);
      const shot = (x, yaw, msg) => {
        const d = h * 0.62 / Math.tan(THREE.MathUtils.degToRad(15)), a = THREE.MathUtils.degToRad(yaw);
        cam.position.set(Math.sin(a) * d, h * 0.62, Math.cos(a) * d); cam.lookAt(0, h * 0.5, 0);
        R.setViewport(x, 0, W, H); R.setScissor(x, 0, W, H); R.render(scene, cam);
      };
      mixer.clipAction(clip).play(); mixer.setTime(t); gltf.scene.updateMatrixWorld(true);
      shot(0, 35);
      mixer.stopAllAction(); gltf.scene.traverse(o => { if (o.isSkinnedMesh) o.skeleton.pose(); }); gltf.scene.updateMatrixWorld(true);
      shot(W, 0);
      let n = 0; gltf.scene.traverse(o => { if (o.isSkinnedMesh) n++; });
      document.title = `ok ${n} skinned, clip ${clip.name} at ${t.toFixed(2)} of ${clip.duration.toFixed(2)} s, height ${h.toFixed(3)}`;
      out.textContent = R.domElement.toDataURL("image/png");
    } catch (e) { out.textContent = "ERROR " + e; }
    </script></body></html>
    """
    
    
    def check(glb, png, clip="attack", t=""):
        d = os.path.join(os.path.dirname(os.path.abspath(png)), "model_check_site")   # snap Chromium: not under /tmp
        shutil.rmtree(d, ignore_errors=True)
        os.makedirs(d)
        shutil.copy(glb, os.path.join(d, "model.glb"))
        open(os.path.join(d, "index.html"), "w").write(CHECK_PAGE)
        s = socket.socket()
        s.bind(("127.0.0.1", 0))
        port = s.getsockname()[1]
        s.close()
        srv = 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}/index.html?file=model.glb&clip={clip}&t={t}"
            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=120000", "--dump-dom", url], capture_output=True, text=True, timeout=600)
            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)
                raise SystemExit("check FAILED " + (err.group(1)[:400] if err else r.stderr[-800:]))
            Image.open(io.BytesIO(base64.b64decode(m.group(1)))).convert("RGB").save(png)
            title = re.search(r"<title>([^<]*)</title>", r.stdout)
            print(f"check -> {png}: {title.group(1) if title else ''}")
        finally:
            srv.terminate()
            shutil.rmtree(d, ignore_errors=True)
    
    
    if __name__ == "__main__":
        a = sys.argv[1:]
        if len(a) < 3:
            raise SystemExit(__doc__)
        t0 = time.time()
        export(a[0], a[1], a[2])
        print(f"export {time.time() - t0:.1f}s")
        ok = report(a[2])
        if "--check" in a:
            k = a.index("--check")
            t1 = time.time()
            check(a[2], a[k + 1], *(a[k + 2:k + 4]))
            print(f"check {time.time() - t1:.1f}s")
        sys.exit(0 if ok else 1)
    

    result, 1 line

    File created successfully at: ~/Projects/lowmarch-fable52/tools/whole/export_model.py (file state is current in your context — no need to Read it back)
  • Bashpython3 - <<'EOF'

    command

    python3 - <<'EOF'
    p = "tools/whole/export_model.py"
    s = open(p).read()
    s = s.replace("import colorsys\nimport http.server\n", "").replace("import threading\n", "")
    s = s.replace("        key = (old, bake.__code__.co_name if bake else None, id(bake) if bake else None)\n", "")
    open(p, "w").write(s)
    EOF
    date +%s; OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/export_model.py review/out/whole-lens/site wren review/out/whole-lens/wren.glb --check review/out/whole-lens/model_check.png; date +%s

    result, 12 lines

    1794309329
    export 2.2s
    review/out/whole-lens/wren.glb: 4.32 MB (JSON 131252 B, binary 4191876 B)
      meshes 61, primitives 61, triangles 85506, nodes 165
      materials 25 (6 mask, 2 blend, 9 metallic), textures 10, images 10
      skin: 103 joints, skeleton root Root, rest pose against bind matrices: 5.8e-08 off
      humanoid map in extras: 54 bones
      animations: idle 1.80 s (38 channels), attack 1.50 s (40 channels), apose 1.00 s (4 channels)
      bounds (m): x -0.336..0.336  y -0.009..1.675  z -0.242..0.974; height 1.684; face toward +Z
    check -> review/out/whole-lens/model_check.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
    check 7.0s
    1794309339
  • Read~/Projects/lowmarch-fable52/review/out/whole-lens/model_check.png

    input

    {
      "file_path": "~/Projects/lowmarch-fable52/review/out/whole-lens/model_check.png"
    }

    result

    no output

    model_check.png
    model_check.png
  • Bashpython3 - <<'EOF'

    command

    python3 - <<'EOF'
    p = "tools/whole/export_model.py"
    s = open(p).read()
    old = """  shot(W, 0);
    """
    new = """  shot(W, 0);
      const head = gltf.scene.getObjectByName("J_Bip_C_Head");            // an inset: the face, close
      if (head) {
        const c = head.getWorldPosition(new THREE.Vector3()).add(new THREE.Vector3(0, 0.06, 0));
        const fc = new THREE.PerspectiveCamera(30, 1, 0.05, 50); fc.position.copy(c).add(new THREE.Vector3(0.18, 0.02, 0.62)); fc.lookAt(c);
        R.setViewport(W + 8, H - 408, 400, 400); R.setScissor(W + 8, H - 408, 400, 400); R.render(scene, fc);
      }
    """
    assert s.count(old) == 1
    s = s.replace(old, new)
    s = s.replace("plain light, posed at CLIP (default attack) and SECONDS (default its middle), beside the reference pose from the front.",
                  "plain light, posed at CLIP (default attack) and SECONDS (default its middle), beside the reference pose from the front\nwith the face close in an inset.")
    open(p, "w").write(s)
    EOF
    OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/export_model.py review/out/whole-lens/site wren review/out/whole-lens/wren.glb --check review/out/whole-lens/model_check.png | tail -2 && python3 -c "
    from PIL import Image; Image.open('review/out/whole-lens/model_check.png').crop((960,0,1380,420)).resize((840,840)).save('[redacted: private path]/scratchpad/face.png')"

    result, 2 lines

    check -> review/out/whole-lens/model_check.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
    check 10.4s
  • Read[redacted: private path]/scratchpad/face.png

    input

    {
      "file_path": "[redacted: private path]/scratchpad/face.png"
    }

    result

    no output

    face.png
    face.png
  • BashD=[redacted: private path]/scratchpad && cat > $D/diag.py <<'EOF'

    command

    D=[redacted: private path]/scratchpad && cat > $D/diag.py <<'EOF'
    import sys, os
    sys.path.insert(0, "tools/whole")
    import export_model as em
    page = em.CHECK_PAGE
    page = page.replace('  shot(0, 35);\n', '  shot(0, 35);\n  const hide = (q.get("hide") || "").split(",").filter(Boolean); gltf.scene.traverse(o => { if (o.isMesh && hide.includes(o.userData.role)) o.visible = false; });\n')
    page = page.replace("fc.position.copy(c).add(new THREE.Vector3(0.18, 0.02, 0.62))", "fc.position.copy(c).add(new THREE.Vector3(0.0, -0.03, 0.40))")
    page = page.replace("400, 400); R.setScissor(W + 8, H - 408, 400, 400)", "900, 900); R.setScissor(W + 8, H - 408, 900, 900)").replace("H - 408", "H - 908")
    em.CHECK_PAGE = page
    import re
    def check(glb, png, hide):
        em.CHECK_PAGE = page.replace('q.get("hide")', '"' + hide + '"')
        em.check(glb, png)
    for i, h in enumerate(sys.argv[2:]):
        check(sys.argv[1], f"review/out/whole-lens/diag{i}.png", h)
    EOF
    python3 $D/diag.py review/out/whole-lens/wren.glb "" "highlight" "white" && python3 -c "
    from PIL import Image
    ims=[Image.open(f'review/out/whole-lens/diag{i}.png').crop((1100,250,1700,560)) for i in range(3)]
    s=Image.new('RGB',(600,930)); [s.paste(im,(0,310*k)) for k,im in enumerate(ims)]; s.save('$D/diag.png')"

    result, 3 lines

    check -> review/out/whole-lens/diag0.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
    check -> review/out/whole-lens/diag1.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
    check -> review/out/whole-lens/diag2.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
  • Read[redacted: private path]/scratchpad/diag.png

    input

    {
      "file_path": "[redacted: private path]/scratchpad/diag.png"
    }

    result

    no output

    diag.png
    diag.png
  • Bashcd ~/Projects/lowmarch-fable52 && python3 - <<'EOF'

    command

    cd ~/Projects/lowmarch-fable52 && python3 - <<'EOF'
    p = "tools/whole/export_model.py"
    s = open(p).read()
    old = "  scene.add(gltf.scene);\n"
    new = ("  scene.add(gltf.scene);    // posed skinned meshes keep the bounds of their first pose: small ones (the eyes) get culled\n"
           "  gltf.scene.traverse(o => { if (o.isMesh) o.frustumCulled = false; });\n")
    assert s.count(old) == 1
    s = s.replace(old, new)
    open(p, "w").write(s)
    EOF
    D=[redacted: private path]/scratchpad; python3 $D/diag.py review/out/whole-lens/wren.glb "" && python3 -c "
    from PIL import Image
    Image.open('review/out/whole-lens/diag0.png').crop((960,170,1870,1080)).resize((700,700)).save('$D/diag.png')"

    result, 1 line

    check -> review/out/whole-lens/diag0.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
  • Read[redacted: private path]/scratchpad/diag.png

    input

    {
      "file_path": "[redacted: private path]/scratchpad/diag.png"
    }

    result

    no output

    diag_2.png
    diag_2.png
  • Bashcd ~/Projects/lowmarch-fable52 && sed -i 's/"#c6a296", 0.35)/"#c6a296", 0.25)/' tools/whole/export_model.py && grep -n '0.25)$' tools/whole/export_model.py; rm -f review/out/whole-lens/diag*.png; date +%s; OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/export_model.py review/out/whole-lens/site wren review/out/whole-lens/wren.glb --check review/out/whole-lens/model_check.png; date +%s

    command

    cd ~/Projects/lowmarch-fable52 && sed -i 's/"#c6a296", 0.35)/"#c6a296", 0.25)/' tools/whole/export_model.py && grep -n '0.25)$' tools/whole/export_model.py; rm -f review/out/whole-lens/diag*.png; date +%s; OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/export_model.py review/out/whole-lens/site wren review/out/whole-lens/wren.glb --check review/out/whole-lens/model_check.png; date +%s

    result, 14 lines

    160:        colour((P or {}).get("ramp", [None, base])[1] or base or "#c6a296", 0.25)
    1794309469
    export 4.4s
    review/out/whole-lens/wren.glb: 4.32 MB (JSON 131252 B, binary 4191876 B)
      meshes 61, primitives 61, triangles 85506, nodes 165
      materials 25 (6 mask, 2 blend, 9 metallic), textures 10, images 10
      skin: 103 joints, skeleton root Root, rest pose against bind matrices: 5.8e-08 off
      humanoid map in extras: 54 bones
      animations: idle 1.80 s (38 channels), attack 1.50 s (40 channels), apose 1.00 s (4 channels)
      bounds (m): x -0.336..0.336  y -0.009..1.675  z -0.242..0.974; height 1.684; face toward +Z
    check -> review/out/whole-lens/model_check.png: ok 61 skinned, clip attack at 0.75 of 1.50 s, height 1.684
    check 6.9s
    1794309481
    [This command modified 1 file you've previously read: ../../../../tools/whole/export_model.py. Call Read before editing.]
  • Bashcd ~/Projects/lowmarch-fable52 && ls [redacted: private path] && date +%s && timeout 300 [redacted: private path] -b --factory-startup --python-expr "

    command

    cd ~/Projects/lowmarch-fable52 && ls [redacted: private path] && date +%s && timeout 300 [redacted: private path] -b --factory-startup --python-expr "
    import bpy, time
    for o in list(bpy.data.objects): bpy.data.objects.remove(o)
    t=time.time()
    r=bpy.ops.import_scene.gltf(filepath='~/Projects/lowmarch-fable52/review/out/whole-lens/wren.glb')
    arm=[o for o in bpy.data.objects if o.type=='ARMATURE']; me=[o for o in bpy.data.objects if o.type=='MESH']
    print('IMPORT', r, round(time.time()-t,1), 's; armatures', len(arm), 'bones', len(arm[0].data.bones) if arm else 0, 'meshes', len(me), 'actions', [a.name for a in bpy.data.actions], 'materials', len(bpy.data.materials), 'images', len(bpy.data.images))
    import mathutils
    print('DIMS', [round(x,3) for x in arm[0].dimensions] if arm else None, 'max z of meshes', round(max((o.matrix_world @ mathutils.Vector(c)).z for o in me for c in o.bound_box),3))
    " 2>&1 | grep -v "^$" | tail -15; date +%s

    result, 18 lines

    [redacted: private path]
    1794309488
    19:18:12 | INFO: Blender create Mesh node plate
    19:18:12 | INFO: Blender create Mesh node plate
    19:18:12 | INFO: Blender create Mesh node plate
    19:18:12 | INFO: Blender create Mesh node plate
    19:18:12 | INFO: Blender create Mesh node sword
    19:18:12 | INFO: Blender create Mesh node sword
    19:18:12 | INFO: Blender create Mesh node sword
    19:18:12 | INFO: Blender create Mesh node sword
    19:18:12 | INFO: Blender create Mesh node sword
    19:18:12 | INFO: Blender create Mesh node body
    19:18:12 | INFO: glTF import finished in 1.78s
    IMPORT {'FINISHED'} 2.0 s; armatures 1 bones 103 meshes 62 actions ['apose', 'attack', 'idle'] materials 27 images 12
    DIMS [0.614, 0.574, 1.653] max z of meshes 1.756
    Blender 5.2.3 LTS (hash e13b728c6880 built 2026-10-22 01:35:05)
    Blender quit
    1794309492
  • Bashcd ~/Projects/lowmarch-fable52 && timeout 300 [redacted: private path] -b --factory-startup --python-expr "

    command

    cd ~/Projects/lowmarch-fable52 && timeout 300 [redacted: private path] -b --factory-startup --python-expr "
    import bpy
    for o in list(bpy.data.objects): bpy.data.objects.remove(o)
    bpy.ops.import_scene.gltf(filepath='~/Projects/lowmarch-fable52/review/out/whole-lens/wren.glb')
    print('OBJS', sorted({o.type for o in bpy.data.objects}), [o.name for o in bpy.data.objects if o.type not in ('MESH','ARMATURE')][:5])
    m=[o for o in bpy.data.objects if o.type=='MESH' and 'Face_00' in o.name]
    print('FACEATTR', [a.name for a in m[0].data.attributes] if m else None)
    p=[o for o in bpy.data.objects if o.type=='MESH' and 'breastplate' in o.name]
    print('PLATEATTR', [a.name for a in p[0].data.attributes] if p else None)
    r=[o for o in bpy.data.objects if 'character' in o.name or 'wren' in o.name]; print('ROOT', [(o.name, o.type, list(o.keys())[:5]) for o in r])
    " 2>&1 | grep -E "WARN|ERROR|Error|OBJS|ATTR|ROOT" | head -20

    result, 4 lines

    OBJS ['ARMATURE', 'MESH'] []
    FACEATTR ['.select_vert', 'position', '.corner_vert', '.corner_edge', '.select_poly', 'UVMap', 'material_index', 'sharp_face', '.edge_verts', '.select_edge', 'custom_normal', 'sharp_edge']
    PLATEATTR ['.select_vert', 'position', '.corner_vert', '.corner_edge', '.select_poly', 'material_index', 'sharp_face', '.edge_verts', '.select_edge', 'custom_normal', 'sharp_edge']
    ROOT [('wren', 'ARMATURE', ['lowmarch'])]
  • BashOMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/export_model.py review/out/whole-lens/site mob_soldier review/out/whole-lens/mob_soldier.glb --check review/out/whole-lens/model_check_soldier.png idle 0

    command

    OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python3 tools/whole/export_model.py review/out/whole-lens/site mob_soldier review/out/whole-lens/mob_soldier.glb --check review/out/whole-lens/model_check_soldier.png idle 0

    result, 10 lines

    export 1.7s
    review/out/whole-lens/mob_soldier.glb: 3.83 MB (JSON 119720 B, binary 3708400 B)
      meshes 55, primitives 55, triangles 74258, nodes 123
      materials 24 (5 mask, 2 blend, 5 metallic), textures 12, images 11
      skin: 67 joints, skeleton root Root, rest pose against bind matrices: 5.6e-08 off
      humanoid map in extras: 54 bones
      animations: idle 2.00 s (44 channels), attack 1.50 s (44 channels), apose 1.00 s (4 channels)
      bounds (m): x -0.288..0.287  y 0.007..1.783  z -0.515..1.863; height 1.776; face toward +Z
    check -> review/out/whole-lens/model_check_soldier.png: ok 55 skinned, clip idle at 0.00 of 2.00 s, height 1.776
    check 4.7s
  • Read~/Projects/lowmarch-fable52/review/out/whole-lens/model_check_soldier.png

    input

    {
      "file_path": "~/Projects/lowmarch-fable52/review/out/whole-lens/model_check_soldier.png"
    }

    result

    no output

    model_check_soldier.png
    model_check_soldier.png
  • BashS=review/out/whole-lens/site/index.html; grep -n "display" $S | head -20; grep -n "function setYaw" -A9 $S; grep -n "ROW_VIEW() ? CAM.duel\|stage.rotation\|CAM.duel.place" $S | head

    command

    S=review/out/whole-lens/site/index.html; grep -n "display" $S | head -20; grep -n "function setYaw" -A9 $S; grep -n "ROW_VIEW() ? CAM.duel\|stage.rotation\|CAM.duel.place" $S | head

    result, 34 lines

    6:<link href="https://fonts.googleapis.com/css2?family=Alegreya+Sans:ital,wght@0,400;0,500;0,700;1,400&family=Pixelify+Sans:wght@500;700&family=Silkscreen&display=swap" rel="stylesheet">
    9:   turn and camera); notes, display options, pieces and the round's checks live in a side panel that
    17:  --f-display: "Pixelify Sans", ui-monospace, "Courier New", monospace;
    38:.app { position: fixed; inset: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto; }
    41:.stage canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
    42:.status[hidden] { display: none; }
    43:.status { position: absolute; inset: 0; display: grid; place-items: center; font: 12px/1.4 var(--f-label); letter-spacing: 0.06em;
    46:.hud { position: absolute; left: 0; right: 0; display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center;
    51:.brand { display: grid; gap: 0; margin-right: 6px; }
    53:.brand h1 { font: 700 20px/1.1 var(--f-display); margin: 0; white-space: nowrap; }
    62:.seg { display: inline-flex; }
    63:.seg[hidden] { display: none; }
    70:.turn { display: flex; gap: 10px; align-items: center; flex: 1 1 260px; min-width: 0; }
    76:         overflow-y: auto; overscroll-behavior: contain; padding: 18px 20px 40px; display: grid; gap: 26px; align-content: start; }
    77:.panel[hidden] { display: none; }
    78:.panel header { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
    79:.panel h2 { font: 700 20px/1.15 var(--f-display); margin: 0; }
    81:.panel section { display: grid; gap: 8px; align-content: start; }
    82:.panel ul, .panel ol { margin: 0; padding-left: 1.15em; display: grid; gap: 8px; }
    85:.opts { display: flex; flex-wrap: wrap; gap: 6px; }
    1255:function setYaw(y) {
    1256-  state.yaw = ((y % 360) + 360) % 360;
    1257-  $("yaw").value = Math.round(state.yaw); $("yawOut").textContent = `${Math.round(state.yaw)}°`;
    1258-  const r = -THREE.MathUtils.degToRad(state.yaw);
    1259-  if (state.view === "duel") stage.rotation.y = r;
    1260-  else if (ROW_VIEW()) active().forEach(c => c.turn.rotation.y = r);
    1261-  else { const c = chars.get(state.who); if (c) c.turn.rotation.y = r; }
    1262-}
    1263-
    1264-// ---- controls --------------------------------------------------------------------------------------------------------
    907:const CAM_VIEW = () => state.view === "duel" || ROW_VIEW() ? CAM.duel.cam : charDef(state.who).cams[state.view];
    1259:  if (state.view === "duel") stage.rotation.y = r;
    1345:    stage.rotation.y = 0;
    1356:        const pl = CAM.duel.place[c.name];
  • BashS=review/out/whole-lens/site/index.html; grep -n "class Cloth\|class SkirtRig\|this.display\b\|this.display =" $S | head; grep -n "this.display = " -A4 $S | head -20; sed -n 1331,1376p $S

    command

    S=review/out/whole-lens/site/index.html; grep -n "class Cloth\|class SkirtRig\|this.display\b\|this.display =" $S | head; grep -n "this.display = " -A4 $S | head -20; sed -n 1331,1376p $S

    result, 58 lines

    646:class Cloth {
    672:    this.display = new THREE.Mesh(g, skinned.material);
    673:    this.display.userData = { ...skinned.userData, cloth: true };
    674:    this.display.frustumCulled = false;
    758:    const p = this.display.geometry.attributes.position;
    760:    this.display.geometry.computeVertexNormals(); this.display.geometry.computeBoundingSphere();
    777:class SkirtRig extends Cloth {
    672:    this.display = new THREE.Mesh(g, skinned.material);
    673-    this.display.userData = { ...skinned.userData, cloth: true };
    674-    this.display.frustumCulled = false;
    675-    this.lines = new THREE.LineSegments(new THREE.BufferGeometry(), null);
    676-    this.lines.frustumCulled = false;
    async function setView(view, clip) {
      const changed = view !== state.view;
      state.view = view;
      document.querySelectorAll("[data-view]").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.view === view)));
      buildWho();
      statusEl.hidden = false; statusEl.textContent = view === "duel" ? "Loading both fighters…" : "Loading the model…";
      try {
        const cs = await Promise.all(activeNames().map(loadCharacter));
        const g = view !== "bust" && !ROW_VIEW() ? await loadGround() : null;     // a row of models stands on nothing
        for (const c of chars.values()) { c.turn.removeFromParent(); scene.remove(c.world); }
        if (ground) scene.remove(ground.root);
        if (g) scene.add(g.root);
        const v = CAM_VIEW(), lead = cs[0].info;
        paint.mat.uniforms.uGap.value = lead.depth_gap;
        stage.rotation.y = 0;
        for (const c of cs) {
          scene.add(c.world);
          c.turn.rotation.set(0, 0, 0);
          if (view === "lineup") {
            const i = LINEUP.order.indexOf(c.name);
            stage.add(c.turn);
            c.turn.position.set(lineupX(i), 0, 0); c.holder.position.set(0, 0, 0);
          } else if (view === "compare") {               // placed by layoutCompare, once all are in
            stage.add(c.turn); c.holder.position.set(0, 0, 0);
          } else if (view === "duel") {
            const pl = CAM.duel.place[c.name];
            stage.add(c.turn);
            c.turn.position.set(...pl.pos); c.turn.rotation.y = THREE.MathUtils.degToRad(pl.yaw); c.holder.position.set(0, 0, 0);
          } else {
            scene.add(c.turn);
            c.turn.position.set(v.pivot[0], 0, v.pivot[2]); c.holder.position.set(-v.pivot[0], 0, -v.pivot[2]);
          }
        }
        statusEl.hidden = true;
        if (view === "compare") layoutCompare();
        buildParts(); applyMaterials(); size(); matchCamera();
        setYaw(changed || view === "duel" ? VIEW_YAW[view] : state.yaw);
        const want = clip || (view === "duel" ? "clash" : (CLIP_VIEW[state.clip] === "battle" ? state.clip : "idle"));
        if (view === "duel") setClip("clash", SHEET ? null : "idle"); else if (view === "battle") setClip(want);
        else if (view === "lineup") setClip(clip && CLIP_VIEW[clip] === "battle" ? clip : "idle"); else setClip("idle");
        animate(0);
        scene.updateMatrixWorld(true); cs.forEach(c => c.cloths.forEach(cl => { cl.reset(false); cl.write(); }));
      } catch (e) { console.error(e); statusEl.textContent = "The model didn't load."; }
    }
    
    // ---- rendering -------------------------------------------------------------------------------------------------------
  • BashS=review/out/whole-lens/site/index.html; for t in "vec2 q = uv + dir * dm * uCastPpm * px;" "float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);" "float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);" " float castShadow() {"; do echo "$(grep -c -F "$t" $S) $t"; done; date +%s

    command

    S=review/out/whole-lens/site/index.html; for t in "vec2 q = uv + dir * dm * uCastPpm * px;" "float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);" "float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);" "  float castShadow() {"; do echo "$(grep -c -F "$t" $S) $t"; done; date +%s

    result, 5 lines

    1 vec2 q = uv + dir * dm * uCastPpm * px;
    1 float z0 = uCastNear + texture2D(tCastDepth, uv).x * (uCastFar - uCastNear);
    1 float zq = uCastNear + texture2D(tCastDepth, q).x * (uCastFar - uCastNear);
    1   float castShadow() {
    1794309585