"""Cut rigged characters that share one rig into modular parts that fit each other.

The guide: https://hatchery3d.com/blog/modular-characters-from-rigged-models

Run it with Blender 5.2 in the background:

    blender -b --python modular_split.py -- --ref characters/hero.glb --out parts characters/*.glb

It writes into the --out folder:

- <name>.glb for each character: five skinned meshes (head, torso, hands, legs,
  feet) on the skeleton of the reference character, with no clips.
- base.glb: the reference character's parts, with its skeleton and its clips.
- report.json: for each seam, the characters whose parts fit the shared seam,
  and the size of each character's ring against it.
- modular.blend: all the parts in one Blender file, to check them.

The rig must name its bones like one of RIGS below (Hatchery3D or Mixamo).
Add --no-seam-fix to cut only, without the shared seams, to compare.
"""

import argparse
import json
import math
import os
import sys

import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector

# ---------------------------------------------------------------------------
# Settings: change these for your rig.
# ---------------------------------------------------------------------------

SLOTS = ("head", "torso", "hands", "legs", "feet")

# The bones that the slots and the seams use, for each rig. "{s}" is Left or
# Right. To use another rig, add its names here.
RIGS = {
    "hatchery3d": dict(
        prefix="",
        head=("Neck2", "Head", "HeadEnd", "Jaw", "LeftEye", "RightEye"),
        neck=("Neck1", "Neck2"),
        waist=("Spine1", "Spine2"),
        chest="Chest",
        thigh="{s}Leg",
        shin="{s}Shin",
        feet=("{s}Foot", "{s}ToeBase", "{s}ToeEnd"),
    ),
    "mixamo": dict(
        prefix="mixamorig:",
        head=("Head", "HeadTop_End"),
        neck=("Neck", "Head"),
        waist=("Spine", "Spine1"),
        chest="Spine2",
        thigh="{s}UpLeg",
        shin="{s}Leg",
        feet=("{s}Foot", "{s}ToeBase", "{s}Toe_End"),
    ),
}
RIG = {}  # the rig in use: main() picks it from the reference's bone names
SEAMS = []


def bone_name(name, side=""):
    """The full name of a bone in the rig in use."""
    return RIG["prefix"] + name.format(s=side)


def use_rig(bone_names):
    """Pick the rig whose hips bone the reference has, and build its seams."""
    for rig in RIGS.values():
        if rig["prefix"] + "Hips" in bone_names:
            RIG.update(rig)
            break
    else:
        raise RuntimeError("unknown rig: add its bone names to RIGS")
    neck, waist = RIG["neck"], RIG["waist"]
    shoulders = {bone_name("{s}Shoulder", s) for s in ("Left", "Right")}
    thighs = {bone_name(RIG["thigh"], s) for s in ("Left", "Right")}
    # A seam is a plane across a bone, at a fraction t from bone a's head toward
    # bone b's head. Faces of the `cut` bones within `radius` of the bone line
    # are cut along the plane. Inside `blend` metres of the plane, the shape and
    # the weights blend into the shape and the weights that all parts share.
    SEAMS[:] = [
        dict(name="neck", a=bone_name(neck[0]), b=bone_name(neck[1]), t=0.5, below="torso", above="head",
             cut={bone_name(RIG["chest"]), bone_name(neck[0]), bone_name(neck[1]), bone_name("Head")} | shoulders,
             radius=0.2, blend=0.04),
        dict(name="waist", a=bone_name(waist[0]), b=bone_name(waist[1]), t=0.0, below="legs", above="torso",
             cut={bone_name("Hips"), bone_name(waist[0]), bone_name(waist[1])} | thighs, radius=0.4, blend=0.06),
    ]
    for s in ("Left", "Right"):
        forearm, hand = bone_name("{s}ForeArm", s), bone_name("{s}Hand", s)
        shin, foot = bone_name(RIG["shin"], s), bone_name(RIG["feet"][0], s)
        SEAMS.extend([
            dict(name=f"wrist_{s[0].lower()}", a=forearm, b=hand, t=0.85, below="torso", above="hands",
                 cut={forearm, hand}, radius=0.12, blend=0.03),
            dict(name=f"ankle_{s[0].lower()}", a=shin, b=foot, t=0.75, below="legs", above="feet",
                 cut={shin, foot}, radius=0.15, blend=0.04),
        ])


