Skip to content

Engine core

This page documents how Hitman: Blood Money starts, how one frame runs and how the Glacier engine reaches the PlayStation 2: the boot code, the main loop, game time, the virtual platform classes and their PS2 implementations, the memory allocators, file access, configuration and input. Everything here comes from the decompiled source in src/, which compiles back into the original executable byte for byte. Offsets come from the debug record (analysis/recovered-types.h).

Source map

src/engine/ holds 502 .cpp files and 7 .c files, src/hitman3/ holds 215 .cpp files. The counts below include subdirectories. Beside them, src/common/ (29 .cpp) has IOI's containers and its own namespace std, and src/audiolib/ (60) the shared audio library.

Directory .cpp What it holds
src/engine/animation/ 4 Animation playback, binary animation files, the stream packer
src/engine/audio/ 23 The sound engine (soundengine/, ZDllSound) and sound object controllers
src/engine/boids/ 3 The boid system and its human client
src/engine/camera/ 2 The base camera
src/engine/collision/ 9 Octrees, the quadtree and the old collision code (ZCollisionPS2)
src/engine/drawing/ 54 The renderer interfaces (ZRender, ZRenderBaseDll), the old renderer (old/), PS2 drawing and DMA chains, post filters
src/engine/enginedata/ 21 ZEngineDataBase, scenes, the event list and buffer, scheduled events, save games, checkpoints, locale
src/engine/eventsbase/ 44 Event classes (cut sequences, sound controls, animations, projectiles) and the script engine (scriptc.cpp)
src/engine/fysix/ 22 Physics: rigid bodies, ragdolls, cloth, shatter, plants
src/engine/geomsbase/ 41 Base geom classes: ZGEOM, groups, rooms, cameras, lights, particles
src/engine/geomsextend/ 24 Actors, players, items, linked objects, splines, water boxes
src/engine/globals/ 3 Globals, class information, the build id
src/engine/pathfinder4/ 6 The path finder runtime, its BSP tree and obstacles
src/engine/rendervideo/ 5 Movie playback and the PS2 PSS decoder
src/engine/ScriptInterfaces/ 19 The engine's script interfaces (*.si.cpp)
src/engine/serializerlib/ 29 Serializer streams and their type extensions
src/engine/shared/ 47 Eased and damped values, particle physics, vehicle movers, XML helpers
src/engine/startup/ 4 Static nukes, the restart between scenes, the disc error graphics, memory card title data
src/engine/system/ 28 The platform interfaces, memory, files, input, actions and configuration
src/engine/zstdlib/ 54 Math, strings, reference tables, the zip file system, the COM value stores, the script core (zscriptc.cpp), heaps
src/engine/zwindows/ 59 The GUI toolkit: windows, fonts, controls and the XML menu interface
src/engine/timetype.cpp 1 TIMETYPE::LoadSave
src/hitman3/background/ 58 Level objects: doors, elevators, security cameras and zones, light switches, crowds (humanflow.cpp), inventories
src/hitman3/camera/ 16 The player cameras: third person, first person, scope, binoculars, bullet, dialog
src/hitman3/characters/ 29 47 (zhitman3*.cpp), ZHM3Actor, weapons, items, fights, dialog
src/hitman3/gui/ 49 The HUD, the menus (menu/), the map, save and load screens
src/hitman3/hitman3/ 12 ZHM3GameData, the property graph, game stats, PS2 startup (_ps2/)
src/hitman3/interfaces/ 25 The game's script interfaces (*.si.cpp)
src/hitman3/levelcontrol/ 24 One level controller per mission (M00 to M13) and the hideout, level linking, money, notoriety, rating, music
src/hitman3/vehicles/ 2 Vehicle physics

Several units the debug record names compile to empty objects in the retail build: the console (console.cpp, consolecommand.cpp), the eleven debug-draw units in src/engine/drawing/drawdebug/, memorycheckhandler.cpp, tweak.cpp, sysnet.cpp, zasset.cpp and src/hitman3/hitman3/hm3startup.cpp.

Startup

