Files
4c733a68c8 3D: back faces culled behind the camera too; M_19_03's view no longer covered (#18)
On M_19_03 (the seafront) the camera at (120.5, -4.5, 10) sits inside one
of the level's untextured boxes (prim 0x6792b0 at (120, 0, -30), 100 x 10 x
90). The IMD programs cull back faces in the object's space (L_2250 /
L_1250), so the PS2 draws nothing of it from inside. The port compared
screen areas and kept every triangle with a corner behind the camera, so
the box's inside faces covered everything below the horizon, the player
too.

The cull (and the outline pass's back-face pick) now takes the determinant
of the corners' (x, y, w): the screen area times the three w, whose sign
holds behind the camera. Triangles wholly in front of the camera are judged
as before.

Compared with PCSX2 from the same start: tools/pcsx2/warp_opening.pnach
makes New Game load 19:3:0, and SBC_WARP_OPENING does the same in the port.
Still different there: the platform top's tint and a paved surface past its
edge (docs/RECOMP_NOTES.md).

Diagnostics: SBC_3D_PICK=<kick>:<x>:<y> (meshes over a pixel, with w),
SBC_TRACE_OBJECTS now prints the camera and the matrices, SBC_TRACE_VERTS,
SBC_TRACE_TEXTURE_FAILS, FRAME in the untextured trace. README screenshot.

Co-authored-by: Thomas Martin <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 01:14:26 +01:00

2146 lines
121 KiB
C++

// Steambot Chronicles' 3D, native: the IMD library's geometry primitives drawn from the game's model data.
//
// ImdCallPrimDrv (0x22e9a0) calls each primitive type's driver (docs/RECOMP_NOTES.md, "The 3D"). The geometry types'
// mode-4 drivers send the primitive's prebuilt VIF batches to a VU1 program; here the batches are read as the game's
// model data instead and drawn by BozoEngine's renderer. No VU program runs and no GS packet is made.
//
// A batch: two GIF tags unpacked to VU1 address 0 (PACKED, NREG 3; NLOOP the strip's vertices), then the vertices
// unpacked at address 2 as V4-16 vectors, NLOOP x stride of them:
// 0: the position (integers; w 0 starts a strip, +1 / -1 the winding)
// 1: the normal (x 1/32768); the first vertex's w x 1/32768 is the batch's position scale
// 2: s, t (x 1/4096, over the texture's 2^TW x 2^TH), q, w
// 3 (type 73): the prelit colour, R, G, B, A (0x80 is 1.0)
// 3, 4 (type 88): the weights of the 8 bone slots (x 1/4096)
// Type 72 / 73 (rigid): +0x10 the DMA `ret` tag of the VIF data; the object's matrix (VU 0-3, from the type-16 driver)
// and world to GS screen (VU 48-51), in the VU staging buffer in the scratchpad (0x70000240), the VU's row order.
// Type 88 (skinned): +0x10 eight bone slots (coordinate indices, -1 unused), +0x30 the tag; the driver's 0x23aea0
// leaves each slot's matrix (the bone's world matrix x its bind matrix) in the scratchpad at slot x 0x40: a native site
// after it skins the vertices (sum of weight x position x bone) and draws them through the screen matrix.
// The texture: the TEXimage the last type-33 material primitive took (its driver's TexGetTEXimage, a native site).
#include "sbc_port.h"
#include "bozo/port.h"
#include "bozo/render/renderer.h"
#include "bozo/render/texture.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <map>
#include <string>
#include <memory>
#include <vector>
namespace sbc::draw3d
{
namespace
{
// SBC_3D_PICK's frame: the first one from the given kick on.
bool pickKick(unsigned long long kick)
{
static unsigned long long chosen = ~0ull;
if (chosen == ~0ull && render::frames() >= kick)
{
chosen = render::frames();
std::printf("[sbc:pick] kick %llu\n", chosen);
}
return render::frames() == chosen;
}
using bozo::render::Material;
using bozo::render::Renderer;
using bozo::render::Texture;
using bozo::render::Vertex;
uint8_t *g_ram = nullptr;
uint32_t rd32(uint32_t a)
{
uint32_t v;
std::memcpy(&v, g_ram + (a & 0x1FFFFFFu), 4);
return v;
}
int16_t rd16(uint32_t a)
{
int16_t v;
std::memcpy(&v, g_ram + (a & 0x1FFFFFFu), 2);
return v;
}
bool trace()
{
static const bool on = std::getenv("SBC_TRACE_3D") != nullptr;
return on;
}
bool off()
{
static const bool on = std::getenv("SBC_3D_OFF") != nullptr;
return on;
}
uint32_t g_textureImage = 0; // the TEXimage the last material primitive took
uint32_t g_currentPrim = 0; // the primitive being drawn (traces)
struct Mesh
{
Material material;
float matrix[16];
std::vector<Vertex> vertices;
std::shared_ptr<const Texture> texture;
uint32_t bucket = 0; // the packet bucket its driver wrote into (gp-0x7e80): the kick sends them in order
};
std::vector<Mesh> g_meshes;
uint32_t g_bucket = 0; // the current packet bucket (DmaBeginPacket 0x25ec40 keeps it at gp-0x7e80)
uint32_t g_gp = 0; // the game's gp, for its IMD globals
uint32_t g_material = 0; // the last type-32 material primitive (+0x10 diffuse, +0x20 emission: VU 56, 57)
// This frame's rigid textured triangles in world space (x, y, z a vertex): the ground under the sea's foam.
std::vector<float> g_worldTriangles;
uint64_t g_primitives = 0, g_triangles = 0, g_skinned = 0;
using Matrix = float[4][4];
// A 4x4 in the VU's order (rows: x, y, z, translation) from the scratchpad, at a byte offset.
void matrixAt(const uint8_t *spr, uint32_t offset, Matrix m) { std::memcpy(m, spr + (offset & 0x3FFFu), 64); }
// Row vectors: (p x A) x B = p x (A B).
void multiply(const Matrix a, const Matrix b, Matrix out)
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
out[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j] + a[i][3] * b[3][j];
}
// VU1 data memory as the game's packets leave it, for what the drivers send through the DMA chain rather than
// the scratchpad staging: the material's VU 56-59 (0x238d70: UNPACK V4-32 of +0x20..+0x40 to 57-59, then
// +0x10 x the global colour to 56; the material animations at 0x234000.. send their 0x380.. copy to 56-59). The
// packets appended at *(gp-0x7d10) since the last look are read as the VIF would; an UNPACK V4-32 without FLG
// writes the shadow. The chain restarts when its buffer is sent (the pointer goes back): read from there on.
// The packets go into 128 buckets (DmaBeginPacket 0x25ec40 switches *(gp-0x7e80); every bucket writes at the same
// pointer, so the buffer interleaves them) and the frame's chain sends bucket 0, then CALLs 1-127 in order
// (DmaFlushPacket 0x25efb0): the VU sees the uploads in that order, not as they were written. Each bucket keeps its
// own shadow (bucketSite parses the chain at every switch); a draw takes a qword from its own bucket, else the
// buckets before it, else what the last frame left. SBC_3D_CHAIN_LINEAR=1: one shadow, the writing order.
struct VuShadow
{
float q[1024][4];
uint32_t stamp[1024]; // the frame (g_vuFrame) that wrote it, 0 never
};
std::vector<VuShadow> g_vuBuckets(128);
VuShadow g_vuCarry{}; // the previous frames' last values (stamp 1: set)
uint32_t g_vuFrame = 1, g_parseBucket = 0;
uint64_t g_vuFrameOf = ~0ull;
bool chainLinear()
{
static const bool linear = std::getenv("SBC_3D_CHAIN_LINEAR") != nullptr;
return linear;
}
// A new frame: the last one's buckets folded in their DMA order into the carry.
void newVuFrame()
{
const uint64_t frame = render::frames();
if (frame == g_vuFrameOf)
return;
g_vuFrameOf = frame;
for (const VuShadow &b : g_vuBuckets)
for (uint32_t n = 0; n < 1024; ++n)
if (b.stamp[n] == g_vuFrame)
{
std::memcpy(g_vuCarry.q[n], b.q[n], 16);
g_vuCarry.stamp[n] = 1;
}
++g_vuFrame;
}
const uint8_t *g_spr = nullptr;
uint32_t g_chainSeen[128] = {}; // a bucket's write pointer when last read (each bucket has its own buffer)
uint64_t g_chainSeenFrame[128] = {}; // the frame (render::frames() + 1) of that read
uint64_t g_chainResets = 0, g_chainUnpacks = 0;
// len bytes at a (the scratchpad at 0x70000000, or with a DMA tag's SPR bit), or null when they run out of it.
const uint8_t *bytesAt(uint32_t a, uint32_t len = 16, bool tagAddress = false)
{
if ((a & 0xF0000000u) == 0x70000000u || (tagAddress && (a & 0x80000000u)))
return g_spr && (a & 0x3FFFu) + len <= 0x4000u ? g_spr + (a & 0x3FFFu) : nullptr;
return (a & 0x1FFFFFFu) + static_cast<uint64_t>(len) <= 0x2000000u ? g_ram + (a & 0x1FFFFFFu) : nullptr;
}
bool traceChain();
void vifStream(const std::vector<uint8_t> &s)
{
uint32_t cl = 1, wl = 1;
size_t i = 0;
const auto word = [&](size_t at) {
uint32_t v;
std::memcpy(&v, s.data() + at, 4);
return v;
};
while (i + 4 <= s.size())
{
const uint32_t code = word(i);
i += 4;
const uint32_t cmd = (code >> 24) & 0x7Fu, num = (code >> 16) & 0xFFu, imm = code & 0xFFFFu;
if ((cmd & 0x60u) == 0x60u)
{
const uint32_t vn = (cmd >> 2) & 3u, vl = cmd & 3u, n = num ? num : 256u;
const uint32_t bits = (32u >> vl) * (vn + 1u) * n;
const size_t bytes = ((bits + 31u) / 32u) * 4u;
if (vn == 3 && vl == 0 && !(imm & 0x8000u) && i + bytes <= s.size())
for (uint32_t k = 0; k < n; ++k)
{
const uint32_t at = ((imm & 0x3FFu) + (wl ? (k / wl) * cl + k % wl : k)) & 0x3FFu;
VuShadow &vu = g_vuBuckets[g_parseBucket];
std::memcpy(vu.q[at], s.data() + i + 16u * k, 16);
vu.stamp[at] = g_vuFrame;
++g_chainUnpacks;
if (at >= 56u && at <= 59u && traceChain())
std::printf("[sbc:chain] UNPACK %08x bucket %u VU%u %g %g %g %g\n", code, g_parseBucket,
at, vu.q[at][0], vu.q[at][1], vu.q[at][2], vu.q[at][3]);
}
i += bytes;
continue;
}
switch (cmd)
{
case 0x01: cl = imm & 0xFFu, wl = (imm >> 8) & 0xFFu; break;
case 0x05:
if (traceChain())
std::printf("[sbc:chain] STMOD %u bucket %u\n", imm & 3u, g_parseBucket);
break;
case 0x20: i += 4; break;
case 0x30:
case 0x31:
if (traceChain() && i + 16 <= s.size())
std::printf("[sbc:chain] %s %08x %08x %08x %08x bucket %u\n", cmd == 0x30u ? "STROW" : "STCOL", word(i),
word(i + 4), word(i + 8), word(i + 12), g_parseBucket);
i += 16;
break;
case 0x4A: i += (num ? num : 256u) * 8u; break;
case 0x50:
case 0x51: i = ((i + 15) & ~size_t(15)) + (imm ? imm : 65536u) * 16u; break;
default: break;
}
}
}
void followChain()
{
if (!g_gp || !g_ram)
return;
newVuFrame();
const uint32_t bucket = rd32(g_gp - 0x7e80u);
g_parseBucket = chainLinear() || bucket >= 128u ? 0u : bucket;
// DmaBeginPacket points *(gp-0x7d10) at the bucket's own buffer (its +0x1c) and *(gp-0x7d20) at that
// buffer's start (+0x18): each bucket is read from where it was left, or from its start in a new frame.
const uint32_t now = rd32(g_gp - 0x7d10u);
uint32_t &seen = g_chainSeen[g_parseBucket];
uint32_t p = seen;
seen = now;
if (uint64_t &frame = g_chainSeenFrame[g_parseBucket]; frame != render::frames() + 1)
{
frame = render::frames() + 1;
if (!chainLinear())
p = 0; // a new frame: the bucket's buffer from its start
}
const auto usable = [&](uint32_t from) { return from && now >= from && now - from <= 0x100000u; };
if (!usable(p) || (!chainLinear() && p < rd32(g_gp - 0x7d20u)))
{
++g_chainResets;
p = chainLinear() ? 0u : rd32(g_gp - 0x7d20u);
if (!usable(p))
return;
}
std::vector<uint8_t> s;
while (p + 16 <= now && s.size() < (4u << 20))
{
const uint8_t *tag = bytesAt(p);
if (!tag)
break;
uint64_t t;
std::memcpy(&t, tag, 8);
const uint32_t qwc = static_cast<uint32_t>(t & 0xFFFFu), id = static_cast<uint32_t>(t >> 28) & 7u;
const uint32_t addr = static_cast<uint32_t>(t >> 32);
// The tag's upper half goes to the VIF (TTE): its two codes, aligned as a qword with NOPs before them.
s.insert(s.end(), 8, 0);
s.insert(s.end(), tag + 8, tag + 16);
const bool inline_ = id == 1 || id == 2 || id == 5 || id == 6 || id == 7;
const uint8_t *data = qwc ? (inline_ ? bytesAt(p + 16, 16u * qwc) : bytesAt(addr, 16u * qwc, true)) : nullptr;
if (data && qwc)
s.insert(s.end(), data, data + 16u * qwc);
p += 16u + (inline_ ? 16u * qwc : 0u);
}
vifStream(s);
}
// SBC_TRACE_CHAIN=<kick>: the materials, uploads and draws of that one kick.
bool traceChain()
{
static const char *e = std::getenv("SBC_TRACE_CHAIN");
static int lines = 0;
static const unsigned long long kick = e ? std::strtoull(e, nullptr, 0) : 0;
return e && render::frames() == kick && lines++ < 40000; // one kick
}
bool traceLit()
{
// SBC_TRACE_LIT=1: every lit vertex; =<prim>,..: those primitives' only.
static const char *e = std::getenv("SBC_TRACE_LIT");
if (!e)
return false;
if (std::strcmp(e, "1") == 0)
return true;
char hex[16];
std::snprintf(hex, sizeof hex, "%x", g_currentPrim);
return std::strstr(e, hex) != nullptr;
}
bool traceStw()
{
static const bool on = std::getenv("SBC_TRACE_STW") != nullptr;
return on;
}
// The VU1 qword n as the chain left it, or null when no packet set it.
const float *vuQword(uint32_t n)
{
followChain();
n &= 0x3FFu;
const uint32_t bucket = rd32(g_gp - 0x7e80u);
for (int b = chainLinear() || bucket >= 128u ? 0 : static_cast<int>(bucket); b >= 0; --b)
if (g_vuBuckets[b].stamp[n] == g_vuFrame)
return g_vuBuckets[b].q[n];
return g_vuCarry.stamp[n] ? g_vuCarry.q[n] : nullptr;
}
// The VU programs' lighting (the IMD microcode's kernels; 0x1f70 for type 88, mode 0 L_25c8 for type 72): the
// staged directions (VU 64-66, a light a column) dotted with the vertex's normal as it is stored (object or bind
// space; the staged lights are the frame's, in world space, the same for every mesh: the PS2 lights that way, so
// the port does too), colour = (ambient VU75 + the sum of max(0, n . L_j) x VU72-74) x the material's diffuse
// (VU 56, 128 = 1.0) + its emission (VU 57). Toon (type 72 with flags 0x800, mode 5: L_2098 / L_2c50): s = 0.5 +
// 0.5 n . L0, t = 0.5 into the material's ramp texture, colour (light 0 + ambient) x 128 x VU108 (VU124 x the
// global colour; 1 on the beach).
struct Lights
{
float direction[3][3]; // [axis][light]
float colour[3][3], ambient[3];
float diffuse[3] = {128, 128, 128}, emission[3] = {0, 0, 0};
bool on = false, toon = false;
uint32_t toonColour = 0x80808080u;
};
Lights lightsOf(const uint8_t *spr, const Matrix object, bool objectSpace = false)
{
Lights l;
static const bool disabled = std::getenv("SBC_3D_NO_LIGHTS") != nullptr;
if (disabled)
return l;
Matrix light, colour;
matrixAt(spr, 0x240u + 64u * 16u, light);
matrixAt(spr, 0x240u + 72u * 16u, colour);
static const bool turned = std::getenv("SBC_3D_LIGHTS_OBJECT") != nullptr; // a diagnostic: by the object's rows
static const float sign = std::getenv("SBC_3D_LIGHTS_NEGATE") ? -1.0f : 1.0f; // a diagnostic
const bool raw = !(objectSpace || turned);
for (int i = 0; i < 3; ++i)
{
const float length = std::sqrt(object[i][0] * object[i][0] + object[i][1] * object[i][1] + object[i][2] * object[i][2]);
const float k = length > 0 ? 1.0f / length : 0.0f;
for (int j = 0; j < 3; ++j)
l.direction[i][j] = sign * (raw ? light[i][j]
: k * (object[i][0] * light[0][j] + object[i][1] * light[1][j] + object[i][2] * light[2][j]));
}
for (int j = 0; j < 3; ++j)
for (int c = 0; c < 3; ++c)
l.colour[j][c] = colour[j][c];
for (int c = 0; c < 3; ++c)
l.ambient[c] = colour[3][c];
// The material's diffuse and emission (VU 56, 57) as the kernels apply them, as the chain sent them
// (vuQword). SBC_3D_NO_LIT_MATERIAL=1 leaves them at 1.0 and 0; SBC_3D_LIT_MATERIAL=1 takes them from the
// last material primitive or the staging instead (a diagnostic: not the mesh's own).
static const bool noMaterial = std::getenv("SBC_3D_NO_LIT_MATERIAL") != nullptr; // a diagnostic
static const bool useMaterial = std::getenv("SBC_3D_LIT_MATERIAL") != nullptr; // a diagnostic
const float *sentDiffuse = vuQword(56), *sentEmission = vuQword(57);
if (!noMaterial && !useMaterial && sentDiffuse && sentEmission)
for (int c = 0; c < 3; ++c)
{
l.diffuse[c] = sentDiffuse[c] >= 0 && sentDiffuse[c] < 1024 ? sentDiffuse[c] : 128.0f;
l.emission[c] = sentEmission[c] >= 0 && sentEmission[c] < 1024 ? sentEmission[c] : 0.0f;
}
if (useMaterial)
{
// From the material primitive itself (the staging slot is reused before the skinned driver's site).
float d[4], e[4];
if (g_material && g_ram)
{
std::memcpy(d, g_ram + ((g_material + 0x10u) & 0x1FFFFF0u), 16);
std::memcpy(e, g_ram + ((g_material + 0x20u) & 0x1FFFFF0u), 16);
}
else
{
std::memcpy(d, spr + 0x240u + 56u * 16u, 16);
std::memcpy(e, spr + 0x240u + 57u * 16u, 16);
}
for (int c = 0; c < 3; ++c)
{
l.diffuse[c] = d[c] >= 0 && d[c] < 1024 ? d[c] : 128.0f;
l.emission[c] = e[c] >= 0 && e[c] < 1024 ? e[c] : 0.0f;
}
}
l.on = true;
return l;
}
// The rigid programs (MPG 0x3cd3f0: types 72, 73 and the morph's) never load the lights themselves: their
// kernels use vf5-vf7 as the object's setup program (address 0, run with its matrix) left them, the staged
// lights (VU 64-67) turned into the object's space by its normalized rows (0x01f0-0x02b8, also kept at VU 68-70).
// The skinned program (0x3c9400) loads VU 64-66 as they are (L_0e98). SBC_3D_RIGID_LIGHTS_RAW=1: raw for both.
bool rigidLightsTurned()
{
static const bool raw = std::getenv("SBC_3D_RIGID_LIGHTS_RAW") != nullptr; // a diagnostic
return !raw;
}
// The program entry's mode bits: the drivers index their entry tables by (the IMD state's +0x64 halfword | the
// primitive's flags +8) & 0x3f (0x2361a0 / 0x2361e0 for type 88, 0x42ade0 for 72 / 73). Bit 3 picks mode 1 (vi2 1:
// L_20c8 in 0x3c9400, L_2720 in 0x3cd3f0), which does not light: VU 56 x the s, t vector's w + VU 57.
uint32_t modeBits(uint32_t prim)
{
uint32_t bits = rd32(prim + 8);
if (const uint32_t state = g_gp ? rd32(g_gp - 0x7d5cu) : 0; state)
if (const uint8_t *q = bytesAt(state + 0x64u, 2))
bits |= static_cast<uint32_t>(q[0]) | static_cast<uint32_t>(q[1]) << 8;
return bits;
}
// Mode 1 as lit() computes it: no light, an ambient of 1.0 (lit() then gives diffuse x w + emission).
// SBC_3D_MODE1_LIT=1 lights those meshes as mode 0 (a diagnostic, the earlier choice).
void unlitMode(Lights &l, uint32_t prim)
{
static const bool lit = std::getenv("SBC_3D_MODE1_LIT") != nullptr;
if (lit || !l.on || !(modeBits(prim) & 8u))
return;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
l.direction[i][j] = l.colour[i][j] = 0;
for (float &a : l.ambient)
a = 1.0f;
}
// Toon shading for a type-72 primitive with flags 0x800.
// VU108 is the geometry driver's (0x230a48): the qword at *(gp-0x7c60) + 0x7c0 (+0x10 with flags 0x1000, +0x20
// with 0x2000000; 0x22fc30 copies the IMD state's +0x40 / +0x50 to the second and third) x the global colour.
void makeToon(Lights &l, const uint8_t *spr, uint32_t flags)
{
float vu124[4], global[4] = {1, 1, 1, 1};
std::memcpy(vu124, spr + 0x240u + 124u * 16u, 16);
static const bool staged = std::getenv("SBC_3D_TOON_STAGED") != nullptr; // a diagnostic: the staging's VU124
if (const uint32_t table = g_gp ? rd32(g_gp - 0x7c60u) : 0; table && !staged)
if (const uint8_t *q = bytesAt(table + 0x7c0u + ((flags & 0x1000u) ? 0x10u : 0u) + ((flags & 0x2000000u) ? 0x20u : 0u)))
std::memcpy(vu124, q, 16);
if (traceChain())
std::printf("[sbc:chain] toon %08x flags %08x TEXimage %08x colour %g %g %g %g light0 %g %g %g ambient %g %g %g\n",
g_currentPrim, flags, g_textureImage, vu124[0], vu124[1], vu124[2], vu124[3], l.colour[0][0],
l.colour[0][1], l.colour[0][2], l.ambient[0], l.ambient[1], l.ambient[2]);
const uint32_t state = g_gp ? rd32(g_gp - 0x7d5cu) : 0;
if (state)
{
if ((state & 0xF0000000u) == 0x70000000u)
std::memcpy(global, spr + ((state + 0x30u) & 0x3FF0u), 16);
else
std::memcpy(global, g_ram + ((state + 0x30u) & 0x1FFFFF0u), 16);
}
l.toon = true;
l.toonColour = 0x80000000u;
for (int c = 0; c < 3; ++c)
{
const float g = global[c] >= 0 && global[c] < 4 ? global[c] : 1.0f, m = vu124[c] >= 0 && vu124[c] < 4 ? vu124[c] : 1.0f;
const float v = (l.colour[0][c] + l.ambient[c]) * 128.0f * m * g;
l.toonColour |= static_cast<uint32_t>(v < 0 ? 0 : v > 255 ? 255 : v) << (8 * c);
}
}
uint32_t lit(const Lights &l, const float n[3], float stw = 1.0f)
{
float rgb[3] = {l.ambient[0], l.ambient[1], l.ambient[2]};
for (int j = 0; j < 3; ++j)
{
const float d = n[0] * l.direction[0][j] + n[1] * l.direction[1][j] + n[2] * l.direction[2][j];
if (d > 0)
for (int c = 0; c < 3; ++c)
rgb[c] += d * l.colour[j][c];
if (static int traced = 0; traceLit() && traced < 3000 && traceChain() && ++traced)
std::printf("[sbc:lit] %08x n %.2f %.2f %.2f L%d %.2f %.2f %.2f C %.2f %.2f %.2f d %.2f\n", g_currentPrim,
n[0], n[1], n[2], j, l.direction[0][j], l.direction[1][j], l.direction[2][j],
l.colour[j][0], l.colour[j][1], l.colour[j][2], d);
}
uint32_t out = 0x80000000u;
for (int c = 0; c < 3; ++c)
{
const float v = rgb[c] * l.diffuse[c] * stw + l.emission[c];
out |= static_cast<uint32_t>(v < 0 ? 0 : v > 255 ? 255 : v) << (8 * c);
}
if (static int traced = 0; traceLit() && traced < 3000 && traceChain() && ++traced)
std::printf("[sbc:lit] %08x ambient %.2f diffuse %.1f w %.3f emission %.1f -> %08x\n", g_currentPrim, l.ambient[0],
l.diffuse[0], stw, l.emission[0], out);
return out;
}
// The material's colour as the VU program takes it: the type-32 primitive's diffuse (VU 56 in the staging buffer,
// 128 = 1.0) times the global colour (*(gp-0x7d5c) + 0x30, ImdSetColor 0x22e0e0; the game's fades). Its alpha
// scales every vertex's (a faded object, the camera's occluders); its colour the lit vertices'.
struct MaterialColour
{
float rgba[4] = {1, 1, 1, 1};
};
MaterialColour materialColourOf(const uint8_t *spr, uint32_t gp)
{
MaterialColour m;
static const bool disabled = std::getenv("SBC_3D_NO_MATERIAL") != nullptr;
if (disabled)
return m;
float diffuse[4], global[4];
std::memcpy(diffuse, spr + 0x240u + 56u * 16u, 16);
// As the chain sent it (0x238d70 already multiplied it by the global colour).
static const bool staged = std::getenv("SBC_3D_MATERIAL_STAGED") != nullptr; // a diagnostic
if (const float *sent = vuQword(56); sent && !staged)
{
for (int c = 0; c < 4; ++c)
m.rgba[c] = sent[c] >= 0 && sent[c] < 512 ? sent[c] / 128.0f : 1.0f;
return m;
}
const uint32_t state = rd32(gp - 0x7d5cu);
if ((state & 0xF0000000u) == 0x70000000u) // the IMD state may live in the scratchpad
std::memcpy(global, spr + ((state + 0x30u) & 0x3FF0u), 16);
else
std::memcpy(global, g_ram + ((state + 0x30u) & 0x1FFFFFFu), 16);
if (static int traced = 0; SBC_ENV("SBC_TRACE_MATERIAL") && traced++ < 12)
std::printf("[sbc:3d] material diffuse %g %g %g %g global %g %g %g %g (%08x %08x)\n", diffuse[0], diffuse[1],
diffuse[2], diffuse[3], global[0], global[1], global[2], global[3], rd32(state + 0x30u), rd32(state + 0x3cu));
for (int c = 0; c < 4; ++c)
{
const float d = diffuse[c] / 128.0f, g = global[c];
m.rgba[c] = (d >= 0 && d < 4 ? d : 1.0f) * (g >= 0 && g < 4 ? g : 1.0f);
}
return m;
}
uint32_t withMaterial(uint32_t rgba, const MaterialColour &m, bool colour)
{
uint32_t out = 0;
for (int c = 0; c < 4; ++c)
{
float v = static_cast<float>((rgba >> (8 * c)) & 0xFFu);
if (c == 3 || colour)
v *= m.rgba[c];
out |= static_cast<uint32_t>(v < 0 ? 0 : v > 255 ? 255 : v) << (8 * c);
}
return out;
}
// The current material's texture and how its s, t map onto the decoded image.
struct MaterialTexture
{
std::shared_ptr<const Texture> texture;
float uScale = 1.0f, vScale = 1.0f;
bool alpha = true; // TEX0.TCC
};
MaterialTexture materialTexture()
{
MaterialTexture t;
if (!g_textureImage)
return t;
t.texture = draw2d::textureOfImage(g_ram, g_textureImage);
// SBC_DUMP_TEXTURE=<TEXimage>: the decoded texture to build/texture_<TEXimage>.ppm, once (a diagnostic);
// SBC_DUMP_TEXTURE=ramps: every 16-texel-high texture (the toon ramps), once each; =all: every texture.
static const char *dumpWhich = std::getenv("SBC_DUMP_TEXTURE");
static std::map<uint32_t, bool> dumpedImages;
if (dumpWhich && t.texture &&
(std::strcmp(dumpWhich, "all") == 0 ||
(std::strcmp(dumpWhich, "ramps") == 0 ? t.texture->height == 16 : std::strtoul(dumpWhich, nullptr, 16) == g_textureImage)))
if (bool &dumped = dumpedImages[g_textureImage]; !dumped)
{
dumped = true;
char name[64];
std::snprintf(name, sizeof name, "build/texture_%08x.ppm", g_textureImage);
if (FILE *f = std::fopen(name, "wb"))
{
std::fprintf(f, "P6 %u %u 255\n", t.texture->width, t.texture->height);
for (uint32_t c : t.texture->rgba)
{
const unsigned char px[3] = {static_cast<unsigned char>(c), static_cast<unsigned char>(c >> 8),
static_cast<unsigned char>(c >> 16)};
std::fwrite(px, 1, 3, f);
}
std::fclose(f);
}
// Its alpha (0x80 opaque) as a grey image beside it.
std::snprintf(name, sizeof name, "build/texture_%08x_alpha.pgm", g_textureImage);
if (FILE *f = std::fopen(name, "wb"))
{
std::fprintf(f, "P5 %u %u 255\n", t.texture->width, t.texture->height);
for (uint32_t c : t.texture->rgba)
{
const unsigned char a = static_cast<unsigned char>(c >> 24);
std::fwrite(&a, 1, 1, f);
}
std::fclose(f);
}
}
if (!t.texture)
return t;
uint64_t tex0;
std::memcpy(&tex0, g_ram + ((g_textureImage + 0x20u) & 0x1FFFFFFu), 8);
const uint32_t tw = static_cast<uint32_t>(tex0 >> 26) & 15u, th = static_cast<uint32_t>(tex0 >> 30) & 15u;
t.alpha = ((tex0 >> 34) & 1u) != 0;
if (static const bool tfx = std::getenv("SBC_TRACE_TFX") != nullptr; tfx)
{
static std::map<uint32_t, bool> seen;
if (!seen[g_textureImage])
{
seen[g_textureImage] = true;
uint64_t sum = 0;
for (uint32_t c : t.texture->rgba)
sum += (c & 0xFF) + ((c >> 8) & 0xFF) + ((c >> 16) & 0xFF);
std::printf("[sbc:tfx] prim %08x type %u TEXimage %08x TEX0 %016llx TFX %u TCC %u %ux%u mean %llu\n",
g_currentPrim, rd32(g_currentPrim), g_textureImage, static_cast<unsigned long long>(tex0),
static_cast<unsigned>((tex0 >> 35) & 3u), static_cast<unsigned>((tex0 >> 34) & 1u),
t.texture->width, t.texture->height,
static_cast<unsigned long long>(sum / (3 * std::max<size_t>(1, t.texture->rgba.size()))));
}
}
t.uScale = static_cast<float>(1u << tw) / static_cast<float>(t.texture->width);
t.vScale = static_cast<float>(1u << th) / static_cast<float>(t.texture->height);
return t;
}
// Each batch of the VIF data whose DMA tag is at `tag`: its vertex count, stride (vectors) and first vector's
// address, handed to `take`.
template <class Take> void batches(uint32_t tag, Take &&take)
{
const uint32_t end = tag + 0x10 + (rd32(tag) & 0xFFFFu) * 16u;
uint32_t at = tag + 8, nloop = 0, prim = 0;
while (at < end)
{
const uint32_t code = rd32(at), cmd = (code >> 24) & 0x7Fu, imm = code & 0xFFFFu, num = (code >> 16) & 0xFFu;
if (static const bool codes = std::getenv("SBC_TRACE_VIF_CODES") != nullptr; codes && traceChain())
std::printf("[sbc:chain] VIF %08x at %08x: %08x %08x %08x %08x\n", code, at, rd32(at + 4), rd32(at + 8),
rd32(at + 12), rd32(at + 16));
at += 4;
if (cmd >= 0x60u)
{
const uint32_t vn = (cmd >> 2) & 3u, vl = cmd & 3u, n = num ? num : 256u;
const uint32_t bits = vl == 3u ? 16u : (32u >> vl) * (vn + 1u);
const uint32_t words = (n * bits + 31u) / 32u;
if (cmd == 0x6Cu && (imm & 0x3FFu) == 0) // the batch's GIF tags: NLOOP, PRIM
{
nloop = rd32(at) & 0x7FFFu;
prim = (rd32(at + 4) >> 15) & 0x7FFu;
if (traceChain())
std::printf("[sbc:chain] batch %08x GIF tag %08x %08x %08x %08x PRE %u PRIM %03x\n", g_currentPrim,
rd32(at), rd32(at + 4), rd32(at + 8), rd32(at + 12), (rd32(at + 4) >> 14) & 1u, prim);
}
else if (cmd == 0x6Du && nloop && n >= nloop * 3u) // the vertices
take(nloop, n / nloop, at, prim);
at += words * 4u;
continue;
}
if (cmd == 0x20u)
at += 4;
else if (cmd == 0x30u || cmd == 0x31u)
at += 16;
else if (cmd == 0x4Au)
at += (num ? num : 256u) * 8u;
else if (cmd == 0x50u || cmd == 0x51u)
at += (imm ? imm : 65536u) * 16u;
}
}
// A batch's strip as triangles, each vertex placed by `position(vertex address, scale, out)`.
template <class Position>
void strip(uint32_t count, uint32_t stride, uint32_t at, const MaterialTexture &t, const Lights &lights,
const MaterialColour &material, std::vector<Vertex> &triangles, Position &&position, uint32_t stAt = 16)
{
const uint32_t bytes = stride * 8u;
const float scale = static_cast<float>(rd16(at + 8 + 6)) / 32768.0f;
// SBC_TRACE_VERTS=<primitive>: its batches' first vertices as the VIF data holds them, once each (a diagnostic).
if (const char *e = SBC_ENV("SBC_TRACE_VERTS"); e && std::strtoul(e, nullptr, 16) == g_currentPrim)
if (static int printed = 0; printed++ < 6)
{
std::printf("[sbc:verts] %08x batch %u vertices stride %u at %08x:\n", g_currentPrim, count, stride, at);
for (uint32_t i = 0; i < count && i < 4; ++i)
{
std::printf("[sbc:verts] ");
for (uint32_t w = 0; w < stride * 4; ++w)
std::printf(" %5d", static_cast<int16_t>(rd16(at + i * bytes + w * 2)));
std::printf("\n");
}
}
std::vector<Vertex> s(count);
for (uint32_t i = 0; i < count; ++i)
{
const uint32_t v = at + i * bytes;
Vertex &o = s[i];
float normal[3] = {rd16(v + 8) / 32768.0f, rd16(v + 10) / 32768.0f, rd16(v + 12) / 32768.0f};
position(v, scale, o, normal);
o.u = rd16(v + stAt) / 4096.0f * t.uScale;
o.v = rd16(v + stAt + 2) / 4096.0f * t.vScale;
// The s, t vector's w (ITOF12): the kernels scale the lit colour by it (L_1f70: VU56 x w; the toon's too).
static const bool noStw = std::getenv("SBC_3D_NO_STW") != nullptr; // a diagnostic
const float stw = noStw ? 1.0f : rd16(v + stAt + 6) / 4096.0f;
if (static int traced = 0; traceStw() && lights.on && traced++ < 4000)
std::printf("[sbc:stw] %08x %g\n", g_currentPrim, stw);
static const bool noPrelit = std::getenv("SBC_3D_NO_PRELIT") != nullptr; // a diagnostic
static const bool noVertexColour = std::getenv("SBC_3D_NO_VERTEX_COLOUR") != nullptr; // a diagnostic
if (stride == 4 && !noPrelit) // type 73's prelit colour: 0x80 is 1.0, up to 0xFF (2.0) and past it
{
o.rgba = 0;
for (uint32_t c = 0; c < 4; ++c)
{
const int32_t value = rd16(v + 24 + 2 * c);
o.rgba |= static_cast<uint32_t>(value < 0 ? 0 : value > 255 ? 255 : value) << (8 * c);
}
if (static int traced = 0; SBC_ENV("SBC_TRACE_PRELIT") && traced++ < 40)
std::printf("[sbc:prelit] %d %d %d %d\n", rd16(v + 24), rd16(v + 26), rd16(v + 28), rd16(v + 30));
}
else if (stride == 3 && !lights.on && !noVertexColour)
{
// Type 72's second vector is the vertex's baked colour (R, G, B, 0x80 = 1.0; w the batch's scale),
// not a normal: the sand darker toward the sea, the shade under the rocks.
o.rgba = 0x80000000u;
for (uint32_t c = 0; c < 3; ++c)
{
const int32_t value = rd16(v + 8 + 2 * c);
o.rgba |= static_cast<uint32_t>(value < 0 ? 0 : value > 255 ? 255 : value) << (8 * c);
}
}
else if (lights.toon)
{
const float d = normal[0] * lights.direction[0][0] + normal[1] * lights.direction[1][0] +
normal[2] * lights.direction[2][0];
o.u = (0.5f + 0.5f * d) * t.uScale;
o.v = 0.5f * t.vScale;
o.rgba = 0x80000000u;
for (int c = 0; c < 3; ++c)
{
const float value = static_cast<float>((lights.toonColour >> (8 * c)) & 0xFFu) * stw;
o.rgba |= static_cast<uint32_t>(value < 0 ? 0 : value > 255 ? 255 : value) << (8 * c);
}
}
else if (lights.on)
o.rgba = lit(lights, normal, stw);
else
o.rgba = 0x80808080u;
// The material gives the alpha (VU 56.w); its colour is in lit() already.
o.rgba = withMaterial(o.rgba, material, false);
}
for (uint32_t i = 2; i < count; ++i)
{
const int16_t flag = rd16(at + i * bytes + 6);
if (flag == 0) // a strip starts here
continue;
// The flag's sign is the triangle's winding (the VU program's culling): the triangles are kept with one
// winding, so that the outlines can tell their back faces.
triangles.push_back(s[flag < 0 ? i - 1 : i - 2]);
triangles.push_back(s[flag < 0 ? i - 2 : i - 1]);
triangles.push_back(s[i]);
}
}
// A GS register as the game's shadows hold it (*(gp-0x7cb8) + reg x 8, sent with its packets): what the
// material's driver set for the draw that follows (0x22f8d0: ALPHA_1, TEST_1, ZBUF_1; FOGCOL).
uint64_t gsRegister(const uint8_t *spr, uint32_t reg)
{
if (!g_gp || !spr)
return 0;
const uint32_t at = rd32(g_gp - 0x7cb8u) + reg * 8u;
uint64_t v;
if ((at & 0xF0000000u) == 0x70000000u) // in the scratchpad
std::memcpy(&v, spr + (at & 0x3FF8u), 8);
else
std::memcpy(&v, g_ram + (at & 0x1FFFFF8u), 8);
return v;
}
void keep(const Matrix matrix, const MaterialTexture &t, std::vector<Vertex> &&triangles, bool textured,
const uint8_t *spr, bool fogged, bool lit = false)
{
// PRIM without TME: no texture; the colour is the material's (VU 56, 128 = 1.0), its alpha too (the blob
// shadows under the characters, the dark sheets). A lit mesh's colours have VU 56 in them already (the
// kernels' colour does not depend on TME); a baked one's are the vertex's own (L_29f0: VU 56's alpha only). SBC_3D_UNTEXTURED_MATERIAL_TWICE=1: again (a diagnostic).
static const bool twice = std::getenv("SBC_3D_UNTEXTURED_MATERIAL_TWICE") != nullptr;
if (!textured && spr && (!lit || twice))
{
// The vertex's own colour (0x80 = 1.0) times the material's.
float diffuse[4];
std::memcpy(diffuse, spr + 0x240u + 56u * 16u, 16);
static const bool staged = std::getenv("SBC_3D_MATERIAL_STAGED") != nullptr; // a diagnostic
if (const float *sent = vuQword(56); sent && !staged)
std::memcpy(diffuse, sent, 16);
if (SBC_ENV("SBC_3D_UNTEXTURED_NO_MATERIAL")) // a diagnostic
for (float &d : diffuse)
d = 128.0f;
for (Vertex &v : triangles)
{
uint32_t rgba = 0;
for (int c = 0; c < 4; ++c)
{
const float d = diffuse[c] * static_cast<float>((v.rgba >> (8 * c)) & 0xFFu) / 128.0f;
rgba |= static_cast<uint32_t>(d < 0 ? 0 : d > 255 ? 255 : d) << (8 * c);
}
v.rgba = rgba;
}
}
// PRIM's FGE: the VU program's F is clamp(VU78.z + VU78.w / w, VU78.x, VU78.y) (0..255, 255 no fog); the GS
// takes the colour toward FOGCOL by 1 - F / 255.
// The IMD programs the game uses (MPG 0x3cd3f0 for types 72 / 73, 0x3c9400 for 88) leave every vertex at
// F = 0xff (L_2250: XYZF's F 0xff; the VU78 kernel sits behind a vi2 bit no entry sets): no GS fog, whatever
// PRIM's FGE and FOGCOL say. The distance haze is the screen effect (screenEffects). SBC_3D_GS_FOG=1 applies it.
static const bool gsFog = std::getenv("SBC_3D_GS_FOG") != nullptr; // a diagnostic
const bool fog = fogged && spr && gsFog;
if (fog)
{
float f[4];
std::memcpy(f, spr + 0x240u + 78u * 16u, 16);
for (Vertex &v : triangles)
{
const float w = v.x * matrix[0][3] + v.y * matrix[1][3] + v.z * matrix[2][3] + matrix[3][3];
float F = w > 0 ? f[2] + f[3] / w : f[1];
F = F < f[0] ? f[0] : F > f[1] ? f[1] : F;
v.fog = F / 255.0f;
}
}
// Triangles reaching behind the camera: the VU program clips them; drawn as they are, the divide by w turns
// them across the screen. They are clipped here against w = the near distance (w is linear in the object's
// space, so the cut vertices interpolate there); a triangle keeps 0, 1 or 2 pieces.
static const float nearW = [] {
const char *e = std::getenv("SBC_3D_NEAR");
return e ? static_cast<float>(std::atof(e)) : 0.5f;
}();
const auto wOf = [&](const Vertex &v) {
return v.x * matrix[0][3] + v.y * matrix[1][3] + v.z * matrix[2][3] + matrix[3][3];
};
const auto cut = [](const Vertex &a, const Vertex &b, float f) {
Vertex o = a;
o.x = a.x + (b.x - a.x) * f;
o.y = a.y + (b.y - a.y) * f;
o.z = a.z + (b.z - a.z) * f;
o.u = a.u + (b.u - a.u) * f;
o.v = a.v + (b.v - a.v) * f;
o.fog = a.fog + (b.fog - a.fog) * f;
o.q = a.q + (b.q - a.q) * f;
o.rgba = 0;
for (int c = 0; c < 4; ++c)
{
const float ca = static_cast<float>((a.rgba >> (8 * c)) & 0xFFu);
const float cb = static_cast<float>((b.rgba >> (8 * c)) & 0xFFu);
o.rgba |= static_cast<uint32_t>(ca + (cb - ca) * f + 0.5f) << (8 * c);
}
return o;
};
std::vector<Vertex> pieces;
size_t kept = 0;
for (size_t i = 0; i + 2 < triangles.size(); i += 3)
{
const Vertex tri[3] = {triangles[i], triangles[i + 1], triangles[i + 2]};
const float w[3] = {wOf(tri[0]), wOf(tri[1]), wOf(tri[2])};
const int front = (w[0] > nearW) + (w[1] > nearW) + (w[2] > nearW);
if (front == 3)
{
if (kept != i)
for (size_t k = 0; k < 3; ++k)
triangles[kept + k] = tri[k];
kept += 3;
continue;
}
if (front == 0)
continue;
// The polygon in front of the plane, in the triangle's order (its winding kept).
Vertex poly[4];
int n = 0;
for (int k = 0; k < 3; ++k)
{
const int l = (k + 1) % 3;
const bool inK = w[k] > nearW, inL = w[l] > nearW;
if (inK)
poly[n++] = tri[k];
if (inK != inL)
poly[n++] = cut(tri[k], tri[l], (nearW - w[k]) / (w[l] - w[k]));
}
for (int k = 1; k + 1 < n; ++k)
{
pieces.push_back(poly[0]);
pieces.push_back(poly[k]);
pieces.push_back(poly[k + 1]);
}
}
triangles.resize(kept);
triangles.insert(triangles.end(), pieces.begin(), pieces.end());
if (triangles.empty())
return;
// SBC_3D_PICK=<kick>:<x>:<y>: in the first frame from that kick on, each mesh with a triangle over the screen
// pixel (x, y) of 640 x 448 (the GS's 1728 + x, 1824 + y), after the near clip and the cull: which primitive
// draws there, and at what w (a diagnostic).
if (static const char *pick = std::getenv("SBC_3D_PICK"); pick)
{
unsigned long long kick = 0;
float px = 0, py = 0;
if (std::sscanf(pick, "%llu:%f:%f", &kick, &px, &py) == 3 && pickKick(kick))
{
const float gx = 1728.0f + px, gy = 1824.0f + py;
for (size_t i = 0; i + 2 < triangles.size(); i += 3)
{
float sx[3], sy[3], sw[3];
bool behind = false;
for (int c = 0; c < 3; ++c)
{
const Vertex &v = triangles[i + c];
const float w = v.x * matrix[0][3] + v.y * matrix[1][3] + v.z * matrix[2][3] + matrix[3][3];
behind = behind || w <= 0;
sw[c] = w;
sx[c] = (v.x * matrix[0][0] + v.y * matrix[1][0] + v.z * matrix[2][0] + matrix[3][0]) / w;
sy[c] = (v.x * matrix[0][1] + v.y * matrix[1][1] + v.z * matrix[2][1] + matrix[3][1]) / w;
}
if (behind)
continue;
const auto edge = [&](int a, int b) { return (sx[b] - sx[a]) * (gy - sy[a]) - (sy[b] - sy[a]) * (gx - sx[a]); };
const float e0 = edge(0, 1), e1 = edge(1, 2), e2 = edge(2, 0);
if (!((e0 >= 0 && e1 >= 0 && e2 >= 0) || (e0 <= 0 && e1 <= 0 && e2 <= 0)))
continue;
const Vertex &v = triangles[i];
std::printf("[sbc:pick] w %.2f %.2f %.2f bucket %u fogged %d\n", sw[0], sw[1], sw[2], g_bucket, fogged ? 1 : 0);
std::printf("[sbc:pick] prim %08x type %u flags %08x TEXimage %08x textured %d lit %d: %zu triangles, "
"hit (%.0f,%.0f) (%.0f,%.0f) (%.0f,%.0f) rgba %08x uv %.3f %.3f / %.3f %.3f / %.3f %.3f\n",
g_currentPrim, rd32(g_currentPrim), rd32(g_currentPrim + 8), g_textureImage, textured ? 1 : 0,
lit ? 1 : 0, triangles.size() / 3, sx[0] - 1728, sy[0] - 1824, sx[1] - 1728, sy[1] - 1824,
sx[2] - 1728, sy[2] - 1824, v.rgba, triangles[i].u, triangles[i].v, triangles[i + 1].u,
triangles[i + 1].v, triangles[i + 2].u, triangles[i + 2].v);
break;
}
}
}
// SBC_TRACE_BIG=<kick>: the meshes with a triangle over 20,000 pixels on screen (what covers the view).
if (const char *e = SBC_ENV("SBC_TRACE_BIG"); e && render::frames() == std::strtoull(e, nullptr, 0))
{
float biggest = 0;
for (size_t i = 0; i + 2 < triangles.size(); i += 3)
{
float sx[3], sy[3];
for (int k = 0; k < 3; ++k)
{
const Vertex &v = triangles[i + k];
const float w = v.x * matrix[0][3] + v.y * matrix[1][3] + v.z * matrix[2][3] + matrix[3][3];
sx[k] = (v.x * matrix[0][0] + v.y * matrix[1][0] + v.z * matrix[2][0] + matrix[3][0]) / w;
sy[k] = (v.x * matrix[0][1] + v.y * matrix[1][1] + v.z * matrix[2][1] + matrix[3][1]) / w;
}
const float area = std::fabs((sx[1] - sx[0]) * (sy[2] - sy[0]) - (sx[2] - sx[0]) * (sy[1] - sy[0])) / 2;
biggest = area > biggest ? area : biggest;
}
if (biggest > 20000)
std::printf("[sbc:big] prim %08x flags %08x TEXimage %08x tcc %d vertex rgba %08x biggest %.0f px, %zu triangles\n",
g_currentPrim, rd32(g_currentPrim + 8), g_textureImage, t.alpha ? 1 : 0, triangles[0].rgba,
biggest, triangles.size() / 3);
}
// SBC_3D_FALSE_COLOUR=1: every mesh untextured in a colour made from its TEXimage (which texture draws what).
if (static const bool falseColour = std::getenv("SBC_3D_FALSE_COLOUR") != nullptr; falseColour)
{
const uint32_t h = (g_textureImage * 2654435761u) | 0x80000000u;
for (Vertex &v : triangles)
v.rgba = (h & 0x7F7F7F) | 0x80000000u;
if (static uint32_t printed = 0; SBC_ENV("SBC_TRACE_BIG") && printed++ < 400)
std::printf("[sbc:colour] TEXimage %08x -> %06x\n", g_textureImage, (h & 0x7F7F7F) * 2);
}
Mesh mesh;
mesh.bucket = g_bucket;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
mesh.matrix[4 * i + j] = matrix[i][j];
static const bool falseColourMode = std::getenv("SBC_3D_FALSE_COLOUR") != nullptr;
mesh.texture = falseColourMode || !textured ? nullptr : t.texture;
Material &m = mesh.material;
m.textured = mesh.texture != nullptr;
// PRIM without TME: the GS draws the vertex colour as it is (0x80 is 128 of 255, not the modulation's 1.0).
// SBC_3D_UNTEXTURED_DOUBLED=1: as a modulation, twice as bright (a diagnostic, the earlier choice).
static const bool doubled = std::getenv("SBC_3D_UNTEXTURED_DOUBLED") != nullptr;
m.directColour = !textured && !falseColourMode && !doubled;
// The GS state the material's driver left: ALPHA (0x44 (Cs - Cd) As + Cd; 0x48 Cs As + Cd, the glows; 0x42
// Cd - Cs As, the shadows), ZBUF's ZMSK (no depth written), FOGCOL. Texels with no alpha are not drawn (the
// GS's alpha test: cut-outs).
const uint64_t alphaRegister = gsRegister(spr, 0x42), zbuf = gsRegister(spr, 0x4e);
// FRAME's FBMSK: a draw that leaves the colour channels alone writes a mask for a later full-screen pass
// (0xffff00ff: green only, the shadow masks), not a picture.
static const bool noFrameMask = std::getenv("SBC_3D_NO_FRAME_MASK") != nullptr; // a diagnostic
static const bool showMasked = std::getenv("SBC_3D_SHOW_MASKED") != nullptr; // a diagnostic: in red
if (!noFrameMask && spr && (gsRegister(spr, 0x4c) >> 32) != 0)
{
if (!showMasked)
return;
for (Vertex &v : triangles)
v.rgba = 0x800000FFu;
mesh.texture = nullptr;
m.textured = false;
}
m.blend = Material::Blend::Alpha;
m.alphaTest = true;
m.alphaFunc = Material::AlphaFunc::Greater;
m.alphaRef = 0;
m.depthTest = true;
m.depthWrite = true;
static const bool noGsState = std::getenv("SBC_3D_NO_GS_STATE") != nullptr; // a diagnostic
// TEST_1 (ATE, ATST, AREF, AFAIL): the characters' and the world's draws test alpha >= 0x40 and, failing,
// still write the colour but not the depth (AFAIL RGB_ONLY): a hair card's faint tips blend over what is
// behind them without hiding the cards drawn after. Here the failing texels are a second draw of the mesh
// with the opposite test and no depth write. SBC_3D_ALPHA_ANY=1: alpha > 0 with depth (the earlier choice).
static const bool alphaAny = std::getenv("SBC_3D_ALPHA_ANY") != nullptr; // a diagnostic
bool failPass = false;
uint8_t failMask = 0xFu;
if (!noGsState && spr && !alphaAny)
{
const uint64_t test = gsRegister(spr, 0x47);
if (test & 1u)
{
using F = Material::AlphaFunc;
static const F funcs[8] = {F::Never, F::Always, F::Less, F::LessEqual, F::Equal, F::GreaterEqual, F::Greater,
F::NotEqual};
m.alphaFunc = funcs[(test >> 1) & 7u];
m.alphaRef = static_cast<uint8_t>((test >> 4) & 0xFFu);
const uint32_t afail = static_cast<uint32_t>(test >> 12) & 3u;
failPass = afail == 1u || afail == 3u; // FB_ONLY, RGB_ONLY (ZB_ONLY writes no colour: not drawn)
failMask = afail == 3u ? 0x7u : 0xFu;
}
else
m.alphaTest = false;
}
if (!noGsState && spr)
{
m.depthWrite = ((zbuf >> 32) & 1u) == 0;
if ((alphaRegister & 0xFFu) == 0x48u)
m.blend = Material::Blend::Additive;
else if ((alphaRegister & 0xFFu) == 0x42u)
{
// Cd - Cs As: no reverse subtract in the renderer; drawn as a darkening, Cd (1 - As lum(Cs)).
for (Vertex &v : triangles)
{
const float r = static_cast<float>(v.rgba & 0xFFu), g = static_cast<float>((v.rgba >> 8) & 0xFFu),
b = static_cast<float>((v.rgba >> 16) & 0xFFu), a = static_cast<float>(v.rgba >> 24);
const float darken = a * ((r + g + b) / (3.0f * 128.0f));
v.rgba = static_cast<uint32_t>(darken > 255.0f ? 255.0f : darken) << 24;
}
}
}
if (fog)
{
m.fog = true;
m.fogColour = static_cast<uint32_t>(gsRegister(spr, 0x3d)) & 0xFFFFFFu;
}
if (static const char *e = std::getenv("SBC_TRACE_BLEND"); e && render::frames() == std::strtoull(e, nullptr, 0))
std::printf("[sbc:blend] %08x flags %08x FRAME %016llx TEST %llx ALPHA %02x ZMSK %d fog %d textured %d "
"TEXimage %08x colour %08x, %zu triangles\n",
g_currentPrim, rd32(g_currentPrim + 8), static_cast<unsigned long long>(gsRegister(spr, 0x4c)),
static_cast<unsigned long long>(gsRegister(spr, 0x47)),
static_cast<unsigned>(alphaRegister & 0xFFu), static_cast<int>((zbuf >> 32) & 1u),
fog ? 1 : 0, m.textured ? 1 : 0, g_textureImage, triangles.empty() ? 0u : triangles[0].rgba,
triangles.size() / 3);
if (static const char *e = std::getenv("SBC_TRACE_BLEND"); e && render::frames() == std::strtoull(e, nullptr, 0))
std::printf("[sbc:blend] %08x TEX0_1 %016llx TEX1_1 %016llx CLAMP_1 %016llx PRMODE %llx\n", g_currentPrim,
static_cast<unsigned long long>(gsRegister(spr, 0x06)),
static_cast<unsigned long long>(gsRegister(spr, 0x14)),
static_cast<unsigned long long>(gsRegister(spr, 0x08)),
static_cast<unsigned long long>(gsRegister(spr, 0x1b)));
m.tex0 = t.texture ? t.texture->key : 0;
m.textureAlpha = t.alpha;
// The failing texels' draw, only when some can fail: a texel or a vertex alpha under AREF.
if (failPass && m.alphaTest && m.alphaFunc != Material::AlphaFunc::Always)
{
static std::map<const Texture *, uint8_t> lowest; // a texture's lowest alpha
uint8_t low = 0x80u;
if (m.textured && t.texture && t.alpha)
{
auto it = lowest.find(t.texture.get());
if (it == lowest.end())
{
uint8_t a = 0xFFu;
for (uint32_t c : t.texture->rgba)
a = std::min<uint8_t>(a, static_cast<uint8_t>(c >> 24));
if (lowest.size() > 4096)
lowest.clear();
it = lowest.emplace(t.texture.get(), a).first;
}
low = it->second;
}
for (const Vertex &v : triangles)
low = std::min<uint8_t>(low, static_cast<uint8_t>(v.rgba >> 24));
if (low < m.alphaRef || m.alphaFunc == Material::AlphaFunc::Never)
{
using F = Material::AlphaFunc;
Mesh failing = mesh;
Material &f = failing.material;
switch (m.alphaFunc)
{
case F::Never: f.alphaFunc = F::Always; break;
case F::Less: f.alphaFunc = F::GreaterEqual; break;
case F::LessEqual: f.alphaFunc = F::Greater; break;
case F::Equal: f.alphaFunc = F::NotEqual; break;
case F::GreaterEqual: f.alphaFunc = F::Less; break;
case F::Greater: f.alphaFunc = F::LessEqual; break;
case F::NotEqual: f.alphaFunc = F::Equal; break;
default: break;
}
f.depthWrite = false;
f.colourMask = failMask;
failing.vertices = triangles;
g_triangles += triangles.size() / 3;
mesh.vertices = std::move(triangles);
g_meshes.push_back(std::move(mesh));
g_meshes.push_back(std::move(failing)); // after the passing texels: the faint tips over them
g_triangles += g_meshes.back().vertices.size() / 3;
return;
}
}
g_triangles += triangles.size() / 3;
mesh.vertices = std::move(triangles);
g_meshes.push_back(std::move(mesh));
}
// Which flags (+8) light a rigid primitive: none. Flags 0x60000000 are the toon outline passes (0x2366b0,
// 0x236aa0: the primitive again at XYOFFSET +- the width, in the colour at +0xc), not lighting; the world's
// geometry is drawn with its texture (and prelit colour) as it is. SBC_3D_LIGHT_MASK=<flags> lights some.
uint32_t lightMask()
{
static const uint32_t mask = [] {
const char *e = std::getenv("SBC_3D_LIGHT_MASK");
return e ? static_cast<uint32_t>(std::strtoul(e, nullptr, 0)) : 0u;
}();
return mask;
}
// A primitive's batches sorted by their PRIM's TME (1) and FGE (2): each kind its own draw.
uint32_t kindOf(uint32_t gsPrim) { return ((gsPrim & 0x10u) ? 1u : 0u) | ((gsPrim & 0x20u) ? 2u : 0u); }
// The toon outline (flags +8 & 0x60000000, the DMA tag's byte +8 zero: 0x2366b0 / 0x236aa0 / 0x237140): before the
// primitive, its geometry again without texture in a flat colour (the tag's bytes +0xc..+0xe, times light 0's
// colour, VU 72, when +0xa is 1) four times, XYOFFSET moved by +-(width, width) (the tag's byte +9, 0 meaning
// 0x20, times the IMD state's +0x734, in 1/16 pixels; the state's +0x725 turns them on).
struct Outline
{
bool on = false;
float pixels = 0;
uint32_t rgba = 0;
};
Outline outlineOf(uint32_t prim, uint32_t tag, const uint8_t *spr)
{
Outline o;
static const bool none = std::getenv("SBC_3D_NO_OUTLINES") != nullptr; // a diagnostic
if (none || !g_gp || !spr || !(rd32(prim + 8) & 0x60000000u) || (rd32(tag + 8) & 0xFFu))
return o;
const uint32_t state = rd32(g_gp - 0x7d5cu);
uint8_t enabled;
float scale;
if ((state & 0xF0000000u) == 0x70000000u)
{
enabled = spr[(state + 0x725u) & 0x3FFFu];
std::memcpy(&scale, spr + ((state + 0x734u) & 0x3FFCu), 4);
}
else
{
enabled = g_ram[(state + 0x725u) & 0x1FFFFFFu];
std::memcpy(&scale, g_ram + ((state + 0x734u) & 0x1FFFFFCu), 4);
}
uint32_t width = (rd32(tag + 8) >> 8) & 0xFFu;
width = width ? width : 0x20u;
const int32_t units = static_cast<int32_t>(static_cast<float>(width) * scale);
if (!enabled || units <= 0)
return o;
o.on = true;
o.pixels = static_cast<float>(units) / 16.0f;
float colour[3] = {static_cast<float>((rd32(tag + 0xc)) & 0xFFu), static_cast<float>((rd32(tag + 0xc) >> 8) & 0xFFu),
static_cast<float>((rd32(tag + 0xc) >> 16) & 0xFFu)};
if (((rd32(tag + 8) >> 16) & 0xFFu) == 1u)
{
float light[4];
std::memcpy(light, spr + 0x240u + 72u * 16u, 16);
for (int c = 0; c < 3; ++c)
colour[c] *= light[c];
}
// An untextured colour: the GS's display byte as it is (keep() draws untextured colours directly; halved
// under SBC_3D_UNTEXTURED_DOUBLED, which doubles them).
static const bool doubled = std::getenv("SBC_3D_UNTEXTURED_DOUBLED") != nullptr;
o.rgba = 0x80000000u;
for (int c = 0; c < 3; ++c)
{
const float v = doubled ? colour[c] / 2.0f : colour[c];
o.rgba |= static_cast<uint32_t>(v < 0 ? 0 : v > 255 ? 255 : v) << (8 * c);
}
if (static int traced = 0; trace() && traced++ < 4)
std::printf("[sbc:3d] outline %08x: %.2f px, colour %08x\n", prim, o.pixels, o.rgba);
return o;
}
// A triangle's facing on screen: the determinant of its corners' (x, y, w) after the matrix, which is the screen
// area (positive for the front faces) times the three w. Unlike the area of the divided corners its sign holds
// when corners lie behind the camera (w < 0): the camera's side of the triangle's plane, as the VU's test.
float facing(const Matrix matrix, const Vertex *v)
{
static const int columns[3] = {0, 1, 3}; // x, y, w
float h[3][3];
for (int c = 0; c < 3; ++c)
for (int j = 0; j < 3; ++j)
{
const int col = columns[j];
h[c][j] = v[c].x * matrix[0][col] + v[c].y * matrix[1][col] + v[c].z * matrix[2][col] + matrix[3][col];
}
return h[0][0] * (h[1][1] * h[2][2] - h[1][2] * h[2][1]) - h[0][1] * (h[1][0] * h[2][2] - h[1][2] * h[2][0]) +
h[0][2] * (h[1][0] * h[2][1] - h[1][1] * h[2][0]);
}
void keepAll(const Matrix matrix, const MaterialTexture &t, std::vector<Vertex> (&lists)[4], const uint8_t *spr,
const Outline &outline = Outline{}, bool lit = false)
{
if (outline.on)
{
// The back faces only (the VU program flips its culling for the outline, VU 109.y = -1): an inverted hull.
static const float side = std::getenv("SBC_3D_OUTLINE_FRONT") ? -1.0f : 1.0f; // a diagnostic
std::vector<Vertex> all;
for (const auto &list : lists)
for (size_t i = 0; i + 2 < list.size(); i += 3)
{
if (facing(matrix, &list[i]) * side > 0)
continue;
all.insert(all.end(), list.begin() + static_cast<std::ptrdiff_t>(i),
list.begin() + static_cast<std::ptrdiff_t>(i + 3));
}
for (Vertex &v : all)
{
v.rgba = outline.rgba;
v.fog = 1.0f;
}
static const float signs[4][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
for (const auto &sign : signs)
{
Matrix shifted;
std::memcpy(shifted, matrix, sizeof shifted);
for (int i = 0; i < 4; ++i)
{
shifted[i][0] += sign[0] * outline.pixels * matrix[i][3];
shifted[i][1] += sign[1] * outline.pixels * matrix[i][3];
}
std::vector<Vertex> copy = all;
keep(shifted, t, std::move(copy), false, nullptr, false);
}
}
// The IMD programs cull back faces (rigid L_2250, skinned L_1bf8): a triangle whose normal, times its strip
// winding and VU 109.y (1.0 from every driver; -1 for the outline pass), points away from the camera (VU 117)
// gets the GS's ADC bit and is not drawn. Here the triangles keep one winding (strip()), so the back faces
// are the ones facing() does not find positive, those reaching behind the camera too: the camera inside a
// closed box (M_19_03's platform at (120, 0, -30)) sees only back faces, and none is drawn. A two-sided
// board's dark underside, coplanar with its top, would otherwise cover it. SBC_3D_NO_CULL=1 draws both sides
// (a diagnostic, the earlier choice).
static const bool noCull = std::getenv("SBC_3D_NO_CULL") != nullptr;
for (uint32_t k = 0; k < 4 && !noCull; ++k)
{
std::vector<Vertex> &list = lists[k];
size_t kept = 0;
for (size_t i = 0; i + 2 < list.size(); i += 3)
{
if (facing(matrix, &list[i]) <= 0)
continue;
for (int c = 0; c < 3; ++c)
list[kept + c] = list[i + c];
kept += 3;
}
list.resize(kept);
}
for (uint32_t k = 0; k < 4; ++k)
if (!lists[k].empty())
keep(matrix, t, std::move(lists[k]), (k & 1u) != 0, spr, (k & 2u) != 0, lit);
}
// Untextured batches (PRIM without TME): the material's colour, drawn with the GS state like the rest (the blob
// shadows; the far sea's dark sheets, which the fog turns to the horizon's colour).
bool skipUntextured(uint32_t gsPrim)
{
static const bool none = std::getenv("SBC_3D_NO_UNTEXTURED") != nullptr; // a diagnostic
return none && !(gsPrim & 0x10u);
}
// Types 72 and 73, mode 4: rigid, through the object's matrix.
void drawGeometry(uint8_t *rdram, R5900Context *ctx, Runtime *rt)
{
g_ram = rdram;
const uint32_t prim = ctx->r[4].uw[0];
ctx->r[2].ud[0] = 0;
ctx->pc = ctx->r[31].uw[0];
if (off() || !prim)
return;
g_currentPrim = prim;
g_gp = ctx->r[28].uw[0];
g_bucket = rd32(g_gp - 0x7e80u);
++g_primitives;
const uint8_t *spr = bozo::port::scratchpad(rt);
g_spr = spr;
Matrix object, screen, toScreen;
matrixAt(spr, 0x240u, object);
matrixAt(spr, 0x240u + 48u * 16u, screen);
multiply(object, screen, toScreen);
if (const char *e = SBC_ENV("SBC_TRACE_DARK"); e && render::frames() == std::strtoull(e, nullptr, 0))
if (const MaterialTexture d = materialTexture(); d.texture)
{
uint64_t sum = 0, alpha = 0;
for (uint32_t c : d.texture->rgba)
{
sum += (c & 0xFF) + ((c >> 8) & 0xFF) + ((c >> 16) & 0xFF);
alpha += c >> 24;
}
const uint64_t n = d.texture->rgba.empty() ? 1 : d.texture->rgba.size();
const uint64_t mean = sum / (3 * n);
if (mean < 24)
{
uint64_t tex0;
std::memcpy(&tex0, g_ram + ((g_textureImage + 0x20u) & 0x1FFFFFFu), 8);
std::printf("[sbc:dark] %08x flags %08x TEXimage %08x %ux%u mean %llu alpha %llu TCC %d PSM %02x "
"CPSM %02x\n",
prim, rd32(prim + 8), g_textureImage, d.texture->width, d.texture->height,
static_cast<unsigned long long>(mean), static_cast<unsigned long long>(alpha / n),
d.alpha ? 1 : 0, static_cast<int>((tex0 >> 20) & 0x3F),
static_cast<int>((tex0 >> 51) & 0xF));
}
}
if (const char *e = SBC_ENV("SBC_TRACE_OBJECTS"); e && render::frames() == std::strtoull(e, nullptr, 0))
if (static bool once = false; !once)
{
// The camera: the world point the screen matrix sends to x = y = w = 0 (columns 0, 1, 3).
once = true;
const int col[3] = {0, 1, 3};
float a[3][4];
for (int r = 0; r < 3; ++r)
{
for (int i = 0; i < 3; ++i)
a[r][i] = screen[i][col[r]];
a[r][3] = -screen[3][col[r]];
}
const auto det3 = [](float m[3][3]) {
return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) -
m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) +
m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
};
float m[3][3], c[3];
for (int r = 0; r < 3; ++r)
for (int i = 0; i < 3; ++i)
m[r][i] = a[r][i];
const float d = det3(m);
for (int k = 0; k < 3; ++k)
{
for (int r = 0; r < 3; ++r)
for (int i = 0; i < 3; ++i)
m[r][i] = i == k ? a[r][3] : a[r][i];
c[k] = d != 0 ? det3(m) / d : 0;
}
std::printf("[sbc:obj] camera %.3f %.3f %.3f\n", c[0], c[1], c[2]);
}
if (const char *e = SBC_ENV("SBC_TRACE_OBJECTS"); e && render::frames() == std::strtoull(e, nullptr, 0))
std::printf("[sbc:obj] rigid %08x flags %08x texture %08x object t %.3f %.3f %.3f rows %.2f %.2f %.2f / %.2f %.2f "
"%.2f / %.2f %.2f %.2f\n",
prim, rd32(prim + 8), g_textureImage, object[3][0], object[3][1], object[3][2], object[0][0],
object[0][1], object[0][2], object[1][0], object[1][1], object[1][2], object[2][0], object[2][1],
object[2][2]);
const MaterialTexture t = materialTexture();
// SBC_3D_SKIP_IMAGES=<TEXimage>,..: those textures' rigid meshes are not drawn (a diagnostic: what draws what).
if (static const char *skip = std::getenv("SBC_3D_SKIP_IMAGES"); skip && g_textureImage)
{
char hex[16];
std::snprintf(hex, sizeof hex, "%x", g_textureImage);
if (std::strstr(skip, hex))
return;
}
// SBC_3D_SKIP_PRIMS=<primitive>,..: those rigid primitives are not drawn (a diagnostic).
if (static const char *skip = std::getenv("SBC_3D_SKIP_PRIMS"); skip)
{
char hex[16];
std::snprintf(hex, sizeof hex, "%x", prim);
if (std::strstr(skip, hex))
return;
}
// Not lit (lightMask: the world's geometry carries its own colour).
// Flags +8 & 0x400: the vertices carry a baked colour (type 72's second vector); without it a normal, lit by
// the staged lights (the poles, the rocks' loose stones, the wreckage, Vanilla's hair).
const bool baked = (rd32(prim + 8) & 0x400u) != 0 && rd32(prim) == 72u;
Lights lights = !baked || (rd32(prim + 8) & lightMask()) ? lightsOf(spr, object, rigidLightsTurned()) : Lights{};
static const bool noToon = std::getenv("SBC_3D_NO_TOON") != nullptr; // a diagnostic
if (!baked && !noToon && rd32(prim) == 72u && (rd32(prim + 8) & 0x800u) && lights.on)
makeToon(lights, spr, rd32(prim + 8));
else if (!baked)
unlitMode(lights, prim);
const Lights &untexturedLights = lights;
if (traceChain())
std::printf("[sbc:chain] entries toon %x baked %x / %x (state +0x64 %x)\n", rd32(g_gp - 0x7ee8u),
rd32(g_gp - 0x7ef0u), rd32(g_gp - 0x7eecu), modeBits(prim) & ~rd32(prim + 8));
if (traceChain())
std::printf("[sbc:chain] rigid %08x bucket %u type %u modes %08x diffuse %g %g %g emission %g %g %g chain %08x resets %llu\n",
prim, g_bucket, rd32(prim), modeBits(prim), lights.diffuse[0], lights.diffuse[1], lights.diffuse[2],
lights.emission[0], lights.emission[1], lights.emission[2], rd32(g_gp - 0x7d10u),
static_cast<unsigned long long>(g_chainResets));
if (traceChain())
for (uint32_t n : {64u, 65u, 66u, 67u, 72u, 73u, 74u, 75u})
{
const float *sent = vuQword(n), *staged = reinterpret_cast<const float *>(spr + 0x240u + n * 16u);
std::printf("[sbc:chain] VU%u staged %.3f %.3f %.3f %.3f sent %s %.3f %.3f %.3f %.3f\n", n, staged[0],
staged[1], staged[2], staged[3], sent ? "yes" : "no", sent ? sent[0] : 0.0f,
sent ? sent[1] : 0.0f, sent ? sent[2] : 0.0f, sent ? sent[3] : 0.0f);
}
const MaterialColour material = materialColourOf(spr, ctx->r[28].uw[0]);
std::vector<Vertex> lists[4];
batches(prim + 0x10, [&](uint32_t count, uint32_t stride, uint32_t at, uint32_t gsPrim) {
if (static const char *e = std::getenv("SBC_TRACE_UNTEXTURED");
e && !(gsPrim & 0x10u) && render::frames() == std::strtoull(e, nullptr, 0))
{
const float *d = reinterpret_cast<const float *>(spr + 0x240u + 56u * 16u);
std::printf("[sbc:untex] %08x flags %08x gsPrim %03x %u vertices stride %u, VU56 %g %g %g %g, mode %u, "
"TEXimage %08x, tag %08x %08x %08x %08x\n",
prim, rd32(prim + 8), gsPrim, count, stride, d[0], d[1], d[2], d[3],
rd32(ctx->r[28].uw[0] - 0x7d4cu), g_textureImage, rd32(at - 0x14), rd32(at - 0x10),
rd32(at - 0x0c), rd32(at - 0x08));
const float *f = reinterpret_cast<const float *>(spr + 0x240u + 76u * 16u);
const uint32_t regs = rd32(ctx->r[28].uw[0] - 0x7cb8u);
const auto reg = [&](uint32_t r) {
uint64_t v;
if ((regs & 0xF0000000u) == 0x70000000u)
std::memcpy(&v, spr + ((regs + r * 8) & 0x3FF8u), 8);
else
std::memcpy(&v, g_ram + ((regs + r * 8) & 0x1FFFFF8u), 8);
return v;
};
std::printf("[sbc:untex] VU76 %g %g %g %g VU77 %g %g %g %g VU78 %g %g %g %g FOGCOL %llx ALPHA %llx "
"TEST %llx ZBUF %llx FBA %llx FRAME %llx\n",
f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], f[10], f[11],
static_cast<unsigned long long>(reg(0x3d)), static_cast<unsigned long long>(reg(0x42)),
static_cast<unsigned long long>(reg(0x47)), static_cast<unsigned long long>(reg(0x4e)),
static_cast<unsigned long long>(reg(0x4a)), static_cast<unsigned long long>(reg(0x4c)));
}
if (skipUntextured(gsPrim))
return;
strip(count, stride, at, t, (gsPrim & 0x10u) ? lights : untexturedLights, material, lists[kindOf(gsPrim)],
[](uint32_t v, float scale, Vertex &o, float *) {
o.x = rd16(v) * scale;
o.y = rd16(v + 2) * scale;
o.z = rd16(v + 4) * scale;
});
});
for (uint32_t kind : {1u, 3u})
for (const Vertex &v : lists[kind])
for (int j = 0; j < 3; ++j)
g_worldTriangles.push_back(v.x * object[0][j] + v.y * object[1][j] + v.z * object[2][j] + object[3][j]);
if (const char *e = SBC_ENV("SBC_TRACE_MODES"); e && render::frames() == std::strtoull(e, nullptr, 0))
{
const float *vu = reinterpret_cast<const float *>(spr + 0x240u);
std::printf("[sbc:mode] L0 %.3f %.3f %.3f rowx %.2f %.2f %.2f\n", vu[64 * 4], vu[65 * 4], vu[66 * 4], object[0][0],
object[0][1], object[0][2]);
std::printf("[sbc:mode] %08x flags %08x TEXimage %08x %ux%u VU56 %g %g %g %g VU57 %g %g %g VU124 %g %g %g %g "
"VU125 %g %g %g VU126 %g %g %g VU110 %08x %08x\n",
prim, rd32(prim + 8), g_textureImage, t.texture ? t.texture->width : 0, t.texture ? t.texture->height : 0,
vu[56 * 4], vu[56 * 4 + 1], vu[56 * 4 + 2], vu[56 * 4 + 3], vu[57 * 4], vu[57 * 4 + 1], vu[57 * 4 + 2],
vu[124 * 4], vu[124 * 4 + 1], vu[124 * 4 + 2], vu[124 * 4 + 3], vu[125 * 4], vu[125 * 4 + 1],
vu[125 * 4 + 2], vu[126 * 4], vu[126 * 4 + 1], vu[126 * 4 + 2],
*reinterpret_cast<const uint32_t *>(spr + 0x240u + 110u * 16u),
*reinterpret_cast<const uint32_t *>(spr + 0x240u + 110u * 16u + 4));
}
if (const char *e = SBC_ENV("SBC_TRACE_BLACK"); e && render::frames() == std::strtoull(e, nullptr, 0))
{
size_t dark = 0, all = 0;
for (const auto &list : lists)
for (const Vertex &v : list)
{
++all;
dark += ((v.rgba & 0xFFu) < 12u && ((v.rgba >> 8) & 0xFFu) < 12u && ((v.rgba >> 16) & 0xFFu) < 12u);
}
if (all && dark * 2 > all)
std::printf("[sbc:black] %08x type %u flags %08x TEXimage %08x texture %d lit %d: %zu of %zu dark\n", prim,
rd32(prim), rd32(prim + 8), g_textureImage, t.texture ? 1 : 0, lights.on ? 1 : 0, dark, all);
}
if (traceChain())
{
uint64_t sum = 0, alpha = 0;
if (t.texture)
for (uint32_t c : t.texture->rgba)
{
sum += (c & 0xFF) + ((c >> 8) & 0xFF) + ((c >> 16) & 0xFF);
alpha += c >> 24;
}
const uint64_t n = t.texture && !t.texture->rgba.empty() ? t.texture->rgba.size() : 1;
std::printf("[sbc:chain] %08x TEXimage %08x texture %ux%u mean %llu alpha %llu version %llu; vertices "
"untextured %zu textured %zu fogged %zu %zu\n",
prim, g_textureImage, t.texture ? t.texture->width : 0, t.texture ? t.texture->height : 0,
static_cast<unsigned long long>(sum / (3 * n)), static_cast<unsigned long long>(alpha / n),
static_cast<unsigned long long>(t.texture ? t.texture->version : 0), lists[0].size(),
lists[1].size(), lists[2].size(), lists[3].size());
const float *vu56 = vuQword(56);
std::printf("[sbc:chain] %08x VU56 %g %g %g %g first rgba %08x %08x %08x %08x\n", prim, vu56 ? vu56[0] : -1.0f,
vu56 ? vu56[1] : -1.0f, vu56 ? vu56[2] : -1.0f, vu56 ? vu56[3] : -1.0f,
lists[0].empty() ? 0u : lists[0][0].rgba, lists[1].empty() ? 0u : lists[1][0].rgba,
lists[2].empty() ? 0u : lists[2][0].rgba, lists[3].empty() ? 0u : lists[3][0].rgba);
}
keepAll(toScreen, t, lists, spr, outlineOf(prim, prim + 0x10, spr), (lights.on && !lights.toon) || baked);
}
} // namespace
// The type-32 material driver's 0x238d70 (0x238d80, s0 the primitive): its diffuse and emission for the lights.
bool colourMaterialSite(uint8_t *rdram, R5900Context *ctx, Runtime *rt, uint32_t)
{
g_ram = rdram;
g_material = ctx->r[16].uw[0];
g_gp = ctx->r[28].uw[0];
g_spr = bozo::port::scratchpad(rt);
followChain(); // what came before this material
if (traceChain())
{
const float *d = reinterpret_cast<const float *>(rdram + ((g_material + 0x10u) & 0x1FFFFF0u));
std::printf("[sbc:chain] material %08x bucket %u flags %08x +10 %g %g %g %g chain %08x resets %llu unpacks %llu\n", g_material,
rd32(g_gp - 0x7e80u), rd32(g_material + 8), d[0], d[1], d[2], d[3], rd32(g_gp - 0x7d10u),
static_cast<unsigned long long>(g_chainResets), static_cast<unsigned long long>(g_chainUnpacks));
}
return false;
}
// The type-72 prelight pass's lit bake (0x238a90; 0x238770 picks it for a primitive without flags 8, then sets 0x400):
// a vertex's colour = clamp(colour matrix (IMD table +0x480) x clamp(light matrix (+0x440, the object's) x normal)) x
// (+0x720 x the s, t vector's w) + +0x730. SBC_TRACE_BAKE=1 prints what it bakes with (a diagnostic).
uint32_t g_bakeData = 0;
int16_t g_bakeIn[12] = {};
float g_bakeTable[0x80][4] = {}; // the IMD table's 0x400..0x7ff at the bake's entry
bool bakeSite(uint8_t *rdram, R5900Context *ctx, Runtime *rt, uint32_t)
{
// SBC_TRACE_BAKE=1: the first 200 bakes; =<address>: the bakes of the vertices within 0x2000 bytes after it.
static const char *e = std::getenv("SBC_TRACE_BAKE");
static const uint32_t from = e && std::strcmp(e, "1") != 0 ? static_cast<uint32_t>(std::strtoul(e, nullptr, 16)) : 0u;
static int traced = 0;
g_bakeData = 0;
if (!e || traced >= 200 || (from && ctx->r[5].uw[0] - from >= 0x2000u))
return false;
++traced;
g_ram = rdram;
const uint32_t gp = ctx->r[28].uw[0], table = rd32(gp - 0x7c60u);
const auto q = [&](uint32_t a) {
float v[4];
if ((a & 0xF0000000u) == 0x70000000u)
std::memcpy(v, bozo::port::scratchpad(rt) + (a & 0x3FF0u), 16);
else
std::memcpy(v, rdram + (a & 0x1FFFFF0u), 16);
char s[96];
std::snprintf(s, sizeof s, "(%.3g %.3g %.3g %.3g)", v[0], v[1], v[2], v[3]);
return std::string(s);
};
std::printf("[sbc:bake] kick %llu count %u data %08x table %08x\n", static_cast<unsigned long long>(render::frames()),
ctx->r[4].uw[0], ctx->r[5].uw[0], table);
std::printf("[sbc:bake] world lights +400 %s %s %s %s\n", q(table + 0x400).c_str(), q(table + 0x410).c_str(),
q(table + 0x420).c_str(), q(table + 0x430).c_str());
std::printf("[sbc:bake] object lights +440 %s %s %s %s\n", q(table + 0x440).c_str(), q(table + 0x450).c_str(),
q(table + 0x460).c_str(), q(table + 0x470).c_str());
std::printf("[sbc:bake] colours +480 %s %s %s %s\n", q(table + 0x480).c_str(), q(table + 0x490).c_str(),
q(table + 0x4a0).c_str(), q(table + 0x4b0).c_str());
std::printf("[sbc:bake] material +720 %s +730 %s object rows %s %s %s\n", q(table + 0x720).c_str(),
q(table + 0x730).c_str(), q(table).c_str(), q(table + 0x10).c_str(), q(table + 0x20).c_str());
g_bakeData = ctx->r[5].uw[0];
const uint32_t v = g_bakeData;
for (int k = 0; k < 12; ++k)
g_bakeIn[k] = rd16(v + 2 * k);
for (uint32_t k = 0; k < 0x40; ++k)
{
const uint32_t a = table + 0x400u + 16u * k;
if ((a & 0xF0000000u) == 0x70000000u)
std::memcpy(g_bakeTable[k], bozo::port::scratchpad(rt) + (a & 0x3FF0u), 16);
else
std::memcpy(g_bakeTable[k], rdram + (a & 0x1FFFFF0u), 16);
}
std::printf("[sbc:bake] first vertex q0 %d %d %d %d q1 %d %d %d %d q2 %d %d %d %d\n", rd16(v), rd16(v + 2), rd16(v + 4),
rd16(v + 6), rd16(v + 8), rd16(v + 10), rd16(v + 12), rd16(v + 14), rd16(v + 16), rd16(v + 18),
rd16(v + 20), rd16(v + 22));
return false;
}
// The lit bake's end (0x238c80): what it wrote into the first vertex (SBC_TRACE_BAKE).
bool bakeEndSite(uint8_t *rdram, R5900Context *, Runtime *, uint32_t)
{
static int traced = 0;
if (traced >= 200 || !g_bakeData)
return false;
++traced;
g_ram = rdram;
const uint32_t v = g_bakeData;
// The same bake natively: d = clamp01(L x n + row 3), c = clamp01(C x d), colour = clamp(c x m x w + e, 0, 255).
const float n[4] = {g_bakeIn[4] / 32768.0f, g_bakeIn[5] / 32768.0f, g_bakeIn[6] / 32768.0f, g_bakeIn[7] / 32768.0f};
const float w = g_bakeIn[11] / 4096.0f;
const auto row = [](uint32_t off) { return g_bakeTable[(off - 0x400u) / 16u]; };
float d[4], c[4], out[4];
for (int j = 0; j < 4; ++j)
{
d[j] = row(0x440)[j] * n[0] + row(0x450)[j] * n[1] + row(0x460)[j] * n[2] + row(0x470)[j];
d[j] = d[j] < 0 ? 0 : d[j] > 1 ? 1 : d[j];
}
for (int j = 0; j < 4; ++j)
{
c[j] = row(0x480)[j] * d[0] + row(0x490)[j] * d[1] + row(0x4a0)[j] * d[2] + row(0x4b0)[j] * d[3];
c[j] = c[j] < 0 ? 0 : c[j] > 1 ? 1 : c[j];
out[j] = c[j] * row(0x720)[j] * w + (j < 3 ? row(0x730)[j] : 0.0f);
}
std::printf("[sbc:bake] baked q1 %d %d %d %d expected %.1f %.1f %.1f (n %.2f %.2f %.2f w %.2f d %.2f %.2f %.2f %.2f)\n",
rd16(v + 8), rd16(v + 10), rd16(v + 12), rd16(v + 14), out[0], out[1], out[2], n[0], n[1], n[2], w, d[0],
d[1], d[2], d[3]);
return false;
}
// DmaBeginPacket (0x25ec40), before it switches the bucket: what the bucket being left wrote goes to its shadow.
bool bucketSite(uint8_t *rdram, R5900Context *ctx, Runtime *rt, uint32_t)
{
g_ram = rdram;
g_gp = ctx->r[28].uw[0];
g_spr = bozo::port::scratchpad(rt);
if (!chainLinear())
followChain();
return false; // the instruction runs as it is
}
// The type-33 material driver at 0x2390fc, after its TexGetTEXimage: s1 is the material's TEXimage (0: none).
bool materialSite(uint8_t *, R5900Context *ctx, Runtime *, uint32_t)
{
g_textureImage = ctx->r[17].uw[0];
return false; // the instruction runs as it is
}
// Type 100's driver at 0x23bc28, after 0x23c0b0 staged its morph (s0 the primitive): each vertex is N position /
// normal pairs (the targets, N = prim +0x50, VU 77.y) and its s, t; the VU program blends the targets by the weights
// at VU 92-93 (prim +0x30..0x4c) and draws the result as type 72 does. The sea's waves on the shore.
bool morphSite(uint8_t *rdram, R5900Context *ctx, Runtime *rt, uint32_t)
{
g_ram = rdram;
const uint32_t prim = ctx->r[16].uw[0];
static const bool noMorph = std::getenv("SBC_3D_NO_MORPH") != nullptr; // a diagnostic
if (off() || noMorph || !prim)
return false;
const uint8_t *spr = bozo::port::scratchpad(rt);
const uint32_t state = rd32(ctx->r[28].uw[0] - 0x7d5cu);
const uint32_t skip = (state & 0xF0000000u) == 0x70000000u
? *reinterpret_cast<const uint32_t *>(spr + ((state + 0x528u) & 0x3FFCu))
: rd32(state + 0x528u);
if (skip) // the driver draws nothing then
return false;
g_currentPrim = prim;
g_gp = ctx->r[28].uw[0];
g_bucket = rd32(g_gp - 0x7e80u);
++g_primitives;
Matrix object, screen, toScreen;
matrixAt(spr, 0x240u, object);
matrixAt(spr, 0x240u + 48u * 16u, screen);
multiply(object, screen, toScreen);
uint32_t targets = rd32(prim + 0x50);
targets = targets < 1 ? 1 : targets > 8 ? 8 : targets;
float weights[8];
std::memcpy(weights, spr + 0x240u + 92u * 16u, sizeof weights);
if (static int traced = 0; trace() && traced++ < 4)
std::printf("[sbc:3d] morph %08x: %u targets, weights %g %g %g %g\n", prim, targets, weights[0], weights[1],
weights[2], weights[3]);
const MaterialTexture t = materialTexture();
const Lights lights = (rd32(prim + 8) & lightMask()) ? lightsOf(spr, object, rigidLightsTurned()) : Lights{};
const MaterialColour material = materialColourOf(spr, ctx->r[28].uw[0]);
std::vector<Vertex> lists[4];
batches(prim + 0x70, [&](uint32_t count, uint32_t stride, uint32_t at, uint32_t gsPrim) {
if (skipUntextured(gsPrim) || stride != 2u * targets + 1u)
return;
strip(
count, stride, at, t, lights, material, lists[kindOf(gsPrim)],
[&](uint32_t v, float scale, Vertex &o, float *normal) {
float position[3] = {0, 0, 0};
for (int c = 0; c < 3; ++c)
normal[c] = 0;
for (uint32_t k = 0; k < targets; ++k)
for (int c = 0; c < 3; ++c)
{
position[c] += weights[k] * rd16(v + 16u * k + 2u * c);
normal[c] += weights[k] * rd16(v + 16u * k + 8u + 2u * c) / 32768.0f;
}
o.x = position[0] * scale;
o.y = position[1] * scale;
o.z = position[2] * scale;
},
16u * targets);
});
keepAll(toScreen, t, lists, spr, outlineOf(prim, prim + 0x70, spr), lights.on);
return false; // the driver goes on (its VU packets are not drawn)
}
// The water module (0x13e000-0x143000) draws its planes with its own VU1 program (not IMD): 0x13ed10 for each of
// the 32 slots at 0x57faf0 (0x300 bytes; the object, a g3d coordinate, at +0x140, its descriptor at +0xc0).
// 0x13eec0, after its TexGetTEXimage(*(material + 0x38)): s1 the plane's TEXimage.
namespace
{
uint32_t g_waterImage = 0;
}
bool waterImageSite(uint8_t *, R5900Context *ctx, Runtime *, uint32_t)
{
g_waterImage = ctx->r[17].uw[0];
return false;
}
// 0x13f1fc, once a plane a frame, its material (VU 56-58) and lights (VU 64-75) staged and the object's matrix in VU
// 0-3: s5 the object, *(sp + 0x44c) the descriptor. The descriptor's height field (+0x74, +0x60 x +0x64 vertices,
// +0x6c bytes a row; +0x30 the origin, +0x40 the cell) is the surface: P = (x0 + k cell, y0 + H[r][k], z0 + r cell).
// The VU program (the water's own microcode at 0x3c6e20, byte 0x2d0) maps the texture by the reflected eye vector,
// R = 2 (N.V) N - V: s, t = 0.5 + 0.5 (Rx, Rz) (Rx^2 + Rz^2); colour = diffuse x VU56 + VU57 + specular x VU58
// (specular = light 0's colour x max(0, (1 - k) + k L0.R), k = VU58.w), alpha VU56.w; ALPHA 0x44, depth written, no
// fog. The shore foam passes (descriptor +0x24: 32 flat layers into the frame's green channel, then a grey blend by
// the destination alpha) are not drawn.
bool waterSite(uint8_t *rdram, R5900Context *ctx, Runtime *rt, uint32_t)
{
g_ram = rdram;
static const bool noWater = std::getenv("SBC_3D_NO_WATER") != nullptr; // a diagnostic
if (off() || noWater)
return false;
const uint32_t object = ctx->r[21].uw[0], desc = rd32(ctx->r[29].uw[0] + 0x44c);
if (!object || !desc)
return false;
const uint8_t *spr = bozo::port::scratchpad(rt);
const auto f32 = [](uint32_t a) {
float v;
std::memcpy(&v, g_ram + (a & 0x1FFFFFFu), 4);
return v;
};
const uint32_t width = rd32(desc + 0x60), height = rd32(desc + 0x64), pitch = rd32(desc + 0x6c),
field = rd32(desc + 0x74);
if (!field || width < 2 || height < 2 || width > 4096 || height > 4096 || pitch < width * 4)
return false;
g_currentPrim = object;
g_gp = ctx->r[28].uw[0];
g_bucket = rd32(g_gp - 0x7e80u);
const float x0 = f32(desc + 0x30), y0 = f32(desc + 0x34), z0 = f32(desc + 0x38), cell = f32(desc + 0x40);
Matrix objectMatrix, screen, toScreen;
matrixAt(spr, 0x240u, objectMatrix);
matrixAt(spr, 0x240u + 48u * 16u, screen);
multiply(objectMatrix, screen, toScreen);
// The eye in the object's space (the camera at VU 112; the object's rows orthonormal).
float eyeWorld[3], eye[3];
std::memcpy(eyeWorld, spr + 0x240u + 112u * 16u, 12);
for (int j = 0; j < 3; ++j)
{
eye[j] = 0;
for (int i = 0; i < 3; ++i)
eye[j] += (eyeWorld[i] - objectMatrix[3][i]) * objectMatrix[j][i];
}
float diffuseColour[4], addColour[4], specularColour[4];
std::memcpy(diffuseColour, spr + 0x240u + 56u * 16u, 16);
std::memcpy(addColour, spr + 0x240u + 57u * 16u, 16);
std::memcpy(specularColour, spr + 0x240u + 58u * 16u, 16);
const Lights lights = lightsOf(spr, objectMatrix);
const uint32_t saved = g_textureImage;
g_textureImage = g_waterImage;
const MaterialTexture tex = materialTexture();
g_textureImage = saved;
const auto h = [&](int32_t r, int32_t k) {
r = r < 0 ? 0 : r >= static_cast<int32_t>(height) ? static_cast<int32_t>(height) - 1 : r;
k = k < 0 ? 0 : k >= static_cast<int32_t>(width) ? static_cast<int32_t>(width) - 1 : k;
return f32(field + static_cast<uint32_t>(r) * pitch + static_cast<uint32_t>(k) * 4u);
};
std::vector<Vertex> grid(static_cast<size_t>(width) * height);
for (int32_t r = 0; r < static_cast<int32_t>(height); ++r)
for (int32_t k = 0; k < static_cast<int32_t>(width); ++k)
{
Vertex &o = grid[static_cast<size_t>(r) * width + k];
o.x = x0 + k * cell;
static const float heightSign = std::getenv("SBC_3D_WATER_NEGATE") ? -1.0f : 1.0f; // a diagnostic
o.y = y0 + heightSign * h(r, k);
o.z = z0 + r * cell;
// The normal from the neighbours (0x140940): (dx + d, -cell, dz - d), d along the diagonal.
const float d = 0.7071f * (h(r - 1, k + 1) - h(r + 1, k - 1));
float n[3] = {h(r, k + 1) - h(r, k - 1) + d, -cell, h(r + 1, k) - h(r - 1, k) - d};
float length = std::sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
for (float &c : n)
c /= length > 0 ? length : 1.0f;
float v[3] = {eye[0] - o.x, eye[1] - o.y, eye[2] - o.z};
length = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
for (float &c : v)
c /= length > 0 ? length : 1.0f;
const float nv = n[0] * v[0] + n[1] * v[1] + n[2] * v[2];
const float reflected[3] = {2 * nv * n[0] - v[0], 2 * nv * n[1] - v[1], 2 * nv * n[2] - v[2]};
const float spread = reflected[0] * reflected[0] + reflected[2] * reflected[2];
o.u = (0.5f + 0.5f * reflected[0] * spread) * tex.uScale;
o.v = (0.5f + 0.5f * reflected[2] * spread) * tex.vScale;
float diffuse[3] = {lights.ambient[0], lights.ambient[1], lights.ambient[2]};
for (int j = 0; j < 3; ++j)
{
const float dot = n[0] * lights.direction[0][j] + n[1] * lights.direction[1][j] + n[2] * lights.direction[2][j];
if (dot > 0)
for (int c = 0; c < 3; ++c)
diffuse[c] += dot * lights.colour[j][c];
}
const float l0r = reflected[0] * lights.direction[0][0] + reflected[1] * lights.direction[1][0] +
reflected[2] * lights.direction[2][0];
const float sharpness = specularColour[3];
float specular = (1 - sharpness) + sharpness * l0r;
specular = specular > 0 ? specular : 0;
o.rgba = 0;
for (int c = 0; c < 3; ++c)
{
const float value = diffuse[c] * diffuseColour[c] + addColour[c] +
specular * lights.colour[0][c] * specularColour[c];
o.rgba |= static_cast<uint32_t>(value < 0 ? 0 : value > 255 ? 255 : value) << (8 * c);
}
const float alpha = diffuseColour[3];
o.rgba |= static_cast<uint32_t>(alpha < 0 ? 0 : alpha > 255 ? 255 : alpha) << 24;
}
std::vector<Vertex> triangles;
triangles.reserve(static_cast<size_t>(width - 1) * (height - 1) * 6);
for (uint32_t r = 0; r + 1 < height; ++r)
for (uint32_t k = 0; k + 1 < width; ++k)
{
const Vertex &a = grid[r * width + k], &b = grid[(r + 1) * width + k], &c = grid[r * width + k + 1],
&d = grid[(r + 1) * width + k + 1];
triangles.insert(triangles.end(), {a, b, c, b, d, c});
}
if (static int traced = 0; trace() && traced++ < 2)
std::printf("[sbc:3d] water %08x: %ux%u, cell %g, TEXimage %08x, colour %08x\n", object, width, height, cell,
g_waterImage, grid[0].rgba);
++g_primitives;
const std::vector<Vertex> water = triangles;
keep(toScreen, tex, std::move(triangles), tex.texture != nullptr, nullptr, false);
// The shore foam (descriptor +0x24): the game counts, into the frame's alpha, which of 32 flat layers 0.002 apart
// (from the plane's height - 0.008) are above the ground: Ad = (25 + 103 n / 32) / 128; then it draws the plane
// in grey (128) blended Cd Ad + grey (1 - Ad): the shallows and the shoreline go grey. Here the ground's height
// under each vertex comes from the world's triangles (cached a plane, the topmost seen), and the grey plane
// carries 1 - Ad as its alpha.
static const bool noFoam = std::getenv("SBC_3D_NO_FOAM") != nullptr; // a diagnostic
if (!noFoam && (rd32(desc + 0x24) & 0xFFu))
{
struct Ground
{
uint32_t field = 0;
float base[3] = {0, 0, 0};
std::vector<float> y; // NaN: not seen yet
float up = 0; // +1 if y grows upward, -1 if downward
};
static std::vector<Ground> grounds;
Ground *ground = nullptr;
for (Ground &g : grounds)
if (g.field == field && g.base[0] == objectMatrix[3][0] && g.base[1] == objectMatrix[3][1] &&
g.base[2] == objectMatrix[3][2])
ground = &g;
if (!ground)
{
grounds.push_back(Ground{});
ground = &grounds.back();
ground->field = field;
for (int j = 0; j < 3; ++j)
ground->base[j] = objectMatrix[3][j];
ground->y.assign(static_cast<size_t>(width) * height, std::nanf(""));
ground->up = eyeWorld[1] < objectMatrix[3][1] + y0 ? -1.0f : 1.0f; // the camera is above the sea
}
// The plane's grid in world space is its origin plus (k, r) cells (its matrix a translation, as the
// beach's: the rotation is ignored here).
const float gx = objectMatrix[3][0] + x0, gz = objectMatrix[3][2] + z0, up = ground->up;
for (size_t i = 0; i + 8 < g_worldTriangles.size(); i += 9)
{
const float *tri = &g_worldTriangles[i];
const float minX = std::fmin(tri[0], std::fmin(tri[3], tri[6])), maxX = std::fmax(tri[0], std::fmax(tri[3], tri[6]));
const float minZ = std::fmin(tri[2], std::fmin(tri[5], tri[8])), maxZ = std::fmax(tri[2], std::fmax(tri[5], tri[8]));
const int32_t k0 = static_cast<int32_t>(std::ceil((minX - gx) / cell)), k1 = static_cast<int32_t>(std::floor((maxX - gx) / cell));
const int32_t r0 = static_cast<int32_t>(std::ceil((minZ - gz) / cell)), r1 = static_cast<int32_t>(std::floor((maxZ - gz) / cell));
if (k1 < 0 || r1 < 0 || k0 >= static_cast<int32_t>(width) || r0 >= static_cast<int32_t>(height))
continue;
const float det = (tri[5] - tri[8]) * (tri[0] - tri[6]) + (tri[6] - tri[3]) * (tri[2] - tri[8]);
if (std::fabs(det) < 1e-9f)
continue;
for (int32_t r = r0 < 0 ? 0 : r0; r <= r1 && r < static_cast<int32_t>(height); ++r)
for (int32_t k = k0 < 0 ? 0 : k0; k <= k1 && k < static_cast<int32_t>(width); ++k)
{
const float x = gx + k * cell, z = gz + r * cell;
const float a = ((tri[5] - tri[8]) * (x - tri[6]) + (tri[6] - tri[3]) * (z - tri[8])) / det;
const float b = ((tri[8] - tri[2]) * (x - tri[6]) + (tri[0] - tri[6]) * (z - tri[8])) / det;
const float c = 1 - a - b;
if (a < -1e-4f || b < -1e-4f || c < -1e-4f)
continue;
const float y = a * tri[1] + b * tri[4] + c * tri[7];
if ((y - (objectMatrix[3][1] + y0)) * up > 1.0f)
continue; // far above the sea (the sky, a deck, a rock's top): not its ground
float &known = ground->y[static_cast<size_t>(r) * width + k];
if (std::isnan(known) || (y - known) * up > 0)
known = y; // the topmost surface
}
}
const float layerBase = objectMatrix[3][1] + y0;
std::vector<Vertex> grey;
grey.reserve(water.size());
size_t foamy = 0;
const auto alphaAt = [&](const Vertex &v) -> uint32_t {
const int32_t k = static_cast<int32_t>(std::lround((v.x - x0) / cell)), r = static_cast<int32_t>(std::lround((v.z - z0) / cell));
if (k < 0 || r < 0 || k >= static_cast<int32_t>(width) || r >= static_cast<int32_t>(height))
return 0;
const float groundY = ground->y[static_cast<size_t>(r) * width + k];
if (std::isnan(groundY))
return 0;
uint32_t above = 0;
for (int i = 0; i < 32; ++i)
above += (layerBase + 0.002f * static_cast<float>(i - 4) * -up - groundY) * up > 0 ? 1u : 0u;
float ad = (25.0f + 103.0f * static_cast<float>(above) / 32.0f) / 128.0f;
ad = ad > 1 ? 1 : ad;
return static_cast<uint32_t>((1.0f - ad) * 128.0f + 0.5f);
};
for (const Vertex &v : water)
{
Vertex o = v;
const uint32_t alpha = alphaAt(v);
foamy += alpha != 0;
o.rgba = 0x00404040u | (alpha << 24); // grey 128 (0x40 halved), alpha 1 - Ad
grey.push_back(o);
}
if (static int traced = 0; trace() && traced++ < 4)
std::printf("[sbc:3d] foam: %zu of %zu vertices, up %g, %zu world triangles\n", foamy, grey.size(), up,
g_worldTriangles.size() / 9);
if (foamy)
{
keep(toScreen, tex, std::move(grey), false, nullptr, false);
if (!g_meshes.empty())
g_meshes.back().material.depthWrite = false;
}
}
return false;
}
// Type 88's driver at 0x23a898, after 0x23aea0 left the bone slots' matrices in the scratchpad: s4 the primitive.
bool skinnedSite(uint8_t *rdram, R5900Context *ctx, Runtime *rt, uint32_t)
{
g_ram = rdram;
const uint32_t prim = ctx->r[20].uw[0];
static const bool noSkin = std::getenv("SBC_3D_NO_SKIN") != nullptr; // a diagnostic
if (off() || noSkin || !prim)
return false;
g_currentPrim = prim;
g_gp = ctx->r[28].uw[0];
g_bucket = rd32(g_gp - 0x7e80u);
++g_primitives;
++g_skinned;
const uint8_t *spr = bozo::port::scratchpad(rt);
g_spr = spr;
Matrix bones[8], screen, identity = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
bool used[8];
uint32_t boneCount = 0;
for (uint32_t k = 0; k < 8; ++k)
{
used[k] = static_cast<int32_t>(rd32(prim + 0x10 + 4 * k)) >= 0;
boneCount += used[k];
matrixAt(spr, k * 0x40u, bones[k]);
}
// One bone: 0x23aea0 made its matrix the object's (VU 0-3) itself; the vertices go through it alone.
if (boneCount == 1)
for (uint32_t k = 0; k < 8; ++k)
std::memcpy(bones[k], identity, sizeof identity);
matrixAt(spr, 0x240u + 48u * 16u, screen);
// The character's placement: the object's matrix (VU 0-3), after the bones' skinning matrices.
Matrix object, toScreen;
matrixAt(spr, 0x240u, object);
// The bones' matrices already hold the character's rotation (and scale) but not its place: with several bones the
// object's matrix (the character's root) adds only its translation.
Matrix place = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {object[3][0], object[3][1], object[3][2], 1}};
multiply(boneCount > 1 ? place : object, screen, toScreen);
if (static const bool noObject = std::getenv("SBC_3D_SKIN_NO_OBJECT") != nullptr; noObject && boneCount > 1)
std::memcpy(toScreen, screen, sizeof screen); // a diagnostic
if (const char *e = SBC_ENV("SBC_TRACE_OBJECTS"); e && render::frames() == std::strtoull(e, nullptr, 0))
std::printf("[sbc:obj] skinned %08x bones %u texture %08x object t %.3f %.3f %.3f\n", prim, boneCount,
g_textureImage, object[3][0], object[3][1], object[3][2]);
const MaterialTexture t = materialTexture();
// The driver picks the program set by the bone count (0x23a990): under 2 bones set 1 (0x900.., L_09d0), whose
// kernels light with the setup program's vf5-vf7 (the lights turned into the object's space by its normalized
// rows, the object's matrix being the one bone's) and the stored normal; from 2 bones set 3 (0x4d0.., L_0570),
// which loads VU 64-66 as they are (L_0e98) and lights the normal the skinning kernels (L_1330: L_2d00.. for 2-6
// bones, L_1418 for 7-8) passed through the weighted bones' matrices, not normalized again.
// SBC_3D_BIND_NORMALS=1: the world lights on the stored normal for both (a diagnostic, the earlier choice).
static const bool bindNormals = std::getenv("SBC_3D_BIND_NORMALS") != nullptr;
Lights lights = lightsOf(spr, object, boneCount < 2 && !bindNormals);
// Flags 0x800: toon (0x23abf8): CLAMP 5, VU108 the toon colour table's qword x the global colour as for type 72,
// the entry from 0x42afb0 (vi2 5 / 0x85: L_1a40 puts s, t = 0.5 + 0.5 n . L0, 0.5, L_25f8 colours it) — the
// skin's ramp (the faces, arms). SBC_3D_NO_TOON=1: Lambert with the mesh's s, t (a diagnostic).
static const bool noToon = std::getenv("SBC_3D_NO_TOON") != nullptr;
if (!noToon && (rd32(prim + 8) & 0x800u) && lights.on)
makeToon(lights, spr, rd32(prim + 8));
else
unlitMode(lights, prim);
if (traceChain())
std::printf("[sbc:chain] skinned %08x modes %08x diffuse %g %g %g emission %g %g %g chain %08x resets %llu\n", prim,
modeBits(prim), lights.diffuse[0], lights.diffuse[1], lights.diffuse[2], lights.emission[0], lights.emission[1],
lights.emission[2], rd32(g_gp - 0x7d10u), static_cast<unsigned long long>(g_chainResets));
if (traceChain())
for (uint32_t n : {64u, 65u, 66u, 67u, 72u, 75u})
{
const float *sent = vuQword(n), *staged = reinterpret_cast<const float *>(spr + 0x240u + n * 16u);
std::printf("[sbc:chain] VU%u staged %.3f %.3f %.3f %.3f sent %s %.3f %.3f %.3f %.3f\n", n, staged[0], staged[1],
staged[2], staged[3], sent ? "yes" : "no", sent ? sent[0] : 0.0f, sent ? sent[1] : 0.0f,
sent ? sent[2] : 0.0f, sent ? sent[3] : 0.0f);
}
if (const char *e = SBC_ENV("SBC_TRACE_LIGHTS"); e && render::frames() == std::strtoull(e, nullptr, 0))
{
const float *v = reinterpret_cast<const float *>(spr + 0x240u + 64u * 16u);
std::printf("[sbc:lights] %08x bones %u material %08x diffuse %g %g %g emission %g %g %g TEXimage %08x L0 %.2f %.2f "
"%.2f\n",
prim, boneCount, g_material, lights.diffuse[0], lights.diffuse[1], lights.diffuse[2], lights.emission[0],
lights.emission[1], lights.emission[2], g_textureImage, v[0], v[4], v[8]);
}
const MaterialColour material = materialColourOf(spr, ctx->r[28].uw[0]);
std::vector<Vertex> lists[4];
batches(prim + 0x30, [&](uint32_t count, uint32_t stride, uint32_t at, uint32_t gsPrim) {
if (skipUntextured(gsPrim))
return;
strip(count, stride, at, t, lights, material, lists[kindOf(gsPrim)], [&](uint32_t v, float scale, Vertex &o, float *normal) {
const float p[3] = {rd16(v) * scale, rd16(v + 2) * scale, rd16(v + 4) * scale};
float w[4] = {0, 0, 0, 0}, n[3] = {0, 0, 0}, total = 0;
for (uint32_t k = 0; k < 8; ++k)
{
const float weight = stride >= 5 ? rd16(v + 24 + 2 * k) / 4096.0f : (k == 0 ? 1.0f : 0.0f);
if (!weight || !used[k])
continue;
total += weight;
for (int j = 0; j < 4; ++j)
w[j] += weight * (p[0] * bones[k][0][j] + p[1] * bones[k][1][j] + p[2] * bones[k][2][j] + bones[k][3][j]);
for (int j = 0; j < 3; ++j)
n[j] += weight * (normal[0] * bones[k][0][j] + normal[1] * bones[k][1][j] + normal[2] * bones[k][2][j]);
}
if (total == 0)
for (int j = 0; j < 4; ++j)
w[j] = p[0] * bones[0][0][j] + p[1] * bones[0][1][j] + p[2] * bones[0][2][j] + bones[0][3][j];
o.x = w[0];
o.y = w[1];
o.z = w[2];
// From 2 bones the kernels light the skinned normal as it comes out (scale and weights included).
if (boneCount > 1 && !bindNormals)
for (int j = 0; j < 3; ++j)
normal[j] = n[j];
});
});
(void)identity;
const std::vector<Vertex> &triangles = !lists[3].empty() ? lists[3] : lists[1];
if (static int traced = 0; SBC_ENV("SBC_TRACE_SKIN") && render::frames() >= std::strtoull(SBC_ENV("SBC_TRACE_SKIN"), nullptr, 0) && traced < 6 && !triangles.empty())
{
++traced;
std::printf("[sbc:skin] prim %08x bones", prim);
for (uint32_t k = 0; k < 8; ++k)
if (used[k])
std::printf(" [%d: t %.2f %.2f %.2f | x %.2f %.2f %.2f]", static_cast<int32_t>(rd32(prim + 0x10 + 4 * k)),
bones[k][3][0], bones[k][3][1], bones[k][3][2], bones[k][0][0], bones[k][0][1], bones[k][0][2]);
std::printf("\n[sbc:skin] first vertex world %.2f %.2f %.2f; object matrix t %.2f %.2f %.2f\n", triangles[0].x,
triangles[0].y, triangles[0].z, reinterpret_cast<const float *>(spr + 0x240u)[12],
reinterpret_cast<const float *>(spr + 0x240u)[13], reinterpret_cast<const float *>(spr + 0x240u)[14]);
std::printf("[sbc:skin] object x %.2f %.2f %.2f y %.2f %.2f %.2f z %.2f %.2f %.2f\n", object[0][0], object[0][1],
object[0][2], object[1][0], object[1][1], object[1][2], object[2][0], object[2][1], object[2][2]);
}
keepAll(toScreen, t, lists, spr, outlineOf(prim, prim + 0x30, spr), lights.on && !lights.toon);
return false; // the driver goes on (its VU packets are not drawn)
}
void install(bozo::port::Registry &r)
{
r.registerFunction(0x237df0, drawGeometry); // IMD type 72, mode 4
r.registerFunction(0x23b1f0, drawGeometry); // IMD type 73 (a colour a vertex), mode 4
}
// ScrnEffHueAdd (0x1af6a0, each frame; the object at *(0x58bdf0)): the game turns the depth buffer into
// D = min(255, Z >> (24 - p)) (ZSys 0x1adf20; p at +0x64f0), then for each enabled entry of the active page
// (+0x6328; four of 0x38 bytes from +0x632c, a page 0xe0) writes Ad = CLUT[D] into the frame's alpha (DAlphaSys
// 0x1adcd0; the CLUT from 0x1acf60: v = min(256, 256 ln(1 + D / 2^k) / ln(1 + 256 / 2^k)), Ad = (128 - v / 2) x
// alpha (+4) x the global alpha (+0x64fc); flags +0x2c bit 0 takes v / 2, bit 1 reverses D) and fills the screen in
// the entry's HSV colour (+0x14..+0x1c) blended by it (FillSys 0x1aee00): blend 2 adds, rgb += C Ad / 128. On the
// beach two entries add a warm and a violet haze by distance (the lavender far scene and sky). Natively: one
// additive full-screen draw whose colour comes from the depth (the renderer's depth lookup, 64 steps of D).
void screenEffects(Renderer &renderer, const bozo::render::Screen &screen)
{
static const bool none = std::getenv("SBC_NO_SCREEN_EFFECTS") != nullptr; // a diagnostic
if (none || !g_ram)
return;
const auto f32 = [](uint32_t a) {
float v;
std::memcpy(&v, g_ram + (a & 0x1FFFFFFu), 4);
return v;
};
const uint32_t object = rd32(0x58bdf0u);
if (object < 0x100000u || object >= 0x2000000u)
return;
const uint32_t page = rd32(object + 0x6328u);
if (page > 3)
return;
const float shift = f32(object + 0x64f0u), global = f32(object + 0x64fcu);
if (!(shift >= 0 && shift <= 24))
return;
float added[64][3] = {};
bool any = false;
for (uint32_t i = 0; i < 4; ++i)
{
const uint32_t e = object + 0x632cu + page * 0xe0u + i * 0x38u;
if (!g_ram[e + 8])
continue;
const uint32_t blend = rd32(e), kind = rd32(e + 0xc), mode = rd32(e + 0x20), flags = rd32(e + 0x2c);
if (blend != 2 || kind != 0 || mode != 1)
{
if (static int traced = 0; traced++ < 4)
std::printf("[sbc:3d] screen effect entry %u: blend %u kind %u mode %u not drawn\n", i, blend, kind, mode);
continue;
}
// HSV (degrees, 0..1, 0..1) to RGB (0x1ad9c0).
const float h = f32(e + 0x14), s = f32(e + 0x18), v = f32(e + 0x1c);
const float c = v * s, hh = std::fmod(h < 0 ? h + 360.0f : h, 360.0f) / 60.0f;
const float x = c * (1 - std::fabs(std::fmod(hh, 2.0f) - 1)), m = v - c;
float rgb[3];
switch (static_cast<int>(hh))
{
case 0: rgb[0] = c, rgb[1] = x, rgb[2] = 0; break;
case 1: rgb[0] = x, rgb[1] = c, rgb[2] = 0; break;
case 2: rgb[0] = 0, rgb[1] = c, rgb[2] = x; break;
case 3: rgb[0] = 0, rgb[1] = x, rgb[2] = c; break;
case 4: rgb[0] = x, rgb[1] = 0, rgb[2] = c; break;
default: rgb[0] = c, rgb[1] = 0, rgb[2] = x; break;
}
const float alpha = f32(e + 4), b = std::pow(2.0f, f32(e + 0x30));
for (int bucket = 0; bucket < 64; ++bucket)
{
int d = bucket * 4 + 2;
if (flags & 2u)
d = 255 - d;
const int curve = std::min(256, static_cast<int>(256.0f * std::log(1.0f + d / b) / std::log(1.0f + 256.0f / b)));
const float base = (flags & 1u) ? static_cast<float>(curve >> 1) : 128.0f - static_cast<float>(curve >> 1);
const float ad = std::floor(base * alpha * global);
for (int k = 0; k < 3; ++k)
added[bucket][k] += (rgb[k] + m) * ad / 128.0f;
}
any = true;
}
if (!any)
return;
auto processing = std::make_shared<Material::ImageProcessing>();
processing->depthLookup = true;
processing->depthColours = true;
// The renderer's index is (1 - window depth) x scale = Z / depthMax x scale: one entry per four steps of D.
processing->depthScale = screen.depthMax / (std::pow(2.0f, 24.0f - shift) * 4.0f);
for (int bucket = 0; bucket < 64; ++bucket)
{
for (int k = 0; k < 3; ++k)
processing->depthWeights[4 * bucket + k] = std::min(1.0f, added[bucket][k]);
processing->depthWeights[4 * bucket + 3] = 1.0f;
}
Material m;
m.textured = false;
m.blend = Material::Blend::Additive;
m.alphaTest = false;
m.depthTest = false;
m.depthWrite = false;
m.imageProcessing = processing;
const auto corner = [](float x, float y) {
Vertex v;
v.x = x, v.y = y, v.z = 0, v.rgba = 0x80808080u;
return v;
};
const float x0 = screen.originX, y0 = screen.originY, x1 = x0 + screen.width, y1 = y0 + screen.height;
const Vertex quad[6] = {corner(x0, y0), corner(x1, y0), corner(x0, y1), corner(x1, y0), corner(x1, y1), corner(x0, y1)};
static const float identity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
renderer.draw(m, identity, quad, 6);
if (static int traced = 0; trace() && traced++ < 2)
std::printf("[sbc:3d] screen effect: p %g, far +(%.2f %.2f %.2f), D 128 +(%.2f %.2f %.2f)\n", shift, added[0][0],
added[0][1], added[0][2], added[32][0], added[32][1], added[32][2]);
}
void submit(Renderer &renderer)
{
// The game's order: its packets go out bucket by bucket (the sky and the opaque world before the translucent
// layers that blend over them), each bucket in the order its drivers wrote it.
static const bool callOrder = std::getenv("SBC_3D_CALL_ORDER") != nullptr; // a diagnostic: the drivers' order
if (!callOrder)
std::stable_sort(g_meshes.begin(), g_meshes.end(), [](const Mesh &a, const Mesh &b) { return a.bucket < b.bucket; });
if (trace() && !g_meshes.empty())
{
std::map<uint32_t, uint32_t> buckets;
for (const Mesh &m : g_meshes)
++buckets[m.bucket];
std::printf("[sbc:3d] buckets:");
for (const auto &[b, n] : buckets)
std::printf(" %u:%u", b, n);
std::printf("\n");
}
for (const Mesh &m : g_meshes)
renderer.draw(m.material, m.matrix, m.vertices.data(), static_cast<uint32_t>(m.vertices.size()), m.texture);
if (trace() && !g_meshes.empty())
std::printf("[sbc:3d] kick %llu: %zu meshes (%llu skinned), %llu triangles\n",
static_cast<unsigned long long>(render::frames()), g_meshes.size(),
static_cast<unsigned long long>(g_skinned), static_cast<unsigned long long>(g_triangles));
g_meshes.clear();
g_worldTriangles.clear();
g_primitives = g_triangles = g_skinned = 0;
}
} // namespace sbc::draw3d