def slot_of_bone(name):
    """The part that a bone's skin goes to, before the seams cut it."""
    short = name.removeprefix(RIG["prefix"])
    sides = ("Left", "Right")
    if short in RIG["head"]:
        return "head"
    if "Hand" in short:
        return "hands"
    if short in {f.format(s=s) for f in RIG["feet"] for s in sides}:
        return "feet"
    if short == "Hips" or short in {RIG[k].format(s=s) for k in ("thigh", "shin") for s in sides}:
        return "legs"
    return "torso"


BINS = 72  # angle steps around a seam ring
MAX_ANGLE_GAP = 10.0  # degrees: a ring with a wider opening is not closed, and keeps its own seam
FIT = (0.67, 1.5)  # how much a ring may grow or shrink to take the shared shape
ON_PLANE = 1e-4  # metres: a vertex this close to a seam plane is on it

# ---------------------------------------------------------------------------


def parse_args():
    argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
    p = argparse.ArgumentParser()
    p.add_argument("--ref", required=True, help="the character whose skeleton and clips all parts use")
    p.add_argument("--out", required=True)
    p.add_argument("--no-seam-fix", action="store_true", help="cut only, to compare")
    p.add_argument("characters", nargs="+")
    return p.parse_args(argv)


def import_glb(path):
    before = set(bpy.data.objects)
    bpy.ops.import_scene.gltf(filepath=path, merge_vertices=True)
    new = [o for o in bpy.data.objects if o not in before]
    arm = next(o for o in new if o.type == "ARMATURE")
    meshes = [o for o in new if o.type == "MESH" and any(m.type == "ARMATURE" for m in o.modifiers)]
    if len(meshes) != 1:
        raise RuntimeError(f"{path}: expected one skinned mesh, found {len(meshes)}")
    return arm, meshes[0], new


def rest_heads(arm):
    return {b.name: np.array(arm.matrix_world @ b.head_local) for b in arm.data.bones}


def main_child(bone, heads):
    """The child that continues the chain: the one most in line with the way into this bone."""
    if not bone.children:
        return None
    into = heads[bone.name] - heads[bone.parent.name] if bone.parent else np.array([0.0, 0.0, 1.0])
    into = into / (np.linalg.norm(into) + 1e-9)

    def straightness(child):
        d = heads[child.name] - heads[bone.name]
        return np.dot(d / (np.linalg.norm(d) + 1e-9), into)

    return max(bone.children, key=straightness)


def rotation_between(u, v):
    """The smallest rotation that turns direction u into direction v (3x3)."""
    u = u / np.linalg.norm(u)
    v = v / np.linalg.norm(v)
    q = Vector(u).rotation_difference(Vector(v))
    return np.array(q.to_matrix())


def conform_maps(ref_arm, ref_heads, src_heads):
    """For each bone: a map (L, src_head, ref_head) that moves the source bone onto the reference bone.

    The map turns the bone to the reference direction and stretches it along
    its length to the reference length. The thickness stays the same.
    """
    maps = {}
    for bone in ref_arm.data.bones:  # parents come before children
        name = bone.name
        child = main_child(bone, ref_heads)
        if child is None:
            lin = maps[bone.parent.name][0] if bone.parent else np.eye(3)
        else:
            ds = src_heads[child.name] - src_heads[name]
            dr = ref_heads[child.name] - ref_heads[name]
            k = np.clip(np.linalg.norm(dr) / max(np.linalg.norm(ds), 1e-6), 0.5, 2.0)
            axis = dr / np.linalg.norm(dr)
            stretch = np.eye(3) + (k - 1.0) * np.outer(axis, axis)
            lin = stretch @ rotation_between(ds, dr)
        maps[name] = (lin, src_heads[name], ref_heads[name])
    return maps


def weight_matrix(obj, bone_names):
    """Vertex weights as a (vertices x bones) array, in the order of bone_names, each row summing to 1."""
    index = {n: i for i, n in enumerate(bone_names)}
    group_bone = {g.index: index.get(g.name) for g in obj.vertex_groups}
    w = np.zeros((len(obj.data.vertices), len(bone_names)), dtype=np.float64)
    for v in obj.data.vertices:
        for g in v.groups:
            b = group_bone.get(g.group)
            if b is not None:
                w[v.index, b] += g.weight
    total = w.sum(axis=1, keepdims=True)
    w[total[:, 0] == 0, index[bone_name("Hips")]] = 1.0
    return w / np.maximum(w.sum(axis=1, keepdims=True), 1e-9)


