Module: hassault (HorribleAssault)
An AssaultCube remix that runs as a pane in the dashboard, with its own client, its own netcode, and its own server infrastructure. AssaultCube's original stack — an SDL/OpenGL C++ client speaking ENet over UDP to a master server — cannot run in a browser and is not what we want anyway; the point is to rebuild it on the fabric this app already has.
Implemented so far: the map pipeline, the renderer, the netcode, weapons, and bots — you can walk around a map in first person, and you can fight in it: an authoritative match server on your own backend, five weapons with lag-compensated hit registration, and bot players to fill out a match when nobody else is about.
It needs nothing installed. The game plays nine modelled maps of its own, the same nine on every platform. It used to also read AssaultCube's maps out of a local install, and that was removed on 2026-10-03 (see Bundled maps).
Licensing: whose content ships, and whose does not
AssaultCube splits its licensing, and the split decides the whole design:
- The source is under a zlib-like license. That is the part being remixed —
cgz.pyis a direct port ofload_worldandrldecodecubesfromsource/src/worldio.cpp. - The content (maps, textures, models, sounds) is copyright. It may be redistributed only inside an unmodified AssaultCube package, and never commercially.
This repo is public, deploys to GitHub Pages, and ships a server image to Fly, so
committing a single AssaultCube .cgz or texture would be a violation.
HorribleAssault therefore supported AssaultCube content without ever bundling
it: you pointed it at your own install and the backend read from there. That
support has since been removed, and the game plays only its own maps. Same
precedent as SearXNG (AGPL — supported, never bundled) and choosing pypdf over
AGPL PyMuPDF.
That restriction is about their content, and it says nothing about ours. The
format is understood well enough to write as well as read, so the game ships
its own maps. See Bundled maps. The same rule has held for every asset class
since: surface detail is generated at runtime (surfaces.ts), the weapon and item
shapes are geometric, and the gunshots are synthesized. Nothing that would ever
need someone else's copyright.
The test suite follows the same rule. Hermetic tests synthesize maps in memory, the bundled maps give every machine real maps to play, and the tests that read AssaultCube's maps skip when no install is present.
The setting: The Deadzone
The two team colours were commented "CLA sand, RVSF blue" and the native client's constants were named for the same pair — AssaultCube's factions. The maps are painted from our own JSON brushes and the gunshots are synthesized rather than sampled for one reason, and the fiction gets the same treatment.
Autonomous orchestration ran the grid until it stopped being asked to. What is left are the shells: coolant pits drained to bedrock, switchyards still humming off dead schedules, campus atria with the lights on and nobody billed. Compute is the only currency that survived, and it is all sitting in buildings nobody legally owns any more.
ARC — the Assembly of Reclaimed Compute. Squatters and operators who think a machine left running belongs to whoever keeps it running. Amber and sand. HALON — the custodial contractor that never got the cancellation notice. Still issued, still uniform, still auditing. Steel and cold blue. Neither side is right; the maps are the argument.
It lives in backend/modules/hassault/lore.py as data, not prose, because the
faction palette tints an avatar in two renderers, the rank names go on a ladder
card, and the map briefs go on the loading screen. Four copies of a faction colour
is four places for it to drift, so it is served (GET /api/hassault/lore) — the
plane_order / zoom_levels precedent.
Two things it deliberately does not own:
- The ladder. Tiers, floors and ratings belong to the game server
(
backend/games_server/store.py::TIERS) because a node cannot adjudicate its own player.RANKSis a naming layer keyed by those tier ids — Scavenger, Runner, Operator, Breaker, Warden, Overseer, Architect — and renaming a rank must never be able to move a rating. A tier with no name falls back to its raw id rather than vanishing, because a missing display string must not hide a rated player. - The team split. Which spawn belongs to which side is already in the map's
playerstartentities asteam: 0/team: 1.TEAM_FACTIONSmaps that index onto a faction; it does not decide it, so no existing map changes meaning.
Every map this repo ships has a brief, one per modelled map, and
test_the_lore_route_serves_both_factions_and_the_map_briefs fails if one is
missing.
The hitbox is served, and it is not finished
PLAYER_RADIUS = 1.1 and the crouch scale used to be constants in physics.py,
copied by hand into world.ts, player.ts, avatars.ts and bodies.rs — four
copies of a figure nobody has finished choosing. There is still no wall
penetration, the head band has never been checked against a real character model,
and the relationship between what a body looks like and what it is has only
ever been asserted.
So backend/modules/hassault/hitbox.py is the authority and both clients read it.
The spec is the authority; a mesh never is — an avatar is fitted to the body,
not the other way round, and no renderer gets to widen a hitbox by drawing it wide.
That much is fixed even though the numbers are not.
The version is a content hash, not a label
spec_id is derived from the hit-deciding dimensions themselves, and
physics-vectors.json — the fixture both the Python and TypeScript physics suites
replay — is stamped with it.
A hand-maintained revision number is a thing you forget to bump, and forgetting has
the worst failure mode available here: two implementations replaying a fixture that
no longer describes either of them, agreeing with each other about a body that does
not exist. A hash cannot be forgotten. Change a dimension and
test_the_shared_fixture_is_not_stale fails, naming both hashes, until the vectors
are regenerated deliberately and both suites are made to pass.
The two art tolerances (fit_tolerance, eye_tolerance) are excluded from the
hash on purpose: they decide whether a model is acceptable, not where a bullet
lands, so tightening one must not invalidate vectors that are still accurate.
Nullable defaults, not constants
ray_hits_body and can_stand take radius/height as None and resolve them
from the live spec. A default argument binds at import, so leaving them as
= PLAYER_RADIUS would mean a tuned body reached everywhere except the code that
decides the hit — tuning that appears to work and does not. The same is None
discipline the hardware-resolved request fields use: an explicit 0 is a real
answer, and a head band of zero ("no headshots") must not read as "leave it alone".
resolve_shot reads the spec once per trigger pull, not per pellet: a shotgun
firing eight pellets must resolve all of them against the same body, and a slider
moved mid-shot would otherwise split one blast across two hitboxes.
What is deliberately not in it
- Step height, speeds, gravity, friction — movement, not the body.
- Wall penetration. A bullet stopping at a wall is a property of the wall.
Today
resolve_shot's "nearer than the wall" comparison is the entire cover model, and the temptation to compensate for a missing penetration model by widening a body is exactly what this module exists to make visible. - A setting.
SettingValueis a scalar andGET /api/settingshands the bag to every plugin; more to the point a hitbox is one coherent object, and a half-applied one — a new radius against an old head band — is a state nothing downstream should have to consider.PUT /api/hassault/hitboxtakes the whole thing, and does not persist it: promoting a tuned body is a code change with regenerated vectors behind it, which is the right amount of friction between "this felt better" and "this is the game now".
Why a TypeScript/WebGL rewrite is tractable
Cube 1 worlds — which AssaultCube still uses — are not BSP. The world is a
flat 2D grid of columns: each cell has a type, a floor and ceiling height, three
texture ids, and a vertex delta. A whole map is (1 << sfactor)² records of nine
bytes, which is 65 536 cells for the standard sfactor of 8.
That is why this can be rendered in Three.js without porting a C++ engine.
The .cgz format, and the parts that bite
Transcribed from world.h rather than inferred — a wrong offset here produces
plausible garbage rather than an error.
| Region | Detail |
|---|---|
| Magic | CUBE or ACMP. Every AssaultCube 1.3 map is ACMP. |
| Header | sizeof(header) is 980 bytes; the first 916 precede waterlevel. |
| Header size | Untrustworthy before v10 — see fix_header_size. |
| Entities | 12 bytes before v10, 16 from v10 (attr5..attr7 added). |
| Cubes | Run-length encoded; 255 repeats the previous cube N times. |
Four things are easy to get wrong:
Entities start at headersize, not at the end of the struct. From v10 a map
may carry a variable-length extra-header block between the two, and every
official 1.3 map does — they range from 3 024 to 6 302 bytes against a 980-byte
struct. Reading entities from offset 980 lands in the middle of that blob.
A SOLID record carries only a wall texture and a vdelta. Everything else
comes from sqrdefault (floor 0, ceil 16, default floor/ceil textures). A reader
that leaves them zero produces a map with no ceilings.
v10 scales angles by ten. A spawn stored as 1810 faces 181°. This was
confirmed against the shipped map set rather than assumed: all 1 741 player
spawns across the 44 official maps have attr1 a multiple of ten, spanning
0–3590, with nothing at or above 3600. MapEntity.yaw resolves this at parse
time, because an entity has no way to know its own map's version.
A truncated cube stream is filled, not rejected. The engine fills the
remainder with defaults and carries on; refusing would discard an otherwise
readable map. The result is flagged as truncated.
Positions (x, y, z) are plain signed 16-bit cube coordinates and are never
scaled — only attributes are.
Bundled maps
backend/modules/hassault/mapsource.py + backend/modules/hassault/maps/*.json.
Nine maps ship with the app, and they are the only maps the game plays, on every
platform: the browser, the desktop pane, the native client and the game server.
They are ours, CC0, and named hd_*. All nine are modelled gltf maps:
hd_assault, hd_bank, hd_dust2, hd_facility, hd_inferno, hd_junkflea,
hd_mirage, hd_nuke and hd_office. Each is a Blender generator in
tools/blender/ exported to one GLB that both clients load; see
The modelled maps.
apps/assault-web/src/maps.ts lists the same nine with their key art, plus
the aim range below, and lore.py has a brief for each.
A tenth, hd_aim, is the aim range: an indoor training range modelled in
tools/blender/generate_aim.py, three lanes walled apart (close, gallery,
long) with its drill stations declared in the source under a top-level
drills key. See The aim range. It is a training map, so
the web client's match list leaves it out; see Aim drills. It
passes the same playability bar as the rest (spawns, items, reachability).
What was removed on 2026-10-03. Two catalogs used to sit beside these:
- An AssaultCube install's maps.
hassault.installPath(or a probe of the usual install locations) added an install's 44.cgzmaps to every map picker. The setting, the probe and the install half ofassets.pyare gone. The.cgzreader and writer stay: the Cube grid is still the collision layer that every modelled map is baked into, and the map designer's drafts are Cube maps. - Three Cube heightfields:
hd_atrium,hd_crossingandhd_pit. They moved tobackend/tests/fixtures/hassault_maps/. The backend suite is built on them, since they simulate in milliseconds, andbackend/tests/conftest.pyadds that directory throughHASSAULT_EXTRA_MAP_DIRS(mapsource.EXTRA_MAP_DIRS_ENV). They are in the catalog during tests and nowhere else.test_the_lore_route_serves_both_factions_and_the_map_briefschecks every shipped map has a brief.
Read a map source through mapsource.source_path(name), never
MAPS_DIR / f"{name}.json": the second misses the fixture directory, which is
how the suite's first run after the move failed.
See Two level formats for what the difference
between the two kinds changes. The
adjudicable set is pinned exactly — not as a subset — in
test_games_hassault_rooms.py, because the point of that assertion is that the
set a rated match may be played on is closed, so a map appearing in it without
being added deliberately is precisely what it should catch.
assets.py is the map catalog and nothing else: list_maps and load_map,
which resolves a draft first and then a bundled map. The 3D asset cache — the
GLB download/verify pipeline behind /api/hassault/assets/* — is
asset_cache.py, deliberately a separate module: it was briefly written over
assets.py, which removed install_root/list_maps from under six call sites in
one commit. GET /api/hassault/status then 500'd, and because that call is the
loader's install stage, the pane froze at 17% showing a bare fetch error rather
than anything naming the module that had gone missing.
The manifest (packages/core/src/modules/hassault/assets.manifest.json, mirrored
to assets/manifest.json by pnpm assets:pack) is one release: its sha256
values describe the files on the assets-v<version> GitHub release its baseUrl
points at. Adding or rebuilding a GLB therefore means bumping version, moving
baseUrl to the new tag, and publishing that release with every file — not just the
changed ones, since a client pulls everything from one URL. Neither assets:pull nor
asset_cache.sync_assets refuses a hash mismatch (both warn and install), so a stale
baseUrl silently serves the previous release; assets-manifest.test.ts pins the tag
to the version. The browser's CacheStorage (models/assetCache.ts) keys each entry by
the asset's own sha256, and caches only manifest assets — CacheStorage never
revalidates, and keying by version alone let the hd_*.glb maps (committed files,
not release assets, so they have no manifest entry) be rebuilt under v3 while every
browser that had opened one kept drawing the old geometry. The maps now ride the
ordinary HTTP cache, which revalidates. v2 added hassault-operator-t, hassault-weapon-knife and the three
hassault-grenade-* props. v3 introduced the procedural PBR tactical knife redesign
and 5 rare knife archetypes (karambit, butterfly, bayonet, skeleton, huntsman).
v4 carries the remodelled tactical knife and its five archetypes (three to six times
the geometry of v3's), and hassault-hands, the sleeved and gloved viewmodel, which v3's
manifest listed but its release never held, so assets:pull could not fetch it.
The source of truth is JSON, not a .cgz
A committed binary would be an opaque blob in a public repo — unreviewable, undiffable, and regenerated wholesale to nudge one spawn. A Cube 1 world is a flat grid of columns with no overlapping geometry, so a map is just rectangles painted in order over solid rock, and that fits in a file a reviewer can read:
{
"title": "The Pit",
"sfactor": 6,
"brushes": [
{ "op": "room", "rect": [4, 4, 56, 56], "floor": 0, "ceil": 14 },
{ "op": "room", "rect": [24, 24, 16, 16], "floor": -5, "ceil": 14 },
{ "op": "stairs", "rect": [18, 28, 6, 8], "axis": "x", "from": 0, "to": -5 },
{ "op": "solid", "rect": [12, 12, 4, 4] }
],
"entities": [{ "type": "playerstart", "x": 9, "y": 9, "yaw": 45, "team": 0 }]
}
rect is [x, y, w, h] in cells and later brushes overwrite earlier ones, so a
solid after a room cuts a pillar back out of it. Three ops is the whole
vocabulary. Heights are signed cubes in the units the physics already reads: a
body needs 5.2 of headroom to stand and can step up STEP_HEIGHT (1.6) without
jumping, which is what makes a run of one-cube stairs walkable.
Stairs are stepped rather than a heightfield on purpose. FHF reads vdelta
from the corner-vertex cell, so a slope only holds together when its
neighbours agree — see the heightfield
rule — and getting that
wrong tears the surface at every seam, silently.
The writer, and what pins it
cgz.write_cgz is the inverse of the reader: v10 only, RLE-encoded, a real file
AssaultCube's own editor opens. GET /api/hassault/maps/{name}/download serves
it — for bundled maps only, since re-serving copyright content over HTTP is
precisely the thing this module does not do.
The writer has no independent specification, so its correctness argument is
entirely agreement with a reader that has been validated against 44 real
maps: test_hassault_bundled.py builds each map, writes it, parses it back,
and requires all nine planes and every entity to come out identical.
Two traps the round trip exists to catch:
- A SOLID record stores only
wtexandvdelta. Everything else comes fromsqrdefaulton the way back in, so a solid cube carrying a floor height would be silently rewritten by its own round trip. The writer refuses it instead. - A run length is one byte. Anything longer is split, and each continuation still repeats the same previous cube — an off-by-one there rewrites the grid.
Playability is a test, not an assumption
A map that builds is not a map you can play, and neither the format nor the
renderer has any opinion about that. So the bundled maps are checked the way a
player would experience them: every spawn must be somewhere a body actually fits
(can_stand at the position spawn_at resolves), and a flood fill on foot —
step up at most STEP_HEIGHT, drop freely — must reach every standable cell
from the first spawn.
That last one earns its keep. hd_atrium's gallery ring is cut into four pieces
by the gates through it, and the first draft built two staircases; the reachability
test named the two stranded quadrants by their exact bounds. Nothing else in the
suite would have failed, and the map would simply have had two ledges nobody
could get to.
The modelled maps: how one is built, and what each revision changed
A modelled map is a Blender generator (tools/blender/generate_<map>.py) plus the
shared helpers in maplib.py. Changing one means running five steps in order,
because each reads what the step before it wrote:
- Generate:
blender --background --factory-startup --python tools/blender/generate_dust2.py. This writes the GLB to both homes (backend/modules/hassault/maps/andapps/web/public/). It also writes the map's lights and atmosphere into its JSON (see below), and the hash of the collision mesh ascollisionSource. The export refuses two things the bake would silently get wrong. The first is an object name at Blender's 63-byte limit: it was probably cut short, and Assault's batches lost their_NonColthat way, so sprinkler pipes and floor stripes became invisible walls. The second is a collider island that is open (and not a flat sheet) or inside-out (maplib.audit_colliders).HASSAULT_MAP_STRICT=0exports anyway, for looking at the result. - Bake:
blender --background --factory-startup --python tools/blender/bake_collision.py -- hd_dust2rasterises the GLB into the JSON's brushes, which is what the server simulates. It writes the hash of what it read ascollisionBaked;test_bake_is_of_the_current_modelfails until the two hashes match. It stops if the generator's collision mesh is missing, unless you pass--from-shipped, which bakes the shipped GLB (and so fails that test). - Fit:
uv run python tools/hassault_fit_placements.py hd_dust2moves any spawn, item, site or light the new geometry swallowed to the nearest valid cell. Never skip it: step 1 rewrites every light from the generator, a few of those land inside a wall, and the committed JSON holds them only after fitting. Skipping it shows up as lights "drifting" in a diff that changed none. - Sync Train's spawns:
uv run python tools/hassault_sync_client_spawns.py hd_dust2copies the fitted JSON spawns into the offline tables inworld3d.tsandworld3d.rs. Each row'szis wherespawn_atstands the body. Offline Train grounds each row on the mesh at its cell's middle (groundSpawn/ground_spawn). - Check:
maplint, then the nativetest_spawn_clearance, which grounds every offline spawn the way Train does and fails if the row's floor is not the mesh's. Also run theglb-surfacesvector test, whose golden list gains a row for any new material. Regenerate it withUPDATE_GLB_SURFACE_VECTORS=1. And runmap-geometry.test.ts, which reads every shipped GLB and fails on an inside-out mesh or two surfaces fighting for one plane. Then check the grid against the model withblender --background --factory-startup --python tools/blender/audit_collision.py -- hd_dust2. It exits 1 on any reachable cell where the grid's floor is not the mesh's, or where something solid stands at body height in a cell the grid calls open, and it reports roofed-over rooms that baked into solid boxes. Last, runprobe_eye_inside.py: an eye inside any mesh, colliders included, is a see-through bug.
Run the generators headless on Blender 5.3 (BLENDER=/path/to/blender
for bake_bounce.py, which launches it itself); 4.1, which built the committed
maps, still works. They call read_factory_settings, which the Blender MCP
sandbox refuses, so the MCP connection is for looking at a scene, not for running
a generator. With HASSAULT_MAP_OUT set to a scratch directory a generator
writes there instead of the repo, so a change can be diffed first.
The generators are deterministic: unchanged, they reproduce their own GLB byte for byte, run after run. Moving from 4.1 to 5.3 took four changes to keep that, and to keep every map what it was:
- The exporter's vertex-colour switch was renamed. 4.1's
export_colors=Trueisexport_vertex_color="MATERIAL"from 4.2 (maplib._vertex_color_options, which reads which one the operator has). An unknown keyword fails the export. - Face order stopped being repeatable. From 4.2 the shape passes emit a
mesh's faces in an order that changes between runs — Dust II's merged dressing
came out with the same triangles in a different sequence each time, and the
AO bake, which follows face order, with them.
maplib.order_facessorts every mesh's faces by their centre before export. - Transparency is read from somewhere else. 4.1 exported
BLENDexactly when a material'sblend_methodwasBLEND; from 4.2 the exporter looks only at the shader's Alpha input. The generators' glass and water ask to blend and leave Alpha at 1 (transmission does the see-through), so on 5.3 they came out solid, and Bank's smoked glass, Alpha 0.55 but never asked to blend, came out see-through.maplib._alpha_as_authoredwrites 4.1's rule back into the file after export. Material.shadow_methodis gone (EEVEE shadows every surface since 4.2). Assault, Facility and Junkflea set it, and failed on the first line that did; they now only set it where it exists.
bake_bounce.py asks Cycles for the GPU, which stops with "out of GPU memory"
rather than falling back when something else is using the card;
HASSAULT_BOUNCE_DEVICE=CPU bakes on the processor instead.
Checked on Dust II: 5.3's GLB has the same 560 nodes, the same materials and the
same vertices as 4.1's; a few faces split along the other diagonal (9 triangles
of a palm trunk, 6 of 6,890 on the jars); AO within 0.02 on 95% of vertices; and
bake_collision.py bakes the identical 1,227 brushes from it. Then on the
other nine: each rebuilt on 5.3 has the same nodes, materials (transparency
included), vertex and index counts as what shipped, and bakes the identical
brushes (Aim 32, Assault 606, Bank 925, Facility 412, Inferno 752, Junkflea 371,
Mirage 719, Nuke 849, Office 796).
Two props were moved in that rebuild because probe_eye_inside.py found an eye
inside them. Facility's East-lab duct ran through a standable spot under it;
add_ceiling_mep(..., duct_side=-1.0) puts it on the other side of the span.
Office's meeting-room screens hung on walls the defuse rebuild removed, so the
screens and their trays are gone, and the baffles are raised to 3.76 m.
Mirage, Inferno and Nuke reported an eye inside a NonCol mesh too, on the GLBs that
shipped before the rebuild as well. Welding each mesh's seams and probing it box
by box found five pieces on the first two, and the fixes cost Mirage 41
reachable cells and Inferno 115:
- Mirage, Window room back wall (
Mid_Nest_Stone): it stands on the room's floor, so a body walked into it. Now solid (Mid_Nest_Back_Wall). - Mirage, market awning (
SiteB_Arch_Wood): at 2.55 m, a standing eye on the service counter was inside it. Raised to 3.0 m. - Mirage, palace column plinths (
Palace_ArchDetail_Stone): a standing eye below the raised floor's edge is at plinth height. Now solid (Palace_Column_Plinths). - Inferno, church buttresses (
Church_Graveyard_Stone): they straddled the y = 60.45 layout cut, which stretched them 4 m across the floor it opens. Now short of the cut and solid (Church_Buttresses). - Inferno, graveyard chapel monument: 3.2 by 2.8 by 4.4 m, and bodies walked
through it. Now solid (
Graveyard_Chapel_Monument).
Both maps were rebaked (Mirage 721 brushes, Inferno 766) with their shipped
placements, and their bot graphs rebuilt (hassault_nav_build.py).
Nuke's B-pit console was non-colliding desk and all, so a body walked into it
and an eye ended up inside the monitors (SiteB_Pit_Console_Bezels_NonCol, 24
positions). add_control_station(..., solid=True) makes its desk collide
(852 brushes); Facility's consoles keep the default. Every map now reads 0.
Rotation footage. tools/hassault_rotation_demo.py <map> <out.hademo> writes
a recording of one player running the map's rotation — site A to site B over the
server's own grid (hassault_route_times.dijkstra), or T spawn to CT spawn on a
map without sites — at MOVE_SPEED, looking a little way down the path with the
turn eased. The route ends on the site's floor, not on its cover, stops ten cubes
short to look at it, and is pushed off the walls it would otherwise scrape
(keep_off_walls). hassault-native --replay=<file> --export then writes it as
a 60 fps MP4. On a laptop whose discrete GPU is busy, --adapter="<integrated GPU>" exports on the other one: a ten-second rotation takes about fourteen.
Resizing a map: cut it, do not scale it. A generator's coordinates are metres, and
every detail hangs off a wall by a few centimetres (a rug, a frieze, a sconce, a
plinth), so scaling pulls them off the wall they were built against. Dust II,
Mirage, Inferno, Nuke and Office are instead cut along a few lines in open ground and the halves are spread
apart: the shared machinery is tools/blender/cutlayout.py, and each map's
LAYOUT_CUTS (in dust2_layout.py, mirage_layout.py, inferno_layout.py,
nuke_layout.py, office_layout.py) lists its cuts as
(at, gap) in metres per axis. A generator wraps its own primitives with a
Warper made from them. A piece wholly on one side of a cut only moves; one that crosses
it (a long wall, the ground, a ramp) grows by the gap. So walls stay joined and
everything mounted on them goes with them. Composite helpers (add_crate_stack,
add_palm_tree, the arches, lanterns and sconces) move as one by their anchor
point, and add_crenellations re-lays its teeth between the moved ends.
To choose cuts, run the generator with HASSAULT_<MAP>_SCAN=<file> set (DUST2,
MIRAGE, INFERNO, NUKE, OFFICE): it writes every primitive's footprint, and a candidate line is clean when
no small object (under about 7 m) crosses it. Stairs, composites and anything that
is laid out from a list (roof beams, planters, a row of columns) are small whatever
their size: a cut through one either splits it or stretches it. First run a new
map's generator with empty cuts, which must reproduce its shipped GLB byte for
byte; that proves the wrapping changed nothing. A hand-placed coordinate in cubes (a spawn, an item,
a bomb site, a ladder, a bot's cover node, the MAP_CONFIGS rows in world3d.ts
and world3d.rs) moves with the same cuts through the map's warp_cubes, once, on
the committed unstretched files. With the cuts in place, each map's
walls enclose 74 x 78 m rather than 62 x 62 m, about 1.55 times the area, and
still fit the 256-cell grid with room to spare. Mirage, which was one open square
with a few buildings, kept its several routes to each site and gained length: T's
walk to A went from 5.7 s to 7.3 s and to B from 6.1 s to 7.7 s. Inferno is
crowded (Banana, the apartments, the pit, the casks), so only a handful of lines
are clean; the cuts go through Banana's middle and the middle wall, where only
long walls cross, and T's walk went from 7.0 s to 8.7 s to A and 5.7 s to 7.5 s
to B, with a fourth route to each site. The mid hump (Mid_TRamp_Up) is a wedge
and lengthens with the cut at y = 15, so its slope eases rather than breaks.
After changing cuts run all four steps above, then probe_eye_inside.py.
Nuke needed more than cuts. It was one reactor hall in a bare 62 m yard, and its B silo was modelled directly under hall A, sealed under the ground, because the server's heightfield keeps one floor per column (A's floor would have been B's ceiling). A cut cannot pull apart two things stacked in one column, so the generator was changed first and cut second:
- B is a reactor room of its own, a building against the hall's west wall
whose floor is the pit, 4.5 m down, and whose roof is 5 m up, so no column has
two floors and nobody can stand on top. The ground slab is laid in pieces round
the holes it needs. T come down the ramp room from the south yard, or drop
about 2 m onto the ramp through a breach in its west wall (one way). CT come
down the stairs, which climb north up B's east wall to its north door, or
through the vent, an opening at the foot of A's west wall, in its south-west
corner, that drops 4.5 m straight into B. One way: nothing climbs back. It
was first a hatch in A's floor over a shaft and a crawl, and a bot that fell in
never left, because a pocket whose only exit points away from where a bot is
going is a trap for something that only steers. Its lintel is 2.4 m: lower, and
the bake's conservative sampling rounds the lip in front of it shut (under
MIN_OPENING), so A's floor no longer reached it. - A Lobby against the hall's south wall makes T walk round to A's south door from the Lobby's west door (beside the ramp) or its open east end, and an east door ("Squeaky") from the garage lane is T's second way into A.
- The cuts (x at 6, 32.5, 45.8 and 51.1, y at 18.5, 21 and 32.2) make 74 x 76 m and put the length on the attackers' side: the y gaps are across the south yard, which also eases the ramp, and across the hall and B between the vent and B's stairs. Nothing is cut north of A, because every line there also lengthens CT's walk to B.
T's walk went from 3.9 s to 8.0 s to A, with three routes, and from 4.3 s to
6.8 s to B, with two. CT are 2.3 s from A and 4.7 s from B. Those are pinned in
test_hassault_routes.py, along with the three doorways, the stairs, and the
vent being a drop that does not climb back.
Office was not a defuse map yet. It was one open floor plate: bomb site B stood in the cubicles beside T's spawn (T reached it in 0.7 s), the boardroom that was A had a 1 m slot at one corner and a glass door set in a solid wall, and each side had one way to A. It was redesigned first and cut second:
- A is the boardroom, with three ways in: T's north corridor (the gap by the north glass), double doors from the mid lane in its east wall, and CT's door in its south wall. B is the server room: its east and north sides were glass, which hosted play treats as open (20 m of site with no corner, and the whole site in view of CT's spawn), so they are walls now, with T's south door off the south corridor, T's mid door off the mid, and CT's door at the north wall's west end. The site is the strip between the racks and that wall: a site in one of the rack aisles funnelled every route into one body-wide aisle.
- CT spawn by the elevators, between the two sites; T up the east stairwell, in the aisle along the east wall. The elevator core is 5.2 m long, not 9: the longer core left a 1.5 m slot to each wall beside it, and a CT bot steering for the mid wedged in one for a minute.
- A corridor along each glass façade, a wall across the north and south bands with a door in its middle, so the façade is a route of its own and either side can rotate into the mid halfway along.
- The cuts (x at 25.2 and 38.5, y at 11.2 and 37.2) make 66 x 62 m. Both x cuts are east of CT's spawn and both sites, so they lengthen only T's walk; the y cut at 11.2 falls between two rows of racks and opens a cross aisle through the server room.
T now take 8.1 s to A and 7.9 s to B, with three routes to each; CT take 3.1 s
to A and 1.8 s to B. The clutter is an office mid-move (archive boxes, bins,
planters, and ceiling tiles fallen from the grid as rubble), kept off the
corridors, the mouths of the doors and the duel line across the mid. All of it,
and the eight doorways, is pinned in test_hassault_routes.py.
Bank had its sides the wrong way round, and is not cut. The attackers spawned
in the rear offices beside the vault (A, 1.1 s away) and the defenders out on the
street, and the front door was the only way into the building. Now T come off
the street and CT hold the rear offices; B moved from the banking hall to the
north-west offices, so the hall is the mid both sides cross. The facade has a
side door at each end, set between two columns (a column stands 15 cm off the
wall, so a door behind one is shut), and the vault has a second way in: a
breach blown through its west wall from the rear corridor, past the
kitchenette. The hall's wainscot used to run across its three north doors, a
1.45 m rail every way north had to be jumped; it stops at every doorway now. The
SWAT truck was parked on the sidewalk 2 m off the facade, and with a column it
made a pocket a bot steered into and never left; it is out in the street, and
the two sidewalk planters that stood across the side doors are along the curb. T
take 6.7 s to A (two routes) and 6.7 s to B (three); CT take 2.5 s and 3.0 s.
That is the band of Nuke, so Bank keeps its
56 m square: its generator places boxes by two corners rather than a centre and
a size, which the Warper does not wrap, and its monumental facade and
mezzanines would only stretch. It gets no rule-placed clutter either: the hall,
the offices and the vault are furnished piece by piece already.
Where each defuse map stands. Measured with
tools/hassault_route_times.py on 2026-10-22: the fastest walk from each side's
spawns to each site, with the number of distinct routes in brackets. Every
defuse map is now rebuilt; the P10 map list is closed.
| Map | T to A | T to B | CT to A | CT to B | State |
|---|---|---|---|---|---|
hd_dust2 | 9.0 s (4) | 8.7 s (3) | 2.3 s | 2.6 s | Done: cut, dressed, photographed. |
hd_mirage | 7.4 s (3) | 7.7 s (3) | 2.1 s | 2.4 s | Done. |
hd_inferno | 8.7 s (4) | 7.5 s (3) | 3.3 s | 2.1 s | Done. |
hd_nuke | 8.0 s (3) | 6.8 s (2) | 2.3 s | 4.7 s | Done. |
hd_office | 8.2 s (3) | 7.9 s (3) | 3.1 s | 1.8 s | Done. |
hd_bank | 6.6 s (2) | 6.7 s (3) | 2.8 s | 3.0 s | Done, not cut (see above). |
hd_assault | 6.4 s (4) | 6.7 s (3) | 1.6 s | 1.6 s | Done, not cut (below). |
Assault: both sites to the back of the warehouse. Its spawn sets were
labelled the wrong way round, and once swapped T still reached B, out on the
warehouse floor by the forklift, in 3.9 s through Bay 1. Rather than cut a
56 m square whose generator places boxes by corner (as Bank's does), the sites
moved: A to the ground under the hostage office, B to the workshop in the
north-west corner, and CT spawn between them at the back wall. A door in the
warehouse's west wall (y 49.5 to 52 m) gives T a third way into B, up the alley
from the street, so B is reached through Bay 1, along the west catwalk, or
through the alley door; A through Bay 2's street door, the east door off the
rail yard, or the fire escape into the office. The second pallet rack now
fronts B. Its materials carry the assault_ infix, so the rules that were
waiting in glb-surfaces.json match. No rule-placed clutter: like Bank, it is
furnished piece by piece. test_hassault_routes.py pins the walk, the three
routes each way and the four doors; the eye probe finds nothing an eye fits in.
Baked ambient occlusion. maplib.bake_vertex_ao darkens corners and
contact edges into each map's GLB: a Cycles AO bake (1.5 m, 48 samples) into a
grey colour attribute, remapped so the darkest corner is 0.45, exported as
COLOR_0. It is content, not a setting: every client draws the same darkening
at every quality level, so it changes nobody's view of anybody, and it costs
nothing at runtime. Three things about it are not obvious:
- Per vertex needs vertices. A wall is often one quad, and AO interpolated
across a 30 m floor from its four corners is a smear, not a shadow. So the
bake first halves every edge longer than 2 m on surfaces that take it, and
COLOR_0is repacked from Blender's three floats to four normalised bytes (_bytes_for_colors). The nine GLBs grew from 34.6 MB to 51.4 MB, 1.49 times; Facility, the least detailed, most (2.1 times), Inferno least (1.16). - The exporter writes a vertex colour only if a material uses it (4.1, and
export_vertex_color="MATERIAL"on 5.3). So each receiving material's Base Color becomes Mix(Multiply, factor, Color Attribute "AO"), the one arrangement the exporter reads, which keeps the factor the clients see. Glass, water and anything self-lit take none. - Collision is baked from the mesh before the splits.
bake_collision.pycounts faces along vertical rays, and that count is sensitive to how a floor is triangulated: baked from the split mesh, Inferno moved 45 cells' floors by up to four cubes. Soexport_map_glbalso writes the unsplit map totools/blender/.collision/(not committed) and the bake reads that. Regenerate before re-baking.
Native carries AO as its own vertex attribute (Vertex::ao) rather than
folding it into the colour, because layers 8, 10 and 11 mix the colour with
a photograph, which would wash it out; shader.wgsl multiplies it in after the
mix, as three multiplies a vertex colour after its map, and before shade(),
so Low gets it too. The browser keeps COLOR_0 through the static-batch merge.
browser_parity.rs and map-geometry.test.ts pin all of that: the shader
lines, that neither the skin shader nor the shared lighting sees it, that no
setting mentions it, and that every opaque surface of every map carries it.
Baked bounce light. tools/blender/bake_bounce.py runs after fit (fit
moves lights) and bakes each map's indirect diffuse light into COLOR_1: a
Cycles DIFFUSE bake, indirect only, per vertex, under the rig the server serves
(atmosphere.resolve and atmosphere.lights): the sun as a sun, the
hemisphere as a world whose halves have the sky and ground radiance, each lamp as
a point light of 4π × candela. The fill is left out, because it stands in for
bounce at higher quality levels. Calibrated against Cycles, so the value is in the
units of shade()'s irradiance sum: a client adds it before albedo / π. It is
stored as normalised bytes on a square-root curve, bounce = 4 · c², and the
GLB says so in asset.extras.hassaultBounce. The GLB is patched, not
re-exported, so COLOR_0 stays byte-identical (the script refuses to write
otherwise). Like AO it is content at every quality level, so it changes nobody's
view.
How the clients draw it. Both read asset.extras.hassaultBounce rather than
a constant, refuse an encoding they do not know (the bytes are then dropped, not
guessed at), and decode scale · c² once at load, so the shader only adds:
- Native (
world3d.rsread_bounce): the decoded value rides in the worldVertexasFloat16x4(52 → 60 bytes).fs_mainsets the privatebounce_irradiance, whichshade()adds to its irradiance sum andshade_physicaladds beside the hemisphere as indirect diffuse (× contribution / π). - Browser (
bounce-light.ts):color_1becomes a floathdBounceattribute, carried through the static-batch merge (and welded on). The surface-breakup patch adds it to three'sirradianceright afterlights_fragment_maps, which is three's own light-map slot, on every GLB material, glass and Low's Lambert twins included.
Only the map's own vertices carry it. Operators, the view model and props have
zero bounce (natively their VertexOut is zero-initialised and the skin and prop
shaders never set it), so it never lights a character. A map without COLOR_1
simply has none, which is the old hemisphere-only look. Native Low draws
surfaces unlit, so it has nothing to add bounce to.
The fill light is kept. The bake leaves the fill out because it is a stand-in
for bounce; keeping it on top of the real bounce counts that light twice where
the fill reaches. On Dust II's site A framing the bounce adds about 2.5 of 255
in mean luma, landing on the shaded walls, awnings and crate sides rather than
the sunlit floor. Dropping the fill on maps that have bounce is a look call left
for a playtest. browser_parity.rs
(baked_bounce_light_is_content_on_the_world_in_both_clients_alike) pins the
decode, where it is added, that only the world sets it, and that no setting
names it. PREVIEW_NO_BOUNCE=1 renders dust2_preview without it, for a
before-and-after from one build.
Checked and closed: Bank's street spawn at (36, 8) m was written up as standing
inside the bus shelter. Rendered from the GLB at eye height, it stands 0.4 m in
front of the shelter's open north side, facing the bank, with the canopy behind
it. Entity yaw is degrees from +x towards +y (0 = east, 90 = north), and the
comment in physics.spawn_at (Python and TypeScript) now says so. It used to
say "clockwise from north", which is how Bank's original street spawns came to
face east.
Bots and waypoints
A bot heads for a point (its objective, a sound, a roam target) and probes a
step ahead with physics.can_stand. In the open that is all it needs; behind a
wall it slides along the wall, and on Office a bot sent to the north gap, the
back of A or B's south door from the attackers' end got no closer than 59 to 92
cubes. Each defuse map now has a waypoint graph, backend/modules/hassault/nav/<map>.json:
-
Built, then editable.
tools/hassault_nav_build.py hd_officetakes thewalking route between every pair of spawns, sites and cover nodes over the
cube grid and string-pulls it (from each waypoint, the furthest point still in
a straight walkable line becomes the next), which puts nodes at corners and in
doorways; adds a node every 15 cubes over the rest of the floor; and links
every pair within 30 cubes that a body can walk. 180 to 270 nodes a map.
-
Directed links.
nav.walkablesamples the segment every 0.45 cube: abody must fit on the floor under each sample, and no sample may be more than
a step above the last. A drop is allowed, a climb is not, so A to B and B to A
can differ: Nuke's vent is one-way in the graph as it is in the game.
-
Used only when needed. Every half second the bot asks whether it can walk
straight to where it is going. If so it does, exactly as before; if not, it
plans an A* route (again every 3 s, or when the destination moves) and heads
for the next waypoint, skipping ahead whenever it can already walk to the one
after.
_steerstill does the local avoiding. A goal no body fits at (asite's centre under its table, Dust II's goose ledge, which only a jump
reaches) is approached through the nearest node there is a route to.
-
Outside
maps/on purpose. The generators and the fit tool rewrite mapJSON; a regenerated map keeps its graph. Rebuild the graph after a layout
change;
test_hassault_nav.pyfails if a link stops being walkable or a spawnstops reaching a site or a cover node.
What it does to a match: with it, the same Office bot reaches each of those
three places in about 9 s. In a 300 s defuse soak bots spend their time on
their objectives rather than wandering (Office's floor coverage fell from 22% to
15% while visits to B's CT door went from 0 to 131); Bank's vault breach went
from 53 to 677 visits. A soak ticks about 40% slower in total, 8 bots for 300 s
in 8 s against 6, which is A* on re-plans and the straight-line checks.
The aim range, modelled around its rails
hd_aim was the last brush map. tools/blender/generate_aim.py builds it as an
indoor range (block walls, concrete lane dividers, raised steel booths, a floor
rail under every target post, a distance line and a board at each post, overhead
baffles, high-bay lights and a rubber backstop) in metres equal to the old
cubes divided by three. Since a cube is the same third of a metre on every map,
every drill shooter, rail, spawn and item kept its coordinates: nothing in
drills was converted. The dividers stop short of both end walls, as the
brushes did, so a deathmatch still crosses between lanes. Its materials use the
aim_ infix and borrow the industrial photo kinds (slab and cast concrete,
tread plate, painted metal). Both clients load it like any modelled map, so the
browser's brush-only AO (geometry.ts), which native never had, no longer
decides how one map looks in two clients.
Props: placed by where clutter gathers, not typed in. tools/blender/props.py
dresses a map (Dust II, Mirage, Inferno, Nuke and Office; emit takes each map's own material keys) after everything else is built, so it must be the last builder (and
the lights must come before it). It plans on a quarter-metre grid of the finished
map in final metres: what is solid (everything built that a body could meet below
2.2 m), what is banned, and how far each cell is from a wall. It then walks the
cells next to walls in a seeded random order and lays a vignette in a frame
aligned to the wall: a row of crates (sometimes one stacked), a barrel cluster, a
sack pile or a row of jars, a taller stack where two walls meet, and rubble. A
few crates stand as cover in the open lanes (lane_budget), and a bazaar's
stalls go on open floor with room to walk round them. A vignette is kept only if
every part fits, no part sits in another, and the floor out from the wall is
still mostly open, so clutter does not close a passage.
Banned: spawns, bomb sites, anything named like a way through (arch, door,
portal, exit, window, stairs, ramp, any wedge: 2 m clear), the pit (any Pit_
floor: props stand at ground level, so Nuke's whole sunken B is banned), and
wall-mounted lights (2.5 m clear). The last matters: a crate beside a sconce is a
step up to it, a body on top has an eye in the cage, and probe_eye_inside.py
fails the map. The zones, their density and what they favour live in _ZONES in
the generator, in the authored frame so they stretch with the cuts, and
_DRESS_SEED fixes the result: a regenerated GLB is identical. Solid props are
named without NonCol, so the bake treats them as cover; rubble is under a
quarter metre. Each group (crates, barrels, jars, sacks, rubble) is one merged
node, so the whole layer costs a handful of nodes, and about 57k triangles on Dust
II after the bevel pass; thin rings (hoops, jar necks) are what the pass makes
dear, so keep their segment counts low. backend/tests/test_hassault_props.py
tests the planner without Blender: nothing in a wall or a ban, nothing
overlapping, rubble below an eye, no passage closed, deterministic for a seed.
Photographed surfaces. Dust II's surfaces carry real colour, normal and roughness
maps from ambientCG (CC0; apps/web/public/maps/textures/README.md lists each set
and the licence). They are twenty-five kinds in glb-surfaces.json (photoKinds),
matched only by the dust2_, mirage_, inferno_, nuke_, office_, bank_,
assault_, facility_ and junkflea_ infixes in each map's own
material names, so the names the other maps share (mat_wood_crate,
mat_sandstone_ochre) stay as they were. To give another map photographed
surfaces, give its materials an infix of their own and add that infix to the
rules of the kinds it wants; do not widen the bare names. A material left out
(Mirage's wrought iron, olive van metal, palm fronds; Inferno's terracotta,
bronze, cypress leaves and water) keeps the surface it had.
Nuke added five kinds for an industrial plant rather than a desert town:
cast_concrete (its walls), slab_concrete (the ground and floors),
corrugated (the containers), painted_metal (steel, pipes, the reactor's hull
and the drums) and tread_plate (grating), and reuses souk_crate and burlap
for its crates and sandbags. Its hazard paint keeps the generated stripes.
Six more are for indoors and a warehouse yard: yard_asphalt, carpet_tile,
ceramic_tile, polished_marble, red_brick and wall_plaster, named so they
cannot be mistaken for the generated asphalt, carpet, marble, brick and
plaster they stand in for. Their rules already name Office's, Bank's and
Assault's infixed materials, and Assault reuses Nuke's concrete, corrugated,
painted metal and tread plate; Office uses carpet tile, polished marble (its
floor), ceramic tile (the server room's raised floor) and wall plaster.
Each kind needs an entry in maplib.SOFTEN_BY_KIND too, which every photo kind
already has.
G7 added five more for the biggest surfaces still on a generated tile:
ceiling_tile (Office's and Assault's ceilings), brushed_steel (stainless,
vault steel, ducts), limestone_block (Bank's facade), polished_wood (the
mahogany) and wet_mud (Junk Flea's ground). Facility's and Junk Flea's
generator materials took facility_ and junkflea_ infixes, so both maps went
from none of their area photographed to most of it; Office, Assault and Bank
gained rules for their roofs, steel and concrete. Each new rule names a material
whose old kind softened the same way, so no map changed shape. Every kind also
ships 1024 px variants (<kind>_c_1k.webp …), not loaded yet: they are for the
High quality level, and swapping the suffix is all a client needs.
tools/hassault_process_textures.py turns a downloaded set into three 512 px WebP
files. The albedo is normalised: per channel, in linear light, to the same mean
as the generated tiles (detailMean), so the shader's * 1.5 brings a surface back
to the colour the map authored and the photograph only adds variation. It does not
repaint the map. photoNormalScale sets how hard each kind's relief bites
(stucco at 0.5 to 0.6, wood and rust at 1.5); the browser sets it as the material's
normalScale and the native client bakes it into its layers.
The browser (photo-surfaces.ts) keeps the generated tile on a material at build
time and swaps in the images when they arrive, with roughness taken from the map
(roughness = 1). It never does this on the Low tier, which draws Lambert and has
no use for either map, so Low neither fetches nor shows them. The native client has
no asset directory, so it embeds the files and appends them to the one
Rgba8UnormSrgb texture array: twenty albedo layers, then twenty detail layers
holding the normal's x and y and the roughness. The array decodes sRGB on
sampling, so those values are stored encoded; sampling gives back exactly what
went in, and the sRGB-space mip chain averages the data rather than its encoding.
That is why nothing about the bind group or the pipelines changed. Layers are only
ever appended, but shader.wgsl hardcodes three numbers that follow
PHOTO_COUNT (textures3d.rs): the end of the photo range (18 + PHOTO_COUNT),
the photo detail offset (PHOTO_COUNT) and the generated detail base
(18 + 2 * PHOTO_COUNT). A new kind changes all three; the generated kinds'
8, 10 and 11 never move. The shader
builds the tangent frame from the screen-space derivatives of position and the
planar UV (taken at the top of fs_main, in uniform control flow) and flips the
normal's green, because a texture's row 0 is its top here and the maps are
OpenGL convention.
To look at the result without the game, cargo run --release --example dust2_preview -- out.png x y z yaw pitch (in apps/native-fps) renders the real
GLB with the real world shader from any camera, in cubes and degrees. Its light is
the default cube sun, not the map's atmosphere, so judge texture and relief by it,
not brightness. maplib.py's SOFTEN_BY_KIND gives each photo kind the edge
rounding of the generated kind it replaced; a new kind that is missing there
silently rounds like the default, and a wall loses its softness.
Routes. Stretching Dust II made the walls between its lanes a problem as well as a
feature: Mid's west wall and Long A's west wall were each unbroken for 40 to 50 m,
and B's east wall had no way through (the "B Double Doors" were closed boxes), so
B was reached only through the tunnels. CT took 16.6 s to walk to B and T had one
route to each site. Three openings fix it, cut with wall_with_openings in the
generator (a wall of pieces with a sill and a lintel at each opening, so it is a
hole in the collision and not a painted one):
- the B Doors, from the CT street into B, which took CT to B from 16.6 s to 2.6 s;
- the Long Doors, from lower Mid into Long A, a second way for T to A and a rotation between the two;
- the Lower Dark door, from Mid into the alley beside the tunnels, a second way for T to B that does not go over the catwalk.
And one vertical layer: the Long ledge, a 1.2 m terrace against Long A's west
wall, up a ramp from the north, with a sniper window in the wall above it. The
window's sill is 2.6 m, which a jump from the ledge does not clear, so it is a
sightline and not a way through. The arch helper takes a yaw for a gate in a
wall that runs north to south. Five pickups went in on the new routes, in the JSON
and in both client tables (ids 11 to 15), so the item count is 15, not 10.
tools/hassault_route_times.py <map> measures the walk on the baked grid with the
playability lint's own rules for what a body can stand in and climb (a jump costs
three cubes of running, and a drop off a ledge lands two cells out, as the lint's
own fill does, so a vent or a breach counts as a way down): seconds from each
team's spawns to each site, and how many
different routes there are, the shortest and then the shortest that keeps 14
cubes from the ones already found, within 1.6 times its length.
backend/tests/test_hassault_routes.py pins the result: every team reaches every
site, CT reaches B in under 6 s, T has two routes or more to each site, and each
doorway is walkable. Dust II now: T takes about 9 s to A or B with three routes to
each; CT is 2.3 s from A and 2.6 s from B. The 105 s round clock is unchanged;
whether it wants lengthening is a playtest question, not a number.
tools/hassault_bot_soak.py <map> [seconds] [bots] [mode] lets bots play with no
one watching and reports how much floor they stood on and how many visits each of
the map's cover nodes got. Bots steer straight at a point and probe round what
is in the way, and since 2026-10-22 follow a waypoint graph when the straight
line is not walkable (see Bots and waypoints), so a
cover node belongs at a place a body can walk to. On the original Dust II they never reached B at all; they do
now. A bot sitting still for 13 to 26 s is holding cover, not stuck: Mirage and
Inferno do the same. So is a bot sitting for minutes after the match ends
(phase is over): the soak keeps ticking. On Nuke every cover node gets
visits, B's included (its node is at the ramp's foot, straight down the ramp).
What still costs them time is walls across their straight line: T bots slide
along the Lobby's south wall to reach A. Clutter is kept off the Lobby and its
south wall for that reason; the waypoint graphs are the fix. A pocket with
one way out is worse than a wall: see the vent, above.
To look at a map without running the game,
tools/blender/render_map_views.py -- hd_dust2 [out_dir] [glb] renders a frame
from the first spawn of each team at eye height. It has no detail textures and a
different light rig, so use it for judging shape, not finish.
What export does to every map's shape
export_map_glb first rings the map with invisible walls, then runs five passes
over the finished scene after scaling it to cubes. All of it is generic on
purpose: it fixes every map, and every future map, without touching a generator.
-
add_boundary_wallsputs aMap_Bounds_<side>_ColOnlywall on each side of the map's footprint, 3 m taller than its highest surface. It is the safety floor's sides. Assault's south street ran to the edge of the model at both ends, and so did its north-east yard, with nothing there. Offline, where Rapier walks the GLB itself, a body walked off the map. Hosted matches never showed it, because the baked grid ends in rock.test_glb_colliders.rsonly caught it once a rounded corner stopped one of its 16 rays clipping a wall's exact tip. In the baked grid the walls are columns whose floor is the wall top. The bake leaves them out by that exact prefix, because the grid already ends in rock past the map, and on the roofed Office their corners baked as standable cells nobody could reach. The prefix is unique because Junk Flea's own perimeter walls areBoundary_Wall_*. A looser match dropped them from the server's grid. -
clean_meshesdrops zero-area slivers and re-winds any closed mesh that faces inward. Both clients cull back faces and derive normals from winding, so an inside-out mesh is drawn as its own interior, and the bake, which counts solid by face orientation, gets it wrong too. The bank's 460 gold ingots and Junk Flea's two bridge ramps shipped that way. Open sheets are left alone, because "outward" is a guess there. -
weather_wallsslices big vertical stone and plaster faces into a 1.25 m grid and pushes the interior vertices in and out by up to 3 cm of world-space noise: hand-built walls instead of perfect planes. 3 cm is the ceiling becausebake_collision.pysamples a quarter-cube in from each cell edge, so the grid cannot move. Edge vertices never move, and nothing moves within one and a half cells of any other surface (trim, decor, the floor), so the wall never weaves through what is mounted on or beside it. Office drywall and floors are excluded. -
soften_edgesrounds every edge sharper than 50° with a two-segment bevel. The radius comes from the material's kind inglb-surfaces.json: 15 cm for masonry, 12 cm for plaster, 4 cm for wood, 2.5 cm for steel, and none for glass or emissive surfaces. It is capped at a fraction of each island's thinnest side, not the object's: Dust II's 5 cm crate lids share one mesh with the crates, and a crate's rounding folded them inside out. A bevel that leaves an island inside out is thrown away. Edges where a face carries on into another surface (floor slabs laid edge to edge, a wall standing on the ground) are seams and stay sharp, otherwise every joint would become a gutter. Above 45° on purpose: an eight-sided post's facets meet at 45°, and rounding them collapses the bevels into each other. A bevel that opens a mesh is thrown away. -
separate_coplanarfinds faces of different objects and materials lying in one plane, facing the same way and overlapping. The depth buffer cannot order them, so they flicker. Every map shipped some, from Dust II's canopies drawn twice to Nuke's hazard stripes inside the door reveals. Within one plane, an object goes one 7 mm layer above the highest larger object it actually overlaps, so a mosaic field on a brass border on a floor needs three heights. Same-material overlaps are left alone, since they shade identically. Three things in it were each learned from a wrong first version:- Layers are per plane. An object-wide depth inherited chains across planes and lifted Assault's curbs 8 cm.
- The step is 7 mm, not 1 cm. The generators stack their own decals in 1 cm steps, so a 1 cm lift put a crosswalk stripe exactly on the manhole cover above it.
- It repeats until nothing fights (at most six passes), since any lift can still land on a plane that was already taken. Decals on a busy floor end up at most about 4 cm proud.
-
mark_sharp_edgeskeeps every edge above 35° hard, and keeps the line where a rounding strip meets its flat face hard. Otherwise a flat face shares the strip's vertices, and both clients' recomputed normals shade it as a slow gradient.
HASSAULT_MAP_SOFTEN=0 skips passes 2 and 3, for comparing against the map as
authored. Faces are triangulated with Blender's loop_triangles, never as a fan:
rounding and weathering leave concave n-gons, and a fan of those covers the
wrong area. The cost is triangles: the nine GLBs went from 13.8 MB to 26 MB in total
(Dust II 0.7 to 2.6 MB, the Bank 6.0 to 9.0 MB), and a player only ever loads
one. The native client compiles them into its binary. Inside the boundary, the bake moved at most four cells per map
between solid and open. No spawn, item or site moved on any map.
Lights and atmosphere come from the generator. A GLB carries geometry, not
lighting. maplib.add_light records a point light, and maplib.lights_from_emitters
puts one under every fixture whose material matches (troffers, chandeliers,
floodlights), merging fixtures closer than a few metres. maplib.set_atmosphere
picks a named sky from maplib.ATMOSPHERES (desert_noon, golden_hour,
overcast, interior_cool and so on) with per-map overrides. export_map_glb
writes both into the JSON, replacing its light entities and atmosphere block,
so a re-run is idempotent and nothing else in the JSON moves.
Base colours are linearised on export. glTF's base colour is linear, and every
generator picked its colours by eye as sRGB. Exported as-is, each surface was about
twice as bright as intended and lost most of its saturation, so Dust II's
sandstone drew as pale grey. export_map_glb converts each Principled base colour
once. The exact curve would turn a 0.2 asphalt into 0.033, which draws black under
a rig with no bounce light, so maplib.DARK_FLOOR keeps any channel at no less
than 30% of its authored value.
Keep an eye on GLB size. maplib.add_boxes builds many boxes as one object.
Use it for trim, beams and clutter: at these sizes a GLB's JSON node table, not
its vertices, is what grows. No revision below grew its GLB by more than 44%.
What each map's revision changed:
| Map | Sky | Layout | Dressing and lights |
|---|---|---|---|
hd_dust2 | desert_noon | Mid doors are a choke. A wall now closes the 9 m of open street beside them. A ramp lets you walk onto Catwalk from mid. Pit exit and Suicide are slopes instead of 1.4 m and 1.2 m steps. Adds a cart in Long A, a planter on the CT side of Short and a well in B. | Plinths, vigas, awnings, banners, cables and rubble; 74 louvred blue shutters with sills and flower boxes, a glazed tile frieze on every wall, and crimson, saffron and teal cloth on the mid lines (build_flourish). Lanterns and sconces light the tunnels and doorways (17 lights). |
hd_mirage | desert_noon, lower western sun | Palace gets stairs at both ends; its 2.8 m floor had no way up. Walking onto the Window Room from the connector is now possible. The B Apartments get outside stairs and a ground-floor wall with a door. Two houses in mid and a wall short of B break the spawn-to-spawn and T-to-B sightlines. | Plinths, mosaic bands, vigas, awnings, planters and five lanterns. |
hd_inferno | golden_hour | A house in the east street splits the approach to A into two alleys. The pit exit and the T ramp are slopes, and mid gets a well. | Shutters, coping, washing across Banana, awnings. Lanterns now light, with sconces down Banana and under the apartments. |
hd_nuke | overcast | Adds jersey barriers and a container stack in the yard, and crates inside A. Later rebuilt: B moved out from under A into a sunken reactor room with a ramp, stairs and a vent from A, a Lobby and an east door added, and cut to 74 x 76 m (see above). | Door striping, hall pipes, six yard floodlights, wall packs, and the hall's, Lobby's, ramp's and B's troffers and B's reactor as lights. Rule-placed crates, drums and sandbags, and photographed concrete and steel. |
hd_office | interior_cool | Two meeting rooms, each with two doors, fill the open band between the core and the cubicles. Later rebuilt as a defuse map: A the boardroom, B the server room, CT at the elevators, T in the east aisle, a corridor along each façade, and cut to 66 x 62 m (see above). | Baseboards, planters, every troffer, and the server LEDs as lights. Rule-placed boxes, bins and planters, and photographed carpet, marble, tile and plaster. |
hd_bank | coastal_morning, warm interior | Unchanged at first: it already had the most structure of any map. Later the sides were swapped (T on the street), B moved to the north-west offices, and the facade's side doors and the vault breach added (see above). | Chandeliers, sconces and troffers as lights. Photographed marble, brick, carpet, plaster and asphalt. |
hd_facility | interior_cool, darker | Broken partition walls turn the two lab corridors, which had only ever been rows of lights, into real ones. | Pit-rim striping and wall pipes. Troffers, sirens and coolant glow as lights. |
hd_junkflea | industrial_dusk | Two-high scrap-bale walls and tyre stacks in the flanks of both spawn yards. | Floodlight towers and strobes as lights. |
hd_assault | overcast | A second pallet-rack aisle between B and the CT spawn. The regenerated GLB ends at the map's real edge; the committed one had geometry at the origin that left a reachable strip outside the west and south walls. | High-bays, office troffers, wall packs and the street light as lights. |
No spawn, item or site moved in any of these revisions, so the offline tables did not change.
The map designer
Everything above describes a map pipeline with no way to author a map. Making
hd_atrium meant typing rect coordinates into a text editor and running the
playability tests to find out that its gallery ring had been cut into four pieces
by its own gates. The designer closes that: author the map where you can see
it, and save the same reviewable brush list.
Four decisions shape it, and the rest follows from them.
The document stays the source of truth
The editor edits the JSON brush list, not the cube grid. .cgz remains an export.
This is the rule the map format section already states — a committed binary cannot
be reviewed or diffed, whereas a map here is a few dozen rectangles — and an
editor that wrote cubes directly would quietly repeal it.
So a saved map is still a file a reviewer can read, and git diff on it still
shows which room moved.
A draft is addressed as a map
This is the piece everything else hangs on. drafts.py holds the document being
edited in memory, and assets.load_map — the single chokepoint every map route
and all three clients already go through — grows one branch:
if name.startswith(drafts.PREFIX): # "draft:"
return drafts.compiled(name[len(drafts.PREFIX):])
That is the whole read path. GET /maps/draft:<id> and
GET /maps/draft:<id>/cubes serve an unsaved document through the routes the
clients already call, so the native client's boot sequence (map_info →
map_cubes → World::new → build_world_mesh) works on a draft unchanged,
and an edit is just a re-fetch of a map. There are no designer read routes for the
map itself, and that absence is the design rather than an omission.
A draft never touches the filesystem until it is saved, so it never meets the
map-name validation in mapsource.source_path: a draft id that looks like a
traversal is simply not an open draft.
mapsource.build stays the only compiler
It is a pure function over a plain dict, so compiling an unsaved document needs no disk and costs nothing extra. The alternative — a compiler in the editor, or a port into the native client — would fail the way this module's three physics ports fail when they drift: not with an error, but with an editor showing you a different map from the one the server will serve.
Two consequences worth knowing. mapsource.load_bundled and bundled_names are
lru_cached with no mtime in the key, because bundled maps ship with the code and
were never meant to change under a running process — saving now clears both. And
build_with_owners returns, alongside the map, the index of the brush that
painted each cell: brushes compose by overwrite, so ownership is only knowable
while they are being applied, and it is what turns a crosshair on a wall into a
brush you can drag.
That ownership map is served as its own binary route at its own width
(GET /maps/drafts/{id}/owners, little-endian uint16, 65535 for untouched
rock) and is deliberately not a tenth entry in plane_order: that tuple
describes the map format, which has no such field, and all three clients
validate their cube payload length against it.
Edits are typed, because the edit is also the undo record
A PATCH carries one operation, never a whole document. A whole-document write
cannot be inverted, so an editor built on one has to grow a second, separate
history — and the two disagree the first time an edit does something the history
did not model.
There are ten ops, closed under inversion: brush.add / .remove / .update /
.replace / .reorder, the same five for ent., and map.set. The inverse of
each is another of the ten, replayed through the same _apply_one that made the
original, so there is no backwards code path that can disagree with the forwards
one. .update merges a patch and an explicit null clears a field — which is why
its inverse is always a whole-object .replace: there is no patch that says "put
the key back".
This is the first undo stack in the repo. It lives on the server because the document does, so the native client and the browser share one history rather than forking two.
An edit that would not compile is refused and nothing changes. Not strictness for its own sake: a client re-fetches the map after every edit, so a document left half-mutated in a state that will not build is not a draft with a problem in it — it is a client with nothing to draw and no way back to something that draws.
Lint: the playability tests, live
The checks that were assertions in test_hassault_bundled.py now live in
maplint.py, and the tests call it. One definition, two callers — a second copy
is how an editor ends up happily saving a map the suite would reject.
Every check is there: the solid border, spawns a body fits in, the reachability
flood fill, spawn spread, item count and kinds, items that are buried, stranded or
sitting on a spawn, ladders that actually arrive somewhere, water that covers
everything, and whether write_cgz would accept every cube — that last one asked
at edit time rather than at export, because "your map cannot be saved" is the
worst possible moment to learn it.
A finding carries the cells it is about, not just a count, and that is the
point of moving them here. "2348 standable cells cannot be walked to" is a number;
the same 2348 cells painted red on the floor of the map you are standing in is an
answer. The list is capped at 512 with the real total in cellCount.
Lint is reported on every edit and on save, and never enforced. A map that plays badly is still a map somebody is halfway through making, and refusing to save it would break the editor exactly when it is most useful.
The texture palette is ours
A texture is a bare integer slot, and AssaultCube resolves one through a map
.cfg naming an image in its own package — content this project does not ship,
which is why nothing has ever resolved a slot here and both renderers tint by
hashing the id through a golden-ratio hue step.
textures.py makes that a named catalogue: a slot has a name, a group, a colour
and a procedural pattern, and no image file exists anywhere. Served at
GET /api/hassault/textures so neither client holds a second copy — the
plane_order / zoom_levels precedent.
It is additive by construction. textures.color_for is the existing hue step
ported to Python, and every catalogued entry's colour is read off it rather than
chosen, so a slot that nobody has named renders exactly as it does today and
naming one cannot change how it looks. The port is checked against the value at id
255, which is where an f32 implementation with a truncated constant would have
drifted from the f64 one both clients actually use.
Where the editor lives
In the native client, because that is where the pixels are: it is the only one with real lighting, shadows and raw mouse input, so lights get authored in the renderer that shows them. It follows AssaultCube's own model — an in-world edit mode plus a typed console — which is also the one UI shape the native client can afford, its entire widget vocabulary being a 5×7 glyph font and a rectangle painter.
The dashboard hassault.play pane is the way in, not a second implementation
of it. MainMenu's Play section carries a Map designer row beside Train and
Host — New opens a blank draft (--new), Edit seeds one from the
selected map — and both go through the same launchNative/useNativeLaunch
path Train and Host already use: POST /hassault/launch_native with
mode: "edit" (and blank for New), which the route turns into
--mode=edit [--new] on the native client's command line — the same flags this
section's --mode=edit --map=hd_pit / --new describe by hand. There is no
browser-side visual editor, only the structured edit.* console commands (which
work in hassault.console either way), so on the web client
(apps/assault-web), which has no native client to open, the row is disabled
rather than silently doing nothing.
The structured half is typed into the console, and costs nothing on either client
because console.py already owns the registry and serves it: a command declared
there is rendered by the native client and by the browser's hassault.console
pane without either learning anything new. Eighteen edit.* commands arrive that
way — enough to build a whole playable map without touching the mouse, which is
what the backend suite does to prove it.
--mode=edit --map=hd_pit opens one (--new starts from solid rock). It has no
socket, exactly like Train and for a stronger version of the same reason: there
is no match to be in, so there is no server to lie to about a camera that ignores
gravity and walls.
| WASD, space / shift | Fly. Forward follows the aim, pitch included — a walking camera's W is yaw-only because its feet are on the ground |
| Scroll | Fly speed, multiplicatively, so one notch does the same proportional thing at any scale |
| Click | Select what the crosshair is on. An entity in front of a floor wins: you are pointing at the thing in front |
| Drag | A wall face resizes that side; a floor moves the whole brush; open rock draws a new room |
[ ] | Raise or lower the selected brush's floor |
| E | Place an entity at the crosshair |
| Z / Y / R | Undo, redo, save |
Three things about that loop are load-bearing.
A drag draws a wireframe ghost and nothing else — no request, no compile, no mesh. The edit goes out once, on release. A press that does not move is a selection, so click-to-select and drag-to-reshape are one gesture told apart by what it did rather than by a modifier nobody remembers.
The rebuild is a full one. build_world_mesh is a flat loop over the grid and
finishes in single-digit milliseconds in Rust, so there is nothing to gain from a
dirty-region scheme that could disagree with the mesh a fresh load produces — and
a mesh that is subtly wrong only after an edit is the worst kind to debug. It
re-bakes the shadow map too: that is rendered once from a static sun onto static
geometry, so a rebuilt world keeping the old one would light a room you just
carved with the shadow of the rock that used to be there.
Edits run on a worker thread. NodeApi is blocking HTTP — three requests
stand a world up, and a runtime for three requests would be absurd — but an edit
is a PATCH, a compile and two fetches, and doing that on the frame thread is a
visible hitch every time you let go of the mouse. So it goes to a thread and the
frame drains whatever finished, the way prop::preload already does.
A refused edit is surfaced, not swallowed. The document is unchanged and the map on screen is still right, but an editor that silently ignored a gesture would be indistinguishable from one that had stopped working. The status line keeps the HTTP status's meaning rather than flattening it: a 409 from a save means "that map exists, pass overwrite" and a 422 means "this document will not build".
editor.rs itself imports neither the renderer's pipeline nor winit, the same
rule world.rs and geometry.rs follow, so the camera, the picking, the rect
arithmetic and the gesture logic are all unit-tested with no GPU and no window.
FlyCamera deliberately holds no angles: Camera already owns yaw and pitch,
in degrees, and a second copy in radians would be two owners of the same two
numbers with a conversion at every seam.
Backend surface
| Route | Purpose |
|---|---|
POST /api/hassault/maps/drafts | Open a draft, blank or seeded from a bundled map |
GET /api/hassault/maps/drafts/{id} | The document, revision and lint |
PATCH /api/hassault/maps/drafts/{id} | One typed edit; returns the new revision and lint |
POST /api/hassault/maps/drafts/{id}/undo | /redo | Walk the history |
GET /api/hassault/maps/drafts/{id}/lint | Playability findings, with cells |
GET /api/hassault/maps/drafts/{id}/owners | Per cell, the brush that painted it (uint16) |
POST /api/hassault/maps/drafts/{id}/save | Write maps/hd_<name>.json atomically |
DELETE /api/hassault/maps/drafts/{id} | Close it |
GET /api/hassault/maps/schema | Brush ops, entity types and document fields |
GET /api/hassault/textures | The texture palette |
/maps/schema is declared before /maps/{name}: the two are the same shape
and FastAPI matches in declaration order, so the designer routes have to come
first or schema is read as a map name.
The schema is served for the same reason the weapon table is. An editor holding its own copy would eventually offer a field the compiler had stopped accepting, and the failure is a form that looks right attached to a map that will not build.
What it does not do yet
- No heightfields or corners. The brush vocabulary is three ops, so
FHF,CHFandCORNERcells cannot be expressed and sloped terrain is not authorable. A fourthheightfieldop is the natural follow-up. mapmodelplacement has nothing to place. The entity is parsed and consumed by nothing in either client, and its attr names a model slot resolved through.cfgfiles this project does not read — pointing at content it could not ship. It needs a prop catalogue of our own first.- No live hot-swap into a running match.
server.mapwill load adraft:<id>(that is what fixing it bought), but an edit does not reach a match already in progress.
The renderer
packages/core/src/modules/hassault/. three is lazy-loaded on first render
(matching Avatar3D) — it is a large dependency and most sessions never open the
pane. world.ts, geometry.ts and player.ts deliberately never import three,
which keeps them unit-testable with no WebGL context.
| File | Role |
|---|---|
world.ts | The byte planes as typed arrays, plus the height rules |
geometry.ts | Cube grid → one BufferGeometry worth of triangles |
player.ts | Gravity, jumping, step-up, sliding collision, mouse look |
controls.ts | The game's own keyboard map — separate from the shell's keymap |
net.ts | Prediction, reconciliation, snapshot interpolation — pure, no socket |
session.ts | The /ws channel as a stateful object the pane drives |
avatars.ts | Remote-player bodies, facing wedges, nameplates |
viewmodel.ts | The first-person weapon model, animated in camera space |
boot.ts | The front door's state machine and progress maths — pure, no three |
reveal.ts | The build animation, patched into the world's own material |
backdrop.ts | The grid and mote shaders the map stands in |
BootOverlay.tsx | Loading, sign-in, username, deploy — the DOM half |
GameMenu.tsx | The Escape pause menu: sensitivity, server browser, rebinding |
HorribleAssaultPanel.tsx | Canvas, pointer lock, map picker, HUD, match UI |
net.ts is split from session.ts for the same reason world.ts is split from
the panel: session.ts reaches the shell's socket module, which opens a real
WebSocket at import time and dies in a node test run. Everything worth testing
lives on the pure side.
Nameplates keep depthTest on. A name drawn through walls is a wallhack, and this
is the same scene a human plays in.
Coordinates: the engine's grid is (x, y) with z as height, and three.js is
y-up, so world space maps as three.x = cube.x, three.y = height,
three.z = cube.y. One cube is one world unit.
Light, sky and fog are served, not hard-coded
The light rig used to live twice, by hand. HorribleAssaultPanel.tsx set a
hemisphere, a sun and a fill, lighting.wgsl.inc held the same numbers as WGSL
constants, and every map was lit identically: a desert at noon and an office at
night under one sun. Map light entities were parsed and then drawn by nobody.
Now GET /api/hassault/maps/{name} serves two more fields, resolved on the
backend (backend/modules/hassault/atmosphere.py):
atmosphere: sky zenith and horizon, hemisphere, sun, fill, fog, exposure and whether a sun disc is drawn. A map source may set any of these, and the rest come from its format's default. The two defaults are exactly the old rigs: the dark cube-map rig and the daylight GLB one. So a map that says nothing looks as it always did.lights: the map'slightentities asx, y, z, radius, color, intensity. AC's grey shorthand (g = b = 0means grey of brightnessr) is expanded here, and our intensity percentage rides the fifth attribute, which AC ignores.
Both clients draw from those numbers and carry no default of their own beyond a
fallback for an older node. The fallback copies are pinned against the Python by
browser_parity.rs. A point light gets intensity × radius / 2 candela with
three's getDistanceAttenuation (decay 2, windowed to zero at the radius), ported
line for line into WGSL.
The candela rule was first (radius / 2)². Under inverse-square falloff that made
a wide lamp a white blowout on the wall beside it, which is why it is now linear in
the radius.
The native client keeps the 64 lights nearest the eye (by distance minus radius)
in a uniform beside the camera, at group 0 binding 1, because the downlevel limit
is four bind groups. The skinned and prop shaders include the same shade(), so
operators and weapons are lit by the map's lamps too. Lights cast no shadows.
A modelled map's sky is its image-based light
On a modelled map both clients light the world with an environment built from
the served atmosphere, not from a generic gradient. Above the horizon it is
the sky the map draws: the horizon colour, eased toward the zenith. Below the
horizon it is the hemisphere's ground colour. The easing is sqrt(|y|) in both
directions, and the result depends on height only.
There is no sun disc in it. The sun is already a light; a disc in the environment would light every glossy surface with it twice.
A cube map has no environment. Its sky is a dark sealed ceiling, and it keeps Lambert.
Browser.
environment.tscreateMapEnvironmentwrites the function into a 256×128 half-float equirectangular source and prefilters it withPMREMGenerator.setMeshmakes itscene.environment. It is rebuilt per map and disposed on the next map or on unmount.- World materials are
MeshStandardMaterialatenvMapIntensity1, so every photographed surface reads it with three's own split-sum.
Native.
environment.rsprefilters the same function on the CPU. It writes a 128²Rgba16Floatcube with 6 levels, where levelnis roughnessn / 5, GGX importance sampled with 256 Hammersley samples per texel.- It sits in the pbr group (group 3, bindings 2–4) beside
dfg_lut.rs. That is three'sDFGLUTData.jscopied value for value, not a fit of it. set_lightingrewrites the cube in place when a map's palette differs, so the bind group is never rebuilt for it.
shade_physical in shader.wgsl ports MeshStandardMaterial's physical
path:
- Smith-correlated visibility,
D_GGX, and the Epic Fresnel fit; - Turquin multiscatter compensation from the DFG table, for the sun, the fill and the map's lamps;
- the hemisphere and the map's baked bounce as indirect diffuse, plus the environment's irradiance and its split-sum specular;
- a roughness floor of 0.0525, widened by the normal's screen derivatives, as three does.
It runs for the photographed surfaces (mat_id > 0) at Medium and above. The
cube maps' Lambert shade() is unchanged, and Low stays flat.
Where the two are not identical.
- PMREM's prefilter and its piecewise roughness-to-mip mapping are three's. Native prefilters on the CPU and maps roughness linearly onto its levels. Both are GGX, at slightly different blurs.
- Native props and operators (
prop.wgsl,skin.wgsl) are still Lambert with no environment, where the browser's are Standard. - The browser's view model keeps its own generic gradient (see the next note).
- The browser's Low tier is Lambert, and three r184 adds environment irradiance to Lambert. Native Low is flat.
What it changed.
-
Shade is lighter on modelled maps, in both clients. Native drew no environment at all before this.
-
The browser's world was already getting environment diffuse, but from the generic gradient drawn upside down (next note), which lit floors with its dark ground.
-
Native Dust II under its served sky:
Pixel Before After Barrel side in shadow (17, 10, 6) (62, 49, 43) Floor in shadow 81 grey 125, faintly sky-tinted Sunlit floor (201, 185, 159) (214, 206, 199), nothing clipped
What it costs (hassault_bench_native.py, the physical build interleaved
with the same build forced onto Lambert):
| GPU and tier | Map | GPU p50 | fps |
|---|---|---|---|
| Discrete, Medium | Dust II | 0.25 → 0.33 ms | CPU-bound either way |
| Discrete, High | Bank | 0.55 → 0.73–1.07 ms | CPU-bound either way |
| Integrated (RaptorLake), Medium | Dust II | 7.2 → 9.1–9.6 ms | ~99 → ~83 |
| Integrated (RaptorLake), Medium | Bank | 9.7 → 13.2 ms | ~81 → ~63 |
Low, the integrated GPU's target tier, is untouched. The arithmetic is the cost, not the table: reading the view's DFG texel once per fragment instead of once per light changed no pixel and saved about 0.2 ms on Bank. Bank pays most because every lamp runs the full GGX lobe.
Pinned by browser_parity.rs:
both_clients_read_three_s_dfg_tablereads three's file at test time;both_clients_shade_with_three_s_ggxchecks the Fresnel, multiscatter and roughness constants against three's chunks;both_clients_light_the_world_with_the_map_s_own_sky_and_groundprobes the native palette and pins the browser's spelling and panel wiring.
environment.test.ts checks the browser's decode and row orientation.
The browser's graphics tier
hassault.graphics is auto, low, medium or high. It draws the same map
data at every level and changes only how much of it is drawn
(graphics.ts TIERS):
| Low | Medium | High | |
|---|---|---|---|
| Pixel ratio cap | 1 | 1.5 | 2 |
| Anti-aliasing | off | on | on |
| Shadow map | 1024, hard | 2048, hard | 4096, soft |
| Map lights | 0 | 4 nearest | 8 nearest |
| Sky dome | no | yes | yes |
| Anisotropy | 1 | 4 | 16 |
| Surfaces | Lambert, generated tiles | PBR, photographed | PBR, photographed |
| Surface variation (anti-tiling, macro tint) | off | off | on |
| Fog density | the map's own | the map's own | the map's own |
A level is a preset, and every row is its own setting, as on the native
client's video page. Picking a level sets every row. A row changed afterwards
(the Advanced rows in Settings: resolution, anti-aliasing, surfaces, texture
filtering, shadow map, soft shadows, map lamps, sky, bloom, surface variation) is kept as an override on
top of the level, and the level shows CUSTOM. Moving a row back to the level's
own value drops the override, and picking a level clears them all. The overrides
are one JSON string under hassault.graphics.custom (or localStorage in the
standalone build), parsed defensively: an unknown row or a value off that row's
list is dropped (parseOverrides). Surfaces is one choice over two fields:
Simple (Lambert), Standard (PBR with the generated tiles) and Photographed. Turning
photographs off live puts the generated tiles back (restoreGeneratedSurfaces);
the images stay cached.
Soft shadows is a filter radius, not a shadow-map type. three r184
deprecated PCFSoftShadowMap and swaps it for PCF at the first shadow render.
Every lit program compiled before that point was compiled again, and every
setGraphics set the type back and recompiled the lot. Every tier now uses PCF,
and soft shadows widens sun.shadow.radius to SOFT_SHADOW_RADIUS (2.5
shadow-map texels, against 1). That is a uniform, so switching it recompiles
nothing.
The sun's shadow is fitted to what the map draws, as native fits it. Both clients render the shadow map once per map (the world and the sun are static), so it never moves under the camera and there is nothing to shimmer: the texel snapping a camera-following shadow needs has nothing to do here. How sharp the shadow is depends only on how many texels each unit of map gets, which is the fit.
- The browser used to fit
MAP_CONFIGS'extent(the playable area, written by hand) at ±1.1. Its texels were 1.1–1.7× the size of native's on eight of the ten maps, worst on Aim, Assault and Bank. - On Junk Flea that frustum was narrower than the map: the sun comes in on a diagonal, where a 239-unit square is about 338 units across, against a 250-unit frustum. So the corners of the map had no shadows.
- Now
shadow-fit.tstakes the bounds of every drawn mesh (drawnBounds, which skips hidden collision and clip nodes) and fits the camera round their sphere (shadowSphere), the ruleshadow.rsfitapplies to native's render vertices. Loaded in headless Chromium, every map's radius comes out within 1% of native's (Dust II 185.6). - High's map went from 2048 to 4096 in both clients (native's High preset takes
the
ultrashadow level; saved levels keep their sizes). On Dust II that is a texel of 0.09 units, about 3 cm, against 0.18. Edges are crisper, shadows meet the foot of the thing casting them, and a wire across the market now casts a line it was too thin to cast before (1.1% of a Dust II frame changes, all on shadow edges). Native scales its depth bias with the map's resolution (0.0015 · √(2048 / size)), so the finer map shows no acne. - What it costs: memory and a moment at load, since the map is drawn once, plus
per-frame sampling of a texture four times the size.
Benched on the discrete GPU at High (
--setback tohighfor 2048, runs alternated), GPU p50 went 0.54 → 0.55–0.56 ms on Dust II and Mirage: within the noise. Medium and Low are unchanged.
The browser keeps the map's exported normals. It used to call
computeVertexNormals() on every map mesh after loading it, averaging every
face round each vertex. The export already writes normals (Blender's smoothing,
with mark_sharp_edges keeping creases hard), native reads those
(world3d.rs), and on Dust II, Bank and Office 20% of vertices moved by over a
degree and 2–4% by over ten. applyMatrix4 carries them through the Z flip by
the normal matrix. Loaded in headless Chromium, every map has them on every
mesh, and on 99.98–100% of triangles they face the way the triangle winds.
browser_parity.rs pins both (both_clients_fit_the_sun_shadow_round_what_is_drawn_at_4096_on_high,
both_clients_shade_the_maps_with_their_exported_normals); shadow-fit.test.ts
checks the sphere and that hidden nodes are skipped.
There is deliberately no shadows-off row. Turning off the sun's shadow lights
a player standing in shade, which is a visibility change, so the rows offer
shadow resolution and filtering only. The native client still has a SHADOWS
on/off row, which turns off the world's shadow while characters keep receiving
it; that is an open question rather than a settled rule.
auto picks from the device pixel ratio and the WebGL renderer string. The pane
stores the choice in the settings bag. The standalone build (apps/assault-web)
has no /api/settings, so it keeps the choice in localStorage, wrapped in
try/catch.
The map lights are a fixed pool of PointLights repositioned to the nearest
few every 0.2 s. A changing light count recompiles every material's shader, so
the pool never changes size; unused lights sit at zero intensity. Anti-aliasing is
a WebGL context flag, so changing it takes effect on the next map load. There is no
EffectComposer, which keeps the bundle and the frame cheap.
The same change fixed three placement bugs on the browser side, all of the same kind: z-up map coordinates were put into y-up three space unconverted.
- Items floated in the wrong place (
items.ts). - Water was a vertical sheet across the map (
water.ts). - Ladders lay on their side (
ladders.ts).
Water and ladders now also appear on modelled maps, not only cube ones.
What a graphics setting may not change
A setting may change how the game looks. It may not change what a player can see, because a setting that shows you more is a setting that wins gunfights. Four things were found doing that and were taken out, in both clients:
- Fog. Low doubled the map's fog density and Medium thickened it by ×1.36, to
save fill rate by hiding distance. A player on a weak laptop could not see
somebody a player on a good machine could. Every tier and every native quality
level now draws the map's own density (
graphics.tshas nofogScale;settings.rshas noQuality::fog_scale). Fill rate comes out of the pixel ratio and render scale, the lamps' shading cost and the shadow filter instead. - How a player is lit. The native skin shader took its shading detail from
the quality level, and at Low detail 0
shade()returns the raw albedo: a fully lit operator on the setting meant to look worse, standing out of every dark corner. Characters now always shade at full detail. And because Low draws none of the map's lamps, both clients add the same light floor to a player (CHARACTER_FLOOR: an emissive inmodels/operator.ts, a term inskin.wgsl), so a player is never a black shape where a lamp is not drawn. - Field of view. The browser allowed 60–110° and the native client 70–120°.
Both are now 60–110 (
FOV_MIN/FOV_MAX,FOV_RANGE). - Brightness. The native client had a 0.6–1.6 exposure multiplier and the
browser had none. The browser now has the same row, stored under the same key
(
hassault.video.brightness), so on the desktop one slider moves both clients.
Smoke, fire and flash opacity are not tier-dependent in either client, and no
TierSpec or Preset field may name them. atmosphere.test.ts fails if a tier
grows a key about fog, smoke, flash, players or props, and browser_parity.rs
reads both clients' sources to pin the fog, the light floor, the FOV and the
brightness ranges.
GLB map surfaces: UVs are derived, colour is authored
The modelled maps (hd_*.glb, written by tools/blender/generate_*.py) carry a
base colour per material and no textures and no TEXCOORD_0. The second was a
silent bug: the native loader read UVs off the mesh and fell back to (0, 0), so
every triangle in a map sampled one texel — each surface one flat colour, and that
colour the corner of its tile (a concrete seam, which is why dust2's sandstone drew
near black). The browser drew the bare base colour with no texture at all.
Both clients now do the same three things:
- Classify the material by name against
glb-surfaces.json— ordered lowercase-substring rules, first match wins, read byglb-surfaces.tsand bytextures3d.rsviainclude_str!, so there is one table, not two.none(emissive, liquid, foliage, printed surfaces) gets no tile. Rule order is load-bearing:mat_ceiling_tilemust hit plaster before marble'stile, andmat_wood_cratecrate before wood. - Project UVs from the world position along the dominant axis of the face
normal (a box with shared corners has diagonal vertex normals, which smear every
face), ties broken like the shader's
detail_uv, scaled by the kind'stileScale. The browser de-indexes the geometry to do it. - Treat the tile as detail, not colour. Every multiplied layer is normalised to
grey luminance with a linear mean of
detailMean(0.667), and the albedo is multiplied bydetailGain(1.5 — the native shader's literal), so a surface averages out to the mapper's colour. A high-contrast tile (hazard) is compressed about the mean rather than scaled into clipping, which would drag the mean back down. Glass and the site decals are blended, not multiplied, and stay as drawn.
Six tiles exist for these maps: masonry (running-bond ashlar), plaster, cobblestone
(jittered Voronoi), barrel roof tile, carpet and brick. They are ported in both
languages and use a tiling fBm (fbmTiled, each octave's period dividing the
tile) — the older tiles' fbm does not tile and seams at every repeat.
glb-surface-vectors.json pins agreement: the classification of every material in
every bundled GLB (read out of the files at generation time) and a set of UV cases,
written by glb-surfaces.test.ts (UPDATE_GLB_SURFACE_VECTORS=1) and replayed by
textures3d.rs. A new generator material that falls through to the concrete
default is caught by a count in the same suite.
GLB maps are in cube units, and a spawn needs room for a body
One world unit is one cube and a standing player is 5.2 of them (eye 4.5 +
0.7 above) — about a 1.75 m person, so roughly three cubes to the metre. Every
tools/blender/generate_*.py is authored in metres (a 70 m Dust II, a 4 m
office storey, a 2.6 m shipping container), and for a long time the result was
exported as-is and read as cubes. That made every modelled map a third the size
it was drawn at relative to the player: Dust II was thirty body-widths across,
its 4.4-unit "grand" archways barely cleared a 5.2-unit body, and its 4.2-unit
tunnel was shorter than the player standing in it.
The conversion now lives in one place, tools/blender/maplib.py:
export_map_glb(name) bakes modifiers (so a bevel's width scales with the mesh
it rounds) and scales the finished scene by MAP_SCALE = 3.0 about the origin
before export. It is uniform — scaling only the footprint would turn every
crate into a slab — and it keeps the node tree intact (for a uniform scale,
multiplying each translation in the chain and each mesh once is exactly
D · world), so every node name the clients classify by survives. The
generators keep authoring in metres; everything that places something on a
map is in cubes and was multiplied once: the JSON's brushes, spawns, items and
sites (sfactor 6 → 8, since 210 cubes no longer fits a 64 grid), the
MAP_CONFIGS table in world3d.ts, its twin in world3d.rs, and
bots.TACTICAL_COVER_NODES. The procedural fallbacks (createProcedural*,
create_procedural_*) still build the metre layout and are scaled on the way
out (scaleFallback / scale_fallback), so a fallback lands where the GLB
would have.
hd_office was the one exception before this: it had been fixed by scaling
only Z (VERTICAL_SCALE = 3.0) inside its primitives, which kept a metre
footprint under a cube ceiling. It now authors plain metres like the rest; its
heights come out identical and its footprint triples. Its tables' heights were
already in cubes, so only their x/y were multiplied. In hd_bank's JSON, the
knee-high cover blocks stay at floor 1 rather than 3 — the brush world is a
rough stand-in for the GLB, and a three-cube block is a jump, which the on-foot
reachability check rightly counts as sealing the cells on top off.
HASSAULT_MAP_SCALE=1 HASSAULT_MAP_OUT=<dir> runs a generator unscaled into a
scratch directory. At 1.0 every generator reproduces the committed pre-scale GLB
(same node and material sets, same bounds), which is how the refactor onto
maplib was checked.
Five of office's eight client spawns and six of its ten items were once inside desks, a pillar or cubicle partitions; they were moved to the nearest clear floor.
tests/test_spawn_clearance.rs probes every GLB map's spawns against the collision
mesh with rays (floor below, headroom over the footprint, nothing within the
radius at chest height), and every map passes it. When it was written, five more
failed: bank's south spawns stood where there is no floor at z = 0 (the slab is
at ~0.85), assault's RVSF spawns were on a mezzanine with 4.6 units of headroom
(moved to the ground floor below — there is nowhere on that level a body fits),
and inferno, mirage and nuke each had spawns under an overhang or on a crate.
Each was moved to the nearest clear point on its own level, z set to the floor
it actually stands on, both tables at once. Items are checked on office only:
elsewhere they sit in crouch-height spaces a standing probe rejects.
Note the two spawn sources for a GLB map: Train and the GLB render use the
tables in world3d.ts/world3d.rs, while a hosted match simulates on the cube
world built from the map's JSON brushes, with the JSON's spawns. The JSON's
placements are now copied from those tables, then nudged by
tools/hassault_fit_placements.py wherever the baked world disagrees (a spawn on
a kitchen counter, an item under a crate); the few that moved are the only
divergence left.
What is solid on a modelled map
Solidity is decided in three places, and each was wrong in its own way.
Which GLB nodes collide (glb-colliders.json, read by glb-colliders.ts and
world3d.rs). Both clients used to skip any node whose name contained a
decoration keyword — the browser case-insensitively, native case-sensitively — so
Perimeter matched rim and every map's outer wall was walk-through in the
browser, along with Mirage's Window Room floor (Window), Dust II's bomb-site
crates (Plant), and the office's cubicle dividers (Divide). A keyword now
only marks a node as decoration, and decoration is skipped only when it is too
small to matter: it can neither be stood on (both horizontal sides ≥
standWidth) nor block a body (taller than the step height and wider than
blockWidth). NonCol in a name still always opts out. Name keywords match
case-sensitively and material keywords case-insensitively, in both clients; the
table's cases are replayed by glb-colliders.test.ts and
tests/test_glb_colliders.rs, the second of which also casts rays outward from
each map's centre so a map that can be walked out of fails. ColOnly nodes are
hidden, not intangible — the browser used to drop them from collision too.
Two model fixes came out of that test: the office's façade is floor-to-ceiling
breakable glass over a drop, so each façade now has an invisible
Exterior_Barrier_*_ColOnly behind it; and maplib.add_safety_floor puts an
invisible Safety_Floor_ColOnly under every map at its lowest surface, because
the bank lays one slab per room and the strip under each doorway had no floor at
all — offline, walking through the west door dropped you out of the world.
NonCol is a promise that nobody's eye ends up inside it. Both clients cull
back faces, and from inside a mesh every face is a back face. So a visible prop a
body can walk into vanishes for whoever is in it, while still hiding them from
everyone outside. That is "see-through from one side". NonCol is right for
anything above head height, flush on a wall, below a crouched eye, or standing off
a solid by less than a body's radius: vigas, cables, banners, rafters, jars. It is
wrong for anything at eye level that a body can reach, which is 3.375 to 4.5
cubes above the floor (crouched, standing). What the 2026-10-04 pass fixed:
- Posts and poles a body stood in: Dust II's pergola and well posts,
Inferno's well posts, the office's window mullions, Nuke's yard floodlight
poles, Assault's sprinkler riser. All solid now. A decoration keyword makes a
name non-colliding at that size, so the riser lost its
Pipeand the bank's globe itsGlobe(it is aTerrestrial_Sphere). - Furniture at eye height: the office's conference chair backs, the bank's globe, Assault's air-line regulator, Bank's teller pillar shafts and street trees. All solid now. The pillar shafts are 7 cm, not 6: the bake samples a cell on a quarter-cube grid, and a thin enough cylinder fits between the samples and blocks nothing.
- Foliage: Mirage's and the office's planter leaves are wider than a body at crouched eye height. Their pots are now solid and at least as wide as the leaves, so no body gets into the leaves.
- Overhead pieces at eye height when you stand on something: the bank's teller cage beam sat at a crouched eye on the counter, and the well beams on Dust II and Inferno at an eye standing up on the rim. All were raised clear. Assault's crane pendant and pallet-jack handle were lowered under a crouched eye. The Bank's van mirrors and police spotlight were pulled in against the vehicle body.
- Glass with no wall: Dust II had four panes in open space, Mirage three, and Nuke two (one inside a shipping container). All are removed: a window needs a wall with an opening, so add the two together. Nuke's hut window had a sill and no wall under it; it has a wall now.
- Nuke's turned containers:
add_shipping_containertook a yaw but turned only the trim (ribs, castings, lock rods), never the box. The trim of every 90° container stood in a line across open yard. Containers are long along X now, and the trim matches the box players have always collided with. - Rugs: Dust II's rug floated in a souk doorway. It now hangs on
Wall_LongA_West. Its twin, buried inside the perimeter wall, was moved out.
Dust II's jars were made solid too. They are 1 m tall, below any eye, so they never hid anyone; but a body walked through them, and a 1 m jar is cover.
Breakable glass is the exception. Hosted play treats breakable glass as open
(see bake_collision.py), so a body can stand inside any pane. That is by
design, not a bug. The office's server-room glass walls are the two that report.
The façade did too, until its invisible barrier was moved flush against the
glass: it had stood 0.2 m out, and the server let a body into the gap.
Two checks found these. Both run over the shipped GLB from where the server says a body fits.
-
Back-face sight lines. From every reachable cell, cast sight lines and count any that hit the back of a face first. Put the eye off the half-cube grid the maps are built on. Otherwise rays run inside face planes and report false hits.
-
Eye inside. This one is checked in, and the second command exits 1 on anything other than glass:
uv run python tools/hassault_body_points.py hd_dust2 > dust2-bodies.jsonblender --background --factory-startup --python tools/blender/probe_eye_inside.py -- hd_dust2 dust2-bodies.jsonIt tests every position
physics.can_standaccepts, at the resting eye heights, against every visible mesh the bake does not collide with. All nine maps read 0 after the 2026-10-04 pass; see the Blender 5.3 rebuild for the ones that report now.
That pass cost each map a little open floor, because the newly solid props now take up space:
| Map | Reachable cells lost |
|---|---|
| Office | 598 (the façade gap is half of it) |
| Mirage | 208 |
| Nuke | 132 |
| Bank | 74 |
| Inferno | 68 |
| Assault | 17 |
| Dust II | 4 |
The fit only moved lights; no spawn, item or site.
The body that collides (physics-rapier.ts, physics_rapier.rs). The Rapier
controller was tuned in metres — a 1.8-tall, 0.45-radius capsule — and was never
touched when the maps went to cubes, so it became a third of the avatar's size
and slipped through gaps the avatar visibly could not. Every length, speed and
acceleration is now multiplied by UNITS_PER_METRE (3), which keeps the tuned
feel exactly; the material-penetration model stays in metres and is handed
thickness / U.
What a hosted match simulates. The server, and the client predicting against
it, never see the GLB: they run the cube heightfield built from the JSON's
brushes, which for these maps was a hand-drawn open box with a few dividing
walls, so online every crate, van and building was walk-through.
tools/blender/bake_collision.py now rasterises the GLB's colliders (the same
glb-colliders.json rule) into that grid and writes the result back as merged
room rects, marking the JSON "collision": "baked":
- 4×4 vertical rays per cell, counting solid by face orientation per welded part. Each part's up-facing and down-facing faces go in separate trees, because a ray query returns only the nearest hit, and stepping past it skips a face lying in the same plane. Per object was not enough: Dust II's crate dressing is one joined mesh, and with each crate's bottom flush on the top of the crate below, the whole stack read as a 0.5-cube slab you walked straight through online. A one-sided plane is read as a thin slab, not as rock all the way down.
- A column holds one opening, so the bake walks from the spawns over every
opening of every column — step, running jump, drop — and keeps the lowest
opening that was reached: the street under a catwalk, never the void under a
floor slab. An unreached column keeps its top only when it is open to the sky
(a crate or wall top you can shoot over); anything else closes. Under a roof
that makes a prop nobody reaches (a fridge in the bank's office) solid up to
the roof, which is why the server places bodies only where they fit
(
physics.place_body) rather than on whatever floor the column has. - Footprints are conservative (a cell is blocked if any sample is), minus slivers. When at most one row of a cell's samples, all on one side, stand on something higher, and the neighbour on that side is mostly that thing, the cell keeps the floor most of it stands on. Trimming any minority went too far: it shrank an office chair enough to leave a pocket a body fits in and cannot walk to. A floor is never trimmed down through a slab into the opening below it (Nuke's vent hatch), and a gap too short to stand in is never trimmed at all. A part thinner than the sample spacing (a rail, a pole, a steel plate) gets an extra blocking sample on its centreline, so it no longer falls between them. A crate's edge no longer reads a cube wider than it is, which had players standing on air beside every ledge. A thin wall that straddles a cell line has no such neighbour, so it still blocks. Floors round to the nearest cube and ceilings round down, after a 1e-3 margin for the float32 trees.
maplint holds a baked world to what these maps are built for: reachability
allows a running jump (JUMP_CLIMB = 4, measured against physics.step by
test_maplint_jump_climb), crossing the unstandable cell that hugs any ledge,
and raised islands — standable tops beside ground someone does reach — are
geometry, not a sealed room. Drawn maps keep the stricter on-foot rule.
Rebuilding a modelled map is therefore the generator
(blender --background --factory-startup --python tools/blender/generate_<map>.py),
the bake (... --python tools/blender/bake_collision.py -- hd_<map>), then
uv run python tools/hassault_fit_placements.py hd_<map> and
tools/hassault_sync_client_spawns.py hd_<map>, in that order.
test_modelled_maps_simulate_their_model fails if a gltf map ships without
baked brushes.
Fixing solidity surfaced traversal the models never had: Dust II's Long A and CT
"ramps" and Inferno's apartment stairs were boxes (cliffs), now wedges via
maplib.add_wedge. Until October 2026 every wedge was an open mesh: the top
corners at the low end were separate vertices that never merged with the bottom
ones, so the bake read each ramp as a thin sheet. And Nuke's reactor hall was four unbroken walls — Site A was
unreachable by anyone — and now has three doorways (maplib.add_wall_with_door).
The heightfield rule, which is easy to get backwards
For a heightfield cell, the base height comes from the cell while the
delta comes from the cell owning that corner vertex. physics.cpp:287 shows
both halves — it starts from s->floor and subtracts an average of the four
corner cells' deltas.
Taking the base from the corner cell instead (the obvious reading of "vertex
height") tears adjacent heightfields apart at every seam, and it is not an error
you get told about — the map just renders wrong. cornerFloor is the one place
this lives, and a test pins it.
The two divisors are also distinct and both real:
vdelta / 4per vertex — the corner heights the mesh is built from.(sum of four vdeltas) / 16per cell — the height a body standing there rests on. This is the mean of fourvdelta/4terms, not a different constant; using/4here sinks the player into every slope.
Where walls come from
An open cell contributes a floor and a ceiling. A wall appears wherever an open
cell meets something taller: a solid neighbour, a neighbour with a higher floor
(a step up, textured wtex), or one with a lower ceiling (an overhang, textured
utex — using wtex there is a classic source of subtly wrong walls).
Emitting walls from the open side only means every surface is produced exactly once and always faces the space you can stand in, so the mesh needs no back faces. Both sides of an edge read the same two shared vertices, so heights meet exactly even across heightfields.
Surfaces are tinted by texture id rather than textured — real textures are resolved through map config files this slice does not read yet. Distinct ids getting distinct hues is what makes walls, floors and trim legible as architecture rather than a uniform grey soup.
Movement
Player dimensions are AssaultCube's own (entity.h): radius 1.1, eye height 4.5,
0.7 above the eye. Collision uses the circle's AABB, as AC's rectcollide does,
so the body is 2.2 cubes wide and needs three cells of clearance — worth
knowing before hand-building a test map that a player then cannot enter.
Movement carries momentum. Velocity is integrated against the grid rather than the position being stepped by a direction, and that is not an implementation detail — three of the mechanics this game is for have nowhere to live otherwise. Weapon recoil pushing the shooter is an impulse; the chained-jump boost multiplies a speed that has to already exist; and the difference between ground control and air momentum is the difference between two friction constants.
Two details that matter more than they look:
- Horizontal movement resolves one axis at a time. Testing the combined vector once would reject the whole move and make every corner sticky; resolving x and y separately is what lets the player slide along a wall. A refused axis loses its velocity — keeping it stores up a shove that fires the instant the body clears the wall.
STEP_HEIGHTis not a nicety. Sloped terrain is stored as a series of small floor changes, so a collision test that rejects any rise leaves the player stuck on ground that looks flat.
The frame timestep is clamped: a backgrounded tab returns a huge dt, and
integrating it in one go teleports the player through walls. The client records
the clamped value in its command, not the raw one — recording the raw value
would make the replay step further than the server ever simulated, and the two
would never agree again.
A player wedged inside solid geometry is resolved before gravity, not after. Checking afterwards means they have already been moved down by one frame of falling, which does not look like falling — it looks like sinking half a cube a second, forever. Both implementations had this and both were fixed together.
The skill curve, and where its numbers come from
The constants come from AssaultCube's physics.cpp and entity.h, converted out
of AC's per-millisecond unit soup into plain SI (cubes, seconds). The point of
being faithful is the skill curve: AC's movement is learnable, rewards timing
over reflexes, and cannot be automated into an advantage. Each rule below is one
of the reasons that is true.
| Rule | AC source | Here |
|---|---|---|
| Ground/air response | friction 6 / 30, blended per frame | GROUND_RESPONSE / AIR_RESPONSE = 50/friction per second |
| Stopping | none: the blend only approaches | GROUND_STOP_SPEED 3, Source's sv_stopspeed idea |
| Chained-jump boost | 1.25/max(speed/fullspeed, 1) within 250 ms while strafing | JUMP_CHAIN_BOOST 1.25, JUMP_CHAIN_WINDOW 0.25 s |
| Crouch | eye to 3/4, speed to 0.4, exempt when crouched in air | CROUCH_EYE_SCALE, CROUCH_SPEED_SCALE, crouched_in_air |
| Gravity ramp | dropf = (gravity-1) + timeinair/15 | GRAVITY_RAMP, capped at MAX_GRAVITY_SCALE |
| Recoil pushes the shooter | vel.add(unitv * (recoil/dist)), ×0.75 crouched | Weapon.kickback, CROUCH_KICK_SCALE |
Ground control settles in ~0.12 s while air control takes ~0.6 s, which is what makes momentum, not the stick, decide where a jump lands. That single ratio is most of the feel.
Run speed is 18 cubes/s, which is Counter-Strike's run per body height (3.47
heights a second). It was 22, a sprint no stride could keep up with, so every body
skated. And on the floor the gap to the wish velocity closes as though it were
GROUND_STOP_SPEED larger, then stops at zero:
gap(dt) = max(0, (gap + STOP)·exp(-k·dt) - STOP). The blend alone never arrives:
a released key left the body drifting for 556 ms, and it is now 228 ms. That form
is the exact solution of gap' = -k·(gap + STOP), so it is as frame-rate
independent as the blend. tools/hassault_feel_report.py prints the timings.
Stepping off the top of a ladder uses the ground's response, not the air's. On air control alone it reached the ledge only at the old run speed.
Two deliberate deviations from AC, both because its exact behaviour would be a bug here:
- The velocity blend is
1 - exp(-k·dt)rather than AC's lineark·dt. AC's form is frame-rate dependent — its players tunemaxfpsfor movement — and this server integrates whateverdta client reports, so a frame-rate-dependent rule would literally pay clients for lying about their frame times. - The chain-boost window is measured from landing, not from the previous jump, and carries no "must be higher than last time" test. AC's version only fires on rising terrain, which makes it undiscoverable; measured from the landing it is a timing skill anyone can find and nobody can automate away.
The boost is a clamp above the cap, not a multiplier that compounds: at or above
run speed the factor works out to exactly 1.25 × MOVE_SPEED, so no amount of
chaining passes 125%. In the air the excess decays toward the run cap, so it has to
be re-earned on every landing — which is the loop the whole mechanic exists for.
One bug worth recording because it hid two mechanics at once. The "snap down off a
small lip" branch used to catch a body on its way in from a genuine fall, and a
body resting on the floor dips below it under gravity every single frame. Reading
either as a landing meant the chain window reset continuously (making the timing
free) and fall damage would have been charged for standing still. Both branches now
test was_grounded, captured after the jump: "arrived on the ground" and "was
already on the ground" are different events, and conflating them costs the game
two mechanics.
Crouching
Crouching is the one movement option with a cost on both sides of the ledger, which is what makes it a decision rather than a strictly-better state:
- The eye drops to 3/4 of its height (
entity.h'smaxeyeheight*3/4) whileaboveeyeis unchanged, so the body is ~1.1 cubes shorter and fits under gaps a standing one cannot. - Speed drops to 40% on the ground.
- Movement becomes completely silent — no footsteps are emitted at all (see Noise). This is the payoff that makes the speed penalty a trade rather than a tax.
- Recoil is braced to 75%, so a crouched shot is both the accurate one and the stable one.
- The hitbox genuinely shrinks, and the head band moves down with it. The band is relative to the top of the body, not an absolute height — pinned to a standing figure it would sit above a crouched player entirely, making them unheadshottable, which is not a crouch bonus anybody asked for.
Two subtleties that are easy to miss and both pinned by tests. Crouching while
already airborne costs no speed (AC's crouchedinair), which is what makes a
crouch-jump a way to clear a gap rather than a way to fall short of one. And
releasing crouch under a low ceiling does nothing: the transition target stays
where it is, because popping the body through a roof leaves support shoving it
back down forever.
The transition is animated over CROUCH_TRANSITION (0.15 s) rather than snapped,
and crouch is a 0..1 fraction on the wire, so the avatar squashes smoothly and the
rewound hitbox is whatever height the shooter actually saw.
Crouch is a hold by default (hassault.crouchToggle makes it a toggle). Hold is
what the movement rewards — a crouch you can release the instant you need speed
back — and it is the only mode where blur and losing pointer lock stand you up,
because a toggled crouch is a deliberate state and losing it to a focus change would
be a surprise.
Shoot-jumping
Firing shoves the shooter, opposite their aim, at Weapon.kickback cubes per
second. Aim at the floor and the push is upward: a jump plus a well-timed shotgun
blast reaches ledges a jump cannot, which is AssaultCube's signature trick and the
reason apply_impulse/applyImpulse exist at all.
Three things make it work rather than break:
apply_impulseclearson_groundon an upward kick. Without it the next step's vertical resolve lands the player again immediately, before the velocity has moved them anywhere.kickbackis served, not duplicated in TypeScript (GET /api/hassault/weapons, the same precedent asplane_orderandinterval). The client predicts the identical impulse the server is about to apply, and two copies of that number is a mispredict on every shot.- The client applies it after the step, which is exactly where
match._fireapplies it (simulatesteps, then_handle_combatfires).Predictorremembers each kick by sequence number so a replay repeats it in the same position — and deliberately keeps it off the wire, because a client-supplied impulse is a client-supplied velocity.
It needs no cap. It is held on the big slow weapons (shotgun 9.5, sniper 8.0) and near-zero on the fast ones, so an automatic at 700 rpm loses more to gravity between shots than each shot gives back — self-limiting, and pinned by a test that says so.
The counterweight is fall damage: nothing a plain jump can produce costs
health (FALL_SAFE_SPEED sits above JUMP_SPEED), but a recoil-launched climb has
to be paid for on the way down. Fall damage is applied through _fall_damage rather
than _apply_damage, because a death by map is a death with no killer — no
hitmarker, no score, and an empty killer in the feed.
fall_speed is an output of one step, cleared at the top of every step, so a
replayed command cannot double-count a landing. The server turns it into damage; the
client only flinches and plays the landing sound.
Noise is information
Sound is often better information than sight — you hear someone behind you before
you can look — so it is a real mechanic (backend/modules/hassault/noise.py) rather
than a job left to the client's audio mixer.
The server decides who heard what, and that is a security property, not tidiness. If it simply broadcast every footstep with its position and let each client judge audibility, the packet would contain the position of an enemy two rooms away, and a client that drew it anyway would have a wall hack made of sound. So audibility is resolved per recipient, before the send, and what goes on the wire is only what ears give you:
{ "kind": "step", "volume": 0.42, "bearing": 1.87, "up": 0 }
{ "kind": "shot", "volume": 0.71, "bearing": -0.4, "up": 1, "weapon": "sniper" }
A bearing and a loudness, never an offset. Roughly where and roughly how far, which is the resolution a player should be working at, and not enough to draw a dot on a map with.
weapon rides along on a shot and nothing else, and is the one field worth being
explicit about: it is not a position, and it is not a fact you could not already
have — you can see what somebody is carrying, and a gunshot is the loudest thing
in the game. What it buys is telling a sniper round from a shotgun blast two rooms
away, which is a real decision (push, or hold) made on information ears genuinely
carry. A footstep has no weapon and the key is absent rather than empty, so no
client has to special-case a value the wire had no reason to send.
The rest of the design follows from making that trade meaningful:
- Footsteps are paced by distance covered, not by a timer, so a player creeping forward is genuinely quieter than one sprinting — an option even standing up.
- Walls muffle rather than block (
WALL_MUFFLE, one ray from the ear to the source). Hearing someone through a wall is most of what listening is for; an occlusion test that silenced them would make every corner a hard mute and reward nobody for paying attention. - Volume falls off linearly, not by inverse square. Inverse square spends almost its whole range inaudible, collapsing the useful band into the first few cubes.
- A shot is the loudest thing in the game and scaled by the weapon's damage, so the weapon worth hearing about is the one you hear. A knife is nearly silent, which is the entire reason to carry one.
- Your own noises are never sent back to you. They need no round trip, the client synthesizes them locally the instant they happen, and a footstep that arrives 50 ms late does not sound like a footstep.
- A reload makes no noise on the wire yet.
RELOAD_LOUDNESSis defined and unused: both clients have a reload timbre and neither ever hears somebody else's. Emitting it is a one-line change and a real balance decision — hearing an enemy reload is a large piece of information — so it is left as one, not smuggled in with the audio.
Audio is generated, never sampled from anybody else's game (audio.ts in the
browser, apps/native-fps/src/audio.rs natively) — the same licensing rule that
keeps AC's maps and textures out of this repo. Shots, impacts and grenades are
synthesized live from a timbre table. Footsteps, reloads and radio callouts are
.wav files in apps/web/public/sounds/hassault/, made by
tools/hassault_generate_sounds.py, with the live synth as their fallback until
they decode:
- Footsteps are four takes per surface, picked at random and never the same take twice in a row. Each is a filtered-noise heel strike and a lighter toe roll, high-passed at 70 Hz. The first version put 80% of a step's energy below 150 Hz with a pitched sine "thump", which is what made walking sound like stomping, and its sand step buzzed from a periodic 160 Hz modulation.
- Callouts are neural TTS (
edge-tts, voiceVOICEin the generator) under a light radio band. They replaced a formant synthesizer, which is why the old ones sounded like a robot. "Reloading!" repeats at most every 8 s. - Levels are mastered by A-weighted short-term loudness per category, because
unweighted RMS counts inaudible bass. Your own steps play at
OWN_STEP_GAINof somebody else's: theirs are information, yours are not. - A limiter ends the game bus. A rifle shot alone peaks near 0 dBFS, and a firefight measured +6 to +8 dBFS into a bus with no headroom control, which clipped. The trim after it cancels the compressor's automatic makeup gain, so anything under the threshold leaves at the level it arrived.
The files stay at 24 kHz because the native client embeds them and plays them at
WAV_SAMPLE_RATE; the browser resamples on decode.
A weapon's voice is derived, not tabulated
Each gun sounds like itself, and none of them has a table of its own. weaponVoice
reads the numbers the weapon already carries:
| Number | What it does to the ear |
|---|---|
rpm | The pitch. A fast, small weapon cracks; a slow, heavy one booms — the cue that separates a rifle from a sniper at distance. |
pellets | The width of the band. More than one is a shotgun, and a wide band is a blast rather than a bang. |
damage | The body under it and how long it hangs. Weight. |
Same reasoning as shot_loudness scaling with damage rather than getting its own
dial: tie the sound to the balance numbers and a balance change cannot leave the
audio describing the previous version of the gun — and a weapon added to
weapons.py arrives with a voice and no client release. The knife is the one
special case, told apart exactly as shot_loudness tells it (no kickback, almost
no range): a short quiet swish that must not sound like a gun, because being able
to hear that somebody is carrying a knife is the reason its silence is worth
anything.
An unrecognised weapon id falls back to the generic shot rather than to silence or to a footstep — a client older than its server must still hear a gunshot.
The arithmetic is deliberately duplicated in TypeScript and Rust rather than
served, which is the opposite of the rule interval and zoomLevels follow. The
distinction is what the number is for: those are values the client acts on, so
a stale copy is an aim that is wrong. A voice is presentation — a drift makes a gun
sound wrong, it does not make a shot land somewhere else.
Because the mechanic is information, it is also shown: NoiseRing draws a tick
around the crosshair at the reported bearing, opacity by volume. A player on laptop
speakers and a player on headphones should be playing the same game.
What prediction has to rebase now
Momentum changed what reconciliation needs. Rebasing on the server's position
alone and replaying would run the replay on the client's own velocity — the very
number the correction exists to fix — so the error would compound rather than
settle. The authoritative movement state therefore rides in the private half of
the envelope (you.move): velocity, time in air, crouch, and how long since the
last landing.
Private rather than in the shared rows for two reasons: it is nobody else's business, and it would be sixteen extra numbers in every packet for everyone.
sinceLanded is a duration, not a timestamp. PlayerState.t is a simulated
clock local to each side, started whenever that side started, so the two have no
relation to each other and only "how long ago" transfers. The client converts it
against its own clock on arrival.
pos is the owner's position unrounded. The shared row rounds to three
decimals, and that is enough to put a rebased body across a cell line from where the
server has it. The replay then lifts it onto whatever column stands beyond that line,
and the error passes the 2.0 snap distance because of rounding alone. Both clients
rebase on pos when the server sends it and fall back to the row when it does not.
knifeBoost is the room's live gameplay.knife_speed_boost. The server applies it
when player.weapon == 0, and it reads the weapon before the command's own switch,
because simulate steps first and _handle_combat switches afterwards. So neither
client trusts its HUD weapon for the knife flag. Each anchors on the row's weapon as
of the ack and advances it through the switches of its pending commands, which is
exactly the server's order. A grenade in hand does not count: the server does not
know about it.
Placing a body directly
Walking is guarded by can_stand, but anything that sets a position directly is not.
That covers retake's attackers, player.teleport, a spawn inside a wall, and the
no-spawn fallback. The vertical step then lifts the body onto the highest floor
under its 2.2-cube footprint. Next to a ledge, that means the roof next door. Under a
low ceiling beside one, the body is wedged and cannot move. These callers go through
physics.place_body(world, x, y) instead. It searches outward in rings, at most
PLACE_REACH (4) cubes, for the nearest spot where can_stand holds on the
_support floor, so the body starts where its first step would leave it.
test_hassault_retake.py checks every bundled bomb site with 1–5 attackers.
Mouse look
applyLook in player.ts turns the view from raw movementX/movementY
pixels, and its sign is the one thing in this file that is easy to get backwards
without any error telling you so — both signs are perfectly valid rotations, and
only one of them matches what is on screen.
The camera's yaw is measured about cube +x (step walks toward
(cos yaw, sin yaw)), but the renderer maps cube (x, y) onto three's (x, z) —
a reflection, not a rotation — so the camera's right vector at any yaw works out
to (-sin yaw, cos yaw) in those same cube axes rather than the (sin yaw, -cos yaw) graph-paper intuition would suggest. Getting that one sign wrong is exactly
what shipped once: mouse right rotated the view left. applyLook adds
movementX to yaw directly; __tests__/look.test.ts pins the rendered
direction (dot the new forward vector against the old right vector) rather than
the raw sign, so the test still means the right thing if the camera's rotation
derivation ever changes.
Sensitivity is a multiplier on LOOK_RADIANS_PER_PIXEL, stored as the
hassault.sensitivity setting and also adjustable live from the main menu and the
pause menu — all three are the same value, so the settings page and the in-game
sliders can never disagree. hassault.video.fov, hassault.volume and
hassault.crouchToggle work the same way. FOV is one row for both clients,
60–110: the pane used to keep its own hassault.fov, which useFov (and the
native Settings::from_values) still read while hassault.video.fov has never
been saved — and the pane writes it across the first time it does. FOV reaches the camera through the scene
handle rather than at construction, because it is a setting and can change while a
match is running.
Controls, and why they are not keymap bindings
controls.ts is a second, separate keyboard table from
packages/core/src/keymap — see Keybindings
for the shell's own. That module resolves a chord to a command, dispatched
once. Movement is the other shape: forward is a key being held, sampled by
the render loop sixty times a second, and a shell command per key per frame is
not a thing worth building.
Being a separate table is also what makes it scoped to the game by
construction, with no when clause to get right: the only code that ever reads
it is the pane's own pointer-locked key handler, so a binding here cannot fire
anywhere else in the app no matter what it is bound to. The shell's own bindings
are independently suppressed while the pane holds keyboard capture (useCapture
in HorribleAssaultPanel.tsx), so the two tables never compete for the same
keystroke either.
That capture also declares systemKeys, asking for alt+tab and alt+f4 as well.
Asking is not getting: it needs Chromium, document fullscreen and the
keymap.captureSystemKeys setting, which is off by default — see
system-key capture. Pointer
lock is requested with unadjustedMovement: true, which is the real "raw input" of
a shooter's settings menu — movement before the OS applies pointer acceleration —
falling back to a plain lock where that is unsupported.
One table, both clients
The native client used to hard-code every key in a match in app.rs, so the
Controls screen rebound keys for the pane only. The native window is where the game
is played by default, and it ignored every change. It now reads the same
hassault.controls setting at launch (apps/native-fps/src/controls.rs) and
dispatches through game_key:
- Codes need no translation. winit's
KeyCodevariants are named after the W3CKeyboardEvent.codevalues, so a key'sDebugname is its code, and there is no translation table to drift. - The defaults are pinned. A stored diff is relative to the defaults, so both
clients must agree on them.
tests/browser_parity.rsparsesDEFAULT_CONTROLSout of the TypeScript at test time and compares it withcontrols::DEFAULTS. - A few keys stay fixed because the Controls screen does not offer them: the console (backquote), the menu (Escape), F3/F6/F7, and the buy menu's number row. The arrow keys still turn the view natively, but only when nothing is bound to them. The shared defaults put strafing there, and a key cannot mean both.
- Pane-only actions do nothing natively. Ping, drop and noclip have no native implementation, so bound there they do nothing rather than something else.
- Rebindable from the native Esc menu too. CONTROLS lists PUSH TO TALK up
front, then one page per group (Movement, Combat, Utility, Communication) with
every action the native client acts on; the three pane-only actions are left out.
Activate a row, then press its new key: Escape cancels, Backspace clears.
Controls::bindmirrorssetBinding(taking a held key takes it from the other action), and the result is saved as the same diffserializeControlswrites, so a rebind in either client is a rebind in both.
The screen once listed its groups by hand as ['Movement', 'Combat', 'View'],
which silently left out Utility. So the grenade, throw, buy, use and drop keys
were rebindable in code and on no screen at all. It now iterates CONTROL_GROUPS,
and a test fails if any action's group is missing from that list. The
Communication group adds:
- Push to talk (
voice, V). Held, it tells your team you are on the radio (thevoiceindicator event). In lobby voice with thehassault.voice.pushToTalksetting on, it also opens your mic, which is otherwise closed. The native client has the radio indicator only, since lobby voice lives in the pane. In the pane,RadioIndicatorlists everyone talking at the left edge, you included: your own key, teammates'voiceevents, and anyone the lobby mesh measures as speaking (radio.ts). The hosted games server relaysvoiceto the sender's team, as the node's channel does. - Chat, everyone (
chatAll, Y) and team (chatTeam, U). Noclip moved from V to N to make room.
The mouse is not in the table, and the grenade keys changed
controls.ts binds keyboard codes; the two mouse buttons are handled directly in
the pane's pointer-locked handler because what they mean depends on what is in
your hand. With a weapon up, left is the trigger and right is the scope. With a
grenade equipped, left is the overhand throw and right is the underhand toss —
see Equipping a grenade
for why the grenade is equipped rather than merely readied, and why a global
right-click toss would have been wrong.
Digit6–Digit9 therefore equip rather than select, and a weapon key puts the
pouch away. KeyG and KeyH still throw: a player who has learned them should
not lose them because the default moved. They throw only the grenade in your
hand, though. With a gun up they do nothing, which keeps G from being a second
trigger on every weapon. A press made before equipping is dropped, not queued,
so G then 6 does not throw the moment the grenade comes up. The gate is in
press() on both clients (utility.ts, apps/native-fps/src/utility.rs). The
server still knows nothing about equipping.
Bindings are keyed by KeyboardEvent.code (the physical key), not key (the
character it produces) — WASD is a shape under the fingers, and reading key
would move it to ZQSD on an AZERTY layout. Storage is a diff against the
shipped defaults, persisted as the hassault.controls setting (a JSON string,
not a declared SettingDecl row — the settings page renders scalars, and a
document belongs in its own editor, which is why it is the pause menu's Controls
tab and not a settings-page control). Storing only the diff means a later release
that adds an action, or moves a default, still reaches a player who only ever
touched one binding.
Two keys the pane refuses to bind: Escape (the way back to this table if
everything else has been rebound to nonsense) and the handful of
browser-reserved keys documented in keymap/reserved.ts. Taking a key from
another action removes it there rather than allowing both to fire — a state the
player could reach in two clicks and never see the effects of otherwise.
Crouch is bound to ControlLeft and KeyC, and the rebind capture accepts a bare
Control for exactly that reason — every other bare modifier is discarded as somebody
reaching for a real key, but crouch genuinely wants to live on Ctrl. It is also the one
action that does not live in the panel's held-key set: in toggle mode it outlives the
keypress that set it, so it gets a ref of its own.
The mouse is not in the table at all, and the ACTIONS list says so rather
than offering rows that cannot be bound: left is the trigger, right is the
scope, and the wheel cycles weapons. A keyboard rebinding
table that listed "fire" would be a lie about what it controls.
The weapon view model
Before this there was nothing here: the player was a floating camera with a
crosshair, and the only evidence of a weapon was the ammo counter. viewmodel.ts
draws the thing the counter is about.
Procedural, like every other visual in this module, for the same reason the
map surfaces are tinted rather than textured: AssaultCube's weapon models are its
copyright and are never bundled (see
Licensing). Each of the five
weapons is a handful of boxes and cylinders — a receiver, a barrel, a magazine —
untextured and unmistakably geometric, but a shotgun reads as a shotgun and a
sniper rifle reads as a sniper rifle, which is the job. When real (synthesized)
models land they replace WeaponViewModel.build; nothing else changes.
Parented to the camera, not the scene: a view model has no world position, it has a position in front of the eyes, and recomputing that transform from the camera every frame is how it goes subtly wrong on the one frame the camera moves. three only renders camera children when the camera itself is in the scene graph, which is why the constructor adds it there once.
First-person arms, and the two-bone solve
There were no hands. The view model was a weapon floating in front of the camera — which reads as a weapon floating in front of the camera, and no amount of bob or sway fixes it, because the thing missing is the body it is attached to.
Two arms now (arms.ts / arms.rs), each an upper arm, a forearm and a gloved
hand built from primitives — the module's licensing rule again, and the same
construction the weapons themselves use.
The shoulders are fixed in camera space and each hand is solved onto a grip anchor on the weapon, by two-bone analytic IK. That one decision is most of what makes this work. The anchors are points in the weapon's own space, so they inherit the view model's entire transform for free: every bob, every sway, the recoil kick, the reload dip, the stow, the inspect roll — the arms follow all of it without knowing any of it exists, and there is no second animation to keep in step with the first.
The solve must clamp, never NaN. An unreachable target puts
acosoutside[-1, 1], which yieldsNaN, aNaNmatrix, and a mesh three silently declines to draw. An arm that vanishes with no error anywhere is the failure this file has to not have, so both bounds are clamped explicitly: out of reach the arm straightens, folded past its own reach it stops folding. Both suites sweep the whole reachable space asserting no NaN, because the symptom is no symptom.
Grip anchors live in one JSON, not in two clients
models/grips.json, imported by the browser and include_str!d by the native
client, pinned together by browser_parity.rs. Deliberately not served: an
anchor is a fact about the model, not about the weapon's balance, so putting it
in weapons.py would give the simulation's table a rendering column, need a
WeaponOut field, and hand it the response_model failure mode for nothing.
Only the exceptions are listed. A weapon with no entry gets defaults derived from
its own fitted bounding box, in the spirit of fitWeaponModel — so a weapon the
server grows later has hands that look plausible rather than being empty-handed
until somebody notices. The knife's support is null rather than an off-screen
coordinate: an empty hand is a real state, and a hand parked somewhere arbitrary
is a hand the player will eventually see. undefined (not listed) and null (no
off hand) are kept distinct, or the knife grows a second hand gripping thin air.
A test asserts every anchor lies within the weapon's own fitted bounding box. An anchor floating in space is the silent failure here: the solve reaches it happily, the arms are drawn, the elbows bend, and a hand hovers a few centimetres off the handguard forever.
Two pose layers, and why they must be channel-disjoint
models/viewclips.json — again one file, read by both clients — carries keyframed
offsets from the grip anchors. That is what makes a partial keyframe legal: a
track that says nothing about a hand leaves it on the gun, so reload is written
entirely in terms of the support hand and never mentions the trigger hand it is
not moving.
The base layer is locomotion (idle / walk / run / jump / land), looping, and
phase-driven off the view model's own bobPhase so it cannot drift out of step
with the bob. The upper layer is actions (reload / inspect / throw / draw),
one-shot.
The action layer replaces the channels it names; locomotion supplies the rest. Not a weighted average —
models/clips.tsalready explains that two poses averaged on one bone give you half a reload, a motion belonging to neither animation, and makes its own track sets disjoint viaisUpperBody. This does the same thing with four channels instead of a skeleton.
t is a fraction, never seconds, so the reload track stretches to whatever
reloadTime the server served: one authored motion serves a 1.4 s pistol and a
2.6 s shotgun, and both come back up on the frame the magazine is full. The
reload's t is driven by the server's own progress rather than by a clock of its
own, so the magazine goes in exactly when the magazine fills.
The reload's keyframes are the beats a reload actually has: off the handguard to the magazine well (0.18), magazine out (0.35), fresh one in (0.55), charging handle with the trigger hand briefly off the grip (0.72), back home (1.0). That last-but-one beat is what makes a reload read as mechanical rather than as the gun dipping.
PoseSource is the seam. The authored tracks are one implementation; rigged
clips off a skeleton would be another, and nothing in arms.ts or the view model
would change. One interface, no speculative machinery.
Porting the swap animation, which had already drifted
The native client had holster, stow, HOLSTER_TIME, DRAW_TIME,
HOLSTER_HOLD and a fraction-based reload envelope; the browser still had a
fixed-rate exponential approach that did neither end well — a fast reload was
still on its way down when the magazine filled, and a slow one sat at the bottom
and then snapped back. Nothing caught it, because a weapon animation looks
plausible whatever it does. The browser has all six numbers now and
browser_parity.rs pins them.
That port is also what equipping a grenade uses. The holster is purely
cosmetic: it changes nothing about what is held, what can be fired, or what the
wire says — which is exactly why it is the right tool, and ShotController.select
is not.
Skinned hands, knives in cube units, and one inspect per weapon
The cylinder-and-box arms above are now the fallback. What both clients draw is
hassault-hands.glb: a sleeved forearm and a gloved hand with jointed fingers,
built by tools/blender/generate_arms.py — ours end to end, which is why the
unlicensed "FPS Female Arms" GLB beside it is not what ships. The browser poses it
in hands.ts; the native client in hands.rs, which poses it on the CPU and skins
it on the GPU (vs_hand in prop.wgsl), drawing it with the weapon props'
textured, lit pipeline so the glove and the gun in it are shaded by one model. The
arm mesh is uploaded once; each frame sends only the bones, both arms' worth, and
both arms are that one mesh drawn as two instances, the left with the x-mirror
folded into its bones. Skinning the 129k vertices on the CPU and re-uploading them
was most of the native frame (1.8 of 2.4 ms). hands::skin_cpu is kept as the
reference the tests hold the shader's blend to.
- The fist goes on the grip. An anchor in
grips.jsonis the centre of the closed fist (the rig'sgripbone) plus*Aim(wrist to knuckles) and*Up(the hole through the fist). The hand's rotation falls out of those, the wrist is the grip minus where the grip sits in the hand, and the two-bone solve reaches the wrist.*Curlcloses each finger, thumb first. - Anchors are in the prop's own space — the GLB coordinates both clients read byte for byte — and were measured off each model's geometry (the pistol grip, the handguard, the SVU's forward grip). In box-model space they had put both hands behind every rifle, because the box models are a different length from the props they stand in for.
- Out of reach, the shoulder comes forward — straight forward, so it stays
below the frame (
slideShoulder/slide_shoulder). A view-model rifle's handguard is two cubes from the off shoulder; a hand short of the grip is worse than a shoulder nobody can see. - Knives are in cube units and placed by the hilt. The generator
(
generate_all_knives.py) builds every blade from a profile outline with a real grind, fuller, jimping and serrations, exports at real size in cube units with the origin at the hilt, and both clients put that origin atknifeHiltfromgrips.jsonrather than centring the bounding box — so every knife's handle lands in the same fist whatever its blade does. The butterfly's handles are separate nodes on their pins; the karambit and skeleton carry aspin_origin.
Each weapon's inspect is its own clip in models/inspects.json, authored in
tools/blender/author_inspects.py (which documents every channel and writes
inspects.golden.json, the vectors both samplers are tested against). A pistol
press-checks, a rifle checks its magazine, the FAL pulls its charging handle, the
shotgun half-pumps, the sniper works its bolt; a karambit twirls on its ring
(spin about spin_origin, applied to the prop alone so the hand stays put), the
butterfly flips open and shut (nodes), the bayonet is tossed and caught. A
second F on a knife jumps back to the clip's repeatFrom.
To give a new weapon hands and an inspect: add its anchors to grips.json in its
prop's coordinates, add a clip to author_inspects.py and run it, then check the
picture — cargo run --example viewmodel_preview -- out.png <weapon> renders the
client's own path per inspect moment, and PREVIEW_ORBIT=70 swings the eye round
to show where the arms really are.
Own shots spawn no brass and no smoke wisp in the native client any more. Both are world effects at the shot's origin, which for your own shot is your eye, so they landed on the crosshair for a frame every time you fired.
Muzzle flash: a billboard, not a cone
The complaint was "the pistol seems to just show a simple square in response to us
shooting", and it was a literal description of the geometry. The flash was
ConeGeometry(0.16, 0.42, 5) in an unlit MeshBasicMaterial at opacity 0.9, on the
view model's pivot with renderOrder = 2 so it drew over everything — and the
direction it was pointed was down the barrel, which points away from the camera.
A five-sided cone seen end-on is a pentagon. Close to the eye, over the whole view,
for two frames at a time, it read as the screen flashing rather than the gun.
It is now three billboards (flash.ts): a hot core, a wider dimmer halo, and a
smoke wisp that outlives both. In the browser they are THREE.Sprites, which are
square-on to the camera by construction — there is no orientation left to get
wrong, which is the point of the change rather than the soft texture being prettier.
Natively they are triangle fans lying in the XY plane, placed by translation only:
the view-model pass draws with the view matrix as identity, so a shape in XY is
already exactly facing the camera, and multiplying by the model matrix (which
carries every bob, sway and kick) would tilt it a few degrees — the cone's failure
in miniature.
No light is added, and no exposure is touched. The obvious way to make a gun
feel punchier is a PointLight at the muzzle, and that is exactly what was being
asked against: firing must not change the lighting of the viewport.
The flash is screen-size clamped rather than simply made smaller.
FLASH_MAX_SCREEN_FRACTION caps it at a fraction of the viewport's height, computed
against the camera's FOV as it is right now — scoping divides the FOV by the
magnification, so a cap read from the base value would be correct hipfiring and four
times too generous at 4×, which is precisely the view a flash must not fill.
Two smaller corrections came with it. The per-shot size variation used to be a
Math.random() re-rolled every frame the flash was lit, so one shot was two or
three unrelated sizes; it is now seeded once per shot, with a decay over the flash's
life, so one shot is one event. And the knife no longer flashes in the browser —
a swing resolves as a Shot like everything else, so it reaches the flash code, and
a flare would light up the one weapon whose whole value is that carrying it gives
nothing away. The native client had always refused it; that divergence had no test.
browser_parity.rs now pins the per-weapon shape table, the flash life, the screen
cap, the halo ratio, the two colours, and that neither client flashes for a knife.
The smoke wisp is deliberately browser-only, and recorded under
Known limitations rather than half-shipped: the native
view-model pass is opaque and its Vertex carries no alpha, so a wisp would have to
go through the world-space volume pass, which has a real z-order hazard against the
view model's cleared depth buffer.
Materials, not just colours
The four weapon materials are MeshPhongMaterial, and that is most of what makes
the models read as objects rather than as tinted boxes. Lambert has no specular
term at all, so a steel barrel and a polymer grip painted the same colour are
the same surface — every part of every gun was equally matte and only hue told
them apart. A highlight that travels along a barrel as you turn is what says
"this is metal and it is round", and it costs one extra term per fragment.
Each of the four gets its own response: machined metal is the brightest and tightest highlight, blued metal is darker and softer, polymer and rubber have almost none (a grip that glints reads as wet plastic), and hardware and trim are the shiniest thing on the gun — which is what makes sights and bolts catch the eye at all. The float dulls the shine as well as the colour, so a Battle-Scarred weapon is not merely a darker Factory New one.
They also carry the same procedural grain the world surfaces use
(surfaces.ts), at per-face UV scale rather than per cube: a receiver is a third
of a cube long, so world-scale grain would put a quarter of one noise cell across
the entire gun.
Animation is entirely local — walk bob, a turn-lag sway, recoil kick, a reload
dip — the same concession combat.ts's recoil already makes: view angles are
client-owned, so how the gun waves about is nobody else's business. setWeapon
disposes the outgoing model's own geometry before building the next one, so
cycling a loadout never leaks a rifle.
Wearing a skin
The armoury sells skins; for a while the gun in your hands never wore one. Both
clients now read the equipped inventory and build the weapon from it —
equippedSkins in viewmodel.ts, viewmodel::equipped_skins in the native
client, filtering the same /skins/inventory list the armoury renders. There is
no "what am I wearing" route on purpose: a second endpoint to save a four-line
filter would be a second source of truth for the same fact.
A weapon made of boxes can express four things, so a skin is reduced to four: two
colours, a patternType, and the float.
- The skin is part of the model's identity, not a property set afterwards. The
palette is baked into the materials (and into the vertex colours natively), so
applying one without rebuilding leaves the previous skin on the gun with nothing
anywhere to say a change was made.
setWeapontherefore takes the skin and rebuilds when either half changes — and stays a no-op when neither does, since the render loop calls it every frame. - Wear is drawn, not just recorded. The float mixes the whole palette toward grime: Factory New is essentially untouched, Battle-Scarred visibly dull. A float value nobody can see is a number the entire economy is built on and no player can check.
patternTypedecides the layout, because there are no textures. A fade runs the two colours down the length of the weapon, a camo alternates parts, an anodized skin dyes the metal and keeps bright hardware. Enough that a Fade reads as a fade and a Camo does not read as a Slate.- A skinned surface has a brightness floor.
assault_slate's base colour is#09090b— a legitimate design that, taken literally, draws a gun-shaped hole: these materials have no speculars and the weapon sits in the darkest corner of the screen. The floor keeps the skin's hue and lifts only its brightness, and it is applied to skins only, so a player carrying none sees exactly the palette they always did. - An instance whose definition did not arrive is skipped, never guessed. Without a base colour there is no skin, and inventing one puts a colour on the weapon that the armoury never showed the player.
The arithmetic is duplicated in TypeScript and Rust rather than served, for the same reason a weapon's voice is: this is presentation. A drift makes a gun the wrong colour; it does not make a shot land somewhere else.
The browser reloads the inventory on every deploy as well as on mount. The armoury is a different pane, so the gap between opening it and pressing Play is exactly the window in which what you are carrying can change without this pane hearing about it. The native client fetches once at startup, which is the same rule: that process is launched per match.
A drop is a spend, not a button
The armoury's care-package banner used to call POST /skins/claim_drop, and that
route rolled a skin every time it was asked. Nothing counted anything: the button
never dimmed, never went away, and holding it down for a minute produced a
Covert — in an economy whose entire premise is that a Covert is rare. The
trade-up contract, which burns ten items to forge one, was arithmetic over a
currency you could mint.
Level-up drops are now an entitlement spent against a ledger:
- One drop per level, from level 2 up. The level itself is already derived
(
results.progressionis aSUM(xp)overhassault_matches), so what is claimable is a subtraction —level - 1earned, minus the rows inhassault_drop_claims— and no column anywhere holds a drop count that could disagree with the matches it is supposedly the sum of. - The primary key is the guard, not the read.
hassault_drop_claimsis keyed(account_id, level)and the claim row is written before the skin reaches the inventory. Two clicks that arrive together both compute "level 4 is unclaimed" — that is what a race is — and the secondINSERTis the thing that fails. A counter decremented after a check would have let both of them win. - Nothing to claim is a 409, not a quiet 200. The refusal carries the reason ("you are level 3; 600 XP earns the next one"), because a claim that silently succeeds with no item is exactly what leaves somebody pressing the button again.
- The banner reads the ledger (
GET /skins/drops) and disables itself when the count is zero, showing the XP to the next drop and a progress bar instead of an invitation. The disabled button is a convenience; the 409 is the gate, since the browser is holding a copy of a number the server owns.
The match-completion drop is untouched. skin_manager.roll_drop still hands
out a skin unconditionally when a match ends, because that one is earned by the
thing that just happened and needs no ledger. It is claim_level_drop — reserve,
then roll — that the banner goes through. Keeping them separate is why a finished
match does not quietly consume a level's entitlement.
Converting a weapon model into a prop
scripts/build_hassault_weapon.mjs (pnpm build:hassault-weapon), sharing
scripts/lib/three-headless.mjs with the character build.
Both clients draw weapons as procedural boxes. This produces the alternative: one
GLB per weapon, scaled to cube units, oriented so the barrel runs down -Z, with
its PBR maps wired up — the same shape the operator GLB has.
node scripts/build_hassault_weapon.mjs --model assets/horribleAssault/beretta-92 --inspect
--inspect measures and writes nothing, which is how you find out what the other
flags should be. Then:
node scripts/build_hassault_weapon.mjs --model assets/horribleAssault/beretta-92 --length 0.6 --forward +z --out apps/web/public/hassault-weapon-pistol.glb
The four shipped props, in full — a cube is ~36 cm, so each --length is the
weapon's real length divided by that, which is the only reason they are
consistent with each other:
# pistol — Beretta 92, ~21.7 cm
node scripts/build_hassault_weapon.mjs --model assets/horribleAssault/beretta-92 --length 0.6 --forward +z --out apps/web/public/hassault-weapon-pistol.glb
# assault — M4A1, ~84 cm, built from the decimated LOD rather than the 687k source
node scripts/build_hassault_weapon.mjs --fbx .cache/hassault/carbine-m4a1-lod.fbx --textures assets/horribleAssault/carbine-m4a1/textures --exclude "Bullet_01$" --length 2.3 --forward -x --out apps/web/public/hassault-weapon-assault.glb
# shotgun — Remington 870, ~104 cm
node scripts/build_hassault_weapon.mjs --model assets/horribleAssault/remington-870-express-tactical --exclude shell --length 2.9 --forward -z --out apps/web/public/hassault-weapon-shotgun.glb
# sniper — SVU-A
node scripts/build_hassault_weapon.mjs --model assets/horribleAssault/svu-a-sniper-rifle --length 2.72 --forward -z --out apps/web/public/hassault-weapon-sniper.glb
Six things it exists to get right
Each was found by measuring the actual downloads, and each fails silently.
There is no shared unit. Measured across three models: the Beretta's longest
bounding-box axis is 21.4 for a ~21.7 cm pistol (centimetres); the Remington's is
463.9 for a ~104 cm shotgun (~0.22 cm per unit); the M4A1's is 20.0 for a ~84 cm
carbine (~4.2 cm per unit) — a 450× spread with nothing in any file saying which.
So scale is derived from a stated real length, exactly as the character build
derives its from --height: you say how long the weapon is in cubes and the box
is measured to get there. A converter that assumed centimetres would render two
of those three at the wrong size, and being wrong by 20× is not subtle — the
weapon is either invisible or it fills the screen.
Which way it points is not derivable. A rifle pointing backwards has exactly
the same bounding box as one pointing forwards, so --forward is required and
the script refuses to guess. It reports which axis is longest (z, z and x
for the three above), so --inspect gives you the letter and you supply the sign.
And getting that sign wrong is silent, which it proved by shipping: three of
the four props were exported barrel-first down +Z, so the shotgun and the
sniper spent their whole lives in the view model pointing back at the player,
with their muzzle flash 0.2 cubes behind the buttstock. Nothing could have
caught it — a GLB is a binary blob in review, the fit tests build their
prototypes synthetically, and fitWeaponModel defines the muzzle as the
model's min.z, so it will put a flash on a stock without complaint.
weapon-prop-orientation.test.ts now measures the shipped files instead. The
discriminator is thickness: a weapon's front is a barrel and its back is a stock
or a grip, so it compares the cross-section of the frontmost twentieth
against the rearmost. Measured, the four score 2.14 (shotgun), 2.45 (pistol),
4.26 (sniper) and 4.35 (assault); a deliberately flipped build of the assault
scores 0.23. A twentieth and not a tenth because the shotgun's front tenth
reaches back over its underslung light and magazine tube, which are as bulky as
the stock and say nothing about which way it points — that window drops it to
1.32 and the margin with it.
Stray geometry corrupts both the length and the muzzle, so --exclude <regex> drops meshes by object or material name before anything is measured.
The M4A1 carries a loose cartridge floating past its flash hider: it made the
rifle itself 6% shorter than the stated --length (the box is measured over it)
and put the muzzle flash out in front of the barrel in mid-air (min.z is the
bullet's tip, not the weapon's). The Remington carries a loose 12-gauge shell
under the receiver, worth 0.12 cubes of height. Matched against both names
because these downloads name their objects nothing at all — the M4A1's are
mesh1.dat.desirefx.me_out — while their materials are descriptive
(Carbine_M4A1_Bullet_01); anchor with $ where a name is a prefix of its
siblings, since Bullet_01 is also the four rounds in the magazine, which stay.
A pattern that matches nothing is an error, not a shrug: an exclusion is
stated because something is known to be in the way, so a typo that quietly
excluded nothing would hand back the exact model the flag was passed to avoid.
The maps are not in the FBX. Every material comes back from FBXLoader with
no maps at all bar one normal map, while the PBR set sits unreferenced in a
sibling textures/ directory under a different naming scheme per model. They are
matched by name (MAP_PATTERNS), anchored to the end of the stem so
M4_Colour_Variant_Normal.png is a normal map rather than a colour one. The
bare single-letter forms are not redundant with the underscored ones: the
Beretta's maps are literally D.png, N.png, Metal.png and rough.png, so
requiring a separator matched two of four and silently lost its base colour and
its normals — worse than matching none, because a half-wired material looks
deliberate.
Textures are grouped into sets by stripping the map suffix, because these
models carry several (svu_a_sniper_rifle_texset_*, ..._scope_texset_*,
..._lens_texset_*) and pouring them all into one material gives the rifle its
own scope's paint. A material picks its set by longest shared prefix, since
neither side is authoritative — the FBX says R870 Express Tactical and the
files say R870_Express_Tactical_Basecolor, agreeing on everything but
separators and case.
Phong is not PBR, and glTF packs two maps into one. FBXLoader produces
MeshPhongMaterial; glTF's model is metallic-roughness with a single
texture carrying roughness in G and metalness in B. Exported as-is, metalness and
roughness are dropped and the weapon has a base colour and no surface response.
Every material is converted to MeshStandardMaterial, and the two maps are
packed with sharp — GLTFExporter will do that packing itself by drawing onto a
canvas, which the headless shims cannot do, and it surfaces as
context.fillRect is not a function long after the interesting part of the
conversion has succeeded. The packed texture is assigned to both slots as the
same object, which is what makes the exporter take its already-packed branch.
Occlusion rides in R, where glTF expects it. A missing roughness map fills with
255 and a missing metalness with 0, never the other way round: zero roughness is
a mirror finish and a black occlusion channel is a weapon in permanent shadow.
A prop is geometry and nothing else. The Remington's FBX carries a light and a camera. An exported prop that lights the room it is carried through is a bug nobody would go looking for in a model — it reads as the renderer's lighting being wrong — so lights and cameras are stripped and the count reported.
The state of the four models
| Model | Triangles | Longest axis | Usable |
|---|---|---|---|
beretta-92 | 5.4k | z | yes |
remington-870-express-tactical | 28k | z | yes |
carbine-m4a1 | 687k → 30k, 25 meshes | x | yes, after scripts/decimate_weapon.py |
svu-a-sniper-rifle | 25k | z | yes, once its source/dragunov_svu.zip is extracted |
m4-carbine-rifle | — | — | mesh is inside a .rar |
687k triangles is not a viewmodel — the entire hd_atrium world draws about 32k.
The script warns above 40k rather than refusing, because what counts as too many
is a judgement about the target machine that a converter has no business making;
but decimation belongs in Blender, since three has no simplifier worth using at a
98% reduction. An archive that still holds its mesh is named explicitly in the
error, because the directory looks complete until you go looking for the FBX.
Decimating the M4A1
scripts/decimate_weapon.py, run under Blender, takes it to 29,990 triangles —
the same order as the other three — and the prop is built from that rather than
from the original:
"C:/Program Files/Blender Foundation/Blender 5.0/blender.exe" --background \
--python scripts/decimate_weapon.py -- \
--in "assets/horribleAssault/carbine-m4a1/source/Carbine M4A1.fbx" \
--out .cache/hassault/carbine-m4a1-lod.fbx \
--budget 30000
The budget is per mesh, proportional, and floored — not one ratio across
the model, which produces a weapon wrong in a specific and recognisable way.
This M4A1 is 25 meshes whose sizes span three orders of magnitude: a flat 4%
takes the receiver somewhere reasonable and takes the rear sight aperture to
one triangle, so the small parts — exactly the ones a player is looking down
— dissolve first. No mesh goes below MIN_FACES (or its own original count, if
it began smaller), and the surplus comes out of the large meshes, where it is
invisible.
That floor is why the allocation is two passes: the first totals the meshes already at or under the floor, whose triangles are spent whatever the ratio says, and the second shares what is left over the meshes that can actually give it up. Without the split the floor silently pushes the total back over the budget.
Collapse decimation is geometric: it does not know about UV seams, so the budget is spent where the silhouette is rather than uniformly, and the modifier is applied rather than left in the stack, since the FBX exporter would bake it either way and an unapplied modifier makes the file look untouched.
hasattr(bpy.ops, ...) is not a version probebpy.ops resolves its members dynamically, so hasattr is always true for
any plausible name — the probe reads as working right up until the call itself
raises. Blender 5.0 replaced the FBX importer (wm.fbx_import) while leaving the
exporter where it was, so the two halves genuinely need separate handling; both
are done by calling and catching, never by asking whether the operator exists.
FBXLoader and GLTFExporter are written for a browser and reach for
OffscreenCanvas, FileReader and URL.createObjectURL whether or not a pixel
needs drawing. scripts/lib/three-headless.mjs carries the encoded bytes
straight through instead, so nothing is rasterised and no map is re-compressed on
the way out. It was extracted from the character build when this one needed the
same thing, and it is shared rather than copied because two of its pieces are
subtle enough to drift into being wrong without failing: the FileReader shim
must not resolve synchronously (the exporter installs its handler after
calling), and resolveFlips has to bake every flip out before the exporter runs.
The extraction is verified by the operator GLB rebuilding to a byte-identical
sha256.
Drawing the props: both clients
packages/core/src/modules/hassault/models/weapons.ts +
apps/native-fps/src/{prop.rs,props_gpu.rs,prop.wgsl}.
Four weapons now render as real models — pistol, assault, shotgun, sniper. Only
knife does not, and that is the answer rather than a gap: there is no knife
model at all. A weapon with no prop keeps its procedural boxes, which is a
complete working weapon and was the only kind there was. tests/browser_parity.rs pins the two clients' lists equal, because a
weapon that is a model in one and boxes in the other is invisible from either
side alone — each renders something that looks deliberate.
The fallback is the design, not politeness. In the browser the boxes are built
first and a GLB is swapped in behind them if one arrives, so a missing model,
a 404 and a load still in flight all render the same working weapon; making the
view model wait would leave a player who deployed on a slow connection holding
nothing, and an empty hand reads as a broken client rather than a pending fetch.
Natively every failure — no GLB, a parse error, a prop that will not fit — falls
back the same way, and a parse failure is reported through
divergence::note_prop, since silently drawing boxes because an asset is corrupt
looks exactly like a weapon that simply has no model.
The fit is measured, not tuned
Both clients place a prop by translating it so its bounding-box centre lands
on the box model's. Everything the pose is expressed in — HOME, the bob, the
sway, the recoil kick, the muzzle — is relative to that space, so a prop that
occupies it needs none of them changed, and re-running the converter with a
different --length moves the model rather than breaking the pose.
Centres and not origins, and that is the whole of it: the converter puts a prop's origin at the rear of its box, which on a rifle is the buttstock, while the box models are built around roughly where a hand is. Matching origins hangs every rifle a foot in front of the screen. The muzzle flash moves to the prop's own barrel for the same reason — left at the box model's muzzle it hangs in the air beside the gun.
A prop is drawn without the box model's rest rotation. That constant
describes how a pile of boxes had to be turned to look like a weapon; the GLB is
exported already oriented.
A prop is its own reason to run the view-model pass
Natively the weapon is drawn in a second pass with its own cleared depth buffer,
so a 2.5-cube rifle is not sawn in half by a wall you are standing against. That
pass used to be gated on the count of CPU vertices WeaponViewModel::vertices
produced — and once a prop is fitted, that function deliberately emits nothing but
the muzzle flare. The prop is the gun, and pushing the boxes as well would draw
a box gun inside the real one.
So the four weapons that have models were drawn only during the ~55 ms a flare exists: you glimpsed the gun for two frames when you shot and never otherwise, while the knife and the grenades — which have no GLB, so they keep their boxes and their vertices — stayed visible throughout. A model appearing to flicker in only on a shot reads as an animation bug or a bad asset; it was neither.
renderer::draws_viewmodel is the fix and the shape of it is the lesson: a prop
is a reason to run the pass on its own, so the predicate is
viewmodel_verts > 0 || has_prop. Two things about it are load-bearing:
- The same answer must reach two places. The main pass hands its MSAA
resolve_targetto whichever pass is last, so if the resolve and the pass gate disagree the scene resolves twice or never — a black or half-drawn frame, with no error anywhere. It is one function called once per frame for that reason. prop_model()checksvisible, exactly asverticesdoes. The pose is now what says a weapon exists, so returning one while dead or in the menu would put a gun on screen at the one moment there is meant to be none — the mirror image of the same bug.
Game modes
MatchRoom used to encode "the only mode is deathmatch" in exactly five places,
and modes/ exists to be those five places rather than to be a framework:
| What | Where it lived |
|---|---|
scores[attacker.team] += 1 | _apply_damage |
other.team == player.team | _fire, _detonate, _burn |
| unconditional timed respawn | _respawn_due |
room-relative won / mvp | result_for |
| no clock at all | absent from simulate |
Everything else in the simulation — physics, weapons, noise, radar, grenades,
pickups, prediction, the peer fabric, the time budget — is genuinely
mode-invariant, and no hook was added for it. The rest of GameMode is three
wire methods and lifecycle plumbing that was already a method body somewhere.
Every hook has a working default. A MatchRoom built without a mode gets
Deathmatch() and behaves exactly as it did before, which is what made this
landable: no existing test needed changing, and a new mode overrides only what it
actually changes.
Deathmatch(teams=True) shipped in the same change as the proof that the
abstraction is real — team deathmatch needed no new hook and no new mechanic.
Note that both deathmatch modes have friendly fire off: MatchRoom.add
auto-balances every joiner into team 0 or 1 and _spawn_state picks a spawn by
that team, so the game always had sides whether or not anything called them that.
The difference between the two is what the score means, not who you can shoot.
A genuine free-for-all is a third mode and a real change to how a match plays.
The P7 modes
| Mode | Id | What changes |
|---|---|---|
| Duel | duel | 1v1, first to KILLS_TO_WIN (10) or most kills after TIME_LIMIT (180 s); leaving a live duel forfeits it. The only rated mode. |
| Retake | retake | Defuse with the bomb already planted on a site the room's RNG picks, attackers spawned on it, a short freeze, no economy: each side's card (its own rifle, armour, a kit for defenders). Needs bomb sites. |
| Aim arena | aim | Deathmatch with everyone on the rifle and pistol, whatever they picked, and a 0.6 s respawn. |
| AWP arena | awp | As the aim arena, on the sniper and knife. |
| Random guns | dm_random | Deathmatch dealing a primary from the room's RNG every life, so a room deals the same guns from the same seed. |
Two hooks arrived with them: GameMode.respawn_delay (the arenas' quick
respawn; the default is weapons.RESPAWN_DELAY) and GameMode.slots (from P6).
Every one is buildable anywhere modes.build is, so a node can host them too;
only a duel the game server runs is rated.
Duels and the rating
A rating is a claim about two players who played each other, so it is written in
one place: the game server, from a duel it ran (games_server/hassault_rating.py,
migration _m14_hassault_glicko, cap hassault_duel).
- The queue (
HassaultReferee.queue_duel, WS eventsduel_queue/duel_cancel) is for signed-in accounts only. It pairs the oldest waiting seat with the closest rating inside a window of ±DUEL_WINDOW, widening byDUEL_WINDOW_STEPeveryDUEL_WINDOW_STEP_Swaited, and re-tries everyDUEL_SWEEP_Swhile anyone waits. A pair gets aduelroom on the served duel map (duelMapon/hassault/mapsand/api/hassault/ranked/maps; both clients load it before they queue, because the native client builds its world first). - The duel map is hd_office, and duel spawns always see each other. Random
team spawns on the bundled maps had a clear line for at most about half of the
pairs (none at all on Nuke).
duel.duel_spawnsfinds, once per room, the largest sets of T and CT spawns in which every pair has a clear line at eye height through the server's own hitscan ray, andDuel.spawn_optionsrestricts spawning to them. A map can name its own duel places: aduelSpawnslist in its JSON ({x, y, yaw, team}in cubes, like aplayerstart) replaces its team spawns as the candidates (duel.candidates), and they still go through the same search, so one with no line to the other side is dropped rather than trusted. Office needs it: rebuilt as a defuse map, its team spawns are 55 m and three walls apart, so it names two a side across its mid, about 68 cubes apart, and its dressing keeps that line bare.DUEL_MAPSputs hd_office first, and the duel test pins the choice, the sightlines and at least two spawns a side. - The end is reported once, through
room.on_over; a forfeit carries the leaver's seat.rate_matchinserts thehassault_rated_matchesrow first, so a second report of the same match rates nothing, then moves both players withrating.compute_glicko2_step, each against the other's pre-match rating. - Each player hears
rating_update: before, after, delta, won or drew. The browser shows it as a result card; the native client as a HUD note. - Reads are public (
/api/hassault/rating/{account},/rating/leaderboard, placed players only) except one's own (/api/hassault/account/rating). A player is unranked untilPLACEMENT_MATCHES_REQUIRED(10) duels. - The node proxies.
/ranked/rating,/ranked/rating/{id},/ranked/leaderboardand the rating half of/ranked/profileread the server's when this node's account is known to be on the service (account_sync.known_active, which never probes the server itself), else the frozen local row. The node writes no rating anywhere any more. - Queueing is the menu's Find duel (browser:
MatchSession.queueDuel; native:--mode=duel, which sendsduel_queueinstead of a join).
damage_scale returns a float, and both halves matter
The three damage sites ask it as a legality filter (> 0) because
weapons.resolve_shot is pure geometry and expects the caller to have filtered;
_apply_damage multiplies the amount by it. A float rather than a bool because a
defuse mode wants CS-style partial friendly fire, and a bool would need a second
hook beside it.
Applying it as a filter but not to the amount is the half-fix that looks
complete: a mode returning 0.0 still behaves correctly, because nobody is a
candidate in the first place. The omission only surfaces as a mode asking for
partial friendly fire and getting all of it — which is why there is a test for a
0.5 scale specifically, and one per damage site. Honouring it at two of three
is the regression this refactor most invites.
Bots keep their own hardcoded other.team == me.team targeting filter, and that
is deliberate rather than an inconsistency: a bot must never deliberately team
kill even in a mode where friendly fire is on.
Where mode state goes on the wire
Three methods onto the three places the snapshot already has:
welcome_staterides once instate_payload(), like item placements — timings, prices, site positions. This is also what carries the mode across the peer fabric with no fabric changes at all, becausefabric.handle_joinsends that payload verbatim as a guest's welcome.shared_stateis public, per tick, onemodekey inshared_view().private_stateis per recipient and goes insideyou.
snapshot_message gains no new top-level key, and there is a test asserting
its exact key set.
The dangerous mistake, and the reason the split is worth stating twice: putting
per-recipient data in shared_state does not raise, does not warn, and does not
break the snapshot template's fragmentation. It simply sends every player's
money to every player. The _ACK_HOLE / _YOU_HOLE split only guards ack and
you.
Relatedly, never echo a client-supplied string into a mode blob. A sentinel
collision is caught, but it falls back to send_json — so the failure is not a
crash, it is the bandwidth optimisation silently switching itself off. Site ids
and phase names are server-chosen enums for exactly that reason.
The blob carries a v so the native client can report a mismatch once.
divergence.rs reports unknown event names and unknown fx kinds, but not
unknown keys inside you or shared — serde's #[serde(default)] swallows
those. Without the version probe, an old build joins a CTF match, renders no
flags, and says nothing.
Discovery, and two silent failures in it
find_or_create is keyed on (map, mode), not on the map alone. Keyed on the
map, "join hd_pit" drops a player into a stranger's defuse round holding a HUD
for a different game — and it looks like a successful join from every angle.
listing() carries mode and modeName, and so must MatchSummary. A
Pydantic response model drops undeclared keys without a word (the trap
TacticalOut already records), so leaving them off means the server browser shows
every match as deathmatch. There is a test that round-trips every key listing()
produces through the model and asserts nothing was lost.
modes.build raises on an unknown id rather than falling back to deathmatch.
A silent substitution would open a room that looks right and plays as something
else, and since each client renders whatever the welcome describes, nothing
anywhere would report it.
Capture the flag
Two flags, one per team, each on a stand. Take the enemy's, carry it to your own, and score — provided your own flag is home, which is the rule that makes a full defence worth playing rather than a race between two teams running past each other.
A flag is a small state machine (home / carried / dropped) and not a
pickups item, because an item's whole lifecycle is "taken, then respawns" and a
flag's is not: it comes back, and while carried it is somewhere specific.
Running it through Field.collect would mean the mode reading state it does not
own out of a structure that cannot express it.
Rules that were each a bug first:
- Taking and returning are automatic on contact, and CTF deliberately uses
none of
Command.use. A player who has to press a key for a flag they just ran onto will not notice the flag is there. - A carrier who dies drops it where they fell, on a timer before it returns itself. Teleporting it home instantly removes every fight over a dropped flag, which is most of the mode; leaving it forever lets one be parked where nobody goes.
- The drop happens in
on_kill, not intick. This one is not a style point:simulateruns_respawn_duebeforemode.tick, so a player whose respawn timer has elapsed is alive again — and standing somewhere else — by the time a poll would look. The flag would stay carried by a dead player, or land at their spawn. Thetickpoll remains as the backstop for a death with no killer, since_fall_damagedeliberately does not come throughon_kill. - A carrier who quits drops it rather than taking it with them. Deleting it would make quitting-while-carrying a way to deny a flag outright.
on_killdoes not callsuper(), and its absence is load-bearing. The base implementation adds one to the killer's team score, which is right for deathmatch and wrong under a scoreboard labelled "Captures". Inherited, it silently mixed the two: a bot match read 9–0 off six captures and three kills. Both numbers were real, which is exactly why it looked plausible — the only way to catch it is to assert that the score equals the capture count, which a test now does over a whole match.
Bots play it through the one bot_goal hook: carry it home, chase the enemy
carrier (whose position is public, so this is not knowledge a player lacks), go
and fetch your own dropped flag, or go for theirs. Every goal carries an
expires_in, and that is not politeness — a goal with no timeout parks a whole
team against a wall for the match, which reads as "the mode is broken" rather
than "the pathing is dumb". Verified by running bot-only matches on all three
bundled maps: six captures apiece in sixty seconds, with take / drop / return /
capture all firing.
Bomb defuse
Rounds, a plant, a defuse and a side swap. The phase machine —
warmup → freeze → live → post → (freeze | over) — is a pure function,
advance(state, dt, facts) -> (state, emits), with everything that touches
MatchRoom in the tick wrapper around it. That is not tidiness: three clients
have to agree about when a round ends, and the cheapest way to keep them
agreeing is for the rule to be a function with no world in it, the way
physics-vectors.json binds the three physics ports.
Facts is the whole of the world's influence on the machine — two head counts
and two flags — and Emit is the whole of its influence back.
Rules with a reason:
HALF_AT = ROUNDS_TO_WIN - 1, and the minus one is the point. Set equal, a side takes every round of the first half and wins the match without the other ever having attacked, which makes the map's balance the entire result. One short of winning means the swap always happens. This is CS's structure and the same arithmetic is why.- The swap changes roles, and the role picks the spawn. It flips one boolean
and
attackersis derived from it, so nobody'steamchanges andwinsstays indexed by the people who earned it — no score to reverse. But a spawn belongs to an end of the map: the team-1 spawns (defuse.ATTACKER_SPAWNS) are the attackers' end, far from the sites, and the team-0 spawns the defenders', beside them.Defuse.spawn_optionsand the buy zones follow the role, so at half time both teams move ends, as in CS. The swap used to keep everyone's spawn, which only works while sites sit neutrally between the ends; the rebuilt maps put CT two or three seconds from a site and T seven to nine, so every first half was played with the attackers starting beside the sites. - A plant swaps the round clock for the fuse, which is what makes planting with four seconds left a winning play rather than a wasted one.
- Wiping the attackers after a plant does not win the round. It only means nobody is left to stop the defuse, and that asymmetry is the whole reason to plant early.
- Time out with no bomb down is a defender win. The attackers had a job.
- The bomb moves to another attacker when its carrier dies, rather than dropping. A dropped bomb on maps this size is a hunt, not a round. The only way it reaches the floor is on purpose — the drop key, below.
- A mid-round joiner waits for the next one. Dropping them in alive hands one side a body the other did not have to shoot, deciding the round on when somebody's browser finished loading.
on_killdoes not callsuper(), same as CTF: rounds are the score.
Freeze time turns damage off (damage_scale returns 0) but deliberately does
not freeze movement — that would need a physics hook and every mode would pay
for a branch one of them uses. Walking to your side of the map during the buy is
not an exploit.
Friendly fire is 0.35, and this is the mode that makes damage_scale a float
rather than a bool: a teammate you spray through should be a real cost, and one
you cannot hurt at all makes a doorway a place to stand.
What a round reset must clear
room.items.reset(), every player respawned, nades and zones cleared — and
room.history.clear(), which is the one that hides. Every body has just
teleported, so without it a shot in the first quarter-second of the new round is
rewound against last round's positions and registers on somebody who was
somewhere else. It is silent, lasts a few ticks, and is close to impossible to
reproduce deliberately. PositionHistory.clear already existed; it simply had to
be called.
Money, kills and deaths persist: they are the match, not the round.
The economy
Money on MatchPlayer (not a mode-side dict, which leaks its entries when
remove fires), and every number served in welcome_state().config plus a
catalog — the /weapons and /items precedent. A client with its own copy of
a price is a menu that offers a purchase the server then refuses, and that fails
as money still sitting there with nothing saying why.
The catalogue is {id, name, kind, slot, price, side, category} rather than raw
WEAPONS indices, so armour and grenades ride the same integer as a rifle and
Command.buy stays one number. The index into it is what goes on the wire,
which is why a duplicate id is a tested-for error: two rows would buy the same
thing while the menu showed two.
Its gun rows are built from the weapon table (defuse._weapon_rows):
every weapon with a price that is not one of the free knife and pistol,
sidearms first, then primaries, at the weapon's own price and side. A gun
added to weapons.py is for sale without touching the mode. The index is the
same for both sides all match: a row the buyer's side cannot carry (a CT rifle
on T) is refused, not renumbered.
Kills pay by weapon (Weapon.kill_reward): the shotgun and the SMG pay more
than a rifle and the sniper far less, which is what makes an eco round a plan
rather than a forfeit. A kill with no weapon behind it (a grenade) pays
KILL_REWARD.
Buying needs the window and the zone (Defuse.can_buy). The window is the
freeze plus BUY_TIME (20 s) of the live round, closed early by a plant. The
zone is a BUY_ZONE_RADIUS circle round each of the team's spawn points; maps
declare no zones of their own yet. A dead player buys from
anywhere, but only in the freeze: they are buying for the round they spawn
into. The envelope says which of the two is shut (canBuy, buyIn,
inBuyZone), so both menus can say why a buy would be refused.
One gun per slot. A primary bought over a primary puts the old one on the
floor, magazine and all, where a teammate can take it; a sidearm bought over the
free pistol replaces it on the keys. GameMode.slots is what the number keys
select, and defuse answers with what is owned rather than with the loadout.
The menu is CS's (buy-menu.ts, buy_menu.rs): the catalogue outgrew one
row of keys, so a number opens a group (pistols, primary, gear, grenades), a
second buys a row in it, and 0 goes back. A side sees only its own rows.
economy-vectors.json (scripts/gen_hassault_economy_vectors.py) pins both
clients' groups to the server's table. The purse is always on the HUD in a buy
mode, counting toward each change.
Bots buy. They used to read a buy_open flag no mode had, so they never
bought anything; they now ask the mode (can_buy, catalog_index).
Game-server rooms take a mode (cap hassault_modes): a join with mode
lands in, or opens, a room on that map in that mode, and a map that cannot host
it (defuse with no bomb sites) is refused. Which menu modes
(hassault_rooms.MENU_MODES: deathmatch, team deathmatch, defuse, retake, aim
and AWP arena) a map offers comes from its own source's modes list, with
retake going wherever defuse does and neither on a map without sites
(HassaultReferee.map_modes). /hassault/maps serves it per map as modes,
and join refuses a menu mode a map does not offer, so the web client's Create
match, which greys out the rest, never offers a room the server would refuse.
The aim range offers deathmatch, aim and AWP arena as rooms, but its card and
Create match open Aim Training first, which is no room at all: the offline
range and its drills (see aim drills). Duel is not a menu mode:
Create match has a Queue for a duel button instead (accounts only), which
opens the game on the served duelMap with initialMode: 'duel', and the
standalone panel queues rather than joins. Results in menu rooms stay unrated
with the mode in their ruleset: a room people join and leave one at a time is
not two seats facing each other.
Command.buy and not a /ws event, for the reason throw gives: commands are
forwarded verbatim by fabric.handle_input, so a field crosses the peer wire,
the ranked relay and the console with no changes at all. An event needs a
channel.py branch, a fabric.py send and handle pair, a new frame kind, a
guest-side normaliser and a ranked.py relay — five touch points, four of them
security boundaries, for something that costs nine bytes here. It is -1 when
absent, the weapon/nade shape: a default of zero names the first entry and
would make every movement command a request to buy a rifle.
Rules with reasons:
- A purchase that would give nothing spends nothing — the
pickups.applyshape. Armour at full armour, or a rifle you hold, must not quietly cost you the round's money. - A dead player may still buy. They are buying for the next round and the
freeze is when that is decided, so
aliveis deliberately not one of the checks — see theon_commandnote below, which is what makes it possible. - A loss pays, and pays more the longer it goes on. Without it a side that
loses once buys nothing, loses again, and the scoreline stops being about
play. That is the failure an economy is most likely to introduce and the one it
is least obvious it has. Capped at
MAX_LOSS_STREAK, or a side that never wins ends richer than the one beating them. - Planting and defusing pay even on a losing round. Planting and then being wiped is still the play that nearly worked. Paid at the objective rather than at round end, which also avoids having to remember who the planter was — they may not be alive by then.
- Half time levels the purses, or the first half's economy decides a match whose sides have just swapped.
- A team kill charges rather than pays, floored at zero: friendly fire here is partial, so a teammate in a doorway is already a cost, and this stops shooting through them being free. A debt would follow somebody into a round they had nothing to do with.
Dropping and selling back
Two more Command fields, for buy's reason: drop (a flag) and sell (a
catalogue index, -1 when absent). Both are handled in Defuse.on_command,
so deathmatch — where everyone already holds everything — ignores them. In
that handler sell runs before buy, so one frame can trade a rifle for a
sniper on the strength of the refund.
Drop (X in the browser) puts down the bomb if you carry it, and
otherwise the gun in your hands. The bomb comes first because handing it to a
teammate better placed to plant is what a carrier means by the key.
- Only a bought gun can be dropped, never the knife or pistol (
FREE_SLOTS), and only by a living player. - A dropped gun keeps its magazine and reserve. A drop that refilled itself would be a free reload for two players standing side by side.
- It rides in the shared state as
drops: [{id, slot, x, y, z}], with no ammunition. How full it is belongs to whoever picks it up. - It is taken by walking over it. One reach,
_standing_on, covers kits, guns and the bomb, so no two of them can be taken from different distances. - A gun goes to anyone who doesn't already own one of that kind. It moves into their hands only if they were holding the knife or pistol: swapping someone off a rifle because they brushed past a shotgun would be a pickup that costs a fight.
- A dropped bomb (
bomb.state == "dropped", with its position) is taken only by an attacker. Attacker bots go and fetch it throughbot_goal. - Your own drop ignores you for
DROP_REPICK_DELAY(1s). It lands at your feet, so without the delay the next tick hands it straight back and the key appears to do nothing.
Sell refunds the full price, only while buying is open (the freeze and
the buy time, in the buy zone). Pressing a row that
you.mode.sellable lists sells it back. The menu shows that row as
SELL +$price in a colour of its own, because a row that looks finished but
refunds you on a keypress is a misclick waiting to happen.
sellable is its own list and not derived from bought, because owning is
not having paid. MatchPlayer.purchased records what you bought, and two rules
keep it honest:
- A gun that leaves your hands leaves
purchased. Without that, one player buys a rifle, drops it for a teammate, and both of them sell it back: one purchase, two refunds. A picked-up gun is never added topurchased, so it is owned but not refundable.test_a_dropped_gun_cannot_be_sold_by_either_playerpins both halves. - What is sold must still be exactly what was bought: a grenade not yet thrown, armour that has absorbed nothing. Refunding spent utility would make the freeze a window in which it is free.
The client decides buy-or-sell in trade.ts (native: App::buy) from the
latest envelope at send time, never from its own idea of what it paid for.
Both clients send both fields: the native client's drop key (X) and its menu's
sell rows went in with P6.
Two ordering bugs the economy exposed
Both were invisible until something was actually bought.
outfit was never called on respawn. It ran in MatchRoom.add only, so
reset_loadout's full grant won at the start of every round: you paid, you
spawned, and you were holding the whole loadout anyway. There is no error
anywhere in that — the buy menu simply appears not to work. respawn now calls
it immediately after reset_loadout, and the docstring on both says why that
order is the contract.
mode.on_command sat inside if player.alive:. It was called from
_handle_combat, which is gated on being alive, so a dead player's commands
never reached the mode at all and the buy window was closed to exactly the people
using it. It now runs in the queue drain outside that guard: what a dead
player's command may do is the mode's decision, not the loop's. Still inside the
drain, so the command's dt has already been spent from the budget and a
progress bar accrued from it is bounded by the same clock movement is.
The buy menu, in both clients
A held panel like the scoreboard rather than a mode you toggle into: it is
read during the freeze while the round is being decided around you, and a menu
you can leave up by accident is one you die behind. B holds it; the number row
buys while it is open, which is two jobs for one row and unambiguous precisely
because the menu is held — the other hand is on it.
Three row states, and they are three because they mean three things: owned,
buyable, out of reach. Collapsing the first two gives a menu that keeps offering
what you already have. canBuy comes off the wire rather than being a phase
check either client repeats, and a closed window says so instead of hiding
the panel — hidden, a player pressing B during a live round cannot tell whether
the key is broken or the window is.
Two things the native render caught that no test would have: the key column and
the item name touched ("2Shotgun") at a gutter sized for the digit rather than
for a column, and the scoreboard drew over the menu. Both are held panels, so
they rarely overlap in play — but the buy menu is the one being typed into, and a
panel you are pressing keys at must not be the one underneath. It is drawn last
now, and near-opaque, unlike the scoreboard: that one is glanced at while the game
carries on behind it, and this one is read.
Bots, honestly
Bots play defuse through the same bot_goal hook, and one thing had to move for
it to work at all: the action key is decided outside the fight-or-roam branch.
Planting is a commitment, and a bot that breaks off every time an enemy appears
never plants — measured, every round on the larger map timed out with the bomb
still in a carrier's hands until that moved out of the else.
With that fixed, bot-only matches on hd_crossing play the whole mode: plants,
defuses, a half-time swap and a match won. On hd_atrium they still do not
reach the sites — 128 cubes of ring is more than _steer's local avoidance
handles, so those rounds time out. That is a pathing limit on one map rather than
a mode bug (a human plants there fine), and expires_in keeps a stuck bot from
parking against a wall for the match.
Which clock
Three, and the choice is load-bearing in each:
- Plant / defuse progress → the player's
sim_time, accrued onecommand.dtat a time inon_command, so it is bounded by the same budget as movement and a client cannot plant faster than time passes. On the wall clock a stuttering client would plant more slowly than a smooth one, invisibly. - Round clock and bomb fuse → the room clock in
tick. The same argument_step_grenadesmakes: a planted bomb belongs to nobody, so pacing it by the planter's command stream would freeze the fuse when they disconnect. - Freeze-time buy window → the room clock, so a dead player can still buy.
tick runs after grenades and before history.record, so a round ending on a
tick has seen every consequence of the commands in it, and a round reset that
teleports everybody happens before the positions those bodies will be rewound to
are written down.
The mode HUD, in the native client
Top-centre, which is the one region of this HUD nothing else uses — the kill feed is top-right, health bottom-left, ammo bottom-right. It draws the score under its own label, a round clock or a bomb fuse, which side you are on, the state of each flag, and a bar for whatever is being held.
Everything is drawn from what the server sent and nothing is re-derived. The
score's label is scoreLabel off the wire rather than a match on the mode id, so
a mode that counts something new needs no change in the HUD at all. The fuse and
the phase clock are the server's own countdowns rather than local timers started
on an event, which is what keeps them right after a stall. The progress bar is
you.mode.progress, not a local one — a local timer keeps running through the
interruption that resets it server-side, through a stall, and through dying, each
of which is a bar that finishes while nothing happens.
Two collisions the unit tests could never have caught, both found by rendering
examples/hud_preview and looking:
- The score line and the bomb line overlapped. A 5×7 glyph is
7 * scaletall, so the8.0 * scaleline advance left one scale of gap and the two touched.paint_centeralready used9.0; now so does this. - The progress bar's label printed straight through the bar.
center_textplaces a glyph's top, so a label aty - 3.2uat scale0.8uran fromy - 3.2udown toy + 2.4u— across the thing it was labelling.
hud_preview takes defuse or ctf now, and the fixtures it draws are
deliberately the awkward moment in each — a planted bomb with four seconds left
while you are defusing it, a CTF with our flag taken and theirs dropped. A HUD
checked against the calm case passes with a layout that collides the moment two
things are true at once.
Objective events all share one banner rather than getting a treatment each: what
a player needs from "bomb planted at A" and "they took our flag" is the same
short sentence, briefly, where they are already looking. It sits above the
crosshair because the kill notice sits below it, and both landing in the same
second is the ordinary case — planting while somebody shoots you off the site.
Fx::RoundLive deliberately produces no banner: the phase clock already says
LIVE, and a banner that only repeats a readout is one people learn to ignore,
including on the events that matter.
A Fx::Half clears the kill feed. Its entries are coloured by whether they
were ours, and after the sides change every one from before is coloured for a
side that player is no longer on — which reads as the feed having got the kills
wrong rather than as the colours meaning something else now.
The same layer in the browser pane
panels/ModeHud.tsx, in the same place on screen and saying the same things, so
the two clients read alike. It draws from the wire the same way — scoreLabel
verbatim, the server's own countdowns, you.mode.progress rather than a local
timer — and the reasons are the same ones written up for the native client above.
One structural difference worth knowing: this one stacks in normal document
flow, where the native HUD advances a y by hand. The two collisions the
native version shipped with — a line advance one scale too tight, and a label
placed by its top across the bar it labelled — cannot happen here by
construction. That is not an argument that this file needs less care; it is the
reason it needed less of the same care.
objectiveNote lives in session.ts beside the class that consumes it rather
than in the component, because absorb uses it as the test as well as the
phrasing: returning null for anything that is not an objective event is what
lets one function decide both. A second list of the same fourteen kinds is
exactly the pair that drifts, and a kind with no phrasing renders no banner at
all — silent, and only on the event nobody happened to try.
__tests__/mode-wire.test.ts reads the same captured fixture the Rust test
does, apps/native-fps/tests/mode-wire.json. One artefact, two readers: it is
the only thing that can catch the two clients drifting from each other and from
the server at once.
The kill feed is a structured record, not a sentence
panels/KillFeed.tsx draws the browser pane's feed, and the thing worth knowing is
the shape of what it draws. KillNote (session.ts) carries killerName /
assisterName / victimName with a KillFeedTeam (CT | T | FFA) each,
the weaponId, and seven independent modifier flags — isHeadshot,
isWallbang, isThroughSmoke, isNoScope, isAirborne, isBlind,
isNutshot — plus isLocalPlayerInvolved.
It also still carries text. Both matter: the flags are what let the component
render a weapon badge and per-modifier icons and colour each name by that
player's team, and the pre-rendered string is what anything without a renderer
(a log line, an agent tool, the native HUD's simpler feed) can still read. A feed
that shipped only the sentence could not colour the two names differently; one
that shipped only the flags would force every consumer to learn the grammar of a
kill.
The split between what the server decides and what the client does is the usual
one, and it runs straight through this record. isThroughSmoke is server-side
— match.py resolves whether the shot crossed a smoke volume and puts it on the
wire as fx.smoke; the client only reads it. Letting a client decide that would
make a smoke worth exactly as much as the renderer that drew it.
isLocalPlayerInvolved, by contrast, is derived client-side in
session.absorb by comparing fx.killer / fx.victim / fx.assister against
the local playerId — which is right, because "am I in this line" is the one
question whose answer differs per recipient and needs no authority to settle.
mine is the same boolean under its older name, kept because the native HUD and
the older feed both read it.
Two bugs the live API found that the tests did not
Worth recording because both were invisible to everything else:
catalog()reported capture the flag and defuse as free-for-alls.teamswas declared only inside each mode'swelcome_state, sogetattr(mode, "teams", False)found nothing on them. The welcome said one thing and the catalog another, both plausibly, and the only place it showed was a lobby offering one scoreboard for a game with two sides.teamsis now aGameModeclass attribute and a test asserts the catalog and the welcome agree, per mode.use: ['KeyE']collided with a controls test's example key. Rebinding steals a key, sosetBinding(defaults, 'jump', 0, 'KeyE')began producing a diff foruseas well. The behaviour is right and the round-trip case covers it; the case about storing only what differs now uses a key nothing is bound to, so it measures one thing again.
The version probe, and why Extra could not cover it
divergence reports unknown event names and unknown fx kinds. It reports nothing
at all about an unknown key inside the mode blob, because the blob is a field
this build does declare and #[serde(default)] swallows the rest without a
word. An old client would join a capture-the-flag match, render no flags, score
nothing, and say nothing about why.
So the server stamps v into every mode blob and report_welcome compares it
against SUPPORTED_MODE_V, once. That is the only thing there is to compare —
which is also why tests/mode_wire.rs asserts the stamp is actually on the wire.
tests/mode-wire.json
A welcome and a snapshot captured out of a live defuse room mid-round with the bomb planted, not written by hand. Every other test of these types builds the struct it then asserts on, so all of them would pass just as happily against a wire shape the server has never sent.
This is the one seam where the two sides can disagree in silence: serde(default)
is on every field — it has to be, so an older server does not break a newer client
— and the cost is that a renamed key, a camelCase slip or a struct nested one
level differently all deserialize to a default with no error. The symptom is a HUD
drawing zeros over a round that is really happening.
Regenerate it by driving a room to a plant and dumping
state_payload() + snapshot_message(...) as {"welcome": …, "snapshot": …}.
Joining a mode
--game=dm|tdm|ctf|defuse on the client's command line, carried in the join.
Spelled --game and not --mode because --mode already means how the client
was launched (train, host, join, edit, ranked) — two different things that both
want the word.
The server ignores it when a room id is given, and that is the right way round: a room id names a match already in progress, and what mode it is running is the room's answer rather than the joiner's. An invite is an invite to a game, not a request to change it. Empty asks for the server's default, so a launcher that knows nothing about modes keeps working.
The square that froze on the viewport while spraying
The most-reported thing about the native client, and one geometry bug rather than the performance problem it read as.
A tracer is drawn as a square prism from the shot's origin to the pellet's
endpoint (effects.rs, push_beam). The origin is the server's
weapons.eye_position — exactly the camera. The prism's radius is 0.035
and the near plane sits at 0.05, further out than the beam is wide, so the
camera sat inside its own tracer; and because the volume pass draws both faces
(cull_mode: None) the prism's side quads straddled the near plane and
rasterized as one large blended quad centred on the view. A tracer lives 75 ms
and a rifle fires every ~90 ms, so while spraying it never went away. Marking
mine only lowered its alpha to 0.35, which made it translucent rather than
absent. The point-blank impact Ball did the same thing against a near wall.
Two things about the fix are worth keeping:
- It clips every beam, not only your own. Somebody shooting at you sends a
tracer that ends at your body and passes straight through your eye — the same
bug from the other end, which a
mine-only fix would have left in place. - It clips against the live camera in
vertices, not against the origin inshot. The eye keeps moving during the beam's 75 ms, so a strafe can walk the camera into a beam that was clear when it was born.
clip_from_eye returns up to two pieces, and that is the interesting case: a
round going past you enters the clear sphere and leaves it again, so collapsing
it to one piece would either erase a near miss or bridge it back through the near
plane. That doubles a tracer's 24 vertices to 48 in the worst case, which the
volume-buffer budget test in renderer.rs now exercises deliberately by firing
with the eye inside the pattern.
Separately, your own tracer starts 0.6 cubes down range so it leaves the barrel
rather than your face, and a pellet that stopped closer than that gets no tracer
at all — only its impact.
The ball over your hands (November). The same report came back in a new
shape: a lit tan disc over the support hand on every shot. It was never a
tracer or an impact — it is your own muzzle flash, drawn in the wrong place.
PropFit::muzzle was stored with the fit's offset already added and then drawn
through placement(), which adds it again, so the flash sat one offset back
from the barrel: toward the camera, over the hands, and several times the size
for being that close. The muzzle is now kept in the prop's own space, and
the_flash_sits_on_the_props_own_muzzle pins it against prop_model().
The flash is also drawn at half the browser's size with only its bright middle
kept (FLASH_DRAW_SCALE, and a discard in the shader's unlit branch): the fan
fades to black at its rim, and in an opaque pass that fade is a dark ball. Worth
knowing when the next "bullet on the viewport" arrives: the view model's flare
(viewmodel.rs) and the world's shot effects (effects.rs) are separate
systems, and a fix to one says nothing about the other.
The crosshair was drawing the wrong cone
HudView.spread fed the reticle's gap from the weapon's spread /
hipfire_spread. Those are the cone a weapon without a pattern uses. A
patterned weapon is aimed by apply_spray first and then scattered by the much
tighter residual_spread, and the server passes exactly that to resolve_shot
for every shot — so the rifle's reticle was drawn at 0.021 against a real cone
of 0.004, five times too wide, permanently. It reads as "this gun is inaccurate".
Nothing errored, because both are real numbers about the same weapon.
api::WeaponInfo::residual_cone already mirrored the server's rule and simply
was not being called.
Note the reticle still moves with a burst — recoil walks the camera through the same pattern the server aims by — so it follows the shots rather than opening around them. That is what makes a pattern learnable, and it is why this is a cone question rather than a spread-over-time one.
Crosshair legibility
Three changes, each of which was a bug first:
- Every element is drawn twice, once in near-black at
thick + 2 * outlineand then in colour. A one-colour reticle vanishes against any surface near its own brightness and the player finds out by missing. - The hitmarker is drawn around the reticle rather than replacing it, and
never by recolouring it. It used to
returnearly with an X in its place, and then to tint the reticle amber; either way, while spraying into somebody the thing you aim with changed under you about ten times a second. Both clients now draw the marker as its own layer outside the arms. - Elements are feathered (
soft_rect). The overlay pass has no MSAA and this painter has no texture, so the oldthickness.max(1.0)pixel-snap turned the centre dot into a hard square at the default 0.6.
outline, dot and alpha are settings and draw.crosshair.* cvars; dot is
now independent of style, so choosing a ring no longer costs you the choice.
Crosshair spec v1 and share codes
The crosshair is one spec, defined once in Python and drawn identically by both clients:
| Part | Where |
|---|---|
| Reference: spec, normalization, share code, geometry | backend/modules/hassault/crosshair.py |
| Browser port | packages/core/.../hassault/crosshair.ts, drawn by crosshair-view.tsx |
| Native port | apps/native-fps/src/crosshair.rs, drawn by Painter::crosshair_at |
| Agreement | crosshair-vectors.json (scripts/gen_hassault_crosshair_vectors.py), replayed by test_hassault_crosshair.py, crosshair.test.ts and tests/conformance.rs |
Fields. Style (cross, crossDot, dot, circle), size 1–12 and a
signed gap −5–20 (both in halves), thickness 0.2–3 and outline width 0–2 (in
tenths), opacity 0.15–1, centre dot, T-style (no top arm), dynamic, and a
colour: one of six named colours or a custom #rrggbb. A custom colour may be
any hue but not dark — one whose Rec. 709 luma is under 90/255 is lifted towards
white, in integer arithmetic so all three ports land on the same bytes.
normalize quantizes every field to what a code can carry. Both clients
normalize what they read from the settings bag before drawing, so the picture a
code produces is the picture its author saw. Every quantization is
floor(x * k + 0.5) in f64: Python's round is banker's rounding, Rust's rounds
half away from zero, and an f32 turns 1.45 into 1.4500000476 — any of those
would give the two clients different codes for one slider position.
Share codes look like HXC1-0400A-1G80R-1NM00-00008-P: a version byte, the
fields in a fixed order, a CRC-8 (polynomial 0x07) over all of it, in Crockford
base32 in groups of five. Decoding is forgiving about what a paste does (case,
spaces, dashes, O/I/L for 0/1) and strict about the rest. A bad CRC or an unknown
version is refused with a reason (prefix, char, short, crc, version).
Bytes after the known fields are ignored, so a later writer can append a
field under the same version and an older reader still decodes the rest; the
version only moves for a layout an older reader would misread.
Geometry is one pure function, crosshair_rects(spec, cone_gap_px, hud_unit): rects (and, for the ring, annuli) around the centre, the outline
layer first, each with its final opacity. The client picks colour by layer and
nothing else. The unit is the native HUD's — hud_unit(height, hudScale), whole
pixels per 360 of height times the HUD scale — computed from the window height
natively and from the game view's height in the pane, so a code is the same size
in both. The cone opens the gap by cone_gap_px(cone) = cone × 130 × unit, the
native client's old spread × 260 × u × 0.5.
dynamic opens the arms with the cone the next shot will use
(residualSpread); off draws the gap alone. Either way the shot goes where the
cone says — it changes what you are shown, never where rounds land. The pane used
to add its own movement and air bloom, which the native client never drew and the
server never applied; it is gone, and the served movement cone (P3) is what will
put movement back, in both.
The generator. The pane's main and pause menus have a Crosshair page: the
live reticle over three surfaces (sky, sandstone, shadow — the contrast cases),
every field, a preview spread and a hitmarker toggle, presets, and the code to
copy or paste. Applying a code writes the same rows the controls write, so a
pasted crosshair is the player's crosshair in the native client too. The native
pause menu's Crosshair page has the same fields, a preview panel drawn by the
HUD's own painter, preset stepping, and paste/copy code. Natively the
clipboard is the OS's own tool (powershell Get-Clipboard / clip, pbpaste /
pbcopy, wl-paste / xclip) on a worker thread (clipboard.rs) — no
clipboard crate, for the reason console.rs gives, and no frame waits on it.
Mipmaps, anisotropy and supersampling
The world used to shimmer, and the cause was that no sampler uploaded mips at
all — one level, mipmap_filter: Nearest, no anisotropy. The map's UVs are in
cube units, so a floor down a corridor covers hundreds of detail tiles per pixel
row and the sampler picked one of them per pixel, near enough at random. That
boils as you walk.
mipmap.rs builds the chains on the CPU, which is possible here because every
texture this client uses is already CPU-side — the detail tile is drawn by
draw_tile, character and prop maps arrive as decoded RGBA out of a glTF. So
none of the GPU machinery a mip generator usually needs (a blit chain or a
compute pass, plus RENDER_ATTACHMENT on every texture) has to exist.
The colour-space rule is the whole reason it is one shared function, and both ways of getting it wrong are silent and look like a lighting bug:
| Texture | Format | Space | Getting it wrong |
|---|---|---|---|
| detail tile | Rgba8Unorm | Linear — it is a multiplier, not a colour | decoding as sRGB dims every level below the first; the world darkens with distance and reads as fog |
| character / prop maps | Rgba8UnormSrgb | Srgb — decode, average, re-encode | averaging raw bytes comes out darker, worst in the mid-tones; a character dims as they walk away |
Space has no Default for that reason: the caller states which it has. Alpha is
coverage and is averaged linearly in both cases — running it through the transfer
function is the third version of the same bug and it eats soft edges.
anisotropy_clamp > 1 requires mag_filter, min_filter and mipmap_filter
all Linear. Any of the three left on Nearest is a validation error at
sampler creation — a hard stop on the first frame, not a softer picture — so
mipmap::ANISOTROPY lives next to the chain builder and the two changes are made
together.
render_scale now goes to 2.0, which is supersampling: the world is drawn
larger than the window and the blit's existing linear filter averages it down. It
needed no renderer change at all — create_scene already allocated at
width * scale — only the clamp, which makes it the cheapest real image-quality
knob here, and the only anti-aliasing that touches shader aliasing and alpha
edges. It did make an oversized allocation reachable, so create_scene now
clamps both axes together against device.limits().max_texture_dimension_2d;
without that, 2.0 on a 4K display asks for 7680×4320 and some adapters refuse it
with a validation error rather than a picture.
Two smaller ones: WindowEvent::ScaleFactorChanged is handled, because winit does
not guarantee a Resized alongside it and the surface is configured in physical
pixels — dragging the window to a monitor with a different scale used to leave a
stale swapchain, which reads as "the game went blurry on my second screen". And
hassault.video.hudScale multiplies the HUD's derived round(height / 360) unit,
which is a whole-pixel step and so lands on the same value across wide resolution
bands.
A metal with nothing to reflect renders black
The browser needed one thing the boxes never did. A metallic surface in a physically-based renderer has no diffuse response at all — it only reflects — and the hassault scene is lit purely by analytic lights, so every prop came out a silhouette. Measured on the SVU with the game's own rig: mean luminance 3.5/255 and 93% of its pixels near-black with no environment, against 41.2 and 21% with one. It looks exactly like textures that failed to load.
createPropEnvironment builds one, and three details in it each cost a debugging
round:
- The gradient is the hemisphere light's own two colours, not a studio box.
RoomEnvironmentis the usual answer and it is wrong here — it would light the gun in your hands from a room that is not the map you are standing in, and a weapon lit differently from its surroundings reads as pasted on. That is the same failurelighting.wgsl.incexists to prevent between the two clients. - An equirectangular map is twice as wide as it is tall, and it must not be
tiny. Both were wrong first time and neither failed: a 16×32 portrait source
drove
PMREMGeneratorto a degenerate 336×16 output that rendered pure black, indistinguishable from having no environment at all. A metal sphere lit by it had zero non-black pixels. 128×64 prefilters to a sane pyramid. - It is prefiltered. A raw texture assigned as an environment ignores roughness, so a matte grip comes out as shiny as a barrel.
- Row 0 is straight down. A
DataTextureuploads withflipYoff, so row 0 isv = 0, and three'sequirectUvputsv = 0at the nadir. The gradient was first written sky-first and lit every gun from below: a sphere under it measured (89, 92, 100) on top and (159, 175, 207) underneath. It now runst = 1 - y / (H - 1), andenvironment.tsrowHeightis the same inverse, pinned byenvironment.test.ts.
PROP_ENV_INTENSITY is 1.55 because that is the scene's hemisphere intensity and
the environment encodes its colours at 1.0 — the factor that puts the two on the
same footing, not a number picked because it looked better. Nothing clips at it,
or at 2.2: the headroom is real and the weapons are simply dark.
It is applied to the view model only. On a modelled map, scene.environment
is the map's own sky and ground (see "A modelled map's sky is its image-based
light"); a cube map has none. This gradient exists to stop the gun rendering as a
silhouette, not to relight the game.
The native side is a third pipeline
prop.rs is a separate parser from character.rs, and prop.wgsl a third
shader beside shader.wgsl and skin.wgsl. Both splits come from the same fact:
a weapon has textures but no bones.
- The operator is skinned, so its vertex positions are in skin space and the node hierarchy reaches them through the skinning matrices — reading positions raw is correct there.
- A weapon is not. Everything the converter computed lives in node
transforms, and reading its positions raw yields a pistol thirty-five times too
large in the wrong place. So
prop.rswalks the node tree and bakes each node's world matrix into its vertices, with the inverse transpose for normals. Getting this wrong in the direction of doing nothing is silent: the GLB loads, the primitives are there, the textures decode, and the weapon is simply enormous. local_matrixreads a node's transform either way glTF spells it. The format allows a matrix or a TRS triple and one file may mix them —GLTFExporterwrites a matrix for a node carrying a rotation and TRS for one that does not — so reading only TRS drops the scale off every matrix node.
A prop could have been pushed through the character pipeline with one bone at identity. That costs eight bytes a vertex, a storage-buffer binding and a bone array on geometry that never deforms; the extra pipeline is cheaper than the pretence.
Two things the prop shader does differently from the world's, both deliberate: it
is always fully lit (a prop is a hand's width from the eye, so a shadow it
received would cross an edge as a hard flicker across the whole model — and the
browser does not shadow it either, since three only shadows a mesh with
receiveShadow), and it applies no fog (it is roughly a cube and a half
away, where every fog curve worth having is still the identity).
The props get a third camera uniform. The prop's vertices are in its own
model space, so the view model's pose is folded into both matrices: into
view_proj to place it on screen, and into light_transform so a model-space
normal reaches world space through the same pose. Feeding the second without the
pose gives a weapon whose shading ignores every kick, bob and sway the first one
applies — lit as though it never moved. That uniform is forty floats, not the
thirty-six it is easy to count; wgpu rejects a short one at draw time naming both
byte counts, which makes it the rare mistake here that fails loudly.
The GLBs are compiled in with include_bytes!, like the operator. Every prop
stays resident once uploaded, and all three are parsed on a background thread at
startup (prop::preload) — which is a correction, not a refinement. It used to
be one resident prop parsed inline on the frame the player pressed a number key,
on the argument that a re-upload is imperceptible. The upload was; the parse in
front of it was not — 57–110 ms of frame thread per swap, measured in a release
build, dominated by decoding the webp maps. And because dropping the prop dropped
the parse with it, switching back to a gun paid it again, so 1–2–1 cost three
stalls. Pressing a weapon key visibly froze the game, which is what it was
reported as. sync_prop now parses nothing: it drains whatever the preloader has
finished, uploads that, and picks a weapon with a hash lookup. A weapon whose
prop has not landed yet keeps its boxes and is retried, which is the same
fallback a weapon with no prop at all has always used. This is the lesson
Squad::load already documents for the operator's fourteen textures — decoding
them mid-match is a visible hitch — arrived at a second time.
Looking at it
The unit tests check properties a wrong-looking weapon would still satisfy: the GLB parses, the bounds are right, the normals are unit length, the shader validates. None would catch one rendered inside out, unlit, or with its base colour in the wrong slot. Those are properties of a picture, so there is one:
cargo run --manifest-path apps/native-fps/Cargo.toml --example weapon_preview
It prints coverage and mean luminance alongside the PNG, which is what makes it checkable without eyes on it — the likeliest failure in this pipeline (a base colour sampled as linear, a normal left at source scale) renders a weapon that is there and dark, so "something was drawn" is not the assertion worth making.
The Remington's GLB carries a loose 12-gauge shell as a second material, sitting where the artist left it — so the shotgun draws with a shell floating beside it. It is a mesh in the source model rather than anything the converter did, and the fix is to drop that object before export.
Skin packs: skins that are not in this repo
backend/modules/hassault/skinpacks.py.
SKIN_CATALOG is a Python list, which is the right shape for the skins the game
ships with and the wrong shape for every skin after them. Adding one meant
editing the backend, a player could not have a skin the node's own source did not
name, and a skin somebody else made had nowhere to live at all.
A pack is the unit that fixes that: a zip carrying a pack.json and its
textures, fetched to the user's own node and unpacked under
$HORRIBLE_DATA_DIR/hassault/skins/<pack id>/. Nothing is bundled — the same
rule that keeps AssaultCube's maps on the user's own install, SearXNG supported
rather than shipped, and karaoke songs fetched rather than committed. The catalog
the rest of the module reads becomes built-ins plus whatever is installed.
{
"id": "neon-collection",
"name": "Neon Collection",
"version": "1.0.0",
"license": "CC-BY-NC-4.0",
"attribution": "SVU-A sniper rifle by Luiz Reis (https://www.artstation.com/izreis)",
"skins": [
{
"id": "neon_assault_pulse",
"name": "Pulse",
"weaponId": "assault",
"rarity": "covert",
"collection": "Neon Collection",
"baseColor": "#22d3ee",
"accentColor": "#f472b6",
"patternType": "custom_art",
"description": "...",
"texture": "pulse.png"
}
]
}
| Route | What it does |
|---|---|
GET /api/hassault/skins/packs | What is installed |
POST /api/hassault/skins/packs/install | {url, sha256?} — fetch and install |
DELETE /api/hassault/skins/packs/{id} | Remove one, and its files |
GET /api/hassault/skins/packs/{id}/files/{name} | Serve a texture |
GET /api/hassault/skins/catalog returns built-ins and pack skins together. A
pack skin carries two extra keys, packId and textureUrl; a built-in carries
neither, which is what tells a client there is nothing to fetch rather than
something that failed to load. textureUrl is built by the backend, not by
each client — three clients composing that path is three chances to compose it
differently.
texture is optional, and that is what makes a pack useful today: without one
the skin renders exactly as a built-in does, its two colours distributed across
the weapon's parts by patternType. Neither client draws a weapon texture yet —
the procedural props have no UVs and the native view-model pass has no sampler —
so the distribution half landed first and the rendering half is the next slice.
A pack has to say what its art is, and who made it
license is required and attribution is required for any licence whose
name starts CC-BY (however it is spelled — CC BY 4.0, cc-by-nc-4.0 and
Creative Commons Attribution 4.0 all count, because refusing a pack over
punctuation pushes authors toward writing something vaguer that passes).
This is not paperwork, and the case it exists for is in this repo. The SVU-A
rifle under assets/horribleAssault/svu-a-sniper-rifle/ ships its own
readme.txt inside its source zip saying it is CC BY-NC 4.0 by Luiz Reis,
naming the exact credit line to use and offering a separate commercial licence
on request — while the directory's provenance table had it as GPL by somebody
else. Those cannot both be true, and CC BY-NC cannot be relicensed as GPL by
anyone but its author: GPL permits commercial use and BY-NC forbids it.
A pack format that let the licence field be omitted would have carried that
mistake onto every machine that installed the pack, with nothing in the
installed directory to notice it by. So a pack with no license does not
install, the credit line is stored verbatim (the licensor writes the
sentence; a schema that reformatted it into a name and a URL would be failing
the condition while looking tidier), and both are copied down onto every skin as
well as the pack — because a player looks at a skin in the armoury and nobody
opens a list of installed packs to find out who made the gun they are holding.
Six rules, every one of them silent if broken
- A pack may not shadow a built-in. Refused at install time, not filtered out
when the catalog is assembled: a pack that installed and then had half its
skins quietly disappear is the worst of both, since it is on disk, it is
listed, and it does not work. Same reasoning as
hd_*map names resolving before the AssaultCube install — two catalogs that can each define one id means the same name renders differently depending on what somebody installed, and it reads as a rendering bug rather than a collision. - A zip member's path is not to be trusted.
../../.ssh/authorized_keysis a legal name inside a zip andextractallwrites it. Every member is resolved against the destination and refused if it lands outside, andtexture_pathresolves again on the way out — a symlink planted by a hostile pack points wherever it likes regardless of what its name looks like, and onlyPath.resolveanswers that. - The size budget is checked before extracting, from the declared sizes. A 40 KB zip can declare 40 GB of contents. Checking as you go means finding out when the disk is full, which is the lesson the llama.cpp downloader already learned.
- A pack lands via
.partand a rename, and a failure part-way takes the staging directory with it. A half-extracted directory scanned as installed is a skin with half its textures and nothing to say so.installed_packsskips.partdirectories silently — those are downloads in flight, and reporting one as broken would report a normal state as a fault. - A digest mismatch aborts and writes nothing; a pack fetched without one
installs as
verified: falserather than as probably fine. The provenance is written into the pack's own manifest, so a directory copied to another machine carries where it came from. - The fetch goes through
browser.fetch, not a barehttpxcall. This is a route that takes a URL from a user and makes the server request it, which is the definition of an SSRF sink; that module is the single place the policy lives, and a second copy of the redirect loop is a second guard to keep in step.
Two smaller decisions worth keeping. A zip made by right-clicking a folder has
everything one directory down, so the manifest is looked for at the root or
one level in and the members are flattened relative to it — otherwise "it works
if you zip it the other way" becomes something a user has to know, and a
texture naming a bare file name would resolve in one layout and not the other.
And a file type a pack has no business carrying (.dll, .exe) is a refusal,
not a skipped file: silently ignoring it installs the pack anyway, under a name
nobody looked at.
The catalog scan is cached for 30 seconds, because it is consulted on every drop
roll, inventory read and trade-up, and a directory walk plus a JSON parse per
skin is not something to do inside a match tick. skins.invalidate_pack_cache()
is what makes an install visible immediately instead of up to half a minute
later; every route that changes what is installed calls it.
The skin has to be visible before it is equipped
WeaponSilhouettes.tsx is the armoury's product shot: the inventory card, the
catalogue tile and the inspect viewport are one component at three sizes, and it
is the only place a skin is seen before the decision to equip it. Three of the
economy's numbers were being carried on the card as text while the drawing
ignored them:
patternTypedid nothing at all. The<pattern>in<defs>was never referenced by a single shape, so a Camo, a Fade and a Solid drew as the same gun. Each type now paints an overlay of its own — blotches for camo, mottling for patina, a line motif for custom art, vertical dye for anodized — and a fade is carried by the gradient instead, since a repeating overlay on top of a fade is a second pattern nobody asked for.patternSeedonly went into an element id. A seed is what makes two copies of one skin different items; it now rotates the finish, phases the pattern and places the wear, so seed #4 and seed #822 are visibly not the same gun.floatValuewas a slightly lower opacity. Wear is scratches: a small deterministic generator, seeded by the pattern seed so an item's scuffs are that item's scuffs on every render, drawing nothing below 0.07 — which is what Factory New means — and a couple of dozen marks on a Battle-Scarred one.
The silhouettes themselves went from a handful of rectangles to real parts: slide serrations and a rail on the pistol, an over-and-under barrel with a ribbed pump on the shotgun, both scope bells and a turned-down bolt on the sniper. Weapon furniture — polymer, steel, bore — is deliberately not themed, because a stock that turned white under the light theme reads as a different weapon rather than as a themed panel; the painted surfaces take the skin.
WeaponViewModel.build got the same treatment in 3D, and for the same reason:
these are still boxes and cylinders (see
Licensing), but a magazine
drawn as two raked segments has a visible curve, and a trigger guard drawn as
three bars is a loop with a hole in it. paletteFor also grew branches for
patina and custom_art, which had been falling through to the solid
arrangement — so a Case Hardened and a Slate were one object in two colours,
with the armoury card promising otherwise.
The post-match card belongs to the pane
PostMatchDebrief is an overlay inside the pane, at a z-index that means
something relative to its siblings (BootOverlay at 10, MatchCompanion at 100,
this at 200). It was position: fixed at zIndex: 9999, which is positioned
against the viewport rather than against whatever contains it — so a card
belonging to one pane's match covered the entire application, taskbar and
workspace strip included, with nothing able to draw over it.
Two rules keep it from coming back, and both matter because the poll behind it runs every 1.5 s:
- A dismissal sticks locally, not only on the server. The poll's request is
usually already in flight when the button is pressed, so clearing the state
alone lets the older response put the same card straight back; and if the
dismiss_summaryPOST fails, or a workspace switch remounts the pane, the server still has the summary and hands it over again. The pane remembers thetimestampit closed, so the same match can never be shown twice. - It never draws over live gameplay. A summary is only ever produced when a native match exits, but the card outlives the match that made it, and one left over from an earlier game would otherwise sit on top of a browser match still being played.
The card is for a match played in this pane session
The remembered timestamp used to start at 0 on every mount, which means "no match
has ever been closed" — so any undismissed row reopened the card the moment the
pane appeared. A failed dismiss, or simply the last match of a previous session, was
enough; docking, undocking or switching workspaces brought it back. The pane now
asks the server once on mount what is already there and treats all of it as seen,
and suppresses the summary half of the poll until that answer lands, because
otherwise the first interval can win the race and show the stale card exactly once.
Deliberately not clock arithmetic. played_at is the backend's time.time() and has
no relationship to the browser's clock, so "newer than now" would either swallow a
real card or replay an old one depending on which way the two machines were skewed.
A panel that is read may not be translucent
The native card fills its body with its own opaque CARD_BG, not the shared
menu::PANEL_BG, which is 0.96. Four percent of a bright glyph sounds like
nothing. It is not: the killfeed, the multi-kill banner, the floating damage
numbers and a held scoreboard all sit behind that card, and every one of them
came through it at 7–12% Weber contrast against the panel. Brightness is not
what gives it away — structure is, and the eye finds readable words at a
contrast where it would never notice a shade.
Its own constant rather than a bump to PANEL_BG, which is shared with the pause
menu and every HUD panel that never asked for this; the buy menu already sets its
own alpha, so a panel choosing one is the established shape here. The rule both
follow: a panel that is glanced at may be translucent, a panel that is read may
not. The scoreboard is looked at during a lull with the game carrying on behind
it; these are panels somebody stops to read.
Alongside it, a modal suppresses the scoreboard rather than covering it
(app.rs, where the HudView is built). Two reasons, and the first is the one
opacity cannot fix: the scoreboard is wider than the card, so its edges stick
out past both sides where only the scrim attenuates them. The second is that it
makes the claim already written beside the summary's draw call — "the card is the
only thing on screen once it is up" — true rather than aspirational, and it hands
back the largest single block of overlay vertices (34.2k → 26.6k, a fifth of the
budget) at the one moment nothing can read them.
Both are pinned by nothing_behind_the_card_can_be_read_through_it, which asks
the question geometrically — is every sampled point of the card body covered by an
opaque triangle? — rather than asserting the constant back at itself. It samples
the corners as well as the middle, because a fill that covered the centre and not
the corners would pass a single-point check and still leak a killfeed into the
card's bottom-left. It also asserts something translucent is still drawn, since
an overlay opaque out to the window edge would not be a fix but a different bug.
Was this a match at all?
The other half of the same complaint — the card came up for sessions nobody would call a match. Two independent causes:
- A row was written on every leave.
channel._leave_anyfiles whateverresult_forreturns, so opening the pane, deploying and pressing Menu produced a match. - That row said VICTORY.
result_forscored a player againstmax(others, default=-1), and alone in a room0 >= -1. The native client's own card had the identical bug, arrived at independently by the same arithmetic (app.rs,build_summary).
results.is_recordable is now the one place the rule lives: somebody to play
against, and something that happened — an opponent (bots count, the same call
result_for makes about won), and at least one kill, death, point of damage, or
objective.
won and mvp are gated on it, channel._record_result refuses to write a row
without it, and the native card says NO CONTEST rather than ranking a session
that had nobody in it.
It is deliberately not a quality bar. A match you lost 0–15 is recordable and
should be — XP_BASE exists precisely because turning up counts. What is excluded
is the empty session, not the bad one.
Two details are load-bearing:
opponentscounts everyone you ever shared the room with, viaMatchPlayer.faced_opponents, not who is still standing in it.result_forruns at leave time, so a host who kicks the bots before quitting would otherwise file a real match as an empty one.- The native predicate's third term differs on purpose. The node tests
damageDealt > 0; the native client teststally.hits > 0, because assummary.rs's header explains it cannot reproducedamage_dealt(the wire's hitmarker is uncapped, the server's counter is capped at the victim's remaining health). They agree in every reachable case, and__tests__/result-vectors.jsonis a shared fixture replayed bytest_hassault_results.pyandconformance.rswhose generator refuses to write a case where they disagree.
The fourth term, and why three were not enough
Kills, deaths and damage all describe a fight, and in defuse the fight is not the game. A player who planted the bomb twice, was traded for both times by somebody else's shot and never landed one of their own has zero of each — and used to file as "not a match": no row, no card, no XP, for the player who decided two rounds. The mode most likely to produce that player was the one the predicate had never been updated for.
So objectives — bombs planted or defused, flags captured — is the fourth term.
Three things about it are deliberate:
- It rides in
you.objectives, besidekills, not insideyou.mode. All three modes replace the mode blob wholesale, so a counter living in there depends on each of them remembering to pass it on, and the one that forgot would silently file a defuse specialist as having done nothing. opponents > 0still gates it. Standing on a site until the bar fills is something you can do in an empty room. An objective is evidence that something happened, never evidence that there was anybody to have played against.- It is the opposite arrangement from
damageDealt, and the contrast is the rule. The native client cannot reproduce damage, so it does without it; it cannot derive an objective either —bomb_plantedandbomb_defusedcarry noby— so it is served the number instead. A figure the client can count exactly, it counts; one it cannot, it is told or it goes without. Nothing is approximated. That also means the objective term needs no care in the shared fixture: unlikehitsversusdamageDealt, the two sides read the same number.
What a row records, and what cannot be recovered later
Two columns arrived with the modes, both through _ensure_column because
CREATE TABLE IF NOT EXISTS never adds one to a table that already exists:
mode, backfilling todm. Not a placeholder — before modes existed a room could only be deathmatch, so that is what those rows genuinely were. Without the column a 5–3 in rounds and a 5–3 in kills are the same two numbers and nothing else in the row tells them apart, which is unrecoverable after the fact rather than merely missing.objectives, so the card can show what earned the XP rather than only the total.
XP gained two terms with them. XP_PER_OBJECTIVE is worth six kills — the
same argument XP_PER_100_DAMAGE makes, taken to the mode that needs it most:
paying the player who planted under fire by their frag count describes a different
game than the one the scoreline showed. (outcome_for weights an objective at
three kills for MVP; XP weights it higher because MVP is a comparison within a
team and this is not.) XP_ROUND_WIN is deliberately small — winning already
pays XP_WIN, and a large per-round term would make a 5–4 grind worth more than a
5–0, rewarding length rather than play. It is asked of mode.rounds_won, never
read off room.scores, because scores counts kills in deathmatch and reading it
directly would pay a round bonus once per frag.
Both cards show it. The native card substitutes the objectives figure for
OPPONENTS rather than adding a seventh cell — the grid is two rows of three and a
third row of one would sit exactly where the leave button is, and OPPONENTS is
the cell it replaces because that figure exists to explain NO CONTEST, which a
card showing objectives is by construction not. The dashboard card grows to five
columns instead, and labels the number per mode (Captures, Plants/Defuses),
because three captures and three defuses are not the same achievement.
Ranked stays deathmatch, and the absence is enforced
HassaultReferee.join takes no mode parameter, and that is the decision
rather than a leftover. A rated round-based mode is a different project, not a
flag: defuse is scored by round, a round is settled between two full sides, and
a server-hosted room people join and leave one at a time has no such thing to
report. The referee would have to hold a side together for a whole match, decide
what a leaver does to the round in progress, and report a per-round result the
store has no shape for — none of which becomes true by accepting a string.
Leaving the parameter out is what makes adding it a decision somebody has to make
on purpose, instead of discovering the problem from a ladder full of half-played
rounds. mode is written into the ruleset all the same, so the day it stops being
one value the rows already say which.
A server-refereed result (ranked.py) is not gated by any of this. That
predicate exists to stop this node filing its own empty sessions; a result the
referee reported is the referee's call.
Identity: sign in, enlist, play
It is a game, so it has a front door. Opening the pane runs a boot sequence — the map assembles itself, then you sign in, then you deploy — and there is no way past it: no account, no play, enforced on the backend and not just in the UI.
boot.ts owns those transitions and nothing else — no React, no three, no fetch —
so it is unit-testable in a core vitest run, which has no DOM.
Note the arrow back. deployed is a flag the panel can clear, not a one-way
latch, because a game you can only enter is a game you have to close the pane to
leave.
Account data lives on the game server
A node's app.db was where an account's skins, level and settings lived, so
they were whatever the machine you sat at held, and the standalone web client,
which has no node, had none. The game server now keeps them per account
(backend/games_server/hassault_account.py, migration _m12_hassault_accounts,
cap hassault_account), under /api/hassault/account/*:
| Route | What it is |
|---|---|
GET/PUT /settings | account-scoped settings only; machine keys and unknown keys are dropped |
GET /progression, /drops | level, XP and drops, all derived from the ledgers |
GET /inventory | the node's SkinInstance.to_dict shape, so clients cannot tell |
POST /claim_drop, /equip, /tradeup | the node's three writes, with the same rules; /equip takes a side |
POST /unequip, GET /cosmetics | a side's skin off; the account's look (see "Sides, agents and visible skins") |
POST /import | one machine's local history, once |
Ledgers, not counters. Level is a SUM(xp) over hassault_xp_ledger, which
server-hosted matches write (hassault_rooms calls grant_match_xp, keyed per
session so a retry pays once). A drop inserts its hassault_drop_claims row
before the item exists, so two racing claims both pick the same level and one
INSERT loses. Every item has a row of provenance in hassault_item_events, and a
tradable_after a week out, ready for trading (P9).
An import is self-reported, so it is kept apart. The first time a signed-in
node finds the service (account_sync.active_account) it sends its inventory and
every match's XP. The server inserts the (account, node) row first, so a repeat
is a no-op; skips instance ids it already has (a copied database); marks imported
items origin = 'import' and never tradable; and pre-claims the levels the
imported XP reached, so no drop is ever paid for a number a node wrote down about
itself. A marker row in the node's hassault_exports stops it asking again.
The node proxies. Its /skins/inventory, /equip, /drops, /claim_drop
and /tradeup forward to the service when the node is signed in and the server
has it, and answer from app.db otherwise, so a LAN or offline node still works.
The native client's finishing drop (_watchdog_game_process) is skipped for an
account the server keeps: it was a free roll for a match the node scored itself.
Settings follow the account. On startup and every sign-in
(server_auth.schedule_enrollment calls account_sync.schedule_sync) the node
pulls the account's settings into its bag, the server's copy winning, or seeds an
account that has none from this machine. Each later write to a hassault.*
account key is pushed up in the background (settings/routes.py →
account_sync.push_setting); a settings write never waits on a server. Scope
comes from settings_schema.py, so a GPU choice never travels to another
machine. The native client needs nothing for any of this: it reads the node's
bag. The standalone web client has no node, so once signed in its settings store
persists straight to the account (setSettingsBackend in core settings.ts,
bindSettingsToAccount in apps/assault-web/src/auth.ts).
Credits, cases and StatTrak
Credits are earned only: never bought, never cashed out, never sent to
another account. They live on the game server (games_server/hassault_wallet.py,
migration _m15_hassault_wallet, cap hassault_wallet) and the node only proxies
them (/api/hassault/wallet, /wallet/keys/buy, /wallet/cases/open). A node
that cannot reach the service answers 409 rather than inventing a balance.
The balance is a sum. hassault_wallet_ledger holds one row per credit or
debit, and UNIQUE(account_id, kind, ref) makes every earning idempotent on what
paid it. A BEFORE INSERT trigger refuses any row that would take a balance
below zero, whichever code tried to write it, and every spend runs under
BEGIN IMMEDIATE, so two spends cannot both read the same credits.
| Earned from | ref | How much |
|---|---|---|
| A server-hosted match | match:<id> | MATCH_BASE + MATCH_PER_KILL per kill + MATCH_WIN; a quarter with no human opponent; at most DAILY_MATCH_CAP a UTC day |
| Each level reached | level:<n> | LEVEL_REWARD |
| The week's first win | week:<yyyy-ww> | WEEKLY_WIN_REWARD, and a case |
Cases (cases.py, served at /api/hassault/cases by node and server) hold
their weapons' skins plus every Special, at odds that are CASE_WEIGHTS
renormalised over the rarities the case holds, so a case missing a rarity keeps
no share for it. Cases and keys are rows in hassault_items (kind = case /
key), so trading (P9) can move them like skins; the inventory route lists
skins only. Keys are the sink: KEY_PRICE credits each. Opening consumes
the case and a key and makes the skin in one locked transaction, rolled with the
server's SystemRandom, with a 10% StatTrak chance and every step logged in
hassault_item_events.
StatTrak counts human kills in server rooms. MatchPlayer.human_kills keys
them by side:weapon; at match end the referee adds them to whichever skin was
equipped for that weapon on that side, if it carries a counter, through
hassault_stattrak_ledger keyed (match, item), so a match counts once.
The browser shows this as the armoury's Store tab (panels/CaseStore.tsx):
the balance counting toward each change, keys, the cases you own, the odds per
case, the ledger, and a reel that is built around the result the server already
rolled and only slides to it. The native client has a STORE menu page
(menu.rs Page::Store), whose requests run on a worker thread so the frame
never waits on one.
Trading and the market
The first place an item leaves the account that earned it
(games_server/hassault_trading.py, migration _m16_hassault_trading, cap
hassault_trading), so most of it is reasons to refuse.
- Who may trade (
eligibility): a real account, not a guest or a bot,MIN_ACCOUNT_AGE(7 days) old, at levelMIN_LEVEL(5), withMIN_SERVER_MATCHES(10) server-hosted matches. Every reason it may not is returned, so the client can say all of them at once. - What may move: owned, in state
owned(so not listed or consumed), past itstradable_afterhold. Imports have no hold date and never move; drops, case openings, trades and purchases set one a week out. - To whom: an accepted friend (
friendships), or anyone holding your trade link token (/account/trade/link; rotating it revokes every old copy). The same rule decides who may see your tradable items (/account/trade/partner/{id}). - How: an offer is fixed once made. The recipient accepts, which arms the
confirm
ARMING_DELAY(10 s) later, then confirms. The swap re-checks every item and the sender's eligibility underBEGIN IMMEDIATE; anything changed since the offer (an item listed, consumed or traded) marks the tradefailedand moves nothing. Moved items lose their equips and get a fresh hold. - The market sells for credits only. A purchase debits the buyer the price,
credits the seller the price less
MARKET_FEE(10%, at leastMIN_FEE), and burns the fee: no account receives it, andhassault_sinksrecords it. A listed item is in statelisted, so it cannot be equipped, traded or listed again; a partial unique index stops two live listings of one item. Prices runMIN_PRICEtoMAX_PRICE, and/market/historyserves past sales. - Rate limits:
OFFERS_PER_DAY(30),PENDING_PER_PAIR(5),MAX_LISTINGS(50),PURCHASES_PER_DAY(100).
The node proxies all of it (/api/hassault/trade*, /trades*, /market*), and
its public market reads only run for an account already known to be on the
service. The browser shows it as the armoury's Trade & Market tab
(panels/TradeMarket.tsx), with the arming countdown as a display of armsAt
only; the native client has a MARKET menu page beside STORE.
Whose rows these are
Every account-keyed row on a node (matches, skins, drop claims, rating, ranked
history) is filed under results.current_account_id(): the signed-in account's
id, or local_player when nobody is signed in. It is the only spelling, and
server_auth.signed_in_account_id() is the only read of the id.
It needed one because three call sites read signed_in_account()["account_id"],
a key that dict never has, so everything recorded while signed in landed under
local_player. The ranked tests mocked the same wrong key, so they agreed with
the bug. To give those rows back, the first account to sign in on a node adopts
every local_player row, once (results.adopt_local_rows):
- A marker row in
hassault_adoptions, keyed by the stand-in, is inserted before anything moves. Two requests racing here both try that INSERT and only one of them moves rows, the same shape ashassault_drop_claims. - Collisions are
UPDATE OR IGNOREd: if the account already has a rating, or already claimed a level, its own row wins. - A second account signing in later gets nothing. By then the rows have an owner.
/ranked/calibrate also stopped taking accountId from the request body, which
let any caller write a rating row for anybody. Since P7 it is retired outright
(410): a rating moves only through a rated duel on the game server (see "Duels
and the rating").
The native HUD
apps/native-fps/src/hud.rs is one vertex stream and one draw. OverlayVertex
is position, colour and a uv whose sign carries a mode: negative is a solid
fill, -2 is a grid pattern computed in the fragment shader (cell size in
uv.y), anything else samples the glyph atlas. Shapes and text go into the
same buffer, so the draw order is the call order — a label sits on its panel,
and the pause menu covers chat, with no pass ordering to get wrong. Everything is
built from rect, line, tri, ring, arc, disc, panel, banner,
grid and rule, and the whole layout is derived from one unit,
u = height / 360. The pipeline and its WGSL live in overlay_gpu.rs, shared by
the client and the hud_preview example so the preview cannot draw a HUD the game
would not.
The house style is angular rather than soft: a 45° chamfer is exact at every size,
and a 2 px accent top edge, never a full perimeter, gives a stack of panels a
reading order without competing with the crosshair. Large panels (scoreboard, buy
menu, pause menu, the post-match and drill cards, the console) carry a faint
technical grid; centre notices are slanted banners that slide in. Outer edges of
rings, arcs, discs, lines and chamfers get a 1 px alpha fringe — anti-aliasing
without MSAA on the overlay — but edges where two tiled shapes meet do not, or the
fringe would draw a seam between them. The palette is ui_theme.rs, taken from
the browser (panels rgb(13,17,23), accent #6ea8fe); the radar's colours are
not in it, because they are pinned to the browser by their own fixture.
Type
Three faces, all the operating system's — nothing is bundled (text_kit.rs):
| Face | Windows | Used for |
|---|---|---|
| Display | Bahnschrift, tracked | labels, headings, weapon names |
| Mono | Cascadia Mono, then Consolas | every figure: HP, ammo, money, clocks, K/D, the console |
| Body | Segoe UI | player names and chat — the face with every script |
Elsewhere each falls back to the system sans or mono. Strings are shaped once by
cosmic-text and cached; glyphs are rasterised by swash into one 2048² atlas
(shelf-packed, dirty rows uploaded, cleared at the next frame if it ever fills).
Faces are sized by cap height: every layout here reserved a 7 * scale box
for the old 5×7 font, so a real face is sized to make its capitals exactly that
tall and drops into the same space. A busy HUD went from about 25,000 overlay
vertices (one quad per lit pixel) to about 5,000 (one per glyph); a console full
of scrollback, which used to overrun the 65,536 cap and lose its tail silently,
is about 14,000.
Benched on Dust II at Medium (2026-11-06, RTX 4080 Laptop, HUDFONT=bitmap as
the control): the hud phase is about 0.07 ms either way and GPU time moves by
about 0.04 ms. Capped at 240 fps the two are indistinguishable (p99 frame 4.9 ms
both). Uncapped, a first pair of runs suggested fonts cost 10–20% fps, all of it
in acquire (the swapchain wait) with every CPU phase equal; interleaving the
modes six runs deep showed that was run order, not fonts — 735–761 fps with
fonts, 753–760 with bitmap, and acquire swinging 0.17–0.48 ms within one mode.
At 700+ fps uncapped and windowed, compare modes interleaved or not at all.
The 5×7 bitmap font is still there, as the fallback: for the few hundred
milliseconds the fonts take to load on their thread, and on demand with
HUDFONT=bitmap for an A/B comparison. Unit tests build a bitmap-mode painter,
so their vertex counts stay exact on any machine.
Figures roll rather than jump (anim.rs): HP, armour and money ease to a new value
over 420 ms, seeded at their final value and snapped on first sight, so a tile
never reads 0 when it means 62. Kill-feed rows and the post-match card's cells
arrive with a short staggered slide, capped so a long list is not late.
The pause menu, post-match card and drill card scale with the window too: the
menu by whole HUD units (menu::zoom), so its hit-tested rows stay on whole
pixels, the cards by a clamped height / 800. Values in the menu are chips —
figures in the mono face, words in the display face — with stepping arrows on the
selected row.
What the blocks say that a number alone does not
- The damage-lag trail. The health bar leaves a dim red trail behind it that
holds for a moment and then drains. The gap between bar and trail is what the
last hit cost, readable without doing arithmetic on two numbers. It is taken from
the last seen health rather than from the trail's own position, so a second hit
during a burst extends one trail instead of restarting it partway down and
reporting the pair as smaller than the first shot alone. A heal snaps it —
.max()was the obvious way to write that and is the wrong one, since it can only raise the trail and so left a heal drawing damage that never happened. - The magazine strip. One tick per round, spent ticks dimmed. A count says how
many are left; the strip says it without being read. Past ~20 rounds a per-round
tick is thinner than a pixel, so it becomes a plain bar — the threshold is where a
tick stops being drawable, not a round number.
mag == 0is the knife and draws no strip at all, the same distinction the dash in the counter already makes. - The reload dial. An arc, not the word
RELOADING: during a reload the question is never whether — you pressed it — it is how much longer. It needs the weapon's servedreloadTime, becausereloadInis a remainder and a dial cannot be drawn from a remainder alone; with no served time the word comes back rather than an arc implying progress it cannot know. - The armour bar. See Armour. Its trough is drawn even at zero: an empty trough says "you could be wearing some and are not", which is a different statement from blank space.
Everything is always reserved
The reload row, the magazine strip and the armour row all take their space whether or not they have anything to show. This is the rule the ammo counter already followed and the reason is the same in each case: a block that only takes the space it needs moves the counter at the moment the magazine empties, or moves the health bar the moment a vest runs out — which is the moment each is being read hardest.
Two blocks that share a corner have to share the arithmetic
Three collisions existed here at once, and all three were invisible until the HUD was rendered and looked at:
- The ammo block was laid out inside the net graph's box, so the two printed
over each other whenever a player turned the graph on.
net_graph_linesandnet_graph_heightnow measure it without drawing it, and the weapon block sits above whatever that comes to. - The utility tray recomputed the weapon block's four rows by hand, with a
comment saying the arithmetic had to agree — which it then silently stopped doing
the first time that layout changed. Both now call
weapon_rows. - The health block cleared the movement line but the panel drawn around it did not, so the two overlapped by exactly the panel's padding: invisible at 720p, obvious at 1440p, and a function of the window size either way.
Looking at it is the test
None of the above would fail a unit test. cargo run --example hud_preview renders
the HUD offscreen to a PNG, the same way weapon_preview and operator_preview do
for the models — it takes an optional path and a WIDTHxHEIGHT, and the size is a
parameter precisely because the layout is derived from the window height, so a HUD
that reads at 1080p can be a smear at 720p and overlapping at 1440p. Flags after
the size add a layer: summary, defuse or ctf, radar, menu, menu-video,
menu-crosshair, drill, chat (emoji, CJK, Arabic, a wrapping line and an
open prompt) and console (a full scrollback). Run one with HUDFONT=bitmap to
see the fallback font against the same frame.
Two things about that harness are deliberate. It draws a mid-grey backdrop with a
bright band, not black, because a HUD checked against black passes with
translucent panels that turn out to be unreadable over a lit wall. And it seeds the
player healthy and then hurts them, because the lag trail is driven by a drop
and on_self ignores the first sample it ever sees — seeding straight into the
wounded state draws no trail and quietly makes the harness useless for the element
it was added to check.
It also prints the overlay vertex count against the 65536 cap. That cap is closer
than it looks with a font that spends a quad per lit pixel, and set_overlay
truncates — silently, until now: the overlay and the view model report an overflow
through divergence::note_overflow the way the bodies and volumes already did.
Truncating in silence is how a HUD loses its last panel on a full server and nobody
finds out, because the frame still draws, at the right frame rate, simply missing
whatever was laid out last.
The main menu
MainMenu.tsx replaced what used to be a single Deploy button. That button was
fine while the only thing to do was walk around a map, but the game now has matches
on other people's machines, bots, a friends roster and four screens of settings —
and a game that drops you straight into a level has nowhere to put any of it.
It renders over the live scene, like the sign-in screen: the map behind it is the one you are about to play, still orbiting. That is the whole reason the boot sequence finishes the world before asking anything — the menu is a layer on a game, not a screen in front of one.
Six sections, as a list on the left and its panel on the right, so the actions people came for stay one click deep however much settings grow:
| Section | What it answers |
|---|---|
| Play | Map, then Quick play, Train (alone, against dummies) or Host (a match here, with bots) |
| Armor & Skins | Float wear, level-up drops earned and unclaimed, trade-up contracts |
| Servers | What is running — here, on the LAN, and on friends' machines |
| Friends | Who is about, who has invited you, and how to add somebody |
| Settings | Sensitivity, field of view, volume, crouch mode, voice, the native prototype |
| Controls | Rebind every key |
The menu is labels and state, not prose
Every one of those rows used to carry a hint line under it, every start option two sentences of explanation, and the Play section closed with a paragraph describing the momentum system. All of it is gone, on a rule worth stating because it is easy to violate one row at a time:
A menu says what things are and what is true right now. It does not explain how the game works.
The hints were also redundant — the panel one click away is the explanation, and it is the accurate one, whereas a summary drifts the moment the panel changes. The movement description was worse than redundant: it was advertising copy, sitting in front of somebody who had already decided to play. It lives in Movement instead, where a reader is actually reading. Error banners and the loadout warning stay, because those are state.
What is not prose and stays: slider hints (they describe a control whose effect is not otherwise visible until you drag it) and the footer keybinding line.
Quick play is first and is the only accented button on the screen. It joins the
fullest joinable match a friend or the LAN is running — fullest because a room with
people in it is the one worth joining — and hosts one only when there is nothing to
join, skipping any map this node cannot load rather than offering it and then failing.
It is composed entirely from browseServers, joinRoom and host; there is no
matchmaking endpoint behind it. A public queue across strangers is a deliberate
non-goal for now, and Quick play is the button it
would route through if it lands.
Train is deliberately not a match. It is one player on a map against static dummies that do not shoot back, which is what learning the movement wants: the chained-jump timing and the shoot-jump are exactly the sort of thing to practise before somebody is aiming at you. The gun works there — see the training range — because the shoot-jump cannot be practised without one.
Demos (.hademo)
Record demo (the pause menu in the browser, the pane's toolbar on the
desktop) saves what you saw as a .hademo file; Play a demo opens one.
demo.ts holds the format and both halves, and the panel's frame loop drives
them:
- Recording keeps one frame per
1 / tickRate(30 per second), whatever the display's rate (DemoRecorder.due): your own view, under your player id (header.pov), plus every body the avatar pool drew that frame, asPlayerRows (snapshotFromRow). Kills from the feed become events and the bar's frag bookmarks. Angles are the wire's, radians with yaw 0 = +x. - Playback leaves any match, loads the demo's own map if another is up,
and poses the world from
sampleCurrentFrame: the camera behind the recorder's eyes, everybody else through the same avatar pool a match uses. Nothing is simulated or sent. The mouse stays free, because the bar is the thing to use; a click on the world takes it only for the Drone camera (F3 or C), which steers by it and starts a step behind the recorder. - What was in their hands. Your own frame also carries
weaponIdand the scope (scoped, the zoom step, andzoom, the magnification it meant). Behind the recorder's eyes, the hands, the scope overlay and the FOV read those (heldWeapon,heldZoom, throughreplayViewRef) instead ofShotController, which during a replay is still the viewer's gun — that is why every replay used to show whatever you last held. The id is preferred to the index, so a roster that grew since the recording does not hand you a different gun; a demo older than these fields falls back to the index and plays unscoped. - Export MP4 on the bar records the demo from the top, at the bar's speed,
as it plays (
replay-export.ts): each drawn frame is composited onto a 2D canvas with the scope drawn on (on screen it is DOM over the canvas, not in it) and recorded byMediaRecorderasvideo/mp4(H.264). A shell that cannot record MP4 says so instead of offering a WebM. WebCodecs was not used because it needs a secure context, which a pane is not always in. The recorder pauses with the demo and while the pane is hidden; keep it visible to finish. Video only, no sound. parseDemorefuses rather than loads a file that is not a demo or has no frames, and says so on screen.
Neither half was wired at first: the recorder was never fed, so every demo
saved before this has "frames": [], and loading one showed a bar whose
clock never moved over a world nothing posed, with the pointer captured so the
bar could not be clicked. Those files cannot be recovered; record new ones.
The recorder keeps its frames on a grid of the tick: each frame is due one
interval after the last was due, not after it happened to be drawn. Measured
from the draw, a 250 fps display kept 28 frames a second instead of 30, each one
36 ms after the last. A recorder more than a tick behind (a hitch) starts the
grid again rather than bursting. parseDemo also turns an event's killerId
and victimId, and a bookmark's targetPlayerId, into strings as it already
did a body's id: a killer read as the number 7 never matched the body now called
"7".
In the native client
The same files, both ways: demo.rs is demo.ts's interfaces field for field
(it had its own format — snake_case, numeric ids, 60 Hz, angles blended as
degrees when they are radians — and was wired to nothing).
__tests__/demo-vectors.json, written by demo-vectors.test.ts
(UPDATE_DEMO_VECTORS=1), holds a file as it might arrive, what parseDemo
makes of it and what sampleCurrentFrame draws at nine times; demo.rs parses
the same file, serialises it back to the same JSON and samples the same bodies.
- Recording. Pause menu → REPLAYS → RECORD THIS MATCH (it shows
REC m:sswhile on), or RECORD EVERY MATCH (hassault.replay.autoRecord, also on the main menu's settings), which starts at the join — from the menu or from a--maplaunch. TheApprecords once per tick after the frame is posed: its own view from the prediction it draws with, then every body as drawn; kills from the snapshot'sFx::Kill. The player names come from the frames, so somebody who left still has one. It is written when stopped, and on every way out of the match (App::finish, waited for, since a client with no front end exits next), tohAssault/demos/<map>-<UTC time>.hademobeside the local settings file, through a temporary name. - REPLAYS tab (
front/replays.rs). The folder, newest first, read on a worker when the tab opens: map, when, length, frags, whose eyes. WATCH loads the recording's map with no server, as Train does, and hands the demo to theApp(replay.rs): nothing is simulated or sent, the bodies are the demo's, and the camera is in the followed body's eyes with their weapon and health on the view model and the HUD — that body left out of the drawn ones, as your own is in a match. Keys: P (or Space) plays, arrows seek 5 s and step the speed (0.1× to 4×), B jumps to the next frag two seconds early and follows the killer, N follows the next body, F6 the freecam (which sees everyone), H hides the HUD and the bar. OPEN FOLDER shows the folder.--replay=<file>does the same from a terminal, or a double-clicked file once something is associated with it. - EXPORT MP4 (and
--replay=<file> --export) plays it into<demo name>.mp4beside it, offline: the replay's clock is the frame count over 60, never the wall's, so a slow machine takes longer and writes the same file (the browser records in real time, at the bar's speed). The surface is made copyable for the export only (Renderer::enable_capture), each presented frame is read back and piped raw intoffmpegfrom the PATH (export.rs: H.264 throughlibx264when it has it,yuv420p, even sizes,+faststart). The picture is clean — no HUD, no bar; the window title says how far it has got, and Escape abandons it and deletes the partial file. Withoutffmpegthe button says so rather than writing something else. A window resized mid-export stops it, since the encoder was told one size. Video only, as in the browser.
cargo run --example demo_sample writes a recording without playing a match —
four bodies walking Dust II's benchmark framings, through whatever is in the
way — into the demos folder, or to a path given.
The native client
apps/native-fps sat in the Play section advertising a "native C++ / Vulkan client
with 1,000Hz+ Raw Input and sub-tick UDP networking directly to this match server".
None of that was true: it was ~300 lines of Rust on minifb — a CPU framebuffer, not
Vulkan — walking a hardcoded 16×16 raycast grid. It loaded no map, and tungstenite
was declared in its Cargo.toml and never imported, so there was no networking at
all. The backend passed it --connect=127.0.0.1:4000, --room and --raw-input,
and it parsed none of them.
It is being built for real, in stages, and it lives in Settings until it is one. A prototype behind a settings row is fine; a prototype wearing the finished thing's label sends people to file bugs against a game they were never running. See the native client for where it is now.
Local network is a row in the Servers panel that toggles
network.enableLanDiscovery. LAN is a fabric transport owned by the network module,
not a second discovery mechanism for this pane — but "play on LAN" is something people
look for in a game menu rather than in a network settings page, so the switch is here
too.
Bots asked for at host time are queued until the room exists: add_bot needs a
room id, and the room is only ours once the welcome lands. The pending request is
keyed off the room id rather than the connection status, so a new room gets its own
bots and rejoining the same one does not silently double them.
The pause menu, and why it is the same code
GameMenu.tsx (Escape) shows the same four panels, plus two of its own:
Loadout (what you carry, from the next spawn) and, in the training range,
Range (drill, gun, Start and Restart), which it opens on. A game's settings screen and
its paused settings screen differ only in what surrounds them, and two copies would
drift — one gaining a slider the other never got. So the panels live in
menu-panels.tsx and the two menus compose them: MainMenu in front of the orbiting
map, GameMenu over the frozen world.
What is only in the pause menu is the way out — Exit to menu, which leaves the match on the way, deliberately: the main menu is not somewhere you can stand while a server is still simulating your body. The pane's toolbar carries the same action, and is otherwise now status only; choosing a map, hosting, adding bots and inviting people all live in the menus, because two ways to start a match is two things to keep in step.
Both menus are plain DOM overlays rather than anything drawn in WebGL, which is the whole reason they can exist: pointer lock is released while one is open, so the mouse is a mouse again and every control is an ordinary focusable element. That also means the keyboard is the shell's again — which is why the rebind rows capture through a focused input instead of a window listener that would fight the dispatcher.
One account, not a second one
Identity is the existing game-server account (backend/games_server/), the same
one the games ladder uses. Signing in here signs you in there. Three
ways in, all ending in one JWT held node-side:
| Needs | |
|---|---|
| GitHub / Google, redirect flow | OAuth client id + secret on the game server |
| GitHub / Google, device flow | Just a client id (the automatic fallback) |
| Email + password | Nothing — works on a server with no OAuth configured |
The whole sign-in is core's SignInCard (packages/core/src/SignInCard.tsx)
— the same component the games lobby and the home page's setup flow render. The
front door owns only its frame: the wordmark, and the fact that you sign in over a
real level.
That is a deliberate consolidation. There used to be three copies of this flow
(here, the games sidebar, the games first-run hero), and they had drifted: this one
had a fallback for a blocked pop-up, the first-run hero did not — it called the
device-only entry point, so it never opened a consent page at all, and its prompt
rendered Enter code at with both values blank. A flow this fiddly duplicated
three times is three chances to be subtly wrong in a way nobody notices until a
user hits the worst copy. Signed-in state comes from the shared account store
(useAccount), so signing in anywhere in the app is reflected everywhere at once.
See Onboarding for the setup flow and the failure ladder that sits under every "open this page" in the app.
Email+password uses stdlib hashlib.scrypt — memory-hard, and no new
dependency (bcrypt is in the lock file only via the optional chroma extra, so
it is absent from a default uv sync). Parameters are stored in the hash string
so they can be raised later without invalidating existing rows. A login against an
unknown address still spends the scrypt time and returns the same message as a
wrong password, so neither the response nor its latency reveals who has an account.
The panel captures request and response bodies raw, unmasked, by design. A
sign-in crosses three capture points — the backend's inbound middleware, its
outbound httpx hook (the node proxies the call onward), and the frontend client
recorder — so /api/games/auth/local and /auth/local are in
_REDACT_BODY_PREFIXES at all three. The event is still recorded; only the bodies
are dropped. See observability.
The username is the identity
Your username is the game server's globally unique handle — the same one the
ladder shows. "Enlisted" is derived from having one rather than stored
separately, so there is nothing to keep in sync, and the username follows you to
another machine because the account does.
It is called username everywhere now. It used to be "callsign" here, in the
games module, in social and in people, while the wire, the DB column and the routes
all said handle — one identity under two names, which is exactly the confusion a
single identity is supposed to remove. The game server's handle column and
/account/handle are unchanged (already neutral); the node-local surfaces moved
with the copy: SessionInfo.username, POST /api/games/auth/username.
It has to be chosen, and that was the bug
The chooser (BootOverlay's enlist screen) has always existed and has always been
unskippable — but nobody ever saw it. store.ensure_handle ran on every sign-in
path, deriving a handle from the OAuth login or the email local part and locking it,
so enlisted was already true by the time bootPhase could ask. Everyone arrived
holding a name like rob-ranieri-2 that they had never agreed to, and the name the
ladder, the killfeed and @handle resolution all key on was decided by a string
transform.
So sign-in no longer claims one. A fresh account arrives with handle IS NULL and
lands on the enlist screen; local signup requires a username in the form.
ensure_handle survives for the _m6 backfill only, so accounts that predate the
chooser keep the name they have.
What is left of the old behaviour is a suggestion: suggested_handle rides
along on the sign-in payload and on GET /me, pre-filling the field with the
provider login. A suggestion may collide — two sam@ addresses are both offered
sam — and that is the honest version of what ensure_handle did by silently
handing the second person sam2. The claim is what has to be unique, and a
refused claim comes back with a reason they can act on.
A successful claim also calls handles.publish_binding(), from the route rather
than from each caller: three clients claim through
POST /api/games/auth/username, and a binding driven from three places is a
binding that runs from two of them. That binding — handle → person_id on the
game server — is what makes @name resolvable to a friend code, which is the
difference between a label on a scoreboard and an identity somebody can reach you
at. See social.
The join handler takes the name from the account and ignores data["name"]
entirely. There is deliberately no name field in the pane any more: offering one
would be a lie. Two details in channel.py are load-bearing:
- The check sits above both join branches. The remote branch returns before
match_server.joinis ever reached, so a gate placed next to that call would leave cross-node play completely open. - It sits above
_leave_any, so a refused join cannot evict you from a match you are already in.
What a remote player's name is worth: nothing
fabric.handle_join receives a name from a peer node. It is a label, never an
identity — the same rule handle_invite already states for the string it carries.
Authentication there is the Ed25519 node id the fabric verified; the name is
whatever the guest's backend wrote on the wire, so a trusted friend's node could
otherwise send a nameplate reading as somebody else's account. It is tagged with
the peer's node id and used for display only: no lookup, no decision.
Verifying a remote player's account would mean forwarding their game-server JWT
for the host to resolve_token, which drags the central server into every join and
breaks matches on an offline LAN. Deliberately not done — see
Known limitations.
The loading screen builds the level
The loading animation is the map. Cubes rise into place along a front that sweeps outward from the middle, lit at the frontier and settling into normal shading behind it, over the same three.js scene you then play in. When it finishes the camera keeps a slow orbit, and the sign-in card sits over a live level rather than a screenshot.
Two decisions carry it:
The reveal patches the existing MeshLambertMaterial via onBeforeCompile
rather than swapping in a ShaderMaterial. A separate material would have to
reproduce three's lighting exactly or the world visibly pops the instant the build
ends — and it never quite does. Patching makes the lit result identical by
construction. (Chunk names are a three-internal contract, so a missed
String.replace would silently mean no reveal and no error; reveal.ts warns
instead.)
The build order comes from the vertex position, not a new attribute.
buildWorldMesh emits positions as (cube x, height, cube y) directly in
three-space and the mesh has an identity transform, so object space is world
space — which means geometry.ts, pure and shared with the physics, needed no
changes at all for a visual effect.
The numbers are real. Progress is weighted actual work — renderer, install, map
bytes, mesh, build — and the byte counter is the map download's own
Content-Length, read through a stream reader. Three things that look like polish
and are not:
- Progress is monotonic. A re-fetch or a mesh rebuild can legitimately report less than a later stage already has, and a bar that jumps back reads as a fault.
- The unit is picked from the total, so it can't switch mid-download — and it
is usually KB, because a 128-cube map is nine 16 KB planes. A fixed MB unit
showed the entire load as
0.0. - The build runs on its own clock, not on load progress. The map route sets
Cache-Control: max-age=3600, so a warm reload downloads in one frame and a build tied to bytes would be over before it was visible.
The grid under the map uses derivative-based line width (fwidth). A fixed
smoothstep is fine face-on but collapses at the grazing angles a low camera
produces: cells compress below a pixel near the horizon and alias into a flat grey
wash. And the camera frames the mesh's bounding sphere, not ssize — a map's
grid is mostly empty border, so orbiting the grid centre puts the level small and
off to one side.
prefers-reduced-motion cuts straight to the finished world.
Pointer lock is requested only in the playing phase, guarded in the handler
rather than the markup: the pre-existing "click to play" layer is
pointerEvents: none by design, so without the guard a click on the email field
would grab the pointer instead of focusing it — and Esc during play returns to the
unlocked state and re-arms that exact path.
Locking also takes the shell's input capture (mode: 'full'), which is what
stops the app's own shortcuts firing mid-match — before that, t/n/b toggled
region strips and mod+1..9 switched workspace while you were playing, because
this pane preventDefault'ed its keys but never stopped propagation. Capture is
released by the Escape ladder,
by focus moving to another pane, or by the browser dropping pointer lock on its
own; whichever fires, onRelease runs exactly once and unwinds pointer lock, the
held-key set and the trigger together.
The netcode
The server owns every player's position; the client predicts so that pressing W
moves you now rather than a round trip from now. match.py simulates,
channel.py carries input and snapshots, net.ts predicts and reconciles.
The three pieces that make prediction work
Every input carries a sequence number. The client keeps each command until
the server acknowledges it. Snapshots carry ack — the last command consumed
from that client — so the client knows precisely which of its own predictions
are still unconfirmed. ack is per recipient, which is why one shared list of
player rows still needs a per-player envelope.
The server advances a player only on that player's own commands, each with
the dt the client measured, rather than ticking everyone by wall clock. Two
clients at 120 fps and 30 fps then travel the same distance per second, and — the
part that actually matters — the server integrates the same sequence of steps the
client predicted with. A correct prediction reconciles to zero error rather
than to a small permanent jitter.
Client dt is spent from a replenishing budget. Trusting the client for dt
is trusting it for speed, so each player earns simulated time at real time plus a
10% jitter allowance, banked into a 0.25 s reservoir. A stutter is absorbed; a
client that simply claims time faster than it passes runs dry and is throttled.
Measured against the running server: 6.4 s of input submitted in one burst was
metered out at ~1.15 simulated seconds per real second instead of being granted
at once.
It is a cap on the exploit, not a lie detector. This is a game you host for friends, and a cheat-proof design would cost far more than it is worth here.
Correction without jolting
Reconciliation sets the simulation to the authoritative state and replays what
the server has not seen. Small disagreements would still show as a constant
micro-jitter, so the difference is kept as a visual offset applied to the camera
only and decayed to nothing in about 150 ms — the simulation is already correct
while the picture catches up. Past SNAP_DISTANCE (2 cubes) the offset is
dropped instead: easing across a large error draws the player somewhere they are
not for the whole ease, possibly through a wall.
In a live match on ac_desert the steady-state correction averaged 0.04 cubes
(max 1.19) — well inside the smoothing band, so nothing snapped.
Where a playerstart actually puts you
A spawn entity's z is not a ground height, and reading it as one is the
single easiest mistake in the format. It is the mapper's own origin at the moment
they typed /newent playerstart, and in Cube 1 that origin is the eye, not the
feet. The evidence is in the numbers: entity z is stored as a short (all 1741
official values are integers), and the single most common distance from it down to
the floor the body rests on is exactly 4 — 27% of them, far above any other
value — which is (int)(floor + 4.5), a mapper standing on flat ground with an
eye height of 4.5, truncated on save.
It is not usable even read that way, though. AC's editor flies, so the rest are
scattered from one to twenty-two cubes up with no relation to anything, and that
spread survives restricting the sample to spawns on flat open ground with no map
model within three cubes. The engine gets away with it because entinmap and
gravity resolve the spawn on arrival.
So spawn_at takes the height from the world instead, resolving against the same
_support query step does. That makes a spawn the fixed point of the first
simulated frame: all 1741 official spawns now rest exactly on the ground and not
one of them moves on its first step.
The earlier reading — max(floor_at(cell), spawn.z), treating the entity height
as a lower bound — put every one of those 1741 spawns in mid-air, because
spawn.z is above the floor at all but six of them and so the clamp never once
fired. On ac_desert that was a seven-cube drop on every spawn and respawn, and
it briefly lifted the eye above the cell ceiling, which makes raycast_world
report an immediate block for anything fired on that frame.
Spawn placement is pinned across the two languages by the same fixture step is.
Remote players are rendered in the past
Everyone else is drawn behind the newest snapshot, interpolated between two that have both already arrived, so ordinary jitter never becomes visible motion. Since G4 how far behind is adaptive (25–100 ms, from the measured jitter), the clock offset is a sliding-window minimum, and a starved body is carried on for at most 50 ms before it holds: see After G4: one curve and an adaptive render clock. The rest of this section describes the original buffer.
Server and client clocks are unrelated, so rather than synchronising them the
buffer tracks the smallest arrival - timestamp ever seen. The minimum is the
sample that queued least, which is both the best estimate available without a
clock-sync protocol and — more usefully — a stable one.
Angles interpolate the short way round. A player turning past π would otherwise spin most of a circle the wrong way between two snapshots.
Verified against the running server with two browser tabs in one match: 39 snapshots produced 233 distinct rendered orientations across 239 frames, which is interpolation doing its job rather than the renderer stepping snapshot to snapshot.
Why JSON on the shared socket, not a binary one
This revises the earlier "binary WebSocket first" plan, and the reason is
arithmetic. JSON on the shell's existing /ws socket shows up in the
observability panel, needs no second connection to manage or reconnect, and can
be debugged by reading it. Binary framing is worth reaching for when player
counts or tick rates make the bandwidth real.
The numbers, measured rather than estimated — an earlier version of this section claimed "~500 bytes for eight players, about 10 KB/s", which was written before health, crouch, the held weapon, grenades, zones, the radar and the noise envelope were in the packet, and was off by a factor of five:
| Players | Per player per tick | Per player | Host uplink |
|---|---|---|---|
| 8 | ~2.5 KB | ~50 KiB/s | ~400 KiB/s |
| 16 | ~4.5 KB | ~88 KiB/s | ~1.4 MiB/s |
Still nothing on a LAN, which is the only place this runs, and the host's uplink
is the number to watch rather than any one client's. And the cost of producing
those bytes is no longer the argument it might have been: serialising a
16-player tick now costs ~0.16 ms of the 50 ms budget (see below), so a binary
codec would be optimising three tenths of one percent of a tick — in exchange
for a second encoder to keep in step across match.py, session.ts and the
Rust client's protocol.rs. That is the silent-drift shape this module already
guards against with physics-vectors.json, bought with nothing.
Input is batched — one message per send tick carrying every command since the last, rather than one per rendered frame. At 60 fps that is ~30 messages a second instead of 60, for identical information.
The snapshot is serialised once, not once per player
Only two fields of a snapshot differ per recipient: ack, which prediction
depends on, and you, the private half (ammo, hitmarkers, the noise envelope,
what your team can see). Everything else — the player table, the scores, the
grenades and zones in the air, the tick's effects — is identical for everyone in
the room.
It was nevertheless rebuilt and re-serialised for each of them: every grenade
snapshotted sixteen times to produce sixteen identical lists, and json.dumps
run over all sixteen player rows once per recipient, so a full room cost 256 row
serialisations per tick. MatchRoom.snapshot_template now serialises the tick
once and splits it at the two per-recipient holes, and WsConnection.send_text
puts the assembled string on the socket without a second encode.
The layout is not written out by hand. The holes are placeholder values that
go through json.dumps with the rest of the envelope, so key order, separators
and escaping all come from the encoder — there is no second copy of the
envelope's shape to drift from snapshot_message. The wire is byte-for-byte
what it was, and a test asserts exactly that against a room with grenades, zones
and effects in flight. Without that test the fast path would have no independent
spec, and a reordered key would be a silent protocol change that only the Rust
client would notice.
Two things make it fall back to plain send_json, both on purpose:
- A peer's connection. A remote player is a
PeerPlayerConn(see Playing in a friend's match), which exposes onlysend_jsonand stamps the payload with the guest's client id. It has no text path and needs none — the choice is made per connection, so one room can hold both. - An observed frame.
WsConnection.send_jsonhands every outbound frame to the/wsobserver as a dict, and a pre-serialised frame has none to give it. The question is asked per event (ws.is_observed), not "is an observer registered":backend/app.pyregisters one unconditionally at import, so a global check would be permanently true and would have made this whole path dead code in every real process while still passing unit tests that never import the app.
Today the answer for hassault/snapshot is that nothing observes it, because
the snapshot joined the observer's skip list alongside share/mirror — it is
the largest repeated payload on the socket by a wide margin and every tick looks
like the last, so recording it meant two further json.dumps of that payload per
frame (compact, then again with indent=2) on every tick whether or not anybody
had the panel open. The rest of the hassault channel — joins, the killfeed,
invites, results — is small, individually interesting, and still recorded. If
that list ever changes, the snapshot correctly reverts to the plain path rather
than silently starving the panel.
Where the tick's 50 ms goes
The match loop sleeps the remainder of TICK_INTERVAL rather than a flat
interval, so the rate does not sag under load — which also means a room running
out of budget slows down without ever saying so. TickStats (a rolling
200-tick window per room, ~10 seconds at 20 Hz) reports simulate and broadcast
cost separately, plus the bytes one tick puts on the wire across all recipients.
Read it with the server.tick() console command or the hassault.status agent
tool.
What it said when the counters first went in was that about two thirds of the
broadcast was the radar — spotted_by, raycasting every ally against every
living enemy, once per recipient. That is now fixed (see
The radar); on a full 16-player room on hd_atrium the controlled
before/after is:
| raycasts/tick | broadcast | |
|---|---|---|
| radar per recipient | 216 | 2.36 ms |
| radar per team | 24 | 0.40 ms |
Serialisation, the thing that looks expensive, is ~0.16 ms of what remains — which is the measured answer to "should the wire be binary?" and the answer is no. Pre-serialising the tick was worth ~0.45 ms; the radar was worth four times that, and neither would have been known without the counters.
A note on reading these numbers: they are a controlled A/B in one process,
not two server.tick() readings taken minutes apart. Live samples move with
whatever else the machine is doing — a later run showed broadcast higher than
an earlier one while simulate, which nothing had touched, had risen 43% along
with it. Compare within a run, or compare the raycast count, which is
deterministic.
Two reporting rules, both the hardware module's: a window with no samples reports
None rather than 0 — a room that has not ticked and a room whose ticks are
free are different facts — and byte counts are recorded only on the
pre-serialised path, where the string is already in hand. Weighing the plain path
would mean serialising a second time to measure the cost of serialising, so it
reports "not measured" instead of a number it had to manufacture.
The snapshot after G3: roster on change, sends side by side, one clock
Three changes to the tick's wire, none of them visible to a client that does not ask for them.
The roster is sent when it changes. name, team, kills, deaths and
bot (ROSTER_FIELDS in match.py) change on a join, a team switch, a kill or
a death, and were in every row of every tick. A client that puts
caps: ["roster"] in its join now gets rows without them, an rv (roster
version) on every snapshot, and a roster list on the ticks where the version
changed or this client has not had it yet. Rows are 29% smaller: for eight
players, 2,008 bytes a tick become 1,416, about 35 KiB/s per recipient at
60 Hz. Both clients put the fields back as the snapshot arrives (RosterCache
in net.ts and protocol.rs), so everything after that sees the full rows.
- Opt-in per connection.
match.parse_capskeeps only capabilities the server knows. A client that declares none, or a socket in a friend's match (the fabric does not passcapson), gets the full rows it always did. The node passes the client'scapson to the game server for an online or ranked room (ranked.join), whose frames it relays unchanged. - One serialisation per shape. The full-row template, and the slim ones with and without the roster, are each built at most once per tick and only if a recipient needs them.
- What the server keeps is the full rows. The replay recorder, PVS culling
(which reads
team) and the welcome all work on them; slim rows are made at the last moment, per recipient.
Sends run side by side. Each recipient's frame is its own task, and the
broadcast waits at most half a tick for them together (SEND_WAIT). Before,
they were awaited one after another, so one slow socket held the whole room's
tick while it drained. A socket still writing the last frame is skipped this
tick, and it is skipped before its private view is built, so the hitmarkers
it would have drained ride the next frame instead of being lost.
server.tick() reports the count as skippedSends. A send is never cancelled:
a websocket write abandoned halfway leaves a torn frame on the stream.
The game server gained SeatConn.send_text with this. Without it, the
production server had always taken the per-recipient json.dumps path, never
the serialise-once one above. It also gained a send lock, since an event can
now be sent while a snapshot is still writing.
One monotonic clock. t, the lag-compensation history and a shot's rewind
all read match.wire_clock(): the monotonic clock plus a fixed offset to epoch
time, taken at import. They read time.time(), which an NTP correction can step
mid-match, putting snapshots out of order by their own timestamps and a rewind
on the wrong instant. t is still epoch milliseconds, so a client's offset
estimate does not change.
After G4: one curve and an adaptive render clock
Three changes to how remote bodies are drawn and judged, held together by one
fixture, __tests__/interp-vectors.json, which scripts/gen_hassault_vectors.py
writes and all three languages replay.
One curve. A shot is judged by rewinding the server's position history to
the instant the shooter was drawing (viewT). Both clients draw remote bodies by
lerping between the two snapshots around that instant. The server's
PositionHistory.rewind lerped only as a fallback: whenever a neighbouring frame
existed, which was nearly always, it ran a Catmull-Rom spline through four
frames, which lands a little ahead of or behind the straight line on any body
that is speeding up, slowing down or turning. The rewind is now the straight
line, and the fixture's rewinds cases are written from it and replayed by
test_hassault_weapons.py, interp-vectors.test.ts (through
SnapshotBuffer.sampleAt) and conformance.rs (sample_at). The body you aimed
at is the body you are judged against, to f32 precision.
An adaptive delay. The delay was a flat 45 ms: too much on a clean link and
too little on a jittery one. InterpClock (net.ts, interp.rs) now works it
out:
| Piece | Rule |
|---|---|
| Delay | one tick + 2 × interarrival jitter (RFC 3550, gain 1/16), clamped to 25–100 ms |
| Clock offset | smallest local − t in the last 5 s, not of all time |
| Easing | the drawn lag moves at most 10% (backing off) or 4% (catching up) per ms of wall time |
| Snap | a change over 250 ms is a new clock: taken at once, and the jitter estimate reset |
| Warm-up | for 1 s after the first snapshot (or a snap) the lag follows its target directly |
| Starved | past the newest snapshot, a body carries on along its last velocity for at most 50 ms, horizontally, at most 40 cubes/s; then holds |
Why each piece:
- The windowed minimum follows a local clock that runs slightly fast. With the all-time minimum, the true offset grows away from the estimate, and the render clock creeps ahead of the data for the rest of the match.
- The easing keeps the delay from visibly speeding anyone up or slowing them down when the estimate moves.
- The warm-up exists because a connection's first frames are the ones that queue. Easing down from one of those at 4% took about 4.6 s, during which every body was drawn late.
- Extrapolation is bounded three ways. A falling body carried on vertically would sink into the floor it lands on. A respawn between two snapshots reads as a sprint across the map, so it is held instead.
The constants live in the fixture, and both ports assert theirs equal them.
The net graph's interp readout (net.graph 2 in both clients) is now the live
delay rather than a constant, so a jittery link shows up as the number climbing.
The reference implementation is InterpClock in the generator itself, because
only the clients run it: it is the spec both ports are held to, and the
interpClock cases cover:
- a clean link;
- a jittery one;
- a local clock 0.3% fast;
- a 400 ms stall and its burst;
- the server clock jumping 2 s;
- a slow first snapshot.
Transport. Nothing needed changing. The native socket has set TCP_NODELAY
since G0 (net.rs), and Python's asyncio sets it on every TCP transport it
creates, accepted sockets included, on both the selector and proactor loops.
Train steps the match's physics. Offline Train on a modelled map stepped a Rapier capsule against the render mesh. That controller had its own sprint, slide and stamina, a 0.4 step instead of 1.6, and in the browser a shot trace against the mesh that could shatter windows. None of those exist in a match, which steps everyone against the cube grid the map bakes. So Train taught moves that fail in a match.
Both clients now step player.ts/physics.rs against that grid in Train too:
- spawns and drill stations are grounded with
spawnAt/spawn_at; - the browser range traces shots with
raycastWorldFace; - wallbangs follow the server's rule: within the weapon's served
penetration, never into a body standing in solid, at 0.6× damage. The range had let a body behind any wall take full damage on cube maps.
The cleanup:
physics-rapier.ts, its test and@dimforge/rapier3d-compatare gone.physics_rapier.rsstays, but only as a probe over the drawn mesh for the content tests (spawn clearance, perimeter walls).- Native drill stations now work on modelled maps; they were skipped there because the body was Rapier's.
One Train/match difference is left, and it is a damage rule, not movement: the range scales groin hits by 1.5 and limb hits by 0.75, and the server does not.
After G5: input and combat feel
The native eye moves on every frame. Commands step the predicted body at
250 Hz, and the camera used to be placed straight from that body. So above
250 fps some frames repeated the last position: at 300 fps a strafe juddered in
a 2:1 cadence. eye.rs records the eye after each command step, and every frame
draws it between the last two steps by how far through the next interval it is
(input_accum). The cost is that the view trails the newest step by at most one
command interval (4–7 ms). It is position only: the angles are the mouse's and
are applied the instant it moves. A step over 2 cubes (a respawn, a teleport, a
correction too big to ease) is taken at once instead of slid through.
Native feels its own shot on the click. The kick, shake, gunshot and recoil
step used to wait for the server's Fx::Shot naming us, a round trip plus a
tick. own_shots.rs predicts the shot when the command carrying fire is sent,
but only if the server will take it:
- alive and not reloading;
- a round left once every shot still in flight has spent its own;
- for a semi-automatic, the trigger released since the last shot;
- no weapon switch still in flight.
What makes it safe is the reconciliation, not the guess. Each snapshot's ack
says which commands the server stepped, and its fx which of them fired:
- a server shot beyond the predicted ones it acknowledged was not foreseen, so it gets its feedback late rather than never;
- a predicted shot acknowledged without firing was refused and is dropped (a kick cannot be un-felt);
- the recoil index the camera follows is the server's plus the predicted shots in flight, so no shot is kicked twice.
Hits are never predicted, here or in the browser.
The browser caught up on game feel. These were rows in the two-clients "native has" table:
- damage-direction arrows from
you.hurt(damage-arrows.ts), with native's life, cap, fade and geometry in HUD units; - the kill chord, the same
Timbreas native's.
Two rows were already done and only the table was stale. Impact effects are per
pellet, off the served faces. The crosshair draws spec v1 from the
hassault.crosshair.* settings.
Movement and first-shot feel, measured against CS.
tools/hassault_feel_report.py steps the server's own physics.step and
weapons.shot_cone at 250 Hz. It compares them with Source's ground movement,
stepped at 64 tick with stock cvars. Speeds are in body heights per second,
because the two games share no unit. Selected rows:
| Measure | hAssault | CS (derived) |
|---|---|---|
| Run speed | 4.23 heights/s | 3.47 heights/s |
| Crouch speed | ×0.40 of run | ×0.34 of run |
| Rest → 95% run | 360 ms | 438 ms |
| Release → accurate | 132 ms | 203 ms |
| Counter-strafe → accurate | 16 ms | 78 ms |
| Counter-strafe → stopped | 28 ms | 125 ms |
| Release → stopped (1%) | 556 ms | 406 ms |
| Jump apex | 0.56 heights | 0.79 heights |
| Jump air time | 576 ms | 755 ms |
What it says:
- Counter-strafing is about five times quicker than CS's. The 3.2× braking response when the wish opposes the velocity gets a full run under the accurate threshold in four commands. That makes the counter-strafe close to free, where in CS it is a timing skill.
- Running is about 20% faster relative to body size.
- Jumps are lower and shorter, because gravity ramps with time in the air.
- Releasing without countering never quite stops: the convergence is exponential, so the last 1% takes longer than CS's linear stop-speed floor.
First-shot accuracy: a tap rhythm slower than 350 ms gives the rifles a fresh
first shot and a restarted pattern every time (the larger of recovery_time and
spray_reset). The script prints the per-weapon table. It has no CS column,
because CS's per-weapon recovery figures are not stock cvars to derive from.
None of this is tuned yet. It is a measurement for the playtest, and any
change goes to physics.py, player.ts and physics.rs together, with the
vectors regenerated.
Playing in a friend's match
A match is authoritative on one node. A guest's browser cannot reach it — the host may be behind NAT, on another network, or simply not somewhere a browser is allowed to open a socket. So the guest's own backend proxies for them:
The peer fabric already solves NAT traversal, relays, LAN discovery and identity, so this is four message types and two mappings.
The host never learns that some of its players are not browsers. A remote
player is a PeerPlayerConn, which has the single method the match server calls —
send_json. MatchRoom is unchanged.
The browser never learns that the match is somewhere else. The guest backend
reshapes the host's welcome into exactly the frame a local join produces, so the
client has one code path rather than two.
Three details that are easy to get wrong and are each pinned by a test:
- Every inbound message is gated on
session.info.trusted— what accepting a friend grants. Friendship means reachability, so knowing a room id is not enough to walk into someone's match. - Remote input goes through the same validator as a browser's. A peer is another user's machine, not a trusted extension of ours; a second, laxer validator on the peer path is exactly where a gap appears.
- A dropped peer's players are swept. They have no browser socket, so nothing else would ever notice they left — they would stand in the match forever.
Frames are tagged with a client id, because one machine can have two tabs in the
same match and otherwise both sets of snapshots go to whichever joined last.
Invites
Invite a person, not a machine: the pane resolves a name or friend code through
the social roster and sends hassault_invite to every device they have
online, because you invite a human and they pick which box to answer on.
The pane's invite list comes from GET /api/hassault/invitees, which the hassault
backend assembles from the social roster. That join is deliberately backend-side:
the pane must not import across a module boundary, so it only ever calls
/api/hassault. Friends whose node did not advertise the hassault capability
during the handshake are shown greyed out rather than hidden, since "your friend
needs to update" is more useful than an absence.
Inviting does not require that you already be hosting. "Invite Rob" is a complete
intent, so when you are not hosting a match, inviteFriend invites them into your
lobby (below) and opens one if you have none. It used to host a match and
then invite, which failed twice over: it dropped the inviter into a live map
alone, and the invite never left the node. session.invite refuses unless the
status is joined, and it was called while still joining, so every invite
from the menu was silently discarded. lobby_invite opens the lobby and sends
the invite in one message, so there is no second step to race. Invites
carry a kind (lobby | match). An older sender sends none, and its invites
read as match.
Lobbies
A lobby (lobby.py) is the room in front of a match: the host picks the map,
friends join, chat and mark themselves ready, and Start opens a match and
sends every member into it at once. The lobby outlives the match. Leaving
the match returns you to the lobby with the same people, and pressing Start
again while that match still runs sends latecomers into the same game rather
than splitting the party. It follows karaoke's shape:
- Process-global on the host's node. Every change pushes the whole
LobbyState, stamped with arevision, so the pane drops out-of-order pushes. - Members are renderers. A member is a local socket or a
PeerLobbyConn, which isPeerPlayerConn's twin (hassault_lobbyguest to host, carrying anop;hassault_lobby_framehost to guest).LobbyServeronly callssend_json. - The host leaving closes it. It is not handed over, because the match it would start is simulated on the host's node.
- Changing the map clears every ready flag. A ready given for one map is not consent to another.
- Start creates the room empty. Each member joins it themselves on
lobby_start, which is the only join path. An empty room survivesEMPTY_GRACE. The guest's backend stamps the host node id ontolobbyandlobby_start, which is how a remote member's pane knows where to join. - Trust gates every inbound peer op, the same as a match join. Remote
names are tagged
name@node.
Lobby voice
Voice (lobby-voice.ts) is a mesh of browser-to-browser RTCPeerConnections:
one audio link per pair of people in voice. The audio rides DTLS-SRTP directly
between the browsers, the same shape as share/rtc.ts, and never touches a
backend. The lobby is only the postman:
- Signalling.
lobby_signalcarries SDP and ICE to one named member. It travels over the fabric as thesignalop, like chat does. The host stampsfromwith the member the socket belongs to, never with what the frame claims. - Frame limits. Only
offer/answer/ice/byeframes are passed, each under 32 KB. A handshake is not a state change, so it does not bumprevision. - Who is in voice. Each member carries
voiceandmuted(lobby_voice), which is how every pane knows whom to connect to.
Four rules that fail silently if broken:
- Exactly one side of each pair offers: the smaller member id. If both offered at once (glare), each would reject the other's offer and nobody would connect. An offer from the wrong direction is ignored.
- ICE candidates are queued until the remote description is set. Adding one earlier throws, and dropping it can cost the only route that works.
- Playback goes through the mixer's
lobby-voicestrip. It also needs a muted<audio>element on the stream, because Chrome feeds a remote WebRTC track into Web Audio only while a media element is consuming it. Without that, the voice is silent. - Speaking is metered on a 100 ms timer, not rAF. rAF stops in a background tab, and a lobby is the thing you leave in the background.
- The desktop shell answers the permission request itself. Under the Tauri
shell, WebKitGTK sent each
getUserMediacall to the embedder and denied any request nobody answered, so the voice bar showed "Microphone permission was denied" on Ubuntu while Windows worked. The Electron shell grants media to the app's own origin (configureAppSessioninapps/desktop/src/sessions.ts) and never to the embedded browser's sites, which get a per-site prompt.
By default the mic is open while you are in voice, with Mute and Deafen. With
hassault.voice.pushToTalk on (a checkbox in the voice bar, or Settings) it is
closed except while the Push to talk key is held. That works in a match, where the
game owns the keyboard, but not in the menu, where the keyboard is the shell's.
Push-to-talk toggles track.enabled rather than renegotiating, so each press is
free and cannot drop a link. A window blur releases it, because a key released
elsewhere never sends its key-up. Voice hangs up when the pane closes, not
when it unmounts: the match session is pane-owned (pane-match.ts, via
usePaneSession), so a tab or desktop switch keeps the session — the only path
handshakes arrive on — and with it the match, the lobby and the mesh. It used to
disconnect() on unmount, which sent leave: glancing at another tab dropped you
from the match and put you back on the main menu. A remount now lands on the
click-to-play overlay in the same room, on its map. The standalone assault-web page
has no pane to close, so there the old per-mount lifetime stands. A
mesh is right for a party and wrong for sixteen people, which is a known
limit rather than a bug. ICE uses the network.stunServer/network.turn*
settings, with the same semantics as share. Two networks with symmetric NAT
need TURN.
Match chat
One chat box holds everyone's messages (ALL) and your team's (TEAM). Every
message goes through chat.post (backend/modules/hassault/chat.py), whether
it comes from a browser on this node, a friend's node over the fabric
(hassault_chat, a message type of its own because the rules are not the input
rules), or the native client. So no path can be the lax one. A remote player's
chat used to be dropped outright, and so did chat in a ranked match, whose
room is on the game server rather than the node. The node now relays it
(ranked.relay_chat) and the game server runs the same chat.post against the
referee's rooms (HassaultReferee.chat, which passes server=). The echo comes
back through the ranked pump like any other event. The server's copy is the only
copy:
- Stamped and echoed. Each line gets an
idand a servertsand is echoed to its sender too. Both clients render only that echo and drop a repeatedid. The native client used to echo locally and receive the server's copy, so every message it sent appeared twice. - Grapheme limits. A message is at most 200 grapheme clusters and 1024 UTF-8
bytes, cut only between clusters (
regex's\X, UAX #29).text[:200]used to split a ZWJ family or a flag into garbage. The byte ceiling exists because one cluster can be arbitrarily long ("Zalgo" text). - Normalisation. Text is NFC-normalised, and newlines and runs of whitespace collapse to one space.
- Format characters. Bidi overrides and isolates (U+202A–202E, U+2066–2069) are removed, since in a chat box they reorder somebody else's name. ZWJ, ZWNJ, variation selectors and tag characters stay, because emoji sequences, Persian and subdivision flags are built from them.
- Rate limit. Five messages per four seconds per player. A refusal comes
back as
chat_refused, and the box says "not sent — slow down".
The pane (ChatBox.tsx, chat-text.ts):
- Counts graphemes with
Intl.Segmenterrather thanmaxLength, which counts UTF-16 units and would cut an emoji in half. - Ignores the IME's Enter. An Enter that arrives with
isComposingset is choosing a CJK candidate, not sending. - Isolates names and messages in
<bdi>. - Names every platform's colour emoji font in its font stack.
While the box is open it owns the keyboard, ahead of even the console's backquote. Tab switches between everyone and team, and a line fades nine seconds after it arrives.
The native client draws chat in real fonts, through the same glyph atlas as
the rest of the HUD (see Type). Each line is a Paragraph from
text_kit.rs: laid out by cosmic-text (wrapping, bidi, fallback to the emoji
font) and rasterised by swash, which draws COLR and bitmap emoji in colour, using
the OS's own fonts: Segoe UI and Segoe UI Emoji on Windows, Apple Color Emoji
on macOS, Noto on Linux. Nothing is bundled.
- Fonts load on a thread. Discovery takes a few hundred milliseconds, and the bitmap font covers chat until it lands.
- Colour is chosen at draw time, not at layout. Each span's attributes carry its index as cosmic-text metadata, which every glyph it shapes inherits, and the span colours are supplied when the line is drawn. So a line is shaped once however long it is on screen, and fading it is a vertex alpha — emoji fade with it, since a colour glyph takes only the alpha.
- In the HUD's vertex stream, not over it. Chat used to be a CPU-composited
texture drawn after the HUD (
textlayer.rs,textquad.rs, both gone), which covered whatever it overlapped and therefore hid whenever the menu, the summary card or the console was open. Drawn into the overlay before the console, it is simply under all three. It sits on top of the health panel, whose rows come from the samehealth_rowsthe panel is drawn from. - Names and messages are isolated with U+2068/U+2069, so a right-to-left name
cannot reorder the tag or the text around it — the
bdielement in the browser. - Grapheme editing. Caret, backspace and delete step by grapheme cluster
(
unicode-segmentation), so one backspace removes a whole family emoji, and the prompt enforces the server's limits. - IME input. Input-method text arrives as
Ime::Commit, which is the only way the Windows emoji panel (Win+.) and CJK input reach a winit window. IME is enabled exactly while the prompt is open, and composition text is drawn at the caret.
Two platform limits, not bugs: Windows' emoji font has no flag glyphs, so 🇺🇸
reads as "us" (Chrome on Windows does the same), and a machine with no colour
emoji font shows the text font's monochrome glyph. text_kit's tests lay a line
out with the real system fonts, draw it, and read the atlas texels its quads cover:
an emoji has to come out in colour, and Japanese, Cyrillic and Arabic have to
produce ink. The colour check is skipped on a machine with no colour emoji font.
An invite names a person, and the two authorities it has to cross
The payload used to carry node_identity.node_name(), so an invitation from a
friend read "horribleComputer invited you". Nothing errored — a machine name
was simply the only noun in scope where the payload was assembled.
Two identity authorities meet at this seam, and neither knows the other's answer:
- the fabric knows a node id and a person key, and labels things with a device name;
- the game server is the authority for the username (
accounts.handle), which is what the ladder, the killfeed and@handleresolution all key on.
The invite is built on the fabric side, so the username has to be carried across deliberately or it is not there at all. The sender stamps its own — it knows it without asking anyone, from the signed-in account. Resolving it on the receiving side would mean a game-server directory round-trip per invite, for an answer that is also only a claim.
The receiver then picks a display name in this order (fabric._invite_display_name),
which is the same precedence browse_peers already applies to node_name:
- The roster's
handlefor the person that node belongs to — the only one that is more than a claim, because we resolved it ourselves, and it costs no lookup (social_friends.handleis already stored). - The sender's stamped username. A claim, but from an authenticated friend.
- The device name, then a generic.
Preferring the stamp over the roster would let an authenticated friend render under somebody else's username in your invite list. The device name survives as a secondary line — "on horribleComputer" — which is genuinely useful, since an invite fans out to every machine they have online and knowing which one answered tells you something.
The authenticated node id remains the authority for everything that is a decision. All of the above is a label.
Delivery: a toast is a cache, the inbox is the truth
The invite was broadcast on the hassault /ws channel — and only there. That
channel has exactly one subscriber, the game pane, and panes unmount on a workspace
switch and when their tab is inactive. So for most of the day an invite arrived,
updated a dict, and was seen by nobody. No error, no dropped message: no audience.
handle_invite now also calls notifications.service.notify(), which is one call
rather than a new subsystem because that door already fans out to the shell toast,
the notification feed and the OS notification, with mute rules enforced at the
producer. Four surfaces, from most to least ambient:
| Surface | When it is the one you see |
|---|---|
| Shell toast, with a Join button | The app is open and you are looking at it |
| Notification feed (the bell) | You were not looking; it is still there later |
| In-game card over the canvas | Pointer lock is held, so the shell's chrome is not on screen at all |
| OS notification | The window is not focused |
The in-game card is the same idea as Steam's overlay notification, and it shows
"Esc to answer" rather than buttons while phase === 'playing': the pointer is
captured, so a button there would be unreachable.
The durable inbox is what makes a missed toast harmless. notify() writes a
row to a notifications table in app.db before it broadcasts, and the
frontend hydrates from GET /api/notifications/feed at boot — the feed used to be
a JavaScript array that a reload emptied. Read and cleared state are server-side
too, so answering on one surface is answering on all of them.
That is what dedupe is for: one key, hassault-invite:<node>:<room>, built in
exactly one place on each side (invite-notify.ts and fabric._notify_invite).
It does two jobs — a repeated invite replaces the live row instead of stacking
a second identical card, and service.retract() on accept or decline clears every
surface at once. Two spellings of that key would be a bug that looks like nothing:
everything still works, notifications just never clear.
The OS notification goes through the Web Notification API, gated on the
notifications.system capability; the desktop shell grants notifications to the
app's own origin like any other permission.
An offline friend is queued on the sender
peer_hub.send_to is a direct node-to-node send. There is no relay in the path, so
an offline target does not mean a queued invite somewhere — it means nothing was
sent at all, and the receiver cannot store what never arrived. Steam can queue on
its connection-manager servers because they are in the path; here nothing is.
So the sender holds it (fabric.queue_invite) and flushes on the peer_update
event that _on_peer_event already receives. Deliberately not persisted, and
expiring with INVITE_TTL (five minutes): a room does not outlive the process
hosting it, so an invite that survived a restart would point at a match that no
longer exists — the same reason a Steam lobby invite dies with the lobby.
One consequence worth stating plainly: an invite is not retracted when the host tears the room down. The room is retired on the host's node and the notification lives on the invitee's, so clearing it would need a second peer message. It expires on its own instead, and joining a dead room fails with an error that clears it. That is a limitation, not a design.
Matchmaking is friends-first
There is no public queue and no stranger matchmaking, which follows from the fabric rather than being a separate decision: a stranger's match is not discoverable because it is also not joinable. What "good matchmaking" means here is therefore about friends, and the gaps were all in the same direction — the game could show you a roster but not let you do anything to it:
- Add somebody without leaving the game. The Friends panel used to say "the
roster lives in the Social panel" and stop. That made an empty friends list a dead
end: the one screen where you have just discovered you have nobody to play with
was the one screen that could not do anything about it. It now carries an
@usernamesearch built onsearchDirectory+addFriendfrom the social module's own client — the same pair people's Discover section uses, so it is a second view, not a second implementation, with no new route behind it. The request is sent as@usernamerather than the person id already in hand, because the browser is not a trusted source of person ids and the backend re-resolves and re-checks the key fingerprint itself. - Show the username.
/inviteesreturneddisplay_nameand never the handle, so the game named people differently from everything else in the app. BothInviteeandBrowsePlayernow carryusername, filled from the roster's storedhandle. It can be legitimately empty — a friend added by friend code before either of you signed in to the game server has no account bound to their person key yet — which is why it is served alongsidenamerather than replacing it. - Presence beyond a dot.
/inviteesalready readfabric.hosted_rooms()and threw the answer away; a row now says "playing hd_crossing" rather than only that somebody is online. - One roster, not two. The Servers panel rendered the same friends a second time, with its own Invite buttons, and the two copies had already drifted — that one disabled Invite for anyone already in a match, the Friends copy did not. Servers answers what is running; Friends answers who is about. The duplicate is gone and Servers now lists only who is in your match.
The server browser
There is no master server, and there is not going to be one. GET /api/hassault/browse — the pause menu's Servers tab — is the honest extent of
"available servers": every match on this node (match_server.listing())
plus every match on the nodes of friends the fabric currently has a session
with. A stranger's match is not discoverable, because it is also not joinable
(fabric.handle_join gates on session.info.trusted the same as every other
entry point).
Reaching a friend's rooms is fabric.browse_peers: it fans a hassault_browse
peer-wire request out to every trusted, hassault-capable peer concurrently and
answers on a two-second deadline. A peer that misses the deadline contributes
nothing rather than stalling the whole list — a friend's node having gone quiet
without the TCP connection noticing yet must not make a browser refresh as slow
as the slowest peer. The reply carries peers_asked/peers_answered back to the
pane, so a partial list says so instead of quietly looking complete.
fabric.handle_browse answers with exactly match_server.listing() — the same
rows a local GET /matches call would see — because a friend can already join
any of those rooms; there is nothing to withhold from someone who could ask to
join instead. An untrusted peer gets silence, not an error: the roster is not a
thing to confirm the shape of to a stranger.
fabric.hosted_rooms() — a node id → room id map built from _hosted, the same
dict that holds every PeerPlayerConn this node is proxying for — is the only
place "which of my rooms is this friend's device standing in" can be answered
from: a remote player has no browser socket of its own, only the fact that some
peer node is proxying for one. /browse and /invitees both read it, and the
Friends panel is where it is rendered, as "playing <map>".
One socket is one player
Membership is keyed by connection, so joining twice on the same socket replaces the first player rather than leaving a body behind that nothing can remove. A second player means a second browser tab (or a second machine).
The AFK timer
A human who sends no real input for afk.WARN_AFTER (90 s) is warned, and at
afk.KICK_AFTER (120 s) is removed from the match. No mode has a spectator seat,
so removed means out of the room. Both numbers live in
backend/modules/hassault/afk.py; the game server can retune them without a
code change through HASSAULT_AFK_WARN / HASSAULT_AFK_KICK (seconds, and
HASSAULT_AFK_KICK=0 turns the timer off).
- The server decides.
MatchRoom._step_afkaccrues idle seconds from the tick's ownelapsed. Onlyafk.is_activityresets them, and it reads the commands the simulation consumed: movement, jump, a crouch toggle, aim pastAIM_TRAVEL, fire, reload, a weapon switch, a throw, use, drop, buy and sell. A chat linechat.postaccepted counts too. Aping, an input batch'srtt, an empty batch, or frames with every key up and the view still do not count, so a keep-alive is idle however often it arrives. Tactical pings do not count either: a ping key on a macro is just a keep-alive. - Paused, not reset, while there is nothing to do: dead and waiting to
respawn, or whenever
GameMode.afk_clock_runssays no (defuse's freeze time, the gap between rounds, a finished match). Bots are never timed. A respawn clears the aim baseline, so the spawn's facing does not count as a turn. Without that, every defuse round start would reset every idle player. - A warning always comes first. A stalled tick that jumps past the kick threshold only warns, and the full grace window still follows.
- The warning is an
afk_warningevent plus a chat line fromSERVERto that player only. The native client shows the chat line without knowing the event. While warned,you.afk.kickInrides in every snapshot, and the browser HUD draws it as a countdown. - The removal sends
afk_kicked, announces it to the room in chat, and then leaves through the host's own path (MatchServer.kick_handler). The node's channel files the result as a disconnect would. A friend's player is dropped through the fabric with nothing filed here. The game server's referee records the result and sendsresultback so the player's node files it.
Two implementations of one set of rules
An authoritative server has to simulate, so backend/modules/hassault/physics.py
is a port of world.ts and player.ts. Duplication is a real cost and the
failure mode is nasty: a drifted match does not throw, it just puts each player
somewhere the other cannot see.
So the two are pinned together by
packages/core/src/modules/hassault/__tests__/physics-vectors.json, replayed by
both backend/tests/test_hassault_physics.py and conformance.test.ts. It
carries two kinds of vector — cases, which replay a sequence of movement
commands, and spawns, which place a player from an entity — because spawn
placement is duplicated exactly like step is, and a disagreement about where a
player starts is a desync from the very first frame. The fixture pins
agreement; each side's own unit tests are what argue the rules are right. Agreement is asserted to a tolerance rather than bit-for-bit, because
math.sin and Math.sin are not required to round identically and demanding
they do would be a test about libm.
Changing a movement rule means changing both sides and regenerating the fixture, in one commit:
PYTHONPATH=. uv run python scripts/gen_hassault_vectors.py
If that ever becomes a burden, it is the burden telling you the truth about the cost of the design.
Weapons
backend/modules/hassault/weapons.py owns the loadout and every shot fired with
it. The client draws a muzzle flash, kicks its own crosshair and counts its own
magazine down the instant you press the button — a gun that waits a round trip to
acknowledge the trigger does not feel like a gun — but whether you hit anything
is decided on the server, from the server's own copy of the world.
Twelve weapons. The first five keep the wire indexes they always had (knife, pistol, assault rifle, shotgun, sniper rifle) and the rest are appended, so an older client's weapon index still means the same gun: the Hand Cannon, the ARC Viper SMG, the ARC Raider (T side), the HALON Lancer and Lancer-S (CT side), the Scout and the Breacher auto-shotgun. The numbers are AssaultCube-flavoured rather than derived: our movement speed is 18 cubes/s, which is not AC's, so copying its damage table would produce a different game wearing its numbers.
They are served, not duplicated — GET /api/hassault/weapons — for the same
reason plane_order is reported rather than hardcoded. The client needs each
weapon's fire interval so it does not send input the server will only discard, and
a second copy of that constant in TypeScript is a bug waiting for someone to tune
the rifle.
Loadouts: one primary, one secondary, the knife
A player carries a loadout, CS-style: MatchPlayer.loadout is
{primary, secondary, melee} as weapon indexes, and held is what is in hand.
reset_loadout re-issues the loadout at every spawn, and _handle_combat
refuses a switch to anything not held, which is what makes a loadout a loadout
rather than a list of favourites.
- Picked in the menu, per side, applied at the next spawn. The pane's
Loadout · T and Loadout · CT rows (beside Host), the pause menu's
Loadout tab (the same
LoadoutSideRow, and the only picker the browser client has, since it never shows the main menu), and the native menu's LOADOUT page, store{t: {primary, secondary}, ct: {...}}weapon ids underhassault.loadout, an account-scoped setting (an older flat{primary, secondary}still reads as both sides). The server validates it slot by slot and side by side (weapons.loadouts_for): an unknown id, a sniper named as a sidearm, or a T rifle picked for CT costs only that slot.reset_loadoutpicks the half for the player's team at every spawn, so a side swap carries the other side's guns from the next life. A change never applies mid-life: it is a decision about the next fight, not a way out of this one. The client sends it on the game server'sjoinas well as after the welcome, so the first spawn has it: a guest has no stored loadout, and one that waited for the welcome spawned the first life with the rifle. - The number keys select slots. 1 primary, 2 secondary, 3 knife, from the
slotsthe private view now carries; the wheel steps throughheldonly. Against a server too old to sendslots, key N is weapon N as it always was. - A mode decides what "held" means (
GameMode.holds). The default is the loadout. Defuse answers with what was bought or picked up, plus the free knife and pistol, so the loadout picker has no say in a buy mode: the money does. - Bots carry loadouts too, by archetype (
bots.BOT_LOADOUTS): the entry bot an SMG, the sniper a sniper and a Hand Cannon, the anchor the Breacher. Archetypes turn over the room's bots, not oneadd_botscall's, so bots added one at a time cycle through them too; counted per call, every one was the SMG entry bot and no room filled that way had a sniper (test_hassault_sniper.py)._choose_weaponpicks from what they hold, so a bot never asks for a gun the server would refuse. - The training range carries the loadout as well (
TrainingRange.setLoadout,training.rs::set_loadout), so Train hands you the guns a match does, unless the Range tab has picked a gun of its own.
Visuals borrow a base model. There are five view models, props and HUD
silhouettes, and twelve guns, so each weapon serves a model naming the one it
is drawn as (always concrete on the wire). weapon-visuals.ts and
WeaponSpec::visual / api::visual_slot are the one place a weapon id or a
wire index becomes a model, in each client. A skin is still looked up by the
weapon's own id, so a rifle skin does not appear on a Lancer.
Behaviour that used to be keyed on an id is now a served field: penetration
(how far a round carries through a wall), armorPen (the share of a vest it
ignores, which is how the sniper, now 115 damage, one-shots an armoured body),
and boltAction (the quick-switch rechamber cancel).
Sides, agents and visible skins
What a player looks like to everyone else is a cosmetics bundle
(backend/modules/hassault/cosmetics.py): an agent and the weapon skins, per
side, both sides in one document so a team swap needs nothing resent.
{"t": {"agent": {"id", "armor", "trim"},
"weapons": {weapon id: {skinId, name, baseColor, accentColor,
patternType, floatValue, seed, statTrak}}},
"ct": {...}}
- Built from the account's own rows, never sent by a client. On the game
server,
hassault_rooms.account_lookreads the seat's equips and itshassault.agentssetting (hassault_account.cosmetics) and itshassault.loadout(hassault_account.loadouts) at join. An equip, or a change to either setting, re-reads them for any room the account is seated in (refresh_account) and broadcasts the new look at once. A guest wears the defaults. - Equips are per side (migration
_m13_hassault_equips, keyed(account, side, weapon)):POST /account/equip?side=t|ct(or both, with no side) and/account/unequip.hassault_items.equippedsurvives as "on for some side", recomputed from the equips, and the inventory gainsequippedSides. The armoury shows T and CT toggles where the server keeps the account; a node's own inventory still has one equip per weapon. - Agents are a served catalogue (
GET /api/hassault/agents, node and game server alike), moved out of the browser'smodels/skins.ts. ARC agents play T, HALON agents CT, neutral either; a pick for the wrong side is that side's default (cosmetics.agents_for). - On the wire, never in a snapshot. The welcome carries
cosmetics({playerId: bundle}),joinedcarries the newcomer's, and acosmeticsevent carries a change. A snapshot goes to everyone twenty times a second and a look changes once a match;test_hassault_cosmetics.pyasserts the snapshot never carries one. - Node-hosted rooms take their own player's look from the game server when
the account is kept there (
account_sync.local_look), else from the node's inventory. A guest's node sends its look with the fabric join; the host runs it throughcosmetics.clean_bundle, which re-resolves the agent from its own catalogue and keeps a weapon entry only as valid colours on a real weapon. That is the same trust a nameplate gets: display only. - Drawn the same in both clients. The browser's
CharacterModeltakes the agent's colours (rebuilt when they change, since the wash is baked into the operator's materials) andsetWeaponSkinrecolours the held prop; native lays the look over each pose (app.rsdress_squad): the agent's wash as the pose's tint, the skin as the prop's two colours (held.rs). A skin belongs to the gun, not the model it borrows, so the lookup is by the weapon's own id. The first-person view model uses the player's own bundle for the side they are on, so a CT-only skin is not in their hands on T. - One palette, three ports.
cosmetics.paletteis the reference for how a skin's two colours spread over a gun made of boxes;viewmodel.tspaletteForandviewmodel.rspalette_forare pinned to it bycosmetics-vectors.json(scripts/gen_hassault_cosmetics_vectors.py), which also carries the agent list, the bundle wire and the per-side loadout cases.
Accuracy: stopping is what buys the shot
Every shot's cone is weapons.shot_cone(weapon, ctx), built by the server from
its own state after the step that carried the shot:
- The base is
residual_spread(the scope and the pattern already applied). - At rest (no shot within
recoveryTime)firstShotSpreadreplaces it if tighter: a tap is a different shot from a spam. - Crouching scales the base by
crouchScale. - Horizontal speed above a third of a run (
ACCURATE_SPEED_SCALE) adds up tomoveInaccuracyat full speed; being off the ground addsairInaccuracy. - A shot inside
recoveryTimeof the last adds a fadingperShotInaccuracy.
So counter-strafing's braking finally has an accuracy payoff, a jump-shot is a gamble, and a scoped sniper on the move is a miss. Movement itself is unchanged: AssaultCube's momentum and air control stay as they are. Every new field defaults to "no change", so a weapon nobody tuned fires as it did before.
The training ranges fire through ports of the same function (shotCone in
trace.ts, WeaponSpec::shot_cone), fed the player's real velocity, so Train
teaches the same thing about stopping to shoot. accuracy-vectors.json pins all
three and carries a weaponsSpecId content hash of the weapon table: retuning a
gun without regenerating the fixture fails the Python suite instead of leaving
the clients pinned against yesterday's numbers. It is its own file so that
tuning a gun never churns the movement fixture.
Walk. Shift is now walk, the CS convention: 52% of a run, silent like a
crouch, and above the accurate threshold on purpose, so a walking shot is
steadier than a running one but not free. It is a walk flag on the command and
a speed scale in all three physics ports, pinned by two cases in
physics-vectors.json. Sprint moved off Shift and ships unbound: the server has
never simulated it, so online it mispredicted on every press.
Firing is a flag on a movement command
There is no fire message. fire, reload, the weapon slot and viewT ride on
the ordinary input command, which buys three things:
- A shot carries the exact view angles and sequence number of the frame it happened on, rather than the angles of whenever a separate message was processed.
- The rate limiter spends from the same replenishing time budget as movement, so nobody's rifle fires faster than time passes — the anti-cheat that was already there covers weapons for free.
- The peer fabric forwards commands verbatim, so weapons crossed to remote matches with no changes to the fabric at all.
Fire rate and reloads are measured on that budgeted simulated clock, not on the wall clock. Commands arrive in batches — several trigger pulls are consumed in one tick — and gating on real time would drop all but the first and silently halve a 700 rpm rifle. Respawn timers are the exception and use the wall clock on purpose: a dead player stops sending commands, so a respawn on their simulated time would never arrive.
Lag compensation: rewinding to what the shooter saw
A shooter aims at what their screen shows, and their screen shows the past twice over: half a round trip of network delay, plus the ~100 ms of deliberate interpolation delay the renderer adds so remote players move smoothly. On a 60 ms link that is ~130 ms, and in 130 ms a running player covers nearly three cubes — more than their own width. Judging the shot against current positions would mean leading every target by a body width, which reads as "this game does not register hits".
So each room keeps a second of position history and resolves a shot against the world as the shooter saw it:
The rewind instant is client-supplied, and deliberately so: the client already
computes it (SnapshotBuffer.renderTime is literally "the server-clock time I am
drawing right now"), and using it is more accurate than the server guessing from a
latency estimate measured on some other packet.
That makes the clamp the security boundary, not a tidiness measure. view_t
is pinned into [now − MAX_REWIND_MS, now]. Unclamped, a client could ask to be
judged against a position from ten seconds ago and shoot people where they used to
be standing. PositionHistory.clamp is the only place that knows the current
time, which is why the range check lives there rather than in the wire parser.
The cost is the one every game with lag compensation pays: occasionally you take damage after stepping behind a wall, because on the shooter's screen you had not reached it yet. That is the honest trade — one of the two players has to be wrong, and it should not be the one who had to aim.
The hit model
A shot is a ray. raycast_world walks the cube grid with a DDA, because the world
is a grid: within each cell only two things can stop the ray — the cell being
solid, or the ray leaving the gap between that cell's floor and ceiling. A shot
across a 256-cube map is a few hundred cheap steps rather than a scene traversal.
Bodies are the collision cylinder — the same radius the movement code keeps clear, the same height the avatar capsule is drawn to, so what you see is what you hit. The top cube of it is the head.
Two rules do more work than they look like they do:
- A body is only a target if it is nearer than the wall. That single comparison is the whole of cover; without it every map is a shooting gallery with decorative geometry.
- A negative entry distance with a positive exit is point blank, not a miss. Standing inside someone is a hit at zero range.
Spread is sampled uniformly over the cone's area rather than uniformly in angle, or every pellet clusters at the centre and a shotgun behaves like a rifle at range.
Which face a pellet hit, and why it is on the wire
raycast_world_face returns the distance and which of the six faces stopped the
ray, as a small integer: the cell it stepped into was solid (and the step says
through which side), the ray fell below a floor, or it rose above a ceiling. It is
the outward normal — the direction pointing back at the shooter — so a ray
stepping +x into a block reports that block's -x face. Backwards, every bullet
mark is drawn on the inside of the wall it hit: invisible, and reported by nothing.
ShotResult.faces runs parallel to endpoints, and match.py puts it on the wire
as faces alongside ends. It is served rather than derived for the usual
reason: the server already knows it at the instant its own ray returns, and a client
recomputing it would be a fourth and fifth implementation of the world ray whose
only job is to agree with the first about the exact point the first chose. Half a
cube of disagreement is a mark inside a wall.
An index rather than a vector, because a grid has exactly six faces: a shotgun costs
eight small integers against the twenty-four floats ends already carries. -1
(FACE_NONE) means a body, or a shot that ran out of range — negative rather than a
seventh value, so a client that forgets to check gets nothing rather than a mark
quietly facing +x.
The per-pellet form also fixed something the per-shot hit flag could not: a
shotgun landing one pellet in a body and seven in a wall is hit: true, and the
native client's masonry dust was gated on it, so all seven lost their debris.
The fixture carries the face for every trace case — and carries null for one of
them. A shot fired at exactly 45° from a cell corner crosses its x and y
boundaries at the same instant, and which face wins is decided by the last bit of
cos(yaw): Python's math.cos(π/4) and math.sin(π/4) return the same double,
V8's return values one ULP apart. The generator probes for that by nudging the aim
vector by one ULP and dropping the face where the answer moves. The distance stays
pinned; only the coin flip is dropped.
Recoil is a pattern, not noise
Recoil used to be noise: a fixed upward kick plus (Math.random() - 0.5) sideways,
with the server resolving every shot inside a random cone. Nothing about that is
learnable, which for the game's one automatic weapon is the difference between a
skill and a dice roll.
The assault rifle now has a spray: a table of twenty absolute (yaw, pitch)
offsets from where you are aiming, indexed by how many rounds have gone out in this
burst. A near-vertical climb for the first seven, then a lateral wander — left, then
right, then a shallower drift — so the counter-motion is a shape rather than a
direction and the reward for learning it is real.
Three decisions that are each easy to get wrong in the opposite direction:
- Only the rifle has one. It is the only
auto: Trueweapon. A pattern on a 62 rpm sniper never survives its own reset gate — every shot is the first shot — and one on an 8-pellet shotgun would be fighting a cone twenty times its size. For the other fourspray = (), the index never advances, and the behaviour is bit-for-bit what it was before patterns existed. - The random cone is reduced, never removed.
residual_spreadis about a fifth of the cone it replaces. Zero makes the rifle a laser at two hundred cubes and erases the sniper's reason to exist; a residual is what keeps a pattern counterable rather than solved. - The table is at least a magazine long, so a full spray never has to hold at its last entry. Past the end it holds rather than wraps — a pattern that restarted mid-magazine would be unlearnable, which defeats the only reason it is a pattern.
The offsets are served on GET /api/hassault/weapons, and that is load-bearing
rather than tidy: the server aims the bullets with them and each client kicks its
camera with them, so the crosshair goes where the rounds go. A copy in TypeScript
or Rust would be a crosshair that lies, which is worse than having no pattern at
all. apply_spray works in view angles, not in the direction vector, so the
number the server adds to a shot is bit-for-bit the number a client adds to its
camera.
The
response_modeltrap.WeaponOuthas to declarespray,sprayResetandresidualSpreadas well asWeapon.to_dictreturning them — a Pydantic response model silently drops what it does not declare, andspray: []reads to every client as "this weapon has no pattern".TacticalOuthas carried that warning for a while andWeaponOutdid not, which is exactly why it is now written on both. The test asserts the route's JSON, notto_dict().
Absolute on the wire, a delta on the camera
The single easiest thing here to get wrong. The table is absolute because a spray
pattern is a shape on a wall that a player memorises; the camera accumulates, so
what goes on it is spray[i] - spray[i-1]. Applying the absolute walks the
crosshair away by the running sum of the whole table, and the weapon is unusable
within half a magazine — while looking exactly like a number somebody tuned badly.
All three suites replay a sprays block from physics-vectors.json that pins the
application, and combat.test.ts asserts the accumulated camera offset after N
shots equals spray[N-1] rather than their sum.
Only the climb is owed back to recovery. Giving back the lateral drift too would drag the crosshair sideways after a burst — the one motion a player cannot anticipate, because they did not put it there.
The spray index rides the simulated clock
MatchPlayer.spray_index resets when the trigger has been off for spray_reset of
player.sim_time, never of time.monotonic(). Commands arrive in batches —
simulate drains a whole queue per tick — so a wall-clock gate would disagree with
the fire-rate check about how much time passed inside one tick and pin every shot at
index 0: a rifle with no recoil, and nothing anywhere saying why. last_throw_at
documents the identical reasoning for grenades, and
test_two_commands_drained_in_one_tick_do_not_reset_the_spray is the direct
regression.
It advances only for a shot that actually went out; every early return in _fire is
a trigger pull that produced nothing. It resets on a weapon switch, on a reload, and
on respawn — every event that is recognisably "starting again".
The index is echoed to that player in their private view, and both clients adopt it rather than counting locally — predicted on the frame you fire, corrected on the next snapshot, exactly as ammo is. Without that, a shot the server refused (rate limit, empty magazine, dead) would kick the camera for a bullet that never left and leave the client one step out of phase for the rest of the magazine.
Four consumers, not two
The pattern is applied by the server, by the browser's camera, by the browser's training range, and by the native client — and a range that taught a different recoil than a match would be worse than no range, since learning the spray is what Train is for.
The native client is the one that needed new machinery. It had no view recoil at
all: cmd.fire rode every frame the key was held and try_fire was range-only,
so a deterministic pattern would have walked its bullets away from a crosshair that
never moved. It now rate-limits the trigger to the weapon's interval — the courtesy
the browser always extended, and without which a 700 rpm rifle sent thirty pulls a
second for the server to discard all but eleven of — and kicks the camera from
you.sprayIndex whenever it advances. Driving it from the server's index is a frame
or two late and exact, which is the right trade. Shake is untouched: it is a
copy of the camera by design, and turning it into recoil the server honours would
make a screen effect part of the aim.
The sniper's scope
The sniper is the one weapon with a scope, and the right mouse button steps through it: none → 2× → 4× → none. A cycle rather than a hold, because the magnifications are discrete — holding a button for 2× and needing a different gesture for 4× would be two controls for one axis. Weapons without a scope ignore the button rather than consuming it.
Three things move together, and all three come from the served zoomLevels
rather than a copy in TypeScript:
- The field of view is divided by the magnification. A scope narrows what you can see; it does not enlarge anything.
- The mouse sensitivity is divided by the same number, so a given movement of the hand sweeps the same distance on screen at any zoom. Without this, 4× multiplies every twitch by four and the scope is unusable at exactly the range it exists for.
- The cone the next shot uses, which is the mechanical half and the only part the server decides.
That last one is why the scope is a real choice and not a free magnifier. The
sniper carries a second cone, hipfire_spread, twenty-seven times its scoped one:
a 72-damage rifle that could be fired accurately from the hip would simply be the
best close-quarters weapon as well as the best long-range one. The crosshair
reads whichever cone is currently in force, so an unscoped sniper visibly is not
worth trusting.
The zoom step rides on the shot, as scoped, for the same reason fire rides
on a movement command: what the server does with it is pick the cone for that one
trigger pull. It is client-owned and server-clamped — client-owned because a
scope changes what you can see and how far your mouse moves you, both of which
already live on your machine, and clamped because the weapon you are holding
decides how far it can zoom. weapons.clamp_zoom does that clamping, and it does
it there rather than in the wire parser deliberately: the parser does not know
which weapon the command will be applied to, so a player switching from the sniper
to the shotgun mid-flight would otherwise carry a zoom level onto a weapon with no
scope — which is a request for the shotgun's hip-fire penalty to be silently
waived. The parser floors the claim at zero; the simulation owns the ceiling.
The scope drops on a weapon switch, on death, and when the pause menu opens. The FOV is the one piece of state here whose cause is invisible, so nothing should be able to leave you at 4× wondering why.
Bots scope too. _choose_weapon hands them the sniper past LONG_RANGE, and
without this the hip-fire penalty would land entirely on the bots — reading as the
bots getting worse rather than as the scope being a mechanic.
Health, death, and what is private
Health is public, in the shared snapshot rows: a wounded enemy is exactly the information that makes a firefight a decision rather than a coin toss. Ammunition is private, in the per-recipient envelope — it is nobody else's business how full your magazine is, and it would be sixteen extra numbers per packet for everyone. Hitmarkers go in the same envelope and are drained when it is built, so each is delivered exactly once.
Kills, deaths and team scores are tracked; friendly fire is off (a four-player match on a map with team spawns is otherwise decided by who turns around first); spawn protection lasts a second and a half and is forfeited the moment you fire, because otherwise it is not protection, it is a licence.
Shots are batched into the snapshot rather than sent as they happen. A rifle at
700 rpm would otherwise be its own message stream; batching makes combat cost the
tick rate rather than the fire rate, and the snapshot's fx list carries both
tracers and the kill feed.
Health is also lost to the map: see Shoot-jumping for fall
damage, which goes through _fall_damage rather than _apply_damage because a death
with no killer cannot be expressed by a function that needs an attacker for the feed,
the hitmarker and the score.
Recoil comes in two halves, and only one of them is local. The view climb is
applied client-side, because view angles are client-owned anyway — the server simply
uses whatever angles arrive, so a modified client could fire without climb. That is
the same class of concession as trusting dt, and the same answer applies: this is a
game you host for friends, and the budget caps how much any of it is worth. The
push on the shooter's body is not a concession: the server applies it from its own
weapon table, and the client only predicts the same impulse from the served
kickback. Nothing about the shove is client-supplied.
Being hit tells you which way to turn
The shooter gets a hitmarker; the victim gets an arrow. Both are private, both are drained as the envelope is built, and both are delivered exactly once.
pending_hurt carries a bearing and an amount, never a position — noise.py's
rule, applied for exactly its reason. Sending the attacker's coordinates so the
client could work the angle out itself would hand every player a wall hack that
triggers on being shot at, which is precisely the moment knowing where somebody is
standing is worth the most.
Three details that are each a decision rather than an oversight:
- No wall test.
noise.hearmuffles a footstep that came through a wall; this does not. Being shot is the evidence that a shot reached you, so attenuating the arrow would hide the direction of the one event that has already proved it has line of fire. - The weight is what the hit cost, armour included. A vest absorbing half a shot does not make it half a shot: the arrow is about where to turn and how urgently, and armour changes neither.
- A hit from exactly underfoot records nothing. Two bodies at the same x/y have
no direction between them, and
atan2(0, 0)is zero — an arrow pointing due east for a shot that came from below. Drawing nothing beats inventing a direction.
They are cleared on respawn, or an undrained arrow arrives in the first envelope of the next life and sends a player who has just come back somewhere across the map to look at nothing.
crouch joins health in the public rows, because it changes both what you see and
what you can hit — the avatar is drawn to that height and the server rewinds a shot
against it, and a crouching enemy that still presented a standing hitbox is the kind
of disagreement that makes a game feel dishonest. The movement block prediction
rebases on (you.move) and the noises you can hear (you.noise) go in the private
envelope with ammo, for the same two reasons: nobody else's business, and per-packet
cost.
Items on the map
Every .cgz has always carried item entities — cgz.ENTITY_NAMES has named them
since the reader was written — and for a long time they were parsed and dropped.
That had one visible consequence, recorded in Weapon.reserve: the sidearm had to
be bottomless, because a finite reserve on everything with no way to refill it
ends a long match with everybody standing around empty. pickups.py is the missing
half of that trade, and the reserve comment is now the reason items exist rather
than an apology for their absence.
Six kinds are placed: clips, ammo, grenade, health, helmet, armour.
akimbo is in every official map and is deliberately not placed — we have no
akimbo pistols, and putting something else there would be a lie about what the map
says.
What a pickup gives is ours, not AssaultCube's
AC splits clips (pistol) from ammo (your primary). We carry all five weapons at
once, so "your primary" names nothing, and a pickup keyed to whichever gun you happen
to be holding turns an item into a puzzle about inventory rather than a thing you run
over. Ours top up every weapon with a finite reserve, capped at what that weapon
started with, and the two kinds differ only in size — clips is the small one,
ammo the big one. Amounts are a multiple of each weapon's magazine rather than a
flat round count, because a shotgun magazine and a rifle magazine are not the same
amount of gun.
An item that cannot help you is not consumed. Running over the armour at full
armour, gaining nothing, and taking it off the map for forty seconds is the kind of
quiet unfairness that makes a map feel broken without anybody being able to say why —
so pickups.apply returns None and the item stays where it is.
A taken item is not removed: it is unavailable until available_at, which is what
makes an item a piece of map control. Everyone can learn when the armour comes back,
and a fight over that spot is a fight worth having.
Armour
AC has it; we did not, which left helmet and armour entities with nothing to do.
Rather than leave two of the six kinds inert — the silent no-op this module keeps
refusing — armour is a real mechanic: it absorbs weapons.ARMOUR_ABSORB (half) of
every incoming hit and spends itself point for point on what it absorbs, so a
vest is a fixed amount of protection rather than a permanent discount. A helmet caps
lower than a vest; two armour items with the same cap would make the small one the
large one for whoever found it first.
Three consequences worth keeping:
- Armour is private, unlike health. How much protection somebody is carrying is
exactly what you would like to know before starting a fight, and the public health
number already says how the fight is going. The shooter's hitmarker carries a bare
armour: true— "that one hit a vest" is feedback about the shot they just took; the remaining total is not theirs. damage_dealtcounts health lost, not damage rolled. It is the one stat a player can check against the health bars they watched go down.- Armour never cushions a fall.
_fall_damagegoes around_apply_damagedeliberately, and a vest that softened a four-storey drop would make the shoot-jump free for whoever holds the armour spawn.
You spawn with none: it is something the map gives you, and starting with it would make the item everyone fights over a top-up.
An item's z is the mapper's eye, exactly like a spawn's
pickups.place resolves every item onto the floor beneath it with physics._support
— the same query step resolves against — for precisely the reason
spawn_at does. Read verbatim, an entity's
z leaves items hanging in the air where nothing can run over them and nothing says
why. An item whose every supporting cell is solid is dropped rather than left
sitting inside a wall drawing attention to itself.
The resolved placements are served, on GET /api/hassault/maps/{name} as items
and again with a match's welcome. That is the plane_order precedent: resolving an
item's height is a real rule, and a second implementation of it in TypeScript would be
a Train mode whose items sit somewhere a match's do not. The item table — what each
kind gives, its respawn, and the pickup reach — is served too, on
GET /api/hassault/items, for the same reason interval and zoomLevels are.
Who is told what
The split is the one health and ammo already follow. The hole in the map is
public: the item visibly disappears off a floor everybody can see, so the shared
view carries itemsOut — the ids currently gone. That is the complement of the
usual state on purpose: a map with sixty items normally has a handful missing, so it
is a few numbers per tick rather than sixty. What it gave you is private, in
you.picked, drained like hitmarkers and carrying the amounts that actually
applied — a health pack taken at 90 says +10 hp, not +25.
On the client, an absent itemsOut is deliberately not read as "none are gone".
That would pop every taken item back into existence once a tick; absent means the
server does not do items at all.
A pickup is also audible (noise.PICKUP_LOUDNESS, quieter than a reload).
Standing on the armour is not free map control.
The bundled maps carry items
All three ship with their own layouts — armour on the contested ground, ammunition on the routes, clips in the corners. A bundled map with no items would make this a feature only the people who own AssaultCube can see, which is the exact asymmetry the licensing rule exists to prevent.
Playability is checked the way spawns are, and the checks caught real mistakes: every item must be standable and reachable on foot from a spawn, and no item may sit within pickup reach of a spawn — an item you can take on respawn turns dying into a resupply. That last one moved four of The Pit's items on the first run.
Drawing them
items.ts is a renderer for something the server already decided, the same contract
nades.ts has. Shapes are built from primitives — a health pack is two boxes in a
cross, an armour plate a bevelled slab — because AC's item models are its copyright,
the same rule the maps follow.
Two behaviours are load-bearing rather than decoration. A taken item sinks and fades but its floor ring stays, dimmed: players learn spawn timings off that ring, and an item that simply vanished would make the map's rhythm invisible. And the bob is driven by one clock shared by every item, so a whole map's items rise and fall together — a synchronised field is much easier to pick a missing item out of than a field with per-item phase.
Bullet marks
The world used to keep no memory of being shot at: a tracer for 75 ms, a blob at the
endpoint for 300 ms, and then a room that looked exactly as it had before the
firefight. Now every pellet that stops on a surface leaves a mark
(decals.ts / decals.rs), and they are not decoration — since recoil is a
learnable pattern (below), the marks on a wall are how you read back the pattern
you are supposed to be learning.
Both clients hold a fixed ring of DECAL_MAX = 256 marks: allocated once,
reused in order, so nothing is created per shot and the cap holds by construction
rather than by a trim that runs after every push. An automatic weapon puts thirty
marks on a wall in two seconds.
In the browser the ring is one InstancedMesh, not 256 meshes. A mark is a
slot: a matrix, a tint (instanceColor), and an opacity and atlas tile per
instance, read by a small onBeforeCompile patch on MeshBasicMaterial. The
three kinds (bullet, slash, stab) share one atlas, four 32 px tiles wide, so that
every tile edge falls on a texel edge at every mip level. As separate meshes, the
hidden marks still cost a matrix update each per frame, and every visible one was
a draw call of its own. decals.test.ts runs the shader patch against three's
own MeshBasicMaterial source, so a three upgrade that renames a chunk fails the
suite instead of quietly drawing every mark opaque.
Orientation comes from the served face (above), through six fixed quaternions
indexed by that face — never lookAt, whose axis convention differs between
cameras and everything else and is the kind of thing that is wrong by exactly 180°.
A mark is lifted DECAL_LIFT along its own normal and drawn with polygonOffset,
because a decal coplanar with its wall z-fights, and flicker reads as a bad
graphics driver rather than as a bug worth reporting. Depth is tested but never
written: marks overlap constantly, and a written depth makes the newer one fight
the older.
A mark holds full opacity for most of its life and fades only over the last
DECAL_FADE seconds. One that began fading immediately would never be quite
legible, and legibility across a whole magazine is the point.
Natively the marks ride the translucent volume pass — the one water and smoke
use — because alpha-blended, depth-tested, non-depth-writing is exactly what that
pipeline is for, so this needed no pipeline, bind group or shader of its own. They
are written into that pass's buffer first, deliberately: its vertex budget is
shared, an overflow only reaches divergence::note_overflow, and if it ever bites
it should be the newest transient effects that are dropped rather than the world's
record of the fight.
browser_parity.rs pins the cap, the lifetime, the fade, the lift, the size, and
the order of the six face normals across all three implementations.
The native marks are emitted in render coordinates — cube (x, y, z-up) →
render (x, height, y), mapped once at the push, the same way effects.rs,
nades.rs and water.rs do it. This is the one thing about them that failed
silently and did: the wire, the face normals and the quad's own arithmetic are all
cube space, so emitting the corners unmapped compiles, draws, and puts every mark
somewhere with its height and depth swapped — inside the geometry, invisible, and
indistinguishable from decals never having been wired up at all. Every unit test
passed throughout, because they were written in cube space too;
a_mark_comes_out_in_render_coordinates is the one that now reads the mapping.
Underneath that sat a second fault, and it was not the decals' own: the
volume pass faded itself with view_depth / max(camera.params.x, 1.0), reading
params.x as the distance at which fog is total. It is a fog density —
Quality::fog_density(), 0.0055 to 0.011 — which the world pass integrates as
1 - exp(-(density·depth)²). Being under 1, the max pinned the divisor at 1,
so every fragment of that pass more than one cube from the eye came out at
zero alpha: bullet marks, tracers, impact flashes, smoke, water and the throw
arc alike, all invisible except within arm's reach of the muzzle — which is why
the marks read as "stuck at the viewport where the gun is shooting". Both passes
now go through one shared fog_amount in lighting.wgsl.inc so they cannot
disagree about what the number means, and shaders.rs pins it as text: the
wrong version parses, validates and runs at full frame rate, so nothing else in
that suite could have caught it.
Surface material: what a mark looks and sounds like
A decal used to be one colour regardless of what it landed on, and a bullet
punching a wall made the same sound as one punching a doorframe. decals.ts's
surfaceMaterial() reads the hit cell's texture id off the served face
arrays (wtex/ftex/ctex — the map's own world.ts data, not a guess) and
buckets it into concrete / metal / wood / glass / default by a fixed
id table — the same limit the world renderer's own texture-id tinting is under
("No textures yet", further below): map .cfg files, which would name a
texture, are not parsed yet, so a material guess is only as good as the colour
guess the surface itself is drawn with, and both wait on the same missing
piece. That classification now feeds three things off one lookup, rather than
three separate guesses that could disagree:
decals.marktints the mark by material (MATERIAL_TINTS) instead of a fixed white, so a wall of pocked concrete and a shredded vent read differently at a glance.effects.impactSpatterspawns a short-lived, material-shaped particle burst — ricochet sparks off metal, splinters off wood, shards off glass, dust everywhere else — oriented off the served face normal, using the same fixed particle pool (MAX_LIVE) every other transient effect shares rather than a budget of its own.audio.surfaceImpactplays a per-material timbre (impact_metal,impact_wood,impact_glass,impact_concrete) positioned the same way every other sound in the mixer is — bearing plus listener yaw, never a raw stereo pan — so a shot's material is audible before the decal is in view.
A wallbang kill additionally plays impact_wallbang, a distinct low thump
gated on hit.wallbang in the snapshot (match.py already resolved this per
hit for the kill feed's isWallbang flag; this is a second consumer of the
same server-decided fact, not a new one) — audible confirmation that a shot
landed through geometry, which a normal hit marker doesn't distinguish.
This is browser-only for now, the same status the smoke wisp carries: the
native client keeps its fixed decal tint and has no particle burst or
per-material audio. browser_parity.rs pins what the native side does draw
(cap, lifetime, fade, lift, size, face-normal order); it does not yet cover
material, because there is no native material to compare against.
Bullet smoke channels
A round fired through a smoke cloud used to behave exactly like one fired through open air on the way in and then vanish into the cloud's opacity on the way out — the smoke didn't know it had been shot. CS2's mechanic is that a bullet punches a short-lived visibility tunnel through smoke it passes through, and it is implemented the same way every other simulation fact here is: on the server, because whether a sightline through smoke is currently open decides whether a peek is safe, and a client computing that itself could decide it differently for the shooter and the target.
grenades.Zone gained a channels list: (x, y, z, radius, expires_at)
tuples appended by match.py whenever a non-knife shot's endpoint ray crosses
a live smoke zone's sphere, capped at 8 per zone (oldest evicted) and pruned
every tick by expires_at. Two things read the list:
sight_blocked_by, reached throughMatchRoom.smoked()— the one call both a bot's line-of-sight check and the radar's "is this cloud in the way" logic go through, so a cloud is respected the same way by a human's eyes and a bot's — now walks a target ray against each active channel first and treats a ray passing through one as unblocked, the same way it already treats a ray that misses the zone's sphere entirely.Zone.snapshot()serialises the active channels as[x, y, z, remainingSec, radius]. Internally a channel stores an absolute expiry (time.monotonic()at append time, plus its 0.8 s life), because that is what a tick-by-tick prune compares against —snapshot()converts it to a duration (expires_at − now) on the way out, since a raw expiry timestamp means nothing to a client that doesn't share the server's monotonic clock. The radius goes on the wire too. The browser used to assume a hole 0.26 of the cloud's radius (2.7 cubes on a 10.5-cube smoke) against the server's 1.2, so it drew holes more than twice the size of the ones bots could see through.
Both clients carve a tunnel along the view ray, not on the cloud's surface:
a fragment is cleared where the line from the eye through it passes within the
tunnel's radius of its centre. That is the server's own question
(sight_blocked_by asks it of a line of sight), so the hole you see is the hole
a bot sees through. The browser's first version compared the sphere's surface
point with the tunnel's centre, which is inside the cloud, so a shot through the
middle never showed a hole at all. The native client did not draw tunnels until
this change. It now carries them in a small uniform (SmokeUniform, group 3 of
the volume pass) and runs the same test in smoke_tunnel.
The HE clearing goes out as seconds left (clearedFor), never as a moment.
It used to go out as cleared, the absolute time.monotonic() value, and the
browser compared it with Date.now() / 1000. Those clocks never match, so after
an HE the smoke stayed opaque on screen while the server let bots and the radar
see through it. Both clients now count clearedFor down locally, along with the
cloud's own left, so its opacity moves smoothly between 20 Hz snapshots. The
opacity curve (SMOKE_BLOOM, SMOKE_FADE, SMOKE_CLEARED) is one number set,
pinned between nades.ts and nades.rs.
One shape, every reader. A smoke can have lobes (volumetric_nodes), and
Zone.contains counted them while sight_blocked_by did not, so the edge that
stopped a flash was not the edge that stopped a bot. Zone.spheres() is now the
one shape both ask about, and both clients draw the lobes.
The client mirrors this rather than re-deciding it. net.ts's ZoneRow
carries the same channels field, and NadePool.punchSmoke() (nades.ts) —
called from HorribleAssaultPanel.tsx on every shot's impact endpoints,
alongside the existing decal/spatter/audio calls — both reproduces a channel
locally on the shooter's own screen (so the hole appears with zero added
latency for the person who made it) and reconciles against the server's list
on the next snapshot the same way NadePool.sync reconciles every other zone
field. A channel is stored as a point on the unit sphere local to the
zone ((hit − zoneCenter) / radius), not a world position, because the
cloud's own bloom/fade animates its radius continuously and a fixed-radius
hole would drift off the surface as the cloud grows or shrinks.
Visually, a channel is a soft-edged void carved into the volumetric shader's
density function (uChannels[8], a vec4 per hole: local xyz + fade-scaled
radius) rather than a hole in the mesh — the smoke shader already computes a
scalar density per fragment for its noise-driven bloom, so punching a channel
is one more term multiplied in, not a second draw call. NadePool.smokeDensityAt
— the same query the camera's own smoke-blindness shroud reads when the player
is standing inside a cloud — subtracts the same channel list, so a channel
punched near your own position also thins the first-person whiteout, not only
the view from outside the cloud.
backend/tests/test_hassault_smoke_channels.py pins the channel lifecycle
(creation, expiry, the 8-channel cap) and sight_blocked_by respecting an
active channel; decals.test.ts pins surfaceMaterial's texture-id buckets.
On the range
Train places the same items, from the same served placements, and resolves only the
ammunition half locally. Health and armour mean nothing where nothing shoots back
(hp there is a constant 100), and faking them would teach a resource cycle the range
does not have. They still draw: the map's item layout is a real thing to learn, and
a range missing two thirds of it would teach a map that does not exist. The reach and
the respawn come off the served table rather than being hardcoded — a copy would be a
range where items come off the floor at a different distance than they do in a match.
Water and ladders
Two more things the map has always carried and the simulation ignored: a
waterlevel in the header, and ladder entities in the entity list. Both are now
read, and both are decisions rather than ports — AC's water constants are tuned
against AC's gravity and jump, and this simulation already deviates from AC's
integrator (1-exp(-k·dt) rather than k·dt), so copying its numbers would be a
port in name only.
Water is a slow, safe, loud route
What water is for decides its numbers. You give up speed and the jump; you get a descent that costs no health and a body that is hard to hit cleanly. So:
- Two states, and the line between them is the eye, not the feet. Feet under the plane is wading: slowed, but you still have footing, sight and a jump. Eye under is swimming: no jump at all, because down there the jump key is the swim control. That line is exactly where the screen tint appears, so the moment you lose the jump is the moment the screen says so.
- Water replaces the crouch penalty rather than multiplying with it. There is no crouching in water, and two penalties stacking would make a crouched swimmer slower than a walk.
- Jump swims up, crouch dives, and diving is slower than surfacing — nothing about water should be a fast way to get anywhere.
- A body left alone sinks, slowly. Neutral buoyancy would make water a place you get stuck in.
The safe landing is mostly drag, not a rule: a body entering water sheds its speed over a few frames because water is thick. A landing while submerged then costs nothing outright, and everything shallower is helped in proportion to its depth. Gating that rescue on the feet instead of the eye would make an inch of water a total fall-damage negator — the puddle-dive that would put shoot-jumping back on a free ride.
A ladder is a volume you cannot fall out of
ladder entities carry a height; ladders_from resolves each into a span whose
base is the floor of its cell — the same "the entity's z is the mapper's eye"
problem items and
spawns have. A height of zero is
dropped, not read as unbounded: a mapper who never set the attribute meant "I did
not finish this", and an infinitely tall ladder is a hole in the map's physics.
Inside the volume, gravity is off and the climb is driven by the input. Three rules make it behave, and each was a bug first:
- The climb is
forwardprojected onto where you are facing. Strafing along a ladder does not climb it, and running past one with forward held does not launch you up it — the alignment is near zero when the ladder is off to your side, so the volume merely stops you falling for the frame you are inside it. - While the input is climbing, it is not also walking. Without that grip, pressing forward into a ladder both climbs it and walks you through it, and pressing back to descend walks you straight out of a two-cube volume — which made descending effectively impossible at 0.45 of run speed.
- At the last rung, pressing up lets go entirely. Releasing only the horizontal grip leaves the body attached while it walks forward off the top, and walking forward carries it across the ladder's centre — where "toward the ladder" reverses, the alignment flips sign, and the input that was climbing up starts climbing down. A player stepping off the top would ride the ladder back to the bottom.
Jump pushes off from anywhere on the ladder, and strafing walks off the side. A climber accrues no air time, so stepping off the top falls at plain gravity rather than at whatever the ramp had reached, and a long climb is never charged as a fall.
Three implementations, one fixture
Water and ladders land in physics.py, player.ts and apps/native-fps's
physics.rs in the same change, because that duplication
is only safe while the conformance fixture binds it. Thirteen new cases in
physics-vectors.json cover both, and the ladder cases put the ladder in as an
entity so all three sides run their own ladders_from — the derivation is part
of what is pinned, not a span handed to each of them.
Two things the fixture caught that no unit test would have:
eyeHeightmeans different things in different languages. Inplayer.tsandphysics.rsit is the absolute eye position and already includesz; inphysics.pyit is the offset above the feet. Two of the three ports ofsubmergedaddedzto it and double-counted, which reads as a swimmer who sinks while the server says they are rising.- The generator had lost the hitbox stamp.
scripts/gen_hassault_vectors.pyno longer wrotehitboxSpecId/hitbox, while the committed fixture still carried them and both suites still checked them — so the first regeneration silently dropped two guards. Restored in the same change.
Two level formats: cube and gltf
MapInfo.format (backend/modules/hassault/models.py) is "cube" or "gltf",
and it decides which of two entirely separate world and physics paths a match
runs on.
cubeis everything above: a Cube 1 2.5D heightfield read out of a.cgzor built from our JSON brushes, walked by the ported AssaultCube physics.gltfis a full 3D mesh with collision hulls.hd_facilityandhd_junkfleaare the first two, and the pane fetches their geometry fromGET /api/hassault/maps/{name}/mesh— a route that answersnullfor a cube map rather than existing conditionally.
A map declares its own format: both new maps carry "format": "gltf" at the top
level of their JSON, and routes.py reads it. There is also a hardcoded
name in ("hd_facility", "hd_junkflea") check immediately before that read, which
is redundant with the declaration and reachable only for those two names — a third
gltf map needs the declaration and nothing else. Worth knowing before adding
one, because the shape of that line invites you to append to it.
The heightfield physics runs on every map
It did not always. The three ported implementations (physics.py, player.ts,
physics.rs) and the physics-vectors.json fixture that binds them describe the
cube path, and a match on a modelled map has always stepped that path against
the grid the map bakes. Offline Train on a modelled map used to run a Rapier
capsule against the render mesh instead (physics-rapier.ts, physics_rapier.rs),
with its own sprint, slide, stamina and step height, and nothing replaying it
against the other port. Since G4 Train steps the grid as well, so there is one
movement model, the one the fixture pins. physics_rapier.rs survives only as a
probe over the drawn mesh in the native content tests. See
After G4: one curve and an adaptive render clock.
On the bundled maps
The Pit is flooded to its rim (waterlevel 0, pit floor -5), which turns the
centre into a pool you swim in rather than a hole you fall into: the drop is safe,
the armour at the bottom is contested, and you cannot jump while you are down
there. Two ladders climb out of it — deliberately slower than the stairs, since
a ladder that beat them would make the stairs decoration.
Both are checked the way spawns and items are, and the checks encode a real trap:
our body is 2.2 cubes wide, so a ladder placed flush against the lip it serves is
already stood on by anyone at its foot (_support takes the highest floor the body
overlaps), while one placed too far back drops you off the top before you reach the
ledge. So the test climbs each bundled ladder the way a player would and insists
on arriving somewhere standable. A separate check refuses a water plane above every
floor, which floods a whole map while its source looks completely ordinary.
What draws them
water.ts is one double-sided plane at waterlevel, in the map's own
watercolor — a mapper who chose green water meant it. One plane is an exact
depiction rather than an approximation: Cube 1 water is a single global height,
with no per-cell water. It is drawn from both sides because you spend real time
under it, where the surface is the ceiling of the pool.
ladders.ts draws rails and rungs from boxes, at the width of the volume rather
than of a real ladder: the catch radius is two cubes, and a slender ladder drawn
in the middle of it would teach players to aim for a rung when what actually
catches them is a cylinder. Drawing the rule is the same choice nades.ts makes
for a smoke cloud.
Entering or leaving the water is a noise — louder than a footstep, and resolved per recipient like every other one. Swimming itself is quiet, which is what makes water worth using once you are already in it.
The native client draws all of it too — see Map objects in the native client.
Thrown utility: smoke, flash, incendiary, HE
weapons.TACTICALS used to be a table of grenade numbers served over
GET /api/hassault/tacticals with nothing behind it — no throw, no fuse, no
detonation, no effect. It was the same shape of bug the post-match card had
before results.py: a description of a feature standing in for the feature. A
client that laid out a HUD from that list was showing a loadout the server had
never heard of.
backend/modules/hassault/grenades.py is the simulation, and like weapons.py
it is server-side and authoritative. Where a grenade lands decides a round, so
a client that computed its own bounce would be a client that could decide one.
The four resolve differently, which is why each gets a branch
They differ in when they resolve, not only in what they do:
| Resolves | Leaves behind | |
|---|---|---|
| HE | once, on a fuse | nothing |
| Flashbang | once, on a fuse, per victim | nothing |
| Smoke | continuously, for 15 s | a Zone that blocks sight |
| Incendiary | on impact, then continuously for 8 s | a Zone that burns |
A single "grenade with a radius and a damage number" would have had to special case all of that anyway, with the branches spread across the caller rather than collected in one place.
The incendiary is the one that detonates on contact (impact), and that is its
defining property rather than a detail: it is aimed at a place, so a throw that
lands right must not then be spoiled by the grenade rolling somewhere else.
Everything else cooks on a timer, which is what makes bouncing one round a corner
work at all.
A flashbang blinds: hold, fade, afterimage
The flash was resolved per victim from the start, but it did not blind anybody.
flash_strength returned one number, 0..1, and that number did two jobs: the
overlay drew its square as the whiteness, and the server faded it linearly over
six seconds as the duration. A flash at medium range came out at 0.5, which drew
as a 25% white wash for three seconds: never a white-out, just a nuisance. The
facing term was linear in the dot product too, so a flash 90° off still got
five-eighths of a frontal one and one directly behind got a quarter. Turning
round halved a flash rather than countering it.
It is now modelled on Counter-Strike's, which is the version players already know how to play against:
- Whiteness and duration are separate.
grenades.flash_effectreturns aFlashEffect(peak, hold, fade): how white at its height, seconds held there, and seconds to clear. Distance shortens the hold and the fade. It does not make a frontal flash grey. A full one is 2.8 s held and 3.6 s clearing. - Distance falls off as
1 - (d/r)², not linearly (_flash_reach), over a 44-cube radius. A linear falloff made the flash a point-blank weapon: a throw across a room kept half its length. Now half the radius keeps three quarters. - Facing picks a band, by angle off the crosshair (
FLASH_BANDS). Within 53° (the edge of a 16:9 screen) is a full flash. 53–72° is white with 80% of the hold. 72–101° is still white, with half the hold and 70% of the fade. Past 101° it stops at 0.8 white with a fifth of the hold. The strengths follow Counter-Strike's ownRadiusFlash, which keeps about two thirds of a flash side-on and over a third facing away: turning away shortens a flash, it does not cancel one. WithinFLASH_POINT_BLANKthe band is never worse than the second one, because light that close wraps round your head. - Light is sampled from six points round the bang (
FLASH_PROBES), so a flash half round a corner is half a flash. With one ray to its centre, a lip of floor between you and it was a hard zero. - A smoke between you and the bang stops it. A cloud dense enough to hide a player is dense enough to hide a flash. The exception is a cloud you are inside, where the smoke is around you rather than between.
- A second flash replaces a weaker one and never adds (
apply_flash, by dose). Two flashes a second apart are the same white screen, not twice as long a one.
The wire carries the inputs, not the output. you.flashPeak, flashHold,
flashFade and flashFadeTotal are seconds remaining. Each client runs the
shared curve, flash_alpha (held at the peak, then an ease-out 1 - (1 - t)²
down, so the screen is still three quarters white half way through the fade), at its own
frame rate, and counts the hold and fade down between snapshots exactly as
MatchPlayer.step_flash does. Drawing you.flash as received was a 20 Hz
staircase. The curve and the countdown exist three times (grenades.py,
flashbang.ts, flashbang.rs) and __tests__/flash-vectors.json, written by
scripts/gen_hassault_flash_vectors.py, binds all three.
you.flashed is drained per recipient like hits, and is the single trigger for
the two things that happen once per flash:
- The afterimage. The last frame you saw stays burned in under the white
while it clears. That is why turning to face a blank wall helps. The browser
copies the WebGL canvas in the same frame it was drawn (
flash-layer.ts; the drawing buffer is gone by the next task) into a half-resolution canvas under the white. The native client copies the scene into a half-resolution texture in the post pass (fs_capture) and blends it in the composite. - The ring. A narrow band of noise at 4.1 kHz with a sine under it, lasting as long as the flash. Synthesized, not sampled, and played round the muffle.
While the screen is white the world's sound is muffled too: a low-pass from
open down to 700 Hz at full white, interpolated in log frequency
(muffle_hz). This is a gameplay effect, not mixing taste: a flash costs you
your ears as well as your eyes, which is most of why a flash before a push
works. It is not the "ducking" the mixer has a recorded decision against. The
ring, muffle and afterimage constants are pinned between the clients by
browser_parity.rs.
Blind means blind for everyone, not only humans. Above FLASH_BLIND (0.6)
a bot's _visible returns false and an ally paints nothing on the radar, because
a radar fed by a teammate staring at a white screen is a wall hack with a delay.
Between FLASH_DAZED (0.15) and 0.6 a bot's aim error grows up to sevenfold. A
blinded bot backs away from where it last saw somebody rather than walking on
through them. Bots also used to throw their flashes flat at an enemy they were
looking at. Now that flashes affect them that would blind themselves, so a bot
lobs its flash and then turns its back and looks at the floor until it has gone
off.
The thrower is told what the flash did, as counts only: you.flashAssists
(enemies, teammates, longest blind), never who or where, by the noise.py rule.
Both clients show it under the crosshair ("FLASHED 2 · 1.9s", or "TEAM FLASHED"
in red when it caught nobody but your own side). Only a real blind counts: a
flicker behind somebody's back is not an assist.
There is no spectator view server-side yet. When one arrives it should mirror the followed player's flash fields, as Counter-Strike does.
Equipping a grenade, and what the mouse buttons mean
Selecting used to only ready a grenade: the gun stayed up and throwing was its
own key (G overhand, H underhand). A number key now equips — the weapon
holsters, the grenade comes into your hand, and the two mouse buttons become
left to throw, right to toss.
That is why it equips rather than merely readying. A global right-click toss
would take the scope away from the sniper, whose entire identity is that scope;
with the grenade in hand there is nothing else the two buttons could be doing, so
they are free. A weapon key puts the pouch away, and a throw auto-holsters on the
frame the grenade leaves — a throw is one action, not a mode you have to leave.
G and H still work: a player who has learned them should not lose them
because the default moved.
None of this goes on the wire. The obvious implementation — asking for a weapon switch while a grenade is up — puts
weapon: non the next command, and_handle_combatcancels an in-flight reload on a switch. Taking out a grenade would silently abort a reload and cost a real switch delay. So the holster is the view model's cosmetic one and the trigger is stopped by a localblockedflag. The server has no concept of an equipped grenade and needs none:_throwreadscommand.nadeand nothing else.
ShotController.setBlocked sits after the reconciliation half of frame,
deliberately: the slot, the scope clamp, the ammo and the reload correction are
the server's word about what you are holding, and they have to land whether or
not you can currently shoot it. Skipping them would leave the HUD describing a
weapon you put away two seconds ago.
Selecting an empty slot still equips — the HUD shows the zero, which is a better answer to "why did nothing happen" than silently readying a different grenade — and the pouch auto-holsters when the last one is gone, so nobody is left with the weapon stowed and both buttons doing nothing.
The predicted arc, and the constants it is served
Running and jumping have always fed a throw. throw_velocity has added the
thrower's own velocity at THROW_INHERIT (0.6 of it) since grenades existed.
A jump is carried at THROW_INHERIT_UP, 1.25 — Counter-Strike's figure —
so a throw released on the way up leaves with 24 cubes a second more height
than a standing one and flies much further. It applies to rising only; falling
keeps 0.6, or dropping off a ledge would spike the grenade into the floor. It
is served as throwInheritUp, and a client that predates it reads
throwInherit for both. Nothing on screen ever said any of this: the only way to learn it was to notice grenades
sometimes going further than expected and guess why. While a grenade is equipped
both clients now draw the arc it would take.
Two things make it honest.
Everything is served, on a route of its own — GET /api/hassault/throw →
ThrowPhysicsOut, read from grenades.py and physics.GRAVITY rather than
retyped. A preview integrated with numbers a client invented would be an aiming
aid confidently pointing somewhere the grenade will not go, which is worse than
drawing none; a client that cannot reach the route draws nothing.
A new route, not a reshaped
/tacticals. That one isresponse_model=list[TacticalOut], and turning it into an object to carry the throw constants would make every already-installed native binary deserialise an empty list and show no grenades at all, with no error anywhere. A test pins its shape rather than leaving it to a future refactor's judgement.
It stops at first contact. step_grenade bounces, and bouncing is chaotic: a
1e-6 disagreement in the floor comparison flips a bounce and puts the marker in
the next room. A learnable feature that is confidently wrong is worse than one
that stops early, so the arc ends where the grenade first touches something —
which is stable, and is what a player actually aims with. The landing ring is
drawn only when that contact was the ground: a grenade that clipped a wall
carries on somewhere the preview does not follow. Full bounce prediction is on
the roadmap.
The arc is built from the locally predicted velocity, not the last snapshot's. A velocity half a round trip old would lag exactly the movement the preview exists to show.
physics-vectors.json carries a throws block replayed by all three suites —
the origin, the velocity and the contact point — with a deliberately looser
tolerance than the rest of the file, stated in the file: 1e-9 is right for a
single movement step and wrong for an integrator run for two seconds, where the
three ports' float widths diverge steadily. Pinned tighter it goes flaky, and a
flaky test gets deleted rather than fixed.
A throw is a flag on a movement command
Exactly like firing, and for the same reason: the throw has to carry the yaw, pitch and velocity of the frame it left the hand on. A message of its own would arrive with none of them and the grenade would leave in a direction the player was no longer looking. It also meant the peer fabric — which forwards commands verbatim — carried grenades across the wire with no changes at all.
Because throw rides on a command, two things are load-bearing:
- The client edge-triggers it.
GrenadeController(utility.ts) turns a key press into exactly one flagged command. A key read as held would set it sixty times a second, the server's cooldown would accept one and discard the rest, and the player would see one grenade for a key they held with nothing to explain where the others went. - The server rate-limits it anyway.
THROW_COOLDOWNis spent from the same simulated clock the fire rate uses, so a stuttering client cannot throw faster than a smooth one.
What each player is told, and what they are not
The same rule noise.py established, applied to utility:
- A grenade in the air and a cloud in a doorway are public. They are things on
everybody's screen; withholding one somebody is looking at would be worse than
useless. They ride in the shared half of the snapshot as
nadesandzones. - How much utility you have left is private, exactly like your ammo. It sits
in
you.nades. - How blind you are is private, and it has to be: a client told how blind everyone else is could draw them through the flash.
grenades.flash_strength is resolved per victim on the server, because only
the server holds the three things the answer depends on — where that player was
looking, how far away they were, and whether a wall was between them. Turning
away is the counter every player knows, and it works here because it is the dot
product between the view direction and the direction to the bang. Broadcasting
"a flash went off at (x, y)" and letting each client decide would make not being
blinded a client-side setting.
The rules that would be bugs if they were missed
- A blast checks line of sight. A radius test without one kills people
through floors, and it is the single most common way a grenade system is
wrong. The ray is the same
raycast_worlda bullet uses, so a grenade, a bullet and a bot's eye all agree about what a wall is. - Smoke stops vision, not rounds. Spraying into a smoke stays a real (and punished) decision rather than a free wall.
- The bots have to respect the cloud too.
MatchRoom.smokedis asked byBotBrain._visible, not only by the renderer. A smoke that only humans respect is not a mechanic, it is a handicap — the bot would keep shooting through the one thing you threw to stop being shot. - Your own HE hurts you, and credits nobody. A grenade at your own feet is
your own fault, so it goes through the same no-killer path as fall damage
(
_fall_damage). Routing it through_apply_damagewould award you a kill on yourself and put you on your own scoreboard line. Teammates are unhurt — friendly fire is off for bullets and a grenade cannot be the exception, or every team fight is decided by whoever throws first. - The projectile is stepped on the room's clock, not on its thrower's simulated time. Movement and fire rate are paced by a player's own commands because they belong to that player; a grenade belongs to nobody once it is thrown, and pacing it by its thrower would freeze it mid-air — fuse and all — the moment their connection stuttered.
- Blindness fades on the room's clock too, for the same reason: a blinded player who stops sending input must still recover, or being flashed while alt-tabbed is permanent.
Drawing it
The browser's smoke is volumetric rather than a billboard — nades.ts shades the
puff with self-shadowing and highlights so it reads as a body of smoke you are
looking into, which is the difference between a smoke that hides a lane and a
sprite that sits in front of it. It is a rendering choice only: what a smoke
does to a shot is resolved server-side, and isThroughSmoke on a kill comes
from that resolution, never from what either client drew.
nades.ts is a renderer and nothing else — position, cloud centre and radius all
arrive in the snapshot. Two decisions in it are worth keeping:
- A cloud is drawn as a sphere the same size as the one the server tests against. A particle billboard cloud looks better in a screenshot and is a lie in a firefight: its visual edge is nowhere near the volume that actually blocks sight, so players would learn a shape that does not match the rule.
DoubleSideanddepthWrite: falseare what make walking into a smoke work. With front faces only, stepping inside puts the camera past the geometry and the cloud disappears exactly when it should be blinding you.
Throwing in the native client
The native client drew grenades long before it could throw one. nades.rs
rendered everybody else's canisters and clouds, SelfState.nades and
SelfState.flash were parsed on every snapshot, and none of the three had a
producer or a consumer: there was no /tacticals fetch, no key that readied
anything, no throw on the wire, no tray on the HUD, and a flashbang going off in
your face did nothing at all. A native player was on the receiving end of a
mechanic they could not use — which is a worse state than not having it.
The throwing half is apps/native-fps/src/utility.rs, a deliberate port of the
browser's utility.ts rather than a second design. Two clients play the same game
against the same server, and a rule that exists in only one of them is a rule half
the players are not subject to. It carries the same four:
- The throw is edge-triggered, which is the whole reason the type exists.
throwrides on a movement command, so a key read as held sets it sixty times a second — the server's cooldown accepts one and silently discards the rest, and the player watches a full pouch become one grenade with nothing to explain it. - Counts are predicted and then corrected. The count drops locally the instant
you throw and is overwritten by
you.nadeson the next snapshot, so a throw the server refused gives the grenade back rather than leaving the HUD one short until the next respawn. - Selecting equips; G throws only what is equipped.
6–9take a grenade in hand, thenGthrows it andHlobs it underhand — the browser'sDEFAULT_CONTROLS, key for key. With a gun up,Gdoes nothing. When the moment you throw a smoke is a different decision from which smoke you are holding, a select-that-throws cannot express waiting. - A
SelfStatewith no inventory does not empty the pouch. Train produces one, and adopting it blindly would silently disarm the one mode you would practise a smoke line in.
Three things around it that fail silently if they drift:
- The catalogue is fetched, never tabulated. The wire carries a slot index,
not an id, so a local list of four grenades that drifted by one from
grenades.GRENADESwould throw a smoke where the player asked for a flash and report nothing anywhere. A node that serves none leaves the tray empty and the throw key inert — which is a game missing a mechanic, not a client that guessed. throwis a Rust keyword, soCommand's field isr#throwand serde has to strip ther#on the way out.match.pyreadsraw.get("throw"): if the key were ever spelled otherwise the command would still be accepted, the movement still applied, and the grenade would simply never leave the hand. A test pins the serialized key.nadedefaults to-1, not0. Slot zero is the HE, so a zero default makes every movement command a request to throw one — harmless only for as long as nothing readsnadewithout checkingthrowfirst.- The cooldown is measured on
clock_ms, notlocal_clock. The latter is Train's own clock and is advanced only bytrain(), so in a match it sits at zero forever and a cooldown measured against it would never elapse.
The HUD gained the other two halves. The tray is four cells above the ammo
block — the same information as the browser's NadeTray and deliberately not the
same drawing, because this HUD is a vertex buffer with a 7-pixel bitmap font and
has no SVG to put a glyph in, so a three-letter abbreviation earns its place. An
empty slot is greyed rather than hidden: the tray's order is the wire's slot
index, and a cell that vanished would shift the others under keys the player has
already learned. The flashbang is you.flash drawn as a white-out over the
world and the HUD and under the console — squared on the way in, as the browser's
FlashOverlay does, so the peak is what hurts and the tail clears quickly.
And the sound: audio.rs had no timbre for throw, explosion, nade_flash,
nade_smoke or nade_fire, so every detonation fell through to the footstep
fallback and an HE at your feet sounded like somebody walking past. Your own throw
is played locally, because the server sends a throw noise to everyone else —
your own noises never come back, so the thrower was the one person in the room who
could not hear it leave their hand.
Grenades are not predicted. Unlike movement — where the client predicts because it cannot wait a round trip to know where its own feet are — nobody is holding a grenade after it leaves the hand, so there is nothing to feel laggy. Positions are interpolated toward the newest snapshot, which is cheap precisely because nothing is predicted: there is no correction to fight with.
The radar
Teammates are shown unconditionally — that is a radio, and every team shooter
works that way. An enemy has to have been seen by somebody on your side, and
that decision is MatchRoom.spotted_by on the server, because only the server
holds what the answer depends on: the level's geometry and the smoke standing in
it. It arrives as you.spotted, per recipient, next to the noise envelope and
for the same reason — a shared list would be one team's information sitting in
the other team's packet.
Three conditions, each a counter a player can use: range, facing (walking past somebody with your back turned does not paint them), and sight — which a wall stops and so does a smoke. That last one is most of the reason to throw one; a cloud that blocked eyes but not the minimap would be worth almost nothing.
The order those are tested in is load-bearing: range and facing are arithmetic on
numbers already in hand, and both run before raycast_world walks the level.
Reversing them would not change a single answer and would cost most of what the
radar spends.
It is a team's answer, not a player's
An enemy is painted when anybody on your side can see them — so spotted_by
reads its viewer only through viewer.team, and every player on a side gets a
list that is not merely similar but identical. It was nonetheless recomputed once
per recipient, which made the total work per tick
N recipients x (N/2 allies x N/2 enemies) = O(N³)
spotted_for_team is the real signature of the question, and
MatchRoom.spotted_by_team computes it once per team per tick. _broadcast
builds it alongside rows and shared_view and hands it down, so the work
becomes
2 teams x (N/2 allies x N/2 enemies) = O(N²)
Cubic to quadratic, which is the part that matters — at sixteen players it is a
9x cut in raycasts (216 to 24 on hd_atrium), and the gap widens with every
player added. That is why this was worth doing while still costing only 5% of the
tick budget: MAX_PLAYERS rising or the tick rate going up is exactly the change
that would have made it hurt.
It is deliberately computed once and passed down, not cached inside
spotted_for_team behind a tick number. A cache has to answer when it goes
stale, and the honest answer is "whenever a position changes" — which a tick
counter does not know, since simulate moves everybody within one tick value.
A test that broadcast twice without advancing the tick would have been served the
first answer.
The thing that must never break here is that per-team does not become per-room: two tests assert the sides get different radars, and both fail if one team's list is handed to everybody.
It is a fairness rule, not an anti-cheat one, and it is worth being honest about which. The shared rows already carry every player's position, because the renderer needs them the instant somebody steps into view. A modified client could always draw a full radar. What the spotting rule buys is that the radar the game ships shows the same thing to everyone, and that a smoke does the same job on it that it does on screen.
The map outline is rasterised from the cube grid the client already downloaded, so the radar costs no extra request and no extra byte on the wire — and it is rasterised once per map into an offscreen canvas, because walking a 256×256 grid sixty times a second to draw the same walls is how a minimap ends up costing more than the game. By default it is rotated so up is where you are looking: north-up is easier to draw and much harder to read under pressure, because it makes every glance a mental rotation before it is information. North-up is a setting (below) because plenty of players learn maps the other way.
What is on it
The radar used to read as a black disc: a 16%-alpha floor plan over a 72%-alpha ground. It now draws, bottom to top:
| Layer | From |
|---|---|
| Floor, in six height bands (upper levels lighter) | World.floor, already downloaded |
| A faint 16-cube grid | nothing — it is a scale to read distance off |
| Bomb sites as amber discs with their letter | mode.sites (welcome) |
| Wall outlines, crisp, one segment per straight run | wallEdges, built once per map |
| Your own noise ring (CS2's "how far am I heard") | the client's own synthesised sounds |
| Enemy footstep blobs | you.noise entries with foe and est |
Last-known ? for a contact that stopped being spotted | positions already received |
| Gunfire dots at the shot's origin | you.heard |
| Teammates, spotted enemies, a ring round the bomb carrier | players, you.spotted, mode.bomb |
| The bomb when dropped or planted (pulsing faster as the fuse runs) | mode.bomb |
| Tactical pings | you.pings |
Everything that decides where something lands, how big it is or what colour it
is lives in radar-view.ts and is replayed natively from radar-vectors.json
(see the two clients).
Settings — CS's cl_radar_*
| Row | CS | Default | What it does |
|---|---|---|---|
hassault.radar.scale | cl_radar_scale | 0.7 | 0.3–1.3; lower is more map. Span = 110 × 0.7 / scale cubes |
hassault.radar.hudScale | cl_hud_radar_scale | 1 | 0.8–1.3, the instrument's size |
hassault.radar.iconScale | cl_radar_icon_scale_min | 0.6 | 0.4–1, every blip's size |
hassault.radar.centered | cl_radar_always_centered | on | Off stops the view at the map's edge, so the arrow walks off-centre |
hassault.radar.rotate | cl_radar_rotate | on | Off is north-up with a turning arrow |
hassault.radar.fullOnScores | cl_radar_square_with_scoreboard | on | The whole map, north-up and 1.5× larger, while Tab is held |
hassault.radar.soundPings | — | on | Footstep blobs. Gunfire dots are not optional |
The pro preset from the CS guides is scale 0.4, rotate off, centered off,
iconScale 0.4, hudScale 1.3. Radar zoom (radarZoom, M by default) is
held: it clamps the scale to 0.4 until released — the +radarzoom alias, without
the console. It never zooms in a radar already set wider than that.
Gunfire and footsteps on the radar
The rule is the CoD/Battlefield one, kept honest by the noise system's own invariant:
- An unsuppressed shot puts the shooter's origin on the other side's radar
for
HEARD_SECONDS(2.5 s): a red dot with a ring going out on arrival. It is frozen where the shot was fired — a dot that followed the shooter would be a wall hack on a timer — and it reaches a side only if a living member of that side could actually hear it (noise.hear: same falloff, same wall muffle).MatchRoom.heard_by_sidebuilds it once per side per tick, likespotted. In a free-for-all each player is their own side. - A suppressor opts out entirely, and now also shortens the shot's audible
radius by its
noise_mult(−60%), which was declared on the attachment and never applied. - Footsteps, landings, reloads stay bearing-only on the wire. Two optional
envelope keys make them drawable without making them a position:
foe(the source is on the other side) andest, how far away the noise sounded, quantised to 8 cubes from the perceived volume — so a wall makes a footstep read farther away, which is exactly what your ears gave you. The blob is soft, four cubes wide and anchored where you stood when you heard it.
Shots also now stamp MatchPlayer.last_fire_time, which PVS culling had been
reading (and nothing writing) — so a shooter behind a wall was culled as if
silent.
The training range
Train enters the map alone. For a long time that also meant entering it
unarmed: ShotController needs a SelfState to fire, offline there is nobody to
send one, and the ammo HUD was gated behind being in a match. The result read to a
player as "this game has no shooting" — which is a fair reading of a game where
the trigger does nothing.
training.ts plays the server's part locally. It owns ammo, reloads, a set of
static dummies and the hitscan against them, and hands back the same
SelfState a snapshot would have carried. That is the whole trick: the trigger,
the crosshair, the recoil, the ammo counter and the view model all take the
identical path they take in a match, because they are handed the identical object.
A trigger that behaved differently in training is a trigger training cannot teach
you — and shoot-jumping in particular, which is one of the techniques the mode
exists for, cannot be practised without a working gun.
Nothing in it is authoritative and none of it goes on a wire. In a match the server owns every one of these decisions and the file is not consulted. That is also why it can be simple: no rewind, no lag compensation, no validation, because there is exactly one client and it is the only thing that exists.
Two details worth keeping:
- Dummies are
PlayerRows, so the existing avatar pool draws them. A target that rendered differently from a player would be practice against something the match does not contain. - They stand on the map's own spawn points, nearest first, never the one you are standing on. A bundled map guarantees every spawn is standable — that is what the playability test checks — so this cannot put a dummy inside a wall on a map it has never seen.
Shot geometry exists three times now
trace.ts is a port of raycast_world and ray_hits_body, because the range has
no server to ask where a shot stopped. That makes shot geometry a third rule with
two implementations, after physics.py/world.ts.
The answer is the same one movement gets: physics-vectors.json now carries
traces and bodies alongside cases and spawns, generated from the Python and
replayed by both suites. The fixture pins agreement; each side's own unit
tests pin correctness. The DDA is the part that needed it — a dozen lines where an
off-by-one on a cell boundary stops shots a fraction early, reports nothing, and
quietly teaches a player the wrong thing about their own aim.
falloffStart is served on every weapon for the range's sake. It used to be
guessed as a third of the weapon's range in both clients, which agreed between
them and with no weapon in the server's table (the rifle falls off from 80), so a
dummy took different damage than the same shot in a match. The falloffs block
of physics-vectors.json now pins both ranges' damage against the server's
damage_at; the guess survives only for a backend older than the field.
A gunless game is never a quiet state
The loadout fetch used to fail into a swallowed catch, on the reasoning that
movement and the map still work without weapons. They do — but an empty loadout
also means ShotController bails on every frame, so the game silently becomes
one where the trigger does nothing, in a real match, with nothing anywhere saying
why. The overwhelmingly likely cause is a backend older than
GET /api/hassault/weapons, which 404s here and produces a symptom that points
nowhere near it.
So the error is surfaced: a red line in the main menu and on the click-to-play hint, and Host is disabled while it stands — a match nobody can fire in wastes everyone's time, not just yours. Training stays open, because practising the movement without a gun is still practising the movement.
Aim drills
The free range's dummies stand still. A drill is a minute against targets that
move the way players do: strafing end to end of a rail, AD-spamming,
jiggle-peeking, crouch-peeking, or popping up for about a second. Pick one from
the drill list beside Train, which offers the loaded map's own drills plus
spawn_strafe, the one that runs anywhere. A three-second countdown, a timer,
then a results card: kills per minute, accuracy, headshot share, median reaction
and median time to kill. A personal best per drill is kept in browser storage.
In the pause menu, the Range tab (RangePanel in panels/LoadoutPanel.tsx)
holds the same choices while you are in the range: the drill (defaulting to the
map's first moving one), the gun (any gun, since the range has no sides; it swaps
at once and does not reset a run) and Start, which reads Restart while
that drill is running and begins it again from its countdown. A hint under the
scoreboard says where it is, because the mouse belongs to the gun until Escape.
Starting a drill moves you to its station's shooter mark on a modelled map too
(grounded on the Rapier mesh), not only on a cube map: hd_aim spawns you at the
Close station, so a Gallery or Long Lane drill used to run in a lane you could
not see. Free practice on a map with stations stands its still dummies on
the first still drill's posts (TrainingRange.placeOn), for the same reason:
the spawn-point dummies on hd_aim are all in other lanes.
The browser client reaches the range through the Aim Range card, which reads
Train, and Create match's Aim Training chip (TRAIN_MODE in
apps/assault-web/src/maps.ts, a client-only mode for maps marked range). Both
open the panel with initialMode: 'train', which enters train(null) once the
weapons and the drill list have arrived, instead of joining a room. Until then
the card opened a deathmatch room on hd_aim: lanes, and nobody in them.
The design question was where the targets live, and the answer is the client, on a schedule the server writes:
drills.pymakes every decision. Each target gets a list of input segments,[tick, strafe, crouch, jump, visible], at a fixed 60 Hz. When a target turns back at the end of its rail, how long an AD hold lasts and when a pop-up shows are all decided there, by simulating the samephysics.stepticks the client is about to run. Neither client ports an RNG or a turn-back rule.- Each client moves the target with its own movement code.
DrillMover(training-drill.ts,drills.rs) feeds the segment for each tick through that client'sstep, in whole fixed ticks whatever the frame rate. A target accelerates, brakes and counter-strafes exactly like a player because it runs the same legs.drill-vectors.jsonpins that a replayed schedule lands on the positions the Python saw, in all three suites. - Server bots were the alternative, and lost. Reaction time and time to kill are the whole point of the card, and a target seen through snapshot interpolation is 100 ms or more in the past. The range also has to work offline and as a guest, and a drill costs the one-machine game server nothing this way.
Scoring is drills.summarise, ported to both clients and pinned by the same
fixture's stats cases. Accuracy is per trigger pull (a shotgun blast landing
one pellet is a hit); headshot share is per pellet. Reaction runs from a target
appearing to its first hit, and time to kill from that first hit to the kill. A
heads-only drill still counts a body shot as a hit; it just does no damage.
A drill never feeds XP, credits or a rank. It is scored by the client that ran
it, so its numbers are a personal record, the same rule as authority = local.
Two rules the range follows in a drill that are easy to break:
- A hidden pop-up is not drawn at all. A body standing there unhittable would be a target that lies.
- A crouching target is a shorter body. The hit test and the head band use the crouched height, so the head moves, which is what crouch-peek is for.
The routes are GET /api/hassault/drills?map= and /drills/{id}?map=&x=&y=
(the position only matters to spawn_strafe), on the node and the game server
alike, returning plain dicts so no response model can drop a field.
Bots
backend/modules/hassault/bots.py. A bot is not a second kind of entity. It is
a MatchPlayer whose input happens to be produced on this machine instead of
arriving over a socket: BotBrain.think returns a Command, the room enqueues it
through the same enqueue a browser's input goes through, and it is validated,
budgeted and simulated by exactly the same code.
That is the whole design, and it buys two things worth having. A bot cannot do anything a player could not — no wall-clipping, no infinite ammo, no firing faster than time passes — and there is only ever one simulation to debug.
The AI is reactive rather than planned. There is no navmesh: an AssaultCube map is
a heightfield of columns, and building a graph over it is a larger piece of work
than the rest of the file. Instead a bot steers toward something it wants and
probes ahead with the movement code's own can_stand, so what it believes it
can walk through is precisely what it can walk through. Line of sight uses the
same raycast_world a shot traces, so a bot never fires at something it could
not have hit. When it is wedged on geometry the probe was happy with, a stuck
detector turns it hard and makes it jump.
Aim is the part that has to be wrong on purpose. A bot can compute the exact angle to your head every tick; a bot that uses it is not difficult, it is unplayable. So aim is a rate-limited turn toward the target plus a slowly-wandering error term, and the skill levels are mostly settings for those two numbers:
| Skill | Turn rate | Aim error | Reaction | Sight |
|---|---|---|---|---|
easy | 2.2 rad/s | 0.10 rad | 0.65 s | 70 cubes |
normal | 4.2 rad/s | 0.045 rad | 0.35 s | 110 cubes |
hard | 7.5 rad/s | 0.017 rad | 0.16 s | 170 cubes |
The trigger is pulled when the barrel is where the bot thinks it is aiming — error included — so it shoots with confidence and then misses by that error. Comparing against the true bearing instead would produce the opposite and much worse behaviour: a bot that holds fire until it is perfectly on target, and so never misses at all.
A bot with nobody to shoot at turns too, and for a while it did not. yaw was
only ever assigned inside the target is not None branch, so a roaming bot kept
the yaw it spawned with for the whole match. It still reached its roam point,
because movement is expressed in the bot's own frame and the strafe axis carried
it there — which is exactly what made the bug invisible on a radar and
unmistakable on screen: a body sliding sideways across the map, facing one fixed
direction. Every bot spawning level and most spawning aligned made it read as a
model that could not rotate at all, rather than as an aim bug.
So an untargeted bot now turns toward the heading it is walking, rate-limited by
the same turn_rate its aim is, and levels its pitch off so one that lost a
target while aiming down does not roam staring at the floor. It happens after
heading is final, deliberately: the stuck detector turns the heading hard, and
facing a heading the bot then abandons is what produces a twitch.
Two smaller rules that are easy to get wrong:
- Bots alone do not keep a room alive. The empty clock tracks humans, not bodies; a match with nobody in it is a screensaver, and a room seeded with bots would otherwise never be retired.
- Removal is newest-first, by insertion order rather than by
joined_at—time.monotonic()on Windows has a ~16 ms granularity, and two bots added in the same breath are indistinguishable by it.
Add them from the toolbar (+ Bot, with a skill selector), or ask the agent:
hassault.add_bot takes a count, a skill and an optional team. Bots are host-only
— a guest's socket is bound to a remote match, and there is no fabric message for
reshaping the roster of a match you are only visiting.
The native client (Rust + wgpu)
This module has two clients that must agree — this one and the browser pane — and keeping them in step is its own concern. See HorribleAssault's two clients for what is duplicated between them, which duplications are pinned by a shared fixture and which are maintained by hand, what the native client still lacks, and the checklist to walk when adding a feature to either.
The browser client is the game. This is a second one, native, for the half of a shooter a browser cannot give you: raw mouse input rather than accumulated cursor deltas, an uncapped present mode, and no compositor between the frame and the screen. It is worth being precise about what that buys — input latency and frame pacing, not fidelity. Visual quality here is bounded by the licensing rule that runs through the whole module: no textures, no models, no sampled audio that belongs to somebody else. A native client renders the same untextured architecture the browser one does, faster and with a tighter mouse.
It is being built in four stages, each of which ships something and leaves the previous one working.
| Stage | What it adds | State |
|---|---|---|
| B1 | The wire and the world: real maps, real protocol | done |
| B2 | The wgpu renderer, camera, bodies, raw input | done |
| B3 | Physics and client-side prediction | done |
| B4 | Play/Train/Host route through it, and the HUD, weapon, scope and sound that make it playable | done |
It plays, and it is now the way in: Play, Train and Host open it by default. It loads any map the node serves, joins a real match, predicts your movement, draws its own HUD and weapon, scopes, and makes its own noise. Routing was deliberately last — sending people into it before the prediction was trustworthy would have shipped the rubber-banding as the default experience.
B1: the wire and the world
Two ports and a socket, and deliberately no new renderer. Putting a software rasteriser in between would be a week of work that B2 deletes.
world.rs— a port ofworld.ts. The nine byte planes, and the height rules.geometry.rs— a port ofgeometry.ts. The same mesher, the same colours.api.rs—GET /maps/{name},/maps/{name}/cubes,/weapons.protocol.rs/net.rs— thehassaultchannel on the node's shared/ws.
It talks to the node on this machine, not to a match server. That is not a
shortcut: identity, the map catalogue and the peer fabric all live there, and
channel.py takes the player's name from the backend's signed-in account and
ignores anything a client sends. Pointing at the node means the native client
inherits the session for free and there is no second sign-in to build. A join from
an account with no username comes back as not_signed_in, and the client says so
in those words rather than reporting a network failure.
The reader thread owns the socket's read half and nothing else touches it; the
game loop drains a channel and writes through a mutex. Blocking tungstenite and
threads rather than an async runtime, because there is one socket and three HTTP
calls made once at startup.
B1 shipped with no renderer at all — a top-down debug view, replaced by B2's.
--headless is what remains of that idea and is still the most useful diagnostic
in the client: it skips the window entirely and logs the join and the incoming
ticks, which proves the wire with no GPU involved.
pnpm build:hassault # optimized; `pnpm build:hassault:debug` for the other profile
./apps/native-fps/target/release/hassault-native --server=http://127.0.0.1:8000 --map=hd_dust2 --check
pnpm build:hassault is cargo build --release --manifest-path apps/native-fps/Cargo.toml plus the step that makes a manual rebuild reliable:
it hard-links the fresh binary into apps/native-fps/bin/, the launcher's
third candidate tier. pick_binary runs the newest of the six candidates by
mtime, so the risk of building by hand is a sibling path — the other profile, or
a bin/ copy from a previous session — quietly winning that comparison and
starting a build without the change you just made. Linking rather than copying
makes the two paths one file with one mtime, and both profiles share the one
link name so building either retires the other's. Anything after -- goes
through to cargo.
--check loads and meshes a map and exits, which is the fastest way to see
whether a map the browser renders is one this client agrees about.
B2: the renderer
One pipeline, two vertex buffers, a depth buffer. The world is uploaded once (a map is 13k–113k triangles and never changes) and the bodies are rewritten each frame into a pre-allocated buffer — allocating on the GPU per frame is how a renderer develops a stutter that profiles as "driver".
Three details carry the whole cross-platform claim and the whole latency claim:
wgpupicks the backend. DX12 or Vulkan on Windows, Vulkan on Linux, Metal on macOS. Writing to Vulkan directly would ship nothing for macOS.- Raw mouse input.
winit'sDeviceEvent::MouseMotionis the mouse's own delta, before pointer acceleration, before quantisation to a pixel grid, and before a screen edge can clamp it. A browser gives youmovementX, which is a cursor delta — already accelerated, already integral. That difference is the whole of "the aim feels different", and it cannot be recovered browser-side at any frame rate. - Present mode, lowest latency first.
Immediate(tears, no waiting) →Mailbox(tear-free, still no blocking) →Fifo(vsync, always supported, and up to a frame of lag). Plusdesired_maximum_frame_latency: 1, because every queued frame is a frame of input latency.
Two rules about the surface that only Linux enforced. A Suboptimal frame is
drawn and presented, and the surface reconfigured after: configuring while the
acquired frame is still held is a wgpu validation error, and Vulkan on Wayland
reports Suboptimal as a matter of course (the compositor sizes the window after
the surface exists), so the v0.5.0 Linux client aborted on its first frame, menu
and match alike. Windows almost never reports it, which is how it shipped. And
an empty buffer is never bound — wgpu panics on a zero-sized vertex slice, and
a blank draft in the designer (--new) has no world triangles, on every platform.
There are no textures, because the module ships none — surfaces carry the
mesher's per-texture-id colours, enough that two perpendicular walls of the same
texture id do not merge into one shape when you stand in a corner. There are
lights: the browser's rig, ported whole, over a runtime-generated surface grain
and a sun shadow map rendered once per map. See
Lighting, and why the two clients stopped matching.
Bodies are boxes sized from PLAYER_RADIUS and the player's own crouch fraction,
because a body drawn larger than its hitbox teaches you to miss.
directx, not vulkanIn glam 0.33's vocabulary, wgpu's NDC — Y-up, z in 0..1 — is the directx
convention. vulkan is also 0..1 but Y-down, and renders the world upside down
while compiling perfectly; opengl is Y-up but -1..1, which renders right way up
and quietly throws away half the depth buffer. camera.rs pins the near plane's
NDC depth in a test for exactly this reason.
The bug that made the renderer look slow
The first version put the socket behind a Mutex: the reader thread locked it,
called read(), and the render loop locked it to write. The comment justifying
that said a write "waits at most one inbound frame, and at 20Hz snapshots that is
a fraction of a frame". That is exactly backwards — one inbound frame at 20 Hz
is 50 ms, and read() blocks while holding the lock, so every frame's input
send waited up to a full snapshot interval.
Measured: 36 fps on an RTX 4080 drawing 13,000 triangles. A renderer built for latency, throttled by its own network lock, with the frame time going nowhere near the GPU.
The fix is not a better lock, it is no lock: one thread owns the socket and
does both jobs, reading with a short timeout and draining an outbound queue
between reads. The game loop never blocks on I/O and never takes a lock. Same
machine, same map: 1660 fps. ac_depot, at 113,118 triangles, runs at ~1600.
SO_RCVTIMEO expiry here produces ERROR_IO_PENDING, which Rust maps to no
named ErrorKind at all — not WouldBlock, not TimedOut. A classifier that
checks only the two obvious kinds treats an ordinary timeout as a dead socket, and
the symptom is precise and misleading: the client connects, joins a match, renders
one frame, then reports "connection closed: Overlapped I/O operation is in
progress" — on a loopback connection to a healthy server on the same machine.
Pinned by net.rs's windows_reports_a_timed_out_read_as_error_997.
B3: physics and prediction
physics.rs is the Rust port of the movement rules, and prediction.rs is
rewind-and-replay reconciliation on top of it. The mechanism is three rules:
- Simulate locally, immediately — every command is applied the instant it is produced, so pressing W moves you on that frame rather than a round trip later.
- Keep the commands, each with its sequence number, until acknowledged.
- On a snapshot, rewind and replay — take the server's authoritative state,
drop everything at or below
ack, and re-run the rest.
Rule 3 is the one that is easy to skip and impossible to fake. Without the replay,
every snapshot yanks you back to where you were a round trip ago and you move
forward again — the rubber-banding that reads as "lag" on a perfect connection.
ack is what makes it possible, which is why the server sends it per recipient
rather than in the shared rows.
What is predicted and what is not. Movement is, because it is deterministic
given the same inputs and the same world — which is exactly what
physics-vectors.json pins. Health, ammo, hits and deaths are not: they depend
on other players, and a client that guessed would show you kills you did not get.
Corrections under two cubes are eased away over a few frames and never seen.
Over that, something happened the client could not have predicted — a respawn, a
teleport, an explosion's shove — and easing across it would drag the camera
smoothly through a wall, so it is taken as a hard cut. A respawn is detected
explicitly (was_dead && you.alive) and resets rather than reconciles.
The title bar reports commands in flight, which is a direct read on the round trip the prediction is covering for: at ~1500 fps against 20 Hz snapshots it sits between roughly 25 and 100, draining each time a snapshot lands.
Map objects in the native client
For a while this renderer drew the world mesh and the players and nothing else on the map — no items, no water, no ladders. That was survivable while those things did nothing. It stopped being survivable the moment they decided how a body moves: a player who suddenly cannot jump, moves at two thirds speed and takes no fall damage, with nothing on screen to say why, is the worst kind of bug this client can have. All three are drawn now.
Each one lands in the pass that suits what it is, and the choices are the same ones the browser makes arranged differently:
- Items (
items.rs) go in the opaque body pass, in the same buffer as the players and grenades — an item is a small solid object and wants no pass of its own. Placements come fromMapInfo, not from thewelcome: the server resolved each item onto the floor beneath it, and the placements are a property of the map, so one source serves a live room and a solo range alike. Availability is the per-match half and rides in the snapshot'sitemsOut. - Water (
water.rs) goes in the translucent volume pass with the smoke and the tracers, asMODE_FLAT— the cloud shading is interior noise, which on a surface this large reads as a rendering fault rather than as water. It is emitted both ways round, two quads with opposite winding, because you spend real time under it: wound one way only it would vanish exactly when your head went under, which is when the player most needs to see where the surface is. - Ladders go into the world mesh itself (
geometry.rs), because a ladder is static map furniture whose span never changes. That gets them uploaded once and shadowed like every other surface, for free.
itemsOut is an Option, and that is load-bearing. Absent means "this server has
no items", which is not the same as "every item is present" — read the second way,
every taken item pops back into existence once a tick. The pickup effect also now
has a variant of its own rather than falling into Fx::Other: it starts an item
sinking on the frame the pickup was announced, which at 20 Hz is visibly earlier
than waiting for the next snapshot to say the same thing.
An unknown item kind is drawn, in a fallback grey, and reported once through
divergence. A bare patch of floor where an item is reads as an empty spawn, which
is worse than an unfamiliar box.
What the parity tests pin
tests/browser_parity.rs now compares the two clients' item tints, their bob and
fade constants, the water fallback colour and opacity, and the ladder dimensions —
all read out of the browser's TypeScript source at test time.
Colour is the part worth pinning hardest. The shapes are small and seen at a
distance, and what a player actually reads across a room is "red means health"; a
health pack that is red in one client and orange in the other is invisible from
either client alone, because each looks deliberate. The same goes for FADE and the
bob: the bob is shared by every item on a map precisely so a missing one is easy
to pick out of a moving field, and two clients disagreeing on it would make the
same map read differently to two players standing in it.
A ladder is drawn at the width of the volume that catches you, not of a real ladder, in both clients — a slender ladder drawn in the middle of a two-cube catch radius teaches players to aim for a rung when what actually grabs them is a cylinder.
Since then it also pins the muzzle flash (its per-weapon shape table, how long
it is lit, the screen-fraction cap, the halo ratio, the two colours, and that
neither client flashes for a knife), the bullet marks (how many the world
remembers, how long for, the lift and the size, and the order of the six face
normals — which is a contract with the server as well, since the index is on the
wire), the swap animation's five timings, and the arms (segment lengths,
shoulder positions, the three clip durations, and that both clients still read the
shared grips.json and viewclips.json rather than a local table).
That last one is the odd one out and worth naming: it pins that a file is being read, not that two numbers agree. The grips and the clips are one file compiled into both clients, so they cannot drift — the failure mode it guards against is somebody replacing either read with a local table, which is the change that would look like a harmless refactor.
The range gives ammunition too
Train fetches the served item table (GET /api/hassault/items) and resolves only
the ammunition half of a pickup locally, exactly as the browser's TrainingRange
does: health and armour mean nothing where nothing shoots back, and faking them
would teach a resource cycle the range does not have. Every item still draws —
the map's layout is a real thing to learn.
The reach and the respawn come off that table rather than being hardcoded, the
interval / zoomLevels / plane_order precedent: a copy in Rust would be a range
where items come off the floor at a different distance than they do in a match. A
node too old to serve the table leaves the range's items drawn but inert, which
is a missing convenience rather than a client that refuses to start — and the range
does not invent a reach to fill the gap.
The rules that are easy to get backwards, again
Both traps from the renderer are now implemented three times, so both are pinned again here:
- the base height comes from the cell while the delta comes from the corner-vertex cell — taking both from the vertex cell tears heightfields apart at every seam, silently;
- the divisors differ on purpose:
vdelta/4per render vertex,(sum of four)/16for the height a body stands on. Reusing/4sinks the player into every slope.
And one that is specific to a mesher: an overhang uses utex, not wtex.
The HUD and the weapon in your hands
Everything the snapshot already carried and the client threw away. you in a
snapshot is per-recipient precisely so a client can show the player their own
health, magazine, reload clock and respawn clock — and until this stage all of it
arrived and was discarded, which made the native client playable only by someone
who already knew the game.
The HUD is drawn, not composited (hud.rs). There is no DOM here and no text
renderer, so a frame's state becomes triangles in one pass and
Renderer::set_overlay draws them last, alpha-blended, with no depth attachment
at all — the HUD is not in the world and has nothing to be behind.
Four decisions in it are load-bearing:
- No font is shipped, like the sounds and the maps. The HUD draws in the operating system's own faces (see Type); shipping a TTF would mean shipping someone else's licence. The fallback is a 5×7 bitmap written as binary literals, so every glyph of it is drawn in the source that defines it — which is the only review a hand-made font gets.
- Layout is in pixels and converted to clip space once. A HUD laid out in normalized coordinates stretches with the window, and a crosshair whose arms differ in length by aspect ratio is a crosshair that lies about the spread it is drawing. One HUD unit is derived from the window height, so the same layout is legible on a 720p laptop and on a 4K monitor.
- Every edge-anchored block is laid out upwards from its margin. The block's height depends on the HUD unit, so anchoring its top puts the last line off the bottom of the screen on a small window — where it is not clipped with a warning, it is simply absent. The first cut did exactly that.
- Nothing on it invents a fact. The hitmarker comes from
you.hits, which the server drains as it builds that envelope, so each landed hit arrives exactly once; the damage flash fires on a drop in health, and a respawn explicitly clears the last-seen value so 12 → 100 is not read as healing. A marker driven by the fire key would light up on shots that hit a wall — the same class of lie as drawing footstep positions.
The weapon view model (viewmodel.rs) is a port of the browser's
viewmodel.ts, deliberately a port rather than a second design: the constants —
HOME, the kick decay, the bob and sway rates — are the TypeScript ones
unchanged, because a weapon that sat somewhere else or kicked differently would
make switching clients feel like switching games. Same procedural boxes and
cylinders, for the same licensing reason as everything else here.
Three things differ, and all three are forced by this renderer rather than chosen:
- There is no scene graph to parent to. three.js makes the view model a child of the camera; here its transform is applied on the CPU and the result is drawn in camera space, with the view matrix left as the identity. A few hundred matrix multiplies a frame, and no second uniform.
- It gets its own pass, with the depth buffer cleared. A rifle is two and a
half cubes long and lives inside the player's own collision radius, so drawn
against the world's depth it is sawn in half by every wall you stand against.
In three that was a
renderOrder; here it is a second render pass. It keeps its own depth sorting, so the barrel still occludes the magazine behind it. - The projection uses the camera's own field of view. Many shooters give a
view model a narrower one; this is a port, and three draws the browser's weapon
through the single scene camera — a different angle would put the same weapon at
the same
HOMEat a different size on screen. Only the depth range differs, and only because a weapon 1.4 cubes from the eye has no use for a far plane at 2000.
The muzzle flash is fired from the server's own shot effect, not from the fire
key. The browser can drive its flash locally because it has a trigger controller
that knows the fire interval, the magazine and whether you are alive; this client
has none, so the key would flash on every shot the server refused. It is lit by
cheating the normal: the shader has no unlit material, so the flare's vertices
carry the sun's direction as their normal and land at full brightness — cheaper
than a second pipeline for six triangles. viewmodel.rs's LIGHT_DIR must
therefore equal lighting.wgsl.inc's SUN_DIR, and
tests/browser_parity.rs pins it: a stale copy does not fail, it takes the
cosine between the two off every flash and reads as the flash simply being weak.
zoomLevels and hipfireSpread are camelCase on the wireWeaponSpec read them as zoom_levels and hipfire_spread with no
serde(rename), so both deserialized to empty/zero on every weapon while the
request succeeded and every other field arrived. The symptom is not an error: it
is a game in which no weapon has a scope and the crosshair never opens. Pinned by
a_weapon_is_read_with_the_wire_s_own_spelling.
Train has no server and therefore no you: no health, no ammo, no respawn clock.
The HUD draws the crosshair and the movement readout there and nothing else,
because a hundred hit points in a mode with no damage model is a number the client
made up. It does hold a weapon — the rifle, as the browser's Train does — since an
empty hand reads as the view model having failed rather than as the mode it is.
Both are drawn from the moment you are in the world, not from the moment the pointer is captured. The first cut gated them on pointer lock, reasoning that a released pointer means a menu; it does not here — the world is still drawn behind it, and a world with no weapon and no HUD in it reads exactly like a client that half-loaded. Which is how the missing view model was first reported.
Reading the wire, not guessing it
Three things are served and never duplicated in Rust, for the same reason: a hardcoded copy is a divergence that produces no error.
plane_orderdecides how the nine cube planes are sliced.World::newslices by the order the server reported and refuses a plane it does not know, rather than reading the bytes after it as some other field.floorandceilare signed. Read unsigned, every below-zero floor becomes a value around 250 and those cells launch into orbit.- The weapon table (
interval,kickback,zoom_levels) is fetched. A stale local copy is an aim that is wrong only while scoped.
One thing only a real server teaches: #[serde(default)] does not cover an
explicit null. default applies when a key is absent; a null is a present
key of the wrong type, and serde rejects it. The node sends "yaw": null on every
light entity, so a client without a null-tolerant deserializer fails to parse
every real map while passing every hand-written fixture.
The launch route
POST /api/hassault/launch_native used to pass fiction — --connect=127.0.0.1:4000
(nothing has ever listened there), --room, --raw-input — to a binary that
parsed none of it. It now passes the one thing the client needs: the node's own
HTTP origin, from which the client derives everything else including the /ws
address (two addresses that must agree is two addresses that can disagree).
The origin is read off request.base_url rather than assembled from a host and a
port, because the port is not knowable from inside the route:
HORRIBLE_DEV_BACKEND_PORT moves it, Windows' Hyper-V reserved ranges force that
regularly, and a packaged build binds somewhere else again. The request arrived at
the right address by definition.
The launch path: an address is not an intent
The origin was half the fix. The other half is what was pressed, and until it
travelled every launch was the same launch — join with no room, which the match
server reads as join-or-create. Three things followed from that, none of them
visible as an error:
- Train was not solitary. Pressing Train while anybody was playing that map seated you in their firefight, which is the opposite of the mode's whole point: it exists so the chained jump and the shoot-jump can be practised before someone is aiming at you.
- The bot count went nowhere. The menu collected it, and the launcher had no field to put it in.
- A remote room could not be launched into at all. The client was never told whose node the room was on.
So the request carries mode (train / host / join), the room, the host node
id, and the bot count, and the route turns them into flags:
--server=http://127.0.0.1:8100 --map=hd_dust2 --mode=host --max-fps=240 --bots=3 --bot-skill=hard
Four rules in that translation are load-bearing:
- Train is answered off the wire entirely — no socket, no room, no server. A
"solo room" is not expressible: the roomless join is join-or-create, so
solitude cannot be requested, only stumbled into.
App::newwithsocket: Noneplaces the player with the samephysics::spawn_atthe conformance fixture pins and stepsphysics::stepdirectly each frame. The dummy range istraining.rs, a port oftraining.tsbound to it by the same fixtures; see Training, natively. - A bot count only travels with
host.add_botis host-only on the channel, so a count on a join is an instruction the server would refuse — and it is absent rather than0, because a zero is a request the client would act on. The count is clamped againstMAX_PLAYERSon the way out: it arrives from a browser. - Bots are queued, not sent with the join. They need the room the
welcomenames, exactly as the browser client'spendingBotsRefdoes. - A host with no room is refused in the route, where a browser is still listening. The channel refuses it too ("a remote match needs a room id"), but that refusal would arrive inside a window that had already opened. The client checks it a third time, because a client that only works when launched from the menu is a client that cannot be debugged.
An unknown --mode exits rather than defaulting. A typo silently becoming
join is precisely how Train turns back into a match nobody asked to be in.
A launch is a job, not a request
The route resolves a binary, compiles it if it is older than its own source,
starts it, and waits _LAUNCH_SETTLE_SECONDS to see whether it survived. Three of
those four are instant. The second is not: a cold cargo build --release of this
crate builds wgpu, and _BUILD_TIMEOUT_SECONDS is fifteen minutes for that
reason.
Run inline, that made the response the only signal — and it did not arrive for
minutes. The button said Launching… for all of them, which is indistinguishable
from a hang; and every hassault surface lives in a frame tab, where an inactive
tab is unmounted, so switching away dropped the promise the pane was awaiting
and the launch appeared to stop. It had not: the build was still running, with
nothing left in the app that knew about it.
So the work is a job on the node:
_LAUNCH_JOBSholds one per account, started withasyncio.ensure_futureso the task outlives the request. A browser that goes away cancels nothing.- The POST waits
_LAUNCH_INLINE_SECONDS(3s, deliberately longer than the settle) and then answers with whatever phase the job is in. A launch that needs no build still returns its real result inline, so nothing has to poll for the ordinary case. phaseisstarting,building,launched,failed, oridle— the last only from the status route, and meaning nothing has been launched, which is a different fact from a launch that failed.GET /api/hassault/launch_native/statushands the same job back. This is the half that survives a tab switch:useNativeLaunchreads it on mount, so a remounted pane picks up the build it started before it went away.- A second press while one is running joins it rather than starting another.
Two
cargo builds of one crate block on each other'starget/lock, and the second would look exactly like the hang this replaced.
Two smaller rules in the client half (packages/core/src/modules/hassault/native-launch.ts):
buildingandstartingread differently on screen. A build is minutes and a start is a moment, and one word for both is what made a compile look like a hang in the first place.- A finished job is not adopted on sight.
_LAUNCH_JOBSkeeps the last launch for the life of the backend, so a pane mounted an hour later would otherwise come up announcing a pid that exited long ago. A job that is running when the hook finds it is the hook's to report, and so is whatever it becomes.
Playing in the native client
In the dashboard, the hassault.play pane is a launcher. Every way into a
match — Quick play, Ranked, Duel, Train, Host, a server-browser row, an
accepted invite, a lobby's Start — opens the native window. Train included,
since a learner wants the same mouse and the same frame pacing as a match. The
pane keeps everything that is not being in the world: sign-in, the map picker,
the server browser, friends and invites, the armoury, settings and controls, the
match companion while the client runs, the post-match card, and watching replays.
The Play section opens with a launcher row: which client a launch would run
(describeClientSource), Install native client when none resolves, and
Open in browser, which opens the browser client at the game server's origin
(webClientUrl: wss://… → https://…/, from /games/status's server_url)
and says so when openExternal reports the browser did not open.
There used to be a third way: a hassault.nativeClient setting that, turned
off, played the match inside the pane. It is gone (G1). A 3D match in a
docked webview shared its keyboard with the shell, took the OS window fullscreen
to get a field of view, and was in practice a third client to keep working. The
browser client lives on as apps/assault-web — the same component with
forceWebGl, still one of the three implementations of the movement rules
that physics-vectors.json pins — and in the dashboard the pane never takes
pointer lock or the keyboard, except to fly a replay's drone camera.
Where the binary comes from: three tiers
hassault.nativeBinaryPath— somebody naming the binary they mean.- A local build under
apps/native-fps/target/**, newest wins (_local_client_candidates+pick_binary), rebuilt from source when stale. - A downloaded client, fetched from the GitHub release matching this app's
version into
$HORRIBLE_DATA_DIR/hassault/bin/<version>/— the Install button in the game's main menu, orPOST /api/hassault/client/install.
Tier 3 exists because the native window is the only way to play from the
dashboard, which made the way into the game a Rust toolchain: the launch route's only answer to a missing
binary was cargo build --release, which is not an instruction a player can
follow. It is a download rather than something bundled in the installer for
the same reason llama.cpp builds are: it is versioned and launched by the backend
and lives under $HORRIBLE_DATA_DIR, which no installer touches. See
releases.
The download is deliberately not another entry in pick_binary's candidate
list, and the reason is the warning directly below this one. pick_binary takes
the newest build on disk — the right rule among build outputs, and exactly the
wrong one here: a client downloaded today beats a developer's target/debug from
an hour ago, so the first launch after an install would silently run the release
instead of the edit under test. That is the same class of bug pick_binary was
written to end, arriving through a different door.
So launch_native resolves tiers 1–2 first and only then looks in the data dir
(client_install.installed_binary()). A checkout's own build always wins. The
downloaded client is also exempt from the staleness rebuild: it is not a build
output and has no source to be stale against, so without that exemption a
checkout with a cleaned target/ would answer an install by starting a surprise
cargo build — minutes, on the machine least likely to have a toolchain at all.
backend/tests/test_hassault_client_install.py pins both halves.
The install verifies the sha256 GitHub publishes for the asset; a mismatch aborts
and removes the whole directory (a half-downloaded binary that is launched anyway
is worse than no binary, and the launch route cannot tell them apart by looking).
An asset GitHub publishes no digest for installs as verified: false rather than
dressing a self-computed hash up as verification — the same honesty as
llamacpp's installs. GET /api/hassault/client/status reports
which tier would answer, which is the only thing that distinguishes a developer
running their own build from a player running a download.
Quick Play does not branch twice: it either launches a join at the match it
found, or calls host, which decides for itself what hosting means.
release before debugThe candidates used to be tried in order, so a target/release binary built
before your last change was silently preferred over a target/debug one built
from the current source. The symptom is a game missing whatever was just
added — and nothing anywhere says an old binary was run. That is exactly how a
native client with no weapon view model in it kept starting after the view model
had been written and tested. pick_binary now takes the most recently modified
candidate; a named hassault.nativeBinaryPath still wins outright, because that
is somebody naming the binary they mean.
pick_binary closed half of this. The other half outlived it: the newest build
on disk is still older than the source the moment you edit the client. The
launch then succeeds, the window opens, the game runs perfectly — and simply does
not contain the change, which reads as a change that did not work rather than as
a build that never happened.
So the route now compares the binary's mtime against the newest of
apps/native-fps/{src/**, Cargo.toml, Cargo.lock} and, when it is behind, runs
cargo build before starting it — in the profile already on disk, so a
developer iterating with debug builds is not handed a minutes-long optimised
build every launch. A build that fails refuses the launch and returns
cargo's last lines; falling back to the binary known to be stale would restore
the exact silence this closes. tests/ is deliberately not in that glob: a test
edit changes nothing the binary contains.
Two exemptions, for the same reason in both cases — there is nothing to be stale
against. A named hassault.nativeBinaryPath is the user pointing at the build
they mean, and a packaged install ships the binary with no crate beside it, where
newest_source_mtime returns None.
hassault.autoBuildNative (on) turns the build off. That is a choice to run
what is on disk, not a licence to say nothing about it: the launch still happens,
but the response carries stale: true and the message says in words that this
build predates your last change.
A launch that reported a pid and opened nothing was not a graphics problem. The
client was spawned with subprocess.Popen([bin]), inheriting this process's
stdout and stderr — and the backend is routinely an orphan: pnpm dev exits,
or a --reload parent dies, leaving pipes with no reader on the other end. The
client's very first act is an eprintln! (hassault: loading <map> from <origin>), that write fails, Rust panics on a failed print to stderr, and the
process is gone with exit code 101 before a window is ever created.
Nothing said so, because Popen had already returned: the pane reported
"Launched native FPS client (PID: 12392) from release/, built 18.0h ago" about a
process that no longer existed.
Two changes close it. The child is given a log file —
$HORRIBLE_DATA_DIR/hassault/native-client.log, truncated per launch, with
stderr folded into it and stdin on DEVNULL — so its output depends on
nothing about how the backend was started, and the startup lines (map, GPU
backend, loadout, hitbox) survive to be read. Deliberately not logs/: a second
file there breaks the dev backend outright, because --reload-exclude "logs/*"
is expanded by the launching shell and uvicorn is handed the extra filename as a
positional argument.
And launched: true is now an observation, not an assumption. The route
waits _LAUNCH_SETTLE_SECONDS (0.8s) and polls: everything that kills this
client kills it in the first moments — a panic, a node it cannot read, no usable
GPU backend — so a startup that died comes back as launched: false carrying the
exit code and the tail of the log, instead of a pid for a process that is not
there.
With no node: the downloaded executable
Everything above is the native client launched by a node. It also runs with no
node at all, which is what makes it a file somebody can download and double-click:
https://horrible-games.fly.dev/download/hAssault.exe
(how the server hosts it).
The rule is one line in parse_from (apps/native-fps/src/main.rs): --server
names a node; without it the client is standalone. A double-click passes no
arguments, so no arguments has to mean "play". The launcher has always passed
--server (the node's port moves), so nothing a pane starts is affected, and the
old default of http://127.0.0.1:8000 was never something anyone relied on.
| Launched by a node | Standalone | |
|---|---|---|
| Started with | --server=<node origin> | nothing, or --game-server=<origin> |
| Map, weapons, hitbox, grenades | the node's /api/hassault/* | the game server's (hassault_content.py, the node's own handlers) |
| Match socket | ws://<node>/ws | wss://<game server>/hassault-ws?guest=1&name=… |
| Who you are | the node's signed-in account | a guest, under a callsign |
| Settings | the node's settings bag | settings.json in the user's config directory |
| Maps | bundled, installed and drafts | bundled only |
Three things had to exist for that table's right-hand column:
- TLS on the match socket.
tungstenitewas built withhandshakeonly, sowss://failed at connect; the socket has only ever been plain TCP to a node on the same machine. It now hasrustls-tls-webpki-roots(rustls was already in the tree throughureq). The 4 ms read timeout that lets one thread both read and write is set on the TCP stream underneath the TLS session (net.rstune): that is where a read blocks, and a timeout part-way through a TLS record is safe because rustls keeps the partial record. - A guest identity. A node takes the name from its account and ignores what a
client sends. The game server has no account to ask, so the callsign rides the
socket address, exactly as the browser client's does.
--name=sets it; otherwise it is generated once (Operative-417, the browser's own default) and kept, cut to the 16 characters the server cuts it to. - Somewhere to keep settings.
settings.rsopens by saying the node is the store and not a file beside the binary. Standalone is the one exception, because there is no bag to read: the samekey -> valuedocument lives at%APPDATA%\hAssault\settings.json($XDG_CONFIG_HOME/hAssault/on Linux,~/Library/Application Support/hAssault/on macOS), written whole and renamed into place bySettingsWriter::to_file. Nothing above the store knows which one it has.
What standalone does not have, each because it means "this node": --mode=edit
(refused before anything is fetched: drafts are documents on a node), the armoury's
skins (the inventory route 404s and weapons draw in default colours), and sign-in —
a standalone player is always a guest, so their matches are unrated.
--game-server=http://127.0.0.1:9200 points it at a local game server, which is
how this is tested without touching production:
./apps/native-fps/target/release/hassault-native --game-server=http://127.0.0.1:9200 --headless
Started from Explorer the executable gets a console of its own, which closes the instant the process exits. "Could not reach the server" would flash for a frame and the game would simply seem not to start. So a run with no arguments at all holds the console open on a fatal error until Enter is pressed. Only then: anything started with flags has a terminal or a launcher reading its stderr, and must exit rather than wait on a key.
An MSVC build imports VCRUNTIME140.dll by default, which is not part of
Windows — it arrives with the Visual C++ redistributable, usually as a side effect
of installing something else. .cargo/config.toml at the repo root sets
+crt-static so the download starts on a machine without it. At the root, not
beside the crate: cargo finds config from the directory it is run in, not from
--manifest-path, and both the build script and the release workflow run it from
the root.
The front end: a menu to start in
Launched by a node, the client is handed a match the player already chose in the
dashboard, and opens straight into it. Standalone it used to do the same with
defaults nobody chose: fetch hd_dust2, join whatever room was on it, and open a
window with the match already running — after several seconds of a console
window, with no say in the map and no way to look at the loadout.
So a standalone client with no destination opens into a front end instead.
parse_from decides: any of --map, --room, --mode, --game, --bots,
--host, --drill, --spawn, --bench, --headless or --check is a
destination and goes there as before; --menu and --no-menu say it outright. A
node is never given one — the dashboard is its menu.
BOOT ──► HOME ──► SEARCHING ──► LOADING ──► the match ──► HOME
play / loadout / settings
| Screen | What it is |
|---|---|
| Boot | The window opens at once and lists each table as it is fetched. Weapons and maps are required; the rest are skipped with a note. A failure offers a retry instead of closing |
| Play | Three ways in: Quick play (map or any, game or any, bots for a new room), Browse rooms (the server's list), Practice (one map, no server) |
| Loadout | Per side: primary, secondary, operator. Each weapon's numbers are bars measured against the best on offer, and the whole kit (blade included) is one row along the bottom |
| Settings | The pause menu's own pages (Menu::front), without the rows that mean "this match" |
| Searching | Asks /api/hassault/rooms, picks with front::choose_room, and says which it was |
| Loading | The map's name, each phase with what it produced, and the map's floor plan as a backdrop once the world is built |
Three files, split the way console.rs and menu.rs already are:
front.rs(library) is a state machine and a painter. It owns no window, no socket and no thread: a click or a key becomes anIntent, and it draws itself into the overlay vertices the HUD uses.Front::hitsproduces a rectangle for everything clickable and both the painter and the mouse read it. That is why every screen renders inhud_preview(front,front-browse,front-practice,front-loadout,front-operator,front-search,front-found,front-loading,front-boot,front-bootfail,front-notice,front-name) and is unit-tested without a GPU.front_gpu.rs(library) is one surface and the overlay pipeline. The match'sRendererneeds a world to build and a moment to start; a screen of rectangles and text needs neither, so the menu is up before anything is fetched. It presents with vsync, since a menu has no latency worth a torn frame.shell.rs(binary) owns the window and whichever of the two is in it.
A match is a fresh App, every time. App holds a few hundred fields of match
state. Returning to the menu by resetting them would be a list that is wrong the
day a field is added, and the symptom would be a second match that opens with the
first one's score. So the shell constructs an App, hands it the window
(App::attach, the second half of what resumed used to do) and drops it when
App::take_ended says the match is over. Hosted, leave_and_exit and the two
socket-failure paths report an Ended instead of calling event_loop.exit(). The
cost is a renderer start per match, which is the loading screen's last line.
Nothing that waits runs on the window's thread. Boot, the room search and the whole load (map fetch, world build, connect, join) are worker threads reporting over one channel. Each job carries a ticket; a message whose ticket is not the current one belongs to a job the player cancelled, and is dropped — a socket that arrives that way closes as it is dropped, which is the leave.
The join is answered before the renderer starts. MatchSocket::await_welcome
blocks the loader until the server seats the player or refuses, so a refusal
("that map cannot host Bomb Defuse") is a line on the menu rather than a match
that opens and closes. Everything it reads while waiting is kept and handed out by
the next drain, so the game sees the welcome as if nobody had looked.
There is no queue, and the screen does not pretend there is one. A casual join is seated at once, in a room on that map or a new one. Searching is a real question: the busiest room with a free seat and somebody in it, among those matching the map and game asked for. If there is none, a room is opened and the title says opening a room, not match found. A room nobody is in is never chosen: it closes a minute after its last player, and joining one is being seated alone with no right to add bots. Rated duels are paired by the server and need an account, so they are not offered to a guest.
The menu and the match both save settings, and SettingsWriter::to_file keeps the
whole document in its thread. Two writers would each rewrite the file from their
own copy and undo each other. The match gets SettingsWriter::share — another
handle on the same thread — and the shell is the one that joins it at exit, after
the match's handle is gone.
Driving the real window from a script, for a check that is not a person: winit
takes posted window messages, so PostMessage with WM_MOUSEMOVE,
WM_LBUTTONDOWN and WM_KEYDOWN (scan code in the lParam) clicks and types
without taking the desktop, and PrintWindow with flag 3 photographs the client
area. Point it at a local game server and a scratch APPDATA. Against a server on
the same machine a load is over in a few hundred milliseconds, so
HASSAULT_LOAD_HOLD_MS=5000 pauses it once the world is built — long enough to
look at the loading screen, and nothing at all when unset. hud_preview front-loading-real draws the same screen over a real map's floor plan.
Finding a match is the server's rule
The browser's Quick Play and the native menu's Find Match used to read
/api/hassault/rooms and each choose a room for itself. They ran different
rules and opened on different default maps, so two people searching an empty
server at the same moment got a room each. Both now ask the server:
| Route | Answer |
|---|---|
POST /api/hassault/matchmake with {"map"?, "mode"?} | A room in the shape the room list uses, plus opened and humans |
GET /api/hassault/rooms/{id} | That room, its host and its roster (the scoreboard's columns, nothing else) |
HassaultReferee.find_match picks the fullest room with space that fits the
request, where full counts the humans seated and the seats already promised
to clients still loading the map. With no such room it opens one at once, before
anyone has joined it, so the next search lands there too. A promise lapses after
MATCH_HOLD_S (30 s). A room with nobody in it or coming is skipped: it is
counting down to closing. The first seat to reach a room opened this way is its
creator, exactly as if its own join had opened it.
The route is public, so opening is bounded twice: by HASSAULT_MAX_ROOMS, and
by MAX_UNCLAIMED_ROOMS rooms that nobody has reached yet. The map a search
with no map opens on is HASSAULT_QUICK_MAP (default hd_dust2).
Both clients fall back to choosing from the room list when the route answers 404, so a client newer than the server it dials still plays.
Several maps, and a lobby
A search may name several maps: POST /api/hassault/matchmake takes
{"maps": [...], "mode"?}, and a room on any of them satisfies it. With no
such room, one is opened on the first map named that can host the mode. The
native menu's quick-play tiles toggle, so the request is every tile that is on;
none is any map.
A lobby is a group gathered before the search (hassault_lobby.py). One
player opens it and gets a five-character code; up to four more join with the
code; when the leader presses play, find_match is asked once with
seats set to the size of the group, so the room it returns has a seat promised
for every member.
| Route | Does |
|---|---|
POST /api/hassault/lobbies | Opens a lobby; answers this member's token and the lobby |
POST /api/hassault/lobbies/{code}/join | Joins it |
GET /api/hassault/lobbies/{code}?token= | The lobby as this member sees it. Polled, and the heartbeat |
POST /api/hassault/lobbies/{code}/play | The leader's search, with maps and mode |
POST /api/hassault/lobbies/{code}/leave | Leaves |
It is polled HTTP because a lobby exists before anyone has a match socket. A
member who has not asked for 12 s is dropped, so a client keeps asking during a
match (every 4 s) as well as in the menu (every 1.5 s). The leader is the
longest-standing member; nobody is elected. Each search increments serial,
and a client acts on a serial once. Nothing here is an account: a member is a
callsign and the token the server handed back.
Map art in the menu
The front end draws the web client's key art (apps/assault-web/src/assets/maps/)
behind the menu, on each map tile, and behind the loading screen. map_art.rs
compiles the pictures in, decodes them on a worker thread, and packs them into
one texture; front_gpu.rs draws them in a pass under the overlay. Front::images
lists what goes where by map name, and a map with no picture (hd_aim today)
keeps its flat card.
The loadout's stage: models, not silhouettes
The LOADOUT tab drew its weapon and operator as silhouettes built from
rectangles (front::weapon_art), which say which class a weapon is and nothing
about what it looks like — while the models themselves were already compiled
into the executable for the match to draw. The tab now shows those, in three
dimensions, and lets them be handled: drag turns, the wheel closes in,
F turns a weapon over and brings it back, R resets. Left alone it turns
slowly by itself.
showcase.rsis the state and the arithmetic, free ofwgpuand tested headless: what is on the stage, how it has been turned, and where the camera stands. The model turns and the camera only climbs, so the light stays put and moves across the metal. The camera is fitted to what the subject can sweep — its widest reach across the frame, its height plus whatever of that reach the climb tips into view — rather than to a bounding sphere, which would leave a rifle (all length, no height) using half the frame it is given.showcase_gpu.rsborrows the match's ownPropsandCharacterspipelines and its tone curve, pointed at a small target of its own, so what is turned over in the menu is shaded as it will be in the hands. The operator is the client's ownSquad, so it breathes and aims where it is turned. Its light is not a map's: a studio rig — key over the left shoulder, cool rim from behind, a bright sky for gun metal to reflect — because under the default rig a black pistol on a dark panel is a hole in the picture.- Placed by coverage, not as a box. The tone curve does not carry alpha, so
the last pass (
showcase.wgsl) takes its colour from the tone-mapped picture and its alpha from the scene it was made from — zero where the stage was cleared, one where a model was drawn. Only the weapon lands on the panel, and the panel's grid runs behind it. The stage is drawn at 1.5× and scaled down, which with FXAA is its anti-aliasing. - Nothing blocks the menu. The parses are a tenth of a second a weapon and
more for the operators' textures, so they run off the frame thread
(
prop::preload, and a worker that warmsSquad::load); the silhouette holds the place untilFront::stagedsays the model has landed. A newFrontGpuafter a match is a new device, and loads them again.
A weapon is shown as its class model (showcase::prop_for): there are five
props and more weapons than that, the same arrangement the match has.
INVENTORY and STORE have the stage too, at the top right with the grid or
the market narrowed to its left. The inventory shows the skin last pointed at —
it stays after the pointer leaves, since the pointer has to leave to reach the
model — and the store shows the selected listing when it is a skin (a key or a
case has no model). A knife is shown as the archetype its design names
(inspects::knife_archetype, the match's rule), so a karambit is a karambit.
Under the model, the skin's name in its grade's colour, then the grade, the
wear and the float.
The grade's colour is the server's: skins.py serves rarityColor beside
rarity on every definition, and the client reads it rather than keeping a
table of its own. Inventory cards carry it as light rising from their foot and
a line along it; market rows as their leading edge and their KIND column.
Finishes are shown, in the match as well. The weapon models were drawn
stock in the native client whatever was equipped: props_gpu had no input for a
skin, and only the box fallback was ever recoloured. The browser tints its GLB
prop rather than repainting it — the materials carry real texture maps, and the
colour multiplies the map — with the skin palette's body colour, worn as the
boxes wear it, and leaves an archetype knife white because its finish is baked
into its texture. viewmodel::prop_tint is that rule, decoding the colour from
sRGB as three's setHex does, and Props::tint multiplies it into each
material's own base colour (written only when it changes). The first-person
weapon in a match wears it, and so does the stage. Three things the browser
also changes are not: roughness, metalness and reflection strength by wear —
the native prop shader has no environment term to change.
The tab bar's light slides from the last tab to the new one over 0.22 s rather
than jumping (Front::tab_light).
Setting this up found a crash the match could also hit: Squad kept an actor's
pose across a change of side, and the two operators are different rigs (34
bones and 65), so the next frame reset one from the other and panicked on the
slice length. An actor is now rebuilt when its player swaps sides.
cargo run --example showcase_preview writes a sheet of every prop and both
operators through the same object; hud_preview front-loadout,
front-operator, front-inventory and front-store draw the stage in place.
The same pass gave the tab colour: each side has its own (ui_theme::SIDE_T,
SIDE_CT) on its tab, the panel's edge and the light under the stage; each
statistic has a hue, graded along its bar; and two slow washes cross the
backdrop behind every screen.
The map behind the menu, live
The main menu used to sit on a still picture of a map. Once a map has loaded
it is the map itself, flying behind the menu: the match's own Renderer, with
the world built from the same compiled GLB a match uses
(world3d::is_modelled, shared with App::new) and lit as a match on it would
be. The camera holds each of the map's benchmark framings (bench-paths.json,
views somebody already chose) for 14 seconds with a slow pan and drift, then dips
to dark and cuts to the next (backdrop.rs) — framings are rooms apart, and a
glide between two goes through the walls between them.
- One window, one surface, either owner.
FrontGpustarts flat, on its own device, and the menu is on screen before anything is fetched. When the backdrop's map has been built on a worker, the shell drops the flat one and makes aRendereron the window; from then on the menu's passes (FrontPasses: the pictures, the overlay, the stage) are built on the renderer's device and drawn into each of its finished frames throughRenderer::render_with. Another map is aset_world, not a new renderer. - Darkened under the pictures, not over them. The map tiles are drawn before the overlay, so a scrim painted in the overlay would darken them with the world. The scrim is its own pass, between the world and the tiles, at 0.78 — about as bright as the still picture was, a little more so the motion reads — and to black at the cuts.
- Which map: whatever the home screen's picture would have been — the map under the cursor, or the busiest room's when picking. A map with no framings, and the Low quality tier, keep the still picture. While a match loads, its own map's picture is shown, since that is the subject.
- The renderer does not wait for the display with vsync off, so a live menu is
capped at 120 frames a second (
pacing::FramePacer). HASSAULT_MENU_SHOT=<file.png>saves one frame of the live menu (HASSAULT_MENU_SHOT_ATseconds in, default 6), for looking at it without a screenshot tool — the export's readback, once.
The top bar fits seven tabs. The identity block on the right is as wide as
what it says (Front::identity_width): it used to be a fixed 200 units, and its
right-aligned status line spilled out under the last tab. When the whole status
and seven tabs at their natural size do not both fit, the status drops its room
count first; then the tabs' margins narrow; then, at 4:3, their labels shrink.
There is always a clear gap before the block.
Signing in, with no node
A client with no node played as a guest and owned nothing. It can now sign in
to the game server directly, and the menu's INVENTORY and STORE tabs are
the account (front/account.rs). For a guest, both tabs are where to sign in.
No password is typed in the client. It uses the game server's existing provider flows, and the rest happens in the player's browser:
POST /auth/{provider}/web/startanswers alogin_urland a privateretrieval_code. The client opens the address and pollsPOST /auth/{provider}/web/poll.- Where a server has no redirect client,
POST /auth/{provider}/startanswers auser_codeand averification_uri(the device flow). The client shows both and pollsPOST /auth/{provider}/poll.
The address is always drawn on screen as well as opened, because an open that
fails does so silently. Only an http or https address is ever handed to the
system, as an argument and never through a shell. GET /auth/providers decides
which buttons are live.
What comes back is the server's token. It is kept in the local settings file
under hassault.standalone.token, checked against GET /me when the menu
opens, and cleared when the server refuses it. Signed in:
- the match socket is
/hassault-ws?token=, so the seat is the account's; - account routes are asked with
Authorization: Bearer(NodeApi::with_token).
| Tab | Shows | Routes |
|---|---|---|
| Inventory | Owned skins; click one to equip it or take it off | /api/hassault/account/inventory, equip, unequip |
| Store | Credits, keys and cases; the market | /api/hassault/account/wallet, keys/buy, cases/open, /api/hassault/market, account/market/{id}/buy |
A refusal from the server (not enough credits, no key for a case) is shown in its own words.
Developer tools, in the executable
The menu's DEV TOOLS tab (front.rs, Tab::Dev) starts what used to need a
command line or the dashboard:
| Tool | What it starts | Needs |
|---|---|---|
| Aim drill | A drill from /api/hassault/drills on the range | Any game server |
| Benchmark | The map's benchmark path; the result returns to the menu as one line | A map with a path in bench-paths.json |
| Map editor | The map designer on a draft of the selected map | A server that keeps drafts |
| Model viewer | Every served weapon in hand, in any finish from /api/hassault/skins/catalog, at any wear, with its inspect clip looping (viewer.rs) | Any game server |
| Server | The rooms running, the selected room's roster, and a button to join it | Any game server |
Three switches under the tools turn on the net graph, hitboxes and first-person tracers for the next match. Each sets the console CVar of the same name.
A game server keeps map drafts only when started with
HASSAULT_ENABLE_DRAFTS=1. Its content routes have no accounts, and a draft can
be saved as a map file, so the public server leaves it off. With it on, the
draft routes and draft:<id> maps are served there and the editor needs no
dashboard node; --mode=edit works with --game-server= as well. The switch is
read per request.
The console, for a client with no node
Two faults made the console useless standalone, and neither was in the console:
- The game server dropped
console_exec. The native client sends server commands down its match socket, where a node's channel resolves the room from the connection. The game server's socket had no arm for the event, so every command went nowhere and nothing said so. It answers now (hassault_console.socket_console), under the same roles as its HTTP route but read off the socket's own account — so a guest who is hosting can run the room's commands, which the sign-in-only HTTP route never allowed. - It served no client CVars.
draw.fovis the client's to apply, but the client learns the name and the range from the registry — and without it could not telldraw.fovfrom a server command, so it sent that too.console_definitionsnow adds everyclient-flagged CVar from the node's ownconsole_registry, so both servers describe one set of settings.
And three things in the console itself:
- A sent line that is never answered is reported (
Console::expire, four seconds). A console that sends a command and prints nothing is indistinguishable from one that ran it. - A CVar this client reads is settable even when nothing described it
(
honored_def): an older game server, or Train. It carries only the type, which is this client's own knowledge — the type of the read that consumes it. - Built-ins and borrowed spellings.
help [name],find <text>,echo,quit/exitanddisconnectrun with or without a server (BUILTINS, one table for help, search and completion).SPELLINGSmaps what people type first —sensitivity,fov,net_graph,cl_crosshairsize,bot_add— onto the names that exist here. They are spellings, not a registry: each resolves to a name that is then typed, range-checked and routed like any other.
It is also drawn differently. It was a translucent band the width of the window, and the scoreboard read straight through it as if it were output. It is now an opaque panel hung from the top, inset on a wide window, with a field for the input, a list of completions above the caret (one name to a row, its current value on the right, Up and Down to choose) and a scrollbar. Long lines wrap by column rather than running off the panel.
The pane stops rendering while the native client plays
The pane's three.js loop used to run the whole time the native window was up: a
full WebGL render, in a compositing webview, on the same GPU the game is trying to
have to itself — and invisible, because the companion overlay covers it. The frame
callback now returns early while a native process is running, keeping the loop
alive (so the map is back the instant the window exits) rather than cancelling it,
and updating last first so the first frame back is not a two-minute dt.
The scope and the sound, natively
The last two things the native client did not have, and the two that make it a different game rather than a different window.
The scope is the browser's, rule for rule (combat.ts's cycleScope): right
mouse steps none → 2× → 4× → none, a cycle rather than a hold because the levels
are discrete and holding for one while a second gesture reaches the other is two
controls for one axis. A weapon with no zoomLevels ignores the click rather
than consuming it, so the button stays free to mean something else later.
Three things about it are easy to half-implement, and all three are pinned:
- The magnification divides the mouse as well as the field of view. A zoom is a narrower view, not an enlargement, so a hand movement that swept 10° unscoped must sweep 2.5° at 4×. Zooming without dividing the sensitivity is an aim that is wrong only while scoped — which is the one situation the scope exists for.
- It drops on a weapon swap, on death, and on releasing the pointer. The step is an index into this weapon's levels, so carrying it across a swap is a magnification the gun in your hands does not have; and coming back to the window at 4× with no memory of having scoped reads as the mouse having broken.
- The crosshair reads the cone the next shot will actually use —
spreadwhile scoped,hipfireSpreadotherwise, and those differ by 27× on the sniper. Drawingspreadunconditionally would hide the hip-fire penalty, which is precisely what an unscoped sniper is.
The sight itself is drawn, like everything else on the HUD: two rings, two hairlines with a gap at the centre, a dot, and the magnification underneath. The blacked-out surround is the mechanical half and not decoration — it is what the zoom costs, and a magnified view with clear peripheral vision would be a free upgrade rather than the trade the weapon is built around. The rings are sized in pixels on both axes so the sight stays circular in a window of any shape.
The sound is audio.rs, the Rust half of audio.ts: the same timbres, the
same envelope, the same equal-power pan on sin(bearing − listenerYaw), and the
same rule that your own noises are made locally rather than waited for. cpal rather
than rodio, because rodio's job is decoding and mixing files and there are no
files here.
Two decisions carry it:
- The audio thread owns every voice. The game thread sends a voice down a
bounded
mpscchannel and the callback drains it before mixing. AMutex<Vec<Voice>>is shorter and is the classic way to get a dropout: the callback runs on a real-time thread, and blocking it on a lock the game thread holds is a glitch, not a delay. A full queue drops the sound rather than blocking the frame loop. - The filter's stability condition is a relationship, not a bound. The
band-pass is a Chamberlin state-variable filter, stable while
f < 2 − q— so a bright centre frequency and a wide band are only unstable together. The first version clamped each independently, and the failure is not quiet distortion: it is full-scale noise, at the exact moment a shotgun goes off. Pinned bythe_filter_stays_stable_at_the_brightest_timbre.
A machine with no output device gets a client that says so and plays on. This is a game; refusing to start because a speaker is missing would be the wrong trade.
Training, natively
training.rs is a port of training.ts, and it exists for the same reason that
file does: the shoot-jump is the thing Train is for, and it cannot be practised
without a trigger. Offline there is no server to send a SelfState, so the range
plays that part — ammo, reloads, six dummies on the map's own spawn points, and
the hitscan against them.
The shape that makes it worth having is self_state(): it returns the same
SelfState a snapshot would have, so the HUD, the view model and the trigger
have no offline branch at all. Native Train now counts a magazine down, reloads,
and lights a hitmarker through exactly the code a match does.
Three rules are inherited from the TS original and are bugs if forgotten: a
-1 reserve is unlimited and stays unlimited (decrementing it turns the
sidearm bottomless into four billion rounds on the first reload); a weapon switch
cancels a reload rather than letting the timer fill a gun you walked away
from; and hitmarkers drain on read, so each is shown once.
One thing the range must do that the browser's does not: apply the kick
itself. In a match the server applies kickback and reconciliation hands it
back, so a client that never applies it is still correct. Offline there is nobody
to do it, and without trace::kick_vector the shoot-jump silently does nothing —
in the one mode built to teach it.
Porting the range also brought the shot geometry (trace.rs), which is a fourth
copy of arithmetic that already exists in weapons.py, trace.ts and this
crate's physics. The fixture's traces and bodies cases had been sitting there
read by only two of the three clients; tests/conformance.rs now replays them
too. The body cases carry an optional height, and honouring it is what the
crouched-target case is for — a replay that assumed the standing height passes
it wrongly.
One consequence of getting this right, worth knowing before it looks like a bug: a level shot at somebody standing on your own floor is a headshot. The eye sits at 4.5, a body is 5.2 tall, and the head band is its top cube — 4.2 to 5.2. The server agrees, so a rifle kills a dummy in one shot, not two.
Aim drills run natively too. The pane's drill picker launches the
client with --drill=<id> (the node passes it only with --mode=train, and only
for an id in the drill table). main.rs fetches the expanded drill once Train
has placed the player and calls App::set_drill. The clock and the results card
are drill_hud.rs. The card answers to the keyboard, R to run again and
F for the free range, because Train keeps the pointer captured and a card
you had to free the mouse for would have worse controls than the game around
it.
The pause menu
Escape used to release the pointer and nothing else. It now opens a menu, which does that too — the pointer is released whenever the menu is up, because a menu you cannot click is a menu with a second and worse set of controls.
It is not a pause, and cannot be. In a match the server keeps simulating; a client that stopped reading its socket to show a settings page would come back to a body that had been shot at for a minute. Train runs on for the same reason rather than growing a second rule nobody could see. What the menu does do is drop every held key on the way in, so you do not return to the game already walking.
Every row is one of three things — an action, a choice that cycles, or a number
that steps — driven by the same four keys and the same click. rows_at produces
the on-screen rectangle for every row and both the painter and the mouse read
it, which is what stops a click landing on the row above the one it is drawn
over.
| Page | What is on it |
|---|---|
| Root | Resume, the three sub-pages, and Quit — labelled Leave match in a match, because a button that ends something you were winning should say so |
| Crosshair | Preset, style (cross / cross+pip / dot / ring), size, gap, thickness, colour, outline and its width, centre dot, T-style, dynamic, opacity, paste code, copy code — with a preview panel beside it |
| Video | Display (fullscreen / windowed), resolution scale, field of view, quality, anti-aliasing, shadows, vsync, frame cap, show hitboxes |
| Controls | Sensitivity |
The settings live in the node's settings bag, not a file beside the binary: they are declared in the module manifest, so the pane's Settings page edits the same rows. Writes go through a worker thread — an HTTP round trip on the frame somebody nudges a slider is a visible hitch, and a slider produces one per frame — and the in-memory value is authoritative for the session either way, so a node that is down costs a preference and never a frame.
The crosshair's gap is the floor its arms open from, never a cap: with
dynamic on (the default) it widens with the weapon's cone. Turning dynamic
off is a choice to be shown less — the cone is the server's either way, so it
changes nothing about where a shot lands. See
Crosshair spec v1 and share codes.
Fullscreen, resolution and quality
The client opens fullscreen from the first frame rather than toggling after
one. The alternative is a visible flash of a 1280×800 window on a 4K monitor.
hassault.video.displayMode cycles through three modes, and borderless stays the
default:
- Windowed.
- Borderless. Covers the chosen monitor without taking it over.
- Exclusive. Takes the display mode chosen in
hassault.video.exclusiveMode(resolution and refresh rate, stored asWIDTHxHEIGHT@HZ) on the monitor chosen inhassault.video.monitor. This costs a mode switch at each end, a black screen with it, and every other window on that monitor rearranged when the game exits. It is there for the display that only runs its highest refresh rate in exclusive mode.
A saved monitor or mode that no longer exists falls back to borderless on the
primary monitor rather than failing. display.rs snapshots the monitors once and
builds both fullscreen variants from that snapshot.
"Resolution" is a render scale, not a mode switch. The world is drawn into an offscreen target at 50–200% of the window and composited up. The HUD is drawn onto the swapchain after that, at native resolution, because 5×7 glyphs upscaled from half resolution are unreadable and the HUD costs nothing to draw at full size. The title bar reports the rendered size whenever it differs from the window's, since a render scale is otherwise invisible in a screenshot.
Quality is a preset, not a ceiling. Picking a level writes every row it
covers, and any later change to a row turns the label into CUSTOM (HIGH). That
is also why menu::apply returns a list of keys: persisting only
hassault.video.quality would bring the level back next session with the old
rows underneath it.
| Low | Medium | High | Ultra | |
|---|---|---|---|---|
| Shading | flat | hemisphere + sun | + fill | + fill |
| Fog | the map's own | the map's own | the map's own | the map's own |
| MSAA | off | off | 4× | 8×, where supported |
| FXAA | off | on | off | off |
| Anisotropy | 4× | 8× | 16× | 16× |
| Textures (per layer) | 128 | 256 | 256 | 512 |
| Shadows | 1024, 4 taps | 2048, 8 taps | 4096, 16 taps | 4096, 16 taps |
| Map lights | 0 | 8 | 16 | 64 |
| Sky dome | no | yes | yes | yes |
| Bloom | off | 25% | 25% | 50% |
Every level uses the map's own fog density. Low and Medium used to thicken it (×2 and ×1.36) to save fill rate, which let a player on a weak GPU lose a gunfight to fog a stronger machine did not draw; see What a graphics setting may not change. Fill rate now comes out of the render scale, the light count and the shadow taps. Low returns the surface flat, with no hemisphere, sun or shadow. That is the level's choice, not a cheaper approximation of the same picture, so a screenshot taken at Low beside a browser screenshot is not evidence the clients diverge.
Advanced video
The Video page opens an Advanced page with the rows the preset writes, plus four that no preset touches:
- Anti-aliasing (
msaa): off, 2×, 4× or 8×, offered only where the GPU supports it (see below). - FXAA (
fxaa): edges smoothed from the finished image, in the final pass. Medium's anti-aliasing, where MSAA is off. - Anisotropy (
anisotropy): 1× to 16×. - Texture quality (
textureQuality): 128, 256 or 512 texels per layer. The procedural surface array is regenerated with a full mip chain. - Shadows (
shadowQuality): Low to Extreme, from 1024 texels and 4 filter taps up to 8192 and 16. The map is still baked once at load, so this costs memory and sampling, not a pass per frame. Bias scales with the texel size. - Map lights (
mapLights): 0 to 64 of the nearest. - Sky (
sky): the dome on open maps, drawn from the served atmosphere with the same formula as the browser's. - Bloom (
bloom): a five-level chain inpost.rs, a 13-tap downsample and a tent upsample, thresholded on the scene's linear light at 1.4 with a 0.5 knee and added back into it before the curve. Only light brighter than white glows: the maps' emissive lamps, screens and LEDs (strength 4–10), and the sun's disc. A sunlit wall (about 0.95) does not. - Sharpening (
sharpen): contrast-adaptive, in the final composite. Most useful below a render scale of 100%.
The browser runs the same chain (post-chain.ts), from the same two
settings: the same threshold, knee and five levels, the same 13-tap down and
tent up, the same CAS and the same dither, which browser_parity.rs pins in
both sources. three tone maps inside each material only when drawing to the
canvas, so with the chain on the scene goes to a linear half-float target. The
bloom is taken from that target times the exposure, and the display pass adds
it to the scene and applies three's own ACES and sRGB curve. The clear colour
is the one thing three never tone maps on the canvas, so the chain pre-distorts
it (inverseAces) and the sky comes out unchanged: verified pixel-exact against
the plain render in a browser.
Bloom is on by default at Medium and High, in both clients. The shared
setting defaults to 0.25 (MODERATE_BLOOM in settings.rs and
post-chain.ts, and the default in the schema and the manifest). Native's Low
preset writes 0. The browser's tiers have a Bloom row (TierSpec.bloom),
off at Low, so Low still skips the chain and draws the plain renderer.render.
The chain runs whenever bloom or sharpening is above zero.
Why HDR bloom. The old bloom thresholded the tone-mapped image at 0.82 and screen-blended the glow on top. Thresholding after ACES cannot tell a lamp at 8 from one at 1, since both are near white there. Now both clients take the glow from linear light and add it before the curve, so it grows with how bright the source is and rolls off in the curve's shoulder.
Measured on native Bank (dust2_preview, PREVIEW_MAP=hd_bank): at 0.25 the
chandelier's region gains 44 levels on average and the walls gain none; 4% of
the frame moves by more than 4 levels. On sunlit Dust II with no lantern in
view, not one pixel changes. The browser's chain, run on a scene with a quad
emitting at 6 and one at 0.95 in headless Chromium, does the same:
- the lamp gains a halo (180, 130, 84, 43 at 10–30 px out, from 0);
- the wall's centre is 225 with the chain on or off, so the chain's display is three's canvas exactly.
Emissive light, natively. Every modelled map's lamps, screens and LEDs are
KHR_materials_emissive_strength materials at 4–10. three adds
emissive × emissiveIntensity to the light leaving the surface. Native used to
draw them as an ordinary surface tinted the emissive colour, which no
threshold could find.
world3d.rsreads the strength (the gltf crate'sKHR_materials_emissive_strengthfeature).- It carries the strength in the AO attribute as
1 + strength. AO never exceeds 1, so the world vertex does not widen for a dozen materials. fs_mainsplits the attribute back into the occlusion and the glow, and addscolor × glowbefore the exposure and fog, at every quality level.
FXAA, natively at Medium. Medium has no MSAA, for fill rate, and the browser's Medium multisamples, so native's Medium had jagged edges the browser did not. With FXAA on:
fs_tonemapwrites the scene plus its bloom through the curve into a half-float target. It is half float so a sky gradient is not cut to 8 bits before the dither.- The composite runs FXAA 3.11's compact "PC console" form on that target: five luma taps for the direction, then two or four taps along it.
- The filter first runs FXAA 3.11's local-contrast test (0.166 relative, 0.0833 absolute). Without it, every pixel is filtered and the photographed surfaces' grain blurs along with the stairs.
On Dust II it touches 8.4% of the pixels, all on edges. The target is allocated only while FXAA is on.
The dither. One output step of triangular noise, from two interleaved
gradient noise samples (Jimenez), in the final write of both clients. Natively
it is added in sRGB-encoded space, because that is where the swapchain's steps
are, and decoded back for the sRGB target to re-encode. In the browser the
composite's colour is already encoded. It moves pixels by at most one level: on
Dust II, 58% of pixels by exactly one. The previews leave it off
(display_once), because their coverage statistics count exact clear-colour
bytes; PREVIEW_DITHER=1 turns it on.
What it costs (hassault_bench_native.py, 1080p, this build's presets
interleaved with the previous build's, which had no FXAA and no bloom below
Ultra):
| GPU | Map | Level | GPU p50 before → after (ms) | GPU p99 | fps |
|---|---|---|---|---|---|
| discrete | Dust II | Medium | 0.32 → 0.43 | 0.41 → 0.75 | 642 → 642 |
| discrete | Dust II | High | 0.49 → 0.55 | 0.89 → 0.91 | 673 → 630 |
| discrete | Bank | Medium | 0.53 → 0.62 | 1.05 → 1.10 | 656 → 594 |
| discrete | Bank | High | 1.00 → 1.00 | 2.21 → 2.19 | 568 → 548 |
| integrated | Dust II | Medium | 10.31 → 11.73 | 14.66 → 16.23 | 75 → 69 |
| integrated | Bank | Medium | 13.20 → 15.12 | 18.50 → 20.79 | 63 → 56 |
Each row is the mean of two runs, except discrete Dust II Medium after, which
is one. On the discrete GPU the frame stays limited by the CPU (acquire), so
its fps column is noise and the GPU time is the number to read: a tenth of a
millisecond at most.
On the integrated GPU (Intel, powerPreference=low) the slice costs about
1.4–1.9 ms at Medium, and Bank Medium falls from 63 to 56 fps. Bank Medium,
benched with each part switched off in turn (--set):
| Bank Medium, integrated | GPU p50 (ms) | fps |
|---|---|---|
| Both on (the preset) | 15.09 | 56 |
| FXAA off | 14.27 | 58 |
| Bloom 0 | 14.22 | 59 |
| Both off | 13.51 | 62 |
So the bloom chain costs about 0.9 ms there and FXAA about 0.8 ms; the emissive and the dither are within the noise. Low has neither, so the iGPU's Low target is untouched. If Medium must hold 60 on an iGPU, FXAA or bloom is the setting to turn off there.
Pinned by browser_parity.rs:
both_clients_bloom_and_sharpen_with_the_same_numberscovers the threshold, knee and dither constants;both_clients_bloom_linear_light_before_the_curve;moderate_bloom_is_medium_and_high_in_both_clients_and_off_at_low;native_medium_anti_aliases_with_fxaa_and_the_rest_multisample;a_glowing_material_emits_in_both_clients.
post-chain.test.ts checks the knee against the measured cases (bloomShare).
The native scene is HDR, and tone mapped once. Every pass that draws into
the scene (world, volumes, sky, props, characters) writes pre-exposed linear
light — expose in lighting.wgsl.inc, the map's exposure times Brightness —
into an Rgba16Float target (SCENE_FORMAT in renderer.rs). The tone curve
is applied once, as display in post.wgsl, which every post pass reads the
scene through; this runs whether bloom and sharpening are on or not. The curve
is three's own ACESFilmicToneMapping (Hill's fit, its two matrices and the
/ 0.6), the same as the browser's materials and its DISPLAY pass;
browser_parity.rs pins the coefficients in post.wgsl, post-chain.ts and
atmosphere.rs. Before this, every native shader tone mapped on its own with
Narkowicz's fit. That is a different curve, and it put native mid-tones about
a fifth above the browser's: 0.18 grey at exposure 1.15 came out at 0.311
against three's 0.2525.
The cost is bandwidth, and it shows only with MSAA. Medium has no MSAA and
moved by about 0.01 ms of GPU time. High's 4× MSAA samples are now twice as
wide, and High rose by 0.06–0.09 ms: Dust II's GPU p50 went from 0.35 to
0.43 ms, Bank's from 0.52 to 0.59 (--bench, 1080p, interleaved runs against
the previous build). The frame stays CPU-bound either way.
Fog is mixed in linear light, before the curve, in both clients. That is
the only order a linear scene allows, and the browser has it whenever its chain
is on (inside a render target, three fogs before tone mapping). Unadjusted,
though, the curve would then lift the fog colour itself, and a corridor would
recede into grey instead of the map's colour. So both clients hand over the
fog colour already run backwards through the curve, and the clear colour
too: display_hex_to_scene in atmosphere.rs on native, and
sceneColoursForChain in post-chain.ts, swapped for the length of the scene
render. A fully fogged pixel and the empty sky then come out as exactly the
map's hex. Bloom is taken from the same linear light and added before the
curve, in both clients (see the bloom notes above).
- Brightness (
brightness): a multiplier on the map's exposure. - Frame latency (
frameLatency): 1 to 3 frames queued, passed to the surface asdesired_maximum_frame_latency. One is the lowest input lag, three the smoothest pacing on a GPU that is near its limit.
All the keys live under hassault.video., and all are in the manifest, so the
dashboard's settings page lists them.
Choosing the GPU
A Display and GPU page holds the rows that need the device rebuilt. Each is marked "applies on restart", and the page ends in a Restart now row. That row finishes the settings write, leaves the match and re-executes the client with the same arguments.
- GPU (
hassault.video.adapter):auto, or an adapter saved by name rather than by index, so adding a second GPU does not silently switch the game to it.gpu::adapterslists each physical GPU once, deduplicated by PCI vendor and device id; GL reports no device id, so it matches on the name before the first/. The list is sorted discrete-first. - Graphics API (
hassault.video.backend):auto,dx12,vulkanorgl.automeans the primary backends and never GL, which is there for a machine whose driver is broken for the other two. - Power preference (
hassault.video.powerPreference): high performance, or low power for a laptop on battery.
Hybrid laptops. On an NVIDIA Optimus or AMD switchable machine, the driver
can pin a process to the integrated GPU whatever wgpu asks for. The executable
therefore exports NvOptimusEnablement and AmdPowerXpressRequestHighPerformance,
which the drivers read at process start. Rust does not export symbols from a
binary by default, so build.rs passes /EXPORT: to the MSVC linker. The machine
this was written on is such a laptop (RTX 4080 Laptop plus an Intel iGPU), and
with the GPU on auto it opens on the RTX over Vulkan.
From the command line:
--list-adaptersprints the deduplicated list as JSON and exits.GET /api/hassault/native/adaptersruns it and caches the answer by binary path and modification time.--adapter=,--backend=and--low-poweroverride the saved choice for one run.--windowedstarts in a window.--set=key=valueoverrides any setting for one run without saving it, which is how the screenshot scripts pin a preset.
The title bar names the backend and GPU actually in use.
The rest of the video page
Four more knobs, and what each one honestly costs is the point of listing them separately rather than folding them into the preset.
Field of view (hassault.video.fov, 70–120°) is the only row here that
changes how the game plays rather than how it looks — a wider view is more of
the room and a smaller enemy in it. 75 is the pane's, so the default is the same
picture in both clients. It is read through App::base_fov() rather than written
onto the camera, because the scope divides the base FOV and a value assigned
straight to camera.fov would be overwritten by the next scope step — a bug
visible only while scoped.
That accessor also folds in the console's draw.fov, with the same precedence
the crosshair and draw.hitboxes use: a CVar assignment is a statement about
now, a setting is a preference. draw.fov was one of the served client CVars
this client stored and admitted it was not reading; it now has a reader, so it
moved into console::HONORED. Its declared range in console.py was widened from
60–110 to match settings::FOV_RANGE — a console that accepted 65 would set a
value the menu cannot show, and the next nudge of that row would silently jump it.
Shadows (hassault.video.shadows) is a look, not a frame rate, and the
setting says so. The map and the sun are both static, so ShadowMap::new bakes
the map once at load; turning this off skips no pass, it only stops the fragment
shader taking the filter taps. It is offered because some people prefer the flat
read — presenting it as a performance option would be the placebo the rest of this
page keeps refusing to ship.
Vsync (hassault.video.vsync) is off by default: the native client
presents immediately (Immediate), which is the lowest input latency there is and
the reason the client exists, at the cost of tearing. It defaulted on until G2,
which made that an opt-in. A player who minds the tearing turns it on, or sets a
frame cap.
Frame cap (hassault.video.fpsLimit, one of 0/60/120/144/240/360, uncapped by
default) waits out the remainder of a frame's slice. Unlike vsync it queues no
frame and adds no latency; it is for a laptop that would otherwise run its fan
flat out drawing frames no display will show and then thermally throttle below
the cap anyway. The sleep happens before the frame clock is read, so it lands
inside dt rather than between two frames — sleeping after it would leave the
simulation stepping at the uncapped rate while the screen ran at the capped one,
the same class of bug as ticking a player by wall clock.
The native cap (pacing.rs) keeps a cadence of deadlines and sleeps to just
short of each, then yields the last fraction of a millisecond. It used to sleep
"whatever is left" each frame, and the OS wakes a sleeper late by a nearly constant
amount: measured, a 240 cap ran at 217 and a 144 cap at 137, below the refresh
rate of the display it was set to match. Deadlines that advance by the budget pay
one late wake back on the next frame; the sleep aims short by the overshoot it has
been seeing (an average, capped at 2 ms, so a busy machine does not turn the cap
into a spin); and a frame that ran more than a slice long restarts the cadence
rather than earning a burst of catch-up frames. Now 240 runs at 241 and 144 at
144.0, with p99 within 0.6 ms of the slice.
A saved cap is snapped to the offered list rather than clamped, because a cap of 37 is not wrong so much as meaningless — honouring it would leave the menu holding a value none of its steps can reach, so the row would jump the first time it was touched.
The spec guarantees only 1 and 4. Counts beyond those sit behind
TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES. A pipeline built with an unsupported
count is a validation error on the first frame, not a slower one, and that is
exactly how the first build of the quality setting crashed.
So the client requests that feature only if the adapter lists it. Requiring it
is how a client refuses to start on a perfectly capable integrated GPU. The client
then asks the adapter which counts every attachment format of the pass supports,
and offers only those (gpu::supported_sample_counts).
A saved count is snapped down to that list (gpu::snap_samples), never up:
8× on a GPU that tops out at 4× becomes 4×, and 2× where only 1 and 4 exist becomes
off, since the reason to pick 2× was that 4× was too slow. The setting used to be a
bool so that it could not hold an unsupported 2; the snap is what now makes a
count safe to store.
Selecting High crashed the client
Worth writing down because the fix is structural rather than a corrected value, and because the symptom named the wrong culprit.
set_video rebuilds what a sample-count change invalidates. For the character
and prop passes it calls each module's own build_pipeline — the same
function construction uses — so those two cannot drift. For the world pass it
built a second PipelineLayout inline, and the second one was wrong: it named
[camera, detail] where the construction path names [camera, detail, shadow].
The render pass binds the shadow map at group 2 regardless. So the first frame after switching quality bound a group the pipeline's layout did not have, which is a wgpu validation error — a panic, not a darker picture. Every path to a sample-count change hit it, in both directions, which is why it read as "High crashes" rather than as anything to do with shadows.
The fix is that there is now exactly one world layout, held on the Renderer as
world_layout. A pipeline layout is immutable and says nothing about multisample
state, so there was never a reason to build a second one; holding the single
definition is what makes the two paths unable to disagree again. The same change
caught a second, quieter instance: the translucent-volume pipeline draws inside
the same pass and was not rebuilt at all, so it needed a smoke cloud on screen
to fire — switching quality in an empty room looked like it worked and the crash
landed on somebody's grenade a match later.
What "the netcode feels laggy" actually was
Four separate faults, none of them in the protocol, and all four with the same symptom: bodies snapping about, shots that should have landed not landing, and your own player being pulled backwards. Worth writing down together, because "rubber-banding" is a symptom people diagnose as one thing.
1. The native client did not interpolate remote players at all. It drew
self.players — the newest snapshot — verbatim. The server broadcasts at 20 Hz,
so every other player in the match moved in fifty-millisecond jumps, with
ordinary jitter landing on top of those jumps and pushing bodies backwards and
forwards around where they really were. The browser client has had
SnapshotBuffer since the beginning; the native one never got the port.
interp.rs is that port, deliberately field-for-field with
packages/core/src/modules/hassault/net.ts. (Since G4 both run the adaptive
InterpClock instead of the fixed delay and all-time minimum below: see
After G4: one curve and an adaptive render clock.) Bodies are drawn
INTERP_DELAY_MS (100 ms, two snapshot intervals) in the past, between two
snapshots that have both already arrived — so the position shown is an
interpolation rather than an extrapolation. Past the newest snapshot it holds
rather than guessing: a brief freeze is honest, and a guess is a body drawn where
nobody is and at worst inside a wall.
The clock is the subtle part, and the tests pin it. Server t and this process's
clock are unrelated, so rather than synchronising them the buffer tracks the
smallest local_arrival − server_t ever seen. The minimum is the sample that
queued least — the best estimate available without a clock-sync protocol, and,
more importantly, stable. An average would wander with the network and drag
every body on screen with it.
App::clock_ms is process-relative. The base is arbitrary — the buffer only
ever differences it against the server's stamp — but it must not step, which is
exactly what a wall clock does when NTP corrects it. A jump there moves every
interpolated body at once and puts a viewT on the wire pointing at a moment the
server's position history never covered.
2. The native client never sent viewT. The field existed on Command and
was never set, so every shot from the native client was resolved against the
target's current server position while the client was rendering that target
100 ms in the past. Hitting a moving player meant leading them by a body width,
for no reason the player could see. It is now stamped from
SnapshotBuffer::render_time — the same number the browser sends — and left
absent before the first snapshot rather than defaulted, because a fabricated
render time asks the server to rewind to a moment that never existed.
3. The native client flushed the socket every frame. It runs deliberately
without a frame cap, so that was several hundred WebSocket text frames a second
per player, each a JSON parse on the backend's single event loop — the same loop
running the 20 Hz match tick for everybody in the room. The tick slipped,
snapshots arrived in lumps, and the prediction was corrected in lumps: rubber
banding produced entirely by the client's own send rate. flush now rate-limits
itself to SEND_INTERVAL (33 ms, the browser's SEND_INTERVAL_MS), which costs
nothing — a command carries its own dt and sequence number, so a batch of eight
is exactly as simulable as eight messages of one.
4. The server dropped overflowed commands silently. MatchRoom.enqueue
bounds the queue at MAX_QUEUED_COMMANDS and drops the oldest, which is right.
But ack only moves when a command is simulated, so a dropped command was
never acknowledged — and the client replays every unacknowledged command on top
of each correction. Its prediction then sat permanently ahead of the server, which
is precisely what the bound exists to prevent. The drop now advances ack past
the discarded command: "this one is not coming back." Monotonic by construction,
since the dropped sequence is lower than anything still queued behind it.
5. Input was produced per frame, and dt had a floor. The two remaining
halves of the same mistake, and both were silent.
send_input clamped the frame time with dt.clamp(0.001, MAX_DT). That lower
bound is the problem: this client runs uncapped on purpose (Immediate present
mode, hassault.video.vsync off by default), so about_to_wait iterates
thousands of times a second and every iteration shorter than a millisecond
claimed a millisecond. At 4000 iterations a second the client asked the server to
simulate four seconds for every real one. The server spends client-supplied
dt from a budget replenishing at 1.1× real time, so it granted a fraction of
what the client had already predicted; the prediction sat permanently ahead and every snapshot
dragged it back. Reported — reasonably — as "I hold forward and can't move", which
is what a constant backward correction feels like from inside.
Compounding it, flush carries at most MAX_COMMANDS_PER_MESSAGE (64) per 33 ms
window, so above ~1940 iterations a second the surplus was trimmed after
push_command had numbered it and Prediction::predict had already moved the
body on it. The client was walking on commands the server would never see.
Input is now produced on its own clock (INPUT_HZ, 250 Hz), with the real
elapsed time banked in input_accum between commands. The sum of the dts on the
wire is therefore exactly the wall-clock time that passed, however fast the loop
spins, and a flush window carries 8.25 commands rather than 132. 250 Hz is above
any display refresh rate and the mouse is unaffected — look still runs per
device event, so aim keeps the full input rate the client exists to deliver. The
MAX_DT upper clamp stays: a stall longer than that is time the server would
refuse anyway, and banking it would spend the next second paying it back.
Four cases in app::tests pin it, and all four fail against the old code: the
claimed time for one real second at 60 / 144 / 500 / 1000 / 4000 / 20 000 fps
(4.000 s at 4000 before), a mixed-rate loop where bursts must contribute the
microseconds they actually took, the per-flush command count against the 64 cap
(132 before), and that a loop slower than INPUT_HZ still sends one command per
frame — the accumulator refuses to round time up, it never withholds time that has
passed. flush also says so now if the backlog ever overflows again, once rather
than per flush.
6. The native client reconciled onto its own momentum. The one that survived everything above, and the one that made a match feel elastic while Train felt perfect — Train never reconciles, so it could not show.
Prediction::reconcile built its replay base as the server's position with
..self.settled for everything else, on the stated reasoning that "the snapshot
sends a position but not a velocity". It sends both.
MatchPlayer.private_view has carried a move block — velocity, time in air,
crouch, crouchedInAir, sinceLanded — since movement became velocity-based, and
the browser's reconcile has read it since. The native client never parsed it.
That is not a small drift. Movement here is a velocity integrated against AC's
friction constants, so the velocity is the state: a position alone does not
describe a body that is still sliding. Replaying the unacknowledged tail on the
client's own velocity re-runs the exact number the correction exists to fix, so
the error compounds instead of settling — the prediction runs away, the next
snapshot drags it back, twenty times a second. Measured in
prediction::tests, with a ten-command tail and a server reporting a body at
rest: the replay lands 3.66 cubes past the acknowledged position instead of
1.82. Just under SNAP_DISTANCE, so it is eased rather than snapped, which
is what makes it read as an elastic pull rather than as a teleport.
The same call also passed on_ground: false unconditionally, with a comment
saying the support state is not on the wire. It is — ground is on the shared
row and the browser reads it. A replay that starts airborne converges on the wish
direction at AIR_RESPONSE rather than GROUND_RESPONSE (five times slower),
takes a frame of gravity, and refuses a jump.
Both are now read off the snapshot. A server too old to send the move block
leaves the predicted momentum alone — the best guess available, rather than a
lie.
sinceLanded is a duration, not a timestampThe client's simulated clock and the server's are unrelated, so only "how long
ago" transfers. It is converted against the client's own t as it is applied;
adopting the server's timestamp would open the chain-jump window at an arbitrary
moment.
7. The native client sent its view angles in degrees. The one underneath all of the above, and the reason a match felt wrong in a way Train never did.
The wire carries yaw and pitch in radians. Nothing declares that, and nothing
can check it: the server assigns player.state.yaw = command.yaw and takes its
sine, so there is no range to validate and no value that looks wrong. The browser
sends player.yaw straight off the physics state, which is radians, so the
convention was only ever recorded in the two clients that agreed with it.
camera.rs works in degrees — reasonably, it is a view. Every seam in
app.rs converted at the boundary: place_offline, try_fire, the respawn
reset, and the prediction.predict call. The line that built the outgoing
command did not. So the server received a heading of 315 and read it as 315
radians — 48 degrees — and walked the body away from where the player was aiming:
| camera yaw | client predicts | server actually walks | error |
|---|---|---|---|
| 0° | 0° | 0.0° | +0.0° |
| 45° | 45° | 58.3° | +13.3° |
| 90° | 90° | 116.6° | +26.6° |
| 180° | 180° | 233.2° | +53.2° |
| 315° | 315° | 48.2° | +93.2° |
Past 90° the forward key carries a backward component, which is why it presented as "sometimes W goes backwards" rather than as a units bug. Below that it is a slide — you travel at an angle to your aim, the snapshot corrects you onto the server's path, and you are pulled sideways twenty times a second.
Three things hid it. The error is exactly zero at yaw 0, and every test in the
crate aims along +x. Train sends no command at all — it steps the physics
directly off to_radians() — so the one mode with no server was the one mode with
the conversion right, which pointed the investigation at the netcode. And the
shared conformance fixture cannot see it: physics-vectors.json pins the
simulation, and this was never a disagreement about the simulation.
The fix is structural rather than a third to_radians(): App::view_angles
returns the angles in the simulation's units, and the command and the prediction
both read that one expression. Two sites eighteen lines apart that had to agree
are now one site. walking_forward_goes_where_the_camera_points replays eight
headings and asserts the bearing travelled is the bearing asked for; it fails at
45° against the old code.
Two more units bugs fell out of the same audit:
interp.rswrapped headings on 360. APlayerRow's yaw is radians, so a difference never exceeds 2π and neither wrap branch could fire — a remote body turning past ±π took the long way round between snapshots. It wraps on 2π now, and the helper's name no longer claims degrees.SelfStatedeclaredx/y/zthat the server never sends.private_viewcarries no position; the authoritative one is in the shared row, which is where reconciliation and the browser both read it. With#[serde(default)]the three fields deserialized to0.0in silence, and the respawn path reset the body to the world origin — inside the solid border every map has, wherestepfinds itself enclosed and holds still. Every death parked the player in rock until the next snapshot reconciled them out. The fields are gone and respawn reads the row.
The native client also pings now (MatchSocket::ping, once a second, echoed
by the channel's existing pong) and shows the round trip on the HUD. It is an
Option<f32>: drawing 0 MS for "not measured yet" is a claim of a perfect
link, and someone judging whether a lost duel was theirs or the network's would
be reading a number the client made up.
Seeing the hitbox
hassault.debug.hitboxes draws the exact volume a shot is resolved against
around every body, with the head band marked in a second colour. It works in both
clients and is one node setting, which is the point — the question it answers is
"is what I am shooting at where it is drawn?", and an overlay you can only turn on
in one client cannot be used to compare them.
It exists because that question had no way to be asked, and the first thing it
found was a real bug. The native client's bodies.rs carried
const CROUCH_SCALE: f32 = 0.75 — which is the scale applied to the eye, not
to the body. A crouched body's height is (eye × 0.75 + above_eye) / standing =
0.784. Four percent short, all of it at the top, which is where the head band
is: you aimed at the drawn head of a crouching player and missed, slightly more
often than chance, and blamed the netcode. The file's own comment said "a body
drawn larger than its hitbox teaches you to miss" and then got the number wrong.
The fix is the rule the rest of this module already follows: the native client now
fetches GET /api/hassault/hitbox at startup, next to the loadout, and holds
no dimensions of its own. Every derived height is served computed —
crouch_height, standing_height — because two implementations of
crouch_height is two chances to round it differently.
Two things about how the overlay is drawn:
- It is depth-tested. The wireframes go into the same vertex stream as the bodies, so a hitbox behind a wall is hidden by the wall. Drawn in an always-on-top pass it would be a wall hack, whatever it is labelled.
- In the pane it is a pool of its own, not a child of the avatar group. The avatar group is scaled on Y to animate a crouch, so a head band parented to it would be squashed by the same factor and would stop being the band the server actually uses — which is the exact class of error the overlay exists to catch.
A spec whose shape this build does not know how to draw yields no bodies at
all rather than boxes. A capsule drawn as a box is a confident picture of the
wrong body, and an aim learned against it is wrong everywhere the two differ.
Inspect, and the scoreboard
Inspect (F) was declared in controls.ts — label, note, default binding —
and consumed by nothing. It now runs a weapon-inspect animation in both clients:
the gun comes in towards the centre of the screen, lifts, and rolls most of the
way over so the side of the receiver — where a skin's pattern lives — faces the
camera. A pose that only lifted the gun would show the face it already shows.
It is purely local and never on the wire, the same concession client-side recoil makes. That is what makes it safe to interrupt on any frame, which in turn is what makes it usable in a match rather than a state you have to wait out. Firing cancels it — the pose swings the barrel away from the crosshair, and a shot drawn out of a weapon pointing at the floor is a picture of a shot that did not happen — and so does a reload, because the reload is the animation the server is doing. Dying drops it, since it is something you asked for rather than a state of the weapon.
Why the pose needs three numbers, not one
The first version was one scalar — inspectEnvelope(t), ramp up, hold, ramp down
— multiplied into every axis of the pivot's position and rotation. That is a
correct animation and it looks wrong, for a reason worth writing down because it
is not obvious from the code: the hold is a hold. The weapon travelled out,
stopped dead for the ~0.7s the envelope sits at 1.0, and then retraced its exact
path. What the eye reads there is not "somebody is looking at a weapon", it is a
stutter — and the retrace reads as the clip being played backwards, because it
is.
Three numbers fix it, and each one is doing a specific job:
| What it drives | Why it is separate | |
|---|---|---|
inspectEnvelope(t) | the rotation, and how much of the pose applies at all | Has to return to zero, or the weapon never comes back to the aim |
inspectEnvelope(t + LEAD) | the translation | 60 ms of lead means the gun is already rising before it starts to turn. Every axis starting and stopping on the same frame is the signature of a single rigid transform, which is exactly what this is |
inspectTurn(t) | the extra roll, added to the base | Monotonic, so the roll only ever winds one way. This is what removes the freeze: through the whole hold the weapon keeps turning, even though the envelope is flat |
The roll is envelope * (ROLL + TURN * turn) rather than envelope * ROLL. The
envelope still scales it, so the weapon starts and ends at rest with no extra
bookkeeping; the turn is only what it does in between. A roll driven by the
envelope alone must unwind along the path it wound up, and no amount of easing
hides that.
The easing is smootherstep, not smoothstep. Smoothstep's acceleration jumps
at both ends, and over a 0.3s rise that is a visible tick as the weapon leaves
rest; the quintic costs two multiplies and has a continuous second derivative.
Its output is clamped as well as its input — algebraically it cannot exceed 1 on
[0,1], but in floats it lands on 1.0000000000000013 near the top, which was
enough to fail the envelope's own bound check.
INSPECT_DURATION went 1.35 → 1.5s to give the turn room. It is still a maximum
rather than a commitment, for the reason above: any frame can interrupt it.
Both clients carry the same constants and the same curves, and a test samples them rather than comparing the source — the Rust and the TypeScript are separate implementations, so what has to agree is the curve. Two clients drawing the same weapon differently is the drift this module's shape exists to avoid, and an inspect is the one animation a player watches closely enough to notice.
The scoreboard is new in the native client (Tab, held). Names, kills, deaths
and a team stripe, with the match score above them; ranked most kills first then
fewest deaths, matching the browser, because two clients ranking the same match
differently is a thing people notice and nobody can explain. Sorting happens in
app.rs rather than in the painter — what "winning" means is a game-mode question.
Held rather than toggled, like every shooter: you read the scores during a lull, and a toggle is a scoreboard you leave up by accident and then die behind. It reads the authoritative roster, never the interpolated copy, which is a tenth of a second old and deliberately excludes you.
None is not an empty matchHudView.scoreboard is an Option. None means the key is not held; an empty
slice means a match with nobody in it. Drawing the panel for both would put a
scoreboard on screen permanently — pinned by
a_scoreboard_that_was_not_asked_for_is_not_an_empty_one.
Testing a third implementation
physics-vectors.json is now replayed by three suites — the server's
(backend/tests/test_hassault_physics.py), the browser client's
(conformance.test.ts), and this one (apps/native-fps/tests/conformance.rs).
The fixture pins agreement; each side's own unit tests pin correctness. A third
implementation without a seat at that table is a third implementation that drifts,
and the drift has no symptom except shots that miss things you are looking at.
cargo test --manifest-path apps/native-fps/Cargo.toml
Two things about that test are deliberate:
- The crate has a library target purely so the test can exist. Rust integration tests link a library, not a binary, and a test that cannot be written is a test that does not exist.
- The tolerance is loosened to 1e-3, from the fixture's 1e-9. That is a
double's tolerance and this implementation is
f32— matching the wire and the renderer — so it cannot meet it. Loosening the fixture itself would loosen it for the two implementations that can. 1e-3 is about six significant figures at these magnitudes: far tighter than any drift that could affect play.
The mesher has no shared fixture, so its cross-check is coarser but real: triangle
counts match the browser client's HUD on every map tried (hd_atrium 31,944 →
"32k", hd_crossing 30,552 → "31k", hd_pit 13,360 → "13k").
Game feel, natively
The combat rules did not change here and neither did the wire. This is the layer
between "the server said you hit them" and "that felt like a hit" — five things,
all client-side, all in apps/native-fps.
One rule governs the whole of it and is the only thing here that can fail silently.
self.camera is what view_angles puts on the wire on every command, and what a
shot's ray is built from. Camera::shaken therefore returns a copy, and only
Renderer::render is handed it — the shake exists on the way to the GPU and
nowhere else.
Written as a mutation instead, screen shake stops being cosmetic and becomes
recoil the server faithfully honours. Nothing errors. The game simply feels like
it has recoil nobody can find the tuning for, and the tuning is not there because
the recoil is not real. shaking_does_not_move_the_camera_the_game_runs_on is a
unit test for exactly this.
Screen shake
camera::Shake holds a trauma value in 0..1 and squares it to get an angle.
That is the whole design, and the squaring is worth a sentence: trauma climbs
linearly with what happened to you and the displacement is its square, so a pistol
round barely registers while a grenade at your feet throws the view — from one
number, with no table of cases. A linear ramp makes small hits too loud and large
ones too quiet at the same time, and no single scale factor fixes both.
Three things feed it, each through a pure function with its own tests:
| Source | Function | Note |
|---|---|---|
| Your own shot | fire_trauma(kickback) | From the served kickback, like kick_vector and weapon_voice before it — a balance change to the gun moves how it feels with it. kickback <= 0 is how all three tell a knife from a gun, and a knife shakes nothing: a swing that jolted the camera would advertise the one weapon whose entire value is that carrying it gives nothing away |
| A hit taken | damage_trauma(amount) | A square root, because the message is "you are being shot" and a graze means that just as much as a near-fatal hit. One shake per tick, not one per marker — a shotgun lands eight pellets in one snapshot, and eight calls would put a point-blank blast at full trauma while the same damage from a rifle burst barely registered. Fall damage goes through here too; it appears in neither hurt nor hits, so it would otherwise be the one damage in the game felt by nothing |
| A nearby detonation | blast_trauma(distance, radius) | Reaches twice the blast radius, deliberately. The shake is not a damage indicator, and stopping it exactly where the damage stops would teach the radius by accident — the one number effects::detonate is careful to draw honestly. Measured from camera, never from the drawn copy, or the shake would depend on itself |
Trauma decays linearly, not exponentially. An exponential is asymptotic: the
camera would never actually stop, only shake by amounts too small to see, and
Shake::active would answer "yes" for the rest of the match. effects.rs fades
its tracers the same way and for the same reason.
The noise is three sines at unrelated periods, sampled on a clock rather than a frame counter, and all three sit below ~23 Hz. That last part is the subtle one: a component faster than half the frame rate does not read as a faster shake, it aliases — a 40 Hz wobble sampled at 60 fps becomes a slow, wrong-looking crawl that gets worse the smoother the machine is running.
Roll is the largest of the three axes because it is the one the eye reads as
impact; yaw and pitch look like the view being nudged off aim, which is the one
sensation a cosmetic effect must not counterfeit. Camera grew a roll field to
express it, and up() rotates the up vector about the forward axis — any
other axis would move where the eye is looking.
The weapon draw and holster
A swap now reads as an action rather than as one model being substituted for
another between two frames. One scalar, stow, runs from 0 (in frame) to 1
(fully out), and the holster is faster than the draw on purpose: putting something
away is a motion you have already committed to, while bringing one up is the
moment that has to land.
The holster fires on the key, not on the server's answer, and that is the
interesting part. This client does not own the slot — select_weapon sends a
request and the server decides. A holster that waited for the confirmation would
start a round trip after the press and read as input lag, so it starts
immediately and is willing to be wrong for HOLSTER_HOLD (0.4s); if the switch
is refused, the weapon comes back up on its own with nothing anywhere having to
notice. When the swap does arrive, set_weapon clears the hold outright, so a
confirmed switch never waits out the remainder of the guess.
Two smaller rules, both bugs first:
- The draw triggers on the id, not on
set_weaponbeing called. Equipping a skin goes through the same function, and re-holstering for a change of colour would dive the gun out of frame in the middle of a firefight. - Going invisible arms a draw for the return, so respawning brings the weapon
up rather than having it appear at rest. Holding the same weapon through a
death means
set_weaponnever fires, so nothing else would start one.
The reload dip, on the served time
Frame::reload_progress is a fraction and reload_envelope takes fractions, so
the dip's shape is the same on every weapon and its duration is whatever the
server served. That is the whole change. The old fixed-rate approach did neither
end well — a fast reload was still on its way down when the magazine filled, and a
slow one sat at the bottom for two seconds and then snapped back up.
The progress comes from two served numbers: reloadTime on the weapon and
reloadIn on the snapshot. The range fills both, so Train and a match take one
code path.
It is an Option, and the distinction is load-bearing: Some(0.0) is "the reload
has just started" and None is "there is no length to measure against". Collapsed
into one number, a server too old to serve reloadTime would look like a reload
permanently at its first frame — the weapon would go down and stay there. None
falls back to the old approach instead.
Muzzle flash, sparks and dust
The flash is shaped per weapon class (flash_shape): a shotgun throws a wide short
bloom, a sniper a long narrow lance, and the knife has no muzzle at all. A
swing is resolved as a Shot like everything else, so it reaches the flare code;
lighting one would give away the position of the one weapon whose silence is the
point. An unknown id gets the rifle's, so a weapon the server has grown since this
client was built looks ordinary rather than invisible.
The bloom is a second cone, not a post-process. There is no bright-pass, no blur target and no second pipeline — the view model is drawn with the world pipeline — so a halo wider, shorter and dimmer than the core, drawn first and fading on the flare's own age, is the whole of it.
EffectsPool gained two shapes off the endpoints it already receives:
- Sparks spray back along the incoming ray, because that is the only
direction available: the server sends where a bullet stopped, never the normal
of what stopped it, and a guessed normal would put half the sparks inside the
wall. Their length is
sqrt(t), so they leap out and stall — grown linearly a burst reads as an expanding wire model rather than as debris. OneLiveholds the whole burst of five, which is what makes it affordable. - Dust is the only slow thing in the file, and it is the cue that says a shot
has already happened. It is gated on the shot's
hitflag — sparks read as a strike on anything, masonry dust off a player does not.
hit is per shot, not per pellet, so a shotgun with one pellet in a body and
seven in a wall loses the wall dust. That is the honest reading of what the wire
carries; inventing a per-pellet answer would be the mistake effects.rs's header
is about. The field had been parsed into nothing since shots existed.
MAX_LIVE did not move, and the arithmetic is worth writing down before anyone
raises it: the volume buffer holds 65,536 vertices, the most expensive shape here
is a ball at 8 × 6 × 6 = 288, and 192 of that worst case is 55k. Sparks are five
thin beams and dust is a deliberately coarse sphere, so both are cheaper than a
ball — adding them raises how fast the cap is reached without raising its worst
case at all.
Kill confirmation, and the punch under a shot
A kill you made puts a centre notice up (ELIMINATED <name>, or HEADSHOT <name>)
and plays a chord that is unmistakably not a gunshot.
Two sources feed the notice, deliberately. on_hits sets the generic form from
our own hitmarkers, which exist in a match and on the range — so Train
confirms a downed dummy rather than being the one mode where a kill says nothing,
and it is the mode a player meets first. on_fx then upgrades it with the
victim's name from the authoritative kill event, which only a match has. Online
the two arrive in the same tick and only the named form is ever drawn. The
generic form must overwrite unconditionally: written as "only if empty", a
second kill would keep showing the first victim's name forever.
The notice sits below the crosshair. The obvious place for a kill confirmation
is above the aim, and it was there first — until examples/hud_preview drew it.
The scoreboard is a centred panel spanning roughly 0.28–0.47 of the height, so a
notice at 0.36 printed straight through it every time somebody opened the board.
That collision is intermittent in play, because the board is a held key, which is
exactly the kind of fault that ships. No unit test would have caught it; the
picture did. This is the checklist item "is it visual? Then it will not be caught
by any test — render it and look" paying for itself.
The audio gained a thump: a sub-bass transient distinct from the existing body,
and the distinction is the whole of the punch. The body is a tone lasting as long
as the sound does and giving it weight; the thump is a fast downward sweep, over in
about 45 ms, giving it an impact. A gunshot with weight and no impact sounds like
a door closing. It has an envelope of its own rather than riding the main one —
otherwise a sniper's 0.36s tail would carry the sub the whole way and turn a
gunshot into a note.
It is kept under half the voice's gain, and that is not timidity. The mixer
clips rather than limits, for a reason GameAudio::open records: a limiter
that ducked the whole mix when a grenade went off would make every other cue
quieter exactly when they matter most. Every layer added here is spent out of the
same headroom, so a sub loud enough to be impressive alone is a shot that clips
into a click whenever two people fire at once.
The plan for this work paired the thump with "a short duck on the ambient bed when
one fires". Neither client has an ambient audio bed — ambient in this codebase is
the map's light level — and the nearest substitute, ducking the mix, is the thing
the paragraph above explains the mixer deliberately does not do. The thump shipped;
the duck did not, and would need a bed to exist first.
Progression and feedback, natively
Three things that tell you what you just did: a number off the body you hit, a
notice when a run of kills becomes a run, and a card at the end. None of them
changes the wire. Every figure comes from you.hits, which the server has been
sending per-recipient since weapons existed.
Damage numbers
HitMarker carries victim, damage, head and killed — and deliberately no
point of impact. So the anchor is the victim's body, looked up in the roster
the renderer is drawing this frame, and projected fresh every frame rather than
stamped once into screen space. Stamped once, a number slides off the body the
moment either of you moves, which at these lifetimes is most of them.
Four rules, each of which was a decision rather than an accident:
- Summed per victim, not one number per marker. A shotgun lands eight pellets
in one snapshot; eight numbers stacked on a body is unreadable and, worse, reads
as eight hits when it was one trigger pull. The same reasoning that gives
confirm_killone sound per tick. - A victim who is not in the roster falls back to the crosshair. This is not a rare edge: you kill somebody through smoke and the kill removes them, and a shot at maximum range can outlive its target in the snapshot buffer. Dropping the number there would make exactly the most satisfying hits the silent ones.
- They project through the camera the world is drawn with — the shaken copy,
not the one the game runs on. Projected through the true camera a number sits
still while the body underneath it shakes, which reads as the number belonging
to the HUD. This is why
Workstream C's shaken camera is now built before the HUD rather than at therendercall. - They are drawn under the scoreboard. A damage number belongs to the world, so it sits beneath the panels you deliberately hold over it.
The projection lives in damage.rs, not in hud.rs. The painter holds no
matrices and should not start; Camera is pure maths with no device in it, so
both halves stay testable headless. That matters here because the two ways a
projection goes wrong — a point behind the eye, and a flipped vertical axis —
both produce a picture rather than an error:
w, not a small oneDivide by it and the point mirrors through the centre of the screen, so a hit on
somebody behind you draws a number in front of you. Clip space is also Y-up
while the painter is Y-down; miss that flip and every number appears mirrored
about the horizon. Both are pinned by tests, including one that asserts cube +y
lands screen-right — which it does, because apply_look increases yaw when
the mouse goes right and yaw 90° faces cube +y.
Killstreak notices
Counted from our own hitmarkers, not from Fx::Kill. That is the only source
that exists in both modes: the range has no server and so no kill effects at all,
and a Train mode where a streak never appears is a feature you would first notice
missing in the mode you meet first.
Counted rather than any()-ed, too — one tick can carry two kills (a shotgun
through two bodies), and collapsing them makes a streak silently undercount.
Only the listed milestones announce anything (STREAKS, ascending, read from
the back so a high streak reports the highest threshold it passed rather than
the first). A notice on every kill past three would make the streak the loudest
thing on screen exactly when the kill itself is what you want to see. The notice
is cleared unless this kill earned one, or a TRIPLE 3 rides along under kills
four through ten.
The streak ends at the death, not at the respawn — on_self sees alive go
false, and several seconds pass before on_respawn. A streak still counting
through them is the one number on the HUD that is simply wrong.
It shares the kill notice's clock rather than having one of its own: a streak is only ever announced at the instant of a kill, so a second timer could only ever disagree with the first.
The post-match summary
Action::Quit in a match now shows a card before it leaves; Escape goes back,
Enter (or the button) leaves. Train quits as it always did — there is no match to
summarise and no opponents to be measured against.
Leaving is the moment, and not for want of a better one. There is no round end
to hang this on: deathmatch is the only mode and it runs until you go. That makes
leaving the end of the match for this player, and it is already the instant the
server settles up — MatchServer.leave reads result_for before remove drops
the counters. So the native card and the dashboard card describe the same moment
by construction rather than by agreement.
MatchRoom._apply_damage accumulates damage_dealt from landed, which is
capped at the victim's remaining health. The HitMarker it puts on the wire
in the same breath carries round(amount) — post-armour, but not capped. A
90-damage sniper hit on a player with 30 health left contributes 30 to the
server's figure and 90 to anything the client adds up.
Over a match that is a systematic overstatement, and two cards for the same match
showing two different numbers under one word is worse than one card with one
fewer number on it. What the client can count exactly is hits landed and
headshot kills — one hitmarker per pellet that connected, and killed set
exactly once per kill because _shoot skips a victim who is already dead. Those
are what the card shows, under their own names, so it never competes with a figure
it cannot reproduce.
won and mvp use result_for's own definitions — nobody outscored you, and
nobody equalled you, bots included — because a second definition of winning is
how two cards for one match come to disagree. K/D with no deaths is shown as the
kill count with no denominator: a player who never died has an undefined
ratio, not a ratio equal to their kills, and max(deaths, 1) prints a number that
is wrong where absent would have been right.
The card scales with the window (summary::scale), as the HUD does from
u = height / 360. The pause menu does not — it is a fixed 460px — and that is a
real inconsistency left alone deliberately: the menu is a settings list read for a
while rather than a card glanced at once, and changing it would move every row
rect the input path hit-tests against. button_rect is the single definition of
the button's geometry, used by the painter and the hit test, because two copies
of it is a button drawn in one place and clicked in another, failing only at sizes
nobody develops at.
Verified by rendering it
examples/hud_preview takes a third argument, summary, and draws the card over
a live HUD — which is the only arrangement in which the scrim's job is visible.
Both halves of this work were checked at 720p, 1080p and 4K, and the preview
earned its keep twice: the first pass put all three damage numbers inside the
scoreboard's footprint, where they are correctly but uselessly drawn underneath
it, and the footer hint sat visibly low against the leave button. Neither is
something a unit test has an opinion about.
After the match
A finished match produces a row, and the debrief card reads it.
That is worth stating plainly because it was not true. _watchdog_game_process
waited for the native client to exit and then invented the entire card —
random.randint for kills, deaths, headshots and damage, a level, an XP figure,
a rating delta against a hardcoded 1520, and a tier name to match — and filed
it in a module-level dict that a backend restart emptied. The numbers had no
relationship to the match that had just been played.
The simulation already knew all of it. MatchPlayer now also counts
damage_dealt and head_kills alongside the kills and deaths it always had, and
MatchRoom.result_for reports them.
Three rules in that path:
- The result is read before the player is removed.
removedrops theMatchPlayerand every counter with it, so reading afterwards files a match of zeroes.MatchServer.leavereturns the result;channel._leave_anyrecords it. - Damage is what landed, not what was rolled. A 90-damage sniper round into a body with 20 left counts 20. Overkill would make the stat a description of the weapon rather than of the match, and it is the one number a player can check against the health bars they watched go down.
head_killscounts kills, not hits, because the card divides it bykillsto show a percentage. Counting hits there prints numbers over 100%.
won and mvp are relative to the room rather than to a team score, since the
only mode is deathmatch: you won if nobody outscored you, and you are MVP if
nobody equalled you either. Bots count — losing to one is losing, and a card
that quietly excluded them would be flattering rather than true.
Where it is written
hassault_matches in app.db — the same database the library catalog, browser
history and karaoke queue use, so a match history survives a restart and the
database pane can query it like anything else:
SELECT map_name, kills, deaths, head_kills, damage_dealt, xp FROM hassault_matches
ORDER BY played_at DESC;
GET /api/hassault/match/latest_summary reads the most recent undismissed row;
/match/history reads the rest; /match/dismiss_summary sets dismissed_at
rather than deleting, because the row is the history and closing a card is not a
claim that the match did not happen.
Progression is derived, never stored twice. Level and career XP are a
SUM(xp) over the table rather than a counter someone remembers to bump: a
running total in its own column is a number that can disagree with the matches it
claims to summarise, and there is no way to tell which one is wrong.
Skin drops are persisted too, in hassault_skins. They were an in-memory dict on
the skin manager with an optional Atlas sync that nothing awaited — so every skin
anybody earned, including the drop the card had just congratulated them on, was
gone the next time the backend restarted.
The drop reaches the row a step later than the row does. record runs when
the player leaves the match, from the simulation's own counters; the drop is the
reward for finishing, so _watchdog_game_process rolls it once the client
process has exited and its result has landed. results.attach_drop(match_id, instance_id) hangs it on the row — and only the id: the card wants the
skin's name, rarity colour and wear, and copying those onto the match row would
mean a renamed skin showing its old name on every card that ever mentioned it.
GET /match/latest_summary resolves the id against the inventory instead.
attach_drop did not exist. The watchdog called it anyway, so every finished
match raised AttributeError inside a try that logged "could not roll a drop
for the finished match" — which was the one thing that had worked. The skin was
rolled, saved into the armoury, and attached to nothing; the card showed no drop,
and an item appeared in the inventory having come from nowhere.
An UPDATE that matches no row now logs a warning naming the instance, because
that is the same failure in its next disguise.
Rating and tier. The old card printed 1520 + random.randint(18, 32) under
the heading "Competitive Rank", which looked exactly like a ladder standing and
was not one. Rating returns with rated matches — see below — where a referee
rather than a player's machine decides what happened.
Who adjudicated it
Storage is not the trust boundary; simulation is. A local SQLite file can be edited by whoever owns it — but so can the backend that fills it, which is Python source on the same disk. Pushing rows to a central database would not fix either: it would file a self-reported number somewhere more official-looking, and a central leaderboard reads as authoritative in a way a personal history does not.
So every match records who adjudicated it, and the column exists before it is needed:
authority | Where the room ran | What it may be used for |
|---|---|---|
local | This node — Host, Train's neighbours, or a friend's node over the fabric | A personal record. Nothing comparative, ever. |
server | The game server's referee | Rated. The only kind a ladder may count. |
The migration matters: CREATE TABLE IF NOT EXISTS never adds a column to a table
that already exists, so init_results_db also runs an ALTER TABLE for installs
that recorded a match before the column existed. Those rows backfill to local,
which is the honest answer — they were adjudicated by the node that wrote them.
That check is _ensure_column, and it covers drop_id as well: one column had
grown its own inline migration, which is how the second one goes missing.
Rated matches: the game server as referee
backend/games_server/hassault_rooms.py runs the same MatchServer a node runs,
on a machine nobody playing controls, and writes the result itself — exactly the
shape every other game on that server already has (hub.py calls
store.record_result on game_over; no client ever posts a result).
It owns no physics. It holds a MatchServer and feeds it connections, which is
the same trick fabric.py uses to make a remote peer look like a browser: a
MatchRoom never learns what is on the other end of send_json. A second
implementation of the simulation on the server is the one thing guaranteed to make
the server and the clients disagree.
Three properties are load-bearing:
- Bundled maps only. A map that exists on one player's disk cannot be
adjudicated by anybody else. Since AssaultCube installs stopped being read,
every node's catalog is the bundled set, but a draft (
draft:<id>) still resolves throughassets.load_mapand is still refused here. The refusal is explicit (referee.playable) so the reason is legible instead of arriving as aLookupError. - One validator. Input goes through
match.parse_command— the same function the browser channel and the peer fabric use. It moved out ofchannel.pywhen this landed: it had three callers and a second, laxer copy on whichever path happens to be rated is exactly where a gap appears, in the one place nobody looks. - Identity is the token, never the wire. The account comes from
auth.resolve_tokenon the query string; anamein the join payload is ignored the same waychannel.pyignores it. TheSeatConnholds the mapping, which is what stops a player naming themselves into somebody else's row.
The wire is the node's own hassault envelope ({channel, event, data}), so a
client speaks one protocol whether the room is on its own node or on the server.
GET /hassault/maps → maps a rated match can use
WS /hassault-ws?token= → join / input / leave, same events as the node channel
store.record_result applies ELO to two seats facing each other, and a
free-for-all people come and go from is not that shape. A finished session is
logged and its XP granted — both by the server, both real — with rated=False,
rather than inventing a rating, which is the very thing this module exists to
stop. ELO belongs to a 1v1 duel mode, where the shape fits.
Getting in: the node proxies
Clients reach the referee through their own node, not directly:
client --/ws--> node (ranked.py) --wss--> game server (MatchRoom, referee)
Two reasons, and both would be wrong the other way round:
- The token stays on the node. The game-server JWT lives in
server_auth, the same one sign-in and/game-wsuse. A client opening its own socket would need a copy of it, spreading the node's credential to every surface that wants to play. - One protocol. The join carries
ranked: trueand nothing else changes — snapshots, inputs and the welcome are the wire the client already reads. A second client-side transport is a second place for the two to drift.
It is the same shape fabric.py uses for a friend's match, and the channel now
has three destinations for one join: local, a friend's node (host), and the
game server (ranked). Ranked is checked first: a join cannot be both, and
"ranked on a friend's node" is not a thing — a friend's node has no more authority
over a result than yours does.
Three things the relay does not do:
- It does not validate input. Commands are forwarded untouched, because the server validates and the server is the one being lied to. A second check on the way out would be a copy of the rules with no authority behind it — the same reasoning the fabric gives for forwarding a guest's input verbatim.
- It does not record anything itself. The result arrives from the server as
a
resultevent, andranked._recordfiles it withauthority="server"because it was told, never because the node knew it was in a ranked room. Leaving a ranked seat files no local row: a secondlocalcopy of the same match would be a self-reported row sitting beside the real one. - It does not offer bots.
add_botis refused for a ranked seat. A match whose roster a player can reshape is not one their result should count for.
leave waits briefly (RESULT_WAIT) for that parting result before closing —
cancelling the pump immediately is how a player's last match silently never gets
a card.
Where the button is
| Surface | How |
|---|---|
| Pane | Ranked, directly under Quick play. Greyed out unless the chosen map is one the server lists. |
| Native client | --mode=ranked, which the launch route passes through; the flag rides on the join. |
The map guard asks GET /api/hassault/ranked/maps, which proxies the server's own
list rather than filtering locally for source == "bundled". The two agree today
and the server's answer is the one that decides, so a map added on either side
needs no matching change on the other — and a server that is down greys the button
out instead of failing at the socket after a map has loaded.
Train produces no card at all, which is correct: there is no match, nobody to play against, and nothing to be MVP of.
The workspace: three windows and their strips
The game has three windows, one per job: HorribleAssault (hassault.play)
to play, hAssault Dev Tools (hassault.studio) to build for it, and
hAssault Server (hassault.server) to run rooms on this node. It used to have
ten — the studio three more times on a different tab, an armory pane duplicating
the main menu's armory section, and four narrow companions each claiming a dock of
their own — and a launcher offering ten ways into one game told nobody which one
they wanted. The companions (match stats, radar, voice, console) are now region
strips on the window they accompany (embedded: true), so they open at its edge
rather than somewhere else in the frame. Old ids still resolve: RENAMED_VIEWS
migrates saved layouts and VIEW_ALIASES keeps the agent's vocabulary.
Everything around the game still talks across panes and strips —
workspace-bus.ts is the channel between them, and it exists because the obvious
implementation does not survive contact with the frame engine.
The target pane is usually not open yet. Clicking "inspect in the studio" from the armory has to open the studio, and the studio mounts a tick later — so an event broadcast at click time is delivered to nobody. Worse, only an area's active tab renders, so a pane that is open may still be unmounted while you look at another tab. A plain listener registry loses the request in both cases, silently.
So three of the five channels park their request and the consumer drains it on mount:
| Channel | Parks? | Producer → consumer |
|---|---|---|
requestMapLoad | ✅ takePendingMapLoad | studio / console / armory / menu / companion → the play pane |
requestMapEditorInspect | ✅ takePendingMapEditorInspect | play / console / menu / companion → the studio |
requestWeaponInspect | ✅ takePendingWeaponInspect | armory / play / studio / console → the studio |
broadcastWeaponEquipped | ❌ | armory / studio / console → whoever is listening |
dispatchConsoleCommand | ❌ | console / panel / UI → the play pane |
HorribleAssaultPanel shows the pattern exactly: its effect calls
takePendingMapLoad() first, applies whatever was parked, and only then
subscribes with onMapLoadRequested. Drain-then-subscribe, not the reverse — the
reverse leaves the parked intent sitting there until something unrelated fires.
The two that do not park are the ones where a missed event is genuinely nothing: an equip is a cosmetic broadcast, and a console command aimed at a match that is not running has nowhere to land anyway.
Telemetry is a latest, not a queue. broadcastMatchTelemetry overwrites, and
getLatestMatchTelemetry() reads the current value — because a radar or companion
pane opened mid-match wants the state of the match now, and replaying the
history of a firefight to a panel that just appeared would be worse than useless.
MatchTelemetry carries the phase, map, roster, spotted list, round time, score,
kill events and the local player's vitals in one object, so a consumer re-renders
from a single snapshot rather than assembling one out of five subscriptions.
Every request carries a source. 'studio' | 'console' | 'armory' | 'menu' | 'companion' and friends are not decoration: a pane that both produces and
consumes a channel — the studio does, for weapon inspect — needs to ignore its own
echo, the same problem the code locus solves the same way.
The bus is module-global, not React state or context. A pane's state does not
survive its unmount, and the whole point here is to outlive one.
resetWorkspaceBusForTesting() clears every parked intent and listener, which is
what lets workspace-bus.test.ts run each channel in isolation.
Contributions to the layout shell
-
Panels:
Id Role Singleton What hassault.playdocument ✅ The game. fullscreen: true. Strips: companion, radar, voice (right), console (bottom).hassault.studiodocument ✅ Dev tools: asset viewer, map/scene, materials, animator, rig editor as its own tabs; params.tabselects one. Strips: console, radar.hassault.serverdocument ✅ Host rooms, field bots, invite friends, watch the roster — without playing. hassault.consoletool, embedded — The developer console. hassault.companiontool, embedded — Telemetry, vitals, team scoreboard. hassault.radartool, embedded — 2D tactical minimap and callouts. hassault.voicetool, embedded — Voice comms. hassault.playis the onlyfullscreen: true. It is adocumentbecause it wants a lot of pixels, and it grabs pointer lock. Thefullscreenopt-in earns it the⛶titlebar control and Escape-able presentation over the taskbar and the titlebar — and on the desktop build that escalates to OS-window fullscreen, which is what makes pointer lock and the full field of view behave the way the game assumes. See desktop-shell.mdx.All three windows are singletons: the studio's tabs are one window's state, so opening "the rig editor" switches the open studio's tab rather than making a second studio.
openPanelon an embedded strip id (hassault.radar) reveals it in its host rather than opening it bare — the same resolutionshowmakes.The Server window is the dedicated-server view of the rooms the main menu can also host. It holds no socket: every verb is a REST call the agent tools already make —
POST /matches(host),GET /matches/{room}(roster),POST/DELETE /matches/{room}/bots,POST /matches/{room}/invite— so the window and the agent cannot describe one room two ways. "Join in game" openshassault.playand parks the join withrequestJoin, the invite toast's path. -
Commands:
hassault.open,hassault.openServer,hassault.openStudio; the retired openers (openModelViewer/openModelEditor/openAnimEditor,openConsole/openCompanion/openRadar/openVoice) now land on the studio tab or strip that replaced each pane. -
Console commands (namespace
edit, served to both clients):edit.new,.open,.close,.status,.save,.list,.select,.brush.add,.brush.set,.brush.remove,.ent.add,.ent.set,.ent.remove,.undo,.redo,.lint,.textures,.playtest. -
Settings:
hassault.sensitivity— mouse look multiplier, also editable live from the pause menu. The control map (hassault.controls) rides the same setting storage but is not a declaredSettingDeclrow — see Controls. Everyhassault.*key is in one schema,settings_schema.py, served atGET /api/hassault/settings/schemaby the node and the game server: type, range or snapped choices, enum, default, and scope —account(aim, FOV, crosshair, binds, the practice overlays) ormachine(GPU, API, monitor, display mode, render and quality rows, the binary path). Account sync (P4) will carry onlyaccountrows.settings-vectors.json(scripts/gen_hassault_settings_vectors.py) pins it twice:settings-schema.test.tschecks the manifest has a row per value with the same type and default, andconformance.rsfeeds every native key toSettings::from_valuesbelow, above and inside its range. The preset rows' defaults are what Medium writes (anisotropy 8, shadow quality medium), which is what the native client always used; the manifest used to say 16 and high. Ranked play needs no setting: the entry point is a button, and the server it talks to is the onegames.serverUrlalready names for sign-in.hassault.video.fullscreen/.renderScale/.fov/.quality/.antialias/.shadows/.vsync/.fpsLimitandhassault.crosshair.style/.size/.gap/.thickness/.outline/.outlineThickness/.alpha/.dot/.tStyle/.dynamic/.color(a name or#rrggbb) — what the native client's pause menu edits; see the rest of the video page for what each of the video rows actually costs. Declared rows rather than a file beside the binary, so the pane's Settings page and the in-game menu write the same values.hassault.nativeBinaryPath— where the native binary is, when it is not in the usual build output. A declared row: the path was read by the launch route and named in its own error message long before it was editable anywhere.hassault.autoBuildNative(on) — compile the client before launching it when it is older than its own source; see the launch path for why launching it anyway is a silent failure. -
Agent tools (group
hassault):list_maps,list_matches,host,invite,status,surroundings,add_bot,remove_bot,console_exec,run_macro.
The map designer adds no pane of its own on the backend
side: it is a set of routes plus an edit mode in the native client, and the
console commands it declares are rendered by the existing hassault.console pane
because that pane draws a served registry rather than a list of its own.
Escape opens the in-game pause menu (GameMenu.tsx) rather than any shell
surface — it releases pointer lock and keyboard capture the same way leaving a
match does, so the mouse and every ordinary control in the menu just work.
Rebinding there records the same hassault.controls document controls.ts
reads; nothing about it touches packages/core/src/keymap.
Agent tools
Most of these run the social side of a game — "start a match on ac_desert and
invite Rob", "who's in the match?", "what's around me?" — which is the tedious part
for a human mid-session and the easy part for an agent. The last two,
console_exec and run_macro, are the developer console
reached from a tool call instead of the console pane, which is a different job:
changing the state of a running match rather than describing it.
| Tool | Does |
|---|---|
hassault.list_maps | The maps this node can host |
hassault.list_matches | Matches running here, plus invitations received |
hassault.host | Open a match, optionally inviting someone in the same call |
hassault.invite | Invite a friend; the room may be omitted when only one runs |
hassault.status | Who is in a match: teams, health, kills, latency, remote or not |
hassault.surroundings | Walls in each compass direction, and who is nearby |
hassault.add_bot | Field bots: a count, a skill, an optional team |
hassault.remove_bot | Take them back out, by name, by count, or all of them |
hassault.console_exec | Run a developer-console command, CVar or Python script |
hassault.run_macro | Run a named console macro (warmup, bot_1v5) |
surroundings casts its rays through the same World the simulation uses, so it
reports what the server believes rather than a guess from a map file, and it
answers in compass words and cubes because the agent is talking to a human. It
also reports line of sight per person, traced with the same ray a shot would
follow — "behind the wall" is the useful half of spotting.
They deliberately stop short of playing. Driving a player means producing input at 60 Hz and an agent turn takes seconds; a tool that "moves you forward" would be a bot controller wearing a tool's clothes. The agent can field bots — "put three hard ones on the other team" — but the thing producing their input is a tick-rate brain on the server, not a tool call. What is here is everything needed to set up and talk about a match, including acting as a spotter for whoever is actually playing.
The console tools are the edge of that line rather than an exception to it.
console_exec can hand a player a weapon or slow time to 0.5x, but it acts once
per call on the match's state — it is not a channel for per-frame input, and no
sequence of these calls adds up to steering a player. Like every other tool here
that changes something (host, invite, add_bot, remove_bot) they are
side_effect=True and pass the permission gate; only the four that just describe
a match — list_maps, list_matches, status, surroundings — are ungated.
Controls: click to lock the pointer, WASD to move, mouse to look, Space to jump, left mouse to fire, 1–5 or the wheel to change weapon, R to reload, Tab for the scoreboard, V for noclip (offline only), Esc to release. Keys are swallowed only while the pointer is locked, so the command palette and every other shortcut keep working when it is not; releasing the pointer also releases the trigger, or a weapon left firing keeps firing into whatever you tabbed away to.
Escape is nominally the game's own key (escape: 'passthrough'), with a hold
releasing the mouse — but that only works where the browser lets the page keep
Escape (Chromium, in document fullscreen). Elsewhere a single press releases and
the on-screen badge says so, rather than promising a gesture that silently does
nothing. See the Escape ladder.
The standalone web client (apps/assault-web) has no pane, so no capture and no
ladder: its App is the one owner of the Escape lock, taking it on every
fullscreenchange into fullscreen and dropping it on the way out, and the panel
leaves the lock alone when standalone. A tap of Escape therefore opens the pause
menu and fullscreen stays; holding it leaves fullscreen by the browser's own rule,
and Resume (a click, so a valid gesture) puts fullscreen back. Two owners is how it
used to break — the panel's cleanup unlocked on re-render and nothing re-locked
until the next fullscreenchange, so Escape quietly went back to the browser.
The toolbar carries the match controls: your username (shown, not typed — the backend refuses any name the client supplies), Join/Leave, bot add/remove with a skill selector, and — once in — the team scores, the head count and your round-trip time. Changing map while in a match leaves it rather than silently simulating you in a different world.
The HUD is health bottom-left, weapon and magazine bottom-right, kill feed top-right, and a crosshair whose gap is the weapon's actual spread cone, so a shotgun looks like a shotgun without anyone reading the numbers. Hitmarkers rotate it into an X rather than fading a second element in and out.
Backend surface
backend/modules/hassault/, mounted at /api/hassault.
| Route | Purpose |
|---|---|
GET /api/hassault/session | Who this node plays as: {signed_in, username, enlisted}. ?refresh=true re-reads it from the game server, which is how a username claimed on another machine appears |
GET /api/hassault/status | What is playable (CatalogStatus): map_count, bundled_count and a message. Zero maps only if the bundled maps failed to build |
GET /api/hassault/maps | Every playable map. source is always bundled, kept on the wire because the native client and older panes read it |
GET /api/hassault/maps/{name} | Header, entities, spawn counts (JSON) |
GET /api/hassault/maps/{name}/cubes | The cube grid as raw byte planes. {name} may be draft:<id>, which is how an unsaved map reaches every client through the path it already uses |
GET /api/hassault/maps/{name}/download | A bundled map, or a draft, as a real .cgz, openable in AssaultCube's editor. For a modelled map that is its baked collision grid |
POST /api/hassault/maps/drafts | Open a map for editing, blank or seeded from a bundled one. See The map designer |
GET/PATCH/DELETE /api/hassault/maps/drafts/{id} | The document; one typed edit; close it |
POST /api/hassault/maps/drafts/{id}/undo | /redo | Walk the edit history |
GET /api/hassault/maps/drafts/{id}/lint | Playability findings, each carrying the cells it is about |
GET /api/hassault/maps/drafts/{id}/owners | Per cell, the brush that painted it, as uint16 |
POST /api/hassault/maps/drafts/{id}/save | Write maps/hd_<name>.json atomically |
GET /api/hassault/maps/schema | Brush ops, entity types and document fields — declared before /maps/{name}, which would otherwise match it |
GET /api/hassault/textures | The texture palette, ours and procedural |
GET /api/hassault/weapons | The loadout, in slot order — served so the client cannot drift from it |
GET /api/hassault/hitbox | The body a shot is resolved against — served for the same reason, and the one both clients draw to. See The hitbox is served, and it is not finished |
PUT /api/hassault/hitbox | Tune the live body, or {"reset": true}. Not persisted |
GET /api/hassault/tacticals | The four grenades, in slot order — the table the simulation runs on. Deliberately still a bare list: reshaping it would make every installed native binary see no grenades at all |
GET /api/hassault/throw | The constants a throw is integrated with, for the trajectory preview. A route of its own for exactly the reason above — see The predicted arc |
GET /api/hassault/lore | The setting: factions, palette, insignia, rank names, map briefs |
GET /api/hassault/matches | Live matches on this node — enough to render a lobby row |
POST /api/hassault/matches | Open a match without joining, so its id can be handed to a friend |
GET /api/hassault/invitees | Friends who could join right now, from the social roster |
GET /api/hassault/invites | Invitations received from friends, unexpired |
GET /api/hassault/browse | The server browser: matches here and on friends' nodes, plus reachable players — see The server browser |
Joining is a /ws operation, not REST, because it binds a player to a socket. A
match created over REST stays empty and is retired after a grace period if nobody
arrives — without that grace an invite room would be swept away before the
invitee could click it.
The hassault /ws channel
| Direction | Event | Purpose |
|---|---|---|
| → | join | { map, room?, host? }; host makes it a friend's match. Refused with {code: "not_signed_in"} unless this node holds an account with a username — and any name in the payload is ignored, because identity comes from the account |
| → | input | { commands: [...], rtt } — batched, sequence-numbered |
| → | respawn | The server owns spawn points, so respawning is asked for |
| → | invite | { who, room } — who is a person, not a node id |
| → | add_bot | { count, skill } — host only |
| → | remove_bot | { count } or { id } — host only |
| → | leave, ping, list, invites | |
| ← | welcome | Your player id, the room, everyone in it, the scores, and host if remote |
| ← | snapshot | All players plus your ack, you and the tick's fx, at 20 Hz |
| ← | invite | A friend has invited you to a match |
| ← | roster | Bots joined or left; membership itself follows in the next snapshot |
| ← | joined, left, pong, error, matches, invites, invite_sent |
One command, with the combat fields it may carry:
{ "seq": 412, "forward": 1, "strafe": 0, "jump": false, "crouch": true,
"yaw": 1.57, "pitch": -0.02, "dt": 0.0166,
"fire": true, "reload": false, "weapon": -1, "scoped": 2,
"viewT": 1743102934812 }
weapon is -1 for "no change", so an absent or nonsensical slot leaves the
weapon alone rather than silently arming the knife. The combat fields are omitted
entirely on the frames that are not shots, which is most of them.
Note what is not here: the recoil impulse. A shot's push on the shooter is
derived server-side from its own weapon table, and the client's copy is a prediction
computed from the served kickback — a client-supplied impulse would be a
client-supplied velocity. Predictor keeps each frame's kick in a map beside the
pending list, not on the Command, so the replay can repeat it without it ever
reaching the wire.
The snapshot's you envelope gained two blocks:
{ "hp": 74, "ammo": 12, "…": "…",
"move": { "vel": [11.2, -3.4, 0], "air": 0, "crouch": 1,
"crouchedInAir": false, "sinceLanded": 0.83 },
"noise": [{ "kind": "step", "volume": 0.42, "bearing": 1.87, "up": 0 }],
"fell": 0 }
move is what prediction rebases on; noise is what this player can hear, already
filtered for audibility. Both are per-recipient rather than in the shared rows, and
for noise that is a security property — see Noise is
information.
And on the peer wire, declared in fabric.py rather than network/protocol.py —
a module owns its own wire vocabulary, following the training-ads precedent, so
adding a feature never edits the fabric core:
hassault_invite, hassault_join, hassault_input, hassault_leave,
hassault_frame, hassault_browse (a PeerHub.request/reply pair — see
The server browser).
Every field of an inbound command is clamped rather than trusted: the movement
axes to ±1 (asking for 50 is the obvious cheat), dt to 0.25 s, pitch to a right
angle, the weapon slot to the loadout. jump and crouch are booleans and need no
clamp, but note that neither is a request the server grants blindly — step
decides whether a jump is possible (on_ground) and whether a crouch can be released
(headroom), so holding both keys forever is not a state a client can assert. NaN and infinity survive JSON and poison
every comparison downstream, so they are rejected at the edge instead of at the
first surprising position. viewT is the exception and is not range-checked
here: it is clamped against the clock in PositionHistory.clamp, which is the
only place that knows what time it is. There is deliberately no noclip on the
wire — it is a local sightseeing tool, and the pane disables it while you are in
a match.
Why the grid is binary
A 256×256 map is 65 536 cubes across nine fields — roughly 590 000 numbers. As
JSON that is several megabytes to serialize and parse. The /cubes endpoint
returns the nine planes concatenated raw, so the browser adopts them directly
as typed arrays with one copy and no parsing:
const info = await fetch(`/api/hassault/maps/${name}`).then((r) => r.json());
const buf = await fetch(`/api/hassault/maps/${name}/cubes`).then((r) => r.arrayBuffer());
const n = info.cubic_size;
const plane = (i) => info.plane_order[i];
const types = new Uint8Array(buf, 0 * n, n);
const floor = new Int8Array(buf, 1 * n, n); // floor and ceil are SIGNED
const ceil = new Int8Array(buf, 2 * n, n);
// index a cell at (x, y) as y * info.ssize + x
plane_order is reported by the metadata route rather than hardcoded on both
sides, so the two cannot drift. floor and ceil are signed; the rest are not.
Path safety
A map name arrives in a URL and indexes into a directory, so it is validated
rather than trusted. mapsource.is_bundled_name accepts only an hd_ prefix and
bare alphanumeric names (plus - and _); anything containing a separator or a
dot is refused outright rather than normalised, because a "cleaned" traversal
attempt is still an attempt. test_load_map_refuses_anything_that_is_not_a_bare_name
pins it. (This section used to cover an AssaultCube install path too; that
support is gone.)
In-Browser vs. Native Desktop Client
hAssault supports two client execution targets that speak the exact same backend protocol:
-
In-Browser Client (
packages/core/src/modules/hassault/*):- Built with TypeScript, React 19, and Three.js (WebGL).
- Served as a web page by
apps/assault-web(see the standalone web client). The dashboard'shassault.playpane renders the same component as a launcher — the menu over the live map — and plays nothing in it; see Playing in the native client. - Features the full HTML/React Developer Console (
~), NetGraph HUD, and articulated character rigs.
-
Native Desktop FPS Client (
apps/native-fps/*):- Built in Rust using
wgpu(DirectX 12 / Vulkan / Metal),winit, andcpal. - Runs as a standalone external OS window for maximum performance and ultra-low input latency.
- Shares the same authoritative
/wswire, collision hitboxes, and physics models. - Renders the same skinned operator GLB the browser client does, GPU-skinned, with the 23 Mixamo clips and procedural weapon props. See The operator in the native client.
- Includes in-game CS:GO-style NetGraph HUD (FPS, frame and GPU time, tick rate, bandwidth, loss, jitter) toggled with
F3, and a--bench=<map>frame-time benchmark. See Measuring performance.
- Built in Rust using
The standalone web client
apps/assault-web runs the in-browser client without a node: a guest with a
callsign plays on the central game server's /hassault-ws, and every REST call
goes to that server too (VITE_BACKEND_URL). What the server has to serve for
that, and the limits that make it safe to leave public, are in
deploying the game server.
On the client, HorribleAssaultPanel takes a standalone prop, and it is one
switch rather than a guest check scattered through the pane:
- Skipped: the node account (
/session— identity is the guest callsign), the armoury (/skins/inventory), the friends roster (/invitees), ranked maps, the native launcher's status, and the process/debrief poll — which otherwise 404s twice every 1.5 s for as long as the tab is open. - Joins on load. The page's own buttons already chose to play; the node's main
menu (ranked, the designer, friends) offers nothing a guest can use. No room id
means "any room on this map with space", the server's
find_or_create.
The armory on the web client
The landing page has an Armory section (nav: play · servers · armory · maps)
that renders the dashboard's own ArmoryMarketplace — inventory and per-side
equips, the catalog, trade-ups, the case store and wallet, trades and the market —
exported from @horrible/core along with the switch below. It is account-only:
ArmorySection (apps/assault-web/src/components/ArmorySection.tsx) shows a
guest, or a token that never resolved to an account, a sign-in prompt instead,
since every one of those routes answers a request without a bearer token 401.
The calls themselves needed a second route. In the dashboard and the native client
they go to the node, which holds the game-server token and proxies them, on its own
paths (/hassault/skins/inventory, /hassault/wallet, /hassault/trades), to the
server's /api/hassault/account/* (account_sync.request). The web client has no
node, so main.tsx calls routeAccountToGameServer(getToken) at boot and every
account call in hassault/api.ts then goes to the game server directly, on the
server's paths, with Authorization: Bearer <token>. The token is read per call,
so signing in or out needs no re-binding. Two shapes differ between the routes and
are translated there: trade-up posts {instanceIds} rather than a bare list, and
the market's reads are on the public /api/hassault/market.
The game server serves /api/hassault/skins/catalog as one of its pure catalogs
(hassault_content.py). Against a server deployed before that, the client builds
the catalog from the cases' contents — every skin that can be earned there is in
one. ArmoryMarketplace takes studio={false} here: its "inspect in 3D" buttons
open a dashboard pane, and a page with no pane shell would show buttons that do
nothing. The panel's dashboard tokens (--warn, --border-dim, --bg-tertiary)
are mapped onto the game palette by .armory-host in landing.css.
Desktop and web players meet in online rooms. A node's casual and hosted
matches live in its own process, which a browser cannot reach, so the meeting
point is the game server. The desktop server browser lists the server's rooms
alongside local and friends' matches (ranked.online_rooms, tagged with
host == "@server", shown with a web badge), and Open under Online room
opens a new one there on the loaded bundled map (new: true on the join). Both go
through the same proxy as ranked, so the node's token never reaches the client. A
room is unrated once a guest is in it — the server's call, not the node's.
Two fixes the web client surfaced apply to every client. The map list no longer
overrides a chosen map: it used to set hd_assault unconditionally when it
arrived, racing a join, so a pane could render one map while the server simulated
another. And the console's REST calls go through apiUrl, so they reach the
backend from the desktop build and the web client instead of the page's own origin.
The web build ships only the game's files from apps/web/public (hassault-*.glb,
hd_*.glb, the icon) — the dashboard's avatar and animation files stay behind —
and fails if it finds no models, since a build without them renders procedural
fallbacks and no weapons without any error.
Replays are bounded
A ReplayRecorder keeps at most the last ten minutes of ticks (MAX_FRAMES,
a deque): it used to hold every tick of the room's life in memory, ~1 GB an hour
for a full room. Recordings live under $HORRIBLE_DATA_DIR/hassault/ via
backend/paths.py (they were pinned to <repo>/.data), and a MatchServer can
be built with record_replays=False — the game server's is, since nobody could
watch a replay kept there.
The Developer Console and Macro System
backend/modules/hassault/console.py + packages/core/src/modules/hassault/console/*.
A Counter-Strike and Source-engine inspired Developer Console providing direct, low-level control over rendering variables, authoritative networking simulations, server physics, bot populations, player cheats, and Python macro scripting.
The console is accessible at any time during gameplay by pressing Backquote
(` or ~), clicking the in-game HUD console indicator, or opening the
standalone dashboard panel (HorribleAssault: Open Developer Console / hassault.console).
+---------------------------------------------------------------------------------------+
| ~ DEV CONSOLE [ROOM: rm_8f3 (hd_atrium)] [PING: 24ms] [CHEATS: ON] |
+---------------------------------------------------------------------------------------+
| [🎯 Hitboxes: ON] [🕸️ Wireframe: OFF] [📊 NetGraph: L2] [Freeze Bots: OFF] |
+-----------------------------------------------------------------------+---------------+
| [04:30:12] net.graph = 2 | Python Macros |
| [04:30:15] draw.hitboxes = true | ------------- |
| [04:30:18] server.bots.freeze = true | ▶ warmup |
| [04:30:22] > server.bots.add(count=3, skill="hard") | ▶ bot_1v5 |
| [04:30:22] [bots] Added 3 bot(s) (skill=hard) to room rm_8f3 | ▶ net_stress |
+-----------------------------------------------------------------------+---------------+
| > draw.hitboxes 1 [Single] [Execute]|
+---------------------------------------------------------------------------------------+
Dual-Syntax Parser: Source Commands + Python AST
Commands can be expressed in either standard Source-engine console syntax or native Python expression/statement syntax. The console parser automatically differentiates between the two:
-
Source / Quake Command Syntax:
- Set CVar:
net.graph 2,draw.hitboxes 1,server.bots.freeze 1 - Query CVar:
draw.fov,net.simulate_lag - Command with keyword params:
server.start map:hd_dust2 bots:3 skill:hard - Command chaining:
server.cheats 1; draw.hitboxes 1; net.graph 2 - Client binds & aliases:
bind F1 "macro.run('warmup')",alias prac "server.cheats 1; draw.hitboxes 1"
- Set CVar:
-
Python Sandbox Syntax:
- Property assignment:
draw.wireframe = True,server.bots.freeze = True - Function invocation:
server.bots.add(count=2, skill="hard") - Multi-line scripting & loops:
server.cheats = Trueplayer.god = Truefor s in ["easy", "normal", "hard"]:server.bots.add(count=1, skill=s)print("Configured test arena with multi-tier bots!")
- Property assignment:
Hierarchical Namespaces
Every CVar and ConCommand is strictly structured into modular namespaces:
net.* — Networking & Lag Compensation
| Name | Type | Default | Description | Flags |
|---|---|---|---|---|
net.graph | int (0-3) | 0 | In-game NetGraph overlay (0: off, 1: fps/ping, 2: frame cost + tick/io/interp, 3: + loss/jitter). Every value measured; see Measuring performance | client |
net.simulate_lag | float (0-1000) | 0.0 | Injects artificial round-trip latency in milliseconds | cheat, client |
net.simulate_loss | float (0-1) | 0.0 | Injects artificial packet loss ratio (0.0 to 1.0) | cheat, client |
net.simulate_jitter | float (0-500) | 0.0 | Injects latency variance in milliseconds | cheat, client |
net.prediction | bool | true | Client-side movement prediction | client |
net.reconciliation | bool | true | Server reconciliation on snapshot replay | client |
net.interp_delay | float (0-500) | 50.0 | Entity interpolation buffer delay in milliseconds | client |
draw.* — Visuals, Rendering & Debugging
| Name | Type | Default | Description | Flags |
|---|---|---|---|---|
draw.hitboxes | bool | false | Renders authoritative bounding boxes & headshot bands | client |
draw.trajectories | bool | true | Traces bullet raycast rays and impact decals | client |
draw.wireframe | bool | false | Renders map geometry in wireframe mode | client |
draw.fps | bool | false | Shows FPS & frame time variance counter | client |
draw.noise_rings | bool | true | Shows spatial audio noise bearing indicator | client |
draw.fov | float (60-110) | 75.0 | Vertical field of view | client, archived |
draw.viewmodel | bool | true | Renders first-person weapon model | client |
draw.crosshair.* | sub-ns | - | Dynamic spread crosshair color, size, and dot toggles | client |
server.* — Match & Bot Simulation
| Name | Type | Description |
|---|---|---|
server.cheats | bool CVar | Allows cheat commands (player.god, player.noclip, give) |
server.max_players | int CVar | Max client capacity per match room |
server.start(map, bots, skill) | Command | Spawns a new server room with optional bots |
server.stop() | Command | Terminates current match session |
server.map(name) | Command | Changes the active map |
server.restart() | Command | Resets match scores, timer, and positions |
server.bots.add(count, skill) | Command | Spawns reactive AI bots into the match |
server.bots.kick_all() | Command | Removes all active bots |
server.bots.freeze | bool CVar | Bots produce no input while set: they stand, never turn or fire, and can still be shot |
player.* — Movement, State & Loadout
| Name | Type | Description |
|---|---|---|
player.god | bool CVar | Invulnerability / god mode (cheat protected) |
player.noclip | bool CVar | Freely fly through walls and level geometry |
player.infinite_ammo | bool CVar | Infinite magazine and reserve ammunition |
player.speed_scale | float CVar | Movement speed modifier (0.1 to 10.0) |
player.give(weapon) | Command | Equips a weapon with full ammo, by id (knife, pistol, assault, shotgun, sniper), by display name (Sniper Rifle), or by slot number. The offered list is derived from the weapon table, not written out here or in the command — see below |
player.teleport(x, y, z) | Command | Warps player to the nearest spot near (x, y) where a body fits (physics.place_body); z is optional and ignored, since the floor decides it |
player.respawn() | Command | Forces immediate respawn at a team spawn point |
player.get_pos() | Command | Returns player coordinate tuple (x, y, z) |
player.give is the one command in this table worth a paragraph, because it
spent its whole life broken in two ways that a served registry is supposed to
prevent.
It resolved its argument against a weapons.WEAPON_NAMES that has never existed,
so every invocation raised AttributeError — and it advertised carbine and
subgun, neither of which has ever been a weapon here, while omitting assault,
which is one. That enum is served to both clients, so the autocomplete in the
native console and the browser pane offered weapons the node had never heard of.
Both halves now come from weapons.WEAPONS itself, via weapon_slots() and
resolve_slot(). The argument is resolved with is None rather than truthiness,
because slot 0 is the knife and 0 is falsy — player.give 0 used to hand out
the default rifle. And an out-of-range slot is refused rather than clamped, unlike
weapon_at: that clamps because a bad slot arriving on the wire is a typo which
must not drop a whole input frame, whereas a person typing one at a console wants
to be told.
physics.* & hitbox.* — World & Hitbox Tuning
| Name | Type | Description |
|---|---|---|
physics.gravity | float CVar | World downward acceleration constant (def: 18.0) |
physics.jump_boost | float CVar | Velocity impulse applied upon jumping (def: 9.5) |
hitbox.get(part) | Command | Returns dimensions [radius, height, head_band] |
hitbox.tune(part, radius, height, head_band) | Command | Hot-tunes live hitbox geometry |
hitbox.reset() | Command | Resets hitboxes to canonical specification |
macro.* — Macro Engine & Drills
| Name | Type | Description |
|---|---|---|
macro.run(name) | Command | Executes a saved or built-in macro |
macro.list() | Command | Lists all stored macros and descriptions |
macro.save(name, code, desc) | Command | Saves a new Python macro script |
macro.delete(name) | Command | Removes a user macro |
Built-in Macros & Drills
The console ships with five drills. They run against a server room (Host),
not offline Train, and test_every_builtin_macro_names_real_weapons_and_cvars
checks that each one names only weapons and cvars that exist:
warmup: cheats, god mode, hitboxes and tracers on, plus 3 normal bots.bot_1v5: kicks every bot, adds 5 hard ones on RVSF, and hands you the assault rifle.smoke_practice: cheats, god mode, hitboxes and the grenade arc on, for throwing lineups.net_stress_test: 120 ms of artificial latency and 5% loss, with NetGraph level 2.frozen_targets: 5 easy bots, frozen withserver.bots.freeze, as standing targets.
server.timescale and the slowmo_duel drill were removed. The cvar was
registered and never read: a client predicts its own movement in real time, so
a server-side scale would mispredict every tick. bot_1v5 used to give a
"carbine" that is not a weapon here.
The same console in the native client
apps/native-fps/src/console.rs + the painter in apps/native-fps/src/hud.rs.
The native client's console is not a second console. The registry is served
(GET /api/hassault/console/definitions) and this reads that list rather than
declaring one of its own — a Rust copy of the CVar table would be a third source
of truth after console.py and registry.ts, and the failure mode of a third
copy is not a build error but a console offering a command the server has never
heard of.
What differs is the surface: the pane is a React panel with a toolbar you click, and this is monospace text drawn by the HUD painter while the mouse is aiming a weapon. So every capability arrives by a different route, which is worth writing down because the useful half of a toolbar button is usually not the click.
| Browser | Native |
|---|---|
| Title bar: room, map, ping, cheats | The header line |
| Quick-toggle buttons | F1–F8, drawn as live state chips — or clicked |
| Filter tabs (ALL/NET/DRAW/SERVER/MACRO) | ^F, or filter <name> |
| Macro drawer | macros, listing what the node serves |
| Copy logs | copy, which writes a file |
| Autocomplete rows carrying a type and a description | One detail line under the input, for the selected item |
[4:30:12 AM] timestamps | [02:05], elapsed since the console came up |
The pointer is released whenever the console is up, so the chips and the
completion row take a click and the wheel scrolls the scrollback — the mouse
behaves the way it does in any other shooter's console. Two rules make that safe.
The hit test reads hud::console_hits, the same layout the painter draws
from (the rule Menu::rows_at already follows: a second computation of where a
chip is drawn is a click that lands on its neighbour, silently). And a click that
hits nothing is swallowed rather than falling through — the panel covers the
top half of the screen and the world is still live behind it, so a miss that
reached the trigger would fire a shot at whatever the crosshair was on while the
player was reading their own scrollback. Closing the console takes the pointer
back, the same way closing the pause menu does; it used to release it on the way
in and never re-take it, so the tilde that put you back in the game left you with
a view that would not turn until you clicked.
The font is case-sensitive, and was not always. Every glyph used to be looked
up through to_ascii_uppercase, so the 5×7 set had one case and lowercase came
out shouting. That is right for the HUD — the kill feed, the scoreboard and the
menu uppercase their strings explicitly, and still do — and wrong for the one
surface whose job is to echo back exactly what was typed, next to CVar names that
are lowercase everywhere else in this app. The lowercase cell is the fiddly half
of a 5×7 font: x-height letters occupy rows 2–6, ascenders the full seven, and
descenders (g j p q y) shift up to rows 1–6 because there is no eighth row to
hang a tail in. That cell is now the fallback: the console draws in the system's
monospace face, so it accepts any printable character — an accented name typed
into say shows as typed — where it used to drop anything the 5×7 set lacked.
Its geometry comes from console_unit, which ignores the HUD-scale setting in the
painter and the hit test alike; the two used to disagree, so at any HUD scale but
1.0 a click landed on the chip beside the one drawn.
Six of those carry a decision worth keeping:
- The chips are the point, not the keys. Half of what a toggle button gives
you is the click; the other half is seeing at a glance that hitboxes are on,
which is otherwise a
draw.hitboxesround trip. So a chip is drawn even for the actions that have no state to show. - A chip for something this client does not read is drawn as unhonored, in
red, rather than hidden.
draw.wireframeis a client CVar the browser reads and the native client does not; a chip that drew it like an "off" one would be the console lying about its own coverage, which is the exact failure the module's honesty rule exists to prevent. - A server value nobody has told us yet draws as
?, never asOFF. This bit during development: the registry'scurrent_valuefield isserde(default), so a node that reports no value leavesValue::Nullthere — and a null read as a flag isfalse. Seeding the cache with those nulls turned "never been told" into a confident "off" on the god-mode chip, with nothing anywhere to say so. - A toggle's command comes from the current state, computed in
quick_actionsrather than spelled as a static table. A table of fixed strings gives you a key that turns hitboxes on and can never turn them off, and that is a bug you only find by pressing it twice. - Changing the filter resets the scroll.
scrollcounts lines back from the bottom of the visible set, so keeping the offset across a filter change silently parks the view somewhere unrelated in the log. - The transcript ignores the filter. A filter is a reading aid; a transcript is evidence, and one that dropped three quarters of a session because a tab was selected would be the worst possible artifact to hand somebody debugging.
Two smaller things are different because the platform is:
- Timestamps are elapsed, not wall clock.
stdcannot render a local time — there is no timezone database in it — so the alternatives were a dependency carrying one, or printing UTC and letting the reader do arithmetic. What a console log is read for is the interval between two lines, which elapsed answers directly and cannot be wrong about a timezone. copywrites a file rather than filling the clipboard. The clipboard crates pull an X11/Wayland stack in on Linux and own a background thread for the process's lifetime, which is a lot of surface area for one console action. A file is also the more useful native artifact: it can be attached to a bug report, and it survives the crash you were trying to capture. It goes to the system temp directory, because this client writes nothing else to disk at all — its settings live on the node — and inventing a data directory here would mean a second answer to a questionbackend/paths.pyis the sole authority on.
help prints the client-only commands and still forwards to the node, since
the two halves of the command list live on different sides and answering from
only one leaves the other undiscoverable.
One failure that used to be silent now is not: an affectedCvars entry naming a
CVar the client's registry has no definition for is dropped — there is nothing to
render an untyped value as — and reported through divergence::note_unknown_cvar.
The only symptom otherwise is a status chip that never updates, on a client whose
registry fetch is older than the node it is talking to.
On the game server: host, creator and admin, never in ranked
The standalone web client plays on the central game server, so its console's
POST /api/hassault/console/exec lands there rather than on a node. Until the
route existed the game server's static web mount answered that POST with
405 Method Not Allowed. It is now answered by
backend/games_server/hassault_console.py, which is deliberately much smaller
than the node's console.
The native client reaches the same table a second way: console_exec on its
match socket, answered as console_res by socket_console. The role is read off
the socket's own account rather than a bearer token, so it works for a guest —
see the console, for a client with no node.
The route's definitions also carry the node registry's client-flagged CVars, for
a client that has no node to ask.
The rules are the same on both paths:
-
Who. Three roles, each able to do everything the one before can:
Role Who May run host the room's longest-seated human ( HassaultReferee.host_of)server.bots.add,server.bots.remove,server.bots.kick_all,server.bots.freeze,helpcreator the account that opened the room ( HassaultReferee.creators)the above, plus player.godand the boundedgameplay.*numbersadmin named in HASSAULT_ADMINSall of it in any room, plus server.kick <name>Cheats stay with the creator rather than the host because the host is whoever has been seated longest, which a stranger becomes when the creator steps out — running the bots is the room's business, everyone's damage scale is not.
HASSAULT_ADMINSis comma-separated account ids or handles (constcorrectness,@ConstCorrectness): a game-server handle is unique and locked once claimed, so it names one account as surely as its id. The client sends the account's bearer token; a guest or a caller without the role gets a 403 whosedetailthe console prints as is.helplists what you may run. -
Where. Never a ranked room (mode
duel) — admins included. A node's own console refuses a duel room the same way; otherwise the node's owner opened every room it runs, so a node needs no token. -
What. A fixed command table applied to the simulation, so the server honours it (
godandplay.godaliasplayer.god, the caller's own player). Bothserver.bots.add 3 hardandserver.bots.add(count=3, skill="hard")are accepted; the call form is parsed withast, literal arguments only, and never evaluated. No Python, no macros — those run on a player's own node, never on a public server.GET /api/hassault/console/definitionsserves the table in the node's definitions shape, so the browser's autocomplete offers what the server accepts.
The menu's "host with N bots" and the pane's bot buttons send add_bot /
remove_bot over the socket rather than the console route. The game server
answers those through the same host check (socket_bots), against the socket's
own account — so a guest who is hosting can add bots from the menu, though
not type console commands. A refusal arrives as room_settings_refused, a
notice rather than a match error. Both paths go through
HassaultReferee.add_bots / remove_bots, which broadcast roster.
Agent Tools Integration
The console is fully exposed to AI pair-programming agents via two structured tools:
hassault.console_exec:await agent_tools.hassault_console_exec(command="draw.hitboxes 1; server.bots.freeze 1")hassault.run_macro:await agent_tools.hassault_run_macro(name="warmup")
The operator: a skinned character, and 23 Mixamo clips
packages/core/src/modules/hassault/models/* +
packages/core/src/modules/hassault/avatars.ts, built from
assets/horribleAssault/ by scripts/build_hassault_character.mjs
(pnpm build:hassault-character).
Remote players and bots are a rigged, skinned character playing recorded
animation clips. This replaced a rig assembled in code from 48 box primitives
parented into hand-written joint groups, whose motion was computed every frame in
trigonometry — the walk cycle was literally Math.sin(walkPhase) driving thigh
rotations.
That rig could be posed but never deformed: each limb was a rigid box
pivoting about a Group, with no vertex weights, so an elbow could bend but no
surface bent with it. It is also why the clips could not simply be dropped in —
a Mixamo clip addresses mixamorig:LeftForeArm, and there was nothing of that
name to bind to.
The build is the interesting half
The asset is one GLB — apps/web/public/hassault-operator.glb, 7.9 MB, 30k
triangles, 23 clips — so a match costs one fetch however many players are in it,
and every clip arrives already bound to the skeleton that renders it. Four
things the build script has to get right, each of which fails silently:
- Units. Mixamo exports centimetres and the world is in cubes. The character
is measured and scaled to
DEFAULT_HITBOX.standingHeight, on the root node rather than on the position tracks, so bone-local translations inherit it and clip data is never rewritten. - Root motion. A clip downloaded without Mixamo's "In Place" box walks the hips across the floor. The server owns position here, so that translation fights it and the body skates away from where it is. Horizontal hip movement is zeroed; the vertical component — bob, and the rise of a jump — is kept, because that belongs to the animation.
- One skeleton, not nine.
FBXLoadergives each skinned mesh its ownBoneobjects even when the FBX describes a single skeleton, so the character arrives as nine meshes bound to nine partial copies — 87 bone objects for 34 distinct names. Both the exporter and the runtime mixer resolve a track's bone by name throughPropertyBinding.findNode, which returns the first depth-first match, so the clips drive one copy and eight meshes are bound to copies nothing animates. Untreated, the shirt walks while the body, head and boots stand in a T-pose. Every skin is rebound onto that same first match, and bind poses are compared rather than assumed — a duplicate sitting elsewhere in the hierarchy would deform the mesh instead of animating it. - Alpha. glTF has no alpha-map slot, so an FBX
map_dreaches the exporter as analphaMapit drops. Opacity is folded into the base colour's alpha channel and the mode is measured: four of the seven maps are solid white and becomeOPAQUE, the body's cutout mask becomesMASK(it is what stops bare torso poking through clothing), and genuinely translucent eyewear and shoes stayBLEND.FBXLoadermarks all seventransparent, which would have cost seven depth-sorted draws per player for nothing.
Textures are downscaled and re-encoded once by sharp on the way through — 33.9 MB of PNG becomes 2.9 MB of webp at 1024px — and the FBX-to-glTF V-axis flip is baked into the pixels rather than left to the exporter's canvas transform.
Choosing a clip
models/clips.ts is deliberately three-free and side-effect-free, the same way
world.ts and player.ts are: picking a clip is a decision about game state, so
it is unit tested headless rather than eyeballed in a match. A wrong clip is not
a crash — it is an enemy who appears to walk forward while retreating.
What is chosen is posture, not gait: rifle_aiming_idle standing, the kneel
or the crouch-walk crouched, running_jump airborne, a death clip dead. It used
to pick a walk, a strafe or a retreat by direction, and those clips are still in
the GLB — but their feet do not keep up with the body (below), so a moving
player's legs are solved and its torso holds the aiming pose.
Death and airborne are checked first, because both override everything: a player killed mid-strafe is dying, not strafing. A dead player stays drawn so the death clip can play out; the old rig had no death animation to run, so hiding the body on the frame it died was all there was.
Feet that stay where they are put
Players looked like they were skating because they were. The clips have their
root motion stripped and play at a fixed rate, so each implies a foot speed — and
measured off hassault-operator.glb the fastest is 3.4 cubes/s (rifle_walk)
under a body doing 18. The feet covered a fifth of the ground the body did.
Scaling the playback rate fixes one speed in one direction; a strafe, a diagonal
or a stop still slides.
So the legs are solved, not played. models/locomotion.ts (three-free, like
clips.ts) keeps a gait per body: each foot is either planted, and then it
does not move in the world whatever the body does, or swinging to where the
hip will be when it lands plus the half-stance it lands ahead by. Slide is zero
by construction rather than by tuning, at any speed and in all eight directions.
- Cadence rises with speed, and faster than its line where that is what it
takes to keep one foot down — a slow walk with both feet in the air is a hop.
Past
CADENCE_MAXthe legs cannot keep up and the share of the cycle a foot spends planted (duty) falls below a half: that is a run, with a flight phase, and it falls out of the reach of the leg rather than being a second mode. - The pelvis turns part of the way toward a diagonal and squares up again on
all four axes (
sin 2a), so backing away to one side still points the hips along the line being travelled. It sinks a little into the stride and leans into the travel. - Velocity is not on the wire, so it is read off two positions and smoothed.
Under
IDLE_SPEEDthe legs are handed back to the clip — interpolated positions jitter at rest, and that jitter must not start a stride. A jump in position faster thanTELEPORT_SPEEDis a respawn, not a sprint. - A turn or a stop can leave a planted foot out of reach. It is dragged to the edge of reach: a slide, but a short one, where leaving it would tear the leg off the hip.
CharacterAnimator applies it after the mixer: the pelvis is squared onto its
heading (the aiming clips stand it 40° off), then each leg is solved hip to ankle
with the same two-bone solver the first-person arms use, as two shortest-arc
turns that leave each bone's own twist as the clip had it.
locomotion.test.ts states the complaint as a measurement on both shipped rigs:
a foot whose ankle is on the ground moves less than 2% of the ground the body
covers, walking and running, in eight directions — and each foot must be on the
ground for a minimum share of the time, because a leg that cannot reach its
target would otherwise pass by never being measured.
What else a clip cannot know
All of it is applied after mixer.update(), never before — AnimationMixer
overwrites bone transforms wholesale every update, so anything set beforehand is
discarded without warning.
- The aim. Every Mixamo clip looks at the horizon, and the moving clips carried the rifle across the chest — about 85° off the look direction. A fixed share of the pitch down the spine, which is what this used to be, cannot fix either: it adds to wherever the clip left the weapon. So the barrel's direction is measured off the hand that holds it, and the three spine bones each take a third of the rotation that carries it onto the row's yaw and pitch. The thirds are the same rotation about the same axis, so they compose to the whole exactly — no iteration, no residual. The neck and head then turn the rest of the way onto the look and are levelled about it, since the spine's turn leaves the head cocked. Tested on both rigs in every posture, looking down, level and up: barrel and face within 3° on every frame, crossfades and strides included. A reload is the exception — the rifle is meant to come off the line — so the chest is aimed instead and the arms are left to the clip.
- Upper-body actions. Firing and reloading have to layer over whatever the
legs are doing.
AnimationMixerblends overlapping actions by weighted average rather than letting one win, so a fire clip played over a walk comes out as a half-shrug. The layering therefore works by making the track sets disjoint: the action clip is filtered to the arms, chest and head, and neither layer has an opinion about the other's bones.
Firing is driven from the snapshot's fx, which is the only place a client
learns somebody else pulled a trigger — PlayerRow carries no trigger state,
because a shot is an event and a row is a position.
Per player, not per asset
Two things are cloned rather than shared, and both are silent when missed:
SkeletonUtils.clone, neverObject3D.clone. A plain clone copies the mesh and the bones but leaves every copy'sSkinnedMeshbound to the original skeleton, so all eight players in a match share one pose and animate in lockstep.- Materials. The GLB's materials are shared across every clone, so the
stale-player fade — which sets
opacityon whatever material it finds — would fade every player on the server the moment one of them lagged. Restoring a fade returns each material to its own blend mode rather than to opaque, or the measuredMASK/BLENDclassification above would be undone on recovery.
Geometry stays shared and is never disposed per player; freeing it with one avatar would blank every other body on the field.
Dust II's colour pass, and the operators' gear
Both made with Blender 5.3, both kept off everything gameplay reads.
Dust II got a warmer, more saturated palette — the grey paving a sun-warmed
cream, the sandstones deeper, the tile a stronger blue, the fabrics richer — and
build_flourish in generate_dust2.py: louvred blue shutters with a sill, a
lintel and every other one a flower box, on both faces of the Long A and Mid
walls and the inside of the perimeter; a blue-and-gold frieze along every wall
that lacked one; cloth hung from the mid lines. Two new materials,
mat_dust2_canopy_teal (burlap) and mat_dust2_wood_shutter_blue (wood),
are rows in glb-surface-vectors.json.
- Collision is byte for byte what it was. Everything new is
_NonColand starts above 4.3 m, over the 2.2 m the dressing planner treats as solid, so no rule-placed crate moves either. The bake reproduces all 1,227 brushes; onlycollisionSource/collisionBakedchanged (the collision mesh now holds the trim).maplint, the nav and bake tests, the collision audit (0 floor mismatches) and the eye probe (0 objects) pass. - Windows are placed by what is in front of them.
_wall_is_barereads the warper's scan of everything already built (in the authored frame, before the cuts) and skips any spot with a door, arch, lantern, banner, roof or awning in front of it, so the perimeter could be dressed without a hand-typed list of where its buildings stand. - The key art (
apps/assault-web/src/assets/maps/hd_dust2.webp) is a frame of the game itself: the live menu's renderer at Dust II's "site A lo" framing, taken withHASSAULT_MENU_SHOT_BARE=1 HASSAULT_MENU_SHOT_MAP=hd_dust2 HASSAULT_MENU_SHOT_AT=7, cropped to 1600×782. The old one was a browser screenshot from before the photographed surfaces.
The operators (tools/blender/enhance_operator.py). T gets a plate carrier
with three magazine pouches and a radio pouch, a belt with two pouches, a scarf,
and orange armbands; CT, already in a carrier and helmet, gets blue armbands and
a blue stripe round the helmet. The armbands are the point: which side somebody
is on reads at fifty metres as the colour of their arms.
- Appended, not re-exported. A Blender round trip of three's export would
re-orient bones, resample all 23 clips and rename what the clients look up.
Instead Blender's bmesh models the pieces and the script adds them to the GLB
as one more mesh (
Gear) under the same root, with its own skin over bones the rig already has and inverse binds copied from the skins there. Each piece follows one bone rigidly. The original bytes are kept; the rig is still 34 and 65 bones. - Sized from the body. The carrier, belt, scarf and bands are fitted to the
bind-pose body read from the file. T's eighty primitives index one vertex
buffer (read once), and a sword across his back is weighted to his spine:
coremeasures the body as the run of occupied space round the spine, bridging the hollow of the chest but not the gap to the sword. - A file with
Gearin it is refused: run the script on the undressed model (git show <rev>:apps/web/public/<file>), never on its own output. assets/manifest.jsonandassets.manifest.jsoncarry the new hashes (pnpm assets:pack). Theassets-v5release is not published: until it is,pnpm assets:pullwould fetch the v4 operators and refuse them.
The operator in the native client
apps/native-fps/src/{character,clips,animator,characters_gpu,held}.rs +
src/skin.wgsl.
The native client draws the same GLB, and for a while it did not: it kept the
box rig above long after the browser had replaced it, so the two clients showed
different games. Its walk cycle was (x * 3.5 + y * 3.5).sin() — a function of
position, not speed, so a player strafing on the spot animated at full stride
and a player sprinting along a wall of constant x + y stood still.
The asset is compiled into the binary (include_bytes!). Every other read
this client makes goes to the node over HTTP because the server owns the numbers;
a character is not a number, and fetching it would make the client refuse to draw
players whenever the web layout's static directory was not where it expected.
Same rule as the bundled maps: our content ships, AssaultCube's never does.
Four things differ from the browser, all forced:
- Skinning is on the GPU. The obvious port keeps building vertices on the CPU each frame like every other mesh here. It does not survive the asset: 90,093 vertices per operator is ~720k to transform and re-upload every frame at eight players, around 26 MB/frame across the bus to avoid writing one shader. The geometry is uploaded once; what changes per frame is 34 matrices per player, in a storage buffer selected by a dynamic offset.
EXT_texture_webpis folded away before parsing. The operator's fourteen maps are webp, which is not a core glTF format, so the exporter declares the extension as required — and a conforming parser must refuse a file whose required extensions it does not implement.normalise_glbpromotes each texture's webp source to the coresourcefield and drops the requirement, in memory. Deliberately narrow: any other required extension is still refused, because silently stripping requirements renders a file wrong instead of failing to render it.JOINTS_0is remapped per skin. Each of the nine primitives indexes into its own skin's joint list (lengths 1, 24, 18, 1, 3, 8, 10, 21, 1), and the union is one 34-bone rig. Uploaded unremapped, the shoes bind to the spine's matrices — no error, the character just turns inside out.- No back-face culling on the character, unlike the world. The mesher can cull because it emits every surface once facing the space you can stand in; a character's kit is single-sided sheets — straps, pouch flaps, the cut edges of a vest — and culling them makes a limb vanish when the camera crosses its plane.
Two more that produce no error at all:
- Global transforms are computed for every node, not just the joints. The
build script's scale-to-5.2-cubes lands above the armature, on a node that is
not itself a joint, so walking only the joint hierarchy silently yields a
character of the wrong size — and wrong size means the drawn body disagrees with
the capsule a shot is resolved against.
character.rshas a test asserting the bind pose is 5.2 cubes tall for exactly this reason. - The rig's internal unit is ~1/35th of a cube. Mixamo authors in centimetres,
so a bone's world matrix carries a scale of 0.0285 and anything parented to it
inherits it. A weapon prop stated in cubes therefore renders 35× too small — a
sub-pixel speck, and the character simply looks empty-handed.
held.rstakes the hand's position and orientation and drops its scale, stating the weapon in the units it is actually measured in.
One deliberate omission: no stale fade. The browser dims a player whose
updates have stopped arriving; the native client has no equivalent notion of a
stale row, and inventing one in the animator would put a question that belongs to
interp.rs in the wrong module.
Clip selection is duplicated in clips.rs, and the duplication is made safe the
way the physics is: both clients replay
packages/core/src/modules/hassault/__tests__/clip-vectors.json. The fixture
pins agreement; each side's own unit tests pin correctness. It covers the
crouch > 0.5 and speed > IDLE_SPEED boundaries and the three ways glTF
export writes Mixamo's bone prefix.
The gait is duplicated the same way, in locomotion.rs, against
__tests__/locomotion-vectors.json — which the browser suite writes
(UPDATE_LOCOMOTION_VECTORS=1) from scripted runs, stops, strafes, a jump and a
respawn, on uneven frame times. The port is in f64 although the renderer is
f32: the gait carries state across hundreds of frames and decides things by
comparison (is this foot in stance yet), so single precision would land a
touchdown a frame apart from the browser and fail the fixture over nothing. The
leg and aim solves on top of it are not fixture-pinned — they are stated in each
client's own skeleton types — and are instead held to the same measurements on
each side: animator.rs carries the 2% slide and 3° aim tests too.
Lighting, and why the two clients stopped matching
apps/native-fps/src/{lighting.wgsl.inc,detail.rs}.
Porting the character exposed a wider divergence: the same map rendered in the two clients did not look like the same game. The native side lit everything with a single hardcoded direction over a flat 0.55 ambient floor, with no tone curve and no surface detail, so every surface in every map came out at nearly the same value — a pale, flat world the browser never had.
It is not a colour-space bug, which is the first thing it looks like. Both clients write linear values to an sRGB target and let the GPU encode on write, which is correct and always was. What the native side was missing was shape:
- The browser's light rig, ported verbatim — hemisphere (cool sky, warm ground) plus a warm sun and a cool fill from behind. The fill is what stops a surface facing away from the sun reading as a hole rather than as a wall in shade.
- Lambert's own normalisation. three's
MeshLambertMaterialshades asalbedo / PI * irradiance. Leaving the divide out is not a subtle exposure difference once a tone curve is in front of it: ACES compresses hard above 1.0, so an over-bright albedo lands in the shoulder, the light's colour starts to dominate the surface's, and a muted tint comes out as saturated teal and hot pink. It reads as the palette being wrong rather than the exposure. - ACES tone mapping at the browser's 1.15 exposure. The sun plus a hemisphere light puts lit floors above 1.0, and clipping flattens everything past that into the same white — exactly where a bright surface loses the grain. It is now three's exact curve, applied once in the post pass over a half-float scene (see the Video settings' note on the HDR scene); it began as Narkowicz's fit in every shader, which ran native mid-tones about a fifth brighter.
- The surface grain (
detail.rs, a port ofsurfaces.ts): one small seamless tile of value noise and cube seams, generated at runtime from nothing and used as a multiplier over the vertex tints. Its UVs are in cube units, so its edge seam draws the cube lattice the map is actually built on. The native side derives those UVs in the shader by projecting world position on the face's dominant axis rather than carrying a vertex attribute — the map is axis-aligned cubes, so for this geometry the two are identical.
Two things are shared rather than copied, because a character lit differently
from the room it stands in reads as a sprite pasted over the world: the lighting
lives in lighting.wgsl.inc, concatenated ahead of both shaders at build
time (WGSL has no include), and the detail tile's bind group layout is built by
one function both the renderer and the offscreen preview call.
One value is sRGB and one is not, and the difference is about where each came
from rather than what type it is. The world's vertex tints are raw floats the
browser hands three as a BufferAttribute, which three uses as linear — so
decoding them natively would render every map darker and more saturated than the
browser renders the same map. The operator's team wash is a hex colour someone
picked, so that one is decoded, matching three's Color.
The three that survived the port
Porting the light rig closed the world's divergence and left three narrower ones
behind, all found the same way every divergence here has been — by putting two
screenshots side by side. All three are now pinned by tests/browser_parity.rs,
which reads the browser's own source rather than a second copy of the expected
value: asserting against a literal typed into the test would pin the two clients
to whatever was true the day it was written, and would not notice the browser
moving, which is the only direction drift has ever come from.
1. The view model was being brightened twice. viewmodel.rs carried a palette
a notch above the browser's, justified by a comment reading "this renderer has one
ambient floor and a single directional wash". That renderer stopped existing when
the rig landed: the weapon is drawn with the world pipeline — Renderer::render
binds self.pipeline for it — so it gets the same hemisphere, sun, fill, Lambert
normalisation and ACES curve every wall does. The compensation outlived the thing
it compensated for, and the native rifle read as white plastic beside the browser's
gunmetal. The palette is now viewmodel.ts's DEFAULT_PALETTE unchanged.
This is the shape to watch for: a constant that is correct relative to a subsystem, when the subsystem is the thing being replaced. Nothing about it fails to compile and no test that existed at the time was about the colour of a gun.
2. The view model was lit in camera space. Its vertices are camera space —
that is how it is parented to the eye without a scene graph — but SUN_DIR,
FILL_DIR and the shadow map are all world space, and the shader was shading
those camera-space normals directly. Two symptoms: the weapon's lit side never
moved when you turned (three parents the browser's to the camera and still lights
it in world space, so the browser's does), and the shadow lookup was being handed
what amounted to a point near the map's origin.
The fix is a second matrix in the camera uniform, light_transform: the identity
for the world and the operators, the camera-to-world matrix for the view model.
Deliberately not folded into view_proj — the two answer different questions,
"where does this land on screen" and "where is this in the room", and the view
model is the whole reason they are allowed to disagree. The same uniform's spare
params.w now carries whether a pass receives the sun's shadow, and the view
model does not: three shadows a mesh only with receiveShadow set, and
HorribleAssaultPanel.tsx sets it on the map's mesh and nothing else. Leaving it
on is not merely a difference — the weapon is a hand's width from the eye, so it
crosses a shadow edge as a hard flicker across the whole model.
3. The fog was a linear ramp against an exponential-squared one. The browser
sets FogExp2(0x11161f, 0.0055); the native side ramped linearly from 40 cubes to
a quality-dependent end. A linear fog has an exponential one's shape nowhere along
its length, so near geometry the browser left untouched came out hazed and the far
end of a long corridor arrived at the ramp's end as an edge the browser never had.
Quality::fog_density now returns the browser's exact density at High.
The colour is that hex decoded to linear and then run backwards through the
tone curve (display_hex_to_scene). The scene is linear light now and the curve
comes last, so the fog is mixed before it, and a fully fogged pixel has to come
out of the curve as the hex. A raw hex comes out three shades too pale, and an
un-inverted linear one comes out lifted; either reads as the density being wrong.
The browser does the same whenever its post chain is on (sceneColoursForChain).
With the chain off, three mixes fog after its colour-space encode
(fog_fragment follows colorspace_fragment in every three material). The two
ends of the ramp still match; what differs is the blend space part way along,
so mid-distance can come out a shade different. The colour and the curve are the
parts that read.
The browser panel lays rgba(13,17,23,0.72) over the whole canvas whenever it is
in playing and not pointer-locked — the "Click to play" prompt. Nearly
three-quarters of the picture is that overlay, so an unlocked pane screenshot is
much darker and flatter than what the renderer drew. Every side-by-side with the
native client has to be taken with the pane locked, or most of the difference
being compared is a <div>.
Sun shadows
apps/native-fps/src/{shadow.rs,shadow.wgsl}.
One depth pass, rendered once per map. The browser sets
shadowMap.autoUpdate = false and renders the map exactly once; this does the
same, for the same reason — the geometry is static and so is the sun, so a
per-frame shadow pass pays sixty times a second for a picture that never
changes. It is the whole reason real shadows are affordable here.
Only the static world casts. Players do not, which matches the browser rather
than cutting a corner: with autoUpdate off, an avatar added to the scene never
appears in a map rendered before it existed. Players still receive, which is
the half that matters — an operator standing in a building's shadow should be
dark, and a cast shadow tracking a body interpolated between 20 Hz snapshots
would be a lie about where that body is anyway.
Four things are load-bearing:
- Front faces only — the single line that makes shadows possible in a Cube
world. A Cube 1 map is a sealed box, so every open cell emits a ceiling quad
facing down. Render back faces into the shadow map and the sky lid catches all
the light, putting the whole level in shadow — which reads as the lighting
being broken rather than as a culling bug. three spells this
material.shadowSide = FrontSide; here it iscull_mode: Back, because the mesher winds every quad counter-clockwise as seen from the open side. - Only the sun is shadowed. The hemisphere is ambient — a surface in shadow is still lit by the sky above it — and attenuating that too makes every shadowed face uniformly black, which is the thing real shadows exist to avoid.
- Outside the light frustum is lit, not shadowed. The opposite default puts
everything beyond the fitted box in darkness, which on a large map is a black
border round the edge of the world.
shadow.rshas a test asserting all eight corners of a 256-cube map fall inside the frustum, because a corner that falls out casts nothing and is lit when it should not be. - Slope-scaled bias, not a constant one. These are large flat quads at every angle to the sun, and a constant bias big enough to stop acne on a floor lit head-on detaches the shadow from the foot of every wall.
The sun's direction is the map's served one, used both to build the light
camera and to shade with, so the two cannot disagree. (It used to be a constant
in shadow.rs and another in lighting.wgsl.inc, pinned equal by a test: a
shadow cast from one direction and a Lambert term computed from another gives
surfaces lit from one side and shadowed from the other.) The camera is fitted
round the sphere of the render vertices' bounds, the rule the browser shares
(see the browser's graphics tier).
Surface breakup
shader.wgsl (surface_breakup, anti_tile_offsets, tile_weight) and
packages/core/src/modules/hassault/surface-breakup.ts, the same three steps in
both clients. All three read content only (the UVs, the world position, the
baked AO), so two players on the same tier see the same picture.
tests/browser_parity.rs pins every number and expression in one against the
other.
Only High and up draw all three. Low and Medium draw the grime only: native
detail below 2, and the browser's TierSpec.breakup, which is off at Low and
Medium and is the "Surface variation" row (Low's Lambert twin gets the
grime-only patch). Native has no such row: it follows the level. The anti-tiling and the macro tint
each move a colour either way round its mean, so leaving them out hides nothing.
On an Intel iGPU at 1080p they cost Medium 3.5–4 ms of GPU time, a fifth of its
frame rate (Dust II 71 → 56 fps, Bank 56 → 46). The grime only darkens, so it
stays at every tier, under the house rule that no level changes what a player can
see. A level without it would light the corners a player hides in.
Measured with --bench, interleaved against the build before the breakup:
| GPU | Level | Map | GPU p50 before → after (ms) | fps |
|---|---|---|---|---|
| integrated | Low | Dust II | 5.6 → 6.2 | 118 → 111 |
| integrated | Low | Bank | 6.3 → 7.1 | 110 → 101 |
| integrated | Medium | Dust II | 11.1 → 11.7 | 72 → 69 |
| integrated | Medium | Bank | 15.1 → 15.2 | 56 → 55 |
| discrete | High | Dust II | 0.55 → 0.71 | 652 → 636 |
| discrete | High | Bank | 0.99 → 1.33 | 463 → 424 |
What Low and Medium still pay is the grime and a larger shader. On Intel, a bigger shader can cost occupancy even where its branches are skipped.
- Anti-tiling (Quílez's offset technique). A value noise over the UV picks
one of eight bands; each band shifts the tile by
sin((3, 7) · band), and a pixel blends the two bands it falls between, with the seam nudged by how the two samples differ. The colour, normal and roughness maps are all read at the same two offsets with the same weight. Offsets only, never a rotation, so the normal map stays a valid tangent-space normal. The weight is the band's fraction alone. Quílez also nudges it by how the two samples differ, which bends the seam along the texture, but then it never quite reaches 0 or 1 at a band edge, where one offset jumps. That jump makes implicit derivatives see extreme minification and draw a one-pixel line of the smallest mip. Explicit gradients (textureSampleGrad) avoided the line, but cost about 1 ms on an Intel iGPU at 1080p. With the weight saturated, the jumping sample has no weight there, and plaintextureSampleis invisible on the line. Glass is left alone, and the site letters are never offset: an offset letter is a different letter. - Macro tint. A slow two-octave noise in world space (leaned on by height, so a wall varies up its face too) moves albedo ±10%.
- Grime. Where the baked AO falls below 0.95 (full at 0.55), the albedo is pulled towards a dirt colour, broken up by a third noise that only an occluded pixel evaluates. It is applied after the AO multiply, so a corner gets darker and browner. The plan also named height above the floor. There is no floor height to read per pixel on a multi-level map, and the AO bake is already darkest at the foot of every wall, which is the place that term would have weathered.
The noise is Dave Hoskins' hash without sine. sin of a large argument is not
the same number on every GPU, and a hash that differs per vendor is a pattern
that differs per vendor.
In the browser it is one onBeforeCompile per map material, installed in
applyGlbSurface. setSurfaceQuality switches each physical material between the full patch and
the grime only on a tier change (setBreakupDetail, a recompile), and gives each
Lambert twin the grime-only patch (installLowTierBreakup). The program cache key
(hd-breakup-2[-tile][-tint][-grime]) is what lets three share one program
across every material with the same patch. surface-breakup.test.ts runs the
patch over three's own shader sources and fails if an #include anchor it needs
has moved. A missing anchor is not an error in three, just an unpatched material.
Water
shader.wgsl water_surface (the volume pass, MODE_WATER) and water.ts.
Three travelling waves bend the normal and never the plane, because the plane
is the line a player judges a jump against. The waves have wavelengths 4, 2.3
and 1.1 cubes, at 0.25, 0.375 and 0.5 Hz. Their periods all divide 8 s, so the
clock wraps at 64 s (WATER_CLOCK_WRAP) without a seam. The map's environment is
reflected by Schlick's fresnel (F0 0.02): its served sky above, hemiGround
below, the same function the prefiltered environment is built from. The same
fresnel raises the alpha at a grazing angle, where water is a mirror rather than
a window.
There is no sun glint. The volume pass has no shadow map, so a glint would shine on indoor pools. For the same reason the native water body is unshadowed, and the browser's Lambert body is shadowed. That is a small, known difference under a roof.
Looking at it
The character is the one part of this client a unit test cannot check. The tests prove the rig is 34 bones, that every joint index is in range and that the bind pose is the right height — all of which stay true while the character is drawn facing backwards, inside out, or in the wrong colour. Those are properties of a picture, so there is one:
cargo run --manifest-path apps/native-fps/Cargo.toml --example operator_preview -- operator.png
It renders five operators, one per clip, matching the browser's own
apps/web/operator-check.html so the two can be compared side by side. An
examples/ binary rather than a test because it needs a real GPU adapter, and a
suite that fails on a machine without one gets ignored.
The facing convention is the exception — it is pinned in code rather than by
eye, because one operator at one yaw cannot tell a correct rotation from a
mirrored one: both look right head-on and disagree everywhere else. The test
walks the full circle and compares against Camera::forward at the same yaw.
It was first pinned against the forward vector bodies.rs derived, and that was
the bug: the box rig was itself mirrored, so the test agreed with a wrong
definition. The model was turned by yaw + π/2 where the camera implies
π/2 − yaw; the two agree at yaw 0 and π and nowhere else, so a player looking
along cube +y was drawn looking along −y, and every body on a north-south line
faced away from where it was aiming. The camera is the definition that cannot be
wrong without the player noticing.
The browser client got this wrong for longer. avatars.ts turned the operator
with the camera's own -yaw - π/2, which is correct for a −Z forward. That was
the box rig's forward, but a Mixamo character faces +Z, so every remote player
was drawn facing exactly away from where they were looking. It took a second
player watching you turn to notice. The rotation is now avatarRotationY
(π/2 − yaw). avatar-facing.test.ts pins it the same way the native client
does, and also checks the shipped operator GLBs themselves face +Z: toes ahead
of the feet, left hand on +X.
The weapon props stay procedural
The five weapon props and the muzzle flash are still built from primitives, and
they hang off the RightHand bone rather than off the root — so the skeleton
carries the grip through every clip for free, which is precisely the hand-written
work this rewrite removed. They stay procedural because the FBX weapon downloads
in assets/horribleAssault/ are third-party models with unverified licences, and
the module's standing rule is that other people's content is supported, never
bundled. These boxes ship.
Cosmetic Skins & Hitbox Invariance Guarantee
The skin system provides distinct faction styling and collectible operator skins without ever altering the collision volume or giving competitive advantages:
| Skin ID | Name | Faction | Body Palette | Armor & Trim | Visor Glow |
|---|---|---|---|---|---|
arc_default | ARC Scavenger | ARC | Desert Sand (#d9a441) | Weathered Brown (#4a3b2c) | Ballistic (#222222) |
halon_default | HALON Enforcer | HALON | Steel Blue (#4c8fd4) | Slate Plate (#1e293b) | Cyan Glow (#38bdf8) |
scavenger_prime | Scavenger Prime | ARC | Deep Rust (#b45309) | Carbon Black (#1c1917) | Amber Lens (#fbbf24) |
cyber_ghost | Ghost Recon | Neutral | Stealth Black (#18181b) | Charcoal (#27272a) | Purple Holo (#c084fc) |
arctic_specops | Arctic SpecOps | Neutral | Snow White (#e2e8f0) | Frost Slate (#64748b) | Ice Cyan (#0ea5e9) |
hazmat_warden | Hazmat Warden | HALON | Hazard Yellow (#eab308) | Heavy Rubber (#18181b) | Bio Green (#22c55e) |
[!IMPORTANT] Strict Hitbox Invariance: Every operator skin and attachment is strictly bounded within the canonical collision cylinder (
r = 1.1,h = 5.2) and head band (1.0) defined inDEFAULT_HITBOX. Hit registration remains strictly server-authoritative raycast vs canonical cylinder. Skins never alter hitboxes, movement speeds, or sight lines.
Measuring performance
Every performance change to either client is reported against a measured baseline, never against a feeling. The instruments are the same in both clients so a number read off one means the same thing on the other.
The NetGraph
net.graph (or F3) steps through four levels. Level 1 is fps and ping. Levels
2 and 3 used to print fixed strings in the native client (TICK: 15.6MS,
IN: 14.2 KB/S), which survived the server moving to 60 Hz without changing a
digit. Both clients now print measured values, and -- for anything not yet
measured:
| Line | What it is | Where it comes from |
|---|---|---|
P99 | 99th-percentile frame interval over the last 600 frames | frame loop |
CPU p50/p99 | time spent building and submitting one frame | frame loop |
GPU | GPU time per frame, N/A where the adapter cannot time it | EXT_disjoint_timer_query_webgl2 (browser), wgpu timestamp queries (native, gpu_timer.rs) |
DRAWS, TRIS | scene draw calls and triangles in the last frame | renderer.info (browser), Renderer::last_cost (native) |
TICK | server ticks per second of server time, from each snapshot's tick and t | net-stats.ts / net_stats.rs |
SNAP | snapshots arriving per second on our clock | same |
IN / OUT | WebSocket payload KB/s on the match socket | ws.ts channelTraffic / net::Traffic |
INTERP | the interpolation delay | net.ts / interp.rs |
LOSS (level 3) | ticks the counter skipped, over the last whole second | net-stats.ts / net_stats.rs |
JITTER (level 3) | RFC 3550 interarrival jitter, gain 1/16 | same |
A tick counter that goes backwards is a new match, not loss. The two NetStats
ports share their test cases (perf-instruments.test.ts, net_stats.rs).
The native client also sets TCP_NODELAY on its socket: with Nagle's algorithm
on, an input batch written while the previous one is unacknowledged waits for
that ACK or the delayed-ACK timer (up to 40 ms on Windows).
The bench
A fixed camera path per map, packages/core/src/modules/hassault/bench-paths.json,
generated from the map JSONs by scripts/gen_hassault_bench_paths.py. For each
bomb site (or, on maps without sites, the centre and the two farthest spawns),
plus mid between the teams' first spawns, it holds an eye-height framing, a
4-second turn and a high overview. The first 2 seconds hold the first framing
unrecorded, so shader compiles and uploads count as load cost, not frame cost.
Framings cut rather than blend, so a framing's cost does not depend on its
neighbours.
-
Browser: load a map offline and type
benchin the console (or callwindow.__hassaultBench()from a script). It prints frame, CPU, GPU and draw-call percentiles with a per-framing breakdown, and returns the JSON. It refuses with "still loading" until the map is on screen. Before G3 it started as soon as the map was named, so its warm-up could end before the map had appeared and the reveal was timed as frames (the G0 table includes that). Run it in a foreground tab: a hidden tab gets norequestAnimationFrame. In an ordinary tab the frame interval is capped by the display, so the CPU and GPU columns are the true cost measure there.node scripts/hassault_bench_browser.mjsruns every map at Medium and High in a headed Playwright Chromium at 1920x1080 with vsync and the frame-rate limit off (so the frame interval is the cost, as natively), on the high-performance GPU, opening each map through the offline training link#map=<id>&mode=train. Point assault-web at a node first: theassault-web-benchlaunch config proxies to a backend on port 8123. -
Native:
hassault-native --bench=<map>flies the same path in Train with vsync and the frame cap off, prints oneBENCH {json}line on stdout and exits. Pick the tier with--set=hassault.video.quality=high.scripts/hassault_bench_native.py --server <node>runs every map at Medium and High and prints the table below;--tiers low,medium --set hassault.video.powerPreference=lowruns it on the integrated GPU.The run's video settings are the tier's preset and then any
--setrows, and nothing from the machine's stored settings, so one row's cost can be isolated:--set=hassault.video.shadows=falseagainst the same run without it. Vsync, the frame cap and the render scale are forced off/off/100% unless a--setnames them (renderScale=0.5is how a fill-bound GPU is told from a vertex-bound one).
Both print the same JSON shape (BenchResult in bench.ts / bench.rs). The
native result also carries cpuPhasesMean and cpuPhasesP99, milliseconds per
phase of the frame (profile.rs): net, sim, loop, build, hud,
upload, acquire (waiting for a swapchain image, which is where a GPU-bound
frame shows up on the CPU), encode, submit, present. The means add up to
the CPU time; the p99s do not, and are for finding which phase a tail is in.
Uncapped and windowed, the native p99 is mostly the compositor: at 900+ fps
acquire waits for a free swapchain image in a few percent of frames, and that
wait is the tail. Read gpuP99 for the rendering tail, and bench with a cap
(--set=hassault.video.fpsLimit=240) to see the frame pacing a player gets.
Baseline
Recorded before the G-phase work (graphics, performance and gameplay); later phases report against these rows.
2026-11-04/05, one machine: RTX 4080 Laptop GPU, 1920x1080, vsync and frame cap off, each tier's full preset. Native on Vulkan (scripts/hassault_bench_native.py); browser in a headed Playwright Chromium on ANGLE/D3D11 (scripts/hassault_bench_browser.mjs). Offline Train, so no other players are drawn. One run per row: treat differences under about 10% as noise.
What the baseline says:
- Native is CPU-bound and flat. About 2.4 ms of CPU per frame on every map against 0.5–1.6 ms of GPU, so every map sits near 400 fps. The world is one draw; the other ~460 are most likely the range's skinned dummies (one draw per primitive per actor), not yet confirmed.
- The browser's p50 is fine and its p99 is not. Medians of 1–9 ms, but p99 of 6–40 ms: hitches, not a slow steady state. The worst maps (Assault, Bank, Office, Inferno) are the ones with 800–1160 draws and 600–820k triangles, about twice the native client's triangles for the same map.
- High is not reliably dearer than Medium in the browser. Run-to-run noise is as large as the tier difference on several maps, which is itself a finding: the per-frame cost is dominated by something the tier does not change.
| Map | Client | Tier | Res | fps | p50 ms | p99 ms | CPU p50/p99 ms | GPU p50/p99 ms | Draws (max) | Tris (max) |
|---|---|---|---|---|---|---|---|---|---|---|
| hd_aim | browser | medium | 1920x1080 | 641 | 0.80 | 6.50 | 0.70 / 5.40 | 0.90 / 6.59 | 447 | 151k |
| hd_aim | native | medium | 1920x1080 | 495 | 1.97 | 2.63 | 1.93 / 2.54 | 0.48 / 0.60 | 463 | 159k |
| hd_aim | browser | high | 1920x1080 | 493 | 0.90 | 8.60 | 0.80 / 7.00 | 1.48 / 7.70 | 460 | 151k |
| hd_aim | native | high | 1920x1080 | 463 | 2.11 | 2.80 | 2.07 / 2.73 | 0.78 / 1.09 | 463 | 159k |
| hd_assault | browser | medium | 1920x1080 | 94 | 6.80 | 40.10 | 7.00 / 21.90 | 5.29 / 18.53 | 937 | 645k |
| hd_assault | native | medium | 1920x1080 | 434 | 2.28 | 2.89 | 2.23 / 2.79 | 0.55 / 0.76 | 463 | 325k |
| hd_assault | browser | high | 1920x1080 | 95 | 5.30 | 18.50 | 4.20 / 13.70 | 4.41 / 11.67 | 937 | 645k |
| hd_assault | native | high | 1920x1080 | 413 | 2.37 | 3.24 | 2.32 / 3.17 | 0.88 / 2.73 | 463 | 325k |
| hd_bank | browser | medium | 1920x1080 | 100 | 4.10 | 27.40 | 3.70 / 19.80 | 3.22 / 15.05 | 1160 | 820k |
| hd_bank | native | medium | 1920x1080 | 410 | 2.40 | 3.10 | 2.34 / 3.02 | 0.76 / 2.40 | 463 | 411k |
| hd_bank | browser | high | 1920x1080 | 90 | 5.00 | 33.40 | 4.70 / 23.00 | 4.41 / 20.08 | 1160 | 820k |
| hd_bank | native | high | 1920x1080 | 376 | 2.46 | 5.25 | 2.40 / 5.20 | 1.57 / 4.58 | 463 | 411k |
| hd_dust2 | browser | medium | 1920x1080 | 405 | 1.10 | 9.10 | 0.90 / 5.30 | 2.50 / 5.30 | 562 | 281k |
| hd_dust2 | native | medium | 1920x1080 | 400 | 2.46 | 3.31 | 2.40 / 3.23 | 0.55 / 0.68 | 463 | 281k |
| hd_dust2 | browser | high | 1920x1080 | 324 | 1.10 | 9.80 | 1.00 / 8.00 | 3.03 / 7.58 | 550 | 300k |
| hd_dust2 | native | high | 1920x1080 | 392 | 2.50 | 3.30 | 2.44 / 3.19 | 0.95 / 2.48 | 463 | 281k |
| hd_facility | browser | medium | 1920x1080 | 397 | 1.30 | 8.20 | 1.10 / 5.10 | 1.34 / 5.07 | 563 | 231k |
| hd_facility | native | medium | 1920x1080 | 416 | 2.37 | 3.06 | 2.32 / 2.95 | 0.49 / 0.76 | 464 | 231k |
| hd_facility | browser | high | 1920x1080 | 258 | 2.20 | 13.40 | 2.00 / 12.40 | 1.60 / 9.87 | 563 | 231k |
| hd_facility | native | high | 1920x1080 | 409 | 2.39 | 3.45 | 2.34 / 3.39 | 0.90 / 2.62 | 464 | 231k |
| hd_inferno | browser | medium | 1920x1080 | 120 | 3.10 | 17.30 | 2.90 / 14.30 | 2.49 / 12.88 | 856 | 787k |
| hd_inferno | native | medium | 1920x1080 | 406 | 2.43 | 3.06 | 2.37 / 2.98 | 0.60 / 0.81 | 463 | 394k |
| hd_inferno | browser | high | 1920x1080 | 110 | 3.90 | 32.30 | 3.80 / 24.40 | 3.37 / 20.56 | 856 | 787k |
| hd_inferno | native | high | 1920x1080 | 398 | 2.46 | 3.15 | 2.41 / 3.06 | 1.02 / 2.53 | 463 | 394k |
| hd_junkflea | browser | medium | 1920x1080 | 112 | 4.20 | 29.60 | 3.80 / 16.50 | 1.01 / 9.93 | 569 | 344k |
| hd_junkflea | native | medium | 1920x1080 | 407 | 2.42 | 3.09 | 2.37 / 2.98 | 0.55 / 0.66 | 463 | 344k |
| hd_junkflea | browser | high | 1920x1080 | 207 | 3.70 | 15.20 | 3.50 / 14.30 | 2.32 / 11.50 | 569 | 344k |
| hd_junkflea | native | high | 1920x1080 | 398 | 2.47 | 3.14 | 2.41 / 3.03 | 0.94 / 2.40 | 463 | 344k |
| hd_mirage | browser | medium | 1920x1080 | 271 | 2.00 | 13.70 | 1.80 / 11.40 | 1.46 / 10.24 | 859 | 737k |
| hd_mirage | native | medium | 1920x1080 | 400 | 2.46 | 3.16 | 2.41 / 3.03 | 0.50 / 0.63 | 463 | 369k |
| hd_mirage | browser | high | 1920x1080 | 145 | 2.90 | 30.10 | 2.70 / 21.40 | 2.60 / 18.25 | 859 | 737k |
| hd_mirage | native | high | 1920x1080 | 388 | 2.54 | 3.26 | 2.48 / 3.20 | 0.79 / 1.12 | 463 | 369k |
| hd_nuke | browser | medium | 1920x1080 | 201 | 2.00 | 15.30 | 1.80 / 13.50 | 2.92 / 12.26 | 748 | 781k |
| hd_nuke | native | medium | 1920x1080 | 400 | 2.46 | 3.13 | 2.41 / 3.03 | 0.64 / 0.82 | 463 | 402k |
| hd_nuke | browser | high | 1920x1080 | 135 | 2.50 | 30.60 | 2.20 / 17.40 | 3.71 / 16.03 | 751 | 781k |
| hd_nuke | native | high | 1920x1080 | 388 | 2.52 | 3.35 | 2.46 / 3.26 | 1.15 / 2.58 | 463 | 402k |
| hd_office | browser | medium | 1920x1080 | 115 | 7.10 | 25.10 | 6.90 / 17.10 | 5.94 / 14.61 | 837 | 608k |
| hd_office | native | medium | 1920x1080 | 393 | 2.50 | 3.54 | 2.44 / 3.47 | 0.61 / 0.79 | 463 | 304k |
| hd_office | browser | high | 1920x1080 | 88 | 8.90 | 29.60 | 8.60 / 14.60 | 7.19 / 12.55 | 720 | 592k |
| hd_office | native | high | 1920x1080 | 392 | 2.50 | 3.31 | 2.44 / 3.21 | 1.15 / 2.80 | 463 | 304k |
After G2: native performance
2026-11-05, same machine and method as the baseline. The RTX 4080 Laptop rows
are directly comparable with the native rows above. The integrated-GPU rows
(Intel RaptorLake-S Mobile Graphics, --set hassault.video.powerPreference=low)
are new: they are the plan's real floor, Low holding 60 fps.
| Change | Measured on Dust II |
|---|---|
The hands are skinned on the GPU instead of the CPU (vs_hand, see skinned hands) | sim 1.88 → 0.19 ms of CPU; the client stopped being CPU-bound |
| The sun's shadow takes 4 probe taps first and only takes the rest on a shadow edge | dGPU High: shadows 0.73 → 0.05 ms of GPU |
The shadow taps use literal indices instead of a loop over a const array, which Intel GPUs spill to scratch memory | iGPU: Low's 4-tap shadow had cost more than Medium's 8 |
The world is cut into 24-cube cells (world_chunks.rs), frustum-culled and drawn nearest first, so early depth rejects hidden surfaces before they are shaded | iGPU Low: GPU 10.7 → 7.3 ms. Culling trims ~10% of triangles; the win is overdraw |
| Each cell carries a 64-bit mask of the point lights whose sphere reaches its box, so a fragment loops over those lights and not every selected one. Exact: a light that misses the box contributes zero to every pixel in it | iGPU Medium: map lights ~2 → ~0.8 ms |
The frame cap keeps a cadence and spins the last fraction of a millisecond (pacing.rs) | a 144 cap ran at 137 and now runs at 144.0 |
| A texture-quality change rebuilds on a worker thread and swaps in when ready | a 1.9 s freeze of the game when the setting changed, now none |
What the numbers say:
- Every map holds Low on the integrated GPU: 94–122 fps at p50. The worst p99 is Nuke at 17.1 ms, just under 60 fps for its worst 1% of frames.
- The discrete GPU is no longer the limit anywhere. 600–825 fps, GPU p50 0.27–0.56 ms at both tiers. The uncapped p99 there is mostly the compositor (
acquire, see the bench), not rendering: GPU p99 stays under 1.1 ms. - Draws went up, from 463 to 545–781, because each visible cell is its own draw. They are on one pipeline with no rebinding, and CPU
encodestayed near 0.2 ms.
Discrete GPU (RTX 4080 Laptop):
| Map | Client | Tier | Res | fps | p50 ms | p99 ms | CPU p50/p99 ms | GPU p50/p99 ms | Draws (max) | Tris (max) |
|---|---|---|---|---|---|---|---|---|---|---|
| hd_aim | native | medium | 1920x1080 | 781 | 1.13 | 5.50 | 1.09 / 5.44 | 0.33 / 0.69 | 546 | 159k |
| hd_aim | native | high | 1920x1080 | 603 | 1.30 | 7.41 | 1.26 / 7.37 | 0.45 / 0.84 | 546 | 159k |
| hd_assault | native | medium | 1920x1129 | 785 | 1.22 | 2.83 | 1.19 / 2.76 | 0.36 / 0.48 | 599 | 321k |
| hd_assault | native | high | 1920x1080 | 606 | 1.29 | 4.91 | 1.26 / 4.88 | 0.46 / 0.88 | 600 | 321k |
| hd_bank | native | medium | 1920x1080 | 700 | 1.20 | 5.07 | 1.16 / 5.04 | 0.40 / 0.97 | 637 | 410k |
| hd_bank | native | high | 1920x1080 | 654 | 1.33 | 4.99 | 1.29 / 4.94 | 0.55 / 1.08 | 637 | 410k |
| hd_dust2 | native | medium | 1920x1080 | 825 | 1.14 | 2.63 | 1.10 / 2.42 | 0.27 / 0.35 | 720 | 252k |
| hd_dust2 | native | high | 1920x1080 | 744 | 1.26 | 4.17 | 1.22 / 4.12 | 0.36 / 0.45 | 720 | 253k |
| hd_facility | native | medium | 1920x1080 | 704 | 1.08 | 5.13 | 1.04 / 5.09 | 0.27 / 0.45 | 705 | 228k |
| hd_facility | native | high | 1920x1080 | 627 | 1.25 | 7.71 | 1.20 / 7.63 | 0.36 / 0.88 | 704 | 228k |
| hd_inferno | native | medium | 1920x1129 | 807 | 1.19 | 2.96 | 1.13 / 2.67 | 0.31 / 0.39 | 747 | 320k |
| hd_inferno | native | high | 1920x1080 | 726 | 1.28 | 2.55 | 1.21 / 2.45 | 0.38 / 0.45 | 751 | 325k |
| hd_junkflea | native | medium | 1920x1129 | 778 | 1.26 | 2.54 | 1.19 / 2.25 | 0.37 / 0.50 | 656 | 290k |
| hd_junkflea | native | high | 1920x1129 | 723 | 1.46 | 2.10 | 1.42 / 2.06 | 0.56 / 1.05 | 656 | 290k |
| hd_mirage | native | medium | 1920x1080 | 764 | 1.07 | 5.21 | 1.02 / 5.18 | 0.27 / 0.34 | 723 | 292k |
| hd_mirage | native | high | 1920x1080 | 773 | 1.30 | 2.19 | 1.25 / 2.08 | 0.38 / 0.50 | 723 | 292k |
| hd_nuke | native | medium | 1920x1080 | 697 | 1.18 | 5.20 | 1.14 / 5.16 | 0.36 / 0.87 | 781 | 313k |
| hd_nuke | native | high | 1920x1080 | 715 | 1.30 | 2.37 | 1.26 / 2.34 | 0.43 / 0.63 | 781 | 313k |
| hd_office | native | medium | 1920x1080 | 697 | 1.15 | 5.16 | 1.12 / 5.13 | 0.34 / 0.69 | 676 | 254k |
| hd_office | native | high | 1920x1080 | 616 | 1.26 | 5.35 | 1.23 / 5.30 | 0.43 / 0.85 | 676 | 254k |
Integrated GPU (Intel RaptorLake-S Mobile Graphics):
| Map | Client | Tier | Res | fps | p50 ms | p99 ms | CPU p50/p99 ms | GPU p50/p99 ms | Draws (max) | Tris (max) |
|---|---|---|---|---|---|---|---|---|---|---|
| hd_aim | native | low | 1920x1080 | 103 | 9.56 | 12.76 | 9.42 / 12.64 | 6.88 / 9.70 | 545 | 159k |
| hd_aim | native | medium | 1920x1080 | 68 | 14.42 | 20.25 | 14.24 / 19.99 | 11.64 / 15.76 | 546 | 159k |
| hd_assault | native | low | 1920x1080 | 110 | 9.06 | 11.34 | 8.94 / 11.24 | 6.50 / 8.86 | 599 | 321k |
| hd_assault | native | medium | 1920x1080 | 82 | 12.26 | 15.96 | 12.07 / 15.72 | 9.70 / 13.49 | 600 | 321k |
| hd_bank | native | low | 1920x1080 | 105 | 9.29 | 13.01 | 9.11 / 12.80 | 6.75 / 10.61 | 636 | 410k |
| hd_bank | native | medium | 1920x1080 | 76 | 13.11 | 16.78 | 12.97 / 16.52 | 10.52 / 14.43 | 637 | 410k |
| hd_dust2 | native | low | 1920x1080 | 119 | 8.28 | 10.28 | 8.14 / 10.19 | 5.80 / 7.94 | 719 | 252k |
| hd_dust2 | native | medium | 1920x1080 | 93 | 10.71 | 13.30 | 10.50 / 13.07 | 8.07 / 10.75 | 720 | 251k |
| hd_facility | native | low | 1920x1080 | 122 | 7.99 | 11.21 | 7.83 / 10.92 | 5.36 / 8.61 | 703 | 228k |
| hd_facility | native | medium | 1920x1080 | 89 | 11.02 | 16.13 | 10.86 / 15.92 | 8.57 / 13.82 | 704 | 228k |
| hd_inferno | native | low | 1920x1080 | 104 | 9.08 | 14.82 | 8.84 / 14.69 | 6.19 / 10.78 | 750 | 325k |
| hd_inferno | native | medium | 1920x1129 | 87 | 11.00 | 17.65 | 10.72 / 17.28 | 7.84 / 12.59 | 747 | 320k |
| hd_junkflea | native | low | 1920x1080 | 114 | 8.83 | 10.66 | 8.70 / 10.55 | 6.17 / 8.11 | 658 | 290k |
| hd_junkflea | native | medium | 1920x1080 | 89 | 11.34 | 13.50 | 11.21 / 13.39 | 8.89 / 11.09 | 659 | 290k |
| hd_mirage | native | low | 1920x1129 | 117 | 8.53 | 10.05 | 8.41 / 9.95 | 5.69 / 7.18 | 717 | 292k |
| hd_mirage | native | medium | 1920x1080 | 92 | 10.55 | 16.00 | 10.33 / 15.74 | 7.81 / 12.21 | 723 | 292k |
| hd_nuke | native | low | 1920x1080 | 94 | 10.05 | 17.14 | 9.82 / 16.89 | 6.94 / 12.71 | 780 | 313k |
| hd_nuke | native | medium | 1920x1080 | 80 | 12.47 | 17.79 | 12.35 / 17.74 | 9.89 / 15.39 | 781 | 313k |
| hd_office | native | low | 1920x1080 | 109 | 9.22 | 11.80 | 9.10 / 11.74 | 6.53 / 9.23 | 675 | 254k |
| hd_office | native | medium | 1920x1080 | 77 | 13.15 | 17.38 | 13.04 / 17.26 | 10.61 / 14.98 | 676 | 254k |
After G3: browser performance
2026-11-05, same machine and method as the baseline. Each change was found by
profiling the bench rather than guessed: the CDP sampling profiler, the
long-animation-frame observer, and a log of renderer.info.programs with
timestamps.
| Change | What it fixed |
|---|---|
Glass with KHR_materials_transmission becomes ordinary blended glass at load (withoutTransmission, glb-surfaces.ts). Its opacity scales with how transmissive it was, never above what it had | three re-renders every opaque object into a transmission target for any transmissive material in view. Bank at High: 1148 → 690 draws and 822k → 412k triangles, GPU p50 4.2 → 1.6 ms. The glass stays see-through at every tier |
The operator's skinned primitives are merged by material at load (mergeSkinnedPrimitives) | the T operator loaded as 71 draws. The six range dummies were ~430 of Bank's draws |
Skinned meshes over the same bones share one Skeleton (models/skeletons.ts) | GLTFLoader gives each primitive its own skeleton. 22 bone-texture uploads a frame on Bank became 8, and 2 once off-screen bodies stop animating |
Each body's culling sphere is its bind pose, widened for any pose (presetSkinnedBounds) | left unset, three skins every vertex on the CPU to cull a body the first time it is seen: about 3 s of one frame when the dummies appeared, and when any player joined |
A body outside the view does not animate (AvatarPool.animate, after the camera is placed for the frame). Its clip time is paid back on the first frame in view | the mixer and the bone updates of bodies nobody can see. Nothing else reads their pose; hitboxes are the server's |
The map's and the scene's matrices are composed once (matrixAutoUpdate off) | 1,557 matrix products a frame on Bank, 15% of the frame's JavaScript |
| Bullet marks are one instanced draw (see bullet marks) | 256 hidden meshes walked every frame |
The finger contact solve is memoised per rig (hands.ts) | five fingertip walks of up to 24 steps each, every frame, for the same five numbers: ~5% of the frame |
Effects reuse what they retire (effects.ts free lists) | a material per particle, disposed on fade. Disposing the last user of a program deletes it, so the first tracer after a quiet spell re-linked its shader on the frame it was fired |
prewarm.ts uploads every texture and compiles every program against the target the scene is really drawn into. The map stays hidden until the link finishes, and one throwaway body per operator compiles alongside it | first-sight hitches. Compiling is not enough: a program's first draw waits for its link, in the frame. Prewarm takes ~0.3–1 s on the loading screen |
The photographed surfaces are waited for (up to 3 s) before the map's prewarm, and anything that arrives once the map is up is uploaded a few milliseconds per task (pacedUploads): the photo maps on a slow download or a live tier change, and each weapon's model, which is readied before it replaces the boxes in your hands (WeaponViewModel.setWarmup) | both arrived after prewarm and were uploaded by the first frame that drew them. On Bank: 69 photo maps in one frame (~110 ms of uploads, a 300 ms frame), then the rifle's maps on the first spawn (another ~300 ms frame) |
| PCF shadows at every tier (see the browser's graphics tier) | every lit program compiled twice per load |
Results, against the G0 browser table above (same machine, 1920x1080,
scripts/hassault_bench_browser.mjs, one run per row). "Worst frame" is the
longest single frame on the path.
| Map | Tier | fps, G0 → G3 | p99 ms, G0 → G3 | Worst frame ms | Draws (max), G0 → G3 |
|---|---|---|---|---|---|
| hd_aim | medium | 641 → 1033 | 6.5 → 2.3 | 10 | 447 → 97 |
| hd_assault | medium | 94 → 656 | 40.1 → 3.5 | 13 | 937 → 175 |
| hd_bank | medium | 100 → 616 | 27.4 → 4.0 | 10 | 1160 → 277 |
| hd_dust2 | medium | 405 → 847 | 9.1 → 2.7 | 18 | 562 → 134 |
| hd_facility | medium | 397 → 777 | 8.2 → 2.9 | 15 | 563 → 150 |
| hd_inferno | medium | 120 → 753 | 17.3 → 3.2 | 12 | 856 → 128 |
| hd_junkflea | medium | 112 → 685 | 29.6 → 3.4 | 17 | 569 → 157 |
| hd_mirage | medium | 271 → 733 | 13.7 → 3.1 | 16 | 859 → 128 |
| hd_nuke | medium | 201 → 714 | 15.3 → 3.5 | 19 | 748 → 119 |
| hd_office | medium | 115 → 771 | 25.1 → 2.9 | 14 | 837 → 120 |
| hd_aim | high | 493 → 651 | 8.6 → 5.4 | 36 | 460 → 97 |
| hd_assault | high | 95 → 537 | 18.5 → 5.2 | 17 | 937 → 175 |
| hd_bank | high | 90 → 432 | 33.4 → 7.7 | 24 | 1160 → 277 |
| hd_dust2 | high ¹ | 324 → 695 | 9.8 → 6.7 | 591 | 550 → 134 |
| hd_facility | high ¹ | 258 → 860 | 13.4 → 3.0 | 454 | 563 → 152 |
| hd_inferno | high ¹ | 110 → 873 | 32.3 → 2.6 | 191 | 856 → 128 |
| hd_junkflea | high ¹ | 207 → 692 | 15.2 → 4.0 | 55 | 569 → 157 |
| hd_mirage | high ¹ | 145 → 793 | 30.1 → 3.2 | 215 | 859 → 128 |
| hd_nuke | high ¹ | 135 → 740 | 30.6 → 3.9 | 204 | 751 → 125 |
| hd_office | high ¹ | 88 → 767 | 29.6 → 4.2 | 236 | 720 → 120 |
¹ From an earlier run of the same code without the late-texture fix, on the bench that still timed the reveal: their worst frames are that reveal, the hitch the late-texture row removed. Their steady-state columns stand.
- p99 fell 3–10× on every map. The worst maps of G0 (Assault, Bank, Office, Inferno) gained the most, because draws were their cost: 840–1160 draws became 120–280.
- Every row meets the 144 fps target (p99 ≤ 6.9 ms) except Bank at High, at 7.7 ms. Bank is still the map with the most draws.
- The worst frame on the path is now 10–36 ms, against several hundred milliseconds before.
The server half of G3 (the roster on change, sends side by side, one clock) is described under The snapshot after G3.
Not done, measured first:
- The HUD's React state stays in the panel. React is ~2% of a frame in the development build, and the frame is already a fraction of the 6.9 ms budget.
net.ts'ssamplestill builds new rows. The panel keeps them past the frame (the demo recorder,remoteRowsRef), so reusing them would corrupt recordings. G4 rewrites that function.- The first one or two frames of the map cost 50–80 ms on Bank. That is
three's first-draw bookkeeping for several hundred objects: geometry
uploads, vertex array objects, each program's uniform table.
compileAsyncdoes none of it, and the GL calls themselves are ~6 ms of it. It lands on the frame the loading screen lets go, before you can do anything; drawing the map once into a hidden target would move it, at the cost of a render pass on every load.
Known limitations
-
The native client still has the old box rig.
apps/native-fpsrenders its own operators from primitives with a procedural walk cycle; the skinned GLB and its clips are browser-only. The two share the wire, so a match mixing clients is consistent about where everybody is and inconsistent about what they look like doing it. -
Roughness is flat.
FBXLoaderdoes not support theShininessExponentchannel, so the Fuse gloss maps are dropped and everything exports atroughness: 1. The data is real and varied — gloves0-30, shoes0-255— so restoring it is the difference between matte fabric and shiny boots. It needs the build script to read the originaltextures/folder, since the maps embedded in the FBX do not survive the drop. -
The operator sits 0.05 cubes low. The model origin is not exactly at the sole, so feet sink about 5cm into the floor.
-
Reload is never triggered.
CharacterAnimator.triggerReloadexists and works, but nothing on the wire says a player started reloading —PlayerRowcarries no reload state and there is noReloadFx. Adding one is a server change, not a renderer one. -
The muzzle flash's smoke wisp is browser-only. The native view-model pass is opaque and its
Vertexcarries no alpha, so a wisp would have to be transformed into the world-space volume pass — which has a real z-order hazard against the view model's cleared depth buffer, and is not what makes the flash read correctly. The core and the halo are in both clients and pinned against each other. -
Bullet marks have one appearance.
decals.tshas atintparameter and the world knows each cell'swtex/ftex, so a mark on concrete could differ from one on metal, but nothing reads that yet — every mark is the same crater. -
Grenades are browser-only.Fixed — see Throwing in the native client. The drawing half (nades.rs) landed first, and this entry outlived it by a release: for a while the native client drew everybody else's grenades perfectly and could not produce one, which is the worse half of the original bug rather than a fix for it. -
The bots do not throw. They respect a smoke (
BotBrain._visibleasksMatchRoom.smoked) but never use one, so utility is a purely human advantage in a match against them. -
Smoke does not block a bullet's tracer, only sight. That is deliberate for the round itself, but the drawn tracer also passes through the cloud unattenuated, which reads as the smoke being thinner than it is.
-
Only duels are rated. Deathmatch, defuse and the practice modes record a result and grant XP but move no rating: a room people come and go from is not two seats facing each other. The node's old self-reported Glicko-2 row (
rating.py,ranked_mmr.py) is frozen; it is read only when the game server cannot be. -
Nothing binds keys yet. The native client's controls are fixed (WASD, space, shift, R, 1–5, 6–9 to equip a grenade, G to throw it and H to lob, right mouse to scope, Escape for the menu); the pane's rebindable
hassault.controlsmap is not read. The menu has a Controls page with sensitivity on it and nothing else, which is where rebinding will land. -
The native client has no
NoiseRing. It plays what it hears, but the browser also draws the bearings around the crosshair so headphones are not a competitive advantage — and natively they still are. -
No textures yet. Texture slots are mapped to image files by map config files (
.cfg), which are not parsed yet; surfaces are tinted by texture id instead. For the bundled maps the answer will be procedural rather than a shipped image set — generated from the texture id, so it costs no files and no license. -
Bundled maps have no map models, ladders, or ammo entities. The brush vocabulary is
room,solidandstairs, which is enough for architecture and nothing else. They are arenas, not a campaign. -
CORNERcells render as open. The type is a diagonal half-wall; treating it as fully open leaves a small gap rather than blocking a passage, which is the safer wrong answer. They are rare — 104 of 65 536 cells inac_desert. -
Map lights cast no shadows. Only the sun does, from a map baked once at load. A lamp lights the wall behind a crate as if the crate were not there. Both clients also cap how many they draw at once: the native client the 64 nearest, the browser 8.
-
A site cannot be under another floor. The server's heightfield keeps one floor per column, which is why Nuke's B is a sunken room beside hall A rather than under it, as it is in the original, and why its vent is an opening in A's wall instead of a hatch in A's floor over B.
-
Upper floors are offline-only on modelled maps. The same one-floor rule means a catwalk or a second storey over a walkable street (Mirage's apartments, Nuke's rafters) is the street's ceiling on the server. It can be stood on offline through Rapier, not in a hosted match.
-
Two official spawns leave your head in a lintel.
ac_arid(180, 122) andac_snow(48, 146) sit where the 2.2-cube body reaches into a cell with one or two cubes of headroom, socan_standis false at the spot the spawn names. AC gets away with it becauseentinmapnudges a spawning player until they fit; we have no equivalent, and the ceiling push-down instepcannot help when the floor is already the only option. Two spawns in 1741, and the effect is a shot from that exact tile reading as blocked. -
No ammo pickups. The entities are parsed but not placed, so a finite reserve on every weapon would end a long match with everyone standing around empty. The sidearm is bottomless and the rest are not, and dying refills you. Pickups are the real answer and are their own slice.
-
Sound is synthesized, and deliberately crude. Every noise is a band-passed noise burst with an envelope, because a shipped sample set is either somebody else's copyright or a large pile of files. It is enough to tell a footstep from a shot from a reload, and to tell a sniper round from a shotgun blast — which is all the mechanic needs — and it does not pretend to be a recording.
-
Noise has no vertical axis. The wire carries an
upflag (-1/0/1) and the synth turns it into a filter tilt, because WebAudio's stereo panner has no elevation. On a map with real verticality "above me" is a guess. -
The view climb from recoil is client-side. View angles are client-owned anyway — the server uses whatever arrives — so a modified client could fire without climb. Same class of concession as trusting
dt, and the same answer: this is a game you host for friends. The push on the body is server-applied and is not a concession. -
Air control is weak on purpose, and that is not for everyone. A 0.6 s air time constant means a mistimed jump cannot be corrected mid-flight. It is the mechanic AssaultCube's skill curve is built on, and it is also the thing most likely to read as unresponsive to somebody arriving from a modern shooter.
-
No water, ladder or slide physics.Water and ladders are implemented across all three cube-path ports and bound by thirteen fixture cases — see Water and ladders. Sliding is not.sprint,isSliding,slideTimeandstaminaexist as fields onplayer.ts'sPlayerState/MoveInputand ride the telemetry bus, butphysics.pysimulates none of them, so nothing on the wire can make you slide. The Rapier controller names slide-hopping among its capabilities; that is the wasm controller's own vocabulary, not a mechanic this game currently has. -
A remote player's account is not verified, only their node. In a cross-node match the host authenticates the guest's machine (Ed25519 node id, plus friendship), and the username that arrives with them is a display label tagged with that node id — never looked up, never trusted. Verifying the account itself would mean forwarding the guest's game-server JWT for the host to
resolve_token, which puts the central server in the path of every join and breaks matches on an offline LAN. The practical effect: a friend's node can show a misleading nameplate, and a stranger's cannot get in at all. -
A username is claimed per account, not reserved per person. Two people who share an account share a username; the uniqueness index is the only arbiter.
-
No password reset. An email+password account whose password is lost has no recovery path — there is no mail sender in this app, and adding one for a game login is not worth it. Sign in with GitHub or Google instead.
-
Bots do not use ladders, lifts, or teleporters, and have no notion of objectives. They steer, take cover by accident rather than on purpose, and get lost in complicated geometry. There is no navmesh.
-
Bots are host-only. A guest across the fabric cannot add or remove them: their socket is bound to a remote match, and a fabric message for reshaping someone else's roster would let a friend change a match from a pane you cannot see.
-
A guest's latency is two hops. Their input goes browser → their backend → the fabric → the host, and snapshots come back the same way. Prediction hides it for their own movement; other players are correspondingly further in the past. A direct WebRTC datachannel between the two browsers would cut a hop, and the fabric already has that transport — it is just not wired to matches yet.
-
Invites are not persisted. They live in memory with a five-minute expiry, so a backend restart forgets them. An invitation is a "now" thing; a durable one would want to be a notification, which is a different feature.
-
Pre-v10 entity attributes are unscaled. Maps older than v10 need a per-entity-type scaling table this reader does not apply; such maps are flagged
legacy_unscaled_attrs. Every official 1.3 map is v10, so nothing shipped is affected. Positions and the cube grid are correct regardless. -
AC's baked lighting (
r/g/bper cube) is computed by the engine at load time viacalclightand is not stored in the file, so it is not reproduced. Thelightentities it is computed from are drawn as real point lights instead. -
The whole map is one mesh with no culling beyond the frustum. Fine at the ~50–90k triangles a 256×256 map produces; it would need chunking before it grows.
Roadmap
- Map and asset pipeline — done, both directions: a reader for AssaultCube's maps and a writer for ours.
- Bundled maps — done: nine original
gltflevels are the whole catalog, on every platform, with real 3D geometry, their own light and sky, and a Blender generator each. AssaultCube installs are no longer read. - Three.js renderer — done: walk any map in first person.
- Netcode — done: an authoritative match server on the local backend, with
client prediction, reconciliation, and entity interpolation. JSON on the shared
/wssocket rather than a binary one, for the reasons above; the existing WebRTC datachannel transport remains the upgrade path for matches between nodes rather than between tabs. - Lobby and friends integration — done: invite a friend from the Friends roster and play in their match across the fabric, plus agent tools for hosting, inviting and spotting.
- Weapons and scoring — done: five weapons, server-authoritative hitscan with a clamped rewind to the shooter's own render instant, health, deaths, kill feed and team scores.
- Bot players — done: reactive AI at three skill levels, producing ordinary input through the ordinary queue, so a bot is a player rather than a second simulation.
- FPS mechanics with a skill curve — done: momentum-based movement with AC's friction constants, the chained-jump boost, crouching (silent, shorter, steadier, slower), the recoil push that makes shoot-jumping work, fall damage as its counterweight, and a server-resolved noise model that only ever puts a bearing and a loudness on the wire.
- A front door — done: a main menu with map selection, training, hosting with bots, the server browser, LAN discovery and the friends roster, plus an Escape menu that shares its panels and can exit back to it.
- A workspace, not a pane — done, then consolidated: three windows (game, dev tools, server) whose companions are strips, wired together by a typed event bus that parks an intent for a pane that has not mounted yet. (Two workspace presets once arranged them; they went with the tiling frame.)
- Full 3D levels —
gltfmaps are drawn from their mesh and collided against the cube grid they bake, in a match and (since G4) in Train, so the conformance fixture covers every map. - Textures and map models — the largest remaining gap between this and
something that looks like AssaultCube. Needs the
.cfgparser that maps texture slots to files. - Pickups — done: six kinds off the map's own entities, with armour as a real mechanic and an item that cannot help you left where it stands. See Items on the map.
- Per-weapon sound — done: a weapon's voice is derived from its own numbers rather than tabulated, so five weapons sound different with no assets added.
- Water and ladders — done across the cube path's three ports; see Water and ladders. The scramble state is the one AC friction constant still missing, and sliding with it.
- Game modes — done beyond deathmatch: capture the flag and bomb defuse, with a round structure and an economy. Ranked play deliberately stays deathmatch.
See also
- Module: social — friends and invites
- Module: network — the peer fabric the netcode will ride
- Module: games — the existing competitive-play platform