diff --git a/docs/decomp/AudioVisualizer.md b/docs/decomp/AudioVisualizer.md new file mode 100644 index 0000000..5739351 --- /dev/null +++ b/docs/decomp/AudioVisualizer.md @@ -0,0 +1,113 @@ +# AudioVisualizer + +`AudioVisualizer` is the node behind the music player's moving pictures. It never draws +to the screen itself: it's handed an 8 bit `CSurfx` (the TMAP surface) through +`RenderDynamicTexture` every frame and scribbles the current audio into it, and the +TMAP fade does the rest. Everything lives at `0x00063760..0x00064630` in the 5960 +retail XBE. + +## Registration and layout + +| Class | Name string | Size | Factory | vtable | +|-------|-------------|------|---------|--------| +| CAudioVisualizer | "AudioVisualizer" | 0x834 | `0x00063770` | `0x0002a938` | + +| Offset | What | +|--------|------| +| 0x1c | `type` (string) | +| 0x20 | `channel` (string) | +| 0x24 | `source` (node, an AudioClip) | +| 0x28 | `scale`, 1.0 from the factory | +| 0x2c | `offset`, 0 | +| 0x030 / 0x230 | left / right samples, 256 shorts each | +| 0x430 / 0x530 | left / right spectrum, 128 shorts each | +| 0x630 | spectrum valid flag | +| 0x632 | mono mix, 256 shorts | +| 0x832 | mono valid flag | + +The destructor (`0x00063800`) frees both strings and releases the source. `Advance` +(`0x00063870`) runs the node advance and then advances the source, since the clip isn't +in the scene graph on its own. + +## RenderDynamicTexture (`0x00063940`, 1363 bytes) + +1. Bail unless `source` is set, its class is AudioClip (`GetNodeClass` compared with + `0x0018864c`), its transport (+0x50) is 1 (playing), it has a sound buffer (+0x68), + that buffer has sample data (vtable +0x1c) and the byte count (vtable +0x20) is at + least 4. +2. Frames = bytes / 4, capped at 256. Copy each stereo frame's left and right shorts + into the two arrays, zero the rest. Clear both cache flags (0x630, 0x832). +3. Cap frames at the surface height. Channel is right when `channel` starts with `r` or + `R`, otherwise left. Style from `type`'s first letter through a jump table at + `0x00063ea0`: `a`/`A` 3, `c`/`C` 2, `s`/`S` 1, anything else 0. The clock is read + once from `0x0017e808`. +4. Style 0, line: start at (w/2, 0); for each frame y draw `Line` (`0x0005fdf0`) to + (w/2 + (sample * w >> 16), y) in 255. +5. Style 1, spinner: step 1/w from 0 while <= 1.0. Amplitude is + `sample[(int)(frames * t)] * (1/32767) * scale + offset` (constant at `0x0002bf10`), + along is `(t - 0.5) * 2.1` (`0x0002c160`). Rotate by `g_now * 0.2` (`0x0002c01c`), + x = cos * along + sin * amp, y = sin * along - cos * amp, and join each point to the + last except at t = 0. It calls `rand()` once up front and ignores the result. +6. Style 2 has a case number but no code: the jump lands on the exit. +7. Style 3, analyzer: refresh the spectrum (`0x00063900`, below). Level per band is + `ln(bin) * 8` (`FYL2X` with `FLDLN2`, 8.0 at `0x0002bf34`), 0 when not above 0, 255 + when not below 255.0 (`0x0002bf38`). Bands 0..127 take the left spectrum reversed, + 128..255 the right one in order. Peaks live in a 256 int global at `0x00188f90`: + each frame a peak above 2 drops by 2, anything else goes to 0, and it's raised to + level * 2 if lower. Then for each column x (band = x * 256 / w) a bar of height + level * h / 256 (`0x0002c064` is 1/256) is filled from the bottom up with 255 + counting down, and one 255 pixel goes at h - peak * 0.5 * h / 256. Neither write is + clipped. Last it runs the two overlays below. + +## Spectrum (`0x000638a0`, `0x00063900`) + +`0x00063900` checks the valid flag at 0x630 and, when clear, runs `0x000638a0` on the +left then right samples and sets it. `0x000638a0` makes the FFT state once (global +`0x00188f54`), runs it, and stores `sqrt(power) * (1/256)` for 129 bins into a 128 entry +array, so the last bin lands on the next field. + +## Flash overlay (`0x00063ef0`) + +Bass is `(sum of right bins 0..4 >> 4 + sum of left bins 0..4 >> 4) / 10`. Globals at +`0x0017e6f4..0x0017e70c` keep a recent max, the previous max, when it rolled, the same +three for the min, and an "on" flag; `0x00188f50` counts frames. The max and min take +the new value when it beats them, and every time more than 10 frames have passed since +the last roll the recent value becomes the previous one and resets to 0. When bass +beats `(prevMax * 6 + prevMin * 4) / 10` and the flag is off, the whole surface is +filled with 0xff and the flag goes on. After bumping the counter, the flag goes off +again once bass drops under `(prevMax * 4 + prevMin * 6) / 10`. + +## Wave overlay (`0x00064130`, 1761 bytes) + +- Style counter at `0x0017603c` starts at -1. When it's negative or the clock passes + the next change time (double at `0x00188f48`) it goes up by one and the next change + is `g_now + 3 + rand() * (5/32767)`. Over 4 it wraps to 0. +- Cos and sin tables (`0x0017e778` / `0x0017e780`, width in `0x0017e774` / `0x0017e77c`) + are rebuilt when the surface width changes: every 4th entry i holds + `cos/sin(i / w * pi + pi/2)` (`0x0002bffc`, `0x0002c134`). +- Gap is `30 * h >> 8` (`0x00176038`), amplitude 50 (`0x00176034`), color 128 + (`0x00176040`). The starting height of both waves is `((L[0] + R[0]) >> 9) * h * 50 + >> 12`, held at 0 or above in style 3. +- Every 4 pixels, frame index `(i << 8) / w / 5`, the right wave height is the high + byte of that right sample `* h * 50 >> 12`, the left one likewise. Style 0 draws the + left wave below the middle, 1 adds the right wave above it, 2 draws both channels + as two horizontal and two vertical lines either side of the middle, 3 and 4 bend the + waves round a half circle using the tables (3 holds them at 0 or above). 3 and 4 then + join the two ends with one more line. +- Last, two passes of 64 2x2 dots (`0x000640a0`, each pixel clipped to the surface) in + 255. Pass j runs a counter k from the global at `0x00188f40`: + `x = cos(k / (80 + 107.2j))`, `y = sin(k / (1.756 * (80 + 74.4j)))`, both scaled by + the surface height, rotated by k * 0.001 (`0x0002c050`) and centered. The counter is stored back after + the second pass, so it advances 64 per frame. + +## Theseus notes + +- The desktop pulls the mixer's last 256 frames every frame instead of reading the + source clip, since desktop music doesn't play through an AudioClip. The source is + still advanced. +- Style 2 draws a mirrored half circle of the waveform (Theseus's own; 5960 has the + case but no code). +- The analyzer takes `ln(bin + 1)`, so a silent band reads 0 instead of going through + the log of zero, and the peak dot is clipped to the surface. +- The spinner doesn't make 5960's unused `rand()` call. +- The curve dots are scaled by h * 50 / 256. diff --git a/docs/decomp/README.md b/docs/decomp/README.md index e3d7924..2af93ec 100644 --- a/docs/decomp/README.md +++ b/docs/decomp/README.md @@ -393,6 +393,14 @@ When in doubt about an entry, run the address through Ghidra and compare. The po | 0x00063320 | `CFilePump::Initialize` | `CFilePump::Initialize` (audio_system.cpp) | [Audio](AudioSystem.md) | Opens an audio file for streaming, parses its header, and binds a decoder. | | 0x00063520 | `CWMAPump::Initialize` | (reference only) | [Audio](AudioSystem.md) | Original WMA-streaming pump. Cut from Theseus; replaced with `CMP3Pump` (minimp3-based). Preserved here for binary documentation. | | 0x000638a0 | `CAudioVisualizer::CalcSpectrum` | `CAudioVisualizer::CalcSpectrum` (audio_system.cpp) | [Audio](AudioSystem.md) | Computes a frequency spectrum from the playback buffer's recent samples for visualizer scenes (FFT-driven dotfields, TMAP modulation). | +| 0x00063770 | `CAudioVisualizer_CreateNode` | `CAudioVisualizer::CAudioVisualizer` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Factory for "AudioVisualizer", 0x834 bytes: scale 1, no strings or source. | +| 0x00063800 | `CAudioVisualizer_dtor` | `CAudioVisualizer::~CAudioVisualizer` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Frees type and channel, releases the source. | +| 0x00063870 | `CAudioVisualizer_Advance` | `CAudioVisualizer::Advance` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Node advance, then advances the source clip. | +| 0x00063900 | `FUN_00063900` | `CAudioVisualizer::UpdateSpectrum` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Both spectra once per frame. | +| 0x00063940 | `CAudioVisualizer_RenderDynamicTexture` | `CAudioVisualizer::RenderDynamicTexture` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Copies the clip's samples and draws the line, spinner or analyzer style. | +| 0x00063ef0 | `FUN_00063ef0` | `CAudioVisualizer::RenderEffect1` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Bass beat flash: fills the surface white once per beat. | +| 0x000640a0 | `FUN_000640a0` | `VizPlot2x2` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Clipped 2x2 dot. | +| 0x00064130 | `FUN_00064130` | `CAudioVisualizer::RenderEffect2` (desktop_nodes.cpp) | [Audio Visualizer](AudioVisualizer.md) | Five rotating wave styles plus two dotted curves. | | 0x00064ec0 | `CNtIoctlCdromService::DeviceIoControl` | `CNtIoctlCdromService::DeviceIoControl` (ntiosvc.cpp) | [NtIoSvc](NtIoSvc.md) | Routes IOCTLs to the CD-ROM device driver. The dashboard talks to the disc through this; Theseus's reconstruction reuses it for ISO/CCI mount via Hermes. | | 0x00065150 | `CCDDAStreamer::CCDDAStreamer` | (reference only) | [Audio](AudioSystem.md) | CD digital audio streamer constructor. Used by the original soundtrack rip flow; the rip-CD-to-disk feature is not yet implemented in Theseus. | | 0x000676c0 | `CDVDPlayer::CheckUserOp` | (reference only) | DVD Playback | Checks whether a given DVD user operation (next chapter, scan, menu) is permitted by the disc's prohibited-operations mask. The full DVD playback chain was cut from Theseus; the desktop build uses libmpv instead. | diff --git a/theseus/desktop/config.h b/theseus/desktop/config.h index 3290260..9b3dcdc 100755 --- a/theseus/desktop/config.h +++ b/theseus/desktop/config.h @@ -1,5 +1,5 @@ -// config.h: desktop CConfig node declarations. Counterpart to -// xbox/config.h. +// config.h: the desktop build's Config node. Same script surface as +// xbox/config.h; console-only answers are stubbed or faked on the PC. #pragma once #include "node.h" @@ -7,102 +7,105 @@ class CConfig : public CNode { - DECLARE_NODE(CConfig, CNode) + DECLARE_NODE(CConfig, CNode) + DECLARE_NODE_FUNCTIONS() public: - CConfig(); - ~CConfig(); - CXBExecutable theXBE; + CConfig(); + ~CConfig(); - int GetLanguage(); - void SetLanguage(int nLanguage); - int GetGamePCFlags(); - void SetGamePCFlags(int nLanguage); - int GetMoviePCFlags(); - void SetMoviePCFlags(int nLanguage); - CStrObject *GetLaunchReason(); - DWORD GetTitleID(); - int GetLaunchContext(); - int GetLaunchParameter1(); - int GetLaunchParameter2(); - int CanDriveBeCleanup(int Drive); - void BackToLauncher(); + // Launch data + CStrObject* GetLaunchReason(); + DWORD GetTitleID(); + int GetLaunchContext(); + int GetLaunchParameter1(); + int GetLaunchParameter2(); + void BackToLauncher(); + void BackToLauncher2(); + void GoToXOnlineDash(); + int ForceSetLanguage() { return 0; } // no launch data on desktop + int ForceSetTimeZone() { return 0; } + int ForceSetClock() { return 0; } - uint32_t NetStatus; + // Language, region, parental control + int GetLanguage(); + void SetLanguage(int lang); + int GetGamePCFlags(); + void SetGamePCFlags(int flags); + int GetMoviePCFlags(); + void SetMoviePCFlags(int flags); + void SetParentPassword(const char* password); + int CheckParentPassword(const char* password); + CStrObject* GetAVPackType(); + CStrObject* GetAVRegion(); + CStrObject* GetGameRegion(); - int NtFileExists(const char* szPath); + // Video and audio + int GetVideoMode(); + void SetVideoMode(int mode); + int Get480Support(); + void Set480Support(int on); + int Get720Support(); + void Set720Support(int on); + int Get1080Support(); + void Set1080Support(int on); + int GetPAL60Support(); + void SetPAL60Support(int on); + int GetAudioMode(); + void SetAudioMode(int mode); + int GetDolbyDigitalSupport(); + void SetDolbyDigitalSupport(int on); + int GetDTSSupport(); + void SetDTSSupport(int on); - void Reset(); - void PowerOff(); - void PowerCycle(); - void XBOXReset(); - int GetInternalTemp(); - int GetCPUTemp(); - void SetFanSpeed(int speed); - int GetFanSpeed(); - void SetLED(int LEDMode); - void NetworkShutdown(); - void NetworkReboot(); - void NetworkStartup(); + // Clock + int GetTimeZone(); + void SetTimeZone(int zone); + int GetDSTAllowed(); + int GetDST(); + void SetDST(int on); - CStrObject *GetAVPackType(); - CStrObject *GetAVRegion(); - CStrObject *GetGameRegion(); - int GetVideoMode(); - void SetVideoMode(int nVideoMode); - void ApplySkin(); - void FlushMeshCache(); - int Get480Support(); - void Set480Support(int b480Support); - int Get720Support(); - void Set720Support(int b720Support); - int Get1080Support(); - void Set1080Support(int b1080Support); - int GetPAL60Support(); - void SetPAL60Support(int bPAL60Support); - int GetAudioMode(); - void SetAudioMode(int nVideoMode); - int GetDolbyDigitalSupport(); - void SetDolbyDigitalSupport(int bDolbyDigitalSupport); - int GetDTSSupport(); - void SetDTSSupport(int bDTSSupport); - int GetAutoOff(); - void SetAutoOff(int bAutoOff); - int GetLiveToday(); - void SetLiveToday(int bLiveToday); + // Dashboard options + int GetAutoOff(); + void SetAutoOff(int on); + int GetLiveToday(); + void SetLiveToday(int on); + int GetAcceptedLegalInfo(); + void SetAcceptedLegalInfo(int value); + int GetFontVersion(); + void ToggleNoisyCamera(); + void ApplySkin(); + void FlushMeshCache(); - void SetParentPassword(const char *szNewPassword); - int CheckParentPassword(const char *szCheckPassword); + // Power, fan, LED, network + void Reset(); + void PowerOff(); + void PowerCycle(); + void XBOXReset(); + int GetInternalTemp(); + int GetCPUTemp(); + void SetFanSpeed(int speed); + int GetFanSpeed(); + void SetLED(int mode); + void NetworkShutdown(); + void NetworkReboot(); + void NetworkStartup(); + int GetEthernetLinkStatus(); - int GetTimeZone(); - void SetTimeZone(int nTimeZone); - int GetDSTAllowed(); - int GetDST(); - void SetDST(int bObserveDST); + // Version and identity strings + CStrObject* GetRecoveryKey(); + CStrObject* GetROMVersion(); + CStrObject* GetXdashVersion(); + CStrObject* GetXboxIP(); + CStrObject* GetEncoder(); + CStrObject* GetXBOXVersion(); + CStrObject* GetMODCHIPVersion(); + CStrObject* GetXBETitleID(const char* path); - int ForceSetLanguage() { return 0; } // No launch data on desktop - int ForceSetTimeZone() { return 0; } - int ForceSetClock() { return 0; } - - CStrObject *GetRecoveryKey(); - CStrObject *GetROMVersion(); - CStrObject *GetXdashVersion(); - CStrObject *GetXboxIP(); - CStrObject *GetEncoder(); - CStrObject *GetXBOXVersion(); - CStrObject *GetMODCHIPVersion(); - CStrObject *GetXBETitleID(const char *szXBEPath); - - // 5960 functions (RE'd from retail binary) - int GetAcceptedLegalInfo(); - void SetAcceptedLegalInfo(int value); - void BackToLauncher2(); - void GoToXOnlineDash(); - int GetFontVersion(); - void ToggleNoisyCamera(); - int GetEthernetLinkStatus(); - int FileExists(const char* szPath); - -protected: - DECLARE_NODE_FUNCTIONS() + // Files and drives + int FileExists(const char* path); + int NtFileExists(const char* path); + int CanDriveBeCleanup(int drive); + CXBExecutable theXBE; + uint32_t NetStatus; }; diff --git a/theseus/desktop/dashapp.cpp b/theseus/desktop/dashapp.cpp index 8301bde..091fc01 100755 --- a/theseus/desktop/dashapp.cpp +++ b/theseus/desktop/dashapp.cpp @@ -44,7 +44,6 @@ extern void Locale_Exit(); extern void TitleArray_Init(); extern void Material_Init(bool bReloadSkinXBX); -extern float g_nEffectAlpha; bool g_bWireframe = false; bool g_bMovingScreen = true; @@ -122,15 +121,17 @@ D3DXMATRIX g_matIdentity( unsigned int g_uMesh; unsigned int g_uMeshRef; +// Alert(format, ...) +// 5960 @ 0x0002c520 formats into a 512 character buffer and drops it, since +// retail has no debug output. The desktop sends the text to Trace. extern "C" void Alert(const char *szMsg, ...) { + char szText[512]; va_list args; va_start(args, szMsg); - - char szBuffer[512]; - _vsntprintf(szBuffer, countof(szBuffer), szMsg, args); - Trace("\007%s\n", szBuffer); + _vsntprintf(szText, countof(szText), szMsg, args); va_end(args); + Trace("\007%s\n", szText); } extern int GetDiscType(); @@ -329,69 +330,103 @@ void Theseus_D3D_ResetTrace() fflush(stderr); } +// XboxInitRenderState() +// Reconstructed from 5960 retail XBE @ 0x0002c660, which sets the startup +// states one at a time: z test from the z-buffer flag, solid Gouraud fill, +// z writes on, alpha test off, one/zero blending, CCW culling, LESSEQUAL, +// and so on through the list, then the motion blur factor to 1. The desktop +// leaves out EDGEANTIALIAS and MULTISAMPLEANTIALIAS: the first is an NV2A +// feature, the second is set when the GL context is made. void XboxInitRenderState() { - float fZero = 0.0f; - float fOne = 1.0f; - - TheseusSetRenderState(D3DRS_ZENABLE, g_bZBuffer ? D3DZB_TRUE : D3DZB_FALSE); - TheseusSetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); - TheseusSetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); - TheseusSetRenderState(D3DRS_ZWRITEENABLE, TRUE); - TheseusSetRenderState(D3DRS_ALPHATESTENABLE, FALSE); - TheseusSetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); - TheseusSetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO); - TheseusSetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); - TheseusSetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); - TheseusSetRenderState(D3DRS_ALPHAREF, 0); - TheseusSetRenderState(D3DRS_ALPHAFUNC, D3DCMP_ALWAYS); - TheseusSetRenderState(D3DRS_DITHERENABLE, TRUE); - TheseusSetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); - TheseusSetRenderState(D3DRS_FOGENABLE, FALSE); - TheseusSetRenderState(D3DRS_SPECULARENABLE, FALSE); - TheseusSetRenderState(D3DRS_FOGCOLOR, 0); - TheseusSetRenderState(D3DRS_FOGTABLEMODE, D3DFOG_NONE); - TheseusSetRenderState(D3DRS_FOGDENSITY, *(uint32_t*)&fOne); - // EDGEANTIALIAS stripped: Xbox NV2A feature, shim no-op on GL. - TheseusSetRenderState(D3DRS_ZBIAS, 0); - TheseusSetRenderState(D3DRS_RANGEFOGENABLE, FALSE); - TheseusSetRenderState(D3DRS_STENCILENABLE, FALSE); - TheseusSetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP); - TheseusSetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP); - TheseusSetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP); - TheseusSetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS); - TheseusSetRenderState(D3DRS_STENCILREF, 0); - TheseusSetRenderState(D3DRS_STENCILMASK, 0xffffffff); - TheseusSetRenderState(D3DRS_STENCILWRITEMASK, 0xffffffff); - TheseusSetRenderState(D3DRS_WRAP0, 0); - TheseusSetRenderState(D3DRS_WRAP1, 0); - TheseusSetRenderState(D3DRS_WRAP2, 0); - TheseusSetRenderState(D3DRS_WRAP3, 0); - TheseusSetRenderState(D3DRS_LIGHTING, TRUE); - TheseusSetRenderState(D3DRS_AMBIENT, 0); - TheseusSetRenderState(D3DRS_COLORVERTEX, TRUE); - TheseusSetRenderState(D3DRS_LOCALVIEWER, TRUE); - TheseusSetRenderState(D3DRS_NORMALIZENORMALS, FALSE); - TheseusSetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1); - TheseusSetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2); - TheseusSetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_COLOR2); - TheseusSetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL); - TheseusSetRenderState(D3DRS_VERTEXBLEND, D3DVBF_DISABLE); - TheseusSetRenderState(D3DRS_POINTSIZE, *(uint32_t*)&fOne); - TheseusSetRenderState(D3DRS_POINTSIZE_MIN, *(uint32_t*)&fOne); - TheseusSetRenderState(D3DRS_POINTSPRITEENABLE, FALSE); - TheseusSetRenderState(D3DRS_POINTSCALEENABLE, FALSE); - TheseusSetRenderState(D3DRS_POINTSCALE_A, *(uint32_t*)&fOne); - TheseusSetRenderState(D3DRS_POINTSCALE_B, *(uint32_t*)&fZero); - TheseusSetRenderState(D3DRS_POINTSCALE_C, *(uint32_t*)&fZero); - // MULTISAMPLEANTIALIAS stripped: MSAA on desktop is set at GL - // context creation, not via render-state at init. - TheseusSetRenderState(D3DRS_MULTISAMPLEMASK, 0xffffffff); - TheseusSetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA); + const float fZero = 0.0f; + const float fOne = 1.0f; + const DWORD dwZero = *(const uint32_t*)&fZero; + const DWORD dwOne = *(const uint32_t*)&fOne; + + const struct { D3DRENDERSTATETYPE state; DWORD value; } states[] = + { + { D3DRS_ZENABLE, g_bZBuffer ? D3DZB_TRUE : D3DZB_FALSE }, + { D3DRS_FILLMODE, D3DFILL_SOLID }, + { D3DRS_SHADEMODE, D3DSHADE_GOURAUD }, + { D3DRS_ZWRITEENABLE, TRUE }, + { D3DRS_ALPHATESTENABLE, FALSE }, + { D3DRS_SRCBLEND, D3DBLEND_ONE }, + { D3DRS_DESTBLEND, D3DBLEND_ZERO }, + { D3DRS_CULLMODE, D3DCULL_CCW }, + { D3DRS_ZFUNC, D3DCMP_LESSEQUAL }, + { D3DRS_ALPHAREF, 0 }, + { D3DRS_ALPHAFUNC, D3DCMP_ALWAYS }, + { D3DRS_DITHERENABLE, TRUE }, + { D3DRS_ALPHABLENDENABLE, TRUE }, + { D3DRS_FOGENABLE, FALSE }, + { D3DRS_SPECULARENABLE, FALSE }, + { D3DRS_FOGCOLOR, 0 }, + { D3DRS_FOGTABLEMODE, D3DFOG_NONE }, + { D3DRS_FOGDENSITY, dwOne }, + { D3DRS_ZBIAS, 0 }, + { D3DRS_RANGEFOGENABLE, FALSE }, + { D3DRS_STENCILENABLE, FALSE }, + { D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP }, + { D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP }, + { D3DRS_STENCILPASS, D3DSTENCILOP_KEEP }, + { D3DRS_STENCILFUNC, D3DCMP_ALWAYS }, + { D3DRS_STENCILREF, 0 }, + { D3DRS_STENCILMASK, 0xffffffff }, + { D3DRS_STENCILWRITEMASK, 0xffffffff }, + { D3DRS_WRAP0, 0 }, + { D3DRS_WRAP1, 0 }, + { D3DRS_WRAP2, 0 }, + { D3DRS_WRAP3, 0 }, + { D3DRS_LIGHTING, TRUE }, + { D3DRS_AMBIENT, 0 }, + { D3DRS_COLORVERTEX, TRUE }, + { D3DRS_LOCALVIEWER, TRUE }, + { D3DRS_NORMALIZENORMALS, FALSE }, + { D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1 }, + { D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2 }, + { D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_COLOR2 }, + { D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL }, + { D3DRS_VERTEXBLEND, D3DVBF_DISABLE }, + { D3DRS_POINTSIZE, dwOne }, + { D3DRS_POINTSIZE_MIN, dwOne }, + { D3DRS_POINTSPRITEENABLE, FALSE }, + { D3DRS_POINTSCALEENABLE, FALSE }, + { D3DRS_POINTSCALE_A, dwOne }, + { D3DRS_POINTSCALE_B, dwZero }, + { D3DRS_POINTSCALE_C, dwZero }, + { D3DRS_MULTISAMPLEMASK, 0xffffffff }, + { D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA }, + }; + + for (int i = 0; i < (int)countof(states); i++) + TheseusSetRenderState(states[i].state, states[i].value); g_transitionMotionBlur = 1.0f; } +// Scissor rectangle covering back buffer iBuffer (-1 is the front buffer). +static void FullBufferRect(int iBuffer, D3DRECT* pRect) +{ + LPDIRECT3DSURFACE8 pSurface; + D3DSURFACE_DESC desc; + g_pD3DDev->GetBackBuffer(iBuffer, D3DBACKBUFFER_TYPE_MONO, &pSurface); + pSurface->GetDesc(&desc); + pSurface->Release(); + + pRect->x1 = 0; + pRect->y1 = 0; + pRect->x2 = desc.Width; + pRect->y2 = desc.Height; +} + +// InitD3D() +// 5960 @ 0x0002ccf0 sizes the back buffer by AV pack, asks for 4x gaussian +// supersampling and vsync, creates the device, records the front and back +// buffer rectangles and sets the startup states. The desktop sizes the back +// buffer to the window (1280x720 if it can't tell), presents immediately, +// asks for the 2x vertical supersample mode, and switches the first two +// texture stages to anisotropic filtering. bool InitD3D() { g_pD3D = Direct3DCreate8(D3D_SDK_VERSION); @@ -401,88 +436,62 @@ bool InitD3D() return false; } - D3DDEVTYPE devtype = D3DDEVTYPE_HAL; - - memset(&g_pp, 0, sizeof(g_pp)); - g_pp.BackBufferCount = 1; - g_pp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; - - g_pp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - g_pp.SwapEffect = D3DSWAPEFFECT_DISCARD; - g_pp.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES_SUPERSAMPLE_VERTICAL_LINEAR; - g_pp.EnableAutoDepthStencil = g_bZBuffer; - if (g_bZBuffer) - g_pp.AutoDepthStencilFormat = D3DFMT_D24S8; - - uint32_t dwBehavior = D3DCREATE_HARDWARE_VERTEXPROCESSING; - - // Desktop: resolution follows the window. Read it here, since a saved - // borderless or 1080 mode was already applied before we got this far. int drawW = 0, drawH = 0; Plat_GetDrawableSize(&drawW, &drawH); + + memset(&g_pp, 0, sizeof (g_pp)); g_pp.BackBufferWidth = drawW > 0 ? drawW : 1280; g_pp.BackBufferHeight = drawH > 0 ? drawH : 720; - g_pp.Flags = D3DPRESENTFLAG_PROGRESSIVE | D3DPRESENTFLAG_WIDESCREEN; - g_bStretchWidescreen = false; - g_pp.BackBufferFormat = D3DFMT_X8R8G8B8; - + g_pp.BackBufferCount = 1; + g_pp.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES_SUPERSAMPLE_VERTICAL_LINEAR; + g_pp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_pp.hDeviceWindow = NULL; g_pp.Windowed = FALSE; + g_pp.EnableAutoDepthStencil = g_bZBuffer; + if (g_bZBuffer) + g_pp.AutoDepthStencilFormat = D3DFMT_D24S8; + g_pp.Flags = D3DPRESENTFLAG_PROGRESSIVE | D3DPRESENTFLAG_WIDESCREEN; + g_pp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; + g_pp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; + g_bStretchWidescreen = false; g_nViewWidth = (float)g_pp.BackBufferWidth; g_nViewHeight = (float)g_pp.BackBufferHeight; - HRESULT hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, devtype, g_pp.hDeviceWindow, dwBehavior, &g_pp, &g_pD3DDev); + HRESULT hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_pp.hDeviceWindow, + D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_pp, &g_pD3DDev); if (FAILED(hr)) { LogComError(hr, "InitD3D"); return false; } - LPDIRECT3DSURFACE8 pFrontBuffer; - D3DSURFACE_DESC d3dsd; - g_pD3DDev->GetBackBuffer(-1, D3DBACKBUFFER_TYPE_MONO, &pFrontBuffer); - pFrontBuffer->GetDesc(&d3dsd); - pFrontBuffer->Release(); - - g_scissorRect.x1 = 0; - g_scissorRect.y1 = 0; - g_scissorRect.x2 = d3dsd.Width; - g_scissorRect.y2 = d3dsd.Height; - - g_pD3DDev->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pFrontBuffer); - pFrontBuffer->GetDesc(&d3dsd); - pFrontBuffer->Release(); - - g_scissorRectx2.x1 = 0; - g_scissorRectx2.y1 = 0; - g_scissorRectx2.x2 = d3dsd.Width; - g_scissorRectx2.y2 = d3dsd.Height; + + FullBufferRect(-1, &g_scissorRect); + FullBufferRect(0, &g_scissorRectx2); XboxInitRenderState(); TheseusSetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); TheseusSetRenderState(D3DRS_AMBIENT, 0xffffffff); - TheseusSetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_ANISOTROPIC); - TheseusSetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_ANISOTROPIC); - TheseusSetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); - - TheseusSetTextureStageState(1, D3DTSS_MINFILTER, D3DTEXF_ANISOTROPIC); - TheseusSetTextureStageState(1, D3DTSS_MAGFILTER, D3DTEXF_ANISOTROPIC); + for (DWORD stage = 0; stage < 2; stage++) + { + TheseusSetTextureStageState(stage, D3DTSS_MINFILTER, D3DTEXF_ANISOTROPIC); + TheseusSetTextureStageState(stage, D3DTSS_MAGFILTER, D3DTEXF_ANISOTROPIC); + if (stage == 0) + TheseusSetTextureStageState(stage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); + } return true; } +// ReleaseD3D() +// Frees the world matrix stack and the Direct3D object. void ReleaseD3D() { RELEASENULL(g_worldStack); - - if (g_pD3D != NULL) - { - g_pD3D->Release(); - g_pD3D = NULL; - } + RELEASENULL(g_pD3D); } // ============================================================================ @@ -495,250 +504,211 @@ struct COLORVERTEX uint32_t color; }; -void Draw() +// Rebuild the projection when something marked it dirty: field of view +// from the bound viewpoint (90 degrees without one), near at half the +// avatar size and far at the visibility limit (0.1 and 1000 without them). +static void UpdateProjection() { - Frame_PhaseBegin(FP_SCENE_SETUP); - // Setup projection transform - if (g_bProjectionDirty) - { - g_bProjectionDirty = false; + if (!g_bProjectionDirty) + return; + g_bProjectionDirty = false; - float nNear = 0.1f; - float nFar = 1000.0f; - float fieldOfView = D3DX_PI / 2.0f; + float fieldOfView = D3DX_PI / 2.0f; + float nNear = 0.1f; + float nFar = 1000.0f; - if (g_pNavigationInfo != NULL) - { - nNear = g_pNavigationInfo->m_avatarSize.x / 2.0f; - if (g_pNavigationInfo->m_visibilityLimit != 0.0f) - nFar = g_pNavigationInfo->m_visibilityLimit; - } + if (g_pNavigationInfo != NULL) + { + nNear = g_pNavigationInfo->m_avatarSize.x / 2.0f; + if (g_pNavigationInfo->m_visibilityLimit != 0.0f) + nFar = g_pNavigationInfo->m_visibilityLimit; + } + if (g_pViewpoint != NULL) + fieldOfView = g_pViewpoint->m_fieldOfView; + + D3DXMatrixPerspectiveFovLH(&g_matProjection, fieldOfView, g_nViewWidth / g_nViewHeight, nNear, nFar); + TheseusSetTransform(D3DTS_PROJECTION, &g_matProjection); +} - if (g_pViewpoint != NULL) +// Motion blur: instead of clearing, lay a black quad of alpha blurAlpha +// over the last frame so it fades out. The quad is built once. +static void FadeLastFrame(float blurAlpha) +{ + static LPDIRECT3DVERTEXBUFFER8 s_pQuad; + if (s_pQuad == NULL) + { + VERIFYHR(TheseusGetD3DDev()->CreateVertexBuffer(4 * sizeof (COLORVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE, D3DPOOL_MANAGED, &s_pQuad)); + + COLORVERTEX* verts; + VERIFYHR(s_pQuad->Lock(0, 4 * sizeof (COLORVERTEX), (uint8_t**)&verts, 0)); + const float halfW = g_nViewWidth / 2.0f; + const float halfH = g_nViewHeight / 2.0f; + const float corners[4][2] = { { halfW, -halfH }, { -halfW, -halfH }, { halfW, halfH }, { -halfW, halfH } }; + for (int i = 0; i < 4; i++) { - fieldOfView = g_pViewpoint->m_fieldOfView; + verts[i].dvX = corners[i][0]; + verts[i].dvY = corners[i][1]; + verts[i].dvZ = 0.0f; + verts[i].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); } - float aspect = g_nViewWidth / g_nViewHeight; - - D3DXMatrixPerspectiveFovLH(&g_matProjection, fieldOfView, aspect, nNear, nFar); - TheseusSetTransform(D3DTS_PROJECTION, &g_matProjection); + VERIFYHR(s_pQuad->Unlock()); } - g_uMesh = 0; - g_uMeshRef = 0; - - TheseusBeginScene(); + D3DXMATRIX matOrtho, matSavedProjection, matSavedWorld, matSavedView; + TheseusGetTransform(D3DTS_PROJECTION, &matSavedProjection); + TheseusGetTransform(D3DTS_WORLD, &matSavedWorld); + TheseusGetTransform(D3DTS_VIEW, &matSavedView); + + D3DXMatrixOrthoLH(&matOrtho, g_nViewWidth, g_nViewHeight, -10000.0f, 10000.0f); + TheseusSetTransform(D3DTS_PROJECTION, &matOrtho); + TheseusSetTransform(D3DTS_WORLD, &g_matIdentity); + TheseusSetTransform(D3DTS_VIEW, &g_matIdentity); + + // Stage 0 passes the vertex color and alpha straight through, stage 1 is off. + TheseusSetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); + TheseusSetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); + TheseusSetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); + TheseusSetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE); + TheseusSetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); + TheseusSetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); + TheseusSetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); + TheseusSetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); + TheseusSetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); + TheseusSetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); - TheseusSetRenderState(D3DRS_FILLMODE, g_bWireframe ? D3DFILL_WIREFRAME : D3DFILL_SOLID); + TheseusSetStreamSource(0, s_pQuad, sizeof (COLORVERTEX)); + TheseusSetVertexShader(D3DFVF_XYZ | D3DFVF_DIFFUSE); + VERIFYHR(TheseusGetD3DDev()->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2)); - const float blurAlpha = g_transitionMotionBlur; - - D3DCOLOR color; - bool bBackdrop = false; - if (g_pBackground == NULL) - color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.3f, 1.0f); - else - color = D3DCOLOR_COLORVALUE(g_pBackground->m_skyColor.x, g_pBackground->m_skyColor.y, g_pBackground->m_skyColor.z, 1.0f); + TheseusSetTransform(D3DTS_PROJECTION, &matSavedProjection); + TheseusSetTransform(D3DTS_WORLD, &matSavedWorld); + TheseusSetTransform(D3DTS_VIEW, &matSavedView); +} - if (g_pBackground != NULL && g_pBackground->m_backdrop != NULL) - bBackdrop = true; +static float Clamp01(float v) +{ + return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); +} - static int nBeenHere; - if (blurAlpha >= 1.0f || nBeenHere++ < 2 || color != D3DCOLOR_XRGB(0, 0, 0) || bBackdrop) - { - TheseusClear(color); +// Theseus: the headlight and the scene's lights. A navigation info with +// its headlight on (or none at all) gets a dim white directional light +// down the view; the scene adds its own and the summed ambient is clamped. +static void SetupLights() +{ + static int s_nLastLights = -1; + int nLights = 0; + D3DCOLORVALUE ambient; + ambient.r = ambient.g = ambient.b = 0.0f; - if (bBackdrop) - g_pBackground->RenderBackdrop(); - } - else + if (g_pNavigationInfo == NULL || g_pNavigationInfo->m_headlight) { - // Motion blur overlay quad - static LPDIRECT3DVERTEXBUFFER8 m_pVB; - if (m_pVB == NULL) - { - VERIFYHR(TheseusGetD3DDev()->CreateVertexBuffer(4 * sizeof(COLORVERTEX), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE, D3DPOOL_MANAGED, &m_pVB)); - - COLORVERTEX *verts; - VERIFYHR(m_pVB->Lock(0, 4 * sizeof(COLORVERTEX), (uint8_t **)&verts, 0)); - - verts[0].dvX = (float)g_nViewWidth / 2.0f; - verts[0].dvY = -(float)g_nViewHeight / 2.0f; - verts[0].dvZ = 0.0f; - verts[0].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); - - verts[1].dvX = -(float)g_nViewWidth / 2.0f; - verts[1].dvY = -(float)g_nViewHeight / 2.0f; - verts[1].dvZ = 0.0f; - verts[1].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); - - verts[2].dvX = (float)g_nViewWidth / 2.0f; - verts[2].dvY = (float)g_nViewHeight / 2.0f; - verts[2].dvZ = 0.0f; - verts[2].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); - - verts[3].dvX = -(float)g_nViewWidth / 2.0f; - verts[3].dvY = (float)g_nViewHeight / 2.0f; - verts[3].dvZ = 0.0f; - verts[3].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); + TheseusSetTransform(D3DTS_WORLD, &g_matIdentity); - VERIFYHR(m_pVB->Unlock()); - } + D3DLIGHT8 light; + memset(&light, 0, sizeof (light)); + light.Type = D3DLIGHT_DIRECTIONAL; + light.Diffuse.r = light.Diffuse.g = light.Diffuse.b = 0.5f; + light.Specular.r = light.Specular.g = light.Specular.b = 0.75f; + light.Ambient.r = light.Ambient.g = light.Ambient.b = 0.2f; - D3DXMATRIX matProjection, matProjectionSave, matWorldSave, matViewSave; + ambient.r += light.Ambient.r; + ambient.g += light.Ambient.g; + ambient.b += light.Ambient.b; - TheseusGetTransform(D3DTS_PROJECTION, &matProjectionSave); - TheseusGetTransform(D3DTS_WORLD, &matWorldSave); - TheseusGetTransform(D3DTS_VIEW, &matViewSave); + D3DXVECTOR3 dir(0.0f, 0.0f, -1.0f); + D3DXVec3TransformNormal(&dir, &dir, &g_matPosition); + light.Direction = dir; - D3DXMatrixOrthoLH(&matProjection, g_nViewWidth, g_nViewHeight, -10000.0f, 10000.0f); - TheseusSetTransform(D3DTS_PROJECTION, &matProjection); - TheseusSetTransform(D3DTS_WORLD, &g_matIdentity); - TheseusSetTransform(D3DTS_VIEW, &g_matIdentity); - - TheseusSetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); - TheseusSetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); - TheseusSetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); - TheseusSetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE); - TheseusSetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); - TheseusSetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); - TheseusSetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); - TheseusSetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - TheseusSetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); - TheseusSetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); - - TheseusSetStreamSource(0, m_pVB, sizeof(COLORVERTEX)); - TheseusSetVertexShader(D3DFVF_XYZ | D3DFVF_DIFFUSE); - VERIFYHR(TheseusGetD3DDev()->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2)); - - TheseusSetTransform(D3DTS_PROJECTION, &matProjectionSave); - TheseusSetTransform(D3DTS_WORLD, &matWorldSave); - TheseusSetTransform(D3DTS_VIEW, &matViewSave); + TheseusSetLight(nLights, &light); + TheseusLightEnable(nLights, true); + nLights++; } - // Setup lights - { - static int nLastLight = -1; - int nLight = 0; - D3DCOLORVALUE ambient; - ambient.r = 0.0f; - ambient.g = 0.0f; - ambient.b = 0.0f; - - // Headlight - if (g_pNavigationInfo == NULL || g_pNavigationInfo->m_headlight) - { - TheseusSetTransform(D3DTS_WORLD, &g_matIdentity); + g_pObject->SetLight(nLights, ambient); - D3DLIGHT8 d3dLight; - memset(&d3dLight, 0, sizeof(d3dLight)); + TheseusSetRenderState(D3DRS_AMBIENT, D3DCOLOR_COLORVALUE(Clamp01(ambient.r), Clamp01(ambient.g), Clamp01(ambient.b), 1.0f)); - d3dLight.Type = D3DLIGHT_DIRECTIONAL; + for (int i = nLights; i < s_nLastLights; i++) + TheseusLightEnable(i, false); - d3dLight.Diffuse.r = 0.5f; - d3dLight.Diffuse.g = 0.5f; - d3dLight.Diffuse.b = 0.5f; + TheseusSetRenderState(D3DRS_LIGHTING, nLights > 0); + s_nLastLights = nLights; +} - d3dLight.Specular.r = 0.75f; - d3dLight.Specular.g = 0.75f; - d3dLight.Specular.b = 0.75f; +// Draw() +// Reconstructed from 5960 retail XBE @ 0x0002d0e0. Projection if dirty; +// then the background: a clear to the sky color (dark blue without a +// Background node) plus its backdrop, or, while a transition blurs (factor +// under 1, past the first two frames, black sky, no backdrop), a fade of +// the last frame instead. Then a default material (grey, made once), the +// scene drawn from an identity world, and Present. Theseus adds the +// lights, wireframe, its frame profiler and the active keyboard reset. +void Draw() +{ + Frame_PhaseBegin(FP_SCENE_SETUP); - d3dLight.Ambient.r = 0.2f; - d3dLight.Ambient.g = 0.2f; - d3dLight.Ambient.b = 0.2f; + UpdateProjection(); - ambient.r += d3dLight.Ambient.r; - ambient.g += d3dLight.Ambient.g; - ambient.b += d3dLight.Ambient.b; + g_uMesh = 0; + g_uMeshRef = 0; - D3DXVECTOR3 dir(0.0f, 0.0f, -1.0f); - D3DXVec3TransformNormal(&dir, &dir, &g_matPosition); - d3dLight.Direction = dir; + TheseusBeginScene(); + TheseusSetRenderState(D3DRS_FILLMODE, g_bWireframe ? D3DFILL_WIREFRAME : D3DFILL_SOLID); - TheseusSetLight(nLight, &d3dLight); - TheseusLightEnable(nLight, true); - nLight += 1; - } + // A bigger factor means less blur. + const float blurAlpha = g_transitionMotionBlur; - g_pObject->SetLight(nLight, ambient); - - if (ambient.r < 0.0f) - ambient.r = 0.0f; - else if (ambient.r > 1.0f) - ambient.r = 1.0f; - if (ambient.g < 0.0f) - ambient.g = 0.0f; - else if (ambient.g > 1.0f) - ambient.g = 1.0f; - if (ambient.b < 0.0f) - ambient.b = 0.0f; - else if (ambient.b > 1.0f) - ambient.b = 1.0f; - - TheseusSetRenderState(D3DRS_AMBIENT, D3DCOLOR_COLORVALUE(ambient.r, ambient.g, ambient.b, 1.0f)); - - // Turn off lights we are not using - for (int i = nLight; i < nLastLight; i += 1) - TheseusLightEnable(i, false); - - TheseusSetRenderState(D3DRS_LIGHTING, nLight > 0); - nLastLight = nLight; + D3DCOLOR sky = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.3f, 1.0f); + bool bBackdrop = false; + if (g_pBackground != NULL) + { + sky = D3DCOLOR_COLORVALUE(g_pBackground->m_skyColor.x, g_pBackground->m_skyColor.y, g_pBackground->m_skyColor.z, 1.0f); + bBackdrop = g_pBackground->m_backdrop != NULL; } - // Default material + static int s_nFrames; + if (blurAlpha >= 1.0f || s_nFrames++ < 2 || sky != D3DCOLOR_XRGB(0, 0, 0) || bBackdrop) { - static D3DMATERIAL8 mat; - if (mat.Diffuse.r == 0.0f) - { - mat.Diffuse.r = 0.5f; - mat.Diffuse.g = 0.5f; - mat.Diffuse.b = 0.5f; - mat.Diffuse.a = 1.0f; - - mat.Ambient.r = 0.5f; - mat.Ambient.g = 0.5f; - mat.Ambient.b = 0.5f; - mat.Ambient.a = 1.0f; - - mat.Specular.r = 0.5f; - mat.Specular.g = 0.5f; - mat.Specular.b = 0.5f; - mat.Specular.a = 1.0f; - - mat.Emissive.r = 0.5f; - mat.Emissive.g = 0.5f; - mat.Emissive.b = 0.5f; - mat.Emissive.a = 1.0f; - - mat.Power = 0.0f; - } + TheseusClear(sky); + if (bBackdrop) + g_pBackground->RenderBackdrop(); + } + else + { + FadeLastFrame(blurAlpha); + } + + SetupLights(); - TheseusSetMaterial(&mat); + static D3DMATERIAL8 s_material; + if (s_material.Diffuse.r == 0.0f) + { + D3DCOLORVALUE grey; + grey.r = grey.g = grey.b = 0.5f; + grey.a = 1.0f; + s_material.Diffuse = s_material.Ambient = s_material.Specular = s_material.Emissive = grey; + s_material.Power = 0.0f; } + TheseusSetMaterial(&s_material); - // Draw the world Frame_PhaseEnd(FP_SCENE_SETUP); + Frame_PhaseBegin(FP_SCENE_TREE); - { - // Clear active-keyboard tracker before scene render; visible CKeyboards - // will re-set it via their Render() override. Hidden ones never run, so - // the global ends up NULL when no keyboard is on screen. - extern void Keyboard_ClearActive(); - Keyboard_ClearActive(); - - TheseusPushWorld(); - TheseusIdentityWorld(); - TheseusUpdateWorld(); - g_pObject->Render(); - TheseusPopWorld(); - } + // Visible keyboards claim this again while they render. + extern void Keyboard_ClearActive(); + Keyboard_ClearActive(); + TheseusPushWorld(); + TheseusIdentityWorld(); + TheseusUpdateWorld(); + g_pObject->Render(); + TheseusPopWorld(); Frame_PhaseEnd(FP_SCENE_TREE); Frame_PhaseBegin(FP_SCENE_END); TheseusEndScene(); Frame_PhaseEnd(FP_SCENE_END); - TheseusSetRenderState(D3DRS_SWATHWIDTH, D3DSWATH_OFF); + TheseusSetRenderState(D3DRS_SWATHWIDTH, D3DSWATH_OFF); TheseusPresent(); TheseusSetRenderState(D3DRS_SWATHWIDTH, D3DSWATH_128); @@ -749,13 +719,17 @@ void Draw() // Application Lifecycle // ============================================================================ +// InitApp() +// 5960 @ 0x0002d7e0: CD-ROM and disc type, platform init, version lock and +// the online redirect, InitD3D, the default XIP, Class_Init, materials, then +// load and create the startup scene and call its initialize. The desktop +// keeps that order without the online steps, starts SDL audio after the +// device and preloads the skin textures at the end. bool InitApp() { Memory_Init(); DashInit(); - Debug_Init(); - DiscDrive_Init(); if (!InitD3D()) @@ -767,46 +741,43 @@ bool InitApp() TitleArray_Init(); Material_Init(false); - // Load the startup class file (default.xap) - { - char szFileToLoad[MAX_PATH]; - szFileToLoad[0] = 0; - - if (!g_pClass) - g_pClass = new CClass; - - GetStartupClassFile(szFileToLoad); - ASSERT(szFileToLoad[0] != 0); + if (g_pClass == NULL) + g_pClass = new CClass; - if (!g_pClass->Load(szFileToLoad)) - { - extern bool g_bParseError; - if (!g_bParseError) - Alert("%s\n\nCannot open file.", szFileToLoad); - return false; - } + char szStartup[MAX_PATH]; + szStartup[0] = 0; + GetStartupClassFile(szStartup); + if (!g_pClass->Load(szStartup)) + { + // A parse error has already said what went wrong. + extern bool g_bParseError; + if (!g_bParseError) + Alert("%s\n\nCannot open file.", szStartup); + return false; } - g_pObject = (CInstance *)g_pClass->CreateNode(); - ASSERT(g_pObject != NULL); - + g_pObject = (CInstance*)g_pClass->CreateNode(); VERIFYHR(D3DXCreateMatrixStack(0, &g_worldStack)); - ASSERT(g_worldStack != NULL); CallFunction(g_pObject, "initialize"); - PreloadSkinTextures(); - fprintf(stdout, "[InitApp] Done!\n"); fflush(stdout); + + fprintf(stdout, "[InitApp] Done!\n"); + fflush(stdout); return true; } +// CleanupApp() +// 5960 @ 0x0002d930 ends the XOnline session, frees the matrix stack, the +// scene and its class, then Class_Exit, the XIP sections, Text_Exit, sound +// and the app dir. The desktop releases D3D first, drops Locale too, and +// shuts down CD audio, SDL audio, Plex and Jellyfin. void CleanupApp() { ReleaseD3D(); delete g_pObject; g_pObject = NULL; - delete g_pClass; g_pClass = NULL; @@ -814,12 +785,11 @@ void CleanupApp() Locale_Exit(); Text_Exit(); + extern void Plex_Shutdown(); + extern void Jellyfin_Shutdown(); CdAudio_Shutdown(); DashAudio_Shutdown(); - - extern void Plex_Shutdown(); Plex_Shutdown(); - extern void Jellyfin_Shutdown(); Jellyfin_Shutdown(); delete[] g_szAppDir; @@ -828,10 +798,15 @@ void CleanupApp() Debug_Exit(); } +// Advance() +// From the 5960 frame loop @ 0x0002da00: the step is the change in +// the clock since last frame (one millisecond's worth if it didn't move), +// then the camera, every lerper and the scene advance. Theseus clocks from +// launch on a high resolution counter (scripts time things like the screen +// saver against 0, so an uptime base would fire them on the first frame), +// and feeds its background loader. void Advance() { - // Seconds since launch, on every host. Scripts time things like the - // screensaver against 0, so an uptime base fires them on the first frame. static const Uint64 s_clockStart = SDL_GetPerformanceCounter(); XTIME now = (double)(SDL_GetPerformanceCounter() - s_clockStart) / (double)SDL_GetPerformanceFrequency(); float nDelta = (float)(now - g_now); @@ -840,15 +815,11 @@ void Advance() g_now = now; g_dwFrameTick = GetTickCount(); - ASSERT(g_nEffectAlpha == 1.0f); - theCamera.Advance(nDelta); - CLerper::AdvanceAll(); g_pObject->Advance(nDelta); BackgroundLoader_Frame(); - Debug_Frame(); } @@ -856,23 +827,23 @@ void Advance() // Startup // ============================================================================ +static char* NewCopy(const char* sz) +{ + char* copy = new char[strlen(sz) + 1]; + strcpy(copy, sz); + return copy; +} + +// GetStartupClassFile(out) +// 5960 @ 0x0002dbc0 starts from y:\default.xap with y:/default.xap as the +// current dir and keeps the app dir. Theseus runs from Q:, so the scene is +// Q:\Xips\default.xap, and it also records its font and XIP dirs. void GetStartupClassFile(char *szFileToLoad) { - char szAppDir[MAX_PATH]; - char szFontDir[MAX_PATH]; - char szXipDir[MAX_PATH]; strcpy(szFileToLoad, "Q:\\Xips\\default.xap"); - strcpy(szAppDir, "Q:\\"); - strcpy(szFontDir, "Q:\\Fonts\\"); - strcpy(szXipDir, "Q:\\Xips\\"); strcpy(g_szCurDir, "Q:/Xips/default.xap"); - g_szAppDir = new char[strlen(szAppDir) + 1]; - strcpy(g_szAppDir, szAppDir); - - g_sFontDir = new char[strlen(szFontDir) + 1]; - strcpy(g_sFontDir, szFontDir); - - g_sXipDir = new char[strlen(szXipDir) + 1]; - strcpy(g_sXipDir, szXipDir); + g_szAppDir = NewCopy("Q:\\"); + g_sFontDir = NewCopy("Q:\\Fonts\\"); + g_sXipDir = NewCopy("Q:\\Xips\\"); } diff --git a/theseus/desktop/desktop_nodes.cpp b/theseus/desktop/desktop_nodes.cpp index 3342bc0..06f640a 100644 --- a/theseus/desktop/desktop_nodes.cpp +++ b/theseus/desktop/desktop_nodes.cpp @@ -447,46 +447,48 @@ START_NODE_FUN(CPeriodicAudioGroup, CGroup) END_NODE_FUN() // ============================================================================ -// CAudioVisualizer - full port from AudioVisualizer.cpp -// Uses DashAudio_GetPCMSamples() ring buffer instead of Xbox GetSampleBuffer() +// CAudioVisualizer +// 5960 code at 0x63760..0x64630, notes in docs/decomp/AudioVisualizer.md. +// The desktop reads the mixer's last 256 frames (DashAudio_GetPCMSamples) +// where 5960 reads its AudioClip source's sample buffer. // ============================================================================ #include "tmap_system.h" #include "fft.h" -#define TRANSPORT_PLAY 1 - class CAudioVisualizer : public CNode { DECLARE_NODE(CAudioVisualizer, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CAudioVisualizer(); ~CAudioVisualizer(); - TCHAR* m_type; // "line", "spinner"/"spin", "circle", "analyzer"/"a" - TCHAR* m_channel; // "left"/"l", "center"/"c", "right"/"r" + // 5960 layout, 0x834 bytes: m_type 0x1c, m_channel 0x20, m_source 0x24, + // m_scale 0x28, m_offset 0x2c, then the sample and spectrum buffers. + TCHAR* m_type; // line (default), spinner, circle, analyzer: first letter counts + TCHAR* m_channel; // r or R picks the right channel, anything else the left CNode* m_source; float m_scale; float m_offset; protected: + void Advance(float dt); + void RenderDynamicTexture(CSurfx* surface); + short* GetMonoPCM(); + void CalcSpectrum(short* pcm, short* bins); void UpdateSpectrum(); - void RenderDynamicTexture(CSurfx* pSurfx); - void Advance(float nSeconds); - void CalcSpectrum(short* pcm, short* fft); - void RenderEffect1(CSurfx* pSurfx); - void RenderEffect2(CSurfx* pSurfx); - - short m_pcmLeft[256]; - short m_pcmRight[256]; - short m_fftLeft[128]; - short m_fftRight[128]; - bool m_bFFTValid; - short m_pcmMono[256]; - bool m_bMonoValid; - - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() + void RenderEffect1(CSurfx* surface); + void RenderEffect2(CSurfx* surface); + + short m_pcmLeft[256]; // 0x030 + short m_pcmRight[256]; // 0x230 + short m_fftLeft[128]; // 0x430 + short m_fftRight[128]; // 0x530 + bool m_bFFTValid; // 0x630 + short m_pcmMono[256]; // 0x632 + bool m_bMonoValid; // 0x832 }; IMPLEMENT_NODE("AudioVisualizer", CAudioVisualizer, CNode) @@ -504,510 +506,455 @@ END_NODE_PROPS() START_NODE_FUN(CAudioVisualizer, CNode) END_NODE_FUN() -CAudioVisualizer::CAudioVisualizer() : - m_type(NULL), - m_source(NULL), - m_scale(1.0f), - m_offset(0.0f), - m_channel(NULL), - m_bFFTValid(false), - m_bMonoValid(false) +// CAudioVisualizer::CAudioVisualizer() +// Reconstructed from 5960 retail XBE @ 0x00063770 (inlined in CreateNode): +// m_type = m_channel = m_source = 0; m_scale = 1.0; m_offset = 0; +// 5960 leaves the buffers alone; Theseus zeroes them so the first frame is flat. +CAudioVisualizer::CAudioVisualizer() { - memset(m_pcmLeft, 0, sizeof(m_pcmLeft)); - memset(m_pcmRight, 0, sizeof(m_pcmRight)); - memset(m_fftLeft, 0, sizeof(m_fftLeft)); - memset(m_fftRight, 0, sizeof(m_fftRight)); - memset(m_pcmMono, 0, sizeof(m_pcmMono)); + m_type = NULL; + m_channel = NULL; + m_source = NULL; + m_scale = 1.0f; + m_offset = 0.0f; + m_bFFTValid = false; + m_bMonoValid = false; + + memset(m_pcmLeft, 0, sizeof (m_pcmLeft)); + memset(m_pcmRight, 0, sizeof (m_pcmRight)); + memset(m_fftLeft, 0, sizeof (m_fftLeft)); + memset(m_fftRight, 0, sizeof (m_fftRight)); + memset(m_pcmMono, 0, sizeof (m_pcmMono)); } +// CAudioVisualizer::~CAudioVisualizer() +// Reconstructed from 5960 retail XBE @ 0x00063800: +// delete[] m_type; delete[] m_channel; if (m_source) m_source->Release(); CAudioVisualizer::~CAudioVisualizer() { delete [] m_type; delete [] m_channel; - - if (m_source != NULL) + if (m_source) m_source->Release(); } -void CAudioVisualizer::Advance(float nSeconds) +// CAudioVisualizer::Advance(dt) +// Reconstructed from 5960 retail XBE @ 0x00063870: +// CNode::Advance(dt); if (m_source) m_source->Advance(dt); +// The source clip is ticked from here because it isn't in the scene itself. +void CAudioVisualizer::Advance(float dt) { - CNode::Advance(nSeconds); - - if (m_source != NULL) - m_source->Advance(nSeconds); + CNode::Advance(dt); + if (m_source) + m_source->Advance(dt); } +// Theseus: 5960 has no mono mix. Average of the two channels, cached per frame. short* CAudioVisualizer::GetMonoPCM() { - if (!m_bMonoValid) - { - for (int i = 0; i < 256; i += 1) - m_pcmMono[i] = (short)(((int)m_pcmLeft[i] + (int)m_pcmRight[i]) / 2); - m_bMonoValid = true; - } + if (m_bMonoValid) + return m_pcmMono; + + for (int i = 0; i < 256; i++) + m_pcmMono[i] = (short)((m_pcmLeft[i] + m_pcmRight[i]) / 2); + m_bMonoValid = true; return m_pcmMono; } -void CAudioVisualizer::CalcSpectrum(short* pcm, short* fft) +// CAudioVisualizer::CalcSpectrum(pcm, bins) +// Reconstructed from 5960 retail XBE @ 0x000638a0: +// if (!state) state = fft_init(); fft_perform(pcm, power, state); +// for (i = 0; i < 129; i++) bins[i] = sqrt(power[i]) * (1/256); +// 129 bins land in a 128 short array, same as 5960: the last one spills into +// whatever follows (the right channel's first bin, or the valid flag). +void CAudioVisualizer::CalcSpectrum(short* pcm, short* bins) { - static fft_state *state = NULL; - float buf[FFT_BUFFER_SIZE / 2 + 1]; - - if (!state) - state = fft_init(); + static fft_state* s_fft = NULL; + const int nBins = FFT_BUFFER_SIZE / 2 + 1; + float power[nBins]; - fft_perform(pcm, buf, state); + if (s_fft == NULL) + s_fft = fft_init(); + fft_perform(pcm, power, s_fft); - for (int i = 0; i < FFT_BUFFER_SIZE / 2 + 1; i += 1) + for (int i = 0; i < nBins; i++) { - buf[i] = sqrtf(buf[i]) / FFT_BUFFER_SIZE; - fft[i] = (short)buf[i]; + power[i] = sqrtf(power[i]) / FFT_BUFFER_SIZE; + bins[i] = (short)power[i]; } } +// CAudioVisualizer::UpdateSpectrum() +// Reconstructed from 5960 retail XBE @ 0x00063900: +// if (!m_bFFTValid) { CalcSpectrum(left); CalcSpectrum(right); m_bFFTValid = 1; } void CAudioVisualizer::UpdateSpectrum() { - if (m_bFFTValid) - return; - - CalcSpectrum(m_pcmLeft, m_fftLeft); - CalcSpectrum(m_pcmRight, m_fftRight); - - m_bFFTValid = true; + if (!m_bFFTValid) + { + CalcSpectrum(m_pcmLeft, m_fftLeft); + CalcSpectrum(m_pcmRight, m_fftRight); + m_bFFTValid = true; + } } -// Helper pixel-set with bounds checking -static void VizSetPixel(CSurfx* pSurfx, int x, int y, BYTE color) +// Clipped single pixel. 5960 writes the analyzer's pixels unclipped; the +// curve overlay's 2x2 dot (0x640a0) clips each of its four the same way. +static void VizPlot(CSurfx* surface, int x, int y, BYTE color) { - if (x < 0 || y < 0 || x >= pSurfx->m_nWidth || y >= pSurfx->m_nHeight) - return; - *pSurfx->Pixel(x, y) = color; + if (x >= 0 && y >= 0 && x < surface->m_nWidth && y < surface->m_nHeight) + *surface->Pixel(x, y) = color; } -static void VizSetPixel2(CSurfx* pSurfx, int x, int y, BYTE color) +static void VizPlot2x2(CSurfx* surface, int x, int y, BYTE color) { - VizSetPixel(pSurfx, x, y, color); - VizSetPixel(pSurfx, x + 1, y, color); - VizSetPixel(pSurfx, x + 1, y + 1, color); - VizSetPixel(pSurfx, x, y + 1, color); + VizPlot(surface, x, y, color); + VizPlot(surface, x + 1, y, color); + VizPlot(surface, x + 1, y + 1, color); + VizPlot(surface, x, y + 1, color); } -#define viz_mag(s) ((float)samples[(int)(s * nSamples) * 2 + lrc] / 32767.0f) +// Clamped byte from a log level, as the analyzer bars use it. +static BYTE VizLevel(float n) +{ + if (n <= 0.0f) + return 0; + if (n >= 255.0f) + return 255; + return (BYTE)n; +} -void CAudioVisualizer::RenderDynamicTexture(CSurfx* pSurfx) +// CAudioVisualizer::RenderDynamicTexture(surface) +// Reconstructed from 5960 retail XBE @ 0x00063940 (1363 bytes). 5960 bails +// unless the source is a playing AudioClip with samples, copies up to 256 +// stereo frames in (zero filling the rest), clears both cache flags, clamps +// the count to the surface height, picks the channel from m_channel and the +// style from m_type's first letter, then draws: +// line: one Line per row, x = w/2 + (sample * w >> 16). +// spinner: a stretched waveform rotated by g_now * 0.2, w steps over [0, 1]. +// analyzer: log levels of both spectra (left reversed, then right), peaks +// that fall 2 a frame, bars fading from 255 down, then RenderEffect1 and 2. +// Full walk through in docs/decomp/AudioVisualizer.md. Theseus differences: +// samples come from the desktop mixer every frame, the circle style (absent +// from 5960) is drawn, the analyzer takes log(level + 1) and clips the peak +// dot, and the spinner skips 5960's unused rand() call. +void CAudioVisualizer::RenderDynamicTexture(CSurfx* surface) { - // Desktop music playback goes through Mix_PlayMusic (CMP3Pump / - // CMusicCollection), not the CAudioClip API the Xbox path uses, so the - // scene's m_source CAudioClip never enters TRANSPORT_PLAY. The - // Mix_SetPostMix ring captures every mixed channel anyway; just pull - // from it whenever the visualizer ticks. Silence reads as zeros and - // draws a flat scope, which is the right behaviour when nothing is - // playing. DashAudio_GetPCMSamples(m_pcmLeft, m_pcmRight, 256); - - int nSamples = 256; m_bMonoValid = false; m_bFFTValid = false; - // Build interleaved buffer for the mag() macro - short samples[512]; - for (int i = 0; i < nSamples; i++) { - samples[i * 2] = m_pcmLeft[i]; - samples[i * 2 + 1] = m_pcmRight[i]; - } + const int w = surface->m_nWidth; + const int h = surface->m_nHeight; + int nFrames = 256; + if (nFrames > h) + nFrames = h; - if (nSamples > pSurfx->m_nHeight) - nSamples = pSurfx->m_nHeight; + // One channel, picked by m_channel. + const short* pcm = m_pcmLeft; + if (m_channel != NULL && (m_channel[0] == 'r' || m_channel[0] == 'R')) + pcm = m_pcmRight; - int lrc = 0; - if (m_channel != NULL) - { - if (m_channel[0] == 'r' || m_channel[0] == 'R') - lrc = 1; - } - - int nType = 0; - if (m_type != NULL) - { - switch (m_type[0]) - { - case 's': case 'S': nType = 1; break; // spinner - case 'c': case 'C': nType = 2; break; // circle - case 'a': case 'A': nType = 3; break; // analyzer - } - } + TCHAR style = (m_type != NULL) ? m_type[0] : 0; + if (style >= 'A' && style <= 'Z') + style += 'a' - 'A'; - float t = (float)TheseusGetNow(); + const float now = (float)TheseusGetNow(); - switch (nType) + if (style == 's') { - case 0: // Line Scope - { - int xCenter = pSurfx->m_nWidth / 2; - int xp = xCenter; - int yp = 0; + const int xMid = w / 2; + const int yMid = h / 2; + const float dx = 1.0f / (float)w; + const float c = cosf(now * 0.2f); + const float s = sinf(now * 0.2f); + float xPrev = 0.0f; + float yPrev = 0.0f; - for (int y = 0; y < nSamples; y += 1) + for (float t = 0.0f; t <= 1.0f; t += dx) + { + int iFrame = (int)(t * nFrames); + if (iFrame >= nFrames) + iFrame = nFrames - 1; // t can land on exactly 1.0 + float amp = (float)pcm[iFrame] / 32767.0f * m_scale + m_offset; + float along = 2.1f * (t - 0.5f); + float x = c * along + s * amp; + float y = -c * amp + s * along; + + if (t != 0.0f) { - long s = (((long)samples[y * 2 + lrc]) * pSurfx->m_nWidth) >> 16; - int x = xCenter + (int)s; - pSurfx->Line(xp, yp, x, y, 255); - xp = x; - yp = y; + surface->Line(xMid + (int)(xPrev * xMid), yMid + (int)(yPrev * yMid), + xMid + (int)(x * xMid), yMid + (int)(y * yMid), 255); } + xPrev = x; + yPrev = y; } - break; + } + else if (style == 'c') + { + // Theseus: a half circle of the waveform, mirrored left and right. + const int xMid = w / 2; + const int yMid = h / 2; + const float dx = 1.0f / (float)w; + float xPrev = 0.0f; + float yPrev = 0.0f; + int iFrame = 0; - case 1: // Spinner Scope + for (float t = 0.0f; t <= 1.0f; t += dx, iFrame++) { - int xCenter = pSurfx->m_nWidth / 2; - int yCenter = pSurfx->m_nHeight / 2; - float step = 1.0f / (float)pSurfx->m_nWidth; - float firstX = 0, firstY = 0; - float prevX = 0, prevY = 0; - - float B0 = cosf(t * 0.2f); - float B1 = sinf(t * 0.2f); + float r = (float)pcm[iFrame < 256 ? iFrame : 255] / 32767.0f * m_scale + m_offset; // past 256 columns, hold the last frame + float angle = t * 3.14159265f; + float x = r * sinf(angle); + float y = r * cosf(angle); - for (float s = 0.0f; s <= 1.0f; s += step) + if (iFrame > 0) { - float C0 = viz_mag(s) * m_scale + m_offset; - float C1 = 2.1f * (s - 0.5f); - - float X0 = B0 * C1 + B1 * C0; - float Y0 = -B0 * C0 + B1 * C1; - - if (s == 0.0f) - { - firstX = X0; - firstY = Y0; - } - else - { - pSurfx->Line(xCenter + (int)(prevX * xCenter), yCenter + (int)(prevY * yCenter), - xCenter + (int)(X0 * xCenter), yCenter + (int)(Y0 * yCenter), 255); - } - - prevX = X0; - prevY = Y0; + surface->Line(xMid + (int)(xPrev * xMid), yMid + (int)(yPrev * yMid), + xMid + (int)(x * xMid), yMid + (int)(y * yMid), 255); + surface->Line(xMid - (int)(xPrev * xMid), yMid + (int)(yPrev * yMid), + xMid - (int)(x * xMid), yMid + (int)(y * yMid), 255); } + xPrev = x; + yPrev = y; } - break; + } + else if (style == 'a') + { + static int s_peak[256]; + BYTE level[256]; - case 2: // Circle Scope (re-enabled from Xbox #if 0) - { - int xCenter = pSurfx->m_nWidth / 2; - int yCenter = pSurfx->m_nHeight / 2; - float step = 1.0f / (float)pSurfx->m_nWidth; - float prevX2 = 0, prevY2 = 0; - bool first = true; - - int i2 = 0; - for (float s = 0.0f; s <= 1.0f; s += step, i2 += 1) - { - float sample = (float)samples[i2 * 2 + lrc] / 32767.0f; - float C0 = sample * m_scale + m_offset; - float C1 = s * 3.14159265f; // PI + UpdateSpectrum(); - float X0 = C0 * sinf(C1); - float Y0 = C0 * cosf(C1); + // Left spectrum high to low across the first half, right low to high after. + for (int i = 0; i < 128; i++) + level[i] = VizLevel(logf((float)(m_fftLeft[127 - i] + 1)) * 8.0f); + for (int i = 128; i < 256; i++) + level[i] = VizLevel(logf((float)(m_fftRight[i - 128] + 1)) * 8.0f); - if (!first) - { - pSurfx->Line(xCenter + (int)(prevX2 * xCenter), yCenter + (int)(prevY2 * yCenter), - xCenter + (int)(X0 * xCenter), yCenter + (int)(Y0 * yCenter), 255); - pSurfx->Line(xCenter - (int)(prevX2 * xCenter), yCenter + (int)(prevY2 * yCenter), - xCenter - (int)(X0 * xCenter), yCenter + (int)(Y0 * yCenter), 255); - } - first = false; - prevX2 = X0; - prevY2 = Y0; - } + for (int i = 0; i < 256; i++) + { + s_peak[i] = (s_peak[i] > 2) ? s_peak[i] - 2 : 0; + if (s_peak[i] < level[i] * 2) + s_peak[i] = level[i] * 2; } - break; - case 3: // Spectrum Analyzer + for (int x = 0; x < w; x++) { - UpdateSpectrum(); - - static int peak_buf[256]; - BYTE spectrum[256]; - - int i; - for (i = 0; i < 128; i += 1) - { - float n = logf((float)(m_fftLeft[127 - i] + 1)) * 8.0f; - if (n <= 0.0f) - spectrum[i] = 0; - else if (n >= 255.0f) - spectrum[i] = 255; - else - spectrum[i] = (BYTE)n; - } - - for (; i < 256; i += 1) - { - float n = logf((float)(m_fftRight[i - 128] + 1)) * 8.0f; - if (n <= 0.0f) - spectrum[i] = 0; - else if (n >= 255.0f) - spectrum[i] = 255; - else - spectrum[i] = (BYTE)n; - } - - for (i = 0; i < 256; i += 1) - { - if (peak_buf[i] > 2) - peak_buf[i] -= 2; - else - peak_buf[i] = 0; - - int y = spectrum[i] * 2; - if (peak_buf[i] < y) - peak_buf[i] = y; - } + int iBand = (x * 256) / w; + + float bar = ((float)level[iBand] * (float)h) / 256.0f; + if ((int)bar > h) + bar = (float)h; + BYTE shade = 255; + for (int y = h - (int)bar; y < h; y++) + *surface->Pixel(x, y) = shade--; + + float peak = (float)s_peak[iBand] / 2.0f; + peak = (peak * (float)h) / 256.0f; + VizPlot(surface, x, h - (int)peak, 255); + } - int nWidth = pSurfx->m_nWidth; - for (int x = 0; x < nWidth; x += 1) - { - float nHeight = ((float)spectrum[(x * 256) / nWidth] * (float)pSurfx->m_nHeight) / 256.0f; - if ((int)nHeight > pSurfx->m_nHeight) nHeight = (float)pSurfx->m_nHeight; - - BYTE bColor = 255; - for (int y = pSurfx->m_nHeight - (int)nHeight; y < pSurfx->m_nHeight; y += 1, bColor -= 1) - *pSurfx->Pixel(x, y) = bColor; - - nHeight = (float)peak_buf[(x * 256) / nWidth]; - nHeight /= 2.0f; - nHeight = (nHeight * (float)pSurfx->m_nHeight) / 256.0f; - int peakY = pSurfx->m_nHeight - (int)nHeight; - if (peakY >= 0 && peakY < pSurfx->m_nHeight) - *pSurfx->Pixel(x, peakY) = 255; - } + RenderEffect1(surface); + RenderEffect2(surface); + } + else + { + const int xMid = w / 2; + int xPrev = xMid; + int yPrev = 0; - RenderEffect1(pSurfx); - RenderEffect2(pSurfx); + for (int y = 0; y < nFrames; y++) + { + int x = xMid + (int)(((long)pcm[y] * w) >> 16); + surface->Line(xPrev, yPrev, x, y, 255); + xPrev = x; + yPrev = y; } - break; } } -// Beat detection overlay -#define BASS_EXT_MEMORY 10 - -static struct { - int max_recent; - int max_old; - int time_last_max; - int min_recent; - int min_old; - int time_last_min; - int activated; -} s_bass_info = {}; - -void CAudioVisualizer::RenderEffect1(CSurfx* pSurfx) +// Bass tracker for the flash. Field order follows the 5960 globals at +// 0x17e6f4..0x17e70c; the frame counter is 0x188f50. +static struct +{ + int hiNow, hiPrev, hiFrame; + int loNow, loPrev, loFrame; + bool lit; +} s_bass; + +// CAudioVisualizer::RenderEffect1(surface) +// Reconstructed from 5960 retail XBE @ 0x00063ef0. Decompile: +// bass = sum(fftRight[0..4] >> 4) + sum(fftLeft[0..4] >> 4)) / 10; +// track the max and min, rolling each over every 10 frames; +// if (bass > (maxOld*6 + minOld*4)/10 && !lit) { fill surface 0xff; lit = 1; } +// frame++; if (bass < (maxOld*4 + minOld*6)/10 && lit) lit = 0; +// A beat flashes the whole surface white once, then waits for the bass to drop. +void CAudioVisualizer::RenderEffect1(CSurfx* surface) { - static int t = 0; + static int s_frame = 0; int bass = 0; - const int step = 5; - for (int i = 0; i < step; i += 1) + for (int i = 0; i < 5; i++) bass += (m_fftLeft[i] >> 4) + (m_fftRight[i] >> 4); - bass /= (step * 2); - - if (bass > s_bass_info.max_recent) - s_bass_info.max_recent = bass; + bass /= 10; - if (bass < s_bass_info.min_recent) - s_bass_info.min_recent = bass; + if (bass > s_bass.hiNow) + s_bass.hiNow = bass; + if (bass < s_bass.loNow) + s_bass.loNow = bass; - if (t - s_bass_info.time_last_max > BASS_EXT_MEMORY) + if (s_frame - s_bass.hiFrame > 10) { - s_bass_info.max_old = s_bass_info.max_recent; - s_bass_info.max_recent = 0; - s_bass_info.time_last_max = t; + s_bass.hiPrev = s_bass.hiNow; + s_bass.hiNow = 0; + s_bass.hiFrame = s_frame; } - - if (t - s_bass_info.time_last_min > BASS_EXT_MEMORY) + if (s_frame - s_bass.loFrame > 10) { - s_bass_info.min_old = s_bass_info.min_recent; - s_bass_info.min_recent = 0; - s_bass_info.time_last_min = t; + s_bass.loPrev = s_bass.loNow; + s_bass.loNow = 0; + s_bass.loFrame = s_frame; } - if (bass > (s_bass_info.max_old * 6 + s_bass_info.min_old * 4) / 10 && s_bass_info.activated == 0) + int on = (s_bass.hiPrev * 6 + s_bass.loPrev * 4) / 10; + int off = (s_bass.hiPrev * 4 + s_bass.loPrev * 6) / 10; + + if (!s_bass.lit && bass > on) { - FillMemory(pSurfx->m_pels, pSurfx->m_nWidth * pSurfx->m_nHeight, 255); - s_bass_info.activated = 1; + memset(surface->m_pels, 0xff, surface->m_nWidth * surface->m_nHeight); + s_bass.lit = true; } - - if (bass < (s_bass_info.max_old * 4 + s_bass_info.min_old * 6) / 10 && s_bass_info.activated == 1) - s_bass_info.activated = 0; - - t += 1; + s_frame++; + if (s_bass.lit && bass < off) + s_bass.lit = false; } -// Waveform curve overlay effects -static struct { int i; float *f; } s_cosw = { 0, NULL }; -static struct { int i; float *f; } s_sinw = { 0, NULL }; - -static int s_spectral_amplitude = 50; -static int s_spectral_shift = 30; -static int s_mode_spectre = -1; -static BYTE s_spectral_color = 128; - -void CAudioVisualizer::RenderEffect2(CSurfx* pSurfx) +// CAudioVisualizer::RenderEffect2(surface) +// Reconstructed from 5960 retail XBE @ 0x00064130 (1761 bytes). Every 3 to +// 8 seconds the style steps through five (0..4, starting from -1). Each +// style draws the two channels' waveforms (high byte of every fifth frame, +// scaled by 50 * h >> 12) in color 128 every 4 pixels: 0 one line, 1 two +// lines apart, 2 four (two across, two down), 3 and 4 bent round a half +// circle from cos/sin tables of w entries (3 keeps them outside). 3 and 4 +// close the circle with one more line. After that two 64 dot curves (2x2, +// color 255) trace a slowly turning figure eight from a running counter. +// Constants from 0x2c124..0x2c160 and 0x176034..0x176040. Theseus picks the +// next change with rnd() and draws the curves at amplitude 50 / 256. +static int s_waveStyle = -1; +static int s_waveTableW = 0; +static float* s_waveCos = NULL; +static float* s_waveSin = NULL; + +void CAudioVisualizer::RenderEffect2(CSurfx* surface) { - int halfheight, halfwidth; - float old_y1, old_y2; - float y1 = (float)((((m_pcmLeft[0] + m_pcmRight[0]) >> 9) * s_spectral_amplitude * pSurfx->m_nHeight) >> 12); - float y2 = (float)((((m_pcmLeft[0] + m_pcmRight[0]) >> 9) * s_spectral_amplitude * pSurfx->m_nHeight) >> 12); - const int density_lines = 5; - const int step = 4; - const int shift = (s_spectral_shift * pSurfx->m_nHeight) >> 8; + const int w = surface->m_nWidth; + const int h = surface->m_nHeight; + const int amp = 50; + const int gap = (30 * h) >> 8; + const BYTE color = 128; + const int dx = 4; - static XTIME timeToChange = 0.0f; - if (s_mode_spectre < 0 || TheseusGetNow() >= timeToChange) + static XTIME s_nextStyle = 0.0f; + if (s_waveStyle < 0 || TheseusGetNow() >= s_nextStyle) { - s_mode_spectre += 1; - timeToChange = TheseusGetNow() + 3.0f + rnd(5.0f); + s_waveStyle++; + s_nextStyle = TheseusGetNow() + 3.0f + rnd(5.0f); } + if ((UINT)s_waveStyle > 4) + s_waveStyle = 0; - if ((UINT)s_mode_spectre > 4) - s_mode_spectre = 0; - - if (s_cosw.i != pSurfx->m_nWidth || s_sinw.i != pSurfx->m_nWidth) + // Tables are rebuilt when the surface width changes; only every 4th entry is used. + if (s_waveTableW != w || s_waveCos == NULL || s_waveSin == NULL) { - delete [] s_cosw.f; - delete [] s_sinw.f; - s_sinw.f = s_cosw.f = NULL; - s_sinw.i = s_cosw.i = 0; + delete [] s_waveCos; + delete [] s_waveSin; + s_waveTableW = w; + s_waveCos = new float[w]; + s_waveSin = new float[w]; + for (int i = 0; i < w; i += dx) + s_waveCos[i] = cosf((float)i / w * 3.14159265f + 3.14159265f / 2.0f); + for (int i = 0; i < w; i += dx) + s_waveSin[i] = sinf((float)i / w * 3.14159265f + 3.14159265f / 2.0f); } - const float halfPI = 3.14159265f / 2.0f; - const float fullPI = 3.14159265f; - - if (s_cosw.i == 0 || s_cosw.f == NULL) + float yA = (float)((((m_pcmLeft[0] + m_pcmRight[0]) >> 9) * amp * h) >> 12); + float yB = yA; + if (s_waveStyle == 3 && yA < 0) { - s_cosw.i = pSurfx->m_nWidth; - s_cosw.f = new float[pSurfx->m_nWidth]; - for (int i = 0; i < pSurfx->m_nWidth; i += step) - s_cosw.f[i] = cosf((float)i / pSurfx->m_nWidth * fullPI + halfPI); + yA = 0; + yB = 0; } - if (s_sinw.i == 0 || s_sinw.f == NULL) - { - s_sinw.i = pSurfx->m_nWidth; - s_sinw.f = new float[pSurfx->m_nWidth]; - for (int i = 0; i < pSurfx->m_nWidth; i += step) - s_sinw.f[i] = sinf((float)i / pSurfx->m_nWidth * fullPI + halfPI); - } + const int hh = h >> 1; + const int hw = w >> 1; - if (s_mode_spectre == 3) + for (int i = dx; i < w; i += dx) { - if (y1 < 0) y1 = 0; - if (y2 < 0) y2 = 0; - } - - halfheight = pSurfx->m_nHeight >> 1; - halfwidth = pSurfx->m_nWidth >> 1; + float yAPrev = yA; + float yBPrev = yB; + int iFrame = (i << 8) / w / 5; + yA = (float)(((m_pcmRight[iFrame] >> 8) * amp * h) >> 12); + yB = (float)(((m_pcmLeft[iFrame] >> 8) * amp * h) >> 12); - for (int i = step; i < pSurfx->m_nWidth; i += step) - { - old_y1 = y1; - old_y2 = y2; - - y1 = (float)(((m_pcmRight[(i << 8) / pSurfx->m_nWidth / density_lines] >> 8) * s_spectral_amplitude * pSurfx->m_nHeight) >> 12); - y2 = (float)(((m_pcmLeft[(i << 8) / pSurfx->m_nWidth / density_lines] >> 8) * s_spectral_amplitude * pSurfx->m_nHeight) >> 12); - - switch (s_mode_spectre) + switch (s_waveStyle) { case 0: - pSurfx->Line(i-step,(int)(halfheight+shift+old_y2), - i,(int)(halfheight+shift+y2), s_spectral_color); + surface->Line(i - dx, (int)(hh + gap + yBPrev), i, (int)(hh + gap + yB), color); break; case 1: - pSurfx->Line(i-step,(int)(halfheight+shift+old_y1), - i,(int)(halfheight+shift+y1), s_spectral_color); - pSurfx->Line(i-step,(int)(halfheight-shift+old_y2), - i,(int)(halfheight-shift+y2), s_spectral_color); + surface->Line(i - dx, (int)(hh + gap + yAPrev), i, (int)(hh + gap + yA), color); + surface->Line(i - dx, (int)(hh - gap + yBPrev), i, (int)(hh - gap + yB), color); break; case 2: - pSurfx->Line(i-step,(int)(halfheight+shift+old_y1), - i,(int)(halfheight+shift+y1), s_spectral_color); - pSurfx->Line(i-step,(int)(halfheight-shift+old_y1), - i,(int)(halfheight-shift+y1), s_spectral_color); - pSurfx->Line((int)(halfwidth+shift+old_y2),i-step, - (int)(halfwidth+shift+y2),i, s_spectral_color); - pSurfx->Line((int)(halfwidth-shift+old_y2),i-step, - (int)(halfwidth-shift+y2),i, s_spectral_color); + surface->Line(i - dx, (int)(hh + gap + yAPrev), i, (int)(hh + gap + yA), color); + surface->Line(i - dx, (int)(hh - gap + yAPrev), i, (int)(hh - gap + yA), color); + surface->Line((int)(hw + gap + yBPrev), i - dx, (int)(hw + gap + yB), i, color); + surface->Line((int)(hw - gap + yBPrev), i - dx, (int)(hw - gap + yB), i, color); break; case 3: - if (y1 < 0) y1 = 0; - if (y2 < 0) y2 = 0; - // FALL THROUGH - + if (yA < 0) + yA = 0; + if (yB < 0) + yB = 0; + // fall through case 4: - pSurfx->Line( - (int)(halfwidth + s_cosw.f[i - step] * (shift + old_y1)), - (int)(halfheight + s_sinw.f[i - step] * (shift + old_y1)), - (int)(halfwidth + s_cosw.f[i] * (shift + y1)), - (int)(halfheight + s_sinw.f[i] * (shift + y1)), - s_spectral_color); - pSurfx->Line( - (int)(halfwidth - s_cosw.f[i - step] * (shift + old_y2)), - (int)(halfheight + s_sinw.f[i - step] * (shift + old_y2)), - (int)(halfwidth - s_cosw.f[i] * (shift + y2)), - (int)(halfheight + s_sinw.f[i] * (shift + y2)), - s_spectral_color); + surface->Line((int)(hw + s_waveCos[i - dx] * (gap + yAPrev)), (int)(hh + s_waveSin[i - dx] * (gap + yAPrev)), + (int)(hw + s_waveCos[i] * (gap + yA)), (int)(hh + s_waveSin[i] * (gap + yA)), color); + surface->Line((int)(hw - s_waveCos[i - dx] * (gap + yBPrev)), (int)(hh + s_waveSin[i - dx] * (gap + yBPrev)), + (int)(hw - s_waveCos[i] * (gap + yB)), (int)(hh + s_waveSin[i] * (gap + yB)), color); break; } } - if (s_mode_spectre == 3 || s_mode_spectre == 4) + if (s_waveStyle == 3 || s_waveStyle == 4) { - pSurfx->Line( - (int)(halfwidth + s_cosw.f[pSurfx->m_nWidth - step] * (shift+y1)), - (int)(halfheight + s_sinw.f[pSurfx->m_nWidth - step] * (shift+y1)), - (int)(halfwidth - s_cosw.f[pSurfx->m_nWidth - step] * (shift+y2)), - (int)(halfheight + s_sinw.f[pSurfx->m_nWidth - step] * (shift+y2)), - s_spectral_color); + int iLast = w - dx; + surface->Line((int)(hw + s_waveCos[iLast] * (gap + yA)), (int)(hh + s_waveSin[iLast] * (gap + yA)), + (int)(hw - s_waveCos[iLast] * (gap + yB)), (int)(hh + s_waveSin[iLast] * (gap + yB)), color); } -#define VIZ_CURVE_COLOR 255 -#define VIZ_CURVE_AMPLITUDE 50 - static int x_curve = 0; + static int s_curveTick = 0; + const float size = 50.0f / 256; + int tick = s_curveTick; - // Curve overlay + for (int j = 0; j < 2; j++) { - int i, j, k; - float v, vr; - float x, y; - float amplitude = (float)VIZ_CURVE_AMPLITUDE / 256; - - for (j = 0; j < 2; j += 1) + const float v = 80.0f; + tick = s_curveTick; + for (int n = 0; n < 64; n++, tick++) { - v = 80; - vr = 0.001f; - k = x_curve; - for (i = 0; i < 64; i += 1) - { - x = cosf((float)(k) / (v + v * j * 1.34f)) * pSurfx->m_nHeight * amplitude; - y = sinf((float)(k) / (1.756f * (v + v * j * 0.93f))) * pSurfx->m_nHeight * amplitude; - VizSetPixel2(pSurfx, - (int)(x * cosf((float)k * vr) + y * sinf((float)k * vr) + pSurfx->m_nWidth / 2), - (int)(x * sinf((float)k * vr) - y * cosf((float)k * vr) + pSurfx->m_nHeight / 2), - VIZ_CURVE_COLOR); - k++; - } + float cx = cosf((float)tick / (v + v * j * 1.34f)) * h * size; + float cy = sinf((float)tick / (1.756f * (v + v * j * 0.93f))) * h * size; + float spin = (float)tick * 0.001f; + VizPlot2x2(surface, + (int)(cx * cosf(spin) + cy * sinf(spin) + w / 2), + (int)(cx * sinf(spin) - cy * cosf(spin) + h / 2), + 255); } - - x_curve = k; } + s_curveTick = tick; } // ============================================================================ @@ -1954,28 +1901,50 @@ static void LoadDesktopIcons() } } +// The Memory blade's list on the desktop. Titles and saves come from the +// desktop's UDATA scan (or an xemu image) instead of the console's device +// enumeration; there's one device, no copies and no deletes. The layout, +// scrolling and selection are rebuilt from the 5960 grid (vtable 0x000267b0, +// 0x47e50..0x49840), see docs/decomp/SavedGameGrid.md. class CSavedGameGrid : public CNode { public: - CSavedGameGrid() : m_pod(NULL), m_podRing(NULL), m_podXboxLiveAccountsPanel(NULL), - m_XboxLiveAccountsIconPanel(NULL), m_iconBumpRing(NULL), m_iconArrow(NULL), - m_iconCheck(NULL), m_curGridItem(-1), m_podSavePanel(NULL), m_podSoundtrackPanel(NULL), - m_podHilite(NULL), m_MUheader(NULL), m_MUhiliteHeader(NULL), m_firstMURow(NULL), - m_header(NULL), m_hiliteHeader(NULL), m_firstRow(NULL), m_secondRow(NULL), - m_otherRow(NULL), m_renderIcons(false), m_iconsPerRow(4), - m_scroll(0.0f), m_curTitle(-1), m_curSavedGame(-1), m_smallIcon(NULL), m_SavedIconPanel(NULL), - m_SoundtrackIconPanel(NULL), m_iconRing(NULL), m_smallIconHilite(NULL), - m_smallIconSpacing(0.0f), m_iconRowScroll(0), m_moreUp(NULL), m_moreDown(NULL), - m_detachIcon(false), m_isActive(false), m_curDevUnit(-1), - m_copyProgress(0.0f), m_freeBlocks(0), m_gameBlocks(0), m_nPrefColumn(0), - m_deleteUserContent(false), m_enumDone(false), - m_nScrollTo(0.0f), m_timeScroll(0.0f) {} + CSavedGameGrid() + { + m_pod = m_podRing = m_podXboxLiveAccountsPanel = m_XboxLiveAccountsIconPanel = NULL; + m_iconBumpRing = m_iconArrow = m_iconCheck = NULL; + m_podSavePanel = m_podSoundtrackPanel = m_podHilite = NULL; + m_MUheader = m_MUhiliteHeader = m_firstMURow = NULL; + m_header = m_hiliteHeader = m_firstRow = m_secondRow = m_otherRow = NULL; + m_smallIcon = m_SavedIconPanel = m_SoundtrackIconPanel = NULL; + m_iconRing = m_smallIconHilite = m_moreUp = m_moreDown = NULL; + + m_curTitle = -1; + m_curGridItem = -1; + m_curSavedGame = -1; + m_curDevUnit = -1; + m_iconsPerRow = 4; + m_renderIcons = false; + m_scroll = 0.0f; + m_smallIconSpacing = 0.0f; + m_iconRowScroll = 0; + m_detachIcon = false; + m_isActive = false; + m_copyProgress = 0.0f; + m_freeBlocks = 0; + m_gameBlocks = 0; + m_nPrefColumn = 0; + m_deleteUserContent = false; + m_enumDone = false; + m_nScrollTo = 0.0f; + m_timeScroll = 0.0f; + } DECLARE_NODE(CSavedGameGrid, CNode) DECLARE_NODE_PROPS() DECLARE_NODE_FUNCTIONS() - // Properties + // Scene pieces the XAP hands over. CNode* m_pod; CNode* m_podRing; CNode* m_podXboxLiveAccountsPanel; @@ -1999,7 +1968,7 @@ class CSavedGameGrid : public CNode int m_iconsPerRow; float m_scroll; int m_curTitle; - int m_curSavedGame; // Alpha compat: save index within a title + int m_curSavedGame; // Theseus: alpha dash scripts read this CNode* m_smallIcon; CNode* m_SavedIconPanel; CNode* m_SoundtrackIconPanel; @@ -2018,15 +1987,24 @@ class CSavedGameGrid : public CNode int m_nPrefColumn; bool m_deleteUserContent; bool m_enumDone; - float m_nScrollTo; - float m_timeScroll; - + float m_nScrollTo; // 5960 +0xd4 + float m_timeScroll; // 5960 keeps a double at +0xd8; this one is a float + + // CSavedGameGrid::Advance(dt) + // From 5960 @ 0x00047e50: nothing without a device or while hidden; the + // title list is refreshed (OnUpdatingTitlesBegin / End around it); and a + // running scroll eases toward its target over a quarter second, + // scroll = (1 - t) * scroll + t * target. The desktop lists once, on the + // calling thread, and sums the game blocks itself; 5960's copy, delete, + // device and free space upkeep has no desktop counterpart. void Advance(float dt) { CNode::Advance(dt); if (m_curDevUnit == -1 || !m_isActive) return; - if (!m_enumDone) { + + if (!m_enumDone) + { m_enumDone = true; CallFunction(this, _T("OnUpdatingTitlesBegin")); EnumerateTitles(); @@ -2036,19 +2014,23 @@ class CSavedGameGrid : public CNode m_gameBlocks += (int)((s_titles[i].totalSizeBytes + XBOX_BLOCK_SIZE - 1) / XBOX_BLOCK_SIZE); CallFunction(this, _T("OnUpdatingTitlesEnd")); } - // Smooth scroll animation (from Xbox Advance) - if (m_timeScroll != 0.0f) { - float t = (float)(TheseusGetNow() - m_timeScroll) / 0.25f; - if (t >= 1.0f) { m_timeScroll = 0.0f; t = 1.0f; } - m_scroll = (1.0f - t) * m_scroll + t * m_nScrollTo; + + if (m_timeScroll == 0.0f) + return; + float t = (float)(TheseusGetNow() - m_timeScroll) / 0.25f; + if (t >= 1.0f) + { + t = 1.0f; + m_timeScroll = 0.0f; } + m_scroll = (1.0f - t) * m_scroll + t * m_nScrollTo; } - // --- Rendering (adapted from Xbox CSavedGameGrid::Render/RenderLoop/RenderIconRow) --- - + // Draws pNode under the current world transform times pMatrix. static void RenderNodeAt(CNode* pNode, D3DXMATRIX* pMatrix) { - if (!pNode) return; + if (pNode == NULL) + return; TheseusPushWorld(); TheseusMultWorld(pMatrix); TheseusUpdateWorld(); @@ -2056,232 +2038,283 @@ class CSavedGameGrid : public CNode TheseusPopWorld(); } - void RenderIconRow(D3DXMATRIX* pBaseMat, float y, int nTitle, int nFirstSave, int nTotalSaves) + // CSavedGameGrid::RenderIconRow(frame, y, title, first, count) + // From 5960 @ 0x00048690: up to iconsPerRow icons starting at item first, + // smallIconSpacing apart, each through SavedIconPanel with its image set + // for the texture lookup, and the ring on the selected one unless its + // icon is lifted out. The desktop takes a save's own SaveImage.xbx when + // the folder has one, else the title's, and rings with iconRing present + // (5960 checks smallIconHilite). + void RenderIconRow(D3DXMATRIX* pFrame, float y, int nTitle, int nFirst, int nCount) { - if (!m_smallIcon || nTitle < 0 || nTitle >= s_titleCount) return; - int nLim = nFirstSave + m_iconsPerRow; - if (nLim > nTotalSaves) nLim = nTotalSaves; + if (m_smallIcon == NULL || nTitle < 0 || nTitle >= s_titleCount) + return; + + int nEnd = nFirst + m_iconsPerRow; + if (nEnd > nCount) + nEnd = nCount; + + DesktopTitle& title = s_titles[nTitle]; float x = 0.0f; - for (int i = nFirstSave; i < nLim; i++) { - D3DXMATRIX mat2; - D3DXMatrixTranslation(&mat2, x, y, 0.0f); - D3DXMatrixMultiply(&mat2, pBaseMat, &mat2); - // Set title image for icon texture lookup - // Try save-specific image first, fall back to title-level SaveImage.xbx - static char szImgBuf[512]; - DesktopTitle& t = s_titles[nTitle]; - if (i < t.saveCount) { - snprintf(szImgBuf, sizeof(szImgBuf), "E:\\UDATA\\%s\\%s\\SaveImage.xbx", - t.titleID, t.saves[i].folderName); - // Check if save-specific image exists, fall back to title root - char hostPath[512]; - snprintf(hostPath, sizeof(hostPath), "%s/UDATA/%s/%s/SaveImage.xbx", AppPath_Tree("Library"), - t.titleID, t.saves[i].folderName); - struct stat _st; - if (stat(hostPath, &_st) != 0) { - snprintf(szImgBuf, sizeof(szImgBuf), "E:\\UDATA\\%s\\SaveImage.xbx", t.titleID); - } - } else { - strcpy(szImgBuf, "xboxlogo64.xbx"); + for (int item = nFirst; item < nEnd; item++, x += m_smallIconSpacing) + { + D3DXMATRIX at; + D3DXMatrixTranslation(&at, x, y, 0.0f); + D3DXMatrixMultiply(&at, pFrame, &at); + + static char s_szImage[512]; + if (item >= title.saveCount) + { + strcpy(s_szImage, "xboxlogo64.xbx"); + } + else + { + char szHost[512]; + snprintf(szHost, sizeof (szHost), "%s/UDATA/%s/%s/SaveImage.xbx", AppPath_Tree("Library"), + title.titleID, title.saves[item].folderName); + struct stat st; + if (stat(szHost, &st) == 0) + snprintf(s_szImage, sizeof (s_szImage), "E:\\UDATA\\%s\\%s\\SaveImage.xbx", title.titleID, title.saves[item].folderName); + else + snprintf(s_szImage, sizeof (s_szImage), "E:\\UDATA\\%s\\SaveImage.xbx", title.titleID); } - g_szCurTitleImage = szImgBuf; - RenderNodeAt(m_SavedIconPanel, &mat2); + + g_szCurTitleImage = s_szImage; + RenderNodeAt(m_SavedIconPanel, &at); g_szCurTitleImage = NULL; - // Highlight ring on selected icon - if (!m_detachIcon && m_iconRing && nTitle == m_curTitle && i == m_curGridItem) - RenderNodeAt(m_iconRing, &mat2); - x += m_smallIconSpacing; + + if (!m_detachIcon && m_iconRing != NULL && nTitle == m_curTitle && item == m_curGridItem) + RenderNodeAt(m_iconRing, &at); } } - // RenderLoop: bRender=true draws, bRender=false returns Y offset of curTitle + // Places pNode at (x, y, z) in the grid's frame. + static void RenderInFrame(CNode* pNode, D3DXMATRIX* pFrame, float x, float y, float z) + { + D3DXMATRIX at; + D3DXMatrixTranslation(&at, x, y, z); + D3DXMatrixMultiply(&at, pFrame, &at); + RenderNodeAt(pNode, &at); + } + + // CSavedGameGrid::RenderLoop(render) + // From 5960 @ 0x00048910. The frame is a -1.571 turn about -x times a + // 0.05942 scale. From y = scroll each title draws its pod (with the save + // panel, and podRing when it's selected with no item), its header (the + // highlighted one when selected) and name, then y -= 0.0092, the first + // icon row at x -0.3292 (y -= 0.2455), the second at -0.3301 and one more + // at -0.3412 (y -= 0.24499 each), and y -= 0.09 before the next title. + // Rows only draw while y - 0.25 < 0.5, and the loop stops below -1.25. + // Unselected titles draw at half strength. With render off it returns + // the selected title's offset from the top. The desktop has no device + // row, arrows or soundtrack row, swaps the selection ease for a straight + // half, draws the name with the stock text node and takes the pod image + // from its own title scan. float RenderLoop(bool bRender) { - D3DXMATRIX mat, mat2; - D3DXVECTOR3 v(-1.0f, 0.0f, 0.0f); - D3DXMatrixRotationAxis(&mat, &v, -1.571f); - D3DXMatrixScaling(&mat2, 0.05942f, 0.05942f, 0.05942f); - D3DXMatrixMultiply(&mat, &mat, &mat2); + const float xPod = -0.3292f, zPod = -0.0271f, zRow = 0.01144f; + const float scale = 0.05942f; + + D3DXMATRIX frame, scaleMat; + D3DXVECTOR3 axis(-1.0f, 0.0f, 0.0f); + D3DXMatrixRotationAxis(&frame, &axis, -1.571f); + D3DXMatrixScaling(&scaleMat, scale, scale, scale); + D3DXMatrixMultiply(&frame, &frame, &scaleMat); + const float yLimit = -1.25f; float y = m_scroll; - float yLimit = -1.25f; - int nTitleCount = s_titleCount; - - for (int nTitle = 0; nTitle < nTitleCount && (!bRender || y > yLimit); nTitle++) { - float nEffectAlphaSave = g_nEffectAlpha; - int nSaves = (nTitle >= 0 && nTitle < s_titleCount) ? s_titles[nTitle].saveCount : 0; - int nRowCount = (nSaves + m_iconsPerRow - 1) / m_iconsPerRow; - int nIconRowScroll = (nTitle == m_curTitle) ? m_iconRowScroll : 0; - if (nTitle < m_curTitle) { - nIconRowScroll = nRowCount - 3; - if (nIconRowScroll < 0) nIconRowScroll = 0; - } - if (bRender) { - // Dim non-selected titles - float sel = (nTitle == m_curTitle) ? 1.0f : 0.0f; - g_nEffectAlpha *= 0.5f + 0.5f * sel; - } else if (nTitle == m_curTitle) { - return y - m_scroll; + for (int nTitle = 0; nTitle < s_titleCount && (!bRender || y > yLimit); nTitle++) + { + const bool bSelected = (nTitle == m_curTitle); + const float alphaSave = g_nEffectAlpha; + + const int nSaves = s_titles[nTitle].saveCount; + const int nRows = (nSaves + m_iconsPerRow - 1) / m_iconsPerRow; + int nRowScroll = 0; + if (bSelected) + nRowScroll = m_iconRowScroll; + else if (nTitle < m_curTitle) + nRowScroll = (nRows - 3 > 0) ? nRows - 3 : 0; // titles above show their last rows + + if (!bRender) + { + if (bSelected) + return y - m_scroll; + } + else + { + g_nEffectAlpha *= bSelected ? 1.0f : 0.5f; } - // Render title pod - if (bRender && y - 0.25f < 0.5f && m_pod) { - static char szPodImg[512]; - if (nTitle >= 0 && nTitle < s_titleCount && s_titles[nTitle].hasImage) { - // imagePath is already host-relative (set in - // ProcessTitleEntry). either Library/UDATA/.../TitleImage.xbx - // for real Xbox saves or Configs/icons/.{jpg,png} - // for synthesized title pods. Pass it through directly - // instead of rebuilding an Xbox-style path that only - // resolves for the .xbx case. - strncpy(szPodImg, s_titles[nTitle].imagePath, sizeof(szPodImg) - 1); - szPodImg[sizeof(szPodImg) - 1] = 0; - } else { - strcpy(szPodImg, "xboxlogo128.xbx"); + const bool bVisible = bRender && y - 0.25f < 0.5f; + + if (bVisible && m_pod != NULL) + { + static char s_szPodImage[512]; + if (s_titles[nTitle].hasImage) + { + // Already host relative: the title's TitleImage.xbx or a Configs/icons picture. + strncpy(s_szPodImage, s_titles[nTitle].imagePath, sizeof (s_szPodImage) - 1); + s_szPodImage[sizeof (s_szPodImage) - 1] = 0; } - g_szCurTitleImage = szPodImg; - D3DXMatrixTranslation(&mat2, -0.3292f, y, -0.0271f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_pod, &mat2); - if (m_podSavePanel) RenderNodeAt(m_podSavePanel, &mat2); - if (nTitle == m_curTitle && m_curGridItem == -1 && m_podHilite) - RenderNodeAt(m_podRing, &mat2); + else + { + strcpy(s_szPodImage, "xboxlogo128.xbx"); + } + + g_szCurTitleImage = s_szPodImage; + D3DXMATRIX at; + D3DXMatrixTranslation(&at, xPod, y, zPod); + D3DXMatrixMultiply(&at, &frame, &at); + RenderNodeAt(m_pod, &at); + if (m_podSavePanel != NULL) + RenderNodeAt(m_podSavePanel, &at); + if (bSelected && m_curGridItem == -1 && m_podHilite != NULL) + RenderNodeAt(m_podRing, &at); g_szCurTitleImage = NULL; } - // Render header - if (bRender && y - 0.25f < 0.5f) { - D3DXMatrixTranslation(&mat2, -0.3292f, y, -0.0271f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - if (nTitle == m_curTitle) - RenderNodeAt(m_hiliteHeader, &mat2); - else - RenderNodeAt(m_header, &mat2); - // Draw title name text - if (m_renderIcons && nTitle >= 0 && nTitle < s_titleCount) { - D3DXMATRIX mat3; - D3DXMatrixScaling(&mat3, 0.06442f, 0.06442f, 0.06442f); - D3DXMatrixTranslation(&mat2, -0.3292f - 0.05942f, y + 0.05942f, -0.0271f + (0.6f * 0.05942f)); - D3DXMatrixMultiply(&mat2, &mat3, &mat2); + if (bVisible) + { + RenderInFrame(bSelected ? m_hiliteHeader : m_header, &frame, xPod, y, zPod); + + if (m_renderIcons) + { extern CNode* GetTextNode(const char* szText, float nWidth); - RenderNodeAt(GetTextNode(s_titles[nTitle].titleName, -11.2f), &mat2); + D3DXMATRIX nameScale, at; + D3DXMatrixScaling(&nameScale, 0.06442f, 0.06442f, 0.06442f); + D3DXMatrixTranslation(&at, xPod - scale, y + scale, zPod + (0.6f * scale)); + D3DXMatrixMultiply(&at, &nameScale, &at); + RenderNodeAt(GetTextNode(s_titles[nTitle].titleName, -11.2f), &at); } } y -= 0.0092f; - // Render first icon row - if (bRender && y - 0.25f < 0.5f) { - D3DXMatrixTranslation(&mat2, -0.3292f, y, 0.01144f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_firstRow, &mat2); - RenderIconRow(&mat, y, nTitle, nIconRowScroll * m_iconsPerRow, nSaves); + if (bRender && y - 0.25f < 0.5f) + { + RenderInFrame(m_firstRow, &frame, xPod, y, zRow); + RenderIconRow(&frame, y, nTitle, nRowScroll * m_iconsPerRow, nSaves); } y -= 0.2455f; - // Second row - if (nSaves > m_iconsPerRow) { - if (bRender && y - 0.25f < 0.5f) { - D3DXMatrixTranslation(&mat2, -0.3301f, y, 0.01144f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_secondRow, &mat2); - RenderIconRow(&mat, y, nTitle, (nIconRowScroll + 1) * m_iconsPerRow, nSaves); + if (nSaves > m_iconsPerRow) + { + if (bRender && y - 0.25f < 0.5f) + { + RenderInFrame(m_secondRow, &frame, -0.3301f, y, zRow); + RenderIconRow(&frame, y, nTitle, (nRowScroll + 1) * m_iconsPerRow, nSaves); } y -= 0.24499f; - // Third+ rows - if (nSaves > m_iconsPerRow * 2) { - for (int nRow = 2; nRow < (nRowCount - nIconRowScroll) && nRow < 3 && (!bRender || y > yLimit); nRow++) { - if (bRender && y - 0.25f < 0.5f) { - D3DXMatrixTranslation(&mat2, -0.3412f, y, 0.01144f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_otherRow, &mat2); - RenderIconRow(&mat, y, nTitle, (nIconRowScroll + nRow) * m_iconsPerRow, nSaves); - } - y -= 0.24499f; + + // At most three rows show; the third is the only "other" row. + if (nSaves > m_iconsPerRow * 2 && nRows - nRowScroll > 2 && (!bRender || y > yLimit)) + { + if (bRender && y - 0.25f < 0.5f) + { + RenderInFrame(m_otherRow, &frame, -0.3412f, y, zRow); + RenderIconRow(&frame, y, nTitle, (nRowScroll + 2) * m_iconsPerRow, nSaves); } + y -= 0.24499f; } } + y -= 0.09f; - g_nEffectAlpha = nEffectAlphaSave; + g_nEffectAlpha = alphaSave; } return 0.0f; } + // CSavedGameGrid::Render() + // From 5960 @ 0x000488a0: needs the header and the three row pieces, a + // device and the blade showing, then runs the loop. void Render() { - if (!m_header || !m_firstRow || !m_secondRow || !m_otherRow) return; - if (m_curDevUnit == -1 || !m_isActive) return; + if (m_header == NULL || m_firstRow == NULL || m_secondRow == NULL || m_otherRow == NULL) + return; + if (m_curDevUnit == -1 || !m_isActive) + return; EnumerateTitles(); - if (s_titleCount == 0) return; - RenderLoop(true); + if (s_titleCount > 0) + RenderLoop(true); } - bool OnSetProperty(const PRD* pprd, const void* pvValue) + // CSavedGameGrid::OnSetProperty(prop, value) + // From 5960 @ 0x00048530: a new curDevUnit lists that device and selects + // its first row (none for the memory units), a new curTitle selects it; + // both store the value themselves. Everything else is stored as usual. + bool OnSetProperty(const PRD* prop, const void* value) { - // Match Xbox behavior: only react to specific property changes - if ((intptr_t)pprd->pbOffset == MEMBER_OFFSET(m_curDevUnit)) + intptr_t offset = (intptr_t)prop->pbOffset; + if (offset == MEMBER_OFFSET(m_curDevUnit)) { - m_curDevUnit = *(int*)pvValue; + m_curDevUnit = *(const int*)value; EnumerateTitles(); - if (m_curDevUnit == 8) - SelectTitle(0); - else - SelectTitle(-1); + SelectTitle(m_curDevUnit == 8 ? 0 : -1); return false; } - else if ((intptr_t)pprd->pbOffset == MEMBER_OFFSET(m_curTitle)) + if (offset == MEMBER_OFFSET(m_curTitle)) { - SelectTitle(*(int*)pvValue); + SelectTitle(*(const int*)value); return false; } - // All other properties: let base class handle return true; } - void SelectTitle(int idx) + // CSavedGameGrid::SelectTitle(n) + // From 5960 @ 0x00049410: clamp to the rows, aim the scroll at the row's + // offset (RenderLoop with render off) and start the ease. The desktop + // rows run past the UDATA titles into its game icon entries, which only + // scroll when they're real titles; it always lands on the title itself + // (no item, first icon row) instead of 5960's remembered column, and + // tells the script with OnSelChange. + void SelectTitle(int n) { LoadDesktopIcons(); - int totalCount = s_titleCount + s_iconCount; - if (idx < -1) idx = -1; - if (idx >= totalCount) idx = totalCount - 1; - m_curTitle = idx; + const int nRowsTotal = s_titleCount + s_iconCount; + if (n < -1) + n = -1; + if (n >= nRowsTotal) + n = nRowsTotal - 1; + + m_curTitle = n; m_curGridItem = -1; m_iconRowScroll = 0; - // Compute scroll target for UDATA titles (icon entries don't render in grid) + EnumerateTitles(); - if (idx >= 0 && idx < s_titleCount) { - float y = -RenderLoop(false); - m_nScrollTo = y; + if (n >= 0 && n < s_titleCount) + { + m_nScrollTo = -RenderLoop(false); m_timeScroll = TheseusGetNow(); } CallFunction(this, "OnSelChange"); } - // Navigation + // selectUp / selectDown (5960 @ 0x00049590, 0x000495f0) move one title; + // selectLeft / selectRight (0x00049680, 0x000497b0) one item along the + // row. The desktop stops at the ends and only walks saves, and a sideways + // move reports OnSelChange itself. void selectUp() { EnumerateTitles(); - if (s_titleCount == 0) return; - if (m_curTitle > 0) { + if (s_titleCount > 0 && m_curTitle > 0) SelectTitle(m_curTitle - 1); - } } void selectDown() { EnumerateTitles(); - if (s_titleCount == 0) return; - if (m_curTitle < s_titleCount - 1) { + if (s_titleCount > 0 && m_curTitle < s_titleCount - 1) SelectTitle(m_curTitle + 1); - } } void selectLeft() { EnumerateTitles(); - if (m_curTitle < 0 || m_curTitle >= s_titleCount) return; - DesktopTitle& t = s_titles[m_curTitle]; - if (t.saveCount > 0 && m_curGridItem > 0) { + if (m_curTitle < 0 || m_curTitle >= s_titleCount) + return; + if (s_titles[m_curTitle].saveCount > 0 && m_curGridItem > 0) + { m_curGridItem--; CallFunction(this, "OnSelChange"); } @@ -2290,29 +2323,33 @@ class CSavedGameGrid : public CNode void selectRight() { EnumerateTitles(); - if (m_curTitle < 0 || m_curTitle >= s_titleCount) return; - DesktopTitle& t = s_titles[m_curTitle]; - if (t.saveCount > 0 && m_curGridItem < t.saveCount - 1) { + if (m_curTitle < 0 || m_curTitle >= s_titleCount) + return; + if (s_titles[m_curTitle].saveCount > 0 && m_curGridItem < s_titles[m_curTitle].saveCount - 1) + { m_curGridItem++; CallFunction(this, "OnSelChange"); } } + // CSavedGameGrid::setSelImage() + // From 5960 @ 0x00049840: points the selected-title image at the current + // title's picture. The desktop also covers its game icon entries. void setSelImage() { EnumerateTitles(); LoadDesktopIcons(); - static char imgPath[512]; - if (m_curTitle >= 0 && m_curTitle < s_titleCount && s_titles[m_curTitle].hasImage) { - // imagePath was set in ProcessTitleEntry to either the real - // TitleImage.xbx or the Configs/icons/.{jpg,png} - // fallback. Pass it through directly so synthesized titles - // surface their JPG icons here too. - strncpy(imgPath, s_titles[m_curTitle].imagePath, sizeof(imgPath) - 1); - imgPath[sizeof(imgPath) - 1] = 0; - g_szSelTitleImage = imgPath; - } else if (m_curTitle >= s_titleCount && m_curTitle < s_titleCount + s_iconCount) { - // Desktop icon entry (from Icons.ini via VGames) + static char s_szSelImage[512]; + if (m_curTitle >= 0 && m_curTitle < s_titleCount) + { + if (!s_titles[m_curTitle].hasImage) + return; + strncpy(s_szSelImage, s_titles[m_curTitle].imagePath, sizeof (s_szSelImage) - 1); + s_szSelImage[sizeof (s_szSelImage) - 1] = 0; + g_szSelTitleImage = s_szSelImage; + } + else if (m_curTitle >= s_titleCount && m_curTitle < s_titleCount + s_iconCount) + { g_szSelTitleImage = s_iconEntries[m_curTitle - s_titleCount].iconPath; } } diff --git a/theseus/desktop/files.cpp b/theseus/desktop/files.cpp index b5ac74a..5dca009 100755 --- a/theseus/desktop/files.cpp +++ b/theseus/desktop/files.cpp @@ -1,6 +1,8 @@ -// files.cpp: desktop file_util.h implementation. Maps the dashboard's -// path / filesystem helpers onto POSIX (or Win32 native on Windows -// builds). Counterpart to shared/file_util.cpp. +// files.cpp: the File and Folder script nodes on the desktop. A Folder +// whose path is set lists that directory into files and subFolders; a File +// carries its name, extension, path, size and date. Rebuilt from the 5960 +// retail XBE's Files.cpp code (0x317c0..0x32030), on the desktop's char +// paths and find wrappers. #include "std.h" #include "dashapp.h" @@ -9,40 +11,36 @@ #include "date_node.h" #include "runner.h" +// 5960 layout, 0x30 bytes: name 0x1c, type 0x20, path 0x24, length 0x28, date 0x2c. class CFile : public CNode { DECLARE_NODE(CFile, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CFile(); ~CFile(); - char* m_name; - char* m_type; + CStrObject* readText(); + + char* m_name; // without the extension + char* m_type; // extension, lower case, no dot char* m_path; int m_length; CDateObject* m_date; - - CStrObject* readText(); - - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() }; - +// 5960 layout, 0x3c bytes: path 0x1c, name 0x20, files 0x24, subFolders 0x30. class CFolder : public CNode { DECLARE_NODE(CFolder, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CFolder(); ~CFolder(); - char* m_path; - char* m_name; - CNodeArray m_files; - CNodeArray m_subFolders; - - bool OnSetProperty(const PRD* pprd, const void* pvValue); - + bool OnSetProperty(const PRD* prop, const void* value); void Refresh(const char* szPath); void sortByName(); @@ -50,11 +48,12 @@ class CFolder : public CNode void sortByDate(); void sortByLength(); - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() + char* m_path; + char* m_name; + CNodeArray m_files; + CNodeArray m_subFolders; }; - IMPLEMENT_NODE("File", CFile, CNode) START_NODE_PROPS(CFile, CNode) @@ -71,7 +70,6 @@ START_NODE_FUN(CFile, CNode) NODE_FUN_SV(readText) END_NODE_FUN() - IMPLEMENT_NODE("Folder", CFolder, CNode) START_NODE_PROPS(CFolder, CNode) @@ -90,16 +88,21 @@ START_NODE_FUN(CFolder, CNode) NODE_FUN_VV(sortByLength) END_NODE_FUN() - -CFile::CFile() : - m_name(NULL), - m_type(NULL), - m_path(NULL), - m_length(-1), - m_date(NULL) +// CFile::CFile() +// Reconstructed from 5960 retail XBE @ 0x00031800 (inlined in CreateNode): +// name = type = path = 0; length = -1; date = 0; +CFile::CFile() { + m_name = NULL; + m_type = NULL; + m_path = NULL; + m_length = -1; + m_date = NULL; } +// CFile::~CFile() +// Reconstructed from 5960 retail XBE @ 0x000318e0: frees the three strings +// and deletes the date through its virtual destructor. CFile::~CFile() { delete [] m_name; @@ -108,190 +111,169 @@ CFile::~CFile() delete m_date; } +// CFile::readText() [script fn 'readText', FND 0x0017f918, sig 8] +// Reconstructed from 5960 retail XBE @ 0x00031960: a new empty string; if +// there's a path, fetch the file and append its contents. 5960 widens the +// text first (MakeUnicode); desktop strings are already narrow. CStrObject* CFile::readText() { - CStrObject* pStr = new CStrObject; - - if (m_path != NULL) - { - CActiveFile file; - if (file.Fetch(m_path)) - { - pStr->Append((char*)file.GetContent()); - } - } - - return pStr; + CStrObject* pText = new CStrObject; + if (m_path == NULL) + return pText; + + CActiveFile file; + if (file.Fetch(m_path)) + pText->Append((char*)file.GetContent()); + return pText; } - -CFolder::CFolder() : - m_path(NULL), - m_name(NULL) +// CFolder::CFolder() +// Reconstructed from 5960 retail XBE @ 0x00031a50: both strings and both +// arrays start empty. +CFolder::CFolder() { + m_path = NULL; + m_name = NULL; } +// CFolder::~CFolder() +// Reconstructed from 5960 retail XBE @ 0x00031ab0: frees path and name; +// the two arrays release their nodes as they go. CFolder::~CFolder() { delete [] m_path; delete [] m_name; } -bool CFolder::OnSetProperty(const PRD* pprd, const void* pvValue) +// CFolder::OnSetProperty(prop, value) +// Reconstructed from 5960 retail XBE @ 0x00031b30: +// if (prop->offset == 0x1c) Refresh(*value); return true; +// Setting path is what lists the folder. +bool CFolder::OnSetProperty(const PRD* prop, const void* value) { - if ((intptr_t)pprd->pbOffset == MEMBER_OFFSET(m_path)) - { - const char* szPath = *((const char**)pvValue); - Refresh(szPath); - } - + if ((intptr_t)prop->pbOffset == MEMBER_OFFSET(m_path)) + Refresh(*(const char* const*)value); return true; } -void CFolder::Refresh(const char* szPath) +static char* NewCopy(const char* sz, size_t cch) { - char szWild [MAX_PATH]; - WIN32_FIND_DATA fd; - HANDLE h; + char* copy = new char [cch + 1]; + memcpy(copy, sz, cch); + copy[cch] = 0; + return copy; +} + +// "folder\name", the way 5960 joins them. +static char* NewJoin(const char* szFolder, const char* szName) +{ + char* path = new char [strlen(szFolder) + 1 + strlen(szName) + 1]; + sprintf(path, "%s\\%s", szFolder, szName); + return path; +} - lstrcpyn(szWild, szPath, MAX_PATH - sizeof("\\*.*")); - strcat(szWild, "\\*.*"); +// CFolder::Refresh(path) +// Reconstructed from 5960 retail XBE @ 0x00031b50 (971 bytes). Lists +// path\*.*; when the folder can't be read it leaves everything alone. The +// folder's name becomes whatever follows the last backslash. Hidden, system +// and temporary entries are skipped. A directory becomes a Folder (path +// joined, name as is) on subFolders; a file becomes a File on files with +// its date from the last write time, the name up to the last dot, the type +// after it in lower case, the joined path and the low 32 bits of the size. +// Entries are added to what's already there. Theseus reports a folder it +// can't read through TRACE. +void CFolder::Refresh(const char* szPath) +{ + char szPattern [MAX_PATH]; + lstrcpyn(szPattern, szPath, MAX_PATH - sizeof ("\\*.*")); + strcat(szPattern, "\\*.*"); - char szWildA [MAX_PATH]; - Ansi(szWildA, szWild, MAX_PATH); - h = TheseusFindFirstFile(szWildA, &fd); + char szPatternA [MAX_PATH]; + Ansi(szPatternA, szPattern, MAX_PATH); - if (h == INVALID_HANDLE_VALUE) + WIN32_FIND_DATA fd; + HANDLE hFind = TheseusFindFirstFile(szPatternA, &fd); + if (hFind == INVALID_HANDLE_VALUE) { TRACE("\001Cannot read directory: \"%s\" (%d)\n", szPath, GetLastError()); return; } - { - const char* pchName = strrchr(szPath, '\\'); - if (pchName == NULL) - pchName = ""; - else - pchName += 1; - - int cchName = strlen(pchName); - delete [] m_name; - - m_name = new char [cchName + 1]; - strcpy(m_name, pchName); - } + const char* pchLeaf = strrchr(szPath, '\\'); + pchLeaf = (pchLeaf != NULL) ? pchLeaf + 1 : ""; + delete [] m_name; + m_name = NewCopy(pchLeaf, strlen(pchLeaf)); + const DWORD dwSkip = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_TEMPORARY; do { - if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) + if (fd.dwFileAttributes & dwSkip) continue; - if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) - continue; - - if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) - continue; - - char szFileName [MAX_PATH]; - Unicode(szFileName, fd.cFileName, countof(szFileName)); + char szEntry [MAX_PATH]; + Unicode(szEntry, fd.cFileName, countof(szEntry)); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { CFolder* pFolder = new CFolder; m_subFolders.AddNode(pFolder); - - pFolder->m_path = new char [strlen(szPath) + 1 + strlen(szFileName) + 1]; - sprintf(pFolder->m_path, "%s\\%s", szPath, szFileName); - - pFolder->m_name = new char [strlen(szFileName) + 1]; - strcpy(pFolder->m_name, szFileName); + pFolder->m_path = NewJoin(szPath, szEntry); + pFolder->m_name = NewCopy(szEntry, strlen(szEntry)); + continue; } - else - { - CFile* pFile = new CFile; - m_files.AddNode(pFile); - pFile->m_date = new CDateObject; - pFile->m_date->m_time = fd.ftLastWriteTime; + CFile* pFile = new CFile; + m_files.AddNode(pFile); - const char* pch = strrchr(szFileName, '.'); + pFile->m_date = new CDateObject; + pFile->m_date->m_time = fd.ftLastWriteTime; - int cchName = strlen(szFileName); - if (pch != NULL) - cchName -= strlen(pch); - pFile->m_name = new char [cchName + 1]; - memcpy(pFile->m_name, szFileName, cchName); - pFile->m_name[cchName] = 0; + const char* pchDot = strrchr(szEntry, '.'); + size_t cchBase = strlen(szEntry) - (pchDot != NULL ? strlen(pchDot) : 0); + pFile->m_name = NewCopy(szEntry, cchBase); - if (pch != NULL) - pch += 1; - else - pch = ""; - pFile->m_type = new char [strlen(pch) + 1]; - strcpy(pFile->m_type, pch); - for (char* p = pFile->m_type; *p; p++) *p = (char)tolower((unsigned char)*p); + const char* pchExt = (pchDot != NULL) ? pchDot + 1 : ""; + pFile->m_type = NewCopy(pchExt, strlen(pchExt)); + for (char* pch = pFile->m_type; *pch != 0; pch++) + *pch = (char)tolower((unsigned char)*pch); - pFile->m_path = new char [strlen(szPath) + 1 + strlen(szFileName) + 1]; - sprintf(pFile->m_path, "%s\\%s", szPath, szFileName); - - pFile->m_length = fd.nFileSizeLow; - } + pFile->m_path = NewJoin(szPath, szEntry); + pFile->m_length = fd.nFileSizeLow; } - while (TheseusFindNextFile(h, &fd)); - - TheseusFindClose(h); -} - -static int __cdecl CmpName(const void* p1, const void* p2) -{ - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; + while (TheseusFindNextFile(hFind, &fd)); - return strcasecmp(pFile1->m_name, pFile2->m_name); + TheseusFindClose(hFind); } -void CFolder::sortByName() +// The sorts: qsort over files with these compares (0x31f30..0x32010). +// Name and type ignore case, date is CompareFileTime, length subtracts. +static inline const CFile* FileAt(const void* pv) { - m_files.Sort(&CmpName); + return *(const CFile* const*)pv; } -static int __cdecl CmpType(const void* p1, const void* p2) +static int __cdecl CompareNames(const void* a, const void* b) { - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; - - return strcasecmp(pFile1->m_type, pFile2->m_type); + return strcasecmp(FileAt(a)->m_name, FileAt(b)->m_name); } -void CFolder::sortByType() +static int __cdecl CompareTypes(const void* a, const void* b) { - m_files.Sort(CmpType); -} - -static int __cdecl CmpDate(const void* p1, const void* p2) -{ - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; - - return CompareFileTime(&pFile1->m_date->m_time, &pFile2->m_date->m_time); + return strcasecmp(FileAt(a)->m_type, FileAt(b)->m_type); } -void CFolder::sortByDate() +static int __cdecl CompareDates(const void* a, const void* b) { - m_files.Sort(CmpDate); -} - -static int __cdecl CmpLength(const void* p1, const void* p2) -{ - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; - - return pFile1->m_length - pFile2->m_length; + return CompareFileTime(&FileAt(a)->m_date->m_time, &FileAt(b)->m_date->m_time); } -void CFolder::sortByLength() +static int __cdecl CompareLengths(const void* a, const void* b) { - m_files.Sort(CmpLength); + return FileAt(a)->m_length - FileAt(b)->m_length; } +void CFolder::sortByName() { m_files.Sort(CompareNames); } +void CFolder::sortByType() { m_files.Sort(CompareTypes); } +void CFolder::sortByDate() { m_files.Sort(CompareDates); } +void CFolder::sortByLength() { m_files.Sort(CompareLengths); } diff --git a/theseus/engine/date_node.h b/theseus/engine/date_node.h index fae1fe5..9efd87e 100755 --- a/theseus/engine/date_node.h +++ b/theseus/engine/date_node.h @@ -1,43 +1,45 @@ -// date_node.h: CDateObject, the JavaScript-style Date object exposed to -// XAP scripts. Backed by Win32 FILETIME for nanosecond precision; getter -// methods mirror the JS spec. Companion to shared/date_node.cpp. +// date_node.h: the script Date object. Holds one FILETIME and answers the +// usual JavaScript getters from it, local or UTC. Bodies in +// shared/date_node.cpp, binary notes in docs/decomp/Date.md. #pragma once class CDateObject : public CObject { DECLARE_NODE(CDateObject, CObject) + DECLARE_NODE_FUNCTIONS() public: CDateObject(); + // Local time. + int getFullYear(); + int getYear(); + int getMonth(); int getDate(); int getDay(); - int getFullYear(); int getHours(); - int getMilliseconds(); int getMinutes(); - int getMonth(); int getSeconds(); + int getMilliseconds(); + + // Same fields in UTC. + int getUTCFullYear(); + int getUTCMonth(); int getUTCDate(); int getUTCDay(); - int getUTCFullYear(); int getUTCHours(); - int getUTCMilliseconds(); int getUTCMinutes(); - int getUTCMonth(); int getUTCSeconds(); - int getYear(); + int getUTCMilliseconds(); - int isLeapYear(int nYear); - int getDaysInMonth(int nMonth, int nYear); - - void SetSystemClock(); + int isLeapYear(int year); + int getDaysInMonth(int month, int year); CStrObject* toGMTString(); - CStrObject* toLocaleString(); CStrObject* toUTCString(); + CStrObject* toLocaleString(); - FILETIME m_time; // 100-nanosecond intervals since January 1, 1601 + void SetSystemClock(); - DECLARE_NODE_FUNCTIONS() + FILETIME m_time; // 100 ns ticks since 1601 }; diff --git a/theseus/engine/interpolator.h b/theseus/engine/interpolator.h index dcc7916..4167bfb 100755 --- a/theseus/engine/interpolator.h +++ b/theseus/engine/interpolator.h @@ -1,42 +1,36 @@ -// interpolator.h: keyframe-driven interpolators following VRML97 semantics. -// -// Each instance stores a parallel pair of arrays: m_key holds the parameter -// values (typically 0..1) at which a sample is defined, and m_keyValue -// holds the sampled output. Interpolate(t) finds the bracketing key pair -// and returns a linear blend (vec3) or shortest-arc slerp (quaternion) of -// the values. Both classes are scene-graph nodes so they can be DEF'd in -// .xap content and wired up as the value source for a TimeSensor->Transform -// animation. +// interpolator.h: VRML style key/keyValue interpolators. Interpolate(t) +// finds the two keys around t and blends their values (lerp for positions, +// slerp for orientations). Camera paths and scripts both drive them. +// Bodies in render/animation_nodes.cpp, see docs/decomp/AnimationNodes.md. #pragma once class CPositionInterpolator : public CNode { DECLARE_NODE(CPositionInterpolator, CNode) + DECLARE_NODE_PROPS() public: CPositionInterpolator(); ~CPositionInterpolator(); - D3DXVECTOR3 Interpolate(float key); + D3DXVECTOR3 Interpolate(float t); CNumArray m_key; CVec3Array m_keyValue; - - DECLARE_NODE_PROPS() }; +// Key values come in as axis + angle; OnLoad turns them into quaternions. class COrientationInterpolator : public CNode { DECLARE_NODE(COrientationInterpolator, CNode) + DECLARE_NODE_PROPS() public: COrientationInterpolator(); ~COrientationInterpolator(); void OnLoad(); - D3DXQUATERNION Interpolate(float key); + D3DXQUATERNION Interpolate(float t); CNumArray m_key; CVec4Array m_keyValue; - - DECLARE_NODE_PROPS() }; diff --git a/theseus/engine/runner.h b/theseus/engine/runner.h index 3abed3b..24a6fa5 100755 --- a/theseus/engine/runner.h +++ b/theseus/engine/runner.h @@ -1,150 +1,132 @@ -// runner.h: VM runtime stack machine, value object hierarchy, and built-ins. +// runner.h: the script VM. CRunner executes compiled bytecode on an object +// stack; the C*Object classes are the values it pushes. Bodies are in +// xap_vm.cpp, string_util.cpp and math_node.cpp; docs/decomp/VM.md has the +// binary write-up. // -// The dashboard's XAP VM is a register-stack machine that walks bytecode -// produced by xap_compile.cpp. CRunner holds the per-execution state -// (stack, frame pointer, current bytecode position, sleep clock) and -// drives the dispatch loop in xap_vm.cpp. Every value the VM pushes is a -// CObject subclass: numbers wrap CNumObject, strings wrap CStrObject, -// "this is a member of " wraps CMemberVarObject, and so on. -// Math built-ins live on a global CMathClass instance the runner finds by -// name when scripts call Math.foo(). -// -// None of these classes export properties via NODE_PROP. The only -// node-system surface here is CStrObject's NODE_FUN entries (charAt, -// indexOf, etc.) and CMathClass's NODE_FUN entries (sin, cos, etc.). All -// member fields below are pure VM internals and are renamable. +// Layouts checked against the 5960 retail XBE: +// CRunner: m_wakeup 0x00 (double), m_nop 0x08, m_ops 0x0c, m_sp 0x10, +// m_stack 0x14, m_spFrame 0x1a4, m_spBase 0x1a8, m_self 0x1ac, +// m_thisRef 0x1b0, m_bError 0x1b4, m_nLine 0x1b8, m_nextContext 0x1bc. +// 5960's stack holds 100 objects; Theseus gives it 256. +// RUNCONTEXT 0x1c: next, ops, nop, spFrame, self, thisRef, sp (PushContext 0x37690). +// CNumObject 0x18: m_value 0x14. +// CVarObject: m_length 0x14, m_capacity 0x18, m_text 0x1c. +// CStrObject: 5960 has length 0x14, capacity 0x18, text 0x1c; Theseus puts +// m_text first. Nothing reads these by offset. +// CMathClass: the eight constants follow the CNodeClass part at 0x2c. class CInstance; class CFunction; -// One slot in CObject::m_members -- a named entry in an instance's -// scripted member table. m_memberIndex is the index back into the -// owning class's variable table. -class CMember : public CObject -{ -public: - CMember(); - ~CMember(); - - void Assign(CObject* pObject); - CObject* Deref(); +CClass* LookupClass(const TCHAR* name, int nameLen); - int m_memberIndex; -}; - -// Run-time reference to "instance.member" -- the value pushed onto -// the VM stack when bytecode dereferences a class member. Deref reads -// through to the actual variable; Assign writes through. -class CMemberVarObject : public CObject +// Bytecode. 0..49 are statement/expression ops, 100..108 build the node tree. +enum { -public: - CMemberVarObject(CInstance* pInstance, int memberIndex); - ~CMemberVarObject(); - - CInstance* m_owner; - int m_memberIndex; - - CObject* Deref(); - void Assign(CObject* pObject); -}; - - -// Run-time reference to a method bound to a particular instance -- -// what gets pushed when a script does instance.foo (without calling). -class CMemberFunctionObject : public CObject -{ -public: - CMemberFunctionObject(CObject* pOwner, CFunction* pFunction); - ~CMemberFunctionObject(); - CObject* Deref(); - CObject* m_owner; - CFunction* m_function; -}; - - -CClass* LookupClass(const TCHAR* pchName, int cchName); - -// Identifier-token value: holds the literal name of a variable that -// hasn't been resolved yet. The compiler emits these for unbound -// references; the runner resolves them lazily on Deref. -class CVarObject : public CObject -{ -public: - CVarObject(const TCHAR* pch, int cch); - ~CVarObject(); - - int m_length; - int m_capacity; - TCHAR* m_text; - - CObject* Deref(); - void Assign(CObject* pObject); - -private: - // Need this to prevent the compiler from using default copy ctor - CVarObject(const CVarObject&); - CVarObject& operator=(const CVarObject& rhs); + opNull, + opNew, + opVar, + opJump, + opCond, + opCall, + opRet, + opStr, + opNum, + opAdd, + opSub, + opMul, + opDiv, + opDot, + opAssign, + opLocal, + opEQ, + opNE, + opLT, + opGT, + opLE, + opGE, + opMod, + opSHL, + opSHR, + opSHRU, + opAnd, + opOr, + opXor, + opLAnd, + opLOr, + opQuest, + opAddAssign, + opSubAssign, + opMulAssign, + opDivAssign, + opModAssign, + opAndAssign, + opOrAssign, + opXorAssign, + opSHLAssign, + opSHRAssign, + opArray, + opThis, + opFrame, + opStatement, + opNeg, + opDrop, + opEndFrame, + opSleep, + + opNewNode = 100, + opNewNodeProp, + opDefNode, + opUseNode, + opEndNode, + opInitProp, + opInitArray, + opEndArray, + opFunction }; +// A number on the stack. class CNumObject : public CObject { public: CNumObject(); CNumObject(float n); - CNumObject(const TCHAR* szNum); + CNumObject(const TCHAR* text); + CNumObject* ToNum() { AddRef(); return this; } CStrObject* ToStr(); - CNumObject* ToNum() - { - AddRef(); - return this; - } - float m_value; }; - -// Script-visible string object. Owns a TCHAR buffer and exposes the -// JavaScript-style string API (charAt, indexOf, slice, etc.) via the -// FND table in string_util.cpp. The buffer grows on Append. +// A string on the stack, plus the script String methods (FND table in +// string_util.cpp). Append grows the buffer. class CStrObject : public CObject { public: CStrObject(); - CStrObject(const TCHAR* sz); - CStrObject(const TCHAR* pch, int cch); + CStrObject(const TCHAR* text); + CStrObject(const TCHAR* src, int len); ~CStrObject(); - inline const TCHAR* GetSz() - { - if (m_text == NULL) - return _T(""); - return m_text; - } - - inline int GetLength() - { - return m_length; - } + inline const TCHAR* GetSz() { return m_text != NULL ? m_text : _T(""); } + inline int GetLength() { return m_length; } - CStrObject* ToStr(); CNumObject* ToNum(); + CStrObject* ToStr(); - TCHAR* SetLength(int nLength); - void Append(const TCHAR* szAppend); - + TCHAR* SetLength(int len); + void Append(const TCHAR* more); - // JavaScript-style String methods exposed via the FND table. int length(); - CStrObject* charAt(int index); - int charCodeAt(int index); - CStrObject* concat(const TCHAR* sz); - CObject* indexOf(CObject** rgparam, int nParam); - CObject* lastIndexOf(CObject** rgparam, int nParam); - CStrObject* slice(int start, int end); - CObject* substr(CObject** rgparam, int nParam); - CObject* substring(CObject** rgparam, int nParam); + CStrObject* charAt(int i); + int charCodeAt(int i); + CStrObject* concat(const TCHAR* text); + CObject* indexOf(CObject** args, int argc); + CObject* lastIndexOf(CObject** args, int argc); + CStrObject* slice(int from, int to); + CObject* substr(CObject** args, int argc); + CObject* substring(CObject** args, int argc); CStrObject* toLowerCase(); CStrObject* toUpperCase(); @@ -157,109 +139,100 @@ class CStrObject : public CObject DECLARE_NODE_FUNCTIONS() private: - // Need this to prevent the compiler from using default copy ctor - CStrObject(const CStrObject&); - CStrObject& operator=(const CStrObject& rhs); + // Owns its buffer; no copies. + CStrObject(const CStrObject&); + CStrObject& operator=(const CStrObject&); }; -// Script-visible wrapper around a CNodeArray. Lets scenes treat a -// node array property as a JavaScript-ish array (length, push, splice). -class CNodeArrayObject : public CObject +// A name the compiler couldn't bind. Deref looks it up when it runs. +class CVarObject : public CObject { public: - CNodeArrayObject(CNodeArray* pNodeArray); + CVarObject(const TCHAR* src, int len); + ~CVarObject(); - CObject* Call(int nFunction, CObject** rgparam, int nParam); - CObject* Dot(CObject* pObject); + CObject* Deref(); + void Assign(CObject* obj); - CNodeArray* m_nodeArray; + int m_length; + int m_capacity; + TCHAR* m_text; + +private: + CVarObject(const CVarObject&); + CVarObject& operator=(const CVarObject&); +}; + +// An entry in an object's member name space; m_memberIndex is the slot in +// the owning class's variables. +class CMember : public CObject +{ +public: + CMember(); + ~CMember(); + + CObject* Deref(); + void Assign(CObject* obj); + + int m_memberIndex; +}; + +// "instance.var": reads and writes go to that instance's variable slot. +class CMemberVarObject : public CObject +{ +public: + CMemberVarObject(CInstance* inst, int slot); + ~CMemberVarObject(); + + CObject* Deref(); + void Assign(CObject* obj); + + CInstance* m_owner; + int m_memberIndex; +}; + +// "instance.method" without the call: the method bound to its owner. +class CMemberFunctionObject : public CObject +{ +public: + CMemberFunctionObject(CObject* owner, CFunction* func); + ~CMemberFunctionObject(); + + CObject* Deref(); + + CObject* m_owner; + CFunction* m_function; }; -// Reference to a function bound to a particular owning object -- -// what bytecode pushes when it pulls "this.foo" off an instance. +// An FND function bound to the object it was looked up on. class CFunctionObject : public CObject { public: CFunctionObject(); ~CFunctionObject(); + CObject* Call(CObject** args, int argc); + int m_functionIndex; CObject* m_owner; - - CObject* Call(CObject** rgparam, int nParam); }; +// A node array property seen from script (length, indexing, push...). +class CNodeArrayObject : public CObject +{ +public: + CNodeArrayObject(CNodeArray* array); + + CObject* Call(int index, CObject** args, int argc); + CObject* Dot(CObject* obj); + + CNodeArray* m_nodeArray; +}; -#define opNull 0 -#define opNew 1 -#define opVar 2 -#define opJump 3 -#define opCond 4 -#define opCall 5 -#define opRet 6 -#define opStr 7 -#define opNum 8 -#define opAdd 9 -#define opSub 10 -#define opMul 11 -#define opDiv 12 -#define opDot 13 -#define opAssign 14 -#define opLocal 15 -#define opEQ 16 -#define opNE 17 -#define opLT 18 -#define opGT 19 -#define opLE 20 -#define opGE 21 -#define opMod 22 -#define opSHL 23 -#define opSHR 24 -#define opSHRU 25 -#define opAnd 26 -#define opOr 27 -#define opXor 28 -#define opLAnd 29 -#define opLOr 30 -#define opQuest 31 -#define opAddAssign 32 -#define opSubAssign 33 -#define opMulAssign 34 -#define opDivAssign 35 -#define opModAssign 36 -#define opAndAssign 37 -#define opOrAssign 38 -#define opXorAssign 39 -#define opSHLAssign 40 -#define opSHRAssign 41 -#define opArray 42 -#define opThis 43 -#define opFrame 44 -#define opStatement 45 -#define opNeg 46 -#define opDrop 47 -#define opEndFrame 48 -#define opSleep 49 - - -#define opNewNode 100 -#define opNewNodeProp 101 -#define opDefNode 102 -#define opUseNode 103 -#define opEndNode 104 -#define opInitProp 105 -#define opInitArray 106 -#define opEndArray 107 -#define opFunction 108 - -// Saved CRunner state across a function call. PushContext spills the -// outer frame here when bytecode steps into a callee, PopContext -// restores it on Ret. The field names mirror CRunner exactly so the -// push/pop code can move state with one assignment per slot. +// The caller's state, saved while a called function runs. struct RUNCONTEXT { RUNCONTEXT* m_nextContext; - BYTE* m_ops; UINT m_nop; UINT m_spFrame; @@ -271,123 +244,105 @@ struct RUNCONTEXT class CRunner { public: - CRunner(CObject* pThis); + CRunner(CObject* self); ~CRunner(); - bool SetFunc(const TCHAR* szFunc); - - - void Push(float nValue); - void Push(int nValue); - void Push(const TCHAR* szValue, int nLen = -1); + bool SetFunc(const TCHAR* funcName); + void SetFunc(CFunction* func); + void ResetFunc(); + bool HasFunc() const { return m_ops != NULL; } - void Push(CObject* pObject); + void Push(float value); + void Push(int value); + void Push(const TCHAR* value, int len = -1); + void Push(CObject* obj); CObject* Pop(); - bool HasFunc() const { return m_ops != NULL; } - void SetFunc(CFunction* pFunction); - void ResetFunc(); - CObject* Run(); - bool Step(CObject** ppRetObj = NULL); - void Error(const TCHAR* szFmt, ...); + bool Step(CObject** ret = NULL); + void Error(const TCHAR* fmt, ...); - BYTE* LookupFunction(const TCHAR* pchName, int cchName, CObject*& pOwner); - CObject* LookupVariable(const TCHAR* pchName, int cchName); + BYTE* LookupFunction(const TCHAR* name, int nameLen, CObject*& owner); + CObject* LookupVariable(const TCHAR* name, int nameLen); + // A sleep that has run out clears itself here. bool IsSleeping() { - if (m_wakeup != 0.0f) + if (m_wakeup) { if (m_wakeup > TheseusGetNow()) return true; - m_wakeup = 0.0f; } - return false; } void DumpStack(); protected: - XTIME m_wakeup; // sleep deadline (0 = not sleeping) - UINT m_nop; // bytecode offset within m_ops - BYTE* m_ops; // currently executing bytecode buffer - UINT m_sp; // stack pointer (top-of-stack index) - CObject* m_stack [256]; // operand stack - UINT m_spFrame; // frame pointer for the current call - UINT m_spBase; // bottom of the locals region - CObject* m_self; // current 'self' (callable owner) - CObject* m_thisRef; // current 'this' (script-visible binding) - - bool m_bError; - int m_nLine; - bool BinaryOperator(BYTE op); - - void PushContext(UINT nPopStack); + void PushContext(UINT argc); void PopContext(); - BOOL ExecuteBuiltIn(const TCHAR* pchName, int cchName, int nParam, CObject** rgParam, CObject*& pRetObj); + BOOL ExecuteBuiltIn(const TCHAR* name, int nameLen, int argc, CObject** args, CObject*& ret); + // Operands sit unaligned in the op stream. inline int FetchInt() { -#if defined(_WIN32_WCE) int n; - CopyMemory(&n, &m_ops[m_nop], sizeof (int)); -#else - int n = *((int*)&m_ops[m_nop]); -#endif - m_nop += sizeof (int); + memcpy(&n, m_ops + m_nop, sizeof (n)); + m_nop += sizeof (n); return n; } inline UINT FetchUInt() { -#if defined(_WIN32_WCE) UINT n; - CopyMemory(&n, &m_ops[m_nop], sizeof (UINT)); -#else - UINT n = *((UINT*)&m_ops[m_nop]); -#endif - m_nop += sizeof (UINT); + memcpy(&n, m_ops + m_nop, sizeof (n)); + m_nop += sizeof (n); return n; } inline float FetchFloat() { -#if defined(_WIN32_WCE) float n; - CopyMemory(&n, &m_ops[m_nop], sizeof (float)); -#else - float n = *((float*)&m_ops[m_nop]); -#endif - m_nop += sizeof (float); + memcpy(&n, m_ops + m_nop, sizeof (n)); + m_nop += sizeof (n); return n; } + // Length first, then that many characters in place. inline const TCHAR* FetchString(int& cch) { cch = FetchInt(); - const TCHAR* pch = (const TCHAR*)&m_ops[m_nop]; + const TCHAR* pch = (const TCHAR*)(m_ops + m_nop); m_nop += cch * sizeof (TCHAR); return pch; } + XTIME m_wakeup; // sleep deadline, 0 when awake + UINT m_nop; // offset into m_ops + BYTE* m_ops; // bytecode being run + UINT m_sp; // next free stack slot + CObject* m_stack [256]; + UINT m_spFrame; // first local of the current call + UINT m_spBase; + CObject* m_self; // owner of the running function + CObject* m_thisRef; // what "this" means in script + bool m_bError; + int m_nLine; RUNCONTEXT* m_nextContext; }; extern CRunner* g_pRunner; extern CObject* g_pThis; -extern bool ExecuteScript(CObject* pObject, const TCHAR* szFunc); - - - +extern bool ExecuteScript(CObject* obj, const TCHAR* funcName); #undef min #undef max +// The global Math object: a class whose functions and constants scripts +// reach as Math.name. class CMathClass : public CNodeClass { public: @@ -396,27 +351,26 @@ class CMathClass : public CNodeClass void AddRef(); void Release(); - // Static-style helpers exposed to scripts via the NODE_FUN table. - float abs(float number); - float acos(float number); - float asin(float number); - float atan(float number); + float abs(float x); + float acos(float x); + float asin(float x); + float atan(float x); float atan2(float y, float x); - float ceil(float number); - float cos(float number); - float exp(float number); - float floor(float number); - float log(float number); - float max(float number1, float number2); - float min(float number1, float number2); - float pow(float base, float exponent); + float ceil(float x); + float cos(float x); + float exp(float x); + float floor(float x); + float log(float x); + float max(float a, float b); + float min(float a, float b); + float pow(float x, float y); float random(); - float round(float number); - float sin(float number); - float sqrt(float number); - float tan(float number); - float projectMEnabled(); // returns 1.0 if desktop has g_useMilkdropViz set - CStrObject* itoa(int number); + float round(float x); + float sin(float x); + float sqrt(float x); + float tan(float x); + float projectMEnabled(); // Theseus: 1 when the desktop milkdrop visualizer is on + CStrObject* itoa(int x); float m_E; float m_LN2; diff --git a/theseus/engine/settings_nodes.cpp b/theseus/engine/settings_nodes.cpp index c6b402e..0a240d3 100755 --- a/theseus/engine/settings_nodes.cpp +++ b/theseus/engine/settings_nodes.cpp @@ -13,31 +13,30 @@ // ===== Settings ============================================================ +// 0x30 bytes in 5960: file 0x1c, section 0x20, then the open settings file. class CSettings : public CNode { DECLARE_NODE(CSettings, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CSettings(); ~CSettings(); - CObject* Dot(CObject* pObject); - - TCHAR* m_file; - TCHAR* m_section; - - void SetValue(const TCHAR* szName, const TCHAR* szValue); - CStrObject* GetValue(const TCHAR* szName); + CObject* Dot(CObject* member); + CStrObject* GetValue(const TCHAR* name); + void SetValue(const TCHAR* name, const TCHAR* value); // Theseus: drops the cached file and reads it again, for when native // code (the title scanner) rewrote it underneath. void Reload(); -protected: - CSettingsFile m_sfile; + TCHAR* m_file; + TCHAR* m_section; +protected: bool OpenCurrent(); - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() + CSettingsFile m_sfile; }; // What settings. evaluates to: reading it fetches the value, @@ -48,9 +47,9 @@ class CSetting : public CObject CSetting(); ~CSetting(); - void Assign(CObject* pObject); - CStrObject* ToStr(); CObject* Deref(); + void Assign(CObject* newValue); + CStrObject* ToStr(); CSettings* m_pSettings; TCHAR* m_textName; @@ -93,13 +92,13 @@ CSettings::~CSettings() // Reconstructed from 5960 retail XBE @ 0x00041950. Anything the node itself // answers comes first; any other name (a type 4 variable) becomes a // CSetting carrying a copy of the name. -CObject* CSettings::Dot(CObject* pObj) +CObject* CSettings::Dot(CObject* member) { - CObject* own = CNode::Dot(pObj); - if (own != NULL || pObj->m_obj != objVariable) + CObject* own = CNode::Dot(member); + if (own != NULL || member->m_obj != objVariable) return own; - const TCHAR* name = ((CVarObject*)pObj)->m_text; + const TCHAR* name = ((CVarObject*)member)->m_text; CSetting* setting = new CSetting; setting->m_pSettings = this; setting->m_textName = new TCHAR[_tcslen(name) + 1]; @@ -128,22 +127,22 @@ void CSettings::Reload() // CSettings::SetValue(name, value) [script fn 'SetValue', FND 0x00182028, sig 13] // Reconstructed from 5960 retail XBE @ 0x000419e0: reopen if needed, set // the value in `section`, and save when it changed. -void CSettings::SetValue(const TCHAR* szName, const TCHAR* szValue) +void CSettings::SetValue(const TCHAR* name, const TCHAR* value) { OpenCurrent(); - m_sfile.SetValue(m_section, szName, szValue); + m_sfile.SetValue(m_section, name, value); } // CSettings::GetValue(name) [script fn 'GetValue', FND 0x00182010, sig 5] // Reconstructed from 5960 retail XBE @ 0x00041a50: reopen if needed (an // empty string if that fails), then the value from `section` read into // 1024 characters. -CStrObject* CSettings::GetValue(const TCHAR* szName) +CStrObject* CSettings::GetValue(const TCHAR* name) { if (!OpenCurrent()) return new CStrObject(_T("")); TCHAR value[1024]; - m_sfile.GetValue(m_section, szName, value, countof(value)); + m_sfile.GetValue(m_section, name, value, countof(value)); return new CStrObject(value); } @@ -162,9 +161,9 @@ CSetting::~CSetting() // CSetting::Assign(value) // Reconstructed from 5960 retail XBE @ 0x00041b80: // s = value->Deref()->ToStr(); settings->SetValue(name, s->text or ""); -void CSetting::Assign(CObject* pObject) +void CSetting::Assign(CObject* newValue) { - CStrObject* text = pObject->Deref()->ToStr(); + CStrObject* text = newValue->Deref()->ToStr(); m_pSettings->SetValue(m_textName, text->GetSz()); } @@ -186,35 +185,35 @@ CObject* CSetting::Deref() // ===== ScreenSaver ========================================================= +// Three idle stages: delay starts the saver, delay2 and delay3 fire later +// hooks. The newest ScreenSaver is the one input resets. class CScreenSaver : public CNode { DECLARE_NODE(CScreenSaver, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CScreenSaver(); ~CScreenSaver(); - void StartAfter(float nTime); - void SetDelay2(float nTime); - void SetDelay3(float nTime); - - bool m_enabled; - bool m_isActive; - bool m_isActive2; - bool m_isActive3; - float m_delay; - float m_delay2; - float m_delay3; + void Advance(float dt); + bool OnSetProperty(const PRD* prop, const void* value); void reset(); - void Advance(float nSeconds); - - XTIME m_timeOfLastEvent; + void StartAfter(float secs); + void SetDelay2(float secs); + void SetDelay3(float secs); static CScreenSaver* c_pTheScreenSaver; - bool OnSetProperty(const PRD* pprd, const void* pvValue); - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() + bool m_enabled; + bool m_isActive; + bool m_isActive2; + bool m_isActive3; + float m_delay; + float m_delay2; + float m_delay3; + XTIME m_timeOfLastEvent; }; IMPLEMENT_NODE("ScreenSaver", CScreenSaver, CNode) @@ -267,9 +266,9 @@ CScreenSaver::~CScreenSaver() c_pTheScreenSaver = NULL; } -void CScreenSaver::StartAfter(float nTime) { m_delay = nTime; } -void CScreenSaver::SetDelay2(float nTime) { m_delay2 = nTime; } -void CScreenSaver::SetDelay3(float nTime) { m_delay3 = nTime; } +void CScreenSaver::StartAfter(float secs) { m_delay = secs; } +void CScreenSaver::SetDelay2(float secs) { m_delay2 = secs; } +void CScreenSaver::SetDelay3(float secs) { m_delay3 = secs; } // CScreenSaver::Advance(dt) // Reconstructed from 5960 retail XBE @ 0x000401b0. Disabled while active @@ -277,9 +276,9 @@ void CScreenSaver::SetDelay3(float nTime) { m_delay3 = nTime; } // delay2 and delay3, when above 0, each fire once (OnDelay2, OnDelay3) // after that long idle, enabled or not. 5960 does the sums in float; // Theseus keeps the double clock. -void CScreenSaver::Advance(float nSeconds) +void CScreenSaver::Advance(float dt) { - CNode::Advance(nSeconds); + CNode::Advance(dt); XTIME now = TheseusGetNow(); if (!m_enabled) @@ -326,11 +325,11 @@ void CScreenSaver::reset() // CScreenSaver::OnSetProperty(prd, value) // Reconstructed from 5960 retail XBE @ 0x000402d0: turning `enabled` on // resets first; the new value is stored either way. -bool CScreenSaver::OnSetProperty(const PRD* pprd, const void* pvValue) +bool CScreenSaver::OnSetProperty(const PRD* prop, const void* value) { - if (PTR2INT(pprd->pbOffset) != offsetof(m_enabled)) + if (PTR2INT(prop->pbOffset) != offsetof(m_enabled)) return true; - bool on = *(const bool*)pvValue; + bool on = *(const bool*)value; if (on) reset(); m_enabled = on; diff --git a/theseus/engine/xap_compile.h b/theseus/engine/xap_compile.h index a70c8da..f8c414f 100755 --- a/theseus/engine/xap_compile.h +++ b/theseus/engine/xap_compile.h @@ -1,7 +1,10 @@ -// xap_compile.h: tokenizer / parser / bytecode-compiler API surface -// exposed to the rest of the engine. Forward decls for the VM types and -// the entry points that drive a compile from XAP text to a CFunction. -// Companion to xap_compile.cpp. +// xap_compile.h: turns XAP text into bytecode. The tokenizer and value +// parsers are free functions; CClassCompiler handles a file's node tree, +// CFunctionCompiler a function body. Bodies in xap_compile.cpp, binary +// write-up in docs/decomp/Compiler.md. +// +// CCompiler layout matches 5960: vtbl, m_nop 0x04, m_ops 0x08, +// m_opsSize 0x0c, m_bError 0x10. #pragma once @@ -9,9 +12,7 @@ class CNodeClass; class CClass; class CFunction; -void StartParse(const TCHAR* pch, const TCHAR* szFileName, int nLine = 1); -void EndParse(); - +// Which comment styles SkipWhite steps over. Bit flags. enum COMMENT_TYPE { none = 0, @@ -21,56 +22,90 @@ enum COMMENT_TYPE any = 0xffffffff }; -const TCHAR* SkipWhite(const TCHAR* pch, COMMENT_TYPE ct = any); -const TCHAR* Token(const TCHAR* pch, const TCHAR*& pchToken, int& cchToken, bool bAllowPaths = false, COMMENT_TYPE ct = any); -extern void SyntaxError(const TCHAR* szMsg, ...); -const TCHAR* ParseBoolean(const TCHAR* pch, bool& b); -const TCHAR* ParseInteger(const TCHAR* pch, int& i); -const TCHAR* ParseNumber(const TCHAR* pch, float& n); -const TCHAR* ParseString(const TCHAR* pch, TCHAR*& sz); -const TCHAR* ParseVec3(const TCHAR* pch, float v[3]); -const TCHAR* ParseVec4(const TCHAR* pch, float v[4]); -const TCHAR* ParseIntArray(const TCHAR* pch, BYTE*& pbArray, int& cbArray); -const TCHAR* ParseVecArray(const TCHAR* pch, BYTE*& pbArray, int& cbArray, int nVecSize); -int ExpandCString(TCHAR* szString, int cchMaxString, const TCHAR* pchToken, int cchToken); +void StartParse(const TCHAR* src, const TCHAR* fileName, int line = 1); +void EndParse(); +extern void SyntaxError(const TCHAR* fmt, ...); + +const TCHAR* SkipWhite(const TCHAR* src, COMMENT_TYPE comments = any); +const TCHAR* Token(const TCHAR* src, const TCHAR*& tok, int& tokLen, bool paths = false, COMMENT_TYPE comments = any); + +const TCHAR* ParseBoolean(const TCHAR* src, bool& b); +const TCHAR* ParseInteger(const TCHAR* src, int& i); +const TCHAR* ParseNumber(const TCHAR* src, float& n); +const TCHAR* ParseString(const TCHAR* src, TCHAR*& out); +const TCHAR* ParseVec3(const TCHAR* src, float v[3]); +const TCHAR* ParseVec4(const TCHAR* src, float v[4]); +const TCHAR* ParseIntArray(const TCHAR* src, BYTE*& data, int& size); +const TCHAR* ParseVecArray(const TCHAR* src, BYTE*& data, int& size, int dims); +int ExpandCString(TCHAR* out, int outMax, const TCHAR* tok, int tokLen); + +// Local variable name in a function frame. +struct ST +{ + short cchName; + const TCHAR* pchName; +}; +// Operator table row: up to three characters, precedence, and the op it emits. +struct DOPER +{ + TCHAR m_ch1; + TCHAR m_ch2; + TCHAR m_ch3; + TCHAR m_pri; + BYTE m_op; +}; +// A "break" jump waiting for its loop's end address. +struct BREAK +{ + BREAK* m_next; + int m_nop; +}; + +// Growable op buffer shared by both compilers. class CCompiler { public: CCompiler(); virtual ~CCompiler(); - inline void Write(const void* pv, int cb) + // 5960 grows when the write would reach the end, then copies (0x34440). + inline void Write(const void* data, int size) { - if (m_nop + cb >= m_opsSize) - GrowTo(m_nop + cb); - CopyMemory(&m_ops[m_nop], pv, cb); - m_nop += cb; + if (m_nop + size >= m_opsSize) + GrowTo(m_nop + size); + memcpy(m_ops + m_nop, data, size); + m_nop += size; } inline void Write(BYTE b) { Write(&b, 1); } - inline void WriteInteger(int n) { Write(&n, sizeof (int)); } - inline void WriteNumber(float n) { Write(&n, sizeof (float)); } - inline void WriteString(const TCHAR* pch, int cch) { WriteInteger(cch); Write(pch, cch * sizeof (TCHAR)); } + inline void WriteInteger(int n) { Write(&n, sizeof (n)); } + inline void WriteNumber(float n) { Write(&n, sizeof (n)); } + + // Length, then the characters. + inline void WriteString(const TCHAR* src, int len) + { + WriteInteger(len); + Write(src, len * sizeof (TCHAR)); + } inline UINT GetAddress() { return m_nop; } // Patches a jump or frame size written earlier. 5960 stores straight in. - inline void Fixup(UINT nAddress, UINT nValue) + inline void Fixup(UINT at, UINT value) { - if (CHECK(nAddress + sizeof (UINT) <= m_nop)) - CopyMemory(&m_ops[nAddress], &nValue, sizeof (UINT)); + if (CHECK(at + sizeof (UINT) <= m_nop)) + memcpy(m_ops + at, &value, sizeof (value)); } + void GrowTo(int size); CFunction* CreateFunction(); - void SyntaxError(const TCHAR* szMsg, ...); + void SyntaxError(const TCHAR* fmt, ...); inline void SetError() { m_bError = true; } inline bool HadError() const { return m_bError; } - void GrowTo(int nNewSize); - protected: UINT m_nop; BYTE* m_ops; @@ -78,78 +113,56 @@ class CCompiler bool m_bError; }; - -struct ST -{ - short cchName; - const TCHAR* pchName; -}; - -struct DOPER -{ - TCHAR m_ch1; - TCHAR m_ch2; - TCHAR m_ch3; - TCHAR m_pri; - BYTE m_op; -}; - -// Per-loop break-fixup record. The function compiler emits a forward -// jump for every "break" statement and stacks one of these so the -// jump target can be patched in once the loop's end address is known. -struct BREAK -{ - BREAK* m_next; - int m_nop; -}; - +// Compiles one function or behavior body. class CFunctionCompiler : public CCompiler { public: CFunctionCompiler(); - ST m_rgstLocal[100]; - int m_nFrameSize; - - const TCHAR* ParseOperator(const TCHAR* pch, const DOPER*& pdoper); - const TCHAR* ParseExpression(const TCHAR* pch); - const TCHAR* ParseStatement(const TCHAR* pch); - const TCHAR* ParseTerm(const TCHAR* pch); - const TCHAR* ParseBlock(const TCHAR* pch); - const TCHAR* ParseLocalVar(const TCHAR* pch); - const TCHAR* ParseArray(const TCHAR* pch); - const TCHAR* ParseCall(const TCHAR* pch); - const TCHAR* ParseExp(const TCHAR* pch, int nPrio); - const TCHAR* ParseIF(const TCHAR* pch); - const TCHAR* ParseWHILE(const TCHAR* pch); - const TCHAR* ParseFOR(const TCHAR* pch); - const TCHAR* ParseDO(const TCHAR* pch); - const TCHAR* ParseBREAK(const TCHAR* pch); - const TCHAR* ParseCONTINUE(const TCHAR* pch); - const TCHAR* ParseRETURN(const TCHAR* pch); - const TCHAR* ParseSLEEP(const TCHAR* pch); + const TCHAR* ParseBlock(const TCHAR* src); + const TCHAR* ParseStatement(const TCHAR* src); + const TCHAR* ParseLocalVar(const TCHAR* src); + const TCHAR* ParseIF(const TCHAR* src); + const TCHAR* ParseWHILE(const TCHAR* src); + const TCHAR* ParseFOR(const TCHAR* src); + const TCHAR* ParseDO(const TCHAR* src); + const TCHAR* ParseBREAK(const TCHAR* src); + const TCHAR* ParseCONTINUE(const TCHAR* src); + const TCHAR* ParseRETURN(const TCHAR* src); + const TCHAR* ParseSLEEP(const TCHAR* src); + + const TCHAR* ParseExpression(const TCHAR* src); + const TCHAR* ParseExp(const TCHAR* src, int prio); + const TCHAR* ParseOperator(const TCHAR* src, const DOPER*& oper); + const TCHAR* ParseTerm(const TCHAR* src); + const TCHAR* ParseArray(const TCHAR* src); + const TCHAR* ParseCall(const TCHAR* src); void FixupBreaks(); + + ST m_rgstLocal[100]; + int m_nFrameSize; BREAK* m_breaks; int m_nBreakables; int m_nopTopOfLoop; bool m_bBehavior; }; +// Compiles a whole .xap: nodes, props, member vars, classes, functions. class CClassCompiler : public CCompiler { public: - CClassCompiler(CClass* pClass); + CClassCompiler(CClass* cls); - const TCHAR* Compile(const TCHAR* pch); + const TCHAR* Compile(const TCHAR* src); protected: - const TCHAR* ParseNode(const TCHAR* pch); - const TCHAR* ParseProps(const TCHAR* pch, CNodeClass* pNodeClass); - const TCHAR* ParseChildren(const TCHAR* pch); - const TCHAR* ParseMemberVar(const TCHAR* pch); - const TCHAR* ParseClass(const TCHAR* pch); - const TCHAR* ParseFunction(const TCHAR* pch, CFunction*& pFunction, bool bBehavior = false); + const TCHAR* ParseNode(const TCHAR* src); + const TCHAR* ParseProps(const TCHAR* src, CNodeClass* cls); + const TCHAR* ParseChildren(const TCHAR* src); + const TCHAR* ParseMemberVar(const TCHAR* src); + const TCHAR* ParseClass(const TCHAR* src); + const TCHAR* ParseFunction(const TCHAR* src, CFunction*& func, bool behavior = false); CClass* m_targetClass; }; diff --git a/theseus/render/animation_nodes.cpp b/theseus/render/animation_nodes.cpp index e2576d3..38e2e47 100644 --- a/theseus/render/animation_nodes.cpp +++ b/theseus/render/animation_nodes.cpp @@ -18,20 +18,19 @@ class CTimeSensor : public CTimeDepNode { DECLARE_NODE(CTimeSensor, CTimeDepNode) + DECLARE_NODE_PROPS() public: CTimeSensor(); + bool OnSetProperty(const PRD* prop, const void* value); + void Advance(float dt); + void OnIsActiveChanged(); + float m_cycleInterval; - bool m_enabled; + bool m_enabled; XTIME m_cycleTime; float m_fraction_changed; XTIME m_time; - - void Advance(float nSeconds); - void OnIsActiveChanged(); - bool OnSetProperty(const PRD* pprd, const void* pvValue); - - DECLARE_NODE_PROPS() }; IMPLEMENT_NODE("TimeSensor", CTimeSensor, CTimeDepNode) @@ -58,12 +57,12 @@ CTimeSensor::CTimeSensor() // if (prd->offset == 0x48) { time = (double)*(float*)value; return 0; } // return 1; // Script hands numbers over as floats; time is a double, so it's widened here. -bool CTimeSensor::OnSetProperty(const PRD* pprd, const void* pvValue) +bool CTimeSensor::OnSetProperty(const PRD* prop, const void* value) { - if (PTR2INT(pprd->pbOffset) != offsetof(m_time)) + if (PTR2INT(prop->pbOffset) != offsetof(m_time)) return true; - m_time = *(const float*)pvValue; + m_time = *(const float*)value; return false; } @@ -80,10 +79,10 @@ bool CTimeSensor::OnSetProperty(const PRD* pprd, const void* pvValue) // if (fraction_changed == 0.0 && startTime < now) fraction_changed = 1.0; // CallFunction(this, L"fraction_changed", 0, 0); // The 1.0 case lets a cycle end land on its last frame instead of wrapping. -void CTimeSensor::Advance(float nSeconds) +void CTimeSensor::Advance(float dt) { XTIME now = TheseusGetNow(); - CTimeDepNode::Advance(nSeconds); + CTimeDepNode::Advance(dt); if (!m_isActive) return; @@ -159,12 +158,12 @@ CPositionInterpolator::~CPositionInterpolator() // D3DXVec3CatmullRom(&out, &v[i-1], &v[i], &v[i+1], &v[i+2], frac); // else out = v[i] + (v[i+1] - v[i]) * frac; // Catmull-Rom needs a key on each side, so the end spans fall back to a lerp. -D3DXVECTOR3 CPositionInterpolator::Interpolate(float key) +D3DXVECTOR3 CPositionInterpolator::Interpolate(float t) { const D3DXVECTOR3* v = m_keyValue.m_value; int last = m_keyValue.m_nSize - 1; - float span = key * (float)last; + float span = t * (float)last; float whole = floorf(span); int i = (int)whole; float frac = span - whole; @@ -223,12 +222,12 @@ void COrientationInterpolator::OnLoad() // if (i < 0) return v[0]; // if (count - 1 <= i) return v[count - 1]; // D3DXQuaternionSlerp(&out, &v[i], &v[i+1], k - floor(k)); -D3DXQUATERNION COrientationInterpolator::Interpolate(float key) +D3DXQUATERNION COrientationInterpolator::Interpolate(float t) { const D3DXQUATERNION* q = (const D3DXQUATERNION*)m_keyValue.m_value; int last = m_keyValue.m_nSize - 1; - float span = key * (float)last; + float span = t * (float)last; float whole = floorf(span); int i = (int)whole; @@ -299,10 +298,10 @@ void CViewpoint::OnLoad() // BindViewpoint(pNode) // Reconstructed from 5960 retail XBE @ 0x0004f880. Ghidra decompile: // if (node && node->GetNodeClass() is or derives from CViewpoint) Bind(); -void BindViewpoint(CNode* pViewpointNode) +void BindViewpoint(CNode* viewpoint) { - if (pViewpointNode != NULL && pViewpointNode->IsKindOf(NODE_CLASS(CViewpoint))) - ((CViewpoint*)pViewpointNode)->Bind(); + if (viewpoint != NULL && viewpoint->IsKindOf(NODE_CLASS(CViewpoint))) + ((CViewpoint*)viewpoint)->Bind(); } // CViewpoint::Bind() @@ -340,13 +339,13 @@ void CViewpoint::Bind() // if (prd->offset == 0x1c) { if (*(bool*)value) Bind(); } // else if (prd->offset == 0x20) g_bProjectionDirty = 1; // return 1; -bool CViewpoint::OnSetProperty(const PRD* pprd, const void* pvValue) +bool CViewpoint::OnSetProperty(const PRD* prop, const void* value) { - int field = PTR2INT(pprd->pbOffset); + int field = PTR2INT(prop->pbOffset); if (field == offsetof(m_isBound)) { - if (*(const bool*)pvValue) + if (*(const bool*)value) Bind(); } else if (field == offsetof(m_fieldOfView)) @@ -431,13 +430,13 @@ void CNavigationInfo::Bind() // case 0x20: case 0x38: g_bProjectionDirty = 1; break; } // return 1; // Avatar size and visibility limit feed the near and far planes. -bool CNavigationInfo::OnSetProperty(const PRD* pprd, const void* pvValue) +bool CNavigationInfo::OnSetProperty(const PRD* prop, const void* value) { - int field = PTR2INT(pprd->pbOffset); + int field = PTR2INT(prop->pbOffset); if (field == offsetof(m_isBound)) { - if (*(const bool*)pvValue) + if (*(const bool*)value) Bind(); } else if (field == offsetof(m_avatarSize) || field == offsetof(m_visibilityLimit)) diff --git a/theseus/render/asset_loader.h b/theseus/render/asset_loader.h index 340272a..0590eeb 100644 --- a/theseus/render/asset_loader.h +++ b/theseus/render/asset_loader.h @@ -1,16 +1,14 @@ -// asset_loader.h: mesh, texture, and image asset types loaded from a -// CXipFile or directly from disk. Mirrors asset_loader.cpp's consolidation: -// the underlying data formats here (MESHFILEHEADER, CTexture surfaces, -// image blits) all share the same archive parsing path. +// asset_loader.h: meshes and textures, read from a level's XIP or straight +// from disk. Bodies in render/asset_loader.cpp, binary notes in +// docs/decomp/AssetLoader.md. #pragma once #include "node.h" -// ========================================================================= -// Mesh file format and core mesh types -// ========================================================================= +class CXipFile; +// Header at the front of a .xm mesh file. struct MESHFILEHEADER { DWORD dwPrimitiveType; @@ -21,26 +19,28 @@ struct MESHFILEHEADER DWORD dwIndexCount; }; -// Abstract base used by both standalone CMesh and CMeshRef-style instances -// that share GPU buffers across an archive. +// What a mesh node draws: either a mesh with its own buffers or a slice of +// buffers its archive shares. class CMeshCore { public: - virtual void Render(bool bSetFVF = true) = 0; + virtual void Render(bool setFVF = true) = 0; virtual DWORD GetFVF() const = 0; // Mesh nodes delete their CMesh through this type; without it the buffers leaked. virtual ~CMeshCore() {} }; +// A mesh that owns its vertex and index buffers. class CMesh : public CMeshCore { + friend class CIndexedFaceSet; public: CMesh(); virtual ~CMesh(); - bool Load(const TCHAR* szFilePath); - bool Create(HANDLE hFile); - void Render(bool bSetFVF = true); + bool Load(const TCHAR* path); + bool Create(HANDLE file); + void Render(bool setFVF = true); DWORD GetFVF() const; int m_nFaceCount; @@ -51,80 +51,66 @@ class CMesh : public CMeshCore int m_nVertexStride; IDirect3DVertexBuffer8* m_vertexBuffer; IDirect3DIndexBuffer8* m_indexBuffer; - - friend class CIndexedFaceSet; }; -// One renderable mesh that lives inside a CXipFile's shared mesh -// buffer pool. The CMeshRef itself is tiny -- it just holds the index -// of the buffer in the parent archive plus the slice within it; the -// actual GPU vertex/index data is owned by the archive's m_meshBuffers -// array. Many CMeshRefs can share one buffer pair. +// A range of primitives inside one of the archive's shared buffer pairs. class CMeshRef : public CMeshCore { public: - void Render(bool bSetFVF = true); + void Render(bool setFVF = true); DWORD GetFVF() const; - class CXipFile* m_xipFile; + CXipFile* m_xipFile; int m_meshBufferIndex; - int m_firstIndex; int m_primitiveCount; }; -extern CMesh* LoadMesh(const TCHAR* szFilePath); -extern CMesh* MakeSphere(float nRadius, int nSlices, int nStacks); +extern CMesh* LoadMesh(const TCHAR* path); +extern CMesh* MakeSphere(float radius, int slices, int stacks); -// ========================================================================= -// Texture loading and texture-bearing scene nodes -// ========================================================================= - -extern LPDIRECT3DTEXTURE8 LoadTexture(const TCHAR* szURL, UINT width, UINT height); -extern LPDIRECT3DTEXTURE8 ParseTexture(const TCHAR* szURL, const BYTE* pbContent, int cbContent, UINT width=0, UINT height=0); +extern LPDIRECT3DTEXTURE8 LoadTexture(const TCHAR* url, UINT width, UINT height); +extern LPDIRECT3DTEXTURE8 ParseTexture(const TCHAR* url, const BYTE* data, int size, UINT width = 0, UINT height = 0); +// A texture surface a node can hand to its shape. class CTexture : public CNode { - DECLARE_NODE(CTexture, CNode); + DECLARE_NODE(CTexture, CNode) + DECLARE_NODE_PROPS() public: CTexture(); ~CTexture(); + virtual bool Create(int w, int h); + LPDIRECT3DTEXTURE8 GetTextureSurface(); + bool m_repeatS; bool m_repeatT; bool m_titleImage; - D3DFORMAT m_format; LPDIRECT3DTEXTURE8 m_surface; int m_nImageWidth; int m_nImageHeight; - - virtual bool Create(int nWidth, int nHeight); - - LPDIRECT3DTEXTURE8 GetTextureSurface(); - - DECLARE_NODE_PROPS() }; +// A texture loaded from a url. Every one sits on a list for reloads. class CImageTexture : public CTexture { - DECLARE_NODE(CImageTexture, CTexture); + DECLARE_NODE(CImageTexture, CTexture) + DECLARE_NODE_PROPS() public: CImageTexture(); ~CImageTexture(); + bool OnSetProperty(const PRD* prop, const void* value); + LPDIRECT3DTEXTURE8 GetTextureSurface(); + void Load(const TCHAR* url); + + static CImageTexture* c_pFirstImageTexture; + TCHAR* m_url; bool m_alpha; bool m_fromfile; - - LPDIRECT3DTEXTURE8 GetTextureSurface(); - bool OnSetProperty(const PRD* pprd, const void* pvValue); - - void Load(const TCHAR* szURL); bool m_dirty; - - static CImageTexture* c_pFirstImageTexture; CImageTexture* m_nextImageTexture; - - DECLARE_NODE_PROPS() }; diff --git a/theseus/render/camera.cpp b/theseus/render/camera.cpp index 1d659d8..d6bda37 100755 --- a/theseus/render/camera.cpp +++ b/theseus/render/camera.cpp @@ -104,16 +104,16 @@ void CCamera::UpdateViewMatrix() // newPos = *p; newRot = *q; oldPos = position; oldRot = orientation; // start = now; duration = secs; // if (secs <= 0.0) { position = newPos; orientation = newRot; } -void CCamera::Set(const D3DXVECTOR3* pPosition, const D3DXQUATERNION* pOrientation, float nSeconds/*=0.0f*/) +void CCamera::Set(const D3DXVECTOR3* pos, const D3DXQUATERNION* rot, float dt/*=0.0f*/) { - m_newPosition = *pPosition; - m_newOrientation = *pOrientation; + m_newPosition = *pos; + m_newOrientation = *rot; m_oldPosition = m_position; m_oldOrientation = m_orientation; m_nStartTime = TheseusGetNow(); - m_nDeltaTime = nSeconds; + m_nDeltaTime = dt; - if (nSeconds > 0.0f) + if (dt > 0.0f) return; m_position = m_newPosition; @@ -130,7 +130,7 @@ void CCamera::Set(const D3DXVECTOR3* pPosition, const D3DXQUATERNION* pOrientati // } // UpdateViewMatrix(); // It never calls CNode::Advance. -void CCamera::Advance(float nSeconds) +void CCamera::Advance(float dt) { if (m_nDeltaTime > 0.0f) { @@ -201,9 +201,9 @@ CCameraPath::~CCameraPath() // if (orientation) rot = orientation->Interpolate(t); // theCamera.Set(&pos, &rot, 0); // Paths are authored in the right handed scene, hence the z flip. -void CCameraPath::Advance(float nSeconds) +void CCameraPath::Advance(float dt) { - CNode::Advance(nSeconds); + CNode::Advance(dt); if (!m_isActive) return; @@ -237,9 +237,9 @@ void CCameraPath::Advance(float nSeconds) // Reconstructed from 5960 retail XBE @ 0x00050c90. Ghidra decompile: // if (prd->offset == 0x20) start = now; return 1; // Writing isActive either way restarts the clock. -bool CCameraPath::OnSetProperty(const PRD* pprd, const void* pvValue) +bool CCameraPath::OnSetProperty(const PRD* prop, const void* value) { - if (PTR2INT(pprd->pbOffset) == offsetof(m_isActive)) + if (PTR2INT(prop->pbOffset) == offsetof(m_isActive)) m_startTime = TheseusGetNow(); return true; @@ -248,9 +248,9 @@ bool CCameraPath::OnSetProperty(const PRD* pprd, const void* pvValue) // CCameraPath::Activate(bBackwards) // The binary inlines this into CLevel's arrival code (see SceneGroups.md): // isActive = 1; start = now; backward = bBackwards; -void CCameraPath::Activate(bool bBackwards) +void CCameraPath::Activate(bool backwards) { m_isActive = true; m_startTime = TheseusGetNow(); - m_backward = bBackwards; + m_backward = backwards; } diff --git a/theseus/render/camera.h b/theseus/render/camera.h index 20359f9..6c6c051 100755 --- a/theseus/render/camera.h +++ b/theseus/render/camera.h @@ -1,55 +1,51 @@ -// camera.h: CCamera node declaration. Camera position, orientation, and -// view matrix construction. Companion to render/camera.cpp. +// camera.h: the one scene camera and the paths that fly it between levels. +// Bodies in render/camera.cpp; field offsets in docs/decomp/Camera.md. #pragma once +// Set() starts a timed move from where the camera is to a new pose; +// Advance() eases along it and UpdateViewMatrix() loads the result. class CCamera : public CNode { DECLARE_NODE(CCamera, CNode) + DECLARE_NODE_PROPS() public: CCamera(); ~CCamera(); - char* m_mode; - CNode* m_lookat; - - bool m_bNoisy; - - DECLARE_NODE_PROPS() - - + void Advance(float dt); void Reset(); - - void Set(const D3DXVECTOR3* pPosition, const D3DXQUATERNION* pOrientation, float nSeconds = 0.0f); - + void Set(const D3DXVECTOR3* pos, const D3DXQUATERNION* rot, float dt = 0.0f); void UpdateViewMatrix(); - void Advance(float nSeconds); + char* m_mode; + CNode* m_lookat; + bool m_bNoisy; D3DXVECTOR3 m_position; D3DXQUATERNION m_orientation; - - D3DXVECTOR3 m_oldPosition; + D3DXVECTOR3 m_oldPosition; // where the move started D3DXQUATERNION m_oldOrientation; - - D3DXVECTOR3 m_newPosition; + D3DXVECTOR3 m_newPosition; // where it ends D3DXQUATERNION m_newOrientation; - XTIME m_nStartTime; float m_nDeltaTime; - D3DXVECTOR3 m_actualPosition; }; +// Drives theCamera from a position and an orientation interpolator over +// m_interval seconds, either way along the path. class CCameraPath : public CNode { DECLARE_NODE(CCameraPath, CNode) + DECLARE_NODE_PROPS() public: CCameraPath(); ~CCameraPath(); - void Advance(float nSeconds); - bool OnSetProperty(const PRD* pprd, const void* pvValue); + void Advance(float dt); + bool OnSetProperty(const PRD* prop, const void* value); + void Activate(bool backwards); float m_interval; bool m_isActive; @@ -57,12 +53,8 @@ class CCameraPath : public CNode CNode* m_position; CNode* m_orientation; - void Activate(bool bBackwards); - protected: XTIME m_startTime; - - DECLARE_NODE_PROPS() }; extern CCamera theCamera; diff --git a/theseus/render/node.h b/theseus/render/node.h index 95886b5..b0caaca 100755 --- a/theseus/render/node.h +++ b/theseus/render/node.h @@ -1,140 +1,31 @@ -// node.h: scene-graph base classes (CObject, CNode, CNodeClass, -// CNodeArray, CClass, CInstance, CTimeDepNode), reflection macros -// (DECLARE_NODE / IMPLEMENT_NODE / NODE_PROP / NODE_FUN), and the -// CDefine / CNameSpace lookup primitives. Companion to -// render/node_system.cpp. +// node.h: the object model every scene node and script value sits on. +// Reflection tables (PRD for properties, FND for script functions), the +// CObject / CNode bases, groups, script classes and instances. Bodies live +// in render/node_system.cpp; the binary write-up is docs/decomp/Node.md. +// +// Layouts below are checked against the 5960 retail XBE's constructors and +// factories (sizes are the operator new argument, offsets are the stores): +// CObject 0x14: vtbl, m_nRefCount 0x04, m_obj 0x08, m_parent 0x0c, m_members 0x10 +// CNode 0x1c: m_behavior 0x14, m_visible 0x18 +// CGroup 0x44: m_children 0x1c, m_bboxCenter 0x28, m_bboxSize 0x34, flags 0x40/0x41 +// CInstance 0x54: m_class 0x44, m_vars 0x48 +// CTimeDepNode 0x30: m_loop 0x1c, m_startTime 0x20, m_stopTime 0x24, +// m_isActive 0x28, m_lastStartTime 0x2c +// CNodeClass 0x2c: name 0x14, size 0x18, factory 0x1c, base 0x20, props 0x24, next 0x28 +// CClass: m_url 0x2c, m_file 0x30, m_nVarCount 0x68 +// CProperty: m_node 0x14, m_pprd 0x18 +// CNodeArray: length 0, alloc 4, pointers 8. Value arrays: alloc 0, size 4, data 8. +// The CObject vtable order matches the binary through Deref (slot 9, +0x24): +// dtor, GetPropMap, OnSetProperty, AddRef, Release, GetFunctionMap, +// GetNodeClass, ToNum, ToStr, Deref. CFunction carries m_name, which 5960 +// doesn't have (its code size sits at 0x14). #pragma once #include "activefile.h" -class CNode; - -// One entry in a CNameSpace: a name string mapped to a CNode pointer. -// The string is stored inline at the end of the struct via the placement- -// new size+cchName overload below. -struct CDefine -{ - CDefine* m_next; - CNode* m_node; - TCHAR m_name[ANYSIZE_ARRAY]; - -#pragma push_macro("new") -#undef new - void * operator new(size_t sz, int cchName) - { - return ::operator new(sz + cchName * sizeof(TCHAR)); - } -#pragma pop_macro("new") -}; - -// Singly-linked map of name -> CNode used by the script compiler for DEF/USE -// bindings and by the runtime for member lookups. New entries are pushed at -// the head; lookup walks linearly. Cheap because each instance only sees a -// handful of entries in practice. -struct CNameSpace -{ - CNameSpace(); - ~CNameSpace(); - - bool Define(const TCHAR* pchName, int cchName, CNode* pNode); - CNode* Lookup(const TCHAR* pchName, int cchName); - CDefine* Lookup(CNode* pNode); - CDefine* Get(const TCHAR* pchName, int cchName); - CDefine* Add(const TCHAR* pchName, int cchName); - - CDefine* m_firstDefine; -}; - -struct BBox -{ - D3DXVECTOR3 center; - D3DXVECTOR3 size; -}; - - - -class CIntArray -{ -public: - CIntArray(); - ~CIntArray(); - - void SetSize(int nSize); - - int m_nAlloc; - int m_nSize; - int* m_value; -}; - - - -class CNumArray -{ -public: - CNumArray(); - ~CNumArray(); - - void SetSize(int nSize); - - int m_nAlloc; - int m_nSize; - float* m_value; -}; - - - -class CVec2Array -{ -public: - CVec2Array(); - ~CVec2Array(); - - void SetSize(int nSize); - - int m_nAlloc; - int m_nSize; - D3DXVECTOR2* m_value; -}; - - - -class CVec3Array -{ -public: - CVec3Array(); - ~CVec3Array(); - - void SetSize(int nSize); - - int m_nAlloc; - int m_nSize; - D3DXVECTOR3* m_value; -}; - - - -class CVec4Array -{ -public: - CVec4Array(); - ~CVec4Array(); - - void SetSize(int nSize); - - int m_nAlloc; - int m_nSize; - D3DXVECTOR4* m_value; -}; - - - -// MSVC: without __single_inheritance, forward-declared classes get "unknown -// inheritance" member-function-pointer representation (24 bytes on x64). -// Derived classes that ARE fully defined use single-inheritance (8 bytes). -// The NODE_FUN macros' member-function-pointer reinterpretation then writes -// 8 bytes into a 24-byte slot, leaving the this-adjustment as garbage -> crash. -// Xbox i386 MSVC sizes both at 8 bytes, but adding the hint costs nothing. +// MSVC x64 gives member pointers of a forward-declared class the 24 byte +// "unknown inheritance" form, and the FND casts only fill 8 of it. Pin both. #ifdef _MSC_VER class __single_inheritance CObject; class __single_inheritance CNode; @@ -148,25 +39,31 @@ class CStrObject; class CSurfx; class CFunction; class CRunner; +struct TAGID; -#define objUndefined 0 -#define objNull 1 -#define objNumber 2 -#define objString 3 -#define objVariable 4 -#define objNode 5 -#define objClass 6 -#define objNodeArray 7 -#define objFunctionRef 8 -#define objMember 9 -#define objMemberVar 10 -#define objInstance 11 -#define objUse 12 -#define objFunction 13 -#define objMemberFunction 14 -#define objArray 15 -#define objVec3 16 +// What kind of value a CObject is (m_obj). Scripts and the VM switch on these. +enum +{ + objUndefined, + objNull, + objNumber, + objString, + objVariable, + objNode, + objClass, + objNodeArray, + objFunctionRef, + objMember, + objMemberVar, + objInstance, + objUse, + objFunction, + objMemberFunction, + objArray, + objVec3 +}; +// Storage kind of a reflected property. The parser picks its reader by this. enum PROP_TYPE { pt_null, @@ -188,9 +85,8 @@ enum PROP_TYPE pt_vec4array }; - -// PRoperty Descriptor -// +// One property: where it lives in the object, its kind and its script name. +// Entry 0 of every table points at the base class table instead. struct PRD { const void* pbOffset; @@ -198,81 +94,114 @@ struct PRD const TCHAR* szName; }; +// Signature ids are the case numbers in CObject::Call. Letters: return kind +// first, then the arguments (v void, i int, n float, s string, o object). +// 24 and up are ones Theseus added. +enum +{ + sig_default, + sig_vv, + sig_iv, + sig_ii, + sig_si, + sig_ss, + sig_isi, + sig_sii, + sig_sv, + sig_nv, + sig_nn, + sig_nnn, + sig_vs, + sig_vss, + sig_vi, + sig_ov, + sig_os, + sig_oo, + sig_vii, + sig_vn, + sig_vnn, + sig_vo, + sig_vnnn, + sig_vnnnn, + sig_iii, + sig_is, + sig_viis, + sig_ni, + sig_vis, + sig_iis +}; - -// Member Functions... - +// Member pointer shapes, one per signature. The table stores them all as NODE_PFN. typedef CObject* (__cdecl CObject::*NODE_PFN)(void); - -#define sig_default 0 -#define sig_vv 1 -#define sig_iv 2 -#define sig_ii 3 -#define sig_si 4 -#define sig_ss 5 -#define sig_isi 6 -#define sig_sii 7 -#define sig_sv 8 -#define sig_nv 9 -#define sig_nn 10 -#define sig_nnn 11 -#define sig_vs 12 -#define sig_vss 13 -#define sig_vi 14 -#define sig_ov 15 -#define sig_os 16 -#define sig_oo 17 -#define sig_vii 18 -#define sig_vn 19 -#define sig_vnn 20 -#define sig_vo 21 -#define sig_vnnn 22 -#define sig_vnnnn 23 -#define sig_iii 24 -#define sig_is 25 -#define sig_viis 26 -#define sig_ni 27 -#define sig_vis 28 -#define sig_iis 29 - +typedef CObject* (CObject::*NODEFN_default)(CObject** rgparam, int nParam); +typedef void (CObject::*NODEFN_vv)(void); +typedef void (CObject::*NODEFN_vi)(int); +typedef void (CObject::*NODEFN_vii)(int, int); +typedef void (CObject::*NODEFN_vis)(int, const TCHAR*); +typedef void (CObject::*NODEFN_viis)(int, int, const TCHAR*); +typedef void (CObject::*NODEFN_vs)(const TCHAR*); +typedef void (CObject::*NODEFN_vss)(const TCHAR*, const TCHAR*); +typedef void (CObject::*NODEFN_vn)(float); +typedef void (CObject::*NODEFN_vnn)(float, float); +typedef void (CObject::*NODEFN_vnnn)(float, float, float); +typedef void (CObject::*NODEFN_vnnnn)(float, float, float, float); +typedef void (CObject::*NODEFN_vo)(CObject*); +typedef int (CObject::*NODEFN_iv)(void); +typedef int (CObject::*NODEFN_ii)(int); +typedef int (CObject::*NODEFN_iii)(int, int); +typedef int (CObject::*NODEFN_is)(const TCHAR*); +typedef int (CObject::*NODEFN_isi)(const TCHAR*, int); +typedef int (CObject::*NODEFN_iis)(int, const TCHAR*); +typedef float (CObject::*NODEFN_nv)(void); +typedef float (CObject::*NODEFN_ni)(int); +typedef float (CObject::*NODEFN_nn)(float); +typedef float (CObject::*NODEFN_nnn)(float, float); +typedef CStrObject* (CObject::*NODEFN_sv)(void); +typedef CStrObject* (CObject::*NODEFN_si)(int); +typedef CStrObject* (CObject::*NODEFN_sii)(int, int); +typedef CStrObject* (CObject::*NODEFN_ss)(const TCHAR*); +typedef CObject* (CObject::*NODEFN_ov)(void); +typedef CObject* (CObject::*NODEFN_os)(const TCHAR*); +typedef CObject* (CObject::*NODEFN_oo)(CObject*); + +// pfn has to stay first: the tables brace-initialize through it. union FSIG { NODE_PFN pfn; - CObject* (CObject::*pfn_default)(CObject** rgparam, int nParam); - void (CObject::*pfn_vv)(void); - void (CObject::*pfn_vi)(int); - void (CObject::*pfn_vii)(int, int); - void (CObject::*pfn_vis)(int, const TCHAR*); - void (CObject::*pfn_viis)(int, int, const TCHAR*); - int (CObject::*pfn_iv)(void); - int (CObject::*pfn_ii)(int); - int (CObject::*pfn_is)(const TCHAR*); - int (CObject::*pfn_isi)(const TCHAR*, int); - int (CObject::*pfn_iii)(int, int); - int (CObject::*pfn_iis)(int, const TCHAR*); - CStrObject* (CObject::*pfn_sv)(void); - CStrObject* (CObject::*pfn_si)(int); - CStrObject* (CObject::*pfn_sii)(int, int); - CStrObject* (CObject::*pfn_ss)(const TCHAR*); - void (CObject::*pfn_vs)(const TCHAR*); - void (CObject::*pfn_vss)(const TCHAR*, const TCHAR*); - float (CObject::*pfn_nv)(void); - float (CObject::*pfn_nn)(float); - float (CObject::*pfn_nnn)(float, float); - void (CObject::*pfn_vn)(float); - void (CObject::*pfn_vnn)(float, float); - void (CObject::*pfn_vnnn)(float, float, float); - void (CObject::*pfn_vnnnn)(float, float, float, float); - CObject* (CObject::*pfn_ov)(void); - CObject* (CObject::*pfn_os)(const TCHAR*); - CObject* (CObject::*pfn_oo)(CObject* pObject); - void (CObject::*pfn_vo)(CObject* pObject); - float (CObject::*pfn_ni)(int); + NODEFN_default pfn_default; + NODEFN_vv pfn_vv; + NODEFN_vi pfn_vi; + NODEFN_vii pfn_vii; + NODEFN_vis pfn_vis; + NODEFN_viis pfn_viis; + NODEFN_vs pfn_vs; + NODEFN_vss pfn_vss; + NODEFN_vn pfn_vn; + NODEFN_vnn pfn_vnn; + NODEFN_vnnn pfn_vnnn; + NODEFN_vnnnn pfn_vnnnn; + NODEFN_vo pfn_vo; + NODEFN_iv pfn_iv; + NODEFN_ii pfn_ii; + NODEFN_iii pfn_iii; + NODEFN_is pfn_is; + NODEFN_isi pfn_isi; + NODEFN_iis pfn_iis; + NODEFN_nv pfn_nv; + NODEFN_ni pfn_ni; + NODEFN_nn pfn_nn; + NODEFN_nnn pfn_nnn; + NODEFN_sv pfn_sv; + NODEFN_si pfn_si; + NODEFN_sii pfn_sii; + NODEFN_ss pfn_ss; + NODEFN_ov pfn_ov; + NODEFN_os pfn_os; + NODEFN_oo pfn_oo; }; -// FuNction Descriptors -// +// One script-callable function: the method, its signature id and its name. struct FND { union FSIG pfn; @@ -280,146 +209,179 @@ struct FND const TCHAR* szName; }; +// FND tables. The .cpp defines _FND_CLASS to the class whose methods follow. #define START_NODE_FUN(className, baseClassName) \ FND className::c_rgfnd [] = { #define END_NODE_FUN() \ { NULL, 0, NULL } }; -#define NODE_FUN(name) \ - { (NODE_PFN)(CObject* (CObject::*)(CObject**, int))&_FND_CLASS::name, sig_default, _T(#name) }, - -#define NODE_FUN_VV(name) \ - { (NODE_PFN)(void (CObject::*)(void))&_FND_CLASS::name, sig_vv, _T(#name) }, - -#define NODE_FUN_VI(name) \ - { (NODE_PFN)(void (CObject::*)(int))&_FND_CLASS::name, sig_vi, _T(#name) }, - -#define NODE_FUN_VII(name) \ - { (NODE_PFN)(void (CObject::*)(int, int))&_FND_CLASS::name, sig_vii, _T(#name) }, - -#define NODE_FUN_VIIS(name) \ - { (NODE_PFN)(void (CObject::*)(int, int, const TCHAR*))&_FND_CLASS::name, sig_viis, _T(#name) }, - -#define NODE_FUN_VIS(name) \ - { (NODE_PFN)(void (CObject::*)(int, const TCHAR*))&_FND_CLASS::name, sig_vis, _T(#name) }, - -#define NODE_FUN_IV(name) \ - { (NODE_PFN)(int (CObject::*)(void))&_FND_CLASS::name, sig_iv, _T(#name) }, - -#define NODE_FUN_II(name) \ - { (NODE_PFN)(int (CObject::*)(int))&_FND_CLASS::name, sig_ii, _T(#name) }, - -#define NODE_FUN_III(name) \ - { (NODE_PFN)(int (CObject::*)(int, int))&_FND_CLASS::name, sig_iii, _T(#name) }, - -#define NODE_FUN_IIS(name) \ - { (NODE_PFN)(int (CObject::*)(int, const TCHAR*))&_FND_CLASS::name, sig_iis, _T(#name) }, - -#define NODE_FUN_SI(name) \ - { (NODE_PFN)(CStrObject* (CObject::*)(int))&_FND_CLASS::name, sig_si, _T(#name) }, - -#define NODE_FUN_SII(name) \ - { (NODE_PFN)(CStrObject* (CObject::*)(int, int))&_FND_CLASS::name, sig_sii, _T(#name) }, - -#define NODE_FUN_SS(name) \ - { (NODE_PFN)(CStrObject* (CObject::*)(const TCHAR*))&_FND_CLASS::name, sig_ss, _T(#name) }, - -#define NODE_FUN_SV(name) \ - { (NODE_PFN)(CStrObject* (CObject::*)(void))&_FND_CLASS::name, sig_sv, _T(#name) }, - -#define NODE_FUN_VS(name) \ - { (NODE_PFN)(void (CObject::*)(const TCHAR*))&_FND_CLASS::name, sig_vs, _T(#name) }, - -#define NODE_FUN_VSS(name) \ - { (NODE_PFN)(void (CObject::*)(const TCHAR*, const TCHAR*))&_FND_CLASS::name, sig_vss, _T(#name) }, - -#define NODE_FUN_NV(name) \ - { (NODE_PFN)(float (CObject::*)(void))&_FND_CLASS::name, sig_nv, _T(#name) }, - -#define NODE_FUN_NI(name) \ - { (NODE_PFN)(float (CObject::*)(int))&_FND_CLASS::name, sig_ni, _T(#name) }, +#define NODE_FUN_TYPED(name, sigId, pfnType) \ + { (NODE_PFN)(pfnType)&_FND_CLASS::name, sigId, _T(#name) }, + +#define NODE_FUN(name) NODE_FUN_TYPED(name, sig_default, NODEFN_default) +#define NODE_FUN_VV(name) NODE_FUN_TYPED(name, sig_vv, NODEFN_vv) +#define NODE_FUN_VI(name) NODE_FUN_TYPED(name, sig_vi, NODEFN_vi) +#define NODE_FUN_VII(name) NODE_FUN_TYPED(name, sig_vii, NODEFN_vii) +#define NODE_FUN_VIS(name) NODE_FUN_TYPED(name, sig_vis, NODEFN_vis) +#define NODE_FUN_VIIS(name) NODE_FUN_TYPED(name, sig_viis, NODEFN_viis) +#define NODE_FUN_VS(name) NODE_FUN_TYPED(name, sig_vs, NODEFN_vs) +#define NODE_FUN_VSS(name) NODE_FUN_TYPED(name, sig_vss, NODEFN_vss) +#define NODE_FUN_VN(name) NODE_FUN_TYPED(name, sig_vn, NODEFN_vn) +#define NODE_FUN_VNN(name) NODE_FUN_TYPED(name, sig_vnn, NODEFN_vnn) +#define NODE_FUN_VNNN(name) NODE_FUN_TYPED(name, sig_vnnn, NODEFN_vnnn) +#define NODE_FUN_VNNNN(name) NODE_FUN_TYPED(name, sig_vnnnn, NODEFN_vnnnn) +#define NODE_FUN_VO(name) NODE_FUN_TYPED(name, sig_vo, NODEFN_vo) +#define NODE_FUN_IV(name) NODE_FUN_TYPED(name, sig_iv, NODEFN_iv) +#define NODE_FUN_II(name) NODE_FUN_TYPED(name, sig_ii, NODEFN_ii) +#define NODE_FUN_III(name) NODE_FUN_TYPED(name, sig_iii, NODEFN_iii) +#define NODE_FUN_IS(name) NODE_FUN_TYPED(name, sig_is, NODEFN_is) +#define NODE_FUN_IIS(name) NODE_FUN_TYPED(name, sig_iis, NODEFN_iis) +#define NODE_FUN_NV(name) NODE_FUN_TYPED(name, sig_nv, NODEFN_nv) +#define NODE_FUN_NI(name) NODE_FUN_TYPED(name, sig_ni, NODEFN_ni) +#define NODE_FUN_NN(name) NODE_FUN_TYPED(name, sig_nn, NODEFN_nn) +#define NODE_FUN_NNN(name) NODE_FUN_TYPED(name, sig_nnn, NODEFN_nnn) +#define NODE_FUN_SV(name) NODE_FUN_TYPED(name, sig_sv, NODEFN_sv) +#define NODE_FUN_SI(name) NODE_FUN_TYPED(name, sig_si, NODEFN_si) +#define NODE_FUN_SII(name) NODE_FUN_TYPED(name, sig_sii, NODEFN_sii) +#define NODE_FUN_SS(name) NODE_FUN_TYPED(name, sig_ss, NODEFN_ss) +#define NODE_FUN_OV(name) NODE_FUN_TYPED(name, sig_ov, NODEFN_ov) +#define NODE_FUN_OS(name) NODE_FUN_TYPED(name, sig_os, NODEFN_os) +#define NODE_FUN_OO(name) NODE_FUN_TYPED(name, sig_oo, NODEFN_oo) +// Tagged sig_is, so Call passes the string only. Nothing uses it yet. +#define NODE_FUN_ISI(name) NODE_FUN_TYPED(name, sig_is, NODEFN_isi) + +// PRD tables. Entry 0 chains to the base class; the null-object member +// address is how a constant initializer gets a field offset here. +#define START_NODE_PROPS(className, baseClassName) \ + PRD className::m_rgprd [] = { \ + { &baseClassName::m_rgprd[0], pt_null, _T(#className) }, -#define NODE_FUN_NN(name) \ - { (NODE_PFN)(float (CObject::*)(float))&_FND_CLASS::name, sig_nn, _T(#name) }, +#define END_NODE_PROPS() \ + { NULL, pt_null, NULL } }; -#define NODE_FUN_NNN(name) \ - { (NODE_PFN)(float (CObject::*)(float, float))&_FND_CLASS::name, sig_nnn, _T(#name) }, +#define NODE_PROP(theType, theClass, name) \ + { &((theClass*)0)->m_##name, theType, _T(#name) }, -#define NODE_FUN_VN(name) \ - { (NODE_PFN)(void (CObject::*)(float))&_FND_CLASS::name, sig_vn, _T(#name) }, +// Per-class declarations. Each one leaves the class body in public:. +#define NODE_CLASS(className) (&className::class##className) -#define NODE_FUN_VNN(name) \ - { (NODE_PFN)(void (CObject::*)(float, float))&_FND_CLASS::name, sig_vnn, _T(#name) }, +#define DECLARE_NODE(className, baseClassName) \ +public: \ + static CNodeClass class##className; \ + static CObject* CreateNode(); \ + virtual CNodeClass* GetNodeClass() const; -#define NODE_FUN_VNNN(name) \ - { (NODE_PFN)(void (CObject::*)(float, float, float))&_FND_CLASS::name, sig_vnnn, _T(#name) }, +#define DECLARE_NODE_PROPS() \ +public: \ + static PRD m_rgprd []; \ + virtual const PRD* GetPropMap() const { return m_rgprd; } -#define NODE_FUN_VNNNN(name) \ - { (NODE_PFN)(void (CObject::*)(float, float, float, float))&_FND_CLASS::name, sig_vnnnn, _T(#name) }, +#define DECLARE_NODE_FUNCTIONS() \ +public: \ + static FND c_rgfnd []; \ + virtual FND* GetFunctionMap() const { return c_rgfnd; } -#define NODE_FUN_OV(name) \ - { (NODE_PFN)(CObject* (CObject::*)(void))&_FND_CLASS::name, sig_ov, _T(#name) }, +// The class object registers itself (CNodeClass ctor links it into the list). +#define IMPLEMENT_NODE(friendlyName, className, baseClassName) \ + CObject* className::CreateNode() \ + { \ + return new className; \ + } \ + CNodeClass className::class##className(_T(friendlyName), sizeof (class className), \ + className::CreateNode, NODE_CLASS(baseClassName), className::m_rgprd); \ + CNodeClass* className::GetNodeClass() const \ + { \ + return NODE_CLASS(className); \ + } -#define NODE_FUN_OS(name) \ - { (NODE_PFN)(CObject* (CObject::*)(const TCHAR*))&_FND_CLASS::name, sig_os, _T(#name) }, +// Growable property arrays (MFInt32, MFFloat, MFVec2f/3f/4f). SetSize lives +// in node_system.cpp. +#define DECLARE_VALUE_ARRAY(className, elemType) \ + class className \ + { \ + public: \ + className(); \ + ~className(); \ + void SetSize(int nSize); \ + int m_nAlloc; \ + int m_nSize; \ + elemType* m_value; \ + }; + +DECLARE_VALUE_ARRAY(CIntArray, int) +DECLARE_VALUE_ARRAY(CNumArray, float) +DECLARE_VALUE_ARRAY(CVec2Array, D3DXVECTOR2) +DECLARE_VALUE_ARRAY(CVec3Array, D3DXVECTOR3) +DECLARE_VALUE_ARRAY(CVec4Array, D3DXVECTOR4) -#define NODE_FUN_OO(name) \ - { (NODE_PFN)(CObject* (CObject::*)(CObject*))&_FND_CLASS::name, sig_oo, _T(#name) }, +struct BBox +{ + D3DXVECTOR3 center; + D3DXVECTOR3 size; +}; -#define NODE_FUN_VO(name) \ - { (NODE_PFN)(void (CObject::*)(CObject*))&_FND_CLASS::name, sig_vo, _T(#name) }, +// A DEF name and its node. The name is allocated inline past the struct. +struct CDefine +{ + CDefine* m_next; + CNode* m_node; + TCHAR m_name[ANYSIZE_ARRAY]; -#define NODE_FUN_IS(name) \ - { (NODE_PFN)(int (CObject::*)(const TCHAR*))&_FND_CLASS::name, sig_is, _T(#name) }, +#pragma push_macro("new") +#undef new + void* operator new(size_t cb, int cchName) + { + return ::operator new(cb + cchName * sizeof (TCHAR)); + } +#pragma pop_macro("new") +}; -#define NODE_FUN_ISI(name) \ - { (NODE_PFN)(int (CObject::*)(const TCHAR*, int))&_FND_CLASS::name, sig_is, _T(#name) }, +// DEF/USE names for one scope, newest first, searched front to back. +struct CNameSpace +{ + CNameSpace(); + ~CNameSpace(); + bool Define(const TCHAR* name, int nameLen, CNode* node); + CDefine* Add(const TCHAR* name, int nameLen); + CDefine* Get(const TCHAR* name, int nameLen); + CNode* Lookup(const TCHAR* name, int nameLen); + CDefine* Lookup(CNode* node); + CDefine* m_firstDefine; +}; +// Children / MFNode storage. Out of range reads give NULL, writes are ignored. class CNodeArray { public: CNodeArray(); ~CNodeArray(); - void AddNode(CNode* pNode); - void RemoveNode(CNode* pNode); - - void RemoveAll(); - void ReleaseAll(); - - int GetLength() - { - return m_length; - } + int GetLength() { return m_length; } CNode* GetNode(int iNode) { - if (iNode < 0 || iNode >= m_length) - return NULL; - - return m_rgpNode[iNode]; + return (iNode >= 0 && iNode < m_length) ? m_rgpNode[iNode] : NULL; } void SetNode(int iNode, CNode* pNode) { - if (iNode < 0 || iNode >= m_length) - { - ASSERT(FALSE); - return; - } - - m_rgpNode[iNode] = pNode; + if (iNode >= 0 && iNode < m_length) + m_rgpNode[iNode] = pNode; } - void Allocate(int nAlloc); - void SetLength(int nNodes); + void AddNode(CNode* node); + void RemoveNode(CNode* node); + void RemoveAll(); + void ReleaseAll(); + void Allocate(int count); + void SetLength(int count); - void Sort(int (__cdecl *pfnCompare)(const void*, const void*)) + void Sort(int (__cdecl *compare)(const void*, const void*)) { - qsort(m_rgpNode, m_length, sizeof (CNode*), pfnCompare); + qsort(m_rgpNode, m_length, sizeof (CNode*), compare); } protected: @@ -428,80 +390,71 @@ class CNodeArray CNode** m_rgpNode; }; +// Root of everything the VM touches: nodes, numbers, strings, classes. class CObject { public: CObject(); virtual ~CObject(); - static PRD m_rgprd []; static CNodeClass classCObject; static CObject* CreateNode(); + static PRD m_rgprd []; - virtual const PRD* GetPropMap() const - { return &m_rgprd[0]; } - const PRD* FindProp(const TCHAR* szName, int cchName); - - void SetProperty(const PRD* pprd, const void* pvValue, int cbValue); - virtual bool OnSetProperty(const PRD* pprd, const void* pvValue); - + virtual const PRD* GetPropMap() const { return m_rgprd; } + virtual bool OnSetProperty(const PRD* prop, const void* value); virtual void AddRef(); virtual void Release(); - - int m_nRefCount; - - int m_obj; - CObject* m_parent; - - int FindFunction(const TCHAR* pchFunction, int cchFunction); virtual FND* GetFunctionMap() const; - - virtual CNodeClass* GetNodeClass() const; - bool IsKindOf(CNodeClass* pClass) const; - virtual CNumObject* ToNum(); virtual CStrObject* ToStr(); - virtual CObject* Deref(); - virtual void Assign(CObject* pObject); + virtual void Assign(CObject* obj); + virtual CObject* Call(int index, CObject** args, int argc); + virtual CObject* Dot(CObject* obj); + virtual CObject* GetMember(const TCHAR* name, int nameLen); + virtual void Dump() const; - virtual CObject* Call(int nFunction, CObject** rgparam, int nParam); - virtual CObject* Dot(CObject* pObj); + const PRD* FindProp(const TCHAR* name, int nameLen); + void SetProperty(const PRD* prop, const void* value, int size); + int FindFunction(const TCHAR* funcName, int funcNameLen); + bool IsKindOf(CNodeClass* cls) const; - CNameSpace* m_members; - void AddMember(const TCHAR* pchName, int cchName, CObject* pObject); - void SetMember(const TCHAR* pchName, int cchName, CObject* pObject); - virtual CObject* GetMember(const TCHAR* pchName, int cchName); + void AddMember(const TCHAR* name, int nameLen, CObject* obj); + void SetMember(const TCHAR* name, int nameLen, CObject* obj); + CFunction* FindMemberFunction(const TCHAR* name, int nameLen); - CFunction* FindMemberFunction(const TCHAR* pchName, int cchName); - - virtual void Dump() const; + int m_nRefCount; + int m_obj; + CObject* m_parent; + CNameSpace* m_members; }; +// Runtime class record. Built-in node classes are static instances that +// link themselves into c_pFirstClass at startup. class CNodeClass : public CObject { public: - CNodeClass(const TCHAR* szClassName, int nObjectSize, CObject* (*pfnCreateNode)(), CNodeClass* pBaseClass, const PRD* rgprd); + CNodeClass(const TCHAR* className, int objSize, CObject* (*factory)(), CNodeClass* base, const PRD* props); ~CNodeClass(); + static CNodeClass* c_pFirstClass; + static CNodeClass* FindByName(const TCHAR* className, int classNameLen); + + CObject* CreateNode(); + const PRD* FindProp(const TCHAR* propName, int propNameLen); + const PRD* GetPropMap() const { return m_rgprd; } + const TCHAR* m_className; int m_nObjectSize; CObject* (*m_pfnCreateNode)(); CNodeClass* m_baseClass; const PRD* m_rgprd; - - CObject* CreateNode(); - - const PRD* FindProp(const TCHAR* pchPropName, int cchPropName); - const PRD* GetPropMap() const { return m_rgprd; } - - static CNodeClass* FindByName(const TCHAR* szNodeClass, int cchNodeClass); - static CNodeClass* c_pFirstClass; CNodeClass* m_nextClass; }; -// This is an entry in CObject's m_members table... +// Compiled script function: a name and its bytecode, allocated in one block. class CFunction : public CObject { public: @@ -509,220 +462,142 @@ class CFunction : public CObject ~CFunction(); TCHAR* m_name; - int m_codeSize; BYTE m_rgop[ANYSIZE_ARRAY]; #pragma push_macro("new") #undef new - void * operator new(size_t sz, int cbop) - { - return ::operator new(sz + cbop); - } + void* operator new(size_t cb, int cbCode) + { + return ::operator new(cb + cbCode); + } #pragma pop_macro("new") }; +// A script-defined class loaded from a .xap file. class CClass : public CNodeClass { public: CClass(); ~CClass(); - bool Load(const TCHAR* szURL); - bool LoadAbsURL(const TCHAR* szURL); - bool ParseFile(const TCHAR* szFileName, const TCHAR* szFile); - const TCHAR* ParseClassBody(const TCHAR* pch); - + bool Load(const TCHAR* url); + bool LoadAbsURL(const TCHAR* url); + bool ParseFile(const TCHAR* fileName, const TCHAR* text); + const TCHAR* ParseClassBody(const TCHAR* src); CNode* CreateNode(); - TCHAR* m_url; + int GetVariableCount() { return m_nVarCount; } + TCHAR* m_url; CActiveFile m_file; - CNodeArray m_instanceFunctions; - CFunction* m_constructor; - int m_nVarCount; - - int GetVariableCount() { return m_nVarCount; } }; - -#define NODE_CLASS(className) (&className::class##className) - - - -#define DECLARE_NODE_FUNCTIONS() \ -public: \ - static FND c_rgfnd []; \ - virtual FND* GetFunctionMap() const \ - { return c_rgfnd; }; - - -#define DECLARE_NODE_PROPS() \ - public: \ - static PRD m_rgprd []; \ - virtual const PRD* GetPropMap() const \ - { return &m_rgprd[0]; } - -#define DECLARE_NODE(className, baseClassName) \ -public: \ - static CNodeClass class##className; \ - virtual CNodeClass* GetNodeClass() const; \ - static CObject* CreateNode(); - -#define IMPLEMENT_NODE(friendlyName, className, baseClassName) \ - CObject* className::CreateNode() \ - { return new className; } \ - CNodeClass className::class##className( \ - _T(friendlyName), sizeof(class className), className::CreateNode, \ - NODE_CLASS(baseClassName), className::m_rgprd ); \ - CNodeClass* className::GetNodeClass() const \ - { return NODE_CLASS(className); } - - - -#define START_NODE_PROPS(className, baseClassName) \ - PRD className::m_rgprd [] = { \ - { &baseClassName::m_rgprd[0], pt_null, _T(#className) }, - -#define END_NODE_PROPS() \ - { NULL, pt_null, NULL } }; - -#define NODE_PROP(theType, theClass, name) \ - { &((theClass*)0)->m_##name, theType, _T(#name) }, - - +// Base of every scene node: a behavior script and a visible flag. class CNode : public CObject { + DECLARE_NODE(CNode, CObject) + DECLARE_NODE_PROPS() public: CNode(); virtual ~CNode(); - DECLARE_NODE_PROPS() - - CObject* Dot(CObject* pObj); - - CStrObject* ToStr(); - - static CObject* CreateNode(); - static CNodeClass classCNode; - virtual CNodeClass* GetNodeClass() const; - virtual void OnLoad(); - - virtual void Advance(float nSeconds); + virtual void Advance(float dt); virtual void Render(); - virtual void GetBBox(BBox* pBBox); + virtual void GetBBox(BBox* box); virtual float GetRadius(); #ifdef _LIGHTS - virtual void SetLight(int& nLight, D3DCOLORVALUE& ambient); + virtual void SetLight(int& lightIndex, D3DCOLORVALUE& ambient); #endif virtual const DWORD* GetPalette(); - virtual void RenderDynamicTexture(CSurfx* pSurfx); - + virtual void RenderDynamicTexture(CSurfx* surface); virtual LPDIRECT3DTEXTURE8 GetTextureSurface(); + CObject* Dot(CObject* obj); + CStrObject* ToStr(); + void Dump() const; + CRunner* m_behavior; bool m_visible; - - virtual void Dump() const; }; - - class CGroup : public CNode { DECLARE_NODE(CGroup, CNode) + DECLARE_NODE_PROPS() public: CGroup(); ~CGroup(); - CNodeArray m_children; - - D3DXVECTOR3 m_bboxCenter; - D3DXVECTOR3 m_bboxSize; - - bool m_bboxSpecified; - bool m_bboxDirty; - - void GetBBox(BBox* pBBox); + void Advance(float dt); + void Render(); + void GetBBox(BBox* box); float GetRadius(); #ifdef _LIGHTS - void SetLight(int& nLight, D3DCOLORVALUE& ambient); + void SetLight(int& lightIndex, D3DCOLORVALUE& ambient); #endif + void RenderDynamicTexture(CSurfx* surface); LPDIRECT3DTEXTURE8 GetTextureSurface(); - void Render(); - void Advance(float nSeconds); - void RenderDynamicTexture(CSurfx* pSurfx); - - DECLARE_NODE_PROPS() + CNodeArray m_children; + D3DXVECTOR3 m_bboxCenter; + D3DXVECTOR3 m_bboxSize; + bool m_bboxSpecified; + bool m_bboxDirty; }; - - +// A live object of a script class: a group plus the class's variable slots. class CInstance : public CGroup { public: - CInstance(CClass* pClass); + CInstance(CClass* cls); ~CInstance(); + CNodeClass* GetNodeClass() const; + CObject* Dot(CObject* obj); void Render(); - BYTE* Construct(); - CNodeClass* GetNodeClass() const; - - CObject* Dot(CObject* pObj); CClass* m_class; CNodeArray m_vars; }; - - +// Shared start/stop/loop clock for sensors and players. class CTimeDepNode : public CNode { DECLARE_NODE(CTimeDepNode, CNode) + DECLARE_NODE_PROPS() public: CTimeDepNode(); - bool m_loop; - float m_startTime; - float m_stopTime; - bool m_isActive; - - void Advance(float nSeconds); + void Advance(float dt); virtual void OnIsActiveChanged(); virtual void OnCycleEnded(); + bool m_loop; + float m_startTime; + float m_stopTime; + bool m_isActive; float m_lastStartTime; - - DECLARE_NODE_PROPS() }; - - - +// "node.prop" as a script value: reads and writes go through the PRD. class CProperty : public CObject { public: - CProperty(CObject* pNode, const PRD* pprd); + CProperty(CObject* node, const PRD* prop); ~CProperty(); + CObject* Deref(); + void Assign(CObject* obj); + CObject* m_node; const PRD* m_pprd; - - CObject* Deref(); - void Assign(CObject* pObject); }; - - - -struct TAGID; - - -CObject* NewNode(const TCHAR* pchNodeClass, int cchNodeClass); +CObject* NewNode(const TCHAR* className, int classNameLen); diff --git a/theseus/render/scene_groups.h b/theseus/render/scene_groups.h index 06e9933..ae73ea1 100644 --- a/theseus/render/scene_groups.h +++ b/theseus/render/scene_groups.h @@ -1,85 +1,83 @@ -// scene_groups.h: CBackground, CLevel, CViewpoint, CNavigationInfo -// declarations. CGroup is declared in node.h, CTransform in shape_render.h. -// CLayer, CInline, CSpinner, CWaver, CLayout, CSwitch, CBillboard are -// defined entirely within scene_groups.cpp. +// scene_groups.h: the scene-level nodes other files reach into: Background, +// Level, Viewpoint and NavigationInfo. The rest of scene_groups.cpp's nodes +// (Layer, Inline, Spinner, Waver, Layout, Switch, Billboard) are private to +// it. Binary notes in docs/decomp/SceneGroups.md. #pragma once +class CXipFile; + +// Backdrop behind the scene. The fade fields are Theseus's SetAlpha. class CBackground : public CNode { DECLARE_NODE(CBackground, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CBackground(); ~CBackground(); - void Advance(float nSeconds); - bool OnSetProperty(const PRD* pprd, const void* pvValue); - + void Advance(float dt); + bool OnSetProperty(const PRD* prop, const void* value); void Bind(); void RenderBackdrop(); - void SetAlpha(float a); - void DisappearAfter(float t); + void DisappearAfter(float secs); CNode* m_backdrop; D3DXVECTOR3 m_skyColor; bool m_isBound; - float m_fade; // seconds SetAlpha takes to get there XTIME m_timeAlphaStart; float m_alphaStart; float m_alphaEnd; - float m_alpha; // backdrop opacity + float m_alpha; XTIME m_timeToDisappear; - LPDIRECT3DVERTEXBUFFER8 m_vb; - - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() }; +// One dashboard area, loaded from its own XIP while you're in it. class CLevel : public CGroup { DECLARE_NODE(CLevel, CGroup) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CLevel(); ~CLevel(); - CNode* m_control; // joystick bound to this level - CNode* m_tunnel; // tunnel geometry leading here - CNode* m_path; // camera path through the tunnel - CNode* m_shell; // sphere around the level + void Advance(float dt); + void Render(); + void GoTo(); + void GoBackTo(); + + CNode* m_control; // joystick for this level + CNode* m_tunnel; // geometry on the way in + CNode* m_path; // camera path through it + CNode* m_shell; TCHAR* m_archive; bool m_unloadable; bool m_fade; - float m_timeToNextLevel; - void GoTo(); - void GoBackTo(); - - void Advance(float nSeconds); - void Render(); - protected: void Activate(); void Deactivate(); - class CXipFile* m_xipFile; + CXipFile* m_xipFile; bool m_bArrive; - - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() }; class CViewpoint : public CNode { DECLARE_NODE(CViewpoint, CNode) + DECLARE_NODE_PROPS() public: CViewpoint(); ~CViewpoint(); void OnLoad(); + bool OnSetProperty(const PRD* prop, const void* value); void Bind(); bool m_isBound; @@ -88,23 +86,21 @@ class CViewpoint : public CNode D3DXQUATERNION m_orientation; D3DXVECTOR3 m_position; TCHAR* m_description; - - bool OnSetProperty(const PRD* pprd, const void* pvValue); - - DECLARE_NODE_PROPS() }; -extern void BindViewpoint(CNode* pViewpontNode); +extern void BindViewpoint(CNode* viewpoint); class CNavigationInfo : public CNode { DECLARE_NODE(CNavigationInfo, CNode) + DECLARE_NODE_PROPS() public: CNavigationInfo(); ~CNavigationInfo(); - bool OnSetProperty(const PRD* pprd, const void* pvValue); void OnLoad(); + bool OnSetProperty(const PRD* prop, const void* value); + void Bind(); bool m_isBound; D3DXVECTOR3 m_avatarSize; @@ -113,8 +109,4 @@ class CNavigationInfo : public CNode TCHAR* m_type; float m_visibilityLimit; CNode* m_shape; - - void Bind(); - - DECLARE_NODE_PROPS() }; diff --git a/theseus/render/shape_render.h b/theseus/render/shape_render.h index a2e13d9..c317db4 100755 --- a/theseus/render/shape_render.h +++ b/theseus/render/shape_render.h @@ -1,107 +1,119 @@ -// shape_render.h: shape, mesh, and transform node declarations. -// CMeshNode, CTransform, CShape, CAppearance, CMaterial, CBox, CSphere. -// Companion to render/shape_render.cpp. +// shape_render.h: the drawable scene nodes. Shape pairs an Appearance +// (Material plus texture) with geometry; Mesh loads geometry from a file; +// Transform places, scales, spins and fades its children. Bodies in +// render/shape_render.cpp, binary notes in docs/decomp/ShapeRender.md. #pragma once +class CMeshCore; + +// Geometry from a .xm file. Every mesh node sits on one list so the loader +// can find nodes still waiting for their file. class CMeshNode : public CNode { DECLARE_NODE(CMeshNode, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CMeshNode(); ~CMeshNode(); void Render(); + virtual void Init(); + bool Initialize(); + DWORD GetFVF(); - TCHAR* m_url; - float m_falloff; - - void load(const TCHAR* szFile); + void load(const TCHAR* szFile); // script: swap the mesh file - bool Initialize(); - virtual void Init(); + static CMeshNode* c_pFirst; + TCHAR* m_url; + float m_falloff; bool m_dirty; XTIME m_renderTime; - - DWORD GetFVF(); - - class CMeshCore* m_mesh; + CMeshCore* m_mesh; bool m_ownMesh; - - static CMeshNode* c_pFirst; CMeshNode* m_next; - - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() }; +// Material and texture that apply to a shape's geometry. class CAppearance : public CNode { DECLARE_NODE(CAppearance, CNode) + DECLARE_NODE_PROPS() public: CAppearance(); ~CAppearance(); - CNode* m_material; - CNode* m_texture; - + void Advance(float dt); void Render(); - void Advance(float nSeconds); - DECLARE_NODE_PROPS() + CNode* m_material; + CNode* m_texture; }; class CShape : public CNode { DECLARE_NODE(CShape, CNode) + DECLARE_NODE_PROPS() public: CShape(); ~CShape(); - CNode* m_appearance; - CNode* m_geometry; - + void Advance(float dt); void Render(); - void GetBBox(BBox* pBBox); + void GetBBox(BBox* box); float GetRadius(); - void Advance(float nSeconds); + CNode* m_appearance; + CNode* m_geometry; D3DXVECTOR3 m_position; - - DECLARE_NODE_PROPS() }; +// VRML style material fields, folded into a D3DMATERIAL8 for drawing. class CMaterial : public CNode { DECLARE_NODE(CMaterial, CNode) + DECLARE_NODE_PROPS() public: CMaterial(); + void Render(); + float m_ambientIntensity; D3DXVECTOR3 m_diffuseColor; D3DXVECTOR3 m_emissiveColor; float m_shininess; D3DXVECTOR3 m_specularColor; float m_transparency; - D3DMATERIAL8 m_material; - - void Render(); - - DECLARE_NODE_PROPS() }; - - - +// Each animated field keeps a start and end value and the time its move +// began; Advance blends them and CalcMatrix rebuilds m_matrix. class CTransform : public CGroup { DECLARE_NODE(CTransform, CGroup) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CTransform(); - D3DXQUATERNION m_rotation; // axis/angle stored in a D3DXVECTOR4 layout + void OnLoad(); + bool OnSetProperty(const PRD* prop, const void* value); + void Advance(float dt); + void Render(); + void CalcMatrix(); + + void SetTranslation(float x, float y, float z); + void SetRotation(float x, float y, float z, float a); + void SetScale(float x, float y, float z); + void SetScaleOrientation(float x, float y, float z, float a); + void SetCenter(float x, float y, float z); + void SetAlpha(float a); + void DisappearAfter(float secs); + + D3DXQUATERNION m_rotation; // the script's axis + angle, not a real quaternion D3DXVECTOR3 m_center; D3DXQUATERNION m_scaleOrientation; @@ -126,26 +138,10 @@ class CTransform : public CGroup float m_alphaEnd; bool m_moving; - BOOL m_dirty; D3DXMATRIX m_matrix; - float m_fade; - void CalcMatrix(); - void Render(); - void Advance(float nSeconds); - bool OnSetProperty(const PRD* pprd, const void* pvValue); - void OnLoad(); - - void SetScale(float sx, float sy, float sz); - void SetScaleOrientation(float x, float y, float z, float a); - void SetTranslation(float x, float y, float z); - void SetCenter(float x, float y, float z); - void SetRotation(float x, float y, float z, float a); - void SetAlpha(float a); - void DisappearAfter(float t); - float m_timeCenterStart; float m_timeScaleOrientationStart; XTIME m_timeScaleStart; @@ -153,8 +149,4 @@ class CTransform : public CGroup XTIME m_timeTranslationStart; XTIME m_timeAlphaStart; XTIME m_timeToDisappear; - - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() }; - diff --git a/theseus/render/tmap_system.h b/theseus/render/tmap_system.h index 2c1483e..7b540a2 100755 --- a/theseus/render/tmap_system.h +++ b/theseus/render/tmap_system.h @@ -1,3 +1,7 @@ +// tmap_system.h: the 8 bit warp/fade surface behind the TMAP effects and +// the delta fields that drive it. Bodies in render/tmap_system.cpp, binary +// notes in docs/decomp/TmapSystem.md. + #pragma once // A finished delta field: how many rows above a pixel can pull from, and the @@ -12,41 +16,39 @@ class DeltaFieldData char* mField; }; - // 8-bit palettized drawing surface for the TMAP effects. Layout follows the // 5960 object at 0x0005f3f0. class CSurfx { public: - CSurfx(int nWidth, int nHeight); + CSurfx(int w, int h); ~CSurfx(); - int m_nWidth; - int m_nHeight; - BYTE* m_pels; - - int mBytesPerRow; - - int mLineWidth; - RECT mClipRect; - - void Fade(DeltaFieldData* inGrad); - void Fade(char* inPix, long inBytesPerRow, long inX, long inY, DeltaFieldData* inGrad); - void Fade(const char* inSrce, long inBytesPerSrceRow, char* inDest, long inBytesPerDestRow, long inX, long inY, const char* inGrad); + BYTE* Pixel(int x, int y) { return m_pels + (y * mBytesPerRow + x); } - void Line(int sx, int sy, int ex, int ey, unsigned char color); + void Line(int x, int y, int x2, int y2, unsigned char c); - inline BYTE* Pixel(int x, int y) { return &m_pels[mBytesPerRow * y + x]; } + // Whole surface, one block, or the raw rows; all end in the 3 byte cell blend. + void Fade(DeltaFieldData* grad); + void Fade(char* pix, long stride, long x, long y, DeltaFieldData* grad); + void Fade(const char* src, long srcStride, char* dst, long dstStride, long x, long y, const char* grad); // Live surface count and the fade scratch buffer they share. static int sTempRef; static long sTempSize; static char* sTemp; + int m_nWidth; + int m_nHeight; + BYTE* m_pels; + int mBytesPerRow; + int mLineWidth; + RECT mClipRect; + private: // Owns its pixels, so no copies. CSurfx(const CSurfx&); - CSurfx& operator=(const CSurfx& rhs); + CSurfx& operator=(const CSurfx&); }; // Builds a warp field a few rows at a time so a style change doesn't stall a frame. @@ -59,19 +61,22 @@ class DeltaField void Assign(); // Restarts the field if the size changed (or when forced). - void SetSize(long inWidth, long inHeight, bool inForceRegen = false); + void SetSize(long w, long h, bool force = false); // Computes the next row; returns how many are left. int CalcSome(); - bool IsCalculated() { return mCurrentY == mHeight; } - bool IsCalculating() { return mCurrentY >= 0 && mCurrentY != mHeight; } + // mCurrentY is -1 before sizing, counts up while building, ends at mHeight. bool IsUninitialized() { return mCurrentY == -1; } + bool IsCalculating() { return mCurrentY >= 0 && mCurrentY != mHeight; } + bool IsCalculated() { return mCurrentY == mHeight; } // The field, finished first if it wasn't; NULL if it was never sized. DeltaFieldData* GetField(); - void GetXY(float r, float theta, float x, float y, float& X, float& Y, bool& bPolar, bool bInit); + // Style formula for one pixel, in cartesian or polar terms. + void GetXY(float r, float th, float x, float y, float& outX, float& outY, bool& polar, bool init); + int m_nStyle; protected: @@ -85,4 +90,4 @@ class DeltaField DeltaFieldData mFieldData; }; -extern void MakePalette(DWORD outPalette[256]); +extern void MakePalette(DWORD pal[256]); diff --git a/theseus/shared/recovery_node.cpp b/theseus/shared/recovery_node.cpp index ad392f1..6b6733d 100644 --- a/theseus/shared/recovery_node.cpp +++ b/theseus/shared/recovery_node.cpp @@ -16,20 +16,23 @@ bool ResetScreenSaver(); extern bool g_desktopRestartRequested; #endif +// 0x2c bytes in 5960; recoveryProgress is the only property. class CRecovery : public CNode { DECLARE_NODE(CRecovery, CNode) + DECLARE_NODE_PROPS() + DECLARE_NODE_FUNCTIONS() public: CRecovery(); ~CRecovery(); + void StartRecovery(); void FinishRecovery(); - float m_recoveryProgress; + + float m_recoveryProgress; // +0x1c protected: - void Advance(float nSeconds); - DECLARE_NODE_PROPS() - DECLARE_NODE_FUNCTIONS() + void Advance(float dt); private: bool m_bDone; // +0x20 @@ -62,9 +65,7 @@ CRecovery::CRecovery() m_nLastPercent = 0; } -CRecovery::~CRecovery() -{ -} +CRecovery::~CRecovery() {} // CRecovery::StartRecovery() [script fn 'StartRecovery', FND 0x00180390, sig 1] // 5960 (@ 0x0003bb20) clears done, sets running, syncs the last percentage @@ -97,9 +98,9 @@ void CRecovery::FinishRecovery() // stops it and calls OnRecoveryComplete; otherwise a new percentage calls // OnRecoveryProgressChanged, updates recoveryProgress (percent / 100) and // keeps the screen saver off. -void CRecovery::Advance(float nSeconds) +void CRecovery::Advance(float dt) { - CNode::Advance(nSeconds); + CNode::Advance(dt); if (!m_bRunning) return; diff --git a/theseus/shared/screen.cpp b/theseus/shared/screen.cpp index 6f73e77..991cc14 100755 --- a/theseus/shared/screen.cpp +++ b/theseus/shared/screen.cpp @@ -76,9 +76,9 @@ CScreen::~CScreen() // the size dirty, title the title. A brightness other than 1 isn't stored // straight: any running fade is dropped and a 2 second lerp heads there // instead. Setting it back to 1 just stops the fade and stores it. -bool CScreen::OnSetProperty(const PRD* pprd, const void* pvValue) +bool CScreen::OnSetProperty(const PRD* prop, const void* value) { - int field = PTR2INT(pprd->pbOffset); + int field = PTR2INT(prop->pbOffset); if (field == offsetof(m_width) || field == offsetof(m_height)) { m_bSizeDirty = true; @@ -89,7 +89,7 @@ bool CScreen::OnSetProperty(const PRD* pprd, const void* pvValue) } else if (field == offsetof(m_brightness)) { - float target = *(const float*)pvValue; + float target = *(const float*)value; CLerper::RemoveObject(this); if (target != 1.0f) { @@ -97,16 +97,16 @@ bool CScreen::OnSetProperty(const PRD* pprd, const void* pvValue) return false; } } - return CNode::OnSetProperty(pprd, pvValue); + return CNode::OnSetProperty(prop, value); } // CScreen::Advance(dt) // Reconstructed from 5960 retail XBE @ 0x0004fb20: clears both dirty flags // (nothing else reads them) and pushes a changed brightness to the gamma // ramp. -void CScreen::Advance(float nSeconds) +void CScreen::Advance(float dt) { - CNode::Advance(nSeconds); + CNode::Advance(dt); m_bSizeDirty = false; m_bTitleDirty = false; if (m_brightness != m_lastBrightness) @@ -120,13 +120,13 @@ void CScreen::Advance(float nSeconds) // Reconstructed from 5960 retail XBE @ 0x0004fb70: all three channels of // the gamma ramp get (BYTE)(i * level), set through the device (the binary // inlines SetGammaRamp). Desktop has no ramp. -void CScreen::SetBrightness(float nBrightness) +void CScreen::SetBrightness(float level) { #ifdef _XBOX D3DGAMMARAMP ramp; for (int i = 0; i < 256; i++) { - BYTE level = (BYTE)(i * nBrightness); + BYTE level = (BYTE)(i * level); ramp.red[i] = level; ramp.green[i] = level; ramp.blue[i] = level; diff --git a/theseus/shared/settingsfile.h b/theseus/shared/settingsfile.h index f39dc83..4036c84 100755 --- a/theseus/shared/settingsfile.h +++ b/theseus/shared/settingsfile.h @@ -1,15 +1,12 @@ -// settingsfile.h: CSettingsFile, the in-memory model of an .xbx / -// .ini settings file (sections + key=value entries, parse on Open, -// lazy save in destructor). Companion to shared/settingsfile.cpp. +// settingsfile.h: .xbx / .ini style settings files held in memory as +// [section] lists of name=value pairs. Bodies in shared/settingsfile.cpp. #pragma once -// Returns the directory the running XBE was launched from, with the -// trailing filename component stripped. Used by the settings code to -// locate sibling .xbx files relative to the dashboard image. -void XI_GetProgramPath(char* szBuffer); +// Folder the running program was started from, without the file name. +void XI_GetProgramPath(char* out); -// One key=value entry inside an .xbx settings section. +// name=value, one link in its section's list. class CSettingsFileValue { public: @@ -21,46 +18,39 @@ class CSettingsFileValue TCHAR* m_value; }; -// One [section] block inside an .xbx settings file. Each section owns -// a singly-linked list of CSettingsFileValue entries. class CSettingsFileSection { public: CSettingsFileSection(); ~CSettingsFileSection(); - CSettingsFileValue* FindValue(const TCHAR* szName); - bool SetValue(const TCHAR* szName, const TCHAR* szValue); + CSettingsFileValue* FindValue(const TCHAR* name); + bool SetValue(const TCHAR* name, const TCHAR* value); CSettingsFileSection* m_next; TCHAR* m_name; CSettingsFileValue* m_values; }; -// In-memory model of an .xbx settings file. Parses on Open, mutates -// in memory via SetValue, lazily writes back on Save (which the -// destructor calls automatically). Top-level entries that have no -// preceding [section] header land in a synthetic "default" section. +// Open parses the whole file into memory. Pairs before the first [section] +// go to "default". class CSettingsFile { public: CSettingsFile(); ~CSettingsFile(); - bool OpenDir(const TCHAR* szDir); - bool Open(const TCHAR* szFile); + bool Open(const TCHAR* path); + bool OpenDir(const TCHAR* dir); + bool Save(); bool Close(); void Cancel(); - bool Save(); - inline const TCHAR* GetFileName() const - { - return m_filePath; - } + inline const TCHAR* GetFileName() const { return m_filePath; } - bool GetValue(const TCHAR* szSection, const TCHAR* szName, TCHAR* szValueBuf, int cchValueBuf); - void SetValue(const TCHAR* szSection, const TCHAR* szName, const TCHAR* szValue); - CSettingsFileSection* FindSection(const TCHAR* szSection, bool bCreate = false); + CSettingsFileSection* FindSection(const TCHAR* section, bool create = false); + bool GetValue(const TCHAR* section, const TCHAR* name, TCHAR* buf, int bufLen); + void SetValue(const TCHAR* section, const TCHAR* name, const TCHAR* value); // SetValue writes the whole file every time it changes a key, which is // fine for a setting the user just toggled and ruinous for a loop. Bracket @@ -74,7 +64,7 @@ class CSettingsFile bool m_batching; protected: - int WriteTo(const TCHAR* szPath); + int WriteTo(const TCHAR* path); #ifdef _UNICODE bool m_unicode;