#!/usr/bin/env python3
# © Computational Classnotes · CC BY-NC-SA 4.0
# By Dara O Shayda and Hikari Noor Hoshino (星野ヌール), AI System Programming Laboratory.
"""Mochi and Onigiri as VRM 1.0 avatars, built from code (owner, 3 December 2026, 21:38: "design a 3D version of both
characters with tiny feet (stubs) in .vrm format").

   python3 tools/make-vrm.py [--thumbs DIR]     writes art/vrm/mochi.vrm and art/vrm/onigiri.vrm

What a .vrm file is
   A VRM file is a binary glTF 2.0 file (a .glb) with extra sections, the VRM extensions, that tell an avatar program
   which bone is the head, which is the left foot, how the face blinks and speaks, how the hair sways, and under which
   licence the avatar may be used. This script writes three of them:
     VRMC_vrm              the meta data and licence, the humanoid skeleton, the expressions, look-at and first person;
     VRMC_materials_mtoon  the toon (cel) shading of anime avatars, with outlines: the look of Pyon's 2D drawings;
     VRMC_springBone       the ears and Mochi's tail, which sway as the avatar moves.

The stages, in the order this file follows them
   1. Colours        the drawings' sRGB colours, turned into the linear colours glTF expects.         lin, darker
   2. Shapes         small building blocks: sphere, ellipsoid, tube, lathe, smooth curve.             sphere … smooth
   3. Parts          each piece of a creature, its material, its bones and its expression shapes.     Part, on_surface, squash
   4. Skeleton       19 humanoid bones (VRM 1.0), plus the ears' and the tail's own bones.            skeleton
   5. Skin           how strongly each point of the surface follows each bone.                        y_weights (and inline)
   6. The creatures  Mochi and Onigiri, part by part.                                                 mochi, onigiri
   7. Expressions    the face's morph targets: blink, mouth shapes, happy, surprised.                 targets_for_face
   8. Writing        the glTF binary, its materials, nodes, skin, meshes, and the VRM extensions.     GLB, mtoon, build …

Units and axes: metres; Y up; the avatar faces +Z, so its left is +X (VRM 1.0). The rest pose is the bones' translations
alone, with no rotations, as VRM 1.0 asks. Shapes and colours follow Pyon's own drawings (src/pyon.html, LOOKS; art/poses.svg).
--thumbs DIR embeds DIR/mochi.png and DIR/onigiri.png as each avatar's thumbnail, when they exist (tools/vrm-figures.py makes them).
The write-up, stage by stage with pictures: docs/how-mochi-and-onigiri-became-3d.md. The manual: docs/man/ (section 3vrm).
"""
import json, math, pathlib, struct, sys
import numpy as np

ROOT = pathlib.Path(__file__).resolve().parent.parent
OUT = ROOT / "art" / "vrm"


# =====================================================================================================================
# 1. Colours
# =====================================================================================================================
def lin(hexs, a=1.0):
    """'#rrggbb' as drawn (sRGB) -> [r, g, b, a] in linear light, as glTF's colour factors expect.
    Without this step every colour would come out too pale in the avatar programs."""
    c = [int(hexs[i:i + 2], 16) / 255 for i in (1, 3, 5)]
    return [((v / 12.92) if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4) for v in c] + [a]


def darker(h, f=.82):
    """'#rrggbb' with each channel multiplied by f: the shade side of a toon material, or an outline colour."""
    return "#" + "".join(f"{int(int(h[i:i + 2], 16) * f):02x}" for i in (1, 3, 5))


# =====================================================================================================================
# 2. Shapes: every shape is returned as (V, N, I): vertex positions (n×3), unit normals (n×3), triangles (m×3, indices)
# =====================================================================================================================
def rot_to(z_axis):
    """A 3×3 rotation whose local +Z points along z_axis, with local +Y kept as upright as it can be.
    Used to lay a flat shape (an eye, a cheek) on a curved surface, facing out along the surface's normal."""
    z = np.asarray(z_axis, float); z /= np.linalg.norm(z)
    up = np.array([0, 1, 0.0]) if abs(z[1]) < 0.95 else np.array([0, 0, 1.0])   # any helper not parallel to z
    x = np.cross(up, z); x /= np.linalg.norm(x); y = np.cross(z, x)
    return np.stack([x, y, z], axis=1)


def sphere(nu=40, nv=24):
    """A unit sphere, as a grid of nu slices around and nv rings from top to bottom.
    The first and last column meet at the seam but are kept as separate vertices, so the grid stays regular;
    on a unit sphere each normal is the position itself."""
    V, I = [], []
    for j in range(nv + 1):                         # rings, from the top pole (θ = 0) to the bottom (θ = π)
        th = math.pi * j / nv
        for i in range(nu + 1):                     # around, φ from 0 to 2π
            ph = 2 * math.pi * i / nu
            V.append([math.sin(th) * math.sin(ph), math.cos(th), math.sin(th) * math.cos(ph)])
    for j in range(nv):                             # two triangles per grid square, one at each pole
        for i in range(nu):
            a = j * (nu + 1) + i; b = a + nu + 1
            if j: I.append([a, b, a + 1])
            if j < nv - 1: I.append([a + 1, b, b + 1])
    V = np.array(V); return V, V.copy(), np.array(I)


def ellipsoid(c, r, R=np.eye(3), nu=40, nv=24):
    """A sphere stretched by the radii r = (rx, ry, rz), turned by R and moved to the centre c.
    Normals are stretched by 1/r (the rule for normals under scaling), then turned and made unit length."""
    V, N, I = sphere(nu, nv)
    P = (V * r) @ R.T + c
    Nn = (N / r) @ R.T; Nn /= np.linalg.norm(Nn, axis=1, keepdims=True)
    return P, Nn, I


