Skip to content
TiPSYSPiTPublic

About

CoD4 Demo Inspector / Analyzer

Resources

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

30 Commits

Folders and files

Repository files navigation

CoD4 Demo Viewer

A single-page replay viewer for Call of Duty 4: Modern Warfare (2007) demos (.dm_1, stock CoD4 and CoD4X). Drop a demo on the page and watch the match top-down in 2D or in the real map in 3D. Toggle between the two at any time: the time, the selected player and the filters stay as they are.

The demo is parsed in your browser (a Web Worker). Nothing is uploaded. The site is plain HTML, CSS and JavaScript with no build step, and it runs on GitHub Pages. three.js (r187) comes with the project in vendor/ (see vendor/README.md), so it also runs offline; nothing is loaded from other sites (the fonts, Inter and JetBrains Mono, are in assets/fonts too). The 3D maps are prebuilt once with a Python script from your own game files.

The 3D view: following a player on mp_strike

The 2D view of the same moment

More pictures: the option popovers (Layers, Heatmap, Camera, Display, Graphics, Match info), the match details, the export dialogs (2D, 3D) and smaller screens (1440 × 900: 2D, 3D; 1366 × 768: 2D, 3D; browser zoom 125 %: 2D, 3D); the UI before the redesign: 2D, 3D (the other sizes are in docs/screenshots/redesign/before/).


Run it locally

ES modules (needed for three.js) do not work from file://, so serve the folder:

cd cod4-demo
py tools/serve.py

(tools/serve.py: port 8765, no browser caching and a large listen backlog - py -m http.server 8765 works too, but on Windows it refuses connections while the 3D view loads a map in a burst, and browsers may keep old copies.)

Open http://127.0.0.1:8765/ and drop a .dm_1 file on the page (or use Open demo). Deep links work too: index.html?demo=demos/my.dm_1&view=3d&t=300&focus=name loads a demo served from the same site (?demo= takes only a path on the site, no other website), opens the 3D view at 5:00 and selects the first player whose name contains "name".

Tested with Chrome and Firefox. Any browser with WebGL 2 and ES modules should work.

If the 3D view can't start, the page says why and stays in 2D. A failed module load is checked file by file (js/app/moduleCheck.js: the browser itself only says "Failed to fetch dynamically imported module" for any missing file of the chain): the message names the file that is not on the server (HTTP 404, e.g. js/view3d/graphics.js is not on the server - imported by js/view3d/view3d.js), is not served as JavaScript, or cannot be reached (three.js: the vendor/ folder not served, or the CDN unreachable if you switched the import map to the CDN alternative noted in index.html); when every file downloads, the module that is broken (a syntax error, a missing export). The 3D view's own start errors keep their message; the full stack trace is in the browser console. With py -m http.server (no cache headers) a browser may keep old copies after an update: reload with Ctrl+F5 if the page behaves oddly.

Using it

The view fills the window; the panels float over it ("Minimal / clean", the design of cod2-demo). Every choice below is remembered in the browser.

Shared by both views

