Reference ยท Engine

How the game is put together

Covers18
INF SLUS_202.67:0x0015a780 main0x00167940 ccThMother0x001671e0 ccGame::ChangeRequest0x001680e0 ccThLoadOverlay0x0010a5f0 ccSystem::Ctrl0x001099e0 VSyncCallBack0x0015a5c0 ccThControl0x00159e10 ccTscb::Breath0x00102d40 ccPad::Read0x00102a50 ccPad::Ctrl0x00102bf0 ccPad::SetActuater0x0010a740 ccSystem::Ctrl (the motors)0x0010a900 ccSystem::Init0x0010ad20 ccSystem::SetScreenMode0x0010ad40 ccSystem::SetScreenModeMain0x0010ab30 ccSystem::SetDisplayOffset0x0010ac40 ccSystem::SwapDoubleBuffer0x0010de50 sceGsSetDefDispEnv

One resident program, one overlay at a time, and a set of frame-locked tasks.

Boot

main                                   main.cpp
  ccHeap::InitFirst, mwInit, ccCdInit, InitCCSys, ccLoad_SndModules,
  ccSndInit, ccMcardInit, ccInitThread
  start task ccPadThread
  start task ccThMother
  loop:  WakeupThread(tscbCtrl); SleepThread(); ccSystem::Ctrl(); ccAddPlayTime()

ccThMother                             mother.cpp
  common file list + resources, fonts, task ccSoundMain, gcmn file list,
  draw packet controller, layer, screen fader,
  game = new ccGame, saveSys, saveData = new ccSaveData,
  eventMng = new ccEvent, task ccThEvent
  ccStartEvent(1); game->ChangeRequest(2, 7)
  loop: take game->request[0], shift the queue, dispatch (below)

Modes

ccGame::ChangeRequest(num, sf) puts num in the first free slot of ccGame.request[4] and, unless num is 6, calls ccGame::InitScene.

requestsetupoverlay loadedframeRate
2ccSetupDemocdrom0:\DATA\DEMO.PRG1
3ccSetupDesktopcdrom0:\DATA\DESKTOP.PRG1
4ccSetupToppagecdrom0:\DATA\TOPPAGE.PRG1
5ccSetupNewGamecdrom0:\DATA\GCMN.PRG2
6ccSetupGameCtrlnone; gcmn stays resident-
1inside ccThMother: the soft reset1
0x1000inside ccThMother: every task deleted, no set-up

Mode 1 (INF ccThMother 0x00167ca0) goes back to the start-up path at 0x00167b18:

  1. ccAllSoundOff, the layers flipped back and every task deleted (ccDeleteAllThread);
  2. the system and draw environment reset, SetFrameRate(1);
  3. ccGame::Init, ccSaveData::Init(1), ccEvent::Init, ccStartEvent(1, 0);
  4. ChangeRequest(2, 7): the title.

Three things ask for it with ChangeRequest(1, 7): the desktop's Reset (ccDtMenu::ResetMenu, 0x0016ed90), The World's Reset (ccMenuCtrl::ResetMenu, gcmn 0x00540688) and the game over (ccOpenGameOverMenu, gcmn 0x0056a7d4). Mode 0x1000 (0x00167d00) only flips the layers and deletes every task. None of the 12 ChangeRequest calls in main and the four overlays asks for it; the scripts' mode uses 3 and 5.

Overlays are loaded on the task ccThLoadOverlay, which retries mwLoadOverlay until it succeeds; see the overlay format. The event interpreter ccEvent::Execute (event VM) can also load one through ccLoadOverlay. Main code calls into gcmn at fixed addresses, valid only while gcmn is resident.

Frames

ccSystem::Ctrl                          one frame
  shadow packets; wait for the GS path
  while (frameRateCnt < frameRate) sceGsSyncV
  frameRateCnt = 0; EE Timer 0 = 0; count += 1
  screen mode; FlushCache; swap double buffer
  font and layer display lists; SendDMA
  read pad 0 and pad 1; refresh the display list

VSyncCallBack                           every vertical blank
  frameRateCnt += 1; tick += 1