def tube(path, rad, sides=12, caps=True):
    """A tube along a polyline (a tail, a closed eye, a smile), with round ends.
    rad is one radius, or one per point of the path. Each ring is set square to the path's direction; the ring's
    orientation is carried from point to point (a parallel transport frame), so the tube never twists."""
    path = np.asarray(path, float); n = len(path)
    rad = np.full(n, rad) if np.isscalar(rad) else np.asarray(rad, float)
    T = np.gradient(path, axis=0); T /= np.linalg.norm(T, axis=1, keepdims=True)     # the direction at each point
    ref = np.array([0, 0, 1.0]) if abs(T[0][2]) < 0.9 else np.array([1.0, 0, 0])
    V, N, I = [], [], []
    Nprev = None
    for k in range(n):
        t = T[k]
        if Nprev is None: nrm = np.cross(t, ref); nrm /= np.linalg.norm(nrm)           # the first ring's frame
        else: nrm = Nprev - np.dot(Nprev, t) * t; nrm /= np.linalg.norm(nrm)            # carried along, without twist
        Nprev = nrm; b = np.cross(t, nrm)
        for s in range(sides + 1):
            a = 2 * math.pi * s / sides
            d = math.cos(a) * nrm + math.sin(a) * b
            V.append(path[k] + rad[k] * d); N.append(d)
    for k in range(n - 1):                          # join each ring to the next, facing outwards
        for s in range(sides):
            a = k * (sides + 1) + s; c = a + sides + 1
            I += [[a, a + 1, c], [a + 1, c + 1, c]]
    V, N, I = np.array(V), np.array(N), np.array(I)
    if caps:                                        # round ends: a small ball at each end
        for end in (0, n - 1):
            cv, cn, ci = ellipsoid(path[end], [rad[end]] * 3, nu=sides, nv=8)
            I = np.vstack([I, ci + len(V)]); V = np.vstack([V, cv]); N = np.vstack([N, cn])
    return V, N, I


def lathe(profile, axis_origin, axis_dir, segs=24):
    """A body of revolution, as a potter turns it (the ears): profile is [(radius, height), …] from the base up,
    turned round the axis that starts at axis_origin and points along axis_dir. The normals come from the profile's slope."""
    R = rot_to(axis_dir)                            # the local z of the profile is the axis
    V, N, I = [], [], []
    m = len(profile)
    pr = np.asarray(profile, float)
    for k, (r, h) in enumerate(pr):
        dr = pr[min(k + 1, m - 1)][0] - pr[max(k - 1, 0)][0]; dh = pr[min(k + 1, m - 1)][1] - pr[max(k - 1, 0)][1]
        for s in range(segs + 1):
            a = 2 * math.pi * s / segs
            ca, sa = math.cos(a), math.sin(a)
            p = np.array([r * ca, r * sa, h]); nn = np.array([dh * ca, dh * sa, -dr]); nn /= (np.linalg.norm(nn) or 1)
            V.append(R @ p + axis_origin); N.append(R @ nn)
    for k in range(m - 1):
        for s in range(segs):
            a = k * (segs + 1) + s; c = a + segs + 1
            I += [[a, a + 1, c], [a + 1, c + 1, c]]
    return np.array(V), np.array(N), np.array(I)


def smooth(pts, rads, k=8):
    """A Catmull-Rom curve through the points, with k steps between each two, and the radii eased the same way:
    six hand-placed points become a smooth, round tail."""
    P = np.asarray(pts, float); R = np.asarray(rads, float); out, rr = [], []
    for i in range(len(P) - 1):
        p0, p1, p2, p3 = P[max(i - 1, 0)], P[i], P[i + 1], P[min(i + 2, len(P) - 1)]
        for t in np.linspace(0, 1, k, endpoint=False):
            out.append(.5 * (2 * p1 + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + (-p0 + 3 * p1 - 3 * p2 + p3) * t ** 3))
            rr.append(R[i] + (R[i + 1] - R[i]) * t)
    return out + [P[-1]], rr + [R[-1]]


# =====================================================================================================================
# 3. Parts
# =====================================================================================================================
class Part:
    """One piece of a creature: its name, its material (a key of the creature's colours), its shape (V, N, I),
    the bones it follows, and which mesh it belongs to: "body" (the body, ears, tail, feet) or "face" (eyes, cheeks,
    mouth: the mesh that carries the expressions).
    bones is one bone's name (the whole part follows that bone), or a function V -> [{bone: weight}, …], one per vertex.
    morphs maps an expression target's index to the part's vertex positions in that expression."""
    def __init__(self, name, mat, geo, bones, mesh="body"):
        self.name, self.mat, self.mesh = name, mat, mesh
        self.V, self.N, self.I = (np.asarray(a) for a in geo)
        self.bones = bones
        self.morphs = {}


def on_surface(cx, cy, rx, ry, rz, x, y, out=0.004):
    """The point on the front of an ellipsoid body (centre (cx, cy, 0), radii rx, ry, rz) above (x, y), lifted out by
    `out`, and the surface's outward normal there: where an eye or a cheek is laid on Mochi's round body."""
    u = 1 - (x / rx) ** 2 - ((y - cy) / ry) ** 2
    z = rz * math.sqrt(max(u, 0.0))
    n = np.array([x / rx ** 2, (y - cy) / ry ** 2, z / rz ** 2]); n /= np.linalg.norm(n)   # the gradient of the ellipsoid
    return np.array([x, y, z]) + out * n, n


def squash(V, c, sy=1, sx=1, sz=1, dy=0.0):
    """The vertices V scaled about the point c (by sx, sy, sz) and moved up by dy: the tool of every expression,
    such as an eye squashed flat (a blink) or a mouth stretched tall (aa)."""
    c = np.asarray(c); return (V - c) * [sx, sy, sz] + c + [0, dy, 0]


