Replace native graphics device state with SDK services

This commit is contained in:
Thomas Martin committed 2026-11-06 12:57:31 +01:00
1 parent 149bf90ddf
commit 5030dbbe43
12 files changed
+535 -241

No files matched your search

+45 -21
View File
@@ -173,26 +173,31 @@ overrides, kind 2 in the logs, the others as library stubs.)
Phase 4 (TMB's overrides native, `kernel.md` section 3b) reached what only ran inside overrides before:
`sceGsExecLoadImage(lp, src)` returns 0 and uploads nothing (boot: 86 calls, all inside `texmResInit` /
`texmLoadResTexture`); `sceGsSetDefLoadImage`'s image tag counts T8H, T4HL and T4HH (0x1b, 0x24, 0x2c) as 32-bit
texels (match1p #16897863); `sceGsExecStoreImage(sp, dst)` reads GS memory there is none of: the image (its size from
the packet's TRXREG and format) as zeros, 0 (TMB's lens flares outside a match, through its override: match1p frame
13736).
texels (match1p #16897863). `sceGsExecStoreImage` now requires a native port override; it throws rather than parsing
a packet and fabricating an image. Ports implement readback from their own query/model/texture inputs.
There is no GS. The SetDef functions build, in guest memory, the packets the game sends later (the sends themselves are
DMA and GIF stores, answered from the log until the native renderer takes the draws); the native library writes them
exactly as the reference did. Their layout follows the game's own libgraph (its code in the ELF, `0x2033b0`-`0x204e80`)
where the reference agrees with it; where it does not, the reference wins (the records), noted below. What a renderer
needs is kept in `GsState` (`bozo/libs/gs.h`).
There is no GS register bank or transfer history. The SetDef functions only write SDK output structures for
recompiled callers that still use those bytes; native rendering never consumes those packets. When a port explicitly
enables `Registry::nativeGraphics`, image load/store SetDef calls instead return 0 without reading arguments beyond
the port mode, dereferencing the output or serializing any packet. Native uploads belong to the asset boundary;
readback belongs to the port's high-level caller, and unsupported ExecStoreImage still fails explicitly. Other SDK
templates remain available because callers may inspect their scalar fields. Scalar video
parameters come from the SDK's scratchpad parameters, without a second engine copy. The native renderer gets draws,
materials, textures and presentation settings directly from the port. The historical call-log totals below describe
the earlier implementation and do not qualify the current packet-free boundary.
`native_image_builders` is a standalone game-free test of this opt-in boundary: generic calls journal their SDK
output, native calls do not write valid guarded output buffers, and inaccessible native outputs are never read.
| Function | Native answer | Where the reference differs from the game's libgraph |
|---|---|---|
| `sceGsResetGraph(mode, interlace, video, field)` | mode 0: keeps the display mode; writes `{interlace, video, field, 3}` as bytes at scratchpad `0x100`; sets the kernel's field rate (`OP` 37, 60000/1001 in NTSC); returns 0 | the reference writes its own 4 bytes at scratchpad `0x100` (the game's libgraph keeps them in its GParam at `0x4e1f30`, which the reference leaves alone) and does not call `SetGsCrt` |
| `sceGsResetPath()` | nothing (no result) | |
| `sceGsSetDefDispEnv(disp, psm, w, h, dx, dy)` | PMODE `0x66`, SMODE2 (from the display mode), DISPFB, DISPLAY (magnification `(w + 2559) / w`, the vertical start 50/25 in NTSC), BGCOLOR 0; returns 0 | the horizontal start is 652 in NTSC (the game's libgraph: 636) |
| `sceGsSetDefDrawEnv(env, psm, w, h, ztest, zpsm)`, `...DrawEnv2` | the eight A+D pairs (FRAME, ZBUF with the Z buffer after two frame buffers, XYOFFSET at 2048 - w/2, SCISSOR, PRMODECONT and COLCLAMP or'ed with 1, DTHE for 16-bit formats, TEST) for context 1 or 2; returns 8 | |
| `sceGsSetDefDrawEnv(env, psm, w, h, ztest, zpsm)`, `...DrawEnv2` | writes eight A+D pairs for context 1 or 2; initializes PRMODECONT/COLCLAMP to 1 and DTHE from the format without reading old packet bytes; returns 8 | reserved bits are initialized |
| `sceGsSetDefClear(clear, ztest, x, y, w, h, r, g, b, a, z)` | TEST, PRIM sprite, RGBAQ (Q 1.0), two XYZ2, TEST; returns 0 | returns 0 (libgraph: 6) |
| `sceGsSetDefLoadImage(lp, dbp, dbw, dpsm, x, y, w, h)` | the GIF tag, BITBLTBUF, TRXPOS, TRXREG, TRXDIR 0, the IMAGE tag (its size from the format, as libgraph's table); returns 0 | BITBLTBUF has SBW = 1; returns 0 (libgraph: 6) |
| `sceGsSetDefStoreImage(sp, sbp, sbw, spsm, x, y, w, h)` | VIF codes, the GIF tag, BITBLTBUF, TRXPOS, TRXREG, FINISH, TRXDIR 1; returns 0 | the first VIF code is a NOP (libgraph: MSKPATH3); BITBLTBUF has DBW = 1; returns 0 (libgraph: 7) |
| `sceGsPutDrawEnv(packet)` | the A+D pairs kept in `GsState::registers`; returns 0 | |
| `sceGsPutDrawEnv(packet)` | returns 0 without reading the packet; the port supplies native materials | |
| `sceGsSyncPath(mode, timeout)` | 0: nothing is ever in flight | |
| `sceGsSyncV(mode)` | 1 when the frames ended by then (this one included) are odd, else 0 | (settled on all 8 calls of boot and 2,290 of match1p; the vblank count's parity matches only half of them) |
@@ -203,13 +208,8 @@ from the log (`Function::frameBoundary`), in the real runtime from the presentat
A call the run was cut inside (match1p's last `sceGsSyncV`, record flag `cut`: its result is not recorded) stays
answered from the log.
**What the native renderer will need from here** (phase 3's renderer, or TMB's native renderer moved over in phase 4):
the display mode (`interlace`, `videoMode`, `fieldMode`), the display environment (DISPFB: the frame buffer's width and
format; DISPLAY: position, magnification and size of the picture), the draw environment registers the game sets
(FRAME, ZBUF, XYOFFSET, SCISSOR, TEST, DTHE, COLCLAMP of both contexts), and the image transfers set up (GS buffer base,
width, format, rectangle, direction; the last 64 kept). The pixel data of uploads never goes through here: TMB's native
renderer takes textures from the game's own assets; the packets the game kicks (`sceGsExecLoadImage` and the DMA chains)
are still answered from the log as stores, until the renderer takes them (no-packets plan).
Native rendering does not obtain any state from libgraph packet submissions. A port must translate its high-level
draw and image operations into native renderer calls. Unhandled readback cannot silently return a black image.
Results: boot 20,982 calls native (`sceGsSyncPath` 17,966, `sceGsPutDrawEnv` 2,994, `sceGsSyncV` 6, the SetDef and
Reset calls 16), match1p 117,534 (`sceGsSyncPath` 95,644, `sceGsPutDrawEnv` 19,291, `sceGsSyncV` 2,289,
@@ -526,8 +526,32 @@ be answered from the log and counted ("calls with no native answer").
## 11. Hardware registers (`io`)
Native: every hardware load and store TMB's logs hold (`bozo/libs/io.h`, `libs/io.cpp`), answered by a model of only
what the game observes. No DMA, VIF, GIF, IPU or GS runs behind them.
Native: the remaining register/status compatibility operations (`bozo/libs/io.h`, `libs/io.cpp`). No DMA, VIF, GIF,
IPU or GS executes behind them. `sceDmaReset` clears native completion bookkeeping at its SDK entry point instead
of running a hardware reset loop. The free host faults on unknown device accesses; it no longer silently returns
zero or drops a write. Channel register accesses support byte, halfword and word widths at the register base.
`sceDmaSend`, `sceDmaSendN`, `sceDmaSendI` and `sceDmaSync` also have native SDK bindings. VIF1/GIF sends acknowledge
the graphics work the port already submitted and queue the kernel's completion handlers, without reading or
retaining the packet/chain address or transfer length. Normal, chain and interleave calls keep the SDK's completion
status convention; sync returns immediately for completed native work instead of executing libdma's polling loops.
VIF0 chain submissions select a known native VU0 program image by source identity. IPU-to submissions retain only
the native movie decoder's deferred-completion contract. Invalid handles, unsupported data producers, overlapping
pending transfers and unimplemented blocking waits fail explicitly. `IoState::nativeSubmissions` and
`nativeSynchronizations` are service diagnostics, not device state. A port still touching the registers directly
uses the compatibility operations listed below.
With a port registered for native graphics, these SDK submissions and sync calls bypass the retired channel and
status banks entirely. The SDK scheduler receives completion notifications directly. Masked callbacks retain native
job-completion state (`nativeCompleted`) so enabling their handler still delivers them; no CHCR/D_STAT/CPCOND0
values are manufactured. Native reset clears SDK jobs/configuration without resetting a device model.
`sceDmaPutEnv` / `sceDmaGetEnv` validate and round-trip the opaque 20-byte SDK configuration, including the original
field error codes, without programming a controller. `sceGsPutDispEnv` returns without reading its obsolete display
structure or issuing display-register writes; the native renderer/platform layer already owns presentation.
`FreeOptions::profileIo` collects remaining device accesses by guest PC and address in `FreeStats::ioSites`.
It is off by default. Ports can use it to find callers that still need native adaptation; the existing native
graphics guard rejects any attempt to access retired graphics devices before the compatibility path runs.
| Address | Register | Native answer |
|---|---|---|
@@ -537,7 +561,7 @@ what the game observes. No DMA, VIF, GIF, IPU or GS runs behind them.
| 0x12001000 | GS CSR (loads) | FIELD (bit 13) the vblank count's parity, nothing else (TMB's vblankHandler reads it inside its override: boot #729700 on). A port's own access (`bozo::port::ioRead32` / `ioWrite32`) is not the game's: a store of its does not complete channel 4's transfer (match1p #14450438); a T0 read of its is a poll as the game's, a T0 write keeps the last read, its (#34736003) and the game's alike (stage-level0 #13062314: the game read 0, wrote 0 and read 0: a poll), and the EE time the port charges (`bozo::port::accountCycles`, TMB's frame end) takes the poll's pending cycles as a checkpoint would (#17538393, #17541951) |
| 0x10008000-30 | VIF0 CHCR, MADR, QWC, TADR | a start (CHCR STR) completes at once: D_STAT bit 0 and the DMAC interrupt (the kernel runs or keeps it); a chain start notes the microcode image (section 10) |
| 0x10009000-30 | VIF1 | as VIF0 (D_STAT bit 1): TMB's 3D packets, 2.5M kicks in match1p |
| 0x1000a000-30 | GIF | as VIF0 (bit 2), except a chain whose first packet draws (its GIF tag sets PRIM: the sprite TMB sends from 0x4fe180 before `sceGsSyncV` on its loading screens, 2,269 kicks in match1p): the reference drops it, no completion and no interrupt |
| 0x1000a000-30 | GIF | immediate native completion (bit 2); no chain or packet is read, regardless of PRE/PRIM |
| 0x1000b400-30 | IPU_TO (channel 4) | the transfer completes (bit 4, the interrupt) at the game's first store after libmpeg's decoder took it, i.e. after the decoder asked for more data (it queued the game's nodata callback: the native libmpeg says so, section 9.4); a CHCR store without STR stops the channel (TMB's movie end: the last transfer never completes) |
| any channel | CHCR load | the value written, STR cleared once complete |
| any channel | MADR, QWC, TADR loads | 0 (the reference's answer: TMB reads channel 4's MADR, 0 in every record, also before any transfer) |
@@ -547,7 +571,7 @@ what the game observes. No DMA, VIF, GIF, IPU or GS runs behind them.
| 0x1000e030-60 | D_SQWC, D_RBSR, D_RBOR, D_STADR | kept |
| 0x1000f520 | D_ENABLER | 0: no transfer is ever suspended (none runs) |
| 0x1000f590 | D_ENABLEW | kept |
| 0x12000000-f0 | the GS's privileged registers (PMODE, SMODE2, DISPFB1/2, DISPLAY1/2, BGCOLOR...) | 64-bit stores kept in `IoState::gsPrivileged` for the renderer (TMB's movie layer uses both circuits: PMODE 0xff03) |
| 0x12000000-f0 | obsolete GS display-register stores | acknowledged and discarded; native presentation owns the display, no register bank is retained |
The kernel's question at `EnableDmac` (is the channel's D_STAT bit still set, `calllog.md` section 6) is now answered by
the model's D_STAT, no longer from the log.
+6 -1
View File
@@ -257,11 +257,13 @@ namespace bozo::host
if (nativeGraphics() && libs::graphicsIo(address))
fault(*d_, ctx, std::format("native graphics reached a retired register read at 0x{:x}", address));
++stats_.ioAccesses;
if (opt_.profileIo) ++stats_.ioSites[{ctx->pc, address}][0];
watchdog(ctx);
value[0] = value[1] = 0;
if (!libs::ioKnown(address, size, false))
{
++stats_.ioUnknown;
fault(*d_, ctx, std::format("unhandled device read at 0x{:x} ({} bytes), pc 0x{:x}", address, size, ctx->pc));
return;
}
libs_.ioAccess = libs::IoAccess{address, size, false, 0, d_->timerPending()};
@@ -276,9 +278,11 @@ namespace bozo::host
if (nativeGraphics() && libs::graphicsIo(address))
fault(*d_, ctx, std::format("native graphics reached a retired register write at 0x{:x}", address));
++stats_.ioAccesses;
if (opt_.profileIo) ++stats_.ioSites[{ctx->pc, address}][1];
if (!libs::ioKnown(address, size, true))
{
++stats_.ioUnknown;
fault(*d_, ctx, std::format("unhandled device write at 0x{:x} ({} bytes), pc 0x{:x}", address, size, ctx->pc));
return;
}
libs_.ioAccess = libs::IoAccess{address, size, true, value[0], d_->timerPending(), ctx->pc};
@@ -322,7 +326,8 @@ namespace bozo::host
bool FreeHost::dmacStatusSet(uint32_t cause)
{
return !(nativeGraphics() && cause < 3) && cause < 10 && (libs_.io.stat & (1u << cause)) != 0;
if (nativeGraphics() && cause < 3) return libs_.io.nativeCompleted[cause];
return cause < 10 && (libs_.io.stat & (1u << cause)) != 0;
}
void FreeHost::waitCompleted(ee::Dispatcher &, ee::Thread &t)
+3
View File
@@ -35,6 +35,7 @@ namespace bozo::host
std::string out; // a PS2XREF1 record of the run (empty: none)
bool quiet = false;
bool printGameOutput = false; // the game's printf
bool profileIo = false; // count remaining device reads/writes by guest function and address
uint32_t stallFields = 600; // end the run when no game frame ended for this many fields of EE time (0: never)
// The game on the host's clock (a window): port::Host::realTime() true, deterministic() false (the port holds
// its frames to their rate: FramePacer). Off: as fast as the host makes frames, nothing host-timed.
@@ -53,6 +54,8 @@ namespace bozo::host
uint64_t libraryCalls = 0, kernelCalls = 0, overrideCalls = 0, vu0Calls = 0, ioAccesses = 0, ioUnknown = 0;
uint64_t frames = 0;
std::map<std::string, uint64_t> unanswered; // calls with no native answer (by name), which end the run
// (guest PC, device address) -> {reads, writes}; populated only when profileIo is enabled.
std::map<std::pair<uint32_t, uint32_t>, std::array<uint64_t, 2>> ioSites;
};
class FreeHost final : public ee::Host, public ee::KernelObserver, public port::Host
-46
View File
@@ -1,46 +0,0 @@
// The GS library's state as the native libgraph keeps it: no GS behind it, only what a native renderer takes later
// (the display mode, the environments the game sets, its image transfers). Spec: docs/specs/libraries.md section 5.
#pragma once
#include <array>
#include <cstdint>
#include <vector>
namespace bozo::libs
{
struct GsState
{
// sceGsResetGraph: interlaced (1) or not, the video mode (2 NTSC, 3 PAL), field (1) or frame (0) mode.
bool reset = false;
int16_t interlace = 0, videoMode = 0, fieldMode = 0;
// The display environment the game last built (sceGsSetDefDispEnv): PMODE, SMODE2, DISPFB, DISPLAY, BGCOLOR.
struct Display
{
uint32_t address = 0; // the sceGsDispEnv in guest memory
uint64_t pmode = 0, smode2 = 0, dispfb = 0, display = 0, bgcolor = 0;
bool set = false;
} display;
// The GS registers the game's draw environments set (sceGsPutDrawEnv's A+D pairs, by register number):
// FRAME_1/2, ZBUF_1/2, XYOFFSET_1/2, SCISSOR_1/2, PRMODECONT, COLCLAMP, DTHE, TEST_1/2...
std::array<uint64_t, 0x64> registers{};
std::array<bool, 0x64> registerSet{};
uint64_t drawEnvironments = 0; // sceGsPutDrawEnv calls
// Image transfers the game set up (sceGsSetDefLoadImage: host to GS memory; sceGsSetDefStoreImage: GS memory
// to host): where in GS memory and how large. The data itself never reaches a GS: a native renderer takes
// textures from the game's own assets.
struct Transfer
{
uint32_t packet = 0; // the packet in guest memory
bool toHost = false; // a store (GS memory to the host)
uint32_t base = 0, width = 0, psm = 0; // buffer base (64-word blocks), width (64 pixels), pixel format
int32_t x = 0, y = 0, w = 0, h = 0;
};
std::vector<Transfer> transfers; // the last 64
uint64_t loadImages = 0, storeImages = 0;
uint64_t pathSyncs = 0, vsyncs = 0;
};
}
+5 -4
View File
@@ -21,7 +21,6 @@ namespace bozo::libs
struct IoState
{
bool completeNativeGraphics = false; // complete discarded graphics work without reading packets
// ---- Timer 0 (T0_COUNT, T0_MODE; TMB polls the count) ----
uint32_t t0Mode = 0;
uint64_t t0Base = 0; // the EE cycle the count was last written
@@ -38,6 +37,11 @@ namespace bozo::libs
bool running = false; // started, not complete yet (channel 4: the reference completes it later)
};
std::array<Channel, 10> channels{};
// Native SDK service diagnostics, not device registers. The first three channels
// are native VU0 image selection, VIF1 graphics, and GIF graphics respectively.
std::array<uint64_t, 3> nativeSubmissions{};
std::array<bool, 3> nativeCompleted{}; // completed SDK jobs, including callbacks masked at submission
uint64_t nativeSynchronizations = 0;
// libmpeg's decoder asked the game for more data (it queued the game's nodata callback) since channel 4 was
// last started: the IPU has taken that transfer, which completes at the game's next store.
bool ipuDemand = false;
@@ -46,9 +50,6 @@ namespace bozo::libs
bool hostAccess = false;
uint32_t ctrl = 0, stat = 0, pcr = 0, sqwc = 0, rbsr = 0, rbor = 0, stadr = 0, enable = 0;
// ---- The GS's privileged registers (PMODE ... BGCOLOR): what the game sets, for the renderer ----
std::array<uint64_t, 16> gsPrivileged{};
bool pcrWritten = false;
// The transfers CPCOND0 sees completed: D_STAT's channel bits as completions set them and the game's D_STAT
// stores clear them, and none after a FlushCache (the reference: TMB's hierCheckVifComplete, right after
+4 -2
View File
@@ -5,7 +5,6 @@
#include "bozo/ee/kernel.h"
#include "bozo/libs/cd.h"
#include "bozo/libs/gs.h"
#include "bozo/libs/guest.h"
#include "bozo/libs/io.h"
#include "bozo/libs/mc.h"
@@ -195,12 +194,14 @@ namespace bozo::libs
// ---- State ----
Heap heap;
Rand rand;
GsState gs;
PadState pad;
McState mc;
CdState cd;
Vu0State vu0;
IoState io;
// Opaque libdma SDK configuration returned by GetEnv. Native services do not
// turn it into DMA controller registers or execute a hardware environment.
std::array<uint8_t, 20> dmaEnvironment{};
MpegState mpeg;
SifState sif;
SndDriver snd;
@@ -234,6 +235,7 @@ namespace bozo::libs
void addLibc(std::vector<Function> &out);
void addLibm(std::vector<Function> &out);
void addGs(std::vector<Function> &out);
void addDma(std::vector<Function> &out);
void addPad(std::vector<Function> &out);
void addMc(std::vector<Function> &out);
void addCd(std::vector<Function> &out);
+47 -126
View File
@@ -1,13 +1,12 @@
// The GS library calls TMB makes (libraries.md section 5). The SetDef functions build the packets the game later
// sends (environments, image transfers) exactly as the reference does, from the semantics of the game's own libgraph
// (its code in the ELF) where the reference agrees with it; there is no GS: what a renderer needs is kept in GsState.
// Native libgraph ABI compatibility. SetDef functions write the SDK's output structures because
// recompiled callers can use those bytes. Nothing consumes the resulting graphics packets:
// draws, textures and readbacks belong to the port's native renderer, with no GS register state.
#include "bozo/libs/libraries.h"
#include "bozo/ee/dispatcher.h"
#include "bozo/port.h"
#include <algorithm>
#include <cstring>
#include <stdexcept>
namespace bozo::libs
{
@@ -15,12 +14,6 @@ namespace bozo::libs
{
int16_t s16(uint32_t v) { return static_cast<int16_t>(v); }
void write64(Guest &g, uint32_t address, uint64_t v) { g.write(address, &v, 8); }
uint64_t read64(Guest &g, uint32_t address)
{
uint64_t v;
std::memcpy(&v, g.in(address, 8), 8);
return v;
}
uint64_t sx(int64_t v) { return static_cast<uint64_t>(v); }
// GS register numbers (A+D addresses).
@@ -40,17 +33,12 @@ namespace bozo::libs
const int16_t mode = s16(g.arg(0));
if (mode == 0)
{
GsState &s = l.gs;
s.reset = true;
s.interlace = s16(g.arg(1));
s.videoMode = s16(g.arg(2));
s.fieldMode = s16(g.arg(3));
const uint8_t param[4] = {static_cast<uint8_t>(s.interlace), static_cast<uint8_t>(s.videoMode),
static_cast<uint8_t>(s.fieldMode), 3};
const uint8_t param[4] = {static_cast<uint8_t>(g.arg(1)), static_cast<uint8_t>(g.arg(2)),
static_cast<uint8_t>(g.arg(3)), 3};
g.write(kScratchpadBase + 0x100u, param, 4);
if (ee::Dispatcher *d = l.dispatcher())
{
if (s.videoMode == 3)
if (param[1] == 3)
d->kernel().fieldRate(50, 1); // PAL (not in TMB's runs: TMB is NTSC only)
else
d->kernel().fieldRate(60000, 1001);
@@ -63,67 +51,63 @@ namespace bozo::libs
void resetPath(Libraries &, Guest &) {}
// sceGsSetDefDispEnv(disp, psm, w, h, dx, dy): PMODE, SMODE2, DISPFB, DISPLAY, BGCOLOR (64 bits each).
void setDefDispEnv(Libraries &l, Guest &g)
void setDefDispEnv(Libraries &, Guest &g)
{
const uint32_t disp = g.arg(0);
const int32_t psm = s16(g.arg(1)), w = s16(g.arg(2)), h = s16(g.arg(3)), dx = s16(g.arg(4)), dy = s16(g.arg(5));
const GsState &s = l.gs;
GsState::Display d;
d.address = disp;
d.pmode = 0x66;
d.smode2 = s.interlace == 0 ? 2 : (s.fieldMode ? 3 : 1);
d.dispfb = (static_cast<uint64_t>(psm & 0xf) << 15) | (static_cast<uint64_t>(((w + 63) >> 6) & 0x3f) << 9);
write64(g, disp, d.pmode);
write64(g, disp + 8, d.smode2);
write64(g, disp + 16, d.dispfb);
if (s.videoMode == 2 || s.videoMode == 3)
// Read only the SDK's scalar video parameters written by ResetGraph, never a packet.
const auto *mode = g.in(kScratchpadBase + 0x100u, 3);
const uint64_t smode2 = mode[0] == 0 ? 2 : (mode[2] ? 3 : 1);
const uint64_t dispfb = (static_cast<uint64_t>(psm & 0xf) << 15) | (static_cast<uint64_t>(((w + 63) >> 6) & 0x3f) << 9);
write64(g, disp, 0x66);
write64(g, disp + 8, smode2);
write64(g, disp + 16, dispfb);
if (mode[1] == 2 || mode[1] == 3)
{
const bool ntsc = s.videoMode == 2;
const bool ntsc = mode[1] == 2;
const int32_t magh = w ? (w + 2559) / w : 1;
// The horizontal start: the reference's is 652 in NTSC (the game's libgraph has 636), 656 in PAL.
const int32_t x = (dx * magh + (ntsc ? 652 : 656)) & 0xfff;
int32_t y, dh;
if (s.interlace == 1)
if (mode[0] == 1)
{
y = (dy + (ntsc ? 50 : 72)) & 0xfff;
dh = s.fieldMode ? h * 2 - 1 : h - 1;
dh = mode[2] ? h * 2 - 1 : h - 1;
}
else
{
y = (dy + (ntsc ? 25 : 36)) & 0xfff;
dh = h - 1;
}
d.display = static_cast<uint64_t>(x) | (static_cast<uint64_t>(y) << 12) |
const uint64_t display = static_cast<uint64_t>(x) | (static_cast<uint64_t>(y) << 12) |
(static_cast<uint64_t>(magh - 1) << 23) | (sx(magh * w - 1) << 32) | (sx(dh) << 44);
write64(g, disp + 24, d.display);
write64(g, disp + 24, display);
}
d.bgcolor = 0;
write64(g, disp + 32, 0);
d.set = true;
l.gs.display = d;
g.ret(0);
}
// The Z buffer's base after the frame buffers (sceGszbufaddr): in 2048-word pages, two frame buffers unless
// interlaced frame mode NTSC... as the game's libgraph decides it (its GParam's first 48 bits equal to 1).
int32_t zbufAddress(const GsState &s, int32_t psm, int32_t w, int32_t h)
int32_t zbufAddress(Guest &g, int32_t psm, int32_t w, int32_t h)
{
const int32_t pw = ((w + 63) >= 0 ? w + 63 : w + 126) >> 6;
const int32_t ph = (psm & 2) ? (((h + 63) >= 0 ? h + 63 : h + 126) >> 6) : (((h + 31) >= 0 ? h + 31 : h + 62) >> 5);
const int32_t pages = pw * ph;
const bool single = s.interlace == 1 && s.videoMode == 0 && s.fieldMode == 0;
const auto *mode = g.in(kScratchpadBase + 0x100u, 3);
const bool single = mode[0] == 1 && mode[1] == 0 && mode[2] == 0;
return single ? static_cast<int16_t>(pages) : static_cast<int16_t>(static_cast<uint32_t>(pages) << 1);
}
// sceGsSetDefDrawEnv / sceGsSetDefDrawEnv2(draw, psm, w, h, ztest, zpsm): eight A+D pairs for context 1 or 2.
void drawEnv(Libraries &l, Guest &g, bool second)
void drawEnv(Libraries &, Guest &g, bool second)
{
const uint32_t p = g.arg(0);
const int32_t psm = s16(g.arg(1)), w = s16(g.arg(2)), h = s16(g.arg(3)), ztest = s16(g.arg(4)), zpsm = s16(g.arg(5));
const uint64_t fbw = second ? static_cast<uint64_t>((w >> 6) & 0x3f) : static_cast<uint64_t>(((w + 63) >> 6) & 0x3f);
write64(g, p + 0, (static_cast<uint64_t>(psm & 0xf) << 24) | (fbw << 16));
write64(g, p + 8, second ? kFrame2 : kFrame1);
uint64_t zbuf = sx(zbufAddress(l.gs, psm, w, h)) | (static_cast<uint64_t>(zpsm & 0xf) << 24);
uint64_t zbuf = sx(zbufAddress(g, psm, w, h)) | (static_cast<uint64_t>(zpsm & 0xf) << 24);
if (ztest == 0)
zbuf |= 1ull << 32; // ZMSK
write64(g, p + 16, zbuf);
@@ -133,12 +117,11 @@ namespace bozo::libs
write64(g, p + 40, second ? kXyoffset2 : kXyoffset1);
write64(g, p + 48, sx(static_cast<int64_t>(w - 1) << 16) | sx(static_cast<int64_t>(h - 1) << 48));
write64(g, p + 56, second ? kScissor2 : kScissor1);
write64(g, p + 64, read64(g, p + 64) | 1); // PRMODECONT: AC = 1, the rest kept
write64(g, p + 64, 1); // PRMODECONT: AC = 1, reserved bits initialized
write64(g, p + 72, kPrmodecont);
write64(g, p + 80, read64(g, p + 80) | 1); // COLCLAMP: CLAMP = 1
write64(g, p + 80, 1); // COLCLAMP: CLAMP = 1
write64(g, p + 88, kColclamp);
const uint64_t dthe = read64(g, p + 96);
write64(g, p + 96, (psm & 2) ? (dthe | 1) : (dthe & ~1ull)); // dithering for 16-bit formats
write64(g, p + 96, (psm & 2) ? 1 : 0); // dithering for 16-bit formats
write64(g, p + 104, kDthe);
write64(g, p + 112, ztest ? ((static_cast<uint64_t>(ztest & 3) << 17) | 0x10000) : 0x30000);
write64(g, p + 120, second ? kTest2 : kTest1);
@@ -170,13 +153,6 @@ namespace bozo::libs
g.ret(0); // the reference's result (the game's libgraph returns 6, the packet's quadwords)
}
void remember(GsState &s, const GsState::Transfer &t)
{
if (s.transfers.size() >= 64)
s.transfers.erase(s.transfers.begin());
s.transfers.push_back(t);
}
// The transfer's size in quadwords for a pixel format, as the game's libgraph tables it (0 for the formats
// it does not list).
int32_t transferQwords(int32_t psm, int32_t w, int32_t h)
@@ -197,9 +173,10 @@ namespace bozo::libs
// sceGsSetDefLoadImage(lp, dbp, dbw, dpsm, x, y, w, h): a GIF tag with BITBLTBUF, TRXPOS, TRXREG, TRXDIR,
// then the image tag (its size from the format). Returns 0 (nothing written for a transfer over 32767 quadwords).
void setDefLoadImage(Libraries &l, Guest &g)
void setDefLoadImage(Libraries &, Guest &g)
{
// Explicit native ports own image operations; this packet has no consumer.
// A native renderer owns uploads at the asset boundary. There is no consumer
// for this SDK packet; do not serialize it or dereference its output address.
if (port::nativeGraphics(&g.runtime())) { g.ret(0); return; }
const uint32_t p = g.arg(0);
const int32_t dbp = s16(g.arg(1)), dbw = s16(g.arg(2)), dpsm = s16(g.arg(3)), x = s16(g.arg(4)), y = s16(g.arg(5)),
@@ -225,25 +202,15 @@ namespace bozo::libs
write64(g, p + 64, 0); // TRXDIR: host to GS memory
write64(g, p + 72, kTrxdir);
write64(g, p + 80, static_cast<uint64_t>(qwc & 0x7fff) | 0x8000 | (2ull << 58)); // EOP, IMAGE
GsState::Transfer t;
t.packet = p;
t.base = static_cast<uint32_t>(dbp);
t.width = static_cast<uint32_t>(dbw);
t.psm = static_cast<uint32_t>(dpsm);
t.x = x;
t.y = y;
t.w = w;
t.h = h;
remember(l.gs, t);
++l.gs.loadImages;
g.ret(0); // the reference's result (the game's libgraph returns 6)
}
// sceGsSetDefStoreImage(sp, sbp, sbw, spsm, x, y, w, h): VIF codes (NOP, NOP, FLUSHA, DIRECT 6), a GIF
// tag with BITBLTBUF, TRXPOS, TRXREG, FINISH, TRXDIR (GS memory to host). Returns 0.
void setDefStoreImage(Libraries &l, Guest &g)
void setDefStoreImage(Libraries &, Guest &g)
{
// Explicit native ports own image operations; this packet has no consumer.
// Native readback is implemented at the port's caller. Unsupported consumers
// still fail in ExecStoreImage, rather than relying on an unused packet.
if (port::nativeGraphics(&g.runtime())) { g.ret(0); return; }
const uint32_t p = g.arg(0);
const int32_t sbp = s16(g.arg(1)), sbw = s16(g.arg(2)), spsm = s16(g.arg(3)), x = s16(g.arg(4)), y = s16(g.arg(5)),
@@ -266,51 +233,22 @@ namespace bozo::libs
write64(g, p + 88, kFinish);
write64(g, p + 96, 1); // TRXDIR: GS memory to host
write64(g, p + 104, kTrxdir);
GsState::Transfer t;
t.packet = p;
t.toHost = true;
t.base = static_cast<uint32_t>(sbp);
t.width = static_cast<uint32_t>(sbw);
t.psm = static_cast<uint32_t>(spsm);
t.x = x;
t.y = y;
t.w = w;
t.h = h;
remember(l.gs, t);
++l.gs.storeImages;
g.ret(0); // the reference's result (the game's libgraph returns 7)
}
// sceGsPutDrawEnv(packet): the GIF tag's A+D pairs are the environment; kept for the renderer. Returns 0.
void putDrawEnv(Libraries &l, Guest &g)
// The port already submits native materials. Do not dereference the obsolete packet.
void putDrawEnv(Libraries &, Guest &g)
{
if (l.dispatcher() && port::nativeGraphics(&l.dispatcher()->runtime()))
{
// The port submits native materials with its draws. No GIF environment is consumed or mirrored.
g.ret(0);
return;
}
const uint32_t p = g.arg(0);
GsState &s = l.gs;
const uint32_t nloop = std::min<uint32_t>(static_cast<uint32_t>(read64(g, p) & 0x7fff), 32);
for (uint32_t i = 0; i < nloop; ++i)
{
const uint64_t data = read64(g, p + 16 + 16 * i);
const uint32_t reg = static_cast<uint32_t>(read64(g, p + 24 + 16 * i) & 0xff);
if (reg < s.registers.size())
{
s.registers[reg] = data;
s.registerSet[reg] = true;
}
}
++s.drawEnvironments;
g.ret(0);
}
// Native presentation already owns the display. Do not read the legacy display
// structure or execute libgraph's writes to the GS's display circuits.
void putDispEnv(Libraries &, Guest &g) { g.ret(0); }
// sceGsSyncPath(mode, timeout): every path is idle (nothing is ever in flight). Returns 0.
void syncPath(Libraries &l, Guest &g)
void syncPath(Libraries &, Guest &g)
{
++l.gs.pathSyncs;
g.ret(0);
}
@@ -323,28 +261,11 @@ namespace bozo::libs
g.ret(0);
}
// sceGsExecStoreImage(sp, dst): a readback of GS memory as the store packet sp (sceGsSetDefStoreImage's)
// describes. There is no GS memory: the image reads as zeros (TMB's lens flares outside a match, the only
// caller, through its override: match1p frame 13736, inside the attract demo). Returns 0.
void execStoreImage(Libraries &, Guest &g)
// A native port must implement readback at the original high-level caller, using its
// render target and rectangle. Do not parse a console packet or fabricate a black image.
void execStoreImage(Libraries &, Guest &)
{
const uint32_t sp = g.arg(0), dst = g.arg(1);
uint64_t bitbltbuf = 0, trxreg = 0;
for (uint32_t q = 0; q < 8u; ++q)
{
const uint32_t reg = g.read32(sp + q * 16u + 8u) & 0xFFu;
const uint64_t value = g.read32(sp + q * 16u) | (static_cast<uint64_t>(g.read32(sp + q * 16u + 4u)) << 32);
if (reg == 0x50u)
bitbltbuf = value;
else if (reg == 0x52u)
trxreg = value;
}
const uint32_t psm = (bitbltbuf >> 24) & 0x3Fu, w = trxreg & 0xFFFu, h = (trxreg >> 32) & 0xFFFu;
const uint32_t bytes = psm == 0x02u || psm == 0x0Au || psm == 0x32u || psm == 0x3Au ? 2u : psm == 0x01u ? 3u : 4u;
const uint32_t size = w * h * bytes;
if (size && size <= 0x100000u)
g.fill(dst, 0, size);
g.ret(0);
throw std::runtime_error("sceGsExecStoreImage requires a native renderer readback override");
}
// sceGsSyncV(mode): the game waits for the next vblank, and the game frame ends there. The reference returns
@@ -352,7 +273,6 @@ namespace bozo::libs
// match1p's 2,290 calls. The wait and the frame end are the runtime's frame boundary.
void syncV(Libraries &l, Guest &g)
{
++l.gs.vsyncs;
g.ret(static_cast<int32_t>((l.framesEnded + 1u) & 1u));
}
}
@@ -368,6 +288,7 @@ namespace bozo::libs
out.push_back({"sceGsSetDefLoadImage", kGs, setDefLoadImage});
out.push_back({"sceGsSetDefStoreImage", kGs, setDefStoreImage});
out.push_back({"sceGsPutDrawEnv", kGs, putDrawEnv});
out.push_back({"sceGsPutDispEnv", kGs, putDispEnv});
out.push_back({"sceGsSyncPath", kGs, syncPath});
out.push_back({"sceGsExecLoadImage", kGs, execLoadImage});
out.push_back({"sceGsExecStoreImage", kGs, execStoreImage});
+134 -39
View File
@@ -5,6 +5,8 @@
#include "bozo/ee/dispatcher.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include <stdexcept>
#include <cstring>
namespace bozo::libs
{
@@ -13,7 +15,7 @@ namespace bozo::libs
// The DMA channels' register blocks (CHCR at +0, MADR +0x10, QWC +0x20, TADR +0x30).
constexpr uint32_t kChannelBase[10] = {0x10008000u, 0x10009000u, 0x1000A000u, 0x1000B000u, 0x1000B400u,
0x1000C000u, 0x1000C400u, 0x1000C800u, 0x1000D000u, 0x1000D400u};
constexpr uint32_t kGif = 2, kIpuTo = 4;
constexpr uint32_t kIpuTo = 4;
int channelOf(uint32_t a, uint32_t &reg)
{
@@ -54,32 +56,6 @@ namespace bozo::libs
}
namespace
{
// Whether a GIF chain's first packet draws: its GIF tag sets PRIM (PRE, bit 46). The reference completes a
// GIF transfer of register writes at once (its interrupt raised), and drops one that draws (TMB's clear
// before a loading screen's frame boundary): no completion, no interrupt (libraries.md section 11).
bool drawsPrimitive(Libraries &l, const IoState::Channel &c)
{
if (((c.chcr >> 2) & 3u) != 1u)
return false;
Guest g(l.dispatcher()->runtime(), nullptr);
try
{
const uint32_t tag = g.read32(c.tadr), addr = g.read32(c.tadr + 4);
const uint32_t id = (tag >> 28) & 7u, qwc = tag & 0xFFFFu;
if (qwc == 0)
return false;
const uint32_t data = id == 0 || id == 3 || id == 4 ? addr & ~15u : c.tadr + 16;
return (g.read32(data + 4) >> 14) & 1u;
}
catch (const BadAccess &)
{
return false;
}
}
}
bool ioKnown(uint32_t address, uint32_t size, bool store)
{
const uint32_t a = address & 0x1FFFFFFFu;
@@ -87,14 +63,14 @@ namespace bozo::libs
if (a == 0x10000000u || a == 0x10000010u)
return size == 4;
if (channelOf(a, reg) >= 0)
return size == 4;
return size == 1 || size == 2 || size == 4;
if (a >= 0x1000E000u && a <= 0x1000E060u && (a & 0xFu) == 0)
return size == 4;
if (a == 0x1000F520u || a == 0x1000F590u)
return size == 4;
if (store && a >= 0x12000000u && a <= 0x120000F0u && (a & 0xFu) == 0)
return size == 8;
if (!store && a == 0x12001000u) // the GS's CSR (TMB's vblank handler reads its FIELD)
if (a == 0x12001000u) // FIELD reads; obsolete CSR acknowledgement stores have no effect
return size == 8 || size == 4;
return false;
}
@@ -142,11 +118,11 @@ namespace bozo::libs
return v;
}
void ioStore(Libraries &l, uint32_t address, uint32_t, uint64_t value, uint64_t cycle)
void ioStore(Libraries &l, uint32_t address, uint32_t size, uint64_t value, uint64_t cycle)
{
IoState &io = l.io;
const uint32_t a = address & 0x1FFFFFFFu;
const uint32_t v = static_cast<uint32_t>(value);
uint32_t v = static_cast<uint32_t>(value);
uint32_t reg = 0;
// Channel 4 (to the IPU) completes as the reference completed it: at the game's first store after libmpeg's
// decoder took the transfer (asked for more data), before the store's own effect (libraries.md section 11).
@@ -164,6 +140,12 @@ namespace bozo::libs
else if (const int ch = channelOf(a, reg); ch >= 0)
{
IoState::Channel &c = io.channels[static_cast<uint32_t>(ch)];
if (size < 4)
{
const uint32_t mask = size == 1 ? 0xffu : 0xffffu;
const uint32_t old = reg == 0 ? c.chcr : reg == 1 ? c.madr : reg == 2 ? c.qwc : c.tadr;
v = (old & ~mask) | (v & mask);
}
switch (reg)
{
case 0:
@@ -181,12 +163,6 @@ namespace bozo::libs
}
else
{
if (static_cast<uint32_t>(ch) == kGif && !io.completeNativeGraphics && drawsPrimitive(l, c))
{
c.running = false; // dropped: no completion, no interrupt (the reference's renderer path)
c.chcr &= ~0x100u;
break;
}
complete(l, static_cast<uint32_t>(ch)); // VIF0, VIF1, GIF: done at once (no DMA runs)
}
}
@@ -221,8 +197,8 @@ namespace bozo::libs
{
io.enable = v;
}
else if (a >= 0x12000000u && a <= 0x120000F0u)
io.gsPrivileged[(a - 0x12000000u) >> 4] = value;
// Native presentation owns the display. Obsolete display-register stores are
// acknowledged without retaining a GS register bank.
}
namespace
@@ -249,4 +225,123 @@ namespace bozo::libs
static const Function f{"hardware register", kIo, access};
return f;
}
namespace
{
uint32_t sdkChannel(Guest &g)
{
const uint32_t handle = g.arg(0) & 0x1fffffffu;
for (uint32_t ch = 0; ch < 10; ++ch)
if (handle == kChannelBase[ch])
return ch;
throw std::runtime_error("native libdma: invalid channel handle");
}
template <uint32_t Mode>
void submitDma(Libraries &l, Guest &g)
{
const uint32_t ch = sdkChannel(g);
if (ch > 2 && ch != kIpuTo)
throw std::runtime_error("native libdma: transfer needs a native data producer");
if (!l.dispatcher())
throw std::runtime_error("native libdma: no SDK scheduler attached");
if (ch < 3u && port::nativeGraphics(&l.dispatcher()->runtime()))
{
++l.io.nativeSubmissions[ch];
l.io.nativeCompleted[ch] = true;
if (ch == 0u && (Mode & 0xcu) == 4u) l.vu0.kick(Mode, g.arg(1));
// Native work is complete. Notify the SDK scheduler directly; do not
// manufacture CHCR, D_STAT, or CPCOND0 state for a retired device.
l.dispatcher()->kernel().irq(true, ch);
g.ret(0);
return;
}
auto &c = l.io.channels[ch];
if (c.running)
throw std::runtime_error("native libdma: previous native transfer is still pending");
c.chcr = (c.chcr & ~0xcu) | Mode;
if (ch == 0 && (Mode & 0xcu) == 4u)
l.vu0.kick(Mode, g.arg(1)); // select a native program image by its known source, no chain read
if (ch == kIpuTo)
{
// Native libmpeg supplies the stream to FFmpeg. Keep only its outstanding
// completion until the decoder asks for more data, as for direct SDK stores.
c.running = true;
l.io.ipuDemand = false;
}
else
{
++l.io.nativeSubmissions[ch];
// Renderer work was already submitted by the port. Retain no packet address,
// DMA length or transfer chain, and never run libdma's busy-polling code.
complete(l, ch);
}
g.ret(0);
}
void syncDma(Libraries &l, Guest &g)
{
const uint32_t ch = sdkChannel(g);
++l.io.nativeSynchronizations;
if (ch < 3u && l.dispatcher() && port::nativeGraphics(&l.dispatcher()->runtime()))
{
g.ret(0);
return;
}
const bool busy = l.io.channels[ch].running;
if (busy && g.arg(1) != 1u)
throw std::runtime_error("native libdma: blocking wait needs a native completion service");
g.ret(busy ? 1 : 0);
}
// Replace libdma's device-register reset loop at its SDK entry point. Nothing is
// transferred; only outstanding native completion acknowledgements are cleared.
void resetDma(Libraries &l, Guest &g)
{
l.dmaEnvironment.fill(0);
if (l.dispatcher() && port::nativeGraphics(&l.dispatcher()->runtime()))
{
l.io.nativeCompleted.fill(false);
g.ret(0);
return;
}
auto &io = l.io;
const uint32_t enabled = io.ctrl & 1u;
io.channels = {};
io.stat = io.cpcondDone = io.pcr = io.sqwc = io.rbsr = io.rbor = io.stadr = 0;
io.pcrWritten = true;
io.ipuDemand = false;
io.ctrl = g.arg(0) == 1 ? 1u : enabled;
g.ret(enabled);
}
void putDmaEnvironment(Libraries &l, Guest &g)
{
const auto *bytes = g.in(g.arg(0), l.dmaEnvironment.size());
for (unsigned i = 0; i < 4; ++i)
if (bytes[i] >= (i == 3 ? 7u : 10u))
{
g.ret(-static_cast<int32_t>(i) - 1);
return;
}
std::memcpy(l.dmaEnvironment.data(), bytes, l.dmaEnvironment.size());
g.ret(0);
}
void getDmaEnvironment(Libraries &l, Guest &g)
{
g.write(g.arg(0), l.dmaEnvironment.data(), l.dmaEnvironment.size());
g.ret(0);
}
}
void addDma(std::vector<Function> &out)
{
out.push_back({"sceDmaReset", kIo, resetDma});
out.push_back({"sceDmaSend", kIo, submitDma<0x105u>});
out.push_back({"sceDmaSendN", kIo, submitDma<0x101u>});
out.push_back({"sceDmaSendI", kIo, submitDma<0x109u>});
out.push_back({"sceDmaSync", kIo, syncDma});
out.push_back({"sceDmaPutEnv", kIo, putDmaEnvironment});
out.push_back({"sceDmaGetEnv", kIo, getDmaEnvironment});
}
}
+1
View File
@@ -208,6 +208,7 @@ namespace bozo::libs
addLibc(functions_);
addLibm(functions_);
addGs(functions_);
addDma(functions_);
addPad(functions_);
addMc(functions_);
addCd(functions_);
+8
View File
@@ -93,3 +93,11 @@ if(MINGW)
target_link_options(bozo-image-builders-tests PRIVATE -static)
endif()
add_test(NAME native_image_builders COMMAND bozo-image-builders-tests)
# Native graphics services retain no GS register/transfer bank or packet readers.
add_executable(bozo-native-graphics-tests libs/native_graphics_tests.cpp)
target_link_libraries(bozo-native-graphics-tests PRIVATE bozo_libs)
if(MINGW)
target_link_options(bozo-native-graphics-tests PRIVATE -static)
endif()
add_test(NAME native_graphics_boundary COMMAND bozo-native-graphics-tests)
+249
View File
@@ -0,0 +1,249 @@
// Regression coverage for the packet-free native graphics boundary.
#include "bozo/ee/dispatcher.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
namespace
{
template <typename T> concept HasGsState = requires(T t) { t.gs; };
template <typename T> concept HasGsRegisters = requires(T t) { t.gsPrivileged; };
static_assert(!HasGsState<bozo::libs::Libraries>);
static_assert(!HasGsRegisters<bozo::libs::IoState>);
int failures = 0;
void check(bool pass, const char *message)
{
if (!pass) { ++failures; std::printf("FAIL %s\n", message); }
}
struct Machine
{
std::unique_ptr<Runtime> rt = std::make_unique<Runtime>();
R5900Context ctx;
bozo::libs::Libraries libs;
void call(const char *name, std::initializer_list<uint32_t> args)
{
int i = 0;
for (auto a : args) ctx.r[4 + i++].ud[0] = a;
bozo::libs::Guest g(*rt, &ctx);
const auto *fn = libs.find(name);
if (!fn) throw std::runtime_error(name);
fn->handler(libs, g);
}
uint64_t word(uint32_t at)
{
uint64_t v;
std::memcpy(&v, rt->memory.ram() + at, sizeof(v));
return v;
}
};
void sdkBoundary()
{
Machine m;
// An inaccessible packet address must be irrelevant to native submit/upload/sync.
for (const char *name : {"sceGsPutDrawEnv", "sceGsPutDispEnv", "sceGsExecLoadImage", "sceGsSyncPath"})
{
m.ctx.r[2].ud[0] = 123;
m.call(name, {0x12000000, 0x12000000});
check(m.ctx.r[2].sw[0] == 0, name);
}
std::memset(m.rt->memory.ram() + 0x101000, 0x5a, 256);
bool rejected = false;
try { m.call("sceGsExecStoreImage", {0x12000000, 0x101000}); }
catch (const std::runtime_error &e)
{
rejected = std::strstr(e.what(), "native renderer readback") != nullptr;
}
check(rejected, "readback requires a native implementation without reading a packet");
for (unsigned i = 0; i < 256; ++i)
check(m.rt->memory.ram()[0x101000 + i] == 0x5a, "unsupported readback leaves destination intact");
// SDK output builders remain usable; no separate engine GS state stores their results.
m.call("sceGsResetGraph", {0, 1, 2, 0});
m.call("sceGsSetDefDispEnv", {0x100000, 0, 640, 448, 0, 0});
check(m.word(0x100008) == 1, "interlaced frame display template");
m.call("sceGsResetGraph", {0, 0, 3, 1});
m.call("sceGsSetDefDispEnv", {0x100000, 0, 640, 448, 0, 0});
check(m.word(0x100008) == 2, "progressive display template");
check((m.word(0x100018) & 0xfff) == 656, "PAL template uses SDK video parameters");
m.call("sceGsSetDefDrawEnv", {0x102000, 0, 640, 448, 2, 0});
check(m.ctx.r[2].sw[0] == 8, "draw-template ABI result");
check(m.word(0x102040) == 1 && m.word(0x102050) == 1 && m.word(0x102060) == 0,
"draw template initializes flags without reading old packet contents");
m.libs.io.ctrl = 1;
m.libs.io.channels[2].running = true;
m.libs.io.stat = m.libs.io.cpcondDone = 4;
m.call("sceDmaReset", {0});
check(m.ctx.r[2].sw[0] == 1 && m.libs.io.ctrl == 1, "native DMA reset returns previous enable state");
check(!m.libs.io.channels[2].running && m.libs.io.stat == 0 && m.libs.io.cpcondDone == 0,
"native DMA reset clears completion bookkeeping without accessing devices");
std::array<uint8_t, 20> config{};
for (unsigned i = 4; i < config.size(); ++i) config[i] = static_cast<uint8_t>(i * 7);
std::memcpy(m.rt->memory.ram() + 0x104000, config.data(), config.size());
m.call("sceDmaPutEnv", {0x104000});
check(m.ctx.r[2].sw[0] == 0, "native DMA SDK environment accepted");
for (unsigned field = 0; field < 4; ++field)
{
m.rt->memory.ram()[0x104000 + field] = field == 3 ? 7 : 10;
m.call("sceDmaPutEnv", {0x104000});
check(m.ctx.r[2].sw[0] == -static_cast<int>(field) - 1, "DMA SDK environment validation result");
m.rt->memory.ram()[0x104000 + field] = 0;
}
m.call("sceDmaGetEnv", {0x104100});
check(std::memcmp(m.rt->memory.ram() + 0x104100, config.data(), config.size()) == 0,
"native DMA SDK environment round-trips without device registers");
}
struct Host : bozo::ee::Host
{
void libraryCall(bozo::ee::Dispatcher &, R5900Context *, uint32_t) override { throw std::runtime_error("unexpected library call"); }
void vu0Microprogram(bozo::ee::Dispatcher &, R5900Context *, uint32_t) override { throw std::runtime_error("unexpected VU0 call"); }
void ioRead(bozo::ee::Dispatcher &, R5900Context *, uint32_t, uint32_t, uint64_t[2]) override { throw std::runtime_error("unexpected device read"); }
void ioWrite(bozo::ee::Dispatcher &, R5900Context *, uint32_t, uint32_t, const uint64_t[2]) override { throw std::runtime_error("unexpected device write"); }
void fault(bozo::ee::Dispatcher &, R5900Context *, const std::string &what) override { throw std::runtime_error(what); }
};
struct NativePort : bozo::port::Host
{
bozo::libs::Libraries &l;
explicit NativePort(bozo::libs::Libraries &value) : l(value) {}
bozo::libs::Libraries &libraries() override { return l; }
void frameEnd(Runtime *, R5900Context *) override {}
bool callLibrary(Runtime *, R5900Context *, uint32_t) override { return false; }
bool nativeGraphics() const override { return true; }
};
struct CompletionObserver : bozo::ee::KernelObserver
{
bozo::libs::Libraries &l;
explicit CompletionObserver(bozo::libs::Libraries &value) : l(value) {}
bool dmacStatusSet(uint32_t cause) override { return cause < 3 && l.io.nativeCompleted[cause]; }
};
void nativeJobs()
{
Host host;
bozo::ee::Dispatcher d(host);
bozo::libs::Libraries l;
l.attach(d);
NativePort port(l);
d.runtime().port = &port;
CompletionObserver observer(l);
d.kernel().setObserver(&observer);
d.kernel().addHandler(true, 2, 0x123400, -1, 0, 0, 0);
d.kernel().causeEnable(true, 2, false);
l.io.stat = 0x1234;
l.io.cpcondDone = 0x2345;
auto &old = l.io.channels[2];
old.chcr = old.madr = old.qwc = old.tadr = 0xabcdef;
old.running = true; // a stale compatibility bank must not govern native SDK jobs
R5900Context ctx;
bozo::libs::Guest guest(d.runtime(), &ctx);
for (const char *name : {"sceGsSetDefLoadImage", "sceGsSetDefStoreImage"})
{
// Neither the inaccessible output nor stack arguments may be read: the
// packet has no consumer in native graphics mode.
ctx.r[4].uw[0] = ctx.r[29].uw[0] = 0x12000000;
ctx.r[2].sw[0] = -99;
l.find(name)->handler(l, guest);
check(ctx.r[2].sw[0] == 0, "native image builder retires unused output without touching it");
std::memset(d.runtime().memory.ram() + 0x100000, 0x5a, 256);
ctx.r[4].uw[0] = 0x100000;
l.find(name)->handler(l, guest);
for (unsigned i = 0; i < 256; ++i)
check(d.runtime().memory.ram()[0x100000 + i] == 0x5a, "native image builder leaves a valid output buffer unchanged");
}
ctx.r[4].uw[0] = 0x1000a000;
ctx.r[5].uw[0] = 0x12000000;
l.find("sceDmaSend")->handler(l, guest);
check(!d.kernel().handlerQueued(), "masked native completion callback waits");
d.kernel().causeEnable(true, 2, true);
check(d.kernel().handlerQueued(), "native completion callback survives masking without a device status bank");
ctx.r[5].uw[0] = 0;
l.find("sceDmaSync")->handler(l, guest);
check(ctx.r[2].sw[0] == 0, "native job completion ignores retired channel status");
check(old.chcr == 0xabcdef && old.madr == 0xabcdef && old.qwc == 0xabcdef && old.tadr == 0xabcdef && old.running &&
l.io.stat == 0x1234 && l.io.cpcondDone == 0x2345,
"native jobs do not touch retired DMA registers or completion conditions");
l.find("sceDmaReset")->handler(l, guest);
check(!l.io.nativeCompleted[2], "native reset clears native SDK job completion");
check(l.io.stat == 0x1234 && old.chcr == 0xabcdef, "native reset leaves retired register bank untouched");
}
void completionBoundary()
{
Host host;
bozo::ee::Dispatcher d(host);
bozo::libs::Libraries l;
l.attach(d);
// PRE=1 previously selected the packet-reading/drop path. Both forms now acknowledge
// native work identically. Neither a DMA chain nor a GIF packet executes.
for (uint64_t tag : {0ull, 1ull << 46})
{
const uint32_t dmaTag = 0x10000001;
std::memcpy(d.runtime().memory.ram() + 0x100000, &dmaTag, 4);
std::memcpy(d.runtime().memory.ram() + 0x100010, &tag, 8);
bozo::libs::ioStore(l, 0x1000a030, 4, 0x100000, 0);
bozo::libs::ioStore(l, 0x1000a000, 4, 0x105, 0);
uint32_t pending = 0;
check((bozo::libs::ioLoad(l, 0x1000a000, 4, pending, 0) & 0x100) == 0,
"graphics completion clears busy without parsing PRE");
check((l.io.stat & 4) != 0, "graphics completion acknowledges status");
bozo::libs::ioStore(l, 0x1000e010, 4, 4, 0);
}
bozo::libs::ioStore(l, 0x12000000, 8, 0x1234, 0);
check(bozo::libs::ioKnown(0x12000000, 8, true), "obsolete display store is acknowledged");
l.io.channels[1].chcr = 0x30005;
bozo::libs::ioStore(l, 0x10009000, 1, 0x41, 0);
check(l.io.channels[1].chcr == 0x30041, "byte channel update preserves upper completion flags");
bozo::libs::ioStore(l, 0x10009000, 2, 0x71, 0);
check(l.io.channels[1].chcr == 0x30071, "halfword channel update preserves upper completion flags");
R5900Context ctx;
bozo::libs::Guest guest(d.runtime(), &ctx);
d.kernel().addHandler(true, 1, 0x123400, -1, 0, 0, 0);
for (const char *name : {"sceDmaSend", "sceDmaSendN", "sceDmaSendI"})
for (uint32_t channel : {1u, 2u})
{
const auto *send = l.find(name);
check(send != nullptr, "native SDK submission binding");
if (!send) continue;
auto &state = l.io.channels[channel];
state.madr = 0x1111;
state.tadr = 0x2222;
state.qwc = 0x3333;
ctx.r[4].uw[0] = channel == 1 ? 0x10009000 : 0x1000a000;
ctx.r[5].uw[0] = 0x12000000; // inaccessible source/chain must never be read
ctx.r[6].uw[0] = 0xffffffff;
send->handler(l, guest);
check(!state.running && !(state.chcr & 0x100), "native SDK graphics work completes immediately");
check((l.io.stat & (1u << channel)) != 0, "native SDK completion preserves IRQ status");
check(state.madr == 0x1111 && state.tadr == 0x2222 && state.qwc == 0x3333,
"native SDK does not retain unused packet addresses or lengths");
ctx.r[5].uw[0] = 0;
l.find("sceDmaSync")->handler(l, guest);
check(ctx.r[2].sw[0] == 0, "native graphics sync does not poll a hardware register");
}
check(d.kernel().handlerQueued(), "native submission queues the registered completion handler");
check(l.io.nativeSubmissions[1] == 3 && l.io.nativeSubmissions[2] == 3 && l.io.nativeSynchronizations == 6,
"native graphics service counts all submissions and waits");
bool rejected = false;
ctx.r[4].uw[0] = 0x10009010; // field address, not a channel handle
try { l.find("sceDmaSend")->handler(l, guest); }
catch (const std::runtime_error &) { rejected = true; }
check(rejected, "native SDK rejects an invalid channel handle");
rejected = false;
ctx.r[4].uw[0] = 0x1000c000; // an unrelated producer cannot be silently discarded
try { l.find("sceDmaSend")->handler(l, guest); }
catch (const std::runtime_error &) { rejected = true; }
check(rejected, "native SDK requires a data producer for unsupported channels");
}
}
int main()
{
sdkBoundary();
completionBoundary();
nativeJobs();
std::printf("native graphics boundary: %d failures\n", failures);
return failures ? 1 : 0;
}
+33 -2
View File
@@ -13,7 +13,7 @@ namespace
constexpr float identity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
Screen screen{0, 0, 16, 16};
Renderer &renderer = Renderer::instance();
void quad(Material m, uint32_t colour, float y0 = 0, float y1 = 16)
void quad(Material m, uint32_t colour, float y0 = 0, float y1 = 16, float z = 1)
{
Vertex v[6];
const float xy[6][2] = {{0, y0}, {16, y0}, {0, y1}, {16, y0}, {16, y1}, {0, y1}};
@@ -21,7 +21,7 @@ namespace
{
v[i].x = xy[i][0];
v[i].y = xy[i][1];
v[i].z = 1;
v[i].z = z;
v[i].u = xy[i][0] / 16;
v[i].v = xy[i][1] / 16;
v[i].rgba = colour;
@@ -122,6 +122,37 @@ int main()
quad(destination, 0x40004000);
present();
pixel("source plus destination times source alpha", 16, {64, 128, 0});
// The same asynchronous native depth cache used by game visibility queries. A real
// depth-writing primitive must be distinguishable from the next frame's empty depth.
Screen depthScreen = screen;
depthScreen.depthMax = 1000;
auto depthMaterial = plain;
depthMaterial.depthTest = depthMaterial.depthWrite = true;
renderer.beginFrame(depthScreen);
quad(depthMaterial, 0x80808080, 0, 16, 500);
renderer.wantDepth();
present();
auto expectDepth = [&](uint32_t expected)
{
uint32_t z = ~0u;
for (int attempt = 0; attempt < 100; ++attempt)
{
renderer.wantDepth();
const bool available = renderer.depthAt(8, 8, z);
if (available && std::abs(int(z) - int(expected)) <= 1)
return;
renderer.present(0, 0, 32, 32);
SDL_GL_SwapWindow(window);
SDL_Delay(2);
}
std::printf("FAIL native visibility depth: %u, expected %u\n", z, expected);
++failures;
};
expectDepth(500);
renderer.beginFrame(depthScreen);
quad(plain, 0x80808080);
present();
expectDepth(0);
renderer.releaseGpu();
SDL_GL_DestroyContext(context);
SDL_DestroyWindow(window);