frameRate is vertical blanks per frame: 1 = 60 fps, 2 = 30 fps (NTSC). The field game runs at 30, the desktop, bulletin board and demo at 60; event scripts can change it.

The port counts vertical blanks at 59.94 Hz of wall time and steps the frames that are due on each redraw, four at most. A redraw shows only its last frame, so a frame it catches up is drawn only when the next one samples its picture (TexRef::PreviousFrame). In a town the draw costs about 2.5 times the step: Mac Anu's views carry 200,000 to 265,000 vertices, put through on the CPU (worklog 552).

Tasks

ccTscb              0x54 bytes, one per task
  +0x00  entry      void (*)(void *)
  +0x04  tid        s16, the kernel thread id
  +0x06  priority   s16
  +0x08  sleep      s16, holds the task asleep while non-zero
  +0x0a  sr         s8, start request
  +0x0b  del        s8, delete stage
  +0x0c  size       stack size
  +0x10  mask       0x08 suspended, 0x20 waiting in Breath
  +0x14  param[8]
  +0x34  link       next ccTscb
  +0x38  name
  +0x3c  tmng, +0x40 func      cleanup callback and argument
  +0x44  tmngI, +0x48 funcI    delete-stage-2 callback and argument
  +0x4c  stack
  +0x50  t0count, +0x52 stackOverFlag

Each task is a kernel thread (CreateThread + StartThread in ccTscb::GoThread). Once per frame main wakes ccThControl, which walks the list and, per task: starts it if sr; runs funcI at del stage 2 and terminates, deletes and frees it at stage 3; resumes it if suspended; wakes it if it is in Breath and sleep is 0. ccTscb::Breath(n) sleeps through n wake-ups, then keeps sleeping while sleep or del is set. A task's work for one frame is the code between two Breath calls.

