From 288bcc54fc358e3588b8e40b586c90f8349216b4 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 01/13] Rebuilt the CD-ROM service from the binary Wrote Open, Close, the table of contents, raw reads and the track lengths fresh from 0x64da0..0x650c0 and documented them. The disc id and name slots stay as Theseus's own. Track lists, lengths, disc ids and read retries match the old code on 20,000 made up tables of contents. --- docs/decomp/NtIoSvc.md | 82 ++++++-- theseus/shared/ntiosvc.cpp | 406 ++++++++++++++++--------------------- theseus/shared/ntiosvc.h | 100 ++------- 3 files changed, 253 insertions(+), 335 deletions(-) diff --git a/docs/decomp/NtIoSvc.md b/docs/decomp/NtIoSvc.md index 8935356..810b3fc 100644 --- a/docs/decomp/NtIoSvc.md +++ b/docs/decomp/NtIoSvc.md @@ -1,23 +1,63 @@ # NtIoSvc -CD-ROM device I/O service. Wraps NT `DeviceIoControl` calls for CDROM access on Xbox. Backed by `ntiosvc.cpp` in the active source tree. - -## CNtIoctlCdromService - -The main class. Opens a handle to `CDROM0:` (the Xbox DVD drive's device path) and provides methods to query disc information. - -### TOC Reading - -Reads the disc's table of contents via `IOCTL_CDROM_READ_TOC`. The TOC contains track start addresses in MSF (Minutes/Seconds/Frames) format, which are converted to absolute frame offsets for seeking and playback calculations. - -## XCDROM_TOC - -Structure storing parsed disc information: - -- **Track addresses**: Array of start frame offsets for each track on the disc. -- **Disc ID**: A hex string computed from the track frame offsets. This serves as a unique-enough identifier for matching discs against metadata databases (title, artist, track names). -- **Metadata fields**: Optional title, artist, and per-track name strings. Populated from external lookup if available; empty otherwise. - -## Usage - -Used by the disc-management and music-collection layers for audio CD detection and playback. When a disc is inserted, the service reads the TOC, computes the disc ID, and hands the result to the music system for track enumeration. +The CD-ROM service in the 5960 retail binary. One global instance lives at `0x00188780`: the drive +handle, then the audio track count (`0x00188784`), then the start frame of every track +(`0x00188788`). Audio CD detection, the disc's track times and the CD audio streamer all read it. + +## Functions + +| Address | Name | What it does | +|---------|------|--------------| +| 0x00064da0 | CNtIoctlCdromService::CNtIoctlCdromService | Handle -1, no tracks | +| 0x00064db0 | CNtIoctlCdromService::Close | Closes an open handle, sets it to -1, zeroes the track count | +| 0x00064dd0 | CNtIoctlCdromService::Open | Opens `CDROM0:` for reading; a failed open returns the error as an HRESULT; a disc with no usable table of contents closes it again but still returns 0 | +| 0x00064f20 | CNtIoctlCdromService::GetTableOfContents | Reads the TOC and fills the track list, below | +| 0x000650c0 | CNtIoctlCdromService::Read | Raw CDDA read with retries, below | + +## GetTableOfContents + +``` +if (!DeviceIoControl(h, IOCTL_CDROM_READ_TOC, 0, 0, &toc, 0x324, &n, 0)) { + hr = HRESULT_FROM_WIN32(GetLastError()); + if (hr < 0) return false; // ERROR_NOT_READY gets one try, same result +} +if (toc.LastTrack < toc.FirstTrack) return false; +i = 0; +do { + TrackAddr[i] = (Address[1] * 60 + Address[2]) * 75 + Address[3]; + if (TrackNumber == 0xAA) break; // lead out + if (Control & 4) { // data track + Address[1] -= 2; Address[2] += 30; + if (Address[2] < 60) Address[1] -= 1; else Address[2] -= 60; + TrackAddr[i] = (recomputed); break; + } +} while (++i <= LastTrack - FirstTrack + 1); // i stays at the last entry read +LastTrack = i; +return i > 0; +``` + +A data track (an enhanced CD) is moved back two and a half minutes, the gap the drive leaves before +the second session, so the audio track before it ends where its sound does. + +## Read + +``` +rri.DiskOffset = (start - 150) * 2048; rri.SectorCount = count; rri.TrackMode = CDDA; +for (;;) { + if (DeviceIoControl(h, IOCTL_CDROM_RAW_READ, &rri, 0x10, buf, count * 2352, &n, 0)) return 0; + hr = HRESULT_FROM_WIN32(GetLastError()); + if (hr >= 0) break; + if (retries-- == 0) return hr; +} +return hr; +``` + +## Track times + +The disc drive node's `FormatTotalTime` (`0x0003a060`) and `FormatTrackTime` (`0x0003a150`) read the +list directly: the length is `TrackAddr[LastTrack] - TrackAddr[0]` (or `[n + 1] - [n]` for a track +inside `0..LastTrack-1`), printed `%02d:%02d` as `(BYTE)(frames / 4500)` and `frames % 4500 / 75`. +With no disc open, or a track out of range, they return an empty string. + +Theseus adds a disc id (each track's start frame as six hex digits) and title, artist and track name +slots that nothing fills yet. diff --git a/theseus/shared/ntiosvc.cpp b/theseus/shared/ntiosvc.cpp index a110bcd..4b8444d 100755 --- a/theseus/shared/ntiosvc.cpp +++ b/theseus/shared/ntiosvc.cpp @@ -1,7 +1,7 @@ -// ntiosvc.cpp: CD-ROM device I/O service. Wraps NT IOCTL_CDROM calls to -// read TOC, parse track frame offsets, and compute the disc id used by -// the music collection. Decompiled from the 5960 retail XBE; see -// docs/decomp/NtIoSvc.md. +// ntiosvc.cpp: the CD-ROM service behind audio CDs. Open, the table of +// contents, raw reads and the track lengths are rebuilt from the 5960 +// retail XBE (0x64da0..0x650c0, g_cdrom at 0x188780); see +// docs/decomp/NtIoSvc.md. The disc id and name strings are Theseus's. #include "std.h" #include "theseus.h" @@ -9,296 +9,240 @@ CNtIoctlCdromService g_cdrom; +// A TOC address is four bytes: unused, minute, second, frame. +static DWORD AddressToFrames(const UCHAR* addr) +{ + return (addr[1] * 60 + addr[2]) * CDAUDIO_FRAMES_PER_SECOND + addr[3]; +} +static void SplitFrames(DWORD dwFrames, int* pnMinutes, int* pnSeconds, int* pnFrames) +{ + DWORD dwInMinute = dwFrames % CDAUDIO_FRAMES_PER_MINUTE; + if (pnMinutes != NULL) + *pnMinutes = (BYTE)(dwFrames / CDAUDIO_FRAMES_PER_MINUTE); + if (pnSeconds != NULL) + *pnSeconds = dwInMinute / CDAUDIO_FRAMES_PER_SECOND; + if (pnFrames != NULL) + *pnFrames = dwInMinute % CDAUDIO_FRAMES_PER_SECOND; +} +// CNtIoctlCdromService::CNtIoctlCdromService() +// Reconstructed from 5960 retail XBE @ 0x00064da0: +// m_hDevice = -1; m_toc.LastTrack = 0; CNtIoctlCdromService::CNtIoctlCdromService() { - m_hDevice = INVALID_HANDLE_VALUE; + m_hDevice = INVALID_HANDLE_VALUE; } CNtIoctlCdromService::~CNtIoctlCdromService() { - Close(); + Close(); } +// CNtIoctlCdromService::Close() +// Reconstructed from 5960 retail XBE @ 0x00064db0: +// if (m_hDevice != -1) { CloseHandle(m_hDevice); m_hDevice = -1; } +// m_toc.LastTrack = 0; +// Theseus also frees its name strings, which clears the track count too. void CNtIoctlCdromService::Close() { - if (m_hDevice != INVALID_HANDLE_VALUE) - { - CloseHandle(m_hDevice); - m_hDevice = INVALID_HANDLE_VALUE; - } - - m_toc.Delete(); -} - + if (m_hDevice != INVALID_HANDLE_VALUE) + { + CloseHandle(m_hDevice); + m_hDevice = INVALID_HANDLE_VALUE; + } + m_toc.Delete(); +} + +// CNtIoctlCdromService::Open(drive) +// Reconstructed from 5960 retail XBE @ 0x00064dd0: +// h = CreateFile(L"CDROM0:", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, NORMAL, 0); +// if (h == -1) return HRESULT_FROM_WIN32(GetLastError()); +// if (!GetTableOfContents()) Close(); +// return S_OK; +// The drive number goes unused; there is only one drive. HRESULT CNtIoctlCdromService::Open(DWORD dwDriveNumber) { + m_hDevice = TheseusCreateFile(_T("CDROM0:"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (m_hDevice == INVALID_HANDLE_VALUE) + return HRESULT_FROM_WIN32(GetLastError()); - TCHAR szPath [] = _T("CDROM0:"); - - m_hDevice = TheseusCreateFile(szPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - if (m_hDevice == INVALID_HANDLE_VALUE) - { - return HRESULT_FROM_WIN32(GetLastError()); - } - - if (!GetTableOfContents()) - Close(); - - return S_OK; + if (!GetTableOfContents()) + Close(); + return S_OK; } - +// CNtIoctlCdromService::GetTableOfContents() +// Reconstructed from 5960 retail XBE @ 0x00064f20. One IOCTL_CDROM_READ_TOC +// (a drive that isn't ready fails it), then each entry's start frame goes +// into TrackAddr until the lead-out (track 0xAA) or a data track. A data +// track's start is pulled back by the 2:30 gap so the audio before it ends +// there. LastTrack ends up as the index it stopped at. See the doc for the +// loop. bool CNtIoctlCdromService::GetTableOfContents() { - HRESULT hr; - CDROM_TOC toc; - - for (int nRetry = 0; nRetry < 1; nRetry += 1) - { - hr = DeviceIoControl(IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof (toc)); - - if (SUCCEEDED(hr)) - break; - - if (hr != HRESULT_FROM_WIN32(ERROR_NOT_READY)) - return false; - - } - - if (FAILED(hr)) - return false; - - { - // Verify that the TOC is structurally correct and has at least one - // track. - if (toc.FirstTrack > toc.LastTrack) - return false; - - BOOL fFoundEndTrack = FALSE; - - DWORD i; - for (i = 0; i <= (DWORD)(toc.LastTrack - toc.FirstTrack + 1); i++) - { -#define TOC_DATA_TRACK (0x04) -#define TOC_LAST_TRACK (0xaa) - - m_toc.TrackAddr[i] = TocValToFrames(toc.TrackData[i].Address); - - // Break out if we find a last track marker. - if (toc.TrackData[i].TrackNumber == TOC_LAST_TRACK) - { - fFoundEndTrack = TRUE; - break; - } - - // Break out if we find a data track. - if ((toc.TrackData[i].Control & TOC_DATA_TRACK) != 0) - { - // Knock off 2.5 minutes to account for the final leadin. - toc.TrackData[i].Address[1] -= 2; - toc.TrackData[i].Address[2] += 30; - - if (toc.TrackData[i].Address[2] < 60) - toc.TrackData[i].Address[1] -= 1; - else - toc.TrackData[i].Address[2] -= 60; - - m_toc.TrackAddr[i] = TocValToFrames(toc.TrackData[i].Address); - - fFoundEndTrack = TRUE; - break; - } - } - - // If we didn't find an ending track, whether it be a data track or a - // track with the last track marker, then knock off one track because we - // don't know how long the last "audio" track might really be. We can't - // underflow "i" here because the above code already checked for an - // empty TOC. - if (!fFoundEndTrack) - i--; - - m_toc.LastTrack = i; - } - - - if (m_toc.LastTrack > 0) - { - m_toc.UpdateDiscID(); - } - - return m_toc.LastTrack > 0; -} - -HRESULT CNtIoctlCdromService::Read(DWORD dwReadStart, DWORD dwReadLength, LPVOID pvBuffer, DWORD dwRetries) -{ - RAW_READ_INFO rri; - HRESULT hr; - - // NT drivers seem to want the disk offset to be (sector - 150) * 2048, - // regardless of what the actual disk lead-in amount is. - rri.DiskOffset.QuadPart = (ULONGLONG)(dwReadStart - 150) * (ULONGLONG)2048; - rri.SectorCount = dwReadLength; - rri.TrackMode = CDDA; - - do - { - hr = DeviceIoControl(IOCTL_CDROM_RAW_READ, &rri, sizeof (rri), pvBuffer, CDAUDIO_BYTES_PER_FRAME * dwReadLength); - - if (SUCCEEDED(hr)) - break; - - } - while(dwRetries--); - - return hr; -} - + CDROM_TOC toc; + if (FAILED(DeviceIoControl(IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc)))) + return false; + + if (toc.LastTrack < toc.FirstTrack) + return false; + + DWORD nEntries = toc.LastTrack - toc.FirstTrack + 1; + DWORD i = 0; + for (;;) + { + UCHAR* addr = toc.TrackData[i].Address; + m_toc.TrackAddr[i] = AddressToFrames(addr); + + if (toc.TrackData[i].TrackNumber == 0xAA) + break; + + if (toc.TrackData[i].Control & 4) + { + // Back off two minutes thirty, borrowing a minute when the + // seconds wrap. + addr[1] -= 2; + addr[2] += 30; + if (addr[2] < 60) + addr[1] -= 1; + else + addr[2] -= 60; + m_toc.TrackAddr[i] = AddressToFrames(addr); + break; + } + + if (i + 1 > nEntries) + break; + i += 1; + } + + m_toc.LastTrack = i; + + // Theseus: the disc id. + if (m_toc.LastTrack > 0) + m_toc.UpdateDiscID(); + + return m_toc.LastTrack > 0; +} + +// CNtIoctlCdromService::Read(start, count, buffer, retries) +// Reconstructed from 5960 retail XBE @ 0x000650c0: +// rri = { (start - 150) * 2048, count, CDDA }; +// for (;;) { if (ioctl(RAW_READ, &rri, buf, count * 2352)) return S_OK; +// hr = HRESULT_FROM_WIN32(GetLastError()); if (SUCCEEDED(hr)) break; +// if (retries-- == 0) return hr; } +// The drive wants the offset as if every disc had the 150 frame lead in. +HRESULT CNtIoctlCdromService::Read(DWORD dwReadStart, DWORD dwReadLength, LPVOID pvBuffer, DWORD dwRetries) +{ + RAW_READ_INFO rri; + rri.DiskOffset.QuadPart = (ULONGLONG)(dwReadStart - 150) * 2048; + rri.SectorCount = dwReadLength; + rri.TrackMode = CDDA; + + HRESULT hr; + for (;;) + { + hr = DeviceIoControl(IOCTL_CDROM_RAW_READ, &rri, sizeof(rri), pvBuffer, dwReadLength * CDAUDIO_BYTES_PER_FRAME); + if (SUCCEEDED(hr) || dwRetries == 0) + break; + dwRetries -= 1; + } + return hr; +} + +// 5960 inlines this at each IOCTL: the call, then GetLastError as an HRESULT. HRESULT CNtIoctlCdromService::DeviceIoControl(DWORD dwControlCode, LPVOID pvInBuffer, DWORD dwInBufferSize, LPVOID pvOutBuffer, DWORD dwOutBufferSize, LPDWORD pdwBytesReturned) { - DWORD dwBytesReturned; - - if (pdwBytesReturned == NULL) - pdwBytesReturned = &dwBytesReturned; - - if (!::DeviceIoControl(m_hDevice, dwControlCode, pvInBuffer, dwInBufferSize, pvOutBuffer, dwOutBufferSize, pdwBytesReturned, NULL)) - return HRESULT_FROM_WIN32(GetLastError()); - - return S_OK; + DWORD dwIgnored; + if (::DeviceIoControl(m_hDevice, dwControlCode, pvInBuffer, dwInBufferSize, pvOutBuffer, dwOutBufferSize, + pdwBytesReturned != NULL ? pdwBytesReturned : &dwIgnored, NULL)) + return S_OK; + return HRESULT_FROM_WIN32(GetLastError()); } +// Disc and track lengths. 5960 inlines these into FormatTotalTime @ 0x0003a060 +// and FormatTrackTime @ 0x0003a150: +// frames = TrackAddr[LastTrack] - TrackAddr[0]; (or [n + 1] - [n]) +// minutes = (BYTE)(frames / 4500); seconds = frames % 4500 / 75; +// A track number past the last audio track gets nothing. bool CNtIoctlCdromService::GetTotalLength(int* pnMinutes, int* pnSeconds, int* pnFrames) { - if (!IsOpen()) - return false; - - DWORD dwFrames = m_toc.TrackAddr[GetTrackCount()] - m_toc.TrackAddr[0]; - DWORD dwMsf = FramesToMsf(dwFrames); - - if (pnMinutes != NULL) - *pnMinutes = MCI_MSF_MINUTE(dwMsf); - - if (pnSeconds != NULL) - *pnSeconds = MCI_MSF_SECOND(dwMsf); - - if (pnFrames != NULL) - *pnFrames = MCI_MSF_FRAME(dwMsf); - - return true; + if (!IsOpen()) + return false; + SplitFrames(m_toc.TrackAddr[m_toc.LastTrack] - m_toc.TrackAddr[0], pnMinutes, pnSeconds, pnFrames); + return true; } bool CNtIoctlCdromService::GetTrackLength(int nTrack, int* pnMinutes, int* pnSeconds, int* pnFrames) { - if (!IsOpen() || nTrack < 0 || nTrack > GetTrackCount() - 1) - return false; - - DWORD dwFrames = m_toc.TrackAddr[nTrack + 1] - m_toc.TrackAddr[nTrack]; - DWORD dwMsf = FramesToMsf(dwFrames); - - if (pnMinutes != NULL) - *pnMinutes = MCI_MSF_MINUTE(dwMsf); - - if (pnSeconds != NULL) - *pnSeconds = MCI_MSF_SECOND(dwMsf); - - if (pnFrames != NULL) - *pnFrames = MCI_MSF_FRAME(dwMsf); - - return true; + if (!IsOpen() || nTrack < 0 || nTrack >= m_toc.LastTrack) + return false; + SplitFrames(m_toc.TrackAddr[nTrack + 1] - m_toc.TrackAddr[nTrack], pnMinutes, pnSeconds, pnFrames); + return true; } - - +// Theseus: name lookups. Nothing fills these in yet, so they stay NULL. const TCHAR* CNtIoctlCdromService::GetTitle() { - if (!IsOpen()) - return NULL; - - return m_toc.szTitle; + return IsOpen() ? m_toc.szTitle : NULL; } const TCHAR* CNtIoctlCdromService::GetArtist() { - if (!IsOpen()) - return NULL; - - return m_toc.szArtist; + return IsOpen() ? m_toc.szArtist : NULL; } const TCHAR* CNtIoctlCdromService::GetTrackName(int nTrack) { - if (!IsOpen()) - return NULL; - - return m_toc.rgszTrack[nTrack]; + return IsOpen() ? m_toc.rgszTrack[nTrack] : NULL; } - - +// Theseus: the strings around the 5960 track list. XCDROM_TOC::XCDROM_TOC() { - Clear(); + Clear(); } XCDROM_TOC::~XCDROM_TOC() { - Delete(); + Delete(); } void XCDROM_TOC::Delete() { - - delete [] szTitle; - delete [] szArtist; - delete [] szID; - - for (unsigned i = 0; i < 100; i += 1) - delete [] rgszTrack[i]; - - Clear(); + delete[] szTitle; + delete[] szArtist; + delete[] szID; + for (int i = 0; i < 100; i++) + delete[] rgszTrack[i]; + Clear(); } void XCDROM_TOC::Clear() { - - szTitle = NULL; - szArtist = NULL; - szID = NULL; - - for (unsigned i = 0; i < 100; i += 1) - { - rgszTrack[i] = NULL; - TrackAddr[i] = 0; - } - - LastTrack = 0; + szTitle = szArtist = szID = NULL; + memset(rgszTrack, 0, sizeof(rgszTrack)); + memset(TrackAddr, 0, sizeof(TrackAddr)); + LastTrack = 0; } +// The track a frame falls in; anything past the end counts as the first. int XCDROM_TOC::GetTrackFromFrame(DWORD dwPosition) const { - int i; - for (i = 0; i < LastTrack; i += 1) - { - if (dwPosition < TrackAddr[i + 1]) - return i; - } - - return 0; + for (int track = 0; track < LastTrack; track++) + { + if (dwPosition < TrackAddr[track + 1]) + return track; + } + return 0; } -// Calculate the disc id used by WindowsMedia.com - +// Theseus: the disc id is every track's start frame as six hex digits. void XCDROM_TOC::UpdateDiscID() { - szID = new TCHAR [6 * LastTrack + 1]; - - TCHAR* pch = szID; - int i; - for (i = 0; i < LastTrack; i += 1) - pch += _stprintf(pch, _T("%06X"), TrackAddr[i]); - *pch = 0; + szID = new TCHAR[LastTrack * 6 + 1]; + szID[0] = 0; + for (int track = 0; track < LastTrack; track++) + _stprintf(szID + track * 6, _T("%06X"), TrackAddr[track]); } - diff --git a/theseus/shared/ntiosvc.h b/theseus/shared/ntiosvc.h index 4d546e1..9373652 100755 --- a/theseus/shared/ntiosvc.h +++ b/theseus/shared/ntiosvc.h @@ -1,54 +1,16 @@ -// ntiosvc.h: NT IOCTL CD-ROM service. CDDA TOC parsing, raw-frame -// reads, CD-Text title / artist / track lookup. Used by the music -// player when a regular audio CD is inserted. Decompiled from the -// 5960 retail XBE. +// ntiosvc.h: the CD-ROM service behind audio CDs. Opens the drive, reads +// the table of contents into frame offsets and does raw CDDA reads. +// Rebuilt from the 5960 retail XBE; see docs/decomp/NtIoSvc.md. #pragma once -// CD audio type conversions - -#define CDAUDIO_BYTES_PER_FRAME 2352 -#define CDAUDIO_BYTES_PER_SECOND 176400 -#define CDAUDIO_BYTES_PER_MINUTE 10584000 - -#define CDAUDIO_FRAMES_PER_SECOND 75 -#define CDAUDIO_FRAMES_PER_MINUTE 4500 - -// MCI time format conversion macros - -#define MCI_MSF_MINUTE(msf) ((BYTE)(msf)) -#define MCI_MSF_SECOND(msf) ((BYTE)(((WORD)(msf)) >> 8)) -#define MCI_MSF_FRAME(msf) ((BYTE)((msf)>>16)) - -#define MCI_MAKE_MSF(m, s, f) ((DWORD)(((BYTE)(m) | \ - ((WORD)(s)<<8)) | \ - (((DWORD)(BYTE)(f))<<16))) - -__inline DWORD MsfToFrames(DWORD dwMsf) -{ - return MCI_MSF_MINUTE(dwMsf) * CDAUDIO_FRAMES_PER_MINUTE + - MCI_MSF_SECOND(dwMsf) * CDAUDIO_FRAMES_PER_SECOND + - MCI_MSF_FRAME(dwMsf); -} - -__inline DWORD FramesToMsf(DWORD dwFrames) -{ - return MCI_MAKE_MSF( - dwFrames / CDAUDIO_FRAMES_PER_MINUTE, - (dwFrames % CDAUDIO_FRAMES_PER_MINUTE) / CDAUDIO_FRAMES_PER_SECOND, - (dwFrames % CDAUDIO_FRAMES_PER_MINUTE) % CDAUDIO_FRAMES_PER_SECOND); -} - -__inline DWORD TocValToMsf(LPBYTE ab) -{ - return MCI_MAKE_MSF(ab[1], ab[2], ab[3]); -} - -__inline DWORD TocValToFrames(LPBYTE ab) -{ - return MsfToFrames(TocValToMsf(ab)); -} +// Red Book audio: 75 frames a second, 2352 bytes a frame. +#define CDAUDIO_FRAMES_PER_SECOND 75 +#define CDAUDIO_FRAMES_PER_MINUTE (60 * CDAUDIO_FRAMES_PER_SECOND) +#define CDAUDIO_BYTES_PER_FRAME 2352 +// What the drive told us about the disc. 5960 keeps just the track count +// and the start frames; the name strings and disc id are Theseus's. struct XCDROM_TOC { public: @@ -58,12 +20,13 @@ struct XCDROM_TOC void Delete(); int GetTrackFromFrame(DWORD dwPosition) const; - int LastTrack; - DWORD TrackAddr [100]; + // TrackAddr[LastTrack] is where the last audio track ends. + int LastTrack; + DWORD TrackAddr[100]; void UpdateDiscID(); - TCHAR* rgszTrack [100]; + TCHAR* rgszTrack[100]; TCHAR* szTitle; TCHAR* szArtist; TCHAR* szID; @@ -74,14 +37,6 @@ struct XCDROM_TOC typedef XCDROM_TOC* PXCDROM_TOC; -// Read in 1-second chunks: small enough that music can stop on a -// chunk boundary, large enough that older drives stay happy. -#define FRAMES_PER_CHUNK (CDAUDIO_FRAMES_PER_SECOND) - -#define CD_AUDIO_SEGMENTS_PER_BUFFER ((4*CDAUDIO_FRAMES_PER_SECOND)/FRAMES_PER_CHUNK) - -#define BYTES_PER_CHUNK (FRAMES_PER_CHUNK * CDAUDIO_BYTES_PER_FRAME) - class CNtIoctlCdromService { private: @@ -95,18 +50,8 @@ class CNtIoctlCdromService void Close(); HRESULT Read(DWORD dwReadStart, DWORD dwReadLength, LPVOID pvBuffer, DWORD dwRetries = 0); - inline bool IsOpen() const - { - return m_hDevice != INVALID_HANDLE_VALUE; - } - - inline int GetTrackCount() const - { - if (!IsOpen()) - return 0; - - return m_toc.LastTrack; - } + bool IsOpen() const { return m_hDevice != INVALID_HANDLE_VALUE; } + int GetTrackCount() const { return IsOpen() ? m_toc.LastTrack : 0; } bool GetTotalLength(int* pnMinutes, int* pnSeconds, int* pnFrames); bool GetTrackLength(int nTrack, int* pnMinutes, int* pnSeconds, int* pnFrames); @@ -115,18 +60,8 @@ class CNtIoctlCdromService const TCHAR* GetArtist(); const TCHAR* GetTrackName(int nTrack); - inline DWORD GetTrackFrame(int nTrack) const - { - if (!IsOpen()) - return 0; - - return m_toc.TrackAddr[nTrack]; - } - - inline int GetTrackFromFrame(DWORD dwFrame) const - { - return m_toc.GetTrackFromFrame(dwFrame); - } + DWORD GetTrackFrame(int nTrack) const { return IsOpen() ? m_toc.TrackAddr[nTrack] : 0; } + int GetTrackFromFrame(DWORD dwFrame) const { return m_toc.GetTrackFromFrame(dwFrame); } protected: XCDROM_TOC m_toc; @@ -135,4 +70,3 @@ class CNtIoctlCdromService }; extern CNtIoctlCdromService g_cdrom; -extern bool OpenCDROM(); From 5600b554083da68c3420c3ecc5d9a3a3fb741206 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 02/13] Rebuilt DirectSound setup and the debug helpers DirectSound init and buffer creation are written fresh from 0x62750 and 0x626b0; the singleton, cleanup and lock helpers are Theseus's. The debug build's trace and error helpers have no retail counterpart, so I wrote a smaller set from scratch and dropped the unused hex dump and class list. Both build for Xbox retail and debug; needs a console test. --- theseus/engine/debug.cpp | 298 +++++++------------------------- theseus/xbox/dsound_manager.cpp | 137 +++++++-------- 2 files changed, 129 insertions(+), 306 deletions(-) diff --git a/theseus/engine/debug.cpp b/theseus/engine/debug.cpp index a35fe8c..6967a00 100755 --- a/theseus/engine/debug.cpp +++ b/theseus/engine/debug.cpp @@ -1,6 +1,6 @@ -// debug.cpp: debug-build-only diagnostic helpers (CRT alloc hook, trace -// stream gate, kernel-debugger present check). Most of this compiles to -// nothing in retail. +// debug.cpp: the Xbox debug build's trace, assert and error-text helpers. +// None of this is in the 5960 retail XBE: retail formats its alerts +// (0x0002c520) and throws them away. Theseus's own, and empty in retail. #include "std.h" #include "theseus.h" @@ -8,205 +8,94 @@ #ifdef _DEBUG -long _dbgBreakAlloc = -1; - +#ifdef _XBOX +// Untagged trace lines are chatter; flip this to see them. +bool bShowComments = false; +#endif -int __cdecl DebugAllocHook(int nAllocType, void *pvData, size_t nSize, int nBlockUse, long lRequest, const unsigned char* szFileName, int nLine) +// A message may start with a 1..7 tag byte (its color on the debug +// console). Tagged lines always print; on Xbox untagged ones are optional. +EXTERN_C void Trace(const TCHAR* szMsg, ...) { - if (lRequest == _dbgBreakAlloc) - _CrtDbgBreak(); + if (*szMsg >= 1 && *szMsg <= 7) + szMsg++; +#ifdef _XBOX + else if (!bShowComments) + return; +#endif - return TRUE; + TCHAR szLine[512]; + va_list args; + va_start(args, szMsg); + _vsntprintf(szLine, countof(szLine), szMsg, args); + va_end(args); + szLine[countof(szLine) - 1] = 0; + OutputDebugString(szLine); } -const TCHAR* GetFacilityName(int nFacility) +static const TCHAR* FacilityName(int nFacility) { - const TCHAR* szFacility; - switch (nFacility) { - default: - szFacility = _T("Unknown Facility"); - break; - - case FACILITY_NULL: - szFacility = _T("null"); - break; - - case FACILITY_RPC: - szFacility = _T("RPC"); - break; - - case FACILITY_DISPATCH: - szFacility = _T("Dispatch"); - break; - - case FACILITY_STORAGE: - szFacility = _T("Storage"); - break; - - case FACILITY_ITF: - szFacility = _T("ITF"); - break; - - case FACILITY_WIN32: - szFacility = _T("Win32"); - break; - - case FACILITY_WINDOWS: - szFacility = _T("Windows"); - break; - - case FACILITY_SSPI: - szFacility = _T("SSPI"); - break; - - case FACILITY_CONTROL: - szFacility = _T("Control"); - break; - - case FACILITY_CERT: - szFacility = _T("Cert"); - break; - - case FACILITY_INTERNET: - szFacility = _T("Internet"); - break; - - case FACILITY_MEDIASERVER: - szFacility = _T("Media Server"); - break; - - case FACILITY_MSMQ: - szFacility = _T("MSMQ"); - break; - - case FACILITY_SETUPAPI: - szFacility = _T("Setup API"); - break; - - case 0x15: // _FACDPV - szFacility = _T("DirectPlayVoice"); - break; - - case 0x876: // _FACDD, _FACD3D - szFacility = _T("Direct3D"); - break; - - case 0x877: // _FACDP - szFacility = _T("DirectPlay"); - break; - - case 0x878: // _FACDS - szFacility = _T("DirectSound"); - break; + case FACILITY_NULL: return _T("null"); + case FACILITY_WIN32: return _T("Win32"); + case FACILITY_WINDOWS: return _T("Windows"); + case FACILITY_ITF: return _T("ITF"); + case 0x876: return _T("Direct3D"); + case 0x878: return _T("DirectSound"); } - - return szFacility; + return _T("Unknown Facility"); } -void TheseusGetErrorString(HRESULT hr, TCHAR* szErrorBuf, int cchErrorBuf) +// ": ", cut to fit. +void TheseusGetErrorString(HRESULT hr, TCHAR* szBuf, int cchBuf) { - int nCode = HRESULT_CODE(hr); - int nFacility = HRESULT_FACILITY(hr); - - const TCHAR* szFacility = GetFacilityName(nFacility); - _tcsncpy(szErrorBuf, szFacility, cchErrorBuf); - int cchFacility = _tcslen(szFacility); - szErrorBuf += cchFacility; - cchErrorBuf -= cchFacility; - - if (cchErrorBuf > 2) - { - *szErrorBuf++ = ':'; - *szErrorBuf++ = ' '; - cchErrorBuf -= 2; - } - - D3DXGetErrorString(hr, szErrorBuf, cchErrorBuf); + if (cchBuf <= 0) + return; + _sntprintf(szBuf, cchBuf, _T("%s: "), FacilityName(HRESULT_FACILITY(hr))); + szBuf[cchBuf - 1] = 0; + int used = (int)_tcslen(szBuf); + if (used < cchBuf - 1) + D3DXGetErrorString(hr, szBuf + used, cchBuf - used); } const TCHAR* TheseusGetErrorString(HRESULT hr) { - static TCHAR szBuf [100]; - TheseusGetErrorString(hr, szBuf, countof(szBuf)); - return szBuf; + static TCHAR szText[100]; + TheseusGetErrorString(hr, szText, countof(szText)); + return szText; } void LogComError(HRESULT hr, const char* szFunc) { - TCHAR szError [100]; - TheseusGetErrorString(hr, szError, countof(szError)); - -#ifdef _UNICODE - TCHAR szFunction [100]; - Unicode(szFunction, szFunc, 100); - - Trace(_T("\001Error in function: %s\n\001%s\n"), szFunc == NULL ? _T("unknown") : szFunction, szError); -#else - Trace(_T("\001Error in function: %s\n\001%s\n"), szFunc == NULL ? _T("unknown") : szFunc, szError); -#endif + TCHAR szFuncW[100]; + Unicode(szFuncW, szFunc != NULL ? szFunc : "unknown", countof(szFuncW)); + Trace(_T("\001%s failed: %s\n"), szFuncW, TheseusGetErrorString(hr)); } void LogError(const char* szFunc) { - Trace(_T("\001Error in function: %s\n"), szFunc); + Trace(_T("\001%hs failed\n"), szFunc); } +// ASSERTHR lands here. True asks the caller to break into the debugger, +// which only makes sense with one attached. EXTERN_C bool AssertFailed(const TCHAR* szFile, int nLine, HRESULT hr) { - TCHAR szBuffer [256]; - if (hr == 0) - { - _stprintf(szBuffer, _T("Assertion failed in %s at line %d (last error code is 0x%x)."), szFile, nLine, GetLastError()); - } + Trace(_T("\001Assert failed: %s(%d), last error %u\n"), szFile, nLine, GetLastError()); else - { - TCHAR szComError [100]; - TheseusGetErrorString(hr, szComError, countof(szComError)); - _stprintf(szBuffer, _T("COM Failure in %s at line %d.\n\nFacility: %d %s\nCode %d (0x%04x)\n\n%s"), - szFile, nLine, HRESULT_FACILITY(hr), GetFacilityName(HRESULT_FACILITY(hr)), HRESULT_CODE(hr), HRESULT_CODE(hr), szComError); - } - - Trace(_T("\001Theseus: %s\n"), szBuffer); + Trace(_T("\001HRESULT 0x%08x at %s(%d): %s\n"), hr, szFile, nLine, TheseusGetErrorString(hr)); #ifdef _MAC_CROSS_COMPILE - return false; // don't break; no debugger attached + return false; #else return true; #endif } -#ifdef _XBOX -bool bShowComments = false; -#endif - -EXTERN_C void Trace(const TCHAR* szMsg, ...) -{ - va_list args; - va_start(args, szMsg); - -#ifdef _XBOX - if (*szMsg > 0 && *szMsg < 8) - szMsg += 1; // skip over message type (color) specifier - else if (!bShowComments) - return; -#endif - - TCHAR szBuffer [512]; - _vsntprintf(szBuffer, countof(szBuffer), szMsg, args); - - const TCHAR* szODS = szBuffer; - OutputDebugString(szODS); - - va_end(args); -} - void Debug_Init() { - TRACE(_T("This is a debug version of Theseus!\n")); - - _CrtSetAllocHook(DebugAllocHook); + Trace(_T("\001Theseus debug build\n")); } void Debug_Exit() @@ -214,86 +103,19 @@ void Debug_Exit() _CrtDumpMemoryLeaks(); } -void DumpHex(const BYTE* pbData, int cbData, int cbMax) -{ - TCHAR szBuf [256]; - TCHAR szBuf2 [32]; - - bool bTruncated = false; - if (cbMax != 0 && cbData > cbMax) - { - bTruncated = true; - cbData = cbMax; - } - - TCHAR* pch = szBuf; - TCHAR* pch2 = szBuf2; - for (int i = 0; i < cbData; i += 1) - { - BYTE b = *pbData++; - - pch += _stprintf(pch, _T("%02x "), b); - - if (b >= ' ' && b < 128) - *pch2++ = b; - else - *pch2++ = '.'; - - if ((i & 15) == 15 || i == cbData - 1) - { - *pch2 = '\0'; - Trace(_T("%-48s %s\n"), szBuf, szBuf2); - pch = szBuf; - pch2 = szBuf2; - } - } - - if (bTruncated) - Trace(_T("...\n")); -} - +// Walk the heap every five seconds and stop on the first sign of damage. void Debug_Frame() { - static XTIME nextHeapCheckTime; - if (TheseusGetNow() < nextHeapCheckTime) + static XTIME nextCheck; + if (TheseusGetNow() < nextCheck) return; + nextCheck = TheseusGetNow() + 5.0f; - nextHeapCheckTime = TheseusGetNow() + 5.0f; // every 5 seconds... - - // Check heap consistency... - switch (_heapchk()) + int status = _heapchk(); + if (status != _HEAPOK) { - case _HEAPBADBEGIN: - TRACE(_T("\001HEAPCHK: Initial header information is bad or cannot be found\n")); + Trace(_T("\001Heap check failed (%d)\n"), status); _CrtDbgBreak(); - break; - - case _HEAPBADNODE: - TRACE(_T("\001HEAPCHK: Bad node has been found or heap is damaged\n")); - _CrtDbgBreak(); - break; - - case _HEAPBADPTR: - TRACE(_T("\001HEAPCHK: Pointer into heap is not valid\n")); - _CrtDbgBreak(); - break; - - case _HEAPEMPTY: - TRACE(_T("\001HEAPCHK: Heap has not been initialized\n")); - _CrtDbgBreak(); - break; - - case _HEAPOK: - break; - } -} - -void DumpRegisteredClasses() -{ - TRACE(_T("Registered Classes:\n")); - for (CNodeClass* pClass = CNodeClass::c_pFirstClass; pClass != NULL; pClass = pClass->m_nextClass) - { - TRACE(_T("\t%s\n"), pClass->m_className); } } diff --git a/theseus/xbox/dsound_manager.cpp b/theseus/xbox/dsound_manager.cpp index f4209af..354cdf9 100755 --- a/theseus/xbox/dsound_manager.cpp +++ b/theseus/xbox/dsound_manager.cpp @@ -1,7 +1,7 @@ -// dsound_manager.cpp: DirectSound initialization and buffer -// management. Singleton owns the DirectSound device and worker -// thread; provides buffer creation, lock / unlock, and notify -// operations. Xbox-only; desktop has its own SDL audio backend. +// dsound_manager.cpp: the Xbox DirectSound device, its work thread and +// the buffer helpers the audio code uses. Init and buffer creation are +// rebuilt from the 5960 retail XBE (0x626b0, 0x62750); the singleton, +// cleanup and the lock / notify helpers are Theseus's. #include "std.h" #include "theseus.h" @@ -14,19 +14,20 @@ extern "C" extern DWORD g_dwDirectSoundOverrideSpeakerConfig; #define DISC_VIDEO 4 extern int g_nDiscType; -DSoundManager* DSoundManager::pinstance = 0; +DSoundManager* DSoundManager::pinstance = NULL; DSoundManager* DSoundManager::Instance() { - if (pinstance == 0) - { + if (pinstance == NULL) pinstance = new DSoundManager; - } return pinstance; } -DSoundManager::DSoundManager() : m_directSound(NULL), m_hDirectSoundThread(NULL), m_bShutdown(false) +DSoundManager::DSoundManager() { + m_directSound = NULL; + m_hDirectSoundThread = NULL; + m_bShutdown = false; } DSoundManager::~DSoundManager() @@ -34,126 +35,126 @@ DSoundManager::~DSoundManager() Cleanup(); } -static DWORD WINAPI DirectSoundThreadProc(LPVOID pvParameter) +// The DirectSound work thread. 5960 (0x00062680, not split out by the +// decompiler) is: +// while (g_pDirectSound != NULL) { DirectSoundDoWork(); Sleep(100); } +// Theseus stops on its own shutdown flag, set before the device goes away. +static DWORD WINAPI DirectSoundWorker(LPVOID pvParameter) { - DSoundManager *pThis = static_cast(pvParameter); - - while (!pThis->m_bShutdown) + DSoundManager* pManager = (DSoundManager*)pvParameter; + while (!pManager->m_bShutdown) { DirectSoundDoWork(); Sleep(100); } - return 0; } +// DSoundManager::Initialize() +// Reconstructed from 5960 retail XBE @ 0x00062750: +// if (g_BootType == DISC_VIDEO) return false; +// g_dwDirectSoundOverrideSpeakerConfig = (XGetAudioFlags() basic == MONO); +// if (DirectSoundCreate(0, &g_pDirectSound, 0) < 0) return false; +// for (bin = 0; bin < 31; bin++) SetMixBinHeadroom(bin, 0); +// return (g_hThread = CreateThread(0, 0, worker, 0, 0, &id)) != 0; +// The DVD player owns the audio hardware, so a movie disc gets no DirectSound. +// Theseus zeroes only the I3DL2 bin's headroom and returns an HRESULT. HRESULT DSoundManager::Initialize() { - HRESULT hr = S_OK; - if (m_directSound != NULL) return S_FALSE; - if (DISC_VIDEO == g_nDiscType) + if (g_nDiscType == DISC_VIDEO) return E_FAIL; - // Configure speaker output based on AV pack - DWORD dwSpeakerConfig = XAudioGetSpeakerConfig(); - - if (DSSPEAKER_MONO == DSSPEAKER_BASIC(dwSpeakerConfig)) + // Mono stays mono; everything else mixes as stereo and lets the + // hardware encoder handle surround. + if (DSSPEAKER_BASIC(XAudioGetSpeakerConfig()) == DSSPEAKER_MONO) g_dwDirectSoundOverrideSpeakerConfig = DSSPEAKER_COMBINED(DSSPEAKER_MONO, 0); else g_dwDirectSoundOverrideSpeakerConfig = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, 0); - hr = DirectSoundCreate(NULL, &m_directSound, NULL); + HRESULT hr = DirectSoundCreate(NULL, &m_directSound, NULL); if (FAILED(hr)) { - LogComError(hr, "DSound_Init: DirectSoundCreate"); + LogComError(hr, "DirectSoundCreate"); return hr; } - if (FAILED(hr = m_directSound->SetMixBinHeadroom(DSMIXBIN_I3DL2, 0))) - { - LogComError(hr, "DSound_Init: SetMixBinHeadroom"); - } + hr = m_directSound->SetMixBinHeadroom(DSMIXBIN_I3DL2, 0); + if (FAILED(hr)) + LogComError(hr, "SetMixBinHeadroom"); - // Spawn the DirectSoundDoWork polling thread DWORD dwThreadId; - m_hDirectSoundThread = CreateThread(NULL, 0, DirectSoundThreadProc, this, 0, &dwThreadId); - if (!m_hDirectSoundThread) + m_hDirectSoundThread = CreateThread(NULL, 0, DirectSoundWorker, this, 0, &dwThreadId); + if (m_hDirectSoundThread == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); - LogComError(hr, "DSound_Init: failed to create DirectSound worker thread"); - return hr; + LogComError(hr, "CreateThread"); } - return hr; } +// Theseus: shut the worker down and drop the device. HRESULT DSoundManager::Cleanup() { m_bShutdown = true; - - if (m_directSound != NULL) - { - m_directSound->Release(); - m_directSound = NULL; - } - + RELEASENULL(m_directSound); if (m_hDirectSoundThread != NULL) { CloseHandle(m_hDirectSoundThread); m_hDirectSoundThread = NULL; } - return S_OK; } +// DSoundManager::DSoundCreateSoundBuffer(format, bytes, flags, out) +// Reconstructed from 5960 retail XBE @ 0x000626b0: +// if (!g_pDirectSound && !DSound_Init()) return NULL; +// DSBUFFERDESC desc = { 0x18, flags, bytes, format }; +// if (CreateSoundBuffer(&desc, &buf, 0) >= 0) buf->SetHeadroom(1200); +// return buf; +// Theseus hands back the HRESULT and the buffer through pDirectBuf. HRESULT DSoundManager::DSoundCreateSoundBuffer(IN WAVEFORMATEX* pwfx, IN int nByteCount, IN DWORD dwFlags, OUT LPDIRECTSOUNDBUFFER* pDirectBuf) { - HRESULT hr = S_OK; *pDirectBuf = NULL; if (m_directSound == NULL) - hr = Initialize(); - - if (FAILED(hr)) - return hr; - - LPDIRECTSOUNDBUFFER lpDirectSoundBuffer = NULL; - DSBUFFERDESC dsbd; - ZeroMemory(&dsbd, sizeof(DSBUFFERDESC)); - dsbd.dwSize = sizeof(DSBUFFERDESC); - dsbd.dwFlags = dwFlags; - dsbd.dwBufferBytes = nByteCount; - dsbd.lpwfxFormat = pwfx; + { + HRESULT hrInit = Initialize(); + if (FAILED(hrInit)) + return hrInit; + } - hr = m_directSound->CreateSoundBuffer(&dsbd, &lpDirectSoundBuffer, NULL); + DSBUFFERDESC desc; + ZeroMemory(&desc, sizeof(desc)); + desc.dwSize = sizeof(desc); + desc.dwFlags = dwFlags; + desc.dwBufferBytes = nByteCount; + desc.lpwfxFormat = pwfx; + LPDIRECTSOUNDBUFFER pBuffer = NULL; + HRESULT hr = m_directSound->CreateSoundBuffer(&desc, &pBuffer, NULL); if (SUCCEEDED(hr)) - lpDirectSoundBuffer->SetHeadroom(1200); + pBuffer->SetHeadroom(1200); - *pDirectBuf = lpDirectSoundBuffer; + *pDirectBuf = pBuffer; return hr; } +// Theseus: copy data into a buffer. HRESULT DSoundManager::DSoundSetSoundBufferData(LPDIRECTSOUNDBUFFER pDirectSoundBuffer, UINT nByteOffset, UINT nByteCount, const void* pvData) { - LPVOID pbBuffer; - DWORD dwBufferLength; - - ASSERT(pDirectSoundBuffer != NULL); - - HRESULT hr = pDirectSoundBuffer->Lock(nByteOffset, nByteCount, &pbBuffer, &dwBufferLength, NULL, NULL, 0L); + LPVOID pvLocked; + DWORD dwLocked; + HRESULT hr = pDirectSoundBuffer->Lock(nByteOffset, nByteCount, &pvLocked, &dwLocked, NULL, NULL, 0); if (FAILED(hr)) return hr; - - CopyMemory(pbBuffer, pvData, nByteCount); - - hr = pDirectSoundBuffer->Unlock(pbBuffer, dwBufferLength, NULL, 0); - return hr; + memcpy(pvLocked, pvData, nByteCount); + return pDirectSoundBuffer->Unlock(pvLocked, dwLocked, NULL, 0); } +// Theseus: position notifications. HRESULT DSoundManager::DSoundSetSoundBufferNotify(LPDIRECTSOUNDBUFFER pDirectSoundBuffer, int nPositionCount, DSBPOSITIONNOTIFY* positions) { return pDirectSoundBuffer->SetNotificationPositions(nPositionCount, positions); From 40106a85345c827873038a77e3db6de9829647b6 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 03/13] Rebuilt the DiscDrive node and disc detection from the binary The node, its tray polling and GetDiscType are written fresh from 0x39d70..0x3a2b0. DiscManager, the tray buttons and the Discord launch stay as they were. Events, disc types and track times match the old code over 400 drives and 24,000 scripted tray changes. --- docs/decomp/Disc.md | 67 ++++++ theseus/xbox/disc_management.cpp | 370 +++++++++++++------------------ 2 files changed, 223 insertions(+), 214 deletions(-) create mode 100644 docs/decomp/Disc.md diff --git a/docs/decomp/Disc.md b/docs/decomp/Disc.md new file mode 100644 index 0000000..edb9d5a --- /dev/null +++ b/docs/decomp/Disc.md @@ -0,0 +1,67 @@ +# Disc Drive + +The `DiscDrive` node and disc type detection in the 5960 retail binary. The boot disc type lives +at `0x0017aee4`; the node's type names are the table at `0x0017453c` (`none`, `unknown`, `Title`, +`Audio`, `Video`). + +## Functions + +| Address | Name | What it does | +|---------|------|--------------| +| 0x00039d70 | CDiscDrive::CDiscDrive | Joins the drive list, takes the starting type and tray state, below | +| 0x00039ec0 | CDiscDrive::~CDiscDrive | Leaves the list (freeing it when empty), frees the type string | +| 0x00039f20 | CDiscDrive::Advance | Deferred event, then a tray poll every 0.04 s, below | +| 0x0003a030 | CDiscDrive::getTrackCount | Audio track count when the boot type is Audio, else 0 | +| 0x0003a060 | CDiscDrive::FormatTotalTime | Disc length as `%02d:%02d` (see NtIoSvc.md) | +| 0x0003a150 | CDiscDrive::FormatTrackTime | One track's length the same way | +| 0x0003a260 | CDiscDrive::LaunchDisc | Keeps the display up; a game disc reboots the console, anything else `XLaunchNewImage(NULL)` | +| 0x0003a2b0 | GetDiscType | Below | + +## Constructor + +``` +if (g_bHasLaunchData && reason == XLD_LAUNCH_DASHBOARD_DVDPLAYER && DoesFileExist("CDROM0:\video_ts\video_ts.ifo")) + g_BootType = DISC_VIDEO; +if ((g_bHasLaunchData && reason != 0x0C) || g_BootType == DISC_VIDEO || g_BootType == DISC_BAD) + { m_nDiscType = g_BootType; HalReadSMCTrayState(&m_trayState, 0); } +else + { m_nDiscType = DISC_NONE; m_trayState = 0x40; } // the first poll reports the disc +``` + +Reason `0x0C` is a return from the online dashboard. + +## Advance + +``` +if (m_bDeferNotification && !m_locked) { m_bDeferNotification = false; fire inserted or removed; } +if (now - lastPoll < 0.04) return; // 0x0002c1c8, one clock for every drive +lastPoll = now; +if (HalReadSMCTrayState(&tray, 0) < 0 || tray == m_trayState) return; +m_trayState = tray; ResetScreenSaver(); +g_BootType = GetDiscType(); +if (g_BootType == m_nDiscType) return; +m_nDiscType = g_BootType; replace discType string; +if (m_locked) m_bDeferNotification = true; else fire OnDiscInserted (type != none) or OnDiscRemoved; +``` + +## GetDiscType + +``` +close the CD service; IoDismountVolumeByName("\??\CdRom0:"); +if (HalReadSMCTrayState(&tray, 0) >= 0 && tray != 0x60 /* still detecting */) { + if (tray != 0x40 /* no media */) return DISC_NONE; + h = CreateFile("cdrom0:"); if (h == -1) return DISC_NONE; + bad = DeviceIoControl(h, IOCTL_CDROM_CHECK_VERIFY) || GetLastError() == ERROR_UNRECOGNIZED_MEDIA; + CloseHandle(h); return bad ? DISC_BAD : DISC_NONE; +} +open the CD service; if it found audio tracks return DISC_AUDIO; +type = DISC_BAD; +for each of default.xbe (Title), video_ts\video_ts.ifo (Video), track01.cda (Audio) on CDROM0: + if it exists return its type; + an error other than file or path not found retries the same file once after Sleep(100); +if (HalReadSMCTrayState(&tray, 0) >= 0 && tray != 0x60) type = DISC_NONE; // gone meanwhile +return type; +``` + +Theseus launches a game disc's `default.xbe` directly (after its Discord relay) instead of +rebooting, and adds `OpenTray`, `CloseTray` and the CD name lookups. diff --git a/theseus/xbox/disc_management.cpp b/theseus/xbox/disc_management.cpp index 6fe67fd..9b2010a 100755 --- a/theseus/xbox/disc_management.cpp +++ b/theseus/xbox/disc_management.cpp @@ -1,6 +1,8 @@ -// disc_management.cpp: combined disc detection, tray state, CDiscDrive -// node, and disc extraction / file-copy / title-reading helpers. -// Decompiled from the 5960 retail XBE. +// disc_management.cpp: the DiscDrive node, disc type detection and +// Theseus's disc extraction helpers. The node and GetDiscType are rebuilt +// from the 5960 retail XBE (0x39d70..0x3a2b0); see docs/decomp/Disc.md. +// Tray control, the CD name lookups, the Discord relay and DiscManager +// are Theseus's. #include "std.h" #include "theseus.h" @@ -20,33 +22,27 @@ extern CConfig *theConfig; -// ========================================================================= -// Disc type table -// ========================================================================= - int GetDiscType(); +// discType strings by DISC_ value (5960 table @ 0x0017453c). static const TCHAR *rgszDiscType[] = - { - _T("none"), - _T("unknown"), - _T("Title"), - _T("Audio"), - _T("Video"), +{ + _T("none"), + _T("unknown"), + _T("Title"), + _T("Audio"), + _T("Video"), }; int g_nDiscType; +// Theseus: 5960 does this inline in CXApp::InitApp (0x0002d7e0). void DiscDrive_Init() { g_cdrom.Open(1); g_nDiscType = GetDiscType(); } -// ========================================================================= -// CDiscDrive node -// ========================================================================= - class CDiscDrive : public CNode { DECLARE_NODE(CDiscDrive, CNode) @@ -56,9 +52,8 @@ class CDiscDrive : public CNode void Advance(float nSeconds); - TCHAR *m_discType; // none, unknown, Audio, Video, Photo, Title + TCHAR *m_discType; - // Audio CD (CDDA) Information... int getTrackCount(); CStrObject *FormatTotalTime(); CStrObject *FormatTrackTime(int nTrack); @@ -82,12 +77,12 @@ class CDiscDrive : public CNode private: ULONG m_trayState; bool m_bDeferNotification; + + void SetDiscTypeString(); + void NotifyDiscChange(); }; -// Events: -// -// OnDiscInserted -// OnDiscRemoved +// Script events: OnDiscInserted, OnDiscRemoved. CNodeArray CDiscDrive::c_drives; @@ -116,24 +111,38 @@ NODE_FUN_SI(getTrackName) END_NODE_FUN() #undef _FND_CLASS -CDiscDrive::CDiscDrive() : m_locked(false), - m_bDeferNotification(false) +// Copies the name for m_nDiscType into the discType property. +void CDiscDrive::SetDiscTypeString() +{ + const TCHAR *szName = rgszDiscType[m_nDiscType]; + m_discType = new TCHAR[_tcslen(szName) + 1]; + _tcscpy(m_discType, szName); +} + +void CDiscDrive::NotifyDiscChange() +{ + CallFunction(this, m_nDiscType != DISC_NONE ? _T("OnDiscInserted") : _T("OnDiscRemoved")); +} + +// CDiscDrive::CDiscDrive() +// Reconstructed from 5960 retail XBE @ 0x00039d70: joins the drive list +// (and holds a reference), unlocked, nothing deferred. A dash started with +// launch data, or on a movie or unreadable disc, takes the boot disc type +// and the tray as they are. Otherwise it starts at "none" with an empty +// tray, so the first poll sees the disc and fires OnDiscInserted. +// A movie disc can't wait for that: playing one reboots, and it would loop. +CDiscDrive::CDiscDrive() { + m_locked = false; + m_bDeferNotification = false; + c_drives.AddNode(this); AddRef(); - // - // Mark the disc type to DISC_NONE if it's not a DVD movie (bug 9014) - // so that Advance will catch change notification and reboot to title. - // For DVD movies, we have to mark as DISC_VIDEO because the way the - // dash plays DVD is to reboot. If we let Advance to catch notification - // the dash will end up reboot infinitely. - // - if (TheseusHasLaunchData() || g_nDiscType == DISC_VIDEO || g_nDiscType == DISC_BAD) { m_nDiscType = g_nDiscType; - HalReadSMCTrayState(&m_trayState, 0); + HalReadSMCTrayState(&m_trayState, NULL); } else { @@ -141,33 +150,33 @@ CDiscDrive::CDiscDrive() : m_locked(false), m_trayState = SMC_TRAY_STATE_NO_MEDIA; } - const TCHAR *szDiscType = rgszDiscType[m_nDiscType]; - - m_discType = new TCHAR[_tcslen(szDiscType) + 1]; - _tcscpy(m_discType, szDiscType); - - TRACE(_T("CDiscDrive: %s\n"), szDiscType); + SetDiscTypeString(); } +// CDiscDrive::~CDiscDrive() +// Reconstructed from 5960 retail XBE @ 0x00039ec0: +// c_drives.RemoveNode(this); if (c_drives.count == 0) c_drives.free(); +// delete m_discType; CDiscDrive::~CDiscDrive() { c_drives.RemoveNode(this); if (c_drives.GetLength() == 0) c_drives.RemoveAll(); - delete[] m_discType; } +// CDiscDrive::Advance(dt) +// Reconstructed from 5960 retail XBE @ 0x00039f20. A change held back while +// locked fires as soon as the drive unlocks. Every 0.04 s (one clock shared +// by all drives) the SMC tray state is read; when it moves, the screen saver +// wakes and the disc is typed again. A new type renames discType and fires +// OnDiscInserted or OnDiscRemoved, or is deferred while locked. void CDiscDrive::Advance(float nSeconds) { - // Check if we need to reboot if (m_bDeferNotification && !m_locked) { m_bDeferNotification = false; - if (m_nDiscType != DISC_NONE) - CallFunction(this, _T("OnDiscInserted")); - else - CallFunction(this, _T("OnDiscRemoved")); + NotifyDiscChange(); } static XTIME lastPoll = 0.0f; @@ -175,264 +184,197 @@ void CDiscDrive::Advance(float nSeconds) return; lastPoll = TheseusGetNow(); - // Poll state of the DVD tray by reading from SMC - NTSTATUS Status; - ULONG TrayState; - - Status = HalReadSMCTrayState(&TrayState, NULL); - if (!NT_SUCCESS(Status)) + ULONG trayState; + if (!NT_SUCCESS(HalReadSMCTrayState(&trayState, NULL)) || trayState == m_trayState) return; + m_trayState = trayState; - if (TrayState == m_trayState) - return; - m_trayState = TrayState; - - // Reset screen saver if tray state changes ResetScreenSaver(); g_nDiscType = GetDiscType(); + if (g_nDiscType == m_nDiscType) + return; - if (m_nDiscType != g_nDiscType) - { - TRACE(_T("\001Disc type: %s\n"), rgszDiscType[g_nDiscType]); - m_nDiscType = g_nDiscType; - - delete[] m_discType; - m_discType = new TCHAR[_tcslen(rgszDiscType[m_nDiscType]) + 1]; - _tcscpy(m_discType, rgszDiscType[m_nDiscType]); + m_nDiscType = g_nDiscType; + delete[] m_discType; + SetDiscTypeString(); - if (!m_locked) - { - if (m_nDiscType != DISC_NONE) - CallFunction(this, _T("OnDiscInserted")); - else - CallFunction(this, _T("OnDiscRemoved")); - } - else - { - m_bDeferNotification = true; - } - } + if (m_locked) + m_bDeferNotification = true; + else + NotifyDiscChange(); } -// ========================================================================= -// Audio CD helpers -// ========================================================================= - +// CDiscDrive::getTrackCount() [script fn 'getTrackCount', FND 0x0017fd48, sig 2] +// Reconstructed from 5960 retail XBE @ 0x0003a030: +// return g_BootType == DISC_AUDIO ? g_cdrom.GetTrackCount() : 0; int CDiscDrive::getTrackCount() { - if (g_nDiscType == DISC_AUDIO) - return g_cdrom.GetTrackCount(); + return g_nDiscType == DISC_AUDIO ? g_cdrom.GetTrackCount() : 0; +} - return 0; +// "mm:ss", or "" when there's nothing to time. +static CStrObject *FormatMinutesSeconds(bool bHave, int nMinutes, int nSeconds) +{ + if (!bHave) + return new CStrObject; + TCHAR szTime[8]; + _stprintf(szTime, _T("%02d:%02d"), nMinutes, nSeconds); + return new CStrObject(szTime); } +// CDiscDrive::FormatTotalTime() [script fn 'FormatTotalTime', FND 0x0017fd60, sig 8] +// CDiscDrive::FormatTrackTime(n) [script fn 'FormatTrackTime', FND 0x0017fd78, sig 4] +// Reconstructed from 5960 retail XBE @ 0x0003a060 and 0x0003a150: the disc's +// or track n's length as "%02d:%02d", empty with no disc or a bad track. +// The frame math is in CNtIoctlCdromService (see docs/decomp/NtIoSvc.md). CStrObject *CDiscDrive::FormatTotalTime() { int nMinutes, nSeconds; - if (!g_cdrom.GetTotalLength(&nMinutes, &nSeconds, NULL)) - return new CStrObject; // empty string - - TCHAR szBuf[8]; - _stprintf(szBuf, _T("%02d:%02d"), nMinutes, nSeconds); - return new CStrObject(szBuf); + bool bHave = g_cdrom.GetTotalLength(&nMinutes, &nSeconds, NULL); + return FormatMinutesSeconds(bHave, nMinutes, nSeconds); } CStrObject *CDiscDrive::FormatTrackTime(int nTrack) { int nMinutes, nSeconds; - if (!g_cdrom.GetTrackLength(nTrack, &nMinutes, &nSeconds, NULL)) - return new CStrObject; // empty string + bool bHave = g_cdrom.GetTrackLength(nTrack, &nMinutes, &nSeconds, NULL); + return FormatMinutesSeconds(bHave, nMinutes, nSeconds); +} - TCHAR szBuf[8]; - _stprintf(szBuf, _T("%02d:%02d"), nMinutes, nSeconds); - return new CStrObject(szBuf); +// Theseus: the CD's names, empty until something fills them in. +static CStrObject *StrOrEmpty(const TCHAR *sz) +{ + return new CStrObject(sz != NULL ? sz : _T("")); } CStrObject *CDiscDrive::getArtist() { - const TCHAR *szArtist = g_cdrom.GetArtist(); - if (szArtist == NULL) - szArtist = _T(""); - return new CStrObject(szArtist); + return StrOrEmpty(g_cdrom.GetArtist()); } CStrObject *CDiscDrive::getTitle() { - const TCHAR *szTitle = g_cdrom.GetTitle(); - if (szTitle == NULL) - szTitle = _T(""); - return new CStrObject(szTitle); + return StrOrEmpty(g_cdrom.GetTitle()); } CStrObject *CDiscDrive::getTrackName(int nTrack) { - const TCHAR *szTrackName = g_cdrom.GetTrackName(nTrack); - if (szTrackName == NULL) - szTrackName = _T(""); - return new CStrObject(szTrackName); + return StrOrEmpty(g_cdrom.GetTrackName(nTrack)); } -// ========================================================================= -// Disc launch -// ========================================================================= - +// CDiscDrive::LaunchDisc() [script fn 'LaunchDisc', FND 0x0017fd90, sig 1] +// Reconstructed from 5960 retail XBE @ 0x0003a260: +// PersistDisplay(); +// if (g_BootType == DISC_TITLE) HalReturnToFirmware(HalRebootRoutine); +// XLaunchNewImage(NULL, NULL); +// 5960 reboots into a game disc. Theseus launches d:\default.xbe directly +// instead, after a short settle and the Discord relay with its title ID. void CDiscDrive::LaunchDisc() { - TRACE(_T("[Discord] CDiscDrive::LaunchDisc() triggered\n")); TheseusGetD3DDev()->PersistDisplay(); - ASSERT(g_nDiscType != DISC_AUDIO); - Sleep(500); // optional delay, since we have CCI's and ISO's loading. - OutputDebugString(_T("[Discord] Attempting to read title ID from \\Device\\CdRom0\\\n")); + Sleep(500); - CStrObject *titleIdStr = theConfig->GetXBETitleID(_T("D:")); - if (titleIdStr) + CStrObject *pTitleId = theConfig->GetXBETitleID(_T("D:")); + if (pTitleId != NULL) { - const TCHAR *szTitleId = titleIdStr->GetSz(); - char szAnsiTitleId[11]; // 8 hex digits + null terminator - Ansi(szAnsiTitleId, szTitleId, sizeof(szAnsiTitleId)); - // Report TitleID to OutputDebugString - TCHAR szDebugMsg[64]; - _stprintf(szDebugMsg, _T("[Discord] Title ID: %s\n"), szTitleId); - OutputDebugString(szDebugMsg); - - OutputDebugString(_T("[Discord] Sending relay...\n")); - SendDiscordRelayFromConfig(szAnsiTitleId); - - delete titleIdStr; + char szTitleId[11]; + Ansi(szTitleId, pTitleId->GetSz(), sizeof(szTitleId)); + SendDiscordRelayFromConfig(szTitleId); + delete pTitleId; } - else - { - OutputDebugString(_T("[Discord] Discord disabled. Launching normally.\n")); - } - XLaunchNewImage(g_nDiscType == DISC_TITLE ? "d:\\default.xbe" : NULL, NULL); } -// ========================================================================= -// Tray control -// ========================================================================= - +// Theseus: the tray, through the SMC's tray register. void CDiscDrive::OpenTray() { - // Tray Open HalWriteSMBusValue(0x20, 0x0C, 0, 0x00); Sleep(1); } void CDiscDrive::CloseTray() { - // Tray Close HalWriteSMBusValue(0x20, 0x0C, 0, 0x01); Sleep(1); } -// ========================================================================= -// GetDiscType: detect what kind of media is in the drive. -// ========================================================================= - +// The files that mark each disc type, checked in order (5960 table @ 0x000201c8). struct DISCTYPECHECK { - TCHAR *szPath; - TCHAR *szDiscType; + const TCHAR *szPath; + const TCHAR *szDiscType; int nDiscType; }; static const DISCTYPECHECK rgddc[] = - { - {_T("CDROM0:\\default.xbe"), _T("Title"), DISC_TITLE}, - {_T("CDROM0:\\video_ts\\video_ts.ifo"), _T("Video"), DISC_VIDEO}, - {_T("CDROM0:\\track01.cda"), _T("Audio"), DISC_AUDIO}, +{ + {_T("CDROM0:\\default.xbe"), _T("Title"), DISC_TITLE}, + {_T("CDROM0:\\video_ts\\video_ts.ifo"), _T("Video"), DISC_VIDEO}, + {_T("CDROM0:\\track01.cda"), _T("Audio"), DISC_AUDIO}, }; +// GetDiscType() +// Reconstructed from 5960 retail XBE @ 0x0003a2b0. Closes the CD service +// and dismounts \??\CdRom0: so the next look is fresh. If the SMC says the +// tray is settled (not still detecting): an empty tray is told apart from an +// unreadable disc by asking the drive (IOCTL_CDROM_CHECK_VERIFY; success or +// ERROR_UNRECOGNIZED_MEDIA means a bad disc), anything else is no disc. +// Otherwise an audio TOC makes it Audio, then the marker files decide; a +// lookup failing with anything but not found gets one retry after 100 ms. +// See docs/decomp/Disc.md for the instruction walk. int GetDiscType() { - int nDiscType = DISC_BAD; - bool bRetry = true; - if (g_cdrom.IsOpen()) g_cdrom.Close(); - OBJECT_STRING DeviceName; - RtlInitObjectString(&DeviceName, "\\??\\CdRom0:"); - IoDismountVolumeByName(&DeviceName); + OBJECT_STRING cdrom; + RtlInitObjectString(&cdrom, "\\??\\CdRom0:"); + IoDismountVolumeByName(&cdrom); - NTSTATUS Status; - ULONG TrayState; - Status = HalReadSMCTrayState(&TrayState, NULL); - if (NT_SUCCESS(Status) && TrayState != SMC_TRAY_STATE_MEDIA_DETECT) + ULONG trayState; + if (NT_SUCCESS(HalReadSMCTrayState(&trayState, NULL)) && trayState != SMC_TRAY_STATE_MEDIA_DETECT) { - if (TrayState == SMC_TRAY_STATE_NO_MEDIA) - { - HANDLE hDevice; - - // At this point, the drive has told the SMC that media could not be - // detected. To decide whether this means that the tray is empty - // versus the tray have unrecognized media, we need to send an IOCTL - // to the device. - - hDevice = CreateFileA("cdrom0:", GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - if (hDevice != INVALID_HANDLE_VALUE && hDevice != NULL) - { - BOOL fReturn; - DWORD cbReturned; - - fReturn = DeviceIoControl(hDevice, IOCTL_CDROM_CHECK_VERIFY, - NULL, 0, NULL, 0, &cbReturned, NULL); - - // If the device reports back that the unit is ready (which it - // shouldn't since the SMC thinks the tray is empty) or if the - // media is unrecognized, then the disc is bad. - if (fReturn || (GetLastError() == ERROR_UNRECOGNIZED_MEDIA)) - { - CloseHandle(hDevice); - return DISC_BAD; - } - - CloseHandle(hDevice); - } - } - - return DISC_NONE; + if (trayState != SMC_TRAY_STATE_NO_MEDIA) + return DISC_NONE; + + HANDLE hDrive = CreateFileA("cdrom0:", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hDrive == INVALID_HANDLE_VALUE || hDrive == NULL) + return DISC_NONE; + + DWORD cbReturned; + bool bBad = DeviceIoControl(hDrive, IOCTL_CDROM_CHECK_VERIFY, NULL, 0, NULL, 0, &cbReturned, NULL) || + GetLastError() == ERROR_UNRECOGNIZED_MEDIA; + CloseHandle(hDrive); + return bBad ? DISC_BAD : DISC_NONE; } g_cdrom.Open(1); - if (g_cdrom.IsOpen()) return DISC_AUDIO; - for (int i = 0; i < sizeof(rgddc) / sizeof(DISCTYPECHECK);) + bool bMayRetry = true; + int i = 0; + while (i < (int)countof(rgddc)) { if (DoesFileExist(rgddc[i].szPath)) - { - nDiscType = rgddc[i].nDiscType; - break; - } + return rgddc[i].nDiscType; DWORD dwError = GetLastError(); - - if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) + if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND && bMayRetry) { - TRACE(_T("\001Error %d on %s\n"), dwError, rgddc[i].szPath); - - if (bRetry) - { - TRACE(_T("Retrying...\n")); - bRetry = false; - Sleep(100); - continue; - } + bMayRetry = false; + Sleep(100); + continue; } - i += 1; - bRetry = true; + i++; + bMayRetry = true; } - return nDiscType; + return DISC_BAD; } // ========================================================================= From cdcc8d32f7821e5f59ceb631bb8c933b4e115e36 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 04/13] Rebuilt the Xbox Config node from the binary Language, video, audio, time zone, ratings, pass codes, launch data and the misc flags are written fresh from 0x3a430..0x3b9e0. The modchip, SMBus, power, skin and network functions stay Theseus's. Every rebuilt function matches the old code over 30,000 randomized EEPROM states, plus 108 font file cases. --- docs/decomp/Config.md | 50 +++ theseus/xbox/config.cpp | 758 ++++++++++++++++++++-------------------- theseus/xbox/config.h | 17 +- 3 files changed, 439 insertions(+), 386 deletions(-) create mode 100644 docs/decomp/Config.md diff --git a/docs/decomp/Config.md b/docs/decomp/Config.md new file mode 100644 index 0000000..f0ee0c8 --- /dev/null +++ b/docs/decomp/Config.md @@ -0,0 +1,50 @@ +# Config + +The `Config` node in the 5960 retail binary (`0x0003a430..0x0003b9e0`, FND table at `0x0017fdf0`). +Nearly everything is one EEPROM DWORD read with `XQueryValue` and written back with `XSetValue`; +5960 never checks either result. + +| Setting | Index | Bits used | +|---------|-------|-----------| +| Language | 7 (`XC_LANGUAGE`) | whole value; 0 or past the last language reads as 1 (English) | +| Video flags | 8 | widescreen 0x10000, 720p 0x20000, 1080i 0x40000, 480p 0x80000, letterbox 0x100000, PAL60 0x400000 | +| Audio flags | 9 | low word speakers (0 stereo, 1 mono, 2 surround), Dolby Digital 0x10000, DTS 0x20000 | +| Game rating | 10 | stored as 6 - level | +| Pass code | 11 | one nibble per pad press, below | +| Movie rating | 12 | stored as 7 - level | +| Misc flags | 0x11 | don't use DST 2, hide Live today 4, legal notice accepted 8 | + +## Notes per function + +- `GetVideoMode` (`0x0003a860`): letterbox wins (1), else widescreen (2), else 0. + `SetVideoMode` (`0x0003a8a0`) clears both, sets the chosen one and, if widescreen changed, flips the + widescreen present flag, zeroes D3D's cached AV mode and resets the device; it always marks the + projection dirty. +- `Set480Support` (`0x0003a980`): stores the bit; while a DVD plays on an HDTV pack with the 480p + Macrovision hardware flag it also switches the display between progressive and interlaced. +- `GetAudioMode` / `SetAudioMode` (`0x0003abb0`, `0x0003abf0`): script modes 0 mono, 1 stereo, + 2 surround; the encodings in the high word stay. +- `EncodePassword` (`0x0003b0a0`): `code = code * 16 + n` per character with u1 d2 l3 r4 a5 b6 x7 y8 + B9 W10 L11 R12, anything else 0. +- `GetTimeZone` (`0x0003ae80`): with no zone set the default is 11, 60 or 25 by game region (North + America, Japan, elsewhere). `GetDSTAllowed` / `GetDST` need both transition months set. +- `GetLaunchReason` (`0x0003b2d0`): names by reason through the jump table at `0x0003b3ac`: + 1 Error, 2 Memory, 3 Settings, 4 Music, 12 FromOnlineDash, 13 FriendsInternal, 14 VoiceChatInternal, + 15 MessagesInternal, 16 AccountManagementInternal, 17 NewAccountInternal, 18 AccountRecoveryInternal, + 19 NetworkSettingsInternal; anything else, or no launch data, gives an empty string. +- `ForceSetLanguage` / `ForceSetTimeZone` / `ForceSetClock` (`0x0003a430..0x0003a470`): reason 3 and + bit 4, 2 or 1 of the first launch parameter. +- `BackToLauncher` (`0x0003b4b0`): a forced language, zone or clock reboots; otherwise + `default.xbe` on `\Device\CdRom0` relaunches with the launch context. +- `BackToLauncher2` (`0x0003b550`): `settings_adoc.xip`, title 0xFFFE0000, context 'ADOC', from + wherever the dash's own drive link points. +- `GetFontVersion` (`0x0003a520`): the top byte of the font file's first DWORD as a digit, cached in + the node (+0x1c), -1 when there is no font file. +- `GetROMVersion` / `GetXdashVersion` (`0x0003b7b0`, `0x0003b860`): `%d.%02d.%d.%02d`; the dash + prints 1, 0, 5960, 1. +- `GetEthernetLinkStatus` (`0x0003b9d0`): `XNetGetEthernetLinkStatus() & 1`. + +Theseus differs on purpose in `NtFileExists` / `FileExists` (drive letter mapping instead of +`NtOpenFile`), `GetRecoveryKey` (empty), `GoToXOnlineDash` (logs only), `ToggleNoisyCamera` (skin +setting instead of `T:\NoisyCamera`), `GetFontVersion` (system fonts per language), and adds the +SMBus, power, network, skin, modchip and XBE title id functions. diff --git a/theseus/xbox/config.cpp b/theseus/xbox/config.cpp index 816a7a5..4194305 100755 --- a/theseus/xbox/config.cpp +++ b/theseus/xbox/config.cpp @@ -1,7 +1,8 @@ -// config.cpp: CConfig XAP node. Reads / writes the dashboard's -// system config (timezone, language, av mode, parental ratings, -// audio mode) through the Xbox EEPROM via XConfig. Decompiled from -// the 5960 retail XBE. +// config.cpp: the Xbox Config node. Language, video, audio, time zone, +// parental controls, launch data and the other EEPROM settings are +// rebuilt from the 5960 retail XBE (0x3a430..0x3b9e0); see +// docs/decomp/Config.md. Skins, network, power, the SMBus readings, the +// encoder / revision / modchip probes and XBE title ids are Theseus's. #include "std.h" #include "theseus.h" @@ -24,7 +25,7 @@ extern void Material_Init(bool bReloadSkinXBX); void InitSkin(); -// Cached AV info in Direct3D. Must be cleared before toggling widescreen. +// D3D caches the AV mode here; zero it so a Reset picks up a new one. extern "C" { extern DWORD D3D__AvInfo; @@ -118,270 +119,228 @@ END_NODE_FUN() CConfig::CConfig() { } CConfig::~CConfig() { } -// ========================================================================= -// EEPROM helpers: read / write Xbox configuration values. -// ========================================================================= - -static DWORD QueryVideoFlags() -{ - DWORD dwFlags, dwType; - VERIFY(!XQueryValue(XC_VIDEO_FLAGS, &dwType, &dwFlags, 4, NULL)); - return dwFlags; -} - -static void SetVideoFlags(DWORD dwFlags) -{ - VERIFY(!XSetValue(XC_VIDEO_FLAGS, REG_DWORD, (DWORD *)&dwFlags, 4)); -} - -static DWORD QueryAudioFlags() +// Every EEPROM setting below is a whole DWORD read and written back. 5960 +// ignores the results of XQueryValue / XSetValue throughout. +static DWORD ReadSetting(DWORD dwIndex) { - DWORD dwFlags, dwType; - VERIFY(!XQueryValue(XC_AUDIO_FLAGS, &dwType, &dwFlags, 4, NULL)); - return dwFlags; + DWORD dwType, dwValue; + XQueryValue(dwIndex, &dwType, &dwValue, sizeof(dwValue), NULL); + return dwValue; } -static void SetAudioFlags(DWORD dwFlags) +static void WriteSetting(DWORD dwIndex, DWORD dwValue) { - VERIFY(!XSetValue(XC_AUDIO_FLAGS, REG_DWORD, (DWORD *)&dwFlags, 4)); + XSetValue(dwIndex, REG_DWORD, &dwValue, sizeof(dwValue)); } -static DWORD QueryMiscFlags() +static void WriteSettingBit(DWORD dwIndex, DWORD dwBit, bool bSet) { - DWORD dwType, value = 0; - XQueryValue(XC_MISC_FLAGS, &dwType, &value, sizeof(value), NULL); - return value; + DWORD dwValue = ReadSetting(dwIndex); + if (bSet) + dwValue |= dwBit; + else + dwValue &= ~dwBit; + WriteSetting(dwIndex, dwValue); } -static void SetMiscFlags(DWORD value) +// Theseus starts the misc flags at zero when the read fails. +static DWORD ReadMiscFlags() { - XSetValue(XC_MISC_FLAGS, REG_DWORD, (DWORD *)&value, sizeof(value)); + DWORD dwType, dwValue = 0; + XQueryValue(XC_MISC_FLAGS, &dwType, &dwValue, sizeof(dwValue), NULL); + return dwValue; } -// ========================================================================= -// Language -// ========================================================================= - +// CConfig::GetLanguage() [script fn 'GetLanguage', FND 0x0017fe08, sig 2] +// Reconstructed from 5960 retail XBE @ 0x0003a610: +// XQueryValue(XC_LANGUAGE, ..); max = GetFontVersion() ? 9 : 6; +// if (lang == 0 || lang > max) lang = 1; return lang; +// An unset or unknown language reads as English. Theseus caps it at 6. int CConfig::GetLanguage() { - DWORD nLanguage, dwType; - VERIFY(!XQueryValue(XC_LANGUAGE, &dwType, &nLanguage, 4, NULL)); - - if (nLanguage == 0 || nLanguage > 6) - { - TRACE(_T("\001Invalid language, default to English\n")); - nLanguage = 1; - } - - return (int)nLanguage; + DWORD dwLanguage = ReadSetting(XC_LANGUAGE); + if (dwLanguage == 0 || dwLanguage > 6) + dwLanguage = 1; + return (int)dwLanguage; } +// CConfig::SetLanguage(n) [script fn 'SetLanguage', FND 0x0017fe20, sig 14] +// Reconstructed from 5960 retail XBE @ 0x0003a660: XSetValue(XC_LANGUAGE, n). void CConfig::SetLanguage(int nLanguage) { - VERIFY(!XSetValue(XC_LANGUAGE, REG_DWORD, (DWORD *)&nLanguage, 4)); + WriteSetting(XC_LANGUAGE, (DWORD)nLanguage); } -// ========================================================================= -// AV pack / region identification -// ========================================================================= - +// CConfig::GetAVPackType() [script fn 'GetAVPackType', FND 0x00180018, sig 8] +// CConfig::GetAVRegion() [script fn 'GetAVRegion', FND 0x00180030, sig 8] +// CConfig::GetGameRegion() [script fn 'GetGameRegion', FND 0x00180048, sig 8] +// Reconstructed from 5960 retail XBE @ 0x0003a680, 0x0003a740, 0x0003a7e0: +// XGetAVPack(), XGetVideoStandard() and the game region, each switched to +// its name; an unknown value gives a string object with no text. CStrObject *CConfig::GetAVPackType() { - const TCHAR *sz = NULL; + const TCHAR *szName = NULL; switch (XGetAVPack()) { - case XC_AV_PACK_STANDARD: sz = _T("STANDARD"); break; - case XC_AV_PACK_SVIDEO: sz = _T("SVIDEO"); break; - case XC_AV_PACK_RFU: sz = _T("RFU"); break; - case XC_AV_PACK_SCART: sz = _T("SCART"); break; - case XC_AV_PACK_HDTV: sz = _T("HDTV"); break; - case XC_AV_PACK_VGA: sz = _T("VGA"); break; + case XC_AV_PACK_SCART: szName = _T("SCART"); break; + case XC_AV_PACK_HDTV: szName = _T("HDTV"); break; + case XC_AV_PACK_VGA: szName = _T("VGA"); break; + case XC_AV_PACK_RFU: szName = _T("RFU"); break; + case XC_AV_PACK_SVIDEO: szName = _T("SVIDEO"); break; + case XC_AV_PACK_STANDARD: szName = _T("STANDARD"); break; } - return new CStrObject(sz); + return new CStrObject(szName); } CStrObject *CConfig::GetAVRegion() { - const TCHAR *sz = NULL; + const TCHAR *szName = NULL; switch (XGetVideoStandard()) { - case XC_VIDEO_STANDARD_NTSC_M: sz = _T("NTSC_M"); break; - case XC_VIDEO_STANDARD_NTSC_J: sz = _T("NTSC_J"); break; - case XC_VIDEO_STANDARD_PAL_I: sz = _T("PAL_I"); break; - case XC_VIDEO_STANDARD_PAL_M: sz = _T("PAL_M"); break; + case XC_VIDEO_STANDARD_NTSC_M: szName = _T("NTSC_M"); break; + case XC_VIDEO_STANDARD_NTSC_J: szName = _T("NTSC_J"); break; + case XC_VIDEO_STANDARD_PAL_I: szName = _T("PAL_I"); break; + case XC_VIDEO_STANDARD_PAL_M: szName = _T("PAL_M"); break; } - return new CStrObject(sz); + return new CStrObject(szName); } CStrObject *CConfig::GetGameRegion() { - const TCHAR *sz = NULL; + const TCHAR *szName = NULL; switch (g_nCurRegion) { - case XC_GAME_REGION_NA: sz = _T("NA"); break; - case XC_GAME_REGION_JAPAN: sz = _T("JAPAN"); break; - case XC_GAME_REGION_RESTOFWORLD: sz = _T("RESTOFWORLD"); break; + case XC_GAME_REGION_NA: szName = _T("NA"); break; + case XC_GAME_REGION_JAPAN: szName = _T("JAPAN"); break; + case XC_GAME_REGION_RESTOFWORLD: szName = _T("RESTOFWORLD"); break; } - return new CStrObject(sz); + return new CStrObject(szName); } -// ========================================================================= -// Video mode: normal / letterbox / widescreen. -// ========================================================================= +// The D3D present flags changed: drop the cached AV mode and reset. +static void ResetDisplay() +{ + D3D__AvInfo = 0; + TheseusGetD3DDev()->Reset(&g_pp); + TheseusInvalidateStateCache(); +} +// CConfig::GetVideoMode() [script fn 'GetVideoMode', FND 0x001800f0, sig 2] +// Reconstructed from 5960 retail XBE @ 0x0003a860: +// if (flags & AV_FLAGS_LETTERBOX) return 1; return (flags >> 15) & 2; +// 0 normal, 1 letterbox, 2 widescreen; letterbox wins if both are set. int CConfig::GetVideoMode() { - DWORD dwFlags = QueryVideoFlags(); - if (dwFlags & AV_FLAGS_LETTERBOX) return 1; - if (dwFlags & AV_FLAGS_WIDESCREEN) return 2; - return 0; + DWORD dwFlags = ReadSetting(XC_VIDEO_FLAGS); + if (dwFlags & AV_FLAGS_LETTERBOX) + return 1; + return (dwFlags & AV_FLAGS_WIDESCREEN) ? 2 : 0; } +// CConfig::SetVideoMode(mode) [FND 0x00180108] +// Reconstructed from 5960 retail XBE @ 0x0003a8a0. Stores letterbox (1) or +// widescreen (2), clearing the other. Going in or out of widescreen flips +// the widescreen present flag and resets the device; the projection is +// rebuilt either way. Theseus also invalidates its render state cache. void CConfig::SetVideoMode(int nVideoMode) { - DWORD dwFlags = QueryVideoFlags(); - dwFlags &= ~(AV_FLAGS_WIDESCREEN | AV_FLAGS_LETTERBOX); - + DWORD dwFlags = ReadSetting(XC_VIDEO_FLAGS) & ~(AV_FLAGS_WIDESCREEN | AV_FLAGS_LETTERBOX); if (nVideoMode == 1) dwFlags |= AV_FLAGS_LETTERBOX; else if (nVideoMode == 2) dwFlags |= AV_FLAGS_WIDESCREEN; + WriteSetting(XC_VIDEO_FLAGS, dwFlags); - SetVideoFlags(dwFlags); - - bool bWideScreen = nVideoMode == 2; - if (g_bStretchWidescreen != bWideScreen) + bool bWide = (nVideoMode == 2); + if (bWide != g_bStretchWidescreen) { - if (bWideScreen) + if (bWide) g_pp.Flags |= D3DPRESENTFLAG_WIDESCREEN; else g_pp.Flags &= ~D3DPRESENTFLAG_WIDESCREEN; - - g_bStretchWidescreen = bWideScreen; - D3D__AvInfo = 0; - TheseusGetD3DDev()->Reset(&g_pp); - TheseusInvalidateStateCache(); + g_bStretchWidescreen = bWide; + ResetDisplay(); } g_bProjectionDirty = true; } -// ========================================================================= -// HDTV resolution support -// ========================================================================= - -int CConfig::Get480Support() { return (QueryVideoFlags() & AV_FLAGS_HDTV_480p) != 0; } -int CConfig::Get720Support() { return (QueryVideoFlags() & AV_FLAGS_HDTV_720p) != 0; } -int CConfig::Get1080Support() { return (QueryVideoFlags() & AV_FLAGS_HDTV_1080i) != 0; } -int CConfig::GetPAL60Support(){ return (QueryVideoFlags() & AV_FLAGS_60Hz) != 0; } - +// Get/Set 480p, 720p, 1080i and PAL60 [FND 0x0017ff58..0x00180000] +// Reconstructed from 5960 retail XBE @ 0x0003a950..0x0003ab60: one bit each +// of XC_VIDEO_FLAGS (0x80000, 0x20000, 0x40000, 0x400000). +int CConfig::Get480Support() { return (ReadSetting(XC_VIDEO_FLAGS) & AV_FLAGS_HDTV_480p) != 0; } +int CConfig::Get720Support() { return (ReadSetting(XC_VIDEO_FLAGS) & AV_FLAGS_HDTV_720p) != 0; } +int CConfig::Get1080Support() { return (ReadSetting(XC_VIDEO_FLAGS) & AV_FLAGS_HDTV_1080i) != 0; } +int CConfig::GetPAL60Support() { return (ReadSetting(XC_VIDEO_FLAGS) & AV_FLAGS_60Hz) != 0; } + +void CConfig::Set720Support(int bEnable) { WriteSettingBit(XC_VIDEO_FLAGS, AV_FLAGS_HDTV_720p, bEnable != 0); } +void CConfig::Set1080Support(int bEnable) { WriteSettingBit(XC_VIDEO_FLAGS, AV_FLAGS_HDTV_1080i, bEnable != 0); } +void CConfig::SetPAL60Support(int bEnable) { WriteSettingBit(XC_VIDEO_FLAGS, AV_FLAGS_60Hz, bEnable != 0); } + +// CConfig::Set480Support(on) [FND 0x0017ff70] +// Reconstructed from 5960 retail XBE @ 0x0003a980. Stores the bit. While a +// DVD plays on an HDTV pack with 480p Macrovision support, the display also +// switches between progressive and interlaced on the spot when the setting +// disagrees with it. void CConfig::Set480Support(int bEnable) { - DWORD dwFlags = QueryVideoFlags(); - if (bEnable) dwFlags |= AV_FLAGS_HDTV_480p; - else dwFlags &= ~AV_FLAGS_HDTV_480p; - SetVideoFlags(dwFlags); + WriteSettingBit(XC_VIDEO_FLAGS, AV_FLAGS_HDTV_480p, bEnable != 0); - // If playing a video disc on HDTV and Macrovision is active, update the D3D present flags - if (g_nDiscType == DISC_VIDEO && XGetAVPack() == XC_AV_PACK_HDTV && (XBOX_480P_MACROVISION_ENABLED & XboxHardwareInfo->Flags)) - { - bool bUpdate = false; - if ((g_pp.Flags & D3DPRESENTFLAG_PROGRESSIVE) && !bEnable) - { - g_pp.Flags &= ~D3DPRESENTFLAG_PROGRESSIVE; - g_pp.Flags |= D3DPRESENTFLAG_INTERLACED; - bUpdate = true; - } - else if (!(g_pp.Flags & D3DPRESENTFLAG_PROGRESSIVE) && bEnable) - { - g_pp.Flags |= D3DPRESENTFLAG_PROGRESSIVE; - g_pp.Flags &= ~D3DPRESENTFLAG_INTERLACED; - bUpdate = true; - } - - if (bUpdate) - { - D3D__AvInfo = 0; - TheseusGetD3DDev()->Reset(&g_pp); - TheseusInvalidateStateCache(); - } - } -} - -void CConfig::Set720Support(int bEnable) -{ - DWORD dwFlags = QueryVideoFlags(); - if (bEnable) dwFlags |= AV_FLAGS_HDTV_720p; - else dwFlags &= ~AV_FLAGS_HDTV_720p; - SetVideoFlags(dwFlags); -} + if (g_nDiscType != DISC_VIDEO || XGetAVPack() != XC_AV_PACK_HDTV || + !(XboxHardwareInfo->Flags & XBOX_480P_MACROVISION_ENABLED)) + return; -void CConfig::Set1080Support(int bEnable) -{ - DWORD dwFlags = QueryVideoFlags(); - if (bEnable) dwFlags |= AV_FLAGS_HDTV_1080i; - else dwFlags &= ~AV_FLAGS_HDTV_1080i; - SetVideoFlags(dwFlags); -} + bool bProgressive = (g_pp.Flags & D3DPRESENTFLAG_PROGRESSIVE) != 0; + if (bProgressive == (bEnable != 0)) + return; -void CConfig::SetPAL60Support(int bEnable) -{ - DWORD dwFlags = QueryVideoFlags(); - if (bEnable) dwFlags |= AV_FLAGS_60Hz; - else dwFlags &= ~AV_FLAGS_60Hz; - SetVideoFlags(dwFlags); + if (bEnable) + g_pp.Flags = (g_pp.Flags & ~D3DPRESENTFLAG_INTERLACED) | D3DPRESENTFLAG_PROGRESSIVE; + else + g_pp.Flags = (g_pp.Flags & ~D3DPRESENTFLAG_PROGRESSIVE) | D3DPRESENTFLAG_INTERLACED; + ResetDisplay(); } -// ========================================================================= -// Audio mode -// ========================================================================= - +// CConfig::GetAudioMode() [script fn 'GetAudioMode', FND 0x00180120, sig 2] +// CConfig::SetAudioMode(n) [script fn 'SetAudioMode', FND 0x00180138, sig 14] +// Reconstructed from 5960 retail XBE @ 0x0003abb0 and 0x0003abf0. Script +// numbers modes 0 mono, 1 stereo, 2 surround; the low word of the audio +// flags holds the speaker setup, the high word the encodings, which Set +// leaves alone. Any other speaker value reads as surround; any other mode +// writes nothing new. int CConfig::GetAudioMode() { - switch (DSSPEAKER_BASIC(QueryAudioFlags())) + switch (DSSPEAKER_BASIC(ReadSetting(XC_AUDIO_FLAGS))) { - case DSSPEAKER_MONO: return 0; - case DSSPEAKER_STEREO: return 1; - default: return 2; + case DSSPEAKER_MONO: return 0; + case DSSPEAKER_STEREO: return 1; } + return 2; } void CConfig::SetAudioMode(int nAudioMode) { - DWORD dwFlags = QueryAudioFlags(); - switch (nAudioMode) - { - case 0: dwFlags = DSSPEAKER_COMBINED(DSSPEAKER_MONO, dwFlags); break; - case 1: dwFlags = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, dwFlags); break; - case 2: dwFlags = DSSPEAKER_COMBINED(DSSPEAKER_SURROUND, dwFlags); break; - } - SetAudioFlags(dwFlags); -} - -int CConfig::GetDolbyDigitalSupport() { return (QueryAudioFlags() & DSSPEAKER_ENABLE_AC3) != 0; } - -void CConfig::SetDolbyDigitalSupport(int bEnable) -{ - DWORD dwFlags = QueryAudioFlags(); - if (bEnable) dwFlags |= DSSPEAKER_ENABLE_AC3; - else dwFlags &= ~DSSPEAKER_ENABLE_AC3; - SetAudioFlags(dwFlags); -} - -int CConfig::GetDTSSupport() { return (QueryAudioFlags() & DSSPEAKER_ENABLE_DTS) != 0; } - -void CConfig::SetDTSSupport(int bEnable) -{ - DWORD dwFlags = QueryAudioFlags(); - if (bEnable) dwFlags |= DSSPEAKER_ENABLE_DTS; - else dwFlags &= ~DSSPEAKER_ENABLE_DTS; - SetAudioFlags(dwFlags); + DWORD dwFlags = ReadSetting(XC_AUDIO_FLAGS); + if (nAudioMode == 0) + dwFlags = DSSPEAKER_COMBINED(DSSPEAKER_MONO, dwFlags); + else if (nAudioMode == 1) + dwFlags = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, dwFlags); + else if (nAudioMode == 2) + dwFlags = DSSPEAKER_COMBINED(DSSPEAKER_SURROUND, dwFlags); + WriteSetting(XC_AUDIO_FLAGS, dwFlags); } -// ========================================================================= -// Auto power-off -// ========================================================================= - +// Dolby Digital and DTS [FND 0x00180150..0x00180198] +// Reconstructed from 5960 retail XBE @ 0x0003ac60..0x0003ad10: bits 0x10000 +// and 0x20000 of XC_AUDIO_FLAGS. +int CConfig::GetDolbyDigitalSupport() { return (ReadSetting(XC_AUDIO_FLAGS) & DSSPEAKER_ENABLE_AC3) != 0; } +int CConfig::GetDTSSupport() { return (ReadSetting(XC_AUDIO_FLAGS) & DSSPEAKER_ENABLE_DTS) != 0; } +void CConfig::SetDolbyDigitalSupport(int bEnable) { WriteSettingBit(XC_AUDIO_FLAGS, DSSPEAKER_ENABLE_AC3, bEnable != 0); } +void CConfig::SetDTSSupport(int bEnable) { WriteSettingBit(XC_AUDIO_FLAGS, DSSPEAKER_ENABLE_DTS, bEnable != 0); } + +// CConfig::GetAutoOff / SetAutoOff [FND 0x00180060, 0x00180078] +// Reconstructed from 5960 retail XBE @ 0x0003ad60 and 0x0003ad70: straight +// through to XAutoPowerDownGet / XAutoPowerDownSet. int CConfig::GetAutoOff() { BOOL bAutoOff; @@ -389,7 +348,10 @@ int CConfig::GetAutoOff() return bAutoOff; } -void CConfig::SetAutoOff(int bAutoOff) { XAutoPowerDownSet(bAutoOff); } +void CConfig::SetAutoOff(int bAutoOff) +{ + XAutoPowerDownSet(bAutoOff); +} // ========================================================================= // Skin @@ -463,32 +425,36 @@ int CConfig::GetInternalTemp() return (int)val; } -// ========================================================================= -// Timezone / DST -// ========================================================================= extern int GetTimeZoneIndex(const TIME_ZONE_INFORMATION *tzinfo); extern bool GetTimeZoneInfo(int index, TIME_ZONE_INFORMATION *tzinfo); +// CConfig::GetTimeZone() [script fn 'GetTimeZone', FND 0x001801e0, sig 2] +// Reconstructed from 5960 retail XBE @ 0x0003ae80: +// if (XapipQueryTimeZoneInformation(&tz, 0) == 0 && tz.StandardName[0]) +// return max(GetTimeZoneIndex(&tz), 0); +// return region == NA ? 11 : region == JAPAN ? 60 : 25; +// With no zone set yet, the default is Eastern, Tokyo or London by region. int CConfig::GetTimeZone() { TIME_ZONE_INFORMATION tzinfo; - if ((XapipQueryTimeZoneInformation(&tzinfo, NULL) != ERROR_SUCCESS) || - (L'\0' == tzinfo.StandardName[0])) + if (XapipQueryTimeZoneInformation(&tzinfo, NULL) == ERROR_SUCCESS && tzinfo.StandardName[0] != 0) { - // No valid timezone; return a default based on game region. - switch (XGetGameRegion()) - { - case XC_GAME_REGION_NA: return NA_DEFAULT_TIMEZONE; - case XC_GAME_REGION_JAPAN: return JAPAN_DEFAULT_TIMEZONE; - default: return ROW_DEFAULT_TIMEZONE; - } + int nIndex = GetTimeZoneIndex(&tzinfo); + return nIndex < 0 ? 0 : nIndex; } - int index = GetTimeZoneIndex(&tzinfo); - return (index < 0) ? 0 : index; + switch (XGetGameRegion()) + { + case XC_GAME_REGION_NA: return NA_DEFAULT_TIMEZONE; + case XC_GAME_REGION_JAPAN: return JAPAN_DEFAULT_TIMEZONE; + } + return ROW_DEFAULT_TIMEZONE; } +// CConfig::SetTimeZone(n) [script fn 'SetTimeZone', FND 0x001801f8, sig 14] +// Reconstructed from 5960 retail XBE @ 0x0003af30: +// if (GetTimeZoneInfo(n, &tz)) XapipSetTimeZoneInformation(&tz); void CConfig::SetTimeZone(int nTimeZone) { TIME_ZONE_INFORMATION tzinfo; @@ -496,165 +462,161 @@ void CConfig::SetTimeZone(int nTimeZone) XapipSetTimeZoneInformation(&tzinfo); } +// CConfig::GetDSTAllowed() [script fn 'GetDSTAllowed', FND 0x00180210, sig 2] +// CConfig::GetDST() [script fn 'GetDST', FND 0x00180228, sig 2] +// Reconstructed from 5960 retail XBE @ 0x0003af80 and 0x0003afe0: a zone +// allows daylight time when both its standard and daylight dates name a +// month; GetDST also needs the console's use-DST answer. int CConfig::GetDSTAllowed() { TIME_ZONE_INFORMATION tzinfo; if (XapipQueryTimeZoneInformation(&tzinfo, NULL) != ERROR_SUCCESS) return 0; - return (tzinfo.StandardDate.wMonth && tzinfo.DaylightDate.wMonth); + return tzinfo.StandardDate.wMonth != 0 && tzinfo.DaylightDate.wMonth != 0; } int CConfig::GetDST() { TIME_ZONE_INFORMATION tzinfo; - BOOL fUseDST; - if (XapipQueryTimeZoneInformation(&tzinfo, &fUseDST) != ERROR_SUCCESS) + BOOL bUseDST; + if (XapipQueryTimeZoneInformation(&tzinfo, &bUseDST) != ERROR_SUCCESS) return 0; - return (tzinfo.StandardDate.wMonth && tzinfo.DaylightDate.wMonth && fUseDST); + return tzinfo.StandardDate.wMonth != 0 && tzinfo.DaylightDate.wMonth != 0 && bUseDST; } +// CConfig::SetDST(on) [script fn 'SetDST', FND 0x00180240, sig 14] +// Reconstructed from 5960 retail XBE @ 0x0003b050: if the misc flags read, +// clear (on) or set (off) XC_MISC_FLAG_DONT_USE_DST and write them back. void CConfig::SetDST(int bObserveDST) { -#if DBG + DWORD dwType, dwSize, dwFlags; + if (XQueryValue(XC_MISC_FLAGS, &dwType, &dwFlags, sizeof(dwFlags), &dwSize) != ERROR_SUCCESS) + return; if (bObserveDST) - ASSERT(GetDSTAllowed()); -#endif - - ULONG type, size; - DWORD flags; - if (XQueryValue(XC_MISC_FLAGS, &type, &flags, sizeof(flags), &size) == ERROR_SUCCESS) - { - if (bObserveDST) - flags &= ~XC_MISC_FLAG_DONT_USE_DST; - else - flags |= XC_MISC_FLAG_DONT_USE_DST; - XSetValue(XC_MISC_FLAGS, REG_DWORD, &flags, sizeof(flags)); - } + dwFlags &= ~XC_MISC_FLAG_DONT_USE_DST; + else + dwFlags |= XC_MISC_FLAG_DONT_USE_DST; + XSetValue(XC_MISC_FLAGS, REG_DWORD, &dwFlags, sizeof(dwFlags)); } -// ========================================================================= -// Parental controls -// ========================================================================= - +// EncodePassword(text) +// Reconstructed from 5960 retail XBE @ 0x0003b0a0. A pass code is typed on +// the pad, one nibble per press: +// u 1 d 2 l 3 r 4 a 5 b 6 x 7 y 8 B 9 W 10 L 11 R 12 +// (d-pad, A B X Y, black, white, triggers). Anything else adds a zero nibble. static DWORD EncodePassword(const TCHAR *szPassword) { - DWORD dw = 0; - for (const TCHAR *pch = szPassword; *pch != 0; pch += 1) + static const TCHAR keys[] = _T("udlrabxyBWLR"); + DWORD dwCode = 0; + for (; *szPassword != 0; szPassword++) { - dw <<= 4; - switch (*pch) - { - case 'u': dw += 1; break; // up - case 'd': dw += 2; break; // down - case 'l': dw += 3; break; // left - case 'r': dw += 4; break; // right - case 'a': dw += 5; break; // A - case 'b': dw += 6; break; // B - case 'x': dw += 7; break; // X - case 'y': dw += 8; break; // Y - case 'B': dw += 9; break; // black - case 'W': dw += 10; break; // white - case 'L': dw += 11; break; // L trigger - case 'R': dw += 12; break; // R trigger - default: ASSERT(FALSE); - } + const TCHAR *pKey = _tcschr(keys, *szPassword); + dwCode = dwCode * 16 + (pKey != NULL ? (DWORD)(pKey - keys) + 1 : 0); } - return dw; + return dwCode; } +// CConfig::CheckParentPassword(text) [script fn 'CheckParentPassword', FND 0x001801b0, sig 25] +// CConfig::SetParentPassword(text) [script fn 'SetParentPassword', FND 0x001801c8, sig 12] +// Reconstructed from 5960 retail XBE @ 0x0003b1b0 and 0x0003b1f0: the +// encoded code against, or into, XC_PARENTAL_CONTROL_PASSWORD. int CConfig::CheckParentPassword(const TCHAR *szCheckPassword) { - DWORD dwCheck = EncodePassword(szCheckPassword); - DWORD dwStored, dwType; - VERIFY(!XQueryValue(XC_PARENTAL_CONTROL_PASSWORD, &dwType, &dwStored, 4, NULL)); - return dwStored == dwCheck; + return ReadSetting(XC_PARENTAL_CONTROL_PASSWORD) == EncodePassword(szCheckPassword); } void CConfig::SetParentPassword(const TCHAR *szNewPassword) { - DWORD dw = EncodePassword(szNewPassword); - VERIFY(!XSetValue(XC_PARENTAL_CONTROL_PASSWORD, REG_DWORD, &dw, 4)); + WriteSetting(XC_PARENTAL_CONTROL_PASSWORD, EncodePassword(szNewPassword)); } +// Game and movie ratings [FND 0x0017fe38..0x0017fe80] +// Reconstructed from 5960 retail XBE @ 0x0003b210..0x0003b2a0. The EEPROM +// keeps them upside down: script's game level n is stored as 6 - n, movie +// level n as 7 - n; an unreadable value counts as stored 0. Theseus CHECKs +// the range both ways, since scripts write these straight into the EEPROM. int CConfig::GetGamePCFlags() { - DWORD dwFlags = 0, dwType; - VERIFY(!XQueryValue(XC_PARENTAL_CONTROL_GAMES, &dwType, &dwFlags, 4, NULL)); - if (!CHECK(dwFlags <= 6)) - dwFlags = 0; - return (int)(6 - dwFlags); // stored inverted in EEPROM + DWORD dwType, dwStored = 0; + XQueryValue(XC_PARENTAL_CONTROL_GAMES, &dwType, &dwStored, sizeof(dwStored), NULL); + if (!CHECK(dwStored <= 6)) + dwStored = 0; + return 6 - (int)dwStored; } void CConfig::SetGamePCFlags(int nFlags) { - // Scripts call this and the value goes straight into EEPROM. if (!CHECK(nFlags >= 0 && nFlags <= 6)) return; - nFlags = 6 - nFlags; - VERIFY(!XSetValue(XC_PARENTAL_CONTROL_GAMES, REG_DWORD, (DWORD *)&nFlags, 4)); + WriteSetting(XC_PARENTAL_CONTROL_GAMES, (DWORD)(6 - nFlags)); } int CConfig::GetMoviePCFlags() { - DWORD dwFlags = 0, dwType; - VERIFY(!XQueryValue(XC_PARENTAL_CONTROL_MOVIES, &dwType, &dwFlags, 4, NULL)); - if (!CHECK(dwFlags <= 7)) - dwFlags = 0; - return (int)(7 - dwFlags); + DWORD dwType, dwStored = 0; + XQueryValue(XC_PARENTAL_CONTROL_MOVIES, &dwType, &dwStored, sizeof(dwStored), NULL); + if (!CHECK(dwStored <= 7)) + dwStored = 0; + return 7 - (int)dwStored; } void CConfig::SetMoviePCFlags(int nFlags) { if (!CHECK(nFlags >= 0 && nFlags <= 7)) return; - nFlags = 7 - nFlags; - VERIFY(!XSetValue(XC_PARENTAL_CONTROL_MOVIES, REG_DWORD, (DWORD *)&nFlags, 4)); + WriteSetting(XC_PARENTAL_CONTROL_MOVIES, (DWORD)(7 - nFlags)); } -// ========================================================================= -// Launch data -// ========================================================================= - +// CConfig::GetLaunchReason() [script fn 'GetLaunchReason', FND 0x0017fe98, sig 8] +// Reconstructed from 5960 retail XBE @ 0x0003b2d0: with launch data, the +// reason as a name (jump table @ 0x0003b3ac); otherwise, or for a reason +// it doesn't name, an empty string. Theseus names the online menu, account +// signup and network settings by this XDK's numbering. CStrObject *CConfig::GetLaunchReason() { - const TCHAR *sz = NULL; + const TCHAR *szReason = _T(""); if (g_bHasLaunchData) { switch (g_dwLaunchReason) { - case XLD_LAUNCH_DASHBOARD_ERROR: sz = _T("Error"); break; - case XLD_LAUNCH_DASHBOARD_MEMORY: sz = _T("Memory"); break; - case XLD_LAUNCH_DASHBOARD_SETTINGS: sz = _T("Settings"); break; - case XLD_LAUNCH_DASHBOARD_MUSIC: sz = _T("Music"); break; - case XLD_LAUNCH_DASHBOARD_ONLINE_MENU: sz = _T("FromOnlineDash"); break; - case XLD_LAUNCH_DASHBOARD_NEW_ACCOUNT_SIGNUP: sz = _T("NewAccountInternal"); break; - case XLD_LAUNCH_DASHBOARD_NETWORK_CONFIGURATION: sz = _T("NetworkSettingsInternal"); break; - default: - TRACE(_T("[LaunchReason] Unknown launch reason: %lu\n"), g_dwLaunchReason); - break; + case XLD_LAUNCH_DASHBOARD_ERROR: szReason = _T("Error"); break; + case XLD_LAUNCH_DASHBOARD_MEMORY: szReason = _T("Memory"); break; + case XLD_LAUNCH_DASHBOARD_SETTINGS: szReason = _T("Settings"); break; + case XLD_LAUNCH_DASHBOARD_MUSIC: szReason = _T("Music"); break; + case XLD_LAUNCH_DASHBOARD_ONLINE_MENU: szReason = _T("FromOnlineDash"); break; + case XLD_LAUNCH_DASHBOARD_NEW_ACCOUNT_SIGNUP: szReason = _T("NewAccountInternal"); break; + case XLD_LAUNCH_DASHBOARD_NETWORK_CONFIGURATION: szReason = _T("NetworkSettingsInternal"); break; } } - return new CStrObject(sz ? sz : _T("")); + return new CStrObject(szReason); } -int CConfig::GetLaunchContext() { return g_bHasLaunchData ? g_dwLaunchContext : 0; } -int CConfig::GetLaunchParameter1() { return g_bHasLaunchData ? g_dwLaunchParameter1 : 0; } -int CConfig::GetLaunchParameter2() { return g_bHasLaunchData ? g_dwLaunchParameter2 : 0; } +// GetLaunchContext / GetLaunchParameter1 / GetLaunchParameter2 [FND 0x0017feb0..0x0017fee0] +// Reconstructed from 5960 retail XBE @ 0x0003b400..0x0003b440: the launch +// data's field, or 0 with none. GetTitleID is the same for the title id. +int CConfig::GetLaunchContext() { return g_bHasLaunchData ? (int)g_dwLaunchContext : 0; } +int CConfig::GetLaunchParameter1() { return g_bHasLaunchData ? (int)g_dwLaunchParameter1 : 0; } +int CConfig::GetLaunchParameter2() { return g_bHasLaunchData ? (int)g_dwLaunchParameter2 : 0; } DWORD CConfig::GetTitleID() { return g_bHasLaunchData ? g_dwTitleID : 0; } +// CConfig::CanDriveBeCleanup(drive) [script fn 'CanDriveBeCleanup', FND 0x0017fef8, sig 3] +// Reconstructed from 5960 retail XBE @ 0x0003b460: true for the drives a +// game may ask the dash to clean up, any case. 5960 takes F to M, T and U; +// Theseus takes H to O, T and U, keeping the big F and G partitions out. int CConfig::CanDriveBeCleanup(int Drive) { - switch (toupper(Drive)) - { - case 'T': case 'U': - case 'H': case 'I': case 'J': case 'K': - case 'L': case 'M': case 'N': case 'O': - return true; - default: - return false; - } + int letter = toupper(Drive); + return letter == 'T' || letter == 'U' || (letter >= 'H' && letter <= 'O'); } +// CConfig::BackToLauncher() [script fn 'BackToLauncher', FND 0x0017ff10, sig 1] +// Reconstructed from 5960 retail XBE @ 0x0003b4b0: +// PersistDisplay(); +// if (reason == SETTINGS && (param1 & (CLOCK | TIMEZONE | LANGUAGE))) HalReturnToFirmware(reboot); +// LD_FROM_DASHBOARD fd = {0}; fd.dwContext = GetLaunchContext(); +// XWriteTitleInfoAndReboot("default.xbe", "\\Device\\CdRom0", LDT_FROM_DASHBOARD, GetTitleID(), &fd); +// A game that sent the player to set the clock, zone or language gets a +// clean reboot; otherwise it's relaunched from the disc with its context. void CConfig::BackToLauncher() { TheseusGetD3DDev()->PersistDisplay(); @@ -662,14 +624,13 @@ void CConfig::BackToLauncher() if (CheckForcedSettings(XLD_SETTINGS_CLOCK | XLD_SETTINGS_TIMEZONE | XLD_SETTINGS_LANGUAGE)) { HalReturnToFirmware(HalRebootRoutine); + return; } - else - { - LD_FROM_DASHBOARD fd; - ZeroMemory(&fd, sizeof(fd)); - fd.dwContext = GetLaunchContext(); - XWriteTitleInfoAndReboot("default.xbe", "\\Device\\CdRom0", LDT_FROM_DASHBOARD, GetTitleID(), (PLAUNCH_DATA)&fd); - } + + LD_FROM_DASHBOARD fd; + ZeroMemory(&fd, sizeof(fd)); + fd.dwContext = GetLaunchContext(); + XWriteTitleInfoAndReboot("default.xbe", "\\Device\\CdRom0", LDT_FROM_DASHBOARD, GetTitleID(), (PLAUNCH_DATA)&fd); } // ========================================================================= @@ -699,61 +660,81 @@ CStrObject *CConfig::GetXBETitleID(const TCHAR *path) return new CStrObject(buffer); } -// ========================================================================= -// NT device path file check -// ========================================================================= +// CConfig::NtFileExists(path) [script fn 'NtFileExists', FND 0x00180300, sig 25] +// 5960 @ 0x0003b910 opens the raw NT path (NtOpenFile, read access) and +// answers whether that worked. Theseus maps the hard disk partitions it +// knows to their drive letters and asks for the file's attributes instead. +// Paths it doesn't know go through unchanged. int CConfig::NtFileExists(const TCHAR* FileName) { + static const struct { const TCHAR *szDevice; TCHAR chDrive; } partitions[] = + { + { _T("\\Device\\Harddisk0\\Partition2"), 'C' }, + { _T("\\Device\\Harddisk0\\Partition1"), 'E' }, + { _T("\\Device\\Harddisk0\\Partition6"), 'F' }, + { _T("\\Device\\Harddisk0\\Partition7"), 'G' }, + { _T("\\Device\\Harddisk0\\Partition8"), 'H' }, + { _T("\\Device\\Harddisk0\\Partition9"), 'I' }, + }; + + TCHAR szPath[MAX_PATH]; + _tcsncpy(szPath, FileName, MAX_PATH); + + for (int i = 0; i < (int)countof(partitions); i++) + { + size_t cch = _tcslen(partitions[i].szDevice); + if (_tcsnicmp(FileName, partitions[i].szDevice, cch) == 0) + { + _stprintf(szPath, _T("%c:%s"), partitions[i].chDrive, FileName + cch); + break; + } + } + + char szAnsi[MAX_PATH]; + Ansi(szAnsi, szPath, MAX_PATH); WIN32_FILE_ATTRIBUTE_DATA fad; - TCHAR remappedPath[MAX_PATH]; - - _tcsncpy(remappedPath, FileName, MAX_PATH); - - // Convert NT device paths to DOS drive letters - if (_tcsnicmp(FileName, _T("\\Device\\Harddisk0\\Partition2"), _tcslen(_T("\\Device\\Harddisk0\\Partition2"))) == 0) - _stprintf(remappedPath, _T("C:\%s"), FileName + _tcslen(_T("\\Device\\Harddisk0\\Partition2"))); - else if (_tcsnicmp(FileName, _T("\\Device\\Harddisk0\\Partition1"), _tcslen(_T("\\Device\\Harddisk0\\Partition1"))) == 0) - _stprintf(remappedPath, _T("E:\%s"), FileName + _tcslen(_T("\\Device\\Harddisk0\\Partition1"))); - else if (_tcsnicmp(FileName, _T("\\Device\\Harddisk0\\Partition6"), _tcslen(_T("\\Device\\Harddisk0\\Partition6"))) == 0) - _stprintf(remappedPath, _T("F:\%s"), FileName + _tcslen(_T("\\Device\\Harddisk0\\Partition6"))); - else if (_tcsnicmp(FileName, _T("\\Device\\Harddisk0\\Partition7"), _tcslen(_T("\\Device\\Harddisk0\\Partition7"))) == 0) - _stprintf(remappedPath, _T("G:\%s"), FileName + _tcslen(_T("\\Device\\Harddisk0\\Partition7"))); - else if (_tcsnicmp(FileName, _T("\\Device\\Harddisk0\\Partition8"), _tcslen(_T("\\Device\\Harddisk0\\Partition8"))) == 0) - _stprintf(remappedPath, _T("H:\%s"), FileName + _tcslen(_T("\\Device\\Harddisk0\\Partition8"))); - else if (_tcsnicmp(FileName, _T("\\Device\\Harddisk0\\Partition9"), _tcslen(_T("\\Device\\Harddisk0\\Partition9"))) == 0) - _stprintf(remappedPath, _T("I:\%s"), FileName + _tcslen(_T("\\Device\\Harddisk0\\Partition9"))); - - CHAR szFile[MAX_PATH]; - Ansi(szFile, remappedPath, MAX_PATH); - - return (GetFileAttributesEx(szFile, GetFileExInfoStandard, &fad) > 0) ? 1 : 0; + return GetFileAttributesEx(szAnsi, GetFileExInfoStandard, &fad) ? 1 : 0; } -int CConfig::FileExists(const TCHAR* FileName) { return NtFileExists(FileName); } - -// ========================================================================= -// System info -// ========================================================================= +// CConfig::FileExists(path) [script fn 'FileExists', FND 0x001802e8, sig 25] +// 5960 @ 0x0003b900 is DoesFileExist(path). Theseus routes it through +// NtFileExists so either kind of path works. +int CConfig::FileExists(const TCHAR* FileName) +{ + return NtFileExists(FileName); +} +// CConfig::GetRecoveryKey() [script fn 'GetRecoveryKey', FND 0x001802a0, sig 8] +// 5960 @ 0x0003b6b0 derives a four press pad code (letters "AXYUDLR") from +// an HMAC of the console's hard disk key. Theseus returns it empty: a +// parental lock recovery code means nothing on modified hardware. CStrObject *CConfig::GetRecoveryKey() { - // Parental lock recovery codes aren't meaningful on modified hardware. return new CStrObject(_T("")); } +// CConfig::GetROMVersion() [script fn 'GetROMVersion', FND 0x001802b8, sig 8] +// CConfig::GetXdashVersion() [script fn 'GetXdashVersion', FND 0x001802d0, sig 8] +// Reconstructed from 5960 retail XBE @ 0x0003b7b0 and 0x0003b860: both +// print "%d.%02d.%d.%02d", the kernel's version (QFE without its top bit) +// and the dash's own 1, 0, 5960, 1. +static CStrObject *FormatVersion(int major, int minor, int build, int qfe) +{ + TCHAR szVersion[64]; + _sntprintf(szVersion, countof(szVersion), _T("%d.%02d.%d.%02d"), major, minor, build, qfe); + szVersion[countof(szVersion) - 1] = 0; + return new CStrObject(szVersion); +} + CStrObject *CConfig::GetROMVersion() { - TCHAR buf[64]; - _sntprintf(buf, countof(buf), _T("%d.%02d.%d.%02d"), - XboxKrnlVersion->Major, XboxKrnlVersion->Minor, - XboxKrnlVersion->Build, (XboxKrnlVersion->Qfe & 0x7FFF)); - return new CStrObject(buf); + return FormatVersion(XboxKrnlVersion->Major, XboxKrnlVersion->Minor, XboxKrnlVersion->Build, XboxKrnlVersion->Qfe & 0x7FFF); } CStrObject *CConfig::GetXdashVersion() { - return new CStrObject(_T("1.00.5960.01")); + return FormatVersion(1, 0, 5960, 1); } CStrObject *CConfig::GetXboxIP() @@ -1043,38 +1024,48 @@ CStrObject *CConfig::GetMODCHIPVersion() return new CStrObject(result); } -// ========================================================================= -// LiveToday / legal info / misc flags -// ========================================================================= +// Live today, the accepted legal notice and daylight time all live in +// XC_MISC_FLAGS: bit 2 is "don't show Live today" (so read inverted), bit 3 +// "legal notice accepted". +// CConfig::GetLiveToday / SetLiveToday [FND 0x00180090, 0x001800a8] +// CConfig::GetAcceptedLegalInfo / SetAccepted... [FND 0x001800c0, 0x001800d8] +// Reconstructed from 5960 retail XBE @ 0x0003ad80..0x0003ae30. int CConfig::GetLiveToday() { - // Bit 2 is "disabled" flag, inverted - return (~(QueryMiscFlags() >> 2)) & 1; + return (ReadMiscFlags() & 4) == 0; } void CConfig::SetLiveToday(int bEnable) { - DWORD value = QueryMiscFlags(); - if (bEnable) value &= ~4; - else value |= 4; - SetMiscFlags(value); + DWORD dwFlags = ReadMiscFlags(); + if (bEnable) + dwFlags &= ~4; + else + dwFlags |= 4; + WriteSetting(XC_MISC_FLAGS, dwFlags); } int CConfig::GetAcceptedLegalInfo() { - // Bit 3 is "accepted legal info" flag - return (QueryMiscFlags() >> 3) & 1; + return (ReadMiscFlags() & 8) != 0; } void CConfig::SetAcceptedLegalInfo(int nValue) { - DWORD value = QueryMiscFlags(); - if (nValue) value |= 8; - else value &= ~8; - SetMiscFlags(value); + DWORD dwFlags = ReadMiscFlags(); + if (nValue) + dwFlags |= 8; + else + dwFlags &= ~8; + WriteSetting(XC_MISC_FLAGS, dwFlags); } +// CConfig::BackToLauncher2() [script fn 'BackToLauncher2', FND 0x0017ff28, sig 1] +// Reconstructed from 5960 retail XBE @ 0x0003b550: reboots into +// settings_adoc.xip as title 0xFFFE0000 with 'ADOC' as the launch context. +// 5960 asks the object manager where the dash itself lives and launches +// from there; Theseus names the C partition outright. void CConfig::BackToLauncher2() { TheseusGetD3DDev()->PersistDisplay(); @@ -1082,47 +1073,54 @@ void CConfig::BackToLauncher2() LD_FROM_DASHBOARD fd; ZeroMemory(&fd, sizeof(fd)); fd.dwContext = 'CODA'; - XWriteTitleInfoAndReboot("settings_adoc.xip", - "\\Device\\Harddisk0\\Partition2", - LDT_FROM_DASHBOARD, 0xfffe0000, (PLAUNCH_DATA)&fd); + XWriteTitleInfoAndReboot("settings_adoc.xip", "\\Device\\Harddisk0\\Partition2", + LDT_FROM_DASHBOARD, 0xfffe0000, (PLAUNCH_DATA)&fd); } +// CConfig::GoToXOnlineDash() +// 5960 @ 0x0003b640 reboots into C:\XODash\xonlinedash.xbe with reason 0x0C. +// Theseus has no online dashboard to go to, so it only logs the call. void CConfig::GoToXOnlineDash() { OutputDebugString(_T("[Config] GoToXOnlineDash() called\n")); } +// CConfig::GetFontVersion() [script fn 'GetFontVersion', FND 0x0017fdf0, sig 2] +// Reconstructed from 5960 retail XBE @ 0x0003a520: opens the font file +// (5960: "%sfonts\Xbox.xtf", then "%sXbox.xtf" under the app dir), reads its +// first DWORD and takes the top byte as a digit; cached after the first +// call. Theseus reads the system fonts, C:\Fonts\xbox_.xtf then +// C:\Fonts\xbox.xtf, wants all four bytes, and calls a missing font 0. int CConfig::GetFontVersion() { - static int cachedVersion = -1; - if (cachedVersion != -1) - return cachedVersion; + static int nVersion = -1; + if (nVersion != -1) + return nVersion; char szPath[MAX_PATH]; - DWORD dwRead, dwData = 0; - _snprintf(szPath, MAX_PATH, "C:\\Fonts\\xbox_%d.xtf", GetLanguage()); - HANDLE hFile = CreateFileA(szPath, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - if (hFile == INVALID_HANDLE_VALUE) - hFile = CreateFileA("C:\\Fonts\\xbox.xtf", GENERIC_READ, - FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE hFont = CreateFileA(szPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFont == INVALID_HANDLE_VALUE) + hFont = CreateFileA("C:\\Fonts\\xbox.xtf", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile != INVALID_HANDLE_VALUE) + nVersion = 0; + if (hFont != INVALID_HANDLE_VALUE) { - if (ReadFile(hFile, &dwData, sizeof(dwData), &dwRead, NULL) && dwRead == 4) - cachedVersion = (int)((dwData >> 24) - '0'); - CloseHandle(hFile); + DWORD dwHeader = 0, dwRead = 0; + if (ReadFile(hFont, &dwHeader, sizeof(dwHeader), &dwRead, NULL) && dwRead == sizeof(dwHeader)) + nVersion = (int)(dwHeader >> 24) - '0'; + CloseHandle(hFont); } - - if (cachedVersion == -1) - cachedVersion = 0; - return cachedVersion; + if (nVersion == -1) + nVersion = 0; + return nVersion; } extern bool g_bMovingScreen; +// CConfig::ToggleNoisyCamera() +// 5960 @ 0x0003b9e0 flips the camera drift by creating or deleting +// T:\NoisyCamera. Theseus keeps it in the skin's settings instead. void CConfig::ToggleNoisyCamera() { g_bMovingScreen = !g_bMovingScreen; @@ -1130,9 +1128,11 @@ void CConfig::ToggleNoisyCamera() g_pSkinSettings->SetValue(_T("Camera"), _T("Noisy"), g_bMovingScreen ? _T("true") : _T("false")); } +// CConfig::GetEthernetLinkStatus() [script fn 'GetEthernetLinkStatus', FND 0x00180318, sig 2] +// 5960 @ 0x0003b9d0 is XNetGetEthernetLinkStatus() & 1, the cable's link +// bit. Theseus answers whether XNet has started looking for an address. int CConfig::GetEthernetLinkStatus() { XNADDR xna; - DWORD dwState = XNetGetTitleXnAddr(&xna); - return (dwState != 0) ? 1 : 0; + return XNetGetTitleXnAddr(&xna) != 0 ? 1 : 0; } diff --git a/theseus/xbox/config.h b/theseus/xbox/config.h index 4e87976..1658d00 100755 --- a/theseus/xbox/config.h +++ b/theseus/xbox/config.h @@ -1,7 +1,5 @@ -// config.h: CConfig XAP node. Exposes the dashboard's system config -// (language, video / audio mode, parental controls, timezone / -// DST, network, hardware status, launch context) to scripts. -// Companion to xbox/config.cpp. +// config.h: the Xbox Config node, the dash's settings, launch data and +// hardware readings as script functions. Bodies in xbox/config.cpp. #pragma once #include "node.h" @@ -117,6 +115,10 @@ class CConfig : public CNode int GetLiveToday(); void SetLiveToday(int bLiveToday); + // ForceSetLanguage / ForceSetTimeZone / ForceSetClock [FND 0x00180258..0x00180288] + // Reconstructed from 5960 retail XBE @ 0x0003a430..0x0003a470: + // return reason == XLD_LAUNCH_DASHBOARD_SETTINGS && (param1 & flag); + // A game sent the player here to set that one thing. int ForceSetLanguage() { return CheckForcedSettings(XLD_SETTINGS_LANGUAGE); } int ForceSetTimeZone() { return CheckForcedSettings(XLD_SETTINGS_TIMEZONE); } int ForceSetClock() { return CheckForcedSettings(XLD_SETTINGS_CLOCK); } @@ -125,9 +127,10 @@ class CConfig : public CNode DECLARE_NODE_FUNCTIONS() private: - int CheckForcedSettings(int flag) + int CheckForcedSettings(int flags) { - return ((TheseusGetLaunchReason() == XLD_LAUNCH_DASHBOARD_SETTINGS) && - (TheseusGetLaunchParameter1() & flag)) ? 1 : 0; + if (TheseusGetLaunchReason() != XLD_LAUNCH_DASHBOARD_SETTINGS) + return 0; + return (TheseusGetLaunchParameter1() & flags) != 0; } }; From 4f82505f33996e3d6ac647b49e8df0e5f64adf8a Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 05/13] Rebuilt the MemoryMonitor node from the binary Mounting, removal, selection paths, block counts, naming and formatting are written fresh from 0x4be70..0x4cd10; I checked the path table against the binary's. Events and selection match the old code over 300 runs of 200 random plug, unplug and select steps. --- docs/decomp/MemoryMonitor.md | 50 ++ theseus/xbox/memory_monitor.cpp | 906 +++++++++++--------------------- 2 files changed, 358 insertions(+), 598 deletions(-) create mode 100644 docs/decomp/MemoryMonitor.md diff --git a/docs/decomp/MemoryMonitor.md b/docs/decomp/MemoryMonitor.md new file mode 100644 index 0000000..a2b0204 --- /dev/null +++ b/docs/decomp/MemoryMonitor.md @@ -0,0 +1,50 @@ +# Memory Monitor + +The `MemoryMonitor` node in the 5960 retail binary (one global instance at `0x0017c610`). Memory +units are numbered `port * 2 + slot` (0..7) with the hard drive as 8. Layout: `curDevUnit` +0x1c, +`invalidDevUnit` +0x20, `blockInsertion` +0x24, `enumerationOn` +0x25, block totals +0x28/+0x2c, +slot totals +0x30/+0x34, preferred row/side/slot +0x38..+0x40, pending units +0x44, mounted flags ++0x48, mount letters +0x50. + +## Functions + +| Address | Name | What it does | +|---------|------|--------------| +| 0x0004be70 | CMemoryMonitor::CMemoryMonitor | Totals -1, hard drive selected, everything plugged in pending, one enumeration | +| 0x0004bf50 | CMemoryMonitor::UpdateValidDeviceFlags | Below | +| 0x0004c1f0 / 0x0004c210 | HaveDeviceTop / HaveDeviceBottom | Mounted flag of a port's slot, 0 for a bad port | +| 0x0004c3b0 | CMemoryMonitor::GetTotalAndFreeBlocks | `C:` or the unit's letter through `GetDiskFreeSpaceEx`, rounded up to 16 KB blocks, total less one for the root; a failure marks a unit gone and gives 0 | +| 0x0004c230 | (slot counter) | Xbox Live accounts: 8 on the hard drive less those stored, 1 on a unit without one | +| 0x0004c480 | CMemoryMonitor::Advance | Enumerate, fall back to the hard drive, refresh the selected drive's blocks, `OnTotalFreeChanged` | +| 0x0004c510..0x0004c6e0 | selectUp/Down/Left/Right | Below | +| 0x0004c7d0 | selectDevUnit | T or U is the hard drive, F..M a unit; enumerates once, selects if mounted | +| 0x0004c840 / 0x0004c8c0 | FormatDeviceName | `XMUNameFromDriveLetter` of a mounted unit (-1 is the selection), else "" | +| 0x0004cbc0 / 0x0004ca90 / 0x0004cb90 | FormatTotalBlocks / FormatFreeBlocks / GetTotalFreeBlocks | `%d`, capped as "50000+" | +| 0x0004c930 / 0x0004c9d0 / 0x0004cb60 | FormatTotalSlots / FormatFreeSlots / GetTotalFreeSlots | Slot counts, capped as "8+" | +| 0x0004cc70 | GetFreeTotalRatio | free / total, 0 when the drive can't be read | +| 0x0004ccd0 | SetMUName | Names a mounted unit when the name fits in 32 characters | +| 0x0004cd10 | FormatMemoryUnit | Unmount, format (0x0002dcc0), remount, rescan its titles | + +## UpdateValidDeviceFlags + +Runs only with `enumerationOn`, and only when `XGetDeviceChanges` reports something or a unit is +pending. Wakes the screen saver, then `pending = (pending & ~removed) | inserted` and for each unit +(bit `1 << port` for the top slot, `0x10000 << port` for the bottom): + +- Removed: if mounted, unmount, clear its titles, and if it was selected select the hard drive + (`OnCurDevUnitChange`). If it was the bad unit, `OnInvalidMURemoved`. Then `OnDeviceChange`. +- Pending and insertion not blocked: up to three `XMountMURoot` tries. Mounted: clean it, set its + titles' root, `OnDeviceChange`. Not: it becomes the bad unit, is formatted, `OnDeviceChange`, then + `OnInvalidMU(unit, mounted now ? 1 : 0)`. + +## Selection + +Each unit has a path per direction (table `0x00174b38`, terminated by 0xFF); the first entry that is +the hard drive or a mounted unit wins. From the hard drive, up and down do nothing; left tries the +preferred row's port 1 or 2 (bottom slot first) then the other row, right ports 4 or 3 (top slot +first); nothing there leaves the hard drive selected with no event. Every move records the +preferred row (up 0, down 1) or side (left 0, right 1) and the unit's slot, then fires +`OnCurDevUnitChange`. + +Theseus mounts units at H..O rather than F..M, counts slots from blocks (capped at 8) instead of +accounts, refuses `FormatMemoryUnit` for the hard drive, and returns 0 for an empty drive's ratio. diff --git a/theseus/xbox/memory_monitor.cpp b/theseus/xbox/memory_monitor.cpp index 97789dc..9456c22 100755 --- a/theseus/xbox/memory_monitor.cpp +++ b/theseus/xbox/memory_monitor.cpp @@ -1,7 +1,7 @@ -// memory_monitor.cpp: CMemoryMonitor XAP node. Drives the Memory -// pane (device list, per-device free space, title and savegame -// totals, navigation between devices and the save grid). Decompiled -// from the 5960 retail XBE. +// memory_monitor.cpp: the MemoryMonitor node behind the Memory pane. It +// mounts memory units as they come and go, tracks which one is selected +// and reports their names and free space. Rebuilt from the 5960 retail +// XBE (0x4be70..0x4cd10); see docs/decomp/MemoryMonitor.md. #include "std.h" #include "theseus.h" @@ -11,135 +11,28 @@ #include "locale_node.h" #include "title_collection.h" -#define up 0 -#define down 1 -#define left 2 -#define right 3 +enum { PATH_UP, PATH_DOWN, PATH_LEFT, PATH_RIGHT }; +#define PATH_END 0xff -#define end 0xff - -struct PATHS +// Where each memory unit slot moves to, per direction: the first entry +// that's the hard drive or a mounted unit wins. Units are numbered by +// controller port and slot (port * 2 + slot), laid out on screen as +// port 1 | port 4 +// port 2 | port 3 +// with the hard drive in the middle. 5960 table @ 0x00174b38. +static const BYTE s_paths[8][4][3] = { - const BYTE *rgpath[4]; -}; - -static const BYTE pathDev1Unit1Up[] = {end}; -static const BYTE pathDev1Unit1Down[] = {Dev2Unit1, Dev2Unit2, /*Dev0,*/ end}; -static const BYTE pathDev1Unit1Left[] = {end}; -static const BYTE pathDev1Unit1Right[] = {Dev1Unit2, Dev0, end}; - -static const BYTE pathDev1Unit2Up[] = {end}; -static const BYTE pathDev1Unit2Down[] = {Dev2Unit2, Dev2Unit1, /*Dev0,*/ end}; -static const BYTE pathDev1Unit2Left[] = {Dev1Unit1, end}; -static const BYTE pathDev1Unit2Right[] = {Dev0, end}; - -static const BYTE pathDev2Unit1Up[] = {Dev1Unit1, Dev1Unit2, /*Dev0,*/ end}; -static const BYTE pathDev2Unit1Down[] = {end}; -static const BYTE pathDev2Unit1Left[] = {end}; -static const BYTE pathDev2Unit1Right[] = {Dev2Unit2, Dev0, end}; - -static const BYTE pathDev2Unit2Up[] = {Dev1Unit2, Dev1Unit1, /*Dev0,*/ end}; -static const BYTE pathDev2Unit2Down[] = {end}; -static const BYTE pathDev2Unit2Left[] = {Dev2Unit1, end}; -static const BYTE pathDev2Unit2Right[] = {Dev0, end}; - -static const BYTE pathDev3Unit1Up[] = {Dev4Unit1, Dev4Unit2, /*Dev0,*/ end}; -static const BYTE pathDev3Unit1Down[] = {end}; -static const BYTE pathDev3Unit1Left[] = {Dev0, end}; -static const BYTE pathDev3Unit1Right[] = {Dev3Unit2, end}; - -static const BYTE pathDev3Unit2Up[] = {Dev4Unit2, Dev4Unit1, /*Dev0,*/ end}; -static const BYTE pathDev3Unit2Down[] = {end}; -static const BYTE pathDev3Unit2Left[] = {Dev3Unit1, Dev0, end}; -static const BYTE pathDev3Unit2Right[] = {end}; - -static const BYTE pathDev4Unit1Up[] = {end}; -static const BYTE pathDev4Unit1Down[] = {Dev3Unit1, Dev3Unit2, /*Dev0,*/ end}; -static const BYTE pathDev4Unit1Left[] = {Dev0, end}; -static const BYTE pathDev4Unit1Right[] = {Dev4Unit2, end}; - -static const BYTE pathDev4Unit2Up[] = {end}; -static const BYTE pathDev4Unit2Down[] = {Dev3Unit2, Dev3Unit1, /*Dev0,*/ end}; -static const BYTE pathDev4Unit2Left[] = {Dev4Unit1, Dev0, end}; -static const BYTE pathDev4Unit2Right[] = {end}; - -static const PATHS pathsDev1Unit1 = - { - pathDev1Unit1Up, - pathDev1Unit1Down, - pathDev1Unit1Left, - pathDev1Unit1Right, -}; - -static const PATHS pathsDev1Unit2 = - { - pathDev1Unit2Up, - pathDev1Unit2Down, - pathDev1Unit2Left, - pathDev1Unit2Right, -}; - -static const PATHS pathsDev2Unit1 = - { - pathDev2Unit1Up, - pathDev2Unit1Down, - pathDev2Unit1Left, - pathDev2Unit1Right, -}; - -static const PATHS pathsDev2Unit2 = - { - pathDev2Unit2Up, - pathDev2Unit2Down, - pathDev2Unit2Left, - pathDev2Unit2Right, -}; - -static const PATHS pathsDev3Unit1 = - { - pathDev3Unit1Up, - pathDev3Unit1Down, - pathDev3Unit1Left, - pathDev3Unit1Right, -}; - -static const PATHS pathsDev3Unit2 = - { - pathDev3Unit2Up, - pathDev3Unit2Down, - pathDev3Unit2Left, - pathDev3Unit2Right, -}; - -static const PATHS pathsDev4Unit1 = - { - pathDev4Unit1Up, - pathDev4Unit1Down, - pathDev4Unit1Left, - pathDev4Unit1Right, -}; - -static const PATHS pathsDev4Unit2 = - { - pathDev4Unit2Up, - pathDev4Unit2Down, - pathDev4Unit2Left, - pathDev4Unit2Right, + // up down left right + { { PATH_END }, { Dev2Unit1, Dev2Unit2, PATH_END }, { PATH_END }, { Dev1Unit2, Dev0, PATH_END } }, + { { PATH_END }, { Dev2Unit2, Dev2Unit1, PATH_END }, { Dev1Unit1, PATH_END }, { Dev0, PATH_END } }, + { { Dev1Unit1, Dev1Unit2, PATH_END }, { PATH_END }, { PATH_END }, { Dev2Unit2, Dev0, PATH_END } }, + { { Dev1Unit2, Dev1Unit1, PATH_END }, { PATH_END }, { Dev2Unit1, PATH_END }, { Dev0, PATH_END } }, + { { Dev4Unit1, Dev4Unit2, PATH_END }, { PATH_END }, { Dev0, PATH_END }, { Dev3Unit2, PATH_END } }, + { { Dev4Unit2, Dev4Unit1, PATH_END }, { PATH_END }, { Dev3Unit1, Dev0, PATH_END }, { PATH_END } }, + { { PATH_END }, { Dev3Unit1, Dev3Unit2, PATH_END }, { Dev0, PATH_END }, { Dev4Unit2, PATH_END } }, + { { PATH_END }, { Dev3Unit2, Dev3Unit1, PATH_END }, { Dev4Unit1, Dev0, PATH_END }, { PATH_END } }, }; -static const PATHS *rgpaths[] = - { - &pathsDev1Unit1, - &pathsDev1Unit2, - &pathsDev2Unit1, - &pathsDev2Unit2, - &pathsDev3Unit1, - &pathsDev3Unit2, - &pathsDev4Unit1, - &pathsDev4Unit2, -}; - - class CMemoryMonitor : public CNode { DECLARE_NODE(CMemoryMonitor, CNode) @@ -168,7 +61,6 @@ class CMemoryMonitor : public CNode void SetMUName(int devUnit, const TCHAR *szName); - // 5960 additions - MU slot counting CStrObject *FormatTotalSlots(); CStrObject *FormatFreeSlots(int devUnit); int GetTotalFreeSlots(int devUnit); @@ -190,15 +82,20 @@ class CMemoryMonitor : public CNode int m_nPrefCol; int m_nPrefUnit; - // - // Tracking the status of found memory units - // DWORD m_dwPendingDevUnits; bool m_rgbValidDevUnit[8]; char m_rgchMount[8]; DECLARE_NODE_PROPS(); DECLARE_NODE_FUNCTIONS(); + +private: + void MountPending(int devUnit); + void HandleRemoval(int devUnit); + void FollowPath(int direction); + void SelectionChanged(); + int FreeBlocksOf(int devUnit); + int FreeSlotsOf(int devUnit); }; CMemoryMonitor *g_pMemoryMonitor; @@ -228,36 +125,42 @@ NODE_FUN_II(HaveDeviceBottom) NODE_FUN_NI(GetFreeTotalRatio) NODE_FUN_VIS(SetMUName) NODE_FUN_VI(FormatMemoryUnit) -// 5960 additions (MU slot counting, separate from block counting) NODE_FUN_SV(FormatTotalSlots) NODE_FUN_SI(FormatFreeSlots) NODE_FUN_II(GetTotalFreeSlots) END_NODE_FUN() #undef _FND_CLASS +static int PortOf(int devUnit) { return devUnit / 2; } +static int SlotOf(int devUnit) { return devUnit % 2; } + +// XGetDevices bits: the top slot's ports in the low word, the bottom's in the high. +static DWORD DeviceBit(int devUnit) { return (SlotOf(devUnit) ? 0x10000u : 1u) << PortOf(devUnit); } + +// CMemoryMonitor::CMemoryMonitor() +// Reconstructed from 5960 retail XBE @ 0x0004be70: becomes the global +// monitor, hard drive selected, nothing mounted or invalid, totals unknown +// (-1), insertion allowed, enumeration off. Every unit already plugged in +// starts out pending. CMemoryMonitor::CMemoryMonitor() { - ASSERT(g_pMemoryMonitor == NULL); g_pMemoryMonitor = this; - ZeroMemory(m_rgchMount, sizeof(m_rgchMount)); + m_curDevUnit = Dev0; + m_invalidDevUnit = -1; + m_blockInsertion = false; + m_enumerationOn = false; m_nTotalBlocks = -1; m_nFreeBlocks = -1; - m_nPrefRow = 0; m_nPrefCol = 0; m_nPrefUnit = 0; - m_curDevUnit = Dev0; - ZeroMemory(m_rgbValidDevUnit, sizeof(m_rgbValidDevUnit)); - - m_invalidDevUnit = -1; - m_blockInsertion = false; - m_enumerationOn = false; + memset(m_rgbValidDevUnit, 0, sizeof(m_rgbValidDevUnit)); + memset(m_rgchMount, 0, sizeof(m_rgchMount)); m_dwPendingDevUnits = XGetDevices(XDEVICE_TYPE_MEMORY_UNIT); - UpdateValidDeviceFlags(); } @@ -267,217 +170,154 @@ CMemoryMonitor::~CMemoryMonitor() bool XboxFormatMemoryUnit(UINT nDevicePort, UINT nMemoryUnit); -void CMemoryMonitor::UpdateValidDeviceFlags() +// A unit went away: unmount it, drop its titles, and fall back to the hard +// drive if it was selected. A bad unit that leaves stops being the bad one. +void CMemoryMonitor::HandleRemoval(int devUnit) +{ + if (m_rgbValidDevUnit[devUnit]) + { + XUnmountMU(PortOf(devUnit), SlotOf(devUnit)); + m_rgchMount[devUnit] = 0; + g_titles[devUnit].SetRoot(0, false); + m_rgbValidDevUnit[devUnit] = false; + + if (m_curDevUnit == devUnit) + { + m_curDevUnit = Dev0; + CallFunction(this, _T("OnCurDevUnitChange")); + } + } + + if (m_invalidDevUnit == devUnit) + { + m_invalidDevUnit = -1; + CallFunction(this, _T("OnInvalidMURemoved")); + } + + CallFunction(this, _T("OnDeviceChange")); +} + +// Mount a pending unit, three tries. One that won't mount becomes the bad +// unit: it's formatted (which mounts it again if it can) and the scene +// hears OnInvalidMU(devUnit, mounted now). +void CMemoryMonitor::MountPending(int devUnit) { + m_dwPendingDevUnits &= ~DeviceBit(devUnit); + + DWORD dwError = ERROR_SUCCESS; + for (int attempt = 0; attempt < 3; attempt++) + { + dwError = XMountMURoot(PortOf(devUnit), SlotOf(devUnit), &m_rgchMount[devUnit]); + if (dwError == ERROR_SUCCESS) + break; + } - // - // If the current scene does not require - // enumeration, then just don't bother. - // + if (dwError == ERROR_SUCCESS) + { + XCleanMUFromRoot(m_rgchMount[devUnit], 0); + m_rgbValidDevUnit[devUnit] = true; + g_titles[devUnit].SetRoot(m_rgchMount[devUnit], false); + CallFunction(this, _T("OnDeviceChange")); + return; + } + + m_invalidDevUnit = devUnit; + FormatMemoryUnit(devUnit); + CallFunction(this, _T("OnDeviceChange")); + + CObject *rgArgs[2]; + rgArgs[0] = new CNumObject((float)devUnit); + rgArgs[1] = new CNumObject(m_rgbValidDevUnit[devUnit] ? 1.0f : 0.0f); + CallFunction(this, _T("OnInvalidMU"), 2, rgArgs); +} + +// CMemoryMonitor::UpdateValidDeviceFlags() +// Reconstructed from 5960 retail XBE @ 0x0004bf50. Only while the scene +// wants enumeration, and only when XGetDeviceChanges reports something or a +// unit is still pending: wakes the screen saver, folds the changes into the +// pending set, then per unit handles a removal and, unless insertion is +// blocked, mounts a pending unit. +void CMemoryMonitor::UpdateValidDeviceFlags() +{ if (!m_enumerationOn) return; - DWORD dwMUInsertions; - DWORD dwMURemovals; - DWORD dwMask; + DWORD dwInserted, dwRemoved; + if (!XGetDeviceChanges(XDEVICE_TYPE_MEMORY_UNIT, &dwInserted, &dwRemoved) && m_dwPendingDevUnits == 0) + return; + + ResetScreenSaver(); + + m_dwPendingDevUnits = (m_dwPendingDevUnits & ~dwRemoved) | dwInserted; - if (XGetDeviceChanges(XDEVICE_TYPE_MEMORY_UNIT, &dwMUInsertions, &dwMURemovals) || m_dwPendingDevUnits) + for (int devUnit = 0; devUnit < 8; devUnit++) { - // - // Stave off the screen saver on device removal or insertion - // - ResetScreenSaver(); - - // - // Update the pending list - // - m_dwPendingDevUnits &= ~dwMURemovals; - m_dwPendingDevUnits |= dwMUInsertions; - - for (int i = 0; i < 8; i += 1) - { - dwMask = ((i % 2) ? 0x10000 : 1) << (i >> 1); - - // - // Handle Removal - // - if (dwMURemovals & dwMask) - { - // - // If device was mounted then unmount it. - // - if (m_rgbValidDevUnit[i]) - { - DWORD dwError = XUnmountMU(i / 2, i & 1); - if (dwError != ERROR_SUCCESS) - TRACE(_T("\001XUnmountMU(%d, %d) failed: %d\n"), i / 2, i & 1, dwError); - else - TRACE(_T("Unmounted %d %d (was %c:)\n"), i / 2, i & 1, m_rgchMount[i]); - m_rgchMount[i] = 0; - g_titles[i].SetRoot(0, false); - m_rgbValidDevUnit[i] = false; - - if (m_curDevUnit == i) - { - TRACE(_T("Pulled out current device; selecting hard drive!\n")); - m_curDevUnit = Dev0; - CallFunction(this, _T("OnCurDevUnitChange")); - } - } - - if (m_invalidDevUnit == i) - { - // Don't fire this more than once - m_invalidDevUnit = -1; - CallFunction(this, _T("OnInvalidMURemoved")); - } - - CallFunction(this, _T("OnDeviceChange")); - } - // - // If we are not handling a bad unit, then - // try to mount any devices on the m_dwPendingDevUnits - // list. - // - if (!m_blockInsertion && (m_dwPendingDevUnits & dwMask)) - { - int retry; - DWORD dwError; - - ASSERT(0 == m_rgchMount[i]); - - // - // Clear the pending flag, we will either - // mount it, or it becomes the current - // bad unit. - // - m_dwPendingDevUnits &= ~dwMask; - - // - // Make up to three attempts to mount the - // thing. - // - for (retry = 0; retry < 3; retry++) - { - dwError = XMountMURoot(i / 2, i & 1, &m_rgchMount[i]); - if (dwError == ERROR_SUCCESS) - { - XCleanMUFromRoot(m_rgchMount[i], 0); - break; - } - } - - if (dwError == ERROR_SUCCESS) - { - TRACE(_T("Mounted %d %d as devUnit %d drive %c:\n"), i / 2, i & 1, i, m_rgchMount[i]); - m_rgbValidDevUnit[i] = true; - g_titles[i].SetRoot(m_rgchMount[i], false); - CallFunction(this, _T("OnDeviceChange")); - } - else - { - bool bFormatSucceeded = false; - - m_invalidDevUnit = i; - - TRACE(_T("\002XMountMU(%d, %d) failed: %d\n"), i / 2, i & 1, dwError); - - // - // Reformat, this will also attempt the mount - // - - FormatMemoryUnit(i); - CallFunction(this, _T("OnDeviceChange")); - - // - // Notify script that we found a bad device. - // - CObject *rgparam[2]; - rgparam[0] = new CNumObject((float)i); - rgparam[1] = new CNumObject(m_rgbValidDevUnit[i] ? 1.0f : 0.0f); - - CallFunction(this, _T("OnInvalidMU"), 2, rgparam); - } - } - } + DWORD dwBit = DeviceBit(devUnit); + + if (dwRemoved & dwBit) + HandleRemoval(devUnit); + + if (!m_blockInsertion && (m_dwPendingDevUnits & dwBit)) + MountPending(devUnit); } } +// CMemoryMonitor::HaveDeviceTop(port) [script fn 'HaveDeviceTop', FND 0x00187b60, sig 3] +// CMemoryMonitor::HaveDeviceBottom(port) [script fn 'HaveDeviceBottom', FND 0x00187b78, sig 3] +// Reconstructed from 5960 retail XBE @ 0x0004c1f0 and 0x0004c210: whether +// that port's top or bottom slot holds a mounted unit; 0 for a bad port. int CMemoryMonitor::HaveDeviceTop(int nDevice) { - if (nDevice < 0 || nDevice > 3) - return 0; - - return m_rgbValidDevUnit[nDevice * 2]; + return (nDevice >= 0 && nDevice < 4) ? m_rgbValidDevUnit[nDevice * 2] : 0; } int CMemoryMonitor::HaveDeviceBottom(int nDevice) { - if (nDevice < 0 || nDevice > 3) - return 0; - - return m_rgbValidDevUnit[nDevice * 2 + 1]; + return (nDevice >= 0 && nDevice < 4) ? m_rgbValidDevUnit[nDevice * 2 + 1] : 0; } +// CMemoryMonitor::GetTotalAndFreeBlocks(devUnit, &total, &free) +// Reconstructed from 5960 retail XBE @ 0x0004c3b0. The hard drive is C:, +// a unit its mount letter (unmounted fails). Both sizes are rounded up to +// 16 KB blocks and one block comes off the total for the root directory. +// If the drive can't be asked, a unit is marked gone and both read 0. +// Theseus range checks devUnit first. bool CMemoryMonitor::GetTotalAndFreeBlocks(int devUnit, int *pnTotalBlocks, int *pnFreeBlocks) { if (devUnit < Dev1Unit1 || devUnit > Dev4Unit2) return false; - char szPath[4]; - - if (devUnit == Dev0) + char szRoot[4] = { 'C', ':', '\\', 0 }; + if (devUnit != Dev0) { - szPath[0] = 'C'; - } - else - { - szPath[0] = m_rgchMount[devUnit]; - if (szPath[0] == 0) - { - TRACE(_T("Attempted GetTotalAndFreeBlocks on unmounted devUnit %d\n"), devUnit); + szRoot[0] = m_rgchMount[devUnit]; + if (szRoot[0] == 0) return false; - } } - szPath[1] = ':'; - szPath[2] = '\\'; - szPath[3] = 0; - - ULARGE_INTEGER qwAvailBytes, qwTotalBytes, qwFreeBytes; - if (GetDiskFreeSpaceEx(szPath, &qwAvailBytes, &qwTotalBytes, &qwFreeBytes)) + ULARGE_INTEGER qwAvail, qwTotal, qwFree; + if (!GetDiskFreeSpaceEx(szRoot, &qwAvail, &qwTotal, &qwFree)) { - int nTotalBlocks = (int)((qwTotalBytes.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE); - int nFreeBlocks = (int)((qwFreeBytes.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE); - - nTotalBlocks -= 1; // we always have a root dir that uses at least one block... - - if (pnTotalBlocks != NULL) - *pnTotalBlocks = nTotalBlocks; - if (pnFreeBlocks != NULL) - *pnFreeBlocks = nFreeBlocks; - } - else - { - DWORD dwError = GetLastError(); - TRACE(_T("GetDiskFreeSpaceEx(%c:) failed (%d)\n"), szPath, dwError); - if (devUnit != Dev0) - { m_rgbValidDevUnit[devUnit] = false; - } - if (pnTotalBlocks != NULL) *pnTotalBlocks = 0; if (pnFreeBlocks != NULL) *pnFreeBlocks = 0; - return false; } + if (pnTotalBlocks != NULL) + *pnTotalBlocks = (int)((qwTotal.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE) - 1; + if (pnFreeBlocks != NULL) + *pnFreeBlocks = (int)((qwFree.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE); return true; } +// CMemoryMonitor::Advance(dt) +// Reconstructed from 5960 retail XBE @ 0x0004c480: enumerate, fall back to +// the hard drive if the selected unit is gone, then refresh the selected +// drive's totals and fire OnTotalFreeChanged when either moved. void CMemoryMonitor::Advance(float nSeconds) { CNode::Advance(nSeconds); @@ -486,445 +326,315 @@ void CMemoryMonitor::Advance(float nSeconds) if (m_curDevUnit != Dev0 && !m_rgbValidDevUnit[m_curDevUnit]) { - // We lost the curent memory unit; select the hard drive... - TRACE(_T("We lost the curent memory unit; select the hard drive...\n")); m_curDevUnit = Dev0; CallFunction(this, _T("OnCurDevUnitChange")); } + int nTotal = 0, nFree = 0; + GetTotalAndFreeBlocks(m_curDevUnit, &nTotal, &nFree); + if (nTotal != m_nTotalBlocks || nFree != m_nFreeBlocks) { - int totalBlocks = 0; - int freeBlocks = 0; - - GetTotalAndFreeBlocks(m_curDevUnit, &totalBlocks, &freeBlocks); + m_nTotalBlocks = nTotal; + m_nFreeBlocks = nFree; + CallFunction(this, _T("OnTotalFreeChanged")); + } +} - if (totalBlocks != m_nTotalBlocks || freeBlocks != m_nFreeBlocks) +// Move along the selected unit's path in one direction (s_paths). +void CMemoryMonitor::FollowPath(int direction) +{ + for (const BYTE *pNext = s_paths[m_curDevUnit][direction]; *pNext != PATH_END; pNext++) + { + if (*pNext == Dev0 || m_rgbValidDevUnit[*pNext]) { - m_nTotalBlocks = totalBlocks; - m_nFreeBlocks = freeBlocks; - CallFunction(this, _T("OnTotalFreeChanged")); + m_curDevUnit = *pNext; + return; } } } +// The selection moved; the scene redraws from OnCurDevUnitChange. +void CMemoryMonitor::SelectionChanged() +{ + CallFunction(this, _T("OnCurDevUnitChange")); +} + +// CMemoryMonitor::selectUp() / selectDown() [script fns, FND 0x00187a40, 0x00187a58, sig 1] +// Reconstructed from 5960 retail XBE @ 0x0004c510 and 0x0004c580. Nothing +// from the hard drive. Otherwise follow the path, prefer the top (up) or +// bottom (down) row from now on, note the unit's slot and side (ports 3 +// and 4 are the right side), and fire OnCurDevUnitChange. void CMemoryMonitor::selectUp() { if (m_curDevUnit == Dev0) - { return; - /* - m_curDevUnit = (m_nPrefCol == 0 ? Dev1Unit1 : Dev4Unit1) + m_nPrefUnit; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefCol == 0 ? Dev1Unit1 : Dev4Unit1) + (1 - m_nPrefUnit); - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefCol != 0 ? Dev1Unit1 : Dev4Unit1) + m_nPrefUnit; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefCol != 0 ? Dev1Unit1 : Dev4Unit1) + (1 - m_nPrefUnit); - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = Dev0; - return; - } - } - } - } - */ - } - else - { - const PATHS *ppath = rgpaths[m_curDevUnit]; - for (const BYTE *path = ppath->rgpath[up]; *path != end; path += 1) - { - if (*path == Dev0 || m_rgbValidDevUnit[*path]) - { - m_curDevUnit = *path; - break; - } - } - } - + FollowPath(PATH_UP); m_nPrefRow = 0; - if (m_curDevUnit != Dev0) { - m_nPrefUnit = m_curDevUnit & 1; - m_nPrefCol = (m_curDevUnit / 2) >= 2; + m_nPrefUnit = SlotOf(m_curDevUnit); + m_nPrefCol = PortOf(m_curDevUnit) > 1; } - - CallFunction(this, _T("OnCurDevUnitChange")); + SelectionChanged(); } void CMemoryMonitor::selectDown() { if (m_curDevUnit == Dev0) - { return; - /* - m_curDevUnit = (m_nPrefCol == 0 ? Dev2Unit1 : Dev3Unit1) + m_nPrefUnit; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefCol == 0 ? Dev2Unit1 : Dev3Unit1) + (1 - m_nPrefUnit); - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefCol != 0 ? Dev2Unit1 : Dev3Unit1) + m_nPrefUnit; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefCol != 0 ? Dev2Unit1 : Dev3Unit1) + (1 - m_nPrefUnit); - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = Dev0; - return; - } - } - } - } - */ - } - else - { - const PATHS *ppath = rgpaths[m_curDevUnit]; - for (const BYTE *path = ppath->rgpath[down]; *path != end; path += 1) - { - if (*path == Dev0 || m_rgbValidDevUnit[*path]) - { - m_curDevUnit = *path; - break; - } - } - } - + FollowPath(PATH_DOWN); m_nPrefRow = 1; - if (m_curDevUnit != Dev0) { - m_nPrefUnit = m_curDevUnit & 1; - m_nPrefCol = (m_curDevUnit / 2) >= 2; + m_nPrefUnit = SlotOf(m_curDevUnit); + m_nPrefCol = PortOf(m_curDevUnit) > 1; } - - CallFunction(this, _T("OnCurDevUnitChange")); + SelectionChanged(); } +// CMemoryMonitor::selectLeft() / selectRight() [script fns, FND 0x00187a70, 0x00187a88, sig 1] +// Reconstructed from 5960 retail XBE @ 0x0004c600 and 0x0004c6e0. From the +// hard drive, try that side's port in the preferred row, then the other +// row; left tries the bottom slot first, right the top. Nothing mounted on +// that side leaves the hard drive selected and fires nothing. Otherwise +// follow the path. Then prefer that side, note the slot and row (ports 2 +// and 3 are the bottom row) and fire OnCurDevUnitChange. void CMemoryMonitor::selectLeft() { if (m_curDevUnit == Dev0) { - m_curDevUnit = (m_nPrefRow == 0 ? Dev1Unit1 : Dev2Unit1) + 1; - if (!m_rgbValidDevUnit[m_curDevUnit]) + int nearPort = m_nPrefRow == 0 ? Dev1Unit1 : Dev2Unit1; + int farPort = m_nPrefRow == 0 ? Dev2Unit1 : Dev1Unit1; + const int tries[4] = { nearPort + 1, nearPort, farPort + 1, farPort }; + int i = 0; + while (i < 4 && !m_rgbValidDevUnit[tries[i]]) + i++; + if (i == 4) { - m_curDevUnit = (m_nPrefRow == 0 ? Dev1Unit1 : Dev2Unit1) + 0; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefRow != 0 ? Dev1Unit1 : Dev2Unit1) + 1; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefRow != 0 ? Dev1Unit1 : Dev2Unit1) + 0; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = Dev0; - return; - } - } - } + m_curDevUnit = Dev0; + return; } + m_curDevUnit = tries[i]; } else { - const PATHS *ppath = rgpaths[m_curDevUnit]; - for (const BYTE *path = ppath->rgpath[left]; *path != end; path += 1) - { - if (*path == Dev0 || m_rgbValidDevUnit[*path]) - { - m_curDevUnit = *path; - break; - } - } + FollowPath(PATH_LEFT); } m_nPrefCol = 0; - if (m_curDevUnit != Dev0) { - m_nPrefUnit = m_curDevUnit & 1; - m_nPrefRow = (m_curDevUnit / 2) == 1 || (m_curDevUnit / 2) == 2; + m_nPrefUnit = SlotOf(m_curDevUnit); + m_nPrefRow = PortOf(m_curDevUnit) == 1 || PortOf(m_curDevUnit) == 2; } - - CallFunction(this, _T("OnCurDevUnitChange")); + SelectionChanged(); } void CMemoryMonitor::selectRight() { if (m_curDevUnit == Dev0) { - m_curDevUnit = (m_nPrefRow == 0 ? Dev4Unit1 : Dev3Unit1) + 0; - if (!m_rgbValidDevUnit[m_curDevUnit]) + int nearPort = m_nPrefRow == 0 ? Dev4Unit1 : Dev3Unit1; + int farPort = m_nPrefRow == 0 ? Dev3Unit1 : Dev4Unit1; + const int tries[4] = { nearPort, nearPort + 1, farPort, farPort + 1 }; + int i = 0; + while (i < 4 && !m_rgbValidDevUnit[tries[i]]) + i++; + if (i == 4) { - m_curDevUnit = (m_nPrefRow == 0 ? Dev4Unit1 : Dev3Unit1) + 1; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefRow != 0 ? Dev4Unit1 : Dev3Unit1) + 0; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = (m_nPrefRow != 0 ? Dev4Unit1 : Dev3Unit1) + 1; - if (!m_rgbValidDevUnit[m_curDevUnit]) - { - m_curDevUnit = Dev0; - return; - } - } - } + m_curDevUnit = Dev0; + return; } + m_curDevUnit = tries[i]; } else { - const PATHS *ppath = rgpaths[m_curDevUnit]; - for (const BYTE *path = ppath->rgpath[right]; *path != end; path += 1) - { - if (*path == Dev0 || m_rgbValidDevUnit[*path]) - { - m_curDevUnit = *path; - break; - } - } + FollowPath(PATH_RIGHT); } m_nPrefCol = 1; - if (m_curDevUnit != Dev0) { - m_nPrefUnit = m_curDevUnit & 1; - m_nPrefRow = (m_curDevUnit / 2) == 1 || (m_curDevUnit / 2) == 2; + m_nPrefUnit = SlotOf(m_curDevUnit); + m_nPrefRow = PortOf(m_curDevUnit) == 1 || PortOf(m_curDevUnit) == 2; } - - CallFunction(this, _T("OnCurDevUnitChange")); + SelectionChanged(); } +// CMemoryMonitor::selectDevUnit(letter) [script fn 'selectDevUnit', FND 0x00187aa0, sig 3] +// Reconstructed from 5960 retail XBE @ 0x0004c7d0. T and U mean the hard +// drive, a unit letter means that unit; anything else fails. Enumerates +// once even if the scene hasn't asked to, then selects the drive if it's +// there. 5960's unit letters are F to M; Theseus mounts units at H to O. int CMemoryMonitor::selectDevUnit(int DriveLetter) { - int nDevUnit; - - DriveLetter = toupper(DriveLetter); - - // Convert drive letter to device unit - if (DriveLetter == 'T' || DriveLetter == 'U') - { - nDevUnit = Dev0; - } - else if (DriveLetter >= 'H' && DriveLetter <= 'O') - { - nDevUnit = DriveLetter - 'H'; - ASSERT(nDevUnit >= Dev1Unit1 && nDevUnit <= Dev4Unit2); - } + int letter = toupper(DriveLetter); + int devUnit; + if (letter == 'T' || letter == 'U') + devUnit = Dev0; + else if (letter >= 'H' && letter <= 'O') + devUnit = letter - 'H'; else - { - TRACE(_T("Invalid drive letter: %c\n"), DriveLetter); return false; - } - - // Save enumeration state - bool bSaveEnumerationState = m_enumerationOn; - // Force enumeration in case we haven't done that before + bool bWasOn = m_enumerationOn; m_enumerationOn = true; UpdateValidDeviceFlags(); + m_enumerationOn = bWasOn; - // Restore enumeration state - m_enumerationOn = bSaveEnumerationState; - - if (nDevUnit != Dev0 && !m_rgbValidDevUnit[nDevUnit]) - { + if (devUnit != Dev0 && !m_rgbValidDevUnit[devUnit]) return false; - } - m_curDevUnit = nDevUnit; + m_curDevUnit = devUnit; return true; } +// Name lookup for the save grid; an unmounted unit gives "". void FormatDeviceName(int devUnit, TCHAR *szBuf) { - ASSERT(g_pMemoryMonitor != NULL); if (!g_pMemoryMonitor->FormatDeviceName2(devUnit, szBuf)) szBuf[0] = 0; } +// CMemoryMonitor::FormatDeviceName(devUnit) [script fn 'FormatDeviceName', FND 0x00187ab8, sig 4] +// Reconstructed from 5960 retail XBE @ 0x0004c840 and its helper @ 0x0004c8c0: +// -1 means the selected unit; a mounted unit gives its name +// (XMUNameFromDriveLetter), anything else "". CStrObject *CMemoryMonitor::FormatDeviceName(int devUnit) { - TCHAR szBuf[MAX_MUNAME]; - - if (!FormatDeviceName2(devUnit, szBuf)) - szBuf[0] = 0; - - return new CStrObject(szBuf); + TCHAR szName[MAX_MUNAME]; + if (!FormatDeviceName2(devUnit, szName)) + szName[0] = 0; + return new CStrObject(szName); } bool CMemoryMonitor::FormatDeviceName2(int devUnit, TCHAR *szBuf) { if (devUnit == -1) devUnit = m_curDevUnit; - if (devUnit < Dev1Unit1 || devUnit > Dev4Unit2 || m_rgchMount[devUnit] == 0) - { - TRACE(_T("Attempt to get name of unmounted unit: %d\n"), devUnit); return false; - } TCHAR szName[MAX_MUNAME]; - DWORD dwError = XMUNameFromDriveLetter(m_rgchMount[devUnit], szName, MAX_MUNAME); - if (dwError != ERROR_SUCCESS) + if (XMUNameFromDriveLetter(m_rgchMount[devUnit], szName, MAX_MUNAME) != ERROR_SUCCESS) return false; - _tcscpy(szBuf, szName); return true; } -CStrObject *CMemoryMonitor::FormatFreeBlocks(int devUnit) +// Free blocks of a drive, or the cached figure for -1. Left untouched +// (garbage) when the drive can't be read, as in 5960. +int CMemoryMonitor::FreeBlocksOf(int devUnit) { - int nFreeBlocks; + int nFree; if (devUnit == -1) - nFreeBlocks = m_nFreeBlocks; + nFree = m_nFreeBlocks; else - GetTotalAndFreeBlocks(devUnit, NULL, &nFreeBlocks); - - TCHAR szBuf[16]; + GetTotalAndFreeBlocks(devUnit, NULL, &nFree); + return nFree; +} - FormatBlocks(szBuf, nFreeBlocks); +// FormatTotalBlocks / FormatFreeBlocks / GetTotalFreeBlocks [FND 0x00187ad0, 0x00187ae8, 0x00187b00] +// Reconstructed from 5960 retail XBE @ 0x0004cbc0, 0x0004ca90, 0x0004cb90: +// the cached total, or a drive's free blocks (-1 for the cached free count), +// printed as a number with anything past 50000 shown as "50000+". +CStrObject *CMemoryMonitor::FormatTotalBlocks() +{ + TCHAR szBlocks[16]; + FormatBlocks(szBlocks, m_nTotalBlocks); + return new CStrObject(szBlocks); +} - return new CStrObject(szBuf); +CStrObject *CMemoryMonitor::FormatFreeBlocks(int devUnit) +{ + TCHAR szBlocks[16]; + FormatBlocks(szBlocks, FreeBlocksOf(devUnit)); + return new CStrObject(szBlocks); } int CMemoryMonitor::GetTotalFreeBlocks(int devUnit) { - int nFreeBlocks; - if (devUnit == -1) - nFreeBlocks = m_nFreeBlocks; - else - GetTotalAndFreeBlocks(devUnit, NULL, &nFreeBlocks); - - return nFreeBlocks; + return FreeBlocksOf(devUnit); } -CStrObject *CMemoryMonitor::FormatTotalBlocks() +// Slots [FND 0x00187b18, 0x00187b30, 0x00187b48] +// 5960 (0x0004c930, 0x0004c9d0, 0x0004cb60) counts Xbox Live account slots: +// eight on the hard drive less the accounts stored there, one on a unit +// with no account on it, printed with "8+" past eight. Theseus counts the +// same blocks as above, capped at eight. +int CMemoryMonitor::FreeSlotsOf(int devUnit) { - TCHAR szBuf[16]; - - FormatBlocks(szBuf, m_nTotalBlocks); - - return new CStrObject(szBuf); + int nFree = FreeBlocksOf(devUnit); + return nFree > 8 ? 8 : nFree; } -// 5960 additions: MU slot counting -// On HDD (devUnit > 8), total slots is always 8. -// On MU, slots = number of save game "slots" available. - CStrObject *CMemoryMonitor::FormatTotalSlots() { - TCHAR szBuf[16]; - int nSlots = m_nTotalBlocks; - if (nSlots > 8) - nSlots = 8; - FormatBlocks(szBuf, nSlots); - return new CStrObject(szBuf); + TCHAR szSlots[16]; + FormatBlocks(szSlots, m_nTotalBlocks > 8 ? 8 : m_nTotalBlocks); + return new CStrObject(szSlots); } CStrObject *CMemoryMonitor::FormatFreeSlots(int devUnit) { - int nFreeSlots; - if (devUnit == -1) - nFreeSlots = m_nFreeBlocks; - else - GetTotalAndFreeBlocks(devUnit, NULL, &nFreeSlots); - - if (nFreeSlots > 8) - nFreeSlots = 8; - - TCHAR szBuf[16]; - FormatBlocks(szBuf, nFreeSlots); - return new CStrObject(szBuf); + TCHAR szSlots[16]; + FormatBlocks(szSlots, FreeSlotsOf(devUnit)); + return new CStrObject(szSlots); } int CMemoryMonitor::GetTotalFreeSlots(int devUnit) { - int nFreeSlots; - if (devUnit == -1) - nFreeSlots = m_nFreeBlocks; - else - GetTotalAndFreeBlocks(devUnit, NULL, &nFreeSlots); - - if (nFreeSlots > 8) - nFreeSlots = 8; - return nFreeSlots; + return FreeSlotsOf(devUnit); } +// CMemoryMonitor::GetFreeTotalRatio(devUnit) [script fn 'GetFreeTotalRatio', FND 0x00187b90, sig 27] +// Reconstructed from 5960 retail XBE @ 0x0004cc70: free / total blocks of +// the drive, 0 if it can't be read. Theseus also gives 0 for an empty +// total rather than dividing by it. float CMemoryMonitor::GetFreeTotalRatio(int devUnit) { - int nTotalBlocks, nFreeBlocks; - if (!GetTotalAndFreeBlocks(devUnit, &nTotalBlocks, &nFreeBlocks)) - return 0.0f; - - if (nTotalBlocks == 0) + int nTotal, nFree; + if (!GetTotalAndFreeBlocks(devUnit, &nTotal, &nFree) || nTotal == 0) return 0.0f; - - static float nLast[9]; - float nReturn = (float)nFreeBlocks / nTotalBlocks; - if (nReturn != nLast[devUnit]) - { - TRACE(_T("GetFreeTotalRatio(%d) %f\n"), devUnit, nReturn); - nLast[devUnit] = nReturn; - } - - return (float)nFreeBlocks / nTotalBlocks; + return (float)nFree / nTotal; } +// CMemoryMonitor::SetMUName(devUnit, name) [script fn 'SetMUName', FND 0x00187ba8, sig 28] +// Reconstructed from 5960 retail XBE @ 0x0004ccd0: names a mounted unit +// when the name fits in MAX_MUNAME with its terminator. void CMemoryMonitor::SetMUName(int devUnit, const TCHAR *szName) { if (devUnit < Dev1Unit1 || devUnit > Dev4Unit2 || m_rgchMount[devUnit] == 0) - { - TRACE(_T("Attempt to set name of unmounted unit: %d\n"), devUnit); return; - } - if (_tcslen(szName) + 1 > MAX_MUNAME) - { - TRACE(_T("%s is too long!\n"), szName); return; - } - XMUWriteNameToDriveLetter(m_rgchMount[devUnit], szName); } +// CMemoryMonitor::FormatMemoryUnit(devUnit) [script fn 'FormatMemoryUnit', FND 0x00187bc0, sig 14] +// Reconstructed from 5960 retail XBE @ 0x0004cd10: unmount (dropping its +// titles), format, mount again. On a good mount the titles are rescanned +// at once, so the save grid doesn't see the unit as dirty a frame later. +// Theseus refuses anything that isn't a memory unit: scripts reach this, +// and Dev0 sits one past the end of the mount arrays. void CMemoryMonitor::FormatMemoryUnit(int devUnit) { - // Scripts reach this directly, and Dev0 is a real selection that sits one - // past the end of the mount arrays. Only memory units can be formatted. if (devUnit < Dev1Unit1 || devUnit > Dev4Unit2) - { - TRACE(_T("\001FormatMemoryUnit: %d is not a memory unit\n"), devUnit); return; - } if (m_rgchMount[devUnit] != 0) { - XUnmountMU(devUnit / 2, devUnit & 1); + XUnmountMU(PortOf(devUnit), SlotOf(devUnit)); m_rgchMount[devUnit] = 0; g_titles[devUnit].SetRoot(0, false); } m_rgbValidDevUnit[devUnit] = false; - XboxFormatMemoryUnit(devUnit / 2, devUnit & 1); + XboxFormatMemoryUnit(PortOf(devUnit), SlotOf(devUnit)); - DWORD dwError = XMountMURoot(devUnit / 2, devUnit & 1, &m_rgchMount[devUnit]); - if (dwError == ERROR_SUCCESS) + if (XMountMURoot(PortOf(devUnit), SlotOf(devUnit), &m_rgchMount[devUnit]) == ERROR_SUCCESS) { - TRACE(_T("Mounted %d %d as devUnit %d drive %c:\n"), devUnit / 2, devUnit & 1, devUnit, m_rgchMount[devUnit]); m_rgbValidDevUnit[devUnit] = true; - - // - // Set root drive and force update right away so that the dirty flag - // won't show up in the next CSavedGameGrid::Advance. Besides, this - // should be fast since we just format it to be empty. - // g_titles[devUnit].SetRoot(m_rgchMount[devUnit], true); } } From ae60906c9ef067307768e72c95eb4dd22538e705 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 06/13] Rebuilt the Xbox Joystick node from the binary Binding, properties, device handling, the remote code table, event rules and the secret key are written fresh from 0x40620..0x41800. Per port handling, LastActivePort and the overlay hooks stay Theseus's. All 19,708 events match the old code over 200 runs of 600 random pad, remote and property steps. --- docs/decomp/Input.md | 5 + theseus/xbox/input.cpp | 1121 +++++++++++++++++----------------------- 2 files changed, 470 insertions(+), 656 deletions(-) diff --git a/docs/decomp/Input.md b/docs/decomp/Input.md index 41397a4..c7a5296 100644 --- a/docs/decomp/Input.md +++ b/docs/decomp/Input.md @@ -42,3 +42,8 @@ Every event goes through the binding and `enableGamepad` checks (`enableRemote` Theseus's desktop node reads an SDL pad and the keyboard as one player, adds media keys, has no remote or progressive scan combo, accepts pad events even with `enableGamepad` off, and fires OnMoveCenter after the button events rather than before them. + +The Xbox node (`xbox/input.cpp`) keeps 5960's devices, remote codes and event rules but reads each +port on its own instead of merging the pads first, records the last port that gave input +(`LastActivePort`), lets Theseus's overlay take moves and A/B while it captures input (B with the +left trigger shows or hides it), and has no progressive scan combo or keyboard event. diff --git a/theseus/xbox/input.cpp b/theseus/xbox/input.cpp index c0d69fa..d246e1a 100755 --- a/theseus/xbox/input.cpp +++ b/theseus/xbox/input.cpp @@ -1,7 +1,9 @@ -// input.cpp: CJoystick XAP node. Wraps XInput on Xbox: polls -// gamepads, exposes button state and analog axes to scripts, and -// dispatches OnUp / OnDown / OnA / etc. via the node-function table. -// Decompiled from the 5960 retail XBE. +// input.cpp: the Xbox Joystick node. Opens pads and IR remotes as they +// come and go and turns them into script events. The binding, properties, +// device handling, remote codes, event rules and secret key are rebuilt +// from the 5960 retail XBE (0x40620..0x41800); see docs/decomp/Input.md. +// Theseus handles each port on its own (5960 merges the pads first), adds +// LastActivePort and routes input to its overlay while that's capturing. #include "std.h" #include "theseus.h" @@ -14,12 +16,10 @@ #define KS_VERIFIED 0x0002 #define KS_END 0x0004 -float g_xaxis, g_yaxis; +// An analog button counts as down past this. +#define ANALOG_DOWN 0x20 -#ifdef _DEBUG -extern bool g_bWireframe; -extern void CycleLanguage(); -#endif +float g_xaxis, g_yaxis; bool g_bInputEnable; #include "overlay.h" @@ -107,6 +107,15 @@ class CJoystick : public CNode protected: int CheckSecretKeySequence(TCHAR key); void ProcessSecretKeySequence(int flags); + +private: + void ReadAllDevices(); + void OpenPorts(PXPP_DEVICE_TYPE type); + bool PollRemote(int port, float nSeconds); + void PollPad(int port); + void FireMoves(int port); + void KeyEvent(TCHAR key, const TCHAR *szEvent, bool bDown); + void RemoteGone(int port); }; HANDLE CJoystick::c_hDevices[4]; @@ -154,78 +163,74 @@ NODE_FUN_VV(OnBDown) END_NODE_FUN() #undef _FND_CLASS -CJoystick::CJoystick() : m_frequency(20.0f), - m_hat(-1.0f), - m_xaxis(0.0f), - m_yaxis(0.0f), - m_xaxis2(0.0f), - m_yaxis2(0.0f), - m_a(0.0f), - m_b(0.0f), - m_x(0.0f), - m_y(0.0f), - m_black(0.0f), - m_white(0.0f), - m_left(0.0f), - m_right(0.0f), - m_leftThumb(0.0f), - m_rightThumb(0.0f), - m_start(0.0f), - m_back(0.0f), - m_secretKey(NULL), - m_secretKeyLength(0), - m_secretKeyCurrentIndex(0), - m_enableSecretKey(false), - m_eatSecretKey(false), - m_enableRemote(true), - m_enableGamepad(true), - m_LastActivePort(0), - m_isBound(false), - m_remoteIdleTime(0.0f), - m_timeRemoteRemoved(0.0f), - m_removeRemoteCalled(false), - m_remoteRepeatCount(0) +// CJoystick::CJoystick() +// Reconstructed from 5960 retail XBE @ 0x00040620: 20 polls a second, +// sticks and buttons at rest, no secret key, remote and gamepad enabled, +// waiting for its first poll. The first Joystick made binds itself. +// Theseus starts hat at -1 and keeps per port repeat timers. +CJoystick::CJoystick() { m_needsInit = true; - - for (int i = 0; i < 4; i += 1) + m_isBound = false; + m_frequency = 20.0f; + m_hat = -1.0f; + m_xaxis = m_yaxis = 0.0f; + m_xaxis2 = m_yaxis2 = 0.0f; + m_a = m_b = m_x = m_y = 0.0f; + m_black = m_white = 0.0f; + m_left = m_right = 0.0f; + m_leftThumb = m_rightThumb = 0.0f; + m_start = m_back = 0.0f; + + m_secretKey = NULL; + m_secretKeyLength = 0; + m_secretKeyCurrentIndex = 0; + m_enableSecretKey = false; + m_eatSecretKey = false; + m_enableRemote = true; + m_enableGamepad = true; + m_LastActivePort = 0; + + m_remoteIdleTime = 0.0f; + m_remoteRepeatCount = 0; + m_timeRemoteRemoved = 0.0f; + m_removeRemoteCalled = false; + for (int port = 0; port < 4; port++) { - m_nextRepeatTime[i] = 0.0f; - m_repeatInterval[i] = 0.0f; + m_nextRepeatTime[port] = 0.0f; + m_repeatInterval[port] = 0.0f; } if (c_pBoundJoystick == NULL) Bind(); } +// CJoystick::~CJoystick() +// Reconstructed from 5960 retail XBE @ 0x00040750: forgets itself as the +// previous binding, hands the binding back if it held it, frees the key. CJoystick::~CJoystick() { if (c_pPreviousBoundJoystick == this) c_pPreviousBoundJoystick = NULL; - if (c_pBoundJoystick == this) c_pBoundJoystick = c_pPreviousBoundJoystick; - delete[] m_secretKey; } +// Events go only to the bound joystick, and only while their kind of input +// (remote or gamepad) is enabled. 5960 tests the same at every call site. void CJoystick::CallFunction(const TCHAR *szFunc, bool bRemote /* = false */) { - if (c_pBoundJoystick == this) - { - if (bRemote && !m_enableRemote) - { - TRACE(_T("Ignoring input from remote\n")); - return; - } - if (!bRemote && !m_enableGamepad) - { - TRACE(_T("Ignoring input from gamepad\n")); - return; - } - ::CallFunction(this, szFunc); - } + if (c_pBoundJoystick != this) + return; + if (bRemote ? !m_enableRemote : !m_enableGamepad) + return; + ::CallFunction(this, szFunc); } + +// BindJoystick(node) +// Reconstructed from 5960 retail XBE @ 0x00040790: NULL clears both +// bindings; a Joystick node gets bound; anything else is ignored. void BindJoystick(CNode *pJoystickNode) { if (pJoystickNode == NULL) @@ -234,12 +239,11 @@ void BindJoystick(CNode *pJoystickNode) CJoystick::c_pPreviousBoundJoystick = NULL; return; } - - if (!pJoystickNode->IsKindOf(NODE_CLASS(CJoystick))) - return; - - ((CJoystick *)pJoystickNode)->Bind(); + if (pJoystickNode->IsKindOf(NODE_CLASS(CJoystick))) + ((CJoystick *)pJoystickNode)->Bind(); } + +// Theseus: script-callable names with nothing behind them. void CJoystick::OnMoveUp() { } @@ -256,167 +260,158 @@ void CJoystick::OnBDown() { } +// Take a fresh reading of every open device so held buttons don't fire. +void CJoystick::ReadAllDevices() +{ + for (int port = 0; port < 4; port++) + { + if (c_hDevices[port] != NULL) + XInputGetState(c_hDevices[port], (XINPUT_STATE *)&m_joystate[port]); + } +} + +// CJoystick::Bind() +// Reconstructed from 5960 retail XBE @ 0x000407f0: the current binding +// becomes the previous one and this takes over; once it has polled before, +// it looks for devices and rereads them. void CJoystick::Bind() { c_pPreviousBoundJoystick = c_pBoundJoystick; c_pBoundJoystick = this; - - if (!m_needsInit) - { - CheckDevice(); - for (int i = 0; i < 4; i += 1) - { - if (c_hDevices[i] != NULL) - XInputGetState(c_hDevices[i], (XINPUT_STATE *)&m_joystate[i]); - } - } + if (m_needsInit) + return; + CheckDevice(); + ReadAllDevices(); } +// CJoystick::OnSetProperty(prd, value) +// Reconstructed from 5960 retail XBE @ 0x00040820. +// isBound: true binds; false, if bound, unbinds and rebinds the previous +// secretKey: replaces the key (ending a sequence in progress), and a new +// key turns enableSecretKey on +// enableSecretKey: stores it; turning it off mid sequence ends it; the +// position restarts either way +// eatSecretKey, enableGamepad, enableRemote: stored here, not by the caller bool CJoystick::OnSetProperty(const PRD *pprd, const void *pvValue) { - if (PTR2INT(pprd->pbOffset) == offsetof(m_isBound)) + INT_PTR field = PTR2INT(pprd->pbOffset); + + if (field == offsetof(m_isBound)) { - if (*(bool *)pvValue) + if (*(const bool *)pvValue) { Bind(); } else if (c_pBoundJoystick == this) { c_pBoundJoystick = NULL; - if (c_pPreviousBoundJoystick != NULL) c_pPreviousBoundJoystick->Bind(); } + return true; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_secretKey)) + + if (field == offsetof(m_secretKey)) { - // Delete the previous one if exists delete[] m_secretKey; m_secretKey = NULL; m_secretKeyLength = 0; - - // Cancel if we are in the middle of sequence checking - if (m_secretKeyCurrentIndex) + if (m_secretKeyCurrentIndex != 0) ProcessSecretKeySequence(KS_END); - m_secretKeyCurrentIndex = 0; - TCHAR *pszNewKey = *(TCHAR **)pvValue; - if (pszNewKey) + const TCHAR *szKey = *(TCHAR *const *)pvValue; + if (szKey != NULL) { - m_secretKeyLength = _tcslen(pszNewKey); + m_secretKeyLength = _tcslen(szKey); m_secretKey = new TCHAR[m_secretKeyLength + 1]; - _tcscpy(m_secretKey, pszNewKey); + _tcscpy(m_secretKey, szKey); m_enableSecretKey = true; } + return true; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_enableSecretKey)) - { - m_enableSecretKey = *(bool *)pvValue; - - if (!m_enableSecretKey) - { - // Cancel if we are in the middle of sequence checking - if (m_secretKeyCurrentIndex && m_secretKeyCurrentIndex < m_secretKeyLength) - ProcessSecretKeySequence(KS_END); - } + if (field == offsetof(m_enableSecretKey)) + { + m_enableSecretKey = *(const bool *)pvValue; + if (!m_enableSecretKey && m_secretKeyCurrentIndex != 0 && m_secretKeyCurrentIndex < m_secretKeyLength) + ProcessSecretKeySequence(KS_END); m_secretKeyCurrentIndex = 0; + return true; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_eatSecretKey)) + + if (field == offsetof(m_eatSecretKey)) { - m_eatSecretKey = *(bool *)pvValue; + m_eatSecretKey = *(const bool *)pvValue; return false; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_enableGamepad)) + if (field == offsetof(m_enableGamepad)) { -#if defined(_DEBUG) || defined(COOL_XDASH) - TRACE(_T("\001Gamepad can be disabled only in retail build! ask Tyler (a-tylerc) why\n")); -#else - m_enableGamepad = *(bool *)pvValue; -#endif + m_enableGamepad = *(const bool *)pvValue; return false; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_enableRemote)) + if (field == offsetof(m_enableRemote)) { - m_enableRemote = *(bool *)pvValue; + m_enableRemote = *(const bool *)pvValue; return false; } return true; } -// Poll the XInput device manager for hot-plug changes on every port, -// opening newly-attached pads/remotes and closing handles for any that -// have gone away. Called every Advance pass. -bool CJoystick::CheckDevice() +// Open devices of one type that turned up on a free port, and close ours +// on ports where that type is gone. +void CJoystick::OpenPorts(PXPP_DEVICE_TYPE type) { - DWORD gamepadDevices = XGetDevices(XDEVICE_TYPE_GAMEPAD); - for (int i = 0; i < 4; i += 1) - { - if (c_hDevices[i] == NULL) - { - if ((gamepadDevices & (1 << i)) != 0) - { - TRACE(_T("Opening device %d\n"), i); - c_hDevices[i] = XInputOpen(XDEVICE_TYPE_GAMEPAD, i, XDEVICE_NO_SLOT, NULL); - if (c_hDevices[i] != NULL) - { - TRACE(_T("We have a gamepad on port %d (0x%08x)\n"), i, c_hDevices[i]); - c_devtype[i] = XDEVICE_TYPE_GAMEPAD; - XInputGetState(c_hDevices[i], (XINPUT_STATE *)&m_joystate[i]); - m_timeNextUpdate = TheseusGetNow(); - } - } - } - else if (c_devtype[i] == XDEVICE_TYPE_GAMEPAD) - { - if ((gamepadDevices & (1 << i)) == 0) - { - TRACE(_T("Gamepad %d was removed! (0x%08x)\n"), i, c_hDevices[i]); - XInputClose(c_hDevices[i]); - c_devtype[i] = NULL; - c_hDevices[i] = NULL; - } - } - } + DWORD dwPresent = XGetDevices(type); + bool bRemote = (type == XDEVICE_TYPE_IR_REMOTE); - DWORD remoteDevices = XGetDevices(XDEVICE_TYPE_IR_REMOTE); - for (int i = 0; i < 4; i += 1) + for (int port = 0; port < 4; port++) { - if (c_hDevices[i] == NULL) + bool bThere = (dwPresent & (1 << port)) != 0; + + if (c_hDevices[port] == NULL) { - if ((remoteDevices & (1 << i)) != 0) + if (!bThere) + continue; + c_hDevices[port] = XInputOpen(type, port, XDEVICE_NO_SLOT, NULL); + if (c_hDevices[port] == NULL) + continue; + + c_devtype[port] = type; + XInputGetState(c_hDevices[port], (XINPUT_STATE *)&m_joystate[port]); + m_timeNextUpdate = TheseusGetNow(); + if (bRemote) { - TRACE(_T("Opening device %d\n"), i); - c_hDevices[i] = XInputOpen(XDEVICE_TYPE_IR_REMOTE, i, XDEVICE_NO_SLOT, NULL); - if (c_hDevices[i] != NULL) - { - TRACE(_T("We have a remote control on port %d (0x%08x)\n"), i, c_hDevices[i]); - c_devtype[i] = XDEVICE_TYPE_IR_REMOTE; - XInputGetState(c_hDevices[i], (XINPUT_STATE *)&m_joystate[i]); - m_timeNextUpdate = TheseusGetNow(); - m_timeRemoteRemoved = 0.0f; - if (m_removeRemoteCalled) - { - CallFunction(_T("OnInsertRemote"), true); - } - } + m_timeRemoteRemoved = 0.0f; + if (m_removeRemoteCalled) + CallFunction(_T("OnInsertRemote"), true); } } - else if (c_devtype[i] == XDEVICE_TYPE_IR_REMOTE) + else if (c_devtype[port] == type && !bThere) { - if ((remoteDevices & (1 << i)) == 0) + XInputClose(c_hDevices[port]); + c_devtype[port] = NULL; + c_hDevices[port] = NULL; + if (bRemote) { - XInputClose(c_hDevices[i]); - c_devtype[i] = NULL; - c_hDevices[i] = NULL; m_timeRemoteRemoved = TheseusGetNow() + 2.0f; m_removeRemoteCalled = false; } } } +} +// CJoystick::CheckDevice() +// Reconstructed from 5960 retail XBE @ 0x00040990: gamepads first, then IR +// remotes, each port opened when its device appears (and read once, so the +// state starts current) and closed when it goes. A remote that comes back +// after OnRemoveRemote fired raises OnInsertRemote; one that leaves starts +// a two second grace before OnRemoveRemote. +bool CJoystick::CheckDevice() +{ + OpenPorts(XDEVICE_TYPE_GAMEPAD); + OpenPorts(XDEVICE_TYPE_IR_REMOTE); return true; } @@ -425,602 +420,416 @@ bool CJoystick::OpenDevice() return true; } +// CJoystick::EnableGlobalInput(on) [script fn 'EnableGlobalInput', FND 0x00181fb0, sig 14] +// Reconstructed from 5960 retail XBE @ 0x00040b70: g_bInputEnable = on != 0. void CJoystick::EnableGlobalInput(int bEnable) { g_bInputEnable = (bEnable != 0); } -// Threshold for analog buttons -#define XINPUT_ANALOGBUTTONTHRESHOLD 32 - -static float ConvertThumb(SHORT sThumb); +// A stick axis as -1..1, with everything inside +-0.9 treated as rest +// (5960 constants @ 0x0002bf08..0x0002bf10). +static float StickValue(SHORT sThumb) +{ + float value = (float)sThumb / 32767.0f; + if (value > -0.9f && value < 0.9f) + return 0.0f; + return value; +} // LastActivePort, 5960 PRD @ 0x001747e8 (int, +0x94), written by -// CJoystick::Advance @ 0x00041040 and its pad merge @ 0x00040e00: -// remote: a key that maps to a script function -> port -// pad: wButtons != 0, an analog button > 0x20, or a thumb past -// the 0.9 dead zone -> port -// 5960 merges all pads before testing; Theseus walks them one at a time, -// so the last port that's active in a poll wins either way. +// CJoystick::Advance @ 0x00041040 and its pad merge @ 0x00040e00: a remote +// key that maps to an event, or a pad with a button held, an analog button +// past 0x20 or a stick out of its rest zone. static bool IsPadActive(const XINPUT_GAMEPAD *pad) { if (pad->wButtons != 0) return true; - for (int i = 0; i < 8; i++) { - if (pad->bAnalogButtons[i] > 0x20) + if (pad->bAnalogButtons[i] > ANALOG_DOWN) return true; } + return StickValue(pad->sThumbLX) != 0.0f || StickValue(pad->sThumbLY) != 0.0f || + StickValue(pad->sThumbRX) != 0.0f || StickValue(pad->sThumbRY) != 0.0f; +} - return ConvertThumb(pad->sThumbLX) != 0.0f || ConvertThumb(pad->sThumbLY) != 0.0f || - ConvertThumb(pad->sThumbRX) != 0.0f || ConvertThumb(pad->sThumbRY) != 0.0f; +// Same buttons pressed and sticks in the same place, as the dash sees them. +static bool SamePadInput(const XINPUT_GAMEPAD *a, const XINPUT_GAMEPAD *b) +{ + if (a->wButtons != b->wButtons) + return false; + for (int i = 0; i < 8; i++) + { + if ((a->bAnalogButtons[i] > ANALOG_DOWN) != (b->bAnalogButtons[i] > ANALOG_DOWN)) + return false; + } + return StickValue(a->sThumbLX) == StickValue(b->sThumbLX) && + StickValue(a->sThumbLY) == StickValue(b->sThumbLY) && + StickValue(a->sThumbRX) == StickValue(b->sThumbRX) && + StickValue(a->sThumbRY) == StickValue(b->sThumbRY); } -static float ConvertThumb(SHORT sThumb) +// IR remote codes and the events they raise (5960 table @ 0x00020f60). A +// second event follows at once for the keys that also act as A and B. +struct REMOTE_KEY { - float axis = (float)sThumb / 32767.0f; + WORD wCode; + const TCHAR *szEvent; + const TCHAR *szThenEvent; +}; - // Large dead zone for prototype dukes... - if (axis < 0.0f && axis > -0.9f) - axis = 0.0f; - else if (axis > 0.0f && axis < 0.9f) - axis = 0.0f; +static const REMOTE_KEY s_remoteKeys[] = +{ + { 0xAD5, _T("OnPower"), NULL }, + { 0xAE2, _T("OnReverse"), NULL }, + { 0xAEA, _T("OnPlay"), NULL }, + { 0xAE3, _T("OnForward"), NULL }, + { 0xADD, _T("OnSkipBack"), NULL }, + { 0xAE0, _T("OnStop"), NULL }, + { 0xAE6, _T("OnPause"), NULL }, + { 0xADF, _T("OnSkipForward"), NULL }, + { 0xAE5, _T("OnGuide"), NULL }, + { 0xAC3, _T("OnInfo"), NULL }, + { 0xAF7, _T("OnMenu"), NULL }, + { 0xAD8, _T("OnBDown"), _T("OnBUp") }, + { 0xAA6, _T("OnMoveUp"), NULL }, + { 0xAA9, _T("OnMoveLeft"), NULL }, + { 0xA0B, _T("OnADown"), _T("OnAUp") }, + { 0xAA8, _T("OnMoveRight"), NULL }, + { 0xAA7, _T("OnMoveDown"), NULL }, + { 0xACF, _T("On0"), NULL }, + { 0xACE, _T("On1"), NULL }, + { 0xACD, _T("On2"), NULL }, + { 0xACC, _T("On3"), NULL }, + { 0xACB, _T("On4"), NULL }, + { 0xACA, _T("On5"), NULL }, + { 0xAC9, _T("On6"), NULL }, + { 0xAC8, _T("On7"), NULL }, + { 0xAC7, _T("On8"), NULL }, + { 0xAC6, _T("On9"), NULL }, +}; - return axis; +// GetCodeFunction(code), 5960 @ 0x00040d50: the table entry for a code. +static const REMOTE_KEY *FindRemoteKey(WORD wCode) +{ + for (int i = 0; i < (int)countof(s_remoteKeys); i++) + { + if (s_remoteKeys[i].wCode == wCode) + return &s_remoteKeys[i]; + } + return NULL; } -static bool EqualGamepads(const XINPUT_GAMEPAD *pad1, const XINPUT_GAMEPAD *pad2) +// The remote went quiet or failed: close it and start the grace period. +void CJoystick::RemoteGone(int port) { - if (pad1->wButtons != pad2->wButtons) + XInputClose(c_hDevices[port]); + c_hDevices[port] = NULL; + c_devtype[port] = NULL; + m_timeRemoteRemoved = TheseusGetNow() + 2.0f; + m_removeRemoteCalled = false; +} + +// One remote poll (5960 does this inside Advance). A held key repeats about +// every 65 ms, so: a new packet is a new press when the key differs or more +// than 120 ms passed since the last one, otherwise a repeat; 150 ms with no +// packet ends the hold. The first press fires, then every other repeat from +// the eighth on. Returns false when the remote failed to read. +bool CJoystick::PollRemote(int port, float nSeconds) +{ + XINPUT_STATE_INTERNAL state; + if (XInputGetState(c_hDevices[port], (XINPUT_STATE *)&state) != ERROR_SUCCESS) + { + RemoteGone(port); return false; + } - for (int i = 0; i < 8; i += 1) + if (state.dwPacketNumber == m_joystate[port].dwPacketNumber) { - if ((pad1->bAnalogButtons[i] > XINPUT_ANALOGBUTTONTHRESHOLD) != - (pad2->bAnalogButtons[i] > XINPUT_ANALOGBUTTONTHRESHOLD)) - return false; + m_remoteIdleTime += nSeconds; + if (m_remoteIdleTime > 0.150) + m_remoteRepeatCount = 0; + return true; } - if (ConvertThumb(pad1->sThumbLX) != ConvertThumb(pad2->sThumbLX)) - return false; + ResetScreenSaver(); + m_remoteIdleTime = 0.0f; + m_joystate[port] = state; - if (ConvertThumb(pad1->sThumbLY) != ConvertThumb(pad2->sThumbLY)) - return false; + if (state.IrRemote.wKeyCode != m_joystate[port].IrRemote.wKeyCode || state.IrRemote.wTimeDelta > 120) + m_remoteRepeatCount = 1; + else + m_remoteRepeatCount++; - if (ConvertThumb(pad1->sThumbRX) != ConvertThumb(pad2->sThumbRX)) - return false; + bool bFire = m_remoteRepeatCount == 1 || (m_remoteRepeatCount > 7 && (m_remoteRepeatCount % 2) != 0); + if (!bFire) + return true; - if (ConvertThumb(pad1->sThumbRY) != ConvertThumb(pad2->sThumbRY)) - return false; + const REMOTE_KEY *pKey = FindRemoteKey(state.IrRemote.wKeyCode); + if (pKey == NULL) + return true; + m_LastActivePort = port; + CallFunction(pKey->szEvent, true); + if (pKey->szThenEvent != NULL) + CallFunction(pKey->szThenEvent, true); return true; } -struct REMOTE_CODE_TABLE +// A key press with its secret key letter (0 for none): the letter steps the +// sequence before the event, its result fires after. +void CJoystick::KeyEvent(TCHAR key, const TCHAR *szEvent, bool bDown) { - TCHAR *szFunction1; - TCHAR *szFunction2; - WORD wCode; -}; + int flags = 0; + if (bDown) + flags = CheckSecretKeySequence(key); + CallFunction(szEvent); + if (bDown) + ProcessSecretKeySequence(flags); +} -static const REMOTE_CODE_TABLE RemoteCodeTable[] = - { - {_T("OnPower"), NULL, 0xAD5}, - {_T("OnReverse"), NULL, 0xAE2}, - {_T("OnPlay"), NULL, 0xAEA}, - {_T("OnForward"), NULL, 0xAE3}, - {_T("OnSkipBack"), NULL, 0xADD}, - {_T("OnStop"), NULL, 0xAE0}, - {_T("OnPause"), NULL, 0xAE6}, - {_T("OnSkipForward"), NULL, 0xADF}, - {_T("OnGuide"), NULL, 0xAE5}, - {_T("OnInfo"), NULL, 0xAC3}, - {_T("OnMenu"), NULL, 0xAF7}, - {_T("OnBDown"), _T("OnBUp"), 0xAD8}, - {_T("OnMoveUp"), NULL, 0xAA6}, - {_T("OnMoveLeft"), NULL, 0xAA9}, - {_T("OnADown"), _T("OnAUp"), 0xA0B}, - {_T("OnMoveRight"), NULL, 0xAA8}, - {_T("OnMoveDown"), NULL, 0xAA7}, - {_T("On0"), NULL, 0xACF}, - {_T("On1"), NULL, 0xACE}, - {_T("On2"), NULL, 0xACD}, - {_T("On3"), NULL, 0xACC}, - {_T("On4"), NULL, 0xACB}, - {_T("On5"), NULL, 0xACA}, - {_T("On6"), NULL, 0xAC9}, - {_T("On7"), NULL, 0xAC8}, - {_T("On8"), NULL, 0xAC7}, - {_T("On9"), NULL, 0xAC6}, - {NULL, NULL, 0}}; - -static const REMOTE_CODE_TABLE *GetCodeFunction(WORD wCode) +// Held directions, 5960 @ 0x00041040: horizontal then vertical, at once, +// then after 0.3 s (0x0002c0b8), then every 0.12 s (0x0002c1f4). Coming to +// rest re-arms the first delay. Theseus's overlay takes them while it's +// capturing input. +void CJoystick::FireMoves(int port) { - const REMOTE_CODE_TABLE *pRemoteEntry = RemoteCodeTable; - while (pRemoteEntry->wCode != 0) + if (m_xaxis == 0.0f && m_yaxis == 0.0f) { - if (pRemoteEntry->wCode == wCode) - return pRemoteEntry; + m_nextRepeatTime[port] = 0.0f; + m_repeatInterval[port] = REPEAT_DELAY; + return; + } + + if (TheseusGetNow() < m_nextRepeatTime[port]) + return; + + if (m_xaxis != 0.0f) + { + bool bLeft = m_xaxis < 0.0f; + if (g_bOverlayInputCapture) + { + if (bLeft) + OverlayOnLeft(); + else + OverlayOnRight(); + } + else + { + KeyEvent(bLeft ? _T('L') : _T('R'), bLeft ? _T("OnMoveLeft") : _T("OnMoveRight"), true); + } + } - pRemoteEntry += 1; + if (m_yaxis != 0.0f) + { + bool bDown = m_yaxis < 0.0f; + if (g_bOverlayInputCapture) + { + if (bDown) + OverlayOnDown(); + else + OverlayOnUp(); + } + else + { + KeyEvent(bDown ? _T('D') : _T('U'), bDown ? _T("OnMoveDown") : _T("OnMoveUp"), true); + } } - return NULL; + m_nextRepeatTime[port] = TheseusGetNow() + m_repeatInterval[port]; + m_repeatInterval[port] = REPEAT_INTERVAL; } -void CJoystick::Advance(float nSeconds) +// Analog buttons A B X Y black white L R (5960 @ 0x00176640 / 0x00176620, +// letters "ABXYbwlr"), then digital: d-pad, Start and Back (raised as A and +// B), stick clicks (0x00176600 / 0x001765e0, letters @ 0x000259a0). +static const TCHAR *const s_analogDown[8] = { _T("OnADown"), _T("OnBDown"), _T("OnXDown"), _T("OnYDown"), _T("OnBlackDown"), _T("OnWhiteDown"), _T("OnLeftDown"), _T("OnRightDown") }; +static const TCHAR *const s_analogUp[8] = { _T("OnAUp"), _T("OnBUp"), _T("OnXUp"), _T("OnYUp"), _T("OnBlackUp"), _T("OnWhiteUp"), _T("OnLeftUp"), _T("OnRightUp") }; +static const TCHAR s_analogKeys[8] = { 'A', 'B', 'X', 'Y', 'b', 'w', 'l', 'r' }; +static const TCHAR *const s_digitalDown[8] = { _T("OnPressUp"), _T("OnPressDown"), _T("OnPressLeft"), _T("OnPressRight"), _T("OnADown"), _T("OnBDown"), _T("OnLeftThumbDown"), _T("OnRightThumbDown") }; +static const TCHAR *const s_digitalUp[8] = { _T("OnReleaseUp"), _T("OnReleaseDown"), _T("OnReleaseLeft"), _T("OnReleaseRight"), _T("OnAUp"), _T("OnBUp"), _T("OnLeftThumbUp"), _T("OnRightThumbUp") }; +static const TCHAR s_digitalKeys[8] = { 0, 0, 0, 0, 'S', 'P', 'Q', 'W' }; + +// One gamepad poll, following 5960's event order: wake the screen saver on +// a change (and only wake it), sticks with the d-pad standing in for a +// resting left stick, moves, analog buttons, digital buttons, OnReset for +// Start with A and B, then OnMoveCenter once the stick comes back. +void CJoystick::PollPad(int port) { - int k; - - CNode::Advance(nSeconds); - - if (!g_bInputEnable) + XINPUT_STATE_INTERNAL state; + if (XInputGetState(c_hDevices[port], (XINPUT_STATE *)&state) != ERROR_SUCCESS) return; - if (this != c_pBoundJoystick) - return; + const XINPUT_GAMEPAD &pad = state.Gamepad; + const XINPUT_GAMEPAD &was = m_joystate[port].Gamepad; - if (!m_removeRemoteCalled && m_timeRemoteRemoved != 0.0f && TheseusGetNow() > m_timeRemoteRemoved) + if (IsPadActive(&pad)) + m_LastActivePort = port; + + if (!SamePadInput(&pad, &was) && ResetScreenSaver()) { - TRACE(_T("Remote control was removed!\n")); - CallFunction(_T("OnRemoveRemote"), true); - m_removeRemoteCalled = true; + m_joystate[port] = state; + return; } - if (!CheckDevice()) - return; + bool bWasCentered = m_xaxis == 0.0f && m_yaxis == 0.0f; - if (m_needsInit) - { - for (int i = 0; i < 4; i += 1) - { - if (c_hDevices[i] != NULL) - XInputGetState(c_hDevices[i], (XINPUT_STATE *)&m_joystate[i]); - } + m_xaxis = StickValue(pad.sThumbLX); + m_yaxis = StickValue(pad.sThumbLY); + m_xaxis2 = StickValue(pad.sThumbRX); + m_yaxis2 = StickValue(pad.sThumbRY); - m_timeNextUpdate = TheseusGetNow(); - m_needsInit = false; + if (m_xaxis == 0.0f && m_yaxis == 0.0f) + { + if (pad.wButtons & XINPUT_GAMEPAD_DPAD_UP) + m_yaxis = 1.0f; + else if (pad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) + m_yaxis = -1.0f; + if (pad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) + m_xaxis = -1.0f; + else if (pad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) + m_xaxis = 1.0f; } - if (m_timeNextUpdate > TheseusGetNow()) - return; - - m_timeNextUpdate = TheseusGetNow() + 1.0f / m_frequency; + g_xaxis += m_xaxis; + g_yaxis += m_yaxis; - g_xaxis = g_yaxis = 0.0f; + FireMoves(port); - XINPUT_STATE_INTERNAL joystate; - for (int nJoypad = 0; nJoypad < 4; nJoypad += 1) + for (int i = 0; i < 8; i++) { - if (c_hDevices[nJoypad] == NULL) + bool bDown = pad.bAnalogButtons[i] > ANALOG_DOWN; + if (bDown == (was.bAnalogButtons[i] > ANALOG_DOWN)) continue; - if (c_devtype[nJoypad] == XDEVICE_TYPE_IR_REMOTE) + // Theseus: B with the left trigger held shows or hides the overlay, + // and the overlay takes A and B while it's capturing. + if (i == XINPUT_GAMEPAD_B && bDown && pad.bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER] > ANALOG_DOWN) { - XINPUT_STATE_INTERNAL state; - if (XInputGetState(c_hDevices[nJoypad], (XINPUT_STATE *)&state) != ERROR_SUCCESS) - { - TRACE(_T("XInputGetState for remote failed; close the device...\n")); - XInputClose(c_hDevices[nJoypad]); - c_hDevices[nJoypad] = NULL; - c_devtype[nJoypad] = NULL; - m_timeRemoteRemoved = TheseusGetNow() + 2.0f; - m_removeRemoteCalled = false; - break; - } - - // - // Now some logic to implement typomatic on the IR remote. - //----------------------------------------------------------------- - // It is important to understand how codes are sent: - // 1) When a button is depressed its code is sent in - // state.IrRemote.wKeyCode. - // 2) The time since the last code (as measured by the FW) - // is sent in c_state.IrRemote.wTimeDelta. - // 3) A button held depressed on the remote will repeat about - // every 65 ms. - // 4) Codes are not cached, so if we poll too slowly (less than - // once every 65 ms) we are likely to miss a code or see only - // its repeat. - // 5) If state.dwPacketNumber doesn't change we have not received - // a packet since the last poll. - //----------------------------------------------------------------- - // The desired behavior is: - // 1) If a key is pressed quickly and repeatedly, it should fire once - // per press. - // 2) If a key is held, there should be a short delay (~325 ms), followed - // by a more rapid repeat (~130 ms interval). This interval is partly - // chosen as it is easy. - // 3) When a key is released, it should stop repeating immediately. - //----------------------------------------------------------------- - // To achieve this we follow the following rules: - // 1) If we do not got a new packet in over 150 ms assume that the user - // has released the key. - // 2) Use the state.IrRemote.wTimeDelta to distinguish rapid press - // from repeats. In particular, if the state.IrRemote.wTimeDelta - // is less than 120 ms (and the key is the same as the last one) - // assume that it is repeat, otherwise, assume that it is a new - // button press. - // 3) Pass on the first press, then pause for a number of presses - // and pass every n'th press. The initiali pause and n are - // adjusted for a good feel. - - if (state.dwPacketNumber == m_joystate[nJoypad].dwPacketNumber) - { - m_remoteIdleTime += nSeconds; - if (m_remoteIdleTime > 0.150) - { - m_remoteRepeatCount = 0; - } - } - else - { - // - // Reset Screen Saver - // - - ResetScreenSaver(); - - // - // Reset repeat delay. - // - - m_remoteIdleTime = 0.0; - - // - // Copy the state. - // - - m_joystate[nJoypad] = state; - - // - // Check for new key press - // - if (state.IrRemote.wKeyCode != m_joystate[nJoypad].IrRemote.wKeyCode || state.IrRemote.wTimeDelta > 120) - { - m_remoteRepeatCount = 1; - } - else - // - // Otherwise, it is a repeat - // - { - m_remoteRepeatCount++; - } - // - // Let through repeated buttons based on their repeat count. - // Adjust for an immediate key (on 1) and then a pause with - // a reasonable repeat rate. - // - if ((1 == m_remoteRepeatCount) || - ((m_remoteRepeatCount > 7) && m_remoteRepeatCount % 2)) - { - const REMOTE_CODE_TABLE *pFunction = GetCodeFunction(state.IrRemote.wKeyCode); - if (pFunction != NULL) - { - m_LastActivePort = nJoypad; - TRACE(_T("IR Code: 0x%04x %s\n"), state.IrRemote.wKeyCode, pFunction->szFunction1); - - CallFunction(pFunction->szFunction1, true); - - if (pFunction->szFunction2 != NULL) - CallFunction(pFunction->szFunction2, true); - } - } - } - continue; // done with IR Remote, continue with next port + g_bShowOverlay = !g_bShowOverlay; + OutputDebugString(g_bShowOverlay ? L"[Overlay] Toggled ON\n" : L"[Overlay] Toggled OFF\n"); } - DWORD dwError = XInputGetState(c_hDevices[nJoypad], (XINPUT_STATE *)&joystate); - - if (dwError != ERROR_SUCCESS) + if (g_bOverlayInputCapture) { - // NOTE: We catch device removal above... - TRACE(_T("\001XInputGetState returned %d (device %d)\n"), dwError, nJoypad); - ZeroMemory(&joystate, sizeof(joystate)); + if (bDown && i == XINPUT_GAMEPAD_A) + OverlayOnA(); + if (bDown && i == XINPUT_GAMEPAD_B) + OverlayOnB(); continue; - // return; } - if (IsPadActive(&joystate.Gamepad)) - m_LastActivePort = nJoypad; - - if (!EqualGamepads(&joystate.Gamepad, &m_joystate[nJoypad].Gamepad) /*memcmp(&joystate.Gamepad, &m_joystate[nJoypad].Gamepad, sizeof (XINPUT_GAMEPAD)) != 0*/) - { - if (ResetScreenSaver()) - { - // Screen saver was active, so ignore this change... - m_joystate[nJoypad] = joystate; - continue; - } - } + KeyEvent(s_analogKeys[i], bDown ? s_analogDown[i] : s_analogUp[i], bDown); + } - bool bWasCentered = m_xaxis == 0.0f && m_yaxis == 0.0f; + for (int i = 0; i < 8; i++) + { + WORD bit = (WORD)(1 << i); + bool bDown = (pad.wButtons & bit) != 0; + if (bDown == ((was.wButtons & bit) != 0)) + continue; + KeyEvent(s_digitalKeys[i], bDown ? s_digitalDown[i] : s_digitalUp[i], bDown); + } - m_xaxis = ConvertThumb(joystate.Gamepad.sThumbLX); - m_yaxis = ConvertThumb(joystate.Gamepad.sThumbLY); + if ((pad.wButtons & XINPUT_GAMEPAD_START) && + pad.bAnalogButtons[XINPUT_GAMEPAD_A] > ANALOG_DOWN && + pad.bAnalogButtons[XINPUT_GAMEPAD_B] > ANALOG_DOWN) + CallFunction(_T("OnReset")); - m_xaxis2 = ConvertThumb(joystate.Gamepad.sThumbRX); - m_yaxis2 = ConvertThumb(joystate.Gamepad.sThumbRY); + if (!bWasCentered && m_xaxis == 0.0f && m_yaxis == 0.0f) + CallFunction(_T("OnMoveCenter")); - // Make the DPad act like the left joystick; maybe I'll be more clever later... - if (m_xaxis == 0 && m_yaxis == 0) - { - if (joystate.Gamepad.wButtons & 1) - m_yaxis = 1.0f; - else if (joystate.Gamepad.wButtons & 2) - m_yaxis = -1.0f; - if (joystate.Gamepad.wButtons & 4) - m_xaxis = -1.0f; - else if (joystate.Gamepad.wButtons & 8) - m_xaxis = 1.0f; - } + m_joystate[port] = state; +} - g_xaxis += m_xaxis; - g_yaxis += m_yaxis; +// CJoystick::Advance(dt) +// Reconstructed from 5960 retail XBE @ 0x00041040. Only with input enabled +// and only the bound joystick. A remote gone longer than its grace raises +// OnRemoveRemote once; devices are checked; the first poll just takes a +// reading; then at most `frequency` times a second every port is read. A +// remote that fails to read ends this poll. See docs/decomp/Input.md. +void CJoystick::Advance(float nSeconds) +{ + CNode::Advance(nSeconds); - { - if (m_xaxis == 0 && m_yaxis == 0) - { - m_nextRepeatTime[nJoypad] = 0; - m_repeatInterval[nJoypad] = REPEAT_DELAY; // delay to first repeat - } - else if (TheseusGetNow() >= m_nextRepeatTime[nJoypad]) - { - if (m_xaxis != 0) - { - if (g_bOverlayInputCapture) - { - if (m_xaxis < 0.0f) - OverlayOnLeft(); - else - OverlayOnRight(); - } - else - { - k = CheckSecretKeySequence(m_xaxis < 0.0f ? _T('L') : _T('R')); - CallFunction(m_xaxis < 0.0f ? _T("OnMoveLeft") : _T("OnMoveRight")); - ProcessSecretKeySequence(k); - } - } - - if (m_yaxis != 0) - { - if (g_bOverlayInputCapture) - { - if (m_yaxis < 0.0f) - OverlayOnDown(); - else - OverlayOnUp(); - } - else - { - k = CheckSecretKeySequence(m_yaxis < 0.0f ? _T('D') : _T('U')); - CallFunction(m_yaxis < 0.0f ? _T("OnMoveDown") : _T("OnMoveUp")); - ProcessSecretKeySequence(k); - } - } - - m_nextRepeatTime[nJoypad] = TheseusGetNow() + m_repeatInterval[nJoypad]; - m_repeatInterval[nJoypad] = REPEAT_INTERVAL; // delay for all but first repeat - } - } + if (!g_bInputEnable || this != c_pBoundJoystick) + return; - int i; - for (i = 0; i < 8; i += 1) - { - bool bIsDown = joystate.Gamepad.bAnalogButtons[i] > XINPUT_ANALOGBUTTONTHRESHOLD; - bool bWasDown = m_joystate[nJoypad].Gamepad.bAnalogButtons[i] > XINPUT_ANALOGBUTTONTHRESHOLD; + if (!m_removeRemoteCalled && m_timeRemoteRemoved != 0.0f && TheseusGetNow() > m_timeRemoteRemoved) + { + CallFunction(_T("OnRemoveRemote"), true); + m_removeRemoteCalled = true; + } - if (bIsDown != bWasDown) - { - // Toggle overlay with L trigger + B - if (i == 1 && bIsDown) // B button pressed - { - if (joystate.Gamepad.bAnalogButtons[6] > XINPUT_ANALOGBUTTONTHRESHOLD) // L Trigger held - { - g_bShowOverlay = !g_bShowOverlay; - OutputDebugString(g_bShowOverlay ? L"[Overlay] Toggled ON\n" : L"[Overlay] Toggled OFF\n"); - } - } - - static const TCHAR *rgszDown[] = - { - _T("OnADown"), - _T("OnBDown"), - _T("OnXDown"), - _T("OnYDown"), - _T("OnBlackDown"), - _T("OnWhiteDown"), - _T("OnLeftDown"), - _T("OnRightDown")}; - - static const TCHAR *rgszUp[] = - { - _T("OnAUp"), - _T("OnBUp"), - _T("OnXUp"), - _T("OnYUp"), - _T("OnBlackUp"), - _T("OnWhiteUp"), - _T("OnLeftUp"), - _T("OnRightUp")}; - - static const TCHAR rgszSecretKey[] = - { - _T('A'), - _T('B'), - _T('X'), - _T('Y'), - _T('b'), // Black - _T('w'), // White - _T('l'), // Left-trigger - _T('r') // Right-trigger - }; - - // Overlay input routing - if (g_bOverlayInputCapture) - { - if (bIsDown) - { - if (i == 0) OverlayOnA(); - if (i == 1) OverlayOnB(); - } - } - else - { - if (bIsDown) - k = CheckSecretKeySequence(rgszSecretKey[i]); - - CallFunction(bIsDown ? rgszDown[i] : rgszUp[i]); - - if (bIsDown) - ProcessSecretKeySequence(k); - } - -#if defined(_DEBUG) && defined(_CYCLE_LANGUAGE) - if (i == 7 && bIsDown && m_joystate[nJoypad].Gamepad.bAnalogButtons[6] > XINPUT_ANALOGBUTTONTHRESHOLD) - CycleLanguage(); -#endif - -#ifdef COOL_XDASH - if (m_joystate[nJoypad].Gamepad.bAnalogButtons[6] > XINPUT_ANALOGBUTTONTHRESHOLD && - m_joystate[nJoypad].Gamepad.bAnalogButtons[7] > XINPUT_ANALOGBUTTONTHRESHOLD) - { - if (m_joystate[nJoypad].Gamepad.bAnalogButtons[4] > XINPUT_ANALOGBUTTONTHRESHOLD) - { - XWriteTitleInfoAndReboot("xshell.xbe", "\\Device\\Harddisk0\\Partition2", ~0, 0, NULL); - } - else if (m_joystate[nJoypad].Gamepad.bAnalogButtons[5] > XINPUT_ANALOGBUTTONTHRESHOLD) - { - XWriteTitleInfoAndReboot("default.xbe", "\\Device\\Harddisk0\\Partition1\\Devkit\\Gripper", ~0, 0, NULL); - } - } -#endif - } - } + if (!CheckDevice()) + return; -#ifdef _DEBUG - g_bWireframe = joystate.Gamepad.bAnalogButtons[4] > XINPUT_ANALOGBUTTONTHRESHOLD; -#endif + if (m_needsInit) + { + ReadAllDevices(); + m_timeNextUpdate = TheseusGetNow(); + m_needsInit = false; + } - WORD bit = 1; - for (i = 0; i < 8; i += 1, bit <<= 1) - { - if ((joystate.Gamepad.wButtons & bit) != (m_joystate[nJoypad].Gamepad.wButtons & bit)) - { - static const TCHAR *rgszDown[] = - { - _T("OnPressUp"), - _T("OnPressDown"), - _T("OnPressLeft"), - _T("OnPressRight"), -#if 1 // Make Start/Back the same as A/B; maybe I'll be more clever later... - _T("OnADown"), - _T("OnBDown"), -#else - _T("OnStartDown"), - _T("OnBackDown"), -#endif - _T("OnLeftThumbDown"), - _T("OnRightThumbDown")}; - - static const TCHAR *rgszUp[] = - { - _T("OnReleaseUp"), - _T("OnReleaseDown"), - _T("OnReleaseLeft"), - _T("OnReleaseRight"), -#if 1 // Make Start/Back the same as A/B; maybe I'll be more clever later... - _T("OnAUp"), - _T("OnBUp"), -#else - _T("OnStartUp"), - _T("OnBackUp"), -#endif - _T("OnLeftThumbUp"), - _T("OnRightThumbUp")}; - - static const TCHAR rgszSecretKey[] = - { - _T('\0'), - _T('\0'), - _T('\0'), - _T('\0'), - _T('S'), // Start - _T('P'), // Back - _T('Q'), // Left-thumb - _T('W') // Right-thumb - }; - - if (joystate.Gamepad.wButtons & bit) - k = CheckSecretKeySequence(rgszSecretKey[i]); - CallFunction((joystate.Gamepad.wButtons & bit) ? rgszDown[i] : rgszUp[i]); - if (joystate.Gamepad.wButtons & bit) - ProcessSecretKeySequence(k); - } - } + if (TheseusGetNow() < m_timeNextUpdate) + return; + m_timeNextUpdate = TheseusGetNow() + 1.0f / m_frequency; - if ((joystate.Gamepad.wButtons & XINPUT_GAMEPAD_START) != 0 && - joystate.Gamepad.bAnalogButtons[XINPUT_GAMEPAD_A] > XINPUT_ANALOGBUTTONTHRESHOLD && - joystate.Gamepad.bAnalogButtons[XINPUT_GAMEPAD_B] > XINPUT_ANALOGBUTTONTHRESHOLD) - CallFunction(_T("OnReset")); + g_xaxis = g_yaxis = 0.0f; - bool bIsCentered = m_xaxis == 0.0f && m_yaxis == 0.0f; + for (int port = 0; port < 4; port++) + { + if (c_hDevices[port] == NULL) + continue; - if (!bWasCentered && bIsCentered) - CallFunction(_T("OnMoveCenter")); + if (c_devtype[port] == XDEVICE_TYPE_IR_REMOTE) + { + if (!PollRemote(port, nSeconds)) + break; + continue; + } - m_joystate[nJoypad] = joystate; + PollPad(port); } } +// CJoystick::CheckSecretKeySequence(letter) +// Reconstructed from 5960 retail XBE @ 0x00041790. With a key set and +// enabled: the wrong letter ends a sequence in progress (KS_END) and starts +// over; the right one begins it (KS_BEGIN on the first letter) and the last +// one completes it (KS_VERIFIED | KS_END). int CJoystick::CheckSecretKeySequence(TCHAR key) { - int nReturn = 0; - - if (!m_enableSecretKey || m_secretKeyLength == 0 || !m_secretKey) - { - ASSERT(m_secretKeyCurrentIndex == 0); + if (!m_enableSecretKey || m_secretKeyLength == 0 || m_secretKey == NULL) return 0; - } - - ASSERT(m_secretKeyCurrentIndex < m_secretKeyLength); if (key != m_secretKey[m_secretKeyCurrentIndex]) { - if (m_secretKeyCurrentIndex) - { - nReturn |= KS_END; - } + int flags = m_secretKeyCurrentIndex != 0 ? KS_END : 0; m_secretKeyCurrentIndex = 0; - return nReturn; + return flags; } - if (m_secretKeyCurrentIndex == 0) + int flags = m_secretKeyCurrentIndex == 0 ? KS_BEGIN : 0; + m_secretKeyCurrentIndex++; + if (m_secretKeyCurrentIndex == m_secretKeyLength) { - nReturn |= KS_BEGIN; - } - - if (++m_secretKeyCurrentIndex == m_secretKeyLength) - { - nReturn |= KS_END; - nReturn |= KS_VERIFIED; m_secretKeyCurrentIndex = 0; + flags |= KS_VERIFIED | KS_END; } - - return nReturn; + return flags; } +// CJoystick::ProcessSecretKeySequence(flags) +// Reconstructed from 5960 retail XBE @ 0x00041800: OnKeyVerificationEnter, +// OnKeyVerificationExit, OnKeyVerified, in that order, for the flags set. void CJoystick::ProcessSecretKeySequence(int flags) { if (flags & KS_BEGIN) CallFunction(_T("OnKeyVerificationEnter")); - if (flags & KS_END) CallFunction(_T("OnKeyVerificationExit")); - if (flags & KS_VERIFIED) CallFunction(_T("OnKeyVerified")); -} \ No newline at end of file +} From 0699434f7af878c8d8271ea628efa9c5fa2195b1 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:23 -0500 Subject: [PATCH 07/13] Rebuilt the Xbox app shell from the binary Launch data, the startup render states, Draw, Advance, cleanup, the memory unit format and the startup file are written fresh from 0x2c520..0x2dd20. Boot timing, Config.ini video modes, skins, widgets and the panic screen stay Theseus's. Draw makes the same 124,612 calls as before over 3,000 random frames. --- docs/decomp/AppShell.md | 60 ++++ docs/decomp/README.md | 9 +- theseus/xbox/main.cpp | 616 ++++++++++++++++++++-------------------- 3 files changed, 380 insertions(+), 305 deletions(-) create mode 100644 docs/decomp/AppShell.md diff --git a/docs/decomp/AppShell.md b/docs/decomp/AppShell.md new file mode 100644 index 0000000..c3afe11 --- /dev/null +++ b/docs/decomp/AppShell.md @@ -0,0 +1,60 @@ +# App Shell + +Start up and the frame loop of the 5960 retail binary. The app object lives at `0x0017e7a0`. + +## Functions + +| Address | Name | What it does | +|---------|------|--------------| +| 0x0002c520 | Alert | Formats into a 512 character buffer; retail drops the text | +| 0x0002c570 | app constructor | Frame clock from `GetTickCount`, root class, launch data (below) | +| 0x0002c660 | XboxInitRenderState | Startup render states one by one, motion blur factor 1 | +| 0x0002ccf0 | InitD3D | Present parameters by AV pack, see the video notes; creates the device | +| 0x0002d0e0 | Draw | Below | +| 0x0002d7e0 | InitApp | Below | +| 0x0002d930 | CleanupApp | XOnline cleanup, matrix stack, scene, class, `Class_Exit`, XIP sections, `Text_Exit`, DirectSound, app dir | +| 0x0002da00 | XApp | `InitApp`, then forever: clock, keyboard poll, camera, lerpers, scene advance, deferred deletes, `Draw` | +| 0x0002dbc0 | GetStartupClassFile | `y:\default.xap`, current dir `y:/default.xap` | +| 0x0002dc80 | main | Crash handler unless the hardware is a debug kit, then `XApp` | +| 0x0002dcc0 | XboxFormatMemoryUnit | Device object into a 32 byte name, `XapiFormatFATVolume`, close | +| 0x0002dd20 | Xbox_Init | Below | +| 0x00062750 | DSound_Init | Below | + +## Launch data + +When `*LaunchDataPage` is set and its type is 1 (`LDT_LAUNCH_DASHBOARD`), the 3 KB of launch data +are copied into the app (title id, reason, context, two parameters), the page pointer is cleared and +the page freed with `MmFreeContiguousMemory`. + +## InitApp and Xbox_Init + +``` +_set_new_handler(...); open the CD service; g_BootType = GetDiscType(); +Xbox_Init(): + PAL-I or PAL-M: clear the 480p video flag + XSetFileCacheSize(1 MB); drive links; xboxdashdata. or the default data dir + create C:\TDATA\fffe0000\music; T:\NoisyCamera; keyboard languages + XInitDevices(0, 0); wait while XGetDeviceEnumerationStatus() is busy; open keyboards + delete t:\tempcda.cda and t:\tempwma.wma; remember the game region +srand(GetTickCount()); version lock with the online dash; XOnline start up (may reboot into it) +InitD3D(); LoadXIP; Class_Init; title root; Material_Init; +load y:\default.xap, create it, D3DXCreateMatrixStack, call its initialize +``` + +DirectSound is not touched here. `DSound_Init` runs the first time a sound buffer is asked for: + +``` +if (g_BootType == DISC_VIDEO) return false; +speaker override = (XGetAudioFlags() low word == mono); +DirectSoundCreate(0, &g_pDirectSound, 0); +SetMixBinHeadroom(bin, 0) for all 31 mix bins; +CreateThread(worker): while (g_pDirectSound) { DirectSoundDoWork(); Sleep(100); } +``` + +## Draw + +Projection when dirty (field of view, aspect, near and far from the bound viewpoint and navigation +info). The sky color (or dark blue `0xff00004c`) clears the frame, and a background's backdrop +draws over it; while a transition blurs (factor under 1, sky black, no backdrop, past the first two +frames) a black quad with that alpha fades the last frame instead. A default material (grey, made +once), the scene from an identity world, then Present. diff --git a/docs/decomp/README.md b/docs/decomp/README.md index 8d72f2e..e3d7924 100644 --- a/docs/decomp/README.md +++ b/docs/decomp/README.md @@ -433,13 +433,14 @@ The seed and first expansion cover the application shell, script VM, scene graph | Materials | [Materials.md](Materials.md) | 25 functions | | File Operations | [FileOps.md](FileOps.md) | 7 functions | | File Utilities | [FileUtil.md](FileUtil.md) | 10 functions: paths, URL resolving, block counts | -| Disc | (no doc yet, narrative TODO) | 1 function | +| Disc | [Disc.md](Disc.md) | 8 functions | | HUD & Picture | [HudNode.md](HudNode.md) | 9 functions | | Keyboard | [Keyboard.md](Keyboard.md) | 22 functions | | Locale | [Locale.md](Locale.md) | 20 functions: translation table, Translator node, date/time/number formats, time zones | -| NtIoSvc | [NtIoSvc.md](NtIoSvc.md) | 1 function | +| NtIoSvc | [NtIoSvc.md](NtIoSvc.md) | 5 functions | | Scene Groups | [SceneGroups.md](SceneGroups.md) | 6 functions | | Settings | [Settings.md](Settings.md) | 28 functions: settings file, Settings and ScreenSaver nodes | +| Config | [Config.md](Config.md) | 50 functions | | Screen & Recovery | [Screen.md](Screen.md) | 9 functions | | Shape Render | [ShapeRender.md](ShapeRender.md) | not yet started | | Text | [Text.md](Text.md) | 2 functions | @@ -449,10 +450,10 @@ The seed and first expansion cover the application shell, script VM, scene graph | Save Games | (no doc yet, narrative TODO) | 29 functions | | Live Accounts | (no doc yet, narrative TODO) | 13 verified Theseus mappings + 2 binary-only anchors (bulk delete, single-user delete) | | Input | [Input.md](Input.md) | 9 functions | -| Memory Monitor | (no doc yet, narrative TODO) | 12 functions | +| Memory Monitor | [MemoryMonitor.md](MemoryMonitor.md) | 22 functions | | Music Collection | (no doc yet, narrative TODO) | 5 verified Theseus mappings (FormatSoundtrackSongTime, GetUpdateString + 3 stubs: AddSoundtrack, ClearCopyList, DeleteSoundtrack) + 3 binary-only anchors (global ::DeleteSoundtrack, ::DeleteAllSoundtracks, ThreadProc); more labeling pending | | Render | (no doc yet, narrative TODO) | 1 function | -| App Shell | (no doc yet, narrative TODO) | 9 functions | +| App Shell | [AppShell.md](AppShell.md) | 13 functions | | Asset Loader | [AssetLoader.md](AssetLoader.md) | 30 functions | | DVD Playback | (reference-only, no doc) | 1 function | | Original WMA Pump | (reference-only, folded into AudioSystem.md) | 1 function | diff --git a/theseus/xbox/main.cpp b/theseus/xbox/main.cpp index 4dd137b..e9bf2c9 100644 --- a/theseus/xbox/main.cpp +++ b/theseus/xbox/main.cpp @@ -1,7 +1,9 @@ -// main.cpp: Xbox entry point. Sets up D3D, audio, network, the scene -// graph, and the main loop; defines the dashboard globals declared in -// theseus.h. Owns the boot path, the Advance / Draw cycle, and the -// recovery / panic hook. Decompiled from the 5960 retail XBE. +// main.cpp: the Xbox entry point, boot path and frame loop, plus the +// dashboard globals theseus.h declares. Launch data, render states, Draw, +// Advance, cleanup and the memory unit format are rebuilt from the 5960 +// retail XBE (0x2c520..0x2dd20); see docs/decomp/AppShell.md. Boot timing, +// skins, Config.ini video modes, widgets, FTP, Discord and the panic +// screen are Theseus's. #include "std.h" #include @@ -214,32 +216,38 @@ D3DXMATRIX g_matIdentity( UINT g_uMesh; UINT g_uMeshRef; +// Alert(format, ...) +// 5960 @ 0x0002c520 formats into a 512 character buffer and drops it +// (retail has no debug output). Theseus sends the text to Trace. extern "C" void Alert(const TCHAR *szMsg, ...) { + TCHAR szText[512]; va_list args; va_start(args, szMsg); - - TCHAR szBuffer[512]; - _vsntprintf(szBuffer, countof(szBuffer), szMsg, args); - Trace(_T("\007%s\n"), szBuffer); + _vsntprintf(szText, countof(szText), szMsg, args); va_end(args); + Trace(_T("\007%s\n"), szText); } #ifdef _UNICODE +// Widen or narrow at most nMaxChars characters, stopping after the +// terminator. The narrow side keeps only each character's low byte. void Unicode(TCHAR *wsz, const char *sz, int nMaxChars) { - while (nMaxChars-- > 0) + for (int i = 0; i < nMaxChars; i++) { - if ((*wsz++ = (unsigned char)*sz++) == 0) + wsz[i] = (unsigned char)sz[i]; + if (sz[i] == 0) return; } } void Ansi(char *sz, const TCHAR *wsz, int nMaxChars) { - while (nMaxChars-- > 0) + for (int i = 0; i < nMaxChars; i++) { - if ((*sz++ = (char)*wsz++) == 0) + sz[i] = (char)wsz[i]; + if (sz[i] == 0) return; } } @@ -247,6 +255,12 @@ void Ansi(char *sz, const TCHAR *wsz, int nMaxChars) extern "C" PLAUNCH_DATA_PAGE *LaunchDataPage; +// Theseus_Init() +// Reconstructed from the 5960 app constructor @ 0x0002c570: starts the +// frame clock from GetTickCount and makes the root class. When the kernel +// handed over launch data meant for the dash (LDT_LAUNCH_DASHBOARD), the +// title id, reason, context and both parameters are kept and the page is +// freed so nothing reads it twice. Then the main thread id is noted. static void Theseus_Init() { g_dwStartTick = g_dwFrameTick = GetTickCount(); @@ -254,22 +268,19 @@ static void Theseus_Init() g_pClass = new CClass; - // Retrieve the launch data, if any - if (*LaunchDataPage && (*LaunchDataPage)->Header.dwLaunchDataType == LDT_LAUNCH_DASHBOARD) + PLAUNCH_DATA_PAGE pPage = *LaunchDataPage; + if (pPage != NULL && pPage->Header.dwLaunchDataType == LDT_LAUNCH_DASHBOARD) { - PLD_LAUNCH_DASHBOARD pLaunchDashboard = - (PLD_LAUNCH_DASHBOARD)((*LaunchDataPage)->LaunchData); - + PLD_LAUNCH_DASHBOARD pDash = (PLD_LAUNCH_DASHBOARD)pPage->LaunchData; g_bHasLaunchData = true; - g_dwTitleID = (*LaunchDataPage)->Header.dwTitleId; - g_dwLaunchReason = pLaunchDashboard->dwReason; - g_dwLaunchContext = pLaunchDashboard->dwContext; - g_dwLaunchParameter1 = pLaunchDashboard->dwParameter1; - g_dwLaunchParameter2 = pLaunchDashboard->dwParameter2; + g_dwTitleID = pPage->Header.dwTitleId; + g_dwLaunchReason = pDash->dwReason; + g_dwLaunchContext = pDash->dwContext; + g_dwLaunchParameter1 = pDash->dwParameter1; + g_dwLaunchParameter2 = pDash->dwParameter2; - PLAUNCH_DATA_PAGE pTemp = *LaunchDataPage; *LaunchDataPage = NULL; - MmFreeContiguousMemory(pTemp); + MmFreeContiguousMemory(pPage); } g_dwMainThreadId = GetCurrentThreadId(); @@ -305,68 +316,87 @@ DWORD theseus_rgdwRenderStateCache[256]; bool theseus_rgbRenderStateCache[256]; float g_transitionMotionBlur; +// XboxInitRenderState() +// Reconstructed from 5960 retail XBE @ 0x0002c660: sets the startup render +// states one at a time (z from the app's z-buffer flag, solid Gouraud fill, +// z writes, no alpha test, one/zero blend, CCW culling, LESSEQUAL), then +// the motion blur factor to 1. Theseus sets the full list below, in order. void XboxInitRenderState() { - float fZero = 0.0f; - float fOne = 1.0f; - - TheseusSetRenderState(D3DRS_ZENABLE, TheseusGetZBuffer() ? 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, *(LPDWORD)&fOne); - TheseusSetRenderState(D3DRS_EDGEANTIALIAS, FALSE); - 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, *(LPDWORD)&fOne); - TheseusSetRenderState(D3DRS_POINTSIZE_MIN, *(LPDWORD)&fOne); - TheseusSetRenderState(D3DRS_POINTSPRITEENABLE, FALSE); - TheseusSetRenderState(D3DRS_POINTSCALEENABLE, FALSE); - TheseusSetRenderState(D3DRS_POINTSCALE_A, *(LPDWORD)&fOne); - TheseusSetRenderState(D3DRS_POINTSCALE_B, *(LPDWORD)&fZero); - TheseusSetRenderState(D3DRS_POINTSCALE_C, *(LPDWORD)&fZero); - TheseusSetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE); - 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 DWORD *)&fZero; + const DWORD dwOne = *(const DWORD *)&fOne; + + const struct { D3DRENDERSTATETYPE state; DWORD value; } states[] = + { + { D3DRS_ZENABLE, TheseusGetZBuffer() ? 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_EDGEANTIALIAS, FALSE }, + { 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_MULTISAMPLEANTIALIAS, TRUE }, + { 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; } +// InitD3D() +// 5960 @ 0x0002ccf0 sizes the back buffer by AV pack (640 or 720 wide, 576 +// high on PAL-I), 4x gaussian supersampling, vsync, interlaced unless an +// HDTV pack allows 480p, and creates the device. Theseus reads its modes +// from Q:\System\Config.ini, defaults to no multisampling and immediate +// present, and adds its widgets and overlay once the device exists. bool InitD3D() { #ifdef THESEUS_PUSHBUFFER_KB @@ -555,12 +585,7 @@ bool InitD3D() void ReleaseD3D() { RELEASENULL(g_worldStack); - - if (g_pD3D != NULL) - { - g_pD3D->Release(); - g_pD3D = NULL; - } + RELEASENULL(g_pD3D); } struct COLORVERTEX @@ -569,241 +594,203 @@ struct COLORVERTEX DWORD color; }; -void Draw() +// Rebuild the projection when something marked it dirty: the 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); + if (!g_bProjectionDirty) + return; + g_bProjectionDirty = false; - // Setup projection transform... - if (g_bProjectionDirty) - { - g_bProjectionDirty = false; + float fieldOfView = D3DX_PI / 2.0f; + float nNear = 0.1f; + float nFar = 1000.0f; - float nNear = 0.1f; - float nFar = 1000.0f; - float fieldOfView = D3DX_PI / 2.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_pViewpoint != NULL) + fieldOfView = g_pViewpoint->m_fieldOfView; - if (g_pNavigationInfo != NULL) - { - nNear = g_pNavigationInfo->m_avatarSize.x / 2.0f; - if (g_pNavigationInfo->m_visibilityLimit != 0.0f) - nFar = g_pNavigationInfo->m_visibilityLimit; - } + 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), (BYTE **)&verts, 0)); + float halfW = (float)TheseusGetViewWidth() / 2.0f; + float halfH = (float)TheseusGetViewHeight() / 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(); - - TheseusSetRenderState(D3DRS_FILLMODE, g_bWireframe ? D3DFILL_WIREFRAME : D3DFILL_SOLID); + D3DXMATRIX matOrtho, matSavedProjection, matSavedWorld, matSavedView; + TheseusGetTransform(D3DTS_PROJECTION, &matSavedProjection); + TheseusGetTransform(D3DTS_WORLD, &matSavedWorld); + TheseusGetTransform(D3DTS_VIEW, &matSavedView); + + D3DXMatrixOrthoLH(&matOrtho, TheseusGetViewWidth(), TheseusGetViewHeight(), -10000.0f, 10000.0f); + TheseusSetTransform(D3DTS_PROJECTION, &matOrtho); + 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); - const float blurAlpha = g_transitionMotionBlur; // bigger number -> less blur + TheseusSetStreamSource(0, s_pQuad, sizeof(COLORVERTEX)); + TheseusSetVertexShader(D3DFVF_XYZ | D3DFVF_DIFFUSE); + VERIFYHR(TheseusGetD3DDev()->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2)); - 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); // NOTE: Clears back and Z buffers (if Z buffer is enabled) +// 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 = { 0.0f, 0.0f, 0.0f, 0.0f }; - if (bBackdrop) - g_pBackground->RenderBackdrop(); - } - else + if (g_pNavigationInfo == NULL || g_pNavigationInfo->m_headlight) { - 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), (BYTE **)&verts, 0)); - - verts[0].dvX = (float)TheseusGetViewWidth() / 2.0f; - verts[0].dvY = -(float)TheseusGetViewHeight() / 2.0f; - verts[0].dvZ = 0.0f; - verts[0].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); - - verts[1].dvX = -(float)TheseusGetViewWidth() / 2.0f; - verts[1].dvY = -(float)TheseusGetViewHeight() / 2.0f; - verts[1].dvZ = 0.0f; - verts[1].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); - - verts[2].dvX = (float)TheseusGetViewWidth() / 2.0f; - verts[2].dvY = (float)TheseusGetViewHeight() / 2.0f; - verts[2].dvZ = 0.0f; - verts[2].color = D3DCOLOR_COLORVALUE(0.0f, 0.0f, 0.0f, blurAlpha); - - verts[3].dvX = -(float)TheseusGetViewWidth() / 2.0f; - verts[3].dvY = (float)TheseusGetViewHeight() / 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; + ZeroMemory(&light, 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, TheseusGetViewWidth(), TheseusGetViewHeight(), -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; - ZeroMemory(&d3dLight, 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, created once), +// the scene drawn from an identity world, and Present. Theseus adds the +// lights, wireframe, its frame profiler, widgets and the overlay. +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; } + 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 = { 0.5f, 0.5f, 0.5f, 1.0f }; + s_material.Diffuse = s_material.Ambient = s_material.Specular = s_material.Emissive = grey; + s_material.Power = 0.0f; } + TheseusSetMaterial(&s_material); Frame_PhaseEnd(FP_SCENE_SETUP); - // Draw the world... + Frame_PhaseBegin(FP_SCENE_TREE); - { - TheseusPushWorld(); - TheseusIdentityWorld(); - TheseusUpdateWorld(); - g_pObject->Render(); - TheseusPopWorld(); - } + TheseusPushWorld(); + TheseusIdentityWorld(); + TheseusUpdateWorld(); + g_pObject->Render(); + TheseusPopWorld(); Frame_PhaseEnd(FP_SCENE_TREE); Frame_PhaseBegin(FP_SCENE_END); TheseusEndScene(); Frame_PhaseEnd(FP_SCENE_END); + Frame_PhaseBegin(FP_WIDGETS); TheseusSetRenderState(D3DRS_SWATHWIDTH, D3DSWATH_OFF); Frame_PhaseBegin(FP_WIDGET_TICK); @@ -811,10 +798,12 @@ void Draw() Frame_PhaseEnd(FP_WIDGET_TICK); DrawWidgets(); Frame_PhaseEnd(FP_WIDGETS); + Frame_PhaseBegin(FP_OVERLAY); UpdateCubeOverlay(); DrawCubeOverlay(); Frame_PhaseEnd(FP_OVERLAY); + Frame_PhaseBegin(FP_PRESENT); TheseusPresent(); Frame_PhaseEnd(FP_PRESENT); @@ -833,20 +822,22 @@ static char szConfigPath[255]; #define ARRAYSIZE(a) (sizeof(a) / sizeof((a)[0])) #endif +// XboxFormatMemoryUnit(port, slot) +// Reconstructed from 5960 retail XBE @ 0x0002dcc0: create the unit's device +// object (its name in a 32 byte ANSI buffer), format it as FAT, close the +// object. Fails only if the device object can't be made. bool XboxFormatMemoryUnit(UINT nDevicePort, UINT nMemoryUnit) { - ANSI_STRING st; - char pszMU[MAX_MUNAME]; - st.Length = 0; - st.MaximumLength = sizeof(pszMU) - 1; - st.Buffer = pszMU; + char szDevice[MAX_MUNAME]; + ANSI_STRING device; + device.Length = 0; + device.MaximumLength = sizeof(szDevice) - 1; + device.Buffer = szDevice; - if (MU_CreateDeviceObject(nDevicePort, nMemoryUnit, &st) != NO_ERROR) + if (MU_CreateDeviceObject(nDevicePort, nMemoryUnit, &device) != NO_ERROR) return false; - if (!XapiFormatFATVolume(&st)) - TRACE(_T("XApiFormatFATVolume failed: %d\n"), GetLastError()); - + XapiFormatFATVolume(&device); MU_CloseDeviceObject(nDevicePort, nMemoryUnit); return true; } @@ -974,6 +965,12 @@ static void InitDiscord() SendDiscordRelayFromConfig(titleIdHex); } +// Xbox_Init() +// 5960 @ 0x0002dd20 clears 480p on PAL, sets a 1 MB file cache, links its +// drives, makes C:\TDATA\fffe0000\music, waits for device enumeration and +// clears the temp audio files. Theseus links its own drive set (Q: is its +// data dir, F: to N: the extra partitions), uses a 16 MB cache, and brings +// up the skin, the network and Discord here. static void Xbox_Init() { XI_GetProgramPath(szSystemPath); @@ -1060,6 +1057,12 @@ static void Xbox_Init() +// InitApp() +// 5960 @ 0x0002d7e0: CD-ROM and disc type, Xbox_Init, version lock and the +// online redirect, InitD3D, LoadXIP, Class_Init, materials, then load and +// create the startup scene and call its initialize. Theseus keeps that +// order without the online steps, opens DirectSound up front, and shows +// the panic screen instead of stopping when a step fails. bool InitApp() { BootBanner(); @@ -1130,13 +1133,17 @@ bool InitApp() return true; } +// CleanupApp() +// 5960 @ 0x0002d930 shuts XOnline down, frees the matrix stack, the scene +// and its class, then Class_Exit, the XIP sections, Text_Exit, DirectSound +// and the app dir. Theseus releases D3D first, drops Locale too, has no +// XOnline session to end and lets DSoundManager close the sound side. void CleanupApp() { ReleaseD3D(); delete g_pObject; g_pObject = NULL; - delete g_pClass; g_pClass = NULL; @@ -1154,6 +1161,12 @@ void CleanupApp() #endif } +// Advance() +// Reconstructed from the frame loop in 5960 XApp @ 0x0002da00: the clock is +// GetTickCount in seconds, the step is the change since last frame (never +// zero: 5960 uses one millisecond's worth), then the camera, every lerper +// and the scene advance. Theseus also feeds its background loader; 5960 +// polls the keyboard and runs its deferred deletes here. void Advance() { XTIME now = (float)GetTickCount() / 1000.0f; @@ -1163,7 +1176,6 @@ void Advance() g_now = now; theCamera.Advance(nDelta); - CLerper::AdvanceAll(); g_pObject->Advance(nDelta); @@ -1204,25 +1216,23 @@ void Theseus() CleanupApp(); } +// 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(TCHAR *szFileToLoad) { - TCHAR szAppDir[MAX_PATH]; - TCHAR szFontDir[MAX_PATH]; - TCHAR szXipDir[MAX_PATH]; _tcscpy(szFileToLoad, _T("Q:\\Xips\\default.xap")); - _tcscpy(szAppDir, _T("Q:\\")); - _tcscpy(szFontDir, _T("Q:\\Fonts\\")); - _tcscpy(szXipDir, _T("Q:\\Xips\\")); _tcscpy(g_szCurDir, _T("Q:/Xips/default.xap")); - g_szAppDir = new TCHAR[_tcslen(szAppDir) + 1]; - _tcscpy(g_szAppDir, szAppDir); + g_szAppDir = new TCHAR[_tcslen(_T("Q:\\")) + 1]; + _tcscpy(g_szAppDir, _T("Q:\\")); - g_sFontDir = new TCHAR[_tcslen(szFontDir) + 1]; - _tcscpy(g_sFontDir, szFontDir); + g_sFontDir = new TCHAR[_tcslen(_T("Q:\\Fonts\\")) + 1]; + _tcscpy(g_sFontDir, _T("Q:\\Fonts\\")); - g_sXipDir = new TCHAR[_tcslen(szXipDir) + 1]; - _tcscpy(g_sXipDir, szXipDir); + g_sXipDir = new TCHAR[_tcslen(_T("Q:\\Xips\\")) + 1]; + _tcscpy(g_sXipDir, _T("Q:\\Xips\\")); } LONG XdashUnhandledExceptionFilter(LPEXCEPTION_POINTERS pEx) @@ -1239,6 +1249,10 @@ LONG XdashUnhandledExceptionFilter(LPEXCEPTION_POINTERS pEx) __asm { hlt } } +// main() +// 5960 @ 0x0002dc80 installs its crash handler unless the hardware says +// it's a debug kit, then runs the app. Theseus decides that at build time +// (DEVKIT) and its handler is the panic screen above. int __cdecl main(int /*argc*/, char * /*argv*/[]) { #ifndef DEVKIT From 1479a42dc4194b2282dc1bef18cc38b77bca06fb Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:45 -0500 Subject: [PATCH 08/13] Fixed the Memory pane reading the hard drive as 0 blocks A bounds check added in the hardening pass rejected Dev0, the hard drive, before its C: branch could run, so its totals and the ratio always came back 0. It now allows Dev0, like 5960 does. Needs a console test. --- theseus/xbox/memory_monitor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/theseus/xbox/memory_monitor.cpp b/theseus/xbox/memory_monitor.cpp index 9456c22..48c1176 100755 --- a/theseus/xbox/memory_monitor.cpp +++ b/theseus/xbox/memory_monitor.cpp @@ -281,10 +281,10 @@ int CMemoryMonitor::HaveDeviceBottom(int nDevice) // a unit its mount letter (unmounted fails). Both sizes are rounded up to // 16 KB blocks and one block comes off the total for the root directory. // If the drive can't be asked, a unit is marked gone and both read 0. -// Theseus range checks devUnit first. +// Theseus range checks devUnit first; the hard drive (Dev0) is in range. bool CMemoryMonitor::GetTotalAndFreeBlocks(int devUnit, int *pnTotalBlocks, int *pnFreeBlocks) { - if (devUnit < Dev1Unit1 || devUnit > Dev4Unit2) + if (devUnit < Dev1Unit1 || devUnit > Dev0) return false; char szRoot[4] = { 'C', ':', '\\', 0 }; From 80f48909ba0d9c972e9732e40b5619034cb78b05 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:45 -0500 Subject: [PATCH 09/13] Fixed fast IR remote presses counting as repeats The remote stored the new packet before comparing key codes, so a different key pressed within 120 ms looked like a held key and could be swallowed. It now compares first, the way 5960 does at 0x41040. Needs a console test with a remote. --- theseus/xbox/input.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/theseus/xbox/input.cpp b/theseus/xbox/input.cpp index d246e1a..5aca596 100755 --- a/theseus/xbox/input.cpp +++ b/theseus/xbox/input.cpp @@ -555,12 +555,12 @@ bool CJoystick::PollRemote(int port, float nSeconds) ResetScreenSaver(); m_remoteIdleTime = 0.0f; - m_joystate[port] = state; if (state.IrRemote.wKeyCode != m_joystate[port].IrRemote.wKeyCode || state.IrRemote.wTimeDelta > 120) m_remoteRepeatCount = 1; else m_remoteRepeatCount++; + m_joystate[port] = state; bool bFire = m_remoteRepeatCount == 1 || (m_remoteRepeatCount > 7 && (m_remoteRepeatCount % 2) != 0); if (!bFire) From f6644429ee8555ea22b6cc49d4e7267d63277657 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:46:56 -0500 Subject: [PATCH 10/13] Added 5960's launch reasons to GetLaunchReason 5960 names reasons 12 to 19 (FromOnlineDash, Friends, VoiceChat, Messages, AccountManagement, NewAccount, AccountRecovery and NetworkSettings, all Internal); Theseus only knew the older 6, 7 and 9, which stay. Needs a console test with a title that sends one. --- theseus/xbox/config.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/theseus/xbox/config.cpp b/theseus/xbox/config.cpp index 4194305..18c6e88 100755 --- a/theseus/xbox/config.cpp +++ b/theseus/xbox/config.cpp @@ -570,8 +570,8 @@ void CConfig::SetMoviePCFlags(int nFlags) // CConfig::GetLaunchReason() [script fn 'GetLaunchReason', FND 0x0017fe98, sig 8] // Reconstructed from 5960 retail XBE @ 0x0003b2d0: with launch data, the // reason as a name (jump table @ 0x0003b3ac); otherwise, or for a reason -// it doesn't name, an empty string. Theseus names the online menu, account -// signup and network settings by this XDK's numbering. +// it doesn't name, an empty string. Theseus also names the online menu, +// account signup and network settings by this XDK's older numbering. CStrObject *CConfig::GetLaunchReason() { const TCHAR *szReason = _T(""); @@ -586,6 +586,14 @@ CStrObject *CConfig::GetLaunchReason() case XLD_LAUNCH_DASHBOARD_ONLINE_MENU: szReason = _T("FromOnlineDash"); break; case XLD_LAUNCH_DASHBOARD_NEW_ACCOUNT_SIGNUP: szReason = _T("NewAccountInternal"); break; case XLD_LAUNCH_DASHBOARD_NETWORK_CONFIGURATION: szReason = _T("NetworkSettingsInternal"); break; + case 12: szReason = _T("FromOnlineDash"); break; + case 13: szReason = _T("FriendsInternal"); break; + case 14: szReason = _T("VoiceChatInternal"); break; + case 15: szReason = _T("MessagesInternal"); break; + case 16: szReason = _T("AccountManagementInternal"); break; + case 17: szReason = _T("NewAccountInternal"); break; + case 18: szReason = _T("AccountRecoveryInternal"); break; + case 19: szReason = _T("NetworkSettingsInternal"); break; } } return new CStrObject(szReason); From 58f2f88c25d47a4f838f33542c4055ee3a7abbd9 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:47:20 -0500 Subject: [PATCH 11/13] Disc detection now notices a disc pulled mid check 5960's GetDiscType reads the tray again when none of the marker files turned up, and calls it no disc if the tray settled meanwhile instead of a bad disc. Theseus skipped that second look. Needs a console test. --- theseus/xbox/disc_management.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/theseus/xbox/disc_management.cpp b/theseus/xbox/disc_management.cpp index 9b2010a..6b96dbb 100755 --- a/theseus/xbox/disc_management.cpp +++ b/theseus/xbox/disc_management.cpp @@ -324,7 +324,8 @@ static const DISCTYPECHECK rgddc[] = // ERROR_UNRECOGNIZED_MEDIA means a bad disc), anything else is no disc. // Otherwise an audio TOC makes it Audio, then the marker files decide; a // lookup failing with anything but not found gets one retry after 100 ms. -// See docs/decomp/Disc.md for the instruction walk. +// Nothing found is a bad disc, unless the tray has settled meanwhile, which +// means the disc went away. See docs/decomp/Disc.md for the instruction walk. int GetDiscType() { if (g_cdrom.IsOpen()) @@ -374,6 +375,8 @@ int GetDiscType() bMayRetry = true; } + if (NT_SUCCESS(HalReadSMCTrayState(&trayState, NULL)) && trayState != SMC_TRAY_STATE_MEDIA_DETECT) + return DISC_NONE; return DISC_BAD; } From 98a4dceee755563b336e47a7b8d5e1b23182e19d Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:47:20 -0500 Subject: [PATCH 12/13] GetEthernetLinkStatus reads the cable link again It returned whether XNet had an address lookup going, which is 1 with no cable plugged in. 5960 asks XNetGetEthernetLinkStatus for the link bit, so it does too now. Needs a console test with and without a cable. --- theseus/xbox/config.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/theseus/xbox/config.cpp b/theseus/xbox/config.cpp index 18c6e88..9724a09 100755 --- a/theseus/xbox/config.cpp +++ b/theseus/xbox/config.cpp @@ -1137,10 +1137,9 @@ void CConfig::ToggleNoisyCamera() } // CConfig::GetEthernetLinkStatus() [script fn 'GetEthernetLinkStatus', FND 0x00180318, sig 2] -// 5960 @ 0x0003b9d0 is XNetGetEthernetLinkStatus() & 1, the cable's link -// bit. Theseus answers whether XNet has started looking for an address. +// Reconstructed from 5960 retail XBE @ 0x0003b9d0: whether the cable is +// plugged in and live (XNET_ETHERNET_LINK_ACTIVE). int CConfig::GetEthernetLinkStatus() { - XNADDR xna; - return XNetGetTitleXnAddr(&xna) != 0 ? 1 : 0; + return (XNetGetEthernetLinkStatus() & XNET_ETHERNET_LINK_ACTIVE) ? 1 : 0; } From 8e6ad3f5c5b90775965c2aca98f0d887d148966d Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:47:33 -0500 Subject: [PATCH 13/13] Only use Config.ini's 480p and 720p on an HDTV or VGA pack A console with Use Progressive or Use 720p set booted into a progressive mode even on a composite or S-Video cable, which those can't show: a black screen. Those packs now get the normal interlaced mode, as 5960 does. Might be issue 87. Needs a console test on a standard AV cable. --- theseus/xbox/main.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/theseus/xbox/main.cpp b/theseus/xbox/main.cpp index e9bf2c9..a3ddf84 100644 --- a/theseus/xbox/main.cpp +++ b/theseus/xbox/main.cpp @@ -460,7 +460,11 @@ bool InitD3D() XSetValue(XC_VIDEO_FLAGS, REG_DWORD, &videoFlags, sizeof(videoFlags)); } - if (isPAL) + // Composite, S-Video, RF and SCART can't carry a progressive signal, so + // Config.ini's 480p and 720p only count on an HDTV or VGA pack. 5960 only + // goes progressive on the HDTV pack (0x0002ccf0). + DWORD dwPack = XGetAVPack(); + if (isPAL || (dwPack != XC_AV_PACK_HDTV && dwPack != XC_AV_PACK_VGA)) { bEnable480p = false; bEnable720p = false;