Skip to content

Knowledge base: new levels

What we learned making levels the disc does not have. The format pages (docs/internals/formats/) hold the byte layouts; new-scene.md holds the build steps. The tables below describe failures seen while developing the builder. This page holds everything else worth keeping: decisions and their reasons, the engine's rules, dead ends, open questions, and how the work is tested. All of it dates from November 2026.

Decisions

Decision Why Rejected
Build real scenes, not mods layered on an existing level A Lua mod cannot create geometry, collision, rooms or navigation, or spawn actors. A level on top of an existing one keeps that level's floor and AI paths. A "mod-built level" on an existing scene, with props and recast NPCs.
First prove every format by a byte-for-byte rewrite of all 71 disc scenes The test cannot be faked, and a writer that reproduces the disc can be trusted to write new data in the same shape. Writing new files from the documentation alone.
Start a level from a stripped disc scene (the "base") The objects 47 and a mission need (47's setup, camera, HUD, game data, level control, item groups, character assets) come with it. Building those from nothing.
Base for an empty room: the hideout; for a mission: A Vintage Year (M01_main) The hideout is the smallest scene with a playable 47. M01 has generic guards and civilians, a simple level control (two targets, an exit list, an escape) and its script module. M08 (its level control dereferences a removed river-bank list at start), M06 (parade float, club music and dance animations).
Strip the base rather than merge characters into it Merging moves prims, textures, animation collections and sound offsets between archives. Stripping keeps every character's assets in place. Merging (still open, needed for characters from other missions).
The repository never holds game data Tools read the player's ISO at build time; the repository holds tools, specs, our own content (textures, sounds, the showcase .glb) and docs. Committing built archives.
Level mods are recipes that the port builds from the player's own disc (23 November 2026) A built level contains disc data, so sharing it would ship game data. A recipe (model, level.json, our photos, sounds and text) holds only the modder's work. See architecture.md. Prebuilt levels; a bundled Python builder.
Mission logic is Lua, in the level mod (23 November 2026) It matches the rest of the modding system. A level only ever runs in the port, and the Lua runtime already has the events, obm.mission, obm.scripts.replace and the typed obm.api bridge to the game's own script interfaces. A per-level C script compiled with the script SDK (worked in milestone 4, but needs the PS2 toolchain and ships disc code); a generic C script compiled into the port.
A level's mission file runs only while its scene is loaded, in its own environment, and what it registers goes with the scene (phase B) A mod's entry script runs at startup for every scene; a mission written there must guard every listener, and its message hooks and replacements would apply to the stock mission it is built on. Scoping in the runtime keeps a mission file to its rules and lets several level mods coexist. Guards in each mission; reloading all Lua at each scene change.
A Lua mission keeps the base module and gives the level control alllevels\levelcontrol The base module runs as native code and holds the actors' scripts. The shared base level control has no mission logic but receives the exits' messages, which Lua hooks see. Replacing M01's level script with obm.scripts.replace (needs scoping by level for every M01 game, and its imports would still point at M01's objects); no script on the level control (the exit message would reach no script).
A custom level gets its own row of the level table, swapped in by the port at run time (phase A) GetNextSceneName builds the briefing, level, debriefing and newspaper names from the row's name, and the menus key their text by it. A row of the level's own gives it scenes the disc does not have, so the overlay never replaces a disc file; the slot keeps its number for loadout and statistics. The table's pointers are not const, so no src/ change is needed. See front-end-scenes.md. An overlay that may replace disc archives; a 14th row (changes the PS2 data layout); a src/ hook in GetNextSceneName.
Front-end scenes are edited in place; no geom is added Adding a geom shifts every later run-time REF, and with it the OCT, room trees and the GMS light lists. The main-scene builder clears light lists, which a lit menu scene (weapon models, the debriefing's cellar) would miss. Texels, PRM blocks, LOC, PRP values and geom names change without moving anything. Running the main-scene builder on the briefing scene.
A third target's briefing picture renames an unused graphic The briefing asks for <n>Picture by name, and M01 has two. The sixth objective's arrow (BriefingNotCompletedArrow#05) is the same kind of graphic (a ZWINGROUP with one ZWINPIC) and is unused with up to five objectives. Cloning 1Picture (adds geoms).

How a scene is loaded

  • ZEngineDataBase::DoLoadScene mounts the scene archive, ZEngineDataBase::AllocSequence reads its members in a fixed order (src/engine/enginedata/enginedatabase.cpp). The order and the reading function for each member are in scene.md.
  • The engine mounts a scene archive by reading disc sectors, which bypasses the port's mod file system. port/engine/system/_sdl/cdreadsdl.cpp has a disc overlay: when the disc has no file at a path, an active mod's raw/<disc path> stands in, read through virtual sectors. The disc wins when it has the file, so a mod can add a scene but not replace one. A recipe level therefore gets scene names of its own (<code>/<code>_Premission, _main, _postmission, _News) through its own row of the level table (front-end-scenes.md).
  • The port cuts every path part to 8.3 (DiscFileName): GC1/GC1_postmission is SCENES\GC1\GC1_POST.ZIP. A scene code longer than 5 characters gives the briefing and the debriefing the same file.
  • The scene's effects bank is the loose .WAV/.WHD beside the archive. Dialogue and music stream from PS2_Eng.str.
  • A scene script module is found by name (ScriptCModule), and the port runs it as native code built into the executable from src/scripts/<LEVEL>/ (docs/development/port/native-scripts.md). A level mod therefore runs the base mission's scripts (M01). Since 24 November 2026 there is no emulated CPU, so a script module a mod ships (raw/SCRIPTCS/_GAMEREL/<NAME>.PS2, the old compiled-C route) is never run; level logic is Lua.
  • A level's Lua mission (levels/<id>/mission.lua, named by the mod.json level entry) is loaded with the scene's first script when that level is the active custom level and the scene is its base_scene, and removed with everything it registered when the scene goes (mission-script.md).

Rules the engine imposes

Each of these cost a crash, a black screen or a silent failure.

Archive members

  • .SUP must exist (24-byte default). .ZGF and .SGD may be left out.
  • Never leave out .RMC: the static line and box queries read the room tree without a null check (an empty RMC is 32 bytes).
  • Never leave out .SGP. It is the sound graph, not AI navigation, and without it NPCs hear nothing (empty graph: 20 zero bytes).
  • An .ANM, if present, must contain chunks 4, 8 and 9.

Scene name and object tree

  • A scene's path decides CountNrGeoms: _main scenes get fixed amounts subtracted. A small new scene without _main is safe. A stripped mission scene keeps the base scene's counts.
  • GMS physics offset: 0xffffffff means none. Zero makes the engine parse the BUF magic as physics data.
  • The PRP object tree is the GMS tree in the same order, with the same child counts, minus ROOT. PRP values for Matrix, Position and Prim override the GMS copies. The PRP names no classes; the GMS type field does.

Collision and rooms

  • .OCT, .RMC and .RMI leaves are run-time base-geom slot REFs (root = 1), not GMS geom numbers. Write them after the object layout is final.
  • Collision stores no triangles. OCT trees index windows of up to 16 vertices of the PRM render strips. A prim's lColiId is (record offset + 4) | 1.
  • 47's ground and wall tests use the Sight collision bit 0x20. Visible meshes on the disc don't set it, so new geometry needs collision bits 0xe2 on the geom and 0x62 on the prim, or 47 falls forever.
  • The RMC line test trusts the tree bounds alone, so the bounds must cover the room's collision geometry.
  • When patching prim records, touch only blocks that prm_dump.classify accepts as mesh records. Bone tables, UV data and vertex data can look like records. The builder once rewrote 1,520 of them on the M01 base, and characters lost forearms and shoulders (fixed; failure row 13 in new-scene.md).
  • Every strips prim needs a bounds header, or the engine stops in a debug break.

Rooms and portals

  • Portal (ZExit) corners are ordered so their normal points into the room.
  • The room must stay inside the base scene's root tree frame.
  • A room without lights draws characters black. Add an ambient light and a character light.

Characters and sound

  • A guard only takes his weapon and starts his patrol when his quarters object has a guard-quarters controller.
  • A positional sound plays only when its emitter's parent is a room.
  • LOC subtitle sound ids are SND offsets; copying a LOC to a scene with another SND needs them rewritten.
  • The WHD and WAV are read by the IOP sound module (SYNTHCD.IRX), which is not decompiled. Several WHD fields are unknown; new sounds copy a template record.

Menus, text and front-end scenes

  • The menus key a mission's text by the level table row's name: /<name>/MissionObjectives/<n>/…, <name>/MissionBriefing/<name>_MB_<nn>D, AllLevels/Interface/LevelNames/<name>, <name>/Map/…; money.xml has <Level name="<name>"> rewards. The newspaper keys by the slot's number instead (NewsPaper/Articles_M<n>, NewsPaper/Statistics/MissionData/<field>/<n>), and its headline story is a template filled from that data. The number is atoi of the level name after its first letter (ZStatisticsTest::GenerateText): M01 is 1, a scene code GC1 is 0. Picture captions use keys fixed in the scene (Target1PictureText/1), not that number.
  • A menu picture is a ZWINPIC whose PicResourcePrim is a PRM block of sprites (SSpriteArrayElementUV) and sprite-array prims, one texture each (lTextureId at byte 4 of the prim). M01's target photos are 79 x 85 in three 16-colour strips; the newspaper page is 80 tiles of 128 x 256. Texels map to the picture by the sprites' places and u/v ranges, top row at v = 1 (frontend.render_picture).
  • The briefing finds a target's photo by the graphic's name, <n>Picture (ZHM3BriefingDetail::Setup), through the resource manager's Graphic group; the objective arrows come from the same lookup with a wildcard.
  • Two textures may share one texel block (M01's two photos share their fully transparent bottom strip); repainting in place must skip those.
  • ZHM3LevelControlM01::Init calls SetCurrentLevel("M01"). With the row renamed it finds nothing and changes nothing; on the stock row it resets nextSceneNameType.
  • CompleteCurrentLevel sets the step to NAME, so GetNextSceneName after a mission gives the debriefing, then the newspaper (by the last completed level's row), then saveandcontinue.
  • The pause map is map rooms (ZROOM with MapGroup controllers naming the world rooms or groups they show, m_szName a LOC key). Their meshes sit at world coordinates and are hidden at start (CMapGroup::Init2). A map room needs no room-tree box; with one, 47 could be "in" it.

Scripts

  • (Compiled route, retired.) A script module's name had to end with M01 and be at most 8 characters, because the engine sizes the script allocator by finding M01.ps2 in the name.
  • A Lua mission's level control keeps a script: alllevels\levelcontrol, the shared base level control in every disc module, which has no mission logic. The exits' ZAction sends its message (M01_ExitPlane) to the level control object, and only a script there receives it, where obm.scripts.on_message sees it. With M01's own m01\m01_levelcontrol left in place it would register Don and his son and drive M01's exits.
  • obm.scripts.replace only replaces a script the module has and the scene names: a scene cannot name a script the module lacks and have Lua run it.
  • Script messages (M01_ExitPlane, CutSequence_StartScene2, ids 0x800 and up) have no name in ZEngineDataBase::GetZMsgName, which answers "" from 1024. Lua hooks by name now match them by id (ScriptEngine::GetRegisterZMessageID of the lower-case name).
  • ZVideoPlayer takes CutSequence_StartScene2 (0x80c) with no data and then sends its end message to its own m_rEndMessageTarget, so obm.scripts.send(EscapeCut, "CutSequence_StartScene2") is enough to start M01's escape; CutSequence_End reaches ZHM3LevelControlM01::Command, which calls MissionCompleted.
  • Objective bits are a byte (ZHM3BriefingControl::m_lObjectiveCompletedFlags): at most 8 objectives. ZHM3LevelControl::m_arTargets has 6 slots and SetTargetNum does not check the number, so only targets 1 to 6 may be registered. Kills are counted by character type, not by these slots.
  • Disc missions' objective types are T (target), E (exit), O (optional), R and P (M02, M04, M05, M06, M08, M09).

Textures and meshes

  • Texture ids must stay below 2048. The formats used are p4, p8 and rgba32 (alpha test and alpha blend both work).
  • A mesh chunk holds at most 62 vertices and 16 strips, the maximums measured on the disc. Large meshes are split into sub-prims, about 4,000 triangles each.

Navigation

  • The AI pathfinder (Pathfinder4) lives inside the .GMS. Within a single graph each (x, z) maps to one area, so stacked stories cannot share a single graph. Multi-story custom levels (tools/port/scene/navmesh.py, tools/port/editor/blockout.py) emit one Pathfinder4 graph per floor elevation and join them with inter-graph exits for stairs, ramps and climbable links.

Direct PS2 map editing

  • Campaign scenes mix single-panel doors (ZSTDOBJ with a SingleDoor controller) and multi-panel doors (ZGROUP with a MultiDoor controller whose panels are child ZSTDOBJ leaves). Moving or rotating a stock door (tools/port/editor/doors.py) updates its transform in both .GMS and .PRP (keeping child leaves moving with a ZGROUP pivot) and updates the enclosing room's .OCT tree bounds.
  • Per-instance hiding must never mutate shared .PRM records. Multiple PS2 doors and props share a single .PRM mesh handle. To delete/hide one instance safely, zero compiled.prim = 0, set its .PRP "Prim" to 0, and prune only that instance's run-time ref from its enclosing room's .OCT tree (for hidden doors, also set InitialState = IDS_OPEN and AutoClose = False so characters and 47 walk straight through). Mutating the shared .PRM record would make every sibling instance disappear too.
  • Upright pure-yaw prop filter. Only upright, unscaled, non-mirrored ZSTDOBJ room props (tools/port/editor/stock.py:is_editable_prop, excluding structural room shells and door nodes) are exposed for direct X/Y/Z + Yaw editing so scene.yaw_matrix rotation is lossless. "Hacienda rug" in M01 remains floor-locked inside its room bounds; all other editable PS2 props and doors move freely in X/Y/Z and yaw.
  • Glacier ↔ glTF / Blender yaw math. Glacier's yaw_matrix(a) combined with its Z-flipped world position (wx, wy, -wz) matches local glTF vertices (vx, vy, -vz) rotated by quaternion (0, sin(a/2), 0, cos(a/2)), and tools/port/blender_addon/openblood_blender/coords.py maps Blender Z-up metres (X, Y, Z) cleanly to Glacier Y-up centimetres (X * 100, Z * 100, Y * 100) so 3D viewport previews align directly with the running game.

Hybrid stealth sandbox & hard engine/port caps

  • Custom missions combine compiled Glacier binary data (rooms, portals, collision, Pathfinder4 navmeshes, native doors/pickups/actors, baked vertex lighting) with a level-scoped Lua 5.5.1 runtime (tools/port/editor/sandbox.lua, triggers.lua, lighting.lua, sound.lua, cameras.lua, pickups.lua) for stealth systems the original PS2 binary builders do not synthesize directly (disguise zones, CCTV cones and VCRs, body containers, climbables, sabotage/accident setups, multi-floor elevators, weather/atmosphere and custom rules).
  • Hard caps to respect when designing levels (verified in src/ and port/): at most 8 objectives (byte bitmask m_lObjectiveCompletedFlags), 6 target slots (m_arTargets), 16 dynamic Lua surface lights (MOD_LUA_MAX_DYN_LIGHTS), 32 custom contextual prompts (MOD_LUA_MAX_ACTIONS), 64 disc overlay files (OVERLAY_MAX_FILES in cdreadsdl.cpp), and 500,000 Lua instructions per call (MOD_LUA_INSTRUCTION_LIMIT, 256 MiB Lua heap cap).

Port quirks met on the way

  • A level started with DefaultScene= crashes after the escape: the next scene it loads has no .SUP. Stock M01 does the same, so start missions through the launcher (OPENBLOOD_LAUNCHER_PLAY=quick OPENBLOOD_LAUNCHER_MISSION=13 for scripted runs).
  • A disc path on the command line skips the launcher.
  • Lua: obm.world.set_pos does not move 47. Explosions do not hurt 47, and health 0 leaves him standing. A scripted death is health 1 followed by Silevelcontrol__Killhitmanincloset.
  • Lua: obm.scripts.on_message by name never fired for script messages before 23 November 2026 (see Scripts above); a "*" hook sees their msg as "".
  • Lua: an object named Controllers!EscapeCut in the scene tree is found by that whole name (obm.world.ref), not by EscapeCut.
  • Scripted input: the launcher's PC keyboard layout does not stop pad cross from using an action; 1300 60000 cross 1.0 900 20 uses the exit as before.

Open questions

  • ANM: the layout of the raw animation data in chunk 4, which blocks compacting animations and adding new ones.
  • WHD: the IOP-only fields.
  • Rooms: what the original tool used for about 15% of room-tree object bounds, and where the mission scenes' room-tree frame comes from.
  • Collision: which geoms go into each bound tree, and three OCT header words.
  • SGP: route order within a (room, type) group, M09's via-room table, and the room numbering rule.
  • BUF: blocks only the PRP points at (exits, crowd data, animation keys) round-trip but are not decoded field by field.
  • PRP: what most properties mean beyond their names, and why about 240 matrices and positions differ from the GMS.
  • AI: NPC reactions to 47's own gunfire or weapon are untested.
  • Light lists: a list entry's slot (entry + 0x60) / 0x70 maps onto the simulated REFs as neither slot nor slot + 1 consistently (premission: 69 std objects and 46 omni lights with slot; 70 lights and 50 std objects with slot + 1). Remapping light lists, needed to add geoms to a lit scene, waits on this.
  • Debriefing backdrop: the debriefing's wine cellar is a lit 3D room; building it from a recipe's geometry needs the light lists above, or a scene without lights.
  • Music: mission music streams from PS2_Eng.str under the music controller (ZHM3LevelControlM01::MusicInit); a level's own music needs a stream the port can read beside the disc's.
  • Showcase: the office guard poses without a weapon in his hands, and the office lighting is dark on characters.

How the work is tested

  • Format proof: python -I tools/port/scene/roundtrip.py rewrites all 71 scenes with every module. Each module also has roundtrip and selftest commands.
  • Builders: each spec must rebuild byte-identically. A change to the builder states which specs change and why.
  • In the game:
    • capture PNGs: OPENBLOOD_CAPTURE_DIR, OPENBLOOD_CAPTURE_EVERY, and OPENBLOOD_CAPTURE_OVERLAY for the ImGui layer;
    • Lua probe mods that log positions and events and kill targets;
    • scripted input: OPENBLOOD_INPUT_SCRIPT;
    • mod isolation: OPENBLOOD_ONLY_MODS=1 with OPENBLOOD_ENABLE_MOD;
    • per-run settings: OPENBLOOD_SETTINGS.
  • Visual checks: compare against the stock level with the same framing; for rendering bugs, start from what the stock base looks like.
  • Set OPENBLOOD_USER_DIR to a separate test directory before starting the launcher or game. Compare stock and custom levels with the same input and camera position.
  • Stock levels unchanged: deterministic traced runs (OPENBLOOD_DETERMINISTIC=1, OPENBLOOD_TRACE_SCRIPT_CALLS=1, OPENBLOOD_TRACE_SCRIPT_RUNS=1) of a stock scene with the build before and after a change, compared with tools/port/native_scripts.py compare.
  • PS2 build: any src/ change must keep it exact. None of the level work needed one.
  • Environment pitfalls:
    • Bash heredocs lose a level of backslashes (write files with an editor).
    • Input-script ticks are controller polls, not frames: in the briefing menus about three ticks pass per captured frame.
    • The briefing's buttons are pad buttons: cross opens the objectives (target pages), down steps through them, triangle goes back, start goes to weapon selection.
    • Pad names (Up, cross) press the emulated pad.
    • OPENBLOOD_DETERMINISTIC must be unset, not 0.

Failures and fixes

# Symptom Cause Fix
1 The scene archive was never mounted from a mod. A loose .PRP would have dereferenced null in CreatePropertyInputStream. ZSysFile::AddBig checks the disc only (Exists(name, true)), and FsZip_t reads the archive by disc sector. Neither looks at the mod file system. Disc overlay in cdreadsdl.cpp: a mod's raw/<disc path> stands in for a disc file that does not exist.
2 The scene loaded, but the screen was black apart from the HUD, and 47 fell forever (y −170 after a second, −1,800 after ten). The room, its tree and the collision data were right: probes found NewRoom in the room tree, RoomShell in its bound tree, and a hit from a line test with an all-bits mask. 47's ground and wall tests use COLIMASK_Sight (0x20), and the mesh had only Background (0x82 on the geom, 0x2 on the prim). He fell out of the room, so it stopped being drawn. Geom control byte 0xe2 and prim lColiBits 0x62: Background, Sight, Hero (and Camera on the geom).
3 47 was drawn as a black silhouette. The room had no lights, so CalcBoneEnvironment found no environment. A room EnvironmentLight _env_ambient and a _env_character ZENVIRONMENT with CharacterLight, both with new type-12 light prims, listed in the room's GT_Lights tree.
13 Characters' skinning broke: on the M01 base 47's forearms and cuffs stuck out sideways from his sleeves, Don's son lost his belt and his shirt's shoulders, the guards' forearms came loose; on the hideout base 47's collar was torn. keep_coli_trees walked every .PRM handle and rewrote the lColiId word (0x30) of any block whose header read as a strips record. Most of those 1,500 blocks were not records but bone tables (lLocalBonesQuats, lInvertGlobalBones, lBoneDefinitions, lBoneIndexToIdLookup2), UV and vertex streams; repacking also rewrote the float at 0x44. Only the records prm_dump.classify accepts are repointed or cleared. Every prim that owns a collision tree is among them.
— Avoided: a _main scene with few geoms would make CountNrGeoms underflow. The _main subtraction. Keep the base scene's type counts, which only grow.
— Avoided: removed objects left dangling paths (20 of them, mostly the level control's weapon lists and clone-group owners). scrub_references clears every path that no longer resolves.

The black screen and the fall in row 2 were diagnosed with a probe mod (obm.world.player, obm.camera.get_pose, obm.world.raycast, obm.world.find_geom) and a temporary log in the port. The log called GetInnerRoomsLst, GetStaticGeomsInBound, CalcLineCollision, CalcLineColi and GetStripsInsideBox, and the pathfinder queries. The log has been removed.

Failures and fixes (mission)

# Symptom Cause Fix
4 The guards stood still at their starts, in an arms-out pose without their rifles, while the worker walked his route. Alllevels_Guard's root enter reads the controller of its quarters import (Zgeom__Getcontroller(quarters, "ZGuardQuarterController")). Without one it skips weapon setup and ChooseDefaultStates and parks the guard in DragAmbientState. Our scrub had emptied quarters. Clone a guard-quarters box (Quarters) and point every guard's quarters at it. Its m_rWeaponStorage may be empty, since ZGuardQuarterController checks it.
5 After the escape the process stopped on an illegal instruction in ZEngineDataBase::DoLoadScene. A DefaultScene= run is a single-scene run; the next scene it loads after the debriefing stats has no .SUP. The stock M01 started the same way crashes the same way. Start through the launcher's quick start (OPENBLOOD_LAUNCHER_PLAY=quick, below).
6 Scripted escape presses missed or skipped the debriefing. Input-script ticks are controller polls and do not follow game time; a dense press train also skips the debriefing screens. One cross pulse every 900 ticks from tick 1300.
— Avoided: our room meshes' lColiId collided with base prims' old offsets when several collision trees of ours come first. keep_coli_trees skips our mesh handles and maps every other prim through the old-to-new table.

Failures and fixes (glTF levels)

# Symptom Cause Fix
G1 Background colour showed through a 20 cm strip across each doorway's floor. Each room's floor stopped at its own wall face, and the wall slab between them had jambs and a soffit but no floor. doorway_reveal adds a threshold floor.
G2 Some faces were lit from the wrong side, and lights behind a wall lit it. The generator's walls ran so that their fronts faced out of the room, and the axis change mirrors, which flips every face. Walls run counter-clockwise round a room with their fronts inward; the tool flips each triangle's winding when it mirrors the axes, so face normals stay the modelled fronts.
G3 build() stopped on self.rects after the GMS was written. The report line counts navigation components through self.rects. GltfBuilder.make_navigation sets it to the polygons.
G4 Characters in the showcase's office were dark: faces and fronts unlit, only the tops of heads bright. The office lamp hangs over the room's centre, so room_lights aimed the _env_character light straight down (pitch 90°). The character light keeps the lamp's bearing but comes in at 50° at most (MAX_CHARACTER_PITCH), as the box rooms' hand-set lights do; a lamp right overhead keeps the default bearing. This changes showcase.json's archive (the light records and matrices only).
— Avoided: render steps and a slope colliding together would make 47 trip on step edges. Steps collide = false, a col_ slope through the nosings.