The woken tasks run in kernel priority order, the lowest number first, each until its next Breath. The tasks each set-up starts (INF, the priority as ccStartThread's second argument):

started bytasks, by priority
ccThMother (start-up)ccThEvent 32, ccSoundMain 112
ccSetupDemo (title)ccThLoadOverlay 17, ccThDemo 33, ccThDtMenu 33
ccSetupDesktopccThLoadOverlay 17, ccThDtMenu 33, ccThDesktop 33
ccSetupToppageccThLoadOverlay 17, ccThDtMenu 33, ccThToppage 33
ccSetupNewGameccThLoadOverlay 17
ccSetupGameCtrl (towns, fields, dungeons)ccThGameCtrl 33, ccThMenu 34, ccThCamera 40, ccThSpc 48, ccThEntryCtrl 64, ccThExecuteStream 65, ccThEffect 80, ccThSkill 82, ccThFieldDisp 96, ccThParticle 98

Others start on demand: ccLoadDispTh 17, ccThSaveSys 20, ccThGameOver 33 (field walk). So in The World a frame runs the event task, the game control, the menus, the camera, the party, the entries (enemies, gimmicks, NPCs), the effects, the skills, the display and the particles, and the sound task last. A menu's request is acted on by the characters and heard in the same frame.

The pad

ccPad::Read (0x00102d40) runs once a frame for a pad already connected (ccPad::Ctrl's state 0x40). The pad reports its buttons active low in two bytes; Read inverts them (the first byte in bits 8-15, the second in bits 0-7). In analog mode the left stick also presses the D-pad by its angle when the D-pad itself is not held. Then:

push   = now & ~direct          pressed this frame
unpush = direct & ~now          released this frame
repeat = now on the first frame of a new combination, nothing for the
         next 15 frames it is held, then now every frame
direct = now

Two quirks: a stick with its raw y exactly 128 has angle 0, down (SetAnalogStick tests the y offset before atan2f); and the up-right eighth of the circle presses right alone, where the other diagonals press both directions.

The motors (ccPad +0x28..+0x3f):

SetActuater(small, power, ms)   0x00102bf0: with ccPad::actuaterSw on and a
  DualShock ready, the time (3 ms + 25) / 50 in vblanks; each queued entry
  from the top down loses that time, or is dropped when it has no more
  (the ones above it move down); with room (at most three), the top (or
  the idle entry 0) is marked to send again, and the new one goes on top,
  marked: its time, the small motor on or off, the large motor's power
ccSystem::Ctrl                  0x0010a740, each frame for each pad: the
  finished entries off the top, then the top's time less the frame rate
  (vblanks a frame), not below 0
ccPad::Ctrl                     0x00102a50, state 1: with the queue empty
  and the idle entry marked, both motors off; else a marked top with 6
  vblanks or more left: its motors; either sent (scePadSetActDirect, state
  2), then waited on (scePadGetReqState, state 4) before state 1 looks again

The callers are ccPlayer::DamageActuate (Kite hit: the small motor and DamActuTbl by the damage, 100 ms) and the Vibration menus switching it on (the small motor and 160, 200 ms). The port is crates/piney-input.

Read first stores scePadGetState in ccPad.status (+0x04, so ccSys+0x26c for port 1): 0 with no controller, 2 or 6 once one is found. From Mutation on the save menus read status too (desktop).

The pause

ccThMother (main, INF 0x00167d28 to 0x00168018; MUT 0x00167ea8, OUT 0x00167130, QUA 0x00166fc0, the same code) runs first in every frame (priority 2). It pauses the game while ccSys+0x26c (pad[0].status) reads 0 in a playing mode (eventMng+0x0c, enablePhase, at least 4: the desktop, the top page and The World once their set-up has made ccEnableThEvent(4); never the title, and not from a ChangeRequest, which disables the events) with game.pauseFlag (+0x7c) 0. The set-ups run inside the mother (ccSetupDesktop 0x00167cc0, ccSetupToppage, ccSetupGameCtrl), so the test comes once a set-up has returned: on the desktop and the top page the frame of their ccEnableThEvent(4), in The World after ccSetupGameCtrl's fade in on game.fade (0x00169538 to 0x0016957c, ten frames, then its ccSndBgmCtrl):

begin        fontOffFlip, game.layer->OffFlipExcept (the layers keep their
             last lists); stillLayer.flipFlag one down (not below 0);
             ccSleepNoSleepThread(1, 1); the event task's bit 2 cleared and
             it slept; EntryFade(game.fade, 1, 0, 0x58000000, 0, 0, 512, 384)
each frame   game.fade->SendPacket; fontSys SetType(1), colour
             ccSpriteColorTable[20] alpha 128, "P A U S E" at (16 sx, 10 sy)
             = (192, 160); SetType(0); with a controller the START line at
             (18 sx, 16 sy) = (144, 192): "START button: Retun to game"
             (Infection), "Return" (Mutation on); START (push & 0x800):
             DeleteFade, ccWakeAllThread (the event task's one sleep too)
next frame   fontOnFlip, OnFlipExcept, ccWakeThread(event), its bit 2 set:
             every task runs this frame

game.pauseFlag holds it off. ccGame::Init (0x00167180, power-on and the soft reset) clears it; the writers:

staff_roll (case 147)   1 at its start, 0 after the roll and
                        ccBreathThread(30) (INF 0x001b1cbc, 0x001b1d34;
                        MUT 0x001c7084, 0x001c70fc; OUT 0x001bd444,
                        0x001bd4c0); QUA 0x001c4a9c, 0x001c4ab4, one frame
ending_kanji (QUA 169)  1 (0x001c52fc), never cleared before Init
ccThGameCtrl            1 at the game over (INF gcmn 0x0051792c, MUT
                        0x0053598c, OUT 0x00530c2c, QUA 0x0042353c)
ccSaveSys (OUT, QUA)    LoadInfoReq 1, SlotSelectReq and EndReq 0 (OUT main
                        0x00171090, 0x00171054, 0x0017102c; QUA 0x00170f20,
                        0x00170ee4, 0x00170ebc); MainProccess 1 and 0 around
                        BootCheckProccess (0x0017150c, 0x0017151c)
MainProccess (MUT)      1 and 0 around its card calls (0x00171f7c-0x0017528c)
DataDrainMenu (OUT,     1 at its start, 0 after the rules and again at step
QUA)                    20 (OUT gcmn 0x0054c574, 0x0054cecc, 0x0054e854;
                        QUA 0x0043ee84, 0x0043f7dc, 0x00441164)

The port: crates/piney-demo/src/pause.rs (tools/test_mother_pause_rs.py runs each volume's ccThMother loop in eemu against it), and the session (piney-game Session::mother_pause): each mode reports enablePhase and its writes to pauseFlag, which the session keeps across the modes; on a held frame no mode steps and the last frame shown is drawn again under the fade and the texts. A controller in the port is Pad::unplugged (the keyboard is always one). The port tests at the start of a frame on the state the last one left, so where the game's pause can begin in the very frame a set-up returns (its last calls, then the tasks asleep), the port's begins a frame later, that frame's tasks run. Not modelled: stillLayer (the port keeps no still layers, field UI), and Mutation's card calls, which take no frames in the port.

The screen

ccSystem::Init (0x0010a900) asks SetScreenMode(512, 448, 0), applied by SetScreenModeMain (0x0010ad40) on the next Ctrl. The mode is width (+0xbd0), height (+0xbd2) and a field flag (+0xbd4, forced 0 at 256 lines or fewer):

height <= 256       sceGsResetGraph(0, 0, 2, 1)   NTSC, not interlaced
field flag 0        sceGsResetGraph(0, 1, 2, 0)   interlaced, one 448 buffer
field flag 1        sceGsResetGraph(0, 1, 2, 1)   interlaced, 224 a field

then sceGsSetDefDBuff (the buffers at +0xbe0, their DISPLAY registers at +0xbf8 and +0xc20), and keeps DISPLAY's DX and DY as the base (+0x1c, +0x1e) before re-applying the offset. sceGsSetDefDispEnv (0x0010de50), NTSC interlaced: MAGH = (2559 + w) / w - 1 (4 at 512, 3 at 640), DX = 636, DY = 50; DH is 2h - 1 in field mode, h - 1 otherwise. So DX counts video clocks (2,560 across the picture at either width) and DY lines of the interlaced frame (one row of the 448).

SetDisplayOffset(x, y) (0x0010ab30) keeps (x, y) (+0x20, +0x22) and writes base + x (0..4095) and base + y (0..2046) into both buffers' DISPLAY; with the field flag 0 also into read circuit 1's pair (below), there with y + 1. Adjust Screen moves x by 3 (-48..48) and y by 1 (-16..16), so the picture moves up to 9.6 pixels across and 16 rows down at 512 x 448. The port moves the presented picture by x / 5 pixels and y rows and leaves black where it left (piney_gs::Presenter::present).

In frame mode (field flag 0) the picture is merged with itself a line lower, a deflicker for the interlaced TV. SetScreenModeMain sets both buffers' PMODE EN1 (libgraph's 0x66 already has EN2, MMOD 1, AMOD 1) and ALP 127 (0x0010b4e8-0x0010b520), and copies their DISPLAY with DY + 1 to +0xe10 / +0xe20. Each frame SwapDoubleBuffer (0x0010ac40) writes the shown buffer's DISPFB to DISPFB1 (0x12000070) and its +0xe10 copy to DISPLAY1 (0x12000080) before sceGsSwapDBuff puts circuit 2. So a screen line is 127/255 of the buffer's line above and the rest of its own. Field mode (the movies) skips both. The port merges only when asked (--deflicker, piney_gs::Pcrtc::deflicker), since its picture is progressive.

Not the game's: the port can draw its 512 x 448 frame buffer at N times that size (--render-scale, piney_gs::Gs::set_scale, 1 to 8). The draws keep the frame's coordinates. The scissor rectangles, the frame-buffer copies (and the texels they are read at) and the shadow packets' Z copy and composite scale with it. The half-pixel move that makes the GS's corner rule meet the GPU's centre rule becomes half a frame-buffer pixel (convert::Screen::scale). At scale 1 the picture is unchanged.

Unknown

  • How the kernel orders tasks of equal priority (the title's, the desktop's and the top page's two at 33): taken as their start order, not checked.
  • The merge circuit's arithmetic: the port takes ALP / 255 as PCSX2 does; the console's rounding is not measured.

How this was found out

docs/engine/overview.md