NFSU.cc / Guides

DirectX 9 and Windows XP rebuilt on WebGPU, Web Audio and workers

Translated code is not enough. The game opens windows, files and sound buffers, and asks for a DirectX 9 card. About 14,800 lines of C and a few JavaScript files answer every one of those calls.

The browser version on a phone with touch controls
The game asks for a keyboard; on a phone the touch layer answers with the key codes it expects.

A PC from 2003, always the same one

The host presents one machine and sticks to it: Windows XP SP2, one CPU, code page 1252, the game installed at C:\NFSU, and an ATI Radeon 9800 Pro with 128 MB on a 1920x1080 desktop. Each Windows function is written from Microsoft's documentation and knows nothing about the game. A call to a method that does not exist stops the game with that method's name instead of carrying on with a wrong answer.

Graphics: DirectX 9 to WebGPU

The game draws through DirectX 9 objects. The host keeps those objects in the game's own memory and records each frame as a compact list of commands. When the game presents a frame, the list goes through a mailbox in shared memory to the page, which runs it with WebGPU, or WebGL 2 on a browser without it. The game's shaders are shader model 1 bytecode; a small translator decodes them and writes WGSL, the shader language of WebGPU.

Sound: a software mixer and an AudioWorklet

DirectSound gives the game sound buffers in its own memory. A mixer thread reads them the way a 2003 sound card read its buffers, at 44.1 kHz, and writes into a ring in shared memory. In the page, an AudioWorklet plays that ring and resyncs when the two clocks drift apart.

Threads: real ones, one at a time

The game starts several threads. Each one is a real thread (a Web Worker in the browser), but one global lock, handed out in ticket order, lets only one run game code at a time. A thread gives the lock up only where Windows would block it: sleeping, waiting, a busy critical section. The translated code needs no atomics, and the game still sees real threads. Shared memory between workers is why the site is served with cross-origin isolation headers.

Files: a hard drive on the internet

The game reads its files with ordinary Windows calls. In the browser, a reading thread turns each read into an HTTP request, synchronous inside its worker, so the game waits exactly as it waited for a hard drive. How that stays fast over the internet: loading and hosting.

Input and saves

DirectInput is rebuilt with one keyboard and one mouse. Gamepads and phone buttons are translated into the keyboard codes the game expects, so its own controls menu still works. The save folder lives in memory and is copied to the browser's storage a moment after each change.

Every file named here is on GitHub.

In the repo: host · host/d3d9.c · host/gpu.c · web/gpu.js · host/dsound.c · host/threads.c

More guides