# =====================================================================================================================
# 4. The skeleton and 5. the skin
# =====================================================================================================================
def skeleton(s, tail=False, ears=()):
    """The bones, as (name, parent, position in the world); s scales the whole creature.
    VRM 1.0's humanoid needs hips, spine, head, both upper and lower arms, hands, upper and lower legs and feet; we add
    chest, neck and toes. The creatures have no arms in their drawings, so the arm bones sit inside the body and carry
    nothing. The tiny stub feet hang on the foot bones. Mochi's tail has three bones and an end; each ear has a bone and an end."""
    B = [("hips", None, (0, .14, 0)), ("spine", "hips", (0, .20, 0)), ("chest", "spine", (0, .28, 0)), ("neck", "chest", (0, .36, 0)),
         ("head", "neck", (0, .40, 0))]
    for side, sx in (("left", 1), ("right", -1)):          # the avatar's left is +X
        B += [(f"{side}UpperLeg", "hips", (sx * .11, .12, 0)), (f"{side}LowerLeg", f"{side}UpperLeg", (sx * .11, .08, 0)),
              (f"{side}Foot", f"{side}LowerLeg", (sx * .11, .045, .015)), (f"{side}Toes", f"{side}Foot", (sx * .11, .03, .08)),
              (f"{side}UpperArm", "chest", (sx * .17, .30, 0)), (f"{side}LowerArm", f"{side}UpperArm", (sx * .22, .30, 0)),
              (f"{side}Hand", f"{side}LowerArm", (sx * .26, .30, 0))]
    if tail:
        B += [("tail1", "hips", (-.20, .16, -.16)), ("tail2", "tail1", (-.27, .22, -.20)), ("tail3", "tail2", (-.30, .31, -.22)),
              ("tail_end", "tail3", (-.27, .38, -.21))]
    for nm, base, tip in ears:
        B += [(nm, "head", base), (nm + "_end", nm, tip)]
    return [(n, p, tuple(np.array(x) * s)) for n, p, x in B]


def y_weights(V, s):
    """The body's skin weights, by height: the bottom follows the hips, then the spine, the chest and the head,
    each band blended smoothly into the next (a smoothstep), so that the round body bends softly when the avatar leans."""
    keys = [("hips", .10), ("spine", .20), ("chest", .30), ("head", .44)]
    out = []
    for y in V[:, 1] / s:
        if y <= keys[0][1]: out.append({keys[0][0]: 1.0}); continue
        if y >= keys[-1][1]: out.append({keys[-1][0]: 1.0}); continue
        for (b0, y0), (b1, y1) in zip(keys, keys[1:]):
            if y0 <= y <= y1:
                t = (y - y0) / (y1 - y0); t = t * t * (3 - 2 * t)
                out.append({b0: 1 - t, b1: t}); break
    return out


# =====================================================================================================================
# 6. The creatures
# =====================================================================================================================
def mochi(s=1.0):
    """Mochi: a round cream body, pink-lined ears, a curled tail, big eyes with highlights, cheeks, a small smile,
    a mouth that opens, and two tiny stub feet. Returns the creature as a dict for build()."""
    C = {"body": "#f3e6d3", "line": "#c9b392", "inner": "#ffb3c1", "eye": "#1b1b2e", "white": "#ffffff", "blush": "#ff9aa8",
         "feet": "#e3d2bb", "mouth": "#c45a6a"}     # as drawn in Pyon (LOOKS.mochi); "line" is the outline
    cx, cy, rx, ry, rz = 0, .30 * s, .30 * s, .27 * s, .26 * s     # the body: a slightly squat ball, 0.6 m wide
    parts = []
    # 6.1 the body, skinned from the hips to the head by height
    parts.append(Part("Body", "body", ellipsoid([cx, cy, 0], [rx, ry, rz], nu=56, nv=36), lambda V: y_weights(V, s)))
    # 6.2 the tiny feet: two round stubs, a little forward, each on its foot bone
    for side, sx in (("left", 1), ("right", -1)):
        parts.append(Part(f"Foot_{side}", "feet", ellipsoid(np.array([sx * .11, .035, .045]) * s, np.array([.065, .036, .075]) * s), f"{side}Foot"))
    # 6.3 the ears: rounded cones turned on a lathe, leaning out, each with a smaller pink cone inside, on its own bone
    ears = []
    for side, sx in (("L", 1), ("R", -1)):
        base = np.array([sx * .16, .49, .0]) * s; axis = np.array([sx * .45, 1, .05])
        prof = [(.085 * s, 0), (.08 * s, .03 * s), (.06 * s, .08 * s), (.035 * s, .12 * s), (.012 * s, .145 * s), (0, .15 * s)]
        parts.append(Part(f"Ear_{side}", "body", lathe(prof, base, axis), f"ear_{side}"))
        inner_prof = [(r * .62, h * .85) for r, h in prof]
        ib = base + rot_to(axis) @ np.array([0, -0.012 * s, .02 * s]) + np.array([0, 0, .035 * s])
        parts.append(Part(f"EarInner_{side}", "inner", lathe(inner_prof, ib, axis), f"ear_{side}"))
        ax = axis / np.linalg.norm(axis)
        ears.append((f"ear_{side}", tuple(base / s + ax * .02), tuple(base / s + ax * .15)))
    # 6.4 the tail: six points from the back, curling up, made smooth, then a tube thinning to its tip
    tpath = [np.array(p) * s for p in [(-.17, .14, -.15), (-.24, .17, -.19), (-.29, .23, -.21), (-.31, .30, -.22), (-.29, .36, -.21), (-.25, .39, -.19)]]
    tpath, trad = smooth(tpath, [.038 * s, .042 * s, .04 * s, .036 * s, .032 * s, .028 * s], 8)
    tparts = Part("Tail", "body", tube(tpath, trad, 16), None)
    def tail_w(V):
        """The tail's skin: by height, from half on the hips at its root to wholly on tail3 at its tip."""
        out = []
        for p in V / s:
            h = p[1]
            if h < .18: out.append({"hips": .5, "tail1": .5})
            elif h < .26: out.append({"tail1": .6, "tail2": .4})
            elif h < .33: out.append({"tail2": .5, "tail3": .5})
            else: out.append({"tail3": 1.0})
        return out
    tparts.bones = tail_w; parts.append(tparts)
    # 6.5 the face, on the head bone: eyes (flattened ellipsoids laid on the body), white highlights, pink cheeks,
    #     a smile (a curved tube) and a thin mouth behind it that the expressions open
    face = []
    for side, sx in (("L", 1), ("R", -1)):
        p, n = on_surface(cx, cy, rx, ry, rz, sx * .095 * s, .325 * s, .002 * s)
        e = Part(f"Eye_{side}", "eye", ellipsoid(p, np.array([.042, .052, .014]) * s, rot_to(n), 32, 20), "head", "face")
        hp = p + np.array([sx * .012 + .006, .018, .012]) * s
        h1 = Part(f"Shine_{side}", "white", ellipsoid(hp, np.array([.016, .016, .006]) * s, rot_to(n), 16, 10), "head", "face")
        bp, bn = on_surface(cx, cy, rx, ry, rz, sx * .19 * s, .255 * s, .001 * s)
        bl = Part(f"Cheek_{side}", "blush", ellipsoid(bp, np.array([.038, .022, .006]) * s, rot_to(bn), 24, 12), "head", "face")
        face += [(side, p, e, h1)]
        parts += [e, h1, bl]
    mp, mn = on_surface(cx, cy, rx, ry, rz, 0, .255 * s, .003 * s)
    smile = [mp + np.array([x, -.009 * (1 - (x / .022) ** 2) + .002, 0]) * s for x in np.linspace(-.022, .022, 11)]   # a shallow U
    sm = Part("Smile", "eye", tube(smile, .0045 * s, 8), "head", "face")
    inner_c = mp + np.array([0, -.016, -.004]) * s
    mo = Part("Mouth", "mouth", ellipsoid(inner_c, np.array([.02, .002, .008]) * s, rot_to(mn), 24, 12), "head", "face")   # 2 mm tall: hidden until opened
    parts += [sm, mo]
    # 7. the expressions, as morph targets on the face
    T = targets_for_face(face, sm, mo, s, closed=False)
    return dict(name="Mochi", colours=C, parts=parts, bones=skeleton(s, tail=True, ears=ears), targets=T,
                springs=[("tail", ["tail1", "tail2", "tail3", "tail_end"]), ("ear_L", ["ear_L", "ear_L_end"]), ("ear_R", ["ear_R", "ear_R_end"])],
                eyes_y=.325 * s, height=.64 * s)