_start

src/hitman3/hitman3/_ps2/crt0.cpp is one of the 13 units IOI wrote in assembly (hitman3/hitman3/_ps2/crt0.s in the debug record), kept as file-scope assembly. _start clears the general, hi/lo, shift-amount and FPU registers, zeroes .bss from _fbss to _end (0x005E4E1C), makes two kernel calls (syscall 0x3C with _gp, _stack, _stack_size, _args and _root, whose result becomes $sp; syscall 0x3D with the end of .bss and -1) and then calls, in order:

  1. _InitSys and FlushCache(0).
  2. PreGlobalConstructors, which records the first heap address in g_pBeforeGlobalConstructors with a malloc(1)/free pair.
  3. _init, the static constructors. Every component producer, geom and event class producer (ZFactoryProducer), binding block and pool allocator registers itself here, and the ZGameDataFactory GameDataFactory global in startup.cpp stores itself in g_pGameDataFactory.
  4. atexit(_fini), ei, then main(argc, argv) from _args, then exit.

main

main and its helpers are in src/hitman3/hitman3/_ps2/startup.cpp. It first carves up the 32 MB of main memory:

Value Size Role
pMemoryEnd 0x02000000 top of main memory
g_lStackSize 256,000 bytes stack under pMemoryEnd (_stack is 0x01FC1800); Run fills it with 0x5D
g_lSystemSize 102,400 bytes g_pSystemStart, allocated with malloc first and freed again after the Glacier block
g_pGlacierMem pMemoryEnd - g_pSystemStart - g_lStackSize - g_lSystemSize - 0x3C00 the engine heap (g_lGlacierMemSize), filled with 0x5A
g_lCodeSize g_pSystemStart - 0x00100000 everything below the first allocation

With .bss ending at _end, the Glacier block is at most 27,000,292 bytes (25.75 MiB), less whatever the static constructors took with malloc before main.

main then installs CDErrorCallBack as ZCDErrorCallBack, reboots the IOP with cdrom0:\IOP\IOPRP310.IMG;1, initialises SIF RPC, the IOP heap, the CD (sceCdMmode(2) on a DVD, 1 otherwise) and the file system, resets DMA (DevInit), starts a power-off thread (SetupPowerOff, 1,024-byte stack, priority 1), loads SIO2MAN.IRX and PADMAN.IRX, calls SysInput::StartUp, reads VPAL/VNTSC from the command line (g_dVideoMode is 1 for PAL, 2 for NTSC) and calls Run.

Run and the first scene

Run resets $sp to pMemoryEnd (ZSetStackPointer) and builds the engine:

  1. ZComponentGlobalList::Instance().CreateComponents(1) creates the global components: ZSysMem, whose CreateAllocators puts the Glacier heap behind operator new, and the ZGlobalComponentBase manager. Both are allocated with C malloc.
  2. new ZSysFilePS2() sets g_pSysFile, initialises the memory card system and turns on CD error checking.
  3. new ZSysInterfacePS2(0) sets g_pSysInterface. The base constructor builds the class information tree (CreateGeomClassInfoData, CalcClassInfoNrs, CalcDeriveIds; see objects) and sets the defaults: m_fFramesPerSecond 60, m_lFrameCount 1, m_sScenesPath "SCENES", time multiplier 1.
  4. CreateComponents(0) creates the runtime components: StandardComponent, the ZRuntimeComponentBase manager, IAudioInterface, ZAudioControllerManager, ZScriptCComponent, ZWaterBoxManager, ZBoneExtendPool, ZRigidBodyPoolManager.
  5. SysInput::Initialize creates ZSysInputPS2. Interrupt causes 4 and 5 and DMA channels 0 and 1 are enabled.
  6. ReadPS2SystemFile reads cdrom0:\SYSTEM.CNF: VMODE = PAL selects PAL unless the command line already chose a mode, the product code goes to ZHM3SavePS2::ReadProductCode, and a BOOT2 path naming SLUS sets g_bSLUSBuild.
  7. g_pSysInterface->Init() copies the video mode and sets m_bRestartEngineFlag; the loading bar rectangle becomes (0.1, 0.221, 0.8, 0.004).
  8. LoadAlwaysGFX mounts Scenes\AllLevels\ErrorMessages.zip, copies one texture into the static g_AlwaysGfx buffer (32,944 bytes) as g_pGlobalTexture and unmounts the archive again.
  9. g_pSysInterface->RunMain("@host0:main.ini"), which does not return while the game runs.

