This chapter is the model behind the threading rules in chapter 5: which threads the game runs, what each one does, the order things happen in a frame, game time against real time, pausing, loading and streaming, and when it is safe to call game code or touch an object. Read it before your first hook that does more than look, and come back to the tables in 16.8 and 16.11 when you need to know where a callback runs.
All addresses are for forza_durango_release_final.exe of 24 Nov 2015 (TimeDateStamp 0x565501ED, SizeOfImage
0x3A18000), image base 0x140000000. Each fact is marked proven in game, offline only (read from the exe or
a harness) or unconfirmed, as in the rest of the guide. Where this chapter says "verified on the exe", the call
or the bytes were read from the exe on disk; the behaviour may still be offline only.
Contents
- 16.1 The short version
- 16.2 The threads
- 16.3 One frame on the App Thread
- 16.4 The render side
- 16.5 Game time and real time
- 16.6 Pausing
- 16.7 Loading, streaming and object lifetime
- 16.8 Where common hooks run
- 16.9 Moving work between threads
- 16.10 Per-frame budgets and how to measure them
- 16.11 Platform and Extra Options callback threads
- 16.12 Open questions
16.1 The short version
- One thread owns the game's state: the App Thread. It reads the pad, runs the simulation, the cameras, the game's modules and the UI, once a frame. "The game thread", "the main thread" and "the UI thread" in this guide and in the platform's docs all mean this thread.
- A second thread, the Render Thread, draws. It works on the frame the App Thread finished, so it runs about
one frame behind. Render-side objects belong to it; the App Thread reaches them only through the game's
...Deferredproxies. - Dozens of worker threads load, stream, animate and mix audio. Their hooks can fire at any time, at the same time as the App Thread.
- Call game code from the thread that owns it, in the phase that owns it. Simulation and camera calls from the pad tick or a simulation hook; UI objects, pop-ups and UI sounds from the module tick, inside the UI lock.
- Your own threads never call game code and never allocate game memory. They queue work; a detour on the right game thread drains the queue.
- Detours copy, they don't keep. Copy what you need out of game memory in the detour; never hand a game pointer to another thread.
- Game time is not real time. The game clock stops when paused and follows the game speed. Use the Windows clock for timeouts and rates.
- Budget in microseconds. A frame is 7 to 17 ms in total; per-frame work in a mod should stay well under 0.1 ms. Measure before guessing (13.5).
16.2 The threads
The game names its threads through one helper, game+0x10869A0 (0x1410869A0), called with a string just before
the thread is started by game+0x1081A90 (0x141081A90). Reading the 32 calls of the helper gives the table below.
The names are the game's own; the roles come from the code around each call and from what mods have seen in game.
| Thread (the game's name) | What it does | Started from | What a mod may do there |
|---|---|---|---|
| App Thread | The game loop: pad, simulation, cars, cameras, modules, UI (16.3) | game+0x30C440 (0x14030C440), entry game+0x30B800 (0x14030B800) | Call game code, allocate game memory, touch UI objects inside the UI lock. Keep it short |
| Render Thread | Draws the previous game frame; presents (16.4) | game+0xF94F10 (0x140F94F10), from CForza's start-up; entry game+0xFAF9A0 (0x140FAF9A0) | Read render-side objects in a render-side hook. Never call simulation code |
Visibility Thread, Sub Vis %d, PVS Thread, UpdatePVSSubThread, ProceduralDestroyThread | Culling and the world's potentially visible sets; procedural clean-up | game+0x13536A0 (0x1413536A0), game+0x131F0C0 (0x14131F0C0), game+0x1337B30 (0x141337B30) | Read only, and only what that pass owns. Crowd cull and per-person updates run on Sub Vis workers |
| DrawBundleRecordThread, InstanceCommandListRecorder, AtmosphericScatteringWorker / Delegator, FXParticlesWorker, CreateCrowdSectionsThread | Render work split off: command lists, instancing, sky, particles, crowd sections | various | Nothing, unless you hook that system and know its rules |
AnimUpdate, CarUpdatePoseThread%d, CarUpdateConstantsThread%d | Animation and car render data | game+0x16F33E0 (0x1416F33E0), game+0x13052E0 (0x1413052E0) | Nothing |
| CarLoading, CarUnloading | Building and freeing cars | game+0xFCC4D0 (0x140FCC4D0) | A hook in the car builder runs here (unconfirmed) |
CResourceManager::FileIOThreadFunc, ::WorkerAThreadFunc, ::WorkerBThreadFunc, ::SemaphoreRepeater | Resource loading: read, decode, build | game+0x13D62B0 (0x1413D62B0) | Keep file and loader hooks thread-safe and fast |
CWindowedStreamWorkerThread::Work, OverlapQueueThread, CompressTexture, GarbageCollector | Streaming reads, texture work, deferred frees | various | As above |
| Forza Audio Thread, plus FMOD's own threads | Game audio and the FMOD mixer and streams | game+0xFF43D0 (0x140FF43D0); FMOD starts its own through game+0x19AB5B0 | Audio hooks only; hand anything else to the App Thread |
NERD::IOCompletionPort::BackgroundThread, FileTransferManager, RacingAI::AsyncTraining::Manager(%d) | Network I/O, transfers, drivatar training | various | Nothing |
The "Started from" addresses are the functions that name and start each thread. The table is offline only as a list; the App Thread and Render Thread rows are backed by game runs, below.
Threads that are not the game's own also run in the process:
- Azimuth's, including its audio processor (10 to 20 % of a core in a busy world, proven in game) and the threads that turn the game's D3D11.X calls into D3D12.
- The platform's: its loader thread (which calls
fh2mod_init), the hotkey thread, the command thread and the pad layer's thread (chapter 2). - Extra Options' plugin worker, started on the game's first file lookup (chapter 3).
- Your own threads. The game knows nothing about them. In particular they lack the game's per-thread data (16.9).
Telling which thread you are on
There is no global for the App Thread's id that mods use. Do what Director Mode does: store GetCurrentThreadId()
in your controller-update hook (16.3, step 1) and compare against it elsewhere. Log the thread id once per hook in a
test build; three game runs of a HUD probe that did this proved that the module tick, the pages' callbacks and the
HUD page's shown and hidden calls all share one thread (proven in game).
A note on names used in other chapters
FH2MP's frame-stall log calls game+0xFA78A0 "the logic thread's frame step", and chapters
12 and 13 quote measurements made
with that log. Read from
the exe, that step is reached only from RenderThreadBase slot 48 (game+0xF9A340), which is the loop body of the
thread the game names Render Thread (verified on the exe; offline only). The stall measurements stand; read
them as where the render side waited, which is also why the gamma routine and Azimuth's fence wait show up in them.
16.3 One frame on the App Thread
The App Thread's entry (game+0x30B800) runs CForza's loop at game+0xF74AF0 (0x140F74AF0) until the game ends.
Each pass asks CForza for the frame's time step (vtable slot 22, game+0x21B0E0), runs CForza::Update with it
(slot 18, game+0x2260D0) and then slot 19. CForza is the global [game+0x34ABA60]
(chapter 11). All of this is verified on the exe.
CForza::Update (game+0x2260D0, 0x1402260D0) does the frame in this order:
| Step | Call site | What runs | Status |
|---|---|---|---|
| 1 | game+0x226893 (0x140226893) | CControllerManager::Update game+0x1075490 (0x141075490): the pad is read (ReadPad game+0x106C320 (0x14106C320) once per slot, 8 slots) | proven in game; the only caller (verified on the exe) |
| 2 | game+0x2269D8 (0x1402269D8) | CGameManager::Update, vtable slot 10, game+0xFC8FD0 (0x140FC8FD0): game speed and clock, then the simulation (below) | call verified on the exe; the simulation part proven in game |
| 3 | game+0x2269E6 (0x1402269E6) | The UI lock is taken (UserInterface vtable +0x30; the UserInterface is [game+0x3684B90] (0x143684B90)) | offline only |
| 4 | game+0x2269FA (0x1402269FA) | The modules' update phase (game+0x71BDC0 (0x14071BDC0)). AchievementsModule update game+0x3FCD60 (0x1403FCD60) runs here and always reaches game+0x3FCD84 (0x1403FCD84): the module tick | proven in game |
| 5 | game+0x226A46 (0x140226A46) | The modules' second phase (game+0x71BD60 (0x14071BD60), the HUD prioritiser) | offline only |
| 6 | game+0x226ABC (0x140226ABC) | UI update game+0x2271E0 (0x1402271E0): UserInterface +0x78 (game+0x142C5E0, 0x14142C5E0), the input pump, the pages' handlers | offline only |
| 7 | game+0x227045 (0x140227045) | The UI lock is released | offline only |
Inside step 2, the simulation has two paths, both Simulation vtable slots (vtable game+0x2E6C508):
- Running: slot 15,
game+0xFB33D0(0x140FB33D0). It counts the frame (sim+0x3DC), then in this order: input (slot0x170), each car's slot0x78, the physics step (CPhysicsWorld::StepWorldgame+0x12EB450), each car's slot0x80(ForzaCar::Update,game+0x2A9400), slot0x88, then the views. Each view's camera director runsCMultiCam::Update(game+0xFE6020), which updates the active camera and ends inCMultiCam::PostUpdate(game+0xFE61C0). The order comes from FH2MP's reading of this function (offline only); the frame counter and the PostUpdate path are proven in game. - Paused: slot 16,
game+0xF9A930(0x140F9A930). The world stands still but the views still update: PostUpdate is called fromCMultiCamslot 5 (game+0xFE26F0). Proven in game.
What the order means for a mod:
- Something written at step 1 lands before the frame it changes. Director Mode does its whole frame from the controller-update hook for this reason.
- The camera is final after step 2. Reading the camera cache at the module tick (step 4) gives world-anchored UI no lag: the camera data was 0.9 ms old when the UI used it. Read at step 1, the same data is a frame behind (proven in game).
- The controller update runs outside the UI lock. Another thread held the lock in 136 of 112,818 samples taken there, so it is not a safe place for UI objects (proven in game). Use the module tick for those.
- The module tick is shared. The platform's pop-ups, its HUD layer and Achievements all hook
game+0x3FCD84as an instruction hook, and the platform chains them. Hook it the same way, never as a patch (chapter 9). - A second camera update can come in one frame.
PlacePlayerCarAtRouteLocatormakes one withdt0. Handledt == 0in any camera hook (proven in game).
One more branch, offline only: when the dword at CForza+0x710 is non-zero, CForza::Update skips the frame
and sleeps 2 s (SleepEx(2000) at game+0x226192). Which state sets it under Azimuth is not known.
16.4 The render side
The Render Thread's loop
CForza starts the Render Thread from its vtable slot 13 (game+0x221220, through game+0xF9F7B0 to
game+0xF94F10). The thread's entry, game+0xFAF9A0, loops while [rt+0xB8] is set:
- If a check at
game+0xF9ED60says so (what it tests is not known),Sleep(10)and try again. - Otherwise call
RenderThreadBaseslot 48,game+0xF9A340(0x140F9A340). It compares two frame counters (read as: frames the App Thread has finished against frames drawn). With nothing new, it yields (SleepEx(0, TRUE); its return addressgame+0xF9A51Dis where stall samples find it waiting). Otherwise it calls the frame stepgame+0xFA78A0(0x140FA78A0), which stamps the time and counts the frame atrt+0x128.
The calls and the loop are verified on the exe; what the counters mean is a reading of the code (offline only). In game, a hook on the frame step runs once per drawn frame (proven in game, FH2MP).
One frame behind
The render side draws the frame before the newest App Thread frame about 98 % of the time: a steady one-frame
lag (proven in game). Anything you place from the App Thread that the render side draws (an on-foot body, a marker,
a 3D card) must be matched to the frame whose camera the renderer uses, or it shakes against the camera. An on-foot
mod kept a ring of its last 8 frames and chose the one whose eye matched the render camera (cull view 18) within
0.5 m. The render-side view update, a hook_call at game+0x1340022 (0x141340022), runs once per view per frame
on a render-side thread: in game its thread id differed from the App Thread's (proven in game). See
chapter 8 for the cull views.
Where the frame goes after that: the game presents once a frame at game+0x10F484D, and the render thread waits on
Azimuth's GPU fence through call [ctx+0x748] at game+0xF999D0 (13.5).
The game's own cross-thread proxies
The App Thread doesn't call render-side or audio objects directly. It calls a proxy whose class name ends in
Deferred, which records the call for the owning thread. RTTI lists them: CPresentationDeferred,
CTrackPresentationDeferred, CCarPresentationDeferred, CCrowdPresentationDeferred,
CModelPresentationDeferred, CParticlePresentationDeferred, CPresentationCameraDeferred,
CPresentationViewDeferred, CUI4PresentationRendererDeferred, COverlayRendererDeferred,
RenderThreadBaseDeferred, RenderThread11Deferred, AudioManagerDeferred and the AudioObject...Deferred family.
What this means in practice:
- Call a proxy from the App Thread. WreckingBall hides a telephone pole with
SetModelInstanceHidden(slot0x178) on the world-collision manager's+0x10, which is theCPresentationDeferred; the call is queued for the render side (proven in game). - Proxies are not built for many producers.
AudioManagerDeferred([game+0x365A298]) has a command ring with no producer lock: play at most one UI sound a frame, from the module tick only (proven in game). - The real objects belong to the render side.
TrackPresentation11,CrowdPresentation11and the renderer's own state are read there. An on-foot mod did all its pedestrian work inside the render-side view-update hook, the thread that reads those entries (proven in game). - Plain data writes can be fine. Director Mode sets depth of field by writing the render thread object's block at
[[game+0x354F4F8]+0x28]+0x590, which the renderer reads once per view per frame; no call, no proxy (proven in game). This works because the renderer only reads the block; don't extend it to objects the render side writes.
16.5 Game time and real time
The frame's time step is real time
CForza's slot 22 (game+0x21B0E0) gives each frame its dt from a millisecond clock; a gap of more than 4 s counts
as 33 ms, so a long hitch doesn't throw the world forward. A second path (game+0xF58770), taken when that clock
isn't available, caps dt at 0.2 s, and there two bytes in the game's settings object force a fixed step of
1/59.94 s or 1/29.97 s instead. All verified on the exe (offline only); which path runs under Azimuth, and which
options set those bytes, is not known.
In game, the dt the controller update receives is real time, even while paused (proven in game).
The game clock and the game speed
CGameManager is [CForza+0x48] (vtable game+0x2C5F8C8,
chapter 11):
| Field | Meaning | Status |
|---|---|---|
gm+0x40 (double) | The game clock. GetTime game+0xFBCC50 (0x140FBCC50) returns it as a float | getter verified on the exe |
gm+0x48 (float) | The game speed: 1 normal, 0 frozen, negative plays a replay backwards | proven in game |
gm+0x4C | A fixed dt | offline only |
gm+0x2C / gm+0x37 | Speed enabled / speed blocked: the speed applies only while +0x2C is set and +0x37 clear | offline only |
gm+0x70 | The un-pause ramp; the rewind menu's resume forces the speed back to 1.0 | offline only |
Set the speed with SetGameSpeed, vtable slot 17, game+0x2F6800 (0x1402F6800). It calls game+0xFC7D90,
which stores gm+0x48 and turns the replay to reverse when the sign changes (verified on the exe). The update then
uses dt x speed; above 1.01 it uses speed x min(dt, 1/30), and the result is clamped to +-0.2 s a step, so about
12x is the useful maximum (offline only). 0.25 and 0 work in game (proven, Director Mode).
What follows the game speed, and what doesn't:
| Follows it | Doesn't |
|---|---|
| The picture, physics, cars and cameras that use the simulation's step | Engine sound (proven in game) |
| The replay's playback direction | The controller update, the UI, your threads |
| The radio and any real-time audio source |
Gotchas:
- Races, car meets, fast travel and the rewind menu set their own speed, time of day and weather. Re-apply your speed while you hold it, and hand it back on every exit.
- In a replay the DVR writes the speed every frame; a reverse needs the hook in chapter 7.
- Don't use the physics settings' TimeScale: it slows only part of the simulation.
- If
SetGameSpeedwon't take after a few tries, storegm+0x48yourself, as the call does. Director Mode falls back to this after three failed calls so that it can always give the speed back. - Time of day keeps its own clock:
clock += dt x rateunless paused (ToD+0x24), at 48 game seconds per real second (chapter 9).
Which clock to use
- Timeouts, rates, debouncing, pop-up spacing: a Windows clock (
GetTickCount64,QueryPerformanceCounter). Achievements spaces its pop-ups 5.5 s apart byGetTickCount64, so a pause doesn't hold them forever. - Anything that should freeze with the game (a timed effect in the world, a recorded take): the game clock, or
sum the
dtyour simulation hook receives. - Never mix the two in one rate: a pause or slow motion then makes the result jump.
16.6 Pausing
| Where | Meaning | Status |
|---|---|---|
gm+0x28 (byte) | Paused. Set through CGameManager slot +0xC8, game+0x2EF310 (0x1402EF310), which calls game+0xFC5560 to store it | proven in game; store verified on the exe |
gm+0x29 (byte) | Stop the simulation while paused. Clearing it keeps the world running behind photo mode | proven in game |
game+0x93BF50 (0x14093BF50) | ShouldUpdateSimulationWhenPaused; online play keeps the simulation running | offline only |
sim+0x309 (byte) | PausePhysics | offline only |
What still runs while the game is paused:
| Runs | Stops |
|---|---|
The controller update (dt is real time) | The running simulation path, so cars and physics |
The paused simulation path and CMultiCam::PostUpdate | The game clock (unless the simulation is kept running) |
| The module tick and the UI | The radio stream reads (the game stops reading the station) |
| The Render Thread, drawing the still frame |
Notes:
- Don't count frames with a per-car hook.
ForzaCar::Updateruns from the running path; Extra Options warns its plugins that some stopped simulations don't update the car. Use the controller update or the module tick as your frame clock. - Pause is stateflow's job. Photo mode doesn't pause the game itself; the stateflow pauses before opening it.
If a mod must pause, call the set-paused slot
+0xC8, as FH2MP's online photo mode does, rather than writinggm+0x28. - Focus loss very likely pauses the game (unconfirmed). Many mods also stop reading keys while Azimuth's window is
not in front; Director Mode checks
GetForegroundWindow()against its own process in the tick. - Real-time sources must keep going. FH2 Universal Radio feeds the game's radio from Spotify and other sources that run in real time. When the game stops reading (pause, menus, loading), its control thread drains its ring in real time after 1 s, or the source would stall or run ahead. Pausing those sources with the game is an open feature request.
- The Render Thread has its own idle check (
game+0xF9ED60, 16.4) and sleeps 10 ms a pass while it holds; whether that is tied to the game's pause is not known (offline only).
16.7 Loading, streaming and object lifetime
Loading happens off the App Thread
Files are read by the resource manager's threads, cars are built on CarLoading and freed on CarUnloading, and the world's visibility sets and crowd sections are built on their own threads (16.2). The App Thread asks for things and polls until they are ready (a car part, for example, polls its render model until state 3; offline only). So:
- A hook in a loader runs on a loader thread, at the same time as the App Thread. Don't call simulation or UI code from it. Note what you need and act on it from a game-thread hook.
- The file resolver runs on whichever thread opens a file. Every file goes through
CFileSys's resolver, slotgame+0x2E6EF28(0x142E6EF28) holdinggame+0x11F49B0(chapter 3). A hook there must be thread-safe and fast: a free-roam Drivatar car load makes about 4,000 lookups, and long frames grew with the number of overlay folders until both the platform and Extra Options indexed their folders (proven in game; the numbers are in 13.5). - The game waits for its loads with no timeout in places. A model whose file never arrives makes a car "load for ever" (offline only, seen in game with a missing file), and the streaming wait after a reset gives up only after 60 s (chapter 6).
Objects are freed and their memory reused
The rules are in 5.8. The lifetimes a mod usually tracks:
| Object | Arrives | Goes | Notes |
|---|---|---|---|
A world (TrackPresentation11) | loader store game+0x133DEDF (0x14133DEDF) | unload game+0x1385857 (0x141385857), destructor game+0x1377B50 (0x141377B50) | 6.3; drop every per-world note in the destructor |
| A procedural library (trees, fences) | ProceduralModelsData::Serialize game+0x1871B90 (0x141871B90) | the next Serialize at the same address | WreckingBall forgets all notes about an address there, before looking at the new object (its fix for the crash at game+0x369029) |
| A streamed cell's objects | CWorldCollObjMan::AddCell game+0x36A330 (0x14036A330) | as the car moves on | they stream round the view's target car, not the camera |
A car (ForzaCar) | the car builder | ~ForzaCar game+0x289320 (0x140289320), from the deleting destructor, slot 0 | AI and traffic cars come from pools, so an address can hold another car later |
A car's physics (car+0x4C08) | swapped by game+0xFAABE0 (0x140FAABE0) when the simulation restarts | re-read every frame and check the vtable | |
| The view, camera director and target car chain | changes on loads and view switches | re-walk from CForza each frame (chapter 11) | |
| A radio stream's sample and props | RadioStreamFmod::load | the next track | FH2 Universal Radio checks they are still live before each write from its control thread |
When worlds swap
Travel between worlds happens inside the stateflow: the state machine update game+0x19281E0 (0x1419281E0) runs on
the App Thread, and the swap_track state calls SwapTrack, whose target can be changed at game+0x939410
(chapter 6). Both proven in game. A pick made on the
UI thread should be one atomic value that the swap hook reads once (latched), so a change during a swap counts for
the next one.
Whether the App Thread keeps running its frame through every loading screen is not established (16.12). Director Mode doesn't assume it: a watchdog thread notices when its tick has not run for 2 s and gives back what can safely be given back from another thread (16.9).
16.8 Where common hooks run
"App" is the App Thread. The table is meant to be used on its own, so every address has both forms.
| Hook | Address | Thread | When | Status |
|---|---|---|---|---|
CControllerManager::Update | game+0x1075490 (0x141075490) | App, outside the UI lock | once a frame, paused or not, before the game update | proven in game |
ReadPad call | game+0x1075580 (0x141075580) | App | once per pad slot (8) a frame | proven in game (Director Mode) |
CGameManager::Update | game+0xFC8FD0 (0x140FC8FD0) | App | once a frame | call verified on the exe |
| Simulation, running / paused | game+0xFB33D0 (0x140FB33D0) / game+0xF9A930 (0x140F9A930) | App | one of the two each frame | proven in game |
ForzaCar::Update | game+0x2A9400 (0x1402A9400) | App (from the running simulation path) | each car, each running frame | per-frame proven in game; the thread from the call order, offline only |
CMultiCam::PostUpdate | game+0xFE61C0 (0x140FE61C0) | App, the same thread as the controller update | once a frame per camera director, both paths; sometimes a second time with dt 0 | proven in game |
| ForzaMultiCam rolled-over check | game+0x3986A0 (0x1403986A0) | App (camera update) | per frame | proven in game (Do A Barrel Roll) |
| Module tick (AchievementsModule) | game+0x3FCD84 (0x1403FCD84) | App, inside the UI lock | once a frame | proven in game |
| Stateflow state machine update | game+0x19281E0 (0x1419281E0) | App | per machine, per frame | proven in game |
SwapTrack target | game+0x939410 (0x140939410) | App, inside the state machine update | when travelling | proven in game |
TimeOfDay::Update | game+0x197B170 (0x14197B170) | a game thread (one caller, game+0x300933); Extra Options' Weather Control works there "on the game's thread" | once a frame | offline only |
CWorldCollObjMan::Update | game+0x384C00 (0x140384C00) | a game thread; which one is not recorded | once a frame | proven in game (WreckingBall spawns pieces there) |
CWorldCollObj::OnCollision | slot at game+0x2C6A208 (0x142C6A208) | not recorded | on a hit | proven in game; WreckingBall only queues there |
| Render-side view update call | game+0x1340022 (0x141340022) | a render-side thread, not App | once per view per frame | proven in game |
| Frame step (FH2MP's "logic step") | game+0xFA78A0 (0x140FA78A0) | Render Thread (by the exe) | once per drawn frame | per-frame proven in game; thread offline only |
RadioStreamFmod::load's createSound call | game+0x1018A13 (0x141018A13) | a game thread (which one is not recorded); game allocation works there | when a station loads a track | proven in game (FH2 Universal Radio) |
RadioStreamFmod::start's getSubSound call | game+0x10221F2 (0x1410221F2) | as above | when a track starts | proven in game |
| An FMOD user stream's PCM read callback | (your callback) | FMOD's stream thread | while the game reads the station | proven in game |
| Engine-sound group update | see chapter 9 | an FMOD group-update thread; values eased on the mixer thread | per audio block | proven in game |
| File resolver | slot game+0x2E6EF28 (0x142E6EF28), function game+0x11F49B0 (0x1411F49B0) | any thread that opens a file | per file | proven in game |
ProceduralModelsData::Serialize | game+0x1871B90 (0x141871B90) | a loading thread (unconfirmed) | when a procedural library loads | proven in game |
TrackPresentation11 loader store / destructor | game+0x133DEDF (0x14133DEDF) / game+0x1377B50 (0x141377B50) | the render side (unconfirmed) | world load / unload | proven in game |
EtxEventWrite import slot | game+0x1DD0060 (0x141DD0060) | any thread that sends telemetry (unconfirmed) | per event | proven in game (Achievements, which locks) |
SetStat | game+0x2F7977 (0x1402F7977) | not recorded | per stat change | proven in game |
| HUD notification constructor / destructor | game+0x73E0B1 (0x14073E0B1) / game+0x73F046 (0x14073F046) | not recorded; Achievements guards its list with a lock | per notification | proven in game |
| Entity events (speed zones) | game+0x190BF90 (0x14190BF90) | a game thread; a game call while handling one can send another, so CCBR uses a thread_local guard | per event | proven in game |
Where the table says "not recorded", assume any thread: guard shared state with a lock or atomics, and do nothing there but note what happened.
16.9 Moving work between threads
From your thread to a game thread: queue, then drain in a detour
This is the pattern behind every released mod that calls game code: Achievements shows pop-ups from the module tick, never from its worker; WreckingBall queues logs in the collision callback and spawns them in the world-collision update; Director Mode does every game call in its controller tick.
#include <windows.h>
#include <atomic>
#include <deque>
#include <mutex>
#include "fh2mod.h"
#include "fh2game.h"
struct Job { int kind; float value; }; // plain data only: never a game pointer
static std::mutex g_q_lock;
static std::deque<Job> g_q;
static std::atomic<bool> g_ready{false};
void post_job(const Job& j) { // any thread
std::lock_guard<std::mutex> l(g_q_lock);
if (g_q.size() < 64) g_q.push_back(j); // bounded: drop rather than grow without end
}
static bool take_job(Job& j) {
std::lock_guard<std::mutex> l(g_q_lock);
if (g_q.empty()) return false;
j = g_q.front();
g_q.pop_front();
return true;
}
// App Thread, once a frame, inside the UI lock.
static void on_tick(FH2Context*, void*) {
if (!g_ready.load(std::memory_order_acquire)) return;
Job j;
for (int n = 0; n < 4 && take_job(j); ++n) // a few a frame, never the whole backlog
do_game_work(j); // your game calls, byte-checked once beforehand
}
// On your own thread, after wait_for_code and a byte check of the tick site:
// FH2Hook* h = api->hook_instruction(mod, "frame tick", game + FH2_GAME_ACHIEVEMENTSMODULE_TICK_AT, on_tick, nullptr);
// if (h && api->enable_hooks(mod, h)) g_ready.store(true, std::memory_order_release);
Choose the drain point by what the work touches:
| Work | Drain it in |
|---|---|
| UI objects, pages, pop-ups, UI sounds, AVUI strings | the module tick (inside the UI lock) |
| Camera, input contexts, game speed, car placement, anything that should land before this frame | the controller update |
| One car | ForzaCar::Update, after the original, for that car only |
| World objects, breakable pieces | the world-collision manager's update |
| Render-side objects | a render-side hook such as the view update |
From a UI callback or hotkey: one atomic
Platform UI callbacks run on the App Thread inside the UI update, and hotkeys on the platform's own thread (16.11). Neither is a good place for game calls. Store one atomic value (a request bit, an index) and let the next tick act on it. Director Mode's page, row and hotkey callbacks only post request bits; its tick turns them into actions. One write per thread boundary keeps the order obvious.
From a detour to your thread: copy, then hand over
A detour runs on a game thread that must not wait for yours. Copy the values you need while you are on the game thread, and publish the copy; skip the update if your own lock is busy rather than block the game.
struct CarSample { float pos[3]; float vel[3]; };
static std::mutex g_s_lock;
static CarSample g_latest; // read by your thread under g_s_lock
using UpdateFn = uint64_t (*)(void*, float, float, uint64_t);
static UpdateFn o_update;
static uint64_t d_update(void* car, float dt, float b, uint64_t d) {
uint64_t r = o_update(car, dt, b, d); // the game's own update first
CarSample s;
if (read_player_sample(car, s)) { // kind 0, vtable check, guarded copies (5.8); no locks inside
std::unique_lock<std::mutex> l(g_s_lock, std::try_to_lock);
if (l.owns_lock()) g_latest = s; // busy: skip this frame, never wait
}
return r;
}
Rules that came from real bugs:
- Never keep a game pointer on another thread. FH2MP's network worker must not hold car memory; it gets copies made on the game thread.
- If another thread must write game memory, write in place only, after checking the object is still the one you
mean. FH2 Universal Radio's control thread writes a track's props only after
props_still_live()confirms the stream and its sample are still there, and it never allocates. - Keep
std::lock_guardand other objects with destructors out of any function with__try. Put the guarded reads in a helper, as above (read_player_sample), and the lock in the caller.
Allocating game memory
The game's operator new (game+0x3229C0, 0x1403229C0) reads a memory tag from the game's per-thread data (TLS
slot index at game+0x354EBD8, tag at +0x124; verified on the exe). Only the game's own threads have that data.
So allocate game memory only on a game thread, inside a detour the game called: FH2 Universal Radio grows a track's
strings inside its createSound hook and nowhere else. Strings the game will free must come from this allocator
(chapter 11).
When the game thread stops coming
Don't block a detour waiting for your thread, and don't let your thread wait for ever on the game. Keep a heartbeat:
static std::atomic<ULONGLONG> g_last_tick{0}; // the tick stores GetTickCount64() each frame
bool tick_alive() { // any thread
ULONGLONG t = g_last_tick.load(std::memory_order_acquire);
return t && GetTickCount64() - t < 2000;
}
Director Mode's watchdog thread checks this every 250 ms. After 2 s it gives back only what is safe from another thread (its own flags, the HUD layer, whose calls work on any thread), and leaves the pad mask and the game speed for the tick to put back, telling the player to restart if the tick never returns.
Start-up: hooks go live one at a time
enable_hooks switches hooks on one by one, and a shared per-frame site can fire before the call returns. Set your
"ready" flag only after enable_hooks returns, and check it first in every detour (proven in game: the race was
seen in a run). Set up every table and setting before enabling: detours run on many threads at once.
Scoping by thread
A thread_local flag set around a game call lets hooks deeper down know where they are called from:
- a track-import mod sets a flag around each stateflow machine's update (
game+0x19281E0) when the machine is in one of its own states, and its travel hooks act only while the flag is set; - CCBR's event hook sets one while it handles an event, so the events its own game calls send are not handled twice.
This works because each of those calls runs to completion on one thread.
16.10 Per-frame budgets and how to measure them
What a frame costs
-
Frame time: about 9.6 ms on a fast PC in a busy online session; 16.7 ms at 60 fps and 6.9 ms at 144 fps. The game is usually GPU-bound: CPU time was only 0.1 to 0.2 ms over GPU time (proven in game).
-
Known per-frame costs of mod work:
Work Cost The platform's HUD layer, pumped at the module tick about 0.15 ms plus 0.04 ms per bound value World-anchored 3D cards (4 to 6 bound values on a page of about 630 bindings) 0.3 to 0.5 ms Raising PropertyChangedon a page every frame0.12 to 0.23 ms; 54 to 69 notifications in one frame cost 2 to 3 ms FH2MP's whole client, per frame, after its fixes 31 µs (was 574 µs) One VirtualQueryof a game address every frame527 µs a call, worst calls 15 to 41 ms More in 13.5.
A budget to aim for
- Always-on work: under 0.1 ms a frame in total, measured in a release build.
- Per car, per frame: a few microseconds. Up to a dozen cars are on screen online, and AI and traffic add more (12.8).
- Spread big work over frames (a few queue items a frame, as above), or do it on your own thread on copies.
- Never do a system call per read. The
VirtualQuerylesson is in 13.5: its cost grows with the size of the game's heap block.
Measuring your own cost
Time your detour with QueryPerformanceCounter, add it up, and log once every few seconds, not every frame:
static LONGLONG g_qpf; // QueryPerformanceFrequency, set once at start-up
static std::atomic<LONGLONG> g_spent{0}, g_calls{0};
static uint64_t d_update_timed(void* car, float dt, float b, uint64_t d) {
LARGE_INTEGER a, z;
QueryPerformanceCounter(&a);
uint64_t r = d_update(car, dt, b, d); // the detour from above; hook this one in a measuring build
QueryPerformanceCounter(&z);
g_spent.fetch_add(z.QuadPart - a.QuadPart, std::memory_order_relaxed);
g_calls.fetch_add(1, std::memory_order_relaxed);
return r;
}
// Your own thread, every 10 s: log g_spent * 1e6 / g_qpf / frames as microseconds a frame, and g_calls / frames.
Count calls as well as time: a cheap call made 21 times a frame is how FH2MP's light sync cost what it did. Compare old and new code in alternating turns in one session.
Finding someone else's cost
No log records a frame time. The two tools that found real problems, a frame-stall log that samples the stuck thread and a whole-process sampler, are described in 13.5. Two points from this chapter's model:
- A sampler only sees the thread it samples. FH2MP's stall log sampled the thread that runs
game+0xFA78A0, which is the Render Thread (16.4), so it shows where the render side waited for the App Thread, the driver or Azimuth. To see App Thread stalls, stamp and sample from the controller update instead. - Sampling suspends threads. Suspending about 150 threads per sample made the frames it measured longer (median 79 ms against 64 ms). Keep samplers off in normal play.
16.11 Platform and Extra Options callback threads
| Callback | Thread | Notes |
|---|---|---|
fh2mod_init | the platform's loader thread, not under the loader lock | mods init one after another; return 0 always (chapter 2) |
wait_for_game, wait_for_code, wait_for_mods | your own thread only | wait_for_mods returns 0 inside fh2mod_init |
Settings on_change / on_slide, page on_open / on_select / on_button / on_slot, title on_press / on_choose, message box on_choose, hotkey on_rebind, page text get | the App Thread, during the UI update, inside the UI lock | keep them short; store a request and act in a tick |
Hotkey on_press | the platform's hotkey thread (polls every 15 ms while Azimuth's window has focus) | no game calls |
| Command handlers | the platform's command thread | no game calls |
Pad layer on_press | a platform thread | no game calls |
Detours (hook_function, hook_call, hook_pointer) and hook_instruction callbacks | whichever game thread runs the code (16.8) | set up everything before enable_hooks |
HUD layer calls (show_hud_layer, values, text) | any thread; the layer itself is pumped at the module tick | at most 24 values a frame and 10 text changes a second |
set_page_rows, page_text_changed, set_setting, show_toast, logging | any thread | every API function is thread-safe |
| The platform's own pop-ups and HUD feed | drawn from the module tick | |
EO FH2PluginInitialize | EO's plugin worker, started on the game's first file lookup | other game threads are already running: patch with them suspended |
EO FH2PluginVehicleUpdate | the thread of the local player's car update, before the game's own update; never for AI cars | short; don't keep the car pointer; stopped simulations may not call it |
EO FH2PluginDatabaseUpdate | the game thread that owns the database, once per merged generation | borrowed connection; never use it from a worker |
EO FH2PluginMediaDirectory | the plugin worker, once after init |
Extra Options plugins have no hook framework: anything else they hook runs on the thread the game uses for that code, exactly as in 16.8 (chapter 3).
16.12 Open questions
These are not established. Don't build on them without checking; a short probe that logs thread ids and call counts answers most of them.
- Which threads run
CWorldCollObjMan::Update,CWorldCollObj::OnCollision,ProceduralModelsData::Serialize, theTrackPresentation11loader and destructor,SetStat, the HUD notification constructor and destructor, and theEtxEventWritetelemetry calls. None has had its thread id logged. - Does the App Thread keep running its frame during loading screens and world swaps, and for how long can the controller tick stop? Director Mode's watchdog exists because this isn't known.
- Where exactly the App Thread hands a finished frame to the Render Thread. One study names a submit at
game+0xF5C170; no direct call to it was found inCForza::Update. - Which render-side thread runs the view update at
game+0x1340022: the Render Thread itself or a visibility worker. - Which thread FH2MP's whole-process sampler called "the main thread" when it found the
VirtualQuerycost. - The suspended branch (
CForza+0x710, a 2 s sleep per pass): what sets it under Azimuth. - The fixed time step: which settings set the two bytes that force a 1/59.94 s or 1/29.97 s step, and whether that gives frame-perfect offline capture.
- What else follows the game speed: particles, trees, clouds and time of day were never checked one by one; only engine sound is known not to.
- Which per-frame hooks run while paused beyond the controller update, PostUpdate and the module tick. Whether
ForzaCar::Updateruns on the paused path is not known. - Focus loss: the game very likely pauses itself when Azimuth's window loses focus; the mechanism is not known.
- The long frames online: half of the stall samples were in the gamma routine
game+0x10EF300, but one call costs only about 28 µs, so it is where the render side waited, not the cause. The cause is still unknown (13.5).
