#!/usr/bin/env python3
# © Computational Classnotes · CC BY-NC-SA 4.0
# By Dara O Shayda and Hikari Noor Hoshino (星野ヌール), AI System Programming Laboratory.
"""The pictures of the write-up "How Mochi and Onigiri became 3D", and the avatars' thumbnails, drawn by the real
VRM loader (three.js with pixiv's three-vrm) in a headless Chrome.

   python3 tools/vrm-figures.py [--work DIR]        writes docs/img/vrm/*.png and DIR/thumbs/{mochi,onigiri}.png

How it works
   1. It makes a work folder (by default /tmp/vrm-figures) and installs three and @pixiv/three-vrm there with npm.
   2. It writes a small viewer page into it (VIEWER, below): the page loads one .vrm, sets the camera, expressions and a
      pose from its address, and can draw the model as a wireframe, with its skeleton, with its skin weights as colours,
      with plain (not toon) materials, or turning so that the spring bones lag.
   3. It builds, with tools/make-vrm.py, a .vrm for every stage: a single shape, then each creature part by part.
   4. It serves the work folder on localhost and photographs each view with Playwright, then lays some views side by
      side with Pillow, each sheet with its captions and the copyright line.
Nothing here changes the avatars themselves; make-vrm.py --thumbs DIR/thumbs puts the thumbnails into them.
"""
import functools, http.server, importlib.util, pathlib, subprocess, sys, threading, asyncio
import numpy as np
from PIL import Image, ImageDraw, ImageFont

ROOT = pathlib.Path(__file__).resolve().parent.parent
IMG = ROOT / "docs" / "img" / "vrm"
CR = "© Computational Classnotes · CC BY-NC-SA 4.0"

# make-vrm.py has a hyphen in its name, so it is loaded by its path
_spec = importlib.util.spec_from_file_location("make_vrm", ROOT / "tools" / "make-vrm.py")
mv = importlib.util.module_from_spec(_spec); _spec.loader.exec_module(mv)

