Navigation
Browse the developer docs

FH2 Modding Guide · Chapter 16

The game loop, threads and timing

What runs where and when, before you call game code from a hook.

By Trinculo54 · from the FH2 Modding Guide · CC BY 4.0 · copied 4 Dec 2026 · read the original, which may be newer

On this page

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

  1. 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.
  2. 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 ...Deferred proxies.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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 doesStarted fromWhat a mod may do there
App ThreadThe 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 ThreadDraws 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, ProceduralDestroyThreadCulling and the world's potentially visible sets; procedural clean-upgame+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, CreateCrowdSectionsThreadRender work split off: command lists, instancing, sky, particles, crowd sectionsvariousNothing, unless you hook that system and know its rules
AnimUpdate, CarUpdatePoseThread%d, CarUpdateConstantsThread%dAnimation and car render datagame+0x16F33E0 (0x1416F33E0), game+0x13052E0 (0x1413052E0)Nothing
CarLoading, CarUnloadingBuilding and freeing carsgame+0xFCC4D0 (0x140FCC4D0)A hook in the car builder runs here (unconfirmed)
CResourceManager::FileIOThreadFunc, ::WorkerAThreadFunc, ::WorkerBThreadFunc, ::SemaphoreRepeaterResource loading: read, decode, buildgame+0x13D62B0 (0x1413D62B0)Keep file and loader hooks thread-safe and fast
CWindowedStreamWorkerThread::Work, OverlapQueueThread, CompressTexture, GarbageCollectorStreaming reads, texture work, deferred freesvariousAs above
Forza Audio Thread, plus FMOD's own threadsGame audio and the FMOD mixer and streamsgame+0xFF43D0 (0x140FF43D0); FMOD starts its own through game+0x19AB5B0Audio hooks only; hand anything else to the App Thread
NERD::IOCompletionPort::BackgroundThread, FileTransferManager, RacingAI::AsyncTraining::Manager(%d)Network I/O, transfers, drivatar trainingvariousNothing

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:

StepCall siteWhat runsStatus
1game+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)
2game+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
3game+0x2269E6 (0x1402269E6)The UI lock is taken (UserInterface vtable +0x30; the UserInterface is [game+0x3684B90] (0x143684B90))offline only
4game+0x2269FA (0x1402269FA)The modules' update phase (game+0x71BDC0 (0x14071BDC0)). AchievementsModule update game+0x3FCD60 (0x1403FCD60) runs here and always reaches game+0x3FCD84 (0x1403FCD84): the module tickproven in game
5game+0x226A46 (0x140226A46)The modules' second phase (game+0x71BD60 (0x14071BD60), the HUD prioritiser)offline only
6game+0x226ABC (0x140226ABC)UI update game+0x2271E0 (0x1402271E0): UserInterface +0x78 (game+0x142C5E0, 0x14142C5E0), the input pump, the pages' handlersoffline only
7game+0x227045 (0x140227045)The UI lock is releasedoffline 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 (slot 0x170), each car's slot 0x78, the physics step (CPhysicsWorld::StepWorld game+0x12EB450), each car's slot 0x80 (ForzaCar::Update, game+0x2A9400), slot 0x88, then the views. Each view's camera director runs CMultiCam::Update (game+0xFE6020), which updates the active camera and ends in CMultiCam::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 from CMultiCam slot 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+0x3FCD84 as 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. PlacePlayerCarAtRouteLocator makes one with dt 0. Handle dt == 0 in 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:

  1. If a check at game+0xF9ED60 says so (what it tests is not known), Sleep(10) and try again.
  2. Otherwise call RenderThreadBase slot 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 address game+0xF9A51D is where stall samples find it waiting). Otherwise it calls the frame step game+0xFA78A0 (0x140FA78A0), which stamps the time and counts the frame at rt+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 (slot 0x178) on the world-collision manager's +0x10, which is the CPresentationDeferred; 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, CrowdPresentation11 and 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):