Part What it does
Top bar The file name, the 2D / 3D toggle (key V; a demo opens in 3D, in first person of the demo's own view - the recording player, or the player he followed then; the view and the camera the viewer chose are remembered instead), Match details (chart icon: scoreboard, round by round, chat, events, weapons), Export JSON (file icon), the GitHub link, Open demo
Score pill Top centre: the teams (▲ the POV's team in blue, ◆ the other in red - the shapes tell them apart without the colours), the score at the playback time, the round and its time, map and mode; while a bomb is planted its countdown (the server's setGameEndTime clock of the plant, config string 11 - else the demo's plant-to-explosion time, else 45 s, marked ≈; the 2D bomb shows it too)
Rail The icon bar on the left; each icon opens a popover (Esc or a click outside closes it). Layers: names, trails (5 s, off by default), kill lines, last known position, dropped weapons (2D), the intermission camera and hurt triggers (2D and 3D; all three off by default), grenade types (smoke / frag / flash). The view's own popovers follow (2D: Heatmap; 3D: Camera, Display, Graphics, below). Match info at the bottom: Show final score (the result and the halves), map, mode, ruleset, server, POV, length, record date, protocol (≈ marks heuristic values - hover one for how it was derived), the map data (file, triangle counts, load time) and the keyboard shortcuts
Drawer On the right, hideable (the panel icon), its two sections foldable. Teams: round, status, side, score and the players alive (bars) per team; per player the weapon in hand (its icon) and K / D up to now. Click a player to select them (highlighted in 2D and 3D; the 3D follow and first-person cameras use the selection; also with Tab and Enter). The eye shows or hides a player, the team name the team, All / None everyone, the chart icon opens the player's stats. Kill feed & bomb: kills (attacker, weapon icon, headshot, victim) and plant / defuse of the range; the entry at the playback time is highlighted and kept in view, later ones are dimmed; click one to jump to 2 s before it (that entry stays the highlighted one); separators mark each round ("R7", the knife round, the warm-up, after the match - the same rounds as the timeline; the current round's in the accent, click one for the round's start) and each halftime
Player bar At the bottom: ⏪ / ⏩ 5 s (← / →), play / pause (Space), the time (under it the round and its time), the timeline - the round labels under it (click to jump, hover for the time and score), the rounds as segments (underlined in the winner's colour once played), kills as ticks (the blue team's above, the red team's below), bomb plants (orange) and defuses (green), halftime lines; drag to scrub, strat time is skipped -, Range (whole match or one round), the speed (0.5–4×), [ ] the start / end of an export range at the current time (keys I / O; again to clear), Export video (MP4 / GIF of the 2D or the 3D view, below)
Scoreboard Hold Tab: the game's scoreboard over the view - 2D, 3D in every camera, fullscreen: per team its icon, name, count and score, per player status icon, score, kills, assists, deaths and ping as the server last sent them (only while the recorder looked at the scoreboard, so they can lag behind the playback; a player not listed yet shows the viewer's own kills and deaths), the watched player lit. Not part of the video exports.
Match details The tabs (scoreboard, round by round, chat, events, weapons) over the view. Clicking a kill or bomb event closes the overlay and jumps there
Fullscreen The button left of the drawer or key F (not in the free camera, where F flies down): only the view and its HUD. The player bar slides in while the mouse is at the bottom of the screen, on a touch and on a seek with ← / →, and goes 2 s after that; the cursor and the exit button go after 2 s at rest. Esc, F or the button leave.

Round combat statistics (js/c4/analysis/combat.js, from the kills of the live rounds with the scoreboard's credit rule): the opening duel (first blood), trades (a kill of the enemy who killed a teammate within 5 s), multikills and clutches (the last player of a team alive against one or more enemies; won when the team wins the round). The scoreboard has the columns Open (won - lost), Trades, 3K+ (hover: 2K / 3K / 4K / 5K) and Clutch (won / played) and the JSON download carries them; a round's card lists first blood, 3K+ and the clutches, its kills are marked First blood / Trade. A player the demo never shows in a round is not counted there.

Weapons tab: the numbers of every weapon of the demo from its weapon file (maps3d/_characters/viewmodels.json; for a Promod server Promod's own files): damage and falloff (Bullet_CalcDamageRange), the hit locations' multipliers, hits to kill (head / torso / leg), RPM, clip / ammo, reload, ADS time and zoom, move speed, and how the demo used it (kills, HS %, average kill distance, players seen holding it). Needs the web server (not file://).

Events tab: besides the match events also Weapon picked up, Ammo picked up, Out of ammo (the dry fire) and Out of grenades (the recorder only) - off by default.

Warnings about the demo appear as toasts under the score pill (each one can be dismissed). Below a window width of 1100 px the page becomes one column: the view, the player bar under it, the drawer below.

2D: the in-game compass image placed with the world rectangle from the demo (config string 823). It shows players with team colours, names and view cones, trails, kill lines, death crosses, grenade arcs and clouds, and the bomb (S&D). Wheel zooms, dragging pans, double-click resets. Q / E rotate the map in 90° steps (the map tools bottom right: zoom and rotation). The Heatmap popover (rail) offers positions, kills, deaths, grenade landings, smokes and shots, filtered by team, side and player. Its video export (Export video: MP4 / GIF of the 2D map, with an overlay of round, score and the kill feed) draws the same game kill feed as the 3D view, lower left.

3D: the map geometry from the game files (textures and baked lightmaps, shaded with the formulas of the game's own compiled shaders: the lightmaps' light direction with the normal maps, the sun on the sun's surfaces, reflections and the sun's highlight; the sun's shadow map lets the players cast shadows), the map's sky, the effects - the map's ambient ones (smoke, fire, dust, falling paper, rain, insects: its own effect placements) and the demo's (grenade and rocket explosions, smoke grenade clouds, flashbangs, blood, muzzle flashes, the bullets' impacts and holes on the walls (also where a bullet comes out of a wall), scorch marks, debris such as glass shards, wood splinters and the spent smoke grenade, the shell casings of every shot, the smoke trails of rockets and launched grenades, scripted effects such as the bomb and the burning barrels), played like the game's effect system at the demo time, bouncing off the world and the props, their lights lighting the world and the players (Graphics popover: Effects All / Map only / Demo only / Off; ?fx=off / ambient / demo in the URL does the same), the props (static models: trees, cars, crates, …) with their real geometry, colour maps and vertex colours (foliage's tint and shading; a tree's shadow-caster cards only cast the sun's shadow, as in the game; the ground decals fade by their vertex alpha - see docs/asset-audit.md; ?audit=1 colours every asset (also the effects' sprites) by the audit's status and names the one you click, &cam=x,y,z,yaw,pitch opens the free camera there), the map's script models (destructible cars, the gametypes' objects such as the bomb case, mirrors and corkboards the scripts spawn) in the state the demo records - an exploding car jumps, tilts and is swapped for its burnt-out model, and stands intact again after the next round start; the cars stop bullets and debris with their own collision surfaces where they stand at that moment - and the bomb sites A / B. The Props selector (Display popover) switches between Models (the game's detail level by distance: LOD 0 up to its switch distance, then the coarse LOD, none beyond the model's cull distance - XModelGetLodForDist, scaled by the view's zoom), Models (low detail) (each model's lowest LOD), see-through Boxes of the model bounds (foliage green) and Off. With the props come the map's dynamic entities - bottles, cans, cinder blocks, crates, tyres, fruit: 12,745 on 25 of the 26 maps - where the map places them. The game's client pushes them around with physics when they are shot; a demo does not record that, and on a Promod server it never happens (dynent_active 0), so they stand as its players saw them. The Match info popover shows the triangle counts and load times. Players are capsules in the team colour: standing, crouched or lying prone, with an aim line using their real pitch (Display: View lines; Player rings the team rings at the models' feet; Enemy names off names only the teammates of the watched player, as the game - view lines and rings off by default, enemy names on, remembered). Kill lines, death crosses, grenade arcs, smoke clouds and the bomb are drawn too. The kill feed (Display popover: Kill feed, on by default, remembered) is the game's obituary window, lower left in every camera, drawn on the HUD canvas in the game's font: "Killer [icon] Victim", the icon, its size and direction from the weapon files, a headshot's the headshot icon alone, suicides and world kills without a killer. The names take the team colours from the view of the player seen (his team and the other's; white without a team), with the codes of the names. The server's messages share the window, as in the game: 4 lines, 5 s each, a fifth line fading the oldest out, emptied at the start of a round (js/c4/ui/killfeed.js; docs/changes-cod2-port.md section 18 lists what comes from the engine); the feed depends only on the replay time, so pausing, seeking and the speed need nothing special. Bullet tracers (off by default) draws the game's tracers (CG_SpawnTracer / CG_DrawTracer: a 160-unit glowing beam flying at 7500 units/s from the muzzle, gone at the hit, gfx_tracer's image): for 20 % of the bullet hits the server reports (cg_tracerChance) and half the shots of the player seen in first person (cg_firstPersonTracerChance), decided per bullet so every replay shows the same ones. The weapons lying on the ground (the demo's ET_ITEM entities: dropped and left weapons, the weapon's world model where the server has it) and the grenades in flight (the weapon file's projectileModel, turning by the spin the server gives it, slowed at each bounce) are drawn with their models (js/view3d/worldWeapons.js). Cameras (C cycles):

Sound (Display popover: Game sounds and the volume - on at 30 % until changed, remembered; ?sound=off in the URL leaves it out): the game's sounds, played with the replay and heard at the camera - every player's shots, reloads, weapon raises, melee, footsteps, jumps and landings on the surface they stand on (quieter with specialty_quieter, as in the game), the bullet impacts (the demo's on players and the traced ones on the world, also where a bullet leaves a wall), bullets passing close by the camera (the game's whizby: within 140 units of a shot's path), grenade bounces and explosions by surface, and what the server plays: the bomb's plant, ticking and explosion, quick chat, burning and exploding cars (EV_SOUND_ALIAS, the entities' loop sounds), the POV's own local sounds (the announcer, the hit marker), the map's createfx loop sounds (wind, insects, machines) and the ambient track when the server sets one. Each sound is played as the game's sound system does it (SND_PlaySoundAlias): one of the alias's variants at random by its probability, its volume and pitch ranges, not started beyond its maximum distance, the distance attenuation of its falloff curve, panned left / right by the camera; in the first-person camera the followed player hears his own shots and steps (the _plr aliases). Seeking, pausing and the playback speed (0.5-4×, pitched) keep it in step; a sound that started just before the new position plays from its middle. The browsers let a page play audio only after a click, key or touch in it: the page makes its audio context in the first one (opening a demo, play, the timeline; js/app/audioUnlock.js), so the sound starts with the 3D view, without another click. A dropped file is no such gesture for the browsers - then the sound starts with the first click (the Display popover says so); nothing is reported as an error while it waits.

Camera Controls
Orbit Left drag rotates, right drag pans, wheel zooms. Click a player to select them
Free fly Drag to look, W A S D to move, R / F (or E / Q) for up / down, Shift for fast, wheel sets the speed
Follow player Travels with the selected player (or the POV's followed player). Drag to turn around them
First person The selected player's eyes with their view angles, with their weapon in hand and the crosshair (below)

First-person weapon (Graphics popover: POV weapon and Crosshair, on by default, switched at once; ?viewmodel=off, ?crosshair=off). The first-person camera shows the weapon the player holds as the game draws it: the weapon's view model (gunModel of its weapon file) in the hands of the player's character (the character script's setViewmodel: US Marines in desert and woodland kit, SAS, OpFor, Arab and the snipers' ghillie hands - the hands follow the player's body model, so the faction of the map), the attachments the weapon does not have hidden (hideTags), lit like the players. It is drawn in a pass of its own over the finished frame (never in a wall), in X-Ray, both player modes and the video export. It moves with the weapon's own view animations (tools/export/viewmodels_export.py: 715 clips), chosen from the demo at every moment - nothing is kept from frame to frame, so pause, seek and the playback speed (0.5-4×: the animations run in demo time, each shot restarts the fire animation; a shot between two frames at 4× is skipped, never doubled) need nothing special, and the motion runs at the display's frame rate:

What The recorder (the demo's own player state) Every other player
Animation (idle, fire, last shot, rechamber, reload / from empty, shotgun start - shells - end, raise / first raise / quick, put away, melee, sprint, grenade hold and throw) exact: weapAnim per snapshot (the animation the game played), started where the weapon state's timer (weaponTime) says it began and run as the game's client runs it (WeaponRunXModelAnims): no cross-fade, the idle once the running animation has ended, a weapon switch taken back blending into the idle over 0.5 s, the empty idle with an empty clip from the demo's events (shots, reloads, rechamber, raise / put away, melee swipe), started without a blend; a put away and raise of the same weapon = the quick ones of a grenade throw; sprint from the legs animation
Aiming down the sights (the adsUp animation on tag_ads, the zoom adsZoomFov over adsZoomInFrac, ADS shots) exact: fWeaponPosFrac the legs animation's walk movetype (the game's BG_IsAds for other players) at the weapon's adsTransInTime / OutTime
Sniper scope the overlay (scope_overlay_m40a3) when fully aimed, the gun hidden - as the game the same
Knife the weapon's meleeAnim with the knife (viewmodel_knife) on tag_knife_attach: exact (weapAnim 8) on every melee swipe; a knife kill without a swipe event starts it meleeDelay before the kill (knife rounds included)
Crosshair (CG_DrawCrosshair: the weapon's reticleSide image four times at the spread, at least reticleMinOfs; the grenades' reticleCenter; smaller and moved by adsAimPitch while aiming in; faded by the aim spread scale, never below 0.5; hidden fully aimed, raising, dropping, reloading, in melee and when dead; the team colours over a teammate / an enemy for weapons with crosshairColorChange - none on Promod) exact: aimSpreadScale between the stance's minimum and maximum (hipSpread*, the view height), the player state's weapFlags for the colour approximated: the stance's minimum and maximum, scaled by the speed and the recent shots (hipSpreadMoveAdd, FireAdd, decay); the colour from the player the shot line meets
Bob, landing dip the bob cycle (every 8 ms, from the recorder's own client frames), the velocity and the ground contact of the player state the distance walked and the vertical speed from the positions
Stance and movement offsets, lean, idle sway the game's formulas (BG_CalculateWeaponPosition, KisakCOD): the base position and angles follow the movement at posMoveRate / posRotRate above *MoveMinSpeed, the ADS aim pitch, the lean's roll (-2 f) and offset, the idle sway of hip / ADS amount and speed with the stance factor and holdBreathScale the same with the movement from the positions
Turn sway, gun kick, bob the game's functions (bg_weapons.cpp: the bob as angles only, the sway following the view's turn at swayLerpSpeed, the kick's pull-back, decay and caps gunMaxPitch / gunMaxYaw) with the weapon file's numbers, stepped on a fixed time grid so that a time gives one pose; the kick's random part is not in the demo - a fixed number per shot the same
Eye height, landing the view height of the player state; the landing dip of EV_LANDING (camera 150 ms down, 300 ms up; the gun a quarter) the stance's eye height followed at the game's lerp times (PM_GetViewHeightLerpTime: 200 / 400 ms)

The recorder's own view is replayed from what his client recorded for itself: the demo holds his position and view angles for every frame his client sent (125 a second), and the first-person camera, his model and his 2D marker follow those frames wherever the demo has them (97-98 % of the time he is alive; the 20 snapshots a second elsewhere, as for every other player). His samples stand at their command time, not at the snapshot's (they are 47-57 ms apart, not 50), with the lag between the two kept as it was on average - so he moves at the speed he had. View angles are kept as recorded (they were rounded to 0.1°). js/c4/analysis/build.js recorderTrack, js/app/match.js sampleInto.

Around the weapon in first person: the weapon's view flash (viewFlashEffect, none on Promod) at the view model's tag_flash and its casings (viewShellEjectEffect) from tag_brass - the bolt actions (R700, M40A3, W1200) eject theirs when the bolt is worked (EV_EJECT_BRASS), every other weapon on each shot (CG_EjectWeaponBrass); a sniper scope sways the view (CG_CalculateView_IdleAngles, still while the breath is held - Promod sets no ADS sway) and the recorder's breath is heard (weap_sniper_breathin / breathout / breathgasp); explosions shake the camera (EV_EARTHQUAKE: CG_ShakeCamera's scale, radius and duration).

The game's HUD (Display: Game HUD, on; js/view3d/hud.js, the images by tools/export/hud_export.py): in first person the minimap of Promod's HUD (the compass map turned with the view, teammates, enemies while they fire), the ammo (clip | reserve, red when low) with the weapon's name and the grenades, the hit marker (the scripts' damage_feedback HUD element of _damagefeedback.gsc - stock and Promod -, its fade, size and place as the server sends them: on every hit the recorder lands), the teammate under the crosshair and the use hint - laid out on the game's 640 × 480 screen inside the viewer's panels (the hit marker on the screen's centre, as the game). The game's red damage indicators (the direction arc, the low health overlay) are left out on purpose; the damage data stays (statistics). The ammo, hit marker, hints and the server's HUD elements (the scripts' texts, timers and images: the round's messages, Promod's banner ...) exist only for the recorder (the demo's player state). The text is in the game's fonts; the strings are the game's, with English written by hand over the German install for what the HUD shows (STRINGS_EN in hud_export.py). The minimap shows the objectives (bomb sites, the bomb, its carrier), the view the scripts' waypoints, at the screen's edge with an arrow when out of view. The game's messages stand lower left (obituaries, bomb messages; the viewer's kill feed gives way to them in first person), "You killed" / "Killed by" under the centre. The video export draws the HUD into its frames.

Promod demos (mod / fs_game / promodVersion name Promod): the numbers and effects of Promod's weapon files (promod_x-master/weapons/mp, exported into viewmodels.json as the differences) - no crosshair colours, no muzzle flashes, no ADS sway, the snipers' smaller hip spread, Promod's damage; the 49 effects Promod's fast file replaces by empty ones (promod_x-master/fx: the bullet impacts of the small calibres, the impacts on wood, metal and cloth, the mud decals, the car glass - _fx/common.json → promod.emptyFx) draw nothing; Promod's own sounds (promod_planted, promod_defused, promod_destroyed, its bomb plant / defuse sound - _sound/aliases.json → promod) play instead of the stock ones; stock demos use the stock files.

The first-person camera follows the engine (js/view3d/pov.js, all values in one place): cg_fov 80 x cg_fovScale 1.125 = 90, the horizontal fov of a 4:3 screen, so 73.74° vertical at every aspect ratio, 106.26° horizontal at 16:9; aiming multiplies the weapon's adsZoomFov by the same 1.125; the gun uses the same projection, as in the game. Without a view model for a weapon its world model is drawn ahead of the eye (none of the demos' 13 weapons needs it).

X-Ray (Display popover or key X, remembered): Off, Players - the living players behind walls, props and smoke as a translucent silhouette in the team colour with a brighter rim (the selected player in orange), in both player modes and every camera (in first person not the camera's own player); what is in sight keeps its normal look, also the visible part of a player half behind a wall - or *Players

  • names*: also every living player's name (even with Layers → Names off); a player of whom nothing is in sight gets his name on a badge in the team colour with the team's shape (▲ / ◆), and names that would overlap are moved apart. The players hidden with the eye, the team name or None stay hidden. Dead players, grenades and the bomb are not shown through walls. The technique: after the frame two passes over the players only - their visible surface marks the stencil, then their hidden parts (depth test "greater", stencil not marked) are drawn translucent; one occlusion query per player decides the badge. Cost: 0.3-0.6 ms of GPU time per frame at 1920 × 1080 with 8 players (NVIDIA T400; ~13 ms without). The 3D video export has an X-Ray option, by default the view's mode, so the video looks like the view (silhouettes, badges and the moved names).

Players: Simple / Models (Display popover, remembered; Models by default): Simple draws the capsules described above. Models draws each player's real character:

  • body and head exactly as the demo records them (client state); on the six demo maps USMC vs Arab OpFor, switching at halftime
  • animated with the animations the game itself played: every player sample of the demo carries the player's legs and torso animation (the entity's legsAnim / torsoAnim). The legs animation drives the whole body (idle, aim, walk, run, sprint, crouch, crawl, jumps and landings, mantles, stance changes, bomb plants, grenade throws ...), a torso animation (fire, reload, melee, grenade) plays over the upper body. Pistols, the RPG and grenades have their own sets, as in the game. Moving animations play at the game's rate (measured speed / the animation's move speed, clamped like the game). Changes blend like in the game: over the blend time of mp/playeranim.script, else 120 / 170 / 250 ms by movement and at least 400 ms while the stance changes
  • turned like in the game (js/view3d/controllers.js): the legs follow the view or the movement direction with the game's tolerance and swing speed, the spine and neck turn the upper body back to the view; the torso pitches with the view pitch; lean (leanf) rolls and shifts the torso; prone players tilt with the slope (fTorsoPitch / fWaistPitch)
  • deaths: the demo's corpse entities play the death animation the server chose, where the demo puts them (their trajectory: the drop with gravity, the server's movement by the animation's delta), and stay until the round ends (a body that was already lying when the recorder first saw it shows the end pose, as in the game); once the demo no longer sends a corpse, and for a kill whose corpse the demo does not hold (the death the game picks for the victim's movetype), the server's drop and movement are simulated against the map. The death animation blends in out of the pose the player had, over the game's times (BG_SetNewAnimation: 170 ms from a standing animation, 250 ms from a moving one, 400 ms out of a crouched or prone one; a running torso animation fades out beside it). The game drops a corpse's leg / torso / head turns in the frame of the death (CG_DoControllers has no case for a corpse); here they fade with the blend - the viewer's own addition, actors.easeDeaths
  • the weapon in the hands: the world model the weapon file names for the variant the demo records (worldModel .. worldModel16 by the entity's weaponModel: Promod's camouflages and the gold models; a Promod server's own weapon files for its demos), and during a knife melee the knife (worldKnifeModel on tag_inhand). The game picks each model of a player by that model's own LOD distances (DObjGetLodForDist per model), so the weapon is drawn whichever body LOD is shown, up to its own last LOD distance and not beyond (XModelGetLodForDist returns -1 there: 1,500 units for 105 of the 114 world weapon models, 1,000 - 2,000 for the others; weapons.json → lodDist, scaled by the view's zoom like the body's LODs). Only a weapon's LOD 0 is exported, so that is the one drawn up to there (tools/audit/browser suite heldweapon)
  • a player who is no longer sent (the POV's snapshots) fades out over 600 ms instead of vanishing, and fades in after a gap or a respawn (a dither: no blending, no sorting); the models are culled per pass (the view, the sun's and the lamps' shadow maps) and their textures filtered anisotropically
  • lit like in the game (js/view3d/lighting.js): the map's light grid at the player's lighting origin (a directional "ambient cube" per grid point, trilinear between the 8 points around the player, with the game's sight traces against the map's collision model for the points it flags) plus the sun where it reaches them - dark in a dark room, sunlit on a roof. Props get the same lighting per placement. Normal maps shape the light, specular maps add the sun's highlight and the reflection of the map's reflection probes (the probe the game picks: the nearest probe of the player's DPVS cell). The world reflects its probes too, and its normal maps shade the baked light with the light direction stored in the lightmaps. All of it uses the formulas of the game's own shaders, read from the compiled shaders in the fast files (tools/export/d3dshader.py). The sun's shadow map: players, the world and the props cast shadows, as in the game. The Graphics popover (rail, 3D) switches the Lighting (Game / Simple: the plain scene lights), the Sun shadows and the Effects; a change reloads the 3D map (time, selection and the other options stay) and helps slow graphics cards. Specular Lighting (the game's r_specular: the highlights of the sun and the lamps and the reflection probes of the specular maps - off, the surfaces are drawn as the game draws them with r_specular 0), POV weapon, Crosshair, World decals and Impact marks switch at once, without a reload. The specular maps (two fifths of a map's texture download, a sixth of its texture memory) are downloaded when Specular Lighting is switched on, not before (js/view3d/textures.js). The defaults: Game lighting, sun shadows on, specular lighting off, effects Demo only, POV weapon and crosshair on (js/app/defaults.js, with those of the Display popover; Reset to defaults in both popovers goes back to them). The same in the URL, which wins for that page: ?lighting=scene, ?shadows=off, ?fx=all (ambient, demo, off); ?maps=off drops the normal / specular maps. ?shadows=off drops the shadow maps (the sun's near and far partition, and the lamps' maps: the 4 lamps the game would pick, faded in and out like the game). The light grid is read as the game reads it: its full 56-colour block per grid point (a 4 × 4 × 4 volume texture), the primary light the game picks (the sun or a lamp, with the light's falloff and cone) and its visibility; the map's lamps light the world too; detail maps and the fog the server sends (config string 9; none in the sample demos)
  • a team-coloured ring at the feet

Animation and weapon follow the demo time, so seeking, pausing and the playback speed always show the same frame. Samples without animation state fall back to a choice from the movement (speed, direction, stance); without the exported animations (maps3d/_characters/anims.*) the static stance poses of Phase 1 are used. The clips a demo uses are loaded when Models is switched on.

Labels, selection, aim line, kill lines and all cameras work as in Simple; in first person the followed player's own model is hidden. A player whose model is missing, or who is not currently sent by the server, is drawn as a capsule, with a notice when models are missing.

Player models
Supported the real body + head per player and time (42 models of USMC, SAS, OpFor, Spetsnaz/OpForce), skeleton + skin weights (up to 4 bones), colour maps; the game's own legs / torso animation of every sample (286 player animations of the game: locomotion, jumps, mantles, stance changes, fire, reload, melee, grenades, bomb plants, deaths; rifle, pistol, RPG and grenade sets) with the game's blend times; the game's angle controllers (leg yaw, torso yaw / pitch, neck / head, lean, prone slope); corpses with the server's death animation; 114 world weapon models
Not supported (yet) a mounted turret's gunner (his 42 poses are exported, but no sample demo has a turret to check them against); of the effects: the elements of the class "emission" (14 elements; no spawn path found in the game's code), the game's physics for the 25 elements that use it (they bounce like the others)
Not drawn, as in the game scopes, red dots and grips on the weapons in third person: the game has no world models for them (only silenced and grenade-launcher variants, which are drawn)
Sound
Supported 1,615 shared aliases (weapons, impacts and footsteps for all 29 surface types, explosions, the announcer and quick chat of the four factions, the gametypes' sounds) + 53-77 per map; shots, weapon handling, footsteps / jumps / landings, bullet impacts (entry and exit), bullets passing by (whizby), grenade bounces and explosions, the server's sound alias events and loop sounds, the POV's local sounds, createfx loop sounds, the ambient track; random variant / volume / pitch, distance and falloff curve, restricted channels, secondary and chain aliases, master / slave ducking (the announcer and quick chat lower impacts and footsteps), random start points; the MP4 export and the WebM fallback
Not supported (yet) the effects' sound elements (8 in all maps, half of them unnamed). The game's 3D positioning is done by its sound library (Miles), whose mixing is not public: here stereo panning by the direction. The game sets no reverb in multiplayer (no reverb command in any sample demo)
Silent, as in the game the aliases that play the game's null.wav (e.g. the exits of large-calibre bullets)

Cost (NVIDIA T400): 10 animated players with weapons take ~2 ms per frame instead of ~1.2 ms with capsules; animating is ~0.07 ms per character. Switching Models on loads the models and the demo's clips in 0.5-0.8 s locally. Details, a 42-character test and the flicker check: docs/validation.md.

How a frame keeps its script time low (js/view3d/characters.js, shadows.js, lighting.js, viewmodel.js): a character's bones are not objects of the scene - three.js walked each of the about 2,000 several times a frame - but a tree of their own, and one pass per character computes the bones' matrices, both skeletons and the weapon's matrix, only when the pose or the place changed (Character.updateSkeleton; code that reads a bone outside a render calls updateWorld() first). The shadow passes that run every frame look for their casters below the few objects that hold the moving ones, the map's static objects keep their matrices, and a first-person rig that is not shown is not updated. The lit shaders declare the nine textures a frame does not change (shadow maps, the lights' table, the probes' atlas) first and in one order, so each keeps its texture unit from one material to the next, and take the lamps' and dynamic lights' values as single uniforms, which three.js uploads once a frame instead of with every material. The arithmetic is three.js' own, done once: bone matrices, hit boxes and muzzles are bit-identical to before, the pictures the same. Measured (NVIDIA T400, mp_strike / mp_citystreets, first person): 5,200 → 3,200 WebGL calls per frame; script time per frame in Chrome 5.5 → 4.2 ms / 6.5 → 5.2 ms, in Firefox about 10 → 8 ms.

What limits the frame in Firefox, measured on that card: not the script but the graphics card - the frame takes as long as the card needs to draw it, and the script runs beside the card's work on the frame before (2 ms more script left the frame at 11.4 ms; work for the card alone added one to one). Of the 11.5 ms of a first-person frame on mp_strike 6.7 ms were the main pass (2.7 ms of it the props, 1.8 ms the world), 2.8 ms the blur behind the viewer's glass panels (backdrop-filter) and 0.65 ms their shadows, 0.8 ms the HUD canvas, 0.35 ms the shadow passes. Two things follow from that (js/view3d/props.js, hudFrame.js):

  • The props are drawn only where they can be seen. A model's placements lie all over the map and three.js draws an InstancedMesh whole or not at all: two thirds of the props' triangles went to the card for places behind and beside the view. Now only the placements whose sphere touches the camera's frustum are in the instance buffers (Props.cull), in their old order. The pick is kept while the camera turns less than 0.14 rad and moves less than 40 units, and the spheres are grown by exactly that, so most frames test nothing. The static shadow maps are still rendered with every placement (uncull). tools/audit/browser suite cullcheck proves it by enumeration: for the app's frames and 3,000 random cameras every placement left out has all vertices outside one plane of the frustum (7 million placements on mp_strike, none visible).
  • The HUD canvas is touched only when its picture changes. The HUD and the kill feed draw into a stand-in that notes the calls; when the notes equal those of the picture on the canvas nothing is cleared or drawn, and the browser has no new canvas to bring to the screen (the follow camera: four frames of five). Anything that is not certain to give the same pixels - a canvas that is drawn on again, text in a font, a value read back - is drawn as before.

Measured (Firefox in a window, frames as fast as they come, mp_strike): first person 83 → 95 fps (frame 11.2 → 9.8 ms), follow camera 87 → 100 fps; Chrome: 568,000 → 394,000 triangles per frame, the card's time 8.8 → 8.3 ms.

Maps without exported data fall back to the compass image as a ground plane, and the view says so.

Video export (3D). Export video in the 3D view opens a dialog:

Option Choices
Range the timeline selection (the [ ] markers), the current round, or around a kill (any kill of the range; seconds before / after)
Format MP4 (H.264) or GIF
Resolution 1920 × 1080, 1280 × 720, 854 × 480 or the current viewport (GIF: 854 × 480, 640 × 360, 480 × 270, viewport)
Frame rate 60 / 30 / 15 fps (GIF 15 / 10)
Speed 0.5×, 1×, 2×
Quality MP4: high / medium / low bit rate; GIF: 256 colours with or without dithering, 128, 64 colours
Camera the view's current camera mode and position (orbit, free, follow, first person) with the selected player, and Simple / Models
Overlays name labels (and bomb site letters), kill feed (with the weapon icons, as in the view), bomb / kill markers in the scene, score and timer, a title (map, mode, round)
Sound the game's sounds at the export's camera (MP4; the WebM fallback too; not GIF)

Before it starts, the dialog shows the size, frame count, video length, an estimated file size and the file name (e.g. mp_strike_sd_round02_YYT-VICTORVONDOOM-kill.mp4), and warns about large GIFs. The video is rendered offline, frame by frame: every frame advances the demo time by speed / fps, the scene is rendered at the chosen size (independent of the window) and copied onto a canvas where the overlays are drawn. So the video plays smoothly at its frame rate even when the computer renders a few frames per second. Before the first frame, the export walks once over the range so that every model, animation, effect and texture it needs is loaded. While it runs, the view shows the frames as a preview, with a progress bar, the time left and Cancel. Afterwards (or on cancel) the replay is back at its time, camera, selection and display settings.

Encoding: MP4 with the browser's WebCodecs VideoEncoder (H.264) and a small MP4 writer of this project (js/c4/ui/map/mp4mux.js); GIF with this project's GIF encoder in a Web Worker (js/c4/ui/map/gifenc.js, per-frame palettes, optional Floyd-Steinberg dithering). Neither needs a library. Without H.264 in WebCodecs the browser's MediaRecorder records WebM instead, in real time; the dialog says so. The sound of an MP4 is rendered after the frames, for the camera of every frame: js/view3d/sound.js places every sound of the range in an OfflineAudioContext (48 kHz stereo, the volume and panning following the camera path), and WebCodecs AudioEncoder encodes it (AAC-LC 160 kbit/s, else Opus) into the MP4's audio track. The WebM fallback records in real time, so it takes the live sound: played frame by frame for the export's camera into the recording's audio track (Opus) instead of the speakers. GIF is silent.

Browser (tested 2026-10) MP4 (H.264) GIF Notes
Chrome 155 yes, with AAC sound yes
Firefox 158 yes, with Opus sound (no AAC encoder) yes rendering about 1.5 × slower than Chrome on the same machine
Browsers without WebCodecs H.264 (e.g. older Firefox) WebM via MediaRecorder, recorded in real time yes the WebM has no duration in its header, and a computer that renders slower than the frame rate makes it longer and uneven (docs/validation.md)
Safari not tested not tested

Speed on an NVIDIA T400: 27-55 ms per frame at 720p (Chrome), 45-85 ms in Firefox - a 36 s round at 1280 × 720, 30 fps takes 40-55 s. Test results: docs/validation.md.

Opening a demo from a link

Another website can link or redirect to the viewer so that it downloads a demo and opens it - the same as choosing the file with Open demo (js/app/demoUrl.js, wired in js/app/main.js).

https://tipsyspit.github.io/cod4-demo/?demoUrl=https%3A%2F%2Fexample.com%2Fdemos%2Fmatch.dm_1
Parameter
demoUrl required The full https:// address of the .dm_1 file, URL-encoded (encodeURIComponent)
name optional The name shown in the top bar and used for exports; default: the file name of the address
autoplay optional 1: the playback starts once the demo is loaded; default 0 (paused, as after Open demo)

The parameters work after # as well (…/cod4-demo/#demoUrl=…&autoplay=1), for redirects that drop the query; if both are there, the query's wins. They stay in the address bar, so the page can be bookmarked or shared, and Copy link (next to Open demo, shown only for a demo that came from a link) copies it. The deep-link parameters work alongside: view=2d|3d, t=<match time in s>, focus=<player name>. Without demoUrl the viewer starts as always.

Example links (the demo is a public test file of the CoD4-DM1 project):

https://tipsyspit.github.io/cod4-demo/?demoUrl=https%3A%2F%2Fraw.githubusercontent.com%2FIswenzz%2FCoD4-DM1%2Fmaster%2Ffixtures%2F1.7.dm_1
https://tipsyspit.github.io/cod4-demo/?demoUrl=https%3A%2F%2Fraw.githubusercontent.com%2FIswenzz%2FCoD4-DM1%2Fmaster%2Ffixtures%2F1.7.dm_1&name=Deathrun%20test&autoplay=1&view=2d
https://tipsyspit.github.io/cod4-demo/#demoUrl=https%3A%2F%2Fraw.githubusercontent.com%2FIswenzz%2FCoD4-DM1%2Fmaster%2Ffixtures%2F1.7.dm_1

URL encoding. demoUrl (and name) must be encoded: the demo's own ?, &, # and = would otherwise end the parameter or start the viewer's next one. encodeURIComponent does it (https:// becomes https%3A%2F%2F).

CORS - the server hosting the demo must allow it. The browser lets the viewer read a file from another site only if that site's answer carries Access-Control-Allow-Origin for https://tipsyspit.github.io (or *). Without the header the viewer shows "Download blocked by CORS" and offers Open demo instead. Examples:

  • GitHub: files in a public repository (raw.githubusercontent.com) and GitHub Pages sites send * already.
  • nginx: location ~* \.dm_1$ { add_header Access-Control-Allow-Origin "https://tipsyspit.github.io" always; }
  • Apache (.htaccess): <FilesMatch "\.dm_1$">Header set Access-Control-Allow-Origin "https://tipsyspit.github.io"</FilesMatch>
  • S3 / R2 / other buckets: a CORS rule with AllowedOrigins: https://tipsyspit.github.io, AllowedMethods: GET, HEAD.

The download sends no cookies and no referrer. A file that needs a login, or a download page (HTML) instead of the file itself, cannot be opened - the link must point at the .dm_1 file.

Checks (settings in DEMO_URL_CONFIG, js/app/demoUrl.js): https:// only, no user name / password in the address; an optional list of allowed hosts (empty: every host - then also narrow connect-src in index.html's Content-Security-Policy, which allows https: for the links); at most 200 MB (the Content-Length, and the bytes as they arrive); a 120 s timeout; the first bytes must be a CoD4 / CoD4X demo record, so a web page or an image stops at once ("Not a valid CoD4 demo (.dm_1) file."). The download shows its percentage (or a running bar when the server sends no size) and can be cancelled. The address and the name are shown as plain text only.

On the other website:

A plain link:

<a href="https://tipsyspit.github.io/cod4-demo/?demoUrl=https%3A%2F%2Fexample.com%2Fdemos%2Fmatch.dm_1"
   target="_blank" rel="noopener">Watch the demo</a>

A redirect (server side, e.g. PHP, or any HTTP 302 with this Location):

<?php
$demo = 'https://example.com/demos/' . rawurlencode($file);
header('Location: https://tipsyspit.github.io/cod4-demo/?demoUrl=' . rawurlencode($demo), true, 302);

The link built in JavaScript:

function viewerLink(demoUrl, { name, autoplay } = {}) {
  const p = new URLSearchParams({ demoUrl });            // (URLSearchParams encodes like encodeURIComponent)
  if (name) p.set('name', name);
  if (autoplay) p.set('autoplay', '1');
  return 'https://tipsyspit.github.io/cod4-demo/?' + p.toString();
}
// or by hand: 'https://tipsyspit.github.io/cod4-demo/?demoUrl=' + encodeURIComponent(demoUrl)
document.querySelector('#watch').href = viewerLink('https://example.com/demos/match.dm_1', { name: 'Final, map 2' });

What a demo contains (and does not)

A client demo is the recording player's network view. Other players only exist while the server sent them, so positions have gaps: stale players are hidden, or drawn hollow with "last known position". Health and damage are only known for the recording player. The grenade thrower is not in the demo. The weapon of a headshot kill is derived. Sabotage has no sample demo, so bomb events are shown for S&D only. Details: docs/findings.md.

Validation

The 69 sample demos of the validation run (32.8 hours, 6 maps; 67 of them are in the local demos/ today, two of those the same recording under two names) pass the validation in docs/validation.md:

  • every playing client (692) has a player model, and none is missing
  • all 1.59 million samples of living players play the game's own animation of the sample (legs / torso), whose stance matches the stance flags in 99.9 %; every firearm held has a weapon model; 11,531 of 11,532 deaths are animated, 11,348 of them with the demo's corpse entity
  • no flickering of the player models: a frame-by-frame probe over all demos (play, pause, scrubbing, all camera modes) finds no model / capsule flips, no reversing pose jumps and no degenerate skeletons; the game's angle controllers give finite angles on all 1.59 million samples
  • 0 parse failures and 0 errors
  • no duplicate kills, and round wins equal the final and server scores
  • no position outside the compass rectangle
  • 83-88 % of all live positions standing on a world or prop surface of the 3D map, 0.5-1.3 % on a script model (the cars, in the state the demo records); 6.8 % of the traced bullet hits land on a car, 4.4 % of the traced shots stop at a player's hit boxes (in the animated pose), and 28.3 % of the server's flesh impacts have a traced shot that a player stops (the recorder's own shots: 41.5 %)
  • sound: 99.9 % of 244,004 shots, all 612,909 footsteps, 96.7 % of the traced world impacts (the rest are silent in the game too) and all 48,672 server sound events play an exported alias; every audio file decodes
  • the map assets of the 6 maps against the game's data (docs/asset-audit.md, tools/audit/asset_audit.py): no box fallbacks, no mirrored placements; after the fixes (image references and image names by reference, shadow casters, vertex colours, decal alpha, normal maps, transparent texels, material handles - local shifts and other zones -, the canvas alpha, wavelet images, textures from other zones, chains placed between their neighbours, geometric twins) 100 % of the static models, 99.2 % of the world materials (the rest: the HDR portals, which draw nothing) and 99.8 % of the script models are ok - before 61 %, 89 % and 48 %; materials the game never draws (no lit or emissive technique, e.g. wc/caulk_shadow) are hidden, and the bombsites' brush models, which the parser had named after unrelated XModels (a flag floating at mp_strike's site A), are not drawn; every blend mode is drawn with the game's own factors (js/view3d/blend.js: the floodlight beams in front of mp_citystreets' mosque were black panels), and a texture that fails to load is drawn neutral grey with a warning, never black

The report also lists the known issues (map changes during a recording, recordings that start mid-match, three deaths without a killfeed entry) and the performance before and after the real props. Re-run it with tools/validate/validate.html (see the report for the command). tools/validate/export3d.html tests the 3D video export (9 cases: kill clips as MP4 and GIF, a whole round, a timeline selection, Simple and Models, follow / free / first-person cameras, the WebM fallback, cancel). Each file is decoded again and checked for length, frame count, black or flickering frames, and the replay state afterwards; the MP4's sound track is decoded too (length, loudness), and the WebM fallback's Opus track. It passes in Chrome and Firefox (sound: AAC in Chrome, Opus in Firefox).

Exporting the 3D maps (Python)

tools/export/export_maps.py reads the map fast files of a CoD4 install and writes maps3d/. It needs Python 3.10+ and Pillow with WebP (pip install pillow). There is no other dependency: the fast file parser, tools/export/cod4ff, is a generated copy of the package cod4ff of the project cod4-ff (its python/cod4ff), byte for byte, with no change of its own. It is never edited here: a parser change is made in cod4-ff and brought over.

py tools/export/vendor_cod4ff.py update [--source DIR]   copy the package and write tools/export/cod4ff/VENDORED.json
py tools/export/vendor_cod4ff.py check  [--source DIR]   the copy against its record, the record against the source

--source is the cod4-ff project folder (default: the folder cod4-ff beside this project's). The record holds the parser's version and the SHA-256 of every module, no date and no path; check ends with exit code 1 when a module of the copy was edited or when cod4-ff has moved on. The whole package is copied (38 modules), also the five that only cod4-ff's own command line uses. The exporters open a fast file through tools/export/parser_hooks.py (open_fastfile); the parser imports nothing of this project. Since cod4-ff 0.3.0 the parser reads every asset type itself - effects, animations, weapons with what they hold, the map - so that module no longer lends it this project's effect and model readers (the "hooks"), and fx_export.py and xanim.py decode what the parser's readers read (cod4ff/fx.py, cod4ff/xanim.py). With all its readers the parser reads the whole asset list of a fast file in sequence and resolves every reference exactly; the exporters use that complete pass since 25 November 2026. It gave the shipped data a little more to draw than this project's own layout of the effects had found (materials and child effects of some effects, two thunder sounds, the maps' own impact effect tables: 15 files changed, 8 sound files added; docs/findings.md lists it). The step before it (24 November, the pass of cod4-ff 0.2.0) had resolved the image names of 28 more materials in 15 map zones; the exporters had found the same textures by name or from another map, so that step changed only how those textures are reported as found (11 values in the props.json of 7 maps, 134 in the audit.json of 15 maps; no texture or model). The archives and zones of the game's language come from tools/export/game_iwd.py (GameIwd, zone_path), which applies the parser's rule (cod4ff/iwd.py: the engine's search order; of the localized archives only the chosen language's, English by default).

py tools/export/export_maps.py --game "C:/Games/Call of Duty 4"                  all mp_*.ff
py tools/export/export_maps.py --game "C:/Games/Call of Duty 4" --map mp_strike  one map
Option Meaning
--game DIR The install folder (with zone/<language>/ and main/). Usermaps in usermaps/<map>/<map>.ff (e.g. mp_backlot_x, mp_cluster) are found too, with their own .iwd
--map NAME Only this map (repeatable)
--usermaps All custom maps of usermaps/ (see "Custom maps" below)
--minimap-only Only the 2D maps: minimap.json of each map, the compass image and the registry of the custom maps
--out DIR Output folder (default maps3d/ in the project)
--tex-size N Maximum edge of the colour maps in pixels (default 1024)
--normal-tex-size N Maximum edge of the normal maps (default 512)
--map-tex-size N Maximum edge of the specular maps (default 256) - and of the normal maps when --normal-tex-size is not given, as before
--textures-only Only write the textures again that are smaller than the limits allow and than the game's image (after a change of the limits): every texture of _textures/textures.json, the first-person models' at viewmodels_export.py's limit. Nothing else is written
--force Re-encode textures that are already in the shared cache
--force-models Re-export the player and weapon models even if they are up to date (their materials). Reproducible only over all maps (then viewmodels_export.py --force): two such runs give the same files byte for byte. With --map X it writes the models X shares with other maps from X's zone, which can resolve other bones and materials than the zone a full export takes them from last
--hurt-only Only the hurt triggers, added to the entities.json of maps already exported
--share-materials Only fill the props' surfaces without a material from the same model in other maps (props.json; also done after every export)
--fx-only Only the effects: each map's fx.json, the shared _fx/common.json and the effects' debris models in _characters/ (and the textures of their materials)
--prop-collision Only the props' collision triangles of each map (props_coll.bin, the collision entry of props.json)
--script-models Only the script models of each map (entities.json → scriptModels, their models in _characters/, their collision script_coll.bin)
--characters-only Only the player models (body / head) of each map, with their hit boxes
--sounds-only Only the sounds: maps3d/_sound/aliases.json, each map's sounds.json and the audio files in maps3d/_sound/
--force-sounds Re-encode the audio files that are already in maps3d/_sound/
--sound-format F What a WAV sound of the game is written as: flac (lossless .flac, the default), adpcm (IMA ADPCM .wav, a quarter of the PCM, lossy) or hybrid (FLAC for the sounds whose ADPCM would be below --sound-snr). After a change of the format the next export writes every sound again and removes the other format's files
--sound-snr N --sound-format hybrid: the signal-to-noise ratio in dB below which a sound is written as FLAC (default 25)
--sound-jobs N Processes that encode the sounds side by side (default: one per processor)
--dyn-ents Only the dynamic entities of maps already exported (dynents.json, dynents.bin), with the textures of materials no exported file has yet
--promod DIR The source of Promod (the folder with weapons/mp, fx, soundaliases; read only) for the demos of Promod servers. Default: the folder promod_x-master beside the project folder; none: export without Promod's weapon files, effects and sounds. A folder that is not there ends the export with a message. Also an option of viewmodels_export.py and weapons_export.py
--brush-models Only the brush models with render surfaces of maps already exported (script_brushmodel entities: world.json → brushModels, their draw groups in world.bin), which the viewer places at their entities
--lightgrid-only Only the lighting data of each map: lightgrid.bin, sight.bin, probes.webp, cells.bin, lightmap<N>_secondary/_primary.webp, sky.webp, the sun and their entries in world.json
--anims-only Only the player animations and weapon models of common_mp.ff

Custom maps (usermaps)

A custom map is a folder usermaps/<map>/ in the game folder with <map>.ff (the map), <map>_load.ff and <map>.iwd (its images and sounds); whatever it does not bring itself comes from the stock files (main/*.iwd, common_mp.ff), as in the game. To add one:

  1. Put the folder into <game>/usermaps/ (e.g. mp_coastal/mp_coastal.ff + .iwd).
  2. Export it - in 3D and 2D, one command for all custom maps, no code to change:
py tools/export/export_maps.py --game "C:/Games/Call of Duty 4" --usermaps
  1. Check it - without a demo of the map: tools/validate/mapcheck.html?map=<map> shows the 3D map from above under its compass image and tests every spawn point and bomb site (on the floor of the 3D map, inside the 2D map); with demos: tools/validate/validate.html. And the assets: py tools/audit/asset_audit.py --game ... --map <map> (--all: every exported map; --data DIR: another folder than the project's maps3d).
  2. Deploy as below (push, then py tools/check_deploy.py check --url ...).

The 2D map: the export reads the map's script (maps/mp/<map>.gsc: the compass material of setupMiniMap) and entity string (the two minimap_corner entities, northyaw) and computes the rectangle the game's maps/mp/_compass.gsc sends as config string 823 - for the six maps with demos it is exactly the demos' rectangle. The compass image comes from the map's .iwd (assets/maps/<map>.png); maps the hand-written registry assets/maps/maps.js does not know are listed in the generated assets/maps/usermaps.js (display name from the map name: custom maps carry no localized name). The player models follow the demo, as on every map (the map script's teams, e.g. Russians against OpFor on mp_manorhouse, are only what the server uses). Added this way: mp_coastal (Coastal), mp_manorhouse (Manorhouse), mp_marketcenter (Marketcenter) - see docs/validation.md ("Custom maps without a demo").

Per map it writes (the .bin files gzipped, as <name>.bin.gz - see Hosting on GitHub Pages):

  • minimap.json: the 2D map - compass material and image, the world rectangle (bounds, as config string 823), the corners and northyaw it comes from
  • world.bin/json: positions, normals, vertex colours, UVs, lightmap UVs, the reflection probe of each vertex and indices, with one draw group per material and lightmap (alpha test, blend and culling come from the material state bits; normal and specular map and the reflection constants envMapParms of the material)
  • lightmap<N>.webp (a composite for the scene lighting) and the game's own lightmaps as its shaders read them: lightmap<N>_secondary.webp (RGBA, two layers: light without / with direction, the direction in alpha) and lightmap<N>_primary.webp (the sun's visibility, lossless); world.json carries the sun as the shaders get it (sunDiffuse, direction)
  • lightgrid.bin (model lighting, below), sight.bin (the brushes and terrain triangles that block the light grid's sight traces), probes.webp (the reflection probes: a row of six 64 × 64 cube faces per probe) and cells.bin (the DPVS cell tree with each cell's probes)
  • props.bin/json: static model placements plus the model geometry (LOD 0 and the lowest LOD) with one material and colour map per surface, see below; props_coll.bin: every prop model's collision triangles with their surface types (what the game's bullet traces hit: a palm tree only its trunk, grass nothing), for the 3D view's bullet and debris traces (only these: --prop-collision)
  • dynents.bin/json: the map's dynamic entities - the clip map's DynEntityDef list (clipMap_t.dynEntDefList[0]; tools/export/dynents_export.py): 12,745 on 25 of the 26 maps (12,327 clutter, 418 destructible), 142 models. The game's client gives them physics when they are shot or pushed; until then they rest at the pose the map gives them (DynEntCl_InitEntities copies the def's pose). The files have the props' layout (placements of 14 floats, model geometry, materials, a type byte per entity); a model carries every LOD of the game, and there is no probe section and no collision: the game takes an entity's lighting and reflection probe at its origin at run time, and only the client's own effect traces touch it - no player or bullet trace does (only these: --dyn-ents). No map has a brush-model entity (dynEntDefList[1]); the export prints their count. Drawn by js/view3d/props.js with the props: one InstancedMesh per model and LOD, the same cull (the suite cullcheck covers them), the same shadow layer, governed by the Props selector. What the game does differently from a static model is kept: the LOD is picked among all of the model's LODs by the distance from the eye to the entity's origin, and beyond the last LOD's distance the entity is not drawn (bottles and cans: 1,000 units); light grid and reflection probe are taken at the origin. The suite dynmatrix checks every entity of every map in the viewer's meshes. Cost: 2.8 MB on the site, 0.3 - 0.4 MB of a demo's download, and 5 - 14 % more draw calls and 1 - 8 % more triangles per frame (mp_strike first person: 381 → 399 draw calls; mp_crossfire, the most: 498 → 568)
  • sky.webp: the six faces of the map's sky cube (the GfxWorld's sky image from the .iwd)
  • fx.json: the map's effects - the createfx placements (maps/createfx/<map>_fx.gsc), the map's impact table (which effect a bullet or grenade makes on which surface) and every effect definition of the map zone, with their materials (tools/export/fx_export.py, below); the effects of common_mp.ff the demos play (weapons, impacts, gametypes) are in the shared maps3d/_fx/common.json
  • entities.json: spawns, bomb sites and the script models (script_model entities of the map's entity string: model, origin, angles, targetname, destructible_type) with each model's bounds; the models themselves (kind script) in _characters/: the map zone's own models, the script models' and those the scripts precache (precacheModel: the bomb case), 520 models, 11.7 MB; script_coll.bin: the collision triangles of every model a script entity can show (its spawn model, the destructible's other states and parts, the precached ones; 3,500-59,000 triangles, 0.1-2.2 MB per map) for the bullet and debris traces
  • sounds.json: the map's sounds (below)
  • an entry in maps3d/index.json: the map's counts and bounds - no date and no size, so that the same data gives the same file byte for byte (the sizes are in maps3d/manifest.json, which holds no date either)

Player characters. Every body_mp_* / head_mp_* XModel of a map zone is written once into the shared maps3d/_characters/:

  • LOD 0 geometry, skin indices and weights
  • the skeleton: bone names, hierarchy and the bind pose from baseMat
  • one colour map per surface

The head shares the body's bones by name, as in the game. Each body and head model also carries its hit boxes (hitBoxes: the XBoneInfo of every bone with a hit volume - the box in the bone's space, the bounding sphere), which the 3D view's traced shots hit. 42 models from the 26 maps, 12.7 MB. Models whose geometry is the same byte for byte - the camouflages of a weapon, the colours of a car, the woodland and desert bodies - share one .bin: the first of them by name keeps the file, the others' <model>.json name it in "file", which is what the viewer loads (characters_export.py share_geometry; of the 782 models of all kinds 316 name another model's file: 466 geometry files, 28.4 MB instead of 36.4 MB). A model several exporters ask for keeps the highest kind of the order script < weapon < fx < viewmodel < body / head (KIND_RANK), whichever exporter ran last. Structures and the skinning formula are in docs/findings.md.

Light grid. tools/export/light_grid.py decodes the map's GfxLightGrid (the game's model lighting) into maps3d/<map>/lightgrid.bin: per grid point (32 × 32 × 64 units) its colour set, its primary light and the game's trace flags, per colour set a six-face summary; 0.3-1.9 MB per map, 20 MB for all 26 (the sizes of the binaries here are the unpacked ones). The full 56 colours of every colour set are in lightgrid_colors.webp (lossless, 23 MB for all 26). world.json → lights: the map's primary lights (ComWorld: the sun and the lamps with position, colour, cone, radius and the falloff ramp of their light def). The light grid's sight traces need the collision model: tools/export/sight.py writes the world brushes and terrain / patch triangles that block them (CONTENTS_SOLID | 0x2000) into sight.bin, 0.1-3.8 MB per map, 41 MB for all 26. The reflection probes (probes.webp, 2.2 MB for all 26) are the cube maps the map compiler rendered, decoded from the game's RGBM format. Only these: --lightgrid-only.

Player animations and weapons come from common_mp.ff (read once per export run; only these: --anims-only):

  • tools/export/xanim.py decodes XAnimParts (quantised rotation / translation keys and the root motion). Each clip's stride (root motion per cycle) keeps the feet in step.
  • tools/export/animtree.py rebuilds the game's player anim tree from the rawfiles animtrees/multiplayer.atr and mp/playeranim.script: the index the demo sends as legsAnim / torsoAnim → animation name (303 entries). How the engine numbers the tree, and how the result was checked against the demos, is in docs/findings.md.
  • anims_export.py writes every animation of that tree that common_mp.ff holds (all 286; 44 of them are single-frame poses, 42 of those the mounted SAW gunner's; 17 of the tree's 303 entries name no animation): maps3d/_characters/anims.json (clip list, tracks, the anim tree; 1.4 MB, 0.30 MB compressed), the 37 core clips of the movement-based fallback in anims.bin (1.5 MB) and every other clip in anims/<name>.bin (233 files, 5.1 MB), loaded per demo; a clip with the same data as an earlier one (the game has some animations under two names) names that one's file (clips[...].file).
  • killicons_export.py exports the kill icons: per weapon killIcon, killIconRatio and flipKillIcon of the weapon files, the materials' images from the fast files and .iwd archives, into assets/killfeed/ and the generated table in js/c4/analysis/weapons.js - the one mapping of the feed and of every list. py tools/export/killicons_export.py --game "C:/Games/Call of Duty 4".
  • viewmodels_export.py exports the first-person view models: the weapon files (weapons/mp/* of the .iwd archives: gun model, hands, view animations, hidden attachments, knife, the ADS / kick / spread / sway / offset numbers), the gun models and base hands of common_mp.ff, the faction hands of the map zones that hold them, the character scripts' body -> hands, all 715 view animations (single-frame poses included; vanims/<name>.bin, loaded per weapon; 702 files - a clip with the same data as an earlier one names that one's file) and the sniper scope overlay -> maps3d/_characters/viewmodels.json (3.5 MB; 74 models of the kind viewmodel, 7.1 MB - the guns, the hands, the knife and the five projectile models weapon_c4, weapon_c4_mp, weapon_claymore, com_cinderblock, projectile_m203grenade; the animations 4.7 MB). A view model's bones carry the skeleton's own translation (XModel trans), to which the game adds an animation's: zero on the hands, whose animations hold the whole offset. Run it after export_maps.py: py tools/export/viewmodels_export.py --game "C:/Games/Call of Duty 4" (--force re-exports). The textures of the first-person models - colour, normal and specular maps - are written at the game's own size (--tex-size, default 2048: no image of the game is larger): the gun and the hands fill a large part of the screen at arm's length (149 textures, 74 of them larger than the other exporters' limits). It also writes the numbers of Promod's weapon files (promod_x-master/weapons/mp, read only) as the differences to the stock files ("promod"), the HUD's ammo / clip names and the grenades' projectile models. The exporters look for Promod's source in the folder promod_x-master beside the project folder; --promod DIR names another one, --promod none exports without it (export_maps.py, viewmodels_export.py, weapons_export.py).
  • hud_export.py writes the first-person HUD's images, fonts and strings (maps3d/_hud/: the minimap frame, the compass pings, the hit marker, the reticles, the hints, the grenade icons; 97 images) from the .iwd archives: py tools/export/hud_export.py --game "C:/Games/Call of Duty 4" (after viewmodels_export.py).
  • weapons_export.py exports the world weapon models like the characters and writes weapons.json (format 2): weapon → its world models by variant (worldModel .. worldModel16) and its knife (worldKnifeModel), read from the weapon files - the stock ones and, apart, Promod's. Every variant and the knife only for the weapons of the sample demos (DEMO_WEAPONS), the other weapons their plain model (114 models; 111 of them have the kind weapon, 3.1 MB with the camouflages sharing their geometry files - the two C4 models and the claymore are also the first-person projectile models and have the kind viewmodel); a model whose bone arrays the zone shares takes the skeleton of its family's exported model. lodDist: each model's last LOD distance, up to which the game draws it in a player's hands. Also run by export_maps.py; alone: py tools/export/weapons_export.py --game "C:/Games/Call of Duty 4".
  • The effects' debris models (kind fx: glass shards, wood splinters, rocks, shell casings, the spent smoke grenade and flashbang, the fruit stands' watermelon chunks ...; 35 models, 0.21 MB, and two more under the kind viewmodel) are exported the same way: every model an effect definition of common_mp.ff or of a map's fx.json draws (those only a map zone holds from that zone).

Sounds. tools/export/sound_export.py reads the sound alias lists (snd_alias_list_t) of localized_common_mp.ff (2,769 lists: weapons, impacts, footsteps, explosions, voices) and of each map zone, and the game's channel table (soundaliases/channels.def: which channels are 3D, which restricted). The sounds a replay can play are exported: the client code's tables (impacts, explosions, footsteps and landings for every surface type, gear rattle, melee), the weapons' sound fields, the aliases the gametype and map scripts name (string literals, also composed: the faction's prefix + 1mc_lastalive), the map zone's aliases the zone itself refers to, the createfx loop sounds and the ambient track - with their secondary and chain aliases. maps3d/_sound/aliases.json holds the 1,615 every map shares (0.9 MB), each map's sounds.json its own 53-77 (25-39 kB), the emitters (createLoopSound placements) and the ambient track. The audio: a loaded sound's PCM is inline in the fast file, a streamed one is sound/<dir>/<name> in the .iwd archives. WAV files are written as FLAC - lossless: the game's own samples (tools/export/flac.py; every file is decoded again by a separately written decoder, flac_check.py, and the export stops if a sample differs) - and decoded by the browser, off the main thread, at the file's own rate. Chromium divides a sample above zero by 32767 instead of 32768; sound.js measures that once with a two-sample file and corrects it, so both browsers hold exactly sample / 32768 (suite soundexact). The 1,308 sounds are 100 MB as FLAC (61 % of the 164 MB of PCM). --sound-format adpcm writes them as IMA ADPCM instead (4 bits per sample, 42 MB, decoded by sound.js itself): its encoder searches each block's codes for the least error of what the decoder reconstructs (median signal-to-noise 30 dB, the loudest shots 26 - 30 dB) - lossy all the same. MP3 files are copied (23, 60 MB). 1,331 files, 160 MB for all 26 maps, of which 55 MB are the maps' ambient tracks (MP3). A demo fetches a sound shortly before it is first played, not at load: the sounds a match on mp_strike can play are 148 files, 9.4 MB. How the alias lists are found and their shared parts resolved: docs/findings.md.

Props (static models). tools/export/xmodel.py reads the XModels of the map zone, and of common_mp.ff for models the map places but does not store. That covers surfaces, LODs, vertices (position, normal, UV) and triangles. Models that share vertex or index buffers, and material handles that point back at a material loaded earlier, are resolved by rebuilding the fast file's memory blocks (see docs/findings.md). Each model's geometry is stored once and drawn with THREE.InstancedMesh for all its placements.

Supported Not supported
Geometry LOD 0 + lowest LOD, rigid and skinned surfaces (static props are in bind pose) animated models, bones
Materials colour, normal and specular map (WebP, shared with the world), alpha test, blending, culling; lit like the game's static models (light grid at the centre of each placement + sun) with the reflection probe of each placement
Fallback a model that cannot be read is drawn as a box and listed in the export summary (props drawn as boxes: …) and in index.json → propFallback

On all 26 maps every placed model gets real geometry (mp_creek's last one too: a shrub group whose name the zone stores as a reference to an earlier string) and every prop surface has its material (docs/asset-audit.md, section 18). Cost on the six maps with demos: +3.1 to +5.8 MB of download (props.bin/json), 70-120 ms to load and build locally, and 0.6-1.3 million triangles in under 1.3 ms per frame on an NVIDIA T400. The low detail option halves the triangles. Full table: docs/validation.md. Textures are shared by all maps in maps3d/_textures/. Mp_strike takes about 14 s and 11 MB (26 MB unpacked) plus textures. All 26 maps of a German retail install (21 stock maps plus the usermaps mp_backlot_x, mp_cluster, mp_coastal, mp_manorhouse and mp_marketcenter) take about 12 minutes (twice that the first time, when the textures are encoded; the sounds add about 12 minutes the first time, for the FLAC encoding in 24 processes, the dynamic entities about 11). That is about 617 MB in total with the maps' binaries stored gzipped (588 MB of geometry, collision and light grid as 176 MB; 1,036 MB without - mp_coastal alone has 3.1 million prop triangles at LOD 0), about three fifths of the 1 GB a GitHub Pages site may have; of it 126 MB are the 3,919 shared textures of world, props, players and weapons and 161 MB the sounds. The format is described at the top of the script and in docs/findings.md.

Texture sizes. A texture is never larger than the game's image (the size the game shows at its highest texture setting, r_picmip 0; at most 2048 px), and at most:

Kind Limit (longer edge) Option Why
Colour maps 1024 px --tex-size 62 of the 1,924 are larger in the game (vehicles, a few walls, the player bodies): in first-person frames of three maps 0.3 - 1.6 % of the screen showed one of them closer than the 1024 px resolve
Normal maps 512 px --normal-tex-size at 256 px 59 - 70 % of the screen showed a normal map at least half a mip level coarser than the game's, at 512 px 1 - 5 % (a wall's normal map has 4 texels per unit in the game: 512 px on 128 units)
Specular maps 256 px --map-tex-size loaded only with Specular Lighting on; as WebP they take eight times the bytes of a normal map of the same size (512 px: + 62 MB on the site, + 14 MB per map)
First-person models the game's size viewmodels_export.py --tex-size (2048) all three kinds: the gun and the hands are the closest surfaces of every first-person frame

The files are shared, so the largest need wins: an exporter that asks for a texture that is smaller than its limit and than the game's image writes it again (the view models after the world weapons), a larger one stays; the first-person size is noted in the texture's record (textures.json → view) and holds for --force of every exporter. After a change of the limits --textures-only updates all textures at once (a minute). The 3D view uploads the normal maps with two channels (lighting.js twoChannels: half their memory); a load of mp_strike has 718 textures, 595 MiB on the graphics card without the specular maps (computed from the sizes: 4 bytes a texel, 2 for a normal map, with mip levels), 714 MiB with them.

A demo's map is matched by its raw name (mp_backlot_x uses its own export). Unknown Promod or league variants fall back to the stock map through the aliases in assets/maps/maps.js.

Ambient effects. tools/export/fx_export.py reads the map's createfx placements and the FX definitions (FxEffectDef / FxElemDef: spawn timing, life, velocity and visual state curves, atlas, materials) of the map zone and common_mp.ff, resolving the materials the definitions refer to by reconstructing the fast file's memory block. js/view3d/fx.js evaluates the game's effect update in closed form: every element alive at the demo time, with the game's random table, spawn times, velocity integration, gravity, colour / size / rotation curves, atlas frames, distance fade and light, drawn as the game's sprites. 952 placements of 82 different effects on the 21 stock maps; the five usermaps have none. The same system plays what the demo records: the parser keeps every detonation (with the surface it hit and its normal), every bullet impact the demo holds and every scripted effect, and the 3D view picks the effect the game would (the weapon's explosion effect and the impact table's effect for the surface, the weapon's muzzle flash at its tag_flash). The impacts of the bullets on the world are not in the demo - every client traces the bullets itself - so the 3D view traces them as the game's client does (js/view3d/trace.js): from the frame the client shows when the shot arrives (the snapshot before), seeded with the recorder's command time, for other players from the weapon's tag_flash in the shooter's animated pose along its view angles with the spread the client guesses (stance, speed, aiming down the sights by the legs animation), for the recorder's own shots from its eye with the spread of its player state - against the world's triangles with their surface types - and plays the impact table's effect where they hit (?shots=server in the URL ends a shot at the server's flesh hit of that shooter instead: no wall impacts behind a victim the server says was hit - not what the game's client draws). A traced bullet stops at a living player - at the game's hit boxes of the player's body and head models (every bone's box, in the player's animated pose at the shot: the same animations and angle controllers as the drawn model, also with Players: Simple) - and leaves nothing there - the server's flesh impact in the demo is drawn instead - then goes on through the body as the flesh depth allows, as the game's client does it (MASK_SHOT, sv_clientSideBullets). Marks (bullet holes, scorch marks: the effects' decal elements) stay on the surfaces until the round ends. Bullets pass through walls as the game's client lets them (FireBulletPenetrate: the game's depth table per weapon and surface, the wall's depth up to its inner face) and leave the exit effects. The props stop bullets and debris with their own collision surfaces (XModelCollSurf_s: the triangles the game's traces hit, with their surface types). Colliding elements are simulated once from their spawn (FX_CollisionResponse: traced every 50 ms, mirrored and slowed at each hit, at rest on a floor, an effect on impact such as the flashbang's smoke); elements with an emitted effect spawn it along their path (FX_ProcessEmitting: the dust puffs of brick and rock impacts); the model elements draw their debris models, lit by the light grid. Every shot ejects the weapon's casing at its tag_brass (worldShellEjectEffect; the game spawns them only within 100 units of the camera). Rockets and launched grenades carry their weapon's trail effect along their path (projTrailEffect on the projectile, stopped at the detonation), with the trail elements drawn as the game's ribbons (FX_DrawTrail). The effects' lights become up to 4 dynamic lights of the world and the models. Details: docs/findings.md.

Possible next steps

  • Two lamp materials of mp_manorhouse (mc/mtl_bi_command_center_panel_1_lit, mc/mtl_lights_tinhathood_on): their colour map is an image reference no rule places; drawn in the material's colour.
  • Water (wc/*water*, the game's own water shader) is drawn as a flat translucent colour.
  • The props use LOD 0 and the coarsest LOD; the game's LODs in between are not exported.
  • Promod sets its clients' r_lodbiasrigid and r_lodbiasskinned to -1000 (promod/client.gsc): on a Promod server the game keeps every LOD of a model 1,000 units longer and culls it 1,000 units later. The viewer applies the stock rule (bias 0) to props, dynamic entities, players and their weapons; Props.lodBias is there to try the other.
  • The props' LOD distance is measured to the bounds' centre with the zoom factor of a 65 degree view at 4:3; the game measures to the placement's origin with tanHalfFovY x 2.118673 (r_add_staticmodel.cpp, r_scene.cpp R_UpdateLodParms) - the dynamic entities use the game's.
  • The dynamic entities cost one draw call per model, LOD and surface in view; drawn in one batch per material they would cost about a third of that (the per-entity lighting would have to come from a texture lookup).
  • A weapon lying on the ground is drawn at any distance; the game stops at the model's last LOD distance.
  • Normal maps are lossy WebP: at 512 px the encoding costs about as much detail as halving the size would. One grey image with x and y side by side has less than half the error for about a quarter more bytes (not built).

Hosting on GitHub Pages

  1. Before every push run
py tools/check_deploy.py manifest

It writes maps3d/manifest.json (size and hash of every data file; an export refreshes it too), packs a plain .bin a tool left in a map folder (the maps' binaries are stored gzipped, below) and verifies every packed file, and runs tools/check_imports.py: the module graph of index.html and the test and dev pages under tools/ - every import resolves to a file with exactly that upper / lower case (Windows does not care, GitHub Pages does), every imported name is exported, the import map is valid and comes first, every <script src> exists. Push every file it names: a module missing on the site breaks the 3D view. Check another copy (e.g. your git checkout) with py tools/check_imports.py --root <folder>. 2. Create a repository and push this folder (its root becomes the site root). Included: .nojekyll (without it Jekyll would drop maps3d/_textures/ and the other _ folders) and .gitattributes (text with LF, all data types binary - never converted). Do not use Git LFS for the data: Pages would serve the LFS pointer files instead of the data. 3. Settings → Pages → Build and deployment: either Deploy from a branch (main, / (root)) or GitHub Actions with the "Static HTML" workflow (it uploads the repository as it is). 4. Wait until the deployment has finished (the Actions tab), then check the live site against the local files:

py tools/check_deploy.py check --url https://<user>.github.io/<repo>/

It downloads every file index.html needs (check_imports.py --url: the modules, the classic scripts, the stylesheet and its fonts - a missing one is named with its HTTP status), compares the manifests, every data file's size and the content of the code, the JSON headers and the maps' binaries (--full: every file, ~617 MB; --map mp_strike: one map and the shared folders), and names every file that is missing, different, an HTML page (a 404) or an LFS pointer. 5. Open https://<user>.github.io/<repo>/.

Content-Security-Policy (meta tag in index.html): only the site's own files, except connect-src https: - the downloads of demo links (above); blob: is for the workers (the parser's, the GIF encoder's and the texture decoder's - all three are built from a Blob, no worker file is loaded: worker-src blob:) and for the images the texture decoder hands over (img-src); data: is for one SVG in the stylesheet. There is no media-src: the viewer has no audio or video element (the sounds are fetched and decoded - connect-src). Its sha256-… is the hash of the inline import map: after changing the import map (the CDN alternative also needs its host in script-src) compute the new hash, or the page stops loading three.js.

Stored settings (js/app/defaults.js, js/app/settings.js): the viewer remembers its settings in the browser's localStorage, all under the prefix cod4demo.: the Display options (cod4demo.players, .props, .xray, .viewLines, .rings, .enemyNames, .killfeed, .hud, .items, .casings, .tracers, .sound, .sound.volume), the Graphics choices as one JSON object (.graphics), the camera (.camera2), the 2D / 3D choice (.view2), the drawer and its sections (.drawer, .drawer.teams, .drawer.feed), the final score's switch (.showFinalScore), the 2D map's heatmap settings and rotation per map (.heatmap, .mapRotation.<map>) and the settings' version (.settingsVersion). Until November 2026 most of these keys had the prefix cod4demo3d.; js/app/settings.js moves them to the new names once, at the page's start (a key that exists under both names keeps the new value; the version moves with them, so no setting is reset). Nothing is stored in sessionStorage, IndexedDB or the Cache API. With the storage blocked the viewer works with the defaults. The browser keeps localStorage per origin (https://<user>.github.io), not per path: another page of the same origin that uses a key of the same name shares it with the viewer (every value is checked when it is read; an unusable one counts as the default).

Loading (js/view3d/data.js): every data file is requested as file?v=<hash> from the manifest, so a header (world.json) and its binary (world.bin) always come in the same version, never one from the browser's or the CDN's cache (Pages caches for 10 minutes) and one new. Pages serves the files gzip-compressed: Content-Length is then the compressed size, so the binaries are read as a stream and checked against the size the manifest or their header gives (a loader that sized its buffer from Content-Length cut world.bin short on Pages: "Invalid typed array length: 932169"). A file that is missing (HTTP 404), an HTML page or an LFS pointer, or has another length is reported with its name, e.g. mp_strike/world.bin: expected 13,018,860 bytes, received 3,599,463 (cut short or an old version), and logged to the console with URL, status, type, size and SHA-256; the view falls back to the compass image as the ground.

The maps' binaries are stored gzipped: maps3d/<map>/world.bin.gz, props.bin.gz, props_coll.bin.gz, sight.bin.gz, lightgrid.bin.gz, script_coll.bin.gz, cells.bin.gz, dynents.bin.gz (tools/export/datafile.py; the shared folders stay as they are). Pages compressed a .bin on the way to the browser anyway, so the download is the same, but the files take a third of the space on the site. The JSON headers keep the plain names ("file": "world.bin"); data.js finds the .gz in the manifest, checks its size, unpacks it in the browser (DecompressionStream: Chrome 80, Firefox 113, Safari 16.4) and checks the unpacked length against the header. The export and the audit tools read and write through datafile.py; py tools/export/datafile.py unpack gives the plain files back, pack packs them again, check verifies them.

What the 3D view asks for, and when: the view's code (three.js and its modules) is requested as soon as the page is loaded when the next demo will open in 3D, not after a demo is analysed (js/app/main.js preload3d). The parser names the demo's map a moment into the analysis, and the map's files are requested then (view3d.js prefetch3d): world.json, and with it at once the world's binary, the light grid, the reflection probes, the props, the entities, the sky, the sounds' and the effects' lists (mapLoader.js fetchMapFiles) - they used to be fetched one after the other, after the analysis. The textures go through one queue (js/view3d/textures.js): a limited number of requests at a time instead of about 1,000 at once, a failed one first in line again, and a file that several textures ask for is requested once.

Where the browser can do it, the textures are decoded off the main thread (js/view3d/textures.js): a worker fetches each file and decodes it (createImageBitmap), the page uploads the ready bitmap - a few per frame once the map's first frame is drawn - and then swaps the texture's image for an <img> of the same bytes and closes the bitmap, so the memory and a later upload (a restored WebGL context, the next demo's renderer) are as with a plain image. Whether the browser qualifies is tested once when the module loads, not taken from its name: the worker's bitmaps must give exactly the texels of an <img> (two small test images with alpha, both orientations) and must be decoded while the main thread is busy. Chrome passes. Firefox does not - it decodes a bitmap on the main thread also when a worker asks for it - and loads its textures as before, as does every texture requested before the test has answered. Measured (Chrome, mp_strike, NVIDIA T400): main-thread time in texture uploads while the map loads 1.1 s → 0.16 s, the longest single upload 92 → 28 ms; on a 50 Mbit/s line the frames longer than 33 ms in the 10 s after the first frame 57 → 21. The cost: 40 - 70 MB more memory at the peak of a load and about 20 MB more afterwards. The texels are the same (every WebP of maps3d/ read back from the GPU in both orientations: 0 differences). The tools that wait for a map to be complete ask loadingCount() of that module - the worker's requests are not in the page's network log (tools/bench/bench.py, quality.py).

demos/ and .claude/ are in .gitignore. maps3d/ is committed so the published site shows the real maps. It is extracted game content: read maps3d/NOTICE.md, and leave the folder out (add /maps3d/ to .gitignore) if you do not want to publish it. The site then falls back to the 2D image as the ground. Individual files stay far below GitHub's 100 MB limit (the largest is an ambient sound, 8.8 MB; the largest packed binary mp_manorhouse's world.bin.gz, 6.1 MB - 23 MB unpacked). The whole site is about 0.64 GB (maps3d 617 MB, 161 MB of it the sounds), of the 1 GB a Pages site may have.

Layout

index.html               the page (classic scripts for the parser, ES modules for the app)
favicon.ico              the tab icon
css/styles.css           the page's stylesheet: design tokens (:root - colours, team and timeline
                         colours, type, spacing, radii, shadows, z-index), controls, then one
                         section per component
css/turntable.css        the stylesheet of the models debug view (?debug=models), loaded by it
assets/fonts/            Inter, JetBrains Mono (woff2) and their licences (OFL)
assets/maps/             compass images + calibration: maps.js (written by hand), usermaps.js (the custom
                         maps, written by the export)
assets/killfeed/         the kill icons (tools/export/killicons_export.py)
vendor/three/            three.js r187 (three.module.js + three.core.js, OrbitControls) - see vendor/README.md
maps3d/                  exported maps (see above); NOTICE.md: whose content they are
js/c4/                   the parser (core, parser, common), the analysis (analysis: DemoData) and UI pieces (ui:
                         scoreboard, rounds, chat, events, 2D renderer, heatmap, video export) of the 2D viewer
                         this project began as; in
                         analysis/collect.js + build.js also what the 3D view needs: player models,
                         animation state per sample, corpses, the recorder's weapon state (psWeapon) and
                         every player's weapon events (weapEvents), the HUD state (psHud, psAmmo), the
                         dropped weapons (items), earthquakes, the recorder's 125 Hz track;
                         analysis/combat.js: the round combat statistics; ui/weapons.js: the Weapons tab
js/c4/ui/killfeed.js     the game's kill feed and message windows: 3D view (HUD canvas), both video exports
                         (canvas), with C4.weapons.killIcons - the drawer's icon mapping
js/app/main.js           file loading (worker), app facade, 2D/3D toggle, the rail and its
                         popovers, the drawer, details overlay, keys
js/app/match.js          Match: DemoData prepared for playback - positions at time t, trails,
                         grenade arcs, bomb, rounds (shared by both views)
js/app/replay.js         Replay: the one playback state (time, range, selection, filters),
                         player bar, timeline, Layers popover, drawer (teams, kill feed)
js/app/defaults.js       the defaults of the Display / Graphics options and their storage keys
js/app/settings.js       the remembered settings' migration: the move from the old key prefix (cod4demo3d.),
                         the version steps (drops the keys whose meaning changed)
js/app/demoUrl.js        a demo opened from a link (?demoUrl=): the checks, the download, its errors
js/app/moduleCheck.js    why a module did not load: the file of the chain that is missing,
                         not JavaScript or unreachable, else the broken module
js/app/audioUnlock.js    the game sounds' audio context, made in the page's first click / key
js/app/retry.js          loading with retries (a request the browser or the server dropped)
js/app/infoHint.js       the hints over a view: the technical details, the controls hint
js/app/scoresOverlay.js  the game's scoreboard while Tab is held
js/view2d/view2d.js      2D view
js/view3d/               view3d (scene, loop, Camera / Display / Graphics popovers), graphics
                         (the Graphics settings), xray (players through walls: stencil +
                         silhouette passes, label declutter), exportVideo3d (the 3D video export:
                         dialog, offline rendering, overlays, encoders), data (every file of maps3d:
                         cache-busting by the manifest, size checks, the gzipped binaries), mapLoader
                         (maps3d -> three.js),
                         textures (the texture loader: a request queue, the specular maps held back),
                         props (instanced prop models / boxes, the dynamic entities), actors (players:
                         capsules or models, corpses, weapons), characters (skinned player models, stance
                         poses, animation clips), animator (which clip a player plays at t and
                         the game's blend rules), controllers (the game's leg / torso / head
                         angles, lean, prone slope), lighting (the light grid with its sight
                         traces, reflection probes, normal / specular maps: the game's lighting
                         of players and props, the world's reflections), shadows (the sun's
                         shadow map), sky (the sky cube), fx (the effects: the map's and the
                         demo's, the game's effect system), trace (rays against the render world:
                         the bullets the clients trace themselves), hitboxes (the players' hit boxes
                         for the traced shots), effects (markers, grenades), mapMarks (the
                         intermission camera and the hurt triggers), cameras,
                         scriptModels (the map's script models in the demo's states), sound (the
                         game's sounds: live with Web Audio, offline for the MP4 export),
                         viewmodel (the first-person weapon: rig, animation blending, knife,
                         crosshair, scope, ADS zoom), viewanim (its state at a demo time from
                         the player state or the events), pov (the first-person view's dvars - cg_fov,
                         cg_fovScale, cg_gun_x / y / z - and the engine's fov), hud (the game's HUD in
                         first person), ammo (the HUD's ammo as the game keeps it), hudtext (the game's
                         fonts and strings), hudConfig (the HUD's dvars), hudFrame (the HUD canvas is
                         drawn only when its picture changes), tracers (the bullet tracers),
                         worldWeapons (dropped weapons, grenades in flight), audit
                         (?audit=1: the assets coloured by the asset audit's status), matinfo
                         (?matinfo=1: hover / click names the material and textures of a surface),
                         turntable (?debug=models: every character and weapon model), blend (the
                         game's blend factors for every renderer)
tools/serve.py           the dev server: no browser caching, a large listen backlog
tools/check_deploy.py    maps3d/manifest.json (sizes, hashes) and the check of the deployed site
tools/check_imports.py   the module graph: missing files, case, exports, import map (--url: the site)
tools/shoot.py           headless Chrome screenshots and test runs (Python stdlib only)
tools/export/            export_maps.py, xmodel.py + props_export.py (prop models),
                         datafile.py (the maps' binaries stored gzipped: pack / unpack / check),
                         cod4ff (the fast file parser: a generated copy of cod4-ff's package, never
                         edited here), vendor_cod4ff.py (makes and checks that copy), parser_hooks.py
                         (how the exporters open a fast file: the readers of the parser's
                         sequential pass), game_iwd.py
                         (the .iwd archives and zones of one language),
                         characters_export.py (player models with skeleton and skin weights),
                         xanim.py + animtree.py + anims_export.py (player animations and the
                         game's anim tree), weapons_export.py, viewmodels_export.py (the
                         first-person view models, hands and view animations), hud_export.py (the HUD's
                         images, fonts and strings), killicons_export.py (the kill icons),
                         minimap_export.py (the 2D map: compass image and world rectangle),
                         light_grid.py (model lighting),
                         sight.py (the collision the light grid's sight traces test),
                         d3dshader.py (lists / disassembles the game's compiled shaders),
                         fx_export.py (effects: createfx placements, FX definitions, the impact
                         table, the weapons' effects), sound_export.py (sound aliases and audio),
                         flac.py + flac_check.py (the FLAC encoder and the decoder that checks it),
                         dynents_export.py (the maps' dynamic entities),
                         image_refs.py (the images materials name by reference)
tools/audit/browser/     the browser checks (run.mjs, scenarios/: see Testing)
tools/audit/             read-only audits (see Testing; results in tools/audit/out/, not in git):
                         asset_audit.py (the map assets against the game's data -> docs/asset-audit.md,
                         maps3d/<map>/audit.json), site_audit.py (the site for GitHub Pages), map_audit.py
                         (every map's files and entities), material_audit.py + texture_audit.py (materials
                         and textures of every map -> docs/texture-audit.md), model_inventory.mjs +
                         model_audit.py (player models and weapons -> docs/models-report.md),
                         demo_audit.mjs (the parser over demos/), ammo_audit.mjs (the HUD's ammo),
                         marks_scan.py (do the impact marks lie on a surface), leftovers.py (code left
                         from CoD2), load_c4.mjs (the parser in Node, for the .mjs audits)
tools/bench/             the benchmark, the quality reference and the A/B runs (its README; see Testing)
tools/characters/        preview.html: stance poses / animation clips of a character (dev tool)
tools/probes/            orient.html: how the reflection probe faces map to world directions
                         (dev tool)
tools/validate/          validate.html + validate.js: every demo through the parser + plausibility,
                         map-alignment, player-model and animation checks -> docs/validation.md;
                         export3d.html: the 3D video export's test cases; start3d.html: every demo
                         starts in 3D; mapcheck.html: a map without a demo (spawns and bomb sites on the
                         3D and the 2D map); redesign_shots.py: the screenshots of docs/screenshots/redesign
docs/findings.md         how demos and maps are read
docs/validation.md       validation report over all sample demos (images: docs/validation/)
docs/asset-audit.md      the map assets (trees, bushes, decals ...): root causes and fixes
docs/                    the other reports are records of their date: asset-audit-3d.md, texture-audit.md,
                         models-report.md + changes-models.md, hud-compass-report.md,
                         performance-analysis.md + performance-report.md + changes-perf.md,
                         changes-cod2-port.md (the change log of the features taken from cod2-demo),
                         prelaunch-report.md, ux-suggestions.md
docs/screenshots/        before / after screenshots of the asset audit; redesign/ (the UI, linked at the top),
                         brand/ (icon and drop zone), viewmodel/ (the first-person weapon)

Testing

The browser checks run headless in Chrome and Firefox against the dev server, with the local demos in demos/:

py tools/serve.py
node tools/audit/browser/run.mjs

A suite by name (smoke, badfiles, hud, scores, killfeed, storagekeys, pov, timebar, notes, steps, track, vmanim, deaths, touch, export, extras, polish - these run when no suite is named - and on request fxhash, cullcheck, dynmatrix, heldweapon, soundload, soundmix, soundexact, perf, leak), --browsers chrome,firefox (the default: both; some suites run in Chrome only), --base <the server's address>, --demos a.dm_1,b.dm_1. Each run prints one line; details in tools/audit/out/browser/. Exit code 1 when a check fails or the page logged an error, a warning or a failed request. killfeed checks the defaults of every Display and Graphics option and Reset to defaults besides the kill feed itself; storagekeys proves the stored settings' move from the old key prefix (the values, the version, a full and a blocked storage, every setting kept over a page load; 3 to 4 minutes per browser). fxhash prints the effects' output as hashes: compare two runs after a change to fx.js. cullcheck proves the props' culling for a demo's map: every placement left out of a frame lies outside the camera's frustum, for the app's own frames and for 3,000 random cameras, the dynamic entities included (run it after a change to props.js). dynmatrix builds every map's dynamic entities and checks that each is in the viewer's meshes exactly once (no demo needed). heldweapon checks that a player's weapon is drawn at every body LOD up to its own last LOD distance. soundexact compares the decoded sound files with reference samples, sample for sample (--args '{"list":"<url>"}', see the scenario); soundload lists what a demo fetches and decodes for its sounds; soundmix prints the MP4 export's sound mix as hashes.

Read-only audits of the data, without a browser:

node tools/audit/demo_audit.mjs
node tools/audit/ammo_audit.mjs

The first-person HUD's ammo (js/view3d/ammo.js) over every demo: per snapshot of the recording player the clip never over the clip size, every drop of the clip a shot, every reload taken from the reserve, valid numbers right after a switch; each violation with time and weapon (tools/audit/out/ammo_audit.json).

py tools/audit/site_audit.py
py tools/audit/map_audit.py
py tools/audit/leftovers.py

demo_audit.mjs runs the parser and analysis over demos/ and checks each demo's consistency, site_audit.py the site for GitHub Pages (manifest, exact case of references, sizes), map_audit.py every map's files and entities, leftovers.py looks for code left from CoD2.

Player models and weapons: model_inventory.mjs lists what the demos use (bodies, heads, their combinations, weapons with their camouflage variants), model_audit.py checks every one of those models - and with --raw <folder> the game's own combinations (from the character scripts of common_mp.ff as the fast file extractor cod4-ff writes them, <its output>/common_mp/raw): surfaces and LODs, materials and colour maps, skin weights, normals, the head's bones against the body's, weapons' world models and tags. --poses adds a check in the browser: every head on its body in ten game animations, the helmet / cap bone against its place on the head. Report: tools/audit/out/model-audit.md.

node tools/audit/model_inventory.mjs
py tools/audit/model_audit.py --poses

To look at the models themselves: index.html?debug=models (off by default) shows every character combination and every world weapon model on a turntable, with its model, material and texture names - a surface without a colour map in red - in a game animation, a stance or the bind pose, at each LOD (&zoom=head, &filter=usmc, &list=weapons, &pose=bind, &lod=1, &page=2; &time=<s> the moment of the pose's animation, &angle=<degrees> a fixed turn; &body=<model>&head=<model> one more combination; with &demo= the demo's own combinations too).

Performance and quality checks

tools/bench/ (its README has the details): a benchmark of page load, demo analysis, demo load, the 2D and 3D views, memory and a 4x slower CPU (bench.py), a quality reference - the JSON exports with hashes of all data, 2D and 3D pictures at fixed times and cameras, the panels' text - and its comparison (quality.py), the parser over every local demo (corpus.py), and A/B runs of two versions back to back (ab.py, abframes.py: the machine's own speed varies too much between separate runs). The tools drive Chrome; corpus.py, ab.py and abframes.py take the folder of the other version as --a <folder>.

py tools/bench/check.py <tag> --bench 3d

(check.py compares with the results of the tag baseline, or --base <tag>: run bench.py run and quality.py capture for that tag first.)

The performance work of November 2026 and its numbers: docs/performance-analysis.md, docs/changes-perf.md, docs/performance-report.md.

Credits and licence

GPL-3.0 (see LICENSE). The demo parser, analysis and 2D UI come from the 2D viewer this project began as (the first cod4-demo), whose snapshot decoding follows Iswenzz/CoD4-DM1 (GPL-3.0). The fast file parser is cod4-ff. Engine facts (vertex layout, state bits, lightmap layout) were checked against KisakCOD. three.js is MIT (vendor/three/LICENSE). Ideas for the 3D view come from cod4-demo-inspector. Call of Duty is a trademark of Activision; this project is not affiliated with Activision or Infinity Ward.

About

CoD4 Demo Inspector / Analyzer

Resources

Stars

5 stars

Watchers

0 watching

Forks

Contributors

Languages