Vehicle Generator 0.1.0 (alpha)

Procedural, game-ready vehicles for three.js: 13 body styles, blending, seeded
random vehicles, three LODs, colliders, 13 parametric mods, paint and livery,
a rig that drives, and GLB export that a game can load and drive. Ships with a
studio (browser or Tauri desktop app) and a Play mode.
This commit is contained in:
CRTkafa 2026-10-11 00:22:23 +00:00
commit d8f3a6e3df
112 changed files with 17584 additions and 0 deletions

6
.gitattributes vendored Normal file
View file

@ -0,0 +1,6 @@
* text=auto eol=lf
*.png binary
*.jpg binary
*.glb binary
*.ico binary
*.icns binary

20
.gitignore vendored Normal file
View file

@ -0,0 +1,20 @@
node_modules/
dist/
# Regenerated by `bun run render` and `bun run export:glb`.
renders/
glb/
*.log
*.tgz
*.tsbuildinfo
.DS_Store
# Local tool and agent state.
.omc/
.claude/
.scratch/
__pycache__/
# Private working notes, kept off the public repo.
docs/HANDOFF.md

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 CRTkafa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

339
README.md Normal file
View file

@ -0,0 +1,339 @@
# vehicle-generator
**Alpha · in development.** Things work, things change; the spec format and the
API may still move between 0.x releases.
Procedural, game-ready vehicles for [three.js](https://threejs.org). Give it a
spec (a body style, some proportions, a paint job, a list of mods) and it
builds a rigged car with three levels of detail, a physics collider and a GLB
you can drop into any engine. The same spec always produces the same vertices.
![A generated sedan](media/sedan.png)
It ships as a TypeScript library and as **Vehicle Generator**, a studio app for
shaping cars, fitting parts, driving them and exporting them. The studio runs
in a browser or as a desktop app.
![Every body style](media/styles.png)
## Status
Version 0.1.0, alpha.
**Works today**
- The library: 13 body styles, blending, seeded random vehicles, three LODs,
colliders, 13 mods, paint and livery, the rig, and GLB export that a game can
load and drive.
- The studio, in a browser or as a desktop app: garage, customs, properties,
export, undo and autosave.
- Play mode: drive any vehicle on a generated circuit or in traffic.
**In progress**
- Bodies drawn from authored cages. The sedan is the first: its shape comes
from a control cage subdivided at run time. The other twelve styles still
use the older lofted body and are moving over one by one.
**Planned**
- One-click import into Godot, Unity and Unreal (shown as *planned* in the
studio's export menu; today you export GLB or spec JSON).
- Physics values for game engines: mass, centre of mass, springs, dampers,
steering lock and a torque curve, exported with the GLB.
- Interiors with real seats, dashboards and door cards; more part variants per
style; paint slots and finishes; a photo mode; two-wheelers.
## What you get
- **13 body styles**: `sedan`, `hatchback`, `coupe`, `wagon`, `suv`, `pickup`,
`van`, `sports`, `supercar`, `muscle`, `kei`, `buggy` and `truck` (a cab-over
with a load box). Each is a preset of the same generator, so any two can be
blended: a hatchback 40 % of the way to an SUV is a crossover.
- **Real proportions.** Every preset is measured off a real vehicle of its
segment: overall dimensions, wheelbase, overhangs, tyre size, and where the
windshield, roof and rear glass start and end. The default sedan is
4.85 m long and 1.86 m wide on a 2.84 m wheelbase and 0.69 m tyres.
- **Smooth bodies, not boxes.** The sedan's body is a subdivision surface:
an authored control cage (`assets/src/sedan.py`) is fitted to the spec,
subdivided with creases and split into panels with real gaps. The other
styles are lofted from cross-sections driven by profile curves. Either way,
hard creases sit where a real car has them: the shoulder,
a character line along the flank, the rocker and the windshield base. Panel
gaps are real grooves, and the wheel arches are cut into the sills with
rolled lips. The glass is flush. Lamps are recessed reflectors behind clear
lenses. The car also gets a grille, mirrors, door handles, wipers, licence
plates, brake discs and calipers. Tyres have sidewalls and tread, and there
are seven rim styles. An interior sits behind tinted, reflective glass.
- **Under the panels.** Open the bonnet and there is an engine bay: firewall,
inner wings, strut towers, an engine with its cam cover and intake, a
radiator and fan, a battery, fluid reservoirs and hoses. The boot has a
carpeted load floor and a spare wheel in its well. Hatchbacks, wagons,
SUVs, vans and kei cars lift a whole tailgate. The supercar is mid-engined:
the engine sits under the rear lid and the bonnet covers a front boot.
- **Levels of detail.** For the default sedan, LOD0 is 56,828 triangles, LOD1
is 20,720 and LOD2 is 4,364. A `THREE.LOD` switches between them by
distance. Stock vehicles stay under 60k triangles on LOD0, and mods may add
up to 6k more.
- **A rig that drives.** Wheels spin and the front pair steers with Ackermann
geometry. Doors, bonnet and boot (or tailgate) open on hinges, and the
steering wheel turns. The body rolls and pitches on its suspension while the
wheels stay planted. Head-, tail- and brake lights switch on and off. Every
pivot sits at its hinge or axle, so each motion is a single rotation.
- **Collision.** You get a convex hull of the body and a two-box compound,
plus wheel positions and radii for a raycast-vehicle setup.
- **13 composable mods**: `spoiler`, `bodyKit`, `widebody`, `suspension`,
`wheelSet`, `bullBar`, `roofRack`, `snorkel`, `exhaust`, `hoodScoop`,
`lightBar`, `rollCage` and `mudFlaps`. Each is parametric and fits every body
style, because it is placed against the body's own curves.
- **Paint.** Finishes are solid, metallic, pearl and matte, built on
`MeshPhysicalMaterial` clearcoat and iridescence. You also get two-tone
(roof, lower or upper body), twin-stripe, side-stripe and rally liveries, separate rim, trim
and caliper colours, curated palettes, and a seeded random that picks
believable colours.
- **GLB export that round-trips.** Node names, pivots, rig tags, vertex
colours, clearcoat and animation clips all survive the export, and
`createRig()` drives a re-imported GLB the same way it drives the generated
car.
![Doors, bonnet and tailgate open, wheels steered, lights on](media/rig.png)
## Quick start
Requires [Bun](https://bun.sh).
```sh
bun install
bun run dev # the studio at http://localhost:5173
```
### Use the library
```ts
import { generateVehicle, preset, randomSpec, exportVehicleGlb } from 'vehicle-generator'
const car = generateVehicle(preset('hatchback'))
scene.add(car.group)
// Drive it.
car.rig.setSteer(0.3) // radians, positive is left; also turns the steering wheel
car.rig.update(dt, speed) // rolls the wheels for a car moving at `speed` m/s
car.rig.open('doorFL', 1) // 0 = shut, 1 = open; also 'hood' and 'trunk'
car.rig.setBodyPose(roll, pitch) // lean the sprung body; the wheels stay planted
car.rig.setBrake(true)
car.rig.setHeadlights(true)
// Physics.
car.collider.hull // convex BufferGeometry of the body
car.wheels // hub positions, radius, width, steer/drive flags
// Repaint without a rebuild.
car.setPaint({ ...car.spec.paint, primary: '#1f3a5f', finish: 'pearl' })
// A random vehicle, and a GLB of it.
const other = generateVehicle(randomSpec(1234))
const glb = await exportVehicleGlb(other) // ArrayBuffer, LOD0 plus animation clips
```
The generator imports plain `three`, so it works with `WebGLRenderer` and with
`WebGPURenderer`. The frame is glTF's: +Y up, the vehicle faces +Z, +X is its
left, and the ground is y = 0.
### Load a GLB in a game and drive it
```ts
import { createRig } from 'vehicle-generator'
const gltf = await new GLTFLoader().loadAsync('hatchback.glb')
const rig = createRig(gltf.scene) // reads the tags stored in glTF extras
rig.setSteer(-0.2)
rig.open('trunk', 1)
```
Clips named `open_<part>` and `wheels_roll` come with the file, for engines
that prefer animation clips to code.
## The spec
A `VehicleSpec` is plain JSON:
```jsonc
{
"style": "pickup",
"seed": 42,
"body": { "length": 5.3, "width": 1.95, "roofHeight": 1.9, "cowl": 0.72, "bed": { "start": 0.02, "end": 0.42, "depth": 0.5 } },
"wheels": { "radius": 0.4, "width": 0.265, "rim": "spoke", "spokes": 6, "tread": "offroad", "camber": 0 },
"chassis": { "wheelbase": 3.4, "frontOverhang": 0.9, "track": 0.86, "rideHeight": 0, "drive": "rwd" },
"cargo": { "type": "none", "length": 0, "height": 0 },
"paint": { "primary": "#7a1f1f", "finish": "solid", "twoTone": "none", "livery": "none" },
"mods": [{ "kind": "bullBar", "params": { "height": 0.45 } }, { "kind": "suspension", "params": { "height": 0.1 } }]
}
```
Start from `preset(style)` and change what you need. Longitudinal stations
(`cowl`, `roofFront`, `roofRear`, `deck`) are fractions of the body length
measured from the rear, so they stay put when the length changes.
`blendSpecs(a, b, t)` interpolates two specs. `randomSpec(seed, { style })`
draws one.
### Mods
A mod is `{ kind, params }`. `MODS[kind].params` describes its controls (number
ranges and option lists), and the studio builds its inspector from that. Some
mods change the spec before the build: `widebody` widens the arches and the
track, `suspension` moves the body, and `wheelSet` swaps the wheels. The rest
add geometry afterwards. Each lands in its own node (`mod_roofRack`,
`mod_spoiler`, and so on). Mods mounted on something that opens are parented to
it: a boot-lid spoiler rides the lid and a hood scoop rides the bonnet.
## Node layout
```
vehicle_<style>
└─ vehicle_lod (THREE.LOD)
└─ LOD0
├─ body meshes per material: body_paint, body_glass, body_lightTail, …
├─ doorFL pivot at the front hinge → rotation.y opens
├─ hood pivot at the rear edge → rotation.x opens
├─ trunk pivot at the hinge line → rotation.x opens
├─ steering_column → steering_wheel → rotation.z turns
├─ wheel_FL steer (rotation.y) → wheel_FL_camber → wheel_FL_spin (rotation.x)
└─ mod_* one node per mod
```
LOD1 and LOD2 repeat the same tree with `_LOD1` and `_LOD2` suffixes. Each LOD
costs one draw call per material in each node, about 40 to 50 on LOD0.
## The studio
![The studio: garage, customs, viewport with the variant shelf, properties](media/studio.png)
The studio is `bun run dev`, or the desktop build below. It is one window laid
out like a 3D editor:
- **Garage** (left): collections of saved vehicles, kept in IndexedDB. Click to
open, double-click or F2 to rename, drag to reorder, tick several to export
them together. An entry stores the spec, not the mesh, so a thousand-car
collection is smaller than one GLB. Collections import and export as JSON.
- **Customs** (left): numbered part categories (body style, paint, wheels and
every mod). Picking one swings the camera to that part; the **variant shelf**
under the viewport lists its numbered variants. ↑/↓ move between parts, ←/→
fit the next variant.
- **Properties** (right): vertical tabs for the vehicle, body and proportions,
the selected part, paint, wheels, and the rig (steering, lights, opening
panels). Number fields scrub when dragged (Shift for fine steps), take a typed
value when clicked, and reset with ↺.
- **Export** (top right): a split button that repeats the last format for the
open vehicle, or every ticked one as a zip: GLB, GLB with all LODs, or spec
JSON.
- Every edit saves itself and can be undone (Ctrl+Z, Ctrl+Shift+Z). F3 searches
commands, parts, styles and vehicles.
![Sports car at LOD0, LOD1 and LOD2](media/lods.png)
The viewport uses ACES filmic tone mapping, a PMREM studio environment and a
soft contact shadow, with automatic or pinned LOD, wireframe and the collider
hull. Metallic and pearl paint get a fine flake layer under the clearcoat; the
flake map is studio-only, so exported GLBs carry no textures.
### Play mode
![Twelve random seeds](media/random.png)
Press **Drive** (or `P`) to drive the current vehicle around a generated
world.
- **Circuit**: a closed race track with kerbs, gravel run-off, steel barriers
and a start gantry. Every seed draws a different track.
- **Traffic**: a four-lane ring road with pavements, buildings, street lights
and a dozen generated cars sharing it.
The car follows the track spline. It brakes for bends from their curvature,
steers through its wheelbase, rolls and pitches with the load, and turns on
its brake lights when it slows. The camera cuts and dollies between chase,
low front, tracking side, helicopter and wheel-arch shots, with depth of
field focused on the car. Drag to orbit around the moving car; let go and the
camera goes back to following it. `C` and `T` switch worlds and `Esc` returns
to the studio.
Press `?` for the keyboard shortcuts. The main ones are `F3` (search), `R`
(randomise), `N` (new vehicle), `Ctrl+E` (export again), `W` (wireframe) and
`1`/`2`/`3` (pin a LOD).
### Desktop app
The desktop build wraps the same studio in [Tauri](https://tauri.app) v2 with a
frameless window. The top bar doubles as the title bar: drag it to move the
window, double-click it to maximise, and right-click it for the window menu.
F11 toggles fullscreen.
```sh
bun run desktop:dev # needs a Rust toolchain
bun run desktop:build # installer under src-tauri/target/release/bundle
```
## Command line
```sh
bun run render # contact sheet of every body style → renders/
bun scripts/render.ts --rig sedan # doors open, wheels steered
bun scripts/render.ts --random 12 # twelve random seeds
bun run export:glb # every body style → glb/
bun scripts/export-glb.ts --library my-garage.vehicle-generator.json
bun run cages:build # rebuild the authored body cages (python3)
bun run cages:watch # rebuild a cage on every save; the studio reloads in place
bun run cages:build sedan --render renders/cages # six Blender views of a cage (needs Blender)
```
Rendering uses a small software rasteriser, with no browser and no GPU, so the
images in this README are regenerated by a script.
## Verification
```sh
bun run gate
```
`gate` runs every check below.
- `typecheck`: strict TypeScript over the library, the studio and the scripts.
- `verify`: about 3,400 checks. It runs every body style, 26 random seeds,
style blends, every mod on every style (one at a time and all together) and
every livery on every style.
It checks for finite geometry and unit normals, the triangle budget of each
LOD, and draw calls. It checks that tyres sit on the ground and the body
clears it. It checks that every door, bonnet and boot opens, closes exactly
and keeps its hinge in place, that the Ackermann steering is correct, that
wheels roll at the right rate, and that body roll leaves the wheels where
they are. It also checks that the collider hull
encloses the body and is wound outward, that seeds are deterministic, and
that library operations and file round trips work.
- `verify:glb`: exports every style, re-imports it, and checks meshes,
triangles, vertex colours, node names, pivots and animation clips. It then
drives the imported rig and the generated rig side by side and compares
where they put each part.
- `check:docs`: checks this README's numbers and lists against the code.
- `build`: the production web build.
## Layout
```
src/generator/ the library: bodies (loft and cage), wheels, interior, mods, rig, collider, export
src/library/ vehicle libraries: format, IndexedDB store, zip writer
src/app/ the studio
src-tauri/ the desktop shell
assets/src/ authored body cages as Blender Python (built into src/generator/cages/)
scripts/ verification, renders, batch export, cage builds
tools/ brand art: the app icon's painted master and its cut-out
media/ README images
```
## Contributing
This is alpha software: expect rough edges and breaking changes. Bug reports
with a spec JSON (Export → Spec JSON) that reproduces the problem are the most
useful kind. Before sending a change, run `bun run gate`.
## License
MIT © CRTkafa

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

557
assets/src/cagelib.py Normal file
View file

@ -0,0 +1,557 @@
"""
Shared tooling for the body cages: build a tagged control cage from authored
profile tables, preview it in Blender, export it as JSON for the runtime.
Run through an archetype script, never directly:
blender -b --factory-startup --python assets/src/sedan.py -- --out src/generator/cages/sedan.json [--render DIR]
Coordinates are the generator's: metres, +Y up, +Z forward, the body centred
on the origin in Z with the ground at Y = 0. +X is the vehicle's left.
"""
import json
import math
import os
import sys
# ----------------------------------------------------------------- curves
def pchip(points):
"""Monotone cubic through (t, y) points: no overshoot between them."""
pts = sorted(points)
xs = [p[0] for p in pts]
ys = [p[1] for p in pts]
n = len(xs)
if n == 1:
return lambda t: ys[0]
d = [(ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]) for i in range(n - 1)]
m = [0.0] * n
m[0], m[-1] = d[0], d[-1]
for i in range(1, n - 1):
if d[i - 1] * d[i] <= 0:
m[i] = 0.0
else:
w1 = 2 * (xs[i + 1] - xs[i]) + (xs[i] - xs[i - 1])
w2 = (xs[i + 1] - xs[i]) + 2 * (xs[i] - xs[i - 1])
m[i] = (w1 + w2) / (w1 / d[i - 1] + w2 / d[i])
def f(t):
if t <= xs[0]:
return ys[0]
if t >= xs[-1]:
return ys[-1]
lo, hi = 0, n - 1
while hi - lo > 1:
mid = (lo + hi) // 2
if xs[mid] <= t:
lo = mid
else:
hi = mid
h = xs[hi] - xs[lo]
u = (t - xs[lo]) / h
h00 = 2 * u ** 3 - 3 * u ** 2 + 1
h10 = u ** 3 - 2 * u ** 2 + u
h01 = -2 * u ** 3 + 3 * u ** 2
h11 = u ** 3 - u ** 2
return h00 * ys[lo] + h10 * h * m[lo] + h01 * ys[hi] + h11 * h * m[hi]
return f
def smoothstep(a, b, x):
t = min(1.0, max(0.0, (x - a) / (b - a)))
return t * t * (3 - 2 * t)
# ------------------------------------------------------------------- cage
# Ring points per half section, bottom centre (0) to top centre (11):
# under-pan centre, under-pan edge, sill underside / wheel-well ceiling, sill,
# lower flank, character line, lamp line, shoulder, glass middle, roof rail,
# roof (or bonnet) middle, centre line.
HALF = 12
RING = 2 * HALF - 2
CREASES = {3: 3, 5: 1, 7: 2, 9: 1.5}
class Design:
"""An archetype's authored profile: everything the cage is built from."""
def __init__(self, d):
self.d = d
self.front = d['length'] / 2
self.rear = -d['length'] / 2
self.top = pchip(d['top'])
self.belt_in = pchip(d['belt'])
self.sill_base = pchip(d['sill'])
self.hw = pchip(d['halfWidth'])
self.thw = pchip(d['topHalfWidth'])
self.crown = pchip(d['crown'])
self.cowl = d['cowl']
self.deck = d['deck']
self.roof_front = d['roofFront']
self.roof_rear = d['roofRear']
def in_cabin(self, z):
return self.deck < z < self.cowl
def cabin(self, z):
# 0 on bonnet and boot, 1 under the roof; a short ramp at each end.
return smoothstep(self.deck - 0.02, self.deck + 0.08, z) * (1 - smoothstep(self.cowl - 0.08, self.cowl + 0.02, z))
def belt(self, z):
c = self.cabin(z)
return c * self.belt_in(z) + (1 - c) * self.top(z)
def arch_y(self, z):
"""Sill height with the wheel arches cut out of it."""
y = self.sill_base(z)
for ax in self.d['axles']:
r = ax['radius'] + self.d['archGap']
dz = abs(z - ax['z'])
if dz <= r:
y = max(y, ax['radius'] + math.sqrt(r * r - dz * dz))
return y
def flare(self, z):
f = 0.0
for ax in self.d['axles']:
r = (ax['radius'] + self.d['archGap']) * 1.4
dz = abs(z - ax['z']) / r
if dz < 1:
f = max(f, math.cos(dz * math.pi / 2) ** 2)
return f * self.d['flare']
def surface(self, z, x):
"""Height of the top surface at lateral offset x."""
w = max(1e-6, self.thw(z))
xx = min(abs(x), w)
return self.top(z) + self.crown(z) * (1 - (xx / w) ** 2)
def half_ring(self, z):
hw = self.hw(z) + self.flare(z)
thw = min(self.thw(z), hw * 0.97)
sb = self.sill_base(z)
sl = self.arch_y(z)
bt = self.belt(z)
tp = max(self.top(z), bt)
cab = self.cabin(z)
in_arch = sl > sb + 0.015
floor = sb - 0.05
low = max(sl + 0.05, sb + (bt - sb) * 0.3)
char = max(low + 0.04, sb + (bt - sb) * 0.7)
lamp = max(char + 0.02, bt - 0.06)
# The shoulder steps in from the widest line so the flank reads as two
# planes, not one slab.
sx = hw * 0.965
k8x = sx + (thw - sx) * 0.45
k8y = cab * (bt + (tp - bt) * 0.45) + (1 - cab) * self.surface(z, k8x)
# Off the cabin the fender top rolls over into the flank, so the
# shoulder sits below the bonnet line instead of on a flat edge.
roll = self.d.get('shoulderRoll', 0.0) * (1 - cab)
return [
(0.0, floor),
(hw * 0.55, floor),
(hw * 0.62, sl) if in_arch else (hw * 0.88, sb - 0.02),
(hw * 0.9, sl),
(hw * 0.955, min(low, char - 0.02)),
(hw, min(char, lamp - 0.02 - roll)),
(hw * 0.995, min(lamp, bt - 0.012) - roll),
(sx, bt - roll),
(k8x, max(k8y - roll * 0.3, bt - roll + 0.005)),
(thw, max(tp, bt + 0.01)),
(thw * 0.5, self.surface(z, thw * 0.5)),
(0.0, self.surface(z, 0.0)),
]
def rake(self, z, y):
"""Z with the nose leaned back by height: `noseRake` metres at the
bonnet's leading edge, fading out over the nose rounding."""
r = self.d.get('noseRake', 0.0)
span = self.d['noseRound']
if r <= 0 or z <= self.front - span:
return z
w = ((z - (self.front - span)) / span) ** 2
y0 = self.sill_base(self.front)
h = min(1.0, max(0.0, (y - y0) / (self.top(self.front) - y0)))
return z - r * w * h
def stations(self):
d = self.d
must = list(d.get('stations', []))
for ax in d['axles']:
r = ax['radius'] + d['archGap']
for f in (-1.06, -0.86, -0.5, 0.0, 0.5, 0.86, 1.06):
must.append(ax['z'] + f * r)
for k in ('cowl', 'deck', 'roofFront', 'roofRear', 'sideWindowRear', 'sideWindowFront'):
must.append(d[k])
must += d['doorEdges']
if d.get('hood'):
must += list(d['hood'])
if d.get('trunk'):
must += [d['trunk']['front'], d['trunk']['rear']]
if d.get('bPillar') is not None:
must += [d['bPillar'] - 0.05, d['bPillar'] + 0.05]
must += [self.front - 0.18, self.rear + 0.15]
for f in (0.04, 0.16, 0.38, 0.65):
must.append(self.front - f * d['noseRound'])
must.append(self.rear + f * d['tailRound'])
pts = sorted(set(round(z, 4) for z in must if self.rear + 0.005 < z < self.front - 0.005))
pts = [self.rear] + pts + [self.front]
merged = []
for z in pts:
if merged and z - merged[-1] < 0.025 and z not in (self.front,):
continue
merged.append(z)
if merged[-1] != self.front:
merged[-1] = self.front
out = []
for i, z in enumerate(merged):
out.append(z)
if i + 1 < len(merged):
nxt = merged[i + 1]
n = int((nxt - z) / d.get('spacing', 0.3))
for j in range(1, n + 1):
out.append(z + (nxt - z) * j / (n + 1))
return out
def door_of(d, z):
e = d['doorEdges']
if len(e) >= 2 and e[1] < z < e[0]:
return 'F'
if len(e) >= 3 and e[2] < z < e[1]:
return 'R'
return None
def tag_side(des, z, seg, side, z0, z1):
d = des.d
door = door_of(d, z)
door_part = ('door%s%s' % (door, 'L' if side > 0 else 'R')) if door else None
cab = min(des.cabin(z0), des.cabin(z1))
near_front = z > des.front - d['bumperDepth'][0]
near_rear = z < des.rear + d['bumperDepth'][1]
hood = d.get('hood')
in_hood = hood is not None and hood[0] < z < hood[1]
tr = d.get('trunk')
in_lid = tr is not None and tr['kind'] == 'lid' and tr['rear'] < z < tr['front']
in_gate = tr is not None and tr['kind'] == 'tailgate' and z < tr['front']
if seg <= 2:
return 'body|underbody'
if seg <= 6:
part = door_part or 'body'
if (near_front or near_rear) and seg == 3:
return 'body|bumper'
if seg == 6 and z > des.front - d['headWrap']:
return 'body|lightHead'
if seg == 6 and z < des.rear + d['tailWrap']:
return ('trunk' if in_lid else 'body') + '|lightTail'
return part + '|paint'
if seg <= 8:
if cab > 0.5:
on_pillar = d.get('bPillar') is not None and abs(z - d['bPillar']) < 0.05
in_window = d['sideWindowRear'] < z < d['sideWindowFront'] and not on_pillar
part = door_part or 'body'
return (part + '|glass') if in_window else 'body|roof'
if seg == 8 and in_hood:
return 'hood|paint'
if seg == 8 and in_lid:
return 'trunk|paint'
return 'body|paint'
if in_hood:
return 'hood|paint'
if in_lid:
return 'trunk|paint'
windshield = d['roofFront'] < z < d['cowl'] and cab > 0.3
rear_window = d['deck'] < z < d['roofRear'] and cab > 0.3
if in_gate:
return 'trunk|glass' if rear_window else 'trunk|roof'
if windshield or rear_window:
return 'body|glass'
return 'body|roof' if cab > 0.5 else 'body|paint'
def tag_end(des, row, column, direction):
d = des.d
if row <= 1:
return 'body|underbody'
if row == 2:
return 'body|trim'
tr = d.get('trunk')
if direction > 0:
if row == 3:
# A full-width lower intake under the grille.
return 'body|trim'
if row == 4:
return 'body|trim' if column == 'mid' else 'body|bumper'
if row == 5:
return 'body|paint'
if row == 6:
return 'body|lightHead' if column == 'outer' else 'body|trim'
return 'hood|paint' if d.get('hood') and row >= 8 else 'body|paint'
lid = tr is not None
if row == 3:
return 'body|trim' if column == 'mid' else 'body|bumper'
if row == 4:
return 'body|bumper'
if row == 6:
return ('trunk' if lid else 'body') + '|lightTail'
if lid and row >= 7:
return 'trunk|paint'
return 'body|paint'
def build_cage(des):
"""Vertices, faces (quads and the odd triangle), tags and creases."""
zs = des.stations()
pos = []
ring_start = []
for z in zs:
ring_start.append(len(pos))
half = des.half_ring(z)
for (x, y) in half:
pos.append((x, y, des.rake(z, y)))
for k in range(HALF - 2, 0, -1):
x, y = half[k]
pos.append((-x, y, des.rake(z, y)))
def ring_index(k, left):
return 2 * HALF - 2 - k if (left and 0 < k < HALF - 1) else k
def v(i, r):
return ring_start[i] + (r % RING)
faces, tags, creases = [], [], {}
for i in range(len(zs) - 1):
mid = (zs[i] + zs[i + 1]) / 2
for r in range(RING):
faces.append([v(i, r), v(i, r + 1), v(i + 1, r + 1), v(i + 1, r)])
left = r >= HALF - 1
seg = RING - 1 - r if left else r
tags.append(tag_side(des, mid, seg, -1 if left else 1, zs[i], zs[i + 1]))
def crease(a, b, s):
key = (min(a, b), max(a, b))
creases[key] = max(creases.get(key, 0), s)
for i in range(len(zs) - 1):
for k, s in CREASES.items():
for left in (False, True):
r = ring_index(k, left)
crease(v(i, r), v(i + 1, r), s)
mid = (zs[i] + zs[i + 1]) / 2
hood = des.d.get('hood')
if hood and hood[0] < mid < hood[1]:
for left in (False, True):
r = ring_index(10, left)
crease(v(i, r), v(i + 1, r), 1)
for f, face in enumerate(faces):
if tags[f].endswith('|glass'):
for k in range(4):
crease(face[k], face[(k + 1) % 4], 1)
# End caps: four columns per row, middle points pushed out to round the end.
for i, direction in ((len(zs) - 1, 1), (0, -1)):
base = ring_start[i]
z = zs[i]
rnd = des.d['noseRound'] if direction > 0 else des.d['tailRound']
bulge = direction * min(0.12, rnd * 0.35 + 0.015)
mid_r, mid_l = [], []
for k in range(HALF):
if k in (0, HALF - 1):
mid_r.append(base + k)
mid_l.append(base + k)
continue
x, y, zk = pos[base + k]
mid_r.append(len(pos))
pos.append((x * 0.6, y, zk + bulge * 0.6))
mid_l.append(len(pos))
pos.append((-x * 0.6, y, zk + bulge * 0.6))
for k in range(HALF - 1):
r0, r1 = base + ring_index(k, False), base + ring_index(k + 1, False)
l0, l1 = base + ring_index(k, True), base + ring_index(k + 1, True)
cells = [
([r0, r1, mid_r[k + 1], mid_r[k]], 'outer'),
([mid_r[k], mid_r[k + 1], mid_l[k + 1], mid_l[k]], 'mid'),
([mid_l[k], mid_l[k + 1], l1, l0], 'outer'),
]
for quad, column in cells:
uniq = []
for q in quad:
if q not in uniq:
uniq.append(q)
if len(uniq) < 3:
continue
faces.append(uniq if direction > 0 else list(reversed(uniq)))
tags.append(tag_end(des, k, column, direction))
# Outward winding: positive signed volume.
vol = 0.0
for face in faces:
a = pos[face[0]]
for k in range(1, len(face) - 1):
b, c = pos[face[k]], pos[face[k + 1]]
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]))
if vol < 0:
faces = [list(reversed(f)) for f in faces]
return pos, faces, tags, creases, zs
def frame_tables(des, zs):
"""Profile samples the runtime uses for interior, bays, details and the rig."""
rows = []
for z in zs:
rows.append([round(z, 4), round(des.top(z), 4), round(des.belt(z), 4), round(des.arch_y(z), 4),
round(des.sill_base(z), 4), round(des.hw(z) + des.flare(z), 4), round(min(des.thw(z), des.hw(z) * 0.97), 4),
round(des.crown(z), 4), round(des.cabin(z), 4)])
return {'columns': ['z', 'top', 'belt', 'sill', 'sillBase', 'halfWidth', 'topHalfWidth', 'crown', 'cabin'], 'rows': rows}
def export(des, path):
pos, faces, tags, creases, zs = build_cage(des)
names = sorted(set(tags))
d = des.d
data = {
'format': 'vehicle-generator/cage@1',
'style': d['style'],
'base': {k: d[k] for k in ('length', 'width', 'height', 'wheelbase', 'frontOverhang', 'wheelRadius')},
'positions': [round(c, 5) for p in pos for c in p],
'faces': faces,
'tagNames': names,
'faceTags': [names.index(t) for t in tags],
'creases': [[a, b, s] for (a, b), s in sorted(creases.items())],
'stations': {k: d[k] for k in ('cowl', 'deck', 'roofFront', 'roofRear', 'sideWindowRear', 'sideWindowFront', 'doorEdges', 'bPillar')},
'hood': d.get('hood'),
'trunk': d.get('trunk'),
'noseRake': d.get('noseRake', 0.0),
'axles': d['axles'],
'archGap': d['archGap'],
'anchors': d.get('anchors', {}),
'frame': frame_tables(des, zs),
}
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8', newline='\n') as fh:
json.dump(data, fh, separators=(',', ':'))
fh.write('\n')
print('cage: %s %d verts %d faces %d creases' % (path, len(pos), len(faces), len(creases)))
return pos, faces, tags, creases
# ------------------------------------------------------------------ blender
COLOURS = {
'paint': (0.42, 0.03, 0.05, 1), 'roof': (0.42, 0.03, 0.05, 1), 'bumper': (0.42, 0.03, 0.05, 1),
'glass': (0.02, 0.025, 0.03, 1), 'trim': (0.03, 0.03, 0.035, 1), 'underbody': (0.02, 0.02, 0.02, 1),
'lightHead': (0.9, 0.92, 0.95, 1), 'lightTail': (0.7, 0.02, 0.02, 1),
}
def preview(des, pos, faces, tags, creases, out_dir):
"""Six Eevee renders of the subdivided cage, with wheels as plain tyres."""
import bpy
import bmesh
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
mesh = bpy.data.meshes.new('cage')
# Blender is Z-up: (x, y, z) here = (x, -z, y) there.
mesh.from_pydata([(p[0], -p[2], p[1]) for p in pos], [], faces)
mesh.update()
bm = bmesh.new()
bm.from_mesh(mesh)
bm.edges.ensure_lookup_table()
layer = bm.edges.layers.float.get('crease_edge') or bm.edges.layers.float.new('crease_edge')
for e in bm.edges:
a, b = e.verts[0].index, e.verts[1].index
s = creases.get((min(a, b), max(a, b)), 0)
e[layer] = min(1.0, s / 3.0)
bm.to_mesh(mesh)
bm.free()
obj = bpy.data.objects.new('cage', mesh)
scene.collection.objects.link(obj)
mats = {}
for name, col in COLOURS.items():
m = bpy.data.materials.new(name)
m.use_nodes = True
bsdf = m.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Base Color'].default_value = col
bsdf.inputs['Roughness'].default_value = 0.08 if name in ('glass', 'paint', 'roof', 'bumper') else 0.5
if name == 'paint' or name == 'roof' or name == 'bumper':
bsdf.inputs['Coat Weight'].default_value = 1.0
if name.startswith('light'):
bsdf.inputs['Emission Color'].default_value = col
bsdf.inputs['Emission Strength'].default_value = 1.5
obj.data.materials.append(m)
mats[name] = len(obj.data.materials) - 1
for f, poly in enumerate(mesh.polygons):
poly.material_index = mats.get(tags[f].split('|')[1], 0)
poly.use_smooth = True
mod = obj.modifiers.new('subd', 'SUBSURF')
mod.levels = 2
mod.render_levels = 3
# Wheels.
for ax in des.d['axles']:
for side in (1, -1):
bpy.ops.mesh.primitive_cylinder_add(vertices=48, radius=ax['radius'], depth=0.235,
location=(side * (des.d['track'] / 2), -ax['z'], ax['radius']), rotation=(0, math.pi / 2, 0))
t = bpy.context.active_object
m = bpy.data.materials.new('tyre')
m.use_nodes = True
m.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (0.02, 0.02, 0.02, 1)
t.data.materials.append(m)
bpy.ops.mesh.primitive_cylinder_add(vertices=48, radius=ax['radius'] * 0.72, depth=0.24,
location=(side * (des.d['track'] / 2), -ax['z'], ax['radius']), rotation=(0, math.pi / 2, 0))
rim = bpy.context.active_object
m2 = bpy.data.materials.new('rim')
m2.use_nodes = True
m2.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (0.5, 0.52, 0.55, 1)
m2.node_tree.nodes['Principled BSDF'].inputs['Metallic'].default_value = 1.0
rim.data.materials.append(m2)
bpy.ops.mesh.primitive_plane_add(size=40)
floor = bpy.context.active_object
fm = bpy.data.materials.new('floor')
fm.use_nodes = True
fm.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (0.6, 0.6, 0.6, 1)
floor.data.materials.append(fm)
world = bpy.data.worlds.new('w')
world.use_nodes = True
world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.75, 0.78, 0.82, 1)
world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.9
scene.world = world
sun = bpy.data.objects.new('sun', bpy.data.lights.new('sun', 'SUN'))
sun.data.energy = 3.5
sun.rotation_euler = (0.7, 0.2, 0.6)
scene.collection.objects.link(sun)
cam = bpy.data.objects.new('cam', bpy.data.cameras.new('cam'))
cam.data.lens = 70
scene.collection.objects.link(cam)
scene.camera = cam
scene.render.engine = 'BLENDER_EEVEE'
scene.render.resolution_x = 900
scene.render.resolution_y = 560
scene.render.film_transparent = False
views = {
'front34': (1, 1.25, 0.32), 'rear34': (-1, -1.15, 0.32), 'side': (1, 0.0, 0.06),
'front': (0.0, 1, 0.1), 'rear': (0.0, -1, 0.12), 'top': (0.0, 0.001, 1),
}
import mathutils
target = mathutils.Vector((0, 0, 0.7))
out_dir = os.path.abspath(out_dir)
os.makedirs(out_dir, exist_ok=True)
for name, (x, z, y) in views.items():
direction = mathutils.Vector((x, -z, y)).normalized()
dist = 15.0
cam.location = target + direction * dist
cam.rotation_euler = (target - cam.location).to_track_quat('-Z', 'Y').to_euler()
scene.render.filepath = os.path.join(out_dir, '%s-%s.png' % (des.d['style'], name))
bpy.ops.render.render(write_still=True)
print('renders in', out_dir)
def main(design):
argv = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
out = argv[argv.index('--out') + 1] if '--out' in argv else 'src/generator/cages/%s.json' % design['style']
des = Design(design)
pos, faces, tags, creases = export(des, out)
if '--render' in argv:
preview(des, pos, faces, tags, creases, argv[argv.index('--render') + 1])

79
assets/src/sedan.py Normal file
View file

@ -0,0 +1,79 @@
"""
Sedan cage: a modern (2015-2025) mid-size saloon, unbranded.
4.85 x 1.86 x 1.44 m, 2.84 m wheelbase, 0.93 m front and 1.08 m rear
overhang, 235/40 R19. Short bonnet, windscreen base 0.4 m behind the front
axle, roof peaking over the B-pillar, a long fastback C-pillar into a short
deck with a small ducktail.
blender -b --factory-startup --python assets/src/sedan.py -- --out src/generator/cages/sedan.json [--render DIR]
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import cagelib # noqa: E402
R = 0.345
FRONT_AXLE = 2.425 - 0.93
REAR_AXLE = FRONT_AXLE - 2.84
DESIGN = {
'style': 'sedan',
'length': 4.85, 'width': 1.86, 'height': 1.44, 'wheelbase': 2.84, 'frontOverhang': 0.93, 'wheelRadius': R,
'track': 1.6,
'axles': [{'z': FRONT_AXLE, 'radius': R}, {'z': REAR_AXLE, 'radius': R}],
'archGap': 0.022,
'flare': 0.022,
'noseRound': 0.3,
'tailRound': 0.25,
# The nose leans back 9 cm from bumper to bonnet edge, and the fender tops
# roll 6 cm down into the flank.
'noseRake': 0.09,
'shoulderRoll': 0.06,
'spacing': 0.38,
# Stations (z, metres, +forward). The cabin sits over the middle of the
# wheelbase: windscreen base 0.4 m behind the front axle, roof peak over
# the B-pillar, a fastback C-pillar into a short deck.
'cowl': 1.08, 'roofFront': 0.2, 'roofRear': -0.88, 'deck': -1.70,
'sideWindowFront': 0.80, 'sideWindowRear': -1.22,
'doorEdges': [1.12, 0.02, -0.9], 'bPillar': 0.02,
'hood': [1.13, 2.32],
'trunk': {'kind': 'lid', 'front': -1.74, 'rear': -2.38},
'bumperDepth': [0.45, 0.4], 'headWrap': 0.26, 'tailWrap': 0.18,
# Side profile: height of the top surface at its edge. A tall nose (the
# bonnet's leading edge near 0.8 m, as pedestrian rules set it) and a
# bonnet that climbs gently to the cowl; the roof edge stays near 1.4 m from the
# B-pillar back and drops in one long arc to the deck.
'top': [
(2.425, 0.70), (2.40, 0.77), (2.34, 0.81), (2.15, 0.845), (1.8, 0.885), (1.45, 0.925), (1.08, 0.965),
(0.85, 1.07), (0.6, 1.19), (0.35, 1.30), (0.2, 1.345),
(0.0, 1.385), (-0.35, 1.40), (-0.88, 1.36),
(-1.15, 1.28), (-1.45, 1.17), (-1.70, 1.09),
(-1.95, 1.075), (-2.25, 1.07), (-2.34, 1.055), (-2.40, 1.0), (-2.425, 0.93),
],
# Extra height on the centre line.
'crown': [(2.425, 0.0), (2.2, 0.025), (1.08, 0.04), (0.2, 0.05), (-0.88, 0.05), (-1.7, 0.035), (-2.425, 0.0)],
# Beltline (window sill) through the cabin, rising to the rear.
'belt': [(1.08, 0.965), (0.2, 0.985), (-0.9, 1.03), (-1.70, 1.085)],
# Sill (rocker) height, lifting into the bumpers.
'sill': [(2.425, 0.34), (2.2, 0.27), (1.9, 0.25), (-1.7, 0.25), (-2.1, 0.29), (-2.425, 0.38)],
# Plan view: half width at the flank. A rounded nose and tail.
'halfWidth': [
(2.425, 0.50), (2.40, 0.64), (2.34, 0.75), (2.2, 0.84), (1.95, 0.895), (1.5, 0.915), (0.5, 0.915),
(-0.6, 0.92), (-1.35, 0.92), (-1.9, 0.90), (-2.2, 0.86), (-2.36, 0.78), (-2.425, 0.62),
],
# Half width of the top surface: bonnet between the fender tops, greenhouse
# (tumblehome) and deck.
'topHalfWidth': [
(2.425, 0.44), (2.3, 0.58), (1.8, 0.68), (1.08, 0.72), (0.85, 0.70), (0.2, 0.63), (-0.88, 0.62),
(-1.2, 0.66), (-1.5, 0.72), (-1.7, 0.78), (-2.3, 0.74), (-2.425, 0.56),
],
'anchors': {
'spoiler': [0, 1.08, -2.34], 'roof': [0, 1.45, -0.35], 'exhaust': [0.45, 0.3, -2.42],
'plateFront': [0, 0.45, 2.43], 'plateRear': [0, 0.62, -2.43],
'mirrorL': [0.93, 1.0, 0.93], 'mirrorR': [-0.93, 1.0, 0.93],
},
}
cagelib.main(DESIGN)

203
bun.lock Normal file
View file

@ -0,0 +1,203 @@
{
"lockfileVersion": 2,
"configVersion": 1,
"workspaces": {
"": {
"name": "car-kit",
"dependencies": {
"@tauri-apps/api": "^2",
"three": "^0.185.1",
},
"devDependencies": {
"@tauri-apps/cli": "^2",
"@types/node": "^22.15.3",
"@types/three": "^0.185.4",
"@webgpu/types": "^0.1.72",
"typescript": "^5.9.2",
"vite": "^7.1.5",
},
"peerDependencies": {
"three": ">=0.185.0",
},
},
},
"packages": {
"@dimforge/rapier3d-compat": ["@dimforge/rapier3d-compat@0.12.0", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="],
"@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="],
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="],
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="],
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="],
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="],
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="],
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="],
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="],
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="],
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="],
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="],
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="],
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="],
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="],
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="],
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="],
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="],
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="],
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="],
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="],
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="],
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="],
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="],
"@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.63.5", "", { "os": "android", "cpu": "arm" }, "sha512-J25QJU+B78T4FhhBsNpLJyVWOi31mwtpcMwywHmOKH65Q9IWGA81gPj+dnwlhU8wktVriYE+tFAaQgrnJRzAZg=="],
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.63.5", "", { "os": "android", "cpu": "arm64" }, "sha512-LDopB3zuZM5Ux9TT2luNEBJW/tYbGU2g1d+VpKk6I+gSKDb+/7sYE6M225gRQt4RbMX6MSwMsVR/phdjVUgRLg=="],
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.63.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-wlJEERGfeuHeBavCL2qVnNacOK43NDoZM4sjkeRPymd04OAE9T1zBqDJgmZ+CIsPTYKwdzpUC8vmOw84dwY4Tg=="],
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.63.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-4nJJGg5jbo2wwPP4JP+LfEBA3bvP8rU9CLuhp7jWvq9sxEyhjQFTFdrqi+/dHEin/pd8jpT0vcehIpnZtmEdcQ=="],
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.63.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-DrZbyCDF1hneuO6jRbvZ2D7+PIBM6yIwYnJpg2vIk58T+wuFpiaGZrfUr59lDWw45bg+IrpTGLPiNi/Fk4w3Cg=="],
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.63.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-gqfUVMJMB3mehqywxp6hTBFfgtMQykZY19+cfiaYP0toIJLb/1DZRJHVkQQGP13W4TAwfZDWeg1qBcheTRioXQ=="],
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.63.5", "", { "os": "linux", "cpu": "arm" }, "sha512-CFmhpvAwzSaWMlN3VN7UtmoTihlZNzoP0juQib5TQRnYUyDV8dXeWOp29sobWAT6gXl/hQgAClLlEiYozQG3OQ=="],
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.63.5", "", { "os": "linux", "cpu": "arm" }, "sha512-Uc9H8eXCOayV6JLTH5bXKMId6qbhNHa818/BgYjm4jrlq3vZquC9cqyvHBw17xy5Mnj5f+I3gFK5JcEf3hSqrw=="],
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.63.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-VcPr/szv/1BFw112Kt//fxulXt/JPqzzidU84iW68L2DdjnOO8QFUv2zTSYBEPHD6movBD4z+bbr5y60GYM7Jw=="],
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.63.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-BnxtJ5/91BrIHYIkGrmjz/lbMhqEHt1dPFqIxIFR+jPn0xVc/oUSCtIT089zfp5ufwGDlYz2UC+Fe1SRBpYFbQ=="],
"@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.63.5", "", { "os": "linux", "cpu": "none" }, "sha512-LrYcHZwF+fAMNKHYTOQ5osWM4AZF7YF6D+XtsjDyEvljtt11twc+zHVXBLNEjxVSUnKYsOhvVz4Z213eW02COQ=="],
"@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.63.5", "", { "os": "linux", "cpu": "none" }, "sha512-nj7QKQePAAUpCpJHtg0pR0W/b92A9NO17JS3BAQmHDn/yhmkir2p8llrKY9TOhleKIaSzy1JhxS3T9FVld6coA=="],
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.63.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-5ylkX6dWMeBKge9nTU+Rxfb+ZfaCIJ9lRqIFaK0eAMcWp7OJbYnLveLgXmm0VrvuLKb8qIK+mHyH0qu88RM+iA=="],
"@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.63.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-oHK4ZHYFDKjZviK34I+NwgfbGxgI7ztrNxj2hPTSSNFgeq1a/lEd7dHV2fdGAuTH4Iym3RHJg+vAbWaWG4B7Zg=="],
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.63.5", "", { "os": "linux", "cpu": "none" }, "sha512-UcetmHZ6XOXuUByiKZyQmb55ZPr0LABr3Ec/HB9wKZn6CEAFWZkE+hsJErJ9hbPBC7nI0dKuELx7CoV6IM7TMg=="],
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.63.5", "", { "os": "linux", "cpu": "none" }, "sha512-C5CmDPQBtvjVo8cgQsBs+w6WB0JLkiixhgi6hVLV11hERWdn/p0XcPU2OUcZzac9BPOFq7SbaHFa8r3SWEysCQ=="],
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.63.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-lHVQHJFKsuuxLMi3MQO9XVL8Tje3JR82CzB+QDKC5NWBcsIWuwsn9uIM5e3lBhI+fF1/s63qnyYqsg65+8rV/w=="],
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.63.5", "", { "os": "linux", "cpu": "x64" }, "sha512-3W9bTFcQNJn71cSJVM9RKIiZOy8DO/XLDii8Uv/Pm6WKqDRj7JV3ZfuXIEfyuy5LXpIzAbB/1M4Ukp9GKNa7nA=="],
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.63.5", "", { "os": "linux", "cpu": "x64" }, "sha512-VDC7rRJlee/scpki96GZ27Omf6yU87s1YXwVTpjE5841faVlDYYT565rgfmoR1U0sqL7z5ivQSDjcsF6VRXyBA=="],
"@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.63.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-z86Ok2p4pTdv5xqCKZsTooO7yBEiaJR/HzU3Wx8RmWsPoLppnMKROhJusQob8B3IE1ghC343kUW9rC2r+Wf3ig=="],
"@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.63.5", "", { "os": "none", "cpu": "arm64" }, "sha512-IzQmj+xXwQFGhMAMKMQVXkMwMZN3TqkJgAE0nSsqvVwWWciP4AIPMmWRqOQ2GfX7TUDZr+xqGFcBS36CRPGw0g=="],
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.63.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-F6qpTaPc9bwBH85kjy0/BLmLSW1uv7AoOXCoRIkg2arlgCYlWYcAbiMkvZuAcaWk9TpCRG//okznLAqLGshkMw=="],
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.63.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-igoDsTFhhwECBeGbUuLeIk7t8Y1apa+cs6mDWpx2EZ0ch7oEQgzHbFUXN9euoHekCAQzXdXApAGkV6jznS7tWw=="],
"@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.63.5", "", { "os": "win32", "cpu": "x64" }, "sha512-U3teMeMbXFmaM5D+OTJpsOXd+wV/qftIeYF9kBKL4v73641qyJmoXFtA28DQLsnmlyayEsTe72xpLHrArq6vHw=="],
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.63.5", "", { "os": "win32", "cpu": "x64" }, "sha512-ypfC34F3RKXvCXBglGqGMsUSMKlgwd1HX9AOAlx9RoZZ6GaI42YHVeKpzg3JG+wpBUJYTG+NNZhqbDWL8tBZkw=="],
"@tauri-apps/api": ["@tauri-apps/api@2.12.1", "", {}, "sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ=="],
"@tauri-apps/cli": ["@tauri-apps/cli@2.12.1", "", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.12.1", "@tauri-apps/cli-darwin-x64": "2.12.1", "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.1", "@tauri-apps/cli-linux-arm64-gnu": "2.12.1", "@tauri-apps/cli-linux-arm64-musl": "2.12.1", "@tauri-apps/cli-linux-riscv64-gnu": "2.12.1", "@tauri-apps/cli-linux-x64-gnu": "2.12.1", "@tauri-apps/cli-linux-x64-musl": "2.12.1", "@tauri-apps/cli-win32-arm64-msvc": "2.12.1", "@tauri-apps/cli-win32-ia32-msvc": "2.12.1", "@tauri-apps/cli-win32-x64-msvc": "2.12.1" }, "bin": { "tauri": "tauri.js" } }, "sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg=="],
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.12.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw=="],
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.12.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg=="],
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.12.1", "", { "os": "linux", "cpu": "arm" }, "sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ=="],
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.12.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw=="],
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.12.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg=="],
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.12.1", "", { "os": "linux", "cpu": "none" }, "sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ=="],
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.12.1", "", { "os": "linux", "cpu": "x64" }, "sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA=="],
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.12.1", "", { "os": "linux", "cpu": "x64" }, "sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w=="],
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.12.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA=="],
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.12.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q=="],
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.12.1", "", { "os": "win32", "cpu": "x64" }, "sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg=="],
"@tweenjs/tween.js": ["@tweenjs/tween.js@23.1.3", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
"@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
"@types/node": ["@types/node@22.20.4", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA=="],
"@types/stats.js": ["@types/stats.js@0.17.4", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="],
"@types/three": ["@types/three@0.185.4", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": ">=0.5.17", "fflate": "~0.8.2", "meshoptimizer": "~1.1.1" } }, "sha512-gAsBIC07NIFrxjbf7tH2t71c38uulFfk/RFoC7FNBSjMRAQ8J1x/RBvusX0N5PJouaYFJawXQqfCQ0RKUx/1nA=="],
"@types/webxr": ["@types/webxr@0.5.24", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="],
"@webgpu/types": ["@webgpu/types@0.1.74", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="],
"esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"meshoptimizer": ["meshoptimizer@1.1.1", "", {}, "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g=="],
"nanoid": ["nanoid@3.3.19", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
"postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="],
"rollup": ["rollup@4.63.5", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.63.5", "@rollup/rollup-android-arm64": "4.63.5", "@rollup/rollup-darwin-arm64": "4.63.5", "@rollup/rollup-darwin-x64": "4.63.5", "@rollup/rollup-freebsd-arm64": "4.63.5", "@rollup/rollup-freebsd-x64": "4.63.5", "@rollup/rollup-linux-arm-gnueabihf": "4.63.5", "@rollup/rollup-linux-arm-musleabihf": "4.63.5", "@rollup/rollup-linux-arm64-gnu": "4.63.5", "@rollup/rollup-linux-arm64-musl": "4.63.5", "@rollup/rollup-linux-loong64-gnu": "4.63.5", "@rollup/rollup-linux-loong64-musl": "4.63.5", "@rollup/rollup-linux-ppc64-gnu": "4.63.5", "@rollup/rollup-linux-ppc64-musl": "4.63.5", "@rollup/rollup-linux-riscv64-gnu": "4.63.5", "@rollup/rollup-linux-riscv64-musl": "4.63.5", "@rollup/rollup-linux-s390x-gnu": "4.63.5", "@rollup/rollup-linux-x64-gnu": "4.63.5", "@rollup/rollup-linux-x64-musl": "4.63.5", "@rollup/rollup-openbsd-x64": "4.63.5", "@rollup/rollup-openharmony-arm64": "4.63.5", "@rollup/rollup-win32-arm64-msvc": "4.63.5", "@rollup/rollup-win32-ia32-msvc": "4.63.5", "@rollup/rollup-win32-x64-gnu": "4.63.5", "@rollup/rollup-win32-x64-msvc": "4.63.5", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-KRWwmNLlPw5M7HcdYfm15oBv9n9LPtjzpzCIxS/phwqvPyxHSoKX6Y2YU3pxSPfy0CLquVgsx/j/hBi6OvH1Nw=="],
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"three": ["three@0.185.1", "", {}, "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg=="],
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],
}
}

17
index.html Normal file
View file

@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vehicle Generator</title>
<meta name="description" content="Procedural, game-ready vehicle generator for three.js: body styles, mods, paint, LODs, rigging and GLB export." />
<meta name="theme-color" content="#161618" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@600;700&family=JetBrains+Mono:wght@400;500&family=Manrope:wght@400;500;600;700;800&display=swap" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/app/main.ts"></script>
</body>
</html>

BIN
media/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

BIN
media/lods.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

BIN
media/random.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 291 KiB

BIN
media/rig.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

BIN
media/sedan.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

BIN
media/studio.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

BIN
media/styles.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 301 KiB

64
package.json Normal file
View file

@ -0,0 +1,64 @@
{
"name": "vehicle-generator",
"version": "0.1.0",
"description": "Procedural, game-ready vehicle generator for three.js: parametric body styles, composable mods, paint, LODs, colliders and GLB export.",
"type": "module",
"license": "MIT",
"author": "CRTkafa",
"repository": {
"type": "git",
"url": "git+https://git.crt.fyi/CRT/vehicle-generator.git"
},
"keywords": [
"threejs",
"procedural",
"vehicle",
"car",
"generator",
"gamedev",
"lod",
"gltf"
],
"exports": {
".": "./src/generator/index.ts"
},
"files": [
"src/generator",
"README.md",
"LICENSE"
],
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"verify": "bun scripts/verify.ts",
"verify:glb": "bun scripts/verify-glb.ts",
"cages:build": "bun scripts/cages.ts",
"cages:watch": "bun scripts/cages.ts --watch",
"check:docs": "bun scripts/check-docs.ts",
"render": "bun scripts/render.ts",
"export:glb": "bun scripts/export-glb.ts",
"tauri": "tauri",
"desktop:dev": "tauri dev",
"desktop:build": "tauri build",
"brand:paint": "python3 tools/brand.py paint",
"icons": "tauri icon media/icon.png",
"gate": "bun run typecheck && bun run verify && bun run verify:glb && bun run check:docs && bun run build"
},
"peerDependencies": {
"three": ">=0.185.0"
},
"dependencies": {
"@tauri-apps/api": "^2",
"three": "^0.185.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2",
"@types/node": "^22.15.3",
"@types/three": "^0.185.4",
"@webgpu/types": "^0.1.72",
"typescript": "^5.9.2",
"vite": "^7.1.5"
}
}

76
scripts/cages.ts Normal file
View file

@ -0,0 +1,76 @@
/**
* Rebuilds the authored body cages with Blender, headless.
*
* bun run cages:build every archetype in assets/src
* bun run cages:build sedan one
* bun run cages:build sedan --render renders/cages
* bun run cages:watch rebuild on every save under assets/src
*
* Building a cage is plain Python, so it runs on python3 in a fraction of a
* second; Blender is started only for `--render` (or when python3 is missing).
* BLENDER may point at the executable; otherwise the usual install paths are
* tried. The JSON lands in src/generator/cages; the runtime never needs Blender.
*/
import { spawnSync } from 'node:child_process'
import { copyFileSync, existsSync, readdirSync, readFileSync, rmSync, watch } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const candidates = [
process.env.BLENDER,
'C:/Program Files (x86)/Steam/steamapps/common/Blender/blender.exe',
'C:/Program Files/Blender Foundation/Blender/blender.exe',
'/Applications/Blender.app/Contents/MacOS/Blender',
`${process.env.HOME}/Library/Application Support/Steam/steamapps/common/Blender/Blender.app/Contents/MacOS/Blender`,
'/usr/bin/blender',
'blender',
].filter(Boolean) as string[]
const blender = candidates.find((c) => c === 'blender' || existsSync(c))!
const python = spawnSync('python3', ['--version']).status === 0 ? 'python3' : null
const args = process.argv.slice(2)
const renderAt = args.indexOf('--render')
const render = renderAt >= 0 ? ['--render', args[renderAt + 1]!] : []
const names = args.filter((a, i) => !a.startsWith('--') && i !== renderAt + 1)
const styles = names.length ? names : readdirSync('assets/src').filter((f) => f.endsWith('.py') && f !== 'cagelib.py').map((f) => f.slice(0, -3))
function build(list: readonly string[]): boolean {
for (const style of list) {
const t0 = performance.now()
// Written beside, then moved over the checked-in JSON only when it changed,
// so an unchanged save does not reload the studio.
const out = `src/generator/cages/${style}.json`
const fresh = join(tmpdir(), `vehicle-generator-cage-${style}.json`)
const script = [`assets/src/${style}.py`, '--', '--out', fresh, ...render]
const run = render.length || !python ? spawnSync(blender, ['-b', '--factory-startup', '--python', ...script], { encoding: 'utf8' }) : spawnSync(python, script, { encoding: 'utf8' })
const lines = `${run.stdout}\n${run.stderr}`.split('\n').filter((l) => /^cage:|renders in|Error|Traceback|line \d+/.test(l)).map((l) => l.replace(fresh, out))
console.log(`${lines.join('\n')}${watching ? ` (${Math.round(performance.now() - t0)} ms)` : ''}`)
if (run.status !== 0) return false
if (!existsSync(out) || readFileSync(out, 'utf8') !== readFileSync(fresh, 'utf8')) copyFileSync(fresh, out)
rmSync(fresh)
}
return true
}
const watching = args.includes('--watch')
if (!watching) {
if (!build(styles)) process.exit(1)
} else {
// A save to one archetype rebuilds it; a save to the shared library rebuilds
// them all. Vite picks up the new JSON and the studio reloads in place.
build(styles)
const all = (): string[] => readdirSync('assets/src').filter((f) => f.endsWith('.py') && f !== 'cagelib.py').map((f) => f.slice(0, -3))
let pending = new Set<string>()
let timer: ReturnType<typeof setTimeout> | null = null
watch('assets/src', (_event, file) => {
if (!file || !file.endsWith('.py')) return
for (const style of file === 'cagelib.py' ? all() : [file.slice(0, -3)]) pending.add(style)
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
const list = [...pending].filter((s) => existsSync(`assets/src/${s}.py`))
pending = new Set()
build(list)
}, 150)
})
console.log('watching assets/src')
}

48
scripts/check-docs.ts Normal file
View file

@ -0,0 +1,48 @@
/**
* Checks that the README still describes the generator that exists.
*
* Numbers in a README go stale the day something changes, and a confident
* wrong number is worse than none. So the ones it quotes — how many body
* styles, how many mods, the sedan's triangle counts per LOD — are checked
* against the code, and every style and mod has to be named.
*
* bun scripts/check-docs.ts
*/
import { readFileSync } from 'node:fs'
import { BODY_STYLES, generateVehicle, MOD_KINDS, preset } from '../src/generator/index.ts'
const failures: string[] = []
function expect(label: string, ok: boolean, detail = ''): void {
console.log(` ${ok ? 'PASS' : 'FAIL'} ${label}${!ok && detail ? ` — ${detail}` : ''}`)
if (!ok) failures.push(label)
}
const hasNumber = (text: string, value: number): boolean =>
new RegExp(`\\b${String(value).replace(/\B(?=(\d{3})+(?!\d))/g, '[ ,]?')}\\b`).test(text)
const sedan = generateVehicle(preset('sedan'))
const lods = sedan.lods.map((l) => l.triangles)
sedan.dispose()
const readme = readFileSync('README.md', 'utf8')
console.log('README.md')
expect('body style count', new RegExp(`\\b${BODY_STYLES.length} body styles\\b`).test(readme), `expected "${BODY_STYLES.length} body styles"`)
expect('mod count', new RegExp(`\\b${MOD_KINDS.length} (composable )?mods\\b`).test(readme), `expected "${MOD_KINDS.length} mods"`)
const missingStyles = BODY_STYLES.filter((s) => !readme.includes(`\`${s}\``))
expect('every body style named', missingStyles.length === 0, missingStyles.join(', '))
const missingMods = MOD_KINDS.filter((m) => !readme.includes(`\`${m}\``))
expect('every mod named', missingMods.length === 0, missingMods.join(', '))
for (const [i, n] of lods.entries()) expect(`sedan LOD${i} triangle count (${n})`, hasNumber(readme, n))
expect('no absolute user paths', !/[A-Z]:\\Users\\|\/Users\/|\/home\//.test(readme))
for (const image of [...readme.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)].map((m) => m[1]!)) {
let ok = true
try { readFileSync(image) } catch { ok = false }
expect(`image exists: ${image}`, ok)
}
if (failures.length) {
console.log(`${failures.length} documentation check(s) FAILED.`)
process.exit(1)
}
console.log('Documentation matches the generator.')

60
scripts/export-glb.ts Normal file
View file

@ -0,0 +1,60 @@
/**
* Batch GLB export from the command line.
*
* bun scripts/export-glb.ts every body style → glb/
* bun scripts/export-glb.ts --library garage.json every entry of a saved library
* bun scripts/export-glb.ts --random 20 twenty random vehicles
* bun scripts/export-glb.ts --lod all all three LODs in each file
*/
import './glb-node.ts'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import {
BODY_STYLES,
exportVehicleGlb,
generateVehicle,
type LodLevel,
preset,
randomSpec,
type VehicleSpec,
} from '../src/generator/index.ts'
import { parseLibrary } from '../src/library/format.ts'
const args = process.argv.slice(2)
const flag = (name: string): string | undefined => {
const at = args.indexOf(`--${name}`)
return at >= 0 ? args[at + 1] : undefined
}
const outDir = flag('out') ?? 'glb'
const lodFlag = flag('lod')
const lod: LodLevel | 'all' = lodFlag === 'all' ? 'all' : (Number(lodFlag ?? 0) as LodLevel)
await mkdir(outDir, { recursive: true })
let jobs: { name: string; spec: VehicleSpec }[]
const libraryPath = flag('library')
const random = flag('random')
if (libraryPath) {
const library = parseLibrary(JSON.parse(await readFile(libraryPath, 'utf8')))
jobs = library.entries.map((e) => ({ name: e.name, spec: e.spec }))
} else if (random) {
jobs = Array.from({ length: Number(random) }, (_, k) => ({ name: `random-${k + 1}`, spec: randomSpec(k + 1) }))
} else {
jobs = BODY_STYLES.map((style) => ({ name: style, spec: preset(style) }))
}
const slug = (name: string): string => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'vehicle'
let total = 0
const used = new Set<string>()
for (const job of jobs) {
const vehicle = generateVehicle(job.spec, { lods: lod === 'all' ? [0, 1, 2] : [lod] })
const buffer = await exportVehicleGlb(vehicle, { lod: lod === 'all' ? 'all' : lod })
vehicle.dispose()
let file = slug(job.name)
for (let k = 2; used.has(file); k += 1) file = `${slug(job.name)}-${k}`
used.add(file)
await writeFile(`${outDir}/${file}.glb`, new Uint8Array(buffer))
total += buffer.byteLength
console.log(` ${file.padEnd(24)} ${(buffer.byteLength / 1024).toFixed(0).padStart(6)} KB`)
}
console.log(`\n${jobs.length} vehicles → ${outDir}/ · ${(total / 1024 / 1024).toFixed(1)} MB`)

23
scripts/glb-node.ts Normal file
View file

@ -0,0 +1,23 @@
/**
* GLTFExporter collects its binary output through `FileReader`, a browser API
* bun does not have. This covers the one method the exporter calls. Import it
* before anything that loads the exporter.
*/
class BunFileReader {
result: ArrayBuffer | string | null = null
onloadend: (() => void) | null = null
onerror: ((error: unknown) => void) | null = null
readAsArrayBuffer(blob: Blob): void {
// The exporter assigns `onloadend` after calling this, so resolve later.
void blob.arrayBuffer().then(
(buffer) => { this.result = buffer; this.onloadend?.() },
(error) => { this.onerror?.(error) },
)
}
}
const globals = globalThis as { FileReader?: unknown }
globals.FileReader ??= BunFileReader
export {}

347
scripts/raster.ts Normal file
View file

@ -0,0 +1,347 @@
/**
* A small software rasteriser: a scene graph in, a PNG out. No browser, no GPU.
*
* It exists so a vehicle can be LOOKED AT from a script — in CI, in a review,
* in the README — without a display. Every other check is geometric, and none
* of them can say "that does not look like a pickup".
*
* Shading is deliberately simple: a key light, a sky/ground hemisphere, a
* Blinn highlight scaled by roughness and a fake environment tint for metals.
* Glass is drawn after everything opaque, blended and without depth writes.
* The image is rendered at 2× and box-filtered down for antialiasing.
*/
import { deflateSync } from 'node:zlib'
import {
Box3,
Color,
Matrix3,
Mesh,
type MeshStandardMaterial,
type Object3D,
PerspectiveCamera,
Sphere,
Vector3,
} from 'three'
interface Tri {
readonly p: [Vector3, Vector3, Vector3]
readonly n: [Vector3, Vector3, Vector3]
readonly c: [[number, number, number], [number, number, number], [number, number, number]]
readonly rough: number
readonly metal: number
readonly coat: number
readonly emissive: [number, number, number]
readonly opacity: number
}
export interface Frame {
readonly width: number
readonly height: number
readonly rgb: Float32Array
}
function collect(root: Object3D): { opaque: Tri[]; clear: Tri[] } {
root.updateMatrixWorld(true)
const opaque: Tri[] = []
const clear: Tri[] = []
root.traverseVisible((object) => {
if (!(object instanceof Mesh)) return
const g = object.geometry
const pos = g.getAttribute('position')
const nor = g.getAttribute('normal')
const col = g.getAttribute('color')
const index = g.getIndex()
const m = object.material as MeshStandardMaterial & { opacity: number; transparent: boolean }
const base = (m.color ?? new Color(1, 1, 1)) as Color
const em = m.emissive ? [m.emissive.r * m.emissiveIntensity, m.emissive.g * m.emissiveIntensity, m.emissive.b * m.emissiveIntensity] as [number, number, number] : [0, 0, 0] as [number, number, number]
const nm = new Matrix3().getNormalMatrix(object.matrixWorld)
const count = index ? index.count : pos.count
const vtx = (k: number): { p: Vector3; n: Vector3; c: [number, number, number] } => {
const i = index ? index.getX(k) : k
const p = new Vector3().fromBufferAttribute(pos, i).applyMatrix4(object.matrixWorld)
const n = nor ? new Vector3().fromBufferAttribute(nor, i).applyMatrix3(nm).normalize() : new Vector3(0, 1, 0)
const vc = col ? [col.getX(i), col.getY(i), col.getZ(i)] : [1, 1, 1]
return { p, n, c: [base.r * vc[0]!, base.g * vc[1]!, base.b * vc[2]!] }
}
for (let k = 0; k < count; k += 3) {
const a = vtx(k), b = vtx(k + 1), c = vtx(k + 2)
const tri: Tri = {
p: [a.p, b.p, c.p], n: [a.n, b.n, c.n], c: [a.c, b.c, c.c],
rough: m.roughness ?? 0.5, metal: m.metalness ?? 0, emissive: em,
coat: (m as unknown as { clearcoat?: number }).clearcoat ?? 0,
opacity: m.transparent ? m.opacity : 1,
}
;(m.transparent ? clear : opaque).push(tri)
}
})
return { opaque, clear }
}
const LIGHT = new Vector3(-0.5, 0.75, 0.45).normalize()
/**
* A photo-studio sky: bright soft horizon, darker zenith, a dark floor. What
* sells painted metal is the horizon line sweeping across the flanks, so the
* environment is mostly a gradient with a sharp step at the horizon.
*/
function environment(d: Vector3): [number, number, number] {
if (d.y >= 0) {
const t = Math.pow(d.y, 0.45)
const band = Math.exp(-d.y * 18) * 0.35
return [0.95 - 0.55 * t + band, 0.96 - 0.5 * t + band, 0.98 - 0.4 * t + band]
}
const t = Math.min(1, -d.y * 4)
return [0.2 - 0.12 * t, 0.2 - 0.12 * t, 0.21 - 0.12 * t]
}
function shade(n: Vector3, v: Vector3, c: readonly number[], tri: Tri): [number, number, number] {
const ndl = Math.max(0, n.dot(LIGHT))
const up = n.y * 0.5 + 0.5
const r = v.clone().negate().reflect(n)
const env = environment(r)
const ambient = environment(new Vector3(n.x * 0.3, Math.max(-0.2, n.y), n.z * 0.3).normalize())
const ndv = Math.max(0, n.dot(v))
const fres = 0.04 + 0.96 * Math.pow(1 - ndv, 5)
const h = LIGHT.clone().add(v).normalize()
const shin = 4 + (1 - tri.rough) ** 3 * 600
const spec = Math.pow(Math.max(0, n.dot(h)), shin) * (1 - tri.rough) ** 2 * 2.2
const gloss = Math.pow(1 - tri.rough, 2)
return [0, 1, 2].map((k) => {
const albedo = c[k]!
const diffuse = albedo * (1 - tri.metal) * (ndl * 1.25 + ambient[k]! * (0.35 + 0.35 * up))
const metal = albedo * tri.metal * (env[k]! * (0.35 + 0.65 * gloss) + spec)
const dielectric = (1 - tri.metal) * (fres * gloss * env[k]! + spec * 0.6)
const coat = tri.coat * fres * env[k]! * 0.9 + tri.coat * spec * 0.8
return diffuse + metal + dielectric + coat + tri.emissive[k]!
}) as [number, number, number]
}
export function render(
root: Object3D,
options: { width: number; height: number; direction?: Vector3; background?: [number, number, number]; fov?: number },
): Frame {
const W = options.width * 2
const H = options.height * 2
const { opaque, clear } = collect(root)
const box = new Box3().setFromObject(root)
const sphere = box.getBoundingSphere(new Sphere())
const fov = options.fov ?? 26
const camera = new PerspectiveCamera(fov, W / H, 0.05, 500)
// Three-quarter front from about head height: a camera looking down on a
// car from above is what makes it read as a toy.
const dir = (options.direction ?? new Vector3(0.95, 0.2, 1.0)).clone().normalize()
const fit = sphere.radius / Math.sin((Math.min(fov, fov * (W / H)) * Math.PI) / 360)
const target = box.getCenter(new Vector3())
camera.position.copy(target).addScaledVector(dir, fit * 0.74)
camera.lookAt(target)
camera.updateMatrixWorld(true)
camera.updateProjectionMatrix()
const bg = options.background ?? [0.93, 0.93, 0.92]
const rgb = new Float32Array(W * H * 3)
for (let y = 0; y < H; y += 1) {
const t = y / H
for (let x = 0; x < W; x += 1) {
const i = (y * W + x) * 3
rgb[i] = bg[0]; rgb[i + 1] = bg[1]; rgb[i + 2] = bg[2]
void t
}
}
const depth = new Float32Array(W * H).fill(Infinity)
// Contact shadow: darken the ground-plane footprint under the vehicle.
const floorY = box.min.y
const shadowTris = opaque
const project = (p: Vector3): [number, number, number] => {
const q = p.clone().project(camera)
return [(q.x * 0.5 + 0.5) * W, (1 - (q.y * 0.5 + 0.5)) * H, q.z]
}
const shadowMask = new Float32Array(W * H)
for (const tri of shadowTris) {
const pts = tri.p.map((p) => {
const h = Math.max(0, p.y - floorY)
return project(new Vector3(p.x + LIGHT.x * -h * 0.15, floorY, p.z + LIGHT.z * -h * 0.15))
})
fill(pts as [number, number, number][], W, H, (x, y) => {
shadowMask[y * W + x] = 1
})
}
// Blur the mask a little for a soft edge.
const soft = blur(shadowMask, W, H, Math.max(2, Math.round(W / 160)))
for (let i = 0; i < W * H; i += 1) {
const k = 1 - soft[i]! * 0.45
rgb[i * 3]! *= k; rgb[i * 3 + 1]! *= k; rgb[i * 3 + 2]! *= k
}
const draw = (tri: Tri, blend: boolean): void => {
const s = tri.p.map(project) as [number, number, number][]
const v = camera.position.clone().sub(tri.p[0]).normalize()
const faceN = tri.p[1].clone().sub(tri.p[0]).cross(tri.p[2].clone().sub(tri.p[0])).normalize()
if (!blend && faceN.dot(v) < 0) return
fill(s, W, H, (x, y, w0, w1, w2) => {
const z = s[0]![2] * w0 + s[1]![2] * w1 + s[2]![2] * w2
const di = y * W + x
if (z >= depth[di]!) return
const n = tri.n[0].clone().multiplyScalar(w0).add(tri.n[1].clone().multiplyScalar(w1)).add(tri.n[2].clone().multiplyScalar(w2)).normalize()
if (n.dot(v) < 0) n.negate()
const c = [0, 1, 2].map((k) => tri.c[0][k]! * w0 + tri.c[1][k]! * w1 + tri.c[2][k]! * w2)
const col = shade(n, v, c, tri)
const i = di * 3
if (blend) {
const a = tri.opacity
rgb[i] = rgb[i]! * (1 - a) + col[0] * a
rgb[i + 1] = rgb[i + 1]! * (1 - a) + col[1] * a
rgb[i + 2] = rgb[i + 2]! * (1 - a) + col[2] * a
} else {
depth[di] = z
rgb[i] = col[0]; rgb[i + 1] = col[1]; rgb[i + 2] = col[2]
}
})
}
for (const tri of opaque) draw(tri, false)
const far = (t: Tri): number => t.p[0].distanceToSquared(camera.position)
for (const tri of [...clear].sort((a, b) => far(b) - far(a))) draw(tri, true)
// Downsample 2× → 1×.
const out = new Float32Array(options.width * options.height * 3)
for (let y = 0; y < options.height; y += 1) {
for (let x = 0; x < options.width; x += 1) {
for (let k = 0; k < 3; k += 1) {
const a = rgb[((2 * y) * W + 2 * x) * 3 + k]!
const b = rgb[((2 * y) * W + 2 * x + 1) * 3 + k]!
const c = rgb[((2 * y + 1) * W + 2 * x) * 3 + k]!
const d = rgb[((2 * y + 1) * W + 2 * x + 1) * 3 + k]!
out[(y * options.width + x) * 3 + k] = (a + b + c + d) / 4
}
}
}
return { width: options.width, height: options.height, rgb: out }
}
function fill(
s: readonly [number, number, number][],
W: number,
H: number,
plot: (x: number, y: number, w0: number, w1: number, w2: number) => void,
): void {
const [a, b, c] = s as [[number, number, number], [number, number, number], [number, number, number]]
if (a[2] < -1 || b[2] < -1 || c[2] < -1) return
const minX = Math.max(0, Math.floor(Math.min(a[0], b[0], c[0])))
const maxX = Math.min(W - 1, Math.ceil(Math.max(a[0], b[0], c[0])))
const minY = Math.max(0, Math.floor(Math.min(a[1], b[1], c[1])))
const maxY = Math.min(H - 1, Math.ceil(Math.max(a[1], b[1], c[1])))
const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
if (Math.abs(area) < 1e-9) return
for (let y = minY; y <= maxY; y += 1) {
for (let x = minX; x <= maxX; x += 1) {
const px = x + 0.5, py = y + 0.5
const w0 = ((b[0] - px) * (c[1] - py) - (b[1] - py) * (c[0] - px)) / area
const w1 = ((c[0] - px) * (a[1] - py) - (c[1] - py) * (a[0] - px)) / area
const w2 = 1 - w0 - w1
if (w0 < 0 || w1 < 0 || w2 < 0) continue
plot(x, y, w0, w1, w2)
}
}
}
function blur(src: Float32Array, W: number, H: number, r: number): Float32Array {
const tmp = new Float32Array(W * H)
const out = new Float32Array(W * H)
for (let y = 0; y < H; y += 1) {
let acc = 0
for (let x = -r; x < W + r; x += 1) {
acc += src[y * W + Math.min(W - 1, Math.max(0, x + r))]! - src[y * W + Math.min(W - 1, Math.max(0, x - r - 1))]!
if (x >= 0 && x < W) tmp[y * W + x] = acc / (2 * r + 1)
}
}
for (let x = 0; x < W; x += 1) {
let acc = 0
for (let y = -r; y < H + r; y += 1) {
acc += tmp[Math.min(H - 1, Math.max(0, y + r)) * W + x]! - tmp[Math.min(H - 1, Math.max(0, y - r - 1)) * W + x]!
if (y >= 0 && y < H) out[y * W + x] = acc / (2 * r + 1)
}
}
return out
}
/** Places frames on a grid. */
export function tile(frames: readonly Frame[], columns: number, background: [number, number, number] = [0.93, 0.93, 0.92]): Frame {
const w = frames[0]!.width
const h = frames[0]!.height
const rows = Math.ceil(frames.length / columns)
const W = w * columns
const H = h * rows
const rgb = new Float32Array(W * H * 3)
for (let i = 0; i < W * H; i += 1) { rgb[i * 3] = background[0]; rgb[i * 3 + 1] = background[1]; rgb[i * 3 + 2] = background[2] }
frames.forEach((f, n) => {
const ox = (n % columns) * w
const oy = Math.floor(n / columns) * h
for (let y = 0; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
for (let k = 0; k < 3; k += 1) rgb[((oy + y) * W + ox + x) * 3 + k] = f.rgb[(y * w + x) * 3 + k]!
}
}
})
return { width: W, height: H, rgb }
}
/* --------------------------------------------------------------------- PNG */
const CRC = new Uint32Array(256).map((_, n) => {
let c = n
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
return c >>> 0
})
export function crc32(bytes: Uint8Array): number {
let c = 0xffffffff
for (const b of bytes) c = CRC[(c ^ b) & 255]! ^ (c >>> 8)
return (c ^ 0xffffffff) >>> 0
}
function chunk(type: string, data: Uint8Array): Uint8Array {
const out = new Uint8Array(12 + data.length)
const view = new DataView(out.buffer)
view.setUint32(0, data.length)
for (let i = 0; i < 4; i += 1) out[4 + i] = type.charCodeAt(i)
out.set(data, 8)
view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)))
return out
}
/** Linear light → ACES filmic (Narkowicz fit) → sRGB 8-bit. */
function encode(v: number): number {
const x = v * 0.8
const t = Math.min(1, Math.max(0, (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)))
const s = t <= 0.0031308 ? 12.92 * t : 1.055 * Math.pow(t, 1 / 2.4) - 0.055
return Math.round(Math.min(1, Math.max(0, s)) * 255)
}
/** PNG; with `alpha` (0..1 per pixel) it is written as RGBA. */
export function encodePng(frame: Frame, alpha?: Float32Array): Uint8Array {
const { width, height, rgb } = frame
const channels = alpha ? 4 : 3
const stride = width * channels + 1
const raw = new Uint8Array(stride * height)
for (let y = 0; y < height; y += 1) {
raw[y * stride] = 0
for (let x = 0; x < width; x += 1) {
const o = y * stride + 1 + x * channels
for (let k = 0; k < 3; k += 1) raw[o + k] = encode(rgb[(y * width + x) * 3 + k]!)
if (alpha) raw[o + 3] = Math.round(Math.min(1, Math.max(0, alpha[y * width + x]!)) * 255)
}
}
const header = new Uint8Array(13)
const view = new DataView(header.buffer)
view.setUint32(0, width)
view.setUint32(4, height)
header[8] = 8
header[9] = alpha ? 6 : 2
const signature = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
const parts = [signature, chunk('IHDR', header), chunk('IDAT', deflateSync(raw, { level: 9 })), chunk('IEND', new Uint8Array())]
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
let o = 0
for (const p of parts) { out.set(p, o); o += p.length }
return out
}

78
scripts/render.ts Normal file
View file

@ -0,0 +1,78 @@
/**
* Offline renders, no browser.
*
* bun scripts/render.ts contact sheet of every body style
* bun scripts/render.ts --style pickup one style, large
* bun scripts/render.ts --random 12 a sheet of random vehicles
* bun scripts/render.ts --lods sedan LOD0 / LOD1 / LOD2 side by side
* bun scripts/render.ts --rig hatchback doors, bonnet and boot open, wheels steered
* bun scripts/render.ts --out media write into media/ instead of renders/
*/
import { mkdir, writeFile } from 'node:fs/promises'
import {
BODY_STYLES,
type BodyStyle,
generateVehicle,
type LodLevel,
preset,
randomSpec,
type VehicleSpec,
} from '../src/generator/index.ts'
import { encodePng, render, tile, type Frame } from './raster.ts'
const args = process.argv.slice(2)
const flag = (name: string): string | undefined => {
const at = args.indexOf(`--${name}`)
return at >= 0 ? args[at + 1] : undefined
}
const outDir = flag('out') ?? 'renders'
const size = Number(flag('size') ?? 360)
await mkdir(outDir, { recursive: true })
function shot(spec: VehicleSpec, level: LodLevel = 0, pose?: (v: ReturnType<typeof generateVehicle>) => void, w = size, h = Math.round(size * 0.62)): Frame {
const vehicle = generateVehicle(spec, { lods: [level] })
pose?.(vehicle)
const frame = render(vehicle.lods[0]!.group, { width: w, height: h })
vehicle.dispose()
return frame
}
const style = flag('style') as BodyStyle | undefined
const lods = flag('lods') as BodyStyle | undefined
const rig = flag('rig') as BodyStyle | undefined
const random = flag('random')
if (style) {
await writeFile(`${outDir}/${style}.png`, encodePng(shot(preset(style), 0, undefined, 1200, 720)))
console.log(`${style} → ${outDir}/${style}.png`)
} else if (lods) {
const frames = ([0, 1, 2] as const).map((level) => shot(preset(lods), level))
await writeFile(`${outDir}/lods.png`, encodePng(tile(frames, 3)))
console.log(`${lods} LOD0/1/2 → ${outDir}/lods.png`)
} else if (rig) {
const frame = shot(preset(rig), 0, (v) => {
for (const part of v.rig.openables) v.rig.open(part, 1)
v.rig.setSteer(0.45)
v.rig.setHeadlights(true)
v.rig.setBrake(true)
}, 1200, 720)
await writeFile(`${outDir}/rig.png`, encodePng(frame))
console.log(`${rig} rigged → ${outDir}/rig.png`)
} else if (random) {
const count = Number(random)
const frames: Frame[] = []
for (let k = 0; k < count; k += 1) frames.push(shot(randomSpec(1000 + k)))
await writeFile(`${outDir}/random.png`, encodePng(tile(frames, 4)))
console.log(`${count} random vehicles → ${outDir}/random.png`)
} else {
const frames: Frame[] = []
for (const s of BODY_STYLES) {
frames.push(shot(preset(s)))
console.log(` ${s}`)
}
const sheet = tile(frames, 4)
await writeFile(`${outDir}/styles.png`, encodePng(sheet))
console.log(`${frames.length} styles → ${outDir}/styles.png (${sheet.width}×${sheet.height})`)
}

151
scripts/verify-glb.ts Normal file
View file

@ -0,0 +1,151 @@
/**
* GLB round trip: export every body style, load it back, and check that what
* a game needs survived — not just that a file was written.
*
* - the same meshes, triangles and vertex colours;
* - every rigged node by name, at the same pivot;
* - `createRig()` on the LOADED scene finds the same wheels and openables and
* moves them to the same place as the rig of the generated vehicle;
* - the animation clips, by name, and that they target nodes that exist.
*
* bun scripts/verify-glb.ts
*/
import './glb-node.ts'
import { Box3, Mesh, type Object3D, Vector3 } from 'three'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
import {
BODY_STYLES,
createRig,
exportVehicleGlb,
generateVehicle,
type OpenablePart,
preset,
randomSpec,
type VehicleSpec,
} from '../src/generator/index.ts'
const failures: string[] = []
let checks = 0
function expect(label: string, ok: boolean, detail = ''): void {
checks += 1
if (!ok) {
failures.push(label)
console.log(` FAIL ${label}${detail ? ` — ${detail}` : ''}`)
}
}
interface Summary { meshes: number; triangles: number; colours: number; names: Set<string> }
function summarise(root: Object3D): Summary {
let meshes = 0, triangles = 0, colours = 0
const names = new Set<string>()
root.traverse((o) => {
names.add(o.name)
if (!(o instanceof Mesh)) return
meshes += 1
const index = o.geometry.getIndex()
triangles += (index ? index.count : o.geometry.getAttribute('position').count) / 3
if (o.geometry.getAttribute('color')) colours += 1
})
return { meshes, triangles, colours, names }
}
const find = (root: Object3D, name: string): Object3D | undefined => {
let hit: Object3D | undefined
root.traverse((o) => { if (!hit && o.name === name) hit = o })
return hit
}
const worldBox = (node: Object3D): Box3 => {
node.updateWorldMatrix(true, true)
return new Box3().setFromObject(node)
}
const loader = new GLTFLoader()
let totalBytes = 0
const cases: [string, VehicleSpec][] = [
...BODY_STYLES.map((s) => [s, preset(s)] as [string, VehicleSpec]),
['random 42', randomSpec(42)],
['random 314', randomSpec(314)],
]
for (const [label, spec] of cases) {
const vehicle = generateVehicle(spec, { lods: [0] })
const source = vehicle.lods[0]!.group
const buffer = await exportVehicleGlb(vehicle)
totalBytes += buffer.byteLength
const header = new DataView(buffer)
expect(`${label}: GLB magic and version`, header.getUint32(0, true) === 0x46546c67 && header.getUint32(4, true) === 2)
const gltf = await loader.parseAsync(buffer, '')
const loaded = gltf.scene
const a = summarise(source)
const b = summarise(loaded)
expect(`${label}: mesh count preserved`, a.meshes === b.meshes, `${a.meshes} → ${b.meshes}`)
expect(`${label}: triangle count preserved`, a.triangles === b.triangles, `${a.triangles} → ${b.triangles}`)
expect(`${label}: vertex colours preserved`, a.colours === b.colours)
const missing = [...a.names].filter((n) => n && !b.names.has(n))
expect(`${label}: every node name survives`, missing.length === 0, missing.slice(0, 5).join(', '))
// Pivots: every rigged node at the same place.
let drift = 0
source.updateMatrixWorld(true)
loaded.updateMatrixWorld(true)
source.traverse((o) => {
if (!o.userData.vehicleGenerator) return
const twin = find(loaded, o.name)
if (!twin) { drift = Infinity; return }
drift = Math.max(drift, o.getWorldPosition(new Vector3()).distanceTo(twin.getWorldPosition(new Vector3())))
})
expect(`${label}: pivots in place after import`, drift < 1e-4, `${drift}`)
// The rig, rebuilt from the imported file alone.
const rigA = vehicle.rig
const rigB = createRig(loaded)
expect(`${label}: imported rig finds the wheels`, rigB.wheels.length === 4 && rigB.wheels.filter((w) => w.steer).length === 2)
expect(`${label}: imported rig finds the openables`,
[...rigA.openables].sort().join() === [...rigB.openables].sort().join(),
`${rigA.openables.join()} vs ${rigB.openables.join()}`)
for (const part of rigA.openables as OpenablePart[]) {
rigA.open(part, 0.8)
rigB.open(part, 0.8)
const na = find(source, part)!
const nb = find(loaded, part)!
const ba = worldBox(na)
const bb = worldBox(nb)
const d = ba.min.distanceTo(bb.min) + ba.max.distanceTo(bb.max)
expect(`${label}: ${part} opens the same after import`, d < 2e-3, `${d.toFixed(5)}`)
rigA.open(part, 0)
rigB.open(part, 0)
}
rigA.setSteer(-0.35)
rigB.setSteer(-0.35)
rigA.setWheelSpin(1.2)
rigB.setWheelSpin(1.2)
for (const id of ['FL', 'FR', 'RL', 'RR']) {
const ba = worldBox(find(source, `wheel_${id}`)!)
const bb = worldBox(find(loaded, `wheel_${id}`)!)
const d = ba.min.distanceTo(bb.min) + ba.max.distanceTo(bb.max)
expect(`${label}: wheel ${id} steers and rolls the same after import`, d < 2e-3, `${d.toFixed(5)}`)
}
const steerA = find(source, 'steering_wheel')
const steerB = find(loaded, 'steering_wheel')
if (steerA) expect(`${label}: steering wheel turns after import`, steerB !== undefined && Math.abs(steerA.quaternion.angleTo(steerB.quaternion)) < 1e-4)
// Animation clips survive by name and target real nodes.
const clipsA = vehicle.animations.map((c) => c.name).sort()
const clipsB = gltf.animations.map((c) => c.name).sort()
expect(`${label}: animation clips survive`, clipsA.join() === clipsB.join(), `${clipsA.length} → ${clipsB.length}`)
const dangling = gltf.animations.flatMap((c) => c.tracks.map((t) => t.name.split('.')[0]!)).filter((n) => !find(loaded, n))
expect(`${label}: every track targets a node`, dangling.length === 0, dangling.slice(0, 3).join())
vehicle.dispose()
}
console.log(`${cases.length} vehicles exported and re-imported · ${(totalBytes / 1024 / 1024).toFixed(1)} MB of GLB`)
console.log(`${checks} checks · ${failures.length} failed`)
console.log(failures.length === 0 ? 'All checks passed.' : 'Checks FAILED.')
if (failures.length > 0) process.exitCode = 1

409
scripts/verify.ts Normal file
View file

@ -0,0 +1,409 @@
/**
* The generator's conformance gate. Headless, no GPU.
*
* Runs every body style and a spread of random seeds through the generator
* and checks what a game relies on: finite geometry, triangle budgets per
* LOD, wheels on the ground, a rig whose hinges stay put, determinism,
* blendability, every mod on every kind of body, a collider that encloses
* the car, and a dispose that can be called twice.
*
* bun scripts/verify.ts
*/
import { Box3, Mesh, type Object3D, Vector3 } from 'three'
import {
BODY_STYLES,
blendSpecs,
generateVehicle,
MOD_KINDS,
MODS,
preset,
randomSpec,
type Vehicle,
type VehicleSpec,
} from '../src/generator/index.ts'
import { normalizeSpec, parseLibrary, toLibraryFile } from '../src/library/format.ts'
import { addEntry, createLibrary, duplicateEntry, moveEntry, removeEntry, renameEntry } from '../src/library/store.ts'
import { zip } from '../src/library/zip.ts'
const failures: string[] = []
let checks = 0
function expect(label: string, ok: boolean, detail = ''): void {
checks += 1
if (!ok) {
failures.push(label)
console.log(` FAIL ${label}${detail ? ` — ${detail}` : ''}`)
}
}
// Stock vehicles stay under 60k triangles on LOD0; mods may add up to 6k on top.
const BUDGET = { lod0: [15000, 60000], lod0Modded: 66000, lod1Ratio: 0.55, lod2Ratio: 0.5, lod2Max: 7000, drawCalls: 72, ms: 2000 } as const
function fingerprint(root: Object3D): string {
let hash = 2166136261
root.updateMatrixWorld(true)
root.traverse((o) => {
if (!(o instanceof Mesh)) return
for (const c of o.name) { hash ^= c.charCodeAt(0); hash = Math.imul(hash, 16777619) }
for (const name of ['position', 'normal', 'color'] as const) {
const a = o.geometry.getAttribute(name)?.array as ArrayLike<number> | undefined
if (!a) continue
for (let i = 0; i < a.length; i += 1) {
hash ^= Math.round(a[i]! * 1e5) | 0
hash = Math.imul(hash, 16777619)
}
}
})
return (hash >>> 0).toString(16)
}
function meshBox(root: Object3D, filter: (m: Mesh) => boolean): Box3 {
const box = new Box3()
root.updateMatrixWorld(true)
root.traverse((o) => { if (o instanceof Mesh && filter(o)) box.expandByObject(o) })
return box
}
function findNode(root: Object3D, name: string): Object3D | undefined {
let hit: Object3D | undefined
root.traverse((o) => { if (!hit && o.name === name) hit = o })
return hit
}
function checkVehicle(label: string, spec: VehicleSpec): Vehicle {
const t0 = performance.now()
const v = generateVehicle(spec)
const ms = performance.now() - t0
expect(`${label}: generated in < ${BUDGET.ms} ms`, ms < BUDGET.ms, `${ms.toFixed(0)} ms`)
expect(`${label}: three LODs`, v.lods.length === 3)
// --- geometry validity
let bad = 0
let badNormals = 0
let emptyMeshes = 0
v.group.traverse((o) => {
if (!(o instanceof Mesh)) return
const p = o.geometry.getAttribute('position').array as ArrayLike<number>
const n = o.geometry.getAttribute('normal').array as ArrayLike<number>
if (p.length === 0) emptyMeshes += 1
for (let i = 0; i < p.length; i += 1) if (!Number.isFinite(p[i]!)) bad += 1
for (let i = 0; i < n.length; i += 3) {
const l = Math.hypot(n[i]!, n[i + 1]!, n[i + 2]!)
if (!Number.isFinite(l) || Math.abs(l - 1) > 1e-3) badNormals += 1
}
const index = o.geometry.getIndex()
if (index) {
const count = o.geometry.getAttribute('position').count
for (let i = 0; i < index.count; i += 1) if (index.getX(i) >= count) bad += 1
}
})
expect(`${label}: finite positions, valid indices`, bad === 0, `${bad} bad values`)
expect(`${label}: unit normals`, badNormals === 0, `${badNormals} bad normals`)
expect(`${label}: no empty meshes`, emptyMeshes === 0)
// --- budgets
const [l0, l1, l2] = v.lods
const cap = spec.mods.some((m) => m.kind !== 'rollCage') ? BUDGET.lod0Modded : BUDGET.lod0[1]
expect(`${label}: LOD0 within ${BUDGET.lod0[0]}–${cap} triangles`, l0!.triangles >= BUDGET.lod0[0] && l0!.triangles <= cap, `${l0!.triangles}`)
expect(`${label}: LOD1 ≤ ${BUDGET.lod1Ratio} × LOD0`, l1!.triangles <= l0!.triangles * BUDGET.lod1Ratio, `${l1!.triangles} vs ${l0!.triangles}`)
expect(`${label}: LOD2 ≤ ${BUDGET.lod2Ratio} × LOD1 and ≤ ${BUDGET.lod2Max}`, l2!.triangles <= l1!.triangles * BUDGET.lod2Ratio && l2!.triangles <= BUDGET.lod2Max, `${l2!.triangles}`)
expect(`${label}: ≤ ${BUDGET.drawCalls} draw calls on LOD0`, l0!.meshes <= BUDGET.drawCalls, `${l0!.meshes}`)
// --- names are unique inside one LOD (glTF addresses animations by name)
for (const level of v.lods) {
const names = new Map<string, number>()
level.group.traverse((o) => names.set(o.name, (names.get(o.name) ?? 0) + 1))
const dup = [...names].filter(([n, c]) => n && c > 1).map(([n]) => n)
expect(`${label}: unique node names in LOD${level.level}`, dup.length === 0, dup.slice(0, 4).join(', '))
}
// --- wheels
const lod0 = l0!.group
expect(`${label}: four wheels`, v.wheels.length === 4 && v.rig.wheels.length === 4)
expect(`${label}: only the front wheels steer`, v.wheels.every((w) => w.steer === (w.axle === 'front')))
expect(`${label}: at least one axle driven`, v.wheels.some((w) => w.drive))
for (const w of v.wheels) {
const tyre = meshBox(lod0, (m) => m.name === `wheel_${w.id}_tyre`)
expect(`${label}: ${w.id} tyre on the ground`, Math.abs(tyre.min.y) < 0.012, `min y ${tyre.min.y.toFixed(4)}`)
}
const body = meshBox(lod0, (m) => !m.name.startsWith('wheel_') && !m.name.startsWith('mod_'))
expect(`${label}: body clears the ground`, body.min.y > 0.02, `min y ${body.min.y.toFixed(3)}`)
// --- rig: every opening panel swings about a hinge that stays put
for (const part of v.rig.openables) {
const node = findNode(lod0, part)
expect(`${label}: ${part} node exists`, node !== undefined)
if (!node) continue
const pivot = node.getWorldPosition(new Vector3())
const before = meshBox(node, () => true)
v.rig.open(part, 1)
const after = meshBox(node, () => true)
const moved = before.min.distanceTo(after.min) + before.max.distanceTo(after.max)
expect(`${label}: ${part} opens`, moved > 0.05, `moved ${moved.toFixed(3)}`)
const pivotAfter = node.getWorldPosition(new Vector3())
expect(`${label}: ${part} hinge stays put`, pivot.distanceTo(pivotAfter) < 1e-9)
expect(`${label}: ${part} hinge lies on the panel`, after.distanceToPoint(pivot) < 0.08, `${after.distanceToPoint(pivot).toFixed(3)} m`)
v.rig.open(part, 0)
const closed = meshBox(node, () => true)
expect(`${label}: ${part} closes exactly`, closed.min.distanceTo(before.min) + closed.max.distanceTo(before.max) < 1e-6)
}
const expectedDoors = spec.body.doors * 2
const doors = v.rig.openables.filter((p) => p.startsWith('door')).length
expect(`${label}: ${expectedDoors} doors rigged`, doors === expectedDoors || spec.style === 'buggy', `${doors}`)
// --- steering
const fl = findNode(lod0, 'wheel_FL')!
const rl = findNode(lod0, 'wheel_RL')!
const wheelNode = findNode(lod0, 'steering_wheel')
v.rig.setSteer(0.4)
expect(`${label}: front wheels steer`, Math.abs(fl.rotation.y) > 0.3)
expect(`${label}: rear wheels do not`, rl.rotation.y === 0)
const fr = findNode(lod0, 'wheel_FR')!
expect(`${label}: Ackermann — inner wheel turns more`, fl.rotation.y > fr.rotation.y, `${fl.rotation.y.toFixed(3)} / ${fr.rotation.y.toFixed(3)}`)
if (wheelNode) expect(`${label}: steering wheel turns`, Math.abs(wheelNode.rotation.z) > 1)
v.rig.setSteer(0)
v.rig.update(0.5, 10)
const spin = findNode(lod0, 'wheel_FL_spin')!
expect(`${label}: wheels roll with speed`, Math.abs(spin.rotation.x - (10 * 0.5) / v.wheels[0]!.radius) < 1e-9)
v.rig.setWheelSpin(0)
// Body roll: the sprung body leans, the wheels stay where they are.
{
const bodyNode = findNode(lod0, 'body')!
const tyres = meshBox(lod0, (m) => m.name.startsWith('wheel') && m.name.endsWith('_tyre'))
const before = meshBox(bodyNode, () => true)
v.rig.setBodyPose(0.05, 0.02)
const leaned = meshBox(bodyNode, () => true)
const tyresAfter = meshBox(lod0, (m) => m.name.startsWith('wheel') && m.name.endsWith('_tyre'))
expect(`${label}: body rolls`, leaned.min.distanceTo(before.min) > 0.005)
expect(`${label}: wheels stay planted while the body rolls`, tyres.min.distanceTo(tyresAfter.min) + tyres.max.distanceTo(tyresAfter.max) < 1e-9)
if (v.rig.openables.length) {
const part = v.rig.openables[0]!
v.rig.open(part, 1)
v.rig.open(part, 0)
}
v.rig.setBodyPose(0, 0)
const back = meshBox(bodyNode, () => true)
expect(`${label}: body pose resets exactly`, back.min.distanceTo(before.min) + back.max.distanceTo(before.max) < 1e-6)
}
// --- glass: present on every level, facing out of the cabin, no slivers
for (const level of v.lods) {
level.group.updateMatrixWorld(true)
const centre = new Vector3(0, (v.bounds.min.y + v.bounds.max.y) / 2, (v.bounds.min.z + v.bounds.max.z) / 2)
let glassTris = 0
let outward = 0
let total = 0
let slivers = 0
let tris = 0
const a = new Vector3(), b = new Vector3(), c = new Vector3(), n = new Vector3(), m = new Vector3()
level.group.traverse((o) => {
const mesh = o as Mesh
if (!mesh.isMesh) return
const pos = mesh.geometry.getAttribute('position')
const index = mesh.geometry.getIndex()
const count = index ? index.count : pos.count
const glass = mesh.name.includes('_glass')
for (let i = 0; i < count; i += 3) {
const at = (k: number): number => (index ? index.getX(i + k) : i + k)
a.fromBufferAttribute(pos, at(0)).applyMatrix4(mesh.matrixWorld)
b.fromBufferAttribute(pos, at(1)).applyMatrix4(mesh.matrixWorld)
c.fromBufferAttribute(pos, at(2)).applyMatrix4(mesh.matrixWorld)
n.subVectors(b, a).cross(m.subVectors(c, a))
const area = n.length() / 2
tris += 1
if (area < 1e-10) slivers += 1
if (!glass) continue
glassTris += 1
total += area
m.copy(a).add(b).add(c).divideScalar(3).sub(centre)
if (n.dot(m) > 0) outward += area
}
})
const lvl = `LOD${v.lods.indexOf(level)}`
if (spec.style !== 'buggy') {
expect(`${label}: ${lvl} has glass`, glassTris > 0, `${glassTris}`)
expect(`${label}: ${lvl} glass faces out of the cabin`, outward / Math.max(total, 1e-9) > 0.85, `${((100 * outward) / Math.max(total, 1e-9)).toFixed(1)} %`)
}
expect(`${label}: ${lvl} no degenerate triangles`, slivers / tris < 0.002, `${slivers} of ${tris}`)
}
if (spec.style !== 'buggy' && spec.style !== 'pickup' && spec.style !== 'truck') {
expect(`${label}: boot or tailgate opens`, v.rig.openables.includes('trunk'))
}
// A tailgate car (short deck) shows its rear glass at the back, on the
// roof slope or set into the gate; a van with a blank rear face fails.
if (spec.body.deck < 0.1 && spec.style !== 'buggy' && spec.style !== 'pickup' && spec.style !== 'truck' && v.rig.openables.includes('trunk')) {
const rearGlass = meshBox(lod0, (m) => m.name.includes('_glass'))
expect(`${label}: rear glass reaches the back`, rearGlass.min.z < v.bounds.min.z + 0.6, `${(rearGlass.min.z - v.bounds.min.z).toFixed(2)} m from the tail`)
}
// --- collider
const hull = v.collider.hull
const hullTris = hull.getAttribute('position').count / 3
expect(`${label}: collider hull has 20–2000 triangles`, hullTris >= 20 && hullTris <= 2000, `${hullTris}`)
hull.computeBoundingBox()
const hb = hull.boundingBox!
// Against the level the hull is built from: mirrors and other LOD0 details
// are deliberately not part of a collision shape.
const coarse = meshBox(l2!.group, (m) => !m.name.startsWith('wheel_') && !m.name.startsWith('mod_'))
const bodySize = coarse.getSize(new Vector3())
const hullSize = hb.getSize(new Vector3())
expect(`${label}: hull encloses ≥ 90 % of the body extent`,
hullSize.x >= bodySize.x * 0.9 && hullSize.y >= bodySize.y * 0.8 && hullSize.z >= bodySize.z * 0.9,
`${hullSize.toArray().map((n) => n.toFixed(2))} vs ${bodySize.toArray().map((n) => n.toFixed(2))}`)
let volume = 0
const hp = hull.getAttribute('position')
for (let i = 0; i < hp.count; i += 3) {
const a = new Vector3().fromBufferAttribute(hp, i)
const b = new Vector3().fromBufferAttribute(hp, i + 1)
const c = new Vector3().fromBufferAttribute(hp, i + 2)
volume += a.dot(b.cross(c)) / 6
}
expect(`${label}: hull wound outward`, volume > 0, `${volume.toFixed(3)}`)
expect(`${label}: box colliders`, v.collider.boxes.length >= 1)
expect(`${label}: animation clip per opening panel`, v.animations.filter((a) => a.name.startsWith('open_')).length === v.rig.openables.length)
return v
}
// --- every body style
console.log('body styles')
const sheet: { style: string; lod: number[] }[] = []
for (const style of BODY_STYLES) {
const v = checkVehicle(style, preset(style))
sheet.push({ style, lod: v.lods.map((l) => l.triangles) })
v.dispose()
v.dispose()
}
// --- random vehicles
console.log('random seeds')
for (let seed = 1; seed <= 26; seed += 1) {
const v = checkVehicle(`seed ${seed} (${randomSpec(seed).style})`, randomSpec(seed))
v.dispose()
}
// --- determinism
console.log('determinism')
for (const seed of [3, 77, 4096]) {
const a = generateVehicle(randomSpec(seed))
const b = generateVehicle(randomSpec(seed))
const c = generateVehicle(randomSpec(seed + 1))
expect(`seed ${seed}: same seed, same bytes`, fingerprint(a.group) === fingerprint(b.group))
expect(`seed ${seed}: next seed differs`, fingerprint(a.group) !== fingerprint(c.group))
a.dispose(); b.dispose(); c.dispose()
}
// --- blending
console.log('blending')
{
const a = preset('hatchback')
const b = preset('suv')
const at0 = generateVehicle(blendSpecs(a, b, 0))
const pure = generateVehicle(a)
expect('blend t=0 is the first spec', fingerprint(at0.group) === fingerprint(pure.group))
at0.dispose(); pure.dispose()
for (const t of [0.25, 0.5, 0.75]) {
const v = checkVehicle(`hatchback→suv ${t}`, blendSpecs(a, b, t))
v.dispose()
}
}
// --- every mod on every style
console.log('mods')
for (const style of BODY_STYLES) {
const base = preset(style)
const plain = generateVehicle(base, { lods: [0] })
const plainTris = plain.lods[0]!.triangles
plain.dispose()
for (const kind of MOD_KINDS) {
const spec: VehicleSpec = { ...base, mods: [...base.mods.filter((m) => m.kind !== kind), { kind }] }
let v: Vehicle | undefined
try {
v = generateVehicle(spec, { lods: [0] })
} catch (error) {
expect(`${style} + ${kind}: builds`, false, String(error))
continue
}
const def = MODS[kind]
if (def.build && !base.mods.some((m) => m.kind === kind)) {
const node = findNode(v.lods[0]!.group, `mod_${kind}`)
// Some mods skip bodies they do not fit (a roof rack on a buggy, a scoop without a bonnet).
const optional = (kind === 'roofRack' && style === 'buggy') || (kind === 'hoodScoop' && v.rig.openables.indexOf('hood') < 0)
|| (kind === 'widebody')
if (!optional) expect(`${style} + ${kind}: node mod_${kind}`, node !== undefined)
}
if (def.modifySpec) {
expect(`${style} + ${kind}: spec modified`, JSON.stringify(v.spec) !== JSON.stringify(generateVehicle(base, { lods: [2] }).spec))
}
let nan = 0
v.group.traverse((o) => {
if (!(o instanceof Mesh)) return
const a = o.geometry.getAttribute('position').array as ArrayLike<number>
for (let i = 0; i < a.length; i += 1) if (!Number.isFinite(a[i]!)) nan += 1
})
expect(`${style} + ${kind}: finite`, nan === 0)
expect(`${style} + ${kind}: within LOD0 budget`, v.lods[0]!.triangles <= BUDGET.lod0Modded, `${v.lods[0]!.triangles} (plain ${plainTris})`)
v.dispose()
}
// Everything at once.
const all: VehicleSpec = { ...base, mods: MOD_KINDS.map((kind) => ({ kind })) }
const v = generateVehicle(all, { lods: [0] })
expect(`${style}: all ${MOD_KINDS.length} mods at once, within budget`, v.lods[0]!.triangles <= BUDGET.lod0Modded && v.group.children.length > 0, `${v.lods[0]!.triangles}`)
v.dispose()
}
// --- libraries
console.log('library')
{
let lib = createLibrary('Test garage')
;[lib] = addEntry(lib, 'Daily', preset('hatchback'))
;[lib] = addEntry(lib, 'Daily', preset('suv'))
expect('library: duplicate names made unique', lib.entries[1]!.name === 'Daily copy', lib.entries[1]!.name)
const [dup, copy] = duplicateEntry(lib, lib.entries[0]!.id)
lib = dup
expect('library: duplicate inserted after its source', lib.entries[1]?.id === copy?.id && lib.entries.length === 3)
lib = renameEntry(lib, lib.entries[0]!.id, ' Weekend ')
expect('library: rename trims', lib.entries[0]!.name === 'Weekend')
lib = renameEntry(lib, lib.entries[1]!.id, 'Weekend')
expect('library: rename cannot collide', lib.entries[1]!.name === 'Weekend copy', lib.entries[1]!.name)
lib = moveEntry(lib, lib.entries[2]!.id, 0)
expect('library: move', lib.entries[0]!.spec.style === 'suv')
lib = removeEntry(lib, lib.entries[0]!.id)
expect('library: remove', lib.entries.length === 2 && lib.entries.every((e) => e.spec.style === 'hatchback'))
const back = parseLibrary(JSON.parse(JSON.stringify(toLibraryFile(lib))))
expect('library: JSON round trip keeps names and specs',
back.name === lib.name && back.entries.map((e) => e.name).join() === lib.entries.map((e) => e.name).join()
&& JSON.stringify(back.entries.map((e) => e.spec)) === JSON.stringify(lib.entries.map((e) => e.spec)))
const partial = normalizeSpec({ style: 'pickup', body: { length: 5.6 }, mods: [{ kind: 'bullBar' }, { kind: 'nonsense' }] })
expect('library: partial spec completed from its preset', partial.body.length === 5.6 && partial.body.bed !== null && partial.mods.length === 1)
let threw = false
try { parseLibrary({ format: 'something-else', entries: [] }) } catch { threw = true }
expect('library: foreign file rejected', threw)
const archive = zip([{ name: 'a.glb', data: new Uint8Array([1, 2, 3]) }, { name: 'b.glb', data: new Uint8Array(10) }])
const view = new DataView(archive.buffer)
const end = archive.length - 22
expect('zip: headers and directory', view.getUint32(0, true) === 0x04034b50 && view.getUint32(end, true) === 0x06054b50 && view.getUint16(end + 10, true) === 2)
}
// Livery: every pattern paints stripes on every style, lofted or authored.
for (const style of BODY_STYLES) {
for (const livery of ['stripes', 'side-stripe', 'rally'] as const) {
const base = preset(style)
const v = generateVehicle({ ...base, paint: { ...base.paint, livery } }, { lods: [0] })
let stripeTris = 0
v.group.traverse((o: Object3D) => {
if (!(o instanceof Mesh) || !String((o.material as { name?: string }).name).includes('stripe')) return
const g = o.geometry
stripeTris += (g.index ? g.index.count : g.getAttribute('position').count) / 3
})
v.dispose()
expect(`${style}: ${livery} livery painted`, stripeTris > 0, `${stripeTris} stripe triangles`)
}
}
console.log('\nLOD triangles per style')
for (const row of sheet) console.log(` ${row.style.padEnd(10)} ${row.lod.map((n) => String(n).padStart(6)).join(' ')}`)
console.log(`\n${checks} checks · ${failures.length} failed`)
console.log(failures.length === 0 ? 'All checks passed.' : 'Checks FAILED.')
if (failures.length > 0) process.exitCode = 1

2
src-tauri/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target/
/gen/schemas

4931
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

33
src-tauri/Cargo.toml Normal file
View file

@ -0,0 +1,33 @@
[package]
name = "vehicle-generator"
version = "0.1.0"
description = "Vehicle Generator — procedural vehicle generator"
authors = ["CRTkafa"]
license = "MIT"
repository = "https://git.crt.fyi/CRT/vehicle-generator"
edition = "2021"
rust-version = "1.77.2"
[lib]
name = "vehicle_generator_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
log = "0.4"
tauri = { version = "2", features = [] }
tauri-plugin-log = "2"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-single-instance = "2"
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true

3
src-tauri/build.rs Normal file
View file

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View file

@ -0,0 +1,18 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Window chrome for the frameless studio window.",
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-close",
"core:window:allow-show",
"core:window:allow-set-focus",
"core:window:allow-set-fullscreen",
"core:window:allow-is-fullscreen",
"core:window:allow-is-maximized"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 KiB

49
src-tauri/src/lib.rs Normal file
View file

@ -0,0 +1,49 @@
//! Vehicle Generator, the desktop shell.
//!
//! The studio is the same web app that runs in a browser; this crate only gives it a window.
//! The window is frameless (`decorations: false`) and the page draws its own title bar: the
//! studio's menubar doubles as the drag region and carries the caption buttons
//! (src/app/windowbar.ts). macOS keeps its native traffic lights over an overlay title bar.
#[cfg(desktop)]
mod window_mode;
#[cfg(desktop)]
use tauri::Manager;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let builder = tauri::Builder::default();
// First plugin: a second launch focuses the running studio instead of opening another.
#[cfg(desktop)]
let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(window) = app.get_webview_window(window_mode::MAIN) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}));
builder
.invoke_handler(tauri::generate_handler![vehicle_generator_quit])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(tauri_plugin_log::Builder::default().level(log::LevelFilter::Info).build())?;
}
// `main` is `"create": false` in the config so it is built in one place, sized to the
// monitor it opens on.
#[cfg(desktop)]
window_mode::create_main(app.handle())?;
#[cfg(mobile)]
if let Some(config) = app.config().app.windows.first().cloned() {
tauri::WebviewWindowBuilder::from_config(app.handle(), &config)?.build()?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running Vehicle Generator");
}
/// Quits for real, from the page's File menu.
#[tauri::command]
fn vehicle_generator_quit(app: tauri::AppHandle) {
app.exit(0);
}

6
src-tauri/src/main.rs Normal file
View file

@ -0,0 +1,6 @@
// Prevents an additional console window on Windows in release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
vehicle_generator_lib::run();
}

View file

@ -0,0 +1,124 @@
//! The main window: built hidden, sized to the monitor it opens on, then shown — so it never
//! flashes at the config size first, and a monitor with different display scaling is not guessed
//! at. A fixed 1440x900 is too big for a laptop and small on a wide monitor.
use tauri::{AppHandle, Monitor, PhysicalPosition, PhysicalSize, Runtime, WebviewWindow, WebviewWindowBuilder};
pub const MAIN: &str = "main";
/// The share of the work area (the monitor minus the taskbar) the window takes.
const SHARE: f64 = 0.8;
/// The studio's shape, 16:10.
const ASPECT: f64 = 1.6;
/// The smallest the window opens at, in logical pixels, where the screen has room for it.
const OPEN_MIN: (f64, f64) = (1024.0, 640.0);
/// The smallest it can be resized to, and at most 90% of the work area.
const RESIZE_MIN: (f64, f64) = (960.0, 620.0);
/// Where a monitor's usable area is, in physical pixels, and its display scaling.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WorkArea { pub x: i32, pub y: i32, pub width: u32, pub height: u32, pub scale: f64 }
/// The window's opening size and position and its resize floor, all in physical pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WindowBounds { pub x: i32, pub y: i32, pub width: u32, pub height: u32, pub min_width: u32, pub min_height: u32 }
/// The largest 16:10 box within 80% of the work area, never smaller than 1024x640 logical pixels
/// unless the work area itself is, never larger than it, centred. Worked in logical pixels so
/// 125% and 150% display scaling give the same proportion of the screen as 100%.
pub fn window_bounds(area: WorkArea) -> WindowBounds {
let scale = if area.scale.is_finite() && area.scale > 0.0 { area.scale } else { 1.0 };
let (available_w, available_h) = (area.width as f64 / scale, area.height as f64 / scale);
let width = (available_w * SHARE).min(available_h * SHARE * ASPECT);
let height = width / ASPECT;
let width = width.max(OPEN_MIN.0).min(available_w);
let height = height.max(OPEN_MIN.1).min(available_h);
let physical = |logical: f64, limit: u32| ((logical * scale).round() as u32).min(limit);
let (width_px, height_px) = (physical(width, area.width), physical(height, area.height));
WindowBounds {
x: area.x + ((area.width - width_px) / 2) as i32,
y: area.y + ((area.height - height_px) / 2) as i32,
width: width_px,
height: height_px,
min_width: physical(RESIZE_MIN.0.min(available_w * 0.9), width_px),
min_height: physical(RESIZE_MIN.1.min(available_h * 0.9), height_px),
}
}
/// The monitor under the pointer (where the studio was just launched from), else the primary.
fn launch_monitor<R: Runtime>(app: &AppHandle<R>) -> Option<Monitor> {
let under_cursor = app.cursor_position().ok().and_then(|at| app.monitor_from_point(at.x, at.y).ok().flatten());
under_cursor.or_else(|| app.primary_monitor().ok().flatten())
}
pub fn create_main<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<WebviewWindow<R>> {
let config = app.config().app.windows.iter().find(|window| window.label == MAIN).cloned().ok_or(tauri::Error::WindowNotFound)?;
let visible = config.visible;
let window = WebviewWindowBuilder::from_config(app, &config)?
.visible(false)
// The studio's own background, painted before the page loads, instead of WebView2's white.
.background_color(tauri::window::Color(12, 14, 17, 255))
.build()?;
// A monitor reporting no usable area (some remote sessions and VMs) keeps the config size.
if let Some(monitor) = launch_monitor(app).filter(|m| m.work_area().size.width >= 2 && m.work_area().size.height >= 2) {
let area = monitor.work_area();
let bounds = window_bounds(WorkArea { x: area.position.x, y: area.position.y, width: area.size.width, height: area.size.height, scale: monitor.scale_factor() });
// Onto the monitor first: Windows rescales a window that crosses to a monitor with other
// display scaling, so the physical size is applied once it is there, then centred.
let _ = window.set_position(PhysicalPosition::new(bounds.x, bounds.y));
let _ = window.set_min_size(Some(PhysicalSize::new(bounds.min_width, bounds.min_height)));
let _ = window.set_size(PhysicalSize::new(bounds.width, bounds.height));
let _ = window.set_position(PhysicalPosition::new(bounds.x, bounds.y));
}
if visible {
window.show()?;
let _ = window.set_focus();
}
Ok(window)
}
#[cfg(test)]
mod tests {
use super::*;
fn screen(width: u32, height: u32, taskbar: u32, scale: f64) -> WorkArea {
WorkArea { x: 0, y: 0, width, height: height - taskbar, scale }
}
fn inside(bounds: WindowBounds, area: WorkArea) {
assert!(bounds.width <= area.width && bounds.height <= area.height, "{bounds:?} overflows {area:?}");
assert!(bounds.x >= area.x && bounds.y >= area.y, "{bounds:?} starts outside {area:?}");
assert!(bounds.min_width <= bounds.width && bounds.min_height <= bounds.height);
let (left, right) = (bounds.x - area.x, area.x + area.width as i32 - (bounds.x + bounds.width as i32));
let (top, bottom) = (bounds.y - area.y, area.y + area.height as i32 - (bounds.y + bounds.height as i32));
assert!((left - right).abs() <= 1 && (top - bottom).abs() <= 1, "not centred: {bounds:?} in {area:?}");
}
#[test]
fn every_common_screen_at_every_scaling_fits_and_is_centred() {
for (width, height) in [(1280, 720), (1366, 768), (1920, 1080), (2560, 1440), (3440, 1440), (3840, 2160)] {
for scale in [1.0, 1.25, 1.5, 2.0] {
let area = screen(width, height, (48.0 * scale) as u32, scale);
inside(window_bounds(area), area);
}
}
}
#[test]
fn keeps_the_same_share_of_the_screen_at_any_scaling() {
let at_100 = window_bounds(screen(2560, 1440, 48, 1.0));
let at_150 = window_bounds(screen(2560, 1440, 48, 1.5));
assert_eq!((at_100.width, at_100.height), (at_150.width, at_150.height));
}
#[test]
fn an_ultrawide_is_limited_by_its_height() {
let bounds = window_bounds(screen(3440, 1440, 48, 1.0));
assert!((bounds.width as f64 / bounds.height as f64 - ASPECT).abs() < 0.01);
}
#[test]
fn a_monitor_left_of_the_primary_is_centred_on_itself() {
let area = WorkArea { x: -1920, y: 120, width: 1920, height: 1040, scale: 1.0 };
inside(window_bounds(area), area);
}
}

60
src-tauri/tauri.conf.json Normal file
View file

@ -0,0 +1,60 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Vehicle Generator",
"mainBinaryName": "vehicle-generator",
"version": "0.1.0",
"identifier": "fyi.crt.vehiclegenerator",
"build": {
"frontendDist": "../dist",
"devUrl": "http://localhost:5173",
"beforeDevCommand": "bun run dev",
"beforeBuildCommand": "bun run build"
},
"app": {
"windows": [
{
"label": "main",
"create": false,
"title": "Vehicle Generator",
"width": 1440,
"height": 900,
"minWidth": 960,
"minHeight": 620,
"resizable": true,
"fullscreen": false,
"decorations": false,
"transparent": false,
"visible": true
}
],
"security": {
"csp": {
"default-src": "'self'",
"script-src": "'self' 'wasm-unsafe-eval'",
"style-src": "'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src": "'self' data: https://fonts.gstatic.com",
"img-src": "'self' data: blob:",
"connect-src": "'self' ipc: http://ipc.localhost blob: data:",
"worker-src": "'self' blob:",
"frame-src": "'none'",
"object-src": "'none'",
"base-uri": "'none'"
}
}
},
"bundle": {
"active": true,
"targets": "all",
"createUpdaterArtifacts": false,
"category": "DeveloperTool",
"shortDescription": "Procedural, game-ready vehicle generator",
"copyright": "Copyright (c) 2026 CRTkafa. MIT License.",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

View file

@ -0,0 +1,5 @@
{
"bundle": {
"targets": ["appimage", "deb", "rpm"]
}
}

View file

@ -0,0 +1,23 @@
{
"bundle": {
"targets": ["dmg"]
},
"app": {
"windows": [
{
"label": "main",
"create": false,
"title": "Vehicle Generator",
"width": 1440,
"height": 900,
"minWidth": 960,
"minHeight": 620,
"resizable": true,
"fullscreen": false,
"decorations": true,
"titleBarStyle": "Overlay",
"hiddenTitle": true
}
]
}
}

View file

@ -0,0 +1,14 @@
{
"bundle": {
"targets": ["nsis"],
"windows": {
"webviewInstallMode": { "type": "downloadBootstrapper", "silent": true },
"nsis": {
"installMode": "currentUser",
"displayLanguageSelector": false,
"startMenuFolder": "vehicle-generator",
"installerIcon": "icons/icon.ico"
}
}
}
}

43
src/app/about.ts Normal file
View file

@ -0,0 +1,43 @@
/** Help → About: what the studio is, its version, and what it is built with. */
import pkg from '../../package.json'
import { BODY_STYLES, MOD_KINDS } from '../generator/index.ts'
import mark from './assets/mark.png'
import { stage } from './context.ts'
import { showShortcuts } from './menubar.ts'
import { el } from './ui.ts'
export function showAbout(): void {
const close = (): void => {
backdrop.remove()
window.removeEventListener('keydown', onKey, true)
}
const onKey = (e: KeyboardEvent): void => {
if (e.key !== 'Escape') return
e.stopPropagation()
close()
}
const shortcuts = el('button', { type: 'button' }, 'Keyboard shortcuts')
shortcuts.addEventListener('click', () => { close(); showShortcuts() })
const done = el('button', { type: 'button', class: 'primary' }, 'Close')
done.addEventListener('click', close)
const row = (label: string, value: string): HTMLElement => el('div', { class: 'about-row' }, el('span', {}, label), el('b', {}, value))
const box = el('section', { class: 'about', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'about-title' },
el('div', { class: 'about-hero' },
el('img', { src: mark, alt: '', class: 'about-mark', width: 132, height: 132 }),
el('h2', { id: 'about-title' }, 'VEHICLE', el('em', {}, 'GEN')),
el('span', { class: 'about-version' }, `Studio ${pkg.version}`)),
el('p', { class: 'about-lead' }, 'Procedural, game-ready vehicles for three.js. Shape one, fit its parts, drive it, then export it to any engine.'),
el('div', { class: 'about-rows' },
row('Body styles', String(BODY_STYLES.length)),
row('Parametric mods', String(MOD_KINDS.length)),
row('Renderer', stage.backend),
row('Built with', 'three.js · Tauri'),
row('Licence', pkg.license)),
el('footer', {}, shortcuts, el('span', { class: 'spacer' }), done))
const backdrop = el('div', { class: 'backdrop about-backdrop' }, box)
backdrop.addEventListener('pointerdown', (e) => { if (e.target === backdrop) close() })
window.addEventListener('keydown', onKey, true)
document.body.append(backdrop)
done.focus()
}

BIN
src/app/assets/mark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

62
src/app/build.ts Normal file
View file

@ -0,0 +1,62 @@
/** Turning the spec into a vehicle on screen: coalesced rebuilds, coarse builds while a field is scrubbed, the rig pose. */
import { generateVehicle, type Vehicle } from '../generator/index.ts'
import { effectiveSpec, stage, state } from './context.ts'
import { renderInspector } from './inspector.ts'
import { renderStatus } from './status.ts'
export let vehicle: Vehicle | null = null
export let rebuildQueued = false
export let refit = false
export let scrubbing = false
export let scrubDirty = false
window.addEventListener('pointerdown', (e) => {
if ((e.target as Element | null)?.closest?.('[data-scrub]')) { scrubbing = true; scrubDirty = false }
}, true)
export const endScrub = (): void => {
if (!scrubbing) return
scrubbing = false
if (scrubDirty) rebuild()
}
window.addEventListener('pointerup', endScrub, true)
window.addEventListener('pointercancel', endScrub, true)
export let lastBuildMs = 0
export function rebuild(frame = false): void {
if (scrubbing) scrubDirty = true
refit ||= frame
if (rebuildQueued) return
rebuildQueued = true
requestAnimationFrame(() => {
rebuildQueued = false
const t0 = performance.now()
// While a field is scrubbed, build only the coarse level so dragging stays
// smooth; the full build follows on release.
const next = scrubbing ? generateVehicle(effectiveSpec(), { lods: [2], interior: false }) : generateVehicle(effectiveSpec())
lastBuildMs = performance.now() - t0
stage.setVehicle(next, refit || !vehicle)
if (resumeView) {
stage.camera.position.fromArray(resumeView.camera)
stage.controls.target.fromArray(resumeView.target)
stage.controls.update()
resumeView = null
}
refit = false
vehicle?.dispose()
vehicle = next
applyRig()
renderStatus()
if (state.tab === 'rig') renderInspector()
})
}
export function applyRig(): void {
if (!vehicle) return
vehicle.rig.setSteer(state.steer)
for (const part of vehicle.rig.openables) vehicle.rig.open(part, state.open[part] ?? 0)
vehicle.rig.setHeadlights(state.head)
vehicle.rig.setBrake(state.brake)
}
export let resumeView: { readonly camera: number[]; readonly target: number[] } | null = null
/** A dev reload's camera, applied once the first build is on screen. */
export function setResumeView(view: { readonly camera: number[]; readonly target: number[] }): void { resumeView = view }

59
src/app/context.ts Normal file
View file

@ -0,0 +1,59 @@
/** Shared studio state and small helpers every part of the studio reads. */
import { blendSpecs, type BodyStyle, type OpenablePart, preset, styleLabel, type VehicleSpec } from '../generator/index.ts'
import type { Library, LibraryEntry } from '../library/format.ts'
import { LibraryStore } from '../library/store.ts'
import { Stage } from './scene.ts'
import { el } from './ui.ts'
export type Tab = 'vehicle' | 'body' | 'part' | 'paint' | 'wheels' | 'rig'
export type ExportTarget = 'glb' | 'glb-lods' | 'spec'
export const state = {
spec: preset('hatchback', 1) as VehicleSpec,
blendWith: 'suv' as BodyStyle,
blend: 0,
tab: 'part' as Tab,
cat: 'style',
randomStyle: false,
libraries: [] as Library[],
libraryId: '',
entryId: '' as string,
checked: new Set<string>(),
renaming: '',
dirty: false,
steer: 0,
drive: false,
speed: 0,
open: {} as Partial<Record<OpenablePart, number>>,
head: false,
brake: false,
}
export const store = new LibraryStore()
export const notice = el('span', { class: 'notice' })
export let noticeTimer = 0
export function notify(text: string): void {
notice.textContent = text
clearTimeout(noticeTimer)
noticeTimer = window.setTimeout(() => { notice.textContent = '' }, 4000)
}
export function effectiveSpec(): VehicleSpec {
return state.blend > 0 ? blendSpecs(state.spec, { ...preset(state.blendWith, state.spec.seed), paint: state.spec.paint, mods: state.spec.mods }, state.blend) : state.spec
}
export function currentLibrary(): Library | undefined {
return state.libraries.find((l) => l.id === state.libraryId)
}
export function currentEntry(): LibraryEntry | undefined {
return currentLibrary()?.entries.find((e) => e.id === state.entryId)
}
export function currentName(): string {
return currentEntry()?.name ?? styleLabel(state.spec.style)
}
export const slug = (name: string): string => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'vehicle'
/** Rolls the open vehicle (undoable); `style` keeps it within one style. */
export let stage!: Stage
export function setStage(s: Stage): void { stage = s }

160
src/app/customs.ts Normal file
View file

@ -0,0 +1,160 @@
/** The customs categories on the left and the variant shelf under the viewport. */
import { BODY_STYLES, MOD_KINDS, type ModKind, MODS, type ModSpec, styleLabel } from '../generator/index.ts'
import { vehicle } from './build.ts'
import { stage, state } from './context.ts'
import { edit, editPaint, setStyle } from './editing.ts'
import { bodyPanel, paintPanel, renderInspector, rigPanel, wheelsPanel } from './inspector.ts'
import { customsList, shelf } from './layout.ts'
import type { CameraView } from './scene.ts'
import { renderToolbar } from './toolbar.ts'
import { el, section, select, slider } from './ui.ts'
export interface Category {
readonly id: string
readonly label: string
readonly view: CameraView
variants(): readonly string[]
current(): number
apply(index: number): void
panel(): HTMLElement[]
}
export const RIMS = ['spoke', 'multispoke', 'mesh', 'turbine', 'steelie', 'deepdish', 'beadlock'] as const
export const FINISHES = ['solid', 'metallic', 'pearl', 'matte'] as const
export const MOD_VIEW: Readonly<Record<ModKind, CameraView>> = {
spoiler: 'rear34', bodyKit: 'front34', widebody: 'front34', suspension: 'side', wheelSet: 'wheel', bullBar: 'front',
roofRack: 'top', snorkel: 'front34', exhaust: 'rear', hoodScoop: 'front34', lightBar: 'front34', rollCage: 'top', mudFlaps: 'rear34',
}
export const cap = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1).replace(/-/g, ' ')
export function modCategory(kind: ModKind): Category {
const def = MODS[kind]
const choice = def.params.find((p) => p.type === 'select')
const options = choice?.type === 'select' ? choice.options : []
const fitted = (): ModSpec | undefined => state.spec.mods.find((m) => m.kind === kind)
return {
id: kind,
label: def.label,
view: MOD_VIEW[kind],
variants: () => ['None', ...(options.length ? options.map(cap) : ['Fitted'])],
current: () => {
const m = fitted()
if (!m) return 0
if (!choice) return 1
return Math.max(0, options.indexOf(String(m.params?.[choice.key] ?? choice.default))) + 1
},
apply: (i) => edit((sp) => {
const rest = sp.mods.filter((m) => m.kind !== kind)
if (i === 0) return { ...sp, mods: rest }
const prev = sp.mods.find((m) => m.kind === kind)
const params = choice ? { ...prev?.params, [choice.key]: options[i - 1]! } : prev?.params
return { ...sp, mods: [...rest, params ? { kind, params } : { kind }] }
}),
panel: () => {
const current = fitted()
if (!current) return [section(def.label, el('p', { class: 'hint' }, def.description), el('p', { class: 'hint' }, 'Pick a variant on the shelf below the viewport to fit it.'))]
const fields = def.params.filter((p) => p !== choice).map((param) => {
const value = current.params?.[param.key] ?? param.default
const set = (v: number | string): void => edit((sp) => ({
...sp,
mods: sp.mods.map((m): ModSpec => (m.kind === kind ? { kind, params: { ...m.params, [param.key]: v } } : m)),
}))
return param.type === 'number'
? slider({ label: param.label, min: param.min, max: param.max, step: param.step, value: Number(value), defaultValue: param.default, onInput: set })
: select(param.label, param.options.map((o) => ({ value: o, label: cap(o) })), String(value), set)
})
return [section(def.label, el('p', { class: 'hint' }, def.description), ...fields)]
},
}
}
export const CATEGORIES: readonly Category[] = [
{
id: 'style', label: 'Body style', view: 'side',
variants: () => BODY_STYLES.map(styleLabel),
current: () => BODY_STYLES.indexOf(state.spec.style),
apply: (i) => setStyle(BODY_STYLES[i]!),
panel: () => bodyPanel(),
},
{
id: 'paint', label: 'Paint', view: 'front34',
variants: () => FINISHES.map(cap),
current: () => FINISHES.indexOf(state.spec.paint.finish as typeof FINISHES[number]),
apply: (i) => editPaint({ finish: FINISHES[i]! }),
panel: () => paintPanel(),
},
{
id: 'wheels', label: 'Wheels', view: 'wheel',
variants: () => RIMS.map(cap),
current: () => RIMS.indexOf(state.spec.wheels.rim),
apply: (i) => edit((sp) => ({ ...sp, wheels: { ...sp.wheels, rim: RIMS[i]! } })),
panel: () => wheelsPanel(),
},
...MOD_KINDS.map(modCategory),
{
id: 'rig', label: 'Doors and rig', view: 'side',
variants: () => ['Closed', 'Doors open', 'All open'],
current: () => {
const parts = vehicle?.rig.openables ?? []
const open = parts.filter((p) => (state.open[p] ?? 0) > 0.5)
if (open.length === 0) return 0
return open.length === parts.length ? 2 : 1
},
apply: (i) => {
for (const p of vehicle?.rig.openables ?? []) {
state.open[p] = i === 2 || (i === 1 && p.startsWith('door')) ? 1 : 0
vehicle?.rig.open(p, state.open[p]!)
}
renderCustoms()
if (state.tab === 'rig' || state.tab === 'part') renderInspector()
},
panel: () => rigPanel(),
},
]
export const category = (): Category => CATEGORIES.find((c) => c.id === state.cat) ?? CATEGORIES[0]!
export function pickCategory(id: string): void {
state.cat = id
state.tab = 'part'
stage.look(category().view)
renderCustoms()
renderInspector()
}
export function fitVariant(index: number): void {
const c = category()
const n = c.variants().length
c.apply(((index % n) + n) % n)
renderCustoms()
renderInspector()
}
export function renderCustoms(): void {
customsList.replaceChildren(...CATEGORIES.map((c, i) => {
const on = c.id === state.cat
const variants = c.variants()
const b = el('button', { type: 'button', class: `row${on ? ' on' : ''}`, 'aria-current': String(on) },
el('span', { class: 'num' }, String(i + 1).padStart(2, '0')),
el('span', { class: 'name' }, c.label),
el('span', { class: 'meta' }, variants[c.current()] ?? ''))
b.addEventListener('click', () => pickCategory(c.id))
return el('li', {}, b)
}))
const c = category()
const current = c.current()
const cards = c.variants().map((name, i) => {
const on = i === current
const b = el('button', { type: 'button', role: 'option', 'aria-selected': String(on), class: `variant${on ? ' on' : ''}` },
el('span', { class: 'num' }, String(i).padStart(2, '0')), el('span', { class: 'name' }, name), on ? el('span', { class: 'fitted' }, 'FITTED') : null)
b.addEventListener('click', () => fitVariant(i))
return b
})
const index = CATEGORIES.indexOf(c)
shelf.replaceChildren(
el('header', {}, el('span', { class: 'num' }, String(index + 1).padStart(2, '0')), el('b', {}, c.label),
el('span', { class: 'meta' }, `${cards.length} variants`), el('div', { class: 'spacer' }), el('span', { class: 'meta' }, '← → browse')),
el('div', { class: 'variants', role: 'listbox', 'aria-label': `${c.label} variants` }, ...cards),
)
shelf.querySelector('.variant.on')?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
renderToolbar()
}

14
src/app/devlog.ts Normal file
View file

@ -0,0 +1,14 @@
/** Development only: page errors go to the dev server's terminal (see vite.config.ts). */
const send = (kind: string, message: string, stack?: string, where?: string): void => {
import.meta.hot?.send('vehicle-generator:error', { kind, message, stack, where })
}
if (import.meta.env.DEV) {
addEventListener('error', (e) => {
send('error', e.message, (e.error as Error | undefined)?.stack, e.filename ? `${e.filename.replace(location.origin, '')}:${e.lineno}` : undefined)
})
addEventListener('unhandledrejection', (e) => {
const reason = e.reason as Error | string
send('rejection', reason instanceof Error ? reason.message : String(reason), reason instanceof Error ? reason.stack : undefined)
})
}

752
src/app/drive.ts Normal file
View file

@ -0,0 +1,752 @@
import {
BoxGeometry,
BufferAttribute,
BufferGeometry,
CatmullRomCurve3,
Color,
ConeGeometry,
CylinderGeometry,
DirectionalLight,
Fog,
Group,
HemisphereLight,
InstancedMesh,
Matrix4,
Mesh,
MeshStandardMaterial,
type Object3D,
type Texture,
PerspectiveCamera,
PlaneGeometry,
Quaternion,
RenderPipeline,
Scene,
Vector3,
type WebGPURenderer,
} from 'three/webgpu'
import { pass, uniform } from 'three/tsl'
import { dof } from 'three/addons/tsl/display/DepthOfFieldNode.js'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { createRandom, createRig, generateVehicle, randomSpec, type Vehicle, type VehicleRig, type VehicleSpec } from '../generator/index.ts'
/** A built world, kept between plays: the static scenery and its centre line. */
interface World {
readonly group: Group
readonly curve: CatmullRomCurve3
readonly length: number
readonly table: Float32Array
readonly step: number
readonly sky: Color
readonly disposables: { dispose(): void }[]
}
export interface DriveProgress {
/** 0 to 1. */
readonly done: number
readonly label: string
}
/** Lets the browser paint between heavy steps, so a progress bar moves. */
const yieldToUi = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
const wheelbaseOf = (v: Vehicle): number => Math.abs(v.wheels[0]!.position.z - v.wheels[2]!.position.z)
/**
* Play mode: the current vehicle driving laps of a generated world.
*
* Two worlds. A CIRCUIT is a closed race track with red-and-white kerbs and
* steel barriers; TRAFFIC is a four-lane ring road with pavements, buildings,
* street lights and a dozen other generated cars sharing it.
*
* Every car follows the centre line of a closed spline at a lateral offset.
* Speed comes from curvature (the tighter the bend, the slower), steering from
* curvature through the wheelbase, body roll and pitch from the lateral and
* longitudinal acceleration. Wheels roll at exactly the rate the car moves.
*
* The camera runs a small set of shots — chase, low front, tracking side,
* helicopter, wheel arch — and moves between them with heavy damping, cutting
* now and then. Drag to orbit the car while it drives; let go and the
* director takes over again.
*/
export type DriveWorld = 'circuit' | 'traffic'
interface Agent {
/** The car's root; traffic shares geometry and materials between clones. */
group: Object3D
rig: VehicleRig
wheelbase: number
s: number
speed: number
lane: number
direction: 1 | -1
maxSpeed: number
lastSpeed: number
roll: number
pitch: number
}
type Shot = 'chase' | 'low' | 'side' | 'heli' | 'wheel' | 'front'
export class Drive {
readonly scene = new Scene()
readonly camera = new PerspectiveCamera(34, 1, 0.1, 2000)
readonly controls: OrbitControls
world: DriveWorld = 'circuit'
#renderer: WebGPURenderer
#content = new Group()
#actors = new Group()
#curve!: CatmullRomCurve3
#length = 1
#table: Float32Array = new Float32Array(0)
#step = 0.5
#worlds = new Map<string, World>()
#vehicles: Vehicle[] = []
#frameTimes: number[] = []
#savedPixelRatio = 1
#player: Agent | null = null
#traffic: Agent[] = []
#sun = new DirectionalLight(0xfff0dc, 3)
#shot: Shot = 'chase'
#shotTime = 0
#shotIndex = 0
#manual = false
#manualRelease = 0
#lastPlayerPos = new Vector3()
#pipeline: RenderPipeline | null = null
#focus = uniform(8)
#disposables: { dispose(): void }[] = []
speed = 0
constructor(renderer: WebGPURenderer, canvas: HTMLCanvasElement, environment: Texture | null) {
this.#renderer = renderer
// The studio's reflection environment: paint and glass need something to reflect.
this.scene.environment = environment
this.controls = new OrbitControls(this.camera, canvas)
this.controls.enableDamping = true
this.controls.enabled = false
this.controls.addEventListener('start', () => { this.#manual = true })
this.controls.addEventListener('end', () => { this.#manualRelease = 2.5 })
this.scene.add(this.#actors)
this.#sun.castShadow = true
// 1024 is plenty for a 44 m box round one car, and a quarter of the fill.
this.#sun.shadow.mapSize.set(1024, 1024)
const sc = this.#sun.shadow.camera
sc.left = -22; sc.right = 22; sc.top = 22; sc.bottom = -22; sc.near = 1; sc.far = 260
this.#sun.shadow.bias = -0.0005
this.#sun.shadow.normalBias = 0.03
this.scene.add(new HemisphereLight(0xdfeaf5, 0x4a4436, 0.9), this.#sun, this.#sun.target)
try {
// Depth of field focused on the car: background bokeh is most of what
// separates a cinematic shot from a game camera.
const scenePass = pass(this.scene, this.camera)
const pipeline = new RenderPipeline(renderer)
pipeline.outputNode = dof(scenePass.getTextureNode(), scenePass.getViewZNode(), this.#focus, uniform(14), uniform(0.9))
this.#pipeline = pipeline
} catch {
this.#pipeline = null
}
}
#ready = false
/** True once `prepare` has finished and until `stop`. */
get active(): boolean {
return this.#ready && this.#player !== null
}
/**
* Builds everything Play needs before the first frame: the world (cached
* per world and seed), the player, the traffic, and every shader, compiled
* up front so the first seconds of driving do not stall. Yields between
* steps so a loading screen can show progress; `signal` cancels.
*/
async prepare(spec: VehicleSpec, world: DriveWorld, onProgress: (p: DriveProgress) => void, signal?: AbortSignal): Promise<boolean> {
const t0 = performance.now()
this.stop()
this.world = world
this.timings = {}
let mark = t0
let current = 'start'
const step = async (done: number, label: string): Promise<boolean> => {
const now = performance.now()
this.timings[current] = Math.round(now - mark)
mark = now
current = label
onProgress({ done, label })
await yieldToUi()
return !signal?.aborted
}
if (!await step(0.02, 'Laying out the world')) return false
const key = `${world}:${spec.seed}`
let w = this.#worlds.get(key)
if (!w) {
w = this.#buildWorld(createRandom(spec.seed * 31 + (world === 'circuit' ? 1 : 2)))
this.#worlds.set(key, w)
}
this.#useWorld(w)
if (!await step(0.3, 'Building your car')) return this.#abort()
const player = generateVehicle(spec, { lods: [0, 1] })
this.#vehicles.push(player)
player.rig.setHeadlights(world === 'traffic')
this.#actors.add(player.group)
this.#player = {
group: player.group, rig: player.rig, wheelbase: wheelbaseOf(player), s: 0, speed: 0,
lane: world === 'circuit' ? 0 : -1.75, direction: 1, maxSpeed: world === 'circuit' ? 46 : 16, lastSpeed: 0, roll: 0, pitch: 0,
}
if (world === 'traffic') {
if (!await step(0.45, 'Generating traffic')) return this.#abort()
await this.#spawnTraffic(createRandom(spec.seed * 31 + 7), (k, n) => onProgress({ done: 0.45 + 0.25 * (k / n), label: `Generating traffic ${k}/${n}` }), signal)
if (signal?.aborted) return this.#abort()
}
this.#shotTime = 0
this.#shotIndex = 0
this.#shot = 'chase'
this.#manual = false
this.#place(this.#player, 0)
this.#snapCamera()
if (!await step(0.75, 'Compiling shaders')) return this.#abort()
// Compile every pipeline now instead of on first sight while driving.
await this.#renderer.compileAsync(this.scene, this.camera)
if (!await step(0.95, 'Warming up')) return this.#abort()
this.#savedPixelRatio = this.#renderer.getPixelRatio()
this.#renderer.setPixelRatio(Math.min(globalThis.devicePixelRatio, 1.25))
// Warm-up frames, waiting for the GPU each time: pipelines finish
// compiling in the GPU process, and the first present otherwise waits
// on them (a one-second hitch a few frames into driving).
const device = (this.#renderer.backend as { device?: { queue: { onSubmittedWorkDone(): Promise<void> } } }).device
for (let k = 0; k < 3; k += 1) {
this.render()
await device?.queue.onSubmittedWorkDone()
await new Promise((resolve) => requestAnimationFrame(resolve))
if (signal?.aborted) return this.#abort()
}
this.#frameTimes = []
this.#ready = true
this.timings[current] = Math.round(performance.now() - mark)
this.readyMs = performance.now() - t0
onProgress({ done: 1, label: 'Ready' })
return true
}
/** Time the last `prepare` took, in milliseconds, and per step. */
readyMs = 0
timings: Record<string, number> = {}
#abort(): false {
this.stop()
return false
}
stop(): void {
this.#ready = false
for (const v of this.#vehicles) v.dispose()
this.#vehicles = []
this.#player = null
this.#traffic = []
this.#actors.clear()
this.controls.enabled = false
if (this.#savedPixelRatio !== this.#renderer.getPixelRatio()) this.#renderer.setPixelRatio(this.#savedPixelRatio)
}
/** Records a frame time; `stats` reads the median and 95th percentile. */
sample(ms: number): void {
this.#frameTimes.push(ms)
if (this.#frameTimes.length > 240) this.#frameTimes.shift()
}
get stats(): { median: number; p95: number; fps: number } {
const sorted = [...this.#frameTimes].sort((x, y) => x - y)
if (!sorted.length) return { median: 0, p95: 0, fps: 0 }
const median = sorted[sorted.length >> 1]!
return { median, p95: sorted[Math.floor(sorted.length * 0.95)]!, fps: 1000 / median }
}
#useWorld(w: World): void {
this.scene.remove(this.#content)
this.#content = w.group
this.scene.add(w.group)
this.#curve = w.curve
this.#length = w.length
this.#table = w.table
this.#step = w.step
this.scene.background = w.sky
this.scene.fog = new Fog(w.sky, 120, 650)
this.scene.environmentIntensity = 0.8
}
resize(width: number, height: number): void {
this.camera.aspect = width / Math.max(1, height)
this.camera.updateProjectionMatrix()
}
/* ------------------------------------------------------------- world */
#buildWorld(random: () => number): World {
const circuit = this.world === 'circuit'
this.#content = new Group()
this.#disposables = []
// Control points round a loop, radius jittered so every seed draws a new track.
const points: Vector3[] = []
const n = circuit ? 14 : 10
const base = circuit ? 140 : 230
for (let k = 0; k < n; k += 1) {
const a = (k / n) * Math.PI * 2
const r = base * (circuit ? 0.65 + random() * 0.55 : 0.85 + random() * 0.25)
const stretch = circuit ? 1.35 : 1.15
points.push(new Vector3(Math.cos(a) * r * stretch, 0, Math.sin(a) * r))
}
this.#curve = new CatmullRomCurve3(points, true, 'centripetal', 0.5)
this.#length = this.#curve.getLength()
// The centre line sampled every half metre: position, tangent and
// curvature by lookup instead of a spline evaluation per query.
this.#step = 0.5
const count = Math.ceil(this.#length / this.#step)
this.#table = new Float32Array(count * 5)
for (let i = 0; i < count; i += 1) {
const u = Math.min(1, (i * this.#step) / this.#length)
const p = this.#curve.getPointAt(u)
const t = this.#curve.getTangentAt(u)
this.#table.set([p.x, p.z, t.x, t.z, 0], i * 5)
}
for (let i = 0; i < count; i += 1) {
const a0 = (i - 4 + count) % count
const b0 = (i + 4) % count
const ax = this.#table[a0 * 5 + 2]!, az = this.#table[a0 * 5 + 3]!
const bx = this.#table[b0 * 5 + 2]!, bz = this.#table[b0 * 5 + 3]!
this.#table[i * 5 + 4] = -Math.atan2(ax * bz - az * bx, ax * bx + az * bz) / (8 * this.#step)
}
const sky = circuit ? new Color(0x9fb8d0) : new Color(0xb9c2cc)
const ground = new Mesh(new PlaneGeometry(3000, 3000), this.#mat(circuit ? 0x4f6a3a : 0x5d6a4a, 0.95))
ground.rotation.x = -Math.PI / 2
ground.position.y = -0.02
ground.receiveShadow = true
this.#content.add(ground)
const halfRoad = circuit ? 6.5 : 7.4
this.#content.add(this.#ribbon(-halfRoad, halfRoad, 0, this.#mat(0x2f3134, 0.88)))
if (circuit) {
// Kerbs: alternating red and white blocks on both edges.
this.#content.add(this.#ribbon(halfRoad, halfRoad + 1.2, 0.03, this.#mat(0xffffff, 0.6), 3, 0))
this.#content.add(this.#ribbon(halfRoad, halfRoad + 1.2, 0.03, this.#mat(0xc62b24, 0.6), 3, 1))
this.#content.add(this.#ribbon(-halfRoad - 1.2, -halfRoad, 0.03, this.#mat(0xffffff, 0.6), 3, 0))
this.#content.add(this.#ribbon(-halfRoad - 1.2, -halfRoad, 0.03, this.#mat(0xc62b24, 0.6), 3, 1))
// Gravel run-off and steel barriers.
this.#content.add(this.#ribbon(halfRoad + 1.2, halfRoad + 9, 0.005, this.#mat(0xb7a98c, 1)))
this.#content.add(this.#ribbon(-halfRoad - 9, -halfRoad - 1.2, 0.005, this.#mat(0xb7a98c, 1)))
for (const side of [1, -1]) {
const off = side * (halfRoad + 9.2)
this.#content.add(this.#wall(off, 0.45, 0.8, this.#mat(0xb8bcc0, 0.35, 0.8)))
this.#posts(off, 4, 0.75, this.#mat(0x6d7176, 0.5, 0.6))
}
// Start / finish: a chequered strip and a gantry.
this.#content.add(this.#ribbon(-halfRoad, halfRoad, 0.01, this.#mat(0xf2f2f2, 0.7), 0, 0, 2))
this.#gantry(halfRoad)
} else {
// Lane lines: dashed centre lines between lanes, a solid double line in the middle.
for (const off of [-3.6, 3.6]) this.#content.add(this.#ribbon(off - 0.07, off + 0.07, 0.01, this.#mat(0xeeeeee, 0.6), 6, 0))
this.#content.add(this.#ribbon(-0.2, -0.08, 0.01, this.#mat(0xe8c140, 0.6)))
this.#content.add(this.#ribbon(0.08, 0.2, 0.01, this.#mat(0xe8c140, 0.6)))
this.#content.add(this.#ribbon(halfRoad, halfRoad + 3, 0.15, this.#mat(0x9a9a96, 0.85)))
this.#content.add(this.#ribbon(-halfRoad - 3, -halfRoad, 0.15, this.#mat(0x9a9a96, 0.85)))
this.#buildings(halfRoad + 5, random)
this.#lamps(halfRoad + 1.2)
}
this.#trees(circuit ? halfRoad + 22 : halfRoad + 34, random)
// Static scenery: matrices are computed once, not every frame.
this.#content.traverse((o) => { o.updateMatrix(); o.matrixAutoUpdate = false })
return { group: this.#content, curve: this.#curve, length: this.#length, table: this.#table, step: this.#step, sky, disposables: this.#disposables }
}
#mat(color: number, roughness: number, metalness = 0): MeshStandardMaterial {
const m = new MeshStandardMaterial({ color, roughness, metalness })
this.#disposables.push(m)
return m
}
/** Frame at arc length s: position, tangent and the left-hand normal. */
#frame(s: number): { p: Vector3; t: Vector3; n: Vector3 } {
const T = this.#table
const count = T.length / 5
const x = (((s / this.#step) % count) + count) % count
const i = Math.floor(x) % count
const j = (i + 1) % count
const f = x - Math.floor(x)
const at = (o: number): number => T[i * 5 + o]! + (T[j * 5 + o]! - T[i * 5 + o]!) * f
const p = new Vector3(at(0), 0, at(1))
const t = new Vector3(at(2), 0, at(3)).normalize()
const n = new Vector3(t.z, 0, -t.x)
return { p, t, n }
}
/** Signed curvature at s (positive turns left), from the table. */
#curvature(s: number): number {
const count = this.#table.length / 5
const i = Math.floor((((s / this.#step) % count) + count) % count) % count
return this.#table[i * 5 + 4]!
}
/**
* A strip along the track between two lateral offsets. `dash` splits it
* into blocks of that length; `phase` picks every other one (kerbs).
*/
#ribbon(off0: number, off1: number, y: number, material: MeshStandardMaterial, dash = 0, phase = 0, only = 0): Mesh {
const step = 1.5
const count = Math.ceil(this.#length / step)
const pos: number[] = []
const idx: number[] = []
const emitQuad = (s0: number, s1: number): void => {
const a = this.#frame(s0)
const b = this.#frame(s1)
const base = pos.length / 3
for (const [f, o] of [[a, off0], [a, off1], [b, off0], [b, off1]] as const) {
pos.push(f.p.x + f.n.x * o, y, f.p.z + f.n.z * o)
}
idx.push(base, base + 2, base + 1, base + 1, base + 2, base + 3)
}
if (only > 0) {
emitQuad(0, only)
} else if (dash > 0) {
const blocks = Math.floor(this.#length / dash)
for (let k = phase; k < blocks; k += 2) {
const s0 = k * dash
const segs = Math.max(1, Math.round(dash / step))
for (let j = 0; j < segs; j += 1) emitQuad(s0 + (j / segs) * dash, s0 + ((j + 1) / segs) * dash)
}
} else {
for (let k = 0; k < count; k += 1) emitQuad(k * step, Math.min(this.#length, (k + 1) * step))
}
const g = new BufferGeometry()
g.setAttribute('position', new BufferAttribute(new Float32Array(pos), 3))
g.setIndex(idx)
g.computeVertexNormals()
// Normals all point up for a flat strip; make sure.
const nrm = g.getAttribute('normal')
for (let i = 0; i < nrm.count; i += 1) nrm.setXYZ(i, 0, 1, 0)
this.#disposables.push(g)
const mesh = new Mesh(g, material)
mesh.receiveShadow = true
return mesh
}
/** A vertical rail (Armco) along the track. */
#wall(off: number, y0: number, y1: number, material: MeshStandardMaterial): Mesh {
const step = 2
const count = Math.ceil(this.#length / step)
const pos: number[] = []
const idx: number[] = []
for (let k = 0; k <= count; k += 1) {
const f = this.#frame(Math.min(this.#length, k * step))
pos.push(f.p.x + f.n.x * off, y0, f.p.z + f.n.z * off, f.p.x + f.n.x * off, y1, f.p.z + f.n.z * off)
if (k < count) {
const b = k * 2
idx.push(b, b + 2, b + 1, b + 1, b + 2, b + 3, b, b + 1, b + 2, b + 1, b + 3, b + 2)
}
}
const g = new BufferGeometry()
g.setAttribute('position', new BufferAttribute(new Float32Array(pos), 3))
g.setIndex(idx)
g.computeVertexNormals()
this.#disposables.push(g)
const mesh = new Mesh(g, material)
mesh.castShadow = true
return mesh
}
#instances(geometry: BufferGeometry, material: MeshStandardMaterial, matrices: Matrix4[], shadows = true): void {
if (matrices.length === 0) return
const mesh = new InstancedMesh(geometry, material, matrices.length)
matrices.forEach((m, i) => mesh.setMatrixAt(i, m))
mesh.castShadow = shadows
mesh.receiveShadow = true
this.#disposables.push(geometry)
this.#content.add(mesh)
}
#posts(off: number, every: number, height: number, material: MeshStandardMaterial): void {
const list: Matrix4[] = []
for (let s = 0; s < this.#length; s += every) {
const f = this.#frame(s)
list.push(new Matrix4().makeTranslation(f.p.x + f.n.x * off, height / 2, f.p.z + f.n.z * off))
}
this.#instances(new BoxGeometry(0.12, height, 0.12), material, list)
}
#gantry(half: number): void {
const f = this.#frame(1)
const m = this.#mat(0x22262b, 0.5, 0.4)
for (const side of [1, -1]) {
const pole = new Mesh(new BoxGeometry(0.4, 6, 0.4), m)
pole.position.set(f.p.x + f.n.x * side * (half + 2), 3, f.p.z + f.n.z * side * (half + 2))
pole.castShadow = true
this.#disposables.push(pole.geometry)
this.#content.add(pole)
}
const beam = new Mesh(new BoxGeometry((half + 2) * 2, 1.1, 0.5), this.#mat(0xd8dde2, 0.4))
beam.position.set(f.p.x, 6.2, f.p.z)
beam.rotation.y = Math.atan2(f.n.x, f.n.z) + Math.PI / 2
this.#disposables.push(beam.geometry)
this.#content.add(beam)
}
#buildings(off: number, random: () => number): void {
const list: Matrix4[] = []
for (let s = 0; s < this.#length; s += 14 + random() * 10) {
const f = this.#frame(s)
for (const side of [1, -1]) {
if (random() < 0.15) continue
const w = 10 + random() * 10
const d = 10 + random() * 14
const h = 8 + random() * 34
const o = side * (off + d / 2 + random() * 3)
const m = new Matrix4().compose(
new Vector3(f.p.x + f.n.x * o, h / 2, f.p.z + f.n.z * o),
new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.atan2(f.t.x, f.t.z)),
new Vector3(w, h, d),
)
list.push(m)
}
}
this.#instances(new BoxGeometry(1, 1, 1), this.#mat(0x9aa3ab, 0.8), list)
}
#lamps(off: number): void {
const poles: Matrix4[] = []
for (let s = 0; s < this.#length; s += 30) {
const f = this.#frame(s)
for (const side of [1, -1]) {
poles.push(new Matrix4().makeTranslation(f.p.x + f.n.x * side * off, 4, f.p.z + f.n.z * side * off))
}
}
this.#instances(new CylinderGeometry(0.08, 0.11, 8, 8), this.#mat(0x4a4f55, 0.5, 0.6), poles)
}
#trees(off: number, random: () => number): void {
const crowns: Matrix4[] = []
const trunks: Matrix4[] = []
for (let s = 0; s < this.#length; s += 9 + random() * 12) {
const f = this.#frame(s)
for (const side of [1, -1]) {
if (random() < 0.3) continue
const o = side * (off + random() * 40)
const h = 5 + random() * 7
const x = f.p.x + f.n.x * o
const z = f.p.z + f.n.z * o
crowns.push(new Matrix4().compose(new Vector3(x, h * 0.62, z), new Quaternion(), new Vector3(h * 0.32, h * 0.7, h * 0.32)))
trunks.push(new Matrix4().compose(new Vector3(x, h * 0.15, z), new Quaternion(), new Vector3(1, h * 0.3, 1)))
}
}
this.#instances(new ConeGeometry(1, 1, 7), this.#mat(0x3d5a32, 0.9), crowns)
this.#instances(new CylinderGeometry(0.18, 0.25, 1, 6), this.#mat(0x4a3a2a, 0.9), trunks)
}
/**
* Fourteen cars from five generated models. Clones share geometry and
* materials, so the GPU sees five sets of buffers, not fourteen, and each
* clone gets its own rig. LOD2 only: traffic is never close to the camera
* for long, and it does not cast shadows.
*/
async #spawnTraffic(random: () => number, progress: (k: number, n: number) => void, signal?: AbortSignal): Promise<void> {
// Drive on the right: lanes right of the centre line (negative offsets,
// since +offset is left) run with the track, the others against it.
const lanes = [-1.75, -5.25, 1.75, 5.25]
const models: Vehicle[] = []
const unique = 5
for (let k = 0; k < unique; k += 1) {
if (signal?.aborted) return
const spec = randomSpec(Math.floor(random() * 1e6), { mods: false })
const v = generateVehicle(spec, { lods: [2], interior: false })
v.rig.setHeadlights(true)
v.group.traverse((o) => { o.castShadow = false })
models.push(v)
this.#vehicles.push(v)
progress(k + 1, unique)
await yieldToUi()
}
for (let k = 0; k < 14; k += 1) {
const lane = lanes[k % lanes.length]!
const model = models[k % unique]!
const group = k < unique ? model.group : model.group.clone(true)
const rig = k < unique ? model.rig : createRig(group)
this.#actors.add(group)
const agent: Agent = {
group, rig, wheelbase: wheelbaseOf(model), s: (k / 14) * this.#length + 40 + random() * 20, speed: 10 + random() * 5, lane,
direction: lane < 0 ? 1 : -1, maxSpeed: 11 + random() * 6, lastSpeed: 0, roll: 0, pitch: 0,
}
this.#traffic.push(agent)
this.#place(agent, 0)
}
}
/* ------------------------------------------------------------- motion */
#place(agent: Agent, dt: number): void {
const v = agent
const { p, t, n } = this.#frame(agent.s)
const pos = p.clone().addScaledVector(n, agent.lane)
const heading = agent.direction > 0 ? t : t.clone().negate()
v.group.position.copy(pos)
v.group.rotation.set(0, Math.atan2(heading.x, heading.z), 0)
const k = this.#curvature(agent.s) * agent.direction
v.rig.setSteer(Math.atan(v.wheelbase * k))
v.rig.update(dt, agent.speed)
if (dt > 0) {
const lateral = agent.speed * agent.speed * k
const longitudinal = (agent.speed - agent.lastSpeed) / dt
// Springs and dampers, roughly: the body chases its target lean.
const ease = 1 - Math.exp(-dt * 4)
agent.roll += (Math.max(-0.07, Math.min(0.07, -lateral * 0.0065)) - agent.roll) * ease
agent.pitch += (Math.max(-0.04, Math.min(0.04, longitudinal * 0.004)) - agent.pitch) * ease
v.rig.setBodyPose(agent.roll, agent.pitch)
v.rig.setBrake(longitudinal < -2.5)
}
agent.lastSpeed = agent.speed
}
#advance(agent: Agent, dt: number, ahead: number): void {
// Look ahead for the tightest bend and slow for it: v = sqrt(a_lat / κ).
let k = 0
for (let d = 0; d <= ahead; d += ahead / 6) k = Math.max(k, Math.abs(this.#curvature(agent.s + d * agent.direction)))
const target = Math.min(agent.maxSpeed, Math.sqrt(7.5 / Math.max(k, 1e-4)))
const accel = target > agent.speed ? 4.5 : -9
agent.speed = Math.max(0, agent.speed + Math.sign(target - agent.speed) * Math.min(Math.abs(target - agent.speed), Math.abs(accel) * dt))
agent.s = (agent.s + agent.speed * dt * agent.direction + this.#length) % this.#length
}
update(dt: number): void {
const player = this.#player
if (!player) return
this.#advance(player, dt, Math.max(20, player.speed * 2.2))
if (this.world === 'circuit') {
// Racing line: drift toward the outside before a bend, clip the inside in it.
const kNow = this.#curvature(player.s)
const kAhead = this.#curvature(player.s + 30)
const line = Math.max(-3.6, Math.min(3.6, (kNow * 900) - (kAhead * 500)))
player.lane += (line - player.lane) * (1 - Math.exp(-dt * 0.8))
}
this.#place(player, dt)
this.speed = player.speed
// Traffic: keep a gap to whoever is ahead in the same lane.
for (const agent of this.#traffic) {
let gap = Infinity
for (const other of this.#traffic) {
if (other === agent || other.lane !== agent.lane) continue
const d = ((other.s - agent.s) * agent.direction + this.#length) % this.#length
gap = Math.min(gap, d)
}
if (agent.lane === player.lane || Math.abs(agent.lane - player.lane) < 1) {
const d = ((player.s - agent.s) * agent.direction + this.#length) % this.#length
gap = Math.min(gap, d)
}
this.#advance(agent, dt, 25)
if (gap < 14) agent.speed = Math.max(0, agent.speed - 12 * dt)
this.#place(agent, dt)
}
if (this.world === 'traffic') {
// The player keeps a gap too.
for (const agent of this.#traffic) {
if (agent.lane !== player.lane) continue
const d = ((agent.s - player.s) + this.#length) % this.#length
if (d < 16) player.speed = Math.min(player.speed, agent.speed)
}
}
// The sun's shadow follows the car.
const at = player.group.position
this.#sun.position.set(at.x + 60, 90, at.z + 40)
this.#sun.target.position.copy(at)
this.#sun.target.updateMatrixWorld()
this.#direct(dt)
}
/* ------------------------------------------------------------- camera */
#shotPosition(shot: Shot, car: Object3D): { eye: Vector3; look: Vector3 } {
const fwd = new Vector3(0, 0, 1).applyQuaternion(car.quaternion)
const left = new Vector3(1, 0, 0).applyQuaternion(car.quaternion)
const p = car.position
const at = (f: number, l: number, y: number): Vector3 => p.clone().addScaledVector(fwd, f).addScaledVector(left, l).setY(p.y + y)
switch (shot) {
case 'chase': return { eye: at(-7.5, 0.6, 2.1), look: at(4, 0, 0.9) }
case 'low': return { eye: at(7, 2.4, 0.45), look: at(0, 0, 0.7) }
case 'side': return { eye: at(0.5, 6.5, 1.1), look: at(0.5, 0, 0.75) }
case 'heli': return { eye: at(-16, -9, 10), look: at(6, 0, 0) }
case 'wheel': return { eye: at(2.2, 1.9, 0.35), look: at(-1, 0, 0.6) }
case 'front': return { eye: at(9, -1.5, 1.3), look: at(0, 0, 0.8) }
}
}
#snapCamera(): void {
if (!this.#player) return
const { eye, look } = this.#shotPosition(this.#shot, this.#player.group)
this.camera.position.copy(eye)
this.camera.lookAt(look)
this.controls.target.copy(look)
this.#lastPlayerPos.copy(this.#player.group.position)
}
#direct(dt: number): void {
const car = this.#player!.group
const delta = car.position.clone().sub(this.#lastPlayerPos)
this.#lastPlayerPos.copy(car.position)
if (this.#manual) {
// Orbiting: carry the camera along with the car, keep looking at it.
this.controls.enabled = true
this.camera.position.add(delta)
this.controls.target.copy(car.position).setY(car.position.y + 0.8)
this.controls.update()
if (this.#manualRelease > 0) {
this.#manualRelease -= dt
if (this.#manualRelease <= 0) this.#manual = false
}
this.#focus.value = this.camera.position.distanceTo(car.position)
return
}
this.controls.enabled = true
this.#shotTime += dt
const order: Shot[] = ['chase', 'low', 'side', 'chase', 'wheel', 'heli', 'front', 'chase']
if (this.#shotTime > 7) {
this.#shotTime = 0
this.#shotIndex = (this.#shotIndex + 1) % order.length
const next = order[this.#shotIndex]!
// Some changes are cuts, some are long dollies; alternate.
const cut = this.#shotIndex % 2 === 0
this.#shot = next
if (cut) { this.#snapCamera(); return }
}
const { eye, look } = this.#shotPosition(this.#shot, car)
const ease = 1 - Math.exp(-dt * (this.#shot === 'chase' ? 3.5 : 1.6))
this.camera.position.add(delta).lerp(eye, ease)
this.controls.target.add(delta).lerp(look, 1 - Math.exp(-dt * 5))
// A little breathing in the lens with speed.
const fov = 32 + Math.min(8, this.speed * 0.15)
this.camera.fov += (fov - this.camera.fov) * (1 - Math.exp(-dt * 2))
this.camera.updateProjectionMatrix()
this.camera.lookAt(this.controls.target)
this.#focus.value = this.camera.position.distanceTo(car.position)
}
render(): void {
if (this.#pipeline) {
try {
this.#pipeline.render()
return
} catch {
this.#pipeline = null
}
}
this.#renderer.render(this.scene, this.camera)
}
dispose(): void {
this.stop()
for (const w of this.#worlds.values()) for (const d of w.disposables) d.dispose()
this.#worlds.clear()
this.controls.dispose()
}
}

116
src/app/editing.ts Normal file
View file

@ -0,0 +1,116 @@
/** Changing the spec: every edit is an undo step and saves itself shortly after. */
import { type BodyStyle, type PaintSpec, preset, randomSpec, styleLabel, type VehicleSpec } from '../generator/index.ts'
import { addEntry, updateEntry } from '../library/store.ts'
import { rebuild, vehicle } from './build.ts'
import { currentLibrary, effectiveSpec, notify, stage, state } from './context.ts'
import { commitLibrary } from './garage.ts'
import { renderAll } from './render.ts'
import { renderStatus } from './status.ts'
export const past: { spec: VehicleSpec; blend: number }[] = []
export const future: { spec: VehicleSpec; blend: number }[] = []
export let lastPush = 0
/** One undo step per gesture: edits within half a second of each other merge. */
export function checkpoint(): void {
const now = performance.now()
if (now - lastPush > 500) {
past.push({ spec: state.spec, blend: state.blend })
if (past.length > 200) past.shift()
future.length = 0
}
lastPush = now
}
export function undo(): void {
const prev = past.pop()
if (!prev) { notify('Nothing to undo'); return }
future.push({ spec: state.spec, blend: state.blend })
restore(prev)
}
export function redo(): void {
const next = future.pop()
if (!next) { notify('Nothing to redo'); return }
past.push({ spec: state.spec, blend: state.blend })
restore(next)
}
export function restore(snapshot: { spec: VehicleSpec; blend: number }): void {
const styleChanged = snapshot.spec.style !== state.spec.style
state.spec = snapshot.spec
state.blend = snapshot.blend
lastPush = 0
markDirty()
rebuild(styleChanged)
renderAll()
}
export function edit(mutate: (spec: VehicleSpec) => VehicleSpec, frame = false): void {
checkpoint()
state.spec = mutate(state.spec)
markDirty()
rebuild(frame)
}
export function editPaint(patch: Partial<PaintSpec>, needsRebuild = false): void {
checkpoint()
state.spec = { ...state.spec, paint: { ...state.spec.paint, ...patch } }
markDirty()
if (needsRebuild) rebuild()
else {
vehicle?.setPaint(state.spec.paint)
stage.refreshPaint(state.spec.paint.finish)
}
}
export let saveTimer = 0
/** Edits save themselves: the open entry is written shortly after the last change. */
export function markDirty(): void {
state.dirty = true
renderStatus()
clearTimeout(saveTimer)
saveTimer = window.setTimeout(() => void save(), 600)
}
export async function save(): Promise<void> {
clearTimeout(saveTimer)
const lib = currentLibrary()
if (!lib) return
if (state.entryId && lib.entries.some((e) => e.id === state.entryId)) {
await commitLibrary(updateEntry(lib, state.entryId, { spec: effectiveSpec() }))
} else {
const [next, entry] = addEntry(lib, styleLabel(state.spec.style), effectiveSpec())
state.entryId = entry.id
await commitLibrary(next)
}
state.dirty = false
renderStatus()
}
/** A customs category: a numbered list of variants on the shelf and a panel of exact values. */
export function setStyle(style: BodyStyle): void {
state.blend = 0
edit((prev) => ({ ...preset(style, prev.seed), paint: prev.paint, mods: prev.mods.filter((m) => m.kind !== 'rollCage').concat(preset(style).mods) }), true)
}
export function randomise(style?: BodyStyle): void {
const seed = Math.floor(Math.random() * 1e6)
checkpoint()
lastPush = 0
const next = randomSpec(seed, style ? { style } : {})
const styleChanged = next.style !== state.spec.style
state.spec = next
state.blend = 0
markDirty()
rebuild(styleChanged)
renderAll()
}
/** The next seed of the same style, keeping the mods. */
export function nextSeed(): void {
edit((s) => ({ ...randomSpec(s.seed + 1, { style: s.style }), mods: s.mods }))
renderAll()
}
/** Back to the style's preset at the current seed. */
export function resetToPreset(): void {
edit((s) => preset(s.style, s.seed), true)
renderAll()
}

110
src/app/exporting.ts Normal file
View file

@ -0,0 +1,110 @@
/** Export: the split button, the export popover and the writers. */
import { exportVehicleGlb, generateVehicle } from '../generator/index.ts'
import type { LibraryEntry } from '../library/format.ts'
import { zip } from '../library/zip.ts'
import { vehicle } from './build.ts'
import { currentEntry, currentLibrary, currentName, effectiveSpec, type ExportTarget, notify, slug, state } from './context.ts'
import { icon, ICON } from './icons.ts'
import { renderMenubar } from './menubar.ts'
import { remember, remembered } from './prefs.ts'
import { closePopover, popHeader, popover, showPopover } from './popovers.ts'
import { download, el } from './ui.ts'
export let exportTarget = remembered('export-target', 'glb') as ExportTarget
export const TARGETS: Readonly<Record<ExportTarget, { label: string; short: string; badge: string; note: string; file: (name: string) => string }>> = {
glb: { label: 'GLB', short: 'GLB', badge: 'GLB', note: 'Model, rig animations and collider in one file, for any engine or 3D tool.', file: (n) => `${n}.glb` },
'glb-lods': { label: 'GLB with all LODs', short: 'GLB · LODs', badge: 'LOD', note: 'The same file with LOD1 and LOD2 alongside LOD0, named for engines that pick a level by distance.', file: (n) => `${n}-lods.glb` },
spec: { label: 'Spec JSON', short: 'Spec', badge: '{ }', note: 'A few hundred bytes that rebuild this exact vehicle, vertex for vertex.', file: (n) => `${n}.json` },
}
export const PLANNED = [['GD', 'Godot 4'], ['U', 'Unity'], ['UE', 'Unreal 5']] as const
/** The vehicles an export covers: the ticked ones, or the open one. */
export function exportSet(): LibraryEntry[] {
const lib = currentLibrary()
const ticked = lib?.entries.filter((e) => state.checked.has(e.id)) ?? []
if (ticked.length > 0) return ticked
const entry = currentEntry()
return entry ? [entry] : []
}
export function exportButton(): HTMLElement {
const n = exportSet().length
const main = el('button', { type: 'button', class: 'export-main', title: 'Ctrl+E' }, icon(ICON.export),
n > 1 ? `Export ${n} · ${TARGETS[exportTarget].short}` : `Export · ${TARGETS[exportTarget].short}`)
main.addEventListener('click', () => void runExport(exportTarget))
const more = el('button', { type: 'button', class: 'export-more', 'aria-label': 'Export options', 'aria-expanded': String(popover === 'export') }, icon(ICON.chevron, 12))
more.addEventListener('click', () => (popover === 'export' ? closePopover() : openExport()))
return el('div', { class: 'export-split' }, main, more)
}
export async function runExport(target: ExportTarget): Promise<void> {
const set = exportSet()
if (set.length === 0) { notify('Nothing to export'); return }
if (set.length === 1 && set[0]!.id === state.entryId) {
const name = slug(set[0]!.name)
if (target === 'spec') download(TARGETS.spec.file(name), JSON.stringify(effectiveSpec(), null, 2), 'application/json')
else if (vehicle) {
const buffer = await exportVehicleGlb(vehicle, { lod: target === 'glb-lods' ? 'all' : 0 })
download(TARGETS[target].file(name), buffer, 'model/gltf-binary')
notify(`Exported ${TARGETS[target].file(name)} · ${(buffer.byteLength / 1024).toFixed(0)} KB`)
return
}
notify(`Exported ${TARGETS[target].file(name)}`)
return
}
const files: { name: string; data: Uint8Array }[] = []
const used = new Set<string>()
for (const [i, entry] of set.entries()) {
notify(`Exporting ${i + 1} / ${set.length}…`)
await new Promise((r) => setTimeout(r))
let name = slug(entry.name)
for (let k = 2; used.has(name); k += 1) name = `${slug(entry.name)}-${k}`
used.add(name)
if (target === 'spec') {
files.push({ name: TARGETS.spec.file(name), data: new TextEncoder().encode(JSON.stringify(entry.spec, null, 2)) })
continue
}
const v = generateVehicle(entry.spec, { lods: target === 'glb-lods' ? [0, 1, 2] : [0] })
const buffer = await exportVehicleGlb(v, { lod: target === 'glb-lods' ? 'all' : 0 })
v.dispose()
files.push({ name: TARGETS[target].file(name), data: new Uint8Array(buffer) })
}
download(`${slug(currentLibrary()?.name ?? 'vehicles')}-${set.length}.zip`, zip(files), 'application/zip')
notify(`Exported ${set.length} vehicles`)
}
export function openExport(): void {
const set = exportSet()
const body = el('div', { class: 'pop-body' })
const paint = (): void => {
const targets = el('div', { class: 'targets', role: 'radiogroup', 'aria-label': 'Format' })
for (const id of Object.keys(TARGETS) as ExportTarget[]) {
const b = el('button', { type: 'button', role: 'radio', 'aria-checked': String(id === exportTarget), class: `target${id === exportTarget ? ' on' : ''}` },
el('span', { class: 'badge' }, TARGETS[id].badge), el('span', {}, TARGETS[id].label))
b.addEventListener('click', () => { exportTarget = id; remember('export-target', id); paint(); renderMenubar() })
targets.append(b)
}
for (const [badge, label] of PLANNED) {
targets.append(el('button', { type: 'button', class: 'target', disabled: true, title: 'Planned: one-click import into the engine' },
el('span', { class: 'badge' }, badge), el('span', {}, label), el('small', {}, 'planned')))
}
const names = set.map((e) => TARGETS[exportTarget].file(slug(e.name)))
const files = el('ul', { class: 'files' }, ...(set.length > 1
? [el('li', {}, el('code', {}, `${slug(currentLibrary()?.name ?? 'vehicles')}-${set.length}.zip`), el('span', {}, `${set.length} files`)), ...names.slice(0, 4).map((n) => el('li', { class: 'inner' }, el('code', {}, n))), ...(names.length > 4 ? [el('li', { class: 'inner' }, el('span', {}, `and ${names.length - 4} more`))] : [])]
: names.map((n) => el('li', {}, el('code', {}, n)))))
const go = el('button', { type: 'button', class: 'primary' }, icon(ICON.export), set.length > 1 ? `Export ${set.length} vehicles` : 'Export')
go.addEventListener('click', () => { closePopover(); void runExport(exportTarget) })
body.replaceChildren(
targets,
el('p', { class: 'hint' }, TARGETS[exportTarget].note),
files,
el('p', { class: 'hint' }, set.length > 1 ? 'Ticked vehicles in the garage are exported together.' : 'Tick vehicles in the garage to export several at once.'),
el('footer', {}, el('span', { class: 'hint' }, 'Saved to your downloads'), go),
)
}
paint()
showPopover('export', el('section', { class: 'popover export-pop', role: 'dialog', 'aria-label': 'Export' },
popHeader(set.length > 1 ? `Export ${set.length} vehicles` : `Export ${set[0]?.name ?? currentName()}`), body))
renderMenubar()
}

233
src/app/garage.ts Normal file
View file

@ -0,0 +1,233 @@
/** The garage: collections and their vehicles. */
import { styleLabel } from '../generator/index.ts'
import { type Library, type LibraryEntry, normalizeSpec, parseLibrary, toLibraryFile } from '../library/format.ts'
import { addEntry, createLibrary, duplicateEntry, moveEntry, removeEntry, renameEntry } from '../library/store.ts'
import { rebuild, vehicle } from './build.ts'
import { currentLibrary, notify, slug, state, store } from './context.ts'
import { future, past, save, saveTimer } from './editing.ts'
import { exportTarget, runExport, TARGETS } from './exporting.ts'
import { icon, ICON } from './icons.ts'
import { renderInspector } from './inspector.ts'
import { garageHost } from './layout.ts'
import { renderMenubar } from './menubar.ts'
import { closePopover, openNew, popover } from './popovers.ts'
import { remember } from './prefs.ts'
import { renderAll } from './render.ts'
import { renderStatus } from './status.ts'
import { dialog, download, el, pickFile, showMenu } from './ui.ts'
export async function commitLibrary(library: Library): Promise<void> {
state.libraries = state.libraries.map((l) => (l.id === library.id ? library : l))
if (!state.libraries.some((l) => l.id === library.id)) state.libraries.push(library)
await store.put(library)
renderGarage()
}
export function renderGarage(): void {
const lib = currentLibrary()
const picker = el('select', { 'aria-label': 'Collection' }) as HTMLSelectElement
for (const l of state.libraries) picker.append(el('option', { value: l.id, selected: l.id === state.libraryId }, `${l.name} · ${l.entries.length}`))
picker.addEventListener('change', () => {
state.libraryId = picker.value
state.checked.clear()
const first = currentLibrary()?.entries[0]
if (first) loadEntry(first)
else renderAll()
})
const add = el('button', { type: 'button', class: 'icon-button accent new-button', 'aria-label': 'New vehicle', title: 'New vehicle (N)' }, icon(ICON.plus, 12))
add.addEventListener('click', () => (popover === 'new' ? closePopover() : openNew()))
const more = el('button', { type: 'button', class: 'icon-button', 'aria-label': 'Collection menu' }, icon(ICON.more))
more.addEventListener('click', () => {
const r = more.getBoundingClientRect()
showMenu(r.left, r.bottom + 4, [
{ label: 'New collection…', run: () => void newLibrary() },
{ label: 'Rename collection…', run: () => void renameLibrary() },
{ label: 'Import collection or spec JSON…', run: () => void importLibrary() },
{ label: 'Export collection JSON', run: () => exportLibrary() },
'separator',
{ label: 'Tick all', run: () => { for (const e of lib?.entries ?? []) state.checked.add(e.id); renderGarage() } },
{ label: 'Untick all', run: () => { state.checked.clear(); renderGarage() } },
'separator',
{ label: 'Delete collection…', danger: true, disabled: state.libraries.length <= 1, run: () => deleteLibrary() },
])
})
const list = el('ul', { class: 'entries', 'aria-label': 'Vehicles' })
for (const [index, entry] of (lib?.entries ?? []).entries()) {
const on = entry.id === state.entryId
const tick = el('input', { type: 'checkbox', checked: state.checked.has(entry.id), 'aria-label': `Include ${entry.name} in export` }) as HTMLInputElement
tick.addEventListener('click', (e) => e.stopPropagation())
tick.addEventListener('change', () => {
if (tick.checked) state.checked.add(entry.id)
else state.checked.delete(entry.id)
renderMenubar()
})
const name = state.renaming === entry.id ? renameInput(entry) : el('span', { class: 'name' }, entry.name)
const row = el('li', { class: `entry${on ? ' on' : ''}`, draggable: 'true', title: `${styleLabel(entry.spec.style)} · seed ${entry.spec.seed}` },
tick, el('span', { class: 'dot', style: `background:${entry.spec.paint.primary}` }), name, el('span', { class: 'meta' }, styleLabel(entry.spec.style)))
row.addEventListener('click', () => { if (state.renaming !== entry.id) loadEntry(entry) })
row.addEventListener('dblclick', () => { state.renaming = entry.id; renderGarage() })
row.addEventListener('contextmenu', (e) => {
e.preventDefault()
showMenu(e.clientX, e.clientY, [
{ label: 'Open', run: () => loadEntry(entry) },
{ label: 'Rename', kbd: 'F2', run: () => { state.renaming = entry.id; renderGarage() } },
{ label: 'Duplicate', kbd: 'Ctrl+D', run: () => void duplicate(entry.id) },
{ label: `Export ${TARGETS[exportTarget].label}`, run: () => { loadEntry(entry); void runExport(exportTarget) } },
'separator',
{ label: 'Delete', kbd: 'Del', danger: true, run: () => void deleteEntry(entry.id) },
])
})
row.addEventListener('dragstart', (e) => { e.dataTransfer?.setData('text/plain', entry.id) })
row.addEventListener('dragover', (e) => { e.preventDefault(); row.classList.add('drop-over') })
row.addEventListener('dragleave', () => row.classList.remove('drop-over'))
row.addEventListener('drop', (e) => {
e.preventDefault()
row.classList.remove('drop-over')
const id = e.dataTransfer?.getData('text/plain')
if (id && lib) void commitLibrary(moveEntry(lib, id, index))
})
list.append(row)
}
garageHost.replaceChildren(
el('header', { class: 'area-head' }, el('b', {}, 'Garage'), add, more),
el('div', { class: 'lib-picker' }, picker),
lib && lib.entries.length > 0 ? list
: el('div', { class: 'empty' }, el('b', {}, 'No vehicles yet'), 'Press N for a new vehicle, or R to roll a random one.'),
)
renderStatus()
}
export function renameInput(entry: LibraryEntry): HTMLElement {
const input = el('input', { type: 'text', value: entry.name, 'aria-label': 'Vehicle name' }) as HTMLInputElement
const finish = (commit: boolean): void => {
if (state.renaming !== entry.id) return
state.renaming = ''
const lib = currentLibrary()
if (commit && lib) void commitLibrary(renameEntry(lib, entry.id, input.value))
else renderGarage()
renderInspector()
}
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') finish(true)
if (e.key === 'Escape') finish(false)
e.stopPropagation()
})
input.addEventListener('click', (e) => e.stopPropagation())
input.addEventListener('blur', () => finish(true))
setTimeout(() => { input.focus(); input.select() })
return input
}
export function loadEntry(entry: LibraryEntry): void {
if (state.dirty) void save()
const styleChanged = entry.spec.style !== state.spec.style
state.entryId = entry.id
state.spec = entry.spec
// The studio reopens on the vehicle that was open last, not the first in the garage.
remember('last-open', `${state.libraryId}/${entry.id}`)
state.blend = 0
state.dirty = false
past.length = 0
future.length = 0
rebuild(styleChanged || !vehicle)
renderAll()
}
export async function duplicate(id: string): Promise<void> {
const lib = currentLibrary()
if (!lib || !id) return
if (state.dirty) await save()
const [next, copy] = duplicateEntry(currentLibrary()!, id)
await commitLibrary(next)
if (copy) { loadEntry(copy); notify(`Duplicated as “${copy.name}”`) }
}
export async function deleteEntry(id: string): Promise<void> {
const lib = currentLibrary()
if (!lib || !id) return
const entry = lib.entries.find((e) => e.id === id)
const index = lib.entries.findIndex((e) => e.id === id)
const next = removeEntry(lib, id)
state.checked.delete(id)
clearTimeout(saveTimer)
state.dirty = false
await commitLibrary(next)
if (state.entryId === id) {
const neighbour = next.entries[Math.min(index, next.entries.length - 1)]
if (neighbour) loadEntry(neighbour)
else { state.entryId = ''; renderAll() }
}
if (entry) notify(`Deleted “${entry.name}”`)
}
export async function newLibrary(): Promise<void> {
const name = window.prompt('Collection name', `Garage ${state.libraries.length + 1}`)
if (!name) return
const lib = createLibrary(name.trim().slice(0, 80) || 'Garage')
state.libraryId = lib.id
state.entryId = ''
state.checked.clear()
await commitLibrary(lib)
renderAll()
}
export async function renameLibrary(): Promise<void> {
const lib = currentLibrary()
if (!lib) return
const name = window.prompt('Rename collection', lib.name)
if (!name) return
await commitLibrary({ ...lib, name: name.trim().slice(0, 80) || lib.name, updated: Date.now() })
}
export function deleteLibrary(): void {
const lib = currentLibrary()
if (!lib || state.libraries.length <= 1) return
dialog('Delete collection', el('p', {}, `Delete “${lib.name}” and its ${lib.entries.length} vehicles? Export it first if you may want it back.`), [
{ label: 'Cancel' },
{
label: 'Delete', primary: true, run: () => {
state.libraries = state.libraries.filter((l) => l.id !== lib.id)
void store.remove(lib.id)
state.libraryId = state.libraries[0]!.id
state.checked.clear()
const first = currentLibrary()?.entries[0]
if (first) loadEntry(first)
else { state.entryId = ''; renderAll() }
notify(`Deleted collection “${lib.name}”`)
},
},
])
}
export async function importLibrary(): Promise<void> {
const file = await pickFile('.json,application/json')
if (!file) return
try {
const raw = JSON.parse(await file.text()) as unknown
if (raw && typeof raw === 'object' && (raw as { format?: string }).format) {
const lib = parseLibrary(raw)
state.libraryId = lib.id
state.checked.clear()
await commitLibrary(lib)
const first = lib.entries[0]
if (first) loadEntry(first)
notify(`Imported “${lib.name}” · ${lib.entries.length} vehicles`)
return
}
// A single spec JSON: add it to the current collection instead.
const spec = normalizeSpec(raw)
const [next, entry] = addEntry(currentLibrary()!, file.name.replace(/\.json$/i, ''), spec)
await commitLibrary(next)
loadEntry(entry)
notify('Imported one vehicle')
} catch (error) {
dialog('Import failed', el('p', {}, String(error instanceof Error ? error.message : error)), [{ label: 'OK', primary: true }])
}
}
export function exportLibrary(): void {
const lib = currentLibrary()
if (!lib) return
download(`${slug(lib.name)}.vehicle-generator.json`, JSON.stringify(toLibraryFile(lib), null, 2), 'application/json')
}

28
src/app/icons.ts Normal file
View file

@ -0,0 +1,28 @@
/** Inline stroke icons. */
export const ICON = {
search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-3.5-3.5',
play: 'M7 4.5v15l12-7.5z',
export: 'M12 3v12M7 10l5 5 5-5M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2',
chevron: 'M6 9l6 6 6-6',
plus: 'M12 5v14M5 12h14',
more: 'M5 12h.01M12 12h.01M19 12h.01',
dice: 'M5 4h14a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1zM9 9h.01M15 15h.01M15 9h.01M9 15h.01',
camera: 'M3 8h3l2-3h8l2 3h3v11H3zM12 9.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7z',
close: 'M6 6l12 12M18 6L6 18',
}
export function icon(path: string, size = 14): SVGSVGElement {
const node = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
node.setAttribute('width', String(size))
node.setAttribute('height', String(size))
node.setAttribute('viewBox', '0 0 24 24')
node.setAttribute('fill', path === ICON.play ? 'currentColor' : 'none')
node.setAttribute('stroke', 'currentColor')
node.setAttribute('stroke-width', '2.2')
node.setAttribute('stroke-linecap', 'round')
node.setAttribute('stroke-linejoin', 'round')
node.setAttribute('aria-hidden', 'true')
const p = document.createElementNS('http://www.w3.org/2000/svg', 'path')
p.setAttribute('d', path)
node.append(p)
return node
}

175
src/app/inspector.ts Normal file
View file

@ -0,0 +1,175 @@
/** The properties editor: vertical tabs and their panels. */
import { BODY_STYLES, type BodyStyle, type OpenablePart, type PaintSpec, PALETTES, preset, styleLabel, type VehicleSpec } from '../generator/index.ts'
import { renameEntry } from '../library/store.ts'
import { rebuild, vehicle } from './build.ts'
import { currentLibrary, currentName, effectiveSpec, state, type Tab } from './context.ts'
import { cap, category, FINISHES, renderCustoms, RIMS } from './customs.ts'
import { checkpoint, edit, editPaint, markDirty, setStyle } from './editing.ts'
import { commitLibrary } from './garage.ts'
import { icon } from './icons.ts'
import { inspector } from './layout.ts'
import { renderAll } from './render.ts'
import { button, colour, el, section, segmented, select, slider, toggle } from './ui.ts'
export const TABS: readonly { id: Tab; label: string; icon: string }[] = [
{ id: 'vehicle', label: 'Vehicle', icon: 'M3 13l2-5a2 2 0 0 1 2-1h10a2 2 0 0 1 2 1l2 5v5h-3M3 13v5h3M3 13h18M6 18a2 2 0 1 0 4 0M14 18a2 2 0 1 0 4 0' },
{ id: 'body', label: 'Body and proportions', icon: 'M4 20V4h16v16zM4 12h16M12 4v16' },
{ id: 'part', label: 'Selected part', icon: 'M14 6l4 4-8 8H6v-4zM12 8l4 4' },
{ id: 'paint', label: 'Paint', icon: 'M12 3a9 9 0 1 0 0 18c1 0 2-1 2-2s-1-2 0-3 3 0 4-1a9 9 0 0 0-6-12zM7.5 11h.01M10 7.5h.01M15 7.5h.01' },
{ id: 'wheels', label: 'Wheels', icon: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM12 3v6M12 15v6M3 12h6M15 12h6' },
{ id: 'rig', label: 'Rig and lights', icon: 'M12 2v4M12 18v4M4.9 4.9l2.8 2.8M16.3 16.3l2.8 2.8M2 12h4M18 12h4M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z' },
]
export function renderInspector(): void {
const rail = el('nav', { class: 'rail', role: 'tablist', 'aria-orientation': 'vertical', 'aria-label': 'Properties' })
for (const t of TABS) {
const b = el('button', { type: 'button', role: 'tab', 'aria-selected': String(state.tab === t.id), 'aria-label': t.label, title: t.label, class: state.tab === t.id ? 'on' : '' }, icon(t.icon, 16))
b.addEventListener('click', () => { state.tab = t.id; renderInspector() })
rail.append(b)
}
const tab = TABS.find((t) => t.id === state.tab)!
const panels = state.tab === 'vehicle' ? vehiclePanel()
: state.tab === 'body' ? bodyPanel()
: state.tab === 'part' ? category().panel()
: state.tab === 'paint' ? paintPanel()
: state.tab === 'wheels' ? wheelsPanel()
: rigPanel()
const scroll = inspector.querySelector('.panel-body')?.scrollTop ?? 0
const body = el('div', { class: 'panel-body' }, ...panels,
el('p', { class: 'hint foot' }, 'Drag a field to scrub (Shift: fine), click to type, ↺ resets. Ctrl+Z undoes anything.'))
inspector.replaceChildren(rail, el('div', { class: 'props' },
el('header', { class: 'area-head' }, el('b', {}, state.tab === 'part' ? category().label : tab.label), el('span', { class: 'meta' }, currentName())),
body))
body.scrollTop = scroll
}
export function vehiclePanel(): HTMLElement[] {
const s = state.spec
const nameInput = el('input', { type: 'text', value: currentName(), 'aria-label': 'Name' }) as HTMLInputElement
nameInput.addEventListener('change', () => {
const lib = currentLibrary()
if (lib && state.entryId) void commitLibrary(renameEntry(lib, state.entryId, nameInput.value)).then(() => renderInspector())
})
const seedInput = el('input', { type: 'number', value: s.seed, min: 0, step: 1, 'aria-label': 'Seed' }) as HTMLInputElement
seedInput.addEventListener('change', () => edit((prev) => ({ ...prev, seed: Math.max(0, Math.floor(Number(seedInput.value) || 0)) })))
return [
section('Vehicle',
el('label', { class: 'field' }, el('span', { class: 'field-label' }, 'Name'), nameInput),
select('Style', BODY_STYLES.map((st) => ({ value: st, label: styleLabel(st) })), s.style, (v) => { setStyle(v as BodyStyle); renderAll() }),
el('label', { class: 'field' }, el('span', { class: 'field-label' }, 'Seed'), seedInput),
toggle('Randomise picks the style too', state.randomStyle, (v) => { state.randomStyle = v })),
section('Blend',
select('With', BODY_STYLES.map((st) => ({ value: st, label: styleLabel(st) })), state.blendWith, (v) => { state.blendWith = v as BodyStyle; rebuild() }),
slider({ label: 'Amount', min: 0, max: 1, step: 0.01, value: state.blend, defaultValue: 0, onInput: (v) => { checkpoint(); state.blend = v; markDirty(); rebuild() } }),
button('Bake blend into spec', () => { checkpoint(); state.spec = effectiveSpec(); state.blend = 0; markDirty(); rebuild(); renderInspector() }, 'wide')),
]
}
export function bodyPanel(): HTMLElement[] {
const s = state.spec
const stock = preset(s.style, s.seed)
const num = (label: string, get: (sp: VehicleSpec) => number, set: (sp: VehicleSpec, v: number) => VehicleSpec, min: number, max: number, step: number, unit = 'm'): HTMLElement =>
slider({ label, min, max, step, value: get(s), unit, defaultValue: get(stock), onInput: (v) => edit((prev) => set(prev, v)) })
const b = (key: keyof VehicleSpec['body'], label: string, min: number, max: number, step: number, unit = 'm'): HTMLElement =>
num(label, (sp) => sp.body[key] as number, (sp, v) => ({ ...sp, body: { ...sp.body, [key]: v } }), min, max, step, unit)
const c = (key: 'wheelbase' | 'frontOverhang' | 'track' | 'rideHeight', label: string, min: number, max: number, step: number, unit = 'm'): HTMLElement =>
num(label, (sp) => sp.chassis[key], (sp, v) => ({ ...sp, chassis: { ...sp.chassis, [key]: v } }), min, max, step, unit)
return [
section('Proportions',
b('length', 'Length', 2.4, 7, 0.01), b('width', 'Width', 1.3, 2.5, 0.01),
b('roofHeight', 'Roof', 0.8, 3.2, 0.01), b('hoodHeight', 'Bonnet', 0.5, 1.8, 0.01), b('noseHeight', 'Nose', 0.4, 1.6, 0.01),
b('deckHeight', 'Deck', 0.5, 3, 0.01), b('tailHeight', 'Tail', 0.5, 3, 0.01), b('sill', 'Sill', 0.08, 0.8, 0.005)),
section('Profile',
b('cowl', 'Windshield base', 0.4, 0.97, 0.005, ''), b('roofFront', 'Roof front', 0.3, 0.95, 0.005, ''),
b('roofRear', 'Roof rear', 0.01, 0.8, 0.005, ''), b('deck', 'Rear window base', 0.005, 0.7, 0.005, ''),
b('noseRound', 'Nose radius', 0.02, 0.6, 0.01), b('tailRound', 'Tail radius', 0.02, 0.6, 0.01),
b('tumblehome', 'Tumblehome', 0, 0.45, 0.01, ''), b('sideBulge', 'Side bulge', 0, 1, 0.01, ''),
b('roofCrown', 'Roof crown', 0, 0.15, 0.005), b('flare', 'Arch flare', 0, 0.15, 0.005),
select('Doors per side', [{ value: '0', label: 'None' }, { value: '1', label: 'One' }, { value: '2', label: 'Two' }], String(s.body.doors),
(v) => edit((sp) => ({ ...sp, body: { ...sp.body, doors: Number(v) as 0 | 1 | 2 } }))),
select('Bumpers', [{ value: 'painted', label: 'Painted' }, { value: 'black', label: 'Black' }, { value: 'chrome', label: 'Chrome' }], s.body.bumpers,
(v) => edit((sp) => ({ ...sp, body: { ...sp.body, bumpers: v as VehicleSpec['body']['bumpers'] } })))),
section('Chassis',
c('wheelbase', 'Wheelbase', 1.8, 5, 0.01), c('frontOverhang', 'Front overhang', 0.4, 1.6, 0.01),
c('track', 'Track', 0.7, 1.05, 0.005, ''), c('rideHeight', 'Ride height', -0.08, 0.3, 0.005),
select('Drive', [{ value: 'fwd', label: 'Front' }, { value: 'rwd', label: 'Rear' }, { value: 'awd', label: 'All' }], s.chassis.drive,
(v) => edit((sp) => ({ ...sp, chassis: { ...sp.chassis, drive: v as VehicleSpec['chassis']['drive'] } })))),
]
}
export function wheelsPanel(): HTMLElement[] {
const s = state.spec
const stock = preset(s.style, s.seed)
const w = (key: 'radius' | 'width' | 'rimRatio' | 'offset' | 'camber' | 'spokes', label: string, min: number, max: number, step: number, unit = 'm'): HTMLElement =>
slider({ label, min, max, step, value: s.wheels[key], unit, defaultValue: stock.wheels[key], onInput: (v) => edit((prev) => ({ ...prev, wheels: { ...prev.wheels, [key]: v } })) })
return [
section('Wheels',
select('Rim', RIMS.map((r) => ({ value: r, label: cap(r) })), s.wheels.rim,
(v) => { edit((sp) => ({ ...sp, wheels: { ...sp.wheels, rim: v as VehicleSpec['wheels']['rim'] } })); renderCustoms() }),
w('spokes', 'Spokes', 3, 12, 1, ''), w('radius', 'Radius', 0.22, 0.6, 0.005), w('width', 'Width', 0.12, 0.4, 0.005),
w('rimRatio', 'Rim / tyre', 0.45, 0.8, 0.01, ''), w('offset', 'Offset', -0.03, 0.1, 0.005), w('camber', 'Camber', -0.15, 0.05, 0.005, 'rad')),
section('Tyres',
select('Tread', [{ value: 'road', label: 'Road' }, { value: 'sport', label: 'Sport' }, { value: 'offroad', label: 'Off-road' }], s.wheels.tread,
(v) => edit((sp) => ({ ...sp, wheels: { ...sp.wheels, tread: v as VehicleSpec['wheels']['tread'] } })))),
]
}
export function paintPanel(): HTMLElement[] {
const p = state.spec.paint
const palettes = PALETTES.map((palette) => {
const row = el('div', { class: 'swatches' })
for (const hex of palette.colors) {
const sw = el('button', { type: 'button', class: `swatch${p.primary === hex ? ' on' : ''}`, title: hex, 'aria-label': `${palette.label} ${hex}`, style: `background:${hex}` })
sw.addEventListener('click', () => { editPaint({ primary: hex }); renderInspector() })
sw.addEventListener('contextmenu', (e) => { e.preventDefault(); editPaint({ secondary: hex }); renderInspector() })
row.append(sw)
}
return el('div', {}, el('div', { class: 'palette-name' }, palette.label), row)
})
return [
section('Colours',
colour('Primary', p.primary, (v) => editPaint({ primary: v })),
colour('Secondary', p.secondary, (v) => editPaint({ secondary: v })),
select('Two-tone', [{ value: 'none', label: 'None' }, { value: 'roof', label: 'Roof' }, { value: 'lower', label: 'Lower body' }, { value: 'upper', label: 'Upper body' }], p.twoTone,
(v) => editPaint({ twoTone: v as PaintSpec['twoTone'] }, true))),
section('Finish',
segmented(FINISHES.map((f) => ({ value: f, label: cap(f) })), p.finish, (v) => { editPaint({ finish: v as PaintSpec['finish'] }); renderCustoms() })),
section('Palettes', el('p', { class: 'hint' }, 'Click: primary · right-click: secondary'), ...palettes),
section('Livery',
select('Pattern', [{ value: 'none', label: 'None' }, { value: 'stripes', label: 'Twin stripes' }, { value: 'side-stripe', label: 'Side stripe' }, { value: 'rally', label: 'Rally' }], p.livery,
(v) => editPaint({ livery: v as PaintSpec['livery'] }, true)),
colour('Stripe', p.stripe, (v) => editPaint({ stripe: v }))),
section('Details',
colour('Rims', p.rim, (v) => editPaint({ rim: v })),
segmented(['painted', 'satin', 'chrome'].map((f) => ({ value: f, label: cap(f) })), p.rimFinish, (v) => editPaint({ rimFinish: v as PaintSpec['rimFinish'] })),
colour('Trim', p.trim, (v) => editPaint({ trim: v })),
colour('Calipers', p.caliper, (v) => editPaint({ caliper: v })),
slider({ label: 'Glass tint', min: 0, max: 1, step: 0.01, value: p.tint, onInput: (v) => editPaint({ tint: v }) })),
]
}
export function rigPanel(): HTMLElement[] {
if (!vehicle) return [el('p', { class: 'hint' }, 'Building…')]
const rig = vehicle.rig
const opens = rig.openables.map((part) => slider({
label: partLabel(part), min: 0, max: 1, step: 0.01, value: state.open[part] ?? 0, defaultValue: 0,
onInput: (v) => { state.open[part] = v; rig.open(part, v) },
}))
return [
section('Steering',
slider({ label: 'Steer', min: -0.6, max: 0.6, step: 0.01, value: state.steer, unit: 'rad', defaultValue: 0, onInput: (v) => { state.steer = v; rig.setSteer(v) } }),
toggle('Roll the wheels', state.drive, (v) => { state.drive = v }, 'Space'),
slider({ label: 'Speed', min: -10, max: 30, step: 0.5, value: state.speed || 8, unit: 'm/s', onInput: (v) => { state.speed = v } })),
section('Lights',
toggle('Headlights', state.head, (v) => { state.head = v; rig.setHeadlights(v) }, 'L'),
toggle('Brake lights', state.brake, (v) => { state.brake = v; rig.setBrake(v) }, 'B')),
section(`Opening panels · ${rig.openables.length}`,
...(opens.length ? opens : [el('p', { class: 'hint' }, 'Nothing on this body opens.')])),
section('Wheels',
el('div', { class: 'mono-list' },
...vehicle.wheels.map((w) => el('div', {}, `${w.id} r ${w.radius.toFixed(3)} ${w.steer ? 'steer ' : ''}${w.drive ? 'drive' : ''}`)))),
]
}
export const partLabel = (part: OpenablePart): string => ({
doorFL: 'Door front-left', doorFR: 'Door front-right', doorRL: 'Door rear-left', doorRR: 'Door rear-right', hood: 'Bonnet', trunk: 'Boot / tailgate',
})[part]

75
src/app/keys.ts Normal file
View file

@ -0,0 +1,75 @@
/** Keyboard shortcuts. */
import { vehicle } from './build.ts'
import { notify, stage, state } from './context.ts'
import { CATEGORIES, category, fitVariant, pickCategory } from './customs.ts'
import { nextSeed, randomise, redo, save, undo } from './editing.ts'
import { exportTarget, openExport, runExport } from './exporting.ts'
import { deleteEntry, duplicate, renderGarage } from './garage.ts'
import { renderInspector } from './inspector.ts'
import { showShortcuts } from './menubar.ts'
import { openPalette } from './palette.ts'
import { drive, enterDrive, exitDrive, togglePerf } from './play.ts'
import { closePopover, openNew, popover } from './popovers.ts'
import { setCollider, setLod, setWireframe } from './toolbar.ts'
import { closeMenu } from './ui.ts'
window.addEventListener('keydown', (e) => {
if (drive?.active) {
if (e.key === 'Escape') { e.preventDefault(); exitDrive() }
if (e.key === 'c' || e.key === 'C') void enterDrive('circuit')
if (e.key === 't' || e.key === 'T') void enterDrive('traffic')
if (e.key === 'h' || e.key === 'H') togglePerf()
return
}
const target = e.target instanceof HTMLElement ? e.target : document.body
if (target.tagName === 'INPUT' && (target as HTMLInputElement).type !== 'checkbox') return
if (target.tagName === 'SELECT' || target.closest('.backdrop')) return
const ctrl = e.ctrlKey || e.metaKey
const key = e.key
if (key === 'F3') { e.preventDefault(); openPalette(); return }
if (key === 'Escape' && popover) { closePopover(); return }
if (ctrl && key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) redo(); else undo(); return }
if (ctrl && key.toLowerCase() === 'y') { e.preventDefault(); redo(); return }
if (ctrl && key.toLowerCase() === 's') { e.preventDefault(); void save().then(() => notify('Saved')); return }
if (ctrl && key.toLowerCase() === 'e') { e.preventDefault(); if (e.shiftKey) openExport(); else void runExport(exportTarget); return }
if (ctrl && key.toLowerCase() === 'd') { e.preventDefault(); void duplicate(state.entryId); return }
if (ctrl) return
// Arrow keys belong to a focused control (a number field, a list) when there is one.
const ownsArrows = target.closest('[role="slider"], .pills, select')
switch (key) {
case 'r': randomise(state.randomStyle ? undefined : state.spec.style); break
case 'R': randomise(); break
case '.': nextSeed(); break
case 'n': openNew(); break
case 'w': setWireframe(!stage.wireframe); break
case 'c': setCollider(!stage.showCollider); break
case 'g': stage.grid = !stage.grid; break
case 'o': stage.controls.autoRotate = !stage.controls.autoRotate; break
case 'f': stage.frame(); break
case '`': setLod('auto'); break
case '1': setLod(0); break
case '2': setLod(1); break
case '3': setLod(2); break
case 'l': state.head = !state.head; vehicle?.rig.setHeadlights(state.head); if (state.tab === 'rig') renderInspector(); break
case 'b': state.brake = !state.brake; vehicle?.rig.setBrake(state.brake); if (state.tab === 'rig') renderInspector(); break
case 'ArrowUp': case 'ArrowDown': {
if (ownsArrows) return
e.preventDefault()
const i = CATEGORIES.indexOf(category()) + (key === 'ArrowDown' ? 1 : -1)
pickCategory(CATEGORIES[(i + CATEGORIES.length) % CATEGORIES.length]!.id)
break
}
case 'ArrowLeft': case 'ArrowRight':
if (ownsArrows) return
e.preventDefault()
fitVariant(category().current() + (key === 'ArrowRight' ? 1 : -1))
break
case ' ': e.preventDefault(); state.drive = !state.drive; if (state.tab === 'rig') renderInspector(); break
case 'F2': if (state.entryId) { e.preventDefault(); state.renaming = state.entryId; renderGarage() } break
case 'Delete': if (state.entryId) void deleteEntry(state.entryId); break
case '?': showShortcuts(); break
case 'p': void enterDrive('circuit'); break
default: return
}
closeMenu()
})

25
src/app/layout.ts Normal file
View file

@ -0,0 +1,25 @@
/** The window skeleton: one element per area, created once. */
import { el } from './ui.ts'
export const app = document.querySelector<HTMLDivElement>('#app')!
export const menubar = el('header', { class: 'menubar' })
export const left = el('aside', { class: 'left' })
export const toolbar = el('div', { class: 'viewbar', role: 'toolbar', 'aria-label': 'Viewport' })
export const monitor = el('div', { class: 'monitor' })
export const shelf = el('section', { class: 'shelf' })
export const centre = el('main', { class: 'centre' }, toolbar, monitor, shelf)
export const inspector = el('aside', { class: 'inspector' })
export const statusbar = el('footer', { class: 'statusbar' })
export const studio = el('div', { class: 'studio' }, menubar, left, centre, inspector, statusbar)
app.append(studio)
export const canvas = el('canvas', {})
monitor.append(canvas)
export const popHost = el('div', { class: 'popover-host' })
studio.append(popHost)
export const customsList = el('ul', { class: 'customs', 'aria-label': 'Parts' })
export const garageHost = el('div', { class: 'garage' })
left.append(garageHost,
el('header', { class: 'area-head' }, el('b', {}, 'Customs'), el('span', { class: 'meta' }, '↑ ↓ to move')),
customsList)

110
src/app/main.ts Normal file
View file

@ -0,0 +1,110 @@
/*
* The studio: one window, laid out like a 3D editor. A top bar (menus,
* command search, Drive and the Export button), the garage and the customs
* categories on the left, the viewport with its variant shelf in the middle,
* a properties editor with vertical tabs on the right, a status bar below.
* Every edit saves itself and can be undone. This file only boots it.
*/
import './devlog.ts'
import './studio.css'
import './layout.ts'
import './keys.ts'
import { BODY_STYLES, preset, styleLabel } from '../generator/index.ts'
import { addEntry, createLibrary } from '../library/store.ts'
import { rebuild, vehicle } from './build.ts'
import { currentLibrary, setStage, stage, state, store } from './context.ts'
import { category } from './customs.ts'
import { canvas, menubar, monitor } from './layout.ts'
import { markWindowReady, renderMenubar } from './menubar.ts'
import { drive, perfHud, perfOn, resize, speedo } from './play.ts'
import { remembered } from './prefs.ts'
import { renderAll } from './render.ts'
import { restoreSession } from './resume.ts'
import './showcase.ts'
import { Stage } from './scene.ts'
import { renderStatus } from './status.ts'
import { el } from './ui.ts'
import { mountWindowControls } from './windowbar.ts'
try {
setStage(await Stage.create(canvas))
} catch (error) {
monitor.append(el('div', { class: 'fatal' }, el('b', {}, 'The renderer could not start.'), el('span', {}, String(error))))
throw error
}
/* ------------------------------------------------------------------ garage */
await store.open()
state.libraries = await store.all()
if (state.libraries.length === 0) {
// First run: a starter garage with one of every body style.
let lib = createLibrary('Starter garage')
for (const style of BODY_STYLES) [lib] = addEntry(lib, styleLabel(style), preset(style))
state.libraries = [lib]
await store.put(lib)
} else {
// Starter entries never saved over (updated === created) are still the
// preset they were seeded from; refresh them so a preset change reaches an
// old garage instead of the studio showing the frozen copy.
for (const lib of state.libraries) {
if (lib.name !== 'Starter garage') continue
const stale = lib.entries.filter((e) => e.updated === e.created && e.name === styleLabel(e.spec.style) && JSON.stringify(e.spec) !== JSON.stringify(preset(e.spec.style)))
if (stale.length === 0) continue
const fresh = { ...lib, entries: lib.entries.map((e) => (stale.includes(e) ? { ...e, spec: preset(e.spec.style) } : e)) }
state.libraries = state.libraries.map((l) => (l.id === lib.id ? fresh : l))
await store.put(fresh)
}
}
// Open the vehicle that was open last; the garage's first one only on a first run.
const [lastLibrary, lastEntry] = remembered('last-open', '').split('/')
const reopened = state.libraries.find((l) => l.id === lastLibrary)
state.libraryId = (reopened ?? state.libraries[0]!).id
const first = currentLibrary()?.entries.find((e) => e.id === lastEntry) ?? currentLibrary()?.entries[0]
if (first) {
state.entryId = first.id
state.spec = first.spec
}
// In development a reload (a Vite full reload, a cage rebuilt by
// `cages:watch`) comes back where it left off: the same entry, tab, part and
// camera, and unsaved edits. A clean entry is re-read so it shows the current preset.
restoreSession()
renderMenubar()
await mountWindowControls(menubar)
markWindowReady()
renderAll()
/* ------------------------------------------------------------- render loop */
new ResizeObserver(resize).observe(monitor)
resize()
rebuild(true)
stage.look(category().view)
let last = performance.now()
let prevFrame = performance.now()
let lodShown: number | null = null
stage.renderer.setAnimationLoop(() => {
const now = performance.now()
const dt = Math.min(0.1, (now - last) / 1000)
last = now
if (drive?.active) {
drive.sample(now - prevFrame)
prevFrame = now
drive.update(dt)
drive.render()
speedo.textContent = `${Math.round(drive.speed * 3.6)} km/h`
if (perfOn) {
const s = drive.stats
perfHud.textContent = `${s.median.toFixed(1)} ms median · ${s.p95.toFixed(1)} ms p95 · ${s.fps.toFixed(0)} fps\nready in ${drive.readyMs.toFixed(0)} ms (${Object.entries(drive.timings).map(([k, v]) => `${k} ${v}`).join(', ')})`
}
return
}
prevFrame = now
if (vehicle && state.drive) vehicle.rig.update(dt, state.speed || 8)
stage.render()
const shown = stage.visibleLevel()
if (shown !== lodShown) { lodShown = shown; renderStatus() }
})

110
src/app/menubar.ts Normal file
View file

@ -0,0 +1,110 @@
/** The top bar: menus, command search, Drive and the Export button. */
import { showAbout } from './about.ts'
import mark from './assets/mark.png'
import { stage, state } from './context.ts'
import { edit, future, nextSeed, past, randomise, redo, resetToPreset, undo } from './editing.ts'
import { exportButton, exportTarget, openExport, runExport, TARGETS } from './exporting.ts'
import { deleteEntry, deleteLibrary, duplicate, exportLibrary, importLibrary, newLibrary, renameLibrary, renderGarage } from './garage.ts'
import { icon, ICON } from './icons.ts'
import { menubar } from './layout.ts'
import { openPalette } from './palette.ts'
import { enterDrive } from './play.ts'
import { openNew } from './popovers.ts'
import { renderAll } from './render.ts'
import { setCollider, setLod, setWireframe, viewLabel } from './toolbar.ts'
import { dialog, el, type MenuEntry, showMenu } from './ui.ts'
import { decorateMenubar, isDesktop, quitApp } from './windowbar.ts'
export function menus(): [string, () => MenuEntry[]][] {
return [
['File', () => [
{ label: 'New vehicle…', kbd: 'N', run: () => openNew() },
{ label: 'Duplicate vehicle', kbd: 'Ctrl+D', disabled: !state.entryId, run: () => void duplicate(state.entryId) },
'separator',
{ label: 'Export…', kbd: 'Ctrl+Shift+E', run: () => openExport() },
{ label: `Export again (${TARGETS[exportTarget].label})`, kbd: 'Ctrl+E', run: () => void runExport(exportTarget) },
'separator',
{ label: 'New collection…', run: () => void newLibrary() },
{ label: 'Rename collection…', run: () => void renameLibrary() },
{ label: 'Import collection or spec JSON…', run: () => void importLibrary() },
{ label: 'Export collection JSON', run: () => exportLibrary() },
'separator',
{ label: 'Delete collection…', danger: true, disabled: state.libraries.length <= 1, run: () => deleteLibrary() },
...(isDesktop() ? ['separator' as const, { label: 'Quit', kbd: 'Alt+F4', run: () => void quitApp() }] : []),
]],
['Edit', () => [
{ label: 'Undo', kbd: 'Ctrl+Z', disabled: past.length === 0, run: () => undo() },
{ label: 'Redo', kbd: 'Ctrl+Shift+Z', disabled: future.length === 0, run: () => redo() },
'separator',
{ label: 'Rename vehicle', kbd: 'F2', disabled: !state.entryId, run: () => { state.renaming = state.entryId; renderGarage() } },
{ label: 'Delete vehicle', kbd: 'Del', danger: true, disabled: !state.entryId, run: () => void deleteEntry(state.entryId) },
]],
['Vehicle', () => [
{ label: 'Randomise', kbd: 'R', run: () => randomise(state.randomStyle ? undefined : state.spec.style) },
{ label: 'Randomise any style', kbd: 'Shift+R', run: () => randomise() },
{ label: 'Next seed', kbd: '.', run: () => nextSeed() },
'separator',
{ label: 'Reset to preset', run: () => resetToPreset() },
{ label: 'Remove all mods', run: () => { edit((s) => ({ ...s, mods: [] })); renderAll() } },
'separator',
{ label: 'Drive on the circuit', kbd: 'P', run: () => void enterDrive('circuit') },
{ label: 'Drive in traffic', run: () => void enterDrive('traffic') },
]],
['View', () => [
{ label: 'Wireframe', kbd: 'W', checked: stage.wireframe, run: () => setWireframe(!stage.wireframe) },
{ label: 'Collider hull', kbd: 'C', checked: stage.showCollider, run: () => setCollider(!stage.showCollider) },
{ label: 'Ground grid', kbd: 'G', checked: stage.grid, run: () => { stage.grid = !stage.grid } },
{ label: 'Auto-rotate', kbd: 'O', checked: stage.controls.autoRotate, run: () => { stage.controls.autoRotate = !stage.controls.autoRotate } },
'separator',
...(['auto', 0, 1, 2] as const).map((mode, i): MenuEntry => ({
label: mode === 'auto' ? 'LOD: automatic' : `LOD${mode}`, kbd: String(i === 0 ? '`' : i), checked: stage.lodMode === mode, run: () => setLod(mode),
})),
'separator',
{ label: 'Frame vehicle', kbd: 'F', run: () => stage.frame() },
...(['side', 'front34', 'rear34', 'front', 'rear', 'top'] as const).map((v): MenuEntry => ({ label: `Camera: ${viewLabel(v)}`, run: () => stage.look(v) })),
]],
['Help', () => [
{ label: 'Search commands', kbd: 'F3', run: () => openPalette() },
{ label: 'Keyboard shortcuts', kbd: '?', run: () => showShortcuts() },
'separator',
{ label: 'About Vehicle Generator', run: () => showAbout() },
]],
]
}
export function renderMenubar(): void {
menubar.replaceChildren(el('div', { class: 'logo' }, el('img', { src: mark, alt: '', width: 22, height: 22 }), el('b', {}, 'VEHICLE', el('em', {}, 'GEN'))))
for (const [label, entries] of menus()) {
const b = el('button', { type: 'button', class: 'menu-button' }, label)
b.addEventListener('click', () => {
const r = b.getBoundingClientRect()
b.classList.add('open')
showMenu(r.left, r.bottom + 4, entries())
const off = (): void => { b.classList.remove('open'); window.removeEventListener('pointerdown', off, true) }
setTimeout(() => window.addEventListener('pointerdown', off, true))
})
menubar.append(b)
}
const search = el('button', { type: 'button', class: 'search' }, icon(ICON.search), el('span', {}, 'Search anything…'), el('kbd', {}, 'F3'))
search.addEventListener('click', () => openPalette())
const drive = el('button', { type: 'button', class: 'ghost' }, icon(ICON.play, 12), 'Drive')
drive.addEventListener('click', () => void enterDrive('circuit'))
menubar.append(el('div', { class: 'spacer' }), search, el('div', { class: 'spacer' }), drive, exportButton())
// On the desktop the bar is also the title bar: put its drag layer and caption buttons back.
if (windowReady) decorateMenubar(menubar)
}
export let windowReady = false
export function showShortcuts(): void {
const rows: [string, string][] = [
['Search anything', 'F3'], ['New vehicle', 'N'], ['Randomise (same style)', 'R'], ['Randomise any style', 'Shift+R'],
['Next seed', '.'], ['Undo / redo', 'Ctrl+Z / Ctrl+Shift+Z'], ['Duplicate', 'Ctrl+D'], ['Rename / delete', 'F2 / Del'],
['Export again', 'Ctrl+E'], ['Export options', 'Ctrl+Shift+E'], ['Part up / down', '↑ ↓'], ['Variant', '← →'],
['Wireframe / collider / grid', 'W / C / G'], ['Auto-rotate', 'O'], ['LOD auto / 0 / 1 / 2', '` 1 2 3'], ['Frame vehicle', 'F'],
['Headlights / brake', 'L / B'], ['Roll the wheels', 'Space'], ['Drive', 'P'],
]
dialog('Keyboard shortcuts', el('div', { class: 'shortcuts' }, ...rows.map(([a, k]) => el('div', {}, el('span', {}, a), el('kbd', {}, k)))), [{ label: 'Close', primary: true }])
}
/** The desktop title bar is mounted: later rebuilds of the bar decorate it again. */
export function markWindowReady(): void { windowReady = true }

44
src/app/palette.ts Normal file
View file

@ -0,0 +1,44 @@
/** Command search (F3). */
import { BODY_STYLES, styleLabel } from '../generator/index.ts'
import { currentLibrary } from './context.ts'
import { CATEGORIES, pickCategory } from './customs.ts'
import { setStyle } from './editing.ts'
import { loadEntry } from './garage.ts'
import { menus } from './menubar.ts'
import { renderAll } from './render.ts'
import { dialog, el } from './ui.ts'
export function openPalette(): void {
const commands: { label: string; kbd?: string; run: () => void }[] = []
for (const [menu, entries] of menus()) {
for (const e of entries()) if (e !== 'separator' && !e.disabled && e.run) commands.push({ label: `${menu}: ${e.label}`, kbd: e.kbd, run: e.run })
}
for (const c of CATEGORIES) commands.push({ label: `Part: ${c.label}`, run: () => pickCategory(c.id) })
for (const s of BODY_STYLES) commands.push({ label: `Body style: ${styleLabel(s)}`, run: () => { setStyle(s); renderAll() } })
for (const e of currentLibrary()?.entries ?? []) commands.push({ label: `Open: ${e.name}`, run: () => loadEntry(e) })
const input = el('input', { type: 'text', placeholder: 'Type a command, a part, a style or a vehicle', 'aria-label': 'Search commands' }) as HTMLInputElement
const list = el('ul', { class: 'palette-list', role: 'listbox' })
let shown: typeof commands = []
let active = 0
const close = dialog('Search', el('div', { class: 'palette' }, input, list), [])
const paint = (): void => {
const q = input.value.trim().toLowerCase()
shown = commands.filter((c) => q.split(/\s+/).every((w) => c.label.toLowerCase().includes(w))).slice(0, 12)
active = Math.min(active, Math.max(0, shown.length - 1))
list.replaceChildren(...shown.map((c, i) => {
const row = el('li', { role: 'option', 'aria-selected': String(i === active), class: i === active ? 'on' : '' }, el('span', {}, c.label), c.kbd ? el('kbd', {}, c.kbd) : el('span', {}))
row.addEventListener('click', () => { close(); c.run() })
return row
}))
}
input.addEventListener('input', () => { active = 0; paint() })
input.addEventListener('keydown', (e) => {
e.stopPropagation()
if (e.key === 'ArrowDown') { active = Math.min(shown.length - 1, active + 1); paint(); e.preventDefault() }
if (e.key === 'ArrowUp') { active = Math.max(0, active - 1); paint(); e.preventDefault() }
if (e.key === 'Enter' && shown[active]) { close(); shown[active]!.run() }
if (e.key === 'Escape') close()
})
paint()
setTimeout(() => input.focus())
}

79
src/app/play.ts Normal file
View file

@ -0,0 +1,79 @@
/** Play mode: driving the vehicle on the circuit or in traffic. */
import { effectiveSpec, notify, stage } from './context.ts'
import { Drive, type DriveWorld } from './drive.ts'
import { canvas, monitor, studio } from './layout.ts'
import { closePopover } from './popovers.ts'
import { button, dialog, el, segmented } from './ui.ts'
export let drive: Drive | null = null
export const driveHud = el('div', { class: 'drive-hud', hidden: true })
monitor.append(driveHud)
export const speedo = el('div', { class: 'speedo' })
monitor.append(speedo)
speedo.hidden = true
export function renderDriveHud(world: DriveWorld): void {
driveHud.replaceChildren(
segmented<DriveWorld>([{ value: 'circuit', label: 'Circuit' }, { value: 'traffic', label: 'Traffic' }], world, (w) => void enterDrive(w)),
el('span', { class: 'drive-note' }, 'drag to orbit · release to follow'),
button('Exit Esc', () => exitDrive()),
)
}
// Frame-time readout for Play, toggled with H. Off by default.
export const perfHud = el('div', { class: 'perf-hud' })
perfHud.hidden = true
monitor.append(perfHud)
export let perfOn = false
export let loading: AbortController | null = null
export async function enterDrive(world: DriveWorld): Promise<void> {
loading?.abort()
closePopover()
const abort = new AbortController()
loading = abort
drive ??= new Drive(stage.renderer, canvas, stage.scene.environment)
// A loading screen with real progress: the world, the cars, the shaders.
const bar = el('progress', { max: '1', value: '0', style: 'width:100%' }) as HTMLProgressElement
const label = el('div', { class: 'drive-note' }, 'Starting')
const close = dialog(world === 'circuit' ? 'Loading the circuit' : 'Loading traffic', el('div', { style: 'display:grid;gap:8px;min-width:280px' }, bar, label), [
{ label: 'Cancel', run: () => abort.abort() },
])
// Switch to the driving layout first and size the canvas for it, so the
// warm-up frame renders at the final size; resizing after it rebuilds the
// post-processing targets and stalls the first second of driving.
stage.controls.enabled = false
studio.classList.add('driving')
resize()
const ok = await drive.prepare(effectiveSpec(), world, (p) => { bar.value = p.done; label.textContent = p.label }, abort.signal)
close()
if (loading === abort) loading = null
if (!ok || abort.signal.aborted) {
if (!loading) exitDrive()
return
}
driveHud.hidden = false
speedo.hidden = false
renderDriveHud(world)
notify(`${world === 'circuit' ? 'Circuit' : 'Traffic'} ready in ${(drive.readyMs / 1000).toFixed(1)} s · H shows frame times`)
}
export function exitDrive(): void {
loading?.abort()
drive?.stop()
perfHud.hidden = true
stage.controls.enabled = true
studio.classList.remove('driving')
driveHud.hidden = true
speedo.hidden = true
requestAnimationFrame(() => resize())
}
export const resize = (): void => {
stage.resize()
drive?.resize(canvas.clientWidth, canvas.clientHeight)
}
export function togglePerf(): void {
perfOn = !perfOn
perfHud.hidden = !perfOn
}

72
src/app/popovers.ts Normal file
View file

@ -0,0 +1,72 @@
/** Popovers anchored in the window, and the New vehicle one. */
import { blendSpecs, BODY_STYLES, type BodyStyle, preset, randomSpec, styleLabel } from '../generator/index.ts'
import { addEntry } from '../library/store.ts'
import { currentLibrary, notify, state } from './context.ts'
import { commitLibrary, loadEntry } from './garage.ts'
import { icon, ICON } from './icons.ts'
import { popHost } from './layout.ts'
import { renderMenubar } from './menubar.ts'
import { el, segmented, select } from './ui.ts'
export let popover: 'export' | 'new' | null = null
export function closePopover(): void {
popover = null
popHost.replaceChildren()
renderMenubar()
}
window.addEventListener('pointerdown', (e) => {
if (!popover) return
const t = e.target as Element
if (popHost.contains(t) || t.closest('.export-split, .new-button')) return
closePopover()
}, true)
export function popHeader(title: string): HTMLElement {
const close = el('button', { type: 'button', class: 'icon-button', 'aria-label': 'Close' }, icon(ICON.close))
close.addEventListener('click', closePopover)
return el('header', {}, el('b', {}, title), close)
}
export function openNew(): void {
let style: BodyStyle = state.spec.style
let origin: 'preset' | 'random' | 'blend' = 'preset'
let partner: BodyStyle = style === 'suv' ? 'sedan' : 'suv'
const body = el('div', { class: 'pop-body' })
const create = async (): Promise<void> => {
const lib = currentLibrary()
if (!lib) return
const seed = origin === 'random' ? Math.floor(Math.random() * 1e6) : 1
const spec = origin === 'random' ? randomSpec(seed, { style })
: origin === 'blend' ? blendSpecs(preset(style, 1), preset(partner, 1), 0.5)
: preset(style, 1)
const [next, entry] = addEntry(lib, styleLabel(style), spec)
await commitLibrary(next)
closePopover()
loadEntry(entry)
notify(`Created “${entry.name}”`)
}
const paint = (): void => {
const grid = el('div', { class: 'style-grid' })
for (const s of BODY_STYLES) {
const b = el('button', { type: 'button', 'aria-pressed': String(s === style), class: s === style ? 'on' : '' }, styleLabel(s))
b.addEventListener('click', () => { style = s; paint() })
grid.append(b)
}
const go = el('button', { type: 'button', class: 'primary' }, 'Create')
go.addEventListener('click', () => void create())
body.replaceChildren(
grid,
segmented([{ value: 'preset', label: 'Preset' }, { value: 'random', label: 'Random' }, { value: 'blend', label: 'Blend two' }], origin, (v) => { origin = v; paint() }),
origin === 'blend' ? select('Blend with', BODY_STYLES.filter((s) => s !== style).map((s) => ({ value: s, label: styleLabel(s) })), partner, (v) => { partner = v as BodyStyle }) : el('span', {}),
el('footer', {}, el('span', { class: 'hint' }, `Into “${currentLibrary()?.name ?? ''}”`), go),
)
}
paint()
showPopover('new', el('section', { class: 'popover new-pop', role: 'dialog', 'aria-label': 'New vehicle' }, popHeader('New vehicle'), body))
}
/** Shows one popover, replacing any open one. */
export function showPopover(kind: 'export' | 'new', node: HTMLElement): void {
popover = kind
popHost.replaceChildren(node)
}

7
src/app/prefs.ts Normal file
View file

@ -0,0 +1,7 @@
/** Per-viewer conveniences kept in localStorage: losing them only resets a default. */
export const remembered = (key: string, fallback: string): string => {
try { return localStorage.getItem(`vehicle-generator:${key}`) ?? fallback } catch { return fallback }
}
export const remember = (key: string, value: string): void => {
try { localStorage.setItem(`vehicle-generator:${key}`, value) } catch { /* a convenience only */ }
}

14
src/app/render.ts Normal file
View file

@ -0,0 +1,14 @@
/** Redraws every area. */
import { renderCustoms } from './customs.ts'
import { renderGarage } from './garage.ts'
import { renderInspector } from './inspector.ts'
import { renderMenubar } from './menubar.ts'
import { renderStatus } from './status.ts'
export function renderAll(): void {
renderMenubar()
renderGarage()
renderCustoms()
renderInspector()
renderStatus()
}

50
src/app/resume.ts Normal file
View file

@ -0,0 +1,50 @@
/** Development only: a reload comes back where it left off. */
import type { BodyStyle, VehicleSpec } from '../generator/index.ts'
import { setResumeView } from './build.ts'
import { stage, state, type Tab } from './context.ts'
import { CATEGORIES } from './customs.ts'
import { markDirty } from './editing.ts'
import { TABS } from './inspector.ts'
export const RESUME = 'vehicle-generator:resume'
export interface Resume {
readonly libraryId: string; readonly entryId: string; readonly spec: VehicleSpec; readonly dirty: boolean
readonly tab: Tab; readonly cat: string; readonly blendWith: BodyStyle; readonly blend: number
readonly camera: number[]; readonly target: number[]
}
/**
* Restores the entry, tab, part and camera a development reload left, and
* remembers them for the next one. Runs after the garage is loaded.
*/
export function restoreSession(): void {
if (!import.meta.env.DEV) return
let saved: Resume | null = null
try { saved = JSON.parse(sessionStorage.getItem(RESUME) ?? 'null') as Resume | null } catch { saved = null }
const lib = saved && state.libraries.find((l) => l.id === saved.libraryId)
const entry = lib && lib.entries.find((e) => e.id === saved!.entryId)
if (saved && lib) {
state.libraryId = lib.id
state.entryId = entry ? entry.id : ''
state.spec = saved.dirty || !entry ? saved.spec : entry.spec
state.dirty = saved.dirty
if (TABS.some((t) => t.id === saved.tab)) state.tab = saved.tab
if (CATEGORIES.some((c) => c.id === saved.cat)) state.cat = saved.cat
state.blendWith = saved.blendWith
state.blend = saved.blend
setResumeView({ camera: saved.camera, target: saved.target })
if (state.dirty) markDirty()
}
const keep = (): void => {
if (!stage) return
const resume: Resume = {
libraryId: state.libraryId, entryId: state.entryId, spec: state.spec, dirty: state.dirty,
tab: state.tab, cat: state.cat, blendWith: state.blendWith, blend: state.blend,
camera: stage.camera.position.toArray(), target: stage.controls.target.toArray(),
}
try { sessionStorage.setItem(RESUME, JSON.stringify(resume)) } catch { /* storage blocked: start fresh next time */ }
}
// WebKit does not always fire pagehide on a dev reload, so the session is also kept every second.
addEventListener('pagehide', keep)
setInterval(keep, 1000)
import.meta.hot?.on('vite:beforeFullReload', keep)
}

332
src/app/scene.ts Normal file
View file

@ -0,0 +1,332 @@
import {
ACESFilmicToneMapping,
Box3,
CanvasTexture,
CircleGeometry,
Color,
DataTexture,
LinearMipmapLinearFilter,
MeshPhysicalMaterial,
MeshStandardMaterial,
MultiplyBlending,
RepeatWrapping,
Vector2,
DirectionalLight,
GridHelper,
Group,
HemisphereLight,
LineBasicMaterial,
LineSegments,
Mesh,
MeshBasicMaterial,
type Object3D,
PCFSoftShadowMap,
PerspectiveCamera,
PlaneGeometry,
PMREMGenerator,
Scene,
ShadowMaterial,
Sphere,
Vector3,
WebGPURenderer,
WireframeGeometry,
} from 'three/webgpu'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'
import type { LodLevel, Vehicle } from '../generator/index.ts'
export type LodMode = 'auto' | LodLevel
/** Where the camera looks from when a part is picked: the part faces the viewer. */
export type CameraView = 'side' | 'front34' | 'rear34' | 'front' | 'rear' | 'top' | 'wheel'
const VIEWS: Readonly<Record<CameraView, readonly [number, number, number]>> = {
side: [1, 0.16, 0.02],
front34: [0.78, 0.34, 0.82],
rear34: [0.78, 0.38, -0.82],
front: [0.08, 0.22, 1],
rear: [0.08, 0.3, -1],
top: [0.35, 1.5, 0.3],
wheel: [1, 0.1, 0.7],
}
/**
* The viewport: renderer, lights, ground, camera and the per-vehicle overlays
* (wireframe, collider). WebGPU where the browser has it, three's own WebGL2
* backend where it does not — same code, the renderer picks.
*/
export class Stage {
readonly renderer: WebGPURenderer
readonly scene = new Scene()
readonly camera = new PerspectiveCamera(32, 1, 0.05, 400)
readonly controls: OrbitControls
readonly backend: string
#key = new DirectionalLight(0xfff1e0, 2.4)
#grid = new GridHelper(40, 40, 0x3a414a, 0x22272d)
#shadow = new Mesh(new PlaneGeometry(40, 40), new ShadowMaterial({ opacity: 0.38, transparent: true }))
#floor = new Mesh(new CircleGeometry(30, 96), new MeshStandardMaterial({ color: 0x15181c, roughness: 0.55, metalness: 0, transparent: true, alphaMap: fadeTexture() }))
#contact = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ transparent: true, depthWrite: false, blending: MultiplyBlending, premultipliedAlpha: true }))
readonly studio = new Group()
#flakes = flakeTexture()
#vehicle: Vehicle | null = null
#wire: LineSegments[] = []
#wireMaterial = new LineBasicMaterial({ color: 0x7fd0ff, transparent: true, opacity: 0.35, depthWrite: false })
#collider: Mesh | null = null
#colliderMaterial = new MeshBasicMaterial({ color: 0xff7a2f, wireframe: true, transparent: true, opacity: 0.55 })
lodMode: LodMode = 'auto'
wireframe = false
showCollider = false
private constructor(readonly canvas: HTMLCanvasElement, renderer: WebGPURenderer) {
this.renderer = renderer
this.backend = (renderer.backend as { isWebGPUBackend?: boolean }).isWebGPUBackend ? 'WebGPU' : 'WebGL2'
renderer.setPixelRatio(Math.min(globalThis.devicePixelRatio, 2))
renderer.shadowMap.enabled = true
renderer.shadowMap.type = PCFSoftShadowMap
// Filmic tone mapping: highlights roll off instead of clipping, which is
// most of the difference between "rendered" and "photographed" paint.
renderer.toneMapping = ACESFilmicToneMapping
renderer.toneMappingExposure = 1.05
this.scene.background = new Color(0x15191e)
const pmrem = new PMREMGenerator(renderer)
this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture
pmrem.dispose()
this.scene.environmentIntensity = 0.9
this.#key.position.set(-5, 9, 6)
this.#key.castShadow = true
this.#key.shadow.mapSize.set(2048, 2048)
this.#key.shadow.bias = -0.0004
this.#key.shadow.normalBias = 0.02
const s = this.#key.shadow.camera
s.left = -6; s.right = 6; s.top = 6; s.bottom = -6; s.near = 0.5; s.far = 30
this.scene.add(this.#key, new HemisphereLight(0xbcd0e6, 0x2a2622, 0.45))
// A dark studio floor that takes the key light's shadow, a soft contact
// shadow right under the car (the ambient occlusion a shadow map is too
// coarse to give), and the grid as an optional overlay.
this.#floor.rotation.x = -Math.PI / 2
this.#floor.receiveShadow = true
this.#shadow.rotation.x = -Math.PI / 2
this.#shadow.position.y = 0.0005
this.#shadow.receiveShadow = true
this.#contact.rotation.x = -Math.PI / 2
this.#contact.position.y = 0.002
this.#contact.renderOrder = 1
;(this.#contact.material as MeshBasicMaterial).map = contactTexture()
this.#grid.position.y = 0.003
this.#grid.visible = false
this.studio.add(this.#floor, this.#shadow, this.#contact, this.#grid)
this.scene.add(this.studio)
this.scene.fog = null
this.camera.position.set(5.0, 1.45, 5.4)
this.controls = new OrbitControls(this.camera, canvas)
this.controls.enableDamping = true
this.controls.target.set(0, 0.7, 0)
this.controls.maxPolarAngle = Math.PI * 0.495
this.controls.autoRotateSpeed = 0.8
}
static async create(canvas: HTMLCanvasElement): Promise<Stage> {
const renderer = new WebGPURenderer({ canvas, antialias: true, forceWebGL: new URLSearchParams(location.search).has('webgl') })
await renderer.init()
return new Stage(canvas, renderer)
}
set grid(on: boolean) { this.#grid.visible = on }
get grid(): boolean { return this.#grid.visible }
resize(): void {
const { clientWidth: w, clientHeight: h } = this.canvas
if (w === 0 || h === 0) return
this.renderer.setSize(w, h, false)
this.camera.aspect = w / h
this.camera.updateProjectionMatrix()
}
/** Swaps the displayed vehicle. `frame` refits the camera (first load, style change). */
setVehicle(vehicle: Vehicle, frame: boolean): void {
if (this.#vehicle) this.scene.remove(this.#vehicle.group)
this.#vehicle = vehicle
this.scene.add(vehicle.group)
this.applyLod()
this.applyWireframe()
this.applyCollider()
this.refreshPaint()
const size = vehicle.bounds.getSize(new Vector3())
const centre = vehicle.bounds.getCenter(new Vector3())
this.#contact.scale.set(size.x * 1.35, size.z * 1.18, 1)
this.#contact.position.set(centre.x, 0.002, centre.z)
if (frame) this.frame()
}
/**
* Metallic flake, studio only: a fine noise normal map under the clearcoat.
* Kept out of the generator so exported GLBs carry no texture.
*/
refreshPaint(finish?: Vehicle['spec']['paint']['finish']): void {
const v = this.#vehicle
if (!v) return
const f = finish ?? v.spec.paint.finish
const metallic = f === 'metallic' || f === 'pearl'
for (const channel of ['paint', 'paint2', 'stripe'] as const) {
const m = v.materials[channel] as MeshPhysicalMaterial
m.normalMap = metallic ? this.#flakes : null
m.normalScale = new Vector2(0.045, 0.045)
m.needsUpdate = true
}
}
#turn: { from: Vector3; to: Vector3; t0: number } | null = null
/** Swings the camera round the car to a view, keeping its distance. */
look(view: CameraView): void {
const from = this.camera.position.clone().sub(this.controls.target).normalize()
const to = new Vector3(...VIEWS[view]).normalize()
if (from.angleTo(to) < 0.02) return
this.#turn = { from, to, t0: performance.now() }
}
#applyTurn(): void {
const turn = this.#turn
if (!turn) return
const t = Math.min(1, (performance.now() - turn.t0) / 450)
const e = t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2
const distance = this.camera.position.distanceTo(this.controls.target)
const dir = turn.from.clone().lerp(turn.to, e).normalize()
this.camera.position.copy(this.controls.target).addScaledVector(dir, distance)
if (t >= 1) this.#turn = null
}
frame(): void {
if (!this.#vehicle) return
const box = this.#vehicle.bounds
const sphere = box.getBoundingSphere(new Sphere())
const centre = box.getCenter(new Vector3())
const dir = this.camera.position.clone().sub(this.controls.target).normalize()
this.resize()
const vfov = (this.camera.fov * Math.PI) / 180
const hfov = 2 * Math.atan(Math.tan(vfov / 2) * this.camera.aspect)
const distance = (sphere.radius * 1.12) / Math.sin(Math.min(vfov, hfov) / 2)
this.controls.target.copy(centre)
this.camera.position.copy(centre).addScaledVector(dir.lengthSq() > 0 ? dir : new Vector3(0.7, 0.3, 0.7).normalize(), distance)
this.controls.update()
}
applyLod(): void {
const v = this.#vehicle
if (!v) return
const lod = v.lod
if (this.lodMode === 'auto') {
lod.autoUpdate = true
} else {
lod.autoUpdate = false
for (const level of lod.levels) level.object.visible = false
const wanted = v.lods.find((l) => l.level === this.lodMode) ?? v.lods[0]!
wanted.group.visible = true
}
}
/** The level currently on screen. */
visibleLevel(): LodLevel | null {
const v = this.#vehicle
if (!v) return null
for (const info of v.lods) if (info.group.visible) return info.level
return null
}
applyWireframe(): void {
for (const line of this.#wire) { line.removeFromParent(); line.geometry.dispose() }
this.#wire = []
const v = this.#vehicle
if (!v || !this.wireframe) return
v.group.traverse((o: Object3D) => {
if (!(o instanceof Mesh)) return
const line = new LineSegments(new WireframeGeometry(o.geometry), this.#wireMaterial)
line.renderOrder = 2
o.add(line)
this.#wire.push(line)
})
}
applyCollider(): void {
this.#collider?.removeFromParent()
this.#collider = null
const v = this.#vehicle
if (!v || !this.showCollider) return
this.#collider = new Mesh(v.collider.hull, this.#colliderMaterial)
this.#collider.renderOrder = 3
v.group.add(this.#collider)
}
get vehicleBounds(): Box3 | null {
return this.#vehicle?.bounds ?? null
}
render(): void {
this.#applyTurn()
this.controls.update()
this.renderer.render(this.scene, this.camera)
}
}
/** Fine random normals: one texel is a flake about 2 mm across on the body. */
function flakeTexture(): DataTexture {
const n = 256
const data = new Uint8Array(n * n * 4)
let seed = 1234567
const rand = (): number => {
seed = (seed * 1664525 + 1013904223) >>> 0
return seed / 4294967296
}
for (let i = 0; i < n * n; i += 1) {
const x = (rand() * 2 - 1) * 0.6
const y = (rand() * 2 - 1) * 0.6
const z = Math.sqrt(Math.max(0, 1 - x * x - y * y))
data[i * 4] = Math.round((x * 0.5 + 0.5) * 255)
data[i * 4 + 1] = Math.round((y * 0.5 + 0.5) * 255)
data[i * 4 + 2] = Math.round((z * 0.5 + 0.5) * 255)
data[i * 4 + 3] = 255
}
const texture = new DataTexture(data, n, n)
texture.wrapS = RepeatWrapping
texture.wrapT = RepeatWrapping
texture.repeat.set(9, 6)
texture.minFilter = LinearMipmapLinearFilter
texture.generateMipmaps = true
texture.needsUpdate = true
return texture
}
/** Radial fade so the floor dissolves into the background instead of ending in a horizon. */
function fadeTexture(): CanvasTexture {
const canvas = document.createElement('canvas')
canvas.width = 256
canvas.height = 256
const ctx = canvas.getContext('2d')!
const g = ctx.createRadialGradient(128, 128, 10, 128, 128, 128)
g.addColorStop(0, '#ffffff')
g.addColorStop(0.35, '#ffffff')
g.addColorStop(1, '#000000')
ctx.fillStyle = g
ctx.fillRect(0, 0, 256, 256)
return new CanvasTexture(canvas)
}
/** A soft rounded-rectangle darkening for under the car. */
function contactTexture(): CanvasTexture {
const canvas = document.createElement('canvas')
canvas.width = 256
canvas.height = 256
const ctx = canvas.getContext('2d')!
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, 256, 256)
ctx.filter = 'blur(18px)'
ctx.fillStyle = 'rgba(0,0,0,0.78)'
ctx.beginPath()
ctx.roundRect(52, 34, 152, 188, 40)
ctx.fill()
return new CanvasTexture(canvas)
}

40
src/app/showcase.ts Normal file
View file

@ -0,0 +1,40 @@
/**
* Development only: a showcase that steps the open vehicle through every body
* style, keeping its paint and mods, then puts it back exactly as it was.
* Nothing is saved or added to undo. Triggered over the HMR socket (see
* vite.config.ts): `curl localhost:5173/__vehicle-generator/showcase?interval=300`.
*/
import { BODY_STYLES, preset } from '../generator/index.ts'
import { rebuild } from './build.ts'
import { state } from './context.ts'
import { renderAll } from './render.ts'
let running = false
export async function runShowcase(interval: number): Promise<void> {
if (running) return
running = true
const original = { spec: state.spec, blend: state.blend }
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
try {
state.blend = 0
for (const style of BODY_STYLES) {
state.spec = { ...preset(style, original.spec.seed), paint: original.spec.paint, mods: original.spec.mods }
rebuild(true)
renderAll()
await sleep(interval)
}
} finally {
state.spec = original.spec
state.blend = original.blend
rebuild(true)
renderAll()
running = false
}
}
if (import.meta.env.DEV) {
import.meta.hot?.on('vehicle-generator:showcase', (data: { interval?: number }) => {
void runShowcase(Math.max(50, Number(data.interval) || 300))
})
}

19
src/app/status.ts Normal file
View file

@ -0,0 +1,19 @@
/** The status bar. */
import { lastBuildMs, vehicle } from './build.ts'
import { currentName, notice, stage, state, store } from './context.ts'
import { statusbar } from './layout.ts'
import { el } from './ui.ts'
export function renderStatus(): void {
const size = vehicle?.bounds.getSize(vehicle.bounds.min.clone())
const lod0 = vehicle?.lods.find((l) => l.level === 0)
const shown = stage.visibleLevel()
statusbar.replaceChildren(
el('span', { class: 'hints' }, 'Drag orbit · Right-drag pan · Wheel zoom · F frame · ↑↓ part · ←→ variant · F3 search'),
notice,
el('span', { class: 'stats' },
vehicle ? `${currentName()} · LOD${shown ?? '–'} on screen · LOD0 ${lod0?.triangles.toLocaleString('en') ?? '–'} tris · ${size!.z.toFixed(2)} × ${size!.x.toFixed(2)} × ${size!.y.toFixed(2)} m · ${lastBuildMs.toFixed(0)} ms` : ''),
el('span', { class: state.dirty ? 'saving' : 'saved' }, state.dirty ? 'Saving…' : store.persistent ? 'Saved' : 'In memory only'),
el('span', { class: 'backend' }, stage.backend),
)
}

626
src/app/studio.css Normal file
View file

@ -0,0 +1,626 @@
/*
* Vehicle Generator studio. One window laid out like a 3D editor: a top bar,
* the garage and customs on the left, the viewport with its variant shelf in
* the middle, the properties editor on the right, a status bar. Graphite
* areas, one amber accent. Colours are tokens here and nowhere else.
*/
:root {
--app: #161618;
--area: #232427;
--head: #2b2c30;
--panel: #2a2b2f;
--panel-head: #303136;
--field: #1c1d20;
--line: #0e0e10;
--edge: #34363b;
--edge-strong: #44474e;
--ink: #e6e7e9;
--muted: #a3a8af;
--dim: #73787f;
--accent: #ffb224;
--accent-deep: #e89e12;
--accent-fill: #4a3a16;
--accent-select: #3a3220;
--accent-ink: #1a1300;
--ok: #7fd19a;
--warn: #e8b64a;
--bad: #ef5a55;
--font: 'Manrope', system-ui, -apple-system, 'Segoe UI', sans-serif;
--mark: 'Barlow Condensed', 'Manrope', system-ui, sans-serif;
--mono: 'JetBrains Mono', ui-monospace, 'Cascadia Mono', Consolas, monospace;
color-scheme: dark;
}
* { box-sizing: border-box; }
html, body, #app { height: 100%; margin: 0; }
body {
background: var(--app);
color: var(--ink);
font: 500 13px/1.4 var(--font);
overflow: hidden;
user-select: none;
cursor: default;
}
button, input, select { font: inherit; color: inherit; }
kbd {
border: 1px solid var(--edge);
border-radius: 4px;
padding: 0 5px;
font: 500 10.5px var(--mono);
color: var(--muted);
}
[hidden] { display: none !important; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: -1px; }
/* ------------------------------------------------------------------ layout */
.studio {
position: relative;
display: grid;
height: 100%;
grid-template-columns: 248px minmax(0, 1fr) 330px;
grid-template-rows: 44px minmax(0, 1fr) 26px;
grid-template-areas: 'menu menu menu' 'left centre inspector' 'status status status';
background: var(--line);
gap: 1px 1px;
}
.left { grid-area: left; display: flex; flex-direction: column; min-height: 0; background: var(--area); }
.centre { grid-area: centre; display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--area); }
.inspector { grid-area: inspector; display: flex; min-height: 0; background: var(--area); }
.area-head {
display: flex;
align-items: center;
gap: 6px;
flex: none;
height: 32px;
padding: 0 8px 0 10px;
background: var(--head);
border-bottom: 1px solid var(--line);
}
.area-head b { flex: 1; font-size: 12px; font-weight: 700; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.meta { font-size: 11px; color: var(--muted); white-space: nowrap; }
.hint { margin: 4px 2px 6px; font-size: 11.5px; color: var(--muted); line-height: 1.5; }
.spacer { flex: 1; }
/* ----------------------------------------------------------------- top bar */
.menubar {
grid-area: menu;
display: flex;
align-items: center;
gap: 4px;
padding: 0 10px;
background: #1f2023;
}
.logo { display: flex; align-items: center; gap: 7px; margin-right: 6px; }
.logo img { width: 22px; height: 22px; border-radius: 5px; }
.logo b { font: 700 19px var(--mark); letter-spacing: 0.03em; }
.logo b em { font-style: normal; color: var(--accent); }
.menubar > .menu-button {
height: 30px;
border: 0;
background: none;
padding: 0 9px;
border-radius: 6px;
color: #c9ccd1;
}
.menubar > .menu-button:hover, .menubar > .menu-button.open { background: var(--head); color: var(--ink); }
.menubar .search {
display: flex;
align-items: center;
gap: 8px;
width: min(320px, 30vw);
height: 30px;
padding: 0 10px;
border-radius: 6px;
border: 1px solid var(--edge);
background: var(--app);
color: var(--dim);
text-align: left;
}
.menubar .search span { flex: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.menubar .search:hover { border-color: var(--edge-strong); color: var(--muted); }
button {
border: 1px solid var(--edge);
background: none;
border-radius: 6px;
padding: 4px 10px;
font-weight: 600;
cursor: default;
}
button:hover:not(:disabled) { background: var(--head); }
button:disabled { opacity: 0.4; }
button.ghost { display: inline-flex; align-items: center; gap: 6px; height: 30px; border-color: var(--edge-strong); }
button.ghost[aria-pressed='true'] { background: var(--accent-fill); border-color: var(--accent); color: #ffd27a; }
button.primary {
display: inline-flex;
align-items: center;
gap: 7px;
height: 32px;
padding: 0 14px;
border: 0;
background: var(--accent);
color: var(--accent-ink);
font-weight: 800;
}
button.primary:hover:not(:disabled) { background: var(--accent); filter: brightness(1.08); }
button.wide { width: 100%; margin-top: 6px; border-color: var(--edge-strong); }
button.icon-button {
display: inline-grid;
place-items: center;
width: 24px;
height: 24px;
padding: 0;
border: 0;
border-radius: 5px;
color: var(--muted);
}
button.icon-button.accent { background: var(--accent); color: var(--accent-ink); }
button.icon-button.accent:hover { background: var(--accent); filter: brightness(1.08); }
.export-split { display: inline-flex; border-radius: 6px; overflow: hidden; margin-left: 4px; }
.export-split button { border: 0; border-radius: 0; height: 32px; color: var(--accent-ink); font-weight: 800; }
.export-main { display: inline-flex; align-items: center; gap: 7px; padding: 0 14px; background: var(--accent); white-space: nowrap; }
.export-more { width: 30px; padding: 0; display: grid; place-items: center; background: var(--accent-deep); border-left: 1px solid #b97b0a !important; }
.export-split button:hover:not(:disabled) { background: var(--accent); filter: brightness(1.08); }
/*
* Title bar, desktop app only. The drag layer carries Tauri's drag region;
* everything else in the bar sits above it and stays clickable.
*/
.menubar.titlebar { position: relative; isolation: isolate; }
.titlebar-drag { position: absolute; inset: 0; z-index: 0; }
.menubar.titlebar > :not(.titlebar-drag) { position: relative; z-index: 1; }
.menubar.titlebar > .spacer, .menubar.titlebar > .logo { pointer-events: none; }
html[data-desktop-os='macos'] .menubar.titlebar { padding-left: 78px; }
.window-controls { display: flex; align-self: stretch; margin: 0 -10px 0 6px; }
.window-controls button.caption {
display: grid;
place-items: center;
width: 46px;
height: 100%;
border: 0;
border-radius: 0;
padding: 0;
background: transparent;
color: var(--muted);
}
.window-controls button.caption svg { width: 10px; height: 10px; }
.window-controls button.caption:hover { background: var(--head); color: var(--ink); }
.window-controls button.caption.close:hover { background: #c42b1c; color: #fff; }
/* ------------------------------------------------------------ garage (left) */
.garage { display: flex; flex-direction: column; flex: 1 1 55%; min-height: 0; }
.lib-picker { padding: 6px 8px; border-bottom: 1px solid var(--line); }
.lib-picker select { width: 100%; }
.entries { list-style: none; margin: 0; padding: 4px 0; overflow-y: auto; flex: 1; min-height: 0; }
.entry {
display: grid;
grid-template-columns: 15px 12px minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
height: 28px;
padding: 0 10px;
color: #c9ccd1;
}
.entry:hover { background: var(--head); }
.entry.on { background: var(--accent-select); color: #fff; font-weight: 700; box-shadow: inset 2px 0 var(--accent); }
.entry input[type='checkbox'] { width: 15px; height: 15px; margin: 0; accent-color: var(--accent); }
.entry .dot { width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--line); }
.entry .name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.entry .meta { font-size: 10.5px; color: var(--dim); }
.entry.on .meta { color: var(--accent); }
.entry input[type='text'] { width: 100%; }
.entry.drop-over { outline: 2px solid var(--accent); outline-offset: -2px; }
.empty { padding: 24px 14px; text-align: center; color: var(--muted); font-size: 12px; }
.empty b { display: block; color: var(--ink); font-size: 14px; margin-bottom: 4px; }
.left > .area-head:not(:first-child) { border-top: 1px solid var(--line); }
.customs { list-style: none; margin: 0; padding: 4px 0; overflow-y: auto; flex: 1 1 45%; min-height: 0; }
.customs .row {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
height: 28px;
padding: 0 10px;
border: 0;
border-radius: 0;
color: #c9ccd1;
font-weight: 500;
text-align: left;
}
.customs .row .num { width: 20px; font: 500 11px var(--mono); color: var(--dim); }
.customs .row .name { flex: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.customs .row.on { background: var(--accent-select); color: #fff; font-weight: 700; box-shadow: inset 2px 0 var(--accent); }
.customs .row.on .num { color: var(--accent); }
/* --------------------------------------------------------------- viewport */
.viewbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
flex: none;
min-height: 36px;
padding: 3px 8px;
background: var(--head);
border-bottom: 1px solid var(--line);
}
.viewbar button.ghost { height: 28px; border-color: transparent; font-size: 12px; }
.viewbar button.ghost:hover { border-color: var(--edge); }
.camera-note { display: inline-flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--muted); margin-right: 4px; }
.monitor { position: relative; flex: 1; min-height: 0; overflow: hidden; background: radial-gradient(120% 90% at 50% 38%, #2a2c31, #17181b 72%); }
.monitor canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.fatal { position: absolute; inset: 0; display: grid; place-content: center; text-align: center; color: var(--muted); }
.shelf { flex: none; background: var(--area); border-top: 1px solid var(--line); }
.shelf header { display: flex; align-items: center; gap: 10px; height: 30px; padding: 0 10px; background: var(--head); }
.shelf header .num { font: 500 11px var(--mono); color: var(--accent); }
.shelf header b { font-size: 12px; }
.variants { display: flex; gap: 8px; padding: 8px 10px 10px; overflow-x: auto; }
.variant {
flex: 0 0 124px;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
height: 64px;
padding: 8px 10px;
border-radius: 6px;
border: 1px solid var(--edge);
background: var(--panel);
text-align: left;
position: relative;
}
.variant .num { font: 500 11px var(--mono); color: var(--dim); }
.variant .name { font-weight: 700; }
.variant.on { border: 2px solid var(--accent); background: var(--accent-select); padding: 7px 9px; }
.variant.on .num { color: var(--accent); }
.variant .fitted {
position: absolute;
top: 7px;
right: 7px;
font: 800 9.5px var(--font);
letter-spacing: 0.06em;
color: var(--accent-ink);
background: var(--accent);
border-radius: 3px;
padding: 1px 5px;
}
/* ------------------------------------------------------------ properties */
.rail { display: flex; flex-direction: column; gap: 2px; flex: 0 0 38px; padding: 6px 4px; background: var(--field); border-right: 1px solid var(--line); }
.rail button { display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; color: var(--muted); }
.rail button.on { background: var(--accent); color: var(--accent-ink); }
.props { display: flex; flex-direction: column; flex: 1; min-width: 0; }
.panel-body { flex: 1; overflow-y: auto; padding: 0 6px 10px; }
.panel-body::-webkit-scrollbar, .entries::-webkit-scrollbar, .customs::-webkit-scrollbar, .variants::-webkit-scrollbar { width: 8px; height: 8px; }
.panel-body::-webkit-scrollbar-thumb, .entries::-webkit-scrollbar-thumb, .customs::-webkit-scrollbar-thumb, .variants::-webkit-scrollbar-thumb { background: var(--edge); border-radius: 4px; }
.hint.foot { margin: 12px 4px 0; }
.section { margin-top: 6px; border-radius: 6px; background: var(--panel); overflow: hidden; }
.section > summary {
display: flex;
align-items: center;
gap: 6px;
height: 28px;
padding: 0 8px;
background: var(--panel-head);
list-style: none;
}
.section > summary::-webkit-details-marker { display: none; }
.section > summary::before {
content: '';
width: 0;
height: 0;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 5px solid var(--muted);
transition: transform 0.12s ease;
}
.section:not([open]) > summary::before { transform: rotate(-90deg); }
.section h2 { margin: 0; font-size: 12px; font-weight: 700; }
.section-body { display: flex; flex-direction: column; gap: 4px; padding: 8px; }
.field {
display: grid;
grid-template-columns: 92px minmax(0, 1fr);
align-items: center;
gap: 8px;
font-size: 12px;
}
.field-label { color: var(--muted); text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.field.changed .field-label { color: var(--ink); }
/* Number field: label and value inside a bar filled to the value. */
.num-field { grid-template-columns: minmax(0, 1fr) 18px; gap: 4px; }
.nf {
position: relative;
height: 24px;
border-radius: 4px;
background: var(--field);
overflow: hidden;
cursor: ew-resize;
touch-action: none;
}
.nf:hover { background: #222327; }
.num-fill { position: absolute; inset: 0 auto 0 0; background: var(--accent-fill); pointer-events: none; }
.num-label, .num-value { position: absolute; top: 0; bottom: 0; display: flex; align-items: center; pointer-events: none; white-space: nowrap; }
.num-label { left: 8px; right: 90px; overflow: hidden; text-overflow: ellipsis; color: #c9ccd1; }
.num-value { right: 8px; font: 500 11.5px var(--mono); }
.nf.scrubbing .num-fill { background: #5c4718; }
.num-input {
position: absolute;
inset: 0;
width: 100%;
border: 1px solid var(--accent) !important;
border-radius: 4px;
background: var(--app) !important;
padding: 0 8px !important;
font: 500 12px var(--mono) !important;
text-align: right;
cursor: text;
}
.num-field .reset { width: 18px; height: 22px; padding: 0; border: 0; color: var(--accent); visibility: hidden; }
.num-field.changed .reset { visibility: visible; }
.num-field.changed .num-label::after { content: ' •'; color: var(--accent); }
select, input[type='text'], input[type='number'] {
height: 24px;
background: var(--field);
border: 1px solid transparent;
border-radius: 4px;
padding: 0 7px;
font-size: 12px;
font-weight: 600;
min-width: 0;
}
select:hover, input[type='text']:hover, input[type='number']:hover { background: #222327; }
select:focus, input:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
.colour-row { display: flex; align-items: center; gap: 6px; min-width: 0; }
input[type='color'] { width: 36px; height: 22px; padding: 0; border: 1px solid var(--edge); border-radius: 4px; background: none; }
input[type='color']::-webkit-color-swatch-wrapper { padding: 2px; }
input[type='color']::-webkit-color-swatch { border: 0; border-radius: 3px; }
.hex { font: 11px var(--mono); color: var(--muted); }
.pills { display: flex; gap: 2px; padding: 2px; border-radius: 6px; background: var(--field); }
.pills button { flex: 1; height: 26px; padding: 0 9px; border: 0; border-radius: 4px; font-size: 12px; font-weight: 600; color: var(--muted); white-space: nowrap; }
.pills button.on { background: var(--accent-fill); color: #ffd27a; }
.section .pills button.on, .popover .pills button.on { background: var(--accent); color: var(--accent-ink); }
.viewbar .pills { padding: 2px; }
.viewbar .pills button { flex: none; }
.toggle {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
width: 100%;
height: 28px;
border-color: var(--edge);
font-weight: 600;
}
.toggle[aria-pressed='true'] { border-color: var(--accent); background: var(--accent-select); }
.swatches { display: flex; flex-wrap: wrap; gap: 5px; margin: 4px 0 6px; }
.swatch { width: 22px; height: 22px; border-radius: 4px; border: 1px solid var(--line); padding: 0; }
.swatch.on { outline: 2px solid var(--accent); outline-offset: 1px; }
.palette-name { font-size: 10.5px; color: var(--muted); margin-top: 4px; letter-spacing: 0.08em; text-transform: uppercase; }
.mono-list { font: 11px var(--mono); color: var(--muted); }
/* ---------------------------------------------------------------- status */
.statusbar {
grid-area: status;
display: flex;
align-items: center;
gap: 14px;
padding: 0 10px;
font-size: 11px;
color: var(--dim);
background: #1f2023;
white-space: nowrap;
overflow: hidden;
}
.statusbar .hints { overflow: hidden; text-overflow: ellipsis; }
.statusbar .notice { margin-left: auto; color: var(--ink); }
.statusbar .stats { font-family: var(--mono); color: var(--muted); }
.statusbar .saved { color: var(--ok); }
.statusbar .saving { color: var(--warn); }
/* ------------------------------------------------------------- popovers */
.popover-host { position: absolute; inset: 0; pointer-events: none; z-index: 40; }
.popover {
position: absolute;
pointer-events: auto;
border-radius: 10px;
background: #26272b;
border: 1px solid var(--edge-strong);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.6);
overflow: hidden;
animation: pop 0.12s ease-out;
}
.popover > header { display: flex; align-items: center; height: 36px; padding: 0 8px 0 12px; background: #2e2f34; border-bottom: 1px solid var(--line); }
.popover > header b { flex: 1; }
.pop-body { display: flex; flex-direction: column; gap: 10px; padding: 12px; }
.pop-body footer { display: flex; align-items: center; gap: 8px; }
.pop-body footer .hint { flex: 1; margin: 0; }
.export-pop { top: 50px; right: 10px; width: 440px; }
.new-pop { top: 80px; left: 256px; width: 420px; }
.targets { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.target {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 3px;
height: 58px;
border-color: var(--edge);
background: #1f2023;
font-size: 11.5px;
}
.target .badge { font: 500 12px var(--mono); }
.target small { font-size: 9.5px; color: var(--dim); text-transform: uppercase; letter-spacing: 0.08em; }
.target.on { border: 2px solid var(--accent); background: var(--accent-select); }
.files { list-style: none; margin: 0; padding: 0; border-radius: 6px; background: #1a1b1e; border: 1px solid var(--line); }
.files li { display: flex; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--area); font-size: 12px; }
.files li:last-child { border-bottom: 0; }
.files li.inner { padding-left: 24px; color: var(--muted); }
.files code { flex: 1; font: 12px var(--mono); overflow-wrap: anywhere; }
.files span { color: var(--muted); }
.style-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.style-grid button { height: 32px; padding: 0 4px; font-size: 12px; background: #1f2023; }
.style-grid button.on { border: 2px solid var(--accent); background: var(--accent-select); }
/* ------------------------------------------------------- menus, dialogs */
.menu-list {
position: fixed;
z-index: 50;
min-width: 240px;
padding: 4px;
background: #26272b;
border: 1px solid var(--edge-strong);
border-radius: 8px;
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.55);
}
.menu-row {
display: grid;
grid-template-columns: 16px 1fr auto;
gap: 8px;
align-items: center;
width: 100%;
height: 28px;
border: 0;
border-radius: 4px;
padding: 0 8px;
font-weight: 500;
text-align: left;
}
.menu-row i { font-style: normal; color: var(--accent); }
.menu-row:hover:not(:disabled) { background: var(--accent); color: var(--accent-ink); }
.menu-row:hover:not(:disabled) kbd { color: var(--accent-ink); border-color: rgba(0, 0, 0, 0.3); }
.menu-row.danger { color: var(--bad); }
.menu-list hr { border: 0; border-top: 1px solid var(--edge); margin: 4px 6px; }
.backdrop {
position: fixed;
inset: 0;
z-index: 60;
display: flex;
justify-content: center;
align-items: flex-start;
padding-top: 12vh;
background: rgba(4, 5, 6, 0.55);
}
.dialog {
width: min(480px, 92vw);
background: #26272b;
border: 1px solid var(--edge-strong);
border-radius: 10px;
box-shadow: 0 30px 80px rgba(0, 0, 0, 0.55);
}
.dialog header { display: flex; align-items: center; padding: 10px 10px 0 14px; }
.dialog h3 { flex: 1; margin: 0; font-size: 14px; }
.dialog header button { border: 0; }
.dialog-body { padding: 10px 14px 12px; font-size: 13px; }
.dialog footer { display: flex; justify-content: flex-end; gap: 8px; padding: 0 14px 12px; }
.dialog footer:empty { display: none; }
.shortcuts { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 18px; }
.shortcuts div { display: flex; justify-content: space-between; gap: 8px; color: var(--muted); }
.palette input { width: 100%; height: 34px; font-size: 14px; }
.palette-list { list-style: none; margin: 8px 0 0; padding: 0; max-height: 50vh; overflow-y: auto; }
.palette-list li { display: flex; justify-content: space-between; align-items: center; gap: 10px; height: 30px; padding: 0 10px; border-radius: 5px; }
.palette-list li.on { background: var(--accent); color: var(--accent-ink); }
.palette-list li.on kbd { color: var(--accent-ink); border-color: rgba(0, 0, 0, 0.3); }
/* ----------------------------------------------------------------- about */
.about {
width: min(420px, 92vw);
border-radius: 14px;
background: #1f2023;
border: 1px solid var(--edge-strong);
box-shadow: 0 30px 90px rgba(0, 0, 0, 0.65);
overflow: hidden;
animation: pop 0.16s ease-out;
}
.about-hero {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 28px 24px 18px;
background:
radial-gradient(60% 70% at 50% 34%, rgba(255, 178, 36, 0.22), transparent 70%),
linear-gradient(180deg, #26272b, #1f2023);
border-bottom: 1px solid var(--line);
}
.about-mark { width: 132px; height: 132px; object-fit: contain; filter: drop-shadow(0 14px 22px rgba(0, 0, 0, 0.55)); margin-bottom: 10px; }
.about h2 { margin: 0; font: 700 34px/1 var(--mark); letter-spacing: 0.04em; }
.about h2 em { font-style: normal; color: var(--accent); }
.about-version { font: 500 11.5px var(--mono); color: var(--muted); letter-spacing: 0.06em; }
.about-lead { margin: 16px 24px 4px; color: #c9ccd1; font-size: 13px; line-height: 1.55; text-align: center; }
.about-rows { display: grid; gap: 1px; margin: 14px 24px 0; border-radius: 8px; overflow: hidden; background: var(--line); border: 1px solid var(--line); }
.about-row { display: flex; justify-content: space-between; gap: 12px; padding: 7px 12px; background: var(--area); font-size: 12px; }
.about-row span { color: var(--muted); }
.about-row b { font-weight: 600; }
.about footer { display: flex; align-items: center; gap: 8px; padding: 16px 24px 20px; }
.about footer button:not(.primary) { height: 32px; }
.about-backdrop { align-items: center; padding-top: 0; }
/* ------------------------------------------------------------ play mode */
.studio.driving { grid-template-columns: 0 minmax(0, 1fr) 0; }
.studio.driving .left, .studio.driving .inspector, .studio.driving .viewbar, .studio.driving .shelf { display: none; }
.drive-hud {
position: absolute;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
z-index: 2;
display: flex;
align-items: center;
gap: 10px;
padding: 6px 8px;
border: 1px solid var(--edge);
border-radius: 10px;
background: color-mix(in srgb, var(--area) 80%, transparent);
backdrop-filter: blur(8px);
}
.drive-hud .pills { min-width: 190px; }
.drive-note { font-size: 11.5px; color: var(--muted); }
.speedo {
position: absolute;
right: 18px;
bottom: 16px;
z-index: 2;
font: 700 30px var(--mark);
letter-spacing: 0.02em;
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
pointer-events: none;
}
.perf-hud {
position: absolute;
left: 14px;
bottom: 14px;
z-index: 2;
padding: 4px 8px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.45);
font: 12px var(--mono);
color: #cfd6dd;
white-space: pre;
pointer-events: none;
}
@keyframes pop { from { opacity: 0; transform: translateY(-4px) scale(0.98); } to { opacity: 1; transform: none; } }
.menu-list, .dialog { animation: pop 0.12s ease-out; }
@media (prefers-reduced-motion: reduce) { *, *::after, *::before { animation: none !important; transition: none !important; } }
@media (max-width: 1100px) {
.studio { grid-template-columns: 210px minmax(0, 1fr) 290px; }
.menubar .search { display: none; }
.camera-note { display: none; }
}

52
src/app/toolbar.ts Normal file
View file

@ -0,0 +1,52 @@
/** The viewport toolbar: shading, LOD, overlays. */
import { vehicle } from './build.ts'
import { stage, state } from './context.ts'
import { category, renderCustoms } from './customs.ts'
import { randomise } from './editing.ts'
import { icon, ICON } from './icons.ts'
import { toolbar } from './layout.ts'
import type { CameraView, LodMode } from './scene.ts'
import { renderStatus } from './status.ts'
import { el, segmented } from './ui.ts'
export const viewLabel = (v: CameraView): string => ({ side: 'side', front34: 'front three-quarter', rear34: 'rear three-quarter', front: 'front', rear: 'rear', top: 'from above', wheel: 'front wheel' })[v]
export function renderToolbar(): void {
const randomButton = el('button', { type: 'button', class: 'ghost' }, icon(ICON.dice), 'Randomise', el('kbd', {}, 'R'))
randomButton.addEventListener('click', () => randomise(state.randomStyle ? undefined : state.spec.style))
const doors = vehicle?.rig.openables ?? []
const anyOpen = doors.some((p) => (state.open[p] ?? 0) > 0.5)
toolbar.replaceChildren(
segmented<string>([{ value: 'material', label: 'Material' }, { value: 'wire', label: 'Wire' }], stage.wireframe ? 'wire' : 'material', (v) => setWireframe(v === 'wire')),
segmented<string>([
{ value: 'auto', label: 'LOD auto', title: 'Switch LOD by distance' },
{ value: '0', label: '0' }, { value: '1', label: '1' }, { value: '2', label: '2' },
], String(stage.lodMode), (v) => setLod(v === 'auto' ? 'auto' : (Number(v) as 0 | 1 | 2))),
barToggle('Collider', stage.showCollider, setCollider),
barToggle('Open doors', anyOpen, (on) => { for (const p of doors) { state.open[p] = on ? 1 : 0; vehicle?.rig.open(p, state.open[p]!) } renderCustoms() }),
el('div', { class: 'spacer' }),
el('span', { class: 'camera-note' }, icon(ICON.camera, 13), `Camera follows the part · ${viewLabel(category().view)}`),
randomButton,
)
}
export function barToggle(label: string, on: boolean, set: (v: boolean) => void): HTMLButtonElement {
const b = el('button', { type: 'button', class: 'ghost', 'aria-pressed': String(on) }, label) as HTMLButtonElement
b.addEventListener('click', () => { set(!on); renderToolbar() })
return b
}
export function setLod(mode: LodMode): void {
stage.lodMode = mode
stage.applyLod()
renderToolbar()
renderStatus()
}
export function setWireframe(on: boolean): void {
stage.wireframe = on
stage.applyWireframe()
renderToolbar()
}
export function setCollider(on: boolean): void {
stage.showCollider = on
stage.applyCollider()
renderToolbar()
}

276
src/app/ui.ts Normal file
View file

@ -0,0 +1,276 @@
/**
* Tiny DOM helpers. The studio is plain DOM on purpose: a few hundred
* controls, rebuilt only when the selected panel changes, need no framework.
*/
type Attrs = Record<string, string | number | boolean | undefined | ((e: Event) => void)>
export function el<K extends keyof HTMLElementTagNameMap>(
tag: K,
attrs: Attrs = {},
...children: (Node | string | null | undefined | false)[]
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
for (const [key, value] of Object.entries(attrs)) {
if (value === undefined || value === false) continue
if (typeof value === 'function') node.addEventListener(key.replace(/^on/, '').toLowerCase(), value)
else if (key === 'class') node.className = String(value)
else if (value === true) node.setAttribute(key, '')
else node.setAttribute(key, String(value))
}
for (const child of children) {
if (child === null || child === undefined || child === false) continue
node.append(child)
}
return node
}
/** Collapsible panels remember whether they were folded, by title, for the session. */
const folded = new Set<string>()
/** A collapsible properties panel, Blender style. */
export function section(title: string, ...children: (Node | null | false)[]): HTMLElement {
const panel = el('details', { class: 'section', open: !folded.has(title) },
el('summary', {}, el('h2', {}, title)),
el('div', { class: 'section-body' }, ...children))
panel.addEventListener('toggle', () => {
if (panel.open) folded.delete(title)
else folded.add(title)
})
return panel
}
export interface SliderOptions {
readonly label: string
readonly min: number
readonly max: number
readonly step: number
readonly value: number
readonly unit?: string
readonly digits?: number
/** When given, a reset button appears once the value drifts from it (Backspace on the field resets too). */
readonly defaultValue?: number
onInput(value: number): void
}
/**
* A number field: the label and value sit inside a bar filled to the value.
* Drag sideways to scrub (Shift for fine steps), click to type, arrow keys
* step. While a drag is held the studio builds only the coarse LOD.
*/
export function slider(o: SliderOptions): HTMLElement {
const digits = o.digits ?? (o.step >= 1 ? 0 : o.step >= 0.1 ? 1 : o.step >= 0.01 ? 2 : 3)
const format = (v: number): string => `${v.toFixed(digits)}${o.unit ? ` ${o.unit}` : ''}`
const clampSnap = (v: number): number => {
const snapped = Math.round((v - o.min) / o.step) * o.step + o.min
return Math.min(o.max, Math.max(o.min, Number(snapped.toFixed(6))))
}
let value = clampSnap(o.value)
const fill = el('span', { class: 'num-fill' })
const text = el('span', { class: 'num-value' })
const box = el('div', {
class: 'nf', role: 'slider', tabindex: 0, 'data-scrub': true,
'aria-label': o.label, 'aria-valuemin': o.min, 'aria-valuemax': o.max,
}, fill, el('span', { class: 'num-label' }, o.label), text)
const field = el('div', { class: 'field num-field' }, box)
const reset = o.defaultValue === undefined ? null
: el('button', { type: 'button', class: 'reset', title: `Reset to ${format(o.defaultValue)}`, 'aria-label': `Reset ${o.label}` }, '↺') as HTMLButtonElement
if (reset) field.append(reset)
const paint = (): void => {
fill.style.width = `${((value - o.min) / (o.max - o.min || 1)) * 100}%`
text.textContent = format(value)
box.setAttribute('aria-valuenow', String(value))
box.setAttribute('aria-valuetext', format(value))
if (o.defaultValue !== undefined) field.classList.toggle('changed', Math.abs(value - o.defaultValue) > o.step / 2)
}
const set = (v: number): void => {
const next = clampSnap(v)
if (next === value) return
value = next
paint()
o.onInput(value)
}
reset?.addEventListener('click', () => { if (o.defaultValue !== undefined) set(o.defaultValue) })
let drag: { x: number; v: number; moved: boolean } | null = null
box.addEventListener('pointerdown', (e) => {
if (e.button !== 0 || box.querySelector('input')) return
drag = { x: e.clientX, v: value, moved: false }
box.setPointerCapture(e.pointerId)
})
box.addEventListener('pointermove', (e) => {
if (!drag) return
const dx = e.clientX - drag.x
if (!drag.moved && Math.abs(dx) < 3) return
drag.moved = true
box.classList.add('scrubbing')
const range = (o.max - o.min) * (e.shiftKey ? 0.1 : 1)
set(drag.v + (dx / Math.max(80, box.clientWidth)) * range)
})
box.addEventListener('pointerup', () => {
const clicked = drag && !drag.moved
drag = null
box.classList.remove('scrubbing')
if (clicked) type()
})
box.addEventListener('keydown', (e) => {
if (box.querySelector('input')) return
const k = e.key
if (k === 'ArrowRight' || k === 'ArrowUp') set(value + o.step * (e.shiftKey ? 10 : 1))
else if (k === 'ArrowLeft' || k === 'ArrowDown') set(value - o.step * (e.shiftKey ? 10 : 1))
else if (k === 'Enter') type()
else if ((k === 'Backspace' || k === 'Delete') && o.defaultValue !== undefined) set(o.defaultValue)
else return
e.preventDefault()
e.stopPropagation()
})
function type(): void {
const input = el('input', { type: 'text', class: 'num-input', value: value.toFixed(digits), 'aria-label': o.label }) as HTMLInputElement
box.append(input)
input.focus()
input.select()
const finish = (commit: boolean): void => {
if (!input.isConnected) return
const typed = Number(input.value.replace(',', '.'))
input.remove()
if (commit && Number.isFinite(typed)) set(typed)
box.focus()
}
input.addEventListener('keydown', (e) => {
e.stopPropagation()
if (e.key === 'Enter') finish(true)
if (e.key === 'Escape') finish(false)
})
input.addEventListener('blur', () => finish(true))
}
paint()
return field
}
export function select(label: string, options: readonly { value: string; label: string }[], value: string, onChange: (v: string) => void): HTMLElement {
const s = el('select', {}) as HTMLSelectElement
for (const o of options) s.append(el('option', { value: o.value, selected: o.value === value }, o.label))
s.addEventListener('change', () => onChange(s.value))
return el('label', { class: 'field' }, el('span', { class: 'field-label' }, label), s)
}
export function colour(label: string, value: string, onInput: (v: string) => void): HTMLElement {
const input = el('input', { type: 'color', value }) as HTMLInputElement
const hex = el('code', { class: 'hex' }, value)
input.addEventListener('input', () => {
hex.textContent = input.value
onInput(input.value)
})
return el('label', { class: 'field' }, el('span', { class: 'field-label' }, label), el('span', { class: 'colour-row' }, input, hex))
}
/** Equal-width pill group. */
export function segmented<T extends string>(
options: readonly { value: T; label: string; title?: string }[],
value: T,
onChange: (v: T) => void,
): HTMLElement {
const group = el('div', { class: 'pills', role: 'radiogroup' })
const paint = (current: T): void => {
for (const b of group.querySelectorAll<HTMLButtonElement>('button')) b.classList.toggle('on', b.dataset.value === current)
}
for (const o of options) {
const b = el('button', { type: 'button', 'data-value': o.value, title: o.title }, o.label)
b.addEventListener('click', () => { paint(o.value); onChange(o.value) })
group.append(b)
}
paint(value)
return group
}
export function toggle(label: string, value: boolean, onChange: (v: boolean) => void, kbd?: string): HTMLButtonElement {
const b = el('button', { type: 'button', class: 'toggle', 'aria-pressed': String(value) },
el('span', {}, label), kbd ? el('kbd', {}, kbd) : null) as HTMLButtonElement
b.addEventListener('click', () => {
const next = b.getAttribute('aria-pressed') !== 'true'
b.setAttribute('aria-pressed', String(next))
onChange(next)
})
return b
}
export function button(label: string, onClick: () => void, cls = ''): HTMLButtonElement {
const b = el('button', { type: 'button', class: cls }, label) as HTMLButtonElement
b.addEventListener('click', onClick)
return b
}
export function download(name: string, data: BlobPart, type: string): void {
const url = URL.createObjectURL(new Blob([data], { type }))
const a = el('a', { href: url, download: name })
document.body.append(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 4000)
}
export function pickFile(accept: string): Promise<File | null> {
return new Promise((resolve) => {
const input = el('input', { type: 'file', accept }) as HTMLInputElement
input.addEventListener('change', () => resolve(input.files?.[0] ?? null))
input.click()
})
}
/* ------------------------------------------------------------ menus, dialogs */
export interface MenuItem {
readonly label: string
readonly kbd?: string
readonly checked?: boolean
readonly disabled?: boolean
readonly danger?: boolean
readonly run?: () => void
}
export type MenuEntry = MenuItem | 'separator'
let openMenu: HTMLElement | null = null
export function closeMenu(): void {
openMenu?.remove()
openMenu = null
}
export function showMenu(x: number, y: number, entries: readonly MenuEntry[]): void {
closeMenu()
const list = el('div', { class: 'menu-list', role: 'menu' })
for (const entry of entries) {
if (entry === 'separator') { list.append(el('hr', {})); continue }
const row = el('button', { type: 'button', class: `menu-row${entry.danger ? ' danger' : ''}`, disabled: entry.disabled },
el('i', {}, entry.checked ? '✓' : ''), el('span', {}, entry.label), entry.kbd ? el('kbd', {}, entry.kbd) : el('span', {}))
row.addEventListener('click', () => { closeMenu(); entry.run?.() })
list.append(row)
}
document.body.append(list)
const r = list.getBoundingClientRect()
list.style.left = `${Math.min(x, window.innerWidth - r.width - 6)}px`
list.style.top = `${Math.min(y, window.innerHeight - r.height - 6)}px`
openMenu = list
}
window.addEventListener('pointerdown', (e) => {
if (openMenu && !openMenu.contains(e.target as Node)) closeMenu()
}, true)
window.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeMenu() })
export function dialog(title: string, body: HTMLElement, actions: readonly { label: string; primary?: boolean; run?: () => void }[]): () => void {
const close = (): void => backdrop.remove()
const footer = el('footer', {})
for (const a of actions) {
footer.append(button(a.label, () => { close(); a.run?.() }, a.primary ? 'primary' : ''))
}
const box = el('div', { class: 'dialog', role: 'dialog', 'aria-label': title },
el('header', {}, el('h3', {}, title), button('✕', close, 'icon')),
el('div', { class: 'dialog-body' }, body),
footer)
const backdrop = el('div', { class: 'backdrop' }, box)
backdrop.addEventListener('pointerdown', (e) => { if (e.target === backdrop) close() })
document.body.append(backdrop)
return close
}

148
src/app/windowbar.ts Normal file
View file

@ -0,0 +1,148 @@
/**
* Window chrome for the desktop build (Tauri, frameless window).
*
* The studio's menubar doubles as the title bar. A drag layer sits behind
* everything in the bar and carries Tauri's drag region (and its double-click
* to maximise); the logo, menus and buttons are siblings above it, so they
* stay clickable. Windows-style caption buttons sit on the right, and a
* right-click on the bar opens a window menu of our own.
*
* Desktop-only behaviour lives here too: the browser engine's context menu
* and page shortcuts (reload, print, find) are suppressed, F11 toggles
* fullscreen and Esc leaves it. In a browser none of this runs.
*
* Tauri packages are only reached through dynamic `import()`, so the web build
* never loads native bridge code it cannot use.
*/
import { el, type MenuEntry, showMenu } from './ui.ts'
export const isDesktop = (): boolean => '__TAURI_INTERNALS__' in globalThis
async function win() {
const { getCurrentWindow } = await import('@tauri-apps/api/window')
return getCurrentWindow()
}
export async function minimizeWindow(): Promise<void> { if (isDesktop()) await (await win()).minimize() }
export async function toggleMaximizeWindow(): Promise<void> { if (isDesktop()) await (await win()).toggleMaximize() }
export async function closeWindow(): Promise<void> { if (isDesktop()) await (await win()).close() }
export async function isWindowFullscreen(): Promise<boolean> { return isDesktop() ? (await win()).isFullscreen() : false }
export async function setWindowFullscreen(on: boolean): Promise<void> { if (isDesktop()) await (await win()).setFullscreen(on) }
/** Quits the app for real (File → Quit). Falls back to closing the window. */
export async function quitApp(): Promise<void> {
if (!isDesktop()) return
try {
const { invoke } = await import('@tauri-apps/api/core')
await invoke('vehicle_generator_quit')
} catch {
await closeWindow()
}
}
const svg = (body: string): SVGSVGElement => {
const node = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
node.setAttribute('width', '10')
node.setAttribute('height', '10')
node.setAttribute('viewBox', '0 0 10 10')
node.setAttribute('aria-hidden', 'true')
node.setAttribute('fill', 'none')
node.setAttribute('stroke', 'currentColor')
node.setAttribute('stroke-width', '1')
node.setAttribute('stroke-linecap', 'round')
node.setAttribute('stroke-linejoin', 'round')
node.innerHTML = body
return node
}
const MINIMIZE = '<path d="M1 5.5h8"/>'
const MAXIMIZE = '<rect x="1" y="1" width="8" height="8" rx="1.6"/>'
const RESTORE = '<rect x="1" y="3" width="6" height="6" rx="1.3"/><path d="M3 1.9A1.3 1.3 0 0 1 4.2 1H7.8A1.2 1.2 0 0 1 9 2.2V5.8A1.3 1.3 0 0 1 8.1 7"/>'
const CLOSE = '<path d="M1.5 1.5l7 7M8.5 1.5l-7 7"/>'
const editable = (target: EventTarget | null): boolean =>
target instanceof Element && Boolean(target.closest('input[type="text"], input[type="number"], textarea, [contenteditable="true"], [contenteditable=""]'))
async function toggleFullscreen(): Promise<void> {
const next = !(await isWindowFullscreen())
await setWindowFullscreen(next)
document.documentElement.classList.toggle('window-fullscreen', next)
}
/**
* Turns the menubar into the window's title bar. Call once after the bar is
* built; rebuilding the bar's contents later keeps the drag layer as long as
* `renderMenubar` puts it back (it does, through `decorateMenubar`).
*/
export async function mountWindowControls(bar: HTMLElement): Promise<void> {
if (!isDesktop()) return
const os = navigator.userAgent.includes('Mac') ? 'macos' : navigator.userAgent.includes('Linux') ? 'linux' : 'windows'
document.documentElement.dataset.desktopOs = os
document.documentElement.classList.add('desktop')
decorateMenubar(bar)
// The engine's own menu (Back, Refresh, Inspect) is not an app's menu. Text fields keep it.
document.addEventListener('contextmenu', (e) => { if (!editable(e.target)) e.preventDefault() })
// Nor are its page shortcuts: F5 / Ctrl+R would reload the studio and drop unsaved work.
const PAGE_KEYS = new Set(['r', 'p', 'f', 'g', 'j', 'u', 'o', 'h'])
window.addEventListener('keydown', (e) => {
const name = e.key.length === 1 ? e.key.toLowerCase() : e.key
const reload = name === 'F5' || name === 'BrowserRefresh'
const page = (e.ctrlKey || e.metaKey) && !e.altKey && PAGE_KEYS.has(name) && !editable(e.target)
if (!reload && !page) return
e.preventDefault()
e.stopPropagation()
}, { capture: true })
window.addEventListener('keydown', (e) => {
if (e.defaultPrevented) return
if (e.key === 'F11') { e.preventDefault(); void toggleFullscreen() }
else if (e.key === 'Escape' && document.documentElement.classList.contains('window-fullscreen')) void toggleFullscreen()
})
const w = await win()
const sync = async (): Promise<void> => {
const maximised = await w.isMaximized()
for (const b of document.querySelectorAll<HTMLButtonElement>('[data-caption="max"]')) {
b.replaceChildren(svg(maximised ? RESTORE : MAXIMIZE))
b.title = maximised ? 'Restore' : 'Maximise'
}
document.documentElement.classList.toggle('window-fullscreen', await w.isFullscreen())
}
await sync()
await w.onResized(() => { void sync() })
}
/** Adds the drag layer, the caption buttons and the window menu to a (re)built menubar. */
export function decorateMenubar(bar: HTMLElement): void {
if (!isDesktop()) return
bar.classList.add('titlebar')
bar.prepend(el('div', { class: 'titlebar-drag', 'data-tauri-drag-region': 'deep', 'aria-hidden': 'true' }))
if (document.documentElement.dataset.desktopOs !== 'macos') {
const caption = (name: string, glyph: string, title: string, run: () => void, cls = ''): HTMLButtonElement => {
const b = el('button', { type: 'button', class: `caption ${cls}`, title, 'aria-label': title, 'data-caption': name }) as HTMLButtonElement
b.append(svg(glyph))
b.addEventListener('click', run)
return b
}
bar.append(el('div', { class: 'window-controls' },
caption('min', MINIMIZE, 'Minimise', () => void minimizeWindow()),
caption('max', MAXIMIZE, 'Maximise', () => void toggleMaximizeWindow()),
caption('close', CLOSE, 'Close', () => void closeWindow(), 'close')))
}
// The bar element outlives its contents, so its window menu is wired once.
if (bar.dataset.windowMenu) return
bar.dataset.windowMenu = 'on'
bar.addEventListener('contextmenu', (e) => {
if ((e.target as Element).closest('button, select, input')) return
e.preventDefault()
const entries: MenuEntry[] = [
{ label: 'Maximise / restore', run: () => void toggleMaximizeWindow() },
{ label: 'Minimise', run: () => void minimizeWindow() },
{ label: 'Fullscreen', kbd: 'F11', run: () => void toggleFullscreen() },
'separator',
{ label: 'Close', kbd: 'Alt+F4', danger: true, run: () => void closeWindow() },
]
showMenu(e.clientX, e.clientY, entries)
})
}

234
src/generator/bays.ts Normal file
View file

@ -0,0 +1,234 @@
import type { BodyFrame } from './body.ts'
import { circle, emitBeam, emitTube, roundPath, type RGB, type SinkSet, type Vec3 } from './mesh.ts'
import type { LodLevel } from './spec.ts'
/**
* What is under the bonnet and behind the boot lid.
*
* Front-engined cars get an engine bay under the bonnet: firewall, inner
* wings, radiator support, strut towers, an engine with its cam cover and
* intake, a radiator and fan, a battery, fluid reservoirs and hoses. The boot
* gets a carpeted load floor, side trims and a spare-wheel well. A
* mid-engined car swaps them: the engine sits behind the cabin under the rear
* lid and the space under the bonnet is a carpeted front boot.
*
* Everything belongs to the body node, so it stays put when a lid opens. The
* closed panels hide it, so LOD2 skips it and LOD1 keeps only the big shapes.
*/
export type EngineLayout = 'front' | 'mid'
interface Box {
readonly s0: number
readonly s1: number
readonly floor: number
readonly ceiling: number
readonly half: number
/** Half width of the opening at the skin: the ledges reach out to it. */
readonly outer: number
}
const ALU: RGB = [0.78, 0.8, 0.82]
const CAST: RGB = [0.45, 0.46, 0.48]
const BLACK: RGB = [0.22, 0.22, 0.24]
const COOLANT: RGB = [0.95, 0.86, 0.7]
const WASHER: RGB = [0.45, 0.62, 0.95]
const CAP_YELLOW: RGB = [1, 0.82, 0.18]
export function buildBays(frame: BodyFrame, sinks: SinkSet, lod: LodLevel, layout: EngineLayout): void {
if (lod === 2) return
const front = frame.hood ? boxFor(frame, frame.hood.rearS + 0.04, frame.hood.frontS - 0.04, 0.05) : null
const trunk = frame.trunk
// The load space behind the rear seats, or under a lid behind the rear window.
const rearLimit = trunk ? Math.min(trunk.kind === 'lid' ? frame.deckS - 0.02 : Math.max(frame.roofRearS + 0.05, frame.deckS + 0.05) - 0.02, trunk.frontS + 0.6) : 0
const rear = trunk ? boxFor(frame, (trunk.kind === 'tailgate' ? frame.rearS + 0.1 : trunk.rearS + 0.04), rearLimit, 0.05) : null
if (layout === 'mid') {
if (rear) engine(frame, sinks, lod, rear, -1)
if (front) cargo(frame, sinks, lod, front, false)
} else {
if (front) engine(frame, sinks, lod, front, 1)
if (rear) cargo(frame, sinks, lod, rear, true, trunk?.kind === 'tailgate')
}
}
/** The usable box between two stations: floor above the sill, ceiling under the panel. */
function boxFor(frame: BodyFrame, s0: number, s1: number, margin: number): Box | null {
if (s1 - s0 < 0.3) return null
const mid = (s0 + s1) / 2
// Not the sill at mid: over a wheel arch that is the top of the arch.
const floor = Math.min(frame.sill(s0), frame.sill(s1)) + 0.12
const ceiling = Math.min(frame.top(s0), frame.top(s1), frame.top(mid)) - margin
if (ceiling - floor < 0.15) return null
// Inboard of the wheel wells, which sit at 62 % of the half width.
const skin = Math.min(frame.halfWidth(s0), frame.halfWidth(s1), frame.halfWidth(mid))
const half = skin * 0.6
return { s0, s1, floor, ceiling, half, outer: skin - 0.03 }
}
/** A tub: floor, two side walls, and the two end walls. */
function tub(sinks: SinkSet, box: Box, channel: 'underbody' | 'interior', colour?: RGB, lowRear = false): void {
const sink = sinks.get(`body|${channel}`)
const { s0, s1, floor, ceiling, half, outer } = box
const h = ceiling - floor
const opts = colour ? { colour } : {}
// Ledges (the tops of the inner wings) from the tub wall out to the skin,
// so nothing past the tub shows the road.
for (const side of [-1, 1]) {
const x = side * (half + outer) / 2
emitBeam(sink, [x, ceiling - 0.01, s0], [x, ceiling - 0.01, s1], outer - half + 0.02, 0.02, 0.005, opts)
}
emitBeam(sink, [0, floor, s0], [0, floor, s1], half * 2, 0.03, 0.01, opts)
for (const x of [-half, half]) emitBeam(sink, [x, floor + h / 2, s0], [x, floor + h / 2, s1], 0.03, h, 0.01, opts)
for (const s of [s0, s1]) {
// Behind a tailgate the back wall is only the bumper's height: a load lip.
const wall = lowRear && s === s0 ? Math.min(h, 0.18) : h
emitBeam(sink, [-half, floor + wall / 2, s], [half, floor + wall / 2, s], 0.03, wall, 0.01, opts)
}
}
/**
* An engine bay in `box`. `facing` is +1 when the front of the car is at
* box.s1 (front engine) and -1 for an engine behind the cabin, where the
* radiator end sits at the back of the car.
*/
function engine(frame: BodyFrame, sinks: SinkSet, lod: LodLevel, box: Box, facing: 1 | -1): void {
const { s0, s1, floor, ceiling, half } = box
const under = sinks.get('body|underbody')
const metal = sinks.get('body|brake')
const trim = sinks.get('body|trim')
const accent = sinks.get('body|caliper')
const plastic = sinks.get('body|plate')
const chrome = sinks.get('body|chrome')
tub(sinks, box, 'underbody')
const len = s1 - s0
const mid = (s0 + s1) / 2
const h = ceiling - floor
// The radiator end and the firewall end.
const nose = facing > 0 ? s1 : s0
const wall = facing > 0 ? s0 : s1
const toNose = (d: number): number => nose - facing * d
const fromWall = (d: number): number => wall + facing * d
// Engine: block, head, cam cover. Inline, sat a little behind the bay centre.
const blockLen = Math.min(0.62, len * 0.5)
const blockW = Math.min(0.48, half * 0.95)
const bc = fromWall(Math.max(blockLen / 2 + 0.12, len * 0.42))
const bA = bc - blockLen / 2
const bB = bc + blockLen / 2
const blockTop = floor + Math.min(h * 0.62, 0.42)
emitBeam(metal, [0, (floor + 0.02 + blockTop) / 2, bA], [0, (floor + 0.02 + blockTop) / 2, bB], blockW, blockTop - floor - 0.02, 0.03, { colour: CAST })
const headTop = Math.min(ceiling - 0.04, blockTop + 0.1)
emitBeam(metal, [0, (blockTop + headTop) / 2, bA + 0.02], [0, (blockTop + headTop) / 2, bB - 0.02], blockW * 0.82, headTop - blockTop, 0.02, { colour: ALU })
const coverTop = Math.min(ceiling - 0.015, headTop + 0.06)
if (coverTop > headTop + 0.015) {
emitBeam(accent, [0, (headTop + coverTop) / 2, bA + 0.05], [0, (headTop + coverTop) / 2, bB - 0.05], blockW * 0.62, coverTop - headTop, 0.025)
if (lod === 0) {
// Ribs and an oil filler cap on the cam cover.
for (let k = 1; k <= 4; k += 1) {
const s = bA + 0.05 + ((bB - bA - 0.1) * k) / 5
emitBeam(accent, [-blockW * 0.28, coverTop, s], [blockW * 0.28, coverTop, s], 0.012, 0.012, 0.004, { colour: [0.8, 0.8, 0.8] })
}
emitTube(trim, circle(0.03, 10), [[blockW * 0.18, coverTop - 0.01, bc], [blockW * 0.18, coverTop + 0.02, bc]], { colour: BLACK })
}
}
// Intake: a plenum along one side of the head with runners into it, and an
// air box toward the nose with a duct to the plenum.
const plenumX = -blockW * 0.52
const plenumY = Math.min(ceiling - 0.05, headTop - 0.02)
emitTube(metal, circle(0.045, lod === 0 ? 10 : 6), [[plenumX, plenumY, bA + 0.04], [plenumX, plenumY, bB - 0.04]], { colour: ALU })
if (lod === 0) {
for (let k = 0; k < 4; k += 1) {
const s = bA + 0.08 + ((bB - bA - 0.16) * k) / 3
emitTube(metal, circle(0.018, 6), roundPath([[plenumX, plenumY, s], [plenumX + 0.06, blockTop + 0.03, s], [-blockW * 0.2, blockTop + 0.03, s]], 0.03, 2), { colour: ALU, caps: false })
}
}
// The end of the engine that faces the radiator.
const noseEnd = facing > 0 ? bB : bA
const boxS = toNose(0.24)
const boxX = -Math.min(half - 0.16, blockW * 0.5 + 0.14)
const boxTop = Math.min(ceiling - 0.03, floor + h * 0.85)
emitBeam(trim, [boxX, boxTop - 0.08, boxS - 0.12], [boxX, boxTop - 0.08, boxS + 0.12], 0.24, 0.16, 0.03, { colour: BLACK })
emitTube(under, circle(0.05, lod === 0 ? 10 : 6), roundPath([
[boxX, boxTop - 0.08, boxS - facing * 0.12],
[boxX, plenumY, noseEnd + facing * 0.08],
[plenumX, plenumY, noseEnd - facing * 0.02],
], 0.06, 3), { caps: false })
// Radiator with its fan shroud, across the nose end.
const radS = toNose(0.07)
const radH = Math.min(h * 0.8, 0.5)
emitBeam(trim, [-half * 0.85, floor + 0.05 + radH / 2, radS], [half * 0.85, floor + 0.05 + radH / 2, radS], 0.05, radH, 0.01, { colour: [0.35, 0.36, 0.38] })
emitTube(under, circle(Math.min(radH * 0.42, 0.2), lod === 0 ? 20 : 10), [[0, floor + 0.05 + radH / 2, radS - facing * 0.03], [0, floor + 0.05 + radH / 2, radS - facing * 0.09]])
// Hoses from the radiator to the engine.
if (lod === 0) {
emitTube(under, circle(0.022, 6), roundPath([[half * 0.6, floor + 0.05 + radH * 0.85, radS - facing * 0.03], [blockW * 0.3, headTop - 0.02, noseEnd + facing * 0.06], [blockW * 0.2, headTop - 0.02, noseEnd - facing * 0.02]], 0.05, 2), { caps: false })
emitTube(under, circle(0.022, 6), roundPath([[-half * 0.6, floor + 0.08, radS - facing * 0.03], [-blockW * 0.3, floor + 0.12, noseEnd + facing * 0.06], [-blockW * 0.3, floor + 0.12, noseEnd - facing * 0.02]], 0.05, 2), { caps: false })
}
// Strut towers, where the front wheels are (only in a front bay).
if (facing > 0) {
const axle = frame.axles.reduce((a, b) => (Math.abs(b.s - mid) < Math.abs(a.s - mid) ? b : a))
if (axle.s > s0 + 0.1 && axle.s < s1 - 0.1) {
for (const x of [-(half - 0.1), half - 0.1]) {
const top = Math.min(ceiling - 0.03, floor + h * 0.88)
emitTube(under, circle(0.085, lod === 0 ? 12 : 6), [[x, floor, axle.s], [x, top, axle.s]])
if (lod === 0) emitTube(chrome, circle(0.03, 8), [[x, top, axle.s], [x, top + 0.02, axle.s]], { colour: CAST })
}
}
}
// Battery in one rear corner, reservoirs in the others.
const side = half - 0.17
const corner = fromWall(0.16)
const batTop = Math.min(ceiling - 0.03, floor + 0.3)
emitBeam(trim, [side, (floor + batTop) / 2, corner - 0.11], [side, (floor + batTop) / 2, corner + 0.11], 0.18, batTop - floor, 0.015, { colour: BLACK })
if (lod === 0) {
emitTube(accent, circle(0.014, 6), [[side + 0.05, batTop, corner - 0.06], [side + 0.05, batTop + 0.02, corner - 0.06]])
emitTube(chrome, circle(0.014, 6), [[side - 0.05, batTop, corner - 0.06], [side - 0.05, batTop + 0.02, corner - 0.06]])
}
const reservoir = (x: number, s: number, colour: RGB, cap: RGB): void => {
const top = Math.min(ceiling - 0.04, floor + h * 0.75)
emitBeam(plastic, [x, (floor + 0.06 + top) / 2, s - 0.06], [x, (floor + 0.06 + top) / 2, s + 0.06], 0.12, top - floor - 0.06, 0.03, { colour })
if (lod === 0) emitTube(plastic, circle(0.028, 8), [[x, top, s], [x, top + 0.03, s]], { colour: cap })
}
reservoir(-side, corner, COOLANT, BLACK)
reservoir(-side + 0.02, fromWall(0.36) + facing * 0.02, [0.92, 0.9, 0.85], CAP_YELLOW)
reservoir(side, toNose(0.25), WASHER, [0.25, 0.4, 0.9])
}
/** A carpeted load space; `spare` adds a spare-wheel well in the floor. */
function cargo(frame: BodyFrame, sinks: SinkSet, lod: LodLevel, box: Box, spare: boolean, gate = false): void {
const carpet: RGB = [0.55, 0.55, 0.57]
tub(sinks, box, 'interior', carpet, gate)
if (lod !== 0) return
const sink = sinks.get('body|interior')
const { s0, s1, floor, half } = box
// A pull strap at the lip.
emitBeam(sinks.get('body|trim'), [0, floor + 0.02, s0 + 0.06], [0, floor + 0.02, s0 + 0.16], 0.04, 0.006, 0.002, { colour: BLACK })
void sink
// Tie-down loops in the corners.
for (const x of [-half + 0.08, half - 0.08]) {
for (const s of [s0 + 0.1, s1 - 0.1]) {
emitTube(sinks.get('body|chrome'), circle(0.008, 5), roundPath([[x, floor + 0.06, s - 0.03], [x, floor + 0.09, s], [x, floor + 0.06, s + 0.03]], 0.02, 2), { caps: false })
}
}
if (!spare) return
// The spare: a tyre lying flat in its well, sunk into the load floor.
const r = Math.min(0.3, half * 0.6, (s1 - s0) * 0.4)
if (r < 0.15) return
const c: Vec3 = [0, floor + 0.005, (s0 + s1) / 2]
const ring: Vec3[] = []
const n = 16
for (let k = 0; k <= n; k += 1) {
const a = (k / n) * Math.PI * 2
ring.push([c[0] + Math.cos(a) * r * 0.78, c[1], c[2] + Math.sin(a) * r * 0.78])
}
emitTube(sinks.get('body|tyre'), circle(r * 0.2, 8), ring, { caps: false })
emitTube(sinks.get('body|rim'), circle(r * 0.62, 16), [[c[0], c[1] - 0.01, c[2]], [c[0], c[1] + 0.035, c[2]]], { up: [0, 0, 1] })
// The well's rim, a dark lip round the tyre.
const lip: Vec3[] = ring.map((p) => [c[0] + (p[0] - c[0]) * 1.32, floor + 0.018, c[2] + (p[2] - c[2]) * 1.32])
emitTube(sinks.get('body|underbody'), circle(0.015, 5), lip, { caps: false })
void frame
}

167
src/generator/blend.ts Normal file
View file

@ -0,0 +1,167 @@
import { mixHex } from './palette.ts'
import { createRandom, chance, jitter, pick, range } from './random.ts'
import { MODS, MOD_KINDS } from './mods.ts'
import { BODY_STYLES, preset } from './presets.ts'
import { palettesFor, randomColor } from './palette.ts'
import type { BodyStyle, ModSpec, PaintSpec, RimStyle, VehicleSpec } from './spec.ts'
/**
* Blending and randomising specs.
*
* Because a spec is plain numbers, two body styles can be interpolated: a
* hatchback 40 % of the way to an SUV is a crossover, and nobody had to model
* one. Numbers interpolate, colours interpolate in RGB, and choices (a rim
* style, a bumper finish) switch over at the midpoint.
*/
function blendValue(a: unknown, b: unknown, t: number): unknown {
if (typeof a === 'number' && typeof b === 'number') return a + (b - a) * t
if (typeof a === 'string' && typeof b === 'string' && /^#[0-9a-f]{6}$/i.test(a) && /^#[0-9a-f]{6}$/i.test(b)) {
return mixHex(a, b, t)
}
if (a && b && typeof a === 'object' && typeof b === 'object' && !Array.isArray(a) && !Array.isArray(b)) {
const out: Record<string, unknown> = {}
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
out[key] = blendValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], t)
}
return out
}
return t < 0.5 ? a : b
}
export function blendSpecs(a: VehicleSpec, b: VehicleSpec, t: number): VehicleSpec {
if (t <= 0) return a
if (t >= 1) return b
const out = blendValue(a, b, t) as VehicleSpec
// Integers stay integers.
return {
...out,
seed: t < 0.5 ? a.seed : b.seed,
body: { ...out.body, doors: t < 0.5 ? a.body.doors : b.body.doors },
wheels: { ...out.wheels, spokes: Math.round(out.wheels.spokes) },
}
}
const RIMS_BY_STYLE: Readonly<Record<BodyStyle, readonly RimStyle[]>> = {
sedan: ['spoke', 'multispoke', 'mesh', 'turbine'],
hatchback: ['spoke', 'multispoke', 'steelie', 'mesh'],
coupe: ['multispoke', 'mesh', 'turbine', 'deepdish'],
wagon: ['spoke', 'mesh', 'multispoke'],
suv: ['spoke', 'multispoke', 'beadlock'],
pickup: ['spoke', 'steelie', 'beadlock'],
van: ['steelie', 'spoke'],
sports: ['multispoke', 'mesh', 'turbine', 'deepdish'],
supercar: ['turbine', 'multispoke', 'spoke'],
muscle: ['deepdish', 'spoke', 'steelie'],
kei: ['steelie', 'spoke', 'multispoke'],
buggy: ['beadlock', 'steelie'],
truck: ['steelie'],
}
/** Mods and the chance each style gets them when randomised. */
const MOD_ODDS: Readonly<Partial<Record<BodyStyle, Partial<Record<ModSpec['kind'], number>>>>> = {
sedan: { spoiler: 0.15, exhaust: 0.4, suspension: 0.15, wheelSet: 0.2 },
hatchback: { spoiler: 0.3, bodyKit: 0.2, exhaust: 0.4, suspension: 0.25, wheelSet: 0.25, roofRack: 0.15 },
coupe: { spoiler: 0.4, bodyKit: 0.35, exhaust: 0.6, suspension: 0.3, wheelSet: 0.35, widebody: 0.15 },
wagon: { roofRack: 0.45, exhaust: 0.3, wheelSet: 0.2 },
suv: { roofRack: 0.45, bullBar: 0.25, suspension: 0.2, lightBar: 0.15, snorkel: 0.12, mudFlaps: 0.2 },
pickup: { bullBar: 0.35, lightBar: 0.35, snorkel: 0.2, suspension: 0.35, mudFlaps: 0.35, roofRack: 0.1 },
van: { roofRack: 0.5, mudFlaps: 0.3, bullBar: 0.1 },
sports: { spoiler: 0.6, bodyKit: 0.5, exhaust: 0.8, widebody: 0.25, suspension: 0.4, wheelSet: 0.4 },
supercar: { spoiler: 0.45, bodyKit: 0.6, exhaust: 0.9, widebody: 0.2 },
muscle: { hoodScoop: 0.6, spoiler: 0.4, exhaust: 0.9, widebody: 0.15, suspension: 0.3 },
kei: { roofRack: 0.3, spoiler: 0.15, mudFlaps: 0.2 },
buggy: { lightBar: 0.5, bullBar: 0.3, snorkel: 0.2 },
truck: { mudFlaps: 0.8, lightBar: 0.25, bullBar: 0.2 },
}
export interface RandomOptions {
/** Pin the body style; otherwise one is drawn. */
readonly style?: BodyStyle
/** 0 = stock proportions, 1 = strong variation. */
readonly variation?: number
/** Draw mods for the style (default true). */
readonly mods?: boolean
}
/** A random, fully specified vehicle — the same seed always gives the same one. */
export function randomSpec(seed: number, options: RandomOptions = {}): VehicleSpec {
const random = createRandom(seed)
const style = options.style ?? pick(random, BODY_STYLES)
const base = preset(style, seed)
const v = options.variation ?? 0.5
const vary = (value: number, amount: number): number => value * (1 + jitter(random, amount * v))
const b = base.body
const body = {
...b,
length: vary(b.length, 0.06),
width: vary(b.width, 0.04),
roofHeight: vary(b.roofHeight, 0.04),
hoodHeight: vary(b.hoodHeight, 0.04),
noseHeight: vary(b.noseHeight, 0.05),
deckHeight: vary(b.deckHeight, 0.04),
tumblehome: Math.max(0, vary(b.tumblehome, 0.3)),
sideBulge: Math.min(1, Math.max(0, b.sideBulge + jitter(random, 0.3 * v))),
noseRound: vary(b.noseRound, 0.25),
tailRound: vary(b.tailRound, 0.25),
roofFront: b.roofFront + jitter(random, 0.02 * v),
cowl: b.cowl + jitter(random, 0.02 * v),
}
// Lengths move the axles with them, so the overhangs keep their proportion.
const scale = body.length / b.length
const chassis = {
...base.chassis,
wheelbase: base.chassis.wheelbase * scale,
frontOverhang: base.chassis.frontOverhang * scale,
}
const { color, finish } = randomColor(random, style)
const palette = pick(random, palettesFor(style))
const twoTone = chance(random, 0.12) ? pick(random, ['roof', 'lower'] as const) : base.paint.twoTone
const livery = chance(random, style === 'sports' || style === 'muscle' || style === 'buggy' ? 0.35 : 0.08)
? pick(random, ['stripes', 'side-stripe', 'rally'] as const)
: base.paint.livery
const paint: PaintSpec = {
...base.paint,
primary: color,
finish,
secondary: pick(random, palette.colors),
stripe: pick(random, ['#f4f4f2', '#101114', '#e8b81a', '#c3261f']),
twoTone,
livery,
rim: pick(random, ['#b9bec4', '#2a2c30', '#d7d9dc', '#6d6f73', '#c9a45a']),
rimFinish: pick(random, ['satin', 'satin', 'chrome', 'painted'] as const),
caliper: pick(random, ['#9aa0a6', '#c3261f', '#d9a21b', '#2f7de1', '#1a1a1a']),
tint: range(random, 0.15, 0.8),
}
const wheels = {
...base.wheels,
rim: pick(random, RIMS_BY_STYLE[style]),
spokes: Math.round(range(random, 5, 10)),
}
const mods: ModSpec[] = [...base.mods]
if (options.mods !== false) {
const odds = MOD_ODDS[style] ?? {}
for (const kind of MOD_KINDS) {
const p = odds[kind]
if (!p || !chance(random, p) || mods.some((m) => m.kind === kind)) continue
const params: Record<string, number | string> = {}
for (const param of MODS[kind].params) {
if (param.type === 'number') {
const steps = Math.round((param.max - param.min) / param.step)
params[param.key] = param.min + Math.round(random() * steps) * param.step
} else {
params[param.key] = pick(random, param.options)
}
}
if (kind === 'suspension') {
params.height = style === 'pickup' || style === 'suv' || style === 'buggy' ? range(random, 0.04, 0.14) : range(random, -0.06, -0.02)
}
mods.push({ kind, params })
}
}
return { ...base, seed, body, chassis, paint, wheels, mods }
}

1037
src/generator/body.ts Normal file

File diff suppressed because it is too large Load diff

435
src/generator/cage.ts Normal file
View file

@ -0,0 +1,435 @@
import type { Axle, BodyChannel, BodyPart } from './body.ts'
import { type Sink, type SinkSet, type Vec3 } from './mesh.ts'
import type { LodLevel, PaintSpec } from './spec.ts'
import { edgeKey, type PolyMesh, subdivideTimes } from './subdiv.ts'
/**
* The body skin as a subdivision surface.
*
* A coarse control cage is built from the body's profile curves: one ring of
* eleven points per half section (under-pan, sill, flank, character line,
* shoulder, glass, roof rail, roof), mirrored, at a list of stations that
* includes every panel edge, every window edge and enough samples round each
* wheel arch. Every cage face is tagged with its panel and material, and the
* sill, character line, shoulder and roof rail are creased. Catmull-Clark
* then smooths it — two levels on LOD0, one on LOD1, none on LOD2 — and the
* tags travel with every child face, so doors, bonnet, boot and glass come
* out of the subdivision already separated along their edges. Each opening
* panel is shrunk back from its neighbours by half a panel gap, given a dark
* flange into the gap, and a liner on its inside.
*/
export interface CageInput {
readonly frontS: number
readonly rearS: number
readonly cowlS: number
readonly deckS: number
readonly roofFrontS: number
readonly roofRearS: number
readonly sideWindowRear: number
readonly sideWindowFront: number
readonly bPillarS: number | undefined
readonly doorEdges: readonly number[]
readonly hood: { readonly rearS: number; readonly frontS: number } | null
readonly trunk: { readonly rearS: number; readonly frontS: number; readonly kind: 'lid' | 'tailgate' } | null
readonly arches: readonly Axle[]
readonly noseRound: number
readonly tailRound: number
readonly top: (s: number) => number
readonly belt: (s: number) => number
readonly sill: (s: number) => number
readonly sillBase: (s: number) => number
readonly halfWidth: (s: number) => number
readonly topHalfWidth: (s: number) => number
readonly surfaceY: (s: number, x: number) => number
readonly cabin: (s: number) => number
readonly bumperChannel: BodyChannel
readonly paint: PaintSpec
readonly lod: LodLevel
}
/** Ring points per half section, bottom centre (0) to top centre (10). */
const HALF = 12
const RING = 2 * HALF - 2
const GAP = 0.0025
export function buildCageSkin(c: CageInput, sinks: SinkSet): void {
const stations = cageStations(c)
const positions: number[] = []
const ringStart: number[] = []
// --- rings
for (const s of stations) {
ringStart.push(positions.length / 3)
const half = halfRing(c, s)
for (let k = 0; k < HALF; k += 1) positions.push(half[k]![0], half[k]![1], s)
for (let k = HALF - 2; k >= 1; k -= 1) positions.push(-half[k]![0], half[k]![1], s)
}
const ringIndex = (k: number, left: boolean): number => (left && k > 0 && k < HALF - 1 ? 2 * HALF - 2 - k : k)
const faces: number[][] = []
const groups: string[] = []
const creases = new Map<number, number>()
const v = (i: number, r: number): number => ringStart[i]! + (r % RING)
// --- side faces between consecutive rings
for (let i = 0; i < stations.length - 1; i += 1) {
const mid = (stations[i]! + stations[i + 1]!) / 2
for (let r = 0; r < RING; r += 1) {
faces.push([v(i, r), v(i, r + 1), v(i + 1, r + 1), v(i + 1, r)])
// Which segment of the half section this is, and on which side.
const left = r >= HALF - 1
const seg = left ? RING - 1 - r : r
groups.push(tagSide(c, mid, seg, left ? -1 : 1, stations[i]!, stations[i + 1]!))
}
}
// Longitudinal creases: sill, character line, shoulder, roof rail.
const CREASE: Record<number, number> = { 3: 3, 5: 1, 7: 2, 9: 1.5 }
for (let i = 0; i < stations.length - 1; i += 1) {
for (const [k, sharp] of Object.entries(CREASE)) {
for (const left of [false, true]) {
const r = ringIndex(Number(k), left)
creases.set(edgeKey(v(i, r), v(i + 1, r)), sharp)
}
}
}
// Power lines: two soft creases along the bonnet.
for (let i = 0; i < stations.length - 1; i += 1) {
const mid = (stations[i]! + stations[i + 1]!) / 2
if (!c.hood || mid < c.hood.rearS || mid > c.hood.frontS) continue
for (const left of [false, true]) {
const r = ringIndex(10, left)
creases.set(edgeKey(v(i, r), v(i + 1, r)), 1)
}
}
// Window frames: the transverse edges where glass meets paint.
for (let f = 0; f < faces.length; f += 1) {
if (!groups[f]!.endsWith('|glass')) continue
const face = faces[f]!
for (let k = 0; k < 4; k += 1) creases.set(edgeKey(face[k]!, face[(k + 1) % 4]!), Math.max(creases.get(edgeKey(face[k]!, face[(k + 1) % 4]!)) ?? 0, 1))
}
// --- end caps: four columns (outer, middle, middle, outer), rows by height
for (const [i, dir] of [[stations.length - 1, 1], [0, -1]] as const) {
const base = ringStart[i]!
const s = stations[i]!
const bulge = dir * Math.min(0.11, (dir > 0 ? c.noseRound : c.tailRound) * 0.35 + 0.015)
const midR: number[] = []
const midL: number[] = []
for (let k = 0; k < HALF; k += 1) {
if (k === 0 || k === HALF - 1) { midR.push(base + k); midL.push(base + k); continue }
const x = positions[(base + k) * 3]!
const y = positions[(base + k) * 3 + 1]!
const idx = positions.length / 3
positions.push(x * 0.62, y, s + bulge * 0.6, -x * 0.62, y, s + bulge * 0.6)
midR.push(idx)
midL.push(idx + 1)
}
const centre = positions.length / 3
void centre
for (let k = 0; k < HALF - 1; k += 1) {
const R0 = base + ringIndex(k, false), R1 = base + ringIndex(k + 1, false)
const L0 = base + ringIndex(k, true), L1 = base + ringIndex(k + 1, true)
const cells: [number[], 'outer' | 'mid', 1 | -1][] = [
[[R0, R1, midR[k + 1]!, midR[k]!], 'outer', 1],
[[midR[k]!, midR[k + 1]!, midL[k + 1]!, midL[k]!], 'mid', 1],
[[midL[k]!, midL[k + 1]!, L1, L0], 'outer', -1],
]
for (const [quad, column, side] of cells) {
const uniq = quad.filter((q, n) => quad.indexOf(q) === n)
if (uniq.length < 3) continue
// Built facing +Z; the rear cap is turned round.
faces.push(dir > 0 ? uniq : [...uniq].reverse())
groups.push(tagEnd(c, k, column, side, dir))
}
}
}
// --- orientation: make the volume positive
let volume = 0
for (const face of faces) {
for (let k = 1; k < face.length - 1; k += 1) {
const a = face[0]!, b = face[k]!, d = face[k + 1]!
volume += det(positions, a, b, d)
}
}
if (volume < 0) for (const face of faces) face.reverse()
const levels = c.lod === 0 ? 2 : c.lod === 1 ? 1 : 0
const mesh = subdivideTimes({ positions, faces, groups, creases }, levels)
emitSubdivided(mesh, sinks, c.lod)
}
function det(P: readonly number[], a: number, b: number, d: number): number {
const ax = P[a * 3]!, ay = P[a * 3 + 1]!, az = P[a * 3 + 2]!
const bx = P[b * 3]!, by = P[b * 3 + 1]!, bz = P[b * 3 + 2]!
const dx = P[d * 3]!, dy = P[d * 3 + 1]!, dz = P[d * 3 + 2]!
return ax * (by * dz - bz * dy) - ay * (bx * dz - bz * dx) + az * (bx * dy - by * dx)
}
/** Every panel and window edge, the arch shapes, the rounded ends, and fill. */
function cageStations(c: CageInput): number[] {
const must: number[] = []
const push = (s: number): void => { if (s > c.rearS + 0.01 && s < c.frontS - 0.01) must.push(s) }
for (const arch of c.arches) {
for (const f of [-1.06, -0.86, -0.5, 0, 0.5, 0.86, 1.06]) push(arch.s + f * arch.archRadius)
}
for (const f of [0.1, 0.32, 0.6, 0.9]) {
push(c.frontS - c.noseRound * f)
push(c.rearS + c.tailRound * f)
}
for (const s of [c.cowlS, c.deckS, c.roofFrontS, c.roofRearS, c.sideWindowRear, c.sideWindowFront, ...c.doorEdges]) push(s)
if (c.bPillarS !== undefined) { push(c.bPillarS - 0.05); push(c.bPillarS + 0.05) }
if (c.hood) { push(c.hood.rearS); push(c.hood.frontS) }
if (c.trunk) { push(c.trunk.frontS); if (c.trunk.kind === 'lid') push(c.trunk.rearS) }
// Lamp edges.
push(c.frontS - 0.16)
push(c.rearS + 0.14)
const list = [c.rearS, ...must, c.frontS].sort((a, b) => a - b)
const merged: number[] = []
for (const s of list) {
const last = merged[merged.length - 1]
if (last !== undefined && s - last < 0.025) continue
merged.push(s)
}
// Fill long spans so the surface has something to bend with.
const out: number[] = []
for (let k = 0; k < merged.length; k += 1) {
const s = merged[k]!
out.push(s)
const next = merged[k + 1]
if (next === undefined) continue
const n = Math.floor((next - s) / 0.32)
for (let j = 1; j <= n; j += 1) out.push(s + ((next - s) * j) / (n + 1))
}
return out
}
/** Half a section at station s: x ≥ 0, from the under-pan centre to the roof centre. */
function halfRing(c: CageInput, s: number): [number, number][] {
const hw = c.halfWidth(s)
const thw = Math.min(c.topHalfWidth(s), hw * 0.97)
const sb = c.sillBase(s)
const sl = c.sill(s)
const bt = c.belt(s)
const tp = Math.max(c.top(s), bt)
const cab = c.cabin(s)
const inArch = sl > sb + 0.015
const floor = sb - 0.05
const lowY = Math.max(sl + 0.05, sb + (bt - sb) * 0.33)
const charY = Math.max(lowY + 0.04, sb + (bt - sb) * 0.72)
const shoulderX = hw * 0.985
const k7x = shoulderX + (thw - shoulderX) * 0.5
const glassMidY = bt + (tp - bt) * 0.5
const k7y = cab * glassMidY + (1 - cab) * c.surfaceY(s, k7x)
const lampY = Math.max(charY + 0.02, bt - 0.065)
return [
[0, floor],
[hw * 0.55, floor],
inArch ? [hw * 0.62, sl] : [hw * 0.88, sb - 0.02],
[hw * 0.94, sl],
[hw * 0.985, Math.min(lowY, charY - 0.02)],
[hw, Math.min(charY, lampY - 0.02)],
[hw * 0.995, Math.min(lampY, bt - 0.012)],
[shoulderX, bt],
[k7x, Math.max(k7y, bt + 0.005)],
[thw, Math.max(tp, bt + 0.01)],
[thw * 0.5, c.surfaceY(s, thw * 0.5)],
[0, c.surfaceY(s, 0)],
]
}
function doorOf(c: CageInput, s: number): 'F' | 'R' | null {
const e = c.doorEdges
if (e.length >= 2 && s < e[0]! && s > e[1]!) return 'F'
if (e.length >= 3 && s < e[1]! && s > e[2]!) return 'R'
return null
}
function paintFor(c: CageInput, region: 'roof' | 'lower' | 'body'): BodyChannel {
const t = c.paint.twoTone
if (region === 'roof' && (t === 'roof' || t === 'upper')) return 'paint2'
if (region === 'lower' && t === 'lower') return 'paint2'
return 'paint'
}
/** Part and material of a side face: `seg` 0–9 from the under-pan up. */
function tagSide(c: CageInput, s: number, seg: number, side: 1 | -1, s0: number, s1: number): string {
const door = doorOf(c, s)
const doorPart = door ? (`door${door}${side > 0 ? 'L' : 'R'}` as BodyPart) : null
const cab = Math.min(c.cabin(s0), c.cabin(s1))
const nearFront = s > c.frontS - Math.min(0.42, c.noseRound + 0.22)
const nearRear = s < c.rearS + Math.min(0.38, c.tailRound + 0.2)
const inHood = c.hood !== null && s > c.hood.rearS && s < c.hood.frontS
const trunk = c.trunk
const inLid = trunk !== null && trunk.kind === 'lid' && s > trunk.rearS && s < trunk.frontS
const inGate = trunk !== null && trunk.kind === 'tailgate' && s < trunk.frontS
// seg: 0–2 under, 3 lower flank, 4–5 flank, 6 lamp band, 7–8 glass band, 9–10 top.
if (seg <= 2) return `body|underbody`
if (seg <= 6) {
const part = doorPart ?? 'body'
if ((nearFront || nearRear) && seg === 3) {
return `body|${c.bumperChannel === 'paint' ? paintFor(c, 'lower') : c.bumperChannel}`
}
// Slim lamps that wrap a hand's width round the corner.
if (seg === 6 && s > c.frontS - 0.2) return `body|lightHead`
if (seg === 6 && s < c.rearS + 0.16) return `${c.trunk?.kind === 'lid' ? 'body' : 'body'}|lightTail`
return `${part}|${seg === 3 ? paintFor(c, 'lower') : 'paint'}`
}
if (seg <= 8) {
if (cab > 0.5) {
const onPillar = c.bPillarS !== undefined && Math.abs(s - c.bPillarS) < 0.05
const inWindow = s > c.sideWindowRear && s < c.sideWindowFront && !onPillar
const part = doorPart ?? 'body'
return `${inWindow ? part : 'body'}|${inWindow ? 'glass' : paintFor(c, 'roof')}`
}
if (seg === 8 && inHood) return `hood|paint`
if (seg === 8 && inLid) return `trunk|paint`
return `body|paint`
}
// Top: bonnet, windshield, roof, rear window, boot.
if (inHood) return `hood|paint`
if (inLid) return `trunk|paint`
const windshield = s > c.roofFrontS && s < c.cowlS && cab > 0.3
const rearWindow = s > c.deckS && s < c.roofRearS && cab > 0.3
if (inGate) return `trunk|${rearWindow ? 'glass' : paintFor(c, 'roof')}`
if (windshield || rearWindow) return `body|glass`
return `body|${cab > 0.5 ? paintFor(c, 'roof') : 'paint'}`
}
/** Part and material of an end-cap face: `row` 0–9 from the bottom. */
function tagEnd(c: CageInput, row: number, column: 'outer' | 'mid', side: 1 | -1, dir: 1 | -1): string {
void side
// row: 0–1 under, 2 splitter / diffuser, 3 lower fascia, 4–5 fascia, 6 lamp band, 7+ lids.
if (row <= 1) return 'body|underbody'
if (row === 2) return 'body|trim'
const bumper = `body|${c.bumperChannel === 'paint' ? paintFor(c, 'lower') : c.bumperChannel}`
if (dir > 0) {
if (row === 3) return column === 'mid' ? 'body|trim' : bumper
if (row === 4) return column === 'mid' ? 'body|trim' : 'body|paint'
if (row === 5) return 'body|paint'
if (row === 6) return column === 'outer' ? 'body|lightHead' : 'body|trim'
return c.hood && row >= 8 ? 'hood|paint' : 'body|paint'
}
const gate = c.trunk?.kind === 'tailgate'
const lid = c.trunk?.kind === 'lid'
if (row === 3) return column === 'mid' ? 'body|trim' : bumper
// A full-width light bar across the boot.
if (row === 6) return `${gate || lid ? 'trunk' : 'body'}|lightTail`
if (gate && row >= 4 && column === 'mid') return 'trunk|paint'
if ((gate || lid) && row >= 7) return 'trunk|paint'
return 'body|paint'
}
/** Triangulates the limit mesh into the sinks, opening the panel gaps. */
export function emitSubdivided(m: PolyMesh, sinks: SinkSet, lod: LodLevel): void {
const P = m.positions
const nv = P.length / 3
// Smooth normals over the whole skin, ignoring panels and materials.
const N = new Float64Array(nv * 3)
for (const face of m.faces) {
for (let k = 1; k < face.length - 1; k += 1) {
const a = face[0]!, b = face[k]!, d = face[k + 1]!
const ux = P[b * 3]! - P[a * 3]!, uy = P[b * 3 + 1]! - P[a * 3 + 1]!, uz = P[b * 3 + 2]! - P[a * 3 + 2]!
const wx = P[d * 3]! - P[a * 3]!, wy = P[d * 3 + 1]! - P[a * 3 + 1]!, wz = P[d * 3 + 2]! - P[a * 3 + 2]!
const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx
for (const q of [a, b, d]) { N[q * 3] = N[q * 3]! + nx; N[q * 3 + 1] = N[q * 3 + 1]! + ny; N[q * 3 + 2] = N[q * 3 + 2]! + nz }
}
}
const normal = (q: number): Vec3 => {
const x = N[q * 3]!, y = N[q * 3 + 1]!, z = N[q * 3 + 2]!
const l = Math.hypot(x, y, z) || 1
return [x / l, y / l, z / l]
}
// Panels: which parts touch each vertex.
const partOfFace = m.groups.map((g) => g.slice(0, g.indexOf('|')))
const partsAt: Set<string>[] = Array.from({ length: nv }, () => new Set())
m.faces.forEach((face, f) => { for (const q of face) partsAt[q]!.add(partOfFace[f]!) })
// Half a gap back from each neighbour, along the surface, into the panel.
const shift = new Map<string, Vec3>()
if (lod < 2) {
const pull = new Map<string, [number, number, number]>()
m.faces.forEach((face, f) => {
const part = partOfFace[f]!
let cx = 0, cy = 0, cz = 0
for (const q of face) { cx += P[q * 3]!; cy += P[q * 3 + 1]!; cz += P[q * 3 + 2]! }
cx /= face.length; cy /= face.length; cz /= face.length
for (const q of face) {
if (partsAt[q]!.size < 2) continue
const key = `${q}|${part}`
const acc = pull.get(key) ?? [0, 0, 0]
acc[0] += cx - P[q * 3]!; acc[1] += cy - P[q * 3 + 1]!; acc[2] += cz - P[q * 3 + 2]!
pull.set(key, acc)
}
})
for (const [key, d] of pull) {
const q = Number(key.slice(0, key.indexOf('|')))
const n = normal(q)
const along = d[0] * n[0] + d[1] * n[1] + d[2] * n[2]
const t: Vec3 = [d[0] - n[0] * along, d[1] - n[1] * along, d[2] - n[2] * along]
const l = Math.hypot(t[0], t[1], t[2])
if (l > 1e-9) shift.set(key, [t[0] / l * GAP, t[1] / l * GAP, t[2] / l * GAP])
}
}
const at = (q: number, part: string): Vec3 => {
const d = shift.get(`${q}|${part}`)
return d ? [P[q * 3]! + d[0], P[q * 3 + 1]! + d[1], P[q * 3 + 2]! + d[2]] : [P[q * 3]!, P[q * 3 + 1]!, P[q * 3 + 2]!]
}
const caches = new Map<Sink, Map<number, number>>()
const vertexIn = (sink: Sink, q: number, part: string): number => {
let cache = caches.get(sink)
if (!cache) { cache = new Map(); caches.set(sink, cache) }
let id = cache.get(q)
if (id === undefined) { id = sink.vertex(at(q, part), normal(q)); cache.set(q, id) }
return id
}
m.faces.forEach((face, f) => {
const group = m.groups[f]!
const part = partOfFace[f]!
const sink = sinks.get(group)
const ids = face.map((q) => vertexIn(sink, q, part))
for (let k = 1; k < ids.length - 1; k += 1) sink.triangle(ids[0]!, ids[k]!, ids[k + 1]!)
// The inside of an opening panel: a door card, a bonnet liner.
if (part !== 'body' && lod < 2) {
const inner = sinks.get(`${part}|${part.startsWith('door') ? 'interior' : 'underbody'}`)
const depth = part.startsWith('door') ? 0.045 : 0.03
const pts = face.map((q) => {
const p = at(q, part)
const n = normal(q)
return inner.vertex([p[0] - n[0] * depth, p[1] - n[1] * depth, p[2] - n[2] * depth], [-n[0], -n[1], -n[2]])
})
for (let k = 1; k < pts.length - 1; k += 1) inner.triangle(pts[0]!, pts[k + 1]!, pts[k]!)
}
})
// Flanges: a dark strip down into every panel gap, from both sides.
if (lod < 2) {
const edgeFaces = new Map<number, number[]>()
m.faces.forEach((face, f) => {
for (let k = 0; k < face.length; k += 1) {
const key = edgeKey(face[k]!, face[(k + 1) % face.length]!)
const list = edgeFaces.get(key)
if (list) list.push(f)
else edgeFaces.set(key, [f])
}
})
m.faces.forEach((face, f) => {
const part = partOfFace[f]!
for (let k = 0; k < face.length; k += 1) {
const a = face[k]!, b = face[(k + 1) % face.length]!
const others = edgeFaces.get(edgeKey(a, b))!
if (!others.some((o) => o !== f && partOfFace[o] !== part)) continue
const sink = sinks.get(`${part}|underbody`)
const pa = at(a, part), pb = at(b, part)
const na = normal(a), nb = normal(b)
const d = 0.018
const qa: Vec3 = [pa[0] - na[0] * d, pa[1] - na[1] * d, pa[2] - na[2] * d]
const qb: Vec3 = [pb[0] - nb[0] * d, pb[1] - nb[1] * d, pb[2] - nb[2] * d]
// Facing out of the panel, into the gap.
sink.flat(pa, qa, qb)
sink.flat(pa, qb, pb)
}
})
}
}

279
src/generator/cageAsset.ts Normal file
View file

@ -0,0 +1,279 @@
import type { Axle, BodyChannel } from './body.ts'
import { emitSubdivided } from './cage.ts'
import sedan from './cages/sedan.json'
import type { SinkSet } from './mesh.ts'
import type { BodySpec, LodLevel, PaintSpec } from './spec.ts'
import { edgeKey, type PolyMesh, subdivideTimes } from './subdiv.ts'
/**
* Authored body cages: control meshes built by the Blender scripts in
* assets/src (`bun run cages:build`) and checked in as JSON. The runtime never
* needs Blender. A cage carries its quads, a panel/material tag per face,
* crease sharpness per edge, the station list (windscreen, roof, deck, door
* edges, bonnet and boot), the axles it was drawn round, anchors, and a table
* of profile samples (top, belt, sill, widths) that the rest of the
* generator — interior, engine bay, details, rig — is laid out from.
*/
export interface CageAsset {
readonly format: string
readonly style: string
readonly base: { readonly length: number; readonly width: number; readonly height: number; readonly wheelbase: number; readonly frontOverhang: number; readonly wheelRadius: number }
readonly positions: readonly number[]
readonly faces: readonly (readonly number[])[]
readonly tagNames: readonly string[]
readonly faceTags: readonly number[]
readonly creases: readonly (readonly [number, number, number])[]
readonly stations: {
readonly cowl: number; readonly deck: number; readonly roofFront: number; readonly roofRear: number
readonly sideWindowRear: number; readonly sideWindowFront: number; readonly doorEdges: readonly number[]; readonly bPillar: number | null
}
readonly hood: readonly [number, number] | null
readonly trunk: { readonly kind: 'lid' | 'tailgate'; readonly front: number; readonly rear: number } | null
/** How far the nose face leans back from bumper to bonnet edge, metres. */
readonly noseRake?: number
readonly axles: readonly { readonly z: number; readonly radius: number }[]
readonly archGap: number
readonly anchors: Readonly<Record<string, readonly number[]>>
readonly frame: { readonly columns: readonly string[]; readonly rows: readonly (readonly number[])[] }
}
const CAGES: Readonly<Record<string, CageAsset>> = { sedan: sedan as unknown as CageAsset }
export function cageFor(style: string): CageAsset | null {
return CAGES[style] ?? null
}
/**
* A cage fitted to a spec: Z remapped piecewise so the authored arches land
* on the spec's axles (length, wheelbase and overhangs all morph at once),
* X scaled to the width, Y scaled to the roof height and lifted by the ride.
*/
export interface FittedCage {
readonly z: (s: number) => number
readonly zInverse: (s: number) => number
readonly sx: number
readonly sy: number
readonly ride: number
readonly top: (s: number) => number
readonly belt: (s: number) => number
readonly sill: (s: number) => number
readonly sillBase: (s: number) => number
readonly halfWidth: (s: number) => number
readonly topHalfWidth: (s: number) => number
readonly cabin: (s: number) => number
readonly surfaceY: (s: number, x: number) => number
readonly cowlS: number
readonly deckS: number
readonly roofFrontS: number
readonly roofRearS: number
readonly sideWindowRear: number
readonly sideWindowFront: number
readonly doorEdges: number[]
readonly hood: { readonly rearS: number; readonly frontS: number } | null
readonly trunk: { readonly rearS: number; readonly frontS: number; readonly kind: 'lid' | 'tailgate' } | null
/** How far the nose face sits behind the body's front end at height y. */
readonly noseBack: (y: number) => number
readonly asset: CageAsset
}
export function fitCage(asset: CageAsset, body: BodySpec, axles: readonly { readonly s: number; readonly radius: number }[], ride: number): FittedCage {
const b = asset.base
const L = body.length
// Authored anchors along Z, and where the spec wants them.
const from = [-b.length / 2, ...asset.axles.map((a) => a.z).sort((p, q) => p - q), b.length / 2]
const specAxles = axles.map((a) => a.s).sort((p, q) => p - q)
const to = [-L / 2, ...(specAxles.length === asset.axles.length ? specAxles : asset.axles.map((a) => a.z * L / b.length).sort((p, q) => p - q)), L / 2]
const piecewise = (xs: readonly number[], ys: readonly number[]) => (v: number): number => {
let k = 0
while (k < xs.length - 2 && v > xs[k + 1]!) k += 1
const t = (v - xs[k]!) / (xs[k + 1]! - xs[k]!)
return ys[k]! + (ys[k + 1]! - ys[k]!) * t
}
const z = piecewise(from, to)
const zInverse = piecewise(to, from)
const sx = body.width / b.width
// The cage's roof (at its edge) is the spec's roofHeight.
const col = (name: string): number => asset.frame.columns.indexOf(name)
const rows = asset.frame.rows
const baseRoof = Math.max(...rows.map((r) => r[col('top')]!))
const sy = body.roofHeight / baseRoof
const sample = (name: string) => {
const c = col(name)
return (s: number): number => {
const zz = zInverse(s)
let k = 0
while (k < rows.length - 2 && zz > rows[k + 1]![0]!) k += 1
const r0 = rows[k]!, r1 = rows[k + 1]!
const t = Math.min(1, Math.max(0, (zz - r0[0]!) / (r1[0]! - r0[0]! || 1)))
return r0[c]! + (r1[c]! - r0[c]!) * t
}
}
const topR = sample('top'), beltR = sample('belt'), sillR = sample('sill'), sillBaseR = sample('sillBase')
const hwR = sample('halfWidth'), thwR = sample('topHalfWidth'), crownR = sample('crown'), cabinR = sample('cabin')
const top = (s: number): number => topR(s) * sy + ride
const topHalfWidth = (s: number): number => thwR(s) * sx
const st = asset.stations
const noseLow = sillBaseR(L / 2) * sy + ride
const noseHigh = topR(L / 2) * sy + ride
return {
z, zInverse, sx, sy, ride,
top,
belt: (s) => beltR(s) * sy + ride,
sill: (s) => sillR(s) * sy + ride,
sillBase: (s) => sillBaseR(s) * sy + ride,
halfWidth: (s) => hwR(s) * sx,
topHalfWidth,
cabin: cabinR,
surfaceY: (s, x) => {
const w = Math.max(1e-6, topHalfWidth(s))
const xx = Math.min(Math.abs(x), w)
return top(s) + crownR(s) * sy * (1 - (xx / w) ** 2)
},
cowlS: z(st.cowl), deckS: z(st.deck), roofFrontS: z(st.roofFront), roofRearS: z(st.roofRear),
sideWindowRear: z(st.sideWindowRear), sideWindowFront: z(st.sideWindowFront),
doorEdges: st.doorEdges.map(z),
hood: asset.hood ? { rearS: z(asset.hood[0]), frontS: z(asset.hood[1]) } : null,
trunk: asset.trunk ? { rearS: z(asset.trunk.rear), frontS: z(asset.trunk.front), kind: asset.trunk.kind } : null,
noseBack: (y) => (asset.noseRake ?? 0) * Math.min(1, Math.max(0, (y - noseLow) / (noseHigh - noseLow || 1))),
asset,
}
}
/** Arches as the body frame describes them, from the spec's axles. */
export function cageArches(fit: FittedCage, axles: readonly { readonly s: number; readonly radius: number }[]): Axle[] {
return axles.map((a) => ({ s: a.s, y: a.radius, archRadius: a.radius + fit.asset.archGap, archY: a.radius + fit.ride }))
}
/** Morphs, subdivides and emits the authored skin. */
export function emitCageAsset(fit: FittedCage, sinks: SinkSet, lod: LodLevel, paint: PaintSpec, bumperChannel: BodyChannel): void {
const a = fit.asset
const positions: number[] = []
for (let i = 0; i < a.positions.length; i += 3) {
positions.push(a.positions[i]! * fit.sx, a.positions[i + 1]! * fit.sy + fit.ride, fit.z(a.positions[i + 2]!))
}
const roof: BodyChannel = paint.twoTone === 'roof' || paint.twoTone === 'upper' ? 'paint2' : 'paint'
const lower: BodyChannel = paint.twoTone === 'lower' ? 'paint2' : 'paint'
const names = a.tagNames.map((t) => {
const [part, channel] = t.split('|') as [string, string]
const mapped = channel === 'roof' ? roof : channel === 'bumper' ? (bumperChannel === 'paint' ? lower : bumperChannel) : channel
return `${part}|${mapped}`
})
const creases = new Map<number, number>()
const mesh: PolyMesh = {
positions,
faces: a.faces.map((f) => [...f]),
groups: a.faceTags.map((t) => names[t]!),
creases,
}
for (const [p, q, s] of a.creases) creases.set(edgeKey(p, q), s)
const levels = lod === 0 ? 2 : lod === 1 ? 1 : 0
const skin = subdivideTimes(mesh, levels)
if (paint.livery !== 'none') paintLivery(skin, fit, paint.livery)
emitSubdivided(skin, sinks, lod)
}
/**
* Livery on an authored skin, with the lofted body's layout: twin stripes run
* along the top either side of the centre line; a side stripe sits just under
* the shoulder; a rally band covers the flank between the bumpers, with the
* twin stripes on top. Painted faces that straddle a stripe's edge are cut
* along it first (the cut point on an edge is shared by both faces, so no
* cracks), then each piece moves to the stripe channel by where it sits.
* Panel parts are kept, so stripes open with the doors.
*/
function paintLivery(m: PolyMesh, fit: FittedCage, livery: PaintSpec['livery']): void {
const P = m.positions
let front = -Infinity, rear = Infinity
for (let i = 2; i < P.length; i += 3) { front = Math.max(front, P[i]!); rear = Math.min(rear, P[i]!) }
const twin = livery === 'stripes' || livery === 'rally'
const STRIPE = 0.13, GAP = 0.13 * 0.25
const band: readonly [number, number] | null = livery === 'side-stripe' ? [0.66, 0.74] : livery === 'rally' ? [0.28, 0.62] : null
const rallyEnds: readonly [number, number] = [rear + 0.5, front - 0.55]
// Per-vertex fields the stripe edges are drawn in.
const fieldX = (q: number): number => P[q * 3]!
const fieldZ = (q: number): number => P[q * 3 + 2]!
const fieldV = (q: number): number => {
const z = P[q * 3 + 2]!, sill = fit.sill(z)
return (P[q * 3 + 1]! - sill) / Math.max(1e-6, fit.belt(z) - sill)
}
const cache = new Map<string, number>()
const cut = (a: number, b: number, field: (q: number) => number, name: string, t: number): number => {
const key = `${Math.min(a, b)}:${Math.max(a, b)}:${name}:${t}`
const hit = cache.get(key)
if (hit !== undefined) return hit
const fa = field(a), fb = field(b)
const u = (t - fa) / (fb - fa)
const q = P.length / 3
for (let k = 0; k < 3; k += 1) P.push(P[a * 3 + k]! + (P[b * 3 + k]! - P[a * 3 + k]!) * u)
cache.set(key, q)
return q
}
/** Splits a polygon where `field` crosses `t`: the pieces below and above. */
const split = (poly: number[], field: (q: number) => number, name: string, t: number): number[][] => {
const below: number[] = [], above: number[] = []
for (let i = 0; i < poly.length; i += 1) {
const a = poly[i]!, b = poly[(i + 1) % poly.length]!
const fa = field(a), fb = field(b)
;(fa < t ? below : above).push(a)
if ((fa < t) !== (fb < t)) {
const q = cut(a, b, field, name, t)
below.push(q)
above.push(q)
}
}
return [below, above].filter((p) => p.length >= 3)
}
const normalOf = (poly: readonly number[]): [number, number, number] => {
let nx = 0, ny = 0, nz = 0
for (let i = 0; i < poly.length; i += 1) {
const a = poly[i]!, b = poly[(i + 1) % poly.length]!
const ay = P[a * 3 + 1]!, az = P[a * 3 + 2]!, ax = P[a * 3]!
const by = P[b * 3 + 1]!, bz = P[b * 3 + 2]!, bx = P[b * 3]!
nx += (ay - by) * (az + bz); ny += (az - bz) * (ax + bx); nz += (ax - bx) * (ay + by)
}
const l = Math.hypot(nx, ny, nz) || 1
return [nx / l, ny / l, nz / l]
}
const centre = (poly: readonly number[]): [number, number, number] => {
let x = 0, y = 0, z = 0
for (const q of poly) { x += P[q * 3]!; y += P[q * 3 + 1]!; z += P[q * 3 + 2]! }
return [x / poly.length, y / poly.length, z / poly.length]
}
const faces: number[][] = []
const groups: string[] = []
m.faces.forEach((face, f) => {
const group = m.groups[f]!
const bar = group.indexOf('|')
const channel = group.slice(bar + 1)
if (channel !== 'paint' && channel !== 'paint2') { faces.push(face); groups.push(group); return }
const [, up, ] = normalOf(face)
const out = Math.abs(normalOf(face)[0])
let pieces = [face]
const cutAll = (field: (q: number) => number, name: string, ts: readonly number[]): void => {
for (const t of ts) pieces = pieces.flatMap((p) => split(p, field, name, t))
}
if (twin && up > 0.45) cutAll(fieldX, 'x', [-STRIPE, -GAP, GAP, STRIPE])
if (band && out > 0.45) {
cutAll(fieldV, 'v', band)
if (livery === 'rally') cutAll(fieldZ, 'z', rallyEnds)
}
for (const piece of pieces) {
const [cx, cy, cz] = centre(piece)
let stripe = false
if (twin && up > 0.45) stripe = Math.abs(cx) < STRIPE && Math.abs(cx) > GAP
if (!stripe && band && out > 0.45) {
const sill = fit.sill(cz)
const v = (cy - sill) / Math.max(1e-6, fit.belt(cz) - sill)
stripe = v > band[0] && v < band[1] && (livery !== 'rally' || (cz > rallyEnds[0] && cz < rallyEnds[1]))
}
faces.push(piece)
groups.push(stripe ? `${group.slice(0, bar)}|stripe` : group)
}
})
m.faces.length = 0
m.faces.push(...faces)
m.groups.length = 0
m.groups.push(...groups)
}

File diff suppressed because one or more lines are too long

83
src/generator/collider.ts Normal file
View file

@ -0,0 +1,83 @@
import { Box3, BufferAttribute, BufferGeometry, Mesh, type Object3D, Vector3 } from 'three'
import { ConvexHull } from 'three/addons/math/ConvexHull.js'
import { tagOf } from './rig.ts'
/**
* Collision shapes for physics engines.
*
* `hull` is one convex hull of the body, without the wheels: every engine
* with a raycast-vehicle model (Rapier, cannon-es, Ammo, PhysX) wants the
* chassis as a convex shape and casts the wheels itself, from the `wheels`
* list. `boxes` is the cheaper compound for engines or LOD tiers that would
* rather not have a hull: a chassis box and a cabin box.
*/
export interface VehicleCollider {
readonly hull: BufferGeometry
readonly boxes: readonly { readonly center: Vector3; readonly size: Vector3 }[]
}
const MAX_HULL_POINTS = 1500
export function buildCollider(
root: Object3D,
cabin: { readonly lowY: number; readonly beltY: number; readonly frontS: number; readonly rearS: number },
): VehicleCollider {
root.updateMatrixWorld(true)
const inverse = root.matrixWorld.clone().invert()
const points: Vector3[] = []
const insideWheel = (object: Object3D): boolean => {
for (let o: Object3D | null = object; o && o !== root; o = o.parent) {
const tag = tagOf(o)
if (tag && (tag.role === 'wheel' || tag.role === 'wheelSpin' || tag.role === 'wheelCamber')) return true
}
return false
}
root.traverse((object) => {
if (!(object instanceof Mesh) || insideWheel(object)) return
const position = object.geometry.getAttribute('position')
if (!position) return
const stride = Math.max(1, Math.floor(position.count / 400))
for (let i = 0; i < position.count; i += stride) {
points.push(new Vector3().fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld).applyMatrix4(inverse))
}
})
const sample = points.length > MAX_HULL_POINTS
? points.filter((_, i) => i % Math.ceil(points.length / MAX_HULL_POINTS) === 0)
: points
const hull = new ConvexHull().setFromPoints(sample)
const positions: number[] = []
for (const face of hull.faces) {
let edge = face.edge
const loop: Vector3[] = []
do {
loop.push(edge.head().point)
edge = edge.next
} while (edge !== face.edge)
for (let k = 1; k < loop.length - 1; k += 1) {
for (const p of [loop[0]!, loop[k]!, loop[k + 1]!]) positions.push(p.x, p.y, p.z)
}
}
const geometry = new BufferGeometry()
geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3))
geometry.computeVertexNormals()
geometry.computeBoundingBox()
const box = geometry.boundingBox ?? new Box3()
const size = box.getSize(new Vector3())
const center = box.getCenter(new Vector3())
const chassisTop = Math.min(box.max.y, cabin.beltY)
const chassis = {
center: new Vector3(center.x, (cabin.lowY + chassisTop) / 2, center.z),
size: new Vector3(size.x, Math.max(0.1, chassisTop - cabin.lowY), size.z),
}
const boxes = [chassis]
if (box.max.y - chassisTop > 0.15) {
boxes.push({
center: new Vector3(center.x, (chassisTop + box.max.y) / 2, (cabin.frontS + cabin.rearS) / 2),
size: new Vector3(size.x * 0.82, box.max.y - chassisTop, Math.max(0.3, cabin.frontS - cabin.rearS)),
})
}
return { hull: geometry, boxes }
}

84
src/generator/curve.ts Normal file
View file

@ -0,0 +1,84 @@
/**
* One-dimensional curves: the side profile of a car is a handful of these.
*
* Monotone cubic (Fritsch–Carlson) interpolation is used rather than
* Catmull–Rom because it never overshoots. A roofline that dips below its own
* keypoints between the windshield and the rear window reads as a dented
* roof, and a Catmull–Rom spline through a steep windshield does exactly that.
*/
export interface Key {
readonly t: number
readonly y: number
}
export interface Curve {
(t: number): number
}
export function monotoneCurve(input: readonly Key[]): Curve {
const keys = [...input].sort((a, b) => a.t - b.t)
// Collapse coincident keys; the slope computation divides by the spacing.
const pts: Key[] = []
for (const key of keys) {
const last = pts[pts.length - 1]
if (last && key.t - last.t < 1e-6) pts[pts.length - 1] = { t: last.t, y: (last.y + key.y) / 2 }
else pts.push(key)
}
const n = pts.length
if (n === 0) return () => 0
if (n === 1) return () => pts[0]!.y
const delta: number[] = []
for (let i = 0; i < n - 1; i += 1) {
delta.push((pts[i + 1]!.y - pts[i]!.y) / (pts[i + 1]!.t - pts[i]!.t))
}
const slope: number[] = new Array<number>(n).fill(0)
slope[0] = delta[0]!
slope[n - 1] = delta[n - 2]!
for (let i = 1; i < n - 1; i += 1) {
const a = delta[i - 1]!
const b = delta[i]!
slope[i] = a * b <= 0 ? 0 : (a + b) / 2
}
for (let i = 0; i < n - 1; i += 1) {
const d = delta[i]!
if (d === 0) { slope[i] = 0; slope[i + 1] = 0; continue }
const a = slope[i]! / d
const b = slope[i + 1]! / d
const h = a * a + b * b
if (h > 9) {
const k = 3 / Math.sqrt(h)
slope[i] = k * a * d
slope[i + 1] = k * b * d
}
}
return (t: number): number => {
if (t <= pts[0]!.t) return pts[0]!.y
if (t >= pts[n - 1]!.t) return pts[n - 1]!.y
let lo = 0
let hi = n - 1
while (hi - lo > 1) {
const mid = (lo + hi) >> 1
if (pts[mid]!.t <= t) lo = mid
else hi = mid
}
const p0 = pts[lo]!
const p1 = pts[hi]!
const h = p1.t - p0.t
const s = (t - p0.t) / h
const s2 = s * s
const s3 = s2 * s
return (2 * s3 - 3 * s2 + 1) * p0.y
+ (s3 - 2 * s2 + s) * h * slope[lo]!
+ (-2 * s3 + 3 * s2) * p1.y
+ (s3 - s2) * h * slope[hi]!
}
}
export const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v))
export const lerp = (a: number, b: number, t: number): number => a + (b - a) * t
export const smoothstep = (e0: number, e1: number, x: number): number => {
const t = clamp((x - e0) / (e1 - e0), 0, 1)
return t * t * (3 - 2 * t)
}

44
src/generator/export.ts Normal file
View file

@ -0,0 +1,44 @@
import type { Object3D } from 'three'
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'
import type { LodLevel } from './spec.ts'
import type { Vehicle } from './vehicle.ts'
export interface GlbOptions {
/** Which level to export. Default 0. `'all'` puts every level in one file. */
readonly lod?: LodLevel | 'all'
/** Include the open/roll animation clips. Default true. */
readonly animations?: boolean
}
/**
* Binary glTF of a vehicle.
*
* What survives the trip, and why each one matters to a game:
* - the node hierarchy with every pivot at its hinge or axle, so a door is
* opened by rotating one node;
* - `userData.vehicleGenerator` tags as glTF `extras`, which `createRig()` reads back;
* - vertex colours (panel-gap shading) as COLOR_0;
* - clearcoat and iridescence through KHR_materials_* extensions;
* - the animation clips, addressed by node name.
*/
export async function exportVehicleGlb(vehicle: Vehicle, options: GlbOptions = {}): Promise<ArrayBuffer> {
const which = options.lod ?? 0
let root: Object3D
if (which === 'all') {
root = vehicle.lod
} else {
const level = vehicle.lods.find((l) => l.level === which) ?? vehicle.lods[0]!
root = level.group
}
const exporter = new GLTFExporter()
const result = await exporter.parseAsync(root, {
binary: true,
trs: true,
onlyVisible: false,
includeCustomExtensions: false,
animations: options.animations === false || which !== 0 ? [] : [...vehicle.animations],
})
if (!(result instanceof ArrayBuffer)) throw new Error('GLTFExporter did not return binary output')
return result
}

26
src/generator/index.ts Normal file
View file

@ -0,0 +1,26 @@
/**
* vehicle-generator — procedural, game-ready vehicles for three.js.
*
* const car = generateVehicle(preset('hatchback'))
* scene.add(car.group)
* car.rig.setSteer(0.3)
* car.rig.open('doorFL', 1)
*/
export { generateVehicle, sanitizeSpec } from './vehicle.ts'
export type { GenerateOptions, LodInfo, Vehicle, WheelId, WheelInfo } from './vehicle.ts'
export { preset, BODY_STYLES, DEFAULT_PAINT, styleLabel } from './presets.ts'
export { blendSpecs, randomSpec } from './blend.ts'
export type { RandomOptions } from './blend.ts'
export { MODS, MOD_KINDS, modParams, applyModSpecs } from './mods.ts'
export type { ModDefinition, ModParam, ModParamNumber, ModParamSelect } from './mods.ts'
export { PALETTES, palettesFor, mixHex } from './palette.ts'
export type { Palette } from './palette.ts'
export { createRig, rigAnimations, tagOf } from './rig.ts'
export type { OpenablePart, RigTag, RigWheel, VehicleRig } from './rig.ts'
export { exportVehicleGlb } from './export.ts'
export type { GlbOptions } from './export.ts'
export { applyPaint, CHANNELS } from './materials.ts'
export type { Channel, VehicleMaterials } from './materials.ts'
export type { VehicleCollider } from './collider.ts'
export { createRandom } from './random.ts'
export type * from './spec.ts'

109
src/generator/interior.ts Normal file
View file

@ -0,0 +1,109 @@
import type { BodyFrame } from './body.ts'
import { lerp } from './curve.ts'
import { circle, emitBeam, emitTube, roundedRect, type SinkSet, type Vec3 } from './mesh.ts'
import type { LodLevel } from './spec.ts'
/**
* The interior HINT: enough that a window does not show an empty shell and an
* open door shows somewhere to sit. Seats, a dash, a console, a floor, a
* headliner and a steering wheel — no more. It is dark, it is behind tinted
* glass, and it is cheap.
*/
export interface SteeringRig {
/** Hub centre in vehicle space. */
readonly pivot: Vec3
/** Column tilt from vertical toward the driver, radians. */
readonly tilt: number
}
export function buildInterior(frame: BodyFrame, sinks: SinkSet, lod: LodLevel): SteeringRig | null {
if (lod === 2) return null
const sink = sinks.get('body|interior')
const wheelSink = sinks.get('steering|interior')
const front = Math.min(frame.cowlS - 0.12, frame.hood ? frame.hood.rearS - 0.2 : frame.cowlS - 0.12)
const rear = Math.max(frame.roofRearS + 0.05, frame.deckS + 0.05)
const mid = (front + rear) / 2
const floor = frame.sill(mid) + 0.1
const roof = frame.roofHeight
const hasRoof = frame.cabin(mid) > 0.5
const halfW = frame.halfWidth(mid) * 0.8
const bevel = 0.04
// Floor pan and firewall: what you see past an open door instead of the road.
emitBeam(sink, [0, floor, rear], [0, floor, front + 0.1], halfW * 2, 0.04, 0.01)
const dashTop = Math.min(frame.belt(front) - 0.02, floor + 0.62)
emitBeam(sink, [0, floor, front + 0.12], [0, dashTop, front + 0.18], halfW * 2, 0.08, 0.02)
// Dash: a rounded slab under the windshield base.
emitBeam(sink, [-halfW, dashTop - 0.1, front], [halfW, dashTop - 0.1, front], 0.34, 0.2, 0.06)
if (hasRoof && lod === 0 && frame.roofFrontS - frame.roofRearS > 0.3) {
// Headliner: only under the flat of the roof, or it pokes through the glass.
const a = frame.roofRearS + 0.06
const b = frame.roofFrontS - 0.06
const y = Math.min(frame.top(a), frame.top(b)) - 0.05
emitBeam(sink, [0, y, a], [0, y, b], frame.topHalfWidth((a + b) / 2) * 1.7, 0.02, 0.01)
}
// Seats: cushion + backrest, front pair and a rear bench when there is room.
// Seats shrink to fit a low roof instead of poking their headrests through it.
const k = Math.min(1, Math.max(0.5, (Math.max(roof, frame.belt(mid) + 0.3) - floor - 0.08) / 1.02))
const seat = (x: number, s: number, width: number): void => {
emitBeam(sink, [x, floor + 0.2 * k, s + 0.24], [x, floor + 0.2 * k, s - 0.18], width, 0.13, bevel)
const back0: Vec3 = [x, floor + 0.24 * k, s - 0.2]
const back1: Vec3 = [x, floor + 0.84 * k, s - 0.34]
emitBeam(sink, back0, back1, width * 0.96, 0.12, bevel, { up: [0, 0, 1] })
if (lod === 0) emitBeam(sink, [x, floor + 0.86 * k, s - 0.35], [x, floor + 1.0 * k, s - 0.37], width * 0.5, 0.08, 0.03, { up: [0, 0, 1] })
}
const driverS = lerp(front, rear, 0.18) - 0.55
const span = front - rear
const seatX = halfW * 0.48
if (span > 0.7) {
seat(seatX, Math.max(driverS, rear + 0.35), halfW * 0.72)
seat(-seatX, Math.max(driverS, rear + 0.35), halfW * 0.72)
}
if (span > 1.7) {
const benchS = Math.max(rear + 0.35, driverS - 0.95)
seat(0, benchS, halfW * 1.7)
}
// Centre console between the front seats.
if (span > 0.9) {
emitBeam(sink, [0, floor + 0.12, Math.max(driverS, rear + 0.35) - 0.1], [0, floor + 0.12, front - 0.05], 0.18, 0.2, 0.03)
}
// Steering wheel: a rim swept round a circle, and two spokes. Left-hand
// drive, because +X is the vehicle's left.
const hub: Vec3 = [seatX, dashTop + 0.02, front - 0.28]
const tilt = 0.42
const radius = 0.19
const ringPath: Vec3[] = []
const steps = lod === 0 ? 24 : 12
for (let k = 0; k <= steps; k += 1) {
const a = (k / steps) * Math.PI * 2
ringPath.push(tilted(hub, tilt, Math.cos(a) * radius, Math.sin(a) * radius, 0))
}
emitTube(wheelSink, circle(0.016, lod === 0 ? 8 : 5), ringPath, { caps: false, up: [0, 0, 1] })
for (const a of [0, Math.PI, Math.PI * 1.5]) {
emitTube(wheelSink, roundedRect(0.045, 0.018, 0.006, 1), [
tilted(hub, tilt, 0, 0, 0),
tilted(hub, tilt, Math.cos(a) * radius * 0.94, Math.sin(a) * radius * 0.94, 0),
], { up: [0, 0, 1] })
}
// Column into the dash.
emitTube(sink, circle(0.028, 6), [tilted(hub, tilt, 0, 0, -0.02), tilted(hub, tilt, 0, 0, -0.3)])
return { pivot: hub, tilt }
}
/**
* A point in the steering wheel's own plane (u right, v up, w along the
* column toward the driver), placed in vehicle space.
*/
function tilted(hub: Vec3, tilt: number, u: number, v: number, w: number): Vec3 {
// The wheel plane is vertical, then leaned back by `tilt` about X.
const c = Math.cos(tilt)
const s = Math.sin(tilt)
const y = v * c + w * s
const z = -v * s + w * c
return [hub[0] + u, hub[1] + y, hub[2] - z]
}

172
src/generator/materials.ts Normal file
View file

@ -0,0 +1,172 @@
import {
Color,
DoubleSide,
type Material,
MeshPhysicalMaterial,
MeshStandardMaterial,
} from 'three'
import type { PaintSpec } from './spec.ts'
/**
* Every material a vehicle uses, one per CHANNEL.
*
* A channel is a role, not a colour: `paint` is the body colour whatever it
* is, `lightTail` is whatever the tail lamps are made of. Geometry is written
* per channel and each channel becomes one mesh, so a vehicle is about a dozen
* draw calls no matter how many panels, spokes and mods it has.
*
* Colour lives in the MATERIAL, not in the vertices: the vertex colour is only
* a multiplier that darkens panel gaps. That is what lets a paint change be a
* uniform update instead of a rebuild, which matters in a garage screen where
* the player drags a colour picker.
*/
export type Channel =
| 'paint'
| 'paint2'
| 'stripe'
| 'trim'
| 'chrome'
| 'glass'
| 'lightHead'
| 'lightTail'
| 'underbody'
| 'interior'
| 'tyre'
| 'rim'
| 'brake'
| 'caliper'
| 'lens'
| 'plate'
export const CHANNELS: readonly Channel[] = [
'paint', 'paint2', 'stripe', 'trim', 'chrome', 'glass', 'lightHead', 'lightTail',
'underbody', 'interior', 'tyre', 'rim', 'brake', 'caliper', 'lens', 'plate',
]
export type VehicleMaterials = Record<Channel, Material>
function paintMaterial(name: string): MeshPhysicalMaterial {
return new MeshPhysicalMaterial({ name, vertexColors: true, color: 0xffffff })
}
export function createMaterials(paint: PaintSpec): VehicleMaterials {
const materials: VehicleMaterials = {
paint: paintMaterial('vehicle-generator/paint'),
paint2: paintMaterial('vehicle-generator/paint2'),
stripe: paintMaterial('vehicle-generator/stripe'),
trim: new MeshStandardMaterial({ name: 'vehicle-generator/trim', vertexColors: true, roughness: 0.62, metalness: 0.05 }),
chrome: new MeshStandardMaterial({ name: 'vehicle-generator/chrome', vertexColors: true, color: 0xe8ecef, roughness: 0.08, metalness: 1 }),
glass: new MeshPhysicalMaterial({
name: 'vehicle-generator/glass',
vertexColors: true,
roughness: 0.02,
metalness: 0,
ior: 1.52,
specularIntensity: 1,
envMapIntensity: 1.4,
transparent: true,
depthWrite: false,
side: DoubleSide,
}),
lightHead: new MeshStandardMaterial({
name: 'vehicle-generator/light-head',
vertexColors: true,
color: 0xdfe6ea,
roughness: 0.1,
metalness: 0.4,
emissive: new Color(0xfff4de),
emissiveIntensity: 0,
}),
lightTail: new MeshStandardMaterial({
name: 'vehicle-generator/light-tail',
vertexColors: true,
color: 0x8a0f12,
roughness: 0.18,
metalness: 0.1,
emissive: new Color(0xff1a14),
emissiveIntensity: 0.25,
}),
underbody: new MeshStandardMaterial({ name: 'vehicle-generator/underbody', vertexColors: true, color: 0x1a1c1f, roughness: 0.9 }),
interior: new MeshStandardMaterial({ name: 'vehicle-generator/interior', vertexColors: true, color: 0x1d1e21, roughness: 0.88 }),
tyre: new MeshStandardMaterial({ name: 'vehicle-generator/tyre', vertexColors: true, color: 0x1c1c1e, roughness: 0.92 }),
rim: new MeshPhysicalMaterial({ name: 'vehicle-generator/rim', vertexColors: true }),
brake: new MeshStandardMaterial({ name: 'vehicle-generator/brake', vertexColors: true, color: 0x5d6166, roughness: 0.45, metalness: 0.85 }),
caliper: new MeshStandardMaterial({ name: 'vehicle-generator/caliper', vertexColors: true, roughness: 0.4, metalness: 0.2 }),
// Clear polycarbonate over the lamp reflectors.
lens: new MeshPhysicalMaterial({
name: 'vehicle-generator/lens',
vertexColors: true,
color: 0xf4f7fa,
roughness: 0.02,
metalness: 0,
transparent: true,
opacity: 0.18,
depthWrite: false,
clearcoat: 1,
}),
plate: new MeshStandardMaterial({ name: 'vehicle-generator/plate', vertexColors: true, color: 0xe8e8e2, roughness: 0.45, metalness: 0.1 }),
}
applyPaint(materials, paint)
return materials
}
const FINISH: Record<PaintSpec['finish'], {
roughness: number
metalness: number
clearcoat: number
clearcoatRoughness: number
iridescence: number
}> = {
solid: { roughness: 0.42, metalness: 0, clearcoat: 0.8, clearcoatRoughness: 0.12, iridescence: 0 },
metallic: { roughness: 0.34, metalness: 0.72, clearcoat: 1, clearcoatRoughness: 0.06, iridescence: 0 },
pearl: { roughness: 0.3, metalness: 0.35, clearcoat: 1, clearcoatRoughness: 0.05, iridescence: 0.75 },
matte: { roughness: 0.82, metalness: 0.08, clearcoat: 0, clearcoatRoughness: 0.5, iridescence: 0 },
}
/** Updates colours and finishes in place — no geometry is touched. */
export function applyPaint(materials: VehicleMaterials, paint: PaintSpec): void {
const finish = FINISH[paint.finish]
for (const [channel, hex] of [['paint', paint.primary], ['paint2', paint.secondary], ['stripe', paint.stripe]] as const) {
const m = materials[channel] as MeshPhysicalMaterial
m.color.set(hex)
m.roughness = finish.roughness
m.metalness = finish.metalness
m.clearcoat = finish.clearcoat
m.clearcoatRoughness = finish.clearcoatRoughness
m.iridescence = finish.iridescence
m.iridescenceIOR = 1.45
m.needsUpdate = true
}
const trim = materials.trim as MeshStandardMaterial
trim.color.set(paint.trim)
const rim = materials.rim as MeshPhysicalMaterial
rim.color.set(paint.rim)
if (paint.rimFinish === 'chrome') {
rim.roughness = 0.07; rim.metalness = 1; rim.clearcoat = 0
} else if (paint.rimFinish === 'satin') {
rim.roughness = 0.45; rim.metalness = 0.75; rim.clearcoat = 0
} else {
rim.roughness = 0.35; rim.metalness = 0.3; rim.clearcoat = 0.8; rim.clearcoatRoughness = 0.1
}
rim.needsUpdate = true
;(materials.caliper as MeshStandardMaterial).color.set(paint.caliper)
const glass = materials.glass as MeshPhysicalMaterial
const tint = Math.min(1, Math.max(0, paint.tint))
// Real glass is dark and reflective, not milky: a dim green-grey body
// colour, mostly transparent, getting darker and denser with the tint.
glass.color.setRGB(0.1 - 0.08 * tint, 0.13 - 0.1 * tint, 0.13 - 0.1 * tint)
glass.opacity = 0.2 + 0.62 * tint
}
export function setLights(materials: VehicleMaterials, state: { readonly head: boolean; readonly brake: boolean }): void {
;(materials.lightHead as MeshStandardMaterial).emissiveIntensity = state.head ? 2.4 : 0
;(materials.lightTail as MeshStandardMaterial).emissiveIntensity = state.brake ? 3 : state.head ? 0.9 : 0.25
}
export function disposeMaterials(materials: VehicleMaterials): void {
for (const m of Object.values(materials)) m.dispose()
}

436
src/generator/mesh.ts Normal file
View file

@ -0,0 +1,436 @@
import { BufferAttribute, BufferGeometry, Matrix3, Matrix4, Vector3 } from 'three'
/**
* The generator's geometry vocabulary.
*
* Everything is built as GRIDS of points: a lofted body panel, a revolved
* tyre, a tube swept along a path are all "rows × columns" of vertices. A grid
* gets its normals from its own faces only, which is the whole trick behind
* hard edges: two grids that meet along a crease share positions but not
* normals, so the crease stays sharp while each panel stays smooth.
*
* Output goes into a `Sink` per material. A sink is an indexed triangle list
* with position, normal, colour and uv, and ends up as exactly one mesh — so a
* vehicle costs one draw call per material, not one per part.
*/
export type Vec3 = readonly [number, number, number]
export type Vec2 = readonly [number, number]
export type RGB = readonly [number, number, number]
export const WHITE: RGB = [1, 1, 1]
const ZERO2: Vec2 = [0, 0]
export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
export const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
export const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s]
export const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
export const cross = (a: Vec3, b: Vec3): Vec3 => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
export const length = (a: Vec3): number => Math.hypot(a[0], a[1], a[2])
export const normalize = (a: Vec3, fallback: Vec3 = [0, 1, 0]): Vec3 => {
const l = length(a)
return l > 1e-12 ? [a[0] / l, a[1] / l, a[2] / l] : fallback
}
export const mix = (a: Vec3, b: Vec3, t: number): Vec3 => [
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
]
/* -------------------------------------------------------------------- sink */
export class Sink {
readonly positions: number[] = []
readonly normals: number[] = []
readonly colors: number[] = []
readonly uvs: number[] = []
readonly indices: number[] = []
get vertexCount(): number {
return this.positions.length / 3
}
get triangleCount(): number {
return this.indices.length / 3
}
vertex(p: Vec3, n: Vec3, c: RGB = WHITE, uv: Vec2 = [0, 0]): number {
this.positions.push(p[0], p[1], p[2])
this.normals.push(n[0], n[1], n[2])
this.colors.push(c[0], c[1], c[2])
this.uvs.push(uv[0], uv[1])
return this.vertexCount - 1
}
/**
* Adds a triangle unless it has no area. Grids collapse to a point at a
* pole and panel gaps put two stations at one place; those triangles draw
* nothing but still cost, and they confuse exporters and physics cookers.
*/
triangle(a: number, b: number, c: number): void {
const p = this.positions
const ux = p[b * 3]! - p[a * 3]!, uy = p[b * 3 + 1]! - p[a * 3 + 1]!, uz = p[b * 3 + 2]! - p[a * 3 + 2]!
const vx = p[c * 3]! - p[a * 3]!, vy = p[c * 3 + 1]! - p[a * 3 + 1]!, vz = p[c * 3 + 2]! - p[a * 3 + 2]!
const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx
if (nx * nx + ny * ny + nz * nz < 1e-18) return
this.indices.push(a, b, c)
}
/** A flat triangle with its own three vertices and the face normal. */
flat(a: Vec3, b: Vec3, c: Vec3, colour: RGB = WHITE): void {
const n = normalize(cross(sub(b, a), sub(c, a)))
const i = this.vertex(a, n, colour)
const j = this.vertex(b, n, colour)
const k = this.vertex(c, n, colour)
this.triangle(i, j, k)
}
toGeometry(): BufferGeometry {
const geometry = new BufferGeometry()
geometry.setAttribute('position', new BufferAttribute(new Float32Array(this.positions), 3))
geometry.setAttribute('normal', new BufferAttribute(new Float32Array(this.normals), 3))
geometry.setAttribute('color', new BufferAttribute(new Float32Array(this.colors), 3))
geometry.setAttribute('uv', new BufferAttribute(new Float32Array(this.uvs), 2))
const count = this.vertexCount
geometry.setIndex(count > 65535 ? new BufferAttribute(new Uint32Array(this.indices), 1)
: new BufferAttribute(new Uint16Array(this.indices), 1))
geometry.computeBoundingBox()
geometry.computeBoundingSphere()
return geometry
}
}
/** Named sinks; `get` creates on first use so builders never check for existence. */
export class SinkSet {
readonly map = new Map<string, Sink>()
get(name: string): Sink {
let sink = this.map.get(name)
if (!sink) {
sink = new Sink()
this.map.set(name, sink)
}
return sink
}
}
/* --------------------------------------------------------------------- grid */
export interface Grid {
/** rows[i][j]. Cells span (i, j) → (i + 1, j + 1). */
readonly rows: readonly (readonly Vec3[])[]
/** Close the grid in j (the last column joins the first). */
readonly wrapJ?: boolean
/** Close the grid in i. */
readonly wrapI?: boolean
}
export interface EmitOptions {
/** Which sink a cell goes to; null skips the cell. Defaults to `sink`. */
readonly sinkFor?: (i: number, j: number) => Sink | null
readonly sink?: Sink
readonly colorAt?: (i: number, j: number) => RGB
readonly uvAt?: (i: number, j: number) => Vec2
/** Reverse the winding (a mirrored panel). */
readonly flip?: boolean
readonly transform?: Matrix4
}
/**
* Emits a grid as smooth-shaded triangles.
*
* Normals are area-weighted across the grid's own faces and nothing else. A
* degenerate cell (zero area, where a band collapses to a line) contributes
* nothing, which is what lets a body band shrink to nothing along a station
* without corrupting its neighbours' shading.
*/
export function emitGrid(grid: Grid, options: EmitOptions): void {
const rowsIn = grid.rows
const ni = rowsIn.length
const nj = rowsIn[0]?.length ?? 0
if (ni < 2 && !grid.wrapI) return
if (nj < 2 && !grid.wrapJ) return
const matrix = options.transform
const normalMatrix = matrix ? new Matrix3().getNormalMatrix(matrix) : undefined
const tmp = new Vector3()
const rows: Vec3[][] = rowsIn.map((row) => row.map((p) => {
if (!matrix) return p
tmp.set(p[0], p[1], p[2]).applyMatrix4(matrix)
return [tmp.x, tmp.y, tmp.z] as Vec3
}))
const cellsI = grid.wrapI ? ni : ni - 1
const cellsJ = grid.wrapJ ? nj : nj - 1
const at = (i: number, j: number): Vec3 => rows[i % ni]![j % nj]!
const flip = options.flip === true
// --- normals over the whole grid (scalar maths: this loop is the
// generator's hottest, and tuples allocate)
const acc = new Float64Array(ni * nj * 3)
const sign = flip ? -1 : 1
const add3 = (i: number, j: number, x: number, y: number, z: number): void => {
const k = ((i % ni) * nj + (j % nj)) * 3
acc[k] = acc[k]! + x
acc[k + 1] = acc[k + 1]! + y
acc[k + 2] = acc[k + 2]! + z
}
for (let i = 0; i < cellsI; i += 1) {
for (let j = 0; j < cellsJ; j += 1) {
const a = at(i, j), b = at(i, j + 1), c = at(i + 1, j + 1), d = at(i + 1, j)
const bx = b[0] - a[0], by = b[1] - a[1], bz = b[2] - a[2]
const cx = c[0] - a[0], cy = c[1] - a[1], cz = c[2] - a[2]
const dx = d[0] - a[0], dy = d[1] - a[1], dz = d[2] - a[2]
const n1x = sign * (by * cz - bz * cy), n1y = sign * (bz * cx - bx * cz), n1z = sign * (bx * cy - by * cx)
const n2x = sign * (cy * dz - cz * dy), n2y = sign * (cz * dx - cx * dz), n2z = sign * (cx * dy - cy * dx)
add3(i, j, n1x + n2x, n1y + n2y, n1z + n2z)
add3(i, j + 1, n1x, n1y, n1z)
add3(i + 1, j + 1, n1x + n2x, n1y + n2y, n1z + n2z)
add3(i + 1, j, n2x, n2y, n2z)
}
}
const normalAt = (i: number, j: number): Vec3 => {
const k = ((i % ni) * nj + (j % nj)) * 3
const x = acc[k]!, y = acc[k + 1]!, z = acc[k + 2]!
const len = Math.sqrt(x * x + y * y + z * z)
let n: Vec3 = len > 1e-12 ? [x / len, y / len, z / len] : [0, 1, 0]
if (normalMatrix) {
tmp.set(n[0], n[1], n[2]).applyMatrix3(normalMatrix).normalize()
n = [tmp.x, tmp.y, tmp.z]
}
return n
}
// --- emission, one vertex cache per sink (typed, -1 = not yet emitted)
const caches = new Map<Sink, Int32Array>()
const index = (sink: Sink, i: number, j: number): number => {
let cache = caches.get(sink)
if (!cache) { cache = new Int32Array(ni * nj).fill(-1); caches.set(sink, cache) }
const ii = i % ni
const jj = j % nj
const key = ii * nj + jj
let v = cache[key]!
if (v < 0) {
v = sink.vertex(at(ii, jj), normalAt(ii, jj), options.colorAt?.(ii, jj) ?? WHITE,
options.uvAt?.(ii, jj) ?? ZERO2)
cache[key] = v
}
return v
}
for (let i = 0; i < cellsI; i += 1) {
for (let j = 0; j < cellsJ; j += 1) {
const sink = options.sinkFor ? options.sinkFor(i, j) : options.sink ?? null
if (!sink) continue
const a = index(sink, i, j)
const b = index(sink, i, j + 1)
const c = index(sink, i + 1, j + 1)
const d = index(sink, i + 1, j)
if (flip) {
sink.triangle(a, c, b)
sink.triangle(a, d, c)
} else {
sink.triangle(a, b, c)
sink.triangle(a, c, d)
}
}
}
}
/**
* A flat fan closing a loop of points: end caps, discs, the nose of a body.
* The loop must be counter-clockwise when seen from the side the cap faces.
*/
export function emitCap(
sink: Sink,
loop: readonly Vec3[],
centre: Vec3,
colour: RGB = WHITE,
transform?: Matrix4,
): void {
const tmp = new Vector3()
const place = (p: Vec3): Vec3 => {
if (!transform) return p
tmp.set(p[0], p[1], p[2]).applyMatrix4(transform)
return [tmp.x, tmp.y, tmp.z]
}
const c = place(centre)
const pts = loop.map(place)
let n: Vec3 = [0, 0, 0]
for (let k = 0; k < pts.length; k += 1) {
n = add(n, cross(sub(pts[k]!, c), sub(pts[(k + 1) % pts.length]!, c)))
}
const normal = normalize(n)
const centreIndex = sink.vertex(c, normal, colour)
const ring = pts.map((p) => sink.vertex(p, normal, colour))
for (let k = 0; k < ring.length; k += 1) {
sink.triangle(centreIndex, ring[k]!, ring[(k + 1) % ring.length]!)
}
}
/* ---------------------------------------------------------------- revolve */
/**
* Revolves a profile around the X axis. Profile points are (x, radius).
*
* Walk the profile so the solid is on the LEFT of the direction of travel in
* the (x, r) plane and the faces point outward: a tyre goes up its inner
* sidewall, across the tread toward +x, down the outer sidewall.
*/
export function revolveX(profile: readonly Vec2[], segments: number, closedProfile = false, phase = 0): Grid {
const rows = profile.map(([x, r]) => {
const row: Vec3[] = []
for (let j = 0; j < segments; j += 1) {
const a = phase + (j / segments) * Math.PI * 2
row.push([x, Math.cos(a) * r, Math.sin(a) * r])
}
return row
})
return { rows, wrapJ: true, wrapI: closedProfile }
}
/* ------------------------------------------------------------------ sweep */
export interface SweepFrame {
readonly point: Vec3
readonly tangent: Vec3
readonly side: Vec3
readonly normal: Vec3
}
/**
* Parallel-transport frames along a polyline.
*
* The first frame takes its side vector from `up`; each later frame rotates
* the previous one by the smallest turn that follows the path. A frame built
* from `up` at every point instead would spin 180° the moment a snorkel pipe
* passes through vertical.
*/
export function frames(path: readonly Vec3[], up: Vec3 = [0, 1, 0]): SweepFrame[] {
const n = path.length
const tangents: Vec3[] = path.map((_, i) => {
const a = path[Math.max(0, i - 1)]!
const b = path[Math.min(n - 1, i + 1)]!
return normalize(sub(b, a), [0, 0, 1])
})
const out: SweepFrame[] = []
let side = normalize(cross(tangents[0]!, up), [1, 0, 0])
if (length(cross(tangents[0]!, up)) < 1e-6) side = normalize(cross(tangents[0]!, [1, 0, 0]), [0, 0, 1])
for (let i = 0; i < n; i += 1) {
const t = tangents[i]!
side = normalize(sub(side, scale(t, dot(side, t))), side)
const normal = normalize(cross(t, side))
out.push({ point: path[i]!, tangent: t, side, normal })
}
return out
}
export interface SweepOptions {
readonly closed?: boolean
readonly up?: Vec3
/** Per-station scale of the section, for tapered tubes and wings. */
readonly scaleAt?: (i: number) => number
}
/**
* Sweeps a 2D section along a path. Section points are (side, normal)
* offsets; walk them counter-clockwise for outward faces.
*/
export function sweep(section: readonly Vec2[], path: readonly Vec3[], options: SweepOptions = {}): {
grid: Grid
frames: SweepFrame[]
} {
const fs = frames(path, options.up)
const rows = fs.map((f, i) => {
const s = options.scaleAt?.(i) ?? 1
return section.map(([u, v]) => add(f.point, add(scale(f.side, u * s), scale(f.normal, v * s))))
})
return { grid: { rows, wrapJ: options.closed ?? true }, frames: fs }
}
/** Emits a closed-section sweep with both ends capped. */
export function emitTube(
sink: Sink,
section: readonly Vec2[],
path: readonly Vec3[],
options: SweepOptions & { readonly colour?: RGB; readonly transform?: Matrix4; readonly caps?: boolean } = {},
): void {
const { grid } = sweep(section, path, options)
const colour = options.colour ?? WHITE
emitGrid(grid, { sink, colorAt: () => colour, transform: options.transform })
if (options.caps === false) return
const first = grid.rows[0]!
const last = grid.rows[grid.rows.length - 1]!
const centroid = (row: readonly Vec3[]): Vec3 =>
scale(row.reduce<Vec3>((s, p) => add(s, p), [0, 0, 0]), 1 / row.length)
emitCap(sink, [...first].reverse(), centroid(first), colour, options.transform)
emitCap(sink, last, centroid(last), colour, options.transform)
}
/** Circle section, counter-clockwise. */
export function circle(radius: number, segments: number): Vec2[] {
const out: Vec2[] = []
for (let k = 0; k < segments; k += 1) {
const a = (k / segments) * Math.PI * 2
out.push([Math.cos(a) * radius, Math.sin(a) * radius])
}
return out
}
/**
* Rounded rectangle section, counter-clockwise. `bevel` is the corner radius;
* `corner` the number of segments per corner (1 = a single chamfer facet).
*/
export function roundedRect(width: number, height: number, bevel: number, corner = 1): Vec2[] {
const hw = width / 2
const hh = height / 2
const r = Math.max(0, Math.min(bevel, hw * 0.49, hh * 0.49))
const centres: Vec2[] = [[hw - r, hh - r], [-hw + r, hh - r], [-hw + r, -hh + r], [hw - r, -hh + r]]
const out: Vec2[] = []
centres.forEach(([cx, cy], q) => {
for (let k = 0; k <= corner; k += 1) {
const a = (q + k / corner) * (Math.PI / 2)
out.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r])
}
})
return out
}
/** A bevelled beam from a to b. */
export function emitBeam(
sink: Sink,
a: Vec3,
b: Vec3,
width: number,
height: number,
bevel: number,
options: { readonly up?: Vec3; readonly colour?: RGB; readonly transform?: Matrix4 } = {},
): void {
emitTube(sink, roundedRect(width, height, bevel), [a, b], options)
}
/** Rounds the interior corners of a polyline with `steps` extra points each. */
export function roundPath(path: readonly Vec3[], radius: number, steps = 3): Vec3[] {
if (path.length < 3 || radius <= 0) return [...path]
const out: Vec3[] = [path[0]!]
for (let i = 1; i < path.length - 1; i += 1) {
const p = path[i]!
const toPrev = sub(path[i - 1]!, p)
const toNext = sub(path[i + 1]!, p)
const r = Math.min(radius, length(toPrev) * 0.45, length(toNext) * 0.45)
const a = add(p, scale(normalize(toPrev), r))
const b = add(p, scale(normalize(toNext), r))
for (let k = 0; k <= steps; k += 1) {
const t = k / steps
// Quadratic Bézier with the corner as the control point.
const q = add(add(scale(a, (1 - t) * (1 - t)), scale(p, 2 * (1 - t) * t)), scale(b, t * t))
out.push(q)
}
}
out.push(path[path.length - 1]!)
return out
}

542
src/generator/mods.ts Normal file
View file

@ -0,0 +1,542 @@
import type { BodyFrame } from './body.ts'
import { clamp, lerp } from './curve.ts'
import type { Channel } from './materials.ts'
import {
circle,
emitBeam,
emitCap,
emitTube,
roundedRect,
roundPath,
type Sink,
type SinkSet,
type Vec2,
type Vec3,
} from './mesh.ts'
import type { Random } from './random.ts'
import type { LodLevel, ModKind, ModSpec, RimStyle, VehicleSpec } from './spec.ts'
/**
* Modifications.
*
* A mod is two optional functions: `modifySpec` changes the vehicle BEFORE it
* is built (a widebody widens the arches and the track, a lift raises the
* body) and `build` adds geometry AFTER the body exists, placed against the
* body's own profile curves rather than against fixed coordinates. That is
* what makes every mod fit every body style: a roof rack asks the body where
* its roof is.
*
* Mods are data (`{ kind, params }`), described by a parameter schema the
* viewer turns into controls. Each one lands in its own named node
* (`mod_roofRack`) so a game can hide, swap or break it off.
*/
export interface ModParamNumber {
readonly key: string
readonly label: string
readonly type: 'number'
readonly min: number
readonly max: number
readonly step: number
readonly default: number
}
export interface ModParamSelect {
readonly key: string
readonly label: string
readonly type: 'select'
readonly options: readonly string[]
readonly default: string
}
export type ModParam = ModParamNumber | ModParamSelect
export interface ModContext {
readonly frame: BodyFrame
readonly spec: VehicleSpec
readonly sinks: SinkSet
readonly lod: LodLevel
readonly random: Random
/** Half the distance between the wheel centres across the car. */
readonly trackHalf: number
/** Parent a mod node to a rigged part, so it moves with it. */
attach(node: string, parent: string): void
}
export interface ModDefinition {
readonly kind: ModKind
readonly label: string
readonly description: string
readonly params: readonly ModParam[]
modifySpec?(spec: VehicleSpec, params: Readonly<Record<string, number | string>>): VehicleSpec
build?(ctx: ModContext, params: Readonly<Record<string, number | string>>): void
}
const num = (p: Readonly<Record<string, number | string>>, key: string): number => Number(p[key])
const str = (p: Readonly<Record<string, number | string>>, key: string): string => String(p[key])
/** Resolve a mod's parameters against its schema: defaults filled, numbers clamped. */
export function modParams(mod: ModSpec): Record<string, number | string> {
const def = MODS[mod.kind]
const out: Record<string, number | string> = {}
for (const param of def.params) {
const given = mod.params?.[param.key]
if (param.type === 'number') {
const v = typeof given === 'number' && Number.isFinite(given) ? given : param.default
out[param.key] = clamp(v, param.min, param.max)
} else {
out[param.key] = typeof given === 'string' && param.options.includes(given) ? given : param.default
}
}
return out
}
const sinkOf = (ctx: ModContext, node: string, channel: Channel): Sink => ctx.sinks.get(`${node}|${channel}`)
const tubeSegments = (lod: LodLevel): number => (lod === 0 ? 10 : lod === 1 ? 6 : 4)
/* -------------------------------------------------------------- the mods */
export const MODS: Readonly<Record<ModKind, ModDefinition>> = {
spoiler: {
kind: 'spoiler',
label: 'Spoiler',
description: 'Boot lip, ducktail or a strut-mounted wing; a roof spoiler on hatchbacks.',
params: [
{ key: 'style', label: 'Style', type: 'select', options: ['lip', 'ducktail', 'wing'], default: 'wing' },
{ key: 'size', label: 'Size', type: 'number', min: 0.5, max: 1.6, step: 0.05, default: 1 },
{ key: 'height', label: 'Wing height', type: 'number', min: 0.08, max: 0.45, step: 0.01, default: 0.22 },
],
build(ctx, p) {
const { frame, spec } = ctx
const size = num(p, 'size')
const style = str(p, 'style')
const threeBox = spec.body.deck > 0.12 && !spec.body.bed
const s = threeBox ? frame.rearS + Math.max(0.1, spec.body.tailRound * 0.8) : frame.roofRearS + 0.01
const y = frame.surfaceY(s, 0)
const half = frame.topHalfWidth(s) * (threeBox ? 0.92 : 0.95)
const node = 'mod_spoiler'
const paint = sinkOf(ctx, node, 'paint')
// On a boot lid the spoiler rides the lid; on a hatch it sits on the
// roof, ahead of the tailgate hinge, and stays with the body.
if (threeBox) ctx.attach(node, 'trunk')
if (style === 'lip' || !threeBox) {
const h = 0.03 * size
emitBeam(paint, [-half, y + h * 0.3, s], [half, y + h * 0.3, s], 0.1 * size, h, h * 0.4, { up: [0, 1, 0] })
return
}
if (style === 'ducktail') {
const section: Vec2[] = [[0.1 * size, 0], [-0.1 * size, 0], [-0.11 * size, 0.05 * size], [0.08 * size, 0.012]]
emitTube(paint, section.map(([u, v]) => [v, u] as Vec2), [[-half, y - 0.005, s], [half, y - 0.005, s]], { up: [0, 0, 1] })
return
}
const height = num(p, 'height')
const chord = 0.26 * size
const span = Math.min(half * 2.05, spec.body.width * 0.98)
const wingY = y + height
// Airfoil: sweep a cambered section across the car.
const airfoil: Vec2[] = []
const n = ctx.lod === 0 ? 10 : 5
for (let k = 0; k <= n; k += 1) {
const u = k / n
airfoil.push([lerp(chord / 2, -chord / 2, u), 0.022 * size * Math.sin(u * Math.PI) + 0.012 * (1 - u)])
}
for (let k = n - 1; k >= 1; k -= 1) {
const u = k / n
airfoil.push([lerp(chord / 2, -chord / 2, u), -0.006 * size * Math.sin(u * Math.PI)])
}
const section = airfoil.map(([u, v]) => [-v, u] as Vec2)
emitTube(sinkOf(ctx, node, 'trim'), section, [[span / 2, wingY, s - 0.02], [-span / 2, wingY, s - 0.02]], { up: [0, 0, 1] })
// End plates and struts.
for (const side of [1, -1]) {
const x = side * span / 2
emitBeam(paint, [x, wingY - 0.06, s - 0.02], [x, wingY + 0.06, s - 0.02], 0.012, chord * 1.15, 0.004, { up: [0, 0, 1] })
const sx = side * half * 0.62
emitBeam(paint, [sx, y - 0.01, s + 0.02], [sx, wingY, s - 0.01], 0.018, 0.09 * size, 0.006, { up: [0, 0, 1] })
}
},
},
bodyKit: {
kind: 'bodyKit',
label: 'Body kit',
description: 'Front splitter, side skirts and a finned rear diffuser.',
params: [
{ key: 'splitter', label: 'Splitter', type: 'number', min: 0, max: 1, step: 0.05, default: 0.7 },
{ key: 'skirts', label: 'Side skirts', type: 'number', min: 0, max: 1, step: 0.05, default: 0.7 },
{ key: 'diffuser', label: 'Diffuser', type: 'number', min: 0, max: 1, step: 0.05, default: 0.7 },
],
build(ctx, p) {
const { frame } = ctx
const trim = sinkOf(ctx, 'mod_bodyKit', 'trim')
const splitter = num(p, 'splitter')
if (splitter > 0) {
const s = frame.frontS - 0.08
const y = frame.sill(s) - 0.005
const w = frame.halfWidth(s) * 0.92
emitBeam(trim, [-w, y, s + 0.02 + 0.06 * splitter], [w, y, s + 0.02 + 0.06 * splitter], 0.18 + 0.1 * splitter, 0.018, 0.006, { up: [0, 1, 0] })
}
const skirts = num(p, 'skirts')
if (skirts > 0 && frame.axles.length >= 2) {
const front = Math.max(...frame.axles.map((a) => a.s - a.archRadius)) - 0.04
const rear = Math.min(...frame.axles.map((a) => a.s + a.archRadius)) + 0.04
for (const side of [1, -1]) {
const mid = (front + rear) / 2
const x = side * (frame.halfWidth(mid) - 0.03 + 0.02 * skirts)
const y = frame.sill(mid) + 0.015 - 0.02 * skirts
emitBeam(trim, [x, y, rear], [x, y, front], 0.05 + 0.03 * skirts, 0.07, 0.015, { up: [0, 1, 0] })
}
}
const diffuser = num(p, 'diffuser')
if (diffuser > 0) {
const s = frame.rearS + 0.12
const y = frame.sill(s) + 0.01
const w = frame.halfWidth(s) * 0.75
emitBeam(trim, [-w, y, s + 0.06], [w, y, s + 0.06], 0.3, 0.02, 0.006, { up: [0, 1, 0] })
const fins = 4
for (let k = 0; k < fins; k += 1) {
const x = lerp(-w * 0.8, w * 0.8, k / (fins - 1))
emitBeam(trim, [x, y + 0.01, s + 0.2], [x, y + 0.01, s - 0.11 - 0.05 * diffuser], 0.012, 0.05 + 0.05 * diffuser, 0.004, { up: [0, 1, 0] })
}
}
},
},
widebody: {
kind: 'widebody',
label: 'Widebody',
description: 'Wider arches with bolt-on fender flares, and a wider track to fill them.',
params: [
{ key: 'flare', label: 'Flare', type: 'number', min: 0.02, max: 0.12, step: 0.005, default: 0.06 },
{ key: 'rivets', label: 'Bolt-on lip', type: 'number', min: 0, max: 1, step: 1, default: 1 },
],
modifySpec(spec, p) {
const flare = num(p, 'flare')
return {
...spec,
body: { ...spec.body, flare: spec.body.flare + flare },
chassis: { ...spec.chassis, track: spec.chassis.track + (flare * 1.6) / spec.body.width },
}
},
build(ctx, p) {
if (num(p, 'rivets') < 1) return
const trim = sinkOf(ctx, 'mod_widebody', 'trim')
for (const arch of ctx.frame.axles) {
for (const side of [1, -1]) {
const path: Vec3[] = []
const steps = ctx.lod === 0 ? 14 : ctx.lod === 1 ? 7 : 4
for (let k = 0; k <= steps; k += 1) {
const a = Math.PI * (0.04 + 0.92 * (k / steps))
const s = arch.s + Math.cos(a) * (arch.archRadius + 0.02)
const y = arch.archY + Math.sin(a) * (arch.archRadius + 0.02)
path.push([side * (ctx.frame.halfWidth(s) - 0.005), y, s])
}
emitTube(trim, roundedRect(0.06, 0.035, 0.012, 1), path, { up: [side, 0, 0] })
}
}
},
},
suspension: {
kind: 'suspension',
label: 'Suspension',
description: 'Lowered or lifted: moves the body relative to the wheels.',
params: [
{ key: 'height', label: 'Ride height', type: 'number', min: -0.08, max: 0.2, step: 0.005, default: -0.04 },
],
modifySpec(spec, p) {
const height = num(p, 'height')
return { ...spec, chassis: { ...spec.chassis, rideHeight: spec.chassis.rideHeight + height } }
},
},
wheelSet: {
kind: 'wheelSet',
label: 'Wheel set',
description: 'Aftermarket wheels: rim style, size, width, offset and camber.',
params: [
{
key: 'rim',
label: 'Rim',
type: 'select',
options: ['spoke', 'multispoke', 'mesh', 'turbine', 'steelie', 'deepdish', 'beadlock'],
default: 'multispoke',
},
{ key: 'spokes', label: 'Spokes', type: 'number', min: 3, max: 12, step: 1, default: 6 },
{ key: 'size', label: 'Diameter', type: 'number', min: 0.85, max: 1.3, step: 0.01, default: 1.05 },
{ key: 'rimRatio', label: 'Rim / tyre', type: 'number', min: 0.5, max: 0.8, step: 0.01, default: 0.7 },
{ key: 'width', label: 'Width', type: 'number', min: 0.8, max: 1.5, step: 0.01, default: 1.1 },
{ key: 'offset', label: 'Offset', type: 'number', min: -0.02, max: 0.08, step: 0.005, default: 0.02 },
{ key: 'camber', label: 'Camber', type: 'number', min: -0.14, max: 0.02, step: 0.005, default: -0.03 },
],
modifySpec(spec, p) {
return {
...spec,
wheels: {
...spec.wheels,
rim: str(p, 'rim') as RimStyle,
spokes: Math.round(num(p, 'spokes')),
radius: spec.wheels.radius * num(p, 'size'),
rimRatio: num(p, 'rimRatio'),
width: spec.wheels.width * num(p, 'width'),
offset: num(p, 'offset'),
camber: num(p, 'camber'),
},
}
},
},
bullBar: {
kind: 'bullBar',
label: 'Bull bar',
description: 'Tubular push bar across the nose.',
params: [
{ key: 'height', label: 'Height', type: 'number', min: 0.2, max: 0.7, step: 0.01, default: 0.45 },
{ key: 'finish', label: 'Finish', type: 'select', options: ['black', 'chrome'], default: 'black' },
],
build(ctx, p) {
const { frame } = ctx
const sink = sinkOf(ctx, 'mod_bullBar', str(p, 'finish') === 'chrome' ? 'chrome' : 'trim')
const s = frame.frontS + 0.08
const low = frame.sill(frame.frontS - 0.05) + 0.05
const high = low + num(p, 'height')
const w = frame.halfWidth(frame.frontS - 0.2) * 0.72
const seg = circle(0.03, tubeSegments(ctx.lod))
const hoop = roundPath([[-w, low, s - 0.06], [-w, high, s], [w, high, s], [w, low, s - 0.06]], 0.12, ctx.lod === 0 ? 4 : 2)
emitTube(sink, seg, hoop)
emitTube(sink, circle(0.022, tubeSegments(ctx.lod)), [[-w, lerp(low, high, 0.45), s - 0.02], [w, lerp(low, high, 0.45), s - 0.02]])
for (const x of [-w * 0.35, w * 0.35]) {
emitTube(sink, circle(0.022, tubeSegments(ctx.lod)), [[x, low - 0.02, s - 0.04], [x, high, s]])
}
},
},
roofRack: {
kind: 'roofRack',
label: 'Roof rack',
description: 'Rails and crossbars, optionally a cargo basket.',
params: [
{ key: 'bars', label: 'Crossbars', type: 'number', min: 2, max: 6, step: 1, default: 3 },
{ key: 'basket', label: 'Basket', type: 'number', min: 0, max: 1, step: 1, default: 0 },
],
build(ctx, p) {
const { frame } = ctx
if (frame.cabin((frame.roofFrontS + frame.roofRearS) / 2) < 0.5) return
const trim = sinkOf(ctx, 'mod_roofRack', 'trim')
const a = frame.roofRearS + 0.06
const b = frame.roofFrontS - 0.06
if (b - a < 0.3) return
const railY = (s: number): number => frame.surfaceY(s, frame.topHalfWidth(s) * 0.85) + 0.05
const seg = tubeSegments(ctx.lod)
for (const side of [1, -1]) {
const path: Vec3[] = []
for (let k = 0; k <= 6; k += 1) {
const s = lerp(a, b, k / 6)
path.push([side * frame.topHalfWidth(s) * 0.85, railY(s), s])
}
emitTube(trim, roundedRect(0.03, 0.03, 0.01, 1), path, { up: [0, 1, 0] })
for (const s of [a + 0.03, b - 0.03]) {
const x = side * frame.topHalfWidth(s) * 0.85
emitTube(trim, circle(0.012, seg), [[x, railY(s) - 0.07, s], [x, railY(s), s]])
}
}
const bars = Math.round(num(p, 'bars'))
for (let k = 0; k < bars; k += 1) {
const s = lerp(a + 0.1, b - 0.1, bars === 1 ? 0.5 : k / (bars - 1))
const w = frame.topHalfWidth(s) * 0.9
emitBeam(trim, [-w, railY(s) + 0.025, s], [w, railY(s) + 0.025, s], 0.04, 0.02, 0.006, { up: [0, 1, 0] })
}
if (num(p, 'basket') >= 1) {
const y = railY((a + b) / 2) + 0.12
const s0 = a + 0.1
const s1 = b - 0.1
const w = frame.topHalfWidth((a + b) / 2) * 0.82
const loop = roundPath([[-w, y, s0], [w, y, s0], [w, y, s1], [-w, y, s1], [-w, y, s0]], 0.1, 2)
emitTube(trim, circle(0.012, seg), loop)
for (const [x, s] of [[-w, s0], [w, s0], [w, s1], [-w, s1]] as const) {
emitTube(trim, circle(0.01, seg), [[x, y - 0.1, s], [x, y, s]])
}
}
},
},
snorkel: {
kind: 'snorkel',
label: 'Snorkel',
description: 'Raised air intake up the A-pillar.',
params: [
{ key: 'side', label: 'Side', type: 'select', options: ['right', 'left'], default: 'right' },
],
build(ctx, p) {
const { frame } = ctx
const side = str(p, 'side') === 'left' ? 1 : -1
const trim = sinkOf(ctx, 'mod_snorkel', 'trim')
const s0 = frame.cowlS + 0.28
const x0 = side * (frame.halfWidth(s0) + 0.035)
const y0 = frame.belt(s0) - 0.18
const s1 = frame.cowlS + 0.02
const y1 = frame.roofHeight + 0.02
const x1 = side * (frame.halfWidth(s1) * 0.93 + 0.04)
const path = roundPath([[x0, y0, s0], [x0, frame.belt(s0) + 0.05, s0 - 0.03], [x1, y1 - 0.05, s1], [x1, y1 + 0.02, s1 + 0.02]], 0.1, 3)
emitTube(trim, roundedRect(0.08, 0.06, 0.025, 2), path, { up: [side, 0, 0] })
emitBeam(trim, [x1, y1 + 0.02, s1 - 0.04], [x1, y1 + 0.02, s1 + 0.13], 0.1, 0.1, 0.03, { up: [0, 1, 0] })
},
},
exhaust: {
kind: 'exhaust',
label: 'Exhaust',
description: 'Tailpipe tips out of the rear valance.',
params: [
{ key: 'tips', label: 'Tips', type: 'number', min: 1, max: 4, step: 1, default: 2 },
{ key: 'style', label: 'Shape', type: 'select', options: ['round', 'oval', 'square'], default: 'round' },
{ key: 'size', label: 'Size', type: 'number', min: 0.6, max: 1.8, step: 0.05, default: 1 },
],
build(ctx, p) {
const { frame } = ctx
const chrome = sinkOf(ctx, 'mod_exhaust', 'chrome')
const soot = sinkOf(ctx, 'mod_exhaust', 'underbody')
const tips = Math.round(num(p, 'tips'))
const size = num(p, 'size')
const r = 0.035 * size
const s = frame.rearS
const y = frame.sill(s + 0.2) + 0.04
const w = frame.halfWidth(s + 0.2) * 0.55
const positions: number[] = tips === 1 ? [-w] : tips === 2 ? [-w, w] : tips === 3 ? [-w, 0, w] : [-w - r * 1.2, -w + r * 1.2, w - r * 1.2, w + r * 1.2]
const style = str(p, 'style')
const section: Vec2[] = style === 'square' ? roundedRect(r * 2.2, r * 1.6, r * 0.3, 1)
: style === 'oval' ? circle(r, 12).map(([u, v]) => [u * 1.5, v * 0.8] as Vec2)
: circle(r, tubeSegments(ctx.lod) + 2)
for (const x of positions) {
emitTube(chrome, section, [[x, y, s + 0.25], [x, y, s - 0.05]], { up: [0, 1, 0], caps: false })
const inner: Vec3[] = section.map(([u, v]) => [x + u * 0.82, y + v * 0.82, s - 0.03] as Vec3)
emitCap(soot, [...inner].reverse(), [x, y, s - 0.03])
}
},
},
hoodScoop: {
kind: 'hoodScoop',
label: 'Hood scoop',
description: 'Raised intake on the bonnet — rides with it when it opens.',
params: [
{ key: 'size', label: 'Size', type: 'number', min: 0.5, max: 1.5, step: 0.05, default: 1 },
],
build(ctx, p) {
const { frame } = ctx
if (!frame.hood) return
const size = num(p, 'size')
ctx.attach('mod_hoodScoop', 'hood')
const paint = sinkOf(ctx, 'mod_hoodScoop', 'paint')
const s0 = lerp(frame.hood.rearS, frame.hood.frontS, 0.25)
const s1 = lerp(frame.hood.rearS, frame.hood.frontS, 0.65)
const w = 0.28 * size
const path: Vec3[] = []
for (let k = 0; k <= 6; k += 1) {
const s = lerp(s0, s1, k / 6)
path.push([0, frame.surfaceY(s, 0) - 0.01, s])
}
const h = 0.07 * size
emitTube(paint, roundedRect(w, h * 2, h * 0.6, 2), path, {
up: [0, 1, 0],
scaleAt: (i) => 0.45 + 0.55 * Math.sin(Math.min(1, (i / 6) * 1.3) * Math.PI / 2),
})
const mouth: Vec3 = [0, frame.surfaceY(s1, 0) + h * 0.35, s1 + 0.003]
const hole: Vec3[] = circle(1, 12).map(([u, v]) => [mouth[0] + u * w * 0.4, mouth[1] + v * h * 0.5, mouth[2]] as Vec3)
emitCap(sinkOf(ctx, 'mod_hoodScoop', 'trim'), hole, mouth)
},
},
lightBar: {
kind: 'lightBar',
label: 'Light bar',
description: 'Roof-mounted LED bar; lights up with the headlights.',
params: [
{ key: 'width', label: 'Width', type: 'number', min: 0.4, max: 1, step: 0.05, default: 0.85 },
],
build(ctx, p) {
const { frame } = ctx
const cabinS = frame.roofFrontS - 0.1
const onRoof = frame.cabin(cabinS) > 0.5
const s = onRoof ? cabinS : frame.frontS - 0.15
const y = (onRoof ? frame.surfaceY(s, 0) : frame.top(s) + 0.1) + 0.07
const w = frame.topHalfWidth(s) * num(p, 'width')
const trim = sinkOf(ctx, 'mod_lightBar', 'trim')
emitBeam(trim, [-w, y, s], [w, y, s], 0.07, 0.07, 0.015, { up: [0, 1, 0] })
const lamps = sinkOf(ctx, 'mod_lightBar', 'lightHead')
const n = ctx.lod === 2 ? 1 : 6
for (let k = 0; k < n; k += 1) {
const x0 = lerp(-w * 0.92, w * 0.92, k / n) + 0.01
const x1 = lerp(-w * 0.92, w * 0.92, (k + 1) / n) - 0.01
emitBeam(lamps, [x0, y, s + 0.034], [x1, y, s + 0.034], 0.012, 0.05, 0.004, { up: [0, 0, 1] })
}
for (const side of [1, -1]) {
emitBeam(trim, [side * w * 0.8, y, s], [side * w * 0.8, onRoof ? frame.surfaceY(s, w * 0.8) : frame.top(s), s], 0.03, 0.02, 0.005, { up: [0, 0, 1] })
}
},
},
rollCage: {
kind: 'rollCage',
label: 'Roll cage',
description: 'Tubular cage: main hoop, A-pillar tubes and a roof frame.',
params: [
{ key: 'height', label: 'Height', type: 'number', min: 0.7, max: 1.3, step: 0.02, default: 1 },
],
build(ctx, p) {
const { frame } = ctx
const sink = sinkOf(ctx, 'mod_rollCage', 'trim')
const seg = circle(0.024, tubeSegments(ctx.lod))
const rear = lerp(frame.deckS, frame.cowlS, 0.2)
const front = frame.cowlS - 0.05
const base = (s: number): number => frame.belt(s) - 0.02
const topY = Math.max(frame.roofHeight, base(rear) + 0.25) + 0.25 * num(p, 'height')
const w = frame.halfWidth(rear) * 0.82
const wf = frame.halfWidth(front) * 0.8
const topRear = rear + 0.25
const topFront = front - 0.45
const hoop = roundPath([[-w, base(rear), rear], [-w * 0.9, topY, topRear], [w * 0.9, topY, topRear], [w, base(rear), rear]], 0.12, ctx.lod === 0 ? 4 : 2)
emitTube(sink, seg, hoop)
for (const side of [1, -1]) {
emitTube(sink, seg, roundPath([[side * wf, base(front), front], [side * w * 0.9, topY, topFront], [side * w * 0.9, topY, topRear]], 0.1, 2))
}
emitTube(sink, seg, [[-w * 0.9, topY, topFront], [w * 0.9, topY, topFront]])
emitTube(sink, seg, [[-w * 0.85, topY - 0.02, topRear], [w * 0.85, base(rear) + 0.2, rear]])
for (const side of [1, -1]) {
emitTube(sink, seg, [[side * w * 0.85, topY - 0.05, topRear], [side * w * 0.7, base(rear) - 0.02, frame.rearS + 0.3]])
}
},
},
mudFlaps: {
kind: 'mudFlaps',
label: 'Mud flaps',
description: 'Rubber flaps behind each wheel.',
params: [
{ key: 'length', label: 'Length', type: 'number', min: 0.15, max: 0.45, step: 0.01, default: 0.26 },
],
build(ctx, p) {
const trim = sinkOf(ctx, 'mod_mudFlaps', 'trim')
const len = num(p, 'length')
for (const arch of ctx.frame.axles) {
const s = arch.s - arch.archRadius - 0.03
for (const side of [1, -1]) {
const x = side * ctx.trackHalf
const top = ctx.frame.sill(s + 0.02) + 0.02
emitBeam(trim, [x, top, s], [x, Math.max(0.06, top - len), s], ctx.spec.wheels.width * 1.1, 0.008, 0.002, { up: [0, 0, 1] })
}
}
},
},
}
export const MOD_KINDS = Object.keys(MODS) as ModKind[]
/** Applies every mod's `modifySpec` in order and returns the spec that is actually built. */
export function applyModSpecs(spec: VehicleSpec): VehicleSpec {
let out = spec
for (const mod of spec.mods) {
const def = MODS[mod.kind]
if (def?.modifySpec) out = def.modifySpec(out, modParams(mod))
}
return out
}

98
src/generator/palette.ts Normal file
View file

@ -0,0 +1,98 @@
import { pick, type Random } from './random.ts'
import type { BodyStyle, PaintFinish } from './spec.ts'
/**
* Curated paint palettes.
*
* Uniformly random RGB makes a car park look like a bag of sweets. Real paint
* comes from a small set of colours per era and segment, and most cars are
* grey, white, black or silver — so the palettes are weighted that way and a
* style picks from the palettes that suit it.
*/
export interface Palette {
readonly name: string
readonly label: string
readonly colors: readonly string[]
readonly finishes: readonly PaintFinish[]
}
export const PALETTES: readonly Palette[] = [
{
name: 'factory',
label: 'Factory',
colors: ['#c9ccd0', '#1b1c1e', '#f1f1ef', '#5d6167', '#8c1c24', '#1f3a5f', '#3b4a3e', '#9aa2aa'],
finishes: ['metallic', 'metallic', 'solid', 'pearl'],
},
{
name: 'sport',
label: 'Sport',
colors: ['#c3261f', '#e8b81a', '#ef6c1a', '#2f7de1', '#86c232', '#101114', '#f4f4f2'],
finishes: ['solid', 'metallic', 'pearl'],
},
{
name: 'retro',
label: 'Retro',
colors: ['#a8d5c2', '#efe3c4', '#2f7f7a', '#d9a13b', '#c75b2a', '#7d9bb3', '#6b2f2a'],
finishes: ['solid', 'solid', 'metallic'],
},
{
name: 'utility',
label: 'Utility',
colors: ['#f2f2ef', '#d8d0bd', '#5a6048', '#747a80', '#233246', '#b8a27a'],
finishes: ['solid', 'solid', 'matte'],
},
{
name: 'midnight',
label: 'Midnight',
colors: ['#101216', '#1d2a44', '#2a1538', '#123a37', '#3b0f14', '#2b2e33'],
finishes: ['metallic', 'pearl', 'matte'],
},
{
name: 'pastel',
label: 'Pastel',
colors: ['#f4c7c3', '#c6dfea', '#dbe8c1', '#f3e5a8', '#d7c9ec', '#f7f3ea'],
finishes: ['solid', 'pearl'],
},
]
const BY_STYLE: Readonly<Record<BodyStyle, readonly string[]>> = {
sedan: ['factory', 'factory', 'midnight'],
hatchback: ['factory', 'pastel', 'sport'],
coupe: ['factory', 'sport', 'midnight'],
wagon: ['factory', 'retro'],
suv: ['factory', 'midnight', 'utility'],
pickup: ['utility', 'factory', 'retro'],
van: ['utility', 'utility', 'factory'],
sports: ['sport', 'sport', 'midnight'],
supercar: ['sport', 'midnight'],
muscle: ['sport', 'retro', 'midnight'],
kei: ['pastel', 'retro', 'factory'],
buggy: ['sport', 'utility'],
truck: ['utility', 'factory'],
}
export function palettesFor(style: BodyStyle): Palette[] {
return BY_STYLE[style].map((name) => PALETTES.find((p) => p.name === name)!)
}
export function randomColor(random: Random, style: BodyStyle): { color: string; finish: PaintFinish; palette: string } {
const palette = pick(random, palettesFor(style))
return { color: pick(random, palette.colors), finish: pick(random, palette.finishes), palette: palette.name }
}
/** Parses '#rrggbb' to 0..1 channels. */
export function hexToRgb(hex: string): [number, number, number] {
const v = Number.parseInt(hex.replace('#', ''), 16)
return [((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255]
}
export function rgbToHex([r, g, b]: readonly [number, number, number]): string {
const c = (x: number): string => Math.round(Math.min(1, Math.max(0, x)) * 255).toString(16).padStart(2, '0')
return `#${c(r)}${c(g)}${c(b)}`
}
export function mixHex(a: string, b: string, t: number): string {
const ca = hexToRgb(a)
const cb = hexToRgb(b)
return rgbToHex([ca[0] + (cb[0] - ca[0]) * t, ca[1] + (cb[1] - ca[1]) * t, ca[2] + (cb[2] - ca[2]) * t])
}

283
src/generator/presets.ts Normal file
View file

@ -0,0 +1,283 @@
import type {
BodySpec,
BodyStyle,
CargoSpec,
ChassisSpec,
ModSpec,
PaintSpec,
VehicleSpec,
WheelSpec,
} from './spec.ts'
/**
* Body-style presets.
*
* Every style is the same generator with different numbers, and every set of
* numbers is measured off a real vehicle of its segment: length × width ×
* height, wheelbase, front overhang, tyre size, and the cabin stations — where
* the windshield starts and ends, where the roof ends, where the rear glass
* meets the boot. A car whose wheelbase is off by 10 % or whose glass is a
* hand too tall reads as a toy before anyone can say why.
*
* Roof height is given at the edge of the roof; the crown adds the rest.
*/
/** Mid-size saloon: 4.75 × 1.84 × 1.45 m, 2.83 m wheelbase, 235/45 R18. */
const BODY: BodySpec = {
length: 4.75,
width: 1.84,
sill: 0.2,
noseHeight: 0.8,
hoodHeight: 0.99,
roofHeight: 1.41,
deckHeight: 1.07,
tailHeight: 1.02,
cowl: 0.64,
roofFront: 0.47,
roofRear: 0.24,
deck: 0.12,
noseRound: 0.2,
tailRound: 0.16,
tumblehome: 0.2,
greenhouseWidth: 0.88,
sideBulge: 0.45,
roofCrown: 0.04,
hoodCrown: 0.025,
flare: 0.012,
archGap: 0.045,
doors: 2,
bed: null,
bumpers: 'painted',
noseTaper: 0.05,
tailTaper: 0.03,
}
const WHEELS: WheelSpec = {
radius: 0.334,
width: 0.235,
rimRatio: 0.68,
rim: 'spoke',
spokes: 5,
tread: 'road',
offset: 0,
camber: 0,
dish: 0.012,
}
const CHASSIS: ChassisSpec = {
wheelbase: 2.83,
frontOverhang: 0.95,
track: 0.86,
rideHeight: 0,
drive: 'fwd',
}
const NO_CARGO: CargoSpec = { type: 'none', length: 0, height: 0 }
export const DEFAULT_PAINT: PaintSpec = {
primary: '#8c1c24',
secondary: '#e8e6e1',
finish: 'metallic',
twoTone: 'none',
livery: 'none',
stripe: '#f2f2f2',
rim: '#b9bec4',
rimFinish: 'satin',
trim: '#16181b',
caliper: '#9aa0a6',
tint: 0.35,
}
interface Preset {
readonly label: string
readonly body: Partial<BodySpec>
readonly wheels?: Partial<WheelSpec>
readonly chassis?: Partial<ChassisSpec>
readonly cargo?: CargoSpec
readonly paint?: Partial<PaintSpec>
readonly mods?: readonly ModSpec[]
}
const PRESETS: Readonly<Record<BodyStyle, Preset>> = {
// Mid-size saloon, 4.75 × 1.84 × 1.45 m.
// Modern mid-size saloon: short overhangs, high belt, fastback roof into a
// short deck, 235/40 R19 filling deep, flared arches.
sedan: {
label: 'Sedan',
body: {
length: 4.85, width: 1.86, noseHeight: 0.8, hoodHeight: 0.97, roofHeight: 1.4, deckHeight: 1.08, tailHeight: 1.0,
cowl: 0.72, roofFront: 0.54, roofRear: 0.32, deck: 0.15, noseRound: 0.28, tailRound: 0.24,
tumblehome: 0.27, greenhouseWidth: 0.86, roofCrown: 0.05, hoodCrown: 0.03,
flare: 0.022, archGap: 0.022, noseTaper: 0.1, tailTaper: 0.07,
},
wheels: { radius: 0.345, width: 0.235, rimRatio: 0.72 },
chassis: { wheelbase: 2.84, frontOverhang: 0.93 },
},
// C-segment hatch, 4.28 × 1.79 × 1.46 m, 225/45 R17.
hatchback: {
label: 'Hatchback',
body: {
length: 4.28, width: 1.79, noseHeight: 0.79, hoodHeight: 0.98, roofHeight: 1.42, deckHeight: 1.13,
tailHeight: 1.02, cowl: 0.66, roofFront: 0.49, roofRear: 0.1, deck: 0.035, noseRound: 0.2, tailRound: 0.12,
tumblehome: 0.18,
},
wheels: { radius: 0.317, width: 0.225 },
chassis: { wheelbase: 2.63, frontOverhang: 0.88 },
paint: { primary: '#2a5d8f' },
},
// Two-door coupe, 4.6 × 1.85 × 1.37 m.
coupe: {
label: 'Coupe',
body: {
length: 4.6, width: 1.85, sill: 0.18, noseHeight: 0.76, hoodHeight: 0.95, roofHeight: 1.33, deckHeight: 1.03,
tailHeight: 0.99, cowl: 0.63, roofFront: 0.47, roofRear: 0.29, deck: 0.15, doors: 1, tumblehome: 0.24, sideBulge: 0.55,
},
wheels: { radius: 0.335, width: 0.245, rim: 'multispoke', spokes: 10, rimRatio: 0.7 },
chassis: { wheelbase: 2.75, frontOverhang: 0.95, drive: 'rwd' },
paint: { primary: '#d9d7d2', finish: 'pearl' },
},
// Estate, 4.8 × 1.84 × 1.5 m.
wagon: {
label: 'Wagon',
body: {
length: 4.8, roofHeight: 1.46, roofRear: 0.06, deck: 0.03, deckHeight: 1.13, tailHeight: 1.03, tailRound: 0.12,
roofFront: 0.49, cowl: 0.65,
},
wheels: { rim: 'mesh', spokes: 8 },
chassis: { wheelbase: 2.85 },
paint: { primary: '#3d4a3f', finish: 'metallic' },
},
// Compact SUV, 4.6 × 1.86 × 1.7 m, 225/60 R18.
suv: {
label: 'SUV',
body: {
length: 4.6, width: 1.86, sill: 0.34, noseHeight: 0.96, hoodHeight: 1.13, roofHeight: 1.66, deckHeight: 1.3,
tailHeight: 1.17, cowl: 0.64, roofFront: 0.5, roofRear: 0.08, deck: 0.03, noseRound: 0.2, tailRound: 0.12,
tumblehome: 0.15, bumpers: 'black', flare: 0.02, archGap: 0.06, noseTaper: 0.04,
},
wheels: { radius: 0.365, width: 0.225, rimRatio: 0.63, spokes: 6 },
chassis: { wheelbase: 2.69, frontOverhang: 0.92, track: 0.86, drive: 'awd' },
paint: { primary: '#1d1f22', finish: 'metallic' },
},
// Full-size crew-cab pickup, 5.4 × 2.0 × 1.92 m, 265/70 R17.
pickup: {
label: 'Pickup',
body: {
length: 5.4, width: 2.0, sill: 0.5, noseHeight: 1.16, hoodHeight: 1.3, roofHeight: 1.88, deckHeight: 1.3,
tailHeight: 1.3, cowl: 0.73, roofFront: 0.63, roofRear: 0.46, deck: 0.44, noseRound: 0.16, tailRound: 0.06,
tumblehome: 0.1, bed: { start: 0.02, end: 0.42, depth: 0.52 }, bumpers: 'chrome', flare: 0.02, archGap: 0.07,
noseTaper: 0.02, tailTaper: 0, hoodCrown: 0.02,
},
wheels: { radius: 0.4, width: 0.265, rimRatio: 0.54, rim: 'spoke', spokes: 6, tread: 'offroad' },
chassis: { wheelbase: 3.3, frontOverhang: 0.95, drive: 'rwd' },
paint: { primary: '#7a1f1f', finish: 'solid' },
},
// Mid-size panel van, 5.0 × 1.99 × 1.97 m, 215/65 R16.
van: {
label: 'Van',
body: {
length: 5.0, width: 1.99, sill: 0.32, noseHeight: 0.88, hoodHeight: 1.1, roofHeight: 1.93, deckHeight: 1.88,
tailHeight: 1.84, cowl: 0.85, roofFront: 0.76, roofRear: 0.02, deck: 0.01, noseRound: 0.2, tailRound: 0.08,
tumblehome: 0.06, greenhouseWidth: 0.95, bumpers: 'black', roofCrown: 0.04, sideBulge: 0.2,
},
wheels: { radius: 0.345, width: 0.215, rim: 'steelie', spokes: 8, rimRatio: 0.58 },
chassis: { wheelbase: 2.93, frontOverhang: 0.93 },
paint: { primary: '#e9e9e6', finish: 'solid' },
},
// Front-engined sports coupe, 4.25 × 1.78 × 1.3 m, 215/45 R17.
sports: {
label: 'Sports',
body: {
length: 4.25, width: 1.78, sill: 0.14, noseHeight: 0.66, hoodHeight: 0.87, roofHeight: 1.27, deckHeight: 0.97,
tailHeight: 0.93, cowl: 0.62, roofFront: 0.47, roofRear: 0.3, deck: 0.18, doors: 1, tumblehome: 0.24, sideBulge: 0.65,
flare: 0.02, noseRound: 0.24, roofCrown: 0.03,
},
wheels: { radius: 0.315, width: 0.225, rim: 'multispoke', spokes: 7, rimRatio: 0.7, tread: 'sport', dish: 0.02 },
chassis: { wheelbase: 2.57, frontOverhang: 0.85, drive: 'rwd' },
paint: { primary: '#c3261f', finish: 'metallic', caliper: '#d9a21b' },
},
// Mid-engined supercar, 4.5 × 1.93 × 1.17 m, 305/30 R20.
supercar: {
label: 'Supercar',
body: {
length: 4.5, width: 1.93, sill: 0.12, noseHeight: 0.56, hoodHeight: 0.8, roofHeight: 1.14, deckHeight: 0.99,
tailHeight: 0.97, cowl: 0.7, roofFront: 0.58, roofRear: 0.38, deck: 0.28, noseRound: 0.3, tailRound: 0.16,
doors: 1, tumblehome: 0.28, sideBulge: 0.8, flare: 0.03, hoodCrown: 0.02, roofCrown: 0.03, noseTaper: 0.08,
},
wheels: { radius: 0.345, width: 0.29, rim: 'turbine', spokes: 5, rimRatio: 0.74, tread: 'sport', dish: 0.025 },
chassis: { wheelbase: 2.62, frontOverhang: 1.02, track: 0.86, drive: 'awd' },
paint: { primary: '#e8b81a', finish: 'pearl', caliper: '#1a1a1a' },
},
// Classic fastback muscle car, 4.8 × 1.9 × 1.33 m.
muscle: {
label: 'Muscle',
body: {
length: 4.8, width: 1.9, sill: 0.18, noseHeight: 0.84, hoodHeight: 0.97, roofHeight: 1.3, deckHeight: 1.02,
tailHeight: 1.0, cowl: 0.58, roofFront: 0.45, roofRear: 0.3, deck: 0.13, noseRound: 0.1, tailRound: 0.1,
doors: 1, bumpers: 'chrome', noseTaper: 0.02, tailTaper: 0.01, sideBulge: 0.35, hoodCrown: 0.02,
},
wheels: { radius: 0.345, width: 0.255, rim: 'deepdish', spokes: 5, rimRatio: 0.6, tread: 'sport', dish: 0.03 },
chassis: { wheelbase: 2.78, frontOverhang: 0.98, drive: 'rwd' },
paint: { primary: '#1f3f73', finish: 'solid', livery: 'stripes', stripe: '#f4f1ea', rimFinish: 'chrome' },
},
// Kei car at the legal maximum: 3.4 × 1.48 × 1.8 m, 155/65 R14.
kei: {
label: 'Kei car',
body: {
length: 3.395, width: 1.475, sill: 0.19, noseHeight: 0.8, hoodHeight: 0.94, roofHeight: 1.75, deckHeight: 1.3,
tailHeight: 1.12, cowl: 0.8, roofFront: 0.7, roofRear: 0.06, deck: 0.03, noseRound: 0.16, tailRound: 0.08,
tumblehome: 0.06, greenhouseWidth: 0.94, bumpers: 'black', sideBulge: 0.2, noseTaper: 0.03, tailTaper: 0.01,
},
wheels: { radius: 0.279, width: 0.155, rim: 'steelie', spokes: 6, rimRatio: 0.64 },
chassis: { wheelbase: 2.52, frontOverhang: 0.46, track: 0.88 },
paint: { primary: '#a8d5c2', finish: 'solid', twoTone: 'roof', secondary: '#f3f1ea' },
},
// Off-road buggy with a tube cage.
buggy: {
label: 'Buggy',
body: {
length: 3.6, width: 1.8, sill: 0.46, noseHeight: 0.72, hoodHeight: 0.92, roofHeight: 0.92, deckHeight: 0.96,
tailHeight: 0.9, cowl: 0.62, roofFront: 0.56, roofRear: 0.36, deck: 0.3, noseRound: 0.3, tailRound: 0.2,
doors: 0, bumpers: 'black', flare: 0, archGap: 0.09, tumblehome: 0, greenhouseWidth: 0.92, noseTaper: 0.2,
},
wheels: { radius: 0.42, width: 0.3, rim: 'beadlock', spokes: 8, rimRatio: 0.52, tread: 'offroad' },
chassis: { wheelbase: 2.45, frontOverhang: 0.62, track: 0.9, drive: 'awd' },
paint: { primary: '#ef6c1a', finish: 'matte', rimFinish: 'painted', rim: '#232427' },
mods: [{ kind: 'rollCage' }],
},
// Light cab-over truck with a box body: cab 2.0 × 2.0 × 2.3 m, 215/75 R17.5.
truck: {
label: 'Truck cab',
body: {
length: 2.0, width: 2.0, sill: 0.56, noseHeight: 1.2, hoodHeight: 1.38, roofHeight: 2.26, deckHeight: 2.22,
tailHeight: 2.18, cowl: 0.9, roofFront: 0.82, roofRear: 0.03, deck: 0.015, noseRound: 0.14, tailRound: 0.06,
tumblehome: 0.05, greenhouseWidth: 0.97, bumpers: 'black', sideBulge: 0.1, doors: 1, noseTaper: 0.02, tailTaper: 0,
archGap: 0.08, roofCrown: 0.04,
},
wheels: { radius: 0.385, width: 0.215, rim: 'steelie', spokes: 10, rimRatio: 0.58, tread: 'offroad' },
chassis: { wheelbase: 3.4, frontOverhang: 1.05, track: 0.84, drive: 'rwd' },
cargo: { type: 'box', length: 4.3, height: 2.1 },
paint: { primary: '#f2f2ef', finish: 'solid' },
},
}
export const BODY_STYLES = Object.keys(PRESETS) as BodyStyle[]
export function styleLabel(style: BodyStyle): string {
return PRESETS[style].label
}
/** The full spec of a body style, ready to generate. */
export function preset(style: BodyStyle, seed = 1): VehicleSpec {
const p = PRESETS[style]
return {
style,
seed,
body: { ...BODY, ...p.body },
wheels: { ...WHEELS, ...p.wheels },
chassis: { ...CHASSIS, ...p.chassis },
cargo: p.cargo ?? NO_CARGO,
paint: { ...DEFAULT_PAINT, ...p.paint },
mods: p.mods ?? [],
}
}

42
src/generator/random.ts Normal file
View file

@ -0,0 +1,42 @@
/**
* Deterministic randomness.
*
* The same seed must give the same vehicle on every machine, every run: a
* game that stores `{ style: 'hatchback', seed: 1234 }` in a save file expects
* the same car when it loads it. `Math.random()` is therefore never used
* anywhere in the generator.
*
* mulberry32: 32-bit state, fast, statistically fine for shape variation.
*/
export type Random = () => number
export function createRandom(seed: number): Random {
let state = (Math.floor(seed) ^ 0x9e3779b9) >>> 0
return () => {
state = (state + 0x6d2b79f5) >>> 0
let t = state
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/** Uniform value in [min, max). */
export function range(random: Random, min: number, max: number): number {
return min + (max - min) * random()
}
/** Symmetric deviation in [-amount, +amount). */
export function jitter(random: Random, amount: number): number {
return (random() * 2 - 1) * amount
}
export function pick<T>(random: Random, list: readonly T[]): T {
const item = list[Math.floor(random() * list.length) % list.length]
if (item === undefined) throw new Error('pick() from an empty list')
return item
}
export function chance(random: Random, probability: number): boolean {
return random() < probability
}

Some files were not shown because too many files have changed in this diff Show more