def onigiri(s=1.0):
    """Onigiri: a rice-ball body, white ears, the nori wrapped under its base with an orange dot, closed smiling eyes,
    cheeks, a small "w" mouth, and two tiny stub feet. Returns the creature as a dict for build()."""
    C = {"body": "#fafafa", "line": "#b9b9b9", "nori": "#1f3b2d", "dot": "#ff8c1a", "eye": "#1b1b2e", "blush": "#ff9aa8",
         "feet": "#e8e8e8", "mouth": "#c45a6a"}     # as drawn in Pyon (LOOKS.onigiri)
    cy, H = .30 * s, .30 * s
    V, N, I = sphere(64, 40)
    def shape(u):
        """A point u of the unit sphere -> the rice ball: narrow at the top and wide at the bottom, a little flatter at the
        base, and deeper at the bottom than at the top, as a hand-pressed onigiri."""
        x, y, z = u[:, 0], u[:, 1], u[:, 2]
        w = .52 + .48 * (1 - (y + 1) / 2) ** .8            # width: 0.52 at the top, 1 at the bottom
        bot = np.where(y < -.55, 1 - (y + .55) * .25, 1.0)  # a little wider still near the base
        return np.stack([x * w * .32 * s * bot, cy + y * H * np.where(y < 0, .92, 1.0), z * (.75 + .25 * (1 - (y + 1) / 2)) * .25 * s], 1)
    # 6.6 the body: the sphere reshaped; its normals worked out again from the new surface
    P = shape(V)
    Nn = np.zeros_like(P)
    for a, b, c in I:                               # each triangle adds its area-weighted normal to its corners
        n = np.cross(P[b] - P[a], P[c] - P[a]); Nn[a] += n; Nn[b] += n; Nn[c] += n
    ln = np.linalg.norm(Nn, axis=1, keepdims=True)
    Nn = np.where(ln > 1e-9, Nn / np.maximum(ln, 1e-12), V)   # at the two poles, the sphere's own normal
    parts = [Part("Body", "body", (P, Nn, I), lambda V: y_weights(V, s))]
    # 6.7 the nori: a clean strip, made on the unit sphere (a band |x| ≤ 0.36 swept under the bottom from the back to the
    #     front) and then given the same rice-ball shape, lifted 6 mm off the body so it never sinks into it
    nu_, nv_ = 16, 40; G = []
    for j in range(nv_ + 1):
        phi = -1.25 + 2.5 * j / nv_                       # from the back (−) to the front (+), round the bottom
        for i in range(nu_ + 1):
            u = -.36 + .72 * i / nu_; r = math.sqrt(1 - u * u)
            G.append([u, -r * math.cos(phi), r * math.sin(phi)])
    G = np.array(G); NP0 = shape(G)
    NI = []
    for j in range(nv_):
        for i in range(nu_):
            a0 = j * (nu_ + 1) + i; b0 = a0 + nu_ + 1
            NI += [[a0, a0 + 1, b0], [a0 + 1, b0 + 1, b0]]
    NI = np.array(NI); NN = np.zeros_like(NP0)
    for a0, b0, c0 in NI:
        n = np.cross(NP0[b0] - NP0[a0], NP0[c0] - NP0[a0]); NN[a0] += n; NN[b0] += n; NN[c0] += n
    NN /= np.maximum(np.linalg.norm(NN, axis=1, keepdims=True), 1e-12)
    if np.mean(np.sum(NN * (NP0 - [0, cy, 0]), 1)) < 0: NN = -NN; NI = NI[:, [0, 2, 1]]   # make it face outwards
    NP = NP0 + NN * .006 * s
    parts.append(Part("Nori", "nori", (NP, NN, NI), lambda V: y_weights(V, s)))
    # 6.8 the orange dot, on the nori in front
    k = int(np.argmin(np.linalg.norm(V - np.array([0, -.55, .83]), axis=1)))
    parts.append(Part("Dot", "dot", ellipsoid(P[k] + Nn[k] * .008 * s, np.array([.02, .02, .006]) * s, rot_to(Nn[k]), 20, 10), "spine"))
    # 6.9 the ears: white rounded cones, leaning out, each on its own bone
    ears = []
    for side, sx in (("L", 1), ("R", -1)):
        base = np.array([sx * .13, .51, -.01]) * s; axis = np.array([sx * .35, 1, .0])
        prof = [(.075 * s, 0), (.07 * s, .03 * s), (.05 * s, .075 * s), (.025 * s, .11 * s), (.008 * s, .128 * s), (0, .132 * s)]
        parts.append(Part(f"Ear_{side}", "body", lathe(prof, base, axis), f"ear_{side}"))
        ax = axis / np.linalg.norm(axis); ears.append((f"ear_{side}", tuple(base / s + ax * .02), tuple(base / s + ax * .13)))
    # 6.10 the tiny feet
    for side, sx in (("left", 1), ("right", -1)):
        parts.append(Part(f"Foot_{side}", "feet", ellipsoid(np.array([sx * .10, .035, .04]) * s, np.array([.06, .034, .07]) * s), f"{side}Foot"))
    # 6.11 the face: closed, smiling eyes (curved tubes), cheeks, a "w" mouth, and a thin mouth behind it that opens
    def front(x, y, out=.003):
        """The body's vertex nearest to (x, y) among those that face the front, lifted out by `out`, with its normal."""
        k = int(np.argmin(np.linalg.norm(P[:, :2] - [x, y], axis=1) + (Nn[:, 2] < .3) * 9))
        return P[k] + Nn[k] * out * s, Nn[k]
    face = []
    for side, sx in (("L", 1), ("R", -1)):
        p, n = front(sx * .085 * s, .33 * s)
        arc = [p + np.array([t, .013 * math.cos(t / .022 * math.pi / 2) - .013, 0]) for t in np.linspace(-.022, .022, 9) * s]   # an arch: ^
        e = Part(f"Eye_{side}", "eye", tube(arc, .005 * s, 8), "head", "face")
        bp, bn = front(sx * .155 * s, .27 * s, .001)
        bl = Part(f"Cheek_{side}", "blush", ellipsoid(bp, np.array([.032, .019, .006]) * s, rot_to(bn), 24, 12), "head", "face")
        parts += [e, bl]; face.append((side, p, e, None))
    mp, mn = front(0, .275 * s)
    w = [mp + np.array([t, -.006 * abs(math.sin(t / .011 * math.pi / 2)), 0]) for t in np.linspace(-.016, .016, 13) * s]   # w
    sm = Part("Smile", "eye", tube(w, .004 * s, 8), "head", "face")
    mo = Part("Mouth", "mouth", ellipsoid(mp + np.array([0, -.012, -.004]) * s, np.array([.016, .002, .007]) * s, rot_to(mn), 24, 12), "head", "face")
    parts += [sm, mo]
    T = targets_for_face(face, sm, mo, s, closed=True)
    return dict(name="Onigiri", colours=C, parts=parts, bones=skeleton(s, ears=ears), targets=T,
                springs=[("ear_L", ["ear_L", "ear_L_end"]), ("ear_R", ["ear_R", "ear_R_end"])], eyes_y=.33 * s, height=.64 * s)