def seam_frames(ref_heads):
    """Each seam's plane on the reference skeleton: centre, normal, and two axes in the plane."""
    frames = []
    for s in SEAMS:
        a, b = ref_heads[s["a"]], ref_heads[s["b"]]
        n = (b - a) / np.linalg.norm(b - a)
        c = a + s["t"] * (b - a)
        forward = np.array([0.0, -1.0, 0.0])  # glTF characters face -Y in Blender
        u = forward - np.dot(forward, n) * n
        if np.linalg.norm(u) < 1e-3:
            u = np.array([0.0, 0.0, 1.0]) - n[2] * n
        u /= np.linalg.norm(u)
        frames.append(dict(seam=s, c=c, n=n, u=u, v=np.cross(n, u)))
    return frames


def plane_coords(f, co):
    rel = co - f["c"]
    return rel @ f["n"], rel @ f["u"], rel @ f["v"]


def weld(obj):
    """Join the vertices that the glTF file split at UV and normal seams.

    The file's normals go into the corner attribute "shading", so the look of
    the character stays the same after the weld.
    """
    me = obj.data
    normals = np.array([c.vector for c in me.corner_normals])
    attr = me.attributes.new("shading", "FLOAT_VECTOR", "CORNER")
    attr.data.foreach_set("vector", normals.ravel())
    bm = bmesh.new()
    bm.from_mesh(me)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)
    bm.to_mesh(me)
    bm.free()


def conform(obj, arm, ref_arm, ref_heads, bone_names):
    """Move the mesh onto the reference skeleton. Returns the vertex weights."""
    src_heads = rest_heads(arm)
    missing = set(bone_names) - set(src_heads)
    if missing:
        raise RuntimeError(f"{obj.name}: the skeleton has no {sorted(missing)}")
    maps = conform_maps(ref_arm, ref_heads, src_heads)
    w = weight_matrix(obj, bone_names)

    mw = np.array(obj.matrix_world)
    co = np.array([v.co for v in obj.data.vertices])
    co = co @ mw[:3, :3].T + mw[:3, 3]
    out = np.zeros_like(co)
    blended = np.zeros((len(co), 3, 3))  # each vertex's mix of the bone maps, to turn its normals
    for i, name in enumerate(bone_names):
        sel = w[:, i] > 0
        if sel.any():
            lin, hs, hr = maps[name]
            out[sel] += w[sel, i, None] * ((co[sel] - hs) @ lin.T + hr)
            blended[sel] += w[sel, i, None, None] * (lin @ mw[:3, :3])

    me = obj.data
    shading = np.zeros(len(me.loops) * 3)
    me.attributes["shading"].data.foreach_get("vector", shading)
    loop_vert = np.zeros(len(me.loops), dtype=int)
    me.loops.foreach_get("vertex_index", loop_vert)
    turn = np.linalg.inv(blended).transpose(0, 2, 1)[loop_vert]
    shading = np.einsum("lij,lj->li", turn, shading.reshape(-1, 3))
    shading /= np.maximum(np.linalg.norm(shading, axis=1, keepdims=True), 1e-9)
    me.attributes["shading"].data.foreach_set("vector", shading.ravel())

    # Stand on the floor: stretch each foot below the ankle so that the sole is at z = 0.
    for side in ("Left", "Right"):
        names = [bone_name(b, side) for b in (RIG["shin"], *RIG["feet"])]
        chain = [bone_names.index(n) for n in names if n in bone_names]
        ankle_z = ref_heads[bone_name(RIG["feet"][0], side)][2]
        sel = (w[:, chain].sum(axis=1) > 0.5) & (out[:, 2] < ankle_z)
        if sel.any():
            low = out[sel, 2].min()
            if abs(low) > 1e-4 and low < ankle_z - 0.01:
                out[sel, 2] = ankle_z * (out[sel, 2] - low) / (ankle_z - low)

    obj.parent = None
    obj.matrix_world = Matrix()
    obj.data.vertices.foreach_set("co", out.ravel())
    obj.data.update()
    return w