# ---------------------------------------------------------------------------------------------------------------------
# The viewer page, served from the work folder. Its address holds every choice:
#   f=file.vrm  w,h (pixels)  yaw (degrees)  d (camera distance)  ty (height looked at)  cy (camera height above ty)
#   ex=blink:1,aa:0.5 (expressions)  pose=legs (one stub foot up)  wire=1  skel=1  weights=1  plain=1
#   turn=degrees (the model turns quickly this far, and the picture is taken mid-turn, so the springs show their lag)
# ---------------------------------------------------------------------------------------------------------------------
VIEWER = r"""<!DOCTYPE html><html><head><meta charset="utf-8"><style>html,body{margin:0;background:#fff6ea}canvas{display:block}</style>
<script type="importmap">{"imports":{"three":"./node_modules/three/build/three.module.js","three/addons/":"./node_modules/three/examples/jsm/","@pixiv/three-vrm":"./node_modules/@pixiv/three-vrm/lib/three-vrm.module.js"}}</script></head>
<body><script type="module">
// © Computational Classnotes · CC BY-NC-SA 4.0 — the figure viewer of tools/vrm-figures.py
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { VRMLoaderPlugin } from '@pixiv/three-vrm';
const q = new URLSearchParams(location.search), num = (k, d) => +(q.get(k) ?? d);
const W = num('w', 800), H = num('h', 800);
const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
renderer.setSize(W, H); renderer.setPixelRatio(1); renderer.setClearColor(0xfff6ea); document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene(), cam = new THREE.PerspectiveCamera(30, W / H, .01, 20);
scene.add(new THREE.DirectionalLight(0xffffff, 2.2).translateX(1).translateY(1.5).translateZ(2));
scene.add(new THREE.AmbientLight(0xffffff, .7));
// the bones' colours, for the skin-weight view (the same order as the write-up's legend)
const BONE_COL = { hips: '#e4572e', spine: '#f3a712', chest: '#a8c686', neck: '#669bbc', head: '#3f88c5', leftFoot: '#9b5de5', rightFoot: '#f15bb5',
  tail1: '#00bbf9', tail2: '#00f5d4', tail3: '#8ac926', ear_L: '#ff595e', ear_R: '#ffca3a' };
const loader = new GLTFLoader(); loader.register(p => new VRMLoaderPlugin(p));
loader.load(q.get('f'), g => {
  const vrm = g.userData.vrm; scene.add(vrm.scene);
  const ang = num('yaw', 0) * Math.PI / 180, d = num('d', 1.9), ty = num('ty', .3);
  cam.position.set(Math.sin(ang) * d, ty + num('cy', .08), Math.cos(ang) * d); cam.lookAt(0, ty, 0);
  for (const kv of (q.get('ex') || '').split(',').filter(Boolean)) { const [k, v] = kv.split(':'); vrm.expressionManager?.setValue(k, +(v ?? 1)); }
  if (q.get('pose') === 'legs') {          // one stub foot up and a lean: the skin follows the bones
    vrm.humanoid.getNormalizedBoneNode('leftUpperLeg').rotation.x = -0.6;
    vrm.humanoid.getNormalizedBoneNode('head').rotation.z = 0.25;
    vrm.humanoid.getNormalizedBoneNode('spine').rotation.z = -0.12;
  }
  const meshes = []; vrm.scene.traverse(o => { if (o.isMesh) meshes.push(o); });
  if (q.get('plain') === '1') meshes.forEach(m => { const c = (Array.isArray(m.material) ? m.material[0] : m.material).color;
    m.material = new THREE.MeshStandardMaterial({ color: c ? c.clone() : 0xffffff, roughness: .6 }); });
  if (q.get('weights') === '1') {        // each vertex coloured by its bones, mixed by their weights
    const sk = meshes.find(m => m.isSkinnedMesh)?.skeleton;
    meshes.forEach(m => { const gm = m.geometry, si = gm.attributes.skinIndex, sw = gm.attributes.skinWeight; if (!si) return;
      const col = new Float32Array(si.count * 3), tmp = new THREE.Color();
      for (let i = 0; i < si.count; i++) { let r = 0, gg = 0, b = 0;
        for (let k = 0; k < 4; k++) { const w = sw.getComponent(i, k); if (!w) continue; const name = m.skeleton.bones[si.getComponent(i, k)].name;
          tmp.set(BONE_COL[name] || '#cccccc'); r += tmp.r * w; gg += tmp.g * w; b += tmp.b * w; }
        col.set([r, gg, b], i * 3); }
      gm.setAttribute('color', new THREE.BufferAttribute(col, 3));
      m.material = new THREE.MeshBasicMaterial({ vertexColors: true }); });
  }
  if (q.get('wire') === '1') meshes.forEach(m => {     // a wireframe drawn over the model, following the same bones
    const mat = new THREE.MeshBasicMaterial({ color: 0x2a1d3a, wireframe: true, transparent: true, opacity: .35 });
    let w; if (m.isSkinnedMesh) { w = new THREE.SkinnedMesh(m.geometry, mat); w.bind(m.skeleton, m.bindMatrix); } else w = new THREE.Mesh(m.geometry, mat);
    m.parent.add(w); });
  if (q.get('skel') === '1') {
    meshes.forEach(m => [].concat(m.material).forEach(x => { x.transparent = true; x.opacity = .28; x.depthWrite = false; }));
    const helper = new THREE.SkeletonHelper(vrm.scene); helper.material.linewidth = 3; helper.material.depthTest = false; scene.add(helper);
    const dots = new THREE.Group(); scene.add(dots);
    vrm.scene.traverse(o => { if (o.isBone) { const s = new THREE.Mesh(new THREE.SphereGeometry(.009), new THREE.MeshBasicMaterial({ color: 0xd1495b, depthTest: false }));
      s.renderOrder = 9; o.getWorldPosition(s.position); dots.add(s); } });
  }
  const turn = num('turn', 0) * Math.PI / 180; let n = 0;
  const tick = () => {
    if (turn) vrm.scene.rotation.y = turn * Math.min(1, n / 12);   // a quick turn in 12 frames; the springs follow late
    vrm.update(1 / 60); renderer.render(scene, cam);
    if (++n < (turn ? num('at', 8) : 90)) requestAnimationFrame(tick); else window.done = true;   // with turn: the picture mid-turn
  };
  tick();
}, undefined, e => { document.title = 'ERROR ' + e; window.done = true; });
</script></body></html>"""