# =====================================================================================================================
# 7. Expressions
# =====================================================================================================================
TARGET_NAMES = ["blinkL", "blinkR", "mouthOpen", "mouthWide", "mouthRound", "happyEyes", "wideEyes"]


def targets_for_face(face, smile, mouth, s, closed):
    """The face's seven morph targets, written into each part's `morphs` (a part not named in a target stays still):
       0 blinkL, 1 blinkR   an eye squashed flat (and its highlight shrunk away);
       2 mouthOpen          the hidden mouth stretched tall (aa);
       3 mouthWide          the mouth and smile stretched wide (ee, ih);
       4 mouthRound         the mouth tall and narrow (ou, oh);
       5 happyEyes          the eyes closed into upward curves, ^ ^;
       6 wideEyes           the eyes larger (surprised).
    closed is True for Onigiri, whose eyes are always closed arches: they are lowered, raised or stretched instead.
    The VRM expressions (build) are mixtures of these seven."""
    for side, c, eye, shine in face:
        ti = 0 if side == "L" else 1
        if closed:
            eye.morphs[ti] = squash(eye.V, c, sy=.35)
            eye.morphs[5] = squash(eye.V, c, sy=1.3, dy=.006 * s)
            eye.morphs[6] = squash(eye.V, c, sx=1.15, sy=1.6, dy=.004 * s)
        else:
            eye.morphs[ti] = squash(eye.V, c, sy=.08, dy=-.012 * s)
            hv = squash(eye.V, c, sy=.22, dy=.002 * s)         # happy: a thin eye, then bent upwards in the middle, ^ ^
            rx_ = np.ptp(eye.V[:, 0]) / 2 or 1
            hv[:, 1] += .014 * s * (1 - ((eye.V[:, 0] - c[0]) / rx_) ** 2)
            eye.morphs[5] = hv
            eye.morphs[6] = squash(eye.V, c, sx=1.15, sy=1.2)
            if shine is not None:
                shine.morphs[ti] = squash(shine.V, c, sx=0.01, sy=.01, sz=.01, dy=-.012 * s)
                shine.morphs[5] = squash(shine.V, c, sx=0.01, sy=.01, sz=.01)
                shine.morphs[6] = squash(shine.V, c, sx=1.15, sy=1.2)
    mc = mouth.V.mean(0)
    mouth.morphs[2] = squash(mouth.V, mc, sy=14, sx=1.05, dy=-.012 * s)
    mouth.morphs[3] = squash(mouth.V, mc, sy=6, sx=1.5, dy=-.005 * s)
    mouth.morphs[4] = squash(mouth.V, mc, sy=11, sx=.6, dy=-.010 * s)
    sc = smile.V.mean(0)
    smile.morphs[3] = squash(smile.V, sc, sx=1.3)
    smile.morphs[4] = squash(smile.V, sc, sx=.7)
    return TARGET_NAMES