FieldMeaningStatus
gm+0x40 (double)The game clock. GetTime game+0xFBCC50 (0x140FBCC50) returns it as a floatgetter verified on the exe
gm+0x48 (float)The game speed: 1 normal, 0 frozen, negative plays a replay backwardsproven in game
gm+0x4CA fixed dtoffline only
gm+0x2C / gm+0x37Speed enabled / speed blocked: the speed applies only while +0x2C is set and +0x37 clearoffline only
gm+0x70The un-pause ramp; the rewind menu's resume forces the speed back to 1.0offline 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 itDoesn't
The picture, physics, cars and cameras that use the simulation's stepEngine sound (proven in game)
The replay's playback directionThe 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 SetGameSpeed won't take after a few tries, store gm+0x48 yourself, 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 rate unless 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 by GetTickCount64, 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 dt your simulation hook receives.
  • Never mix the two in one rate: a pause or slow motion then makes the result jump.

16.6 Pausing

WhereMeaningStatus
gm+0x28 (byte)Paused. Set through CGameManager slot +0xC8, game+0x2EF310 (0x1402EF310), which calls game+0xFC5560 to store itproven in game; store verified on the exe
gm+0x29 (byte)Stop the simulation while paused. Clearing it keeps the world running behind photo modeproven in game
game+0x93BF50 (0x14093BF50)ShouldUpdateSimulationWhenPaused; online play keeps the simulation runningoffline only
sim+0x309 (byte)PausePhysicsoffline only

What still runs while the game is paused:

RunsStops
The controller update (dt is real time)The running simulation path, so cars and physics
The paused simulation path and CMultiCam::PostUpdateThe game clock (unless the simulation is kept running)
The module tick and the UIThe 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::Update runs 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 writing gm+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, slot game+0x2E6EF28 (0x142E6EF28) holding game+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:

ObjectArrivesGoesNotes
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 addressWreckingBall 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 objectsCWorldCollObjMan::AddCell game+0x36A330 (0x14036A330)as the car moves onthey 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 0AI 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 restartsre-read every frame and check the vtable
The view, camera director and target car chainchanges on loads and view switchesre-walk from CForza each frame (chapter 11)
A radio stream's sample and propsRadioStreamFmod::loadthe next trackFH2 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.