RunMain stores the command line and calls RunMainOnce(true) until it returns false. The first call runs ZSysInterfacePS2::StartUpMain (sysinterfaceps2.cpp):

  1. ReadCmdLine loads the ini file named after the @ into the option store and ParseOptions reads the engine's options from it (see configuration). The start scene is DefaultScene, or ProjectFile when that is empty.
  2. InitConfiguration creates CConfigurationPS2 and loads it; ResetTime and CalcCycSec start the clock. The option PS2VideoConfigPAL 1 selects PAL, any other value NTSC.
  3. new ZRenderDll becomes g_pRenderDll; its Init creates ZRenderPS2, which creates ZOldDrawPS2 and links itself into g_pSysInterface->WindowFirst. For bootmenu.gms and attractmode.gms the loading bar is drawn at 10%.
  4. new ZEngineDataBase(pFileName) becomes m_pEngineData and g_pEngineData. Its Initialize seeds the random generator from the cycle counter and sets m_lDontDrawFrame to 3, so the first three frames are not drawn.
  5. new ZDllSoundPS2 becomes m_pSoundDll unless the option DisableAudio is set.
  6. ZEngineDataBase::StartUp calls SetupWindow, initialises the sound DLL, and runs LoadScene and ControlSceneChange, which loads the scene (DoLoadScene, described in scene archives). DoLoadScene begins with g_pGameDataFactory->CreateGameData(), which creates ZHM3GameData as g_pGameData.
  7. ResetTime again and m_lIsActive = 1.

On the PAL disc, MAIN.INI sets DefaultScene to bootmenu.gms and ConfigFile to hm3gpad.cfg.

Restarting between scenes