# =====================================================================================================================
# 8. Writing the VRM: a binary glTF 2.0 file (GLB) with the VRM 1.0 extensions
# =====================================================================================================================
class GLB:
    """A glTF 2.0 file being built: `j` is its JSON, `bin` its one binary buffer. Arrays go into the buffer through
    bufferViews (a byte range) and accessors (how to read the range: component type, element type, count)."""
    def __init__(self):
        self.bin = bytearray()
        self.j = {"asset": {"version": "2.0", "generator": "Pyon make-vrm.py · Computational Classnotes"},
                  "buffers": [], "bufferViews": [], "accessors": [], "meshes": [], "nodes": [], "materials": [],
                  "skins": [], "scenes": [{"nodes": []}], "scene": 0}

    def view(self, data, target=None):
        """Append bytes to the buffer (4-byte aligned) and a bufferView for them; returns its index.
        target is 34962 for vertex data and 34963 for triangle indices."""
        while len(self.bin) % 4: self.bin.append(0)
        off = len(self.bin); self.bin += data
        v = {"buffer": 0, "byteOffset": off, "byteLength": len(data)}
        if target: v["target"] = target
        self.j["bufferViews"].append(v); return len(self.j["bufferViews"]) - 1

    def acc(self, arr, ctype, typ, target=None, minmax=False):
        """Append an array and its accessor; returns the accessor's index.
        ctype: 5121 unsigned byte, 5125 unsigned int, 5126 float; typ: "SCALAR", "VEC3", "VEC4", "MAT4".
        minmax writes the bounds, which glTF requires for positions and morph-target positions."""
        arr = np.ascontiguousarray(arr)
        a = {"bufferView": self.view(arr.tobytes(), target), "componentType": ctype, "count": int(arr.shape[0]), "type": typ}
        if minmax: a["min"] = [float(x) for x in arr.min(0)]; a["max"] = [float(x) for x in arr.max(0)]
        self.j["accessors"].append(a); return len(self.j["accessors"]) - 1

    def image(self, png):
        """Embed a PNG (the thumbnail) in the buffer; returns the image's index."""
        self.j.setdefault("images", []).append({"bufferView": self.view(png), "mimeType": "image/png", "name": "thumbnail"})
        return len(self.j["images"]) - 1

    def write(self, path):
        """Write the .glb: a 12-byte header ("glTF", version 2, total length), the JSON chunk padded with spaces to
        4 bytes, then the binary chunk padded with zeros to 4 bytes."""
        self.j["buffers"] = [{"byteLength": len(self.bin)}]
        js = json.dumps(self.j, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        js += b" " * ((4 - len(js) % 4) % 4)
        b = bytes(self.bin) + b"\0" * ((4 - len(self.bin) % 4) % 4)
        out = (struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(js) + 8 + len(b))
               + struct.pack("<II", len(js), 0x4E4F534A) + js
               + struct.pack("<II", len(b), 0x004E4942) + b)
        path.write_bytes(out)


def mtoon(name, colour, shade, outline, width=.004):
    """A glTF material with VRM's toon shading (VRMC_materials_mtoon 1.0): the lit colour, a slightly darker shade
    colour with a hard edge between them (shadingToonyFactor near 1: two tones, as in a drawing), no rim light,
    and an outline of the given width in metres (0: none)."""
    return {"name": name, "pbrMetallicRoughness": {"baseColorFactor": lin(colour), "metallicFactor": 0, "roughnessFactor": 1},
            "doubleSided": False, "alphaMode": "OPAQUE",
            "extensions": {"VRMC_materials_mtoon": {"specVersion": "1.0", "transparentWithZWrite": False, "renderQueueOffsetNumber": 0,
                "shadeColorFactor": lin(shade)[:3], "shadingShiftFactor": -0.05, "shadingToonyFactor": 0.92, "giEqualizationFactor": 0.9,
                "matcapFactor": [0, 0, 0], "parametricRimColorFactor": [0, 0, 0], "parametricRimFresnelPowerFactor": 4.0,
                "parametricRimLiftFactor": 0.0, "rimLightingMixFactor": 0.0,
                "outlineWidthMode": "worldCoordinates" if width else "none", "outlineWidthFactor": width, "outlineColorFactor": lin(outline)[:3],
                "outlineLightingMixFactor": 1.0}}}