HookAddressThreadWhenStatus
CControllerManager::Updategame+0x1075490 (0x141075490)App, outside the UI lockonce a frame, paused or not, before the game updateproven in game
ReadPad callgame+0x1075580 (0x141075580)Apponce per pad slot (8) a frameproven in game (Director Mode)
CGameManager::Updategame+0xFC8FD0 (0x140FC8FD0)Apponce a framecall verified on the exe
Simulation, running / pausedgame+0xFB33D0 (0x140FB33D0) / game+0xF9A930 (0x140F9A930)Appone of the two each frameproven in game
ForzaCar::Updategame+0x2A9400 (0x1402A9400)App (from the running simulation path)each car, each running frameper-frame proven in game; the thread from the call order, offline only
CMultiCam::PostUpdategame+0xFE61C0 (0x140FE61C0)App, the same thread as the controller updateonce a frame per camera director, both paths; sometimes a second time with dt 0proven in game
ForzaMultiCam rolled-over checkgame+0x3986A0 (0x1403986A0)App (camera update)per frameproven in game (Do A Barrel Roll)
Module tick (AchievementsModule)game+0x3FCD84 (0x1403FCD84)App, inside the UI lockonce a frameproven in game
Stateflow state machine updategame+0x19281E0 (0x1419281E0)Appper machine, per frameproven in game
SwapTrack targetgame+0x939410 (0x140939410)App, inside the state machine updatewhen travellingproven in game
TimeOfDay::Updategame+0x197B170 (0x14197B170)a game thread (one caller, game+0x300933); Extra Options' Weather Control works there "on the game's thread"once a frameoffline only
CWorldCollObjMan::Updategame+0x384C00 (0x140384C00)a game thread; which one is not recordedonce a frameproven in game (WreckingBall spawns pieces there)
CWorldCollObj::OnCollisionslot at game+0x2C6A208 (0x142C6A208)not recordedon a hitproven in game; WreckingBall only queues there
Render-side view update callgame+0x1340022 (0x141340022)a render-side thread, not Apponce per view per frameproven in game
Frame step (FH2MP's "logic step")game+0xFA78A0 (0x140FA78A0)Render Thread (by the exe)once per drawn frameper-frame proven in game; thread offline only
RadioStreamFmod::load's createSound callgame+0x1018A13 (0x141018A13)a game thread (which one is not recorded); game allocation works therewhen a station loads a trackproven in game (FH2 Universal Radio)
RadioStreamFmod::start's getSubSound callgame+0x10221F2 (0x1410221F2)as abovewhen a track startsproven in game
An FMOD user stream's PCM read callback(your callback)FMOD's stream threadwhile the game reads the stationproven in game
Engine-sound group updatesee chapter 9an FMOD group-update thread; values eased on the mixer threadper audio blockproven in game
File resolverslot game+0x2E6EF28 (0x142E6EF28), function game+0x11F49B0 (0x1411F49B0)any thread that opens a fileper fileproven in game
ProceduralModelsData::Serializegame+0x1871B90 (0x141871B90)a loading thread (unconfirmed)when a procedural library loadsproven in game
TrackPresentation11 loader store / destructorgame+0x133DEDF (0x14133DEDF) / game+0x1377B50 (0x141377B50)the render side (unconfirmed)world load / unloadproven in game
EtxEventWrite import slotgame+0x1DD0060 (0x141DD0060)any thread that sends telemetry (unconfirmed)per eventproven in game (Achievements, which locks)
SetStatgame+0x2F7977 (0x1402F7977)not recordedper stat changeproven in game
HUD notification constructor / destructorgame+0x73E0B1 (0x14073E0B1) / game+0x73F046 (0x14073F046)not recorded; Achievements guards its list with a lockper notificationproven 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 guardper eventproven 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:

WorkDrain it in
UI objects, pages, pop-ups, UI sounds, AVUI stringsthe module tick (inside the UI lock)
Camera, input contexts, game speed, car placement, anything that should land before this framethe controller update
One carForzaCar::Update, after the original, for that car only
World objects, breakable piecesthe world-collision manager's update
Render-side objectsa 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_guard and 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:

    WorkCost
    The platform's HUD layer, pumped at the module tickabout 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 PropertyChanged on 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 fixes31 µs (was 574 µs)
    One VirtualQuery of 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 VirtualQuery lesson 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

CallbackThreadNotes
fh2mod_initthe platform's loader thread, not under the loader lockmods init one after another; return 0 always (chapter 2)
wait_for_game, wait_for_code, wait_for_modsyour own thread onlywait_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 getthe App Thread, during the UI update, inside the UI lockkeep them short; store a request and act in a tick
Hotkey on_pressthe platform's hotkey thread (polls every 15 ms while Azimuth's window has focus)no game calls
Command handlersthe platform's command threadno game calls
Pad layer on_pressa platform threadno game calls
Detours (hook_function, hook_call, hook_pointer) and hook_instruction callbackswhichever 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 tickat most 24 values a frame and 10 text changes a second
set_page_rows, page_text_changed, set_setting, show_toast, loggingany threadevery API function is thread-safe
The platform's own pop-ups and HUD feeddrawn from the module tick
EO FH2PluginInitializeEO's plugin worker, started on the game's first file lookupother game threads are already running: patch with them suspended
EO FH2PluginVehicleUpdatethe thread of the local player's car update, before the game's own update; never for AI carsshort; don't keep the car pointer; stopped simulations may not call it
EO FH2PluginDatabaseUpdatethe game thread that owns the database, once per merged generationborrowed connection; never use it from a worker
EO FH2PluginMediaDirectorythe 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.

  1. Which threads run CWorldCollObjMan::Update, CWorldCollObj::OnCollision, ProceduralModelsData::Serialize, the TrackPresentation11 loader and destructor, SetStat, the HUD notification constructor and destructor, and the EtxEventWrite telemetry calls. None has had its thread id logged.
  2. 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.
  3. 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 in CForza::Update.
  4. Which render-side thread runs the view update at game+0x1340022: the Render Thread itself or a visibility worker.
  5. Which thread FH2MP's whole-process sampler called "the main thread" when it found the VirtualQuery cost.
  6. The suspended branch (CForza+0x710, a 2 s sleep per pass): what sets it under Azimuth.
  7. 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.
  8. 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.
  9. Which per-frame hooks run while paused beyond the controller update, PostUpdate and the module tick. Whether ForzaCar::Update runs on the paused path is not known.
  10. Focus loss: the game very likely pauses itself when Azimuth's window loses focus; the mechanism is not known.
  11. 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).

“The FH2 Modding Guide” by Trinculo54 is licensed under CC BY 4.0; its code samples are under the MIT licence. This page is an unchanged copy (links point to this site) of 16-game-loop.md at commit bb10508; corrections belong in the original repository.