def cut_into_parts(name, obj, w, bone_names, frames, collection):
    """Cut the mesh along the seam planes and split it into one object for each slot."""
    bm = bmesh.new()
    bm.from_mesh(obj.data)
    deform = bm.verts.layers.deform.verify()
    group_bone = {g.index: bone_names.index(g.name) for g in obj.vertex_groups if g.name in bone_names}

    def dominant(face):
        total = np.zeros(len(bone_names))
        for v in face.verts:
            for g, wt in v[deform].items():
                if g in group_bone:
                    total[group_bone[g]] += wt
        return bone_names[int(total.argmax())]

    def near_seam(f, centre):
        d, x, y = plane_coords(f, np.array(centre))
        return math.hypot(x, y) < f["seam"]["radius"]

    for f in frames:
        faces = [fa for fa in bm.faces if dominant(fa) in f["seam"]["cut"] and near_seam(f, fa.calc_center_median())]
        geom = faces + list({e for fa in faces for e in fa.edges}) + list({v for fa in faces for v in fa.verts})
        bmesh.ops.bisect_plane(bm, geom=geom, dist=ON_PLANE / 10, plane_co=f["c"], plane_no=f["n"])

    slot_faces = {s: [] for s in SLOTS}
    for fa in bm.faces:
        bone = dominant(fa)
        slot = slot_of_bone(bone)
        centre = np.array(fa.calc_center_median())
        for f in frames:
            if bone in f["seam"]["cut"] and near_seam(f, centre):
                slot = f["seam"]["above"] if plane_coords(f, centre)[0] > 0 else f["seam"]["below"]
                break
        slot_faces[slot].append(fa.index)

    parts = {}
    for slot in SLOTS:
        if not slot_faces[slot]:
            continue
        keep = set(slot_faces[slot])
        part_bm = bm.copy()
        part_bm.faces.ensure_lookup_table()
        bmesh.ops.delete(part_bm, geom=[fa for fa in part_bm.faces if fa.index not in keep], context="FACES")
        mesh = obj.data.copy()  # a copy keeps the vertex group names and the materials
        mesh.name = f"{name}_{slot}"
        part_bm.to_mesh(mesh)
        part_bm.free()
        part = obj.copy()
        part.data = mesh
        part.name = slot
        part["character"] = name
        part["slot"] = slot
        collection.objects.link(part)
        parts[slot] = part
    bm.free()
    return parts


def ring_vertices(part, f):
    """Indices of the part's open-edge vertices that lie on the seam plane."""
    bm = bmesh.new()
    bm.from_mesh(part.data)
    out = set()
    for e in bm.edges:
        if e.is_boundary:
            for v in e.verts:
                d, x, y = plane_coords(f, np.array(v.co))
                if abs(d) < ON_PLANE and math.hypot(x, y) < f["seam"]["radius"]:
                    out.add(v.index)
    bm.free()
    return sorted(out)


def fill_bins(values, have):
    """Fill empty angle bins by circular linear interpolation."""
    idx = np.flatnonzero(have)
    if len(idx) == 0:
        return values
    out = values.copy()
    xs = np.concatenate([idx - BINS, idx, idx + BINS])
    for dim in range(values.shape[1]) if values.ndim == 2 else [None]:
        col = values[:, dim] if dim is not None else values
        ys = np.concatenate([col[idx]] * 3)
        filled = np.interp(np.arange(BINS), xs, ys)
        if dim is None:
            out = filled
        else:
            out[:, dim] = filled
    return out


def ring_radius(ring, x, y):
    """The radius of a binned ring at the angles of (x, y), interpolated between bins."""
    a = (np.arctan2(y, x) + math.pi) / (2 * math.pi) * BINS - 0.5
    lo = np.floor(a).astype(int)
    t = a - lo
    return (1 - t) * ring[lo % BINS] + t * ring[(lo + 1) % BINS]


def angle_bin(x, y):
    return ((np.arctan2(y, x) + math.pi) / (2 * math.pi) * BINS).astype(int) % BINS