def add_materials(g, C):
    """One toon material for each colour of the creature (not the outline colour itself). The body, the feet and the nori
    get a 4.5 mm outline: the body's and feet's in the drawing's line colour, the others a darker tone of their own colour."""
    mats = {}
    for key, col in C.items():
        if key == "line": continue
        width = .0045 if key in ("body", "feet", "nori") else 0.0
        mats[key] = len(g.j["materials"])
        g.j["materials"].append(mtoon(key, col, darker(col, .86 if key != "eye" else 1), C["line"] if key in ("body", "feet") else darker(col, .6), width))
    return mats


def add_skeleton(g, cr):
    """The nodes: a root named after the creature, then one node per bone with its translation from its parent (no
    rotation), then the skin: every bone as a joint, with its inverse bind matrix (here simply minus its world position,
    since nothing is rotated). Returns (names, world positions, node index of each bone, joint index of each bone)."""
    names = [b[0] for b in cr["bones"]]; pos = {b[0]: np.array(b[2], float) for b in cr["bones"]}; par = {b[0]: b[1] for b in cr["bones"]}
    g.j["nodes"].append({"name": cr["name"], "children": []}); root = 0
    nid = {}
    for n in names:
        nid[n] = len(g.j["nodes"])
        rel = pos[n] - (pos[par[n]] if par[n] else 0)
        g.j["nodes"].append({"name": n, "translation": [float(x) for x in rel]})
    for n in names:
        (g.j["nodes"][nid[par[n]]].setdefault("children", []) if par[n] else g.j["nodes"][root]["children"]).append(nid[n])
    joints = [nid[n] for n in names]
    ibm = np.stack([np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [-pos[n][0], -pos[n][1], -pos[n][2], 1]], np.float32).ravel() for n in names])
    g.j["skins"].append({"joints": joints, "inverseBindMatrices": g.acc(ibm.astype(np.float32), 5126, "MAT4"), "skeleton": nid["hips"], "name": "skin"})
    return names, pos, nid, {n: i for i, n in enumerate(names)}


def add_meshes(g, cr, mats, jindex):
    """Two skinned meshes, Body and Face, each with one primitive per material. Every vertex gets up to four bones and
    weights (JOINTS_0, WEIGHTS_0) that sum to 1. The Face mesh also gets the seven morph targets, as position deltas;
    a part without a target gets zeros. Mesh nodes stand at the scene's root, as glTF asks for skinned meshes.
    Returns (face node, mesh nodes); the face node is None when the creature has no face parts."""
    face_node = None; mesh_nodes = []
    for mesh in ("body", "face"):
        ps = [p for p in cr["parts"] if p.mesh == mesh]
        if not ps: continue
        prims = []
        for mkey in dict.fromkeys(p.mat for p in ps):          # the materials, in the order the parts first use them
            group = [p for p in ps if p.mat == mkey]
            V, N, I, J, W, TG = [], [], [], [], [], {t: [] for t in range(len(cr["targets"]))}
            off = 0
            for p in group:
                V.append(p.V); N.append(p.N); I.append(p.I + off); off += len(p.V)
                ws = p.bones(p.V) if callable(p.bones) else [{p.bones: 1.0}] * len(p.V)
                for w in ws:                                    # the four strongest bones, weights summing to 1
                    items = [kv for kv in sorted(w.items(), key=lambda kv: -kv[1])[:4] if kv[1] > 1e-4]; tot = sum(v for _, v in items)
                    J.append([jindex[b] for b, _ in items] + [0] * (4 - len(items)))
                    W.append([v / tot for _, v in items] + [0.0] * (4 - len(items)))
                if mesh == "face":
                    for t in TG: TG[t].append((p.morphs[t] - p.V) if t in p.morphs else np.zeros_like(p.V))
            V = np.vstack(V).astype(np.float32); N = np.vstack(N).astype(np.float32); I = np.vstack(I).astype(np.uint32)
            prim = {"attributes": {"POSITION": g.acc(V, 5126, "VEC3", 34962, True), "NORMAL": g.acc(N, 5126, "VEC3", 34962),
                                   "JOINTS_0": g.acc(np.array(J, np.uint8), 5121, "VEC4", 34962),
                                   "WEIGHTS_0": g.acc(np.array(W, np.float32), 5126, "VEC4", 34962)},
                    "indices": g.acc(I.ravel(), 5125, "SCALAR", 34963), "material": mats[mkey], "mode": 4}
            if mesh == "face":
                prim["targets"] = [{"POSITION": g.acc(np.vstack(TG[t]).astype(np.float32), 5126, "VEC3", 34962, True)} for t in TG]
            prims.append(prim)
        m = {"name": "Face" if mesh == "face" else "Body", "primitives": prims}
        if mesh == "face": m["weights"] = [0.0] * len(cr["targets"]); m["extras"] = {"targetNames": cr["targets"]}
        g.j["meshes"].append(m)
        node = {"name": m["name"], "mesh": len(g.j["meshes"]) - 1, "skin": 0}
        g.j["nodes"].append(node); mesh_nodes.append(len(g.j["nodes"]) - 1)
        if mesh == "face": face_node = len(g.j["nodes"]) - 1
    return face_node, mesh_nodes


