mirror of
https://github.com/TheBozos/DC_Recomp.git
synced 2026-12-01 07:38:29 -10:00
CFrameVu1::DrawVu1 skips a model whose projected bounding box lies wholly more than 320 px from the screen centre, the 4:3 half width. In 16:9 the frame reaches 426.67 px each side, so models in the extra strips vanished until they crossed into the 4:3 area. Its two loads of 320.0 (0x129ab4, 0x129ae4) become guarded native sites returning the drawn frame's half width: 426.67 in widescreen, 320 in 4:3 (the same constant as before, so 4:3 is unchanged). Checked headless from a Wise Owl Forest save state while turning the camera: the old and new bounds give identical centres in all 39 frames, and the differences lie only in the side strips, where plants and rocks now show. Co-Authored-By: Claude Opus 5.5 <[email protected]>
5483 lines
330 KiB
C++
5483 lines
330 KiB
C++
// Native PC rendering, Dark Cloud's adapter: DC's 3D models drawn by the fork's native renderer
|
|
// (bozo::render::Renderer) from the game's own data, not by VU1 and the GS.
|
|
//
|
|
// Nothing here reads a packet the game builds for the PS2 hardware (no VIF / GIF / GS data): every draw comes from
|
|
// the game's own structures, as its EE code holds them.
|
|
// - CVisualVu1::DrawVu1 (0x135000) is where DC draws a model piece: the visual, its local-to-world matrix (a2), its
|
|
// RenderInfo (a3: the camera's matrices, the lights, shadow and fog switches) and the VU1 program (t0).
|
|
// - The geometry is the model's MDT, the data DC builds the piece's VU data from (CreateVUdataFromMDT 0x135AA0,
|
|
// CreateVUdataFromMDTRemake 0x135E50, hooked to note which MDT a visual is made of; CVisualMDTVu1 also keeps it at
|
|
// + 0x20): positions, normals, texture coordinates and colours, and a list of primitives (strip or triangle list,
|
|
// count, material) of index tuples into them.
|
|
// - A material's texture is the CTextureManager record its name finds (as CreateVUdataFromMDT finds it), decoded from
|
|
// the record's own pixels and palette in main memory.
|
|
// - An object's alpha test, Z write and translucency are the values CFrameVu1::DrawVu1 hands SetGsReg3 (0x129360).
|
|
// - The transform, the lights and the texture coordinate scale are DrawVu1's own computation (its header) redone from
|
|
// RenderInfo; the lighting is the VU1 program's formula.
|
|
// VU1 is told to skip every program (setVu1Gate): it runs no microcode. The native batches are numbered as the
|
|
// programs VU1 skips (renderer groups), one per primitive, as CreateVUdataFromMDT starts one program per primitive.
|
|
//
|
|
// Always on: Dark Cloud's picture has no other path (no GS).
|
|
|
|
#include "dc_native_api.h"
|
|
#include "dc_visibility.h"
|
|
#include "bozo/state.h"
|
|
#include "bozo/render/renderer.h"
|
|
#include "bozo/hash.h"
|
|
#include "bozo/libs/guest.h"
|
|
#include "bozo/runtime_api.h"
|
|
|
|
#include <array>
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <filesystem>
|
|
#include <string>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <stdexcept>
|
|
#include <unordered_map>
|
|
#include <unordered_set>
|
|
#include <vector>
|
|
|
|
namespace dc::native
|
|
{
|
|
static std::string assetDirectory;
|
|
void setAssetDirectory(const std::string &path) { assetDirectory = path; }
|
|
void publish(); // the game frame's end: below
|
|
namespace
|
|
{
|
|
constexpr uint32_t kVisualDrawVu1 = 0x00135000u; // CVisualVu1::DrawVu1(uint *, float (*)[4], RenderInfo *, ...)
|
|
uint64_t g_nativeFrameDraws = 0, g_nativeFrameMemberDraws = 0;
|
|
// The raw frame methods retain DC's hierarchy, LOD and lighting work.
|
|
// Their output pointer only reaches native material/visual draws, which
|
|
// return zero packet words. The outer wrappers no longer need a packet.
|
|
void frameDrawHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const bool global = ctx->pc == 0x0012ED80u; // MGDraw(CFrame *)
|
|
const uint32_t caller = ctx->r[31].uw[0];
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
const uint32_t frame = guest.arg(0);
|
|
if (global && frame == 0u)
|
|
{
|
|
ctx->pc = caller;
|
|
return;
|
|
}
|
|
const uint32_t method = guest.read32(guest.read32(frame + 0x250u) + 8u);
|
|
if (method != 0x00129400u && method != 0x0012A1A0u)
|
|
throw std::runtime_error("native frame draw: unsupported virtual method");
|
|
++(global ? g_nativeFrameDraws : g_nativeFrameMemberDraws);
|
|
ctx->r[5] = {}; // no console output buffer
|
|
if (global)
|
|
{
|
|
ctx->r[6] = {};
|
|
ctx->r[6].uw[0] = 0x01C75520u;
|
|
}
|
|
bozo_call_indirect(rdram, ctx, runtime, method);
|
|
if (ctx->pc == caller && !ctx->leaving && ctx->r[2].uw[0] != 0u)
|
|
throw std::runtime_error("native frame draw: unexpected console output words");
|
|
}
|
|
constexpr uint32_t kCreateFromMdt = 0x00135AA0u; // CVisualVu1::CreateVUdataFromMDT(uint *, uint *, int)
|
|
constexpr uint32_t kCreateFromMdtRemake = 0x00135E50u; // CVisualVu1::CreateVUdataFromMDTRemake(uint *, uint *, int)
|
|
constexpr uint32_t kSetGsReg3 = 0x00129360u; // SetGsReg3(uint *, ulong *TEST, ulong *ZBUF, ulong *ALPHA)
|
|
constexpr uint32_t kVtVisualMdtVu1 = 0x002A11A0u; // __vt__13CVisualMDTVu1
|
|
constexpr uint32_t kTextureManager = 0x01C75870u; // the CTextureManager every MDT material's texture is in
|
|
uint64_t g_nativeModelBuilds = 0, g_nativeModelRemakes = 0, g_nativeShadowBuilds = 0, g_nativeClothBuilds = 0;
|
|
uint64_t g_retiredModelBytes = 0;
|
|
// DC_PROBE_EXTENTS=1 (diagnosis): every model, remake, shadow and cloth buffer is filled with a pattern when
|
|
// built (the native builders write nothing there and nothing should read it); every 60 frames the buffers
|
|
// built in the last 600 frames are checked, and any byte something else changed is reported once per buffer.
|
|
uint32_t extentWord(const uint8_t *rdram, uint32_t address)
|
|
{
|
|
uint32_t value;
|
|
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), 4);
|
|
return value;
|
|
}
|
|
struct ExtentCanary { uint32_t data = 0, bytes = 0, visual = 0, vtable = 0; uint64_t frame = 0; const char *kind = ""; bool reported = false; };
|
|
std::vector<ExtentCanary> g_extentCanaries;
|
|
uint64_t g_extentFrame = 0, g_extentChecked = 0, g_extentChanged = 0, g_extentLive = 0;
|
|
const uint8_t *g_extentRam = nullptr; // guest RAM, from the first build
|
|
bool extentProbe() { static const bool on = std::getenv("DC_PROBE_EXTENTS") != nullptr; return on; }
|
|
uint8_t extentPattern(uint32_t address) { return static_cast<uint8_t>(0xC5u ^ (address >> 4)); }
|
|
void extentFill(uint8_t *rdram, uint32_t data, uint32_t bytes, const char *kind, uint32_t visual)
|
|
{
|
|
if (!extentProbe() || bytes == 0u || bytes > 0x400000u) return;
|
|
g_extentRam = rdram;
|
|
for (uint32_t i = 0; i < bytes; ++i) rdram[(data + i) & 0x1FFFFFFu] = extentPattern(data + i);
|
|
// A rebuild of the same buffer starts its watch again.
|
|
std::erase_if(g_extentCanaries, [&](const ExtentCanary &c) { return c.data == data; });
|
|
g_extentCanaries.push_back({data, bytes, visual, extentWord(rdram, visual + 8u), g_extentFrame, kind});
|
|
}
|
|
void extentCheck(const uint8_t *rdram)
|
|
{
|
|
if (!extentProbe()) return;
|
|
++g_extentFrame;
|
|
if (g_extentFrame % 60u != 0u) return;
|
|
std::erase_if(g_extentCanaries, [](const ExtentCanary &c) { return g_extentFrame - c.frame > 600u; });
|
|
for (auto &c : g_extentCanaries)
|
|
{
|
|
++g_extentChecked;
|
|
if (c.reported) continue;
|
|
for (uint32_t i = 0; i < c.bytes; ++i)
|
|
if (rdram[(c.data + i) & 0x1FFFFFFu] != extentPattern(c.data + i))
|
|
{
|
|
c.reported = true;
|
|
++g_extentChanged;
|
|
// Live: the visual still has its vtable and still points at this buffer with this size.
|
|
const bool live = extentWord(rdram, c.visual + 8u) == c.vtable && extentWord(rdram, c.visual + 0x18u) == c.data &&
|
|
extentWord(rdram, c.visual + 0x1Cu) * 16u == c.bytes;
|
|
if (live) ++g_extentLive;
|
|
if (live)
|
|
{
|
|
const uint32_t at = (c.data + (i & ~15u)) & 0x1FFFFFFu;
|
|
std::fprintf(stderr, "[dc:extent] new bytes at +0x%x: %08x %08x %08x %08x; visual +0x18 %08x +0x1c %08x\n",
|
|
i & ~15u, extentWord(rdram, at), extentWord(rdram, at + 4u), extentWord(rdram, at + 8u),
|
|
extentWord(rdram, at + 12u), extentWord(rdram, c.visual + 0x18u), extentWord(rdram, c.visual + 0x1Cu));
|
|
}
|
|
std::fprintf(stderr, "[dc:extent] %s buffer %08x (%u bytes, visual %08x, built frame %llu): byte +0x%x changed by frame %llu, %s\n",
|
|
c.kind, c.data, c.bytes, c.visual, static_cast<unsigned long long>(c.frame), i,
|
|
static_cast<unsigned long long>(g_extentFrame), live ? "VISUAL STILL OWNS IT" : "visual gone or moved");
|
|
break;
|
|
}
|
|
}
|
|
if (g_extentFrame % 600u == 0u)
|
|
std::fprintf(stderr, "[dc:extent] frame %llu: %zu buffers watched, %llu checks, %llu changed, %llu while their visual owned them\n",
|
|
static_cast<unsigned long long>(g_extentFrame), g_extentCanaries.size(),
|
|
static_cast<unsigned long long>(g_extentChecked), static_cast<unsigned long long>(g_extentChanged),
|
|
static_cast<unsigned long long>(g_extentLive));
|
|
}
|
|
uint64_t g_group = 0;
|
|
|
|
struct Stats
|
|
{
|
|
uint64_t calls = 0, noModel = 0, primitives = 0, triangles = 0, shadows = 0, screenSpace = 0;
|
|
uint64_t ownTextures = 0, noTexture = 0, gsOrderTextures = 0, cloths = 0, shadowTriangles = 0, waters = 0, staleModel = 0, mdtDiffers = 0, noZWrite = 0, copiedModel = 0, depthOfFields = 0, culled = 0, zPast24 = 0, zNegative = 0, guarded = 0, textureCopies = 0, textureCopiesMissed = 0, stretches = 0, stretchesMissed = 0, madeDraws[9] = {}, clears = 0, lastClear = 0;
|
|
double maxZ = -1e30, minZ = 1e30;
|
|
} g_stats;
|
|
bool g_inSky = false, g_sampleSkyDraws = false;
|
|
uint32_t g_skyDrawIndex = 0;
|
|
std::atomic<uint64_t> g_gateSkipped{0};
|
|
|
|
uint32_t rd32(const uint8_t *rdram, uint32_t address)
|
|
{
|
|
uint32_t value = 0;
|
|
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), sizeof(value));
|
|
return value;
|
|
}
|
|
|
|
float rdf(const uint8_t *rdram, uint32_t address)
|
|
{
|
|
float value = 0.0f;
|
|
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), sizeof(value));
|
|
return value;
|
|
}
|
|
|
|
uint64_t rd64(const uint8_t *rdram, uint32_t address)
|
|
{
|
|
uint64_t value = 0;
|
|
std::memcpy(&value, rdram + (address & 0x1FFFFFFu), sizeof(value));
|
|
return value;
|
|
}
|
|
|
|
void wr64(uint8_t *rdram, uint32_t address, uint64_t value)
|
|
{
|
|
std::memcpy(rdram + (address & 0x1FFFFFFu), &value, sizeof(value));
|
|
}
|
|
|
|
// Widescreen (the engine's Settings::widescreen, posted each frame by dc_main): the frame is 16:9, 853.33 GS
|
|
// pixels wide (640 x 4/3) about the game's own centre (x 2048). The 3D shows more at the sides (Hor+: the game's
|
|
// projection is unchanged, its culling widened, see clipVertexHook); the game's 2D stays where it was, centred,
|
|
// except full-frame draws (clears, fills, fades, frame copies), which span the whole width, and the HUD's side
|
|
// pieces, which move out to the edges (hudShift). Latched once per frame, at its start (screen()).
|
|
std::atomic<bool> g_wideRequest{false};
|
|
bool g_wideFrame = false;
|
|
float frameW() { return g_wideFrame ? 640.0f * 4.0f / 3.0f : 640.0f; }
|
|
float frameLeft() { return 2048.0f - frameW() / 2.0f; }
|
|
// A span of the game's 640-wide frame (game x, 0..640) in GS x: the whole frame stays the whole, wider, frame.
|
|
bool wholeSpan(float x0, float x1) { return x0 <= 0.5f && x1 >= 639.5f; }
|
|
float spanLeft(float x0, float x1) { return g_wideFrame && wholeSpan(x0, x1) ? frameLeft() : 1728.0f + x0; }
|
|
float spanRight(float x0, float x1) { return g_wideFrame && wholeSpan(x0, x1) ? frameLeft() + frameW() : 1728.0f + x1; }
|
|
// An untextured fill's edges (game x): one on the frame's left or right edge reaches the wider frame's edge (the
|
|
// dungeon's fade is 64 x 32 tiles over the frame, letterbox bars and backgrounds touch the edges).
|
|
float fillLeft(float x0) { return g_wideFrame && x0 <= 0.5f ? frameLeft() : 1728.0f + x0; }
|
|
float fillRight(float x1) { return g_wideFrame && x1 >= 639.5f ? frameLeft() + frameW() : 1728.0f + x1; }
|
|
// A frame-sampling texture coordinate (0..1 over the frame) for GS x.
|
|
float frameU(float gsX) { return (gsX - frameLeft()) / frameW(); }
|
|
// A copy between the game's frame-sized pictures, x spans in game pixels: its GS x and its u (0..1 over the
|
|
// frame). Under widescreen each side is taken on its own: the whole 640 is the whole wider frame (a source over
|
|
// it samples all of it, a destination over it covers all of it); a part keeps its game pixels. So the game's
|
|
// half-size work copies of the frame (the whole frame into 0..320) hold the whole wider frame squeezed, and
|
|
// drawn back over the whole frame they spread it out again.
|
|
struct CopySpan
|
|
{
|
|
float x0, x1, u0, u1;
|
|
};
|
|
CopySpan copySpan(float dst0, float dst1, float src0, float src1)
|
|
{
|
|
const bool wideDst = g_wideFrame && wholeSpan(dst0, dst1), wideSrc = g_wideFrame && wholeSpan(src0, src1);
|
|
return {wideDst ? frameLeft() : 1728.0f + dst0, wideDst ? frameLeft() + frameW() : 1728.0f + dst1,
|
|
wideSrc ? 0.0f : frameU(1728.0f + src0), wideSrc ? 1.0f : frameU(1728.0f + src1)};
|
|
}
|
|
// The HUD under widescreen: while the game draws its field HUD (g_hudScope > 0, inside the HUD routines hooked
|
|
// in installWideHud), a piece in the left third of the game's frame moves to the left edge, one in its right
|
|
// third to the right edge; the middle stays. Menus, dialogue and pictures stay centred.
|
|
int g_hudScope = 0;
|
|
// The minimap moves as one piece (its large centred view stays centred): its first piece decides, and the
|
|
// monster symbols drawn on it after (DrawMapSymbol, the key finder's marker) take the same shift.
|
|
int g_mapScope = 0;
|
|
bool g_mapDecided = false;
|
|
float g_mapShift = 0.0f;
|
|
uint32_t g_2dCallerSeen = 0; // the 2D routine's caller (set by the 2D hooks)
|
|
float thirdShift(float gameLo, float gameHi)
|
|
{
|
|
const float half = (frameW() - 640.0f) / 2.0f, middle = (gameLo + gameHi) / 2.0f;
|
|
return middle < 640.0f / 3.0f ? -half : middle > 1280.0f / 3.0f ? half : 0.0f;
|
|
}
|
|
float hudShift(float gameLo, float gameHi)
|
|
{
|
|
if (!g_wideFrame)
|
|
return 0.0f;
|
|
const uint32_t caller = g_2dCallerSeen;
|
|
if (g_mapScope > 0)
|
|
{
|
|
if (!g_mapDecided)
|
|
g_mapShift = thirdShift(gameLo, gameHi), g_mapDecided = true;
|
|
return g_mapShift;
|
|
}
|
|
// DrawMapSymbol (0x1D7AA0..0x1D7C78) and the key finder's marker (drawn from a hook: its return is the
|
|
// cheats' sentinel, 0x80000) lie on the minimap.
|
|
if ((caller >= 0x001D7AA0u && caller < 0x001D7C78u) || caller == 0x00080000u)
|
|
return g_mapShift;
|
|
// DUN's MainDraw draws the weapon-ready plate itself (beside the attack gauge, bottom left).
|
|
if (g_hudScope > 0 || caller == 0x01DB019Cu)
|
|
return thirdShift(gameLo, gameHi);
|
|
return 0.0f;
|
|
}
|
|
|
|
bozo::render::Screen screen()
|
|
{
|
|
// DC's drawing environment: 640 x 224 fields, XYOFFSET (1728, 1936) (0x6C00, 0x7900 in 12.4); widescreen
|
|
// widens it about the same centre.
|
|
bozo::render::Screen s;
|
|
s.originX = frameLeft();
|
|
s.originY = 1936.0f;
|
|
s.width = frameW();
|
|
s.height = 224.0f;
|
|
s.depthMax = 16777215.0f;
|
|
// The models' GIF tag writes ST, RGBAQ, XYZF2 (REGS 0x412) PACKED: the GS takes Z from bits 4..27 of the
|
|
// FTOI4 word, so Z is the matrices' z / w itself (24 bits), not 16 x it as an XYZ2 would have it.
|
|
s.gsZScale = 1.0f;
|
|
return s;
|
|
}
|
|
// A frame's start: widescreen is latched for the whole frame.
|
|
bozo::render::Screen beginScreen()
|
|
{
|
|
g_wideFrame = g_wideRequest.load(std::memory_order_relaxed);
|
|
return screen();
|
|
}
|
|
|
|
// DC's matrices as its VU0 code keeps them: four columns of four floats. mul(a, b) = a x b (MulMatrix).
|
|
struct Matrix
|
|
{
|
|
float m[16];
|
|
};
|
|
Matrix load(const uint8_t *rdram, uint32_t address)
|
|
{
|
|
Matrix out;
|
|
for (int i = 0; i < 16; ++i)
|
|
out.m[i] = rdf(rdram, address + static_cast<uint32_t>(i) * 4u);
|
|
return out;
|
|
}
|
|
Matrix mul(const Matrix &a, const Matrix &b)
|
|
{
|
|
Matrix out;
|
|
for (int c = 0; c < 4; ++c)
|
|
for (int r = 0; r < 4; ++r)
|
|
out.m[c * 4 + r] = a.m[0 * 4 + r] * b.m[c * 4 + 0] + a.m[1 * 4 + r] * b.m[c * 4 + 1] +
|
|
a.m[2 * 4 + r] * b.m[c * 4 + 2] + a.m[3 * 4 + r] * b.m[3 + c * 4];
|
|
return out;
|
|
}
|
|
|
|
// VU1 skips every program it is asked to run: it runs no microcode. The counters below count the skipped
|
|
// programs by their start address.
|
|
std::atomic<uint64_t> g_gateByPc[4]{}; // diagnosis: skipped at pc 0, 8 (the models'), at another pc, the last other
|
|
bool gate(const uint8_t *, uint32_t pc)
|
|
{
|
|
g_gateSkipped.fetch_add(1u, std::memory_order_relaxed);
|
|
g_gateByPc[pc == 0u ? 0 : pc == 8u ? 1 : 2].fetch_add(1u, std::memory_order_relaxed);
|
|
if (pc != 0u && pc != 8u)
|
|
g_gateByPc[3].store(pc, std::memory_order_relaxed);
|
|
return true;
|
|
}
|
|
|
|
// The model a visual is made of. DC builds a visual's VU data from an MDT (CreateVUdataFromMDT /
|
|
// ...Remake: "MDT\0", its size at + 8) and, for most static pieces (the town's map parts), the MDT's memory is
|
|
// used for other data afterwards: the VU data is all that is left in the game, and it is not read here. So the
|
|
// MDT is copied when the game builds from it (its own model data, still valid then), keyed by the VU data it
|
|
// builds. Static visuals always use that owned copy: a matching header in released source memory does not
|
|
// establish ownership of its body. Animated MDT visuals explicitly retain their source at + 0x20, and
|
|
// Remake refreshes the captured geometry at its original update boundary.
|
|
// Its textures are bound there too: CreateVUdataFromMDT takes each primitive's material texture by name
|
|
// (GetTextureHandle -> SearchTextureName, the newest record of that name; none: handle -1, which GetTexture
|
|
// takes as record 0) and writes that record's TEX0 into the VU data; Remake keeps it. Native image ownership
|
|
// captures successful named lookups only: the allocator fallback cannot grant a missing material ownership
|
|
// of a generated work image. Bindings are captured per primitive when the game builds: a later lookup found another model's
|
|
// newer texture of the same name (the Colonel's face blank once Seth and the Genie were loaded).
|
|
struct TextureBinding
|
|
{
|
|
uint32_t record = 0;
|
|
mutable uint32_t resolvedRecord = 0;
|
|
std::array<uint8_t, 0x50> identity{};
|
|
mutable std::shared_ptr<const bozo::render::Texture> image;
|
|
uint32_t word(uint32_t offset) const { uint32_t v; std::memcpy(&v,identity.data()+offset,4); return v; }
|
|
uint64_t tex0() const { uint64_t v; std::memcpy(&v,identity.data()+0x28,8); return v; }
|
|
};
|
|
std::shared_ptr<const bozo::render::Texture> recordTexture(const uint8_t *, uint32_t);
|
|
uint32_t resolveBinding(const uint8_t *rdram, const TextureBinding &binding)
|
|
{
|
|
if (!binding.record) return 0;
|
|
const int32_t last = std::min(static_cast<int32_t>(rd32(rdram, kTextureManager)), 1023);
|
|
const uint32_t first = kTextureManager + 0x10F8u;
|
|
auto matches = [&](uint32_t record) {
|
|
return record >= first && (record-first)%0x50u == 0 &&
|
|
static_cast<int32_t>((record-first)/0x50u) <= last &&
|
|
std::memcmp(rdram+record,binding.identity.data(),0x28)==0 &&
|
|
rd64(rdram,record+0x28)==binding.tex0() &&
|
|
rd32(rdram,record+0x38)==binding.word(0x38) &&
|
|
rd32(rdram,record+0x48)==binding.word(0x48);
|
|
};
|
|
if (matches(binding.resolvedRecord ? binding.resolvedRecord : binding.record))
|
|
return binding.resolvedRecord ? binding.resolvedRecord : binding.record;
|
|
for (int32_t i=last;i>=0;--i)
|
|
if (matches(first+static_cast<uint32_t>(i)*0x50u))
|
|
return binding.resolvedRecord = first+static_cast<uint32_t>(i)*0x50u;
|
|
return 0;
|
|
}
|
|
struct Model
|
|
{
|
|
const uint8_t *rdram = nullptr;
|
|
std::shared_ptr<const std::vector<uint8_t>> copy;
|
|
std::shared_ptr<const std::vector<TextureBinding>> records; // asset identities, not reusable table slots
|
|
uint32_t mdt = 0;
|
|
explicit operator bool() const { return mdt != 0u; }
|
|
uint32_t u32(uint32_t address) const
|
|
{
|
|
if (!copy)
|
|
return rd32(rdram, address);
|
|
const uint32_t offset = address - mdt;
|
|
uint32_t value = 0;
|
|
if (offset <= copy->size() && copy->size() - offset >= 4u)
|
|
std::memcpy(&value, copy->data() + offset, 4);
|
|
return value;
|
|
}
|
|
float f(uint32_t address) const
|
|
{
|
|
const uint32_t bits = u32(address);
|
|
float value = 0.0f;
|
|
std::memcpy(&value, &bits, 4);
|
|
return value;
|
|
}
|
|
uint8_t u8(uint32_t address) const
|
|
{
|
|
if (!copy)
|
|
return rdram[address & 0x1FFFFFFu];
|
|
const uint32_t offset = address - mdt;
|
|
return offset < copy->size() ? (*copy)[offset] : 0u;
|
|
}
|
|
};
|
|
constexpr uint32_t kMdtMagic = 0x0054444Du; // "MDT\0"
|
|
std::mutex g_mdtMutex;
|
|
struct MdtCopy
|
|
{
|
|
uint32_t mdt = 0;
|
|
std::shared_ptr<const std::vector<uint8_t>> copy;
|
|
std::shared_ptr<const std::vector<TextureBinding>> records;
|
|
};
|
|
std::unordered_map<uint32_t, MdtCopy> g_mdtCopies; // VU data -> its MDT, a copy, its texture records
|
|
uint32_t textureRecord(const uint8_t *rdram, uint32_t name);
|
|
uint32_t boundRecord(const uint8_t *rdram, uint32_t name); // GetTexture(GetTextureHandle(name))
|
|
struct MdtPrimitive
|
|
{
|
|
uint32_t count, kind;
|
|
int32_t material;
|
|
};
|
|
struct MdtDescription
|
|
{
|
|
uint32_t size, stride, materials;
|
|
std::vector<MdtPrimitive> primitives;
|
|
};
|
|
MdtDescription describeMdt(bozo::libs::Guest &guest, uint32_t mdt, bool shadow)
|
|
{
|
|
guest.in(mdt, 0x40u);
|
|
MdtDescription model{guest.read32(mdt + 8u), static_cast<int32_t>(guest.read32(mdt + 0x20u)) > 0 ? 4u : 3u,
|
|
guest.read32(mdt + 0x38u), {}};
|
|
if (guest.read32(mdt) != kMdtMagic || model.size < 0x40u || model.size > 0x800000u)
|
|
throw std::runtime_error("native model: invalid MDT header");
|
|
guest.in(mdt, model.size);
|
|
const auto require = [&](uint32_t offset, uint64_t bytes) {
|
|
if (offset > model.size || bytes > model.size - offset)
|
|
throw std::runtime_error("native model: MDT range outside asset");
|
|
};
|
|
uint32_t at = guest.read32(mdt + 0x28u);
|
|
require(at, 16);
|
|
const uint32_t count = guest.read32(mdt + at + 8u);
|
|
if (count > 4096u) throw std::runtime_error("native model: too many MDT primitives");
|
|
at += 16u;
|
|
for (uint32_t p = 0; p < count; ++p)
|
|
{
|
|
require(at, 12);
|
|
const MdtPrimitive primitive{guest.read32(mdt + at + 4u), guest.read32(mdt + at),
|
|
static_cast<int32_t>(guest.read32(mdt + at + 8u))};
|
|
const uint64_t bytes = 12ull + static_cast<uint64_t>(primitive.count) * model.stride * 4u;
|
|
require(at, bytes);
|
|
if (shadow && primitive.count % 3u != 0u)
|
|
throw std::runtime_error("native shadow: incomplete triangle");
|
|
if (!shadow && primitive.material != -1)
|
|
{
|
|
if (primitive.material < 0) throw std::runtime_error("native model: invalid material index");
|
|
const uint64_t offset = static_cast<uint64_t>(model.materials) + static_cast<uint32_t>(primitive.material) * 0x60ull;
|
|
if (offset > model.size) throw std::runtime_error("native model: material outside asset");
|
|
require(static_cast<uint32_t>(offset), 0x60u);
|
|
}
|
|
model.primitives.push_back(primitive);
|
|
at += static_cast<uint32_t>(bytes);
|
|
}
|
|
return model;
|
|
}
|
|
// The extent a model, remake or shadow build reserves in the game's arena: one qword. CreateVisual allocates it
|
|
// at the data address it passed (and Align64 follows), so every build keeps a distinct, aligned address, the key
|
|
// of its retained MDT. The old VIF packet size reserved space nothing fills: DC_PROBE_EXTENTS found no game
|
|
// code writing into a live buffer (docs/BOZO_MIGRATION.md, "Model extents").
|
|
constexpr uint32_t kNativeModelQwords = 1u;
|
|
void noteMdt(const uint8_t *rdram, uint32_t data, uint32_t mdt, bool bind, const MdtDescription &model)
|
|
{
|
|
const uint32_t size = model.size;
|
|
auto copy = std::make_shared<std::vector<uint8_t>>(size);
|
|
for (uint32_t i = 0; i < size; ++i)
|
|
(*copy)[i] = rdram[(mdt + i) & 0x1FFFFFFu];
|
|
std::shared_ptr<std::vector<TextureBinding>> records;
|
|
if (bind)
|
|
{
|
|
records = std::make_shared<std::vector<TextureBinding>>();
|
|
for (const auto &primitive : model.primitives)
|
|
{
|
|
TextureBinding binding;
|
|
if (primitive.material != -1)
|
|
{
|
|
// GetTexture(-1)'s record-zero fallback determines the original
|
|
// allocation ABI, not ownership of a missing material's image.
|
|
binding.record = textureRecord(rdram, mdt + model.materials + static_cast<uint32_t>(primitive.material)*0x60u+0x34u);
|
|
if (binding.record)
|
|
{
|
|
std::memcpy(binding.identity.data(),rdram+binding.record,binding.identity.size());
|
|
binding.image = recordTexture(rdram,binding.record);
|
|
}
|
|
}
|
|
records->push_back(std::move(binding));
|
|
}
|
|
}
|
|
std::lock_guard<std::mutex> lock(g_mdtMutex);
|
|
MdtCopy &entry = g_mdtCopies[data];
|
|
if (bind || !entry.records) // Remake: the bindings stay those of the build
|
|
entry.records = std::move(records);
|
|
entry.mdt = mdt;
|
|
entry.copy = std::move(copy);
|
|
}
|
|
void createModel(uint8_t *rdram, R5900Context *ctx, Runtime *runtime, bool remake, bool shadow)
|
|
{
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
const uint32_t visual = getRegU32(ctx, 4), data = getRegU32(ctx, 5), mdt = getRegU32(ctx, 6);
|
|
const auto model = describeMdt(guest, mdt, shadow);
|
|
const uint32_t qwords = kNativeModelQwords;
|
|
guest.in(visual + 0x18u, 8);
|
|
noteMdt(rdram, data, mdt, !remake && !shadow, model);
|
|
guest.write32(visual + 0x18u, data);
|
|
guest.write32(visual + 0x1cu, qwords);
|
|
++(shadow ? g_nativeShadowBuilds : remake ? g_nativeModelRemakes : g_nativeModelBuilds);
|
|
g_retiredModelBytes += qwords * 16ull;
|
|
extentFill(rdram, data, qwords * 16u, shadow ? "shadow" : remake ? "remake" : "model", visual);
|
|
setReturnS32(ctx, static_cast<int32_t>(qwords));
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
void createFromMdtHook(uint8_t *ram, R5900Context *ctx, Runtime *rt) { createModel(ram, ctx, rt, false, false); }
|
|
void createFromMdtRemakeHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
createModel(rdram, ctx, runtime, true, false);
|
|
}
|
|
void createShadowHook(uint8_t *ram, R5900Context *ctx, Runtime *rt) { createModel(ram, ctx, rt, false, true); }
|
|
Model modelOf(const uint8_t *rdram, uint32_t visual)
|
|
{
|
|
Model model;
|
|
model.rdram = rdram;
|
|
const uint32_t kept = rd32(rdram, visual + 8u) == kVtVisualMdtVu1 ? rd32(rdram, visual + 0x20u) : 0u;
|
|
std::lock_guard<std::mutex> lock(g_mdtMutex);
|
|
const auto it = g_mdtCopies.find(rd32(rdram, visual + 0x18u));
|
|
if (it != g_mdtCopies.end())
|
|
model.records = it->second.records;
|
|
if (kept != 0u && rd32(rdram, kept) == kMdtMagic)
|
|
{
|
|
model.mdt = kept;
|
|
return model;
|
|
}
|
|
if (it == g_mdtCopies.end())
|
|
return model;
|
|
model.mdt = it->second.mdt;
|
|
model.copy = it->second.copy;
|
|
++g_stats.copiedModel;
|
|
return model;
|
|
}
|
|
|
|
// The object state CFrameVu1::DrawVu1 hands SetGsReg3 just before it draws its visual: TEST (alpha test
|
|
// reference), ZBUF (Z write) and ALPHA (translucency), the game's own values.
|
|
struct ObjectMaterial
|
|
{
|
|
bool valid = false;
|
|
bozo::render::Material::Blend blend = bozo::render::Material::Blend::Alpha;
|
|
bool depthWrite = true, alphaTest = false;
|
|
uint8_t alphaRef = 0;
|
|
} g_objectState;
|
|
void setGsReg3Hook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
// Translate the game's scalar material arguments at the call boundary. Retain
|
|
// native draw properties, never a bank of TEST/ZBUF/ALPHA register values.
|
|
const uint64_t test = rd64(rdram, getRegU32(ctx, 5));
|
|
const uint64_t zbuf = rd64(rdram, getRegU32(ctx, 6));
|
|
const uint64_t alpha = rd64(rdram, getRegU32(ctx, 7));
|
|
g_objectState = {};
|
|
g_objectState.valid = true;
|
|
g_objectState.blend = bozo::render::blendOf(alpha);
|
|
g_objectState.depthWrite = ((zbuf >> 32) & 1u) == 0u;
|
|
const uint32_t ate = test & 1u, atst = (test >> 1) & 7u, aref = (test >> 4) & 0xffu;
|
|
if (ate != 0u && ((test >> 12) & 3u) == 0u && (atst == 5u || atst == 6u))
|
|
{
|
|
g_objectState.alphaTest = atst == 6u || aref > 0u;
|
|
g_objectState.alphaRef = static_cast<uint8_t>(atst == 5u && aref > 0u ? aref - 1u : aref);
|
|
}
|
|
// The original only serialized these values into a DMA/GIF output buffer.
|
|
// Native materials need no packet words and do not advance the caller's cursor.
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
|
|
void applyObjectState(const ObjectMaterial &state, bozo::render::Material &material)
|
|
{
|
|
material.blend = bozo::render::Material::Blend::Alpha;
|
|
material.depthWrite = true;
|
|
material.alphaTest = false;
|
|
if (!state.valid)
|
|
return;
|
|
material.blend = state.blend;
|
|
material.depthWrite = state.depthWrite;
|
|
material.alphaTest = state.alphaTest;
|
|
material.alphaRef = state.alphaRef;
|
|
// DC_FORCE_ZWRITE=1 (diagnosis): Z written whatever the object's ZBUF says.
|
|
static const bool s_forceZWrite = [] { const char *v = std::getenv("DC_FORCE_ZWRITE"); return v && v[0] == '1'; }();
|
|
if (!material.depthWrite)
|
|
{
|
|
++g_stats.noZWrite;
|
|
if (s_forceZWrite)
|
|
material.depthWrite = true;
|
|
}
|
|
}
|
|
|
|
uint64_t g_depthSamples = 0, g_depthPending = 0, g_visibilityBatches = 0;
|
|
void depthReadbackHook(uint8_t *, R5900Context *, Runtime *)
|
|
{
|
|
throw std::runtime_error("DC readback caller needs a native implementation; visibility no longer uses SDK readbacks");
|
|
}
|
|
|
|
// The VU1 program's lighting (image 8c7dbae50f1ab651, its setup at pc 0x50; f256fcac190325a3 for the models):
|
|
// DrawVu1 puts RenderInfo's four light directions (+ 0x110..+ 0x130, one light per component) at VU 9-11 and
|
|
// the local-to-world matrix's first three columns, normalised, at VU 5-7; their products are the lights in the
|
|
// model's space (vf2-vf4). Per vertex, d = max(0, vf2 n.x + vf3 n.y + vf4 n.z) and the colour is ambient
|
|
// (+ 0x190) + the lights' colours (+ 0x150..+ 0x180) . d, each scaled by the material's first quadword (VU 37),
|
|
// kept to 254. Texture coordinates are scaled by + 0x1A0's x. A draw with its last argument set reuses the
|
|
// lights of the draw before (VU 9-21 keep them).
|
|
struct Lights
|
|
{
|
|
float dirs[3][4]{}; // RenderInfo + 0x110, + 0x120, + 0x130
|
|
float colour[4][4]{}; // + 0x150..+ 0x180
|
|
float ambient[4]{}; // + 0x190
|
|
float uvScale = 1.0f; // + 0x1A0 x
|
|
} g_lights;
|
|
|
|
struct Lighting
|
|
{
|
|
float dir[3][4]{};
|
|
float colour[4][4]{};
|
|
float ambient[4]{};
|
|
float material[4] = {1.0f, 1.0f, 1.0f, 1.0f};
|
|
};
|
|
|
|
Lighting lightingFor(const Lights &lights, const Matrix &localToWorld)
|
|
{
|
|
Lighting l;
|
|
for (int j = 0; j < 3; ++j)
|
|
{
|
|
const float *column = &localToWorld.m[j * 4];
|
|
const float length = std::sqrt(column[0] * column[0] + column[1] * column[1] + column[2] * column[2]);
|
|
const float inverse = length > 0.0f ? 1.0f / length : 0.0f;
|
|
for (int c = 0; c < 4; ++c)
|
|
l.dir[j][c] = (lights.dirs[0][c] * column[0] + lights.dirs[1][c] * column[1] +
|
|
lights.dirs[2][c] * column[2]) *
|
|
inverse;
|
|
}
|
|
std::memcpy(l.colour, lights.colour, sizeof(l.colour));
|
|
std::memcpy(l.ambient, lights.ambient, sizeof(l.ambient));
|
|
return l;
|
|
}
|
|
|
|
// vertexColour: a model's colour stream (MDT + 0x20, the tuples' fourth index; SetVuData copies its four floats
|
|
// as they are and sets 0x100 in the primitive's header): the program's lighting at 0xBF8 multiplies the lit
|
|
// colour by it, component by component, before the clamp (0xAD0 is the same without it).
|
|
uint32_t shade(const Lighting &l, float nx, float ny, float nz, const float *vertexColour = nullptr)
|
|
{
|
|
float d[4];
|
|
for (int c = 0; c < 4; ++c)
|
|
d[c] = std::max(0.0f, l.dir[0][c] * nx + l.dir[1][c] * ny + l.dir[2][c] * nz);
|
|
uint32_t rgba = 0;
|
|
for (int c = 0; c < 4; ++c)
|
|
{
|
|
float v = (l.ambient[c] + l.colour[0][c] * d[0] + l.colour[1][c] * d[1] + l.colour[2][c] * d[2] +
|
|
l.colour[3][c] * d[3]) *
|
|
l.material[c];
|
|
if (vertexColour)
|
|
v *= vertexColour[c];
|
|
v = std::min(v, 254.0f);
|
|
const uint32_t i = v > 0.0f ? static_cast<uint32_t>(v) : 0u;
|
|
rgba |= std::min(i, 255u) << (8 * c);
|
|
}
|
|
return rgba;
|
|
}
|
|
|
|
// The microprogram clips each triangle to its clip box (CLIPW against the clip matrix, |x|, |y|, |z| <= w;
|
|
// the clipping routine at 0x1C38 of f256fcac190325a3) and draws what is inside. The renderer clamps depth
|
|
// instead of clipping it and keeps GS Z to 24 bits: here triangles are clipped to the near and far planes
|
|
// (z = -w, z = w) of that clip space, the new vertices interpolated in the object's space (clip coordinates
|
|
// are linear in it). x and y are left to the GPU.
|
|
void clipDepth(const Matrix &clip, std::vector<bozo::render::Vertex> &triangles)
|
|
{
|
|
using bozo::render::Vertex;
|
|
struct Clipped
|
|
{
|
|
Vertex v;
|
|
float z, w;
|
|
};
|
|
auto toClip = [&](const Vertex &v) {
|
|
const float z = clip.m[0 * 4 + 2] * v.x + clip.m[1 * 4 + 2] * v.y + clip.m[2 * 4 + 2] * v.z + clip.m[3 * 4 + 2];
|
|
const float w = clip.m[0 * 4 + 3] * v.x + clip.m[1 * 4 + 3] * v.y + clip.m[2 * 4 + 3] * v.z + clip.m[3 * 4 + 3];
|
|
return Clipped{v, z, w};
|
|
};
|
|
auto lerp = [](const Clipped &a, const Clipped &b, float t) {
|
|
Clipped c;
|
|
c.v.x = a.v.x + (b.v.x - a.v.x) * t;
|
|
c.v.y = a.v.y + (b.v.y - a.v.y) * t;
|
|
c.v.z = a.v.z + (b.v.z - a.v.z) * t;
|
|
c.v.u = a.v.u + (b.v.u - a.v.u) * t;
|
|
c.v.v = a.v.v + (b.v.v - a.v.v) * t;
|
|
c.v.fog = a.v.fog + (b.v.fog - a.v.fog) * t;
|
|
c.v.q = a.v.q + (b.v.q - a.v.q) * t;
|
|
uint32_t rgba = 0;
|
|
for (int k = 0; k < 4; ++k)
|
|
{
|
|
const float ca = static_cast<float>((a.v.rgba >> (k * 8)) & 0xFFu);
|
|
const float cb = static_cast<float>((b.v.rgba >> (k * 8)) & 0xFFu);
|
|
rgba |= static_cast<uint32_t>(std::clamp(ca + (cb - ca) * t + 0.5f, 0.0f, 255.0f)) << (k * 8);
|
|
}
|
|
c.v.rgba = rgba;
|
|
c.z = a.z + (b.z - a.z) * t;
|
|
c.w = a.w + (b.w - a.w) * t;
|
|
return c;
|
|
};
|
|
// Distance to a plane, inside >= 0: near z + w, far w - z.
|
|
auto nearDistance = [](const Clipped &c) { return c.z + c.w; };
|
|
auto farDistance = [](const Clipped &c) { return c.w - c.z; };
|
|
std::vector<Vertex> out;
|
|
out.reserve(triangles.size());
|
|
Clipped polygon[9], next[9];
|
|
for (size_t i = 0; i + 2 < triangles.size(); i += 3)
|
|
{
|
|
Clipped a = toClip(triangles[i]), b = toClip(triangles[i + 1]), c = toClip(triangles[i + 2]);
|
|
const bool inside = nearDistance(a) >= 0.0f && nearDistance(b) >= 0.0f && nearDistance(c) >= 0.0f &&
|
|
farDistance(a) >= 0.0f && farDistance(b) >= 0.0f && farDistance(c) >= 0.0f;
|
|
if (inside)
|
|
{
|
|
out.push_back(a.v);
|
|
out.push_back(b.v);
|
|
out.push_back(c.v);
|
|
continue;
|
|
}
|
|
int count = 3;
|
|
polygon[0] = a, polygon[1] = b, polygon[2] = c;
|
|
for (int plane = 0; plane < 2 && count > 0; ++plane)
|
|
{
|
|
int n = 0;
|
|
for (int k = 0; k < count; ++k)
|
|
{
|
|
const Clipped &p = polygon[k], &q = polygon[(k + 1) % count];
|
|
const float dp = plane == 0 ? nearDistance(p) : farDistance(p);
|
|
const float dq = plane == 0 ? nearDistance(q) : farDistance(q);
|
|
if (dp >= 0.0f)
|
|
next[n++] = p;
|
|
if ((dp >= 0.0f) != (dq >= 0.0f))
|
|
next[n++] = lerp(p, q, dp / (dp - dq));
|
|
}
|
|
count = n;
|
|
for (int k = 0; k < count; ++k)
|
|
polygon[k] = next[k];
|
|
}
|
|
for (int k = 1; k + 1 < count; ++k)
|
|
{
|
|
out.push_back(polygon[0].v);
|
|
out.push_back(polygon[k].v);
|
|
out.push_back(polygon[k + 1].v);
|
|
}
|
|
}
|
|
triangles.swap(out);
|
|
}
|
|
|
|
// A CTextureManager record (0x50 bytes from + 0x10F8): + 0 group, + 2 width, + 4 height, + 6 kind (1: 8-bit
|
|
// with a palette, 4: 32-bit), + 8 name, + 0x28 TEX0, + 0x38 the levels' pixels, + 0x48 the palette, + 0x4C
|
|
// set when its 8-bit texels are stored pre-swizzled and sent as a CT32 image of half the width.
|
|
// SearchTextureName (0x131180): from the last record down, a record whose name matches.
|
|
uint32_t textureRecord(const uint8_t *rdram, uint32_t name)
|
|
{
|
|
const int32_t count = static_cast<int32_t>(rd32(rdram, kTextureManager));
|
|
for (int32_t i = std::min(count, 1023); i >= 0; --i)
|
|
{
|
|
const uint32_t record = kTextureManager + 0x10F8u + static_cast<uint32_t>(i) * 0x50u;
|
|
uint32_t k = 0;
|
|
for (; k < 32u; ++k)
|
|
{
|
|
const uint8_t a = rdram[(name + k) & 0x1FFFFFFu], b = rdram[(record + 8u + k) & 0x1FFFFFFu];
|
|
if (a != b || a == 0u)
|
|
break;
|
|
}
|
|
if (k < 32u && rdram[(name + k) & 0x1FFFFFFu] == 0u && rdram[(record + 8u + k) & 0x1FFFFFFu] == 0u &&
|
|
rdram[(record + 8u) & 0x1FFFFFFu] != 0u)
|
|
return record;
|
|
}
|
|
return 0u;
|
|
}
|
|
|
|
uint32_t boundRecord(const uint8_t *rdram, uint32_t name)
|
|
{
|
|
const uint32_t record = textureRecord(rdram, name);
|
|
return record != 0u ? record : kTextureManager + 0x10F8u; // handle -1: GetTexture's record 0
|
|
}
|
|
|
|
std::unordered_map<uint32_t, std::pair<uint64_t, std::shared_ptr<const bozo::render::Texture>>> g_decoded;
|
|
uint64_t g_textureVersion = 0;
|
|
bool g_dump2D = false; // the on-demand frame dump (drawStrip's [dc:dump])
|
|
uint32_t g_2dCaller = 0; // the game code that called the 2D routine being drawn (its return address)
|
|
// Live toggles (diagnosis): D:/DC_Recomp/build/toggles.txt, read every 60 frames, one word per line: noshadow
|
|
// (shadow passes not laid), nosprites3d (effect sprites not drawn), nofog, noguard, nodof (depth of field), nomade
|
|
// (sprites sampling a picture the game makes, frame copies), nomodels (DrawVu1 models), no2d (2D sprites), nocopies
|
|
// (MGMoveImage's texture patches: the face expressions), opaquemodels (models drawn without blending).
|
|
struct Toggles
|
|
{
|
|
bool noShadow = false, noSprites3D = false, noFog = false, noGuard = false, noDof = false, noMade = false, noModels = false,
|
|
no2D = false, noCopies = false, opaqueModels = false;
|
|
} g_toggles;
|
|
void readToggles()
|
|
{
|
|
Toggles t;
|
|
if (FILE *file = std::fopen("D:/DC_Recomp/build/toggles.txt", "rb"))
|
|
{
|
|
char line[64];
|
|
while (std::fgets(line, sizeof(line), file))
|
|
{
|
|
const std::string word(line, std::strcspn(line, "\r\n \t"));
|
|
t.noShadow |= word == "noshadow";
|
|
t.noSprites3D |= word == "nosprites3d";
|
|
t.noFog |= word == "nofog";
|
|
t.noGuard |= word == "noguard";
|
|
t.noDof |= word == "nodof";
|
|
t.noMade |= word == "nomade";
|
|
t.noModels |= word == "nomodels";
|
|
t.no2D |= word == "no2d";
|
|
t.noCopies |= word == "nocopies";
|
|
t.opaqueModels |= word == "opaquemodels";
|
|
}
|
|
std::fclose(file);
|
|
}
|
|
if (std::memcmp(&t, &g_toggles, sizeof(t)) != 0)
|
|
std::fprintf(stderr, "[dc:toggles] noshadow %d nosprites3d %d nofog %d noguard %d\n", t.noShadow, t.noSprites3D, t.noFog,
|
|
t.noGuard);
|
|
g_toggles = t;
|
|
}
|
|
// DC_PROBE_SEQ=1 (diagnosis): each frame's draws in order, one letter each (C clear, Z clear Z, M model, s
|
|
// sprite, P / F / T sprite of the previous frame / the frame / a target, S stretch), for frames with a stretch.
|
|
std::string g_seq;
|
|
void seq(char c)
|
|
{
|
|
static const bool s_on = std::getenv("DC_PROBE_SEQ") != nullptr;
|
|
if (s_on && g_seq.size() < 4000u)
|
|
g_seq.push_back(c);
|
|
}
|
|
// DC_PROBE_HITCH=1 (diagnosis): what each frame decoded, to find the frames that take long.
|
|
struct FrameWork
|
|
{
|
|
uint32_t decodes = 0, storeDecodes = 0, patches = 0, draws = 0;
|
|
uint64_t decodedTexels = 0;
|
|
} g_frameWork;
|
|
// DC_NATIVE_STATS=1: record texture lookups and the bytes their change checks hashed, over the last 300 frames.
|
|
struct LookupWork
|
|
{
|
|
uint64_t lookups = 0, hashedBytes = 0;
|
|
} g_lookupWork;
|
|
|
|
// The 8-bit textures converted offline from the user's disc (tools/dc_texconv.py: the TIM2 pictures of DC's IMG
|
|
// archives, plain on the disc, which EnterTexture keeps in GS order in the game), keyed by name and the FNV-1a 32
|
|
// of the palette as the disc holds it (EnterTexture copies it into the record as it is). DC_TEXTURES=<file>,
|
|
// default build/textures/dc_textures.bin.
|
|
struct StoredTexture
|
|
{
|
|
uint32_t width = 0, height = 0, offset = 0;
|
|
uint32_t texelHash = 0; // CRC-32 of all its texels in GS order (version 3; 0 unknown)
|
|
};
|
|
std::vector<uint8_t> g_store;
|
|
std::unordered_map<std::string, std::vector<StoredTexture>> g_storeIndex;
|
|
std::unordered_map<std::string, std::vector<StoredTexture>> g_storeByName; // every palette of a name
|
|
bool g_storeLoaded = false;
|
|
|
|
uint32_t fnv1a32(const uint8_t *rdram, uint32_t address, uint32_t bytes)
|
|
{
|
|
uint32_t hash = 0x811C9DC5u;
|
|
for (uint32_t i = 0; i < bytes; ++i)
|
|
hash = (hash ^ rdram[(address + i) & 0x1FFFFFFu]) * 0x01000193u;
|
|
return hash;
|
|
}
|
|
|
|
// CRC-32 (the zlib one) of main memory: the store's texel CRC.
|
|
uint32_t crc32(const uint8_t *rdram, uint32_t address, uint32_t bytes)
|
|
{
|
|
static const auto table = [] {
|
|
std::array<uint32_t, 256> t{};
|
|
for (uint32_t i = 0; i < 256u; ++i)
|
|
{
|
|
uint32_t c = i;
|
|
for (int k = 0; k < 8; ++k)
|
|
c = (c & 1u) ? 0xEDB88320u ^ (c >> 1) : c >> 1;
|
|
t[i] = c;
|
|
}
|
|
return t;
|
|
}();
|
|
uint32_t crc = 0xFFFFFFFFu;
|
|
for (uint32_t i = 0; i < bytes; ++i)
|
|
crc = table[(crc ^ rdram[(address + i) & 0x1FFFFFFu]) & 0xFFu] ^ (crc >> 8);
|
|
return crc ^ 0xFFFFFFFFu;
|
|
}
|
|
|
|
void loadStore()
|
|
{
|
|
g_storeLoaded = true;
|
|
const char *path = std::getenv("DC_TEXTURES");
|
|
const auto fallback = assetDirectory.empty() ? std::filesystem::path(DC_DEFAULT_TEXTURES)
|
|
: std::filesystem::path(assetDirectory) / "dc_textures.bin";
|
|
std::ifstream file(path && *path ? std::filesystem::path(path) : fallback, std::ios::binary);
|
|
if (!file)
|
|
{
|
|
std::fprintf(stderr, "[dc:native] no converted textures (run tools/dc_texconv.py game build/textures/dc_textures.bin): "
|
|
"8-bit textures draw untextured\n");
|
|
return;
|
|
}
|
|
g_store.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
|
|
if (g_store.size() < 12u || std::memcmp(g_store.data(), "DCTX", 4) != 0)
|
|
{
|
|
g_store.clear();
|
|
return;
|
|
}
|
|
uint32_t version = 0, count = 0;
|
|
std::memcpy(&version, g_store.data() + 4, 4);
|
|
std::memcpy(&count, g_store.data() + 8, 4);
|
|
const uint32_t entryBytes = version >= 2u ? 48u : 44u;
|
|
for (uint32_t i = 0; i < count && 12u + (i + 1u) * entryBytes <= g_store.size(); ++i)
|
|
{
|
|
const uint8_t *entry = g_store.data() + 12u + i * entryBytes;
|
|
const std::string name(reinterpret_cast<const char *>(entry), strnlen(reinterpret_cast<const char *>(entry), 32));
|
|
uint16_t width = 0, height = 0;
|
|
uint32_t paletteHash = 0;
|
|
StoredTexture texture;
|
|
std::memcpy(&width, entry + 32, 2);
|
|
std::memcpy(&height, entry + 34, 2);
|
|
std::memcpy(&paletteHash, entry + 36, 4);
|
|
std::memcpy(&texture.offset, entry + 40, 4);
|
|
if (version >= 3u) // version 2's hash covered the first 4096 bytes only, alike in many pictures
|
|
std::memcpy(&texture.texelHash, entry + 44, 4);
|
|
texture.width = width;
|
|
texture.height = height;
|
|
if (texture.offset + 1024u + texture.width * texture.height <= g_store.size())
|
|
{
|
|
g_storeIndex[name + '|' + std::to_string(paletteHash)].push_back(texture);
|
|
g_storeByName[name].push_back(texture);
|
|
}
|
|
}
|
|
std::fprintf(stderr, "[dc:native] %u converted 8-bit textures loaded\n", count);
|
|
}
|
|
|
|
// A palette the game loads over a texture's CLUT (SetClut 0x14C5A0: the message windows' text colour, a 256-entry
|
|
// CT32 palette in main memory sent to the texture's CBP), by CBP, for the frame: a record whose TEX0 points there
|
|
// is decoded with it. Cleared at the frame's end.
|
|
std::unordered_map<uint32_t, uint32_t> g_clutOverride;
|
|
uint64_t contentHash(const uint8_t *rdram, uint32_t address, uint32_t bytes, uint64_t hash);
|
|
uint32_t paletteOf(const uint8_t *rdram, uint32_t record)
|
|
{
|
|
const uint32_t cbp = static_cast<uint32_t>((rd64(rdram, record + 0x28u) >> 37) & 0x3FFFu);
|
|
const auto found = g_clutOverride.find(cbp);
|
|
return found != g_clutOverride.end() ? found->second : rd32(rdram, record + 0x48u);
|
|
}
|
|
|
|
// An 8-bit record's entry in the converted store: the record's name, its palette's hash and its size; live when
|
|
// only the name and size match (its indices are then coloured with the record's palette as it is now).
|
|
const StoredTexture *findStored(const uint8_t *rdram, uint32_t record, uint32_t w, uint32_t h, bool &livePalette);
|
|
// A stored entry's 256 colours, alpha as the GS has it (0x80 is 1.0), by index.
|
|
void storedColours(const uint8_t *rdram, uint32_t record, const StoredTexture &stored, bool livePalette, uint32_t out[256])
|
|
{
|
|
const uint32_t palette = paletteOf(rdram, record);
|
|
const uint8_t *rgba = g_store.data() + stored.offset;
|
|
for (uint32_t i = 0; i < 256u; ++i)
|
|
if (livePalette)
|
|
out[i] = rd32(rdram, palette + ((i & 0xE7u) | ((i & 0x08u) << 1) | ((i & 0x10u) >> 1)) * 4u);
|
|
else
|
|
{
|
|
// The store's palettes hold alpha doubled (0x80 as 255): back to the GS's own value.
|
|
uint32_t texel = 0;
|
|
std::memcpy(&texel, rgba + i * 4u, 4);
|
|
const uint32_t a = texel >> 24;
|
|
out[i] = (texel & 0x00FFFFFFu) | (a >= 255u ? 0x80u : a / 2u) << 24;
|
|
}
|
|
}
|
|
// An 8-bit record's texture from the converted store.
|
|
std::shared_ptr<bozo::render::Texture> storedTexture(const uint8_t *rdram, uint32_t record,
|
|
uint32_t w, uint32_t h, uint32_t tw, uint32_t th)
|
|
{
|
|
bool livePalette = false;
|
|
const StoredTexture *stored = findStored(rdram, record, w, h, livePalette);
|
|
if (!stored)
|
|
return nullptr;
|
|
auto texture = std::make_shared<bozo::render::Texture>();
|
|
texture->width = 1u << tw;
|
|
texture->height = 1u << th;
|
|
texture->rgba.assign(static_cast<size_t>(texture->width) * texture->height, 0u);
|
|
++g_frameWork.storeDecodes;
|
|
g_frameWork.decodedTexels += static_cast<uint64_t>(texture->width) * texture->height;
|
|
const uint8_t *indices = g_store.data() + stored->offset + 1024;
|
|
uint32_t colours[256];
|
|
storedColours(rdram, record, *stored, livePalette, colours);
|
|
for (uint32_t y = 0; y < stored->height && y < texture->height; ++y)
|
|
for (uint32_t x = 0; x < stored->width && x < texture->width; ++x)
|
|
texture->rgba[static_cast<size_t>(y) * texture->width + x] = colours[indices[y * stored->width + x]];
|
|
return texture;
|
|
}
|
|
const StoredTexture *findStored(const uint8_t *rdram, uint32_t record, uint32_t w, uint32_t h, bool &livePalette)
|
|
{
|
|
if (!g_storeLoaded)
|
|
loadStore();
|
|
char name[33] = {};
|
|
for (uint32_t k = 0; k < 32u; ++k)
|
|
name[k] = static_cast<char>(rdram[(record + 8u + k) & 0x1FFFFFFu]);
|
|
const uint32_t palette = paletteOf(rdram, record);
|
|
if (palette == 0u)
|
|
return nullptr;
|
|
const uint32_t paletteHash = fnv1a32(rdram, palette, 1024u);
|
|
// One name holds many pictures with the same palette (Toan's expression sheets, 128 x 256 and 256 x 128 among
|
|
// them): the one whose texels are the record's (as EnterTexture left them, in GS order), else the one of the
|
|
// record's width and height, else of its texel count.
|
|
const uint32_t pixels = rd32(rdram, record + 0x38u);
|
|
const uint32_t texelHash = pixels != 0u ? crc32(rdram, pixels, w * h) : 0u;
|
|
uint32_t best = 0;
|
|
auto consider = [&](const StoredTexture &candidate) {
|
|
if (candidate.width * candidate.height != w * h)
|
|
return false;
|
|
const uint32_t score = 1u + (candidate.width == w && candidate.height == h ? 2u : 0u) +
|
|
(candidate.texelHash != 0u && candidate.texelHash == texelHash ? 4u : 0u);
|
|
if (score <= best)
|
|
return false;
|
|
best = score;
|
|
return true;
|
|
};
|
|
const StoredTexture *stored = nullptr;
|
|
if (const auto found = g_storeIndex.find(std::string(name) + '|' + std::to_string(paletteHash)); found != g_storeIndex.end())
|
|
for (const StoredTexture &candidate : found->second)
|
|
if (consider(candidate))
|
|
stored = &candidate;
|
|
// The record's palette is not the disc's (the game changed it after loading): the converted indices of that
|
|
// name and size, coloured with the record's palette as it is now (plain CT32 in main memory, CSM1 order).
|
|
livePalette = false;
|
|
if (!stored)
|
|
if (const auto named = g_storeByName.find(name); named != g_storeByName.end())
|
|
for (const StoredTexture &candidate : named->second)
|
|
if (consider(candidate))
|
|
{
|
|
stored = &candidate;
|
|
livePalette = true;
|
|
}
|
|
static std::unordered_map<std::string, bool> s_logged;
|
|
if ((!stored || livePalette) && !s_logged[std::string(name) + '|' + std::to_string(paletteHash)])
|
|
{
|
|
s_logged[std::string(name) + '|' + std::to_string(paletteHash)] = true;
|
|
std::fprintf(stderr, "[dc:native] texture \"%s\" %ux%u palette %08x not in the store%s\n", name, w, h, paletteHash,
|
|
stored ? ": its indices with the record's palette" : "");
|
|
}
|
|
// A version 2 store and no picture of the name with the record's texels: the one taken is a guess.
|
|
if (stored && best < 4u && texelHash != 0u && stored->texelHash != 0u)
|
|
if (static std::unordered_map<std::string, bool> s_guessed; !s_guessed[std::string(name) + '|' + std::to_string(texelHash)])
|
|
{
|
|
s_guessed[std::string(name) + '|' + std::to_string(texelHash)] = true;
|
|
std::fprintf(stderr, "[dc:native] texture \"%s\" %ux%u: no stored picture has its texels (%08x), %ux%u taken\n", name, w,
|
|
h, texelHash, stored->width, stored->height);
|
|
}
|
|
return stored;
|
|
}
|
|
|
|
uint64_t contentHash(const uint8_t *rdram, uint32_t address, uint32_t bytes, uint64_t hash)
|
|
{
|
|
// The cache must still observe live texel/palette writes on every
|
|
// lookup. A serial multiply per word dominated Dran's house; XXH64
|
|
// checks the same ranges with four independent lanes. This key is
|
|
// local to g_decoded, unrelated to the offline store's identities.
|
|
constexpr uint32_t ramBytes = 0x2000000u;
|
|
uint32_t at = address & (ramBytes - 1u);
|
|
while (bytes)
|
|
{
|
|
const uint32_t count = std::min(bytes, ramBytes - at);
|
|
hash = bozo::hash::xxh64(rdram + at, count, hash);
|
|
g_lookupWork.hashedBytes += count;
|
|
bytes -= count;
|
|
at = 0;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
// A record's texture, decoded from its pixels and palette in main memory (8-bit / 4-bit with a CT32 palette as
|
|
// the game sends it: CSM1 entry order, CSA; CT32). An identical asset keeps its decoded texture. Records whose
|
|
// 8-bit texels are stored in GS memory order (flag + 0x4C: the game sends them as a CT32 image of half the
|
|
// width) are not decoded here: by BaldHuman's rule no GS layout function runs in the game; they are to come
|
|
// from an offline conversion of the disc's texture files, and draw untextured until then.
|
|
// Textures decoded when LoadTexture (0x154950 / 0x154770, the loading screens' pictures) sent them: it sends the
|
|
// pixels and palette at once from the file's buffer, which the next file then overwrites while the record still
|
|
// points there. Kept while the record keeps those pixels and TEX0.
|
|
struct Pinned
|
|
{
|
|
uint32_t pixels = 0;
|
|
uint64_t tex0 = 0;
|
|
std::shared_ptr<const bozo::render::Texture> texture;
|
|
};
|
|
std::unordered_map<uint32_t, Pinned> g_pinned;
|
|
|
|
std::shared_ptr<const bozo::render::Texture> recordTexture(const uint8_t *rdram, uint32_t record)
|
|
{
|
|
++g_lookupWork.lookups;
|
|
if (const auto pinned = g_pinned.find(record); pinned != g_pinned.end())
|
|
{
|
|
if (pinned->second.pixels == rd32(rdram, record + 0x38u) && pinned->second.tex0 == rd64(rdram, record + 0x28u))
|
|
return pinned->second.texture;
|
|
g_pinned.erase(pinned);
|
|
}
|
|
const uint32_t w = rd32(rdram, record) >> 16, h = rd32(rdram, record + 4u) & 0xFFFFu;
|
|
const uint32_t kind = rd32(rdram, record + 4u) >> 16;
|
|
const uint64_t tex0 = rd64(rdram, record + 0x28u);
|
|
const uint32_t pixels = rd32(rdram, record + 0x38u);
|
|
// A picture LoadTexture (TM2) put in the record says kind 0 whatever its format: its texels and palette follow
|
|
// its TEX0 (the map title card is 4-bit, with a palette).
|
|
const uint32_t tm2Indexed = kind == 0u && (((tex0 >> 20) & 0x3Fu) == 0x13u || ((tex0 >> 20) & 0x3Fu) == 0x14u)
|
|
? static_cast<uint32_t>((tex0 >> 20) & 0x3Fu) : 0u;
|
|
const uint32_t palette = kind == 1u || tm2Indexed != 0u ? paletteOf(rdram, record) : 0u;
|
|
if (kind == 1u && rd32(rdram, record + 0x4Cu) != 0u)
|
|
{
|
|
// Kept in GS order by the game: from the offline conversion of the disc's pictures.
|
|
const uint32_t tw = (tex0 >> 26) & 0xFu, th = (tex0 >> 30) & 0xFu;
|
|
// Its texels' head too: a record can be given another picture of the same palette and size.
|
|
const uint64_t hash = contentHash(rdram, pixels, std::min(4096u, w * h),
|
|
contentHash(rdram, palette, 1024u, 0x5354u ^ (static_cast<uint64_t>(palette) << 16) ^ tex0));
|
|
auto &slot = g_decoded[record];
|
|
if (slot.second && slot.first == hash)
|
|
return slot.second;
|
|
auto texture = tw <= 10u && th <= 10u ? storedTexture(rdram, record, w, h, tw, th) : nullptr;
|
|
if (!texture)
|
|
{
|
|
++g_stats.gsOrderTextures;
|
|
return nullptr;
|
|
}
|
|
texture->key = record;
|
|
texture->version = ++g_textureVersion;
|
|
slot = {hash, texture};
|
|
return texture;
|
|
}
|
|
// ReloadTexture's level 0: kind x w x h / 16 qwords; the kind is the bytes per texel (1: 8-bit with a palette,
|
|
// 3: 24-bit, 4: 32-bit).
|
|
const uint32_t bytes = tm2Indexed == 0x14u ? w * h / 2u : (kind == 1u || tm2Indexed != 0u ? 1u : kind == 3u ? 3u : 4u) * w * h;
|
|
const uint32_t tbw = std::max<uint32_t>((tex0 >> 14) & 0x3Fu, 1u);
|
|
// PSMT8H (0x1B, the 8-bit texels kept in the top byte of 32-bit GS words: EnterFixTextureZ's menu sheet) is sent
|
|
// as plain 8-bit texels: decoded as PSMT8.
|
|
const uint32_t psm = ((tex0 >> 20) & 0x3Fu) == 0x1Bu ? 0x13u : (tex0 >> 20) & 0x3Fu;
|
|
const uint32_t tw = (tex0 >> 26) & 0xFu, th = (tex0 >> 30) & 0xFu;
|
|
const uint32_t cpsm = (tex0 >> 51) & 0xFu, csa = (tex0 >> 56) & 0x1Fu;
|
|
if (pixels == 0u || bytes == 0u || (psm != 0x13u && psm != 0x14u && psm != 0x00u && psm != 0x01u) ||
|
|
(psm != 0x00u && psm != 0x01u && (cpsm != 0u || palette == 0u)) || tw > 10u || th > 10u)
|
|
return nullptr;
|
|
// Up to 256 KiB hashed whole (the game rewrites some in place: the message windows' glyphs), larger ones sampled.
|
|
const uint32_t sample = bytes <= 0x40000u ? bytes : 4096u;
|
|
uint64_t hash = contentHash(rdram, pixels, sample, 0xCBF29CE484222325ull ^ tex0);
|
|
if (sample < bytes)
|
|
hash = contentHash(rdram, pixels + bytes - sample, sample, hash ^ pixels);
|
|
if (palette != 0u)
|
|
hash = contentHash(rdram, palette, 1024u, hash ^ palette);
|
|
auto &slot = g_decoded[record];
|
|
if (slot.second && slot.first == hash)
|
|
return slot.second;
|
|
|
|
auto texture = std::make_shared<bozo::render::Texture>();
|
|
texture->width = 1u << tw;
|
|
texture->height = 1u << th;
|
|
texture->rgba.assign(static_cast<size_t>(texture->width) * texture->height, 0u);
|
|
texture->key = record;
|
|
texture->version = ++g_textureVersion;
|
|
++g_frameWork.decodes;
|
|
g_frameWork.decodedTexels += static_cast<uint64_t>(texture->width) * texture->height;
|
|
// Rows as ReloadTexture sends them (LoadImage, 0x132E90: a w x h rectangle into the place, its buffer TBW x 64
|
|
// wide): packed at the record's own width in main memory. They were read TBW x 64 apart, and every texture
|
|
// narrower than its buffer lost rows (the message windows' 16 x 16 more-text triangle kept its rows 0, 4, 8,
|
|
// 12, squashed into its top quarter).
|
|
const uint32_t rowTexels = w != 0u ? w : tbw * 64u;
|
|
const uint32_t bitsPerTexel = psm == 0x13u ? 8u : psm == 0x14u ? 4u : psm == 0x01u ? 24u : 32u;
|
|
const uint32_t rows = bytes * 8u / (rowTexels * bitsPerTexel);
|
|
// Texel alpha as the GS has it (0x80 is 1.0): the renderer scales it by 255 / 128, as the GS's blending reads
|
|
// it. It was doubled here as well, and every partly transparent texture (the dungeon torches' glows) drew at
|
|
// twice its strength.
|
|
auto alpha = [](uint32_t a) { return a; };
|
|
auto colour = [&](uint32_t c) { return (c & 0x00FFFFFFu) | alpha(c >> 24) << 24; };
|
|
for (uint32_t y = 0; y < texture->height && y < rows; ++y)
|
|
for (uint32_t x = 0; x < texture->width && x < rowTexels; ++x)
|
|
{
|
|
uint32_t texel = 0;
|
|
if (psm == 0x00u)
|
|
texel = colour(rd32(rdram, pixels + (y * rowTexels + x) * 4u));
|
|
else if (psm == 0x01u)
|
|
{
|
|
// 24-bit (the title's backdrop "bg"): RGB as stored, opaque.
|
|
const uint32_t at = pixels + (y * rowTexels + x) * 3u;
|
|
texel = rdram[at & 0x1FFFFFFu] | rdram[(at + 1u) & 0x1FFFFFFu] << 8 | rdram[(at + 2u) & 0x1FFFFFFu] << 16 | 0x80000000u;
|
|
}
|
|
else
|
|
{
|
|
uint32_t index = 0;
|
|
if (psm == 0x13u)
|
|
index = rdram[(pixels + y * rowTexels + x) & 0x1FFFFFFu];
|
|
else
|
|
{
|
|
const uint32_t at = y * rowTexels + x;
|
|
index = (rdram[(pixels + at / 2u) & 0x1FFFFFFu] >> ((at & 1u) * 4u)) & 0xFu;
|
|
}
|
|
const uint32_t entry = psm == 0x13u ? (index & 0xE7u) | ((index & 0x08u) << 1) | ((index & 0x10u) >> 1)
|
|
: csa * 16u + index;
|
|
texel = colour(rd32(rdram, palette + entry * 4u));
|
|
}
|
|
texture->rgba[static_cast<size_t>(y) * texture->width + x] = texel;
|
|
}
|
|
slot = {hash, texture};
|
|
return texture;
|
|
}
|
|
|
|
// A material (0x60 bytes): its first quadword is the colour the lights and ambient are scaled by, its texture
|
|
// name is at + 0x34. Its record, found once per material.
|
|
|
|
// What DrawVu1 sets up for a piece, redone from RenderInfo: clip = RenderInfo 0x230 x 0x10 x the local-to-world
|
|
// matrix (the microprogram's clip box), RenderInfo 0x270 from there to GS screen space, the lights in the
|
|
// piece's space, and whether it is textured (PRMODE TME: no shadow, RenderInfo + 0x340 clear).
|
|
struct DrawSetup
|
|
{
|
|
Matrix clip, toScreen;
|
|
Lighting lighting;
|
|
float uvScale = 1.0f;
|
|
bool textureMapped = true;
|
|
// RenderInfo + 0x310 bit 2 (the program's flags at VU 0.z): the program culls a triangle whose screen-space
|
|
// (v2 - v0) x (v1 - v0) has a negative z (ADC set on its last vertex), in its list, strip (winding taken
|
|
// back every other vertex) and clipping loops alike. Models only (drawModel).
|
|
bool cull = false;
|
|
// The guard band. Without RenderInfo + 0x310 bit 1 (the program's clipping loops), the program does not clip:
|
|
// its list and strip loops take each vertex's screen x / w, y / w and w against VU 20 and 21 (RenderInfo +
|
|
// 0x210, + 0x220: FMAND of the signs of VU21 - v and v - VU20, mask 0xD0) and set ADC on a triangle unless
|
|
// all three are strictly inside. Such a triangle is dropped whole, as the GS skips it.
|
|
bool guard = false;
|
|
float guardLow[4] = {}, guardHigh[4] = {};
|
|
// Fog (models: drawModel). DrawVu1 sets PRMODE's FGE when RenderInfo + 0x324 is set (not in the shadow
|
|
// pass), FOGCOL from + 0x338 (24 bits), and puts (+ 0x328, + 0x334, + 0x330, + 0x32C) at VU 22; the program
|
|
// gives each vertex F = max(min(VU22.x + VU22.w / w, VU22.y), VU22.z), w its screen-space w (MADD.w with Q).
|
|
bool fog = false;
|
|
uint32_t fogColour = 0;
|
|
float fogBase = 255.0f, fogMax = 255.0f, fogMin = 0.0f, fogScale = 0.0f;
|
|
};
|
|
DrawSetup drawSetup(const uint8_t *rdram, const Matrix &localToWorld, uint32_t renderInfo)
|
|
{
|
|
// DC_PROBE_SPIKES=1: the program's guard band (VU 20 / 21 = RenderInfo + 0x210 / + 0x220) and flags (+ 0x310)
|
|
// of the first RenderInfos seen.
|
|
static const bool s_probe = [] { const char *e = std::getenv("DC_PROBE_SPIKES"); return e && e[0] == '1'; }();
|
|
static int s_logged = 0;
|
|
if (s_probe && s_logged < 40)
|
|
{
|
|
static uint32_t s_last[40];
|
|
const uint32_t flags = rd32(rdram, renderInfo + 0x310u);
|
|
bool seen = false;
|
|
for (int i = 0; i < s_logged; ++i)
|
|
seen |= s_last[i] == (renderInfo ^ flags << 1);
|
|
if (!seen)
|
|
{
|
|
s_last[s_logged++] = renderInfo ^ flags << 1;
|
|
std::fprintf(stderr, "[dc:guard] RenderInfo %08x flags %x: VU20 (%g %g %g %g) VU21 (%g %g %g %g)\n", renderInfo, flags,
|
|
rdf(rdram, renderInfo + 0x210u), rdf(rdram, renderInfo + 0x214u), rdf(rdram, renderInfo + 0x218u),
|
|
rdf(rdram, renderInfo + 0x21Cu), rdf(rdram, renderInfo + 0x220u), rdf(rdram, renderInfo + 0x224u),
|
|
rdf(rdram, renderInfo + 0x228u), rdf(rdram, renderInfo + 0x22Cu));
|
|
}
|
|
}
|
|
DrawSetup setup;
|
|
setup.clip = mul(mul(load(rdram, renderInfo + 0x230u), load(rdram, renderInfo + 0x10u)), localToWorld);
|
|
setup.toScreen = mul(load(rdram, renderInfo + 0x270u), setup.clip);
|
|
setup.lighting = lightingFor(g_lights, localToWorld);
|
|
setup.uvScale = g_lights.uvScale;
|
|
setup.textureMapped = rd32(rdram, renderInfo + 0x320u) == 0u && rd32(rdram, renderInfo + 0x340u) == 0u;
|
|
static const bool s_noGuard = [] { const char *e = std::getenv("DC_NO_GUARD"); return e && e[0] == '1'; }();
|
|
setup.guard = !s_noGuard && !g_toggles.noGuard && (rd32(rdram, renderInfo + 0x310u) & 2u) == 0u;
|
|
for (uint32_t c = 0; c < 4u; ++c)
|
|
{
|
|
const float a = rdf(rdram, renderInfo + 0x210u + c * 4u), b = rdf(rdram, renderInfo + 0x220u + c * 4u);
|
|
setup.guardLow[c] = std::min(a, b);
|
|
setup.guardHigh[c] = std::max(a, b);
|
|
}
|
|
return setup;
|
|
}
|
|
|
|
void readLights(const uint8_t *rdram, uint32_t renderInfo)
|
|
{
|
|
for (int j = 0; j < 3; ++j)
|
|
for (int c = 0; c < 4; ++c)
|
|
g_lights.dirs[j][c] = rdf(rdram, renderInfo + 0x110u + static_cast<uint32_t>(j) * 16u + static_cast<uint32_t>(c) * 4u);
|
|
for (int k = 0; k < 4; ++k)
|
|
for (int c = 0; c < 4; ++c)
|
|
g_lights.colour[k][c] = rdf(rdram, renderInfo + 0x150u + static_cast<uint32_t>(k) * 16u + static_cast<uint32_t>(c) * 4u);
|
|
for (int c = 0; c < 4; ++c)
|
|
g_lights.ambient[c] = rdf(rdram, renderInfo + 0x190u + static_cast<uint32_t>(c) * 4u);
|
|
g_lights.uvScale = rdf(rdram, renderInfo + 0x1A0u);
|
|
if (!(g_lights.uvScale > 0.0f && g_lights.uvScale <= 16.0f))
|
|
g_lights.uvScale = 1.0f;
|
|
}
|
|
|
|
// Clipped to the near and far planes, then drawn with the decoded texture (untextured without one).
|
|
// DC_PROBE_SPIKES=1 (diagnosis): a triangle spanning over 1500 screen pixels logs the draw it came from (what
|
|
// the hooks note in g_drawWhat), once per source.
|
|
char g_drawWhat[160] = "";
|
|
void probeSpikes(const DrawSetup &setup, const std::vector<bozo::render::Vertex> &vertices)
|
|
{
|
|
static const bool s_on = [] { const char *e = std::getenv("DC_PROBE_SPIKES"); return e && e[0] == '1'; }();
|
|
if (!s_on)
|
|
return;
|
|
static std::unordered_map<std::string, int> s_seen;
|
|
for (size_t t = 0; t + 2u < vertices.size(); t += 3u)
|
|
{
|
|
float sx[3], sy[3];
|
|
bool ok = true;
|
|
for (int k = 0; k < 3; ++k)
|
|
{
|
|
const bozo::render::Vertex &v = vertices[t + static_cast<size_t>(k)];
|
|
const float *m = setup.toScreen.m;
|
|
const float w = m[3] * v.x + m[7] * v.y + m[11] * v.z + m[15];
|
|
if (!(w > 0.0f))
|
|
ok = false;
|
|
sx[k] = (m[0] * v.x + m[4] * v.y + m[8] * v.z + m[12]) / w;
|
|
sy[k] = (m[1] * v.x + m[5] * v.y + m[9] * v.z + m[13]) / w;
|
|
}
|
|
if (!ok)
|
|
continue;
|
|
const float span = std::max({std::fabs(sx[0] - sx[1]), std::fabs(sx[1] - sx[2]), std::fabs(sx[0] - sx[2]),
|
|
std::fabs(sy[0] - sy[1]), std::fabs(sy[1] - sy[2]), std::fabs(sy[0] - sy[2])});
|
|
if (span < 1500.0f)
|
|
continue;
|
|
if (s_seen[g_drawWhat]++ < 2)
|
|
{
|
|
const bozo::render::Vertex *v = &vertices[t];
|
|
std::fprintf(stderr, "[dc:spike] %s: span %.0f, object (%g %g %g) (%g %g %g) (%g %g %g)\n", g_drawWhat, span,
|
|
v[0].x, v[0].y, v[0].z, v[1].x, v[1].y, v[1].z, v[2].x, v[2].y, v[2].z);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
void submit(const DrawSetup &setup, bozo::render::Material &material,
|
|
const std::shared_ptr<const bozo::render::Texture> &texture,
|
|
std::vector<bozo::render::Vertex> &vertices, bool screenRefraction = false)
|
|
{
|
|
probeSpikes(setup, vertices);
|
|
if (setup.guard)
|
|
{
|
|
size_t kept = 0;
|
|
for (size_t t = 0; t + 2u < vertices.size(); t += 3u)
|
|
{
|
|
bool inside = true;
|
|
for (int k = 0; k < 3 && inside; ++k)
|
|
{
|
|
const bozo::render::Vertex &v = vertices[t + static_cast<size_t>(k)];
|
|
const float *m = setup.toScreen.m;
|
|
const float w = m[3] * v.x + m[7] * v.y + m[11] * v.z + m[15];
|
|
const float x = (m[0] * v.x + m[4] * v.y + m[8] * v.z + m[12]) / w;
|
|
const float y = (m[1] * v.x + m[5] * v.y + m[9] * v.z + m[13]) / w;
|
|
inside = x > setup.guardLow[0] && x < setup.guardHigh[0] && y > setup.guardLow[1] && y < setup.guardHigh[1] &&
|
|
w > setup.guardLow[3] && w < setup.guardHigh[3];
|
|
}
|
|
if (!inside)
|
|
{
|
|
++g_stats.guarded;
|
|
continue;
|
|
}
|
|
for (int k = 0; k < 3; ++k)
|
|
vertices[kept++] = vertices[t + static_cast<size_t>(k)];
|
|
}
|
|
vertices.resize(kept);
|
|
}
|
|
if (setup.cull)
|
|
{
|
|
size_t kept = 0;
|
|
for (size_t t = 0; t + 2u < vertices.size(); t += 3u)
|
|
{
|
|
float sx[3], sy[3];
|
|
bool front = true;
|
|
for (int k = 0; k < 3; ++k)
|
|
{
|
|
const bozo::render::Vertex &v = vertices[t + static_cast<size_t>(k)];
|
|
const float *m = setup.toScreen.m;
|
|
const float w = m[3] * v.x + m[7] * v.y + m[11] * v.z + m[15];
|
|
if (!(w > 0.0f))
|
|
{
|
|
front = true; // crosses the camera plane: left to the depth clip, as the program's clipper
|
|
break;
|
|
}
|
|
sx[k] = (m[0] * v.x + m[4] * v.y + m[8] * v.z + m[12]) / w;
|
|
sy[k] = (m[1] * v.x + m[5] * v.y + m[9] * v.z + m[13]) / w;
|
|
if (k == 2)
|
|
front = (sx[2] - sx[0]) * (sy[1] - sy[0]) - (sy[2] - sy[0]) * (sx[1] - sx[0]) >= 0.0f;
|
|
}
|
|
if (!front)
|
|
{
|
|
++g_stats.culled;
|
|
continue;
|
|
}
|
|
for (int k = 0; k < 3; ++k)
|
|
vertices[kept++] = vertices[t + static_cast<size_t>(k)];
|
|
}
|
|
vertices.resize(kept);
|
|
}
|
|
clipDepth(setup.clip, vertices);
|
|
if (vertices.empty())
|
|
return;
|
|
// DC_PROBE_SPIKES=1 also measures the GS Z the clipped vertices get (z / w), against the 24 bits the
|
|
// renderer keeps (it wraps past them): the largest per 300 frames and how many vertices go past.
|
|
static const bool s_probeZ = [] { const char *e = std::getenv("DC_PROBE_SPIKES"); return e && e[0] == '1'; }();
|
|
if (s_probeZ)
|
|
for (const bozo::render::Vertex &v : vertices)
|
|
{
|
|
const float *m = setup.toScreen.m;
|
|
const float w = m[3] * v.x + m[7] * v.y + m[11] * v.z + m[15];
|
|
const float z = (m[2] * v.x + m[6] * v.y + m[10] * v.z + m[14]) / w; // XYZF2: Z = z / w
|
|
g_stats.maxZ = std::max(g_stats.maxZ, static_cast<double>(z));
|
|
g_stats.minZ = std::min(g_stats.minZ, static_cast<double>(z));
|
|
if (z >= 16777216.0f)
|
|
++g_stats.zPast24;
|
|
if (z < 0.0f)
|
|
++g_stats.zNegative;
|
|
}
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
material.textured = setup.textureMapped && (texture != nullptr || material.fromFrame != 0u);
|
|
g_stats.triangles += vertices.size() / 3u;
|
|
// The frame dump: what each draw sends after the guard band and culling (its colours' and fog's ranges, its
|
|
// blend and tests), for a draw that is there but not seen.
|
|
if (g_dump2D)
|
|
{
|
|
uint32_t lo = 0xFFFFFFFFu, hi = 0u;
|
|
float fogLo = 1e9f, fogHi = -1e9f;
|
|
for (const bozo::render::Vertex &v : vertices)
|
|
{
|
|
for (uint32_t b = 0; b < 32u; b += 8u)
|
|
{
|
|
const uint32_t c = (v.rgba >> b) & 0xFFu;
|
|
lo = (lo & ~(0xFFu << b)) | (std::min(c, (lo >> b) & 0xFFu) << b);
|
|
hi = (hi & ~(0xFFu << b)) | (std::max(c, (hi >> b) & 0xFFu) << b);
|
|
}
|
|
fogLo = std::min(fogLo, v.fog);
|
|
fogHi = std::max(fogHi, v.fog);
|
|
}
|
|
std::fprintf(stderr, "[dc:dump] %zu triangles, rgba %08x..%08x (a.b.g.r), fog %s %.2f..%.2f, blend %d test %d/%u depth %d/%d, %s\n",
|
|
vertices.size() / 3u, lo, hi, material.fog ? "on" : "off", fogLo, fogHi, static_cast<int>(material.blend),
|
|
material.alphaTest ? 1 : 0, material.alphaRef, material.depthTest ? 1 : 0, material.depthWrite ? 1 : 0,
|
|
material.textured ? (material.fromFrame != 0u ? "frame" : "textured") : "untextured");
|
|
if (material.tex0 != 0u)
|
|
std::fprintf(stderr, "[dc:dump] tex0 %016llx%s\n", static_cast<unsigned long long>(material.tex0),
|
|
texture ? "" : " (no texture)");
|
|
// Where the draw lands on the screen (GS pixels) and its widest triangle: object coordinates and w.
|
|
float sxLo = 1e30f, syLo = 1e30f, sxHi = -1e30f, syHi = -1e30f, widest = -1.0f;
|
|
size_t widestAt = 0;
|
|
const float *t = setup.toScreen.m;
|
|
for (size_t k = 0; k + 2u < vertices.size(); k += 3u)
|
|
{
|
|
float sx[3], sy[3];
|
|
for (int j = 0; j < 3; ++j)
|
|
{
|
|
const bozo::render::Vertex &v = vertices[k + static_cast<size_t>(j)];
|
|
const float w = t[3] * v.x + t[7] * v.y + t[11] * v.z + t[15];
|
|
sx[j] = (t[0] * v.x + t[4] * v.y + t[8] * v.z + t[12]) / w;
|
|
sy[j] = (t[1] * v.x + t[5] * v.y + t[9] * v.z + t[13]) / w;
|
|
sxLo = std::min(sxLo, sx[j]), sxHi = std::max(sxHi, sx[j]);
|
|
syLo = std::min(syLo, sy[j]), syHi = std::max(syHi, sy[j]);
|
|
}
|
|
const float span = std::max({std::fabs(sx[0] - sx[1]), std::fabs(sx[1] - sx[2]), std::fabs(sx[0] - sx[2]),
|
|
std::fabs(sy[0] - sy[1]), std::fabs(sy[1] - sy[2]), std::fabs(sy[0] - sy[2])});
|
|
if (span > widest)
|
|
widest = span, widestAt = k;
|
|
}
|
|
if (!vertices.empty())
|
|
{
|
|
std::fprintf(stderr, "[dc:dump] screen x %.0f..%.0f y %.0f..%.0f, widest triangle %.0f:", sxLo, sxHi, syLo, syHi, widest);
|
|
for (int j = 0; j < 3; ++j)
|
|
{
|
|
const bozo::render::Vertex &v = vertices[widestAt + static_cast<size_t>(j)];
|
|
std::fprintf(stderr, " (%g %g %g w %g)", v.x, v.y, v.z, t[3] * v.x + t[7] * v.y + t[11] * v.z + t[15]);
|
|
}
|
|
std::fprintf(stderr, "\n");
|
|
}
|
|
}
|
|
if (material.textured && material.fromFrame != 0u)
|
|
{
|
|
if (screenRefraction)
|
|
{
|
|
// Water's program 15 samples the scene at the projected point,
|
|
// displaced by its height differences. Project AFTER clipping;
|
|
// its texture coordinates interpolate in screen space, without
|
|
// the mesh's perspective dividing them a second time.
|
|
const float *m = setup.toScreen.m;
|
|
size_t kept = 0;
|
|
for (size_t t = 0; t + 2u < vertices.size(); t += 3u)
|
|
{
|
|
bozo::render::Vertex projected[3];
|
|
bool valid = true;
|
|
for (int k = 0; k < 3; ++k)
|
|
{
|
|
auto &v = projected[k] = vertices[t + k];
|
|
const float w = m[3] * v.x + m[7] * v.y + m[11] * v.z + m[15];
|
|
if (!(w > 0.0f)) { valid = false; break; }
|
|
const float x = (m[0] * v.x + m[4] * v.y + m[8] * v.z + m[12]) / w;
|
|
const float y = (m[1] * v.x + m[5] * v.y + m[9] * v.z + m[13]) / w;
|
|
const float z = (m[2] * v.x + m[6] * v.y + m[10] * v.z + m[14]) / w;
|
|
v.u = frameU(x + v.u); // v.u held the displacement in GS pixels
|
|
v.v = (y - 1936.0f + v.v) / material.frameHeight;
|
|
v.x = x; v.y = y; v.z = z; v.q = 1.0f;
|
|
valid &= std::isfinite(x) && std::isfinite(y) && std::isfinite(z) && std::isfinite(v.u) && std::isfinite(v.v);
|
|
}
|
|
if (valid)
|
|
for (const auto &v : projected) vertices[kept++] = v;
|
|
}
|
|
vertices.resize(kept);
|
|
static constexpr float identity[16] = {1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
|
|
renderer.draw(material, identity, vertices.data(), static_cast<uint32_t>(vertices.size()));
|
|
}
|
|
else
|
|
renderer.draw(material, setup.toScreen.m, vertices.data(), static_cast<uint32_t>(vertices.size()));
|
|
}
|
|
else if (material.textured)
|
|
{
|
|
++g_stats.ownTextures;
|
|
renderer.draw(material, setup.toScreen.m, vertices.data(), static_cast<uint32_t>(vertices.size()), texture);
|
|
}
|
|
else
|
|
{
|
|
g_stats.noTexture += setup.textureMapped ? 1u : 0u;
|
|
renderer.draw(material, setup.toScreen.m, vertices.data(), static_cast<uint32_t>(vertices.size()));
|
|
}
|
|
}
|
|
|
|
// A material's colour (its first quadword, VU 37 for the program) and its texture record.
|
|
uint32_t materialRecord(const uint8_t *rdram, uint32_t mat)
|
|
{
|
|
return textureRecord(rdram, mat + 0x34u);
|
|
}
|
|
// The same for a model's material (its name read through the model: a copy when the MDT is gone), keyed by
|
|
// the name, as SearchTextureName finds a record by it.
|
|
uint32_t modelMaterialRecord(const uint8_t *rdram, const Model &m, uint32_t mat)
|
|
{
|
|
if (!m.copy)
|
|
return materialRecord(rdram, mat);
|
|
std::string name;
|
|
for (uint32_t k = 0; k < 32u; ++k)
|
|
{
|
|
const char c = static_cast<char>(m.u8(mat + 0x34u + k));
|
|
if (c == '\0')
|
|
break;
|
|
name.push_back(c);
|
|
}
|
|
const int32_t count = static_cast<int32_t>(rd32(rdram, kTextureManager));
|
|
uint32_t record = 0;
|
|
for (int32_t i = std::min(count, 1023); i >= 0 && record == 0u; --i)
|
|
{
|
|
const uint32_t candidate = kTextureManager + 0x10F8u + static_cast<uint32_t>(i) * 0x50u;
|
|
uint32_t k = 0;
|
|
for (; k < name.size() && rdram[(candidate + 8u + k) & 0x1FFFFFFu] == static_cast<uint8_t>(name[k]); ++k)
|
|
{
|
|
}
|
|
if (!name.empty() && k == name.size() && rdram[(candidate + 8u + k) & 0x1FFFFFFu] == 0u)
|
|
record = candidate;
|
|
}
|
|
return record;
|
|
}
|
|
|
|
// One model piece, from its MDT: + 0x10 positions, + 0x18 normals, + 0x20 colours (none when <= 0), + 0x28
|
|
// the primitives (count at + 8, from + 0x10: type (4 strip, 3 list), vertex count, material (-1: the one
|
|
// before), then per vertex the indices of its position, normal, texture coordinates and colour), + 0x30 texture
|
|
// coordinates (the positions when <= 0), + 0x38 the materials.
|
|
uint32_t g_fogColour = 0; // FOGCOL as the models' DrawVu1 last set it (RenderInfo + 0x338): the 3D sprites' fog
|
|
bool sampleMade(uint32_t base, bozo::render::Material &material);
|
|
extern std::unordered_map<uint32_t, uint8_t> g_targetOfBase;
|
|
void drawModel(const uint8_t *rdram, const Model &m, const Matrix &localToWorld, uint32_t renderInfo, bool drawn)
|
|
{
|
|
const uint32_t mdt = m.mdt;
|
|
DrawSetup setup = drawSetup(rdram, localToWorld, renderInfo);
|
|
setup.cull = (rd32(rdram, renderInfo + 0x310u) & 4u) != 0u;
|
|
static const bool s_noFog = std::getenv("DC_NO_FOG") != nullptr; // diagnosis
|
|
setup.fog = !s_noFog && !g_toggles.noFog && rd32(rdram, renderInfo + 0x324u) != 0u && rd32(rdram, renderInfo + 0x320u) == 0u;
|
|
// DC_PROBE_FOG=1 (diagnosis): the fog of the first RenderInfos seen.
|
|
static int s_fogLogged = 0;
|
|
if (std::getenv("DC_PROBE_FOG") && s_fogLogged < 12 && setup.fog)
|
|
{
|
|
++s_fogLogged;
|
|
std::fprintf(stderr, "[dc:fog] RenderInfo %08x colour %06x base %g scale %g range %g..%g\n", renderInfo,
|
|
rd32(rdram, renderInfo + 0x338u) & 0xFFFFFFu, rdf(rdram, renderInfo + 0x328u), rdf(rdram, renderInfo + 0x32Cu),
|
|
rdf(rdram, renderInfo + 0x330u), rdf(rdram, renderInfo + 0x334u));
|
|
}
|
|
setup.fogColour = rd32(rdram, renderInfo + 0x338u) & 0xFFFFFFu;
|
|
setup.fogBase = rdf(rdram, renderInfo + 0x328u);
|
|
setup.fogMax = rdf(rdram, renderInfo + 0x334u);
|
|
setup.fogMin = rdf(rdram, renderInfo + 0x330u);
|
|
setup.fogScale = rdf(rdram, renderInfo + 0x32Cu);
|
|
static const bool s_noCull = [] { const char *v = std::getenv("DC_NO_CULL"); return v && v[0] == '1'; }();
|
|
if (s_noCull) // diagnosis
|
|
setup.cull = false;
|
|
Lighting &lighting = setup.lighting;
|
|
const float uvScale = setup.uvScale;
|
|
|
|
const uint32_t positions = mdt + m.u32(mdt + 0x10u), normals = mdt + m.u32(mdt + 0x18u);
|
|
const int32_t colourOffset = static_cast<int32_t>(m.u32(mdt + 0x20u));
|
|
const int32_t uvOffset = static_cast<int32_t>(m.u32(mdt + 0x30u));
|
|
const uint32_t uvs = uvOffset > 0 ? mdt + static_cast<uint32_t>(uvOffset) : positions;
|
|
const uint32_t stride = colourOffset > 0 ? 4u : 3u;
|
|
const uint32_t colours = colourOffset > 0 ? mdt + static_cast<uint32_t>(colourOffset) : 0u;
|
|
const uint32_t materials = mdt + m.u32(mdt + 0x38u);
|
|
const uint32_t list = mdt + m.u32(mdt + 0x28u);
|
|
const uint32_t primitives = m.u32(list + 8u);
|
|
|
|
bozo::render::Material material;
|
|
material.textured = false;
|
|
material.depthTest = true;
|
|
// SetEnv's original CLAMP_1=5 clamps both axes. Repeating here
|
|
// blends the far atlas edge into mirrored model joins at UV zero.
|
|
material.clampU = material.clampV = true;
|
|
applyObjectState(g_objectState, material);
|
|
if (g_toggles.opaqueModels)
|
|
material.blend = bozo::render::Material::Blend::Opaque;
|
|
float madeU = 1.0f, madeV = 1.0f; // a made picture's texture coordinates (see the record lookup below)
|
|
material.fog = setup.fog;
|
|
material.fogColour = setup.fogColour;
|
|
g_fogColour = setup.fogColour;
|
|
std::shared_ptr<const bozo::render::Texture> texture;
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
// Each record is looked up once per draw: no game code runs between this draw's primitives, so their
|
|
// textures cannot change in between, and a record's change check hashes its whole picture (many
|
|
// primitives of a model share one).
|
|
std::vector<std::pair<uint32_t, std::shared_ptr<const bozo::render::Texture>>> drawTextures;
|
|
auto drawTexture = [&](uint32_t record) {
|
|
for (const auto &[seen, image] : drawTextures)
|
|
if (seen == record)
|
|
return image;
|
|
auto image = recordTexture(rdram, record);
|
|
drawTextures.emplace_back(record, image);
|
|
return image;
|
|
};
|
|
|
|
uint32_t at = list + 0x10u;
|
|
for (uint32_t p = 0; p < primitives && p < 4096u; ++p)
|
|
{
|
|
const uint32_t type = m.u32(at), count = m.u32(at + 4u);
|
|
const int32_t materialIndex = static_cast<int32_t>(m.u32(at + 8u));
|
|
const uint32_t indices = at + 12u;
|
|
at = indices + count * stride * 4u;
|
|
if (materialIndex >= 0)
|
|
{
|
|
const uint32_t mat = materials + static_cast<uint32_t>(materialIndex) * 0x60u;
|
|
for (int c = 0; c < 4; ++c)
|
|
lighting.material[c] = m.f(mat + static_cast<uint32_t>(c) * 4u);
|
|
const TextureBinding *binding = m.records && p < m.records->size() ? &(*m.records)[p] : nullptr;
|
|
const uint32_t record = binding ? resolveBinding(rdram,*binding) : modelMaterialRecord(rdram, m, mat);
|
|
texture = record != 0u ? drawTexture(record) : binding ? binding->image : nullptr;
|
|
if (binding && texture) binding->image = texture;
|
|
material.tex0 = binding ? binding->tex0() : record != 0u ? rd64(rdram, record + 0x28u) : 0u;
|
|
// A record without pixels of its own whose place holds a picture the game makes there (the towns'
|
|
// "work": MainDraw copies the frame into it each frame, and a model piece under the ground samples it
|
|
// through its own texture coordinates): that picture, its texels the frame's (640 x rows of the
|
|
// record's 2^TW x 2^TH).
|
|
material.fromFrame = 0;
|
|
material.source = 0;
|
|
madeU = madeV = 1.0f;
|
|
static const bool s_noMadeModels = std::getenv("DC_NO_MADE_MODELS") != nullptr; // diagnosis
|
|
// Only an actual native producer establishes a work image.
|
|
// A matching legacy place is not provenance for the previous
|
|
// scene: that guess fed village geometry back into the sky.
|
|
if (!s_noMadeModels && !texture && (binding ? binding->record && binding->word(0x38)==0u : record && rd32(rdram,record+0x38)==0u))
|
|
{
|
|
bozo::render::Material made;
|
|
if (sampleMade(static_cast<uint32_t>(material.tex0 & 0x3FFFu), made) && made.source != 0u)
|
|
{
|
|
material.fromFrame = made.fromFrame;
|
|
material.source = made.source;
|
|
material.frameWidth = made.frameWidth;
|
|
material.frameHeight = made.frameHeight;
|
|
madeU = static_cast<float>(1u << ((material.tex0 >> 26) & 0xFu)) / static_cast<float>(made.frameWidth);
|
|
madeV = static_cast<float>(1u << ((material.tex0 >> 30) & 0xFu)) / static_cast<float>(made.frameHeight);
|
|
}
|
|
}
|
|
if (g_sampleSkyDraws && p == 0u && g_skyDrawIndex <= 8u)
|
|
{
|
|
std::fprintf(stderr,"[dc:sky-draw] part %u mdt %08x record %08x name %.32s tex %llx version %llu frame %u/%u ambient %g,%g,%g,%g material %g,%g,%g,%g\n",
|
|
g_skyDrawIndex,mdt,record,record?reinterpret_cast<const char *>(rdram+record+8):"",
|
|
static_cast<unsigned long long>(material.tex0),static_cast<unsigned long long>(texture?texture->version:0),
|
|
material.fromFrame,material.source,lighting.ambient[0],lighting.ambient[1],lighting.ambient[2],lighting.ambient[3],
|
|
lighting.material[0],lighting.material[1],lighting.material[2],lighting.material[3]);
|
|
}
|
|
// DC_PROBE_LEVELS=1 (diagnosis): each model record's TEX0, + 0x30 and level pointers, once.
|
|
static const bool s_probeLevels = std::getenv("DC_PROBE_LEVELS") != nullptr;
|
|
static std::unordered_map<uint32_t, bool> s_levelsSeen;
|
|
if (s_probeLevels && record != 0u && !s_levelsSeen[record] && s_levelsSeen.size() < 400u)
|
|
{
|
|
s_levelsSeen[record] = true;
|
|
std::fprintf(stderr, "[dc:levels] %08x \"%.32s\" %ux%u kind %u tex0 %016llx +30 %016llx levels %08x %08x %08x %08x\n", record,
|
|
reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)), rd32(rdram, record) >> 16,
|
|
rd32(rdram, record + 4u) & 0xFFFFu, rd32(rdram, record + 4u) >> 16,
|
|
static_cast<unsigned long long>(rd64(rdram, record + 0x28u)),
|
|
static_cast<unsigned long long>(rd64(rdram, record + 0x30u)), rd32(rdram, record + 0x38u),
|
|
rd32(rdram, record + 0x3Cu), rd32(rdram, record + 0x40u), rd32(rdram, record + 0x44u));
|
|
}
|
|
// DC_PROBE_UNTEX=1 (diagnosis): each record a model primitive cannot be textured with, once.
|
|
static const bool s_probeUntex = std::getenv("DC_PROBE_UNTEX") != nullptr;
|
|
static std::unordered_map<uint32_t, bool> s_untex;
|
|
if (s_probeUntex && !texture && !s_untex[record])
|
|
{
|
|
s_untex[record] = true;
|
|
char name[33] = {};
|
|
for (uint32_t k = 0; record != 0u && k < 32u; ++k)
|
|
name[k] = static_cast<char>(rdram[(record + 8u + k) & 0x1FFFFFFu]);
|
|
const uint64_t tex0 = record != 0u ? rd64(rdram, record + 0x28u) : 0u;
|
|
std::fprintf(stderr, "[dc:untex] record %08x \"%s\" kind %u psm 0x%x %ux%u flag %u pixels %08x palette %08x\n", record,
|
|
name, record != 0u ? rd32(rdram, record + 4u) >> 16 : 0u, static_cast<unsigned>((tex0 >> 20) & 0x3Fu),
|
|
record != 0u ? rd32(rdram, record) >> 16 : 0u, record != 0u ? rd32(rdram, record + 4u) & 0xFFFFu : 0u,
|
|
record != 0u ? rd32(rdram, record + 0x4Cu) : 0u, record != 0u ? rd32(rdram, record + 0x38u) : 0u,
|
|
record != 0u ? rd32(rdram, record + 0x48u) : 0u);
|
|
std::fprintf(stderr, "[dc:untex] used by %s at (%g %g %g), tex0 %016llx, uv scale %g\n", g_drawWhat, localToWorld.m[12],
|
|
localToWorld.m[13], localToWorld.m[14], static_cast<unsigned long long>(tex0), uvScale);
|
|
}
|
|
}
|
|
if (count == 0u || count > 65536u)
|
|
continue;
|
|
// Each primitive is a program run of its own on VU1 (an MSCAL): the renderer group VIF1 skips there.
|
|
renderer.beginGroup(++g_group);
|
|
if (!drawn)
|
|
continue;
|
|
++g_stats.primitives;
|
|
auto vertex = [&](uint32_t i) {
|
|
const uint32_t tuple = indices + i * stride * 4u;
|
|
const uint32_t pi = m.u32(tuple), ni = m.u32(tuple + 4u), ti = m.u32(tuple + 8u);
|
|
bozo::render::Vertex v;
|
|
v.x = m.f(positions + pi * 16u);
|
|
v.y = m.f(positions + pi * 16u + 4u);
|
|
v.z = m.f(positions + pi * 16u + 8u);
|
|
v.u = m.f(uvs + ti * 16u) * uvScale * madeU;
|
|
v.v = m.f(uvs + ti * 16u + 4u) * uvScale * madeV;
|
|
float colour[4];
|
|
if (stride == 4u)
|
|
{
|
|
const uint32_t ci = m.u32(tuple + 12u);
|
|
for (uint32_t c = 0; c < 4u; ++c)
|
|
colour[c] = m.f(colours + ci * 16u + c * 4u);
|
|
// DC_LOG_VCOLOUR=1 (diagnosis): the first colours read, once.
|
|
static const bool s_log = [] { const char *e = std::getenv("DC_LOG_VCOLOUR"); return e && e[0] == '1'; }();
|
|
static int s_logged = 0;
|
|
if (s_log && s_logged < 24)
|
|
{
|
|
++s_logged;
|
|
std::fprintf(stderr, "[dc:native] vertex colour %u: %g %g %g %g\n", ci, colour[0], colour[1], colour[2], colour[3]);
|
|
}
|
|
}
|
|
v.rgba = shade(lighting, m.f(normals + ni * 16u), m.f(normals + ni * 16u + 4u),
|
|
m.f(normals + ni * 16u + 8u), stride == 4u ? colour : nullptr);
|
|
// The frame dump: a primitive's first vertex, its raw colour and the lighting it gets.
|
|
if (g_dump2D && i == 0u)
|
|
std::fprintf(stderr, "[dc:dump] vertex colour %s (%g %g %g %g) material (%g %g %g %g) ambient (%g %g %g %g) light0 (%g %g %g %g) -> %08x\n",
|
|
stride == 4u ? "" : "none", stride == 4u ? colour[0] : 0.0f, stride == 4u ? colour[1] : 0.0f,
|
|
stride == 4u ? colour[2] : 0.0f, stride == 4u ? colour[3] : 0.0f, lighting.material[0],
|
|
lighting.material[1], lighting.material[2], lighting.material[3], lighting.ambient[0],
|
|
lighting.ambient[1], lighting.ambient[2], lighting.ambient[3], lighting.colour[0][0],
|
|
lighting.colour[0][1], lighting.colour[0][2], lighting.colour[0][3], v.rgba);
|
|
if (setup.fog)
|
|
{
|
|
const float *t = setup.toScreen.m;
|
|
const float w = t[3] * v.x + t[7] * v.y + t[11] * v.z + t[15];
|
|
float f = w != 0.0f ? setup.fogBase + setup.fogScale / w : setup.fogMax;
|
|
f = std::max(std::min(f, setup.fogMax), setup.fogMin);
|
|
v.fog = std::min(std::max(f, 0.0f), 255.0f) / 255.0f;
|
|
}
|
|
return v;
|
|
};
|
|
vertices.clear();
|
|
if (type == 4u)
|
|
for (uint32_t i = 2; i < count; ++i)
|
|
{
|
|
bozo::render::Vertex a = vertex(i - 2), b = vertex(i - 1), c = vertex(i);
|
|
if (i & 1u)
|
|
std::swap(a, b);
|
|
vertices.push_back(a);
|
|
vertices.push_back(b);
|
|
vertices.push_back(c);
|
|
}
|
|
else
|
|
for (uint32_t i = 0; i + 2 < count; i += 3)
|
|
{
|
|
vertices.push_back(vertex(i));
|
|
vertices.push_back(vertex(i + 1));
|
|
vertices.push_back(vertex(i + 2));
|
|
}
|
|
// The untextured model program emits display RGB, not texture
|
|
// modulation factors. Keep alpha's 0x80 unit and textured RGB.
|
|
material.directColour = !(setup.textureMapped && (texture != nullptr || material.fromFrame != 0u));
|
|
submit(setup, material, texture, vertices);
|
|
}
|
|
}
|
|
|
|
void noteShadow(const uint8_t *rdram, const Model &m, const Matrix &localToWorld, uint32_t renderInfo, bool listsOnly);
|
|
|
|
// Water. CWater (CWater::DrawVu1 0x160F20) is a height field: rows at + 0, columns at + 4, its current heights
|
|
// at + 8 (rows x columns floats), the corners at + 0x20 (base), + 0x30 (the last row's) and + 0x40 (the last
|
|
// column's), its colour at + 0x90 (RGBA bytes), the height scale at + 0x9C, its visual at + 0x70 (VU data at
|
|
// + 0x88, its size at + 0x8C, that visual's + 0x18 / + 0x1C). CreateVUData (0x1607E0) walks each row from base +
|
|
// row x row step (no height step) and, per column, outputs the point and then sets its height to the column's
|
|
// height x the scale (a column's vertex has the height of the column before it) and steps it along the row; one
|
|
// strip per pair of rows. The game draws it with the screen-space program, textured with "work" (its copy of the
|
|
// frame) at coordinates perturbed by the height differences (+ 0xA0). Sample only the native target produced
|
|
// by the game's actual copy into that place; an unproduced work texture keeps the colour-only fallback.
|
|
// CreateVUData is taken over to build nothing (the
|
|
// visual's size 0: DrawVu1 sends no packet and VU1 runs nothing), and the water is drawn where DrawVu1 is
|
|
// called for its visual, with the local-to-world matrix CWater::DrawVu1 hands it.
|
|
constexpr uint32_t kWaterCreateVUData = 0x001607E0u;
|
|
std::mutex g_waterMutex;
|
|
std::unordered_map<uint32_t, uint32_t> g_waterOfVisual;
|
|
void waterCreateHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
const uint32_t water = getRegU32(ctx, 4), data = getRegU32(ctx, 5);
|
|
std::memcpy(rdram + ((water + 0x88u) & 0x1FFFFFFu), &data, 4);
|
|
const uint32_t none = 0;
|
|
std::memcpy(rdram + ((water + 0x8Cu) & 0x1FFFFFFu), &none, 4);
|
|
{
|
|
std::lock_guard<std::mutex> lock(g_waterMutex);
|
|
g_waterOfVisual[water + 0x70u] = water;
|
|
}
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
|
|
void drawWater(const uint8_t *rdram, uint32_t water, const Matrix &localToWorld, uint32_t renderInfo)
|
|
{
|
|
const int32_t rows = static_cast<int32_t>(rd32(rdram, water)), columns = static_cast<int32_t>(rd32(rdram, water + 4u));
|
|
const uint32_t heights = rd32(rdram, water + 8u);
|
|
if (rows < 2 || columns < 2 || rows > 256 || columns > 256 || heights == 0u)
|
|
return;
|
|
++g_stats.waters;
|
|
DrawSetup setup = drawSetup(rdram, localToWorld, renderInfo);
|
|
bozo::render::Material material;
|
|
const uint32_t work = textureRecord(rdram, 0x0029A0B8u); // CreateVUData's "work" lookup
|
|
const uint32_t baseOfWork = work ? static_cast<uint32_t>(rd64(rdram, work + 0x28u) & 0x3FFFu) : ~0u;
|
|
// An explicit producer is required. In the dungeon MGMoveImage copies
|
|
// the current frame to "water", which shares "work"'s place. Never
|
|
// interpret an unbacked texture name/base as the previous frame.
|
|
const auto target = g_targetOfBase.find(baseOfWork);
|
|
const bool refracted = work && target != g_targetOfBase.end() && sampleMade(baseOfWork, material) &&
|
|
material.source == target->second;
|
|
setup.textureMapped = refracted;
|
|
material.clampU = material.clampV = true;
|
|
float base[3], rowStep[3], columnStep[3];
|
|
for (int i = 0; i < 3; ++i)
|
|
{
|
|
base[i] = rdf(rdram, water + 0x20u + static_cast<uint32_t>(i) * 4u);
|
|
rowStep[i] = (rdf(rdram, water + 0x30u + static_cast<uint32_t>(i) * 4u) - base[i]) / static_cast<float>(rows - 1);
|
|
columnStep[i] = (rdf(rdram, water + 0x40u + static_cast<uint32_t>(i) * 4u) - base[i]) / static_cast<float>(columns - 1);
|
|
}
|
|
rowStep[1] = columnStep[1] = 0.0f;
|
|
const float scale = rdf(rdram, water + 0x9Cu);
|
|
const float perturbation = rdf(rdram, water + 0xA0u);
|
|
const uint32_t colour = rd32(rdram, water + 0x90u);
|
|
std::vector<bozo::render::Vertex> grid(static_cast<size_t>(rows) * columns);
|
|
for (int32_t r = 0; r < rows; ++r)
|
|
{
|
|
float point[3] = {base[0] + static_cast<float>(r) * rowStep[0], base[1], base[2] + static_cast<float>(r) * rowStep[2]};
|
|
for (int32_t c = 0; c < columns; ++c)
|
|
{
|
|
bozo::render::Vertex &v = grid[static_cast<size_t>(r) * columns + c];
|
|
v.x = point[0];
|
|
v.y = point[1];
|
|
v.z = point[2];
|
|
v.rgba = colour;
|
|
const uint32_t index = static_cast<uint32_t>(r * columns + c);
|
|
const float height = rdf(rdram, heights + index * 4u);
|
|
const float previousRow = rdf(rdram, heights + (r ? index - columns : index) * 4u);
|
|
// The builder reads the following float even at a row end;
|
|
// SetSize reserves an extra quadword after the height grid.
|
|
const float nextColumn = rdf(rdram, heights + (index + 1u) * 4u);
|
|
v.u = perturbation * (previousRow - height);
|
|
v.v = perturbation * (height - nextColumn);
|
|
point[1] = rdf(rdram, heights + static_cast<uint32_t>(r * columns + c) * 4u) * scale;
|
|
point[0] += columnStep[0];
|
|
point[2] += columnStep[2];
|
|
}
|
|
}
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
for (int32_t r = 0; r + 1 < rows; ++r)
|
|
for (int32_t c = 1; c < columns; ++c)
|
|
{
|
|
// CreateVUData's strip: row r, then row r + 1, at each column.
|
|
const bozo::render::Vertex &a = grid[static_cast<size_t>(r) * columns + c - 1];
|
|
const bozo::render::Vertex &b = grid[static_cast<size_t>(r + 1) * columns + c - 1];
|
|
const bozo::render::Vertex &d = grid[static_cast<size_t>(r) * columns + c];
|
|
const bozo::render::Vertex &e = grid[static_cast<size_t>(r + 1) * columns + c];
|
|
vertices.insert(vertices.end(), {a, b, d, b, e, d});
|
|
}
|
|
material.textured = refracted;
|
|
material.depthTest = true;
|
|
material.depthWrite = false;
|
|
material.blend = bozo::render::Material::Blend::Alpha;
|
|
submit(setup, material, nullptr, vertices, refracted);
|
|
}
|
|
|
|
uint64_t g_retiredModelEnvelopes = 0;
|
|
void drawVu1Hook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
// The sceVif1Packet overload (0x134BC0) forwards these same native
|
|
// inputs. Its old packet termination/cursor/reservation is unnecessary.
|
|
if (ctx->pc == 0x00134BC0u) ++g_retiredModelEnvelopes;
|
|
const uint32_t visual = getRegU32(ctx, 4), localToWorld = getRegU32(ctx, 6);
|
|
const uint32_t renderInfo = getRegU32(ctx, 7), program = getRegU32(ctx, 8);
|
|
const bool newLights = getRegU32(ctx, 11) == 0u; // DrawVu1's last argument: 0 sends RenderInfo's lights
|
|
// The original's only nonlocal output was its console packet. Native drawing
|
|
// already computes the matrices/lights below; no packet or packet-sized return.
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
++g_stats.calls;
|
|
{
|
|
uint32_t water = 0;
|
|
{
|
|
std::lock_guard<std::mutex> lock(g_waterMutex);
|
|
const auto found = g_waterOfVisual.find(visual);
|
|
water = found == g_waterOfVisual.end() ? 0u : found->second;
|
|
}
|
|
if (water != 0u)
|
|
{
|
|
g_objectState.valid = false;
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
drawWater(rdram, water, load(rdram, localToWorld), renderInfo);
|
|
return;
|
|
}
|
|
}
|
|
const ObjectMaterial state = g_objectState;
|
|
g_objectState.valid = false;
|
|
if (rd32(rdram, visual + 0x18u) == 0u || rd32(rdram, visual + 0x1Cu) == 0u)
|
|
return; // DrawVu1 drew nothing (no VU data)
|
|
if (newLights)
|
|
readLights(rdram, renderInfo);
|
|
// Shadow volumes (RenderInfo + 0x320) and the screen-space program (0xF) are not drawn yet.
|
|
const bool shadow = rd32(rdram, renderInfo + 0x320u) != 0u, screenSpace = program == 0xFu;
|
|
g_stats.shadows += shadow ? 1u : 0u;
|
|
g_stats.screenSpace += screenSpace ? 1u : 0u;
|
|
const Model model = modelOf(rdram, visual);
|
|
const uint32_t mdt = model.mdt;
|
|
if (!model)
|
|
{
|
|
++g_stats.noModel;
|
|
return;
|
|
}
|
|
if (g_inSky)
|
|
{
|
|
++g_skyDrawIndex;
|
|
}
|
|
g_objectState = state;
|
|
std::snprintf(g_drawWhat, sizeof(g_drawWhat), "model visual %08x vtable %08x data %08x mdt %08x %s program %u flags %x",
|
|
visual, rd32(rdram, visual + 8u), rd32(rdram, visual + 0x18u), mdt, model.copy ? "copy" : "live", program,
|
|
rd32(rdram, renderInfo + 0x310u));
|
|
seq('M');
|
|
if (g_dump2D)
|
|
{
|
|
const Matrix world = load(rdram, localToWorld);
|
|
std::fprintf(stderr, "[dc:dump] %s shadow %u at (%g %g %g) native blend %u%s\n", g_drawWhat, rd32(rdram, renderInfo + 0x320u),
|
|
world.m[12], world.m[13], world.m[14], static_cast<unsigned>(state.blend), state.valid ? "" : " (no material)");
|
|
}
|
|
// DC_SKIP_MDT=<hex address> (diagnosis): models with that MDT are not drawn.
|
|
static const uint32_t s_skipMdt = [] { const char *v = std::getenv("DC_SKIP_MDT"); return v ? static_cast<uint32_t>(std::strtoul(v, nullptr, 16)) : 0u; }();
|
|
if ((s_skipMdt != 0u && mdt == s_skipMdt) || g_toggles.noModels)
|
|
{
|
|
g_objectState.valid = false;
|
|
return;
|
|
}
|
|
drawModel(rdram, model, load(rdram, localToWorld), renderInfo, !shadow && !screenSpace);
|
|
if (shadow)
|
|
noteShadow(rdram, model, load(rdram, localToWorld), renderInfo, false); // a model drawn in the shadow pass
|
|
g_objectState.valid = false;
|
|
}
|
|
|
|
// CCloth::DrawVu1 (0x13C470), taken over: no VU data, packet or VU1 program; the cloth drawn from its own
|
|
// simulation grid (rows at + 0x2C, columns at + 0x30; vertex (r, c) at + r * 0x100 + c * 0x10 from + 0x1110 for
|
|
// its position, + 0x5110 its normal, + 0x6110 its texture coordinates), one strip per pair of rows as
|
|
// CreateVUData (0x13C5F0) lays them out (the two rows swapped when the row's flag at + 0x7110 is set), with its
|
|
// material at + 0x60 (texture name at + 0x94). It draws with RenderInfo's lights, as its DrawVu1 call asks.
|
|
constexpr uint32_t kClothDrawVu1 = 0x0013C470u;
|
|
uint32_t textureRecord(const uint8_t *rdram, uint32_t name);
|
|
void clothCreateHook(uint8_t *ram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
const uint32_t cloth = getRegU32(ctx, 4);
|
|
const int32_t rows = static_cast<int32_t>(guest.read32(cloth + 0x2cu));
|
|
const int32_t columns = static_cast<int32_t>(guest.read32(cloth + 0x30u));
|
|
if (rows < 0 || rows > 16 || columns < 0 || columns > 16)
|
|
throw std::runtime_error("native cloth: grid outside simulation storage");
|
|
// One qword, as for models: CCloth::Initialize reserves it for buffer 0 and takes buffer 1 with Alloc64, so the
|
|
// two stay distinct; its per-frame DrawVu1 (native) never uses the size, and the native draw reads the
|
|
// simulation grid, not either buffer.
|
|
const uint32_t qwords = kNativeModelQwords;
|
|
++g_nativeClothBuilds;
|
|
g_retiredModelBytes += qwords * 16ull;
|
|
setReturnS32(ctx, static_cast<int32_t>(qwords));
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
void clothDrawHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
const uint32_t cloth = getRegU32(ctx, 4), localToWorld = getRegU32(ctx, 6), renderInfo = getRegU32(ctx, 7);
|
|
const ObjectMaterial state = g_objectState;
|
|
g_objectState.valid = false;
|
|
setReturnS32(ctx, 0); // nothing added to the game's packet
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const int32_t rows = static_cast<int32_t>(rd32(rdram, cloth + 0x2Cu));
|
|
const int32_t columns = static_cast<int32_t>(rd32(rdram, cloth + 0x30u));
|
|
if (rows < 2 || columns < 1 || rows > 64 || columns > 16)
|
|
return;
|
|
++g_stats.cloths;
|
|
readLights(rdram, renderInfo);
|
|
DrawSetup setup = drawSetup(rdram, load(rdram, localToWorld), renderInfo);
|
|
const uint32_t mat = cloth + 0x60u;
|
|
for (int c = 0; c < 4; ++c)
|
|
setup.lighting.material[c] = rdf(rdram, mat + static_cast<uint32_t>(c) * 4u);
|
|
const uint32_t record = materialRecord(rdram, mat);
|
|
auto texture = record != 0u ? recordTexture(rdram, record) : nullptr;
|
|
bozo::render::Material material;
|
|
material.depthTest = true;
|
|
material.tex0 = record != 0u ? rd64(rdram, record + 0x28u) : 0u;
|
|
applyObjectState(state, material);
|
|
auto vertex = [&](int32_t r, int32_t c) {
|
|
const uint32_t at = cloth + static_cast<uint32_t>(r) * 0x100u + static_cast<uint32_t>(c) * 0x10u;
|
|
bozo::render::Vertex v;
|
|
v.x = rdf(rdram, at + 0x1110u);
|
|
v.y = rdf(rdram, at + 0x1114u);
|
|
v.z = rdf(rdram, at + 0x1118u);
|
|
v.u = rdf(rdram, at + 0x6110u) * setup.uvScale;
|
|
v.v = rdf(rdram, at + 0x6114u) * setup.uvScale;
|
|
v.rgba = shade(setup.lighting, rdf(rdram, at + 0x5110u), rdf(rdram, at + 0x5114u), rdf(rdram, at + 0x5118u));
|
|
return v;
|
|
};
|
|
std::vector<bozo::render::Vertex> strip, vertices;
|
|
for (int32_t r = 0; r + 1 < rows; ++r)
|
|
{
|
|
const bool swapped = rd32(rdram, cloth + 0x7110u + static_cast<uint32_t>(r) * 4u) != 0u;
|
|
strip.clear();
|
|
for (int32_t c = 0; c < columns; ++c)
|
|
{
|
|
strip.push_back(vertex(swapped ? r + 1 : r, c));
|
|
strip.push_back(vertex(swapped ? r : r + 1, c));
|
|
}
|
|
for (size_t i = 2; i < strip.size(); ++i)
|
|
{
|
|
bozo::render::Vertex a = strip[i - 2], b = strip[i - 1];
|
|
if (i & 1u)
|
|
std::swap(a, b);
|
|
vertices.push_back(a);
|
|
vertices.push_back(b);
|
|
vertices.push_back(strip[i]);
|
|
}
|
|
}
|
|
std::snprintf(g_drawWhat, sizeof(g_drawWhat), "cloth %08x %dx%d flags %x", cloth, rows, columns, rd32(rdram, renderInfo + 0x310u));
|
|
// DC_PROBE_CLOTH=1 (diagnosis): a cloth's grid every 300 calls: its size, where its vertices lie, how many
|
|
// are far off (|x| > 1e6 or not finite), the guard's drops before and after it.
|
|
static const bool s_probe = std::getenv("DC_PROBE_CLOTH") != nullptr;
|
|
static uint32_t s_calls = 0;
|
|
const uint64_t guardedBefore = g_stats.guarded;
|
|
const bool report = s_probe && (s_calls++ % 300u) < 3u;
|
|
if (report)
|
|
{
|
|
float lo[3] = {1e30f, 1e30f, 1e30f}, hi[3] = {-1e30f, -1e30f, -1e30f};
|
|
int far = 0;
|
|
for (int32_t r = 0; r < rows; ++r)
|
|
for (int32_t c = 0; c < columns; ++c)
|
|
{
|
|
const uint32_t at = cloth + static_cast<uint32_t>(r) * 0x100u + static_cast<uint32_t>(c) * 0x10u + 0x1110u;
|
|
for (int k = 0; k < 3; ++k)
|
|
{
|
|
const float v = rdf(rdram, at + static_cast<uint32_t>(k) * 4u);
|
|
if (!std::isfinite(v) || std::fabs(v) > 1e6f)
|
|
{
|
|
++far;
|
|
continue;
|
|
}
|
|
lo[k] = std::min(lo[k], v);
|
|
hi[k] = std::max(hi[k], v);
|
|
}
|
|
}
|
|
std::fprintf(stderr, "[dc:cloth] %08x %dx%d tex %s far %d x %.1f..%.1f y %.1f..%.1f z %.1f..%.1f l2w t (%.1f %.1f %.1f) tris %zu\n",
|
|
cloth, rows, columns, texture ? "yes" : "no", far, lo[0], hi[0], lo[1], hi[1], lo[2], hi[2],
|
|
rdf(rdram, localToWorld + 0x30u), rdf(rdram, localToWorld + 0x34u), rdf(rdram, localToWorld + 0x38u), vertices.size() / 3u);
|
|
}
|
|
submit(setup, material, texture, vertices);
|
|
if (report)
|
|
std::fprintf(stderr, "[dc:cloth] guarded %llu\n", static_cast<unsigned long long>(g_stats.guarded - guardedBefore));
|
|
}
|
|
|
|
// CVisualShadow::DrawVu1 (0x136290), taken over: no VU data, packet or VU1 program. The shadow (the model's
|
|
// MDT positions through RenderInfo's shadow matrix at + 0x2D0, drawn with the shadow program's colour) is not
|
|
// drawn yet.
|
|
constexpr uint32_t kShadowDrawVu1 = 0x00136290u;
|
|
|
|
// Shadows. DC draws them in a pass: MGBeginDrawShadow (0x1308A0) points the GS at a work texture cleared to
|
|
// black; every draw with RenderInfo + 0x320 set projects its geometry through RenderInfo's shadow matrix
|
|
// (+ 0x2D0: clip = RenderInfo 0x230 x 0x10 x 0x2D0 x the local-to-world matrix) and marks the work texture with
|
|
// the shadow program's constant colour (images 69a6 / a750 at 0x1AF8: FTOI0 of 1.0, RGBA 1, 1, 1, 1), no depth
|
|
// test; MGEndDrawShadow (0x130B30, its argument the strength) draws the work texture over the frame read as CT24
|
|
// with TEXA's AEM (black: alpha 0, marked: alpha = the strength) and ALPHA 0x46, Cd x (1 - As). Here each
|
|
// shadow draw's triangles are kept, and the pass's end draws them black with alpha = the strength and an alpha
|
|
// blend (the same Cd x (1 - As)), no depth test. Unlike the work texture, triangles that overlap darken twice.
|
|
// Neither routine's GS side runs: begin's clear covers 432 x 432 of the work texture (fbp 210, the "work" picture
|
|
// Norune's water also copies the frame into), and with no program marking it, end laid the stale rest of it
|
|
// over the frame (Norune in black, with page-sized pieces left: GS pages the backend reloaded).
|
|
struct ShadowDraw
|
|
{
|
|
Matrix toScreen;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
};
|
|
std::vector<ShadowDraw> g_shadowDraws;
|
|
|
|
// A shadow-mode draw: the MDT's triangles (CreateVUdataShadow's reading: each primitive's index tuples taken
|
|
// three by three as triangles; a strip's when the primitive is one), positions only.
|
|
void noteShadow(const uint8_t *rdram, const Model &m, const Matrix &localToWorld, uint32_t renderInfo, bool listsOnly)
|
|
{
|
|
const uint32_t mdt = m.mdt;
|
|
ShadowDraw draw;
|
|
// DrawVu1's own projection for every shadow draw (its SetShadowData): clip x view x RenderInfo + 0x2D0 x the
|
|
// object. + 0x2D0 is the scene light's shadow matrix (EdSetLightParam in the towns): shadows are cast along the
|
|
// light, turning with the time of day. Its plane lies 12.8 below the shadow model's origin (its translation
|
|
// column, (-12.8 kx, -12.8, -12.8 kz)), and the characters' shadows landed a body's height below their feet, off
|
|
// the screen; PCSX2 shows them at the feet (short at noon, long and to one side at dusk). For MGDrawShadowFast /
|
|
// MGDrawShadow (+ 0x320 = 1 / 2) the plane is put through the model's origin, the feet. (Matched against PCSX2;
|
|
// the microprogram's own handling of the 12.8 is not traced. DrawVu1 copies + 0x2B0 / + 0x2C0, the point
|
|
// 12.8 lower and the normal DrawShadow gives, and does not use them.) MGDrawShade (+ 0x320 = 8, the buildings'
|
|
// shades: CMapObject::DrawShade) draws a flat mesh laid on the ground under the building through the same
|
|
// matrix, whatever the last shadow left there: through the plane 12.8 below, it was pushed along the light
|
|
// (a dark rectangle in front of the stairs) and under the ground (hidden by the ground's depth). Its plane is
|
|
// put through its origin too: the mesh stays where it lies.
|
|
Matrix shadowMatrix = load(rdram, renderInfo + 0x2D0u);
|
|
if (const uint32_t mode = rd32(rdram, renderInfo + 0x320u); mode == 1u || mode == 2u || mode == 8u)
|
|
{
|
|
shadowMatrix.m[12] = 0.0f;
|
|
shadowMatrix.m[13] = 0.0f;
|
|
shadowMatrix.m[14] = 0.0f;
|
|
}
|
|
static int s_logged = 0;
|
|
if (std::getenv("DC_PROBE_SHADOW") && s_logged++ < 6)
|
|
std::fprintf(stderr, "[dc:shadow] mode %u point (%g %g %g) normal (%g %g %g) local t (%g %g %g) 0x2D0 columns (%g %g %g %g | %g %g %g %g | %g %g %g %g | %g %g %g %g)\n",
|
|
rd32(rdram, renderInfo + 0x320u), rdf(rdram, renderInfo + 0x2B0u), rdf(rdram, renderInfo + 0x2B4u), rdf(rdram, renderInfo + 0x2B8u),
|
|
rdf(rdram, renderInfo + 0x2C0u), rdf(rdram, renderInfo + 0x2C4u), rdf(rdram, renderInfo + 0x2C8u), localToWorld.m[12], localToWorld.m[13],
|
|
localToWorld.m[14], rdf(rdram, renderInfo + 0x2D0u), rdf(rdram, renderInfo + 0x2D4u), rdf(rdram, renderInfo + 0x2D8u),
|
|
rdf(rdram, renderInfo + 0x2DCu), rdf(rdram, renderInfo + 0x2E0u), rdf(rdram, renderInfo + 0x2E4u), rdf(rdram, renderInfo + 0x2E8u),
|
|
rdf(rdram, renderInfo + 0x2ECu), rdf(rdram, renderInfo + 0x2F0u), rdf(rdram, renderInfo + 0x2F4u), rdf(rdram, renderInfo + 0x2F8u),
|
|
rdf(rdram, renderInfo + 0x2FCu), rdf(rdram, renderInfo + 0x300u), rdf(rdram, renderInfo + 0x304u), rdf(rdram, renderInfo + 0x308u),
|
|
rdf(rdram, renderInfo + 0x30Cu));
|
|
const Matrix clip = mul(mul(mul(load(rdram, renderInfo + 0x230u), load(rdram, renderInfo + 0x10u)), shadowMatrix), localToWorld);
|
|
draw.toScreen = mul(load(rdram, renderInfo + 0x270u), clip);
|
|
// The marks are depth-tested against the scene (endShadowHook); lying on the ground, they are pulled 0.05 %
|
|
// nearer (GS Z, larger nearer) so the ground's own depth does not hide them where the two are equal.
|
|
for (int c = 0; c < 4; ++c)
|
|
draw.toScreen.m[c * 4 + 2] *= 1.0005f;
|
|
const uint32_t positions = mdt + m.u32(mdt + 0x10u);
|
|
const uint32_t stride = static_cast<int32_t>(m.u32(mdt + 0x20u)) > 0 ? 4u : 3u;
|
|
const uint32_t list = mdt + m.u32(mdt + 0x28u);
|
|
const uint32_t primitives = m.u32(list + 8u);
|
|
auto vertex = [&](uint32_t indices, uint32_t i) {
|
|
const uint32_t pi = m.u32(indices + i * stride * 4u);
|
|
bozo::render::Vertex v;
|
|
v.x = m.f(positions + pi * 16u);
|
|
v.y = m.f(positions + pi * 16u + 4u);
|
|
v.z = m.f(positions + pi * 16u + 8u);
|
|
return v;
|
|
};
|
|
uint32_t at = list + 0x10u;
|
|
for (uint32_t p = 0; p < primitives && p < 4096u; ++p)
|
|
{
|
|
const uint32_t type = m.u32(at), count = m.u32(at + 4u);
|
|
const uint32_t indices = at + 12u;
|
|
at = indices + count * stride * 4u;
|
|
if (count > 65536u)
|
|
break;
|
|
if (type == 4u && !listsOnly)
|
|
for (uint32_t i = 2; i < count; ++i)
|
|
{
|
|
bozo::render::Vertex a = vertex(indices, i - 2), b = vertex(indices, i - 1);
|
|
if (i & 1u)
|
|
std::swap(a, b);
|
|
draw.vertices.push_back(a);
|
|
draw.vertices.push_back(b);
|
|
draw.vertices.push_back(vertex(indices, i));
|
|
}
|
|
else
|
|
for (uint32_t i = 0; i + 2 < count; i += 3)
|
|
for (uint32_t k = 0; k < 3; ++k)
|
|
draw.vertices.push_back(vertex(indices, i + k));
|
|
}
|
|
clipDepth(clip, draw.vertices);
|
|
static int s_screenLogged = 0;
|
|
if (std::getenv("DC_PROBE_SHADOW") && !draw.vertices.empty() && (s_screenLogged++ % 2700) < 3)
|
|
{
|
|
const bozo::render::Vertex &v = draw.vertices[0];
|
|
const float *t = draw.toScreen.m;
|
|
const float x = t[0] * v.x + t[4] * v.y + t[8] * v.z + t[12], y = t[1] * v.x + t[5] * v.y + t[9] * v.z + t[13];
|
|
const float w = t[3] * v.x + t[7] * v.y + t[11] * v.z + t[15];
|
|
std::fprintf(stderr, "[dc:shadow] mode %u vertex (%g %g %g) -> screen (%g %g) w %g, %zu vertices\n", rd32(rdram, renderInfo + 0x320u), v.x, v.y,
|
|
v.z, w != 0.0f ? x / w : 0.0f, w != 0.0f ? y / w : 0.0f, w, draw.vertices.size());
|
|
}
|
|
if (!draw.vertices.empty())
|
|
{
|
|
seq('D');
|
|
g_shadowDraws.push_back(std::move(draw));
|
|
}
|
|
}
|
|
|
|
// CVisualShadow::DrawVu1, taken over: no VU data, packet or VU1 program; its shadow model (the MDT at + 0x20)
|
|
// noted for the pass.
|
|
void shadowDrawHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
const uint32_t visual = getRegU32(ctx, 4), localToWorld = getRegU32(ctx, 6), renderInfo = getRegU32(ctx, 7);
|
|
g_objectState.valid = false;
|
|
++g_stats.shadows;
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
Model shadowModel;
|
|
shadowModel.rdram = rdram;
|
|
shadowModel.mdt = rd32(rdram, visual + 0x20u);
|
|
if (shadowModel.mdt != 0u && rd32(rdram, shadowModel.mdt) == kMdtMagic)
|
|
noteShadow(rdram, shadowModel, load(rdram, localToWorld), renderInfo, true);
|
|
}
|
|
|
|
void seq(char c);
|
|
void beginShadowHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
seq('B');
|
|
g_shadowDraws.clear();
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
|
|
// As the game does: the shadow triangles mark a work target cleared to black (alpha 0), and the pass's end lays
|
|
// the target over the frame once, Cd x (1 - As) with As = the strength where marked. Overlapping triangles
|
|
// (an arm over the body) darken once, as on the PS2: drawn straight over the frame, each overlap darkened again
|
|
// and the shadow showed the model's insides.
|
|
uint8_t targetFor(uint32_t base);
|
|
extern std::unordered_map<uint32_t, uint8_t> g_targetOfBase;
|
|
constexpr uint32_t kShadowWork = 0x80000210u; // the work texture (fbp 0x210), apart from the game's TEX0 bases
|
|
// A shadow pass ended: its marks and darkening wait for the end of the frame's 3D (layShadows from flushShadows,
|
|
// before the first 2D draw or at the frame's end). The game calls MGEndDrawShadow between its model draws (Norune:
|
|
// 11 models, the pass, 14 more, the ground among them), and laid there the shadow was drawn over by the ground;
|
|
// on the PS2 those models reach the GS before it. Depth-tested against the finished scene, the marks still leave
|
|
// out a character standing in front.
|
|
struct PendingShadows
|
|
{
|
|
uint32_t strength;
|
|
std::vector<ShadowDraw> draws;
|
|
};
|
|
std::vector<PendingShadows> g_pendingShadows;
|
|
void endShadowHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
const uint32_t strength = getRegU32(ctx, 4) & 0xFFu;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
seq('E');
|
|
if (g_dump2D)
|
|
std::fprintf(stderr, "[dc:dump] shadow pass end, %zu shadow draws\n", g_shadowDraws.size());
|
|
if (g_dump2D)
|
|
for (const ShadowDraw &draw : g_shadowDraws)
|
|
{
|
|
float sxLo = 1e30f, syLo = 1e30f, sxHi = -1e30f, syHi = -1e30f;
|
|
const float *t = draw.toScreen.m;
|
|
for (const bozo::render::Vertex &v : draw.vertices)
|
|
{
|
|
const float w = t[3] * v.x + t[7] * v.y + t[11] * v.z + t[15];
|
|
const float x = (t[0] * v.x + t[4] * v.y + t[8] * v.z + t[12]) / w, y = (t[1] * v.x + t[5] * v.y + t[9] * v.z + t[13]) / w;
|
|
sxLo = std::min(sxLo, x), sxHi = std::max(sxHi, x), syLo = std::min(syLo, y), syHi = std::max(syHi, y);
|
|
}
|
|
std::fprintf(stderr, "[dc:dump] shadow draw: %zu triangles, screen x %.0f..%.0f y %.0f..%.0f, strength %u\n",
|
|
draw.vertices.size() / 3u, sxLo, sxHi, syLo, syHi, strength);
|
|
}
|
|
if (g_shadowDraws.empty() || g_toggles.noShadow)
|
|
{
|
|
g_shadowDraws.clear();
|
|
return;
|
|
}
|
|
g_pendingShadows.push_back({strength, std::move(g_shadowDraws)});
|
|
g_shadowDraws.clear();
|
|
}
|
|
void layShadows(uint32_t strength, std::vector<ShadowDraw> &draws)
|
|
{
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
static const float kIdentity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
|
|
const uint8_t work = targetFor(kShadowWork);
|
|
renderer.setTargetSharesDepth(work, true); // the marks are depth-tested against the characters
|
|
static int s_passLogged = 0;
|
|
if (std::getenv("DC_PROBE_SHADOW") && (s_passLogged++ % 300) == 0)
|
|
{
|
|
std::fprintf(stderr, "[dc:shadow] pass end: strength %u, %zu draws, work target %u; places:", strength, draws.size(), work);
|
|
for (const auto &[base, slot] : g_targetOfBase)
|
|
std::fprintf(stderr, " %x->%u", base, slot);
|
|
std::fputc('\n', stderr);
|
|
}
|
|
auto screenQuad = [](uint32_t rgba) {
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
auto vertex = [&](float x, float y, float u, float v) {
|
|
bozo::render::Vertex out;
|
|
out.x = frameLeft() + x;
|
|
out.y = 1936.0f + y;
|
|
out.u = u;
|
|
out.v = v;
|
|
out.rgba = rgba;
|
|
return out;
|
|
};
|
|
const float w = frameW(); // the whole frame, widescreen or not
|
|
const bozo::render::Vertex a = vertex(0, 0, 0, 0), b = vertex(w, 0, 1, 0), c = vertex(0, 224, 0, 1), d = vertex(w, 224, 1, 1);
|
|
vertices.insert(vertices.end(), {a, b, c, b, d, c});
|
|
return vertices;
|
|
};
|
|
bozo::render::Material mark;
|
|
mark.textured = false;
|
|
mark.blend = bozo::render::Material::Blend::Opaque;
|
|
mark.depthTest = false;
|
|
mark.depthWrite = false;
|
|
mark.target = work;
|
|
const std::vector<bozo::render::Vertex> clear = screenQuad(0u);
|
|
renderer.draw(mark, kIdentity, clear.data(), static_cast<uint32_t>(clear.size()));
|
|
// Opaque draws clear RGB but publish alpha 1. Reset coverage too,
|
|
// otherwise sampling this mask darkens the entire scene, including
|
|
// characters and pixels outside every shadow. Repeat for each pass
|
|
// so reusing the target cannot carry earlier marks into a later one.
|
|
auto clearCoverage = mark;
|
|
clearCoverage.blend = bozo::render::Material::Blend::AlphaOnly;
|
|
renderer.draw(clearCoverage, kIdentity, clear.data(), static_cast<uint32_t>(clear.size()));
|
|
// The marks are depth-tested against the scene (the work target shares the frame's depth, as the GS's work
|
|
// texture shares its Z buffer): where a character stands in front of the ground, its depth hides the flattened
|
|
// shadow, the work texture stays unmarked and the character is not darkened.
|
|
mark.depthTest = true;
|
|
// With anti-aliasing the shared depth is resolved from one sample point off each pixel's centre: on sloping
|
|
// ground it can lie nearer than the mark's centre depth, and every mark failed (the shadows vanished). The
|
|
// marks are moved toward the camera by up to a pixel's depth slope then; without anti-aliasing they stay at
|
|
// the ground's own depth, as on the GS.
|
|
if (renderer.antiAliasing() >= 2)
|
|
mark.depthOffsetSlope = mark.depthOffsetUnits = 1.0f;
|
|
for (ShadowDraw &draw : draws)
|
|
{
|
|
for (bozo::render::Vertex &v : draw.vertices)
|
|
v.rgba = 0x80808080u; // marked: white, alpha 1
|
|
g_stats.shadowTriangles += draw.vertices.size() / 3u;
|
|
renderer.draw(mark, draw.toScreen.m, draw.vertices.data(), static_cast<uint32_t>(draw.vertices.size()));
|
|
}
|
|
bozo::render::Material lay;
|
|
lay.textured = true;
|
|
lay.fromFrame = 1;
|
|
lay.source = work;
|
|
lay.frameWidth = 640;
|
|
lay.frameHeight = 224;
|
|
lay.blend = bozo::render::Material::Blend::Alpha;
|
|
lay.depthTest = false;
|
|
lay.depthWrite = false;
|
|
const std::vector<bozo::render::Vertex> over = screenQuad(strength << 24); // black, alpha = the strength
|
|
renderer.draw(lay, kIdentity, over.data(), static_cast<uint32_t>(over.size()));
|
|
}
|
|
void flushShadows()
|
|
{
|
|
if (g_pendingShadows.empty())
|
|
return;
|
|
std::vector<PendingShadows> pending;
|
|
pending.swap(g_pendingShadows);
|
|
for (PendingShadows &pass : pending)
|
|
layShadows(pass.strength, pass.draws);
|
|
}
|
|
|
|
// DepthOfField (0x1652C0: a0 the focus, two depths; a1 its passes; a2 the blur's alpha; a3 a haze's strength),
|
|
// taken over. The game stretches its 640 x 224 frame to half its width in a work texture, and that to half
|
|
// again, then draws them back in strips over what lies behind the focus: Z test GEQUAL, no Z write, at the
|
|
// depths of four points of its table (0x266930) moved to the focus (z, z + 30 for the first pass, alternating
|
|
// column by column; z', z' + 20 for the second) through the world-to-screen matrix (0x1C75570). The GS's copy
|
|
// has none of the native draws: drawn the same way here from the native frame (Material::fromFrame).
|
|
uint64_t g_hazeSeed = 0x2545F4914F6CDD1Dull;
|
|
void depthOfFieldHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t focus = getRegU32(ctx, 4);
|
|
const int32_t passes = static_cast<int32_t>(getRegU32(ctx, 5)), alpha = static_cast<int32_t>(getRegU32(ctx, 6));
|
|
const int32_t haze = static_cast<int32_t>(getRegU32(ctx, 7));
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
const float zScale = renderer.gsZScale();
|
|
if (g_group == 0u || !(zScale > 0.0f) || g_toggles.noDof)
|
|
return;
|
|
++g_stats.depthOfFields;
|
|
const Matrix toScreen = load(rdram, 0x01C75570u);
|
|
int32_t depth[4];
|
|
for (uint32_t i = 0; i < 4u; ++i)
|
|
{
|
|
float p[4];
|
|
for (uint32_t k = 0; k < 4u; ++k)
|
|
p[k] = rdf(rdram, 0x00266930u + i * 16u + k * 4u);
|
|
p[2] = i == 0u ? rdf(rdram, focus) : i == 1u ? rdf(rdram, focus) + 30.0f
|
|
: i == 2u ? rdf(rdram, focus + 4u) : rdf(rdram, focus + 4u) + 20.0f;
|
|
float out[4];
|
|
for (int r = 0; r < 4; ++r)
|
|
out[r] = toScreen.m[r] * p[0] + toScreen.m[4 + r] * p[1] + toScreen.m[8 + r] * p[2] + toScreen.m[12 + r] * p[3];
|
|
const float z = out[2] / out[3];
|
|
depth[i] = std::isfinite(z) && std::fabs(z) < 2.1e9f ? static_cast<int32_t>(z) : 0;
|
|
}
|
|
bozo::render::Material material;
|
|
material.textured = true;
|
|
material.tex0 = 0; // TFX MODULATE, TCC 0: the strips' alpha
|
|
material.frameWidth = 640;
|
|
material.frameHeight = 224;
|
|
material.blend = bozo::render::Material::Blend::Alpha;
|
|
material.depthTest = true;
|
|
material.depthWrite = false;
|
|
material.clampU = material.clampV = true;
|
|
static const float kIdentity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
|
|
std::vector<bozo::render::Vertex> strip, triangles;
|
|
// The strips cover the whole frame (u 0..1): widescreen stretches them over its width.
|
|
const float xScale = frameW() / 640.0f;
|
|
auto vertex = [&](float x, float y, int32_t z, float u, float v, uint32_t a) {
|
|
bozo::render::Vertex out;
|
|
out.x = frameLeft() + x * xScale;
|
|
out.y = 1936.0f + y;
|
|
out.z = static_cast<float>(static_cast<uint32_t>(z)) / zScale; // XYZ2's Z, unsigned
|
|
out.u = u;
|
|
out.v = v;
|
|
out.rgba = 0x808080u | (a & 0xFFu) << 24;
|
|
strip.push_back(out);
|
|
};
|
|
auto flush = [&]() {
|
|
for (size_t k = 0; k + 2u < strip.size(); ++k)
|
|
triangles.insert(triangles.end(), {strip[k], strip[k + 1u], strip[k + 2u]});
|
|
strip.clear();
|
|
};
|
|
// First pass: the half-width copy, 8 rows of 32 lines, 41 columns 16 pixels apart.
|
|
for (int32_t row = 0; row < 8; ++row)
|
|
{
|
|
for (int32_t column = 0; column < 41; ++column)
|
|
{
|
|
const int32_t z = depth[(column & 1) != 0 ? 1 : 0];
|
|
vertex(column * 16.0f, row * 32.0f, z, column / 40.0f, row * 32.0f / 224.0f, static_cast<uint32_t>(alpha));
|
|
vertex(column * 16.0f, row * 32.0f + 32.0f, z, column / 40.0f, (row * 32.0f + 32.0f) / 224.0f, static_cast<uint32_t>(alpha));
|
|
}
|
|
flush();
|
|
}
|
|
material.fromFrame = 1;
|
|
renderer.draw(material, kIdentity, triangles.data(), static_cast<uint32_t>(triangles.size()));
|
|
triangles.clear();
|
|
if (passes <= 1)
|
|
return;
|
|
// Second pass: the quarter-width copy, 14 rows of 16 lines, 21 columns 32 pixels apart; with a haze, each
|
|
// strip's points move sideways by a random walk the game keeps at 0x1D18A00 (21 columns of 15 floats).
|
|
const uint32_t walk = 0x01D18A00u;
|
|
if (haze > 0)
|
|
{
|
|
const float step = rdf(rdram, 0x002A188Cu);
|
|
for (uint32_t column = 0; column < 21u; ++column)
|
|
for (uint32_t row = 0; row < 15u; ++row)
|
|
{
|
|
g_hazeSeed = g_hazeSeed * 6364136223846793005ull + 1442695040888963407ull;
|
|
const float random = static_cast<float>(g_hazeSeed >> 33) / 2147483648.0f; // 0..1, as rand() / 2^31
|
|
float value = rdf(rdram, walk + row * 4u + column * 0x3Cu) + step * static_cast<float>(haze) * (random - 0.5f);
|
|
value = std::min(std::max(value, 0.0f), static_cast<float>(haze));
|
|
uint32_t bits = 0;
|
|
std::memcpy(&bits, &value, 4);
|
|
std::memcpy(rdram + ((walk + row * 4u + column * 0x3Cu) & 0x1FFFFFFu), &bits, 4);
|
|
}
|
|
}
|
|
const uint32_t secondAlpha = haze > 0 ? 0x80u : static_cast<uint32_t>(alpha);
|
|
for (int32_t row = 0; row < 14; ++row)
|
|
{
|
|
for (uint32_t column = 0; column < 21u; ++column)
|
|
{
|
|
const int32_t z = depth[(column & 1u) != 0u ? 3 : 2];
|
|
float top = 0.0f, bottom = 0.0f; // the walk's offsets, in 1/16 pixels
|
|
if (haze > 0)
|
|
{
|
|
top = static_cast<float>(static_cast<int32_t>(rdf(rdram, walk + static_cast<uint32_t>(row) * 4u + column * 0x3Cu)));
|
|
bottom = static_cast<float>(static_cast<int32_t>(rdf(rdram, walk + static_cast<uint32_t>(row) * 4u + column * 0x3Cu + 4u)));
|
|
}
|
|
vertex(column * 32.0f - top / 16.0f, row * 16.0f, z, column / 20.0f, row * 16.0f / 224.0f, secondAlpha);
|
|
vertex(column * 32.0f - bottom / 16.0f, row * 16.0f + 16.0f, z, column / 20.0f, (row * 16.0f + 16.0f) / 224.0f, secondAlpha);
|
|
}
|
|
flush();
|
|
}
|
|
material.fromFrame = 2;
|
|
renderer.draw(material, kIdentity, triangles.data(), static_cast<uint32_t>(triangles.size()));
|
|
}
|
|
|
|
// DC_PROBE_TEX=1 (diagnosis): DC's 2D sprite functions (packet, CTexture *, const CRect &dst, ...): each
|
|
// (caller, texture) that covers most of the screen (dst at least 512 wide), once.
|
|
struct SpriteHook
|
|
{
|
|
uint32_t address;
|
|
RecompiledFunction original;
|
|
};
|
|
SpriteHook g_spriteHooks[] = {{0x0014C3C0u, nullptr}, {0x0014CD80u, nullptr}, {0x0015BD00u, nullptr},
|
|
{0x0015C000u, nullptr}, {0x0015C310u, nullptr}, {0x0015C630u, nullptr},
|
|
{0x0015C980u, nullptr}, {0x0015E540u, nullptr}, {0x0015EAD0u, nullptr}};
|
|
void spriteProbe(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint32_t pc = ctx->pc;
|
|
RecompiledFunction original = nullptr;
|
|
for (const SpriteHook &hook : g_spriteHooks)
|
|
if (hook.address == pc)
|
|
original = hook.original;
|
|
const uint32_t texture = getRegU32(ctx, 5), rect = getRegU32(ctx, 6);
|
|
const int32_t width = static_cast<int32_t>(rd32(rdram, rect + 8u));
|
|
if (texture != 0u && width >= 512)
|
|
{
|
|
static std::mutex s_mutex;
|
|
static std::vector<uint64_t> s_seen;
|
|
const uint64_t tex0 = rd64(rdram, texture + 0x28u);
|
|
const uint64_t key = static_cast<uint64_t>(getRegU32(ctx, 31)) << 32 ^ tex0;
|
|
std::lock_guard<std::mutex> lock(s_mutex);
|
|
if (std::find(s_seen.begin(), s_seen.end(), key) == s_seen.end() && s_seen.size() < 64u)
|
|
{
|
|
s_seen.push_back(key);
|
|
std::fprintf(stderr, "[dc:probe] sprite 0x%06x from ra 0x%08x: tbp %u tbw %u psm 0x%x cbp %u, dst %d,%d %dx%d\n",
|
|
pc, getRegU32(ctx, 31), static_cast<uint32_t>(tex0 & 0x3FFFu),
|
|
static_cast<uint32_t>(tex0 >> 14) & 0x3Fu, static_cast<uint32_t>(tex0 >> 20) & 0x3Fu,
|
|
static_cast<uint32_t>(tex0 >> 37) & 0x3FFFu, static_cast<int>(rd32(rdram, rect)),
|
|
static_cast<int>(rd32(rdram, rect + 4u)), width, static_cast<int>(rd32(rdram, rect + 12u)));
|
|
}
|
|
}
|
|
// DC_SKIP_TBP=<block>: sprites of that texture are not drawn (diagnosis).
|
|
static const uint32_t s_skip = [] { const char *v = std::getenv("DC_SKIP_TBP"); return v ? static_cast<uint32_t>(std::atoi(v)) : ~0u; }();
|
|
if (texture != 0u && (rd64(rdram, texture + 0x28u) & 0x3FFFu) == s_skip)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
return;
|
|
}
|
|
if (original)
|
|
original(rdram, ctx, runtime);
|
|
}
|
|
|
|
// DC_PROBE_VU1=1 (diagnosis): calls of the routines that may run VU1 programs other than the models'.
|
|
struct CountHook
|
|
{
|
|
uint32_t address;
|
|
const char *name;
|
|
RecompiledFunction original;
|
|
std::atomic<uint64_t> calls;
|
|
};
|
|
CountHook g_countHooks[] = {{0x0013C470u, "CCloth::DrawVu1", nullptr, {}},
|
|
{0x00160F20u, "CWater::DrawVu1", nullptr, {}},
|
|
{0x00164340u, "CEffect::Draw", nullptr, {}},
|
|
{0x00163480u, "CRunEffect::Draw", nullptr, {}},
|
|
{0x00163B20u, "CCandleEffect::Draw", nullptr, {}},
|
|
{0x0012BA20u, "CSpriteTable::DrawTable", nullptr, {}},
|
|
{0x00136290u, "CVisualShadow::DrawVu1", nullptr, {}},
|
|
{0x00129400u, "CFrameVu1::DrawVu1", nullptr, {}}};
|
|
void countHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
for (CountHook &hook : g_countHooks)
|
|
if (hook.address == ctx->pc)
|
|
{
|
|
hook.calls.fetch_add(1u, std::memory_order_relaxed);
|
|
hook.original(rdram, ctx, runtime);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// DC_PROBE_FEEDERS=1 (inventory): calls, per 300 frames, of every routine that builds GS packets or drives the GS
|
|
// library (their list: the routines whose recompiled code calls sceVif1Pk*, sceGif*, sceGs* or sceDma*).
|
|
struct FeederHook
|
|
{
|
|
uint32_t address;
|
|
const char *name;
|
|
RecompiledFunction original = nullptr;
|
|
std::atomic<uint64_t> calls{0};
|
|
};
|
|
FeederHook g_feeders[] = {
|
|
{0x0012A110u, "DrawVu1__9CFrameVu1FP13sceVif1PacketP10RenderInfo"},
|
|
{0x0012BA20u, "DrawTable__12CSpriteTableFv"},
|
|
{0x0012C800u, "StoreImage__Fv"},
|
|
{0x0012CD90u, "MGBeginFrame__Fv"},
|
|
{0x0012D100u, "MGEndFrame__Fv"},
|
|
{0x0012D9A0u, "MGSetWindowRect__Fv"},
|
|
{0x0012DAE0u, "MGSetWindowRect__F8CRect_i_"},
|
|
{0x0012ED80u, "MGDraw__FP6CFrame"},
|
|
{0x0012EDF0u, "MGSetGsTEST__FP9sceGsTest"},
|
|
{0x0012EEC0u, "MGSetGsZBUF__FP9sceGsZbuf"},
|
|
{0x0012EF90u, "MGSetGsALPHA__FP10sceGsAlpha"},
|
|
{0x0012F060u, "MGSetGsTEXA__FP9sceGsTexa"},
|
|
{0x0012F210u, "MGMoveImage__FP9sceGsTex0RC8CRect_i_P9sceGsTex0iii"},
|
|
{0x0012F430u, "MGStretchMoveImage__FP9sceGsTex0RC8CRect_i_P9sceGsTex0RC8CRect_i"},
|
|
{0x0012FA70u, "MGFillBox__FRC8CRect_i_UcUcUcUc"},
|
|
{0x0012FD30u, "MGClearZBuffer__Fi"},
|
|
{0x00130000u, "MGClearScreen__FUcUcUcUc"},
|
|
{0x001303B0u, "MGDrawShadowFast__FP6CFramePfPf"},
|
|
{0x001304D0u, "MGDrawShadowFast2__FP6CFramePfPf"},
|
|
{0x001305F0u, "MGDrawShadow__FP6CFramePfPf"},
|
|
{0x001308A0u, "MGBeginDrawShadow__F9sceGsTex0"},
|
|
{0x00130B30u, "MGEndDrawShadow__FUc"},
|
|
{0x001320E0u, "EnterFixTexture__15CTextureManagerFPcPUciiiPUciiPUcPUcPUcUli"},
|
|
{0x00132930u, "EnterFixTextureZ__15CTextureManagerFPUc"},
|
|
{0x00133070u, "ReloadTexture__15CTextureManagerFP13sceVif1Packeti"},
|
|
{0x00134BC0u, "DrawVu1__10CVisualVu1FP13sceVif1PacketPA4_fP10RenderInfo11VU1_PR"},
|
|
{0x0013DEA0u, "openGiftag__FP13sceVif1Packet"},
|
|
{0x0013DF00u, "closeGiftag__FP13sceVif1Packet"},
|
|
{0x0013DF40u, "Draw__10CDebugFontFv"},
|
|
{0x00140660u, "MoveImageTest__FP13sceVif1PacketiiiRC8CRect_i_iiiiii"},
|
|
{0x00140DA0u, "SetEnv__FP13sceVif1Packet"},
|
|
{0x0014C220u, "set2DSprite_Start__FP13sceVif1PacketP8CTexture"},
|
|
{0x0014C4F0u, "set2DSprite_End__FP13sceVif1PacketP8CTexture"},
|
|
{0x0014C5A0u, "SetClut__FP13sceVif1PacketP8CTextureP1"},
|
|
{0x0014CD80u, "Myset2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i_"},
|
|
{0x00150BB0u, "DrawMaru__FP13sceVif1Packetiiiiiiii"},
|
|
{0x00150F50u, "MakeFukidashi_sub__6ClsMesFP13sceVif1Packeti"},
|
|
{0x00151AD0u, "MakeFukidashi__6ClsMesFP13sceVif1Packet"},
|
|
{0x00153310u, "DrawMesWin__6ClsMesFv"},
|
|
{0x00154320u, "VSyncCallBack_Load__Fi"},
|
|
{0x00154770u, "LoadTexture__FPcPUcP8CTextureii"},
|
|
{0x00154950u, "LoadTexture__FP8TM2_headP8CTextureii"},
|
|
{0x0015BC20u, "setAlphaFlag__FP13sceVif1PacketP10sceGsAlpha"},
|
|
{0x0015BD00u, "set2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_ii"},
|
|
{0x0015C000u, "set2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i_"},
|
|
{0x0015C310u, "set2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i_Uc"},
|
|
{0x0015C630u, "set2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i_Uc"},
|
|
{0x0015C980u, "set2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i_P6"},
|
|
{0x0015D1B0u, "set3DColSprite__FP13sceVif1PacketPiPiPiPiP6spRGBAP6spRGBAP6spRGB"},
|
|
{0x0015D4B0u, "set3DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_PiPiPiPiP6spR"},
|
|
{0x0015D790u, "set3DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_PiPiP6spRGBA"},
|
|
{0x0015D9A0u, "set3DSpriteFog__FP13sceVif1PacketP8CTextureRC8CRect_i_PiPiPiPiUc"},
|
|
{0x0015DCA0u, "set3DSpriteFog__FP13sceVif1PacketP8CTextureRC8CRect_i_PiPiP6spRG"},
|
|
{0x0015DED0u, "setColSprite__FP13sceVif1PacketPiPiPiPiUcUcUcUc"},
|
|
{0x0015E120u, "set2DSpriteC4__FP13sceVif1PacketRC8CRect_i_P6spRGBAP6spRGBAP6spR"},
|
|
{0x0015E540u, "set2DSprite__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i_ii"},
|
|
{0x0015EAD0u, "set2DSpriteRot__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i"},
|
|
{0x00160F20u, "DrawVu1__6CWaterFP10RenderInfoP13sceVif1PacketP1"},
|
|
{0x00161AC0u, "DrawFire__9CFireOmniFiiP7CCameraPffif"},
|
|
{0x00162580u, "blendTextuer__FP13sceVif1PacketiiiP8CTextureRC8CRect_i_RC8CRect_"},
|
|
{0x00162D80u, "blendTextuerTest__FP13sceVif1PacketiiiRC8CRect_i_P8CTextureRC8CR"},
|
|
{0x00163480u, "Draw__10CRunEffectFv"},
|
|
{0x001652C0u, "DepthOfField__FPfiii"},
|
|
{0x00167170u, "TexAnime__13CTextureAnimeFi"},
|
|
{0x00171210u, "DrawLine__FPiPiUcUcUcUc"},
|
|
{0x001797E0u, "EditLoop__Fv"},
|
|
{0x001831D0u, "set2DSpriteRot__FP13sceVif1PacketP8CTextureRC8CRect_i_RC8CRect_i"},
|
|
{0x0019F9B0u, "setTexAnim__Fv"},
|
|
{0x001AB0F0u, "FishLineDraw__Fi"},
|
|
{0x001B1EF0u, "setItemToReserved__FPciiPcii"},
|
|
{0x001F61E0u, "BattleMenuDraw__Fv"},
|
|
{0x00244C70u, "LangsetLoop__Fv"},
|
|
};
|
|
void feederHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
for (FeederHook &hook : g_feeders)
|
|
if (hook.address == ctx->pc)
|
|
{
|
|
hook.calls.fetch_add(1u, std::memory_order_relaxed);
|
|
hook.original(rdram, ctx, runtime);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// DC without the GS (always; there is no GS path to compare with): the frame is the native renderer's alone, drawn by present() in
|
|
// the order the game calls its routines. Its 2D comes from those routines' own arguments: screen-space draws, x
|
|
// and y in GS primitive coordinates (pixels plus DC's XYOFFSET, 1728, 1936), z the GS Z they would write.
|
|
constexpr float kOriginX = 1728.0f, kOriginY = 1936.0f;
|
|
// present() takes a vertex colour as the GS's modulate does (0x80 = 1.0); an untextured GS primitive is its RGB
|
|
// as it is (0xFF = 1.0): flat colours are passed at half.
|
|
uint32_t flatColour(uint32_t r, uint32_t g, uint32_t b, uint32_t a)
|
|
{
|
|
auto half = [](uint32_t c) { return ((c & 0xFFu) * 128u + 127u) / 255u; };
|
|
return half(r) | half(g) << 8 | half(b) << 16 | (a & 0xFFu) << 24;
|
|
}
|
|
void quad(std::vector<bozo::render::Vertex> &out, float x0, float y0, float x1, float y1, float z, uint32_t rgba,
|
|
float u0 = 0.0f, float v0 = 0.0f, float u1 = 1.0f, float v1 = 1.0f)
|
|
{
|
|
auto vertex = [&](float x, float y, float u, float v) {
|
|
bozo::render::Vertex out;
|
|
out.x = x;
|
|
out.y = y;
|
|
out.z = z;
|
|
out.u = u;
|
|
out.v = v;
|
|
out.rgba = rgba;
|
|
return out;
|
|
};
|
|
const bozo::render::Vertex a = vertex(x0, y0, u0, v0), b = vertex(x1, y0, u1, v0), c = vertex(x0, y1, u0, v1),
|
|
d = vertex(x1, y1, u1, v1);
|
|
out.insert(out.end(), {a, b, c, b, d, c});
|
|
}
|
|
void drawScreen(const bozo::render::Material &material, const std::vector<bozo::render::Vertex> &vertices,
|
|
std::shared_ptr<const bozo::render::Texture> texture = nullptr)
|
|
{
|
|
static const float kIdentity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
|
|
flushShadows();
|
|
++g_frameWork.draws;
|
|
if (!vertices.empty())
|
|
bozo::render::Renderer::instance().draw(material, kIdentity, vertices.data(), static_cast<uint32_t>(vertices.size()),
|
|
std::move(texture));
|
|
g_2dCallerSeen = 0; // a caller counts for its own draw only
|
|
}
|
|
|
|
// MGClearScreen (0x130000, a0..a3 the colour): a sprite over the 640 x 224 frame in that colour, ALPHA 0x2A (Cs:
|
|
// opaque), Z test ALWAYS and Z written (0: the far end).
|
|
void clearScreenHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
bozo::render::Material material;
|
|
material.textured = false;
|
|
material.blend = bozo::render::Material::Blend::Opaque;
|
|
material.depthTest = false;
|
|
material.depthWrite = true;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f, 0.0f,
|
|
flatColour(getRegU32(ctx, 4), getRegU32(ctx, 5), getRegU32(ctx, 6), getRegU32(ctx, 7)));
|
|
++g_stats.clears;
|
|
seq('C');
|
|
g_stats.lastClear = (getRegU32(ctx, 4) & 0xFFu) << 16 | (getRegU32(ctx, 5) & 0xFFu) << 8 | (getRegU32(ctx, 6) & 0xFFu);
|
|
drawScreen(material, vertices);
|
|
}
|
|
// MGClearZBuffer (0x12FD30, a0 the Z): the same sprite with ALPHA 0x6A (Cd: the colour kept), Z written.
|
|
void clearZHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
seq('Z');
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
bozo::render::Material material;
|
|
material.textured = false;
|
|
material.blend = bozo::render::Material::Blend::Alpha; // As 0: the target's colour
|
|
material.depthTest = false;
|
|
material.depthWrite = true;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f,
|
|
static_cast<float>(getRegU32(ctx, 4)), 0u);
|
|
drawScreen(material, vertices);
|
|
}
|
|
// The field HUD's routines (widescreen moves their side pieces to the edges, see hudShift): each runs inside a
|
|
// HUD scope. EdDrawClock (0x17DB60) is the towns' day clock, top right.
|
|
struct HudHook
|
|
{
|
|
uint32_t address;
|
|
RecompiledFunction original;
|
|
};
|
|
// topStatusInfo (0x1B04F0) is the dungeon's: health and weapon (top left), the item slots (middle), the floor
|
|
// and keys (top right), the attack gauge (bottom left); its numbers come from ValuePrint inside it.
|
|
// CDungeonMap::DrawMiniMap (0x1C3180) is the minimap, moved as one piece (g_mapScope).
|
|
HudHook g_hudHooks[] = {{0x0017DB60u, nullptr}, {0x001B04F0u, nullptr}, {0x001C3180u, nullptr}};
|
|
void hudHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint32_t pc = ctx->pc;
|
|
for (const HudHook &hook : g_hudHooks)
|
|
if (hook.address == pc && hook.original)
|
|
{
|
|
int &scope = pc == 0x001C3180u ? g_mapScope : g_hudScope;
|
|
if (pc == 0x001C3180u)
|
|
g_mapDecided = false;
|
|
++scope;
|
|
hook.original(rdram, ctx, runtime);
|
|
--scope;
|
|
return;
|
|
}
|
|
}
|
|
// MGClipVertex (0x12EA40: a0 a point; MGClipBox and the models' culling call it): the point through the
|
|
// world-to-screen matrix (0x1C755F0), its clip flags: 0x20 nearer than the near plane (0x1C756E8), 0x10 past the
|
|
// far one (0x1C756F8), 8 / 4 above / below the frame (y within 112 of the centre 0x1C756D4), 2 / 1 left / right
|
|
// of it (x within 320 of the centre 0x1C756D0). Behind the camera (w <= 0) the tests reverse, as the game's do.
|
|
// Widescreen culls against the wider frame's half width instead, so what its sides show is drawn.
|
|
void clipVertexHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const Matrix m = load(rdram, 0x01C755F0u);
|
|
const uint32_t point = getRegU32(ctx, 4);
|
|
float in[4], out[4];
|
|
for (uint32_t k = 0; k < 4u; ++k)
|
|
in[k] = rdf(rdram, point + k * 4u);
|
|
for (int r = 0; r < 4; ++r)
|
|
out[r] = m.m[r] * in[0] + m.m[4 + r] * in[1] + m.m[8 + r] * in[2] + m.m[12 + r] * in[3];
|
|
float w = out[3];
|
|
if (w == 0.0f)
|
|
w = 1.0f;
|
|
const float x = out[0] * (1.0f / w) - rdf(rdram, 0x01C756D0u), y = out[1] * (1.0f / w) - rdf(rdram, 0x01C756D4u);
|
|
const float halfW = frameW() / 2.0f;
|
|
uint32_t flags = 0;
|
|
if (w < rdf(rdram, 0x01C756E8u))
|
|
flags = 0x20u;
|
|
if (rdf(rdram, 0x01C756F8u) < w)
|
|
flags |= 0x10u;
|
|
if (0.0f < w)
|
|
{
|
|
flags |= (y < -112.0f ? 8u : 0u) | (112.0f < y ? 4u : 0u) | (x < -halfW ? 2u : 0u) | (halfW < x ? 1u : 0u);
|
|
}
|
|
else
|
|
{
|
|
flags |= (-112.0f < y ? 8u : 0u) | (y < 112.0f ? 4u : 0u) | (-halfW < x ? 2u : 0u) | (x < halfW ? 1u : 0u);
|
|
}
|
|
setRegU64(ctx, 2, flags);
|
|
}
|
|
// MGFillBox (0x12FA70: a0 the rectangle, x, y, w, h in 1/16 pixels; a1..a4 the colour): an alpha-blended sprite
|
|
// (PRIM ABE with the game's ALPHA, (Cs - Cd) As + Cd), Z test ALWAYS, Z not written.
|
|
void fillBoxHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t rect = getRegU32(ctx, 4);
|
|
const float x = static_cast<float>(static_cast<int32_t>(rd32(rdram, rect))) / 16.0f;
|
|
const float y = static_cast<float>(static_cast<int32_t>(rd32(rdram, rect + 4u))) / 16.0f;
|
|
const float w = static_cast<float>(static_cast<int32_t>(rd32(rdram, rect + 8u))) / 16.0f;
|
|
const float h = static_cast<float>(static_cast<int32_t>(rd32(rdram, rect + 12u))) / 16.0f;
|
|
bozo::render::Material material;
|
|
material.textured = false;
|
|
material.blend = bozo::render::Material::Blend::Alpha;
|
|
material.depthTest = false;
|
|
material.depthWrite = false;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
const float shift = hudShift(x, x + w); // widescreen: a fill on the frame's edges reaches the wider frame's
|
|
if (g_dump2D)
|
|
std::fprintf(stderr, "[dc:dump] caller %08x fill (%.1f %.1f %.1fx%.1f) colour %u %u %u %u\n", g_2dCaller, x, y, w, h,
|
|
getRegU32(ctx, 5) & 0xFFu, getRegU32(ctx, 6) & 0xFFu, getRegU32(ctx, 7) & 0xFFu, getRegU32(ctx, 8) & 0xFFu);
|
|
quad(vertices, shift != 0.0f ? 1728.0f + x + shift : fillLeft(x), kOriginY + y,
|
|
shift != 0.0f ? 1728.0f + x + w + shift : fillRight(x + w), kOriginY + y + h, 0.0f,
|
|
flatColour(getRegU32(ctx, 5), getRegU32(ctx, 6), getRegU32(ctx, 7), getRegU32(ctx, 8)));
|
|
drawScreen(material, vertices);
|
|
}
|
|
|
|
// DC's 2D sprites (set2DSprite and its variants, 0x15BD00..), from their arguments: the CTexture (its record:
|
|
// TEX0 at + 0x28), the destination rectangle (x, y, w, h in DC's 640 x 448 view: GS x = 1728 + x, y = 1936 + y / 2),
|
|
// the source rectangle in texels, the colours. Each is a sprite or a 4-vertex strip with PRIM ABE (the ALPHA
|
|
// the game last set: setAlphaFlag / MGSetGsALPHA), Z test ALWAYS, no Z write. The CRect is (x, y, w, h).
|
|
uint64_t g_alpha2D = 0x44; // (Cs - Cd) As + Cd
|
|
uint64_t g_publishedFrames = 0; // frames published (publish)
|
|
// The game's gp (SetEnv's, each frame). The sprite routines write TEX1 = linear << 5 | 0x41: MMAG from the
|
|
// game's linear (gp - 0x7908), 0 nearest; MMIN 1 (linear, but the 2D is drawn 1:1).
|
|
uint32_t g_gp = 0;
|
|
bool spritesNearest(const uint8_t *rdram) { return g_gp != 0u && rd32(rdram, g_gp - 0x7908u) == 0u; }
|
|
struct Corner
|
|
{
|
|
float x, y; // GS pixels
|
|
float u, v; // texels
|
|
uint32_t rgba;
|
|
};
|
|
uint32_t stackArg(const uint8_t *rdram, R5900Context *ctx, uint32_t index) // the 9th argument on: the caller's stack
|
|
{
|
|
return rd32(rdram, getRegU32(ctx, 29) + index * 8u);
|
|
}
|
|
// Pictures the game makes itself instead of loading them, each kept by the renderer, keyed by the place the game
|
|
// gives them (TEX0's base): its frame and the frame before (MGGetFBuffTex / MGGetFBuffBackTex), and the work
|
|
// textures it draws into (the balloons' 0x299A78, the title's trail) as offscreen targets. A sprite whose
|
|
// texture is one of them samples it.
|
|
uint32_t g_frameBase = ~0u, g_backBase = ~0u;
|
|
bool g_backAsked = false; // the getter the game called last (DC reports one base for both: the last one decides)
|
|
std::unordered_map<uint32_t, uint8_t> g_targetOfBase;
|
|
// The rows a target's picture spans (its texels' v): the frame's 224, or 448 for a picture made from both fields
|
|
// (MGMoveFrameBuffImage).
|
|
float g_targetRows[8] = {224.0f, 224.0f, 224.0f, 224.0f, 224.0f, 224.0f, 224.0f, 224.0f};
|
|
uint8_t targetFor(uint32_t base)
|
|
{
|
|
auto found = g_targetOfBase.find(base);
|
|
if (found != g_targetOfBase.end())
|
|
return found->second;
|
|
const uint8_t n = static_cast<uint8_t>(1u + g_targetOfBase.size() % 7u); // 1..7
|
|
for (auto it = g_targetOfBase.begin(); it != g_targetOfBase.end();)
|
|
it = it->second == n ? g_targetOfBase.erase(it) : std::next(it);
|
|
bozo::render::Renderer::instance().setTargetSize(n, 0, 0); // a new place: the window's size until told otherwise
|
|
bozo::render::Renderer::instance().setTargetSharesDepth(n, false); // and a depth of its own
|
|
g_targetRows[n] = 224.0f;
|
|
return g_targetOfBase[base] = n;
|
|
}
|
|
constexpr uint32_t kBlendedPlace = 0x40000000u; // blendTextuer's picture of a place: its own target
|
|
std::unordered_map<uint32_t, bool> g_blendedLast; // place -> blendTextuer wrote it last (not blendTextuerTest)
|
|
constexpr uint32_t kHazePlace = 0x20000000u; // blendTextuerTest's patch of a place: its own target, at
|
|
// the window's resolution (the place's may be 640 x 224)
|
|
std::unordered_map<uint32_t, bool> g_hazeLast; // place -> blendTextuerTest wrote it last
|
|
std::unordered_map<uint32_t, std::pair<int32_t, int32_t>> g_blendedExtent; // place -> the corner it blends
|
|
// The renderer source for a place (0: not one of the game's own pictures); sets the material to sample it.
|
|
bool sampleMade(uint32_t base, bozo::render::Material &material)
|
|
{
|
|
if (base == g_frameBase && (base != g_backBase || !g_backAsked))
|
|
material.source = 0;
|
|
else if (base == g_backBase)
|
|
material.source = bozo::render::Material::kPreviousFrame;
|
|
else if (const auto found = g_targetOfBase.find(base); found != g_targetOfBase.end())
|
|
material.source = found->second;
|
|
else
|
|
return false;
|
|
material.textured = true;
|
|
material.fromFrame = 1;
|
|
material.frameWidth = 640;
|
|
material.frameHeight = static_cast<uint16_t>(material.source != 0u && material.source < 8u ? g_targetRows[material.source] : 224.0f);
|
|
return true;
|
|
}
|
|
// A strip of four corners (v0 v1 v2, v1 v2 v3), textured with the record's texture when there is one.
|
|
// D:/DC_Recomp/build/dump2d.flag present (diagnosis, checked every 30 frames): the next frame's 2D draws logged one
|
|
// by one ([dc:dump]), then the flag removed.
|
|
void drawStrip(const uint8_t *rdram, uint32_t record, const Corner (&given)[4], bool flat = false)
|
|
{
|
|
if (g_toggles.no2D)
|
|
return;
|
|
// Widescreen: the strip placed in the wider frame. A strip over the whole 640-wide frame (a fade, a fill, a
|
|
// frame copy) spans the whole wide one: stretched here when flat, in the made-picture path below when it
|
|
// samples the frame; a picture of its own stays centred (pillarboxed). A HUD side piece moves out.
|
|
Corner c[4] = {given[0], given[1], given[2], given[3]};
|
|
const float gameLo = std::min({c[0].x, c[1].x, c[2].x, c[3].x}) - 1728.0f;
|
|
const float gameHi = std::max({c[0].x, c[1].x, c[2].x, c[3].x}) - 1728.0f;
|
|
const bool whole = g_wideFrame && wholeSpan(gameLo, gameHi);
|
|
auto stretch = [&]() {
|
|
for (Corner &k : c)
|
|
k.x = 2048.0f + (k.x - 2048.0f) * frameW() / 640.0f;
|
|
};
|
|
if (whole && (flat || record == 0u))
|
|
stretch();
|
|
else if (!whole)
|
|
{
|
|
const float shift = hudShift(gameLo, gameHi);
|
|
for (Corner &k : c)
|
|
{
|
|
k.x += shift;
|
|
if ((flat || record == 0u) && shift == 0.0f) // an untextured strip on an edge reaches the wider frame's
|
|
k.x = k.x <= 1728.5f ? fillLeft(k.x - 1728.0f) : k.x >= 2367.5f ? fillRight(k.x - 1728.0f) : k.x;
|
|
}
|
|
}
|
|
// DC_PROBE_COPIES=1 (diagnosis): the message windows' more-text triangle ("syst04"), each change of its
|
|
// corners, and its decoded texture once (build/syst04.pam).
|
|
static const bool s_probeTriangle = std::getenv("DC_PROBE_COPIES") != nullptr;
|
|
if (s_probeTriangle && record != 0u && std::strncmp(reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)), "syst04", 7) == 0)
|
|
{
|
|
static float s_last[4] = {};
|
|
if (s_last[0] != c[0].x || s_last[1] != c[0].y || s_last[2] != c[3].x || s_last[3] != c[3].y)
|
|
{
|
|
s_last[0] = c[0].x, s_last[1] = c[0].y, s_last[2] = c[3].x, s_last[3] = c[3].y;
|
|
std::fprintf(stderr, "[dc:triangle] frame %llu (%.1f %.1f)-(%.1f %.1f) uv (%.0f %.0f)-(%.0f %.0f) rgba %08x tex0 %016llx\n",
|
|
static_cast<unsigned long long>(g_publishedFrames), c[0].x, c[0].y, c[3].x, c[3].y, c[0].u, c[0].v, c[3].u, c[3].v,
|
|
c[0].rgba, static_cast<unsigned long long>(rd64(rdram, record + 0x28u)));
|
|
}
|
|
static bool s_written = false;
|
|
if (!s_written)
|
|
if (const auto texture = recordTexture(rdram, record))
|
|
if (FILE *out = std::fopen("D:/DC_Recomp/build/syst04.pam", "wb"))
|
|
{
|
|
s_written = true;
|
|
std::fprintf(out, "P7\nWIDTH %u\nHEIGHT %u\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", texture->width, texture->height);
|
|
std::fwrite(texture->rgba.data(), 4u, texture->rgba.size(), out);
|
|
std::fclose(out);
|
|
}
|
|
}
|
|
if (g_dump2D)
|
|
std::fprintf(stderr, "[dc:dump] caller %08x hud %d sprite %08x \"%.32s\" tex0 %016llx pixels %08x (%.1f %.1f)-(%.1f %.1f) uv (%.0f %.0f)-(%.0f %.0f) rgba %08x alpha %llx flat %d\n",
|
|
g_2dCaller, g_hudScope, record, record ? reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)) : "",
|
|
record ? static_cast<unsigned long long>(rd64(rdram, record + 0x28u)) : 0ull, record ? rd32(rdram, record + 0x38u) : 0u,
|
|
c[0].x, c[0].y, c[3].x, c[3].y, c[0].u, c[0].v, c[3].u, c[3].v, c[0].rgba, static_cast<unsigned long long>(g_alpha2D), flat ? 1 : 0);
|
|
bozo::render::Material made;
|
|
// A record with pixels of its own shows them, wherever the game sends them in GS memory: the attract demo's
|
|
// "start2" plate goes to the title's work place 0x1A40 and showed the stale work picture. A record with none
|
|
// ("frame_image") is a picture the game makes there; inside the corner blendTextuer blends ("blender"), the
|
|
// picture it made.
|
|
uint32_t madeBase = record != 0u ? static_cast<uint32_t>(rd64(rdram, record + 0x28u) & 0x3FFFu) : 0u;
|
|
if (g_hazeLast[madeBase] && g_targetOfBase.count(madeBase | kHazePlace) != 0u)
|
|
madeBase |= kHazePlace;
|
|
else
|
|
if (const auto blended = g_blendedExtent.find(madeBase); blended != g_blendedExtent.end() && g_blendedLast[madeBase] &&
|
|
std::max(c[0].u, c[3].u) <= static_cast<float>(blended->second.first) + 1.0f &&
|
|
std::max(c[0].v, c[3].v) <= static_cast<float>(blended->second.second) + 1.0f &&
|
|
g_targetOfBase.count(madeBase | kBlendedPlace) != 0u)
|
|
madeBase |= kBlendedPlace;
|
|
// A native composition owns pixels even when its retail record has
|
|
// no CPU buffer. It takes priority over an old frame-target alias.
|
|
const auto pinned = g_pinned.find(record);
|
|
const bool ownsNativePixels = pinned != g_pinned.end() &&
|
|
pinned->second.pixels == rd32(rdram, record + 0x38u) && pinned->second.tex0 == rd64(rdram, record + 0x28u);
|
|
if (record != 0u && rd32(rdram, record + 0x38u) == 0u && !ownsNativePixels && sampleMade(madeBase, made))
|
|
{
|
|
bozo::render::Material material = made;
|
|
++g_stats.madeDraws[std::min<uint32_t>(made.source, 8u)];
|
|
seq(made.source == bozo::render::Material::kPreviousFrame ? 'P' : made.source == 0u ? 'F' : 'T');
|
|
static const bool s_noMade = std::getenv("DC_NO_MADE") != nullptr; // diagnosis
|
|
if (s_noMade || g_toggles.noMade)
|
|
return;
|
|
static int s_logged = 0, s_loggedTargets = 0;
|
|
if (std::getenv("DC_PROBE_2D") &&
|
|
(made.source == bozo::render::Material::kPreviousFrame ? s_logged++ < 12 : (++s_loggedTargets <= 12 || s_loggedTargets % 1200 == 0)))
|
|
std::fprintf(stderr, "[dc:2d] sprite of record %08x \"%.32s\" tex0 %016llx pixels %08x kind %u samples source %u: (%.1f %.1f)-(%.1f %.1f) uv (%.0f %.0f)-(%.0f %.0f) rgba %08x alpha %llx\n",
|
|
record, reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)),
|
|
static_cast<unsigned long long>(rd64(rdram, record + 0x28u)), rd32(rdram, record + 0x38u),
|
|
rd32(rdram, record + 4u) >> 16, made.source, c[0].x, c[0].y, c[3].x, c[3].y,
|
|
c[0].u, c[0].v, c[3].u, c[3].v, c[0].rgba, static_cast<unsigned long long>(g_alpha2D));
|
|
material.frameWidth = 640;
|
|
material.blend = bozo::render::blendOf(g_alpha2D);
|
|
material.depthTest = false;
|
|
material.depthWrite = false;
|
|
// Widescreen (as copySpan): drawn over the whole frame, it covers the whole wider frame; sampling the
|
|
// whole 640, it samples the whole wider frame; a part is the same game pixels.
|
|
const bool wholeSource = g_wideFrame && wholeSpan(std::min(c[0].u, c[3].u), std::max(c[0].u, c[3].u));
|
|
if (whole)
|
|
stretch();
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
auto vertex = [&](const Corner &k) {
|
|
bozo::render::Vertex v;
|
|
v.x = k.x;
|
|
v.y = k.y;
|
|
v.u = wholeSource ? k.u / 640.0f : frameU(1728.0f + k.u); // the target's pixels are the texture's texels
|
|
v.v = k.v / static_cast<float>(made.frameHeight);
|
|
v.rgba = k.rgba;
|
|
return v;
|
|
};
|
|
vertices.insert(vertices.end(), {vertex(c[0]), vertex(c[1]), vertex(c[2]), vertex(c[1]), vertex(c[3]), vertex(c[2])});
|
|
drawScreen(material, vertices);
|
|
return;
|
|
}
|
|
std::shared_ptr<const bozo::render::Texture> texture = record != 0u ? recordTexture(rdram, record) : nullptr;
|
|
// DC_PROBE_2D=1 (diagnosis): each record the 2D draws use, once: name, kind, TEX0's format and size, the GS-order flag.
|
|
static const bool s_probe2D = [] { const char *e = std::getenv("DC_PROBE_2D"); return e && e[0] == '1'; }();
|
|
static std::unordered_map<uint32_t, bool> s_seen2D;
|
|
if (s_probe2D && record != 0u && !s_seen2D[record])
|
|
{
|
|
s_seen2D[record] = true;
|
|
char name[33] = {};
|
|
for (uint32_t k = 0; k < 32u; ++k)
|
|
name[k] = static_cast<char>(rdram[(record + 8u + k) & 0x1FFFFFFu]);
|
|
const uint64_t tex0 = rd64(rdram, record + 0x28u);
|
|
std::fprintf(stderr, "[dc:2d] record %08x \"%s\" kind %u psm 0x%x %ux%u tw %u th %u csa %u flag %u: %s\n", record, name,
|
|
rd32(rdram, record + 4u) >> 16, static_cast<unsigned>((tex0 >> 20) & 0x3Fu), rd32(rdram, record) >> 16,
|
|
rd32(rdram, record + 4u) & 0xFFFFu, static_cast<unsigned>((tex0 >> 26) & 0xFu), static_cast<unsigned>((tex0 >> 30) & 0xFu),
|
|
static_cast<unsigned>((tex0 >> 56) & 0x1Fu), rd32(rdram, record + 0x4Cu), texture ? "decoded" : "NOT decoded");
|
|
}
|
|
static std::unordered_map<uint32_t, int> s_draws2D;
|
|
if (s_probe2D && record != 0u && s_draws2D[record]++ < 3)
|
|
std::fprintf(stderr, "[dc:2d] draw %08x: (%.1f %.1f) (%.1f %.1f) uv (%.0f %.0f)-(%.0f %.0f) rgba %08x alpha %llx\n", record,
|
|
c[0].x, c[0].y, c[3].x, c[3].y, c[0].u, c[0].v, c[3].u, c[3].v, c[0].rgba,
|
|
static_cast<unsigned long long>(g_alpha2D));
|
|
// DC_PROBE_PALETTE=<name> (diagnosis): that record's pixels / palette pointers and first palette entries, once.
|
|
static const char *s_probePalette = std::getenv("DC_PROBE_PALETTE");
|
|
static bool s_paletteLogged = false;
|
|
if (s_probePalette && record != 0u && !s_paletteLogged &&
|
|
std::strncmp(reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)), s_probePalette, 32) == 0)
|
|
{
|
|
s_paletteLogged = true;
|
|
const uint32_t palette = rd32(rdram, record + 0x48u);
|
|
std::fprintf(stderr, "[dc:palette] %s record %08x pixels %08x palette %08x tex0 %016llx entries", s_probePalette, record,
|
|
rd32(rdram, record + 0x38u), palette, static_cast<unsigned long long>(rd64(rdram, record + 0x28u)));
|
|
for (uint32_t k = 0; k < 8u; ++k)
|
|
std::fprintf(stderr, " %08x", rd32(rdram, palette + k * 4u));
|
|
std::fprintf(stderr, " | pixels");
|
|
for (uint32_t k = 0; k < 8u; ++k)
|
|
std::fprintf(stderr, " %02x", rdram[(rd32(rdram, record + 0x38u) + 64u * 128u + 64u + k) & 0x1FFFFFFu]);
|
|
std::fputc('\n', stderr);
|
|
}
|
|
if (record != 0u && !texture)
|
|
return; // not decodable yet (counted with the GS-order textures not in the store)
|
|
bozo::render::Material material;
|
|
material.textured = texture != nullptr;
|
|
material.tex0 = record != 0u ? rd64(rdram, record + 0x28u) : 0u;
|
|
material.blend = bozo::render::blendOf(g_alpha2D);
|
|
material.depthTest = false;
|
|
material.depthWrite = false;
|
|
material.clampU = material.clampV = true;
|
|
material.nearest = spritesNearest(rdram);
|
|
seq('s');
|
|
const float tw = texture ? static_cast<float>(texture->width) : 1.0f, th = texture ? static_cast<float>(texture->height) : 1.0f;
|
|
// Keep the source interval's width: shrinking its endpoints moves
|
|
// interior separators in wide menu strips. A constant nearest-sample
|
|
// bias resolves exact texel-boundary rounding; fragment-stage bounds
|
|
// keep that bias inside the atlas piece without stretching its UVs.
|
|
const float bias = texture && material.nearest ? 1.0f / 32.0f : 0.0f;
|
|
if (bias != 0.0f)
|
|
{
|
|
const float loU = std::min({c[0].u,c[1].u,c[2].u,c[3].u}), hiU = std::max({c[0].u,c[1].u,c[2].u,c[3].u});
|
|
const float loV = std::min({c[0].v,c[1].v,c[2].v,c[3].v}), hiV = std::max({c[0].v,c[1].v,c[2].v,c[3].v});
|
|
material.uvBounds[0] = (loU + bias) / tw; material.uvBounds[2] = (hiU - bias) / tw;
|
|
material.uvBounds[1] = (loV + bias) / th; material.uvBounds[3] = (hiV - bias) / th;
|
|
}
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
auto vertex = [&](const Corner &k) {
|
|
bozo::render::Vertex v;
|
|
v.x = k.x;
|
|
v.y = k.y;
|
|
v.u = (k.u + bias) / tw;
|
|
v.v = (k.v + bias) / th;
|
|
v.rgba = flat ? flatColour(k.rgba, k.rgba >> 8, k.rgba >> 16, k.rgba >> 24) : k.rgba;
|
|
return v;
|
|
};
|
|
vertices.insert(vertices.end(), {vertex(c[0]), vertex(c[1]), vertex(c[2]), vertex(c[1]), vertex(c[3]), vertex(c[2])});
|
|
drawScreen(material, vertices, texture);
|
|
}
|
|
struct Rect
|
|
{
|
|
int32_t x, y, w, h;
|
|
};
|
|
Rect rectAt(const uint8_t *rdram, uint32_t address)
|
|
{
|
|
return {static_cast<int32_t>(rd32(rdram, address)), static_cast<int32_t>(rd32(rdram, address + 4u)),
|
|
static_cast<int32_t>(rd32(rdram, address + 8u)), static_cast<int32_t>(rd32(rdram, address + 12u))};
|
|
}
|
|
// Native triangles cover the destination's full half-open rectangle.
|
|
// Carrying over the console's one-subpixel right-edge subtraction leaves
|
|
// uncovered pixel centres between adjoining map/dialog pieces at scale.
|
|
// Atlas sampling bounds are applied after interpolation in drawStrip.
|
|
void drawSprite(const uint8_t *rdram, uint32_t record, const Rect &d, float u0, float v0, float u1, float v1, uint32_t rgba)
|
|
{
|
|
const float x0 = kOriginX + static_cast<float>(d.x), x1 = kOriginX + static_cast<float>(d.x + d.w);
|
|
const float y0 = kOriginY + static_cast<float>(d.y) / 2.0f, y1 = kOriginY + static_cast<float>(d.y + d.h) / 2.0f;
|
|
const Corner c[4] = {{x0, y0, u0, v0, rgba}, {x1, y0, u1, v0, rgba}, {x0, y1, u0, v1, rgba}, {x1, y1, u1, v1, rgba}};
|
|
drawStrip(rdram, record, c);
|
|
}
|
|
// set2DSprite (0x15BD00: a1 texture, a2 destination, a3 / t0 the source's corner, its size the destination's).
|
|
void sprite2DHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture == 0u)
|
|
return;
|
|
const Rect d = rectAt(rdram, getRegU32(ctx, 6));
|
|
const float u = static_cast<float>(static_cast<int32_t>(getRegU32(ctx, 7))), v = static_cast<float>(static_cast<int32_t>(getRegU32(ctx, 8)));
|
|
drawSprite(rdram, texture, d, u, v, u + static_cast<float>(d.w), v + static_cast<float>(d.h), 0x80808080u);
|
|
}
|
|
// set2DSprite (0x15C000: a1 texture, a2 destination, a3 source), ...Uc (0x15C310: t0 the alpha), ...UcUcUcUc
|
|
// (0x15C630: t0..t3 the colour).
|
|
void sprite2DRectsHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
const uint32_t entry = ctx->pc;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture == 0u)
|
|
return;
|
|
const Rect d = rectAt(rdram, getRegU32(ctx, 6)), src = rectAt(rdram, getRegU32(ctx, 7));
|
|
uint32_t rgba = 0x80808080u;
|
|
if (entry == 0x0015C310u)
|
|
rgba = 0x00808080u | (getRegU32(ctx, 8) & 0xFFu) << 24;
|
|
else if (entry == 0x0015C630u)
|
|
rgba = (getRegU32(ctx, 8) & 0xFFu) | (getRegU32(ctx, 9) & 0xFFu) << 8 | (getRegU32(ctx, 10) & 0xFFu) << 16 |
|
|
(getRegU32(ctx, 11) & 0xFFu) << 24;
|
|
drawSprite(rdram, texture, d, static_cast<float>(src.x), static_cast<float>(src.y), static_cast<float>(src.x + src.w),
|
|
static_cast<float>(src.y + src.h), rgba);
|
|
}
|
|
// set2DSprite with four colours (0x15C980: a1 texture, a2 destination, a3 source, t0..t3 the corners' spRGBA
|
|
// (top-left, top-right, bottom-left, bottom-right), the 9th argument the strip's order: 0 starts top-right).
|
|
void sprite2DCornersHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture == 0u)
|
|
return;
|
|
const Rect d = rectAt(rdram, getRegU32(ctx, 6)), src = rectAt(rdram, getRegU32(ctx, 7));
|
|
const uint32_t tl = rd32(rdram, getRegU32(ctx, 8)), tr = rd32(rdram, getRegU32(ctx, 9)), bl = rd32(rdram, getRegU32(ctx, 10)),
|
|
br = rd32(rdram, getRegU32(ctx, 11));
|
|
const float x0 = kOriginX + static_cast<float>(d.x), x1 = kOriginX + static_cast<float>(d.x + d.w);
|
|
const float y0 = kOriginY + static_cast<float>(d.y) / 2.0f, y1 = kOriginY + static_cast<float>(d.y + d.h) / 2.0f;
|
|
const float u0 = static_cast<float>(src.x), v0 = static_cast<float>(src.y), u1 = static_cast<float>(src.x + src.w),
|
|
v1 = static_cast<float>(src.y + src.h);
|
|
if (stackArg(rdram, ctx, 0) == 0u)
|
|
{
|
|
const Corner c[4] = {{x1, y0, u1, v0, tr}, {x0, y0, u0, v0, tl}, {x1, y1, u1, v1, br}, {x0, y1, u0, v1, bl}};
|
|
drawStrip(rdram, texture, c);
|
|
}
|
|
else
|
|
{
|
|
const Corner c[4] = {{x0, y0, u0, v0, tl}, {x1, y0, u1, v0, tr}, {x0, y1, u0, v1, bl}, {x1, y1, u1, v1, br}};
|
|
drawStrip(rdram, texture, c);
|
|
}
|
|
}
|
|
// set2DSpriteC4 (0x15E120: a1 the rectangle, a2..a5 the corners' spRGBA): an untextured gradient strip.
|
|
void sprite2DC4Hook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const Rect d = rectAt(rdram, getRegU32(ctx, 5));
|
|
const float x0 = kOriginX + static_cast<float>(d.x), x1 = kOriginX + static_cast<float>(d.x + d.w);
|
|
const float y0 = kOriginY + static_cast<float>(d.y) / 2.0f, y1 = kOriginY + static_cast<float>(d.y + d.h) / 2.0f;
|
|
const Corner c[4] = {{x0, y0, 0, 0, rd32(rdram, getRegU32(ctx, 6))}, {x1, y0, 0, 0, rd32(rdram, getRegU32(ctx, 7))},
|
|
{x0, y1, 0, 0, rd32(rdram, getRegU32(ctx, 8))}, {x1, y1, 0, 0, rd32(rdram, getRegU32(ctx, 9))}};
|
|
drawStrip(rdram, 0u, c, true);
|
|
}
|
|
// setColSprite (0x15DED0: a1..a4 four points, x, y in 1/16 GS pixels and z, t0..t3 the colour): an untextured
|
|
// strip (PRIM 0x44).
|
|
void colSpriteHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t rgba = (getRegU32(ctx, 8) & 0xFFu) | (getRegU32(ctx, 9) & 0xFFu) << 8 | (getRegU32(ctx, 10) & 0xFFu) << 16 |
|
|
(getRegU32(ctx, 11) & 0xFFu) << 24;
|
|
Corner c[4];
|
|
for (uint32_t i = 0; i < 4u; ++i)
|
|
{
|
|
const uint32_t point = getRegU32(ctx, 5 + static_cast<int>(i));
|
|
c[i] = {static_cast<float>(static_cast<int32_t>(rd32(rdram, point))) / 16.0f,
|
|
static_cast<float>(static_cast<int32_t>(rd32(rdram, point + 4u))) / 16.0f, 0.0f, 0.0f, rgba};
|
|
}
|
|
drawStrip(rdram, 0u, c, true);
|
|
}
|
|
// set2DSprite with a rotation (0x15E540: f12 the angle, a1 texture, a2 destination, a3 source, t0 / t1 the pivot in
|
|
// the destination) and set2DSpriteRot with a colour (0x15EAD0: the same, t2 / t3 and the 9th / 10th arguments the
|
|
// colour): the corners turned about the pivot with the game's own formulas.
|
|
void sprite2DRotHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
const uint32_t entry = ctx->pc;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture == 0u)
|
|
return;
|
|
const float angle = std::bit_cast<float>(ctx->fu[12]);
|
|
const Rect d = rectAt(rdram, getRegU32(ctx, 6)), src = rectAt(rdram, getRegU32(ctx, 7));
|
|
const int32_t px = static_cast<int32_t>(getRegU32(ctx, 8)), py = static_cast<int32_t>(getRegU32(ctx, 9));
|
|
const float c = std::cos(angle), sn = std::sin(angle);
|
|
float xs[4], ys[4];
|
|
uint32_t rgba = 0x80808080u;
|
|
if (entry == 0x001831D0u)
|
|
{
|
|
// set2DSpriteRot ...Uc (0x1831D0: t2 the alpha): corners in 1/16 pixels, x = y' cos + x' sin, y halved.
|
|
xs[0] = xs[2] = static_cast<float>(px * -16), xs[1] = xs[3] = static_cast<float>((d.w - px) * 16 - 1);
|
|
ys[0] = ys[1] = static_cast<float>(py * -16), ys[2] = ys[3] = static_cast<float>((d.h - py) * 16 - 1);
|
|
for (int i = 0; i < 4; ++i)
|
|
{
|
|
const int32_t x = static_cast<int32_t>(ys[i] * c + xs[i] * sn);
|
|
const int32_t y = static_cast<int32_t>((xs[i] * c - ys[i] * sn) * 0.5f);
|
|
xs[i] = static_cast<float>(x + d.x * 16 + 0x6C00) / 16.0f;
|
|
ys[i] = static_cast<float>(y + d.y * 8 + 0x7900) / 16.0f;
|
|
}
|
|
rgba = 0x00808080u | (getRegU32(ctx, 10) & 0xFFu) << 24;
|
|
}
|
|
else if (entry == 0x0015E540u)
|
|
{
|
|
xs[0] = xs[2] = static_cast<float>(-px), xs[1] = xs[3] = static_cast<float>(d.w + 1 - px);
|
|
ys[0] = ys[1] = static_cast<float>(-py), ys[2] = ys[3] = static_cast<float>(d.h + 1 - py);
|
|
for (int i = 0; i < 4; ++i)
|
|
{
|
|
const int32_t x = static_cast<int32_t>(ys[i] * c + xs[i] * sn), y = static_cast<int32_t>(xs[i] * c - ys[i] * sn);
|
|
xs[i] = static_cast<float>((x + d.x) * 16 + 0x6C00) / 16.0f;
|
|
ys[i] = static_cast<float>((y + d.y) * 8 + 0x7900) / 16.0f;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
xs[0] = xs[2] = static_cast<float>(px * -16), xs[1] = xs[3] = static_cast<float>((d.w - px) * 16 - 1);
|
|
ys[0] = ys[1] = static_cast<float>(py * -16), ys[2] = ys[3] = static_cast<float>((d.h - py) * 16 - 1);
|
|
for (int i = 0; i < 4; ++i)
|
|
{
|
|
const int32_t x = static_cast<int32_t>(-ys[i] * sn - xs[i] * c);
|
|
const int32_t y = static_cast<int32_t>((-xs[i] * sn + ys[i] * c) * 0.5f);
|
|
xs[i] = static_cast<float>(x + d.x * 16 + 0x6C00) / 16.0f;
|
|
ys[i] = static_cast<float>(y + d.y * 8 + 0x7900) / 16.0f;
|
|
}
|
|
rgba = (getRegU32(ctx, 10) & 0xFFu) | (getRegU32(ctx, 11) & 0xFFu) << 8 | (stackArg(rdram, ctx, 0) & 0xFFu) << 16 |
|
|
(stackArg(rdram, ctx, 1) & 0xFFu) << 24;
|
|
}
|
|
const float u0 = static_cast<float>(src.x), v0 = static_cast<float>(src.y);
|
|
const Corner k[4] = {{xs[0], ys[0], u0, v0, rgba},
|
|
{xs[1], ys[1], static_cast<float>(src.x + d.w), v0, rgba},
|
|
{xs[2], ys[2], u0, static_cast<float>(src.y + src.h), rgba},
|
|
{xs[3], ys[3], static_cast<float>(src.x + src.w), static_cast<float>(src.y + src.h), rgba}};
|
|
drawStrip(rdram, texture, k);
|
|
}
|
|
// Myset2DSprite (0x14CD80: a1 texture, a2 destination, a3 source, t0..t3 the colour) and set2DSprite_Core
|
|
// (0x14C3C0: the same arguments; the sprite set2DSprite_Start opened a batch for, the message windows' glyphs).
|
|
void mySpriteHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture == 0u)
|
|
return;
|
|
const Rect d = rectAt(rdram, getRegU32(ctx, 6)), src = rectAt(rdram, getRegU32(ctx, 7));
|
|
const uint32_t rgba = (getRegU32(ctx, 8) & 0xFFu) | (getRegU32(ctx, 9) & 0xFFu) << 8 | (getRegU32(ctx, 10) & 0xFFu) << 16 |
|
|
(getRegU32(ctx, 11) & 0xFFu) << 24;
|
|
drawSprite(rdram, texture, d, static_cast<float>(src.x), static_cast<float>(src.y), static_cast<float>(src.x + src.w),
|
|
static_cast<float>(src.y + src.h), rgba);
|
|
}
|
|
// set2DSprite_Start / _End (0x14C220 / 0x14C4F0): the batch they open and close is not built; its sprites are
|
|
// drawn one by one (set2DSprite_Core).
|
|
void spriteBatchHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
// The texture record a TEX0 belongs to (sprite tables keep a TEX0, not the CTexture): the newest record with that
|
|
// TBP, CBP and format, from the texture manager's own records.
|
|
uint32_t recordOfTex0(const uint8_t *rdram, uint64_t tex0)
|
|
{
|
|
constexpr uint64_t kMask = 0x3FFFull | 0x3Full << 20 | 0x3FFFull << 37; // TBP0, PSM, CBP
|
|
const int32_t count = static_cast<int32_t>(rd32(rdram, kTextureManager));
|
|
for (int32_t i = std::min(count, 1023); i >= 0; --i)
|
|
{
|
|
const uint32_t record = kTextureManager + 0x10F8u + static_cast<uint32_t>(i) * 0x50u;
|
|
if ((rd64(rdram, record + 0x28u) & kMask) == (tex0 & kMask) && rdram[(record + 8u) & 0x1FFFFFFu] != 0u)
|
|
return record;
|
|
}
|
|
return 0u;
|
|
}
|
|
// CSpriteTable::DrawTable (0x12BA20, a0 the table): the game's sprite lists (+ 4 the count, + 0xC the lists'
|
|
// first entries, + 0x4C their ends). An entry: shorts x, y, w, h (DC's view), u, v, uw, vh, r, g, b, a, TEX0 at
|
|
// + 0x28, the next entry at + 0x30. Sprites with mgAlpha's blend, Z test ALWAYS, no Z write.
|
|
void spriteTableHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t table = getRegU32(ctx, 4);
|
|
const int32_t lists = static_cast<int32_t>(rd32(rdram, table + 4u));
|
|
for (int32_t list = lists - 1; list >= 0 && list < 16; --list)
|
|
{
|
|
uint32_t entry = rd32(rdram, table + 0xCu + static_cast<uint32_t>(list) * 4u);
|
|
const uint32_t end = rd32(rdram, table + 0x4Cu + static_cast<uint32_t>(list) * 4u);
|
|
for (int guard = 0; entry != end && entry != 0u && guard < 4096; ++guard)
|
|
{
|
|
auto sh = [&](uint32_t i) { return static_cast<int32_t>(static_cast<int16_t>(rd32(rdram, entry + i * 2u) & 0xFFFFu)); };
|
|
const Rect d{sh(0), sh(1), sh(2), sh(3)};
|
|
const float u = static_cast<float>(sh(4)), v = static_cast<float>(sh(5));
|
|
const uint32_t rgba = static_cast<uint32_t>(sh(8) & 0xFF) | static_cast<uint32_t>(sh(9) & 0xFF) << 8 |
|
|
static_cast<uint32_t>(sh(10) & 0xFF) << 16 | static_cast<uint32_t>(sh(11) & 0xFF) << 24;
|
|
const uint32_t record = recordOfTex0(rdram, rd64(rdram, entry + 0x28u));
|
|
if (record != 0u)
|
|
{
|
|
// The bottom edge one 1/16 short as the table writes it (0x78FF).
|
|
const float x0 = kOriginX + static_cast<float>(d.x), x1 = kOriginX + static_cast<float>(d.x + d.w);
|
|
const float y0 = kOriginY + static_cast<float>(d.y) / 2.0f;
|
|
const float y1 = kOriginY + static_cast<float>(d.y + d.h) / 2.0f - 1.0f / 16.0f;
|
|
const float u1 = u + static_cast<float>(sh(6)), v1 = v + static_cast<float>(sh(7));
|
|
const Corner c[4] = {{x0, y0, u, v, rgba}, {x1, y0, u1, v, rgba}, {x0, y1, u, v1, rgba}, {x1, y1, u1, v1, rgba}};
|
|
drawStrip(rdram, record, c);
|
|
}
|
|
entry = rd32(rdram, entry + 0x30u);
|
|
}
|
|
}
|
|
}
|
|
|
|
// The effects' 3D sprites (set3DSprite / set3DSpriteFog / set3DColSprite, 0x15D1B0..): points the game projected
|
|
// itself, in GS terms (x, y in 1/16 pixels, Z, and F for the fog ones), a source rectangle and colours. Strips or
|
|
// sprites with PRIM ABE, the game's TEST (its depth test against the scene), Z not written.
|
|
struct Point3
|
|
{
|
|
float x, y, z, fog;
|
|
};
|
|
Point3 pointAt(const uint8_t *rdram, uint32_t address, bool withFog)
|
|
{
|
|
Point3 p;
|
|
p.x = static_cast<float>(static_cast<int32_t>(rd32(rdram, address))) / 16.0f;
|
|
p.y = static_cast<float>(static_cast<int32_t>(rd32(rdram, address + 4u))) / 16.0f;
|
|
p.z = static_cast<float>(rd32(rdram, address + 8u) & 0xFFFFFFu);
|
|
p.fog = withFog ? static_cast<float>(rd32(rdram, address + 12u) & 0xFFu) / 255.0f : 1.0f;
|
|
return p;
|
|
}
|
|
// A strip of four points (corner order TL, TR, BL, BR for the textured ones).
|
|
void draw3D(const uint8_t *rdram, uint32_t record, const Point3 (&p)[4], const float (&u)[4], const float (&v)[4],
|
|
const uint32_t (&rgba)[4], bool fog, bool flat)
|
|
{
|
|
if (g_toggles.noSprites3D)
|
|
return;
|
|
std::shared_ptr<const bozo::render::Texture> texture = record != 0u ? recordTexture(rdram, record) : nullptr;
|
|
// A record without pixels of its own is a picture the game makes (the dungeon torches' flame, which
|
|
// blendTextuer blends in "work"): sampled from its target, in that picture's texels.
|
|
bozo::render::Material made;
|
|
bool fromMade = false;
|
|
if (record != 0u && !texture && rd32(rdram, record + 0x38u) == 0u)
|
|
{
|
|
uint32_t base = static_cast<uint32_t>(rd64(rdram, record + 0x28u) & 0x3FFFu);
|
|
if (const auto blended = g_blendedExtent.find(base); blended != g_blendedExtent.end() &&
|
|
std::max({u[0], u[1], u[2], u[3]}) <= static_cast<float>(blended->second.first) + 1.0f &&
|
|
std::max({v[0], v[1], v[2], v[3]}) <= static_cast<float>(blended->second.second) + 1.0f &&
|
|
g_targetOfBase.count(base | kBlendedPlace) != 0u)
|
|
base |= kBlendedPlace;
|
|
fromMade = sampleMade(base, made);
|
|
}
|
|
if (record != 0u && !texture && !fromMade)
|
|
return;
|
|
bozo::render::Material material = fromMade ? made : bozo::render::Material{};
|
|
material.textured = texture != nullptr || fromMade;
|
|
material.tex0 = record != 0u ? rd64(rdram, record + 0x28u) : 0u;
|
|
material.blend = bozo::render::blendOf(g_alpha2D);
|
|
material.depthTest = true;
|
|
material.depthWrite = false;
|
|
material.clampU = material.clampV = true;
|
|
material.fog = fog;
|
|
material.fogColour = g_fogColour;
|
|
const float tw = texture ? static_cast<float>(texture->width) : fromMade ? 640.0f : 1.0f,
|
|
th = texture ? static_cast<float>(texture->height) : fromMade ? static_cast<float>(made.frameHeight) : 1.0f;
|
|
bozo::render::Vertex k[4];
|
|
for (int i = 0; i < 4; ++i)
|
|
{
|
|
k[i].x = p[i].x;
|
|
k[i].y = p[i].y;
|
|
k[i].z = p[i].z;
|
|
k[i].u = u[i] / tw;
|
|
k[i].v = v[i] / th;
|
|
k[i].fog = p[i].fog;
|
|
k[i].rgba = flat ? flatColour(rgba[i], rgba[i] >> 8, rgba[i] >> 16, rgba[i] >> 24) : rgba[i];
|
|
}
|
|
const std::vector<bozo::render::Vertex> vertices = {k[0], k[1], k[2], k[1], k[3], k[2]};
|
|
// The frame dump: each effect sprite, its texture (record, TEX0, size, its alpha range), colour and ALPHA.
|
|
if (g_dump2D)
|
|
{
|
|
uint32_t alphaLo = 255u, alphaHi = 0u;
|
|
if (texture)
|
|
for (uint32_t texel : texture->rgba)
|
|
alphaLo = std::min(alphaLo, texel >> 24), alphaHi = std::max(alphaHi, texel >> 24);
|
|
std::fprintf(stderr, "[dc:dump] 3D sprite \"%.16s\" tex0 %016llx %ux%u alpha %u..%u uv (%.0f %.0f)-(%.0f %.0f) rgba %08x ALPHA %llx blend %d fog %d at (%.0f %.0f)\n",
|
|
record != 0u ? reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)) : "", static_cast<unsigned long long>(material.tex0),
|
|
texture ? texture->width : 0u, texture ? texture->height : 0u, alphaLo, alphaHi, u[0], v[0], u[3], v[3], rgba[0],
|
|
static_cast<unsigned long long>(g_alpha2D), static_cast<int>(material.blend), fog ? 1 : 0, p[0].x, p[0].y);
|
|
}
|
|
drawScreen(material, vertices, texture);
|
|
}
|
|
// set3DColSprite (0x15D1B0: a1..a4 the points, t0..t3 their spRGBA): untextured, Gouraud.
|
|
void colSprite3DHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
Point3 p[4];
|
|
uint32_t rgba[4];
|
|
for (int i = 0; i < 4; ++i)
|
|
{
|
|
p[i] = pointAt(rdram, getRegU32(ctx, 5 + i), false);
|
|
rgba[i] = rd32(rdram, getRegU32(ctx, 8 + i));
|
|
}
|
|
const float zero[4] = {};
|
|
draw3D(rdram, 0u, p, zero, zero, rgba, false, true);
|
|
}
|
|
// set3DSprite (0x15D4B0: a1 texture, a2 source, a3 / t0 / t1 / t2 the points TL, TR, BL, BR, t3 the spRGBA; 0x15D790:
|
|
// a3 / t0 the sprite's corners, t1 the spRGBA) and set3DSpriteFog (0x15D9A0: the four points with F, t3 the alpha;
|
|
// 0x15DCA0: the sprite's corners with F, t1 the spRGBA).
|
|
void sprite3DHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
const uint32_t entry = ctx->pc;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture == 0u)
|
|
return;
|
|
const Rect src = rectAt(rdram, getRegU32(ctx, 6));
|
|
const bool fog = entry == 0x0015D9A0u || entry == 0x0015DCA0u;
|
|
const bool strip = entry == 0x0015D4B0u || entry == 0x0015D9A0u;
|
|
Point3 p[4];
|
|
uint32_t colour = 0;
|
|
if (strip)
|
|
{
|
|
for (int i = 0; i < 4; ++i)
|
|
p[i] = pointAt(rdram, getRegU32(ctx, 7 + i), fog);
|
|
colour = entry == 0x0015D9A0u ? 0x00808080u | (getRegU32(ctx, 11) & 0xFFu) << 24 : rd32(rdram, getRegU32(ctx, 11));
|
|
}
|
|
else
|
|
{
|
|
const Point3 a = pointAt(rdram, getRegU32(ctx, 7), fog), b = pointAt(rdram, getRegU32(ctx, 8), fog);
|
|
p[0] = a;
|
|
p[1] = {b.x, a.y, b.z, b.fog};
|
|
p[2] = {a.x, b.y, b.z, b.fog};
|
|
p[3] = b;
|
|
colour = rd32(rdram, getRegU32(ctx, 9));
|
|
}
|
|
const float u0 = static_cast<float>(src.x), u1 = static_cast<float>(src.x + src.w);
|
|
const float v0 = static_cast<float>(src.y), v1 = static_cast<float>(src.y + src.h);
|
|
const float u[4] = {u0, u1, u0, u1}, v[4] = {v0, v0, v1, v1};
|
|
const uint32_t rgba[4] = {colour, colour, colour, colour};
|
|
draw3D(rdram, texture, p, u, v, rgba, fog, false);
|
|
}
|
|
// DrawLine (0x171210: a0 / a1 the ends, x, y in 1/16 pixels and Z; a2..a5 the colour): a line, drawn as a thin quad.
|
|
void drawLineHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const Point3 a = pointAt(rdram, getRegU32(ctx, 4), false), b = pointAt(rdram, getRegU32(ctx, 5), false);
|
|
const uint32_t rgba = (getRegU32(ctx, 6) & 0xFFu) | (getRegU32(ctx, 7) & 0xFFu) << 8 | (getRegU32(ctx, 8) & 0xFFu) << 16 |
|
|
(getRegU32(ctx, 9) & 0xFFu) << 24;
|
|
float nx = -(b.y - a.y), ny = b.x - a.x;
|
|
const float length = std::sqrt(nx * nx + ny * ny);
|
|
if (length <= 0.0f)
|
|
return;
|
|
nx *= 0.5f / length, ny *= 0.5f / length;
|
|
const Point3 p[4] = {{a.x - nx, a.y - ny, a.z, 1.0f}, {a.x + nx, a.y + ny, a.z, 1.0f}, {b.x - nx, b.y - ny, b.z, 1.0f},
|
|
{b.x + nx, b.y + ny, b.z, 1.0f}};
|
|
const float zero[4] = {};
|
|
const uint32_t colours[4] = {rgba, rgba, rgba, rgba};
|
|
draw3D(rdram, 0u, p, zero, zero, colours, false, true);
|
|
}
|
|
|
|
// MGMoveImage (0x12F210: a0 the source's TEX0, a1 the source rectangle in texels, a2 the destination's TEX0, a3 / t0
|
|
// the destination point): a copy between two textures' places in GS memory (TexAnime's face expressions and
|
|
// scrolling textures). Here it patches the destination record's decoded texture with the source record's
|
|
// texels; the patched texture stands for the record until the game sends its own pixels again (its content
|
|
// hash changes), as GS memory would keep the copy. Copies from or to a place no record holds (the frame: the
|
|
// water's refraction copy) are not made.
|
|
void patchTexture(const uint8_t *rdram, uint32_t src, const Rect &r, uint32_t dst, int32_t dx, int32_t dy);
|
|
// GS memory's residents: the record ReloadTexture last sent to each place (TBP0 and PSM), and the records holding
|
|
// a copy MGMoveImage made into them. Places are shared (Toan's face and a piece of his house), and the game sends
|
|
// a group's textures again before drawing them: a copy into the face's place must patch the face, and is undone
|
|
// for whatever record is sent there next.
|
|
constexpr uint64_t kTexturePlace = 0x3FFFull | 0x3Full << 20; // TBP0, PSM
|
|
std::unordered_map<uint64_t, uint32_t> g_resident;
|
|
std::unordered_set<uint32_t> g_patchedRecords;
|
|
RecompiledFunction g_cleanupTextureList = nullptr;
|
|
void cleanupTextureListHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
// The original CPU routine compacts 196 CTexture records, copying
|
|
// each complete 0x50-byte asset descriptor into the first hole.
|
|
// Native images/copies must move with those assets, not stay at the
|
|
// table addresses that menu loads are about to reuse.
|
|
constexpr uint32_t count = 196, stride = 0x50;
|
|
const uint32_t first = getRegU32(ctx,4)+0x10F8u, link = getRegU32(ctx,31);
|
|
std::array<std::array<uint8_t,stride>,count> before;
|
|
std::memcpy(before.data(),rdram+first,sizeof(before));
|
|
g_cleanupTextureList(rdram,ctx,runtime);
|
|
if (ctx->pc != link || ctx->leaving) return;
|
|
std::unordered_map<uint32_t,uint32_t> moved;
|
|
std::array<bool,count> used{};
|
|
for (uint32_t old=0;old<count;++old)
|
|
if (before[old][8])
|
|
for (uint32_t now=0;now<count;++now)
|
|
if (!used[now] && std::memcmp(before[old].data(),rdram+first+now*stride,stride)==0)
|
|
{ moved[first+old*stride]=first+now*stride; used[now]=true; break; }
|
|
auto destination = [&](uint32_t at) {
|
|
if (at<first || at>=first+count*stride || (at-first)%stride) return at;
|
|
const auto found=moved.find(at);return found==moved.end()?0u:found->second;
|
|
};
|
|
auto migrate = [&](auto &cache) {
|
|
auto previous=std::move(cache);cache.clear();
|
|
for (auto &[at,value]:previous)
|
|
if (const uint32_t to=destination(at)) cache[to]=std::move(value);
|
|
};
|
|
migrate(g_pinned);migrate(g_decoded);
|
|
std::unordered_set<uint32_t> patched;
|
|
for (uint32_t at:g_patchedRecords)
|
|
if (const uint32_t to=destination(at)) patched.insert(to);
|
|
g_patchedRecords=std::move(patched);
|
|
for (auto it=g_resident.begin();it!=g_resident.end();)
|
|
if (const uint32_t to=destination(it->second)) { it->second=to; ++it; }
|
|
else it=g_resident.erase(it);
|
|
}
|
|
// ReloadTexture (0x133070: a0 the texture manager, a2 the group): sends the group's records (their first half-word,
|
|
// the group) to GS memory when the group is not the current one or not loaded yet.
|
|
uint64_t g_nativeTextureReloads = 0, g_nativeTextureSelections = 0, g_nativeTextureTm2 = 0, g_nativeTextureFiles = 0;
|
|
void reloadTextureHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
const uint32_t manager = getRegU32(ctx, 4);
|
|
const int32_t group = static_cast<int32_t>(getRegU32(ctx, 6));
|
|
++g_nativeTextureReloads;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
if (group < 0 || group >= 0x48)
|
|
{
|
|
guest.write32(manager + 0xcu, 0xffffffffu);
|
|
return;
|
|
}
|
|
guest.in(manager, 0x10f8u);
|
|
const uint32_t selected = manager + static_cast<uint32_t>(group) * 60u;
|
|
if (static_cast<int32_t>(guest.read32(manager + 0xcu)) == group && guest.read32(selected + 0x40u))
|
|
return;
|
|
const int32_t count = static_cast<int32_t>(guest.read32(manager));
|
|
if (count < 0 || count > 1024) throw std::runtime_error("native texture reload: invalid record count");
|
|
guest.in(manager + 0x10f8u, static_cast<uint32_t>(count) * 0x50u);
|
|
const int32_t start = static_cast<int32_t>(guest.read32(selected + 0x3cu));
|
|
// Preserve the manager's group-overlap bookkeeping. Native texture records
|
|
// replace the old flush/upload packets; no packet pointer or mip chain is read.
|
|
for (uint32_t other = 0; other < 72u; ++other)
|
|
{
|
|
const uint32_t pending = manager + other * 60u + 0x48u;
|
|
if (other != static_cast<uint32_t>(group) && static_cast<int32_t>(guest.read32(pending)) < start)
|
|
guest.write32(pending, static_cast<uint32_t>(start));
|
|
}
|
|
guest.write32(manager + 0xcu, static_cast<uint32_t>(group));
|
|
guest.write32(selected + 0x48u, 0);
|
|
guest.write32(selected + 0x40u, 1);
|
|
++g_nativeTextureSelections;
|
|
for (int32_t i = 1; i < count; ++i)
|
|
{
|
|
const uint32_t record = manager + 0x10F8u + static_cast<uint32_t>(i) * 0x50u;
|
|
if (static_cast<int16_t>(rd32(rdram, record) & 0xFFFFu) != group)
|
|
continue;
|
|
g_resident[rd64(rdram, record + 0x28u) & kTexturePlace] = record;
|
|
if (g_patchedRecords.erase(record) != 0u)
|
|
g_decoded.erase(record); // its own texels again
|
|
}
|
|
}
|
|
// TexAnime (0x167170: a0 the CTextureAnime, a1 the group): DC_PROBE_COPIES=1 also logs each slot's keyframe (this +
|
|
// 0x120 + slot x 4: kind, frames to hold (< 0 for ever), source rectangle, next) and its frame count (+ 0x180)
|
|
// whenever the keyframe changes, and every 600 calls.
|
|
RecompiledFunction g_texAnime = nullptr;
|
|
void texAnimeHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
static const bool s_probe = std::getenv("DC_PROBE_COPIES") != nullptr;
|
|
if (s_probe)
|
|
{
|
|
const uint32_t anime = getRegU32(ctx, 4);
|
|
static std::unordered_map<uint64_t, uint32_t> s_last;
|
|
static uint32_t s_calls = 0;
|
|
const bool every = ++s_calls % 600u == 0u;
|
|
for (uint32_t slot = 0; slot < 0x18u; ++slot)
|
|
{
|
|
const uint32_t entry = rd32(rdram, anime + 0x120u + slot * 4u);
|
|
if (rd32(rdram, anime + slot * 4u) == 0u || entry == 0u)
|
|
continue;
|
|
uint32_t &last = s_last[static_cast<uint64_t>(anime) << 8 | slot];
|
|
if (last == entry && !every)
|
|
continue;
|
|
last = entry;
|
|
auto h = [&](uint32_t offset) { return static_cast<int>(static_cast<int16_t>(rd32(rdram, entry + offset) & 0xFFFFu)); };
|
|
std::fprintf(stderr, "[dc:texanime] frame %llu anime %08x group %d slot %u: entry %08x kind %d hold %d chain %d group %d/%d rect (%d,%d %dx%d) to %d,%d next %08x first %08x count %d\n",
|
|
static_cast<unsigned long long>(g_publishedFrames), anime, static_cast<int>(getRegU32(ctx, 5)), slot, entry, h(0), h(4),
|
|
h(6), h(8), h(0x20), h(0x38), h(0x3A), h(0x3C), h(0x3E), h(0x40), h(0x42), rd32(rdram, entry + 0x54u),
|
|
rd32(rdram, anime + 0x60u + slot * 4u), static_cast<int>(rd32(rdram, anime + 0x180u + slot * 4u)));
|
|
}
|
|
}
|
|
g_texAnime(rdram, ctx, runtime);
|
|
}
|
|
// CTextureAnime's Enable (0x167B40) / Disable (0x167B80) (a0 the anime, a1 the slot), DisableAll (0x167AE0) and
|
|
// CCharacter's TexAnimeOn (0x138080) / TexAnimeOff (0x1380B0) (a0 the character, a1 the slot) / ClearTexAnime
|
|
// (0x138020): DC_PROBE_COPIES=1
|
|
// logs each call with its caller, and the first time an anime is enabled, every slot's first keyframe.
|
|
RecompiledFunction g_animeCalls[6] = {};
|
|
constexpr uint32_t kAnimeCallAddress[6] = {0x00167B40u, 0x00167B80u, 0x00167AE0u, 0x00138080u, 0x001380B0u, 0x00138020u};
|
|
constexpr const char *kAnimeCallName[6] = {"Enable", "Disable", "DisableAll", "CCharacter::TexAnimeOn", "CCharacter::TexAnimeOff",
|
|
"CCharacter::ClearTexAnime"};
|
|
template <int N>
|
|
void animeCallHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
static const bool s_probe = std::getenv("DC_PROBE_COPIES") != nullptr;
|
|
if (s_probe)
|
|
{
|
|
const uint32_t self = getRegU32(ctx, 4);
|
|
std::fprintf(stderr, "[dc:texanime] frame %llu %s(%08x, %d) from %08x\n", static_cast<unsigned long long>(g_publishedFrames),
|
|
kAnimeCallName[N], self, static_cast<int>(getRegU32(ctx, 5)), getRegU32(ctx, 31));
|
|
static std::unordered_set<uint32_t> s_listed;
|
|
if (N == 0 && s_listed.insert(self).second)
|
|
for (uint32_t slot = 0; slot < 0x18u; ++slot)
|
|
{
|
|
uint32_t entry = rd32(rdram, self + 0x60u + slot * 4u);
|
|
if (entry == 0u)
|
|
continue;
|
|
std::fprintf(stderr, "[dc:texanime] slot %u:", slot);
|
|
for (int k = 0; k < 12 && entry != 0u; ++k, entry = rd32(rdram, entry + 0x54u))
|
|
{
|
|
auto h = [&](uint32_t offset) { return static_cast<int>(static_cast<int16_t>(rd32(rdram, entry + offset) & 0xFFFFu)); };
|
|
std::fprintf(stderr, " [kind %d hold %d chain %d (%d,%d %dx%d) to %d,%d]", h(0), h(4), h(6), h(0x38), h(0x3A), h(0x3C),
|
|
h(0x3E), h(0x40), h(0x42));
|
|
}
|
|
std::fprintf(stderr, "\n");
|
|
}
|
|
}
|
|
g_animeCalls[N](rdram, ctx, runtime);
|
|
}
|
|
// CActionSeq::Play (0x1554A0: a0 the sequence; + 0x33 x 4 its character): DC_PROBE_COPIES=1 logs the sequence's
|
|
// texture-anime queue (+ 0x2F x 4, ACT_SEQ entries: type 0xF, + 4 frames, + 0x10 slot, + 0x14 on, + 0x18 off at
|
|
// the end, next at + 0x0C?) whenever its head changes, with its run flag (+ 0x17 x 4) and wait (+ 0x18 x 4).
|
|
RecompiledFunction g_actionSeqPlay = nullptr;
|
|
void actionSeqPlayHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
static const bool s_probe = std::getenv("DC_PROBE_COPIES") != nullptr;
|
|
if (s_probe)
|
|
{
|
|
const uint32_t seq = getRegU32(ctx, 4);
|
|
static std::unordered_map<uint32_t, uint32_t> s_head;
|
|
const uint32_t head = rd32(rdram, seq + 0x2Fu * 4u);
|
|
if (s_head[seq] != head)
|
|
{
|
|
s_head[seq] = head;
|
|
std::fprintf(stderr, "[dc:actseq] frame %llu seq %08x chara %08x run %d wait %d count %d texanime queue:",
|
|
static_cast<unsigned long long>(g_publishedFrames), seq, rd32(rdram, seq + 0x33u * 4u),
|
|
static_cast<int>(rd32(rdram, seq + 0x17u * 4u)), static_cast<int>(rd32(rdram, seq + 0x18u * 4u)),
|
|
static_cast<int>(rd32(rdram, seq + 0x11u * 4u)));
|
|
for (int k = 0; k < 16 && head != 0u; ++k)
|
|
{
|
|
const uint32_t e = k == 0 ? head : 0u;
|
|
if (e == 0u)
|
|
break;
|
|
std::fprintf(stderr, " [%08x: type %d frames %d slot %d on %d off-at-end %d | %08x %08x %08x %08x]", e,
|
|
static_cast<int>(rd32(rdram, e)), static_cast<int>(rd32(rdram, e + 4u)), static_cast<int>(rd32(rdram, e + 0x10u)),
|
|
static_cast<int>(rd32(rdram, e + 0x14u)), static_cast<int>(rd32(rdram, e + 0x18u)), rd32(rdram, e + 8u),
|
|
rd32(rdram, e + 0xCu), rd32(rdram, e + 0x1Cu), rd32(rdram, e + 0x20u));
|
|
}
|
|
std::fprintf(stderr, "\n");
|
|
}
|
|
}
|
|
g_actionSeqPlay(rdram, ctx, runtime);
|
|
}
|
|
void moveImageHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
constexpr uint64_t kPlace = 0x3FFFull | 0x3Full << 20; // TBP0, PSM
|
|
const uint64_t srcTex0 = rd64(rdram, getRegU32(ctx, 4)), dstTex0 = rd64(rdram, getRegU32(ctx, 6));
|
|
const Rect r = rectAt(rdram, getRegU32(ctx, 5));
|
|
const int32_t dx = static_cast<int32_t>(getRegU32(ctx, 7)), dy = static_cast<int32_t>(getRegU32(ctx, 8));
|
|
auto recordAt = [&](uint64_t tex0) {
|
|
const int32_t count = static_cast<int32_t>(rd32(rdram, kTextureManager));
|
|
for (int32_t i = std::min(count, 1023); i >= 0; --i)
|
|
{
|
|
const uint32_t record = kTextureManager + 0x10F8u + static_cast<uint32_t>(i) * 0x50u;
|
|
if ((rd64(rdram, record + 0x28u) & kPlace) == (tex0 & kPlace) && rdram[(record + 8u) & 0x1FFFFFFu] != 0u)
|
|
return record;
|
|
}
|
|
return 0u;
|
|
};
|
|
++g_stats.textureCopies;
|
|
// Out of one of the game's own pictures (its frame: the towns copy it each frame) into a place: drawn into
|
|
// that place's target, 1:1.
|
|
bozo::render::Material made;
|
|
const uint32_t dstBase = static_cast<uint32_t>(dstTex0 & 0x3FFFu);
|
|
if (sampleMade(static_cast<uint32_t>(srcTex0 & 0x3FFFu), made) && dstBase != g_frameBase && dstBase != g_backBase)
|
|
{
|
|
made.target = targetFor(dstBase);
|
|
// The place now holds a picture with the source's rows (MGMoveFrameBuffImage's 448 does not outlive it).
|
|
g_targetRows[made.target] = static_cast<float>(made.frameHeight);
|
|
made.blend = bozo::render::Material::Blend::Opaque;
|
|
made.depthTest = false;
|
|
made.depthWrite = false;
|
|
made.clampU = made.clampV = true;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
const CopySpan span = copySpan(static_cast<float>(dx), static_cast<float>(dx + r.w), static_cast<float>(r.x),
|
|
static_cast<float>(r.x + r.w));
|
|
quad(vertices, span.x0, kOriginY + static_cast<float>(dy), span.x1, kOriginY + static_cast<float>(dy + r.h), 0.0f,
|
|
0x80808080u, span.u0, static_cast<float>(r.y) / made.frameHeight, span.u1,
|
|
static_cast<float>(r.y + r.h) / made.frameHeight);
|
|
drawScreen(made, vertices);
|
|
return;
|
|
}
|
|
uint32_t dst = 0u;
|
|
if (const auto resident = g_resident.find(dstTex0 & kTexturePlace);
|
|
resident != g_resident.end() && (rd64(rdram, resident->second + 0x28u) & kTexturePlace) == (dstTex0 & kTexturePlace))
|
|
dst = resident->second;
|
|
else
|
|
dst = recordAt(dstTex0);
|
|
// The source too is what was sent to its place last: places are shared (the face expressions' sheet with
|
|
// other pictures), and the first record of that place copied another picture's transparent black onto
|
|
// Toan's jaw.
|
|
uint32_t src = 0u;
|
|
if (const auto resident = g_resident.find(srcTex0 & kTexturePlace);
|
|
resident != g_resident.end() && (rd64(rdram, resident->second + 0x28u) & kTexturePlace) == (srcTex0 & kTexturePlace))
|
|
src = resident->second;
|
|
else
|
|
src = recordAt(srcTex0);
|
|
if (g_dump2D)
|
|
std::fprintf(stderr, "[dc:dump] texture copy (%d,%d %dx%d) from %08x \"%.16s\" (first at its place %08x) to %08x \"%.16s\" (first %08x) at %d,%d\n",
|
|
r.x, r.y, r.w, r.h, src, src != 0u ? reinterpret_cast<const char *>(rdram + ((src + 8u) & 0x1FFFFFFu)) : "", recordAt(srcTex0), dst,
|
|
dst != 0u ? reinterpret_cast<const char *>(rdram + ((dst + 8u) & 0x1FFFFFFu)) : "", recordAt(dstTex0), dx, dy);
|
|
// DC_PROBE_COPIES=1 (diagnosis): every copy between two records (the face expressions), with the frame.
|
|
static const bool s_probeCopies = std::getenv("DC_PROBE_COPIES") != nullptr;
|
|
if (s_probeCopies && src != 0u && dst != 0u)
|
|
std::fprintf(stderr, "[dc:copies] frame %llu: (%d,%d %dx%d) of \"%.16s\" %08x to \"%.16s\" %08x at %d,%d\n",
|
|
static_cast<unsigned long long>(g_publishedFrames), r.x, r.y, r.w, r.h,
|
|
reinterpret_cast<const char *>(rdram + ((src + 8u) & 0x1FFFFFFu)), src,
|
|
reinterpret_cast<const char *>(rdram + ((dst + 8u) & 0x1FFFFFFu)), dst, dx, dy);
|
|
if (g_toggles.noCopies)
|
|
return;
|
|
if (src == 0u || dst == 0u)
|
|
{
|
|
++g_stats.textureCopiesMissed;
|
|
return;
|
|
}
|
|
patchTexture(rdram, src, r, dst, dx, dy);
|
|
}
|
|
// The copy itself: the destination record's decoded texture patched with the source record's texels.
|
|
void patchTexture(const uint8_t *rdram, uint32_t src, const Rect &r, uint32_t dst, int32_t dx, int32_t dy)
|
|
{
|
|
if (r.w <= 0 || r.h <= 0)
|
|
return;
|
|
const auto from = recordTexture(rdram, src), to = recordTexture(rdram, dst);
|
|
if (!from || !to)
|
|
return;
|
|
auto patched = std::make_shared<bozo::render::Texture>(*to);
|
|
++g_frameWork.patches;
|
|
g_frameWork.decodedTexels += static_cast<uint64_t>(patched->width) * patched->height;
|
|
// GS memory holds 8-bit pictures as palette indices: the copy moves indices, and the destination shows them
|
|
// through its own palette (a face's expression sheet and the face). Both from the converted store: the
|
|
// source's stored indices, coloured with the destination's colours.
|
|
auto storeEntry = [&](uint32_t record, bool &live) -> const StoredTexture * {
|
|
const uint64_t tex0 = rd64(rdram, record + 0x28u);
|
|
if ((rd32(rdram, record + 4u) >> 16) != 1u || rd32(rdram, record + 0x4Cu) == 0u || ((tex0 >> 20) & 0x3Fu) != 0x13u)
|
|
return nullptr;
|
|
return findStored(rdram, record, rd32(rdram, record) >> 16, rd32(rdram, record + 4u) & 0xFFFFu, live);
|
|
};
|
|
bool srcLive = false, dstLive = false;
|
|
const StoredTexture *srcStored = storeEntry(src, srcLive), *dstStored = storeEntry(dst, dstLive);
|
|
const bool byIndex = srcStored != nullptr && dstStored != nullptr;
|
|
uint32_t colours[256] = {};
|
|
if (byIndex)
|
|
storedColours(rdram, dst, *dstStored, dstLive, colours);
|
|
const uint8_t *srcIndices = byIndex ? g_store.data() + srcStored->offset + 1024 : nullptr;
|
|
uint32_t mapped = 0, unmapped = 0;
|
|
for (int32_t y = 0; y < r.h; ++y)
|
|
for (int32_t x = 0; x < r.w; ++x)
|
|
{
|
|
const int32_t sx = r.x + x, sy = r.y + y, tx = dx + x, ty = dy + y;
|
|
if (sx < 0 || sy < 0 || tx < 0 || ty < 0 || sx >= static_cast<int32_t>(from->width) ||
|
|
sy >= static_cast<int32_t>(from->height) || tx >= static_cast<int32_t>(patched->width) ||
|
|
ty >= static_cast<int32_t>(patched->height))
|
|
continue;
|
|
uint32_t texel = from->rgba[static_cast<size_t>(sy) * from->width + static_cast<size_t>(sx)];
|
|
if (byIndex)
|
|
{
|
|
if (static_cast<uint32_t>(sx) < srcStored->width && static_cast<uint32_t>(sy) < srcStored->height)
|
|
texel = colours[srcIndices[static_cast<size_t>(sy) * srcStored->width + static_cast<size_t>(sx)]], ++mapped;
|
|
else
|
|
++unmapped;
|
|
}
|
|
patched->rgba[static_cast<size_t>(ty) * patched->width + static_cast<size_t>(tx)] = texel;
|
|
}
|
|
if (g_dump2D)
|
|
{
|
|
std::fprintf(stderr, "[dc:dump] copy %s: store %ux%u%s -> %ux%u%s, %u texels through the destination's colours, %u outside the source\n",
|
|
byIndex ? "by index" : "by colour", srcStored ? srcStored->width : 0u, srcStored ? srcStored->height : 0u,
|
|
srcLive ? " (live palette)" : "", dstStored ? dstStored->width : 0u, dstStored ? dstStored->height : 0u,
|
|
dstLive ? " (live palette)" : "", mapped, unmapped);
|
|
// The source, the destination before and after, as PAM files (RGBA, alpha as the GS has it).
|
|
static uint32_t s_copyDump = 0;
|
|
const uint32_t n = s_copyDump++ % 8u;
|
|
// And the source's texels as the game holds them (GS order for a store picture), with its record's width
|
|
// and height, for comparing with the store offline.
|
|
{
|
|
const uint32_t w = rd32(rdram, src) >> 16, h = rd32(rdram, src + 4u) & 0xFFFFu, pixels = rd32(rdram, src + 0x38u);
|
|
char path[96];
|
|
std::snprintf(path, sizeof(path), "D:/DC_Recomp/build/copy%u_src_%ux%u.raw", n, w, h);
|
|
if (FILE *out = pixels != 0u && w * h <= 0x100000u ? std::fopen(path, "wb") : nullptr)
|
|
{
|
|
for (uint32_t i = 0; i < w * h; ++i)
|
|
std::fputc(rdram[(pixels + i) & 0x1FFFFFFu], out);
|
|
std::fclose(out);
|
|
}
|
|
}
|
|
const std::pair<const char *, const bozo::render::Texture *> pictures[] = {
|
|
{"from", from.get()}, {"to", to.get()}, {"patched", patched.get()}};
|
|
for (const auto &[what, picture] : pictures)
|
|
{
|
|
char path[96];
|
|
std::snprintf(path, sizeof(path), "D:/DC_Recomp/build/copy%u_%s.pam", n, what);
|
|
if (FILE *out = std::fopen(path, "wb"))
|
|
{
|
|
std::fprintf(out, "P7\nWIDTH %u\nHEIGHT %u\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", picture->width, picture->height);
|
|
std::fwrite(picture->rgba.data(), 4u, picture->rgba.size(), out);
|
|
std::fclose(out);
|
|
}
|
|
}
|
|
}
|
|
patched->version = ++g_textureVersion;
|
|
auto &slot = g_decoded[dst];
|
|
if (slot.second == to)
|
|
{
|
|
slot.second = patched;
|
|
g_patchedRecords.insert(dst);
|
|
}
|
|
}
|
|
|
|
// The message balloons (ClsMes::MakeFukidashi 0x151AD0, a0 the ClsMes): the game points its frame at the balloon
|
|
// texture (0x299A78), clears it and draws the balloon's shape there (MakeFukidashi_sub 0x150F50: a fan of 15
|
|
// points from its table 0x253FA0, or DrawMaru's ellipses 0x150BB0, then the tail), grey 0xBF with alpha 0x80;
|
|
// DrawMesWin then lays that texture on the screen. Here the shape goes to offscreen target 1, which the
|
|
// balloon texture's sprites sample, then the parchment over it where the shape is.
|
|
void balloonFan(std::vector<bozo::render::Vertex> &out, const std::vector<std::pair<float, float>> &points)
|
|
{
|
|
for (size_t i = 1; i + 1 < points.size(); ++i)
|
|
for (const auto &[x, y] : {points[0], points[i], points[i + 1]})
|
|
{
|
|
bozo::render::Vertex v;
|
|
v.x = kOriginX + x;
|
|
v.y = kOriginY + y;
|
|
v.rgba = flatColour(0xBF, 0xBF, 0xBF, 0x80);
|
|
out.push_back(v);
|
|
}
|
|
}
|
|
// DrawMaru (x, y, w, h, the vertical offset, the wobble mode): an ellipse as a fan from its centre.
|
|
void balloonEllipse(const uint8_t *rdram, std::vector<bozo::render::Vertex> &out, int32_t x, int32_t y, int32_t w, int32_t h,
|
|
int32_t offset, bool wobble)
|
|
{
|
|
const float turn = rdf(rdram, 0x002A1988u), wobbleX = rdf(rdram, 0x002A1874u), wobbleY = rdf(rdram, 0x002A1960u);
|
|
std::vector<std::pair<float, float>> points;
|
|
points.emplace_back(static_cast<float>(x + (w >> 1)), static_cast<float>(y + (h >> 1) - offset));
|
|
uint32_t i = 0;
|
|
for (float f = 0.0f, step = 0.0f; f < 128.0f && i < 512u; f += step, ++i)
|
|
{
|
|
const float angle = turn * f / 128.0f;
|
|
float c = std::cos(angle), sn = std::sin(angle);
|
|
if (wobble && (i & 1u))
|
|
c *= wobbleX, sn *= wobbleY;
|
|
points.emplace_back(static_cast<float>(static_cast<int32_t>((c + 1.0f) * static_cast<float>(w) / 2.0f) + x),
|
|
static_cast<float>(static_cast<int32_t>((sn + 1.0f) * static_cast<float>(h) / 2.0f) + y - offset));
|
|
step = wobble ? rdf(rdram, 0x01CF8FF0u + i * 4u) : 4.0f;
|
|
if (!(step > 0.0f))
|
|
break;
|
|
}
|
|
float c = 1.0f, sn = 0.0f;
|
|
if (wobble && (i & 1u))
|
|
c *= wobbleX, sn *= wobbleY;
|
|
points.emplace_back(static_cast<float>(static_cast<int32_t>((c + 1.0f) * static_cast<float>(w) / 2.0f) + x),
|
|
static_cast<float>(static_cast<int32_t>((sn + 1.0f) * static_cast<float>(h) / 2.0f) + y - offset));
|
|
balloonFan(out, points);
|
|
}
|
|
void balloonHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t cls = getRegU32(ctx, 4);
|
|
const uint32_t balloonRecord = textureRecord(rdram, 0x00299A78u);
|
|
if (balloonRecord == 0u)
|
|
return;
|
|
const uint8_t balloon = targetFor(static_cast<uint32_t>(rd64(rdram, balloonRecord + 0x28u) & 0x3FFFu));
|
|
auto i32 = [&](uint32_t offset) { return static_cast<int32_t>(rd32(rdram, cls + offset)); };
|
|
const float t = rdf(rdram, cls + 0x90u);
|
|
auto lerp = [&](uint32_t a, uint32_t b) { return static_cast<int32_t>(static_cast<float>(i32(a)) + (static_cast<float>(i32(b)) - static_cast<float>(i32(a))) * t); };
|
|
// The target cleared, its depth to the near end: the shape below writes the far end, which the parchment's
|
|
// depth test then reads as the shape (in place of the GS's destination alpha test).
|
|
bozo::render::Material clear;
|
|
clear.textured = false;
|
|
clear.blend = bozo::render::Material::Blend::Opaque;
|
|
clear.depthTest = false;
|
|
clear.depthWrite = true;
|
|
clear.target = balloon;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f, screen().depthMax, 0u);
|
|
drawScreen(clear, vertices);
|
|
// Opaque draws deliberately publish full coverage. Clear coverage
|
|
// separately so the sampled image stays transparent outside the
|
|
// shape, including when this target is reused in the same frame.
|
|
auto clearCoverage = clear;
|
|
clearCoverage.blend = bozo::render::Material::Blend::AlphaOnly;
|
|
clearCoverage.depthWrite = false;
|
|
drawScreen(clearCoverage, vertices);
|
|
vertices.clear();
|
|
// MakeFukidashi_sub: the shape.
|
|
int32_t top = std::min(i32(0x48), i32(0x40));
|
|
if (i32(0x58) != 0)
|
|
{
|
|
top = std::min({top, i32(0x78), i32(0x80), i32(0x88)});
|
|
if (i32(0x38) == 2)
|
|
top = std::min(top, i32(0x88) - 5);
|
|
}
|
|
const float fw = static_cast<float>(i32(0x4C)) * t, fh = static_cast<float>(i32(0x50)) * t;
|
|
float table[30];
|
|
for (uint32_t k = 0; k < 30u; ++k)
|
|
table[k] = rdf(rdram, 0x00253FA0u + k * 4u);
|
|
const int32_t type = i32(0x38);
|
|
const int32_t x0 = lerp(0x3C, 0x44), y0 = lerp(0x40, 0x48);
|
|
if (type == 0)
|
|
{
|
|
const uint32_t u = static_cast<uint32_t>(static_cast<int32_t>(rdf(rdram, 0x01CF8FF0u)));
|
|
std::vector<std::pair<float, float>> points;
|
|
for (uint32_t k = 0; k < 15u; ++k)
|
|
{
|
|
const int32_t px = static_cast<int32_t>(fw * ((u & 1u) == 0u ? table[k * 2] : 1.0f - table[k * 2]));
|
|
const int32_t py = static_cast<int32_t>(fh * (static_cast<int32_t>(u) < 2 ? table[k * 2 + 1] : 1.0f - table[k * 2 + 1]));
|
|
points.emplace_back(static_cast<float>(px + x0), static_cast<float>(py + y0 - top));
|
|
}
|
|
balloonFan(vertices, points);
|
|
}
|
|
else if (type == 1)
|
|
balloonEllipse(rdram, vertices, x0, y0, static_cast<int32_t>(fw), static_cast<int32_t>(fh), top, true);
|
|
else if (type == 2)
|
|
{
|
|
const int32_t half = static_cast<int32_t>(fh) >> 1;
|
|
const float lift = static_cast<float>(i32(0x0C)) * 1.5f;
|
|
balloonEllipse(rdram, vertices, x0, y0, static_cast<int32_t>(fw) - i32(8), static_cast<int32_t>(static_cast<float>(half) + lift), top, false);
|
|
balloonEllipse(rdram, vertices, x0 + i32(8), static_cast<int32_t>(static_cast<float>(y0 + half) - lift),
|
|
static_cast<int32_t>(fw) - i32(8), static_cast<int32_t>(static_cast<float>(half) + lift), top, false);
|
|
}
|
|
else
|
|
{
|
|
const int32_t w = static_cast<int32_t>(fw), h = static_cast<int32_t>(fh);
|
|
const float turn = rdf(rdram, 0x002A1988u);
|
|
std::vector<std::pair<float, float>> points;
|
|
points.emplace_back(static_cast<float>(x0 + (w >> 1)), static_cast<float>(y0 + (h >> 1) - top));
|
|
float step = table[28];
|
|
uint32_t k = 0;
|
|
for (float f = 0.0f; f < 128.0f && k < 512u; f += step, ++k)
|
|
{
|
|
const float angle = turn * f / 128.0f, r = rdf(rdram, 0x01CF90F0u + k * 4u);
|
|
points.emplace_back(static_cast<float>(static_cast<int32_t>((std::cos(angle) * r + 0.5f) * static_cast<float>(w)) + x0),
|
|
static_cast<float>(static_cast<int32_t>((std::sin(angle) * r + 0.5f) * static_cast<float>(h)) + y0 - top));
|
|
step = rdf(rdram, 0x01CF8FF0u + k * 4u);
|
|
if (!(step > 0.0f))
|
|
break;
|
|
}
|
|
const float r0 = rdf(rdram, 0x01CF90F0u);
|
|
points.emplace_back(static_cast<float>(static_cast<int32_t>((r0 + 0.5f) * static_cast<float>(w)) + x0),
|
|
static_cast<float>(static_cast<int32_t>(0.5f * static_cast<float>(h)) + y0 - top));
|
|
balloonFan(vertices, points);
|
|
}
|
|
if (i32(0x58) != 0)
|
|
{
|
|
if (type == 2)
|
|
{
|
|
const int32_t cx = static_cast<int32_t>(static_cast<float>(i32(0x3C)) + (static_cast<float>((i32(0x64) + i32(0x84)) >> 1) - static_cast<float>(i32(0x3C))) * t);
|
|
const int32_t cy = static_cast<int32_t>(static_cast<float>(i32(0x40)) + (static_cast<float>((i32(0x68) + i32(0x88)) >> 1) - static_cast<float>(i32(0x40))) * t);
|
|
balloonEllipse(rdram, vertices, cx - 10, cy - 10, 0x14, 0x14, top, false);
|
|
balloonEllipse(rdram, vertices, lerp(0x3C, 0x84) - 5, lerp(0x40, 0x88) - 5, 10, 10, top, false);
|
|
}
|
|
else
|
|
{
|
|
const std::vector<std::pair<float, float>> tail = {
|
|
{static_cast<float>(lerp(0x3C, 0x84)), static_cast<float>(lerp(0x40, 0x88) - top)},
|
|
{static_cast<float>(lerp(0x3C, 0x74)), static_cast<float>(lerp(0x40, 0x78) - top)},
|
|
{static_cast<float>(lerp(0x3C, 0x7C)), static_cast<float>(lerp(0x40, 0x80) - top)}};
|
|
balloonFan(vertices, tail);
|
|
}
|
|
}
|
|
bozo::render::Material shape;
|
|
shape.textured = false;
|
|
shape.blend = bozo::render::Material::Blend::Alpha;
|
|
shape.depthTest = false;
|
|
shape.depthWrite = true; // z 0: the far end, where the parchment may go
|
|
shape.target = balloon;
|
|
// DC_PROBE_BALLOON=1 (diagnosis): each balloon's fields and what is drawn, every 60th.
|
|
static const bool s_probe = std::getenv("DC_PROBE_BALLOON") != nullptr;
|
|
static uint32_t s_calls = 0;
|
|
if (s_probe && s_calls++ % 60u == 0u)
|
|
{
|
|
float lo[2] = {1e9f, 1e9f}, hi[2] = {-1e9f, -1e9f};
|
|
for (const bozo::render::Vertex &v : vertices)
|
|
{
|
|
lo[0] = std::min(lo[0], v.x), hi[0] = std::max(hi[0], v.x);
|
|
lo[1] = std::min(lo[1], v.y), hi[1] = std::max(hi[1], v.y);
|
|
}
|
|
std::fprintf(stderr, "[dc:balloon] cls %08x type %d t %g size %d x %d (%g x %g) from (%d %d) to (%d %d) top %d tail %d: %zu vertices x %.0f..%.0f y %.0f..%.0f target %u\n",
|
|
cls, type, t, i32(0x4C), i32(0x50), fw, fh, i32(0x3C), i32(0x40), i32(0x44), i32(0x48), top, i32(0x58),
|
|
vertices.size(), lo[0], hi[0], lo[1], hi[1], balloon);
|
|
}
|
|
drawScreen(shape, vertices);
|
|
// The parchment: "fuki256" (0x299A88, 128 x 128 of it) as 5 x 4 sprites over the picture (Myset2DSprite, DC's
|
|
// 640 x 448 view: 128 x 64 GS pixels each), colour 0x80 and the window's fade (+ 0x16D4, at most 0x80) for
|
|
// alpha, blended; MakeFukidashi sets the destination alpha test (DATE, DATM 1) for them, so they land only
|
|
// where the shape left alpha 0x80. Here the depth test does it: the shape is the only far depth.
|
|
if (const uint32_t fill = textureRecord(rdram, 0x00299A88u))
|
|
if (const auto texture = recordTexture(rdram, fill))
|
|
{
|
|
bozo::render::Material parchment;
|
|
parchment.textured = true;
|
|
parchment.tex0 = rd64(rdram, fill + 0x28u);
|
|
parchment.blend = bozo::render::Material::Blend::Alpha;
|
|
parchment.depthTest = true;
|
|
parchment.depthWrite = false;
|
|
parchment.target = balloon;
|
|
const uint32_t fade = static_cast<uint32_t>(std::clamp(i32(0x16D4), 0, 0x80));
|
|
const float u1 = 128.0f / static_cast<float>(texture->width), v1 = 128.0f / static_cast<float>(texture->height);
|
|
std::vector<bozo::render::Vertex> tiles;
|
|
for (int32_t row = 0; row < 4; ++row)
|
|
for (int32_t column = 0; column < 5; ++column)
|
|
quad(tiles, kOriginX + static_cast<float>(column * 128), kOriginY + static_cast<float>(row * 64),
|
|
kOriginX + static_cast<float>(column * 128 + 128), kOriginY + static_cast<float>(row * 64 + 64), 0.0f,
|
|
0x00808080u | fade << 24, 0.0f, 0.0f, u1, v1);
|
|
if (s_probe && s_calls % 60u == 1u)
|
|
{
|
|
uint32_t alphaLo = 255u, alphaHi = 0u;
|
|
for (uint32_t texel : texture->rgba)
|
|
alphaLo = std::min(alphaLo, texel >> 24), alphaHi = std::max(alphaHi, texel >> 24);
|
|
std::fprintf(stderr, "[dc:balloon] parchment %ux%u alpha %u..%u fade %u\n", texture->width, texture->height, alphaLo,
|
|
alphaHi, fade);
|
|
}
|
|
drawScreen(parchment, tiles, texture);
|
|
}
|
|
}
|
|
|
|
// MoveImageTest (0x140660: a1 / a2 / a3 the source's base, width and format, t0 the rectangle, t1 / t2 / t3 the
|
|
// destination's, the 9th / 10th arguments the destination point): the same copy as MGMoveImage between two
|
|
// records' places, given by their GS base (the message windows build their text from the font this way).
|
|
void moveImageTestHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
auto recordAt = [&](uint32_t base, uint32_t psm) {
|
|
const int32_t count = static_cast<int32_t>(rd32(rdram, kTextureManager));
|
|
for (int32_t i = std::min(count, 1023); i >= 0; --i)
|
|
{
|
|
const uint32_t record = kTextureManager + 0x10F8u + static_cast<uint32_t>(i) * 0x50u;
|
|
const uint64_t tex0 = rd64(rdram, record + 0x28u);
|
|
if ((tex0 & 0x3FFFu) == base && ((tex0 >> 20) & 0x3Fu) == psm && rdram[(record + 8u) & 0x1FFFFFFu] != 0u)
|
|
return record;
|
|
}
|
|
return 0u;
|
|
};
|
|
const uint32_t src = recordAt(getRegU32(ctx, 5) & 0x3FFFu, getRegU32(ctx, 7) & 0x3Fu);
|
|
const uint32_t dst = recordAt(getRegU32(ctx, 9) & 0x3FFFu, getRegU32(ctx, 11) & 0x3Fu);
|
|
++g_stats.textureCopies;
|
|
if (src == 0u || dst == 0u)
|
|
{
|
|
++g_stats.textureCopiesMissed;
|
|
return;
|
|
}
|
|
patchTexture(rdram, src, rectAt(rdram, getRegU32(ctx, 8)), dst, static_cast<int32_t>(stackArg(rdram, ctx, 0)),
|
|
static_cast<int32_t>(stackArg(rdram, ctx, 1)));
|
|
}
|
|
// CFireOmni::DrawFire (0x161AC0): explicit additive sprite blend, 0x48: Cs As + Cd.
|
|
RecompiledFunction g_drawFire = nullptr;
|
|
void drawFireHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
static const bool probe = [] { const char *v = std::getenv("DC_PROBE_FIRE"); return v && v[0] == '1'; }();
|
|
if (probe)
|
|
{
|
|
static uint64_t calls = 0;
|
|
++calls;
|
|
// Bounded coverage samples, not an exact gameplay call total.
|
|
if (calls <= 16u || (calls % 300u == 0u && calls <= 14400u))
|
|
{
|
|
const uint32_t fire = getRegU32(ctx, 4);
|
|
std::fprintf(stderr, "[dc:fire] frame %llu mode %u counter %d textures %08x/%08x\n",
|
|
static_cast<unsigned long long>(g_publishedFrames), getRegU32(ctx, 9),
|
|
static_cast<int32_t>(rd32(rdram, fire + 0x1Cu)), rd32(rdram, fire + 0x34u), rd32(rdram, fire + 0x38u));
|
|
}
|
|
}
|
|
const uint64_t saved = g_alpha2D;
|
|
g_alpha2D = (g_alpha2D & ~0xFFull) | 0x48u;
|
|
g_drawFire(rdram, ctx, runtime);
|
|
g_alpha2D = saved;
|
|
}
|
|
|
|
// Optional, bounded sky observation. No frame dumps or RAM hashing:
|
|
// record the actual sky clock and camera basis to distinguish the
|
|
// time-of-day fade from camera-dependent changes during a play run.
|
|
RecompiledFunction g_drawSky = nullptr;
|
|
void skyProbeHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
static uint32_t calls = 0, samples = 0;
|
|
static const float fixedTime = [] { const char *v=std::getenv("DC_SKY_TIME");return v?std::strtof(v,nullptr):-1.0f; }();
|
|
if (fixedTime >= 0 && fixedTime <= 12) ctx->fu[12]=std::bit_cast<uint32_t>(fixedTime);
|
|
g_inSky = true;g_skyDrawIndex = 0;
|
|
g_sampleSkyDraws = calls++ % 120u == 0u && samples < 64u;
|
|
if (g_sampleSkyDraws)
|
|
{
|
|
++samples;
|
|
constexpr uint32_t cameraMatrix = 0x01C75520u + 0x10u;
|
|
std::fprintf(stderr, "[dc:sky] frame %llu time %.6f camera %08x basis (%g %g %g) (%g %g %g) (%g %g %g)\n",
|
|
static_cast<unsigned long long>(g_publishedFrames), std::bit_cast<float>(ctx->fu[12]), getRegU32(ctx, 7),
|
|
rdf(rdram,cameraMatrix), rdf(rdram,cameraMatrix+4), rdf(rdram,cameraMatrix+8),
|
|
rdf(rdram,cameraMatrix+16), rdf(rdram,cameraMatrix+20), rdf(rdram,cameraMatrix+24),
|
|
rdf(rdram,cameraMatrix+32), rdf(rdram,cameraMatrix+36), rdf(rdram,cameraMatrix+40));
|
|
}
|
|
g_drawSky(rdram, ctx, runtime);
|
|
g_inSky = false;g_sampleSkyDraws = false;
|
|
}
|
|
|
|
// MGGetFBuffTex / MGGetFBuffBackTex (0x12F130 / 0x12F1A0, a0 the sceGsTex0 they fill): where the game's frame
|
|
// and the frame before are. The originals read the FRAME images sceGsSetDefDBuff left in MGInit's record (no longer
|
|
// made); the two frames are fixed: 640 wide, PSMCT32, at FBP 0x46 and 0, the half DBuffID (gp-0x7440) names being
|
|
// drawn. Only their identity matters (the game's own texture calls compare these TEX0 words): the same words.
|
|
uint64_t frameTex0(uint32_t fbp) { return 0x228000000ull | (10ull << 14) | (static_cast<uint64_t>(fbp & 0x1FFu) << 5); }
|
|
constexpr uint32_t kFrameFbp[2] = {0x46u, 0x00u};
|
|
uint32_t dbuffId(const uint8_t *rdram, R5900Context *ctx) { return rd32(rdram, getRegU32(ctx, 28) - 0x7440u); }
|
|
void getFrameTexHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
const uint64_t tex0 = frameTex0(kFrameFbp[dbuffId(rdram, ctx) == 0u ? 0 : 1]);
|
|
wr64(rdram, getRegU32(ctx, 4), tex0);
|
|
g_frameBase = static_cast<uint32_t>(tex0 & 0x3FFFu);
|
|
g_backAsked = false;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
void getBackTexHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
const uint64_t tex0 = frameTex0(kFrameFbp[dbuffId(rdram, ctx) == 0u ? 1 : 0]);
|
|
wr64(rdram, getRegU32(ctx, 4), tex0);
|
|
g_backBase = static_cast<uint32_t>(tex0 & 0x3FFFu);
|
|
g_backAsked = true;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
// MGStretchMoveImage (0x12F430: a0 / a1 the source's TEX0 and rectangle, a2 / a3 the destination's; rectangles in
|
|
// 1/16 pixels): the game stretching its frame (or the frame before, or a work texture) into a work texture. Here
|
|
// a draw of that source into the destination's offscreen target, stretched. Texture to texture copies (none
|
|
// seen so far) are counted and not made.
|
|
void stretchMoveHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t srcBase = static_cast<uint32_t>(rd64(rdram, getRegU32(ctx, 4)) & 0x3FFFu);
|
|
const uint32_t dstBase = static_cast<uint32_t>(rd64(rdram, getRegU32(ctx, 6)) & 0x3FFFu);
|
|
const Rect from = rectAt(rdram, getRegU32(ctx, 5)), to = rectAt(rdram, getRegU32(ctx, 7));
|
|
bozo::render::Material material;
|
|
if (!sampleMade(srcBase, material) || dstBase == g_frameBase || dstBase == g_backBase)
|
|
{
|
|
++g_stats.stretchesMissed;
|
|
return;
|
|
}
|
|
material.target = targetFor(dstBase);
|
|
// The work picture at the PS2's size (the game's 640 x 224 frame copy): the title draws it back into the
|
|
// frame each frame before copying the frame into it again, a feedback loop whose blur is that of a 640 x
|
|
// 224 picture filtered each frame (at the window's resolution it blurred several times less).
|
|
bozo::render::Renderer::instance().setTargetSize(material.target, static_cast<uint32_t>(frameW() + 0.5f), 224);
|
|
// A 640 x 224 picture from now on: a place the menu's MGMoveFrameBuffImage filled with both fields (448 rows)
|
|
// and the town copies its frame into again each frame (the water's "work") is sampled as 224 rows again.
|
|
g_targetRows[material.target] = 224.0f;
|
|
material.blend = bozo::render::Material::Blend::Opaque;
|
|
material.depthTest = false;
|
|
material.depthWrite = false;
|
|
material.clampU = material.clampV = true;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
const CopySpan span = copySpan(static_cast<float>(to.x) / 16.0f, static_cast<float>(to.x + to.w) / 16.0f,
|
|
static_cast<float>(from.x) / 16.0f, static_cast<float>(from.x + from.w) / 16.0f);
|
|
quad(vertices, span.x0, kOriginY + static_cast<float>(to.y) / 16.0f, span.x1, kOriginY + static_cast<float>(to.y + to.h) / 16.0f,
|
|
0.0f, 0x80808080u, span.u0, static_cast<float>(from.y) / 16.0f / 224.0f, span.u1,
|
|
static_cast<float>(from.y + from.h) / 16.0f / 224.0f);
|
|
drawScreen(material, vertices);
|
|
++g_stats.stretches;
|
|
seq('S');
|
|
if (g_dump2D)
|
|
std::fprintf(stderr, "[dc:dump] stretch base %x (%d,%d %dx%d) -> base %x target %u (%d,%d %dx%d), 1/16 pixels\n", srcBase, from.x, from.y,
|
|
from.w, from.h, dstBase, material.target, to.x, to.y, to.w, to.h);
|
|
static int s_logged = 0;
|
|
if (std::getenv("DC_PROBE_2D") && s_logged++ < 6)
|
|
std::fprintf(stderr, "[dc:2d] stretch base %x (frame %x back %x) %d,%d %dx%d -> base %x target %u %d,%d %dx%d\n", srcBase, g_frameBase,
|
|
g_backBase, from.x, from.y, from.w, from.h, dstBase, material.target, to.x, to.y, to.w, to.h);
|
|
}
|
|
|
|
// blendTextuerTest (0x162D80: a1 a work texture's place (TBP), a2 its width, a3 its format; t0 a rectangle of the
|
|
// frame (pixels, field lines); t1 a mask texture, t2 / t3 its destination and source; f12 the wave's amplitude
|
|
// (/ 10000), f13 its phase): the dungeon torches' heat haze (CFireOmni::DrawRaster). In the GS packet: the frame's
|
|
// rectangle copied into the place's top-left two lines at a time, each band shifted sideways by the wave
|
|
// (waveAnimeCnt 0x1D18980, eight entries from the phase, times a random factor up to 1.3 drawn anew every eight
|
|
// bands); then the mask texture drawn there with ALPHA (0 - 0) x FIX + Cd, which keeps the colours and writes the
|
|
// mask's alpha. The "blender" sprite after it lays the patch back over the torch through that alpha.
|
|
uint32_t g_hazeRandom = 0x12345678u;
|
|
void blendTextureTestHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t place = getRegU32(ctx, 5) & 0x3FFFu;
|
|
const Rect frame = rectAt(rdram, getRegU32(ctx, 8));
|
|
const uint32_t mask = getRegU32(ctx, 9);
|
|
const Rect maskTo = rectAt(rdram, getRegU32(ctx, 10)), maskFrom = rectAt(rdram, getRegU32(ctx, 11));
|
|
const float amplitude = std::bit_cast<float>(ctx->fu[12]) / 10000.0f, phase = std::bit_cast<float>(ctx->fu[13]);
|
|
bozo::render::Material copy;
|
|
if (!sampleMade(g_frameBase, copy))
|
|
return;
|
|
const uint8_t target = targetFor(place | kHazePlace);
|
|
g_blendedLast[place] = false;
|
|
g_hazeLast[place] = true;
|
|
copy.target = target;
|
|
copy.blend = bozo::render::Material::Blend::Opaque;
|
|
copy.depthTest = false;
|
|
copy.depthWrite = false;
|
|
copy.clampU = copy.clampV = true;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
float factor = 0.0f;
|
|
int32_t k = 0;
|
|
for (int32_t row = 0; row < frame.h; row += 2)
|
|
{
|
|
int32_t index = static_cast<int32_t>(phase) + k;
|
|
if (index > 7)
|
|
index -= 8;
|
|
const float wave = rdf(rdram, 0x01D18980u + static_cast<uint32_t>(std::clamp(index, 0, 31)) * 4u);
|
|
const int32_t offset = static_cast<int32_t>(amplitude * factor * wave * 16.0f);
|
|
const int32_t x0 = std::max(frame.x * 16 + offset, 0), x1 = std::min(offset + (frame.x + frame.w) * 16, 0x27F0);
|
|
// Widescreen: the whole frame waves, its offsets in proportion (u 0..1 is the whole frame either way).
|
|
const float w = static_cast<float>(frame.w);
|
|
quad(vertices, spanLeft(0.0f, w), kOriginY + static_cast<float>(row), spanRight(0.0f, w),
|
|
kOriginY + static_cast<float>(row + 2), 0.0f, 0x80808080u, static_cast<float>(x0) / 16.0f / 640.0f,
|
|
static_cast<float>(frame.y + row) / copy.frameHeight, static_cast<float>(x1) / 16.0f / 640.0f,
|
|
static_cast<float>(frame.y + row + 2) / copy.frameHeight);
|
|
if (++k > 7)
|
|
{
|
|
g_hazeRandom = g_hazeRandom * 1103515245u + 12345u;
|
|
factor = rdf(rdram, 0x002A1DA8u) * static_cast<float>((g_hazeRandom >> 1) & 0x7FFFFFFFu) / 2147483648.0f;
|
|
k = 0;
|
|
}
|
|
}
|
|
drawScreen(copy, vertices);
|
|
if (g_dump2D)
|
|
{
|
|
const auto texture = mask != 0u ? recordTexture(rdram, mask) : nullptr;
|
|
uint32_t alphaLo = 255u, alphaHi = 0u;
|
|
if (texture)
|
|
for (uint32_t texel : texture->rgba)
|
|
alphaLo = std::min(alphaLo, texel >> 24), alphaHi = std::max(alphaHi, texel >> 24);
|
|
std::fprintf(stderr, "[dc:dump] haze (%d,%d %dx%d) of the frame, mask %08x \"%.16s\" %s alpha %u..%u from (%d,%d %dx%d) to (%d,%d %dx%d)\n",
|
|
frame.x, frame.y, frame.w, frame.h, mask, mask != 0u ? reinterpret_cast<const char *>(rdram + ((mask + 8u) & 0x1FFFFFFu)) : "",
|
|
texture ? "decoded" : "NOT decoded", alphaLo, alphaHi, maskFrom.x, maskFrom.y, maskFrom.w, maskFrom.h, maskTo.x, maskTo.y,
|
|
maskTo.w, maskTo.h);
|
|
}
|
|
// The mask's alpha into the place, its colours kept.
|
|
if (mask != 0u)
|
|
if (const auto texture = recordTexture(rdram, mask))
|
|
{
|
|
bozo::render::Material alpha;
|
|
alpha.target = target;
|
|
alpha.textured = true;
|
|
alpha.tex0 = rd64(rdram, mask + 0x28u);
|
|
alpha.blend = bozo::render::Material::Blend::AlphaOnly;
|
|
alpha.depthTest = false;
|
|
alpha.depthWrite = false;
|
|
alpha.clampU = alpha.clampV = true;
|
|
std::vector<bozo::render::Vertex> masked;
|
|
const float tw = static_cast<float>(texture->width), th = static_cast<float>(texture->height);
|
|
quad(masked, kOriginX + static_cast<float>(maskTo.x), kOriginY + static_cast<float>(maskTo.y),
|
|
kOriginX + static_cast<float>(maskTo.x + maskTo.w), kOriginY + static_cast<float>(maskTo.y + maskTo.h), 0.0f, 0x80808080u,
|
|
static_cast<float>(maskFrom.x) / tw, static_cast<float>(maskFrom.y) / th,
|
|
static_cast<float>(maskFrom.x + maskFrom.w) / tw, static_cast<float>(maskFrom.y + maskFrom.h) / th);
|
|
drawScreen(alpha, masked, texture);
|
|
}
|
|
}
|
|
|
|
// blendTextuer (0x162580: a1 a work texture's place (TBP), a2 its width, a3 its format; t0 texture A, t1 / t2 its
|
|
// destination and source; t3 texture B, the stack's first two its destination and source): the game points its
|
|
// frame at the work texture, fills A's destination grey (an untextured sprite, 0x80), draws A there with the
|
|
// current ALPHA, then B with ALPHA 0x09 (Cd x As + Cs), and points its frame back. The work texture is the
|
|
// offscreen target that stands for that place; a sprite of it shows it (the attract demo's PUSH START plate).
|
|
void blendTextureHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t place = getRegU32(ctx, 5) & 0x3FFFu;
|
|
const uint32_t textureA = getRegU32(ctx, 8), textureB = getRegU32(ctx, 11);
|
|
const Rect toA = rectAt(rdram, getRegU32(ctx, 9)), fromA = rectAt(rdram, getRegU32(ctx, 10));
|
|
const Rect toB = rectAt(rdram, stackArg(rdram, ctx, 0)), fromB = rectAt(rdram, stackArg(rdram, ctx, 1));
|
|
// A picture of its own (kBlendedPlace | place), apart from what else the game puts in that place: the
|
|
// dungeons' torch halos are blended into the top-left 128 x 128 of "work" (0x1A40), which also takes the
|
|
// frame's stretched copy. On the PS2 blendTextuer reaches the GS at once while the "blender" sprites that show
|
|
// it go out with the frame's packet, after it; here they come first (the game calls them first) and read the
|
|
// place as the frame before left it, the frame's copy on some frames (dark squares over the torches).
|
|
const uint8_t target = targetFor(place | kBlendedPlace);
|
|
g_blendedExtent[place] = {std::max(toA.x + toA.w, toB.x + toB.w), std::max(toA.y + toA.h, toB.y + toB.h)};
|
|
g_blendedLast[place] = true;
|
|
g_hazeLast[place] = false;
|
|
// The work texture's rows are the GS's (y = 1936 + y, not halved as the frame's 448-line view).
|
|
auto sprite = [&](const Rect &to, const Rect &from, uint32_t record, bozo::render::Material::Blend blend, bool textured) {
|
|
bozo::render::Material material;
|
|
material.target = target;
|
|
material.blend = blend;
|
|
material.depthTest = false;
|
|
material.depthWrite = false;
|
|
material.clampU = material.clampV = true;
|
|
std::shared_ptr<const bozo::render::Texture> texture;
|
|
if (textured)
|
|
{
|
|
if (record == 0u || !(texture = recordTexture(rdram, record)))
|
|
return;
|
|
material.tex0 = rd64(rdram, record + 0x28u);
|
|
}
|
|
material.textured = textured;
|
|
const float tw = texture ? static_cast<float>(texture->width) : 1.0f, th = texture ? static_cast<float>(texture->height) : 1.0f;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
quad(vertices, kOriginX + static_cast<float>(to.x), kOriginY + static_cast<float>(to.y), kOriginX + static_cast<float>(to.x + to.w),
|
|
kOriginY + static_cast<float>(to.y + to.h), 0.0f, textured ? 0x80808080u : flatColour(0x80u, 0x80u, 0x80u, 0x80u),
|
|
static_cast<float>(from.x) / tw, static_cast<float>(from.y) / th, static_cast<float>(from.x + from.w) / tw,
|
|
static_cast<float>(from.y + from.h) / th);
|
|
drawScreen(material, vertices, texture);
|
|
};
|
|
sprite(toA, fromA, 0u, bozo::render::Material::Blend::Opaque, false);
|
|
sprite(toA, fromA, textureA, bozo::render::blendOf(g_alpha2D), true);
|
|
sprite(toA, fromA, textureA, bozo::render::Material::Blend::AlphaOnly, true);
|
|
sprite(toB, fromB, textureB, bozo::render::Material::Blend::DestinationBySource, true);
|
|
// The colour equation does not accumulate coverage: the final B
|
|
// sprite writes its own alpha. Keep that alpha separately from the
|
|
// grey initialization and RGB blend, so transparent flame borders
|
|
// remain transparent when sampled by the fogged additive sprite.
|
|
sprite(toB, fromB, textureB, bozo::render::Material::Blend::AlphaOnly, true);
|
|
// The frame dump: both textures (name, TEX0, alpha range) and where they go.
|
|
if (g_dump2D)
|
|
for (const uint32_t record : {textureA, textureB})
|
|
{
|
|
const auto texture = record != 0u ? recordTexture(rdram, record) : nullptr;
|
|
uint32_t alphaLo = 255u, alphaHi = 0u, rgbHi = 0u;
|
|
if (texture)
|
|
for (uint32_t texel : texture->rgba)
|
|
{
|
|
alphaLo = std::min(alphaLo, texel >> 24), alphaHi = std::max(alphaHi, texel >> 24);
|
|
rgbHi = std::max({rgbHi, texel & 0xFFu, (texel >> 8) & 0xFFu, (texel >> 16) & 0xFFu});
|
|
}
|
|
const Rect &to = record == textureA ? toA : toB, &from = record == textureA ? fromA : fromB;
|
|
std::fprintf(stderr, "[dc:dump] blendTextuer place %x target %u: %s \"%.16s\" tex0 %016llx %ux%u alpha %u..%u rgb max %u, ALPHA %llx, from (%d,%d %dx%d) to (%d,%d %dx%d)\n",
|
|
place, target, record == textureA ? "A" : "B", record != 0u ? reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)) : "",
|
|
record != 0u ? static_cast<unsigned long long>(rd64(rdram, record + 0x28u)) : 0ull, texture ? texture->width : 0u,
|
|
texture ? texture->height : 0u, alphaLo, alphaHi, rgbHi, static_cast<unsigned long long>(g_alpha2D), from.x, from.y,
|
|
from.w, from.h, to.x, to.y, to.w, to.h);
|
|
// The decoded texture itself, as a PAM file (RGBA, alpha as the GS has it) beside the dump flag.
|
|
if (texture)
|
|
if (FILE *out = std::fopen(record == textureA ? "D:/DC_Recomp/build/blend_A.pam" : "D:/DC_Recomp/build/blend_B.pam", "wb"))
|
|
{
|
|
std::fprintf(out, "P7\nWIDTH %u\nHEIGHT %u\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", texture->width, texture->height);
|
|
std::fwrite(texture->rgba.data(), 4u, texture->rgba.size(), out);
|
|
std::fclose(out);
|
|
}
|
|
}
|
|
static int s_logged = 0;
|
|
if (std::getenv("DC_PROBE_2D") && s_logged++ < 6)
|
|
std::fprintf(stderr, "[dc:2d] blendTextuer place %x target %u: A %08x (%d,%d %dx%d) B %08x (%d,%d %dx%d)\n", place, target, textureA,
|
|
toA.x, toA.y, toA.w, toA.h, textureB, toB.x, toB.y, toB.w, toB.h);
|
|
}
|
|
|
|
// MGMoveFrameBuffImage (0x12F970: a0 the destination's TEX0): the two fields of the frame shown last, interleaved
|
|
// line by line into a 640 x 448 picture (the menus' backdrop: "frame_image", drawn darkened behind them). The
|
|
// native frame is whole already: the frame presented last, copied into that place's target, as 448 rows.
|
|
void moveFrameBuffHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t dstBase = static_cast<uint32_t>(rd64(rdram, getRegU32(ctx, 4)) & 0x3FFFu);
|
|
if (dstBase == g_frameBase || dstBase == g_backBase)
|
|
return;
|
|
bozo::render::Material material;
|
|
material.target = targetFor(dstBase);
|
|
g_targetRows[material.target] = 448.0f;
|
|
material.textured = true;
|
|
material.fromFrame = 1;
|
|
material.source = bozo::render::Material::kPreviousFrame;
|
|
material.frameWidth = 640;
|
|
material.frameHeight = 224;
|
|
material.blend = bozo::render::Material::Blend::Opaque;
|
|
material.depthTest = false;
|
|
material.depthWrite = false;
|
|
material.clampU = material.clampV = true;
|
|
std::vector<bozo::render::Vertex> vertices;
|
|
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f, 0.0f, 0x80808080u);
|
|
drawScreen(material, vertices);
|
|
}
|
|
|
|
// SetClut (0x14C5A0: a1 the texture whose CBP takes the palette, a2 the palette).
|
|
void setClutHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t texture = getRegU32(ctx, 5);
|
|
if (texture != 0u)
|
|
g_clutOverride[static_cast<uint32_t>((rd64(rdram, texture + 0x28u) >> 37) & 0x3FFFu)] = getRegU32(ctx, 6);
|
|
}
|
|
|
|
// The ALPHA the game sets for its 2D (setAlphaFlag 0x15BC20: a1 its sceGsAlpha; MGSetGsALPHA 0x12EF90: a0).
|
|
// DC_PROBE_2D=1: each distinct (routine, caller, ALPHA) that sets the 2D blend, once.
|
|
void noteAlpha(const char *who, R5900Context *ctx)
|
|
{
|
|
static const bool s_probe = [] { const char *e = std::getenv("DC_PROBE_2D"); return e && e[0] == '1'; }();
|
|
static std::unordered_map<uint64_t, bool> s_seen;
|
|
const uint64_t key = g_alpha2D ^ static_cast<uint64_t>(getRegU32(ctx, 31)) << 40;
|
|
if (s_probe && !s_seen[key])
|
|
{
|
|
s_seen[key] = true;
|
|
std::fprintf(stderr, "[dc:2d] ALPHA %llx from %s, called from %08x\n", static_cast<unsigned long long>(g_alpha2D), who,
|
|
getRegU32(ctx, 31));
|
|
}
|
|
}
|
|
// MGDrawShadow / MGDrawShadowFast / MGDrawShadowFast2 (0x1305F0 / 0x1303B0 / 0x1304D0): the characters' blob
|
|
// shadows set their own ALPHA (0x2A) and restore the state with a prebuilt packet (sceVif1PkCall), which is not
|
|
// read: the 2D blend is kept as it was around them. MGDrawShade (0x130760) sets ALPHA 0x2A for the shade it draws
|
|
// (DAT 0x1C75840 = 8) and leaves it: called by CMapObject::DrawShade directly (Georama, the towns' objects), the 2D
|
|
// drawn after it (the day clock, the hand cursor) came out opaque, their transparent texels magenta and black.
|
|
struct ShadowCall
|
|
{
|
|
uint32_t address;
|
|
RecompiledFunction original;
|
|
};
|
|
ShadowCall g_shadowCalls[] = {{0x001305F0u, nullptr}, {0x001303B0u, nullptr}, {0x001304D0u, nullptr}, {0x00130760u, nullptr}};
|
|
void blobShadowHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint64_t saved = g_alpha2D;
|
|
for (ShadowCall &call : g_shadowCalls)
|
|
if (call.address == ctx->pc && call.original)
|
|
{
|
|
call.original(rdram, ctx, runtime);
|
|
break;
|
|
}
|
|
g_alpha2D = saved;
|
|
}
|
|
// SetEnv (0x140DA0): the frame's default state, ALPHA among it (mgAlpha, gp - 0x7408).
|
|
void setEnvHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_gp = getRegU32(ctx, 28);
|
|
g_alpha2D = rd64(rdram, g_gp - 0x7408u);
|
|
noteAlpha("SetEnv", ctx);
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
void setAlphaFlagHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
g_alpha2D = rd64(rdram, getRegU32(ctx, 5));
|
|
noteAlpha("setAlphaFlag", ctx);
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
void setGsAlphaHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
|
|
{
|
|
// A null argument restores the game's default, mgAlpha (gp - 0x7408), as MGSetGsALPHA does.
|
|
const uint32_t alpha = getRegU32(ctx, 4);
|
|
g_alpha2D = rd64(rdram, alpha != 0u ? alpha : getRegU32(ctx, 28) - 0x7408u);
|
|
noteAlpha(alpha != 0u ? "MGSetGsALPHA" : "MGSetGsALPHA(default)", ctx);
|
|
setReturnS32(ctx, 0);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
|
|
uint64_t g_retiredStateCalls = 0;
|
|
void discardConsoleStateHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
// MGSetGsTEST/ZBUF/TEXA only serialized a register argument into the frame
|
|
// packet. They changed no game data; native draw materials are explicit.
|
|
// Even the optional argument/default scalar need not be read here.
|
|
++g_retiredStateCalls;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
|
|
uint64_t g_retiredEnvelopes = 0, g_nativeWindowRects = 0;
|
|
void discardConsoleEnvelopeHook(uint8_t *, R5900Context *ctx, Runtime *)
|
|
{
|
|
// openGiftag/closeGiftag only wrapped obsolete packet output. Native
|
|
// draws submit directly and need neither a packet pointer nor a tag.
|
|
++g_retiredEnvelopes;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
void setWindowRectHook(uint8_t *, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
// Keep CRect's four full-width game fields. The original additionally
|
|
// packed a hardware scissor command, which has no native consumer.
|
|
std::array<uint32_t, 4> rectangle{0, 0, 640, 224};
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
if (ctx->pc == 0x0012DAE0u)
|
|
std::memcpy(rectangle.data(), guest.in(getRegU32(ctx, 4), sizeof(rectangle)), sizeof(rectangle));
|
|
guest.write(0x01C75510u, rectangle.data(), sizeof(rectangle));
|
|
++g_nativeWindowRects;
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
}
|
|
|
|
// VSyncCallBack_Load (0x154320): while the game loads, its vsync callback draws the loading picture (the SCE and
|
|
// Level-5 logos at boot) and shows it itself; the main loop, which publishes the native frame, is waiting. The
|
|
// native frame built since the last one is published from there too.
|
|
// Only while the main loop is stalled (no frame of its own for 100 ms): the callback stays installed outside
|
|
// loading too, and a publish from it then cut the main loop's frame in two (a frame shown half built).
|
|
RecompiledFunction g_vsyncLoad = nullptr;
|
|
std::atomic<int64_t> g_lastMainPublish{0}; // steady clock, ms
|
|
bool g_publishingFromLoad = false;
|
|
int64_t nowMs()
|
|
{
|
|
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
|
}
|
|
void vsyncLoadHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
// DC_PROBE_LOADCARD=1 (diagnosis): the callback's state every 30 calls (end_flag, nl_start_cnt, map_title_no,
|
|
// col_cnt) and how long the main loop has not published.
|
|
static const bool s_probe = std::getenv("DC_PROBE_LOADCARD") != nullptr;
|
|
static uint32_t s_calls = 0;
|
|
if (s_probe && s_calls++ % 30u == 0u)
|
|
{
|
|
float colour;
|
|
std::memcpy(&colour, rdram + 0x2A25C0u, 4);
|
|
const uint32_t card = 0x01CFB390u; // the picture the callback draws
|
|
std::fprintf(stderr, "[dc:load] end %u start %d title %x colour %g, main loop quiet %lld ms; picture \"%.16s\" tex0 %016llx pixels %08x %s\n",
|
|
rd32(rdram, 0x2A1ED0u), static_cast<int32_t>(rd32(rdram, 0x2A25BCu)), rd32(rdram, 0x2A25D0u), colour,
|
|
static_cast<long long>(nowMs() - g_lastMainPublish.load(std::memory_order_relaxed)),
|
|
reinterpret_cast<const char *>(rdram + card + 8u), static_cast<unsigned long long>(rd64(rdram, card + 0x28u)),
|
|
rd32(rdram, card + 0x38u), recordTexture(rdram, card) ? "decoded" : "NOT decoded");
|
|
std::fprintf(stderr, "[dc:load] record words %08x %08x, palette %08x, +0x4c %08x\n", rd32(rdram, card), rd32(rdram, card + 4u),
|
|
rd32(rdram, card + 0x48u), rd32(rdram, card + 0x4Cu));
|
|
}
|
|
g_vsyncLoad(rdram, ctx, runtime);
|
|
if (bozo::port::deterministic(runtime) || nowMs() - g_lastMainPublish.load(std::memory_order_relaxed) > 100)
|
|
{
|
|
g_publishingFromLoad = true;
|
|
::dc::native::publish();
|
|
bozo::port::frameEnd(runtime, ctx);
|
|
g_publishingFromLoad = false;
|
|
}
|
|
}
|
|
|
|
RecompiledFunction g_textureInfoTm2 = nullptr, g_textureInfoFile = nullptr;
|
|
void pinRecord(const uint8_t *rdram, uint32_t record)
|
|
{
|
|
g_pinned.erase(record);
|
|
g_decoded.erase(record);
|
|
if (auto texture = recordTexture(rdram, record))
|
|
g_pinned[record] = {rd32(rdram, record + 0x38u), rd64(rdram, record + 0x28u), texture};
|
|
}
|
|
// EnterFixTexture (0x1320E0: a1 the name, a2 the pixels, a3 / t0 the size, t1 the kind, t2 the palette; the 14th
|
|
// argument set when 8-bit texels are in GS order): sends a fixed texture (the menus' "stayframe", "window"...) to
|
|
// GS memory once, from a buffer the record never points at (+ 0x38 and + 0x48 stay as they were). Decoded right
|
|
// after it, with those pointers put in the record for the decode and the record then restored as it was.
|
|
uint64_t g_nativeFixedTextures = 0, g_nativeFixedZTextures = 0;
|
|
uint32_t freeTextureRecord(bozo::libs::Guest &guest, uint32_t manager)
|
|
{
|
|
guest.in(manager, 0x10f8u + 196u * 0x50u);
|
|
for (uint32_t i = 1; i < 196u; ++i)
|
|
{
|
|
const uint32_t record = manager + 0x10f8u + i * 0x50u;
|
|
if (!guest.read8(record + 8u)) return record;
|
|
}
|
|
throw std::runtime_error("native fixed texture: no free texture record");
|
|
}
|
|
uint64_t signedWord(uint32_t v) { return static_cast<uint64_t>(static_cast<int64_t>(static_cast<int32_t>(v))); }
|
|
void insertFixedTexture(R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
const uint32_t manager = guest.arg(0), nameAt = guest.arg(1), pixels = guest.arg(2);
|
|
const auto name = guest.string(nameAt, 32);
|
|
if (name.empty()) return;
|
|
const uint32_t kind = guest.arg(5);
|
|
if (kind != 1u && kind != 3u && kind != 4u) return;
|
|
const uint32_t width = guest.arg(3), height = guest.arg(4);
|
|
if (!width || !height || width > 65535u || height > 65535u ||
|
|
static_cast<uint64_t>(width) * height * kind > 0x7fffffffu)
|
|
throw std::runtime_error("native fixed texture: invalid dimensions");
|
|
const bool mipmaps = pixels && guest.arg(8) && guest.arg(9);
|
|
const uint64_t filter = mipmaps ? guest.arg64(12) : 0;
|
|
const uint32_t bytes = width * height * kind;
|
|
uint32_t extent = bytes >> 8;
|
|
if (mipmaps) extent += (bytes >> 12) + (bytes >> 10);
|
|
extent = (extent + 31u) & ~31u;
|
|
// Preserve the caller's allocation/record ABI, without creating an upload,
|
|
// retaining GS memory or reading any mip/pixel stream to serialize it.
|
|
const uint32_t record = freeTextureRecord(guest, manager);
|
|
uint32_t remaining = guest.read32(manager + 20u) - extent;
|
|
const uint32_t base = remaining;
|
|
uint32_t paletteBase = 0;
|
|
if ((pixels && kind == 1u) || (!pixels && kind != 4u))
|
|
{
|
|
paletteBase = pixels ? remaining - 32u : remaining;
|
|
remaining -= 32u;
|
|
}
|
|
const auto exponent = [](uint32_t n) { uint32_t e = 0, power = 1; while (power < n) { power <<= 1; ++e; } return e; };
|
|
const uint32_t format = kind == 1u ? 0x13u : kind == 3u ? 1u : 0u;
|
|
uint64_t descriptor = signedWord(base) | (static_cast<uint64_t>(std::max(1u, width >> 6)) << 14) |
|
|
(static_cast<uint64_t>(format) << 20) | (static_cast<uint64_t>(exponent(width)) << 26) |
|
|
(static_cast<uint64_t>(exponent(height)) << 30) | (1ull << 34);
|
|
if (kind == 1u) descriptor |= signedWord(paletteBase) << 37 | (1ull << 61);
|
|
guest.write(record + 8u, name.c_str(), static_cast<uint32_t>(name.size() + 1u));
|
|
guest.write16(record, 0xffffu);
|
|
guest.write16(record + 2u, static_cast<uint16_t>(width));
|
|
guest.write16(record + 4u, static_cast<uint16_t>(height));
|
|
guest.write16(record + 6u, static_cast<uint16_t>(kind));
|
|
guest.write(record + 0x28u, &descriptor, 8);
|
|
if (pixels && kind != 1u) guest.write32(record + 0x48u, 0);
|
|
if (mipmaps)
|
|
{
|
|
const uint64_t mode = filter ? ((((filter >> 16) & 0x1fu) >> 3) << 19) | 0x368u |
|
|
(((filter >> 32) & 0xfffu) << 32) : 0xffffff8800000368ull;
|
|
guest.write(record + 0x30u, &mode, 8);
|
|
}
|
|
guest.write32(manager + 20u, remaining);
|
|
guest.write32(manager, 195u);
|
|
++g_nativeFixedTextures;
|
|
}
|
|
void enterFixHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint32_t name = getRegU32(ctx, 5), pixels = getRegU32(ctx, 6), palette = getRegU32(ctx, 10);
|
|
const uint32_t gsOrder = stackArg(rdram, ctx, 5);
|
|
insertFixedTexture(ctx, runtime);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
const uint32_t record = pixels != 0u ? textureRecord(rdram, name) : 0u;
|
|
if (record == 0u)
|
|
return;
|
|
auto wr32 = [rdram](uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); };
|
|
const uint32_t keptPixels = rd32(rdram, record + 0x38u), keptPalette = rd32(rdram, record + 0x48u), keptOrder = rd32(rdram, record + 0x4Cu);
|
|
wr32(record + 0x38u, pixels);
|
|
wr32(record + 0x48u, palette);
|
|
wr32(record + 0x4Cu, gsOrder != 0u ? 1u : 0u);
|
|
g_pinned.erase(record);
|
|
g_decoded.erase(record);
|
|
auto texture = recordTexture(rdram, record);
|
|
g_decoded.erase(record);
|
|
wr32(record + 0x38u, keptPixels);
|
|
wr32(record + 0x48u, keptPalette);
|
|
wr32(record + 0x4Cu, keptOrder);
|
|
if (texture)
|
|
g_pinned[record] = {keptPixels, rd64(rdram, record + 0x28u), texture};
|
|
static int s_logged = 0;
|
|
if (std::getenv("DC_PROBE_2D") && s_logged++ < 40)
|
|
std::fprintf(stderr, "[dc:2d] fixed texture \"%.32s\" record %08x kind %u %ux%u gs order %u: %s\n",
|
|
reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)), record, rd32(rdram, record + 4u) >> 16,
|
|
rd32(rdram, record) >> 16, rd32(rdram, record + 4u) & 0xFFFFu, gsOrder != 0u ? 1u : 0u,
|
|
texture ? "decoded" : "NOT decoded");
|
|
}
|
|
// EnterFixTextureZ (0x132930: a1 a picture file): a 640 x 224 8-bit picture (the menus' "stayframe" sheet) sent once
|
|
// as PSMT8H to 0x1180, its palette to 0x3FE0, from the file's buffer; the record holds neither pointer. Decoded
|
|
// right after it, as EnterFixTexture's are.
|
|
void enterFixZHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint32_t file = getRegU32(ctx, 5);
|
|
if (std::getenv("DC_PROBE_2D"))
|
|
std::fprintf(stderr, "[dc:2d] EnterFixTextureZ(file %08x)\n", file);
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
guest.in(file, 0x34u);
|
|
const uint32_t offset = guest.read32(file + 0x30u);
|
|
if (offset > 0xffffffffu - file) throw std::runtime_error("native fixed Z texture: picture address overflow");
|
|
const uint32_t picture = file + offset;
|
|
guest.in(picture, 0x28u);
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
if (guest.read32(picture + 0x24u) != 0x00e00280u || guest.read8(picture + 0x23u) != 5u)
|
|
return;
|
|
const auto name = guest.string(file + 0x10u, 32);
|
|
const uint32_t inserted = freeTextureRecord(guest, getRegU32(ctx, 4));
|
|
guest.write(inserted + 8u, name.c_str(), static_cast<uint32_t>(name.size() + 1u));
|
|
guest.write16(inserted, 0x49u);
|
|
guest.write16(inserted + 2u, 640u);
|
|
guest.write16(inserted + 4u, 224u);
|
|
guest.write16(inserted + 6u, 1u);
|
|
const uint64_t descriptor = 0x2007fc0629b29180ull;
|
|
guest.write(inserted + 0x28u, &descriptor, 8);
|
|
++g_nativeFixedZTextures;
|
|
const uint32_t pixels = picture + 0x10u + (rd32(rdram, picture + 0x1Cu) & 0xFFFFu);
|
|
const uint32_t palette = pixels + rd32(rdram, picture + 0x18u);
|
|
const uint32_t record = textureRecord(rdram, file + 0x10u);
|
|
if (record == 0u)
|
|
{
|
|
std::fprintf(stderr, "[dc:2d] fixed Z texture \"%.32s\" from file %08x: no record of that name\n",
|
|
reinterpret_cast<const char *>(rdram + ((file + 0x10u) & 0x1FFFFFFu)), file);
|
|
return;
|
|
}
|
|
auto wr32 = [rdram](uint32_t address, uint32_t value) { std::memcpy(rdram + (address & 0x1FFFFFFu), &value, 4); };
|
|
const uint32_t keptPixels = rd32(rdram, record + 0x38u), keptPalette = rd32(rdram, record + 0x48u), keptOrder = rd32(rdram, record + 0x4Cu);
|
|
wr32(record + 0x38u, pixels);
|
|
wr32(record + 0x48u, palette);
|
|
wr32(record + 0x4Cu, 0u);
|
|
g_pinned.erase(record);
|
|
g_decoded.erase(record);
|
|
auto texture = recordTexture(rdram, record);
|
|
g_decoded.erase(record);
|
|
wr32(record + 0x38u, keptPixels);
|
|
wr32(record + 0x48u, keptPalette);
|
|
wr32(record + 0x4Cu, keptOrder);
|
|
if (texture)
|
|
g_pinned[record] = {keptPixels, rd64(rdram, record + 0x28u), texture};
|
|
if (std::getenv("DC_PROBE_2D"))
|
|
std::fprintf(stderr, "[dc:2d] fixed Z texture \"%.32s\" record %08x: %s\n",
|
|
reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)), record, texture ? "decoded" : "NOT decoded");
|
|
}
|
|
// LoadTexture(TM2_head *, CTexture *, tbp, cbp) and LoadTexture(char *, u8 *, CTexture *, tbp, cbp).
|
|
void finishTextureLoad(uint8_t *ram, R5900Context *ctx, Runtime *rt, uint32_t record, uint32_t tbp, uint32_t cbp, uint32_t caller)
|
|
{
|
|
bozo::libs::Guest guest(*rt, ctx);
|
|
uint64_t descriptor;
|
|
std::memcpy(&descriptor, guest.in(record + 0x28u, 8), 8);
|
|
descriptor = (descriptor & ~0x3fffull) | (tbp & 0x3fffu);
|
|
descriptor |= 1ull << 34;
|
|
descriptor = (descriptor & 0xfff8001fffffffffull) | (static_cast<uint64_t>(cbp & 0x3fffu) << 37);
|
|
guest.write(record + 0x28u, &descriptor, 8);
|
|
pinRecord(ram, record);
|
|
ctx->pc = caller;
|
|
}
|
|
void loadTm2Hook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint32_t source = getRegU32(ctx, 4), record = getRegU32(ctx, 5);
|
|
const uint32_t tbp = getRegU32(ctx, 6), cbp = getRegU32(ctx, 7), caller = getRegU32(ctx, 31);
|
|
ctx->r[4].ud[0] = record;
|
|
ctx->r[5].ud[0] = 0x00299bf0u; // the original wrapper's default asset name
|
|
ctx->r[6].ud[0] = source;
|
|
g_textureInfoTm2(rdram, ctx, runtime); // asset parsing only, no upload/packet builder
|
|
finishTextureLoad(rdram, ctx, runtime, record, tbp, cbp, caller);
|
|
++g_nativeTextureTm2;
|
|
}
|
|
void loadTextureHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
const uint32_t name = getRegU32(ctx, 4), source = getRegU32(ctx, 5), record = getRegU32(ctx, 6);
|
|
const uint32_t tbp = getRegU32(ctx, 7), cbp = getRegU32(ctx, 8), caller = getRegU32(ctx, 31);
|
|
ctx->r[4].ud[0] = record;
|
|
ctx->r[5].ud[0] = name;
|
|
ctx->r[6].ud[0] = source;
|
|
g_textureInfoFile(rdram, ctx, runtime); // file directory/name selection only
|
|
finishTextureLoad(rdram, ctx, runtime, record, tbp, cbp, caller);
|
|
++g_nativeTextureFiles;
|
|
}
|
|
|
|
bool g_enabled = false;
|
|
}
|
|
|
|
bool enabled()
|
|
{
|
|
return g_enabled;
|
|
}
|
|
|
|
void resolveVisibility(Runtime &runtime, R5900Context &ctx, const DepthSampler &sample)
|
|
{
|
|
bozo::libs::Guest guest(runtime, &ctx);
|
|
for (uint32_t slot = 0; slot < 16; ++slot)
|
|
{
|
|
const uint32_t query = 0x01C751C0u + slot * 16u;
|
|
if (guest.read32(query) == 0) continue;
|
|
const int32_t x = static_cast<int32_t>(guest.read32(query + 4));
|
|
const int32_t y = static_cast<int32_t>(guest.read32(query + 8));
|
|
if (x < 4 || x >= 637 || y < 4 || y >= 445)
|
|
{
|
|
guest.write32(query + 12, 0xffffffffu);
|
|
continue;
|
|
}
|
|
// Preserve the shared arena's logical extent, without allocating or
|
|
// writing a readback tile. The old loop reset it for every valid query.
|
|
const uint32_t arena = guest.read32(getRegU32(&ctx, 28) - 0x7468u);
|
|
if (static_cast<int32_t>(guest.read32(arena + 12)) < 0x800)
|
|
throw std::runtime_error("DC visibility arena is smaller than its legacy extent");
|
|
guest.write32(arena + 8, 0x800);
|
|
uint32_t minimum = 0x00ffffff;
|
|
for (int row = 0; row < 8; ++row)
|
|
for (int col = 0; col < 8; ++col)
|
|
minimum = std::min(minimum, sample(x - 4 + col, y / 2 - 4 + row) & 0x00ffffffu);
|
|
guest.write32(query + 12, minimum);
|
|
}
|
|
}
|
|
|
|
void queryVisibility(Runtime &runtime, R5900Context &ctx)
|
|
{
|
|
++g_visibilityBatches;
|
|
auto &renderer = bozo::render::Renderer::instance();
|
|
bool requested = false;
|
|
resolveVisibility(runtime, ctx, [&](int32_t x, int32_t y) {
|
|
if (!requested) { renderer.wantDepth(); requested = true; }
|
|
// As before, an unavailable asynchronous tile (including headless
|
|
// mode) supplies empty/far depth until the present thread reads it.
|
|
uint32_t z = 0;
|
|
if (renderer.depthAt(1728.0f + x, 1936.0f + y, z)) ++g_depthSamples;
|
|
else ++g_depthPending;
|
|
return z;
|
|
});
|
|
}
|
|
|
|
// FishLineDraw's compiled loop has already projected this point and decided
|
|
// whether it connects to its predecessor. No packed graphics output is read.
|
|
// Like DrawLine, native segments are one-pixel-wide quads; console line
|
|
// rasterization and fishing gameplay still require visual qualification.
|
|
// FishLineDraw's strip between two of its points (namespace scope: a save state carries it, as a state can be saved
|
|
// between two points of the compiled loop).
|
|
struct FishStrip
|
|
{
|
|
Runtime *owner = nullptr;
|
|
uint32_t next = 0;
|
|
Point3 previous{};
|
|
};
|
|
thread_local FishStrip g_fishStrip;
|
|
// The debug font's compositions in progress (debugFontBoundary): a state is not saved in the middle of one.
|
|
thread_local bool g_debugFontBusy = false;
|
|
void fishLineVertex(uint8_t *ram, R5900Context *ctx, Runtime *runtime)
|
|
{
|
|
FishStrip &strip = g_fishStrip;
|
|
const uint32_t index = getRegU32(ctx, 19), decision = getRegU32(ctx, 5);
|
|
if (index >= 24u || (decision != 4u && decision != 12u))
|
|
throw std::runtime_error("native fishing line: invalid point boundary");
|
|
if (index == 0u) strip = FishStrip{runtime, 0u, {}};
|
|
if (strip.owner != runtime || strip.next != index)
|
|
throw std::runtime_error("native fishing line: nonsequential points");
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
const uint32_t address = getRegU32(ctx, 29) + 0x70u;
|
|
guest.in(address, 12);
|
|
const Point3 point = pointAt(ram, address, false);
|
|
if (index != 0u && decision == 4u)
|
|
{
|
|
const Point3 &a = strip.previous, &b = point;
|
|
float nx = -(b.y - a.y), ny = b.x - a.x;
|
|
const float length = std::sqrt(nx * nx + ny * ny);
|
|
if (length > 0.0f)
|
|
{
|
|
nx *= 0.5f / length; ny *= 0.5f / length;
|
|
const Point3 corners[4] = {{a.x - nx, a.y - ny, a.z, 1}, {a.x + nx, a.y + ny, a.z, 1},
|
|
{b.x - nx, b.y - ny, b.z, 1}, {b.x + nx, b.y + ny, b.z, 1}};
|
|
const float zero[4] = {};
|
|
const uint32_t colours[4] = {0x80808080u, 0x80808080u, 0x80808080u, 0x80808080u};
|
|
draw3D(ram, 0u, corners, zero, zero, colours, false, true);
|
|
}
|
|
}
|
|
strip.previous = point;
|
|
strip.next = index + 1u;
|
|
}
|
|
|
|
// The compiled debug-font loop keeps its cursor and original texture lookups.
|
|
// Its atlas-to-picture copies are ordinary native pixels. Work is keyed by
|
|
// runtime and guest stack, so a scheduler unwind cannot discard a partial
|
|
// composition or confuse it with another thread's call.
|
|
void debugFontBoundary(uint8_t *ram, R5900Context *ctx, Runtime *runtime, uint32_t pc)
|
|
{
|
|
struct Work
|
|
{
|
|
uint32_t font = 0, atlasRecord = 0, destination = 0, format = 0;
|
|
uint32_t destinationPixels = 0;
|
|
uint64_t atlasTex0 = 0, destinationTex0 = 0;
|
|
uint8_t alpha = 0;
|
|
std::shared_ptr<const bozo::render::Texture> atlas;
|
|
std::shared_ptr<bozo::render::Texture> image;
|
|
};
|
|
static thread_local std::unordered_map<Runtime *, std::unordered_map<uint32_t, Work>> pending;
|
|
struct Busy
|
|
{
|
|
std::unordered_map<Runtime *, std::unordered_map<uint32_t, Work>> &work;
|
|
Runtime *runtime;
|
|
~Busy() { g_debugFontBusy = !work[runtime].empty(); }
|
|
} busy{pending, runtime};
|
|
const uint32_t stack = getRegU32(ctx, 29);
|
|
bozo::libs::Guest guest(*runtime, ctx);
|
|
if (pc == 0x0013DFA8u)
|
|
{
|
|
auto &work = pending[runtime][stack]; work = {};
|
|
work.font = getRegU32(ctx, 21); work.atlasRecord = getRegU32(ctx, 2);
|
|
guest.in(work.font, 0x1c); guest.in(work.atlasRecord, 0x50);
|
|
work.atlasTex0 = rd64(ram, work.atlasRecord + 0x28u);
|
|
if (((work.atlasTex0 >> 20) & 0x3fu) > 1u)
|
|
throw std::runtime_error("native debug font: atlas must be a true-color picture");
|
|
work.atlas = recordTexture(ram, work.atlasRecord);
|
|
if (!work.atlas) throw std::runtime_error("native debug font: atlas is not decoded");
|
|
return;
|
|
}
|
|
auto owner = pending.find(runtime);
|
|
if (owner == pending.end() || !owner->second.count(stack))
|
|
throw std::runtime_error("native debug font: missing composition");
|
|
auto &work = owner->second.at(stack);
|
|
if (pc == 0x0013DFF0u)
|
|
{
|
|
work.destination = getRegU32(ctx, 2); guest.in(work.destination, 0x50);
|
|
const uint64_t tex0 = rd64(ram, work.destination + 0x28u);
|
|
work.destinationTex0 = tex0; work.destinationPixels = guest.read32(work.destination + 0x38u);
|
|
work.format = static_cast<uint32_t>((tex0 >> 20) & 0x3fu);
|
|
if (work.format != 0u && work.format != 1u)
|
|
throw std::runtime_error("native debug font: destination must be a true-color picture");
|
|
if ((tex0 & 0x3fffu) == (work.atlasTex0 & 0x3fffu))
|
|
throw std::runtime_error("native debug font: atlas aliases destination");
|
|
const uint32_t tw = (tex0 >> 26) & 15u, th = (tex0 >> 30) & 15u;
|
|
const int32_t width = static_cast<int32_t>(getRegU32(ctx, 22)), height = static_cast<int32_t>(getRegU32(ctx, 16));
|
|
if (tw > 10u || th > 10u || width <= 0 || height <= 0 ||
|
|
static_cast<uint32_t>(width) > (1u << tw) || static_cast<uint32_t>(height) > (1u << th))
|
|
throw std::runtime_error("native debug font: invalid picture extent");
|
|
const auto previous = recordTexture(ram, work.destination);
|
|
work.image = previous ? std::make_shared<bozo::render::Texture>(*previous) : std::make_shared<bozo::render::Texture>();
|
|
if (!previous)
|
|
{
|
|
work.image->width = 1u << tw; work.image->height = 1u << th;
|
|
work.image->rgba.assign(static_cast<size_t>(work.image->width) * work.image->height, 0u);
|
|
}
|
|
if (work.image->width < static_cast<uint32_t>(width) || work.image->height < static_cast<uint32_t>(height))
|
|
throw std::runtime_error("native debug font: decoded picture is smaller than its extent");
|
|
work.alpha = guest.read8(work.font + 0x14u);
|
|
if (work.format == 1u)
|
|
for (auto &pixel : work.image->rgba)
|
|
pixel = (pixel & 0xffffffu) | ((pixel & 0xffffffu) ? uint32_t(work.alpha) << 24 : 0u);
|
|
const uint32_t clear = (work.format == 1u ? uint32_t(work.alpha) << 24 : 0x80000000u) | 0x010101u;
|
|
for (int32_t y = 0; y < height; ++y)
|
|
std::fill_n(work.image->rgba.begin() + static_cast<size_t>(y) * work.image->width, width, clear);
|
|
// Retained game-side TEXA fields; no device register or packet state.
|
|
const uint32_t gp = getRegU32(ctx, 28);
|
|
guest.write8(gp - 0x73ffu, guest.read8(gp - 0x73ffu) | 0x80u);
|
|
guest.write8(gp - 0x7400u, work.alpha);
|
|
return;
|
|
}
|
|
if (!work.image) throw std::runtime_error("native debug font: destination is not initialized");
|
|
if (pc == 0x0013E314u)
|
|
{
|
|
const uint32_t glyph = (guest.read8(getRegU32(ctx, 17)) - 33u) & 0xffu;
|
|
const uint32_t sx = (glyph & 15u) * 8u, sy = (glyph >> 4) * 16u;
|
|
if (sx + 8u > work.atlas->width || sy + 16u > work.atlas->height)
|
|
throw std::runtime_error("native debug font: glyph lies outside its atlas");
|
|
const int64_t dx = static_cast<int32_t>(getRegU32(ctx, 18)), dy = static_cast<int32_t>(getRegU32(ctx, 19));
|
|
for (uint32_t y = 0; y < 16u; ++y)
|
|
for (uint32_t x = 0; x < 8u; ++x)
|
|
{
|
|
const int64_t tx = dx + x, ty = dy + y;
|
|
if (tx < 0 || ty < 0 || tx >= work.image->width || ty >= work.image->height) continue;
|
|
const uint32_t rgb = work.atlas->rgba[static_cast<size_t>(sy + y) * work.atlas->width + sx + x] & 0xffffffu;
|
|
auto &pixel = work.image->rgba[static_cast<size_t>(ty) * work.image->width + static_cast<size_t>(tx)];
|
|
const uint32_t alpha = work.format == 1u ? (rgb ? uint32_t(work.alpha) << 24 : 0u) : pixel & 0xff000000u;
|
|
pixel = rgb | alpha;
|
|
}
|
|
return;
|
|
}
|
|
if (pc != 0x0013E420u) throw std::runtime_error("native debug font: unknown boundary");
|
|
work.image->key = work.destination; work.image->version = ++g_textureVersion;
|
|
// Bind the identity captured at lookup, not a record which another
|
|
// resumed call may have rebound while this string was being composed.
|
|
g_pinned[work.destination] = {work.destinationPixels, work.destinationTex0, work.image};
|
|
guest.write32(work.font + 0x18u, 0u);
|
|
owner->second.erase(stack);
|
|
if (owner->second.empty()) pending.erase(owner);
|
|
}
|
|
|
|
void install(Runtime &runtime, bozo::port::Registry ®istry)
|
|
{
|
|
// DC_NO_DOF=1 (diagnosis): DepthOfField (0x1652C0, the cutscenes' blur behind the focus plane) does nothing.
|
|
if (const char *noDof = std::getenv("DC_NO_DOF"); noDof && noDof[0] == '1')
|
|
registry.registerFunction(0x001652C0u, [](uint8_t *, R5900Context *ctx, Runtime *) {
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
});
|
|
// DC_SKIP_FN=<hex>[,<hex>...] (diagnosis): those routines (void draws) do nothing.
|
|
if (const char *skip = std::getenv("DC_SKIP_FN"))
|
|
for (const char *at = skip; *at != '\0';)
|
|
{
|
|
char *end = nullptr;
|
|
const uint32_t address = static_cast<uint32_t>(std::strtoul(at, &end, 16));
|
|
if (end == at)
|
|
break;
|
|
if (address != 0u)
|
|
registry.registerFunction(address, [](uint8_t *, R5900Context *ctx, Runtime *) {
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
});
|
|
at = *end == ',' ? end + 1 : end;
|
|
}
|
|
if (const char *probe = std::getenv("DC_PROBE_TEX"); probe && probe[0] == '1')
|
|
for (SpriteHook &hook : g_spriteHooks)
|
|
if ((hook.original = runtime.functions.generated(hook.address)))
|
|
registry.registerFunction(hook.address, &spriteProbe);
|
|
if (const char *probe = std::getenv("DC_PROBE_FEEDERS"); probe && probe[0] == '1')
|
|
for (FeederHook &hook : g_feeders)
|
|
if ((hook.original = runtime.functions.generated(hook.address)))
|
|
registry.registerFunction(hook.address, &feederHook);
|
|
if (const char *probe = std::getenv("DC_PROBE_VU1"); probe && probe[0] == '1')
|
|
for (CountHook &hook : g_countHooks)
|
|
if ((hook.original = runtime.functions.generated(hook.address)))
|
|
registry.registerFunction(hook.address, &countHook);
|
|
registry.registerFunction(kVisualDrawVu1, &drawVu1Hook);
|
|
registry.registerFunction(0x0012ED80u, &frameDrawHook);
|
|
registry.registerFunction(0x0012A110u, &frameDrawHook);
|
|
registry.registerFunction(0x00134BC0u, &drawVu1Hook);
|
|
registry.registerFunction(kCreateFromMdt, &createFromMdtHook);
|
|
registry.registerFunction(kCreateFromMdtRemake, &createFromMdtRemakeHook);
|
|
registry.registerFunction(0x00136530u, &createShadowHook);
|
|
registry.registerFunction(0x0013C5F0u, &clothCreateHook);
|
|
registry.registerFunction(kSetGsReg3, &setGsReg3Hook);
|
|
registry.registerFunction(0x00113758u, &depthReadbackHook);
|
|
registry.registerFunction(kClothDrawVu1, &clothDrawHook);
|
|
registry.registerFunction(kShadowDrawVu1, &shadowDrawHook);
|
|
registry.registerFunction(kWaterCreateVUData, &waterCreateHook);
|
|
if (!(std::getenv("DC_NO_DOF") && std::getenv("DC_NO_DOF")[0] == '1'))
|
|
registry.registerFunction(0x001652C0u, &depthOfFieldHook);
|
|
registry.registerFunction(0x001308A0u, &beginShadowHook);
|
|
registry.registerFunction(0x00130B30u, &endShadowHook);
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
renderer.setEnabled(true);
|
|
renderer.beginFrame(beginScreen());
|
|
renderer.setStreamDraws(false);
|
|
renderer.setPresentsAlone(true);
|
|
{
|
|
registry.registerFunction(0x00130000u, &clearScreenHook);
|
|
registry.registerFunction(0x0012EA40u, &clipVertexHook); // culls against the frame's width (widescreen)
|
|
for (HudHook &hook : g_hudHooks)
|
|
if ((hook.original = runtime.functions.generated(hook.address)))
|
|
registry.registerFunction(hook.address, &hudHook);
|
|
registry.registerFunction(0x0012FD30u, &clearZHook);
|
|
registry.registerFunction(0x0012FA70u, &fillBoxHook);
|
|
registry.registerFunction(0x0015BD00u, &sprite2DHook);
|
|
for (uint32_t address : {0x0015C000u, 0x0015C310u, 0x0015C630u})
|
|
registry.registerFunction(address, &sprite2DRectsHook);
|
|
registry.registerFunction(0x0015C980u, &sprite2DCornersHook);
|
|
registry.registerFunction(0x0015E120u, &sprite2DC4Hook);
|
|
registry.registerFunction(0x0015DED0u, &colSpriteHook);
|
|
for (uint32_t address : {0x0015E540u, 0x0015EAD0u, 0x001831D0u})
|
|
registry.registerFunction(address, &sprite2DRotHook);
|
|
for (uint32_t address : {0x0014CD80u, 0x0014C3C0u})
|
|
registry.registerFunction(address, &mySpriteHook);
|
|
for (uint32_t address : {0x0014C220u, 0x0014C4F0u})
|
|
registry.registerFunction(address, &spriteBatchHook);
|
|
registry.registerFunction(0x0014C5A0u, &setClutHook);
|
|
registry.registerFunction(0x0012BA20u, &spriteTableHook);
|
|
registry.registerFunction(0x0015D1B0u, &colSprite3DHook);
|
|
for (uint32_t address : {0x0015D4B0u, 0x0015D790u, 0x0015D9A0u, 0x0015DCA0u})
|
|
registry.registerFunction(address, &sprite3DHook);
|
|
registry.registerFunction(0x00171210u, &drawLineHook);
|
|
registry.registerFunction(0x0012F210u, &moveImageHook);
|
|
if ((g_actionSeqPlay = runtime.functions.generated(0x001554A0u)))
|
|
registry.registerFunction(0x001554A0u, &actionSeqPlayHook);
|
|
if ((g_texAnime = runtime.functions.generated(0x00167170u)))
|
|
registry.registerFunction(0x00167170u, &texAnimeHook);
|
|
const RecompiledFunction animeHooks[6] = {&animeCallHook<0>, &animeCallHook<1>, &animeCallHook<2>, &animeCallHook<3>,
|
|
&animeCallHook<4>, &animeCallHook<5>};
|
|
for (int k = 0; k < 6; ++k)
|
|
if ((g_animeCalls[k] = runtime.functions.generated(kAnimeCallAddress[k])))
|
|
registry.registerFunction(kAnimeCallAddress[k], animeHooks[k]);
|
|
registry.registerFunction(0x00133070u, &reloadTextureHook);
|
|
if ((g_cleanupTextureList = runtime.functions.generated(0x00133A60u)))
|
|
registry.registerFunction(0x00133A60u, &cleanupTextureListHook);
|
|
registry.registerFunction(0x00151AD0u, &balloonHook);
|
|
registry.registerFunction(0x00140660u, &moveImageTestHook);
|
|
registry.registerFunction(0x0012F130u, &getFrameTexHook);
|
|
registry.registerFunction(0x0012F1A0u, &getBackTexHook);
|
|
if ((std::getenv("DC_PROBE_SKY") || std::getenv("DC_SKY_TIME")) &&
|
|
(g_drawSky = runtime.functions.generated(0x00187F90u)))
|
|
registry.registerFunction(0x00187F90u, &skyProbeHook);
|
|
registry.registerFunction(0x0012F430u, &stretchMoveHook);
|
|
registry.registerFunction(0x00162580u, &blendTextureHook);
|
|
registry.registerFunction(0x00162D80u, &blendTextureTestHook);
|
|
registry.registerFunction(0x0012F970u, &moveFrameBuffHook);
|
|
registry.registerFunction(0x00132930u, &enterFixZHook);
|
|
registry.registerFunction(0x001320E0u, &enterFixHook);
|
|
if ((g_textureInfoTm2 = runtime.functions.generated(0x00134760u)))
|
|
registry.registerFunction(0x00154950u, &loadTm2Hook);
|
|
if ((g_textureInfoFile = runtime.functions.generated(0x00134A90u)))
|
|
registry.registerFunction(0x00154770u, &loadTextureHook);
|
|
if ((g_vsyncLoad = runtime.functions.generated(0x00154320u)))
|
|
registry.registerFunction(0x00154320u, &vsyncLoadHook);
|
|
// sceGsSyncVCallback (0x113DE8) stays the game's own libgraph code: AddIntcHandler(2, VSyncCallBack) and
|
|
// EnableIntc(2), so VSyncCallBack runs at every vblank start of the kernel's field clock. The engine's
|
|
// native sceGsSyncVCallback runs the callback only where a game frame ends, and DC's loading waits for it
|
|
// without ending one (wait_now_loading_vsync spins on the flag VSyncCallBack_Load sets): the boot stopped
|
|
// there at frame 76.
|
|
if (const RecompiledFunction syncVCallback = runtime.functions.generated(0x00113DE8u))
|
|
registry.registerFunction(0x00113DE8u, syncVCallback);
|
|
if ((g_drawFire = runtime.functions.generated(0x00161AC0u)))
|
|
registry.registerFunction(0x00161AC0u, &drawFireHook);
|
|
registry.registerFunction(0x0015BC20u, &setAlphaFlagHook);
|
|
registry.registerFunction(0x0012EF90u, &setGsAlphaHook);
|
|
registry.registerFunction(0x0012EDF0u, &discardConsoleStateHook);
|
|
registry.registerFunction(0x0012EEC0u, &discardConsoleStateHook);
|
|
registry.registerFunction(0x0012F060u, &discardConsoleStateHook);
|
|
registry.registerFunction(0x0013DEA0u, &discardConsoleEnvelopeHook);
|
|
registry.registerFunction(0x0013DF00u, &discardConsoleEnvelopeHook);
|
|
registry.registerFunction(0x0012D9A0u, &setWindowRectHook);
|
|
registry.registerFunction(0x0012DAE0u, &setWindowRectHook);
|
|
registry.registerFunction(0x00140DA0u, &setEnvHook);
|
|
for (ShadowCall &call : g_shadowCalls)
|
|
if ((call.original = runtime.functions.generated(call.address)))
|
|
registry.registerFunction(call.address, &blobShadowHook);
|
|
}
|
|
// balloonHook owns the complete shape/tail. These private retail
|
|
// children are only called by that replaced parent (or one another);
|
|
// reject an unexpected entry instead of reviving their packet geometry.
|
|
for (uint32_t address : {0x00150BB0u, 0x00150F50u})
|
|
registry.registerFunction(address, [](uint8_t *, R5900Context *, Runtime *) {
|
|
throw std::runtime_error("native graphics: legacy balloon helper requires the native MakeFukidashi owner");
|
|
});
|
|
// Every admitted draw/asset producer now owns its native effects. Keep
|
|
// the retired SDK executable only for explicit original-code fixtures;
|
|
// a missed/indirect production path must fail before touching a packet.
|
|
for (uint32_t address : {0x00120750u, 0x00120760u, 0x00120770u, 0x001207C8u,
|
|
0x00120840u, 0x001208D8u, 0x00120950u, 0x00120968u, 0x00120980u, 0x00120A20u,
|
|
0x00120A48u, 0x00120C08u, 0x00120C18u, 0x00120C28u, 0x00120C80u, 0x00120CD8u,
|
|
0x00120D70u, 0x00120DE0u, 0x00120E38u, 0x00120E90u, 0x00120EC0u, 0x00120ED8u,
|
|
0x00120F78u, 0x00120F90u, 0x00121010u, 0x00121028u, 0x00121058u})
|
|
registry.registerFunction(address, [](uint8_t *, R5900Context *ctx, Runtime *) {
|
|
char message[128];
|
|
std::snprintf(message, sizeof(message), "native graphics: retired packet builder reached at 0x%08x", ctx->pc);
|
|
throw std::runtime_error(message);
|
|
});
|
|
// The console screenshot path used a packet base before opening files
|
|
// and ultimately requesting an unsupported GS readback. Reject at its
|
|
// owner, before those effects or any access to a retired packet object.
|
|
registry.registerFunction(0x0012C800u, [](uint8_t *, R5900Context *, Runtime *) {
|
|
throw std::runtime_error("native graphics: console StoreImage requires a native screenshot owner");
|
|
});
|
|
registry.registerFunction(0x0012C720u, [](uint8_t *, R5900Context *, Runtime *) {
|
|
throw std::runtime_error("native graphics: retired packet-buffer initializer reached");
|
|
});
|
|
registry.registerFunction(0x0012E280u, [](uint8_t *, R5900Context *ctx, Runtime *) {
|
|
setReturnS32(ctx, 0); // compatibility argument; no global/packet object
|
|
ctx->pc = getRegU32(ctx, 31);
|
|
});
|
|
g_enabled = true;
|
|
std::fprintf(stderr, "[dc:native] 3D models drawn natively from the game's MDT models, RenderInfo and textures; VU1 runs nothing\n");
|
|
}
|
|
|
|
// At the game's frame end (dc_overrides.cpp's native frame end): publishes the frame built and starts the next.
|
|
void publish()
|
|
{
|
|
if (!g_enabled)
|
|
return;
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
++g_publishedFrames;
|
|
if (g_extentRam)
|
|
extentCheck(g_extentRam);
|
|
static uint32_t s_frames = 0;
|
|
static const bool s_reportStats = [] {
|
|
const char *value = std::getenv("DC_NATIVE_STATS");
|
|
return value && value[0] == '1';
|
|
}();
|
|
if (++s_frames % 300u == 0u)
|
|
{
|
|
const LookupWork lookupWork = g_lookupWork;
|
|
g_lookupWork = LookupWork{};
|
|
// Synchronous diagnostics run before publishing the picture. A
|
|
// slow terminal/redirected output can otherwise stall play every
|
|
// five seconds while the FPS overlay still reads sixty between.
|
|
if (s_reportStats)
|
|
{
|
|
std::fprintf(stderr, "[dc:native] texture services cumulative: %llu reloads, %llu group selections, %llu TM2 loads, %llu file loads\n",
|
|
static_cast<unsigned long long>(g_nativeTextureReloads), static_cast<unsigned long long>(g_nativeTextureSelections),
|
|
static_cast<unsigned long long>(g_nativeTextureTm2), static_cast<unsigned long long>(g_nativeTextureFiles));
|
|
std::fprintf(stderr, "[dc:native] fixed texture services cumulative: %llu fixed, %llu fixed Z\n",
|
|
static_cast<unsigned long long>(g_nativeFixedTextures), static_cast<unsigned long long>(g_nativeFixedZTextures));
|
|
std::fprintf(stderr, "[dc:native] packet-only state setters retired: %llu\n", static_cast<unsigned long long>(g_retiredStateCalls));
|
|
std::fprintf(stderr, "[dc:native] record textures per frame: %.1f lookups, %.2f MiB hashed\n",
|
|
static_cast<double>(lookupWork.lookups) / 300.0, static_cast<double>(lookupWork.hashedBytes) / 300.0 / 1048576.0);
|
|
std::fprintf(stderr, "[dc:native] native window rectangles: %llu; packet envelopes retired: %llu\n",
|
|
static_cast<unsigned long long>(g_nativeWindowRects), static_cast<unsigned long long>(g_retiredEnvelopes));
|
|
std::fprintf(stderr, "[dc:native] model packet wrappers retired: %llu\n",
|
|
static_cast<unsigned long long>(g_retiredModelEnvelopes));
|
|
std::fprintf(stderr, "[dc:native] frame packet wrappers retired: %llu MGDraw, %llu member\n",
|
|
static_cast<unsigned long long>(g_nativeFrameDraws), static_cast<unsigned long long>(g_nativeFrameMemberDraws));
|
|
std::fprintf(stderr, "[dc:native] asset builders cumulative: %llu models, %llu remakes, %llu shadows, %llu cloths; %llu bytes of legacy output extents bypassed\n",
|
|
static_cast<unsigned long long>(g_nativeModelBuilds), static_cast<unsigned long long>(g_nativeModelRemakes),
|
|
static_cast<unsigned long long>(g_nativeShadowBuilds), static_cast<unsigned long long>(g_nativeClothBuilds),
|
|
static_cast<unsigned long long>(g_retiredModelBytes));
|
|
std::fprintf(stderr, "[dc:native] per 300 frames: %llu DrawVu1 calls (%llu without a known MDT, %llu drawn from a copy of their MDT), %llu primitives, "
|
|
"%llu triangles, %llu own textures, %llu untextured for lack of one; not drawn: %llu shadows, "
|
|
"%llu screen-space; %llu cloths; %llu shadow triangles; %llu waters;%llu GS-order textures not in the store; VU1 programs skipped: %llu\n",
|
|
static_cast<unsigned long long>(g_stats.calls), static_cast<unsigned long long>(g_stats.noModel),
|
|
static_cast<unsigned long long>(g_stats.copiedModel),
|
|
static_cast<unsigned long long>(g_stats.primitives),
|
|
static_cast<unsigned long long>(g_stats.triangles),
|
|
static_cast<unsigned long long>(g_stats.ownTextures),
|
|
static_cast<unsigned long long>(g_stats.noTexture),
|
|
static_cast<unsigned long long>(g_stats.shadows),
|
|
static_cast<unsigned long long>(g_stats.screenSpace),
|
|
static_cast<unsigned long long>(g_stats.cloths),
|
|
static_cast<unsigned long long>(g_stats.shadowTriangles),
|
|
static_cast<unsigned long long>(g_stats.waters),
|
|
static_cast<unsigned long long>(g_stats.gsOrderTextures),
|
|
static_cast<unsigned long long>(g_gateSkipped.exchange(0)));
|
|
std::fprintf(stderr, "[dc:native] groups: %llu numbered here; skipped at pc 0: %llu, pc 8: %llu, other: %llu (last 0x%llx)\n",
|
|
static_cast<unsigned long long>(g_group), static_cast<unsigned long long>(g_gateByPc[0].exchange(0)),
|
|
static_cast<unsigned long long>(g_gateByPc[1].exchange(0)),
|
|
static_cast<unsigned long long>(g_gateByPc[2].exchange(0)),
|
|
static_cast<unsigned long long>(g_gateByPc[3].load()));
|
|
if (g_depthSamples || g_depthPending)
|
|
std::fprintf(stderr, "[dc:native] visibility depth samples: %llu from GPU, %llu pending (empty depth)\n",
|
|
static_cast<unsigned long long>(g_depthSamples), static_cast<unsigned long long>(g_depthPending));
|
|
std::fprintf(stderr, "[dc:native] native visibility batches: %llu\n", static_cast<unsigned long long>(g_visibilityBatches));
|
|
std::fprintf(stderr, "[dc:native] objects without Z write (ZBUF ZMSK): %llu; depths of field: %llu; back faces culled: %llu; outside the guard band: %llu\n",
|
|
static_cast<unsigned long long>(g_stats.noZWrite), static_cast<unsigned long long>(g_stats.depthOfFields),
|
|
static_cast<unsigned long long>(g_stats.culled), static_cast<unsigned long long>(g_stats.guarded));
|
|
if (g_stats.madeDraws[0] + g_stats.madeDraws[1] + g_stats.madeDraws[8] + g_stats.clears != 0u)
|
|
std::fprintf(stderr, "[dc:native] made-picture sprites: frame %llu, previous %llu, targets %llu %llu %llu; clears %llu (last %06llx)\n",
|
|
static_cast<unsigned long long>(g_stats.madeDraws[0]), static_cast<unsigned long long>(g_stats.madeDraws[8]),
|
|
static_cast<unsigned long long>(g_stats.madeDraws[1]), static_cast<unsigned long long>(g_stats.madeDraws[2]),
|
|
static_cast<unsigned long long>(g_stats.madeDraws[3]), static_cast<unsigned long long>(g_stats.clears),
|
|
static_cast<unsigned long long>(g_stats.lastClear));
|
|
if (g_stats.stretches + g_stats.stretchesMissed != 0u)
|
|
std::fprintf(stderr, "[dc:native] frame stretches: %llu, %llu from or to a place not made natively\n",
|
|
static_cast<unsigned long long>(g_stats.stretches), static_cast<unsigned long long>(g_stats.stretchesMissed));
|
|
if (g_stats.textureCopies != 0u)
|
|
std::fprintf(stderr, "[dc:native] texture copies: %llu, %llu between places no record holds\n",
|
|
static_cast<unsigned long long>(g_stats.textureCopies), static_cast<unsigned long long>(g_stats.textureCopiesMissed));
|
|
if (g_stats.maxZ > -1e30)
|
|
std::fprintf(stderr, "[dc:native] GS Z of clipped vertices: %.0f .. %.0f, %llu past 2^24, %llu negative\n", g_stats.minZ,
|
|
g_stats.maxZ, static_cast<unsigned long long>(g_stats.zPast24), static_cast<unsigned long long>(g_stats.zNegative));
|
|
}
|
|
g_stats = Stats{};
|
|
if (!s_reportStats)
|
|
{
|
|
g_gateSkipped.exchange(0);
|
|
for (unsigned i = 0; i < 3; ++i) g_gateByPc[i].exchange(0);
|
|
}
|
|
for (FeederHook &hook : g_feeders)
|
|
if (const uint64_t calls = hook.calls.exchange(0); s_reportStats && calls)
|
|
std::fprintf(stderr, "[dc:feeder] %s: %llu calls\n", hook.name, static_cast<unsigned long long>(calls));
|
|
for (CountHook &hook : g_countHooks)
|
|
if (const uint64_t calls = hook.calls.exchange(0); s_reportStats && calls)
|
|
std::fprintf(stderr, "[dc:probe] %s: %llu calls\n", hook.name, static_cast<unsigned long long>(calls));
|
|
}
|
|
flushShadows();
|
|
renderer.endFrame();
|
|
renderer.beginFrame(beginScreen());
|
|
g_clutOverride.clear();
|
|
if (!g_publishingFromLoad)
|
|
g_lastMainPublish.store(nowMs(), std::memory_order_relaxed);
|
|
static const bool s_probeHitch = std::getenv("DC_PROBE_HITCH") != nullptr;
|
|
if (s_probeHitch)
|
|
{
|
|
static auto s_last = std::chrono::steady_clock::now();
|
|
static double s_average = 16.7;
|
|
static int s_logged = 0;
|
|
const auto now = std::chrono::steady_clock::now();
|
|
const double ms = std::chrono::duration<double, std::milli>(now - s_last).count();
|
|
s_last = now;
|
|
if (ms > s_average * 1.6 && ms > 20.0 && s_logged < 400)
|
|
{
|
|
++s_logged;
|
|
std::fprintf(stderr, "[dc:hitch] frame %u: %.1f ms (average %.1f): %u decodes, %u store decodes, %u patches, %llu texels, %u 2D draws\n",
|
|
s_frames, ms, s_average, g_frameWork.decodes, g_frameWork.storeDecodes, g_frameWork.patches,
|
|
static_cast<unsigned long long>(g_frameWork.decodedTexels), g_frameWork.draws);
|
|
}
|
|
s_average = s_average * 0.95 + std::min(ms, 50.0) * 0.05;
|
|
}
|
|
g_frameWork = FrameWork{};
|
|
static int s_seqLogged = 0;
|
|
if (!g_seq.empty() && (g_seq.find('S') != std::string::npos || g_seq.find('E') != std::string::npos) && (s_seqLogged < 4 || s_frames % 300u == 0u))
|
|
{
|
|
++s_seqLogged;
|
|
std::string runs;
|
|
for (size_t i = 0; i < g_seq.size();)
|
|
{
|
|
size_t j = i;
|
|
while (j < g_seq.size() && g_seq[j] == g_seq[i])
|
|
++j;
|
|
runs += g_seq[i];
|
|
if (j - i > 1)
|
|
runs += std::to_string(j - i);
|
|
runs += ' ';
|
|
i = j;
|
|
}
|
|
std::fprintf(stderr, "[dc:seq] %s\n", runs.c_str());
|
|
}
|
|
g_seq.clear();
|
|
if (g_dump2D)
|
|
{
|
|
g_dump2D = false;
|
|
std::fprintf(stderr, "[dc:dump] frame end\n");
|
|
}
|
|
static uint32_t s_toggleCheck = 0;
|
|
if (++s_toggleCheck % 60u == 0u)
|
|
readToggles();
|
|
// DC_DUMP2D_AT=frame,frame,... (diagnosis, hidden runs): those published frames' 2D dumped as the flag file does.
|
|
static const std::vector<uint64_t> s_dumpAt = [] {
|
|
std::vector<uint64_t> at;
|
|
if (const char *e = std::getenv("DC_DUMP2D_AT"))
|
|
for (const char *p = e; *p;)
|
|
{
|
|
char *end = nullptr;
|
|
at.push_back(std::strtoull(p, &end, 10));
|
|
p = *end ? end + 1 : end;
|
|
}
|
|
return at;
|
|
}();
|
|
if (std::find(s_dumpAt.begin(), s_dumpAt.end(), g_publishedFrames) != s_dumpAt.end())
|
|
{
|
|
g_dump2D = true;
|
|
std::fprintf(stderr, "[dc:dump] frame start %llu\n", static_cast<unsigned long long>(g_publishedFrames));
|
|
}
|
|
static uint32_t s_dumpCheck = 0;
|
|
if (++s_dumpCheck % 30u == 0u)
|
|
if (FILE *flag = std::fopen("D:/DC_Recomp/build/dump2d.flag", "rb"))
|
|
{
|
|
std::fclose(flag);
|
|
std::remove("D:/DC_Recomp/build/dump2d.flag");
|
|
g_dump2D = true;
|
|
std::fprintf(stderr, "[dc:dump] frame start\n");
|
|
}
|
|
}
|
|
|
|
void finishSceneForMenu() { flushShadows(); }
|
|
|
|
// DC_PROBE_TEX=1 (diagnosis): the texture manager's (0x1C75870) records, every 600 frames: count at + 0, records
|
|
// of 0x50 bytes from + 0x10F8, each with its name at + 8 and TEX0 at + 0x28.
|
|
void probeTextures(const uint8_t *rdram)
|
|
{
|
|
static const bool on = [] { const char *v = std::getenv("DC_PROBE_TEX"); return v && v[0] == '1'; }();
|
|
static uint32_t s_frames = 0;
|
|
if (!on || ++s_frames % 600u != 0u)
|
|
return;
|
|
const uint32_t count = rd32(rdram, kTextureManager);
|
|
std::fprintf(stderr, "[dc:probe] frame %u: %u textures\n", s_frames, count);
|
|
for (uint32_t i = 0; i < count && i < 512u; ++i)
|
|
{
|
|
const uint32_t entry = kTextureManager + 0x10F8u + i * 0x50u;
|
|
const uint64_t tex0 = rd64(rdram, entry + 0x28u);
|
|
char name[33] = {};
|
|
for (uint32_t k = 0; k < 32u; ++k)
|
|
{
|
|
const char c = static_cast<char>(rdram[(entry + k) & 0x1FFFFFFu]);
|
|
name[k] = (c >= 32 && c < 127) ? c : '.';
|
|
}
|
|
std::fprintf(stderr, "[dc:probe] %3u tbp %5u tbw %2u psm 0x%02x tw %u th %u cbp %5u %s\n", i,
|
|
static_cast<uint32_t>(tex0 & 0x3FFFu), static_cast<uint32_t>(tex0 >> 14) & 0x3Fu,
|
|
static_cast<uint32_t>(tex0 >> 20) & 0x3Fu, static_cast<uint32_t>(tex0 >> 26) & 0xFu,
|
|
static_cast<uint32_t>(tex0 >> 30) & 0xFu, static_cast<uint32_t>(tex0 >> 37) & 0x3FFFu, name);
|
|
}
|
|
}
|
|
|
|
// ---- Save states ----------------------------------------------------------------------------------------------
|
|
namespace
|
|
{
|
|
// A texture image (null: none), restored with a new version so the renderer sends it again.
|
|
void textureIo(bozo::state::Archive &a, std::shared_ptr<const bozo::render::Texture> &texture)
|
|
{
|
|
bool has = texture != nullptr;
|
|
uint32_t width = 0, height = 0;
|
|
std::vector<uint32_t> rgba;
|
|
uint64_t key = 0;
|
|
std::vector<std::pair<uint32_t, uint32_t>> pages;
|
|
std::vector<std::vector<uint32_t>> levels;
|
|
bool asset = false;
|
|
if (!a.loading() && texture)
|
|
{
|
|
width = texture->width, height = texture->height, rgba = texture->rgba, key = texture->key;
|
|
pages = texture->pages, levels = texture->levels, asset = texture->asset;
|
|
}
|
|
bozo::state::fields(a, has, width, height, rgba, key, pages, levels, asset);
|
|
if (!a.loading())
|
|
return;
|
|
if (!has)
|
|
{
|
|
texture = nullptr;
|
|
return;
|
|
}
|
|
auto made = std::make_shared<bozo::render::Texture>();
|
|
made->width = width, made->height = height, made->rgba = std::move(rgba), made->key = key;
|
|
made->pages = std::move(pages), made->levels = std::move(levels), made->asset = asset;
|
|
made->version = ++g_textureVersion;
|
|
texture = made;
|
|
}
|
|
// The images a state refers to, each written once (many bindings share one), and referred to by index (-1: none).
|
|
struct TextureTable
|
|
{
|
|
std::vector<std::shared_ptr<const bozo::render::Texture>> images;
|
|
std::unordered_map<const bozo::render::Texture *, int32_t> index;
|
|
int32_t add(const std::shared_ptr<const bozo::render::Texture> &image)
|
|
{
|
|
if (!image)
|
|
return -1;
|
|
const auto [at, added] = index.emplace(image.get(), static_cast<int32_t>(images.size()));
|
|
if (added)
|
|
images.push_back(image);
|
|
return at->second;
|
|
}
|
|
std::shared_ptr<const bozo::render::Texture> at(int32_t i) const
|
|
{
|
|
if (i < 0)
|
|
return nullptr;
|
|
if (static_cast<size_t>(i) >= images.size())
|
|
throw std::runtime_error("save state: a texture index past the table");
|
|
return images[static_cast<size_t>(i)];
|
|
}
|
|
};
|
|
template <class Key> std::vector<Key> sortedKeys(const auto &map)
|
|
{
|
|
std::vector<Key> keys;
|
|
for (const auto &entry : map)
|
|
keys.push_back(static_cast<Key>(entry.first));
|
|
std::sort(keys.begin(), keys.end());
|
|
return keys;
|
|
}
|
|
}
|
|
|
|
// What the native renderer and asset builders know that guest memory alone does not tell again, and, on load, the
|
|
// caches decoded from the old guest memory dropped (docs/BOZO_MIGRATION.md, "Save states").
|
|
void state(bozo::state::Archive &a, Runtime &runtime)
|
|
{
|
|
const uint8_t *rdram = runtime.memory.ram();
|
|
TextureTable table;
|
|
if (!a.loading())
|
|
{
|
|
std::lock_guard<std::mutex> lock(g_mdtMutex);
|
|
for (const uint32_t data : sortedKeys<uint32_t>(g_mdtCopies))
|
|
if (const auto &records = g_mdtCopies.at(data).records)
|
|
for (const TextureBinding &binding : *records)
|
|
if (resolveBinding(rdram, binding) == 0u)
|
|
table.add(binding.image);
|
|
for (const uint32_t record : sortedKeys<uint32_t>(g_pinned))
|
|
table.add(g_pinned.at(record).texture);
|
|
for (const uint32_t record : g_patchedRecords)
|
|
if (const auto found = g_decoded.find(record); found != g_decoded.end())
|
|
table.add(found->second.second);
|
|
}
|
|
{
|
|
uint64_t images = table.images.size();
|
|
bozo::state::fields(a, images);
|
|
if (a.loading())
|
|
table.images.resize(images);
|
|
for (auto &image : table.images)
|
|
textureIo(a, image);
|
|
}
|
|
// The MDT copies: the game reuses a static piece's MDT memory after building it, so its copy is the only model
|
|
// left. A binding's image is kept only where its record no longer resolves (otherwise it is decoded again).
|
|
{
|
|
std::lock_guard<std::mutex> lock(g_mdtMutex);
|
|
uint64_t count = g_mdtCopies.size();
|
|
bozo::state::fields(a, count);
|
|
std::vector<uint32_t> keys = a.loading() ? std::vector<uint32_t>(count) : sortedKeys<uint32_t>(g_mdtCopies);
|
|
if (a.loading())
|
|
g_mdtCopies.clear();
|
|
for (uint64_t i = 0; i < count; ++i)
|
|
{
|
|
uint32_t data = keys[i], mdt = 0;
|
|
bool hasCopy = false, hasRecords = false;
|
|
std::vector<uint8_t> bytes;
|
|
std::vector<TextureBinding> bindings;
|
|
if (!a.loading())
|
|
{
|
|
const MdtCopy &entry = g_mdtCopies.at(data);
|
|
mdt = entry.mdt;
|
|
hasCopy = entry.copy != nullptr;
|
|
if (hasCopy)
|
|
bytes = *entry.copy;
|
|
hasRecords = entry.records != nullptr;
|
|
if (hasRecords)
|
|
bindings = *entry.records;
|
|
}
|
|
bozo::state::fields(a, data, mdt, hasCopy, bytes, hasRecords);
|
|
uint64_t bindingCount = bindings.size();
|
|
bozo::state::fields(a, bindingCount);
|
|
if (a.loading())
|
|
bindings.resize(bindingCount);
|
|
for (TextureBinding &binding : bindings)
|
|
{
|
|
bozo::state::fields(a, binding.record, binding.resolvedRecord, binding.identity);
|
|
int32_t image = !a.loading() && resolveBinding(rdram, binding) == 0u ? table.add(binding.image) : -1;
|
|
bozo::state::fields(a, image);
|
|
if (a.loading())
|
|
binding.image = table.at(image);
|
|
}
|
|
if (a.loading())
|
|
{
|
|
MdtCopy &entry = g_mdtCopies[data];
|
|
entry.mdt = mdt;
|
|
entry.copy = hasCopy ? std::make_shared<const std::vector<uint8_t>>(std::move(bytes)) : nullptr;
|
|
entry.records = hasRecords ? std::make_shared<const std::vector<TextureBinding>>(std::move(bindings)) : nullptr;
|
|
}
|
|
}
|
|
}
|
|
{
|
|
uint64_t count = g_pinned.size();
|
|
bozo::state::fields(a, count);
|
|
std::vector<uint32_t> keys = a.loading() ? std::vector<uint32_t>(count) : sortedKeys<uint32_t>(g_pinned);
|
|
if (a.loading())
|
|
g_pinned.clear();
|
|
for (uint64_t i = 0; i < count; ++i)
|
|
{
|
|
uint32_t record = keys[i];
|
|
Pinned pinned = a.loading() ? Pinned{} : g_pinned.at(record);
|
|
int32_t image = a.loading() ? -1 : table.add(pinned.texture);
|
|
bozo::state::fields(a, record, pinned.pixels, pinned.tex0, image);
|
|
if (a.loading())
|
|
pinned.texture = table.at(image);
|
|
if (a.loading())
|
|
g_pinned[record] = std::move(pinned);
|
|
}
|
|
}
|
|
// What was sent to each GS place last, the records MGMoveImage patched and their decoded pictures.
|
|
bozo::state::fields(a, g_resident, g_waterOfVisual);
|
|
{
|
|
std::vector<uint32_t> patched(g_patchedRecords.begin(), g_patchedRecords.end());
|
|
std::sort(patched.begin(), patched.end());
|
|
bozo::state::fields(a, patched);
|
|
if (a.loading())
|
|
{
|
|
g_patchedRecords = std::unordered_set<uint32_t>(patched.begin(), patched.end());
|
|
g_decoded.clear();
|
|
}
|
|
for (uint32_t record : patched)
|
|
{
|
|
bool has = !a.loading() && g_decoded.count(record) != 0;
|
|
uint64_t hash = has ? g_decoded.at(record).first : 0u;
|
|
int32_t image = has ? table.add(g_decoded.at(record).second) : -1;
|
|
bozo::state::fields(a, has, hash, image);
|
|
if (a.loading() && has)
|
|
g_decoded[record] = {hash, table.at(image)};
|
|
}
|
|
}
|
|
// Facts and seeds: the frame identities the game asked for last, the haze's random sequences (the first writes
|
|
// guest RAM), the group the depth of field follows, the fishing strip between two points.
|
|
bozo::state::fields(a, g_frameBase, g_backBase, g_backAsked, g_hazeSeed, g_hazeRandom, g_group);
|
|
bozo::state::fields(a, g_fishStrip.next, g_fishStrip.previous.x, g_fishStrip.previous.y, g_fishStrip.previous.z,
|
|
g_fishStrip.previous.fog);
|
|
if (!a.loading())
|
|
return;
|
|
g_fishStrip.owner = &runtime;
|
|
// Caches of the old guest memory and of render targets whose pictures are on the GPU: dropped.
|
|
g_targetOfBase.clear();
|
|
for (float &rows : g_targetRows)
|
|
rows = 224.0f;
|
|
g_blendedLast.clear();
|
|
g_hazeLast.clear();
|
|
g_blendedExtent.clear();
|
|
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
|
|
for (uint8_t target = 1; target < 8; ++target)
|
|
{
|
|
renderer.setTargetSize(target, 0, 0);
|
|
renderer.setTargetSharesDepth(target, false);
|
|
}
|
|
g_clutOverride.clear();
|
|
g_shadowDraws.clear();
|
|
g_pendingShadows.clear();
|
|
renderer.beginFrame(beginScreen());
|
|
g_lastMainPublish.store(nowMs(), std::memory_order_relaxed);
|
|
}
|
|
|
|
void setWidescreen(bool on) { g_wideRequest.store(on, std::memory_order_relaxed); }
|
|
// CFrameVu1::DrawVu1's culling bound (runtime/dc_port.cpp): the drawn frame's half width, 320 or 426.67.
|
|
float modelCullHalfWidth() { return frameW() / 2.0f; }
|
|
|
|
std::string unsaveable()
|
|
{
|
|
if (g_debugFontBusy)
|
|
return "the debug font is drawing a picture";
|
|
return {};
|
|
}
|
|
}
|