def densify_ring(part, f):
    """Split long ring edges, so that the ring has a vertex at least every 360/BINS degrees.

    A long straight edge cuts inside a round ring, and leaves a sliver gap
    against a ring with more vertices.
    """
    bm = bmesh.new()
    bm.from_mesh(part.data)
    step = 2 * math.pi / BINS
    by_cuts = {}
    for e in bm.edges:
        if not e.is_boundary:
            continue
        p = [plane_coords(f, np.array(v.co)) for v in e.verts]
        if all(abs(d) < ON_PLANE and math.hypot(x, y) < f["seam"]["radius"] for d, x, y in p):
            span = abs((math.atan2(p[0][2], p[0][1]) - math.atan2(p[1][2], p[1][1]) + math.pi) % (2 * math.pi) - math.pi)
            cuts = math.ceil(span / step) - 1
            if cuts > 0:
                by_cuts.setdefault(cuts, []).append(e)
    for cuts, edges in by_cuts.items():
        bmesh.ops.subdivide_edges(bm, edges=edges, cuts=cuts, use_grid_fill=False)
    bm.to_mesh(part.data)
    bm.free()


def angle_gap(part, f):
    """The widest angle, in degrees, that no ring edge covers: 0 for a closed ring, 360 for no ring."""
    covered = np.zeros(720, dtype=bool)
    bm = bmesh.new()
    bm.from_mesh(part.data)
    for e in bm.edges:
        if not e.is_boundary:
            continue
        p = [plane_coords(f, np.array(v.co)) for v in e.verts]
        if not all(abs(d) < ON_PLANE and math.hypot(x, y) < f["seam"]["radius"] for d, x, y in p):
            continue
        a0, a1 = (math.degrees(math.atan2(y, x)) for _, x, y in p)
        span = (a1 - a0 + 180) % 360 - 180
        steps = max(2, int(abs(span) * 2) + 2)
        for t in np.linspace(0, 1, steps):
            covered[int(((a0 + t * span) % 360) * 2) % 720] = True
    bm.free()
    if not covered.any():
        return 360.0
    run, best = 0, 0
    for c in np.r_[covered, covered]:
        run = 0 if c else run + 1
        best = max(best, run)
    return min(best, 720) / 2


def profile(part, f):
    """The outer radius of the seam ring at each angle."""
    ids = ring_vertices(part, f)
    co = np.array([part.data.vertices[i].co for i in ids])
    _, x, y = plane_coords(f, co)
    r = np.hypot(x, y)
    bins = angle_bin(x, y)
    prof = np.zeros(BINS)
    for b, rr in zip(bins, r):
        prof[b] = max(prof[b], rr)
    prof = fill_bins(prof, prof > 0)
    smooth = sum(np.roll(prof, k) for k in range(-2, 3)) / 5
    return smooth, ids


def ring_loops(part, ids):
    """How many separate loops the ring vertices make."""
    ids = set(ids)
    links = {i: set() for i in ids}
    for e in part.data.edges:
        a, b = e.vertices
        if a in ids and b in ids:
            links[a].add(b)
            links[b].add(a)
    seen, loops = set(), 0
    for i in ids:
        if i in seen:
            continue
        loops += 1
        stack = [i]
        while stack:
            j = stack.pop()
            if j not in seen:
                seen.add(j)
                stack.extend(links[j] - seen)
    return loops


def blend_factor(d, blend):
    t = np.clip(1.0 - np.abs(d) / blend, 0.0, 1.0)
    return t * t * (3 - 2 * t)