def setup(work):
    """Make the work folder, install three and three-vrm in it (once), and write the viewer page."""
    work.mkdir(parents=True, exist_ok=True)
    if not (work / "node_modules" / "@pixiv" / "three-vrm").exists():
        (work / "package.json").write_text('{"private": true}')
        subprocess.run(["npm", "i", "--silent", "three", "@pixiv/three-vrm"], cwd=work, check=True)
    (work / "view.html").write_text(VIEWER, encoding="utf-8")


def serve(work, port=8791):
    """Serve the work folder on localhost in a background thread; returns the server."""
    h = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(work))
    http.server.SimpleHTTPRequestHandler.log_message = lambda *a: None
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), h)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv


def stage(cr, keep, name, work):
    """Write a .vrm of the creature with only the parts whose names start with one of `keep` (a stage of the build)."""
    part = dict(cr); part["parts"] = [p for p in cr["parts"] if p.name.startswith(tuple(keep))]
    mv.build(part).write(work / name)
    return name


def single(geo, colour, name, work, mat="body"):
    """Write a .vrm holding one shape only, on the hips, in the given colour: the building blocks of section 2."""
    cr = dict(name="Shape", colours={"body": colour, "line": "#7a6a55"}, parts=[mv.Part("Shape", "body", geo, "hips")],
              bones=mv.skeleton(1.0), targets=mv.TARGET_NAMES, springs=[], eyes_y=.3, height=.6)
    mv.build(cr).write(work / name)
    return name


async def shoot(views, work, port=8791):
    """Photograph each (file name, viewer address) with the real VRM loader in headless Chrome (SwiftShader WebGL)."""
    from playwright.async_api import async_playwright
    async with async_playwright() as p:
        b = await p.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"])
        pg = await b.new_page(viewport={"width": 1024, "height": 1024})
        for out, qs in views:
            w = int(dict(x.split("=") for x in qs.split("&")).get("w", 800)); h = int(dict(x.split("=") for x in qs.split("&")).get("h", 800))
            await pg.set_viewport_size({"width": w, "height": h})
            await pg.goto(f"http://127.0.0.1:{port}/view.html?{qs}"); await pg.wait_for_function("window.done===true", timeout=90000)
            if (await pg.title()).startswith("ERROR"): raise SystemExit(f"{out}: {await pg.title()}")
            await pg.screenshot(path=str(out))
        await b.close()


def font(size, bold=False):
    """Noto Sans CJK, which draws English and Japanese alike; Pillow's own font when it is missing."""
    f = "/usr/share/fonts/opentype/noto/NotoSansCJK-" + ("Bold" if bold else "Regular") + ".ttc"
    try: return ImageFont.truetype(f, size)
    except OSError: return ImageFont.load_default()