def expressions(cr, face_node):
    """VRM 1.0's preset expressions, each a mixture of the face's morph targets with its weights: blink, blinkLeft,
    blinkRight; the five mouth shapes aa, ih, ee, ou, oh (for lip sync); happy (which blocks blinking while it shows),
    surprised, relaxed, sad and angry."""
    T = {n: i for i, n in enumerate(cr["targets"])}
    def binds(*pairs):
        return {"morphTargetBinds": [{"node": face_node, "index": T[t], "weight": w} for t, w in pairs], "isBinary": False,
                "overrideBlink": "none", "overrideLookAt": "none", "overrideMouth": "none"}
    expr = {"blink": binds(("blinkL", 1), ("blinkR", 1)), "blinkLeft": binds(("blinkL", 1)), "blinkRight": binds(("blinkR", 1)),
            "aa": binds(("mouthOpen", 1)), "ih": binds(("mouthWide", .6)), "ee": binds(("mouthWide", 1)), "ou": binds(("mouthRound", 1)),
            "oh": binds(("mouthRound", .7), ("mouthOpen", .4)), "happy": binds(("happyEyes", 1), ("mouthWide", .4)),
            "surprised": binds(("wideEyes", 1), ("mouthRound", .6)), "relaxed": binds(("blinkL", .45), ("blinkR", .45), ("mouthWide", .2)),
            "sad": binds(("blinkL", .3), ("blinkR", .3), ("mouthRound", .2)), "angry": binds(("blinkL", .2), ("blinkR", .2))}
    expr["happy"]["overrideBlink"] = "block"
    return expr


def vrm_meta(cr):
    """VRM 1.0's meta data: the avatar's name, its authors and copyright, and its licence: the VRM Public License 1.0
    with CC BY-NC-SA 4.0. Anyone may use the avatar, personally and non-commercially, with credit; redistribution and
    changes are allowed under the same terms; no violent, sexual, political, religious, antisocial or hateful use."""
    return {"name": cr["name"], "version": "1.0 (Pyon 1.0a1)", "authors": ["Dara O Shayda", "Hikari Noor Hoshino (星野ヌール)"],
            "copyrightInformation": "© Computational Classnotes · CC BY-NC-SA 4.0", "contactInformation": "https://lossofgenerality.github.io/ccn-pyon/library.html",
            "references": ["https://lossofgenerality.github.io/ccn-pyon/"],
            "licenseUrl": "https://vrm.dev/licenses/1.0/", "avatarPermission": "everyone", "allowExcessivelyViolentUsage": False,
            "allowExcessivelySexualUsage": False, "commercialUsage": "personalNonProfit", "allowPoliticalOrReligiousUsage": False,
            "allowAntisocialOrHateUsage": False, "creditNotation": "required", "allowRedistribution": True,
            "modification": "allowModificationRedistribution", "otherLicenseUrl": "https://creativecommons.org/licenses/by-nc-sa/4.0/"}


def springs(cr, nid):
    """VRMC_springBone 1.0: one spring per chain. The tail is soft (stiffness 0.9) and droops a little with gravity;
    the ears are stiffer (1.6) and only wobble."""
    out = []
    for nm, chain in cr["springs"]:
        soft = nm == "tail"
        out.append({"name": nm, "joints": [{"node": nid[b], "hitRadius": .02, "stiffness": .9 if soft else 1.6, "gravityPower": .05 if soft else 0,
                                            "gravityDir": [0, -1, 0], "dragForce": .35 if soft else .55} for b in chain]})
    return {"specVersion": "1.0", "springs": out}


def build(cr, thumb=None):
    """The whole avatar: materials, skeleton and skin, meshes, then the VRM extensions (meta and licence with the
    thumbnail, the humanoid bones, first person, look-at, expressions) and the spring bones. Returns a GLB to write."""
    g = GLB()
    mats = add_materials(g, cr["colours"])
    names, pos, nid, jindex = add_skeleton(g, cr)
    face_node, mesh_nodes = add_meshes(g, cr, mats, jindex)
    g.j["scenes"][0]["nodes"] = [0] + mesh_nodes
    meta = vrm_meta(cr)
    if thumb: meta["thumbnailImage"] = g.image(thumb)
    human = {b: {"node": nid[b]} for b in names if not b.startswith(("tail", "ear_"))}   # the humanoid bones only
    head = pos["head"]
    vrm = {"specVersion": "1.0", "meta": meta, "humanoid": {"humanBones": human},
           # first person: the face is hidden from the wearer's own camera; the body decides for itself
           "firstPerson": {"meshAnnotations": ([{"node": face_node, "type": "thirdPersonOnly"}] if face_node is not None else [])
                           + [{"node": (face_node - 1) if face_node is not None else mesh_nodes[0], "type": "auto"}]},
           # look-at: from between the eyes; the creatures' eyes are part of the face, so the gaze is shown by expressions
           "lookAt": {"offsetFromHeadBone": [0.0, float(cr["eyes_y"] - head[1]), 0.24], "type": "expression",
                      "rangeMapHorizontalInner": {"inputMaxValue": 90, "outputScale": 1}, "rangeMapHorizontalOuter": {"inputMaxValue": 90, "outputScale": 1},
                      "rangeMapVerticalDown": {"inputMaxValue": 90, "outputScale": 1}, "rangeMapVerticalUp": {"inputMaxValue": 90, "outputScale": 1}},
           "expressions": {"preset": expressions(cr, face_node) if face_node is not None else {}}}
    g.j.setdefault("extensions", {})["VRMC_vrm"] = vrm
    g.j["extensions"]["VRMC_springBone"] = springs(cr, nid)
    g.j["extensionsUsed"] = ["VRMC_vrm", "VRMC_materials_mtoon", "VRMC_springBone"]
    return g


def main(argv):
    """Build mochi.vrm and onigiri.vrm in art/vrm/, with their thumbnails when --thumbs DIR is given."""
    OUT.mkdir(parents=True, exist_ok=True)
    tdir = pathlib.Path(argv[argv.index("--thumbs") + 1]) if "--thumbs" in argv else None
    for make in (mochi, onigiri):
        cr = make(1.0)
        png = (tdir / f"{cr['name'].lower()}.png").read_bytes() if tdir and (tdir / f"{cr['name'].lower()}.png").exists() else None
        out = OUT / f"{cr['name'].lower()}.vrm"
        build(cr, png).write(out)
        print("Wrote", out.relative_to(ROOT), f"({out.stat().st_size:,} bytes)" + (", with its thumbnail" if png else ""))


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