def standardise_seams(chars, frames, bone_names):
    """Give every character that fits the same ring shape, ring weights and ring normals at each seam."""
    report = {name: {} for name in chars}
    for f in frames:
        s = f["seam"]
        profiles, ring_ids = {}, {}
        for name, parts in chars.items():
            if s["below"] in parts and s["above"] in parts:
                prof, ids = profile(parts[s["below"]], f)
                if len(ids) >= 3:
                    profiles[name], ring_ids[name] = prof, ids

        # The shared ring: the median shape. A ring that must grow or shrink
        # past the limits keeps its own shape, and its parts fit only each other.
        def size(prof, target):  # the ring's size against the shared ring, by area
            return float(np.sqrt(np.mean(prof**2) / np.mean(target**2)))

        closed = {n for n in profiles if max(angle_gap(chars[n][s["below"]], f), angle_gap(chars[n][s["above"]], f)) <= MAX_ANGLE_GAP}

        def fitting(target):
            return {n for n, p in profiles.items() if n in closed and FIT[0] <= size(p, target) <= FIT[1]}

        target = np.median(list(profiles.values()), axis=0)
        fits = fitting(target)
        target = np.median([profiles[n] for n in fits], axis=0)
        fits = fitting(target)
        f["target"], f["fits"] = target, fits

        # The weights that every ring gets: the mean ring weights, four bones at most.
        canon = np.mean([weight_matrix(chars[n][s["below"]], bone_names)[ring_ids[n]].mean(axis=0) for n in fits], axis=0)
        canon[np.argsort(canon)[:-4]] = 0
        canon /= canon.sum()
        f["weights"] = {bone_names[i]: float(canon[i]) for i in np.flatnonzero(canon)}

        for name, prof in profiles.items():
            scale = target / np.maximum(prof, 1e-4)
            report[name][s["name"]] = dict(
                fits=name in fits,
                closed=name in closed,
                size=round(size(prof, target), 2),
                loops=ring_loops(chars[name][s["below"]], ring_ids[name]),
            )
            if name not in fits:
                continue
            for side, sign in ((s["below"], -1), (s["above"], 1)):
                part = chars[name][side]
                densify_ring(part, f)
                co = np.array([v.co for v in part.data.vertices])
                d, x, y = plane_coords(f, co)
                sel = (sign * d >= -ON_PLANE) & (np.abs(d) < s["blend"]) & (np.hypot(x, y) < s["radius"])
                if not sel.any():
                    continue
                # Each vertex moves toward the shared ring: on the seam it lands on
                # the ring, and the move fades out over `blend`. Inner cloth layers
                # land on the ring too, so no layer leaves a hole at the seam.
                k = blend_factor(d[sel], s["blend"])
                r = np.maximum(np.hypot(x[sel], y[sel]), 1e-4)
                grow = (ring_radius(target, x[sel], y[sel]) / r - 1) * k
                co[sel] += (x[sel] * grow)[:, None] * f["u"] + (y[sel] * grow)[:, None] * f["v"]
                part.data.vertices.foreach_set("co", co.ravel())
                part.data.update()
                set_ring_weights(part, np.flatnonzero(sel), k, f["weights"], bone_names)

    # Normals last, after every seam has its shape.
    set_normals(chars, frames)
    return report


def set_ring_weights(part, verts, k, canon, bone_names):
    groups = {g.name: g for g in part.vertex_groups}
    for name in canon:
        if name not in groups:
            groups[name] = part.vertex_groups.new(name=name)
    index_name = {g.index: g.name for g in part.vertex_groups}
    for vi, t in zip(verts, k):
        old = {index_name[g.group]: g.weight for g in part.data.vertices[vi].groups}
        total = sum(old.values()) or 1.0
        new = {n: (1 - t) * old.get(n, 0) / total + t * canon.get(n, 0) for n in set(old) | set(canon)}
        for n, wt in new.items():
            if wt < 1e-4:
                groups[n].remove([int(vi)])
            else:
                groups[n].add([int(vi)], wt, "REPLACE")


def ring_normals(chars, f):
    """The normal that every ring vertex of this seam gets, at each angle: the mean over all parts."""
    s = f["seam"]
    sums = np.zeros((BINS, 3))
    for name, parts in chars.items():
        if name not in f["fits"]:
            continue
        for side in (s["below"], s["above"]):
            if side not in parts:
                continue
            part = parts[side]
            ids = ring_vertices(part, f)
            if not ids:
                continue
            normals = np.array([part.data.vertices[i].normal for i in ids])
            _, x, y = plane_coords(f, np.array([part.data.vertices[i].co for i in ids]))
            np.add.at(sums, angle_bin(x, y), normals)
    canon = fill_bins(sums, np.linalg.norm(sums, axis=1) > 1e-6)
    return canon / np.maximum(np.linalg.norm(canon, axis=1, keepdims=True), 1e-9)


def set_normals(chars, frames):
    """Put the file's own normals back, with the shared normals on every seam ring."""
    canon = [ring_normals(chars, f) for f in frames]
    for name, parts in chars.items():
        for part in parts.values():
            me = part.data
            normals = np.zeros(len(me.loops) * 3)
            me.attributes["shading"].data.foreach_get("vector", normals)
            normals = normals.reshape(-1, 3)
            loop_vert = np.zeros(len(me.loops), dtype=int)
            me.loops.foreach_get("vertex_index", loop_vert)
            for f, ring in zip(frames, canon):
                if name not in f["fits"]:
                    continue
                ids = ring_vertices(part, f)
                if not ids:
                    continue
                _, x, y = plane_coords(f, np.array([me.vertices[i].co for i in ids]))
                vert_bin = dict(zip(ids, angle_bin(x, y)))
                for li, vi in enumerate(loop_vert):
                    if vi in vert_bin:
                        normals[li] = ring[vert_bin[vi]]
            me.normals_split_custom_set([tuple(n) for n in normals])
            me.attributes.remove(me.attributes["shading"])