def sheet(files, labels, cols, out, title, tw=420):
    """Lay pictures side by side, each with its caption, a title on top and the copyright line at the bottom."""
    rows = (len(files) + cols - 1) // cols; Hh = 70 + rows * (tw + 44) + 44
    S = Image.new("RGB", (cols * tw, Hh), (255, 246, 234)); d = ImageDraw.Draw(S)
    d.text((18, 16), title, fill=(42, 29, 58), font=font(28, True))
    for i, (f, lb) in enumerate(zip(files, labels)):
        im = Image.open(f).convert("RGB"); im.thumbnail((tw, tw)); x = (i % cols) * tw; y = 70 + (i // cols) * (tw + 44)
        S.paste(im, (x + (tw - im.width) // 2, y)); d.text((x + 14, y + tw + 6), lb, fill=(42, 29, 58), font=font(19))
    w = d.textlength(CR, font=font(18)); d.text((cols * tw - w - 16, Hh - 34), CR, fill=(110, 100, 120), font=font(18))
    S.save(out)


def glb_diagram(out, vrm_path):
    """A picture of a .glb file's layout, with the real sizes of mochi.vrm: header, JSON chunk, binary chunk."""
    b = vrm_path.read_bytes(); jl = int.from_bytes(b[12:16], "little"); bl = int.from_bytes(b[20 + jl:24 + jl], "little")
    S = Image.new("RGB", (1400, 560), (255, 246, 234)); d = ImageDraw.Draw(S)
    d.text((24, 18), "Inside mochi.vrm: one binary glTF 2.0 file (.glb)", fill=(42, 29, 58), font=font(30, True))
    boxes = [("Header · 12 bytes", '"glTF"\nversion 2\ntotal length', 230, "#f3a712"),
             (f"JSON chunk · {jl:,} bytes", "nodes, skin, meshes, materials, accessors…\nextensions: VRMC_vrm (meta, licence,\nhumanoid, expressions, look-at,\nfirst person), VRMC_materials_mtoon,\nVRMC_springBone", 500, "#669bbc"),
             (f"Binary chunk · {bl:,} bytes", "vertex positions and normals, bone\nindices and weights, triangle indices,\nmorph-target deltas, inverse bind\nmatrices, the thumbnail", 560, "#a8c686")]
    x = 24
    for t, sub, w, c in boxes:
        d.rounded_rectangle((x, 90, x + w, 400), 16, fill=c, outline=(42, 29, 58), width=3)
        d.text((x + 16, 104), t, fill=(42, 29, 58), font=font(24, True))
        d.multiline_text((x + 16, 150), sub, fill=(42, 29, 58), font=font(19), spacing=8)
        x += w + 24
    d.text((24, 430), f"Total {len(b):,} bytes. Each chunk starts with its length and its type (JSON or BIN); both are padded to 4 bytes.", fill=(42, 29, 58), font=font(20))
    d.text((24, 470), "make-vrm.py writes all three with Python's struct and json modules: GLB.write().", fill=(42, 29, 58), font=font(20))
    w = d.textlength(CR, font=font(18)); d.text((1400 - w - 16, 520), CR, fill=(110, 100, 120), font=font(18))
    S.save(out)


def main(argv):
    """Build every stage, photograph every view, and lay out the sheets of the write-up."""
    work = pathlib.Path(argv[argv.index("--work") + 1]) if "--work" in argv else pathlib.Path("/tmp/vrm-figures")
    setup(work); IMG.mkdir(parents=True, exist_ok=True); (work / "shots").mkdir(exist_ok=True); (work / "thumbs").mkdir(exist_ok=True)
    srv = serve(work)
    M, O = mv.mochi(1.0), mv.onigiri(1.0)
    mv.build(M).write(work / "mochi.vrm"); mv.build(O).write(work / "onigiri.vrm")
    sh = lambda n: work / "shots" / n
    V = []   # (picture, viewer address)
    # --- 2. the building blocks, each alone, as a wireframe over its toon colour
    shapes = [("sphere", mv.ellipsoid([0, .3, 0], [.25, .25, .25], nu=24, nv=16)),
              ("ellipsoid", mv.ellipsoid([0, .3, 0], [.30, .27, .26], nu=40, nv=24)),
              ("lathe", mv.lathe([(.085, 0), (.08, .03), (.06, .08), (.035, .12), (.012, .145), (0, .15)], np.array([0, .22, 0]), np.array([0, 1, 0.0]), 24)),
              ("tube", mv.tube(*mv.smooth([np.array(p) + [.27, 0, .2] for p in [(-.17, .14, -.15), (-.24, .17, -.19), (-.29, .23, -.21), (-.31, .30, -.22), (-.29, .36, -.21), (-.25, .39, -.19)]],
                                          [.038, .042, .04, .036, .032, .028], 8), 16))]
    for nm, geo in shapes:
        f = single(geo, "#f3e6d3", f"shape-{nm}.vrm", work)
        V.append((sh(f"shape-{nm}.png"), f"f={f}&wire=1&yaw={-60 if nm == 'tube' else 0}&d={1.0 if nm in ('lathe', 'tube') else 1.6}&ty={.27 if nm == 'tube' else .3}"))
    # --- 6. Mochi, part by part (each stage keeps the parts before it)
    mst = [("1 the body", ["Body"]), ("2 the stub feet", ["Body", "Foot"]), ("3 the ears", ["Body", "Foot", "Ear"]),
           ("4 the tail", ["Body", "Foot", "Ear", "Tail"]), ("5 the eyes", ["Body", "Foot", "Ear", "Tail", "Eye", "Shine"]),
           ("6 cheeks, smile, mouth", ["Body", "Foot", "Ear", "Tail", "Eye", "Shine", "Cheek", "Smile", "Mouth"])]
    for i, (lb, keep) in enumerate(mst):
        f = stage(M, keep, f"mochi-stage{i + 1}.vrm", work); V.append((sh(f"mochi-stage{i + 1}.png"), f"f={f}&yaw=-35"))
    ost = [("1 the rice-ball body", ["Body"]), ("2 the nori", ["Body", "Nori"]), ("3 the orange dot", ["Body", "Nori", "Dot"]),
           ("4 the ears", ["Body", "Nori", "Dot", "Ear"]), ("5 the stub feet", ["Body", "Nori", "Dot", "Ear", "Foot"]),
           ("6 the face", ["Body", "Nori", "Dot", "Ear", "Foot", "Eye", "Cheek", "Smile", "Mouth"])]
    for i, (lb, keep) in enumerate(ost):
        f = stage(O, keep, f"onigiri-stage{i + 1}.vrm", work); V.append((sh(f"onigiri-stage{i + 1}.png"), f"f={f}&yaw=30"))
    # Onigiri's body: the unit sphere, then reshaped (wireframes)
    sp = mv.sphere(64, 40); f = single((sp[0] * [.25, .25, .25] + [0, .3, 0], sp[1], sp[2]), "#fafafa", "onigiri-sphere.vrm", work)
    V.append((sh("onigiri-sphere.png"), f"f={f}&wire=1&yaw=25"))
    f = stage(O, ["Body"], "onigiri-body.vrm", work); V.append((sh("onigiri-body.png"), f"f={f}&wire=1&yaw=25"))
    # --- 4 and 5. skeleton and skin
    for n in ("mochi", "onigiri"):
        V += [(sh(f"{n}-skeleton.png"), f"f={n}.vrm&skel=1&yaw={-35 if n == 'mochi' else 35}"),
              (sh(f"{n}-weights.png"), f"f={n}.vrm&weights=1&yaw={-35 if n == 'mochi' else 35}"),
              (sh(f"{n}-weights-back.png"), f"f={n}.vrm&weights=1&yaw=180"),
              (sh(f"{n}-pose.png"), f"f={n}.vrm&pose=legs&yaw={-30 if n == 'mochi' else 30}")]
    # --- 7. the expressions, close up on the face
    for n, exs in (("mochi", ["", "blink:1", "blinkLeft:1", "aa:1", "ee:1", "ou:1", "happy:1", "surprised:1"]),
                   ("onigiri", ["", "blink:1", "aa:1", "ou:1", "happy:1", "surprised:1"])):
        for e in exs:
            V.append((sh(f"{n}-face-{e.split(':')[0] or 'neutral'}.png"), f"f={n}.vrm&ex={e}&d=.95&ty=.3&cy=.02"))
    # --- 8. the look: plain materials versus toon with outlines
    for n in ("mochi", "onigiri"):
        V += [(sh(f"{n}-plain.png"), f"f={n}.vrm&plain=1&yaw={-25 if n == 'mochi' else 25}"), (sh(f"{n}-toon.png"), f"f={n}.vrm&yaw={-25 if n == 'mochi' else 25}")]
    # --- the springs: a quick turn, the ears and tail late behind it
    for deg, at in ((0, 0), (80, 7), (80, 11)):         # from behind: at rest, then twice during a quick quarter turn
        V.append((sh(f"mochi-turn{at}.png"), f"f=mochi.vrm&turn={deg}&at={at}&yaw=180&d=1.9&cy=.25" if deg else "f=mochi.vrm&yaw=180&d=1.9&cy=.25"))
    # --- the thumbnails, 1024 pixels
    V += [(work / "thumbs" / "mochi.png", "f=mochi.vrm&w=1024&h=1024&yaw=-18&d=1.7"), (work / "thumbs" / "onigiri.png", "f=onigiri.vrm&w=1024&h=1024&yaw=18&d=1.7")]
    asyncio.run(shoot(V, work))
    srv.shutdown()
    # --- the sheets of the write-up
    S = lambda *n: [sh(x) for x in n]
    sheet(S("shape-sphere.png", "shape-ellipsoid.png", "shape-lathe.png", "shape-tube.png"), ["sphere()", "ellipsoid(): the body", "lathe(): an ear", "smooth() + tube(): the tail"], 4,
          IMG / "01-shapes.png", "Stage 2 · The building blocks, as wireframes")
    sheet([sh(f"mochi-stage{i}.png") for i in range(1, 7)], [x for x, _ in mst], 3, IMG / "02-mochi-stages.png", "Stage 6 · Mochi, part by part")
    sheet(S("onigiri-sphere.png", "onigiri-body.png"), ["the unit sphere (64 × 40)", "shape(): the rice ball"], 2, IMG / "03-onigiri-shape.png", "Stage 6 · Onigiri's body: a sphere reshaped", tw=480)
    sheet([sh(f"onigiri-stage{i}.png") for i in range(1, 7)], [x for x, _ in ost], 3, IMG / "04-onigiri-stages.png", "Stage 6 · Onigiri, part by part")
    sheet(S("mochi-skeleton.png", "onigiri-skeleton.png"), ["Mochi: 19 humanoid bones, the tail's 4, the ears' 4", "Onigiri: 19 humanoid bones, the ears' 4"], 2,
          IMG / "05-skeletons.png", "Stage 4 · The skeletons (red dots: the bones)", tw=520)
    sheet(S("mochi-weights.png", "mochi-weights-back.png", "onigiri-weights.png", "onigiri-weights-back.png"),
          ["Mochi, front", "Mochi, back: the tail's bones", "Onigiri, front", "Onigiri, back"], 4, IMG / "06-weights.png",
          "Stage 5 · The skin: each point coloured by the bones it follows")
    sheet(S("mochi-pose.png", "onigiri-pose.png"), ["Mochi: a stub foot up, the head tilted", "Onigiri: the same pose"], 2, IMG / "07-poses.png",
          "Stage 5 · The skin at work: the bones move, the surface follows", tw=520)
    mfaces = ["neutral", "blink", "blinkLeft", "aa", "ee", "ou", "happy", "surprised"]
    sheet([sh(f"mochi-face-{e}.png") for e in mfaces], mfaces, 4, IMG / "08-mochi-expressions.png", "Stage 7 · Mochi's expressions (VRM presets)", tw=380)
    ofaces = ["neutral", "blink", "aa", "ou", "happy", "surprised"]
    sheet([sh(f"onigiri-face-{e}.png") for e in ofaces], ofaces, 3, IMG / "09-onigiri-expressions.png", "Stage 7 · Onigiri's expressions (VRM presets)", tw=380)
    sheet(S("mochi-plain.png", "mochi-toon.png", "onigiri-plain.png", "onigiri-toon.png"), ["plain material", "MToon: two tones and an outline", "plain material", "MToon"], 4,
          IMG / "10-toon.png", "Stage 8 · The look: VRM's toon shading (MToon)")
    sheet(S("mochi-turn0.png", "mochi-turn7.png", "mochi-turn11.png"), ["at rest, from behind", "mid-turn: the tail swings out", "nearly round: ears and tail still catching up"], 3,
          IMG / "11-springs.png", "Stage 8 · The spring bones: ears and tail sway")
    glb_diagram(IMG / "12-glb-layout.png", ROOT / "art" / "vrm" / "mochi.vrm")
    sheet([ROOT / "art" / "vrm" / "mochi.png", ROOT / "art" / "vrm" / "onigiri.png"], ["mochi.vrm's thumbnail", "onigiri.vrm's thumbnail"], 2,
          IMG / "13-thumbnails.png", "The thumbnails inside the files (1024 × 1024)", tw=520)
    print("Wrote", len(list(IMG.glob("*.png"))), "figures in", IMG.relative_to(ROOT), "and the thumbnails in", work / "thumbs")


if __name__ == "__main__":
    main(sys.argv)
