Skip to content

Rendering

This page describes how Glacier draws a frame on the PS2: the renderer classes and how they connect, visibility through rooms and portals, the sorted draw list, the DMA chains that feed the VU1 microprograms, materials, lighting, shadows, water, sprites, the post filters and the GS frame buffers. All of it comes from the decompiled source in src/engine/drawing/ and src/engine/rendervideo/, which compiles back into the original executable.

The renderer classes

The renderer has three layers. Platform-neutral interfaces sit in src/engine/drawing/. The "old" renderer in src/engine/drawing/old/ keeps per-object state and does visibility and sorting. The PS2 classes in the _ps2 directories turn the result into DMA chains. Most of the code is in zolddrawbase.cpp (114 functions), zoldviewbase.cpp (108), zoldviewps2.cpp (71) and zolddrawps2.cpp (66).

Class Declared in Job
IDraw, ZRenderDrawBase src/engine/drawing/renderdrawbase.h The draw interface. IDraw::Instance() (irender.cpp) returns the first window's draw base. It holds up to 32 views (m_Views, m_ViewNumberToPointer).
IView, ZRenderViewBase src/engine/drawing/renderviewbase.h One view: a viewport (m_lViewPort), a scissor override, up to 16 cameras, a post filter (m_pPostFilter) and a draw surface (ZDrawSurface::SCREEN or TEXTURE).
ZRender src/engine/drawing/renderbase.h One window: the camera list m_Camera (a LINKSORTREFTAB sorted by priority), the 256-entry LOD tables m_LODTableBackground and m_LODTableCharacters, the draw base m_pRenderDraw, Update and Flip.
ZRenderBaseDll src/engine/drawing/renderbase.h The scene's prim and texture buffers and their install functions. g_pRenderDll points at it.
ZOldDrawBase src/engine/drawing/old/zolddrawbase.h Draw entries shared by all views, the per-frame light and bone work, and the dynamic shadow pass.
ZOldViewBase src/engine/drawing/old/zoldviewbase.h Per view: view entries, visibility (GetVisible), the sorted draw list m_DrawSortList (4,096 entries) and the mirror id lists.
ZRenderPS2 src/engine/drawing/old/_ps2/renderps2.h The PS2 window: ZPS2Setup m_Setup, two pairs of draw and texture chains, the VU0 light chain and the PS2 Flip.
ZRenderDll src/engine/drawing/old/_ps2/renderdll.h The PS2 buffer installer. It creates the ZRenderPS2 and a ZPrimControlPS2, and holds 2,048 texture pointers (m_pTextures).
ZOldDrawPS2 src/engine/drawing/old/_ps2/zolddrawps2.h PS2 draw entries with prebuilt DMA chains, texture upload chains, the static light chain and shadow casters.
ZOldViewPS2, ZCameraViewEntryPS2 src/engine/drawing/old/_ps2/zoldviewps2.h Walks the sorted list and writes the frame's VIF1 chain. The camera view entry holds a camera's matrices, clip planes, fog and scissor in the form the VU programs read.
ZPS2Setup src/engine/drawing/old/_ps2/ZPS2Setup.h Video mode, GS memory layout, display registers and GIF tag templates.
ZDMAChain, ZGifChain, ZVifChain0, ZVifChain1 src/engine/drawing/_ps2/zdmachain.h DMA tag chain builders for the GIF, VIF0 and VIF1 channels.
ZPostFilter, ZPostFilterPS2 src/engine/drawing/zpostfilters.h, src/engine/drawing/old/_ps2/zpostfiltersps2.h The screen effects of one view.
Z2DFunctions src/engine/drawing/old/_ps2/z2dfunctions.h Frame-buffer copies, fills, scales, blurs and palette passes (g_2DFunctions).
ZBaseVideo, ZPS2Video src/engine/rendervideo/basevideo.h, src/engine/rendervideo/_ps2/ps2video.h Movie playback.

ZRenderDll::Init creates the ZRenderPS2. Its constructor creates the ZOldDrawPS2 and sets the chain sizes: 0x6000 quadwords for each draw chain, 0x600 for each texture chain and 0x4000 for the light chain. When a camera is added to a view id that has no view yet, ZRender::AddCameraToView creates one over the whole window with the post filter enabled. ZOldDrawPS2::NewView makes it a ZOldViewPS2, and ZOldViewPS2::CreatePostfilter gives it a ZPostFilterPS2.

Draw entries and view entries

Every geom the renderer has seen has a draw id (ZBaseGeom::m_lDrawId, masked with DRAW_ID_INDEX_MASK 0xfff) that indexes ZOldDrawBase::m_pDrawIdToPointer and each view's own table. The draw base keeps one draw entry per object, and each view keeps a view entry per object it has seen with the per-camera state. Both derive from ZOldDrawResource. Sizes are from analysis/recovered-types.h.