def export(path, arm, parts, animations):
    # Each part's node gets the plain slot name ("head"), so that a game finds it by name.
    for p in parts:
        holder = bpy.data.objects.get(p["slot"])
        if holder is not None and holder != p:
            holder.name = f'{holder["character"]}_{holder["slot"]}'
        p.name = p["slot"]
    bpy.ops.object.select_all(action="DESELECT")
    arm.select_set(True)
    for p in parts:
        p.select_set(True)
    bpy.context.view_layer.objects.active = arm
    bpy.ops.export_scene.gltf(
        filepath=path,
        use_selection=True,
        export_animations=animations,
        export_animation_mode="ACTIONS",
        export_yup=True,
    )


def main():
    args = parse_args()
    os.makedirs(args.out, exist_ok=True)
    bpy.ops.wm.read_factory_settings(use_empty=True)
    bpy.context.scene.render.fps = 30

    ref_arm, ref_mesh, ref_objects = import_glb(args.ref)
    ref_arm.name = "Rig"
    bone_names = [b.name for b in ref_arm.data.bones]
    use_rig(bone_names)
    ref_heads = rest_heads(ref_arm)
    frames = seam_frames(ref_heads)
    collection = bpy.context.scene.collection

    chars = {}
    for path in args.characters:
        name = os.path.splitext(os.path.basename(path))[0]
        if os.path.abspath(path) == os.path.abspath(args.ref):
            arm, obj, objects = ref_arm, ref_mesh, []
        else:
            actions = set(bpy.data.actions)
            arm, obj, objects = import_glb(path)
            for action in set(bpy.data.actions) - actions:  # only the reference's clips ship
                bpy.data.actions.remove(action)
        weld(obj)
        w = conform(obj, arm, ref_arm, ref_heads, bone_names)
        parts = cut_into_parts(name, obj, w, bone_names, frames, collection)
        for part in parts.values():
            part.parent = ref_arm
            part.matrix_parent_inverse = ref_arm.matrix_world.inverted()
            for m in part.modifiers:
                if m.type == "ARMATURE":
                    m.object = ref_arm
        for o in objects:
            if o != obj:
                bpy.data.objects.remove(o)
        bpy.data.objects.remove(obj)
        chars[name] = parts
        print(f"cut {name}: " + ", ".join(f"{s} {len(p.data.polygons)}" for s, p in parts.items()), flush=True)

    if args.no_seam_fix:
        report = {}
        set_normals(chars, [])
        for f in frames:
            f["weights"], f["target"], f["fits"] = {}, np.zeros(1), set()
    else:
        report = standardise_seams(chars, frames, bone_names)

    for name, parts in chars.items():
        export(os.path.join(args.out, f"{name}.glb"), ref_arm, list(parts.values()), animations=False)
    ref_name = os.path.splitext(os.path.basename(args.ref))[0]
    if ref_name in chars:
        export(os.path.join(args.out, "base.glb"), ref_arm, list(chars[ref_name].values()), animations=True)
    bpy.ops.wm.save_as_mainfile(filepath=os.path.join(os.path.abspath(args.out), "modular.blend"))

    seams = {
        f["seam"]["name"]: dict(
            ring_weights=f["weights"],
            mean_radius_cm=round(100 * float(f["target"].mean()), 2),
            plane=dict(centre=f["c"].tolist(), normal=f["n"].tolist(), u=f["u"].tolist(), v=f["v"].tolist()),
            below=f["seam"]["below"], above=f["seam"]["above"], radius=f["seam"]["radius"],
            fits=sorted(f["fits"]),
        )
        for f in frames
    }
    with open(os.path.join(args.out, "report.json"), "w") as fh:
        json.dump(dict(seams=seams, characters=report), fh, indent=1)
    print("done", len(chars), "characters", flush=True)


main()