A scene change restarts the engine. When a scene is loaded and another is requested, ZEngineDataBase::ControlSceneChange (enginedatabase.cpp) calls DoUnloadScene and then NukeAndRestart (src/engine/startup/_ps2/nukeandrestart.cpp) with the new scene's name:

  1. DestroyScriptInterfaces ends and deletes g_pScriptDll and g_pScriptIfDll.
  2. BackupValues copies the hero control mode, project path, config file, locale file, stream file and loading bar rectangle into static arrays, shuts input down, destroys ZStaticGameLevelData, runs EngineStaticNukes and GameStaticNukes, which reset static state that outlives the heap (the water manager pointer, the human state's first-run flag, the shatter pool, the post filter lookup, the item pool, the script load count and string map, the visibility check), and deletes g_pSysInterface.
  3. $sp is set back to pMemoryEnd and execution jumps to RestoreAndRestart.
  4. RestoreAndRestart destroys the runtime components and calls ISysMem::Reset, which resets every allocator. ZAllocatorNormal::Reset zeroes its block and hands it to its ZMalloc again, so the whole Glacier heap starts empty.
  5. It creates ZSysFilePS2, ZSysInterfacePS2 and the runtime components again, recreates ZStaticGameLevelData, fills the memory card title record (InitializeMemoryCardInfo, whose strings still read "Hitman 2Silent Assassin" and "BESCES-66666"), restores the saved values, sets m_bAfterNuke, rebuilds the string memory manager in place, restarts input and the action map, and calls RunMain with the scene name.

With m_bAfterNuke set, StartUpMain takes the scene name from the command line and skips the ini file. The option store survives because it lives in a static buffer (g_GlobalComBuffer), and so do g_IniFile and g_ConfigFile, which are read once and cached. RestoreAndRestart ends in RunMain, so the jump does not come back while the game runs. The port replaces this unit with port/engine/startup/_sdl/nukeandrestartsdl.cpp, which leaves through longjmp (g_NukeRestart).

The frame

Order of work

RunMainOnce calls NormalMainLoop. On the first frame after each scene load (DoLoadScene sets them back to 0) it reads the demo timeouts DemoTimeOut, DemoGameplayTimeOut and DemoFinalTimeOut, in milliseconds, and installs input timeout callbacks. After DemoTimeOut without input, a scene whose name contains hitmanbl switches to attractmode.gms; after DemoGameplayTimeOut, a _main or hideout scene opens the in-game menu. Then it steps the clock with StepFrameTime and calls ZEngineDataBase::MainLoop(true). If FrameTime has gone negative it reloads the current scene in place of the frame. MainLoop then does this:

Step Call Notes
1 SysInput::instance->Update() only while m_lDontDrawFrame is 0
2 g_pSysInterface->UnlockRefs()
3 Action::ZHandle a_Pause("Pause") when Digital() is true, m_bPause toggles
4 m_pSoundDll->InitFrame()
5 EngineGeomControl.UpdateMovedGeoms(), SetSaveObject(0) skipped with step 6 and 7 while m_bFrozen
6 ScheduledUpdate() ZScheduledUpdate::ScheduleEvents wakes sleeping threads and runs the 16 priority queues of scheduled events and scripts until m_lMaxCyclesToRun (1,000,000 cycles) have passed; nothing runs while paused
7 FrameUpdate() ZGameData::PreFrameUpdate (boids; ZHM3GameData adds load messages, the briefing and the heartbeat), ZPoolAllocator::CheckAllPools, m_EventList.FrameUpdate() (every event, see events), PostFrameUpdate
8 m_lDontDrawFrame countdown while above 0 the views are not drawn; at 0 it becomes -1 and EngineNotifyGameFirstFrameUpdate (empty, requiredgamecalls.cpp) is called
9 ZRender::Update() for each window in WindowFirst BeginScene (counts m_lFrameCount), UpdateCameras, the animation cache, EndScene, then Flip (see rendering)
10 SysInput::instance->Update()
11 SoundUpdate() DispatchSoundEvents unless paused, then RenderFrame
12 g_pSysInterface->LockRefs()
13 m_pLoadCallBack->LoadDone() once, after a load
14 ControlSceneChange() where a requested scene change, and the restart above, happens
15 SysInput::instance->Update()
16 AutoExit when m_fAutoExitTime is set and passed, ZJumpToExit()

Frame pacing

ZRenderPS2::Flip (renderps2.cpp) paces the loop. After waiting for VU1 and updating the dynamic draw data it spins until CycSec / m_fFramesPerSecond * m_lMaxFrameInterval - 100000 cycles have passed since the previous flip, waits for the vertical blank with sceGsSyncV(0), stores the measured rate in m_FPS, shows the frame, polls input once more, runs the flip callbacks and calls ExecuteDrawLists. ZPS2Setup sets m_fFramesPerSecond to 50 for PAL and 60 for NTSC and 480p. m_lMaxFrameInterval is 1 by default and after every ZRenderBaseDll::PopScene, 1 while the in-game map is open, and 2 during play (ZHM3LevelControl::Init2) and while a movie plays (basevideo.cpp). During play each frame therefore waits for at least two fields, which caps a level at 25 frames per second on a 50 Hz display and 30 on 60 Hz; the front end waits for one. The frame rate guide covers how the port changes this.

Game time

Time is TIMETYPE (src/engine/timetype.h), a signed 22.10 fixed-point count of seconds:

struct TIMETYPE {
    void LoadSave(ISerializerStream &stream);
    int32 secs;
    TIMETYPE() { secs = 0; }
    TIMETYPE(const TIMETYPE &value) { secs = value.secs; }
    TIMETYPE(int value) { secs = value << 10; }
    TIMETYPE(float value) { secs = convert(value); }
    int32 convert(float value) { return static_cast<int32>(value * 1024.0f); }
    ...
    operator float() const { return static_cast<float>(secs) * 0.0009765625f; }
    operator int() const { return secs >> 10; }

The TIMETYPE(int) shown is the PS2 branch of the header. An integer converts as whole seconds and a float as seconds times 1,024, truncated. Free operators mix TIMETYPE with float and int in +, -, * and the comparisons; * multiplies in 64 bits and shifts back by 10. A tick is 1/1,024 s, and secs turns negative after 2^31 ticks (2,097,152 s, about 24 days).

The clock is the COP0 Count register, read by ZSysInterfacePS2::TimeStampCounter and extended to 64 bits when it wraps. CalcCycSec programs EE timer 0 (mode 0x83, count 0) and sets CycSec to 294,912,000 cycles per second (CalcCycSecSD). Each frame ZSysInterfacePS2::StepTime takes the cycles since TimeOffset, limits them to CycSec / 10 (0.1 s), converts them to seconds, multiplies by m_fTimeMultiplier, and adds the result to m_fActualTime, which it also copies to m_fRealTime. ZSysInterface::StepFrameTime (sysinterface.cpp) turns that into game time:

void ZSysInterface::StepFrameTime() {
    TIMETYPE time = StepTime();
    PreFrameTime = FrameTime;
    if (g_pEngineData->IsPaused()) {
        FrameTimeOffset = PreFrameTime - time;
    } else {
        FrameTime = time + FrameTimeOffset;
    }
    DeltaFrameTime = FrameTime - PreFrameTime;
}
Field Offset Meaning
m_fRealTime 0x08 time since ClearTime, scaled by the multiplier; runs during a pause
m_fRealTimeDelta 0x0C the last step in seconds
m_fRealPreTime 0x10 m_fActualTime before the last step
m_fActualTime, m_fActualTimeDelta 0x18, 0x1C the same values as m_fRealTime and m_fRealTimeDelta on the PS2
m_lFrameCount 0x24 frames drawn, counted in ZRender::BeginScene
FrameTime, PreFrameTime 0x28, 0x2C game time this frame and last frame; stops while ZEngineDataBase::m_bPause is set
DeltaFrameTime 0x30 FrameTime - PreFrameTime in seconds; 0 during a pause
FrameTimeOffset 0x34 added to the actual time to give FrameTime; set during a pause so game time resumes where it stopped
m_fFramesPerSecond 0x3C the display's field rate, used as a unit of time
CycSec 0x40 EE cycles per second
m_fTimeMultiplier 0xAFC scale applied in StepTime; Set_TimeMultiplier is ignored while m_iTimeMultiplier_Locked (0xB00) is non-zero
TimeOffset, m_lActualTime 0xB28, 0xB30 ZSysInterfacePS2: the cycle count at the last step and the total cycles

ResetTime sets TimeOffset to the current count, so the time a scene load takes is never stepped; DoLoadScene calls it at the end. ZSysInterface::LoadSave writes the time fields, m_lFrameCount, CycSec and the random seed into a save.

The platform layer

The engine reaches the hardware through virtual classes in src/engine/. Each has one PS2 subclass under a _ps2 directory, and the port adds one _sdl subclass beside it (the port).

Engine class Declared in PS2 class PS2 source Reached through Port class
ZSysInterface engine/system/sysinterface.h ZSysInterfacePS2 engine/system/_ps2/sysinterfaceps2.cpp g_pSysInterface ZSysInterfaceSDL
ZSysFile engine/system/sysfile.h ZSysFilePS2 engine/system/_ps2/sysfileps2.cpp g_pSysFile ZSysFileSDL
ZSysInput engine/system/sysinput.h ZSysInputPS2 engine/system/_ps2/newsysinputps2.cpp SysInput::instance ZSysInputSDL
ZDllSound engine/audio/soundengine/sound.h ZDllSoundPS2 engine/audio/soundengine/_ps2/soundps2.cpp g_pSysInterface->m_pSoundDll (0xAE0) ZDllSoundSDL
ZRenderBaseDll engine/drawing/renderbase.h ZRenderDll engine/drawing/old/_ps2/renderdll.cpp g_pRenderDll ZRenderDllSDL
ZRender engine/drawing/renderbase.h ZRenderPS2 engine/drawing/old/_ps2/renderps2.cpp g_pSysInterface->WindowFirst (0x950), linked by Nxt ZRenderSDL
ZOldDrawBase engine/drawing/old/zolddrawbase.h ZOldDrawPS2 engine/drawing/old/_ps2/zolddrawps2.cpp IDraw::Instance(), the draw base of WindowFirst ZOldDrawSDL
ZOldViewBase engine/drawing/old/zoldviewbase.h ZOldViewPS2 engine/drawing/old/_ps2/zoldviewps2.cpp ZOldDrawPS2::NewView ZOldViewSDL
CConfiguration engine/system/cconfiguration.h CConfigurationPS2 engine/system/_ps2/cconfigurationps2.cpp g_pSysInterface->m_pConfiguration (0xB08) the base class

src/ has 16 _ps2 directories with 53 .cpp files, among them all 13 units IOI wrote in assembly. Other PS2 classes there are ZCollisionPS2, ZPostFilterPS2, ZPrimControlPS2, ZCameraViewEntryPS2 and the save classes ZHM3SavePS2 and ZLoadGameInfoPS2.

ZSysInterface (0xB1C bytes, 0xCC0 with ZSysInterfacePS2) does more than time. It holds the option store accessors, the paths (ScenesPath is m_sProjectPath + m_sScenesPath, WorldPath is m_sProjectPath + "Geometry", and so on), the run mode (RUNTIME, EDITOR, VIEWER, ANIMATION_VIEWER), the window list, the sound DLL and the configuration. Its random generator is m_lRandSeed = m_lRandSeed * 0x10dcd + 1 returning (m_lRandSeed >> 8) & 0x7fff; FRand divides that by 32,768 and FRand1 maps it to -1..1. On the PS2, BeforeFormat calls DisableSoftConversions(false) before SPrintF or Vsprintf runs vsprintf, and they put the old state back afterwards. DisableSoftConversions(true) would write break into seven software float-conversion helpers (fptosi, __fixsfdi and others) to catch their use; no code in src/ calls it with true.

Memory

ISysMem (src/engine/system/sysmem.h) is a global component. ZSysMem keeps one allocator per EAllocType and has no locking on the PS2 (its critical-section functions are empty). ZSysMem::CreateAllocators (sysmemps2.cpp) builds one ZAllocatorNormal over g_pGlacierMem and installs it as DEFAULT_MEM, SLOW_MEM, FAST_MEM and STATIC_MEM; RENDERCPU_MEM and RENDERPRIMACCESS_MEM stay empty, and ZSysMem::New sends a type with no allocator to DEFAULT_MEM. operator new (allocators.cpp) uses DEFAULT_MEM, or malloc before ISysMem exists. On the PS2, when an allocation fails and the allocator does not return null, both operator new and ZSysMem::New loop forever writing a changing colour to the GS background colour register, which is how an out-of-memory error looks on the console.

Allocator Source Memory Used for
ZAllocatorBase system/mallocallocator.h the abstract interface: Alloc, Free, Shrink, Reset, SetAllocDirection, GetFreeTotal, GetLargestBlock
ZAllocatorNormal system/normalallocator.cpp one block, managed by a ZMalloc (zstdlib/zmalloc.cpp), a binned heap that rounds requests up to 16 bytes the Glacier heap; under AD_BACKWARD it carves from the end of the free block it picks, which scene loading uses for temporary buffers
C malloc the C library the heap after _end allocations before ISysMem exists and the global components (ZGlobalComponentAllocator)
ZPoolAllocator system/poolallocator.cpp a static buffer per pool, up to 32 pools small fixed families of objects, below; DoUnloadScene resets every pool
ZPoolAllocRefTab, ZPoolAllocLinkSortRefTab system/poolallocreftab.cpp a ZPoolAllocator reference tables whose blocks come from a pool
ZOffsetAlloc system/offsetalloc.cpp hands out offsets in a range: Alloc takes the low end of the smallest free range that fits, AllocHi the top of the highest one the draw arena of ZOldDrawBase (1,024 links), and script message bodies in a 4,096-byte stack buffer with 32 links (scriptc.cpp)
ZMallocSimple zstdlib/zmallocsimple.cpp a block from the heap the level script data (g_ScriptAllocator), sized by GetLevelScriptExtraSize: 0x14000 (M05) to 0x32000 (M08, M13) bytes

The five pools on the PS2, with their buffer sizes from the ELF:

Pool Buffer Bytes
ZItem::s_ItemMemoryAllocator ZItem::s_ItemMemoryBuffer 98,304
Animation::ActiveAnimation::s_AnimationCallbackAllocator s_AnimationCallbackBuffer 34,816
ZROOM::s_DynamicGeomsAllocator ZROOM::s_DynamicGeomsBuffer 32,768
ZLnkAction::s_LinkActionPool ZLnkAction::s_LinkActionBuffer 32,768
ZScheduledEvent::s_PoolAllocator ZScheduledEvent::s_PoolAllocatorBuffer 16,384

Fixed buffers outside the heap include the option store (g_GlobalComBuffer, 26,624 bytes), the ini and bindings files (g_IniFile, g_ConfigFile, 4,096 bytes each), the disc error texture (g_AlwaysGfx, 32,944 bytes) and the string memory manager (65,536 bytes, ZStringMemoryManager::StringBufferSize).

The draw arena is m_lMemorySize bytes allocated from the heap by ZOldDrawBase::InitAllocation, 0x310000 by default. SetupMemoryBuffers (startup.cpp), called from AllocSequence with the scene name, changes it per level and also sets the PS2 DMA chain sizes (VIF draw chain, GIF texture chain, light chain; 0x6000, 0x600 and 0x4000 by default):

Scene Draw arena Chain sizes
name contains hideout_ default 0x16000, 0x10600, 0x4000
M05_MAIN 0x360000 default
M06_MAIN 0x300000 0x8000, 0x600, 0x4000
M09_MAIN 0x388000 default
M10_MAIN 0x2E0000 default
M11_MAIN 0x2F0000 default
M12_MAIN 0x340000 default
name contains _news 0x168000 0xE000, 0x600, 0x4000

Files

ZSysFile (sysfile.h) is one interface for disc files, mounted zip archives, DLL loading (stubs on the PS2) and memory card saves. ZSysFilePS2::GetSize, Exists and Load first strip the system path (RemoveSysPath) and look the name up in the mounted archives; only when no archive has the file do they go to the disc through ZCDGetFileSize, ZCDGetSector and ZCDReadFile (cdread.cpp). Those find the file with sceCdSearchFile and read whole 2,048-byte sectors, copying partial first and last sectors through a sector buffer. While LoadWholeSceneZip runs (g_bPartialLoadEnabled), the read goes in 64-sector pieces and updates the loading bar after each one.

Before a disc lookup ConvertFilename and ConvertFilenameToMax8Chars rewrite the name for ISO 9660. A name without a device keeps only its last component under host0:. Then / becomes \, anything after ; is dropped, the name is upper-cased, each directory name is cut to eight characters, the device (host0: included) is replaced by cdrom0:\, a file name of 13 or more characters is cut to eight characters plus its extension, and ;1 is appended. host0:main.ini becomes cdrom0:\MAIN.INI;1.

Archives are "big files" in m_pBigFiles. ZSysFile::AddBig replaces the extension with .ZIP, opens the archive as an FsZip_t (zstdlib/iozip.cpp) either loaded whole (IOFS_PRECACHE) or read on demand (IOFS_READONLY), marks files the new archive also holds as invalid in the older ones, and puts it at the head of the list. DoLoadScene mounts the scene archive with LoadWholeSceneZip and RemoveAllBigs drops everything mounted. A buffer can be mounted too (UseBig(CHUNKFILE *, name)), which the scene load does for its unpacked GeomFiles.

On the PS2 the write path (Create, OpenForAppend, Save) ends in PS2Open, which in the retail build is a debug break; saves go to the memory card through the Mc* and *SaveGame functions (missions). Disc errors come back through ZCDErrorCallBack. CDErrorCallBack calls ZRenderDll::SetGlobalMessage, which saves the middle of the front buffer and draws one quarter of the g_pGlobalTexture image (insert disc, retrying, read error, waiting for the drive) at 256 by 64 pixels until ZCDRecover reports no error.

Configuration and the console

Options are strings in g_GlobalCom, a CGlobalCom over the static g_GlobalComBuffer. ZSysInterface::SetOption stores one, GetOption returns it, and code tests a flag option by asking whether it exists. LoadIniFile reads the ini file once into g_IniFile (it must be under 4,096 bytes) and ZIniFileParserSimple::ParseIniFile (inifileprocessor.cpp) turns each line into one option. A line is a name and its arguments, separated by the first = or by white space, with trailing spaces removed; a line whose first or second character is / is skipped. ZSysInterface::ParseOptions then copies the engine's options into fields (DefaultScene, ProjectPath, ScenesPath, TexturePath, ConfigFile, LocaleFile, NoBlood, HeroControlMode, AutoExit and others). ZSysInterfacePS2::ParseOptions adds ProjectPath without the Final\ suffix the base appends, ScriptDebugPrint and LoadFilter. Other code reads its own options where it needs them, such as DisableAudio, NoBriefing or PrintHighWaterMarks.

CConfiguration (cconfiguration.cpp, 0xC4 bytes) holds the player settings as statics. Load loads the key bindings from the ConfigFile (through LoadConfigFile into g_ConfigFile), reads the generic settings back from option names that start with strCC (and removals from strCr), and applies MouseSpeed (clamped to 0.1 to 2), InvertVerticalPlayer0 to 3, InvertHorizontalPlayer0 to 3, UseMouse, EnableCheats, ControlModePlayer0 to 3 and AutoSaveEnabledPlayer0 to 3. WriteIniSettings writes the generic settings back into the option store with the same prefixes, and its file variant WriteIniSettings(const char *) only returns false. AllocSequence calls InitActionMap and CConfiguration::Apply on every scene load.

The console has no code in the retail executable. console.cpp and consolecommand.cpp are empty units, the debug record still names the classes CConsoleCommandVar and CConsoleCommandVarb, ZRenderPS2::ConsoleDraw is empty, and ZRender::ConsoleDrawEnabled returns false, which also keeps the text and memory overlays off.

Input and actions

SysInput::instance is the input interface (sysinput.h). ZSysInput keeps up to 32 ZInputDevices, each with digital and analog controls, names for them and a history of the last four times each digital control changed. ZSysInputPS2 (newsysinputps2.cpp) opens one pad, port 0 slot 0, as a ZGameControlDevicePS2 with 16 digital and 4 analog controls and a dead zone of 0.3. Its Update runs the inactivity callback that the demo timeouts install, opens the controller-missing window when no pad is ready, and otherwise polls the devices.

Game code reads most input through named actions held in Action::ZHandle objects (137 in src/, such as a_Pause("Pause") or a_crouch("CrouchSneak")). ZActionManager (actions_new.cpp) maps each name to an expression tree over device controls. Bindings are text, collected from the 15 Action::ZStaticBinds blocks compiled into the executable and from the bindings file. Operators come before their operands:

static const char *HitmanControlDefs =
    "HMControl={ReloadWeapon=tap(kb,r);"
    "FireWeapon=hold(ms,left);"
    "FireWeapon2=|hold(ms,mb4) hold(kb,x);"
    ...
    "MoveHor=- get(MoveRight) get(MoveLeft);"

The keywords are tap, hold, release, downedge, fasttap, doubleclick, holddown, clickhold, press, ana, rel, seq, get, true and false. A handle caches its tree and looks the name up again whenever ZActionManager::m_iSeq changes, which happens each time bindings are added. How objects offer actions to 47 is a separate system, described in events, messages and actions.