Object Draw entry View entry Holds
camera ZCameraDrawEntry (0x10) ZCameraViewEntryPS2 (0x590) transfer matrices, planes, fog, scissor
room ZRoomDrawEntry (0x70) ZRoomViewEntry (0x14) the room's bound array m_pBoundArray and geom array, rain splash seeds
geom ZGeomDrawEntry (0x60) ZGeomViewEntry (0x20) root matrix, bones, environment light, LOD level, active prim instances
prim ZPrimDrawEntryPS2 (0xe0) ZPrimViewEntry (0x14) GS registers m_Regs, prim chain m_Chain, light chain m_pLightChain
prim instance ZPrimInstDrawEntryPS2 (0x24) ZPrimInstViewEntryPS2 (0x80) instance chain m_pDMAChain, light colours, view chain m_Chain[24]
texture ZTextureDrawEntryPS2 (0x2d0) ZTextureViewEntry (0x10) two ZTextureSetupPS2 (0x160 each)
light ZLightDrawEntryPS2 (0x50) ZLightViewEntry (0x10) root matrix, the slot in the frame's light block
portal ZExitViewEntry (0x34) the portal window clipped so far

Entries live in block arrays (ZOldDrawArray, zolddrawarray.h), and the lists the frame walks (m_Geoms, m_Lights, m_Rooms, m_UpdateViewDrawEntries and others) are ZOldDrawList block-linked pointer lists. Each view entry records the frame it was last seen in, and entries not seen this frame leave. A resource that leaves goes into m_Garbage, a ring of 8,192 (ZOldDrawGarbage). If it enters again it comes back with its chains intact. ZOldDrawBase::Cleanup frees those that left more than 8 frames ago. EndFrame gives it 0x61a80 timestamp cycles, and more once the ring is over a quarter full.

One frame

ZEngineDataBase::MainLoop (src/engine/enginedata/enginedatabase.cpp) calls ZRender::Update on every window after the game update. The order of work:

Step Function Work
1 ZRender::Update, BeginScene Returns unless a prim buffer is installed. BeginScene increments m_lFrameCount and flushes the draw base when ShouldFlush returns true.
2 ZRender::UpdateCameras BeginFrame (shadow counters), ZOldDrawPS2::Update, then EndFrame (garbage cleanup).
3 ZOldViewBase::GetVisible For each active camera, BeginCamera (scissor) and UpdateCamera (visibility). Rooms not seen leave.
4 ZGeometryDecal::Update Decals added through IDraw::AddMark (src/engine/geomsbase/zprojectmarks.cpp).
5 ZOldViewBase::Update Geoms and lights that left are removed, LOD changes reallocate prim instances, and entering prim instances get sort entries.
6 UpdateBoneModifiers, UpdateLightList, ZOldDrawPS2::UpdateLight Bones, and the VU0 light chain for static geometry.
7 ZOldDrawBase::Draw Each view's Draw writes its part of the VIF1 chain. After the first pass HandleShadows runs and the views continue.
8 ZRenderPS2::Flip Updates the data the chains point at and starts the chains.

ZOldDrawBase::Update (zolddrawbase.cpp) is steps 3 to 7:

for (a = 0; a != lNrUpdateViews; a++) {
    UpdateViews[a]->GetVisible();
}
m_GeometryDecal.Update();
for (a = 0; a != lNrUpdateViews; a++) {
    UpdateViews[a]->Update();
}
UpdateBoneModifiers();
UpdateLightList();
UpdateLight();
Draw(UpdateViews, lNrUpdateViews);

ZRenderPS2::Flip (renderps2.cpp) first waits for the previous frame's VIF1 chain (WaitVU1Done). It then calls UpdateDynamic on the draw base, which writes the data the chains refer to: water ripples, the wobble time, scrolling and animated textures, moving matrices, deform bones, bone lights and every camera's transfer matrices (ZCameraViewEntryPS2::Update). It starts the VU0 light chain (ExecuteVU0Lists), busy-waits until m_lMaxFrameInterval fields have passed since the last flip, waits for vertical sync (sceGsSyncV), copies the draw buffer to the display buffer (ZPS2Setup::CopyDrawToDisplay) and runs the flip callbacks. ExecuteDrawLists closes the chains written in step 7, starts the GIF texture chain and the VIF1 draw chain, and switches to the other pair (m_pVifDrawChain1 and 2, m_pGifTextureChain1 and 2). The GS draws frame N while the CPU builds frame N+1, and frame N reaches the display buffer at the next flip. Frame rate covers m_lMaxFrameInterval.

Visibility

Rooms and portals

ZOldViewBase::UpdateCamera sets the camera's six clip planes (SetCam6ClipPlanes) and calls FindVisibleAndAddResourcesToView. That starts with LocateRoomsAndExits. ZCollisionBase::GetInnerRoomsLst finds the rooms holding the camera point from the room inside tree, the .RMI octree. It is the camera's only octree query; decals (GetStripsInsideBox) and the shadow list (GetGeomsInBoxLocal) use the collision trees separately. CalcCameraExit turns the screen corners into a camera portal of four planes, and CheckExitsInRoom recurses through each room's ZROOM::ZExit records. An exit must have EXIT_CONNECTED, must not have EXIT_CLOSED, and must lead to a room that is not already on the draw stack. InitializeExit projects it, ExitVsExitChck clips it against every portal window that reached the room, and the neighbour gets a new ZExitViewEntry with the clipped window. A camera sees at most 128 rooms (ZStackArray<128, ZTempRoom>). Rooms named in a room's m_rAttachedDrawBaseGeoms are added with GROUP_CONTROL_NO_FAR_CLIP.

A camera with CAMERA_DISABLE_GATES skips rooms and portals. GetVisibleGeomsRecur walks the scene graph from the camera root and tests each group's and geom's bounding sphere against the planes. When the camera also has CAMERA_OVERLAY, the plane tests are dropped.

Bounds inside a room

Inside a room there is no tree. ZOldDrawBase::GetGeomsInRoom gathers up to 2,048 geoms (static draw geoms, static lights and the geoms listed in the neighbour exits, moving geoms first), and the room keeps one 64-byte ZBoundElement per geom: centre, radius, matrix and size. UpdateRoomGeomsArray re-transforms the moving ones each time the room is checked. CheckAllStaticGeomsInRoom hands the whole array to doSpeedCheck (src/engine/drawing/old/_ps2/spherechecks.cpp). That function copies the camera planes and up to 24 portal windows into the scratchpad and tests the bounds 83 at a time, writing two bits per bound: sphere outside and hidden. Rooms with GROUP_CONTROL_NO_FAR_CLIP are tested with the far plane moved to 1,000,000. AddVisibleGeomsInRoom reads the bits back (FindNextBits2Scan) and enters each visible geom and light. Dynamic geoms and lights come from ZROOM::GetDynamicDrawGeomsLists and GetDynamicLightsInRoom and go through the same test in CheckAndDrawDynamicsGeomsInRoom.

LOD and draw updates

For each visible geom the LOD index is the distance to the camera times tanf(fov / 2) * 0.01 / tanf(DegToRad(67.4) / 2), clamped to 0..255. It indexes m_LODTableCharacters for ZLNKOBJ geoms and m_LODTableBackground for the rest, and m_lLODLevelNew becomes 1 << entry. GetLODMaskOverride and hide/unhide requests replace it. Geoms with a draw update (CONTROL_DRAWUPDATE) have ZGEOM::DrawBufferViewUpdate(ZDrawBuffer *, ZCameraSpace *) called. Particles, the HUD and other geoms submit sprite and bone arrays there through ZDrawBuffer::DrawSpriteArray and DrawBonesArray. Those create extra prim instances (ExtendPrimInstanceNotify) that last one frame.

Mirrors

A geom with GEOMCONTROL_MIRROR gets a ZOldDrawIdListMirror, or joins a ZOldDrawIdListMirrorGroup by m_lMirrorGroup (zdrawidlist.h). A view holds at most 15 id lists. For each, UpdateCamera runs FindVisibleAndAddResourcesToView again with the camera reflected (FlipXForMatrixAndPlanes). Every id list keeps one bit per draw id for this frame (m_DrawIdStatus) and one for the last (m_RemStatus). GetIdStatus reads them as ENTER, LEAVE, NORMAL or INVALID, and ZOldViewBase::Update only touches the ids whose bit changed (FindNextDiff).

Sorting into the draw list

A sort entry (ZSortEntry, zoldviewentry.h) is a 32-bit key and a prim instance pointer:

void Set(uint32 lMaterial, uint32 lTexture, uint32 lTexturePriority, uint32 lUserPriority, uint32 lSubListId, uint32 lCameraPriority) {
    m_lValue = lMaterial | (lTexture << 4) | (lTexturePriority << 15) | (lUserPriority << 20) | (lSubListId << 24) | (lCameraPriority << 28);
}
Bits Field Filled from
0–3 material the prim type (EPrimType: strips 0, bone strips 1, sprite arrays 2, wire strips 3, splines 4, bone variant 5, dot3 strips 6, scatter 9, shadow mesh 10, water patch 11) or a sentinel 0xc to 0xf
4–14 texture id the prim's texture, 11 bits
15–19 texture priority ZOldViewBase::CalcTexturePrioity (the source's Layer())
20–23 user priority the geom's GetSortPriority() (USV_OPAQUE 0, USV_TRANS_ON_OPAQUE 1, USV_ADD_ON_OPAQUE 3, USV_SEMI_OPAQUE 6, USV_ADD_BEFORE_TRANS 9, USV_TRANS 12, USV_ADD 15), or the priority given to DrawSpriteArray
24–27 sub list the mirror id list, with 0xf the main list
28–30 camera priority the camera view entry's m_lPriority

The list is drawn in ascending key order, so camera priority decides first, then the sub list, the user priority and the texture priority. Sky prims (pack type 4) on the main list store sub list 0, which sorts them ahead of everything else under the same camera priority, and SubListId() still reads that as 0xf. The texture priorities are:

Priority Prims
0, 1, 2 pack type 4 (sky and background): plain, with draw-mode bits 0x8400201, additive
3 plain strips, and strips with draw-mode bit 0x400
4, 5, 6 dot3 strips; subtractive strips and strips without Z write; shadow meshes
9, 12 bone strips without a draw update (12 with blend bits 0x8000203)
10, 11 rigid parts (pack type 8; 11 with bits 0x8400303)
13, 14 bone strips with a draw update (14 with blend bits)
15, 16, 17 wire strips and splines; strips with PRIMDRAWMODE_UNLIT_ADDITIVE (0x8); strips with PRIMDRAWMODE_DEST_ALPHA_BLEND (0x20)
19, 20 strips with bits 0x400201 and water patches; strips with bits 0x8000002
21, 22 scatter (grass); sprite arrays

ZOldViewPS2::AddAlwaysDrawMaterials adds four sentinel entries, all on sub list 0xf with texture 0x7ff. The last three need a main camera, and the shadow break is left out when a main camera exists and g_CancelMaterialBreak is set:

Material Texture priority User priority What it does
MATERIAL_SHADOW_BREAK 0xf 7 7 ends the first pass, so dynamic shadows are drawn here
MATERIAL_SEAMS_FIXUP 0xc 8 7 DrawSeamsLayerFixup (Z2DFunctions::OffsetFrame on the draw buffer)
MATERIAL_RAIN_SPLASH 0xe 18 7 DrawRainSplashes with VU_SplashDraw
MATERIAL_POST_EFFECT_FIXUP 0xd 23 9 the post filter

The list persists between frames. Each frame ZOldViewBase::Update collects the entering entries in a ZSortEntryControler, and ZOldDrawSortListBase::UpdatePrimInstanceEnters (zdrawsortlist.cpp) drops the entries that left, qsorts the new ones and merges them in from the end. Prims with PRIMDEST_CUSTOM in lDrawDestination are routed by flag: DD_RGB to the main list, DD_BLOOM to the bloom list (768 entries, main camera only) and DD_ZBLUR to the depth-blur list (256). Prim instances at USV_ADD_BEFORE_TRANS seen by a CAMERA_FIRST_PERSON camera go to the first-person end layer (256). The last three lists belong to the view's ZPostFilter.

DMA chains and the VU1 programs

ZDMAChain writes DMA tags (DMATAG_CNT, REF, CALL, RET, END), each followed by a 64-bit word that carries VIF codes on the VIF channels. BeginCntPacket and EndPacket patch the quadword count when a packet ends, AddRefPacket points at data elsewhere, AddCallPacket calls another chain, and AddMicroProgram uploads a VU program in 64-quadword MPG blocks. ZVifChain1 feeds VU1 and the GS, ZVifChain0 feeds VU0 and ZGifChain carries texture uploads.

Mesh drawing uses three prebuilt chains, so a frame mostly adds CALL tags:

Chain Owner Built by Contents
prim chain ZPrimDrawEntryPS2::m_Chain ZOldDrawPS2::PrimCreate (AddPrimStripChainStart, AddBonePrimStripChainStart, AddPrimSpriteChainStart) the GS registers CalcGSRegs derives from the prim's draw mode, the bias, Z offset, GIF tags and diffuse colour
instance chain ZPrimInstDrawEntryPS2::m_pDMAChain ZOldDrawPS2::PrimInstanceCreate (AddPrimToDMAChain, AddBonePrimToDMAChain, PrimInstanceCreateDot3Mesh and others) per-geom data (direct lights, rigid bone, angle blend, wobble, keys), then per chunk REFs to the vertex, UV and colour packets in the .PRM and to the light colours
view chain ZPrimInstViewEntryPS2::m_Chain[24] ZOldViewPS2::PrimInstanceCreate REFs to the object matrix and the camera's m_Setup and transfer matrix and planes, then CALLs of the other two

The view chain for ordinary strips ends:

VifChain.AddCallPacket(pPrimDrawEntryPS2->m_Chain, 0);
VifChain.AddCallPacket(pPrimInstDrawEntryPS2->m_pDMAChain, 0);
VifChain.BeginRetPacket(0);
VifChain.EndPacket();

The REFs carry addresses, so the values they point at can change without a rebuild, and Flip rewrites them before the chain runs. ZOldViewPS2::Draw walks the sorted entries and calls SetupMaterial whenever the key changes. An ordinary entry then costs one tag, pChain->AddTransferTag(DMATAG_CALL, ...->m_Chain, 0). Some layers and materials take over a run of entries and return how many they used: DrawStaticShadows (texture priority 6), DrawDestAlpha (priority 16, the source's LAYER_DEST_ALPHA, drawn between Z2DFunctions buffer copies), DrawNormalMapped (dot3), DrawWater, DrawMirrors (mirror sub lists), and DrawSprites and DrawArrays for entries with draw updates.

Material VU program (see VU microprograms)
strips (0) VColClip, or VColClip_Wired when ZRenderPS2::m_lMode is 2
bone strips and variants (1, 5) VColClipBone
wire strips and splines (3, 4) VLineClip
sprite arrays (2) SnowDraw
dot3 strips (6) VU_dot3render, with newlight on VU0
scatter (9) VU_GrassDraw
shadow meshes (10) VUStaticShadowDraw, VUStaticShadowDrawTex
water patches (11) VUWaterRender
dynamic shadows VProjClip, uploaded by ZOldDrawPS2::BeginShadows
rain splashes, post filters and 2D, loading screens VU_SplashDraw, VUScrPass (Z2DFunctions::TransferProgram), VU_LoaderSeq
static lighting and bones (VU0) VLightTest (PrepareLightChainBuild), MatMulMat, MatToParent

Textures travel in the GIF chain. SetTexture alternates between a texture's two setups (m_Setup[m_lTextureCount++ & 1]) and adds a CALL of that setup's upload chain to m_pGifTextureChain and a REF of uTexSync to the VIF1 chain. Before the chains start, ExecuteDrawLists writes an MSKPATH3 that masks PATH3 into the VIF1 FIFO. Each uTexSync block (ZPS2Setup.cpp) holds FLUSHA, FLUSH and an MSKPATH3 that clears the mask, then NOPs and an MSKPATH3 (0x06008000) that sets it again, so the GIF chain's uploads can pass only while the VIF1 chain holds PATH3 open, in the order SetTexture queued them.

Meshes, textures and materials

ZRenderBaseDll::InstallPrimBuffer installs the scene's .PRM, and prims resolve through g_apPrimHandleToPointerTable (prim data). ZRenderDll::CreatePrimControl makes the ZPrimControlPS2 (src/engine/drawing/_ps2/zprimcontrolps2.cpp), which unpacks the PS2 vertex packets on the CPU (UnpackVertices). ZRenderDll::CompactTextureBuffer and InstallTextureBuffer (renderdll.cpp) fix up the .TEX records (ZTexturePS2) in main memory (textures). A texture has no permanent place in GS memory. ZOldDrawPS2::TextureCreate builds two ZTextureSetupPS2 records, each with a GIF upload chain (m_GifChain) and GS registers (m_GifSetRegs). Setup 0 uploads to the start of the texture area, setup 1 to that address plus GetLargestAllowedTexture() (0x20000 bytes). AddGifChainTexture picks the GS format and layout (MakeLocations). UpdateAnimatedTextures moves the offsets of up to 16 scrolling textures (m_fMoveSpeed) and the frames of up to 16 animated ones.

ZRenderBaseDll::InstallMaterialBuffer is empty on the PS2. A prim's look comes from its draw setup (SPrimDrawSetup: lDrawMode, lDiffuseColor, lBias, lTempHeader) and its texture. CalcGSRegs turns the draw mode into GIF tags and the ALPHA, TEST, CLAMP and fog registers once, when the prim is created. The draw-mode flags (EPrimDrawMode, zprimcontrolbase.h):

Flag Value Flag Value Flag Value
TRANSPARENT 0x1 ALPHA_BLEND 0x200 NO_ZTEST 0x20000
ADDITIVE 0x2 RECEIVE_SHADOWS 0x800 FORCE_NO_ZWRITE 0x40000
UNLIT_ADDITIVE 0x8 SHARED_VERTICES 0x1000 NO_FOG 0x100000
DEST_ALPHA_BLEND 0x20 SUBTRACTIVE 0x2000 WOBBLE 0x200000
ANGLE_BLEND 0x40 CLAMP_U 0x4000 MULTIPLY 0x1000000
LIT 0x80 CLAMP_V 0x8000 NO_CHARS_IN_MIRROR 0x2000000
NO_ZWRITE 0x100 MIRROR_MASK 0x10000 ONE_SIDED 0x4000000

SKIP_VIEW (0x40000000) and SKIP_MIRROR_VIEW (0x80000000) complete the list. SKIP_VIEW forces the instance's user priority to USV_ADD.

ZOldViewPS2::SetupMaterial runs per key change. A new camera priority clears that camera's viewport (Clear). A new material type uploads the type's VU program and starts its entry 0, and the four sentinels and water do their own work there. A new texture goes through SetTexture. SetupMaterial returns true when the entry can be drawn by calling its view chain.

Lighting

Static geometry is lit per vertex on VU0. ZOldDrawPS2::UpdateLight walks the draw base's geoms. For each geom with BASEGEOM_LightDirty it gathers the lights from the engine's light list (CListUser::UnfoldList with the geom's m_uListID), skips hidden lights and lights with fMultiplier <= 0 or a black diffuse colour, and keeps at most 12. The geom's environment light (ZGeomDrawEntry::Environment(), an SPrimLightEnvironmentPS2) gives the direction, direction colour and ambient colour. It then adds a call chain to m_pLightChain: two quadwords per light, the root matrix and the environment, then for each lit prim instance the address of its light colour buffer, an MSCAL of InitLightRegs, and a CALL of the prim's m_pLightChain. PrimCreate builds that chain with CreateStripsLightDMAChain when CheckPrimLightEnabled holds. VLightTest writes the colours into m_pLightColors, which PrimInstanceCreate filled with 0x7f7f7f, and the instance chain unpacks them. Flip starts the light chain and waits for it (WaitVU0Done) before the draw chain.

Normal-mapped (dot3) prims are lit on the CPU and VU0. UpdateLight copies newlight into VU0 micro memory and calls ComputeDot3Lighting (src/engine/drawing/old/_ps2/calclightdot3.cpp). Per light it calls ApplyOmniLighting, ApplyCircSpotLighting or ApplySquareSpotLighting, which run newlight segments with vcallms over each vertex, and ApplyEnvironmentLighting or ApplyDirectionalLighting for the environment. The results go to the instance's light colour and direction buffers. Type 0 (LIGHTTYPE_OMNI in zprimcontrolbase.h) takes the circular-spot path and type 1 the omni path. VU microprograms shows the two enum names are the other way round from the data.

Skinned geoms are lit on VU1. ZOldDrawPS2::UpdateDynamic calls CalcBoneLightSources for each active bone geom, and CreatePrettyLightsBuffer packs up to 8 lights and the environment into the geom's HQLights() buffer for VColClipBone's Prettylights entry. UpdateCamera also collects up to four LIGHT_SCATTER lights from the visible rooms for the grass program (m_ScatterLight).

Shadows

Static shadows are meshes (prim type 10, texture priority 6) that DrawStaticShadows draws with VUStaticShadowDraw or VUStaticShadowDrawTex. ZOldViewPS2::Init reads the scene options PS2_EnableStaticShadowSeamsFixup and PS2_DisableStaticShadowAdditive. VU microprograms has the blend passes.

Skinned geoms also sample the static shadows. GetStaticShadowSampleIntensity (src/engine/drawing/renderstaticshadowsampling.cpp) looks the position up in the room's m_StaticShadowSampleData: blocks of one-bit grids at 50-unit spacing, read bilinearly, optionally behind a coarse grid of block lists. The scene option StaticShadowSampleHeightLimit limits the height above a block (values below 100 become 10,000, ZRender::AllocateDrawBuffers). ComputeStaticShadowMultiplier stores (1 - intensity) * 255 in ZGeomDrawEntry::m_MulColor, and CalcBoneLightSources scales the environment light by it unless the light has PRIMLIGHT_IGNORE_SHADOW_MULT. The PC data adds block flags the PS2 code reads as no shadow (8 with 0x10): projected shadows, whose grid is followed by a record with a projection matrix, a shadow texture, a light position and a colour, and which the PC draws onto the characters as textures instead of dimming them; pc-data.md: Static shadows on characters and Enhancements: PC lighting describe them and the port's pc_lighting, which draws them the same way.

Dynamic shadows are drawn at the shadow break. ZOldDrawBase::HandleShadows returns when g_pSysInterface->m_lShadowDetail is 0 (the default is 2). Otherwise ZShadowListBuild (shadowlist.cpp, shadowlist2.cpp) compiles sets of light, caster and receivers into the scratchpad: ProcessLight for every active light, then ProcessEnvironment. Each caster gets the distance term (1000 - distance from camera) * 0.21333333, capped at 64 and skipped when not positive, times CalculateShadowIntensity. The 8 strongest are kept, or 15 during a cut sequence. ZOldDrawPS2::DrawShadow calls GenerateCasterTexture, which renders the caster (a ZLNKOBJ) from the light into a 256-pixel-wide frame at the start of the Z buffer (m_lDrawZBufferStart). Each view's DrawShadowReceivers then projects that texture onto the receivers with VProjClip.

Water and mirrors

ZWaterManager (src/engine/drawing/watermanager.cpp, g_pWaterManager) holds the water patches (SWaterPatchInst, 0xd0 bytes), each with four SSineWaves and up to four ripples. The manager keeps at most four ripples (AddRipple). AddDefaultRipple uses the g_wf* constants, with a separate amplitude in slow motion. FrameUpdate runs from ZOldDrawPS2::UpdateDynamic. It damps and grows the ripples, advances the sine phases and rebuilds each patch's ripple sub-chain, one REF per ripple. For a water patch SetupMaterial draws two GS sprites into the temp buffer, the temp buffer squashed into its top half and the frame into its bottom half, then uploads VUWaterRender and sets the frame, test, alpha and clamp registers (g_bUseTrueReflections changes CLAMP_1). DrawWater, BeginWaterMirrors and DrawWaterMirrors draw the patches and mirror groups. Plain mirrors go through DrawMirrors, BeginMirror and EndMirror with the normal strip programs.

Sprites, particles and 2D

All sprite arrays are material 2 and go through ZOldViewPS2::DrawSprites and SnowDraw:

SPRITETYPE Draw function SnowDraw entry and notes
ARRAY 1, ARRAY_UV 5 DrawSpritesArray, DrawSpritesArrayUV GeneralSpriteDraw
ARRAY_RAW 6 DrawSpritesArrayRaw GeneralSpriteDraw2; each sprite is written as four corners (VU1RawSprite)
ARRAY_BOX 3, ARRAY_BOX_SCALE 4 DrawSpritesBox, DrawSpritesBoxScale SnowDraw_Begin and DropDraw_Begin (rain streaks); ZParticleBox (zparticlebox.cpp) submits these
ARRAY_PARTICLE 7 DrawSpritesParticles PartDraw_Begin, or XPartDraw_Begin when fMotionStretch is set; the blocks of ZParticleController (zparticle.cpp), 41 particles per packet written by ParticleCalc (particle_asmps2.cpp, one of IOI's assembly units)

The HUD is ordinary geoms. ZOSD::DrawBufferViewUpdate (src/hitman3/gui/osd.cpp), ZWINOBJ::DrawBufferViewUpdate (src/engine/zwindows/interface.cpp), the in-game map, ZLightOverlay (lens flares) and the particle classes all call ZDrawBuffer::DrawSpriteArray with a user priority: the OSD uses 7, 11, 13 and 14 and particles 7 to 9. In the same camera priority and sub list, entries above user priority 9 sort after the post-filter sentinel and are drawn over the filtered picture. A sprite prim with a child view (m_lChildViewId) draws that view inline. Z2DFunctions (z2dfunctions.cpp, 49 functions) works on whole buffers through VUScrPass: copies, fills, half and double scales, blurs and palette index passes. Loading screens use loader_sequence_player_ps2.cpp with VU_LoaderSeq. Disc errors go through ZRenderDll::SetGlobalMessage, which saves a 256 by 64 rectangle of the front buffer (BackupFrontBuffer), draws one quarter of the global message texture there with ZRenderPS2::DrawFrontSprite until the callback returns NONE, and restores the rectangle.

Post filters

The post filter runs when the sorted list reaches MATERIAL_POST_EFFECT_FIXUP. ZPostFilterEvent (src/engine/eventsbase/postfilter.cpp) sets its values through SetValues, SetBloom, SetNoise and SetDepthBlurriness. ZPostFilterPS2::Update (zpostfiltersps2.cpp) builds the passes in this order:

Pass Runs when Work
bloom the bloom list has entries and m_fBloomAmount is set draws the bloom list into the temp buffer, scales and blurs it (m_fBloomBlurriness), adds it to the frame with ALPHA_2 0x68
first-person layer the end layer has entries with m_bFirstPersonOnlyInBuffer1 clear, draws it here after clearing Z (m_bFirstPersonZClear); with it set, draws it after the depth blur's alpha pass with FBA_1 set
depth blur the depth-blur list has entries or m_bZBufBlendEnabled writes an alpha from the depth-blur list or from the Z buffer through m_PalTransferAlpha (CopyZBufGToDrawA), blurs a half-size copy by m_fDepthBlur (through curves palette 1 unless it is the default), scales it back with ALPHA_2 0x54, with heat shimmer when m_fHeatShimmerSpeed is set (ScaleAndShimmerFrameToDouble)
curves palette 0 is not the default (IsDefaultCurvesPalette) ApplyCurvesFilter(0, ...) on the whole draw buffer
last frame m_fLastBlendAmountLastBuffer is set restores the previous frame (RestoreDrawBackup), applies curves palette 2 unless it is the default and a blur by m_fLastBlur, blends it in, and saves this frame (MakeDrawBackup)
finish m_fFinishBlendAmount is set and palette 3 is not the default selects, blurs and recolours a half-size copy (m_fFinishBlur, curves palette 3) and blends it in with ALPHA_2 0x44
noise m_fNoiseMax is set uploads a 64 by 64 noise texture (CalcNoiseTexture) and blends it over the frame (CreateVU1CopyChainNoise)

ApplyCurvesFilter uploads the red, green and blue palettes of one of four curve sets (m_PalTransferRGB[3][4]) below the end of the texture area (GetTextureEnd() - 0x100 and the two below it), then reads the source buffer page by page as an 8-bit texture through each palette, at most 40 pages per run (CURVES_MAX_PAGES). The temp pages come from GetTempPage: four half-size buffers at the start of the temp buffer.

Frame buffers and video modes

ZPS2Setup::SetupScreen (ZPS2Setup.cpp) programs the mode, and ZRenderPS2::Init calls it with g_dVideoMode. That global starts at 2 (NTSC) in src/hitman3/hitman3/_ps2/startup.cpp and becomes 1 (PAL) from VMODE = PAL in cdrom0:\SYSTEM.CNF, the VPAL argument or the option PS2VideoConfigPAL (sysinterfaceps2.cpp). ZRenderPS2::ToggleMode switches modes at run time.

ZPS2Setup::Mode sceGsResetGraph Buffers m_fFramesPerSecond SMODE2 DISPLAY2 DX, DY
PAL 1 (0, 1, 3, 0) 512 x 480 50 1 0x290, 0x58
NTSC 2 (and UNDEF) (0, 1, 2, 0) 512 x 448 60 1 0x27c, 0x32
DTV480p 3 (0, 0, 0x50, 1) 512 x 448 60 2 0x1ae, 0x23

PMODE is 0x66, and DISPLAY2 scales the 512 pixels by 5 horizontally (2 in 480p). The constructor's defaults (draw buffer 512 x 896 at depth 2, display 512 x 448 at depth 2) are replaced in every mode by 512 pixels wide at the mode's height, 32-bit colour and Z24. EnableFieldAliasing(true) only sets m_bFieldAliasing, which nothing reads. ZRenderPS2::PixelAspectXY counts 32 extra lines and a factor of 0.93458 in PAL and 96 extra columns in 480p, then scales by 0.75, or 0.5625 in widescreen. SetDisplayOffset moves the picture by at most 200 pixels left, right or up and 50 down. CalcMemBuffers lays out the 4 MB of GS memory from the top down, aligned to 8 KB pages. In PAL mode that gives:

GS bytes Buffer Field
0x310000–0x400000 display buffer m_lDisplayBufferStart
0x220000–0x310000 draw buffer m_lDrawBufferStart
0x130000–0x220000 Z buffer, also the shadow caster frame m_lDrawZBufferStart (GetTextureEnd())
0x0f0000–0x130000 textures: two 128 KB upload slots m_lTextureStart
0x000000–0x0f0000 temp buffer: water copies, post-filter pages, ZDrawSurface::TEXTURE targets m_lTempBufferStart

The fields store 32-bit word addresses (byte address / 4), and the page numbers the GS registers take are those shifted right by 11. In NTSC and 480p the 448-line buffers leave 512 KB for textures. ZOldViewPS2::SetFrameBuffer centres the draw target on the GS's 2048 origin (XYOFFSET_1 is 0x8000 minus half the size, in 1/16 pixels).

Movies

Movies go through ZVideoPlayer (src/engine/rendervideo/video.cpp) and ZPS2Video. SetFileName picks Movies/PAL/ or Movies/NTSC/ .pss by the video mode, and ZBaseVideo::Init sets a frame interval of 2 while the movie runs. ShowNextFrame registers DecodeFrame as a flip callback, which hands the decoded picture to ZOldViewPS2::UploadToBackBuffer for the draw buffer. When the scene's texture buffer is large enough, DecodeFrame decodes into it after saving it to GS memory with CMagicMemSave::Upload and restores it with Download. Sound and movies has the stream format.

The SDL3 port

The port keeps the engine half of this page as engine code: rooms, portals, sorting, decals, shadow lists and the post-filter interface. It replaces the PS2 classes with ZRenderSDL, ZRenderDllSDL, ZOldDrawSDL, ZOldViewSDL and ZPostFilterSDL in port/engine/drawing/old/_sdl/, and draws with SDL_GPU and HLSL shaders from port/shaders/. ZOldViewSDL::Draw walks the same ZSortEntry list as ZOldViewPS2::Draw. The meshes come from PrimDecode and the textures from DecodeTexture, which turn the PS2 records into vertex arrays and RGBA8 images. Nothing emulates the GS, VIF or VU1. The details are in the port, PRM mesh decoding and texture decoding. The optional additions such as FXAA, SSAO and high-precision bloom are in enhancements.