agent

+1:57
reasoning

Initial investigation focuses on several files related to rendering and shell interaction: kit/makers/shell.py, src/render/mech.ts, src/render/palette.ts, src/render/decals.ts, and src/view/viewer.ts. The initial hypothesis is that rendering or shell generation are likely related to the observed issue. The files will be assessed to better understand their roles.

  • read_file{"Path":"~/work/sortie/kit/makers/shell.py"}

    input

    {
      "Path": "~/work/sortie/kit/makers/shell.py"
    }

    result, 298 lines

    Showing lines 1-297 of 297
    1: """Plate building blocks every maker family shares (docs/visual-language.md, Plates).
    2: 
    3: A plate is a slab on one face of a segment. A Face maps 2D outline coordinates (u across, v up) and
    4: a depth w (outward) to world space, so outlines are written in plain world numbers:
    5: 
    6:   front(y)   the face at y, facing -Y   u = x       v = z
    7:   back(y)    facing +Y                  u = x       v = z
    8:   outer(x)   facing +X (the left side)  u = -y      v = z    (u grows toward the front)
    9:   inner(x)   facing -X                  u = -y      v = z
    10:   top(z)     facing up                  u = x       v = -y   (v grows toward the front)
    11: 
    12: Most plates are shells (below): closed blocks from a front and a side outline. Every plate is
    13: closed, none is hollow with its inside showing. Every plate is authored on the left (+X) and
    14: mirrored for the right unless it straddles the centre line. A maker family decides its outlines,
    15: its band, its chamfer and how each grade sizes and adds to them.
    16: """
    17: import bmesh
    18: import bpy
    19: from mathutils import Matrix, Vector
    20: 
    21: from lib import boolean, ccw, clip, copy, empty, link, loft, merge, mirror_x, solid, transform, two_view
    22: from mech import gltf_dir
    23: 
    24: 
    25: class Face:
    26:     def __init__(self, origin, u, v, w):
    27:         self.o, self.u, self.v, self.w = Vector(origin), Vector(u), Vector(v), Vector(w)
    28:         self.m = Matrix((self.u, self.v, self.w)).transposed().to_4x4()
    29:         self.m.translation = self.o
    30: 
    31:     def at(self, u, v, d=0.0):
    32:         return self.o + self.u * u + self.v * v + self.w * d
    33: 
    34:     def slab(self, outline, d0, d1):
    35:         """The outline pushed out from depth d0 to d1."""
    36:         poly = ccw(list(outline))
    37:         return transform(loft([(d0, poly), (d1, poly)]), self.m)
    38: 
    39: 
    40: def front(y):
    41:     return Face((0, y, 0), (1, 0, 0), (0, 0, 1), (0, -1, 0))
    42: 
    43: 
    44: def back(y):
    45:     return Face((0, y, 0), (1, 0, 0), (0, 0, 1), (0, 1, 0))
    46: 
    47: 
    48: def outer(x):
    49:     return Face((x, 0, 0), (0, -1, 0), (0, 0, 1), (1, 0, 0))
    50: 
    51: 
    52: def inner(x):
    53:     return Face((x, 0, 0), (0, -1, 0), (0, 0, 1), (-1, 0, 0))
    54: 
    55: 
    56: def top(z):
    57:     return Face((0, 0, z), (1, 0, 0), (0, -1, 0), (0, 0, 1))
    58: 
    59: 
    60: def bottom(z):
    61:     return Face((0, 0, z), (1, 0, 0), (0, 1, 0), (0, 0, -1))
    62: 
    63: 
    64: def clipped(u0, u1, v0, v1, c, taper=(0.0, 0.0), corner="tr"):
    65:     """A rectangle with one 45 degree clip of size c. `taper` insets the bottom edge from the left and
    66:     right. `corner`: tr (top right, the usual outboard top), tl, or both."""
    67:     tl, tr = taper
    68:     c = min(c, (u1 - u0) * .6, (v1 - v0) * .6)
    69:     pts = [(u0 + tl, v0), (u1 - tr, v0)]
    70:     pts += [(u1, v1 - c), (u1 - c, v1)] if corner in ("tr", "both") else [(u1, v1)]
    71:     pts += [(u0 + c, v1), (u0, v1 - c)] if corner in ("tl", "both") else [(u0, v1)]
    72:     return pts
    73: 
    74: 
    75: def clip_v(poly, lo, hi):
    76:     """The part of a polygon with lo <= v <= hi (Sutherland-Hodgman on two edges)."""
    77:     def cut(pts, keep, edge):
    78:         out = []
    79:         for i, a in enumerate(pts):
    80:             b = pts[(i + 1) % len(pts)]
    81:             ia, ib = keep(a), keep(b)
    82:             if ia:
    83:                 out.append(a)
    84:             if ia != ib:
    85:                 t = (edge - a[1]) / (b[1] - a[1])
    86:                 out.append((a[0] + (b[0] - a[0]) * t, edge))
    87:         return out
    88:     pts = cut(list(poly), lambda p: p[1] >= lo, lo)
    89:     return cut(pts, lambda p: p[1] <= hi, hi) if pts else []
    90: 
    91: 
    92: def clip_u(poly, lo, hi):
    93:     swap = [(v, u) for u, v in poly]
    94:     return [(u, v) for v, u in clip_v(swap, lo, hi)]
    95: 
    96: 
    97: class Plates:
    98:     """Collects one family's plates for a frame and writes them as solids on the joints."""
    99: 
    100:     def __init__(self, n, chamfer, roles=("main", "accent"), smooth=False):
    101:         """smooth: shade plates smooth with sharp rims, for families whose plates are curved."""
    102:         self.n, self.ch = n, chamfer
    103:         self.main, self.band_role = roles
    104:         self.smooth = smooth
    105: 
    106:     def _put(self, name, bm, role, jl, jr, bevel):
    107:         kw = dict(bevel=bevel, panels=False, smooth=self.smooth)
    108:         if jr is None:
    109:             return solid(f"{self.n}_{name}", bm, role, jl, **kw)
    110:         right = mirror_x(bm)
    111:         solid(f"{self.n}_{name}.L", bm, role, jl, **kw)
    112:         solid(f"{self.n}_{name}.R", right, role, jr, **kw)
    113: 
    114:     def plate(self, name, face, outline, t, jl, jr=None, band=None, recess=None, role=None, d0=0.0, lean=None):
    115:         """A slab of thickness t on a face, standing d0 off it. With band=(v0, v1) the slab is cut into
    116:         upper and lower pieces and a recessed band between them in the band role. `lean` (a matrix,
    117:         see shear) tilts the plate."""
    118:         role = role or self.main
    119:         slab = (lambda poly, a, b: face.slab(poly, a, b)) if lean is None else (lambda poly, a, b: transform(face.slab(poly, a, b), lean))
    120:         if band is None:
    121:             self._put(name, slab(outline, d0, d0 + t), role, jl, jr, self.ch)
    122:             return
    123:         recess = recess if recess is not None else max(.04, t * .35)
    124:         b0, b1 = band
    125:         lo, mid, hi = clip_v(outline, -1e3, b0), clip_v(outline, b0, b1), clip_v(outline, b1, 1e3)
    126:         pieces = [(f"{name}_lo", lo, role, t), (f"{name}_hi", hi, role, t), (f"{name}_band", mid, self.band_role, t - recess)]
    127:         for nm, poly, r, tt in pieces:
    128:             if len(poly) >= 3:
    129:                 self._put(nm, slab(poly, d0, d0 + tt), r, jl, jr, self.ch if r == role else self.ch * .5)
    130: 
    131:     def solid(self, name, bm, role, jl, jr=None, bevel=None):
    132:         self._put(name, bm, role, jl, jr, self.ch if bevel is None else bevel)
    133: 
    134:     def marks(self, name, face, d, blocks, jl, jr=None, role="stencil", lean=None):
    135:         """Stencil markings: flat blocks [(u0, v0, u1, v1), ...] standing 0.012 off depth d."""
    136:         bms = [face.slab([(u0, v0), (u1, v0), (u1, v1), (u0, v1)], d - .01, d + .012) for u0, v0, u1, v1 in blocks]
    137:         if lean is not None:
    138:             bms = [transform(b, lean) for b in bms]
    139:         self._put(name, merge(*bms), role, jl, jr, 0)
    140: 
    141: 
    142: def text_row(u0, v0, h, widths, gap=.05):
    143:     """A line of stencil text as blocks: one block per word, `widths` in metres."""
    144:     out, u = [], u0
    145:     for w in widths:
    146:         out.append((u, v0, u + w, v0 + h))
    147:         u += w + gap
    148:     return out
    149: 
    150: 
    151: def shear(axis, k, zref):
    152:     """A lean: x or y moves by k per metre of height above zref. Tilts a plate without bending it."""
    153:     m = Matrix.Identity(4)
    154:     i = {"x": 0, "y": 1}[axis]
    155:     m[i][2] = k
    156:     m[i][3] = -k * zref
    157:     return m
    158: 
    159: 
    160: def bearing(name, face, u, v, d, parent, size, lean=None):
    161:     """An insignia anchor on a plate face: the decal layer looks these up by name."""
    162:     at = face.at(u, v, d + .02)
    163:     if lean is not None:
    164:         at = lean @ at
    165:     return empty(f"bearing.{name}", at, parent, dir=gltf_dir(-face.w), size=size)
    166: 
    167: 
    168: def mirror_face(face):
    169:     """The same face on the right side."""
    170:     f = lambda p: Vector((-p.x, p.y, p.z))
    171:     out = Face(f(face.o), f(face.u), f(face.v), f(face.w))
    172:     return out
    173: 
    174: 
    175: # ---- shells: plates with a volume ------------------------------------------------------------------------
    176: # A shell is the intersection of a front outline (x, z) and a side outline (y, z), the two_view block.
    177: # Every plate is closed: a whole block, or with keep = the outward faces a thin plate on those faces
    178: # only, the block minus a copy of itself moved inward by the thickness. Directions: -x +x -y +y -z +z
    179: # (front is -y).
    180: 
    181: def inset(poly, d):
    182:     """A polygon moved inward by d along every edge (outward for d < 0), corners mitred."""
    183:     poly = ccw(list(poly))
    184:     n = len(poly)
    185:     lines = []
    186:     for i in range(n):
    187:         (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n]
    188:         ex, ey = x1 - x0, y1 - y0
    189:         L = (ex * ex + ey * ey) ** .5 or 1.0
    190:         nx, ny = -ey / L, ex / L  # left of the edge is inside for a CCW polygon
    191:         lines.append(((x0 + nx * d, y0 + ny * d), (ex, ey)))
    192:     out = []
    193:     for i in range(n):
    194:         (p, e), (q, f) = lines[i - 1], lines[i]
    195:         den = e[0] * f[1] - e[1] * f[0]
    196:         if abs(den) < 1e-9:
    197:             out.append(q)
    198:             continue
    199:         t = ((q[0] - p[0]) * f[1] - (q[1] - p[1]) * f[0]) / den
    200:         out.append((p[0] + e[0] * t, p[1] + e[1] * t))
    201:     return out
    202: 
    203: 
    204: def _bool(a, b, op):
    205:     me = bpy.data.meshes.new("_sh")
    206:     a.to_mesh(me)
    207:     a.free()
    208:     o = link(bpy.data.objects.new("_sh", me))
    209:     boolean(o, b, op)
    210:     out = bmesh.new()
    211:     out.from_mesh(o.data)
    212:     data = o.data
    213:     bpy.data.objects.remove(o, do_unlink=True)
    214:     bpy.data.meshes.remove(data)
    215:     return out
    216: 
    217: 
    218: def subtract(a, b):
    219:     """a minus b, both bmeshes (both are used up)."""
    220:     return _bool(a, b, "DIFFERENCE")
    221: 
    222: 
    223: DIRS = {"-x": (-1, 0, 0), "+x": (1, 0, 0), "-y": (0, -1, 0), "+y": (0, 1, 0), "-z": (0, 0, -1), "+z": (0, 0, 1)}
    224: 
    225: 
    226: def behind(front, side, t, keep, top=None):
    227:     """The block moved inward by t from the `keep` faces: what is taken away to leave a thin plate.
    228:     It is grown across the other axes, so its side walls never lie in the plate's own side walls:
    229:     coplanar walls leave the boolean stray slivers there."""
    230:     v = Vector((0, 0, 0))
    231:     for d in keep:
    232:         v -= Vector(DIRS[d])
    233:     axes = {d[1] for d in keep}
    234:     g = .3
    235:     f = front if axes & {"x", "z"} else inset(front, -g)
    236:     s = side if axes & {"y", "z"} else inset(side, -g)
    237:     tp = top if top is None or "z" in axes else inset(top, -g)
    238:     return transform(two_view(f, s, tp), Matrix.Translation(v * t))
    239: 
    240: 
    241: def plan(front, side, cf=.2, cb=.12):
    242:     """A plan outline (x, y) over a front and a side outline, its corners chamfered: cf at the front,
    243:     cb at the back. Takes the box out of a two_view block."""
    244:     xs, ys = [p[0] for p in front], [p[0] for p in side]
    245:     x0, x1, y0, y1 = min(xs) - .01, max(xs) + .01, min(ys) - .01, max(ys) + .01
    246:     return [(x0 + cf, y0), (x1 - cf, y0), (x1, y0 + cf), (x1, y1 - cb), (x1 - cb, y1), (x0 + cb, y1), (x0, y1 - cb), (x0, y0 + cf)]
    247: 
    248: 
    249: def shell(front, side, t=0.0, keep=None, top=None):
    250:     """A closed plate with a volume: the whole block, or a plate of thickness t on the keep faces."""
    251:     bm = two_view(front, side, top)
    252:     if keep is None:
    253:         return bm
    254:     return _bool(bm, behind(front, side, t, keep, top), "DIFFERENCE")
    255: 
    256: 
    257: def banded(front, side, t, keep, band, recess=.06, top=None):
    258:     """A shell cut across by a recessed service band between heights band = (z0, z1). Returns
    259:     (pieces in the main role, band piece)."""
    260:     z0, z1 = band
    261:     whole = shell(front, side, t, keep, top)
    262:     lo, hi = clip(copy(whole), z=(-60, z0)), clip(whole, z=(z1, 60))
    263:     b = two_view(inset(front, recess), inset(side, recess), inset(top, recess) if top is not None else None)
    264:     if keep is not None:
    265:         b = _bool(b, behind(front, side, t, keep, top), "DIFFERENCE")
    266:     return [p for p in (lo, hi) if len(p.faces) >= 4], clip(b, z=(z0, z1))
    267: 
    268: 
    269: 
    270: def inset_panel(front, side, t, keep, box, recess=.06, top=None, cut_back=.02):
    271:     """A shell with a recessed panel let into its front face: box = (x0, x1, z0, z1). Returns (the
    272:     shell with the opening, the panel set back by `recess`)."""
    273:     x0, x1, z0, z1 = box
    274:     y = max(surface(side, z, 0, -1)[0] for z in (z0, (z0 + z1) / 2, z1))
    275:     whole = shell(front, side, t, keep, top)
    276:     hole = two_view([(x0, z0), (x1, z0), (x1, z1), (x0, z1)], [(-60, z0), (y + t + cut_back, z0), (y + t + cut_back, z1), (-60, z1)])
    277:     main = subtract(whole, hole)
    278:     p = two_view(inset(front, recess), inset(side, recess), inset(top, recess) if top is not None else None)
    279:     p = clip(p, x=(x0, x1), y=(-60, y + t + cut_back), z=(z0, z1))
    280:     if keep is not None:
    281:         p = subtract(p, behind(front, side, t, keep, top))
    282:     return main, p
    283: 
    284: 
    285: def surface(poly, z, axis=0, sign=-1):
    286:     """Where an outline is outermost at height z: poly in (u, z), the extreme u toward sign, and the
    287:     slope du/dz of the edge there. For a side outline (y, z) and sign -1 that is the front face."""
    288:     best = None
    289:     n = len(poly)
    290:     for i in range(n):
    291:         (u0, z0), (u1, z1) = poly[i], poly[(i + 1) % n]
    292:         if min(z0, z1) <= z <= max(z0, z1) and z1 != z0:
    293:             k = (u1 - u0) / (z1 - z0)
    294:             u = u0 + k * (z - z0)
    295:             if best is None or u * sign > best[0] * sign:
    296:                 best = (u, k)
    297:     return best
  • read_file{"Path":"~/work/sortie/src/render/mech.ts"}

    input

    {
      "Path": "~/work/sortie/src/render/mech.ts"
    }

    result, 210 lines

    Showing lines 1-209 of 209
    1: import * as THREE from 'three';
    2: import { find, nodes } from './assets';
    3: import { Exhaust, KINDS, type NozzleKind, type ThrustReading } from './exhaust';
    4: import { PALETTES, type PaletteName } from './palette';
    5: import { PLUME_HULL, plumeMaterial, plumeVisible, setPlume } from './plume';
    6: 
    7: /** Joint rotations in degrees, glTF axes: X pitches a limb (negative swings it forward), Z swings it
    8:  *  sideways (positive moves a left limb outward), Y twists. */
    9: export type Pose = Partial<Record<Joint, [number, number, number]>>;
    10: 
    11: export const JOINTS = [
    12:   'pelvis', 'waist', 'torso', 'neck', 'head', 'backpack',
    13:   'shoulder.L', 'upperarm.L', 'forearm.L', 'hand.L', 'shoulder.R', 'upperarm.R', 'forearm.R', 'hand.R',
    14:   'thigh.L', 'shin.L', 'foot.L', 'thigh.R', 'shin.R', 'foot.R', 'binder.L', 'binder.R',
    15: ] as const;
    16: export type Joint = (typeof JOINTS)[number];
    17: 
    18: export const POSES = {
    19:   stand: {
    20:     'upperarm.L': [0, 0, 6], 'upperarm.R': [0, 0, -6], 'forearm.L': [-12, 0, 0], 'forearm.R': [-12, 0, 0],
    21:   },
    22:   /** Standing on the catapult: knees bent, leaning into the launch. */
    23:   launch: {
    24:     pelvis: [8, 0, 0], torso: [10, 0, 0], head: [-14, 0, 0],
    25:     'thigh.L': [-38, 0, 2], 'thigh.R': [-38, 0, -2], 'shin.L': [58, 0, 0], 'shin.R': [58, 0, 0],
    26:     'foot.L': [-20, 0, 0], 'foot.R': [-20, 0, 0],
    27:     'upperarm.L': [-18, 0, 14], 'forearm.L': [-40, 0, 0], 'upperarm.R': [-30, 0, -8], 'forearm.R': [-50, 0, 0],
    28:     'binder.L': [18, 0, 0], 'binder.R': [18, 0, 0],
    29:   },
    30:   /** The launch crouch for a heavy: 24 m in a 26 m tube, so knees deep, head down and binders folded,
    31:    *  which brings it under the tube's signal box. */
    32:   launch_heavy: {
    33:     pelvis: [12, 0, 0], torso: [12, 0, 0], head: [-20, 0, 0],
    34:     'thigh.L': [-58, 0, 3], 'thigh.R': [-58, 0, -3], 'shin.L': [106, 0, 0], 'shin.R': [106, 0, 0],
    35:     'foot.L': [-48, 0, 0], 'foot.R': [-48, 0, 0],
    36:     'upperarm.L': [-18, 0, 14], 'forearm.L': [-40, 0, 0], 'upperarm.R': [-30, 0, -8], 'forearm.R': [-50, 0, 0],
    37:     'binder.L': [40, 0, 0], 'binder.R': [40, 0, 0],
    38:   },
    39:   /** Free flight, rifle up. */
    40:   flight: {
    41:     pelvis: [6, 0, 0], torso: [-4, 0, 0], head: [-2, 0, 0],
    42:     'thigh.L': [-22, 0, 4], 'thigh.R': [6, 0, -3], 'shin.L': [42, 0, 0], 'shin.R': [30, 0, 0],
    43:     'foot.L': [8, 0, 0], 'foot.R': [18, 0, 0],
    44:     'upperarm.L': [-22, 0, 16], 'forearm.L': [-46, 0, 0],
    45:     'upperarm.R': [-62, -8, -6], 'forearm.R': [-26, 0, 0], 'hand.R': [0, 0, 0],
    46:     'binder.L': [-6, 0, 0], 'binder.R': [-6, 0, 0],
    47:   },
    48: } satisfies Record<string, Pose>;
    49: export type PoseName = keyof typeof POSES;
    50: 
    51: /** The catapult pose for a size class: the striker's, with a deeper crouch for heavies. */
    52: export const launchPose = (cls: string): Pose => (cls === 'heavy' ? POSES.launch_heavy : POSES.launch);
    53: 
    54: export interface Nozzle {
    55:   node: THREE.Object3D;
    56:   dir: THREE.Vector3; // exhaust direction in the node's parent space
    57:   radius: number;
    58:   kind: NozzleKind;
    59:   plume: THREE.Mesh;
    60: }
    61: 
    62: const tmpQ = new THREE.Quaternion();
    63: const _sum = new THREE.Vector3();
    64: const _at = new THREE.Vector3();
    65: const _white = new THREE.Color(1, 1, 1);
    66: const tmpE = new THREE.Euler();
    67: const D = THREE.MathUtils.DEG2RAD;
    68: 
    69: /** A frame model's joints, posed by rotation, with weapons held at grip.R and thruster plumes. */
    70: export class MechRig {
    71:   readonly joints = new Map<Joint, THREE.Object3D>();
    72:   readonly nozzles: Nozzle[] = [];
    73:   readonly cockpit: THREE.Object3D;
    74:   readonly grip: THREE.Object3D;
    75:   held: THREE.Object3D | null = null;
    76:   /** Plume state, stepped by thrust(). */
    77:   readonly exhaust = new Exhaust();
    78:   /** One plume material per nozzle kind: a kind fires together. */
    79:   private plumeMats: Record<NozzleKind, THREE.ShaderMaterial>;
    80:   private exhaustColor: THREE.Color;
    81:   private targets = new Map<Joint, THREE.Quaternion>();
    82: 
    83:   constructor(readonly root: THREE.Object3D) {
    84:     const map = nodes(root);
    85:     for (const j of JOINTS) {
    86:       const n = find(map, j);
    87:       if (n) this.joints.set(j, n);
    88:     }
    89:     this.cockpit = find(map, 'cockpit') ?? root;
    90:     this.grip = find(map, 'grip.R') ?? root;
    91:     const paint = PALETTES[(root.userData.palette as PaletteName | undefined) ?? 'merc'].glow_exhaust;
    92:     this.exhaustColor = new THREE.Color(paint.color);
    93:     this.plumeMats = {
    94:       main: plumeMaterial(this.exhaustColor, paint.glow ?? 1, 0),
    95:       binder: plumeMaterial(this.exhaustColor, paint.glow ?? 1, 17.3),
    96:       calf: plumeMaterial(this.exhaustColor, paint.glow ?? 1, 41.7),
    97:     };
    98:     root.traverse((o) => {
    99:       const dir = o.userData.dir as number[] | undefined;
    100:       if (!dir || !/^nozzle/.test(o.name)) return;
    101:       const kind: NozzleKind = /main/.test(o.name) ? 'main' : /binder/.test(o.name) ? 'binder' : 'calf';
    102:       const radius = (o.userData.radius as number) ?? 0.5;
    103:       // the plume's own space is in nozzle radii (render/plume.ts)
    104:       const plume = new THREE.Mesh(PLUME_HULL, this.plumeMats[kind]);
    105:       const d = new THREE.Vector3(...(dir as [number, number, number]));
    106:       plume.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), d);
    107:       plume.scale.setScalar(radius);
    108:       plume.visible = false;
    109:       plume.renderOrder = 2;
    110:       o.add(plume);
    111:       this.nozzles.push({ node: o, dir: d, radius, kind, plume });
    112:     });
    113:   }
    114: 
    115:   /** Any named node of the model (extras like harken.L), or null. */
    116:   node(name: string): THREE.Object3D | null {
    117:     return find(nodes(this.root), name) ?? null;
    118:   }
    119: 
    120:   /** Snap to a pose. */
    121:   apply(pose: Pose) {
    122:     for (const [j, node] of this.joints) {
    123:       const r = pose[j] ?? [0, 0, 0];
    124:       node.quaternion.setFromEuler(tmpE.set(r[0] * D, r[1] * D, r[2] * D));
    125:     }
    126:   }
    127: 
    128:   /** Snap to a pose and measure how high its soles sit above the root, in world metres (root
    129:    *  upright). A crouch lifts the feet, so the frame drops by this much to stand on its clamps. */
    130:   soles(pose: Pose): number {
    131:     this.apply(pose);
    132:     this.root.updateMatrixWorld(true);
    133:     const v = new THREE.Vector3();
    134:     let min = Infinity;
    135:     for (const j of ['foot.L', 'foot.R'] as const) {
    136:       this.joints.get(j)?.traverse((o) => {
    137:         const p = (o as THREE.Mesh).isMesh ? (o as THREE.Mesh).geometry.attributes.position : null;
    138:         if (!p) return;
    139:         for (let i = 0; i < p.count; i++) min = Math.min(min, v.fromBufferAttribute(p, i).applyMatrix4(o.matrixWorld).y);
    140:       });
    141:     }
    142:     return Number.isFinite(min) ? min - this.root.getWorldPosition(v).y : 0;
    143:   }
    144: 
    145:   /** Ease toward a blend of poses; weights need not sum to 1 (the rest is the rest pose). */
    146:   blend(poses: [Pose, number][], rate: number, dt: number) {
    147:     const k = 1 - Math.exp(-rate * dt);
    148:     for (const [j, node] of this.joints) {
    149:       let x = 0, y = 0, z = 0;
    150:       for (const [p, w] of poses) {
    151:         const r = p[j];
    152:         if (r) {
    153:           x += r[0] * w;
    154:           y += r[1] * w;
    155:           z += r[2] * w;
    156:         }
    157:       }
    158:       let t = this.targets.get(j);
    159:       if (!t) this.targets.set(j, (t = new THREE.Quaternion()));
    160:       t.setFromEuler(tmpE.set(x * D, y * D, z * D));
    161:       node.quaternion.slerp(t, k);
    162:     }
    163:   }
    164: 
    165:   /** Turn one joint by an extra rotation on top of its current pose (aim, lean). */
    166:   add(j: Joint, x: number, y: number, z: number) {
    167:     const n = this.joints.get(j);
    168:     if (n) n.quaternion.multiply(tmpQ.setFromEuler(tmpE.set(x * D, y * D, z * D)));
    169:   }
    170: 
    171:   /** Put a weapon in the right hand: barrel along the forearm, handle in the fist. */
    172:   hold(weapon: THREE.Object3D | null) {
    173:     if (this.held && this.held !== weapon) this.held.removeFromParent();
    174:     this.held = weapon;
    175:     if (!weapon) return;
    176:     this.grip.add(weapon);
    177:     weapon.position.set(0, 0, 0);
    178:     weapon.quaternion.setFromEuler(tmpE.set(Math.PI / 2, 0, 0));
    179:   }
    180: 
    181:   /** Step the plumes from this frame's flight reading and draw them. `time` drives the turbulence. */
    182:   thrust(r: ThrustReading, time: number, dt: number) {
    183:     this.exhaust.step(r, dt);
    184:     for (const k of KINDS) setPlume(this.plumeMats[k], this.exhaust.plumes[k], time);
    185:     for (const n of this.nozzles) n.plume.visible = plumeVisible(this.exhaust.plumes[n.kind]);
    186:   }
    187: 
    188:   /** Put `light` at the burning plumes' weighted centre, as bright as they burn: the glow the
    189:    *  exhaust throws on the frame. A light costs every lit pixel, so a scene gives one to the player
    190:    *  and the nearest few frames at most, and keeps the count fixed (a change recompiles shaders). */
    191:   lightExhaust(light: THREE.PointLight, strength = 1) {
    192:     let w = 0;
    193:     _sum.set(0, 0, 0);
    194:     const s = this.root.scale.x;
    195:     for (const n of this.nozzles) {
    196:       const p = this.exhaust.plumes[n.kind];
    197:       const k = (Math.min(1, p.level) * (1 + 0.5 * p.heavy) + 0.4 * p.flash) * (n.radius * s) ** 2;
    198:       if (k <= 0 || !n.plume.visible) continue;
    199:       // a little way downstream, where the plume is brightest
    200:       n.plume.localToWorld(_at.set(0, 0, 2.5));
    201:       _sum.addScaledVector(_at, k);
    202:       w += k;
    203:     }
    204:     light.visible = true;
    205:     light.color.copy(this.exhaustColor).lerp(_white, 0.4);
    206:     light.intensity = w > 0 ? w * 35 * strength : 0;
    207:     if (w > 0) light.position.copy(_sum).divideScalar(w);
    208:   }
    209: }
  • read_file{"Path":"~/work/sortie/src/render/palette.ts"}

    input

    {
      "Path": "~/work/sortie/src/render/palette.ts"
    }

    result, 176 lines

    Showing lines 1-175 of 175
    1: // Material roles are named in the kit (kit/lib.py). A palette paints every role; factions and
    2: // companies get their own palettes, the models stay the same.
    3: 
    4: export type Role =
    5:   | 'main' | 'accent' | 'trim' | 'frame' | 'joint' | 'visor' | 'metal' | 'sensor'
    6:   | 'glow_eye' | 'glow_core' | 'glow_thruster' | 'glow_beam' | 'glow_exhaust'
    7:   | 'hull' | 'hull_dark' | 'interior' | 'deck' | 'hazard' | 'light' | 'screen' | 'glass'
    8:   | 'lamp_red' | 'lamp_green' | 'suit' | 'glow_hot'
    9:   // raider salvage: paint from the donor machines, primer patches, bare rust and hand paint
    10:   | 'donor_a' | 'donor_b' | 'donor_c' | 'primer' | 'rust' | 'handpaint' | 'warpaint'
    11:   | 'crystal' | 'crystal_lit' | 'glow_violet'
    12:   // markings on plates: pattern codes, service text, unit codes
    13:   | 'stencil';
    14: 
    15: export interface Paint {
    16:   color: string;
    17:   /** Emissive roles: brightness multiplier, values above 1 feed the bloom. */
    18:   glow?: number;
    19:   /** Physically based surface: roughness, metalness, clearcoat (paint sheen). */
    20:   rough?: number;
    21:   metal?: number;
    22:   coat?: number;
    23:   /** Rust blotches and streaks over the surface, 0..1 (raider salvage). */
    24:   rust?: number;
    25:   /** A lit surface that also gives off its own colour at this strength (lit from inside). */
    26:   emit?: number;
    27:   /** Painted roles: a lacquered finish, 0..1, kept under every look: roughness no higher than `rough`, less
    28:    *  weathering of the colour, and from 0.5 a clear coat this strong. */
    29:   lacquer?: number;
    30: }
    31: 
    32: export type Palette = Record<Role, Paint>;
    33: 
    34: const paint = (color: string, rough = 0.42, coat = 0.35): Paint => ({ color, rough, metal: 0, coat });
    35: const metal = (color: string, rough = 0.42, m = 0.85): Paint => ({ color, rough, metal: m });
    36: 
    37: const base: Palette = {
    38:   main: paint('#d9dce1'),
    39:   accent: paint('#27527a'),
    40:   trim: paint('#c9452f', 0.4),
    41:   frame: metal('#5b6069', 0.48, 0.8),
    42:   joint: metal('#33363c', 0.55, 0.9),
    43:   visor: { color: '#06080b', rough: 0.22, metal: 0.2, coat: 1 },
    44:   metal: metal('#9aa0a8', 0.3, 1),
    45:   sensor: { color: '#1d6b5c', rough: 0.2, metal: 0.3, coat: 1 },
    46:   glow_eye: { color: '#7ef7e6', glow: 4 },
    47:   glow_core: { color: '#7ef7e6', glow: 2.4 },
    48:   /** The lit throat inside a thruster bell, the exhaust's colour. */
    49:   glow_thruster: { color: '#9cc6ff', glow: 3 },
    50:   /** Thruster plumes (render/plume.ts): the mantle colour, the core runs it to white. Glow scales
    51:    *  the whole plume. A maker or faction tints its drives here. */
    52:   glow_exhaust: { color: '#4f8fff', glow: 1 },
    53:   glow_beam: { color: '#ff5ccf', glow: 5 },
    54:   hull: paint('#a9adb4', 0.55, 0.15),
    55:   hull_dark: metal('#4a4f57', 0.6, 0.6),
    56:   interior: metal('#5e6168', 0.7, 0.3),
    57:   deck: metal('#3f434a', 0.7, 0.6),
    58:   hazard: paint('#e3b62b', 0.6, 0),
    59:   light: { color: '#fff3df', glow: 1.7 },
    60:   screen: { color: '#4fd8cc', glow: 1.6 },
    61:   glass: { color: '#8f9fc4', rough: 0.22, metal: 0.1, coat: 1 },
    62:   lamp_red: { color: '#ff3a2e', glow: 4 },
    63:   lamp_green: { color: '#48ff6c', glow: 4 },
    64:   suit: paint('#1f2a4f', 0.6, 0),
    65:   /** The white-hot core inside an eye or sensor lamp. */
    66:   glow_hot: { color: '#eafffb', glow: 2.6 },
    67:   /** Donor paint on salvaged parts: in a clean palette, the merc's own colours and an olive. */
    68:   donor_a: paint('#d9dce1'),
    69:   donor_b: paint('#27527a'),
    70:   donor_c: paint('#5c6143'),
    71:   primer: paint('#8a8d84', 0.7, 0),
    72:   rust: metal('#6a3a20', 0.85, 0.35),
    73:   handpaint: paint('#ece4cc', 0.7, 0),
    74:   warpaint: paint('#c9452f', 0.6, 0),
    75:   /** The aliens' one material: unpainted silver, no seams. */
    76:   crystal: metal('#c6c9d0', 0.44, 0.95),
    77:   /** Alien crystal lit from inside by the core, the lining of an opened geode. */
    78:   crystal_lit: { color: '#a796dc', rough: 0.4, metal: 0.9, emit: 0.42 },
    79:   /** The alien core light. */
    80:   glow_violet: { color: '#7b3dff', glow: 2.6 },
    81:   /** Stencilled markings: dark ink on light plates, light ink on dark ones. */
    82:   stencil: { color: '#23272d', rough: 0.7, metal: 0 },
    83: };
    84: 
    85: const worn = (color: string, rust: number, rough = 0.6): Paint => ({ color, rough, metal: 0, coat: 0, rust });
    86: 
    87: export const PALETTES = {
    88:   /** The player's default frame paint. */
    89:   merc: base,
    90:   /** The Administration: gate white plates, petrol blue accent blocks (the chest, the boots, the cheeks),
    91:    * gate cyan lights and trim. A light livery, so the frame goes darker to keep the value step. */
    92:   admin: {
    93:     ...base,
    94:     main: paint('#e4e8eb'),
    95:     accent: paint('#1b5c5a', 0.45),
    96:     trim: paint('#3fa7c9', 0.35),
    97:     frame: metal('#3a3e45', 0.5, 0.8),
    98:     joint: metal('#24262b', 0.55, 0.9),
    99:     glow_eye: { color: '#5fd0f0', glow: 4 },
    100:     glow_core: { color: '#5fd0f0', glow: 2.4 },
    101:     glow_hot: { color: '#e6fbff', glow: 2.6 },
    102:     glow_thruster: { color: '#9ee6ff', glow: 3 },
    103:     glow_exhaust: { color: '#3fc4ff', glow: 1 },
    104:   },
    105:   /** The houses: lacquered wine plates, ivory accent fields (the crest, the breastplate, the back panel, the
    106:    * tabard and the shield pale), warm gold trim on the hems and the crest's edge, emerald lenses and pale gold
    107:    * drives. The wine is lifted a step and lacquered so its curves carry highlights, the frame is a darker, less
    108:    * metallic steel so the plates keep a value step above it in shade too (docs/study-atelier.md). */
    109:   houses: {
    110:     ...base,
    111:     main: { ...paint('#781c33', 0.36, 0.5), lacquer: 0.45 },
    112:     accent: { ...paint('#ece3cc', 0.38, 0.4), lacquer: 0.4 },
    113:     trim: metal('#e6b84a', 0.3, 0.75),
    114:     frame: metal('#4c5058', 0.55, 0.4),
    115:     joint: metal('#3a3c42', 0.55, 0.9),
    116:     metal: metal('#b5ab98', 0.3, 1),
    117:     stencil: { color: '#e6dcc4', rough: 0.7, metal: 0 },
    118:     glow_eye: { color: '#4dffa6', glow: 4 },
    119:     // the reactor glow through the chest sides stays low, the lenses carry the green
    120:     glow_core: { color: '#2fb877', glow: 0.7 },
    121:     glow_hot: { color: '#eafff2', glow: 2.6 },
    122:     glow_thruster: { color: '#ffe3a8', glow: 3 },
    123:     glow_exhaust: { color: '#ffcf6a', glow: 1 },
    124:   },
    125:   /** Automated pilotless frames: black and gunmetal shell, red only in lenses, seam lines and stencils. The
    126:    * gunmetal is light enough to read as a block against the black at range. */
    127:   automaton: {
    128:     ...base,
    129:     main: paint('#1d1e23', 0.38),
    130:     accent: paint('#5e646c', 0.34),
    131:     metal: metal('#3e4046', 0.5, 0.8),
    132:     trim: paint('#d12b35', 0.4),
    133:     frame: metal('#2c2d33', 0.5),
    134:     stencil: { color: '#c9c4b8', rough: 0.7, metal: 0 },
    135:     glow_eye: { color: '#ff2f3f', glow: 4.5 },
    136:     glow_core: { color: '#ff2f3f', glow: 5 },
    137:     glow_hot: { color: '#ffe4e4', glow: 2.6 },
    138:     glow_thruster: { color: '#ff9a7a', glow: 3 },
    139:     glow_exhaust: { color: '#ff3a2a', glow: 1 },
    140:   },
    141:   /** Raiders: sun-faded salvage in three donors' paint, primer patches, rust, hand paint. */
    142:   raider: {
    143:     ...base,
    144:     main: worn('#9c8550', 0.35),
    145:     accent: worn('#5e2c22', 0.3),
    146:     trim: worn('#c0561a', 0.3),
    147:     frame: { ...metal('#4d4842', 0.6, 0.75), rust: 0.25 },
    148:     joint: metal('#2f2c29', 0.62, 0.85),
    149:     metal: { ...metal('#8c8780', 0.45, 0.9), rust: 0.3 },
    150:     hazard: worn('#d9a92a', 0.3),
    151:     donor_a: worn('#c6c3b8', 0.3),
    152:     donor_b: worn('#3e566e', 0.3),
    153:     donor_c: worn('#5c6143', 0.35),
    154:     primer: worn('#8a8d84', 0.2, 0.75),
    155:     rust: { ...metal('#5e3019', 0.85, 0.35), rust: 0.75 },
    156:     handpaint: worn('#ece4cc', 0.15, 0.75),
    157:     warpaint: worn('#9e1f16', 0.2, 0.7),
    158:     stencil: worn('#2a2723', 0.2, 0.8),
    159:     glow_eye: { color: '#ffb347', glow: 4 },
    160:     glow_core: { color: '#ff9a3c', glow: 2.6 },
    161:     glow_hot: { color: '#fff1d6', glow: 2.6 },
    162:     // patched up drives burn dirty and orange
    163:     glow_thruster: { color: '#ffb36e', glow: 3 },
    164:     glow_exhaust: { color: '#ff7a1e', glow: 1.1 },
    165:   },
    166:   /** Silver aliens: the kit builds them from the crystal roles alone, any core or eye light goes violet. */
    167:   alien: {
    168:     ...base,
    169:     glow_eye: { color: '#7b3dff', glow: 2.6 },
    170:     glow_core: { color: '#7b3dff', glow: 2.6 },
    171:     glow_hot: { color: '#efe6ff', glow: 2.6 },
    172:   },
    173: } satisfies Record<string, Palette>;
    174: 
    175: export type PaletteName = keyof typeof PALETTES;
  • read_file{"Path":"~/work/sortie/src/view/viewer.ts"}

    input

    {
      "Path": "~/work/sortie/src/view/viewer.ts"
    }

    result, 144 lines

    Showing lines 1-143 of 143
    1: import * as THREE from 'three';
    2: import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
    3: import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
    4: import { model, type ModelName } from '../render/assets';
    5: import { MechRig, POSES, type PoseName } from '../render/mech';
    6: import type { PaletteName } from '../render/palette';
    7: import { Pipeline } from '../render/pipeline';
    8: import { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';
    9: import { STRIKER_DECALS, applyDecals, type DecalSpec } from '../render/decals';
    10: import { PALETTES } from '../render/palette';
    11: import { look, setLook } from '../render/look';
    12: import { treatEyes, type EyeMode } from '../render/eyes';
    13: import { fitShip } from '../render/ship';
    14: import type { FrameClassId } from '../sim/frames';
    15: 
    16: /**
    17:  * Model viewer for review shots, in the game's own renderer:
    18:  *   /?view=striker&yaw=35&pitch=8&dist=34&pose=flight&weapon=rifle&palette=automaton
    19:  *   /?view=lineup  (the frame in each palette, side by side)
    20:  *   /?view=ship&bays=light,heavy&frame=light  (bay fits and shuttle clamps)
    21:  *   /?view=light&pose=launch&weapon=rifle  (light and heavy frames and their variants pose like the striker)
    22:  */
    23: const FRAMES: string[] = ['striker_a', 'striker_b', 'light', 'light_line', 'light_lancer', 'heavy', 'heavy_B', 'heavy_C'];
    24: 
    25: /** An emblem at every bearing anchor of a model: the anchor's position, its direction into the plate, its size. */
    26: function bearingDecals(root: THREE.Object3D, color: string): DecalSpec[] {
    27:   root.updateMatrixWorld(true);
    28:   const out: DecalSpec[] = [];
    29:   root.traverse((o) => {
    30:     if (!o.name.startsWith('bearing') || !o.visible) return;
    31:     const at = root.worldToLocal(o.getWorldPosition(new THREE.Vector3()));
    32:     const dir = o.userData.dir as [number, number, number] | undefined;
    33:     const size = Number(o.userData.size ?? 0.5);
    34:     if (dir) out.push({ kind: 'emblem', at: [at.x, at.y, at.z], dir, size: [size, size], color });
    35:   });
    36:   return out;
    37: }
    38: 
    39: export async function startViewer(canvas: HTMLCanvasElement, q: URLSearchParams) {
    40:   setLook(q.get('look'));
    41:   await document.fonts.ready;
    42:   const scene = new THREE.Scene();
    43:   const camera = new THREE.PerspectiveCamera(Number(q.get('fov') ?? 35), 1, 0.5, 2e5);
    44:   // ?bg=studio: a plain grey ground, an even room light and little bloom, for judging shape
    45:   const studio = q.get('bg') === 'studio';
    46:   const backdrop = createBackdrop();
    47:   const pipe = new Pipeline(canvas, scene, camera, studio ? null : backdrop);
    48:   const sun = addSpaceLight(scene);
    49:   if (studio) {
    50:     scene.background = new THREE.Color('#3a3e45');
    51:     const pmrem = new THREE.PMREMGenerator(pipe.renderer);
    52:     scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
    53:     pipe.bloom.strength = Number(q.get('bloom') ?? 0.12);
    54:   } else scene.environment = spaceEnvironment(pipe.renderer, backdrop);
    55:   scene.environmentIntensity = Number(q.get('env') ?? (studio ? 0.6 : 0.8) * look().fill);
    56:   const name = q.get('view') as ModelName | 'lineup';
    57:   const target = new THREE.Vector3();
    58:   const pose = (q.get('pose') ?? 'stand') as PoseName;
    59:   const weapon = q.get('weapon') as ModelName | null;
    60: 
    61:   async function frame(palette: PaletteName, x: number, mech: ModelName = 'striker') {
    62:     const root = await model(mech, palette);
    63:     root.position.x = x;
    64:     scene.add(root);
    65:     if (mech === 'striker') applyDecals(root, STRIKER_DECALS);
    66:     treatEyes(root, (q.get('eye') ?? 'spill') as EyeMode);
    67:     const rig = new MechRig(root);
    68:     rig.apply(POSES[pose] ?? POSES.stand);
    69:     if (weapon) {
    70:       rig.hold(await model(weapon, palette));
    71:       // weapons are striker sized: scale to the frame's height
    72:       const h = root.getObjectByName('frame')?.userData.height as number | undefined;
    73:       if (h) rig.held!.scale.setScalar(h / 17.6);
    74:     }
    75:     return root;
    76:   }
    77: 
    78:   if (name === 'lineup') {
    79:     await frame('merc', -6);
    80:     await frame('automaton', 6);
    81:     target.set(0, 9, 0);
    82:   } else if (name === 'striker') {
    83:     await frame((q.get('palette') ?? 'merc') as PaletteName, 0);
    84:     target.set(0, 9, 0);
    85:   } else if (FRAMES.includes(name)) {
    86:     const root = await frame((q.get('palette') ?? 'merc') as PaletteName, 0, name);
    87:     new THREE.Box3().setFromObject(root).getCenter(target);
    88:   } else {
    89:     const root = await model(name, (q.get('palette') ?? 'merc') as PaletteName);
    90:     treatEyes(root, (q.get('eye') ?? 'spill') as EyeMode, q.has('t') ? Number(q.get('t')) : null);
    91:     scene.add(root);
    92:     // ?only=slot2 shows one variant of a lab lineup
    93:     const only = q.get('only');
    94:     if (only) root.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== only) o.visible = false; });
    95:     // ?view=ship&bays=light,heavy&frame=light fits the bays and the shuttle clamps
    96:     if (name === 'ship') {
    97:       const ids = (s: string | null, n: number) => (s?.split(',') ?? []).concat(Array(n).fill('standard')).slice(0, n) as FrameClassId[];
    98:       fitShip(root, ids(q.get('bays'), 2), ids(q.get('frame'), 1)[0]);
    99:     }
    100:     // ?bearings=1 puts a test emblem on every bearing anchor (bearing.*), in the palette's trim colour
    101:     if (q.has('bearings')) applyDecals(root, bearingDecals(root, PALETTES[(q.get('palette') ?? 'merc') as PaletteName].trim.color));
    102:     const box = new THREE.Box3().setFromObject(root);
    103:     box.getCenter(target);
    104:   }
    105:   // ?sil=1: flat black forms on a white ground, for judging silhouettes without paint or stencils
    106:   if (q.has('sil')) {
    107:     const black = new THREE.MeshBasicMaterial({ color: 0x000000 });
    108:     scene.traverse((o) => {
    109:       const m = o as THREE.Mesh;
    110:       if (m.isMesh) m.material = black;
    111:       else if ((o as THREE.Sprite).isSprite || (o as THREE.Points).isPoints) o.visible = false;
    112:     });
    113:     scene.background = new THREE.Color('#ffffff');
    114:     // the low tier drops the edge detail, bloom and grade passes, which would draw over the forms
    115:     pipe.setQuality({ tier: 'low' });
    116:   }
    117:   const dist = Number(q.get('dist') ?? 36);
    118:   const yaw = THREE.MathUtils.degToRad(Number(q.get('yaw') ?? 30));
    119:   const pitch = THREE.MathUtils.degToRad(Number(q.get('pitch') ?? 8));
    120:   if (q.has('ty')) target.y = Number(q.get('ty'));
    121:   if (q.has('tx')) target.x = Number(q.get('tx'));
    122:   if (q.has('tz')) target.z = Number(q.get('tz'));
    123:   camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(dist).add(target);
    124:   followSun(sun, target);
    125:   if (name !== 'striker' && name !== 'lineup' && !FRAMES.includes(name)) {
    126:     const c = sun.shadow.camera;
    127:     c.left = c.bottom = -dist;
    128:     c.right = c.top = dist;
    129:     c.far = dist * 20;
    130:     c.updateProjectionMatrix();
    131:   }
    132:   camera.lookAt(target);
    133:   const controls = new OrbitControls(camera, canvas);
    134:   controls.target.copy(target);
    135:   controls.update();
    136:   window.addEventListener('resize', () => pipe.resize());
    137:   const loop = () => {
    138:     pipe.render();
    139:     requestAnimationFrame(loop);
    140:   };
    141:   loop();
    142:   (window as unknown as { __ready: boolean }).__ready = true;
    143: }
  • read_file{"Path":"~/work/sortie/kit/build.py"}

    input

    {
      "Path": "~/work/sortie/kit/build.py"
    }

    result, 74 lines

    Showing lines 1-73 of 73
    1: """Build every model into public/assets/*.glb.
    2: 
    3:     npm run kit                 # everything
    4:     npm run kit -- striker ship # just these
    5:     npm run kit -- block_dummy  # a block model, kit/blocks/dummy.py
    6: """
    7: import os
    8: import sys
    9: import time
    10: 
    11: sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    12: 
    13: import lib  # noqa: E402
    14: from block import build_block  # noqa: E402
    15: from cockpit import build_cockpit  # noqa: E402
    16: from cockpit_light import build_cockpit_light  # noqa: E402
    17: from mech import build_striker  # noqa: E402
    18: from heavy import build_heavy, build_heavy_lab  # noqa: E402
    19: from props import build_cannon, build_drone, build_rifle  # noqa: E402
    20: from ship import build_ship  # noqa: E402
    21: from station import build_station  # noqa: E402
    22: from salvage import build_salvage_pod, build_wreck_field  # noqa: E402
    23: from escape_pod import build_escape_pod  # noqa: E402
    24: from light import build_light, build_light_lab  # noqa: E402
    25: from automaton import build_automaton, build_automaton_lab  # noqa: E402
    26: from alien import build_alien, build_alien_lab  # noqa: E402
    27: sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "lab"))
    28: from heads import build_head_lab, build_head_lab2  # noqa: E402
    29: from headkit import build_head_lab3, build_head_lab4, build_head_lab5, build_head_lab6, build_head_lab7, build_head_lab8  # noqa: E402
    30: from sizes import build_sizes  # noqa: E402
    31: from pilotlab import build_pilot_lab  # noqa: E402
    32: from assembly import build_assembly_lab, build_back_lab, build_chest_frames, build_show, game_frame  # noqa: E402
    33: from raider import build_raider, build_raider_lab  # noqa: E402
    34: from pattern_lab import build_pattern_lab, build_pattern_m  # noqa: E402
    35: from atelier_lab import build_atelier_lab  # noqa: E402
    36: from atelier_board import build_atelier_line  # noqa: E402
    37: from bodykit import build_chest_lab, build_chest_lab2, build_foot_lab, build_foot_lab2, build_chest_lab3, build_foot_lab3  # noqa: E402
    38: 
    39: OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "public", "assets")
    40: ASSETS = {"striker": build_striker, "striker_a": lambda: game_frame(0), "striker_b": lambda: game_frame(1), "rifle": build_rifle, "cannon": build_cannon, "drone": build_drone,
    41:           "cockpit": build_cockpit, "cockpit_light": build_cockpit_light, "ship": build_ship, "station": build_station,
    42:           "wreck_field": build_wreck_field, "salvage_pod": build_salvage_pod, "escape_pod": build_escape_pod,
    43:           "light": lambda: build_light("knight"), "light_line": lambda: build_light("line"), "light_lancer": lambda: build_light("lancer"),
    44:           "heavy": lambda: build_heavy("A"), "heavy_B": lambda: build_heavy("B"), "heavy_C": lambda: build_heavy("C"),
    45:           "lab_heads": build_head_lab, "lab_heads2": build_head_lab2, "lab_heads3": build_head_lab3, "lab_heads4": build_head_lab4, "lab_heads5": build_head_lab5, "lab_heads6": build_head_lab6, "lab_heads7": build_head_lab7, "lab_heads8": build_head_lab8, "lab_chests": build_chest_lab, "lab_feet": build_foot_lab, "lab_chests2": build_chest_lab2, "lab_feet2": build_foot_lab2, "lab_chests3": build_chest_lab3, "lab_feet3": build_foot_lab3, "lab_frames": build_assembly_lab, "lab_backs": build_back_lab, "lab_chests4": build_chest_frames,
    46:           "lab_show": build_show, "lab_show_v": lambda: build_show(formation=True),
    47:           "lab_heavy": build_heavy_lab, "lab_light": build_light_lab, "lab_sizes": build_sizes, "lab_pilot": build_pilot_lab,
    48:           "auto_tally": lambda: build_automaton("tally"), "auto_tick": lambda: build_automaton("tick"),
    49:           "auto_ledger": lambda: build_automaton("ledger"),
    50:           "alien_acicular": lambda: build_alien("acicular"), "alien_druse": lambda: build_alien("druse"),
    51:           "alien_druse_mimic": lambda: build_alien("druse_mimic"), "alien_geode": lambda: build_alien("geode"),
    52:           "raider_grunt": lambda: build_raider("grunt"), "raider_brawler": lambda: build_raider("brawler"),
    53:           "raider_boss": lambda: build_raider("boss"),
    54:           "pattern_m": build_pattern_m, "lab_pattern": build_pattern_lab, "lab_atelier": build_atelier_lab, "lab_atelier_a": lambda: build_atelier_line("a"), "lab_atelier_b": lambda: build_atelier_line("b"),
    55:           "lab_atelier_c": lambda: build_atelier_line("c"), "lab_atelier_d": lambda: build_atelier_line("d"),
    56:           "lab_auto": build_automaton_lab, "lab_alien": build_alien_lab, "lab_raider": build_raider_lab}
    57: 
    58: 
    59: def main(names):
    60:     os.makedirs(OUT, exist_ok=True)
    61:     for name in names or [n for n in ASSETS if not n.startswith("lab")]:
    62:         t = time.time()
    63:         lib.reset()
    64:         if name.startswith("block_"):  # scratch models, kit/blocks/<name>.py
    65:             build_block(name)
    66:         else:
    67:             ASSETS[name]()
    68:         path = os.path.normpath(os.path.join(OUT, f"{name}.glb"))
    69:         lib.export(path)
    70:         print(f"kit: {name} -> {path} ({os.path.getsize(path) // 1024} KB, {time.time() - t:.1f}s)")
    71: 
    72: 
    73: main(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])