Debian Codegraph @

Sources/nCine/Graphics/RHI/GX/GxDevice.cpp

raw
1 #include "GxDevice.h"
2 #include "GxBuffer.h"
3 #include "GxShaderProgram.h"
4 #include "GxRenderTarget.h"
5 #include "GxTexture.h"
6 #include "../FixedFunctionPass.h"
7
8 #include "../../../../Main.h"
9 #include "../../../../Shaders/Generated/ShaderCompilerTypes.h"
10
11 #include <cmath>
12 #include <cstring>
13 #include <malloc.h>
14
15 #include <ogc/cache.h>
16
17 namespace nCine::RHI::GX
18 {
19 namespace
20 {
21 // The DefaultSprite / DefaultBatchedSprites instance layout is a hard contract of the shader family
22 // (std140 offsets within the InstanceBlock / each batched Instance) - identical to the software
23 // backend's decode (see SwDevice.cpp)
24 constexpr std::uint32_t kModelMatrixOffset = 0;
25 constexpr std::uint32_t kColorOffset = 64;
26 constexpr std::uint32_t kTexRectOffset = 80;
27 constexpr std::uint32_t kSpriteSizeOffset = 96;
28 // The palette shaders park a flat palette index in the std140 tail padding after spriteSize
29 constexpr std::uint32_t kPaletteOffsetOffset = 104;
30 // The no-texture sprite family drops texRect, so spriteSize sits directly after color
31 constexpr std::uint32_t kSpriteSizeNoTexOffset = 80;
32
33 constexpr std::uint32_t GxFifoSize = 256 * 1024;
34
35 const float IdentityMatrix[16] = {
36 1, 0, 0, 0,
37 0, 1, 0, 0,
38 0, 0, 1, 0,
39 0, 0, 0, 1
40 };
41
42 // Column-major 4x4 multiply, out = a * b (matches the software device)
43 void Mat4Mul(const float* DEATH_RESTRICT a, const float* DEATH_RESTRICT b, float* DEATH_RESTRICT out)
44 {
45 for (std::int32_t col = 0; col < 4; col++) {
46 for (std::int32_t row = 0; row < 4; row++) {
47 out[col * 4 + row] =
48 a[0 * 4 + row] * b[col * 4 + 0] +
49 a[1 * 4 + row] * b[col * 4 + 1] +
50 a[2 * 4 + row] * b[col * 4 + 2] +
51 a[3 * 4 + row] * b[col * 4 + 3];
52 }
53 }
54 }
55
56 // Both draw paths only ever transform points of the form (x, y, 0, 1), so just six of the sixteen
57 // products of projection*view*model are ever read back. Sprites pay this per instance, which made
58 // the full 4x4 multiply the most expensive step of the per-instance loop.
59 struct Transform2D
60 {
61 float Xx, Xy; // Column 0, rows 0 and 1
62 float Yx, Yy; // Column 1, rows 0 and 1
63 float Tx, Ty; // Column 3, rows 0 and 1
64 };
65
66 void Mat4MulTransform2D(const float* DEATH_RESTRICT pv, const float* DEATH_RESTRICT model, Transform2D& out)
67 {
68 out.Xx = pv[0] * model[0] + pv[4] * model[1] + pv[8] * model[2] + pv[12] * model[3];
69 out.Xy = pv[1] * model[0] + pv[5] * model[1] + pv[9] * model[2] + pv[13] * model[3];
70 out.Yx = pv[0] * model[4] + pv[4] * model[5] + pv[8] * model[6] + pv[12] * model[7];
71 out.Yy = pv[1] * model[4] + pv[5] * model[5] + pv[9] * model[6] + pv[13] * model[7];
72 out.Tx = pv[0] * model[12] + pv[4] * model[13] + pv[8] * model[14] + pv[12] * model[15];
73 out.Ty = pv[1] * model[12] + pv[5] * model[13] + pv[9] * model[14] + pv[13] * model[15];
74 }
75
76 // Maps a pipeline-neutral blend factor onto the GX factor set. GX names the color-source factors
77 // from the destination's viewpoint (GX_BL_SRCCLR is only valid as a destination factor and
78 // GX_BL_DSTCLR as a source factor), which matches how the game uses them.
79 std::uint8_t MapBlendGx(nCine::BlendingFactor factor)
80 {
81 switch (factor) {
82 case nCine::BlendingFactor::Zero: return GX_BL_ZERO;
83 case nCine::BlendingFactor::One: return GX_BL_ONE;
84 case nCine::BlendingFactor::SrcColor: return GX_BL_SRCCLR;
85 case nCine::BlendingFactor::OneMinusSrcColor: return GX_BL_INVSRCCLR;
86 case nCine::BlendingFactor::DstColor: return GX_BL_DSTCLR;
87 case nCine::BlendingFactor::OneMinusDstColor: return GX_BL_INVDSTCLR;
88 case nCine::BlendingFactor::SrcAlpha: return GX_BL_SRCALPHA;
89 case nCine::BlendingFactor::OneMinusSrcAlpha: return GX_BL_INVSRCALPHA;
90 case nCine::BlendingFactor::DstAlpha: return GX_BL_DSTALPHA;
91 case nCine::BlendingFactor::OneMinusDstAlpha: return GX_BL_INVDSTALPHA;
92 default: return GX_BL_ONE;
93 }
94 }
95
96 // Packs one RGBA8 palette entry into the RGB5A3 TLUT format (alpha-capable palette entries)
97 inline std::uint16_t Rgb5a3FromRgba(std::uint32_t rgba)
98 {
99 const std::uint32_t r = rgba & 0xFF;
100 const std::uint32_t g = (rgba >> 8) & 0xFF;
101 const std::uint32_t b = (rgba >> 16) & 0xFF;
102 const std::uint32_t a = (rgba >> 24) & 0xFF;
103 if (a >= 224) {
104 // Opaque: 0b1 RRRRR GGGGG BBBBB
105 return std::uint16_t(0x8000u | ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3));
106 }
107 // Translucent: 0b0 AAA RRRR GGGG BBBB
108 return std::uint16_t(((a >> 5) << 12) | ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4));
109 }
110
111 inline std::uint8_t QuantizeChannel(float v)
112 {
113 v = (v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v));
114 return std::uint8_t(v * 255.0f + 0.5f);
115 }
116
117 // Whether the vertex descriptor currently includes texture coordinates
118 bool g_vertexModeTextured = true;
119
120 // GX register state persists across draws (the same reason SetVertexModeTextured/SetTevMode below
121 // can early-out), so ApplyProjection() and ApplyRenderState() track what they last issued and skip
122 // the reissue when nothing changed - both used to run unconditionally for every draw. Anything
123 // that bypasses them to touch the same registers (target switches, EFB copies, the frame present,
124 // the immediate clear and the lighting hook) invalidates the caches below.
125 bool g_appliedProjectionValid = false;
126 const void* g_appliedProjectionTarget = nullptr;
127 std::int32_t g_appliedProjectionW = 0;
128 std::int32_t g_appliedProjectionH = 0;
129
130 bool g_appliedBlendValid = false;
131 bool g_appliedBlendEnabled = false;
132 nCine::BlendingFactor g_appliedBlendSrc = nCine::BlendingFactor::One;
133 nCine::BlendingFactor g_appliedBlendDst = nCine::BlendingFactor::Zero;
134
135 bool g_appliedScissorValid = false;
136 bool g_appliedScissorEnabled = false;
137 Recti g_appliedScissorRect(0, 0, 0, 0);
138 const void* g_appliedScissorTarget = nullptr;
139
140 void InvalidateAppliedState()
141 {
142 g_appliedProjectionValid = false;
143 g_appliedBlendValid = false;
144 g_appliedScissorValid = false;
145 }
146
147 enum class TevMode
148 {
149 Modulate, // texel * vertex colour (the default sprite combine)
150 Silhouette, // vertex colour, masked by the texel alpha
151 ModulateBrighten, // texel * vertex colour, scaled x2 and clamped
152 ModulateScaled4, // texel * vertex colour, scaled x4 and clamped
153 TintMix, // mix(texel, vertex colour, vertex alpha), opaque (the warp's horizon tint)
154 // The two-stage program: a modulate pass with a flat silhouette alpha-blended over
155 // it, folded into a single premultiplied draw (the FrozenMask pair - see the equivalence
156 // derivation at EffectContext::SubmitMergedSilhouetteOver)
157 ModulateSilhouetteOver,
158 // The same fold, but the silhouette's tone is picked per texel from a two-endpoint ramp by
159 // the texel's amplified luminance instead of being flat (FrozenMask's ice - six stages,
160 // see the stage-by-stage derivation in SetTevMode)
161 ModulateLumaRampOver
162 };
163
164 TevMode g_tevMode = TevMode::Modulate;
165
166 // Whether the luminance program's per-stage channel swizzles are currently installed. They are
167 // the only thing in this renderer that touches GX_SetTevSwapMode, and stage swap selections are
168 // persistent register state, so leaving the mode has to put stages 1-3 back on the identity
169 // table or every later draw would sample a replicated channel instead of the texel.
170 bool g_tevSwizzledStages = false;
171
172 // How the luminance ramp weighs the texel channels: Rec.601, the same coefficients the GLSL
173 // above every LUMA_RAMP pass uses
174 constexpr float LumaWeights[3] = { 0.299f, 0.587f, 0.114f };
175
176 // Puts the channel swizzles the luminance program installs back on the identity table. Stage
177 // swap selections persist like every other TEV register, so this runs on every path that leaves
178 // that program (SetTevMode's mode change and the vertex-format reset below).
179 void ResetTevSwizzles()
180 {
181 if (!g_tevSwizzledStages) {
182 return;
183 }
184 g_tevSwizzledStages = false;
185 GX_SetTevSwapMode(GX_TEVSTAGE1, GX_TEV_SWAP0, GX_TEV_SWAP0);
186 GX_SetTevSwapMode(GX_TEVSTAGE2, GX_TEV_SWAP0, GX_TEV_SWAP0);
187 GX_SetTevSwapMode(GX_TEVSTAGE3, GX_TEV_SWAP0, GX_TEV_SWAP0);
188 }
189
190 void SetVertexModeTextured(bool textured)
191 {
192 if (g_vertexModeTextured == textured) {
193 return;
194 }
195 g_vertexModeTextured = textured;
196 GX_ClearVtxDesc();
197 GX_SetVtxDesc(GX_VA_POS, GX_DIRECT);
198 GX_SetVtxDesc(GX_VA_CLR0, GX_DIRECT);
199 if (textured) {
200 GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT);
201 }
202 GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0);
203 GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0);
204 if (textured) {
205 GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0);
206 }
207 GX_SetNumTexGens(textured ? 1 : 0);
208 if (textured) {
209 GX_SetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY);
210 }
211 GX_SetNumChans(1);
212 GX_SetNumTevStages(1);
213 GX_SetTevOrder(GX_TEVSTAGE0, textured ? GX_TEXCOORD0 : GX_TEXCOORDNULL,
214 textured ? GX_TEXMAP0 : GX_TEXMAP_NULL, GX_COLOR0A0);
215 GX_SetTevOp(GX_TEVSTAGE0, textured ? GX_MODULATE : GX_PASSCLR);
216 ResetTevSwizzles();
217 g_tevMode = TevMode::Modulate;
218 }
219
220 // How many TEV stages a mode's program occupies
221 std::uint8_t TevStageCount(TevMode mode)
222 {
223 switch (mode) {
224 case TevMode::ModulateSilhouetteOver: return 2;
225 case TevMode::ModulateLumaRampOver: return 6;
226 default: return 1;
227 }
228 }
229
230 // How the TEV stage combines the sampled texel with the vertex colour. The actor state effects are
231 // per-texel colour transforms in GLSL, which the fixed-function pipe expresses by choosing the
232 // combine mode (and, for the outline, by drawing offset silhouettes - see Dispatch).
233 void SetTevMode(TevMode mode)
234 {
235 if (g_tevMode == mode) {
236 return;
237 }
238 // Only the merged modes run more than one stage; the register write is paid solely when the
239 // count actually changes (SetVertexModeTextured also resets it to 1 and the mode to Modulate)
240 if (TevStageCount(mode) != TevStageCount(g_tevMode)) {
241 GX_SetNumTevStages(TevStageCount(mode));
242 }
243 // Only the luminance program swizzles its texture inputs; anything else needs the identity
244 if (mode != TevMode::ModulateLumaRampOver) {
245 ResetTevSwizzles();
246 }
247 g_tevMode = mode;
248 switch (mode) {
249 case TevMode::Modulate:
250 GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE);
251 break;
252 case TevMode::Silhouette:
253 // rgb = vertex colour, alpha = texel alpha * vertex alpha: the sprite shape filled with
254 // a flat colour, which is what a fully saturated mask (luma * 6 in the shader) becomes
255 GX_SetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_ZERO, GX_CC_ZERO, GX_CC_RASC);
256 GX_SetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
257 GX_SetTevAlphaIn(GX_TEVSTAGE0, GX_CA_ZERO, GX_CA_TEXA, GX_CA_RASA, GX_CA_ZERO);
258 GX_SetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
259 break;
260 case TevMode::ModulateScaled4:
261 // Same combine as ModulateBrighten with a x4 output scale, which lets a vertex colour
262 // carry a multiplier of up to 4.0 (encoded as a quarter of it) instead of just 1.0
263 GX_SetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_TEXC, GX_CC_RASC, GX_CC_ZERO);
264 GX_SetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_4, GX_TRUE, GX_TEVPREV);
265 GX_SetTevAlphaIn(GX_TEVSTAGE0, GX_CA_ZERO, GX_CA_TEXA, GX_CA_RASA, GX_CA_ZERO);
266 GX_SetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
267 break;
268 case TevMode::ModulateBrighten:
269 // The clamped x2 colour scale stands in for the shader's "luma * 2.5, saturated": the
270 // sprite keeps its shading but is pushed toward white
271 GX_SetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_TEXC, GX_CC_RASC, GX_CC_ZERO);
272 GX_SetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_2, GX_TRUE, GX_TEVPREV);
273 GX_SetTevAlphaIn(GX_TEVSTAGE0, GX_CA_ZERO, GX_CA_TEXA, GX_CA_RASA, GX_CA_ZERO);
274 GX_SetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
275 break;
276 case TevMode::TintMix:
277 // One stage of `d + mix(a, b, c)`: the texel lerped toward the vertex colour by the
278 // vertex ALPHA, which is how a per-row tint becomes part of the textured draw
279 // instead of a second gradient pass over it (the TexturedBackground horizon).
280 // rgb = tex * (1 - rasa) + rasc * rasa
281 GX_SetTevColorIn(GX_TEVSTAGE0, GX_CC_TEXC, GX_CC_RASC, GX_CC_RASA, GX_CC_ZERO);
282 GX_SetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
283 // alpha = 1: the vertex alpha is spent on the lerp, and the effects using this are
284 // opaque (their GLSL ends with "COLOR.a = 1.0"). The konst-alpha SELECTION is the
285 // 1.0 constant, so no KONST register is consumed.
286 GX_SetTevKAlphaSel(GX_TEVSTAGE0, GX_TEV_KASEL_1);
287 GX_SetTevAlphaIn(GX_TEVSTAGE0, GX_CA_ZERO, GX_CA_ZERO, GX_CA_ZERO, GX_CA_KONST);
288 GX_SetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
289 break;
290 case TevMode::ModulateLumaRampOver:
291 /*
292 The luminance-ramp form of the merged draw below: same premultiplied output and
293 same ONE + INVSRCALPHA blend, but the silhouette's tone is picked per TEXEL from a
294 two-endpoint ramp instead of being one flat colour, so a dark sprite pixel keeps a
295 darker ice than a bright one (the GLSL's "grey" term). Six stages, with
296
297 t = texel alpha iceA = KONST0.a s = t * iceA
298 W = KONST0.rgb ramp0 = REG1.rgb ramp1 = KONST1.rgb
299 grey = min(2 * dot(tex.rgb, W), 1)
300 ice = mix(ramp0, ramp1, grey)
301
302 stage 0 C: REG2 = tex.rgb * t (the premultiplied sprite)
303 A: REG0 = t * iceA = s
304 stage 1 C: PREV = W.r * tex.r (texture swap table 1 -> rrr)
305 stage 2 C: PREV = PREV + W.g * tex.g (swap table 2 -> ggg)
306 stage 3 C: PREV = (PREV + W.b * tex.b) * 2, clamped = grey (swap 3 -> bbb)
307 stage 4 C: PREV = mix(ramp0, ramp1, grey) = ice
308 stage 5 C: PREV = mix(REG2, ice, s) = the premultiplied colour
309 A: PREV = mix(t, 1, s) = the coverage
310
311 The x2 output scale of stage 3 is where the caller's LumaGain lives: it hands the
312 weights in as W = Rec.601 * gain/2, so any gain up to ~3.4 fits the 0..1 KONST
313 range exactly. Clamping a PARTIAL sum at stage 2 or 3 cannot lose anything: a
314 partial sum reaching 1 already implies 2 * dot >= 2, i.e. grey saturates anyway.
315 The alpha pipes of stages 1-4 have no work, so they park their result in REG1's
316 alpha (only REG1's RGB is ever read back).
317 */
318 for (std::uint8_t stage = GX_TEVSTAGE1; stage <= GX_TEVSTAGE5; stage++) {
319 GX_SetTevOrder(stage, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0);
320 }
321 // The identity table plus the three single-channel replications the dot product needs.
322 // Set explicitly rather than trusting the GX defaults, and undone by ResetTevSwizzles()
323 // as soon as any other program is installed.
324 GX_SetTevSwapModeTable(GX_TEV_SWAP0, GX_CH_RED, GX_CH_GREEN, GX_CH_BLUE, GX_CH_ALPHA);
325 GX_SetTevSwapModeTable(GX_TEV_SWAP1, GX_CH_RED, GX_CH_RED, GX_CH_RED, GX_CH_ALPHA);
326 GX_SetTevSwapModeTable(GX_TEV_SWAP2, GX_CH_GREEN, GX_CH_GREEN, GX_CH_GREEN, GX_CH_ALPHA);
327 GX_SetTevSwapModeTable(GX_TEV_SWAP3, GX_CH_BLUE, GX_CH_BLUE, GX_CH_BLUE, GX_CH_ALPHA);
328 GX_SetTevSwapMode(GX_TEVSTAGE1, GX_TEV_SWAP0, GX_TEV_SWAP1);
329 GX_SetTevSwapMode(GX_TEVSTAGE2, GX_TEV_SWAP0, GX_TEV_SWAP2);
330 GX_SetTevSwapMode(GX_TEVSTAGE3, GX_TEV_SWAP0, GX_TEV_SWAP3);
331 g_tevSwizzledStages = true;
332 GX_SetTevKAlphaSel(GX_TEVSTAGE0, GX_TEV_KASEL_K0_A);
333 GX_SetTevKColorSel(GX_TEVSTAGE1, GX_TEV_KCSEL_K0_R);
334 GX_SetTevKColorSel(GX_TEVSTAGE2, GX_TEV_KCSEL_K0_G);
335 GX_SetTevKColorSel(GX_TEVSTAGE3, GX_TEV_KCSEL_K0_B);
336 GX_SetTevKColorSel(GX_TEVSTAGE4, GX_TEV_KCSEL_K1);
337 GX_SetTevKAlphaSel(GX_TEVSTAGE5, GX_TEV_KASEL_1);
338 // Stage 0 - premultiply the sprite, and the merged silhouette weight
339 GX_SetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_TEXC, GX_CC_TEXA, GX_CC_ZERO);
340 GX_SetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVREG2);
341 GX_SetTevAlphaIn(GX_TEVSTAGE0, GX_CA_ZERO, GX_CA_TEXA, GX_CA_KONST, GX_CA_ZERO);
342 GX_SetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVREG0);
343 // Stages 1-3 - the weighted channel sum, scaled and saturated into `grey`
344 GX_SetTevColorIn(GX_TEVSTAGE1, GX_CC_ZERO, GX_CC_TEXC, GX_CC_KONST, GX_CC_ZERO);
345 GX_SetTevColorOp(GX_TEVSTAGE1, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
346 GX_SetTevColorIn(GX_TEVSTAGE2, GX_CC_ZERO, GX_CC_TEXC, GX_CC_KONST, GX_CC_CPREV);
347 GX_SetTevColorOp(GX_TEVSTAGE2, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
348 GX_SetTevColorIn(GX_TEVSTAGE3, GX_CC_ZERO, GX_CC_TEXC, GX_CC_KONST, GX_CC_CPREV);
349 GX_SetTevColorOp(GX_TEVSTAGE3, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_2, GX_TRUE, GX_TEVPREV);
350 // Stage 4 - the ramp lookup, stage 5 - the premultiplied mix and the coverage
351 GX_SetTevColorIn(GX_TEVSTAGE4, GX_CC_C1, GX_CC_KONST, GX_CC_CPREV, GX_CC_ZERO);
352 GX_SetTevColorOp(GX_TEVSTAGE4, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
353 GX_SetTevColorIn(GX_TEVSTAGE5, GX_CC_C2, GX_CC_CPREV, GX_CC_A0, GX_CC_ZERO);
354 GX_SetTevColorOp(GX_TEVSTAGE5, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
355 GX_SetTevAlphaIn(GX_TEVSTAGE5, GX_CA_TEXA, GX_CA_KONST, GX_CA_A0, GX_CA_ZERO);
356 GX_SetTevAlphaOp(GX_TEVSTAGE5, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
357 // The idle alpha pipes; REG1's alpha is scratch, only its RGB (the ramp's low end) is read
358 for (std::uint8_t stage = GX_TEVSTAGE1; stage <= GX_TEVSTAGE4; stage++) {
359 GX_SetTevAlphaIn(stage, GX_CA_ZERO, GX_CA_ZERO, GX_CA_ZERO, GX_CA_ZERO);
360 GX_SetTevAlphaOp(stage, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVREG1);
361 }
362 break;
363 case TevMode::ModulateSilhouetteOver:
364 // The merged FrozenMask draw emits the PREMULTIPLIED source of its two original
365 // passes and blends with ONE + INVSRCALPHA (set by the caller). With t = texel
366 // alpha, iceA = KONST0.a and s = t * iceA, the stages compute
367 // colour = mix(tex.rgb * t, KONST0.rgb, s)
368 // alpha = mix(t, 1, s) = 1 - (1 - t)*(1 - s)
369 // which SubmitMergedSilhouetteOver derives to be exactly the two-pass result. The
370 // silhouette colour rides in KONST0 (per-draw), the raster colour is unused.
371 GX_SetTevOrder(GX_TEVSTAGE1, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0);
372 GX_SetTevKAlphaSel(GX_TEVSTAGE0, GX_TEV_KASEL_K0_A);
373 GX_SetTevKColorSel(GX_TEVSTAGE1, GX_TEV_KCSEL_K0);
374 // Stage 1 lerps its alpha toward the CONSTANT 1.0, so its konst-alpha selection is
375 // the 1.0 constant, not the K0 register stage 0 reads
376 GX_SetTevKAlphaSel(GX_TEVSTAGE1, GX_TEV_KASEL_1);
377 // Stage 0: PREV.rgb = tex.rgb * t (the premultiplied sprite), PREV.a = s = t * iceA
378 GX_SetTevColorIn(GX_TEVSTAGE0, GX_CC_ZERO, GX_CC_TEXC, GX_CC_TEXA, GX_CC_ZERO);
379 GX_SetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
380 GX_SetTevAlphaIn(GX_TEVSTAGE0, GX_CA_ZERO, GX_CA_TEXA, GX_CA_KONST, GX_CA_ZERO);
381 GX_SetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
382 // Stage 1: PREV.rgb = mix(PREV.rgb, ice.rgb, s), PREV.a = mix(t, 1, s)
383 GX_SetTevColorIn(GX_TEVSTAGE1, GX_CC_CPREV, GX_CC_KONST, GX_CC_APREV, GX_CC_ZERO);
384 GX_SetTevColorOp(GX_TEVSTAGE1, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
385 GX_SetTevAlphaIn(GX_TEVSTAGE1, GX_CA_TEXA, GX_CA_KONST, GX_CA_APREV, GX_CA_ZERO);
386 GX_SetTevAlphaOp(GX_TEVSTAGE1, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV);
387 break;
388 }
389 }
390
391 }
392
393 // EffectContext deliberately has EXTERNAL linkage (namespace scope, though it is still
394 // defined only in this translation unit): the generated table struct below is itself at
395 // namespace scope - so the backend's ShaderProgram can forward-declare it and hold a typed
396 // entry pointer - and names EffectContext in a member type; the console toolchain's GCC
397 // ICEs when such an external struct member references an internal-linkage type.
398 // ---------------------------------------------------------- fixed-function quad effects
399 //
400 // The quad-family effects are expressed as FixedFunctionPass descriptors handed to this
401 // EffectContext - the structural contract documented in FixedFunctionPass.h. The per-effect
402 // functions live in the shaders' fixed_function blocks and are transpiled by the
403 // ShaderCompiler into Shaders/Generated/GxGeneratedEffects.h, included below against this
404 // concrete context (see Docs/FixedFunctionShaderDesign.md); only the submission machinery
405 // stays here.
406
407 struct EffectContext
408 {
409 // The strip builder stays small - a bigger scratch would only grow the per-instance stack -
410 // but the GP is happier with fewer, longer primitives than with many 4-vertex ones, so this
411 // holds 16 (twice the contract's floor): enough for the iris fan to submit one angular wedge
412 // with all five of its radii as a SINGLE strip. The fixed-function transpiler knows this
413 // number and rejects literal strip indices/counts above it.
414 static constexpr std::int32_t MaxStripVertices = 16;
415
416 // Decoded instance data of the draw being dispatched (the documented contract)
417 const float* InstanceColor;
418 float TexelW;
419 float TexelH;
420 bool Batched;
421
422 // Backend internals the pass state maps onto: the current instance's corner arrays,
423 // whether the vertex stream carries texture coordinates, and the material blend
424 // arguments (for restoring after a pass-level blend override)
425 const float* Px;
426 const float* Py;
427 const float* Pu;
428 const float* Pv;
429 const float* TexRect;
430 bool HasTexture;
431 std::uint8_t MaterialBlendOp;
432 std::uint8_t MaterialBlendSrc;
433 std::uint8_t MaterialBlendDst;
434 bool* BlendOverridden;
435
436 // The pass merger's whole state: whether the previous SubmitQuad was buffered instead of
437 // submitted. Only one pass shape is ever buffered - the fully DEFAULT modulate pass (the
438 // first half of the FrozenMask pair, see SubmitQuad) - so a flag carries everything and a
439 // flush can simply rebuild that default pass.
440 bool PendingBasePass = false;
441
442 // Pre-clip quad geometry (the quad_origin/quad_axis_* built-ins - on the GX the corners are
443 // never clipped, the hardware scissor does that, but the contract stays shared with the
444 // PVR) and the program, for resolved uniforms
445 float OriginX, OriginY;
446 float AxisXx, AxisXy;
447 float AxisYx, AxisYy;
448 const GxShaderProgram* Program;
449
450 // The strip builder scratch; colours are quantized at set time (same quantization as the
451 // quad path, so identical float inputs produce identical vertex words). GX textures are
452 // not padded, so UVs pass through unscaled - the scale fields exist for contract parity.
453 float UvScaleU, UvScaleV;
454 float StripX[MaxStripVertices];
455 float StripY[MaxStripVertices];
456 float StripU[MaxStripVertices];
457 float StripV[MaxStripVertices];
458 std::uint8_t StripR[MaxStripVertices];
459 std::uint8_t StripG[MaxStripVertices];
460 std::uint8_t StripB[MaxStripVertices];
461 std::uint8_t StripA[MaxStripVertices];
462
463 const float* Color() const { return InstanceColor; }
464 float TexelWidth() const { return TexelW; }
465 float TexelHeight() const { return TexelH; }
466 bool IsBatched() const { return Batched; }
467
468 float QuadOriginX() const { return OriginX; }
469 float QuadOriginY() const { return OriginY; }
470 float QuadAxisXx() const { return AxisXx; }
471 float QuadAxisXy() const { return AxisXy; }
472 float QuadAxisYx() const { return AxisYx; }
473 float QuadAxisYy() const { return AxisYy; }
474
475 bool HasUniform(const char* name) const
476 {
477 return (Program->ResolveUniform(name) != nullptr);
478 }
479 void LoadUniform(const char* name, float* out, std::int32_t floatCount) const
480 {
481 // An unresolved name leaves the caller's zeros in place - blocks guard with
482 // has_uniform() exactly like handwritten code null-checked the pointers
483 const std::uint8_t* bytes = Program->ResolveUniform(name);
484 if (bytes != nullptr) {
485 std::memcpy(out, bytes, std::size_t(floatCount) * sizeof(float));
486 }
487 }
488
489 void SetStripVertexPosition(std::int32_t i, float x, float y)
490 {
491 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
492 StripX[i] = x;
493 StripY[i] = y;
494 }
495 }
496 void SetStripVertexUv(std::int32_t i, float u, float v)
497 {
498 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
499 StripU[i] = u * UvScaleU;
500 StripV[i] = v * UvScaleV;
501 }
502 }
503 void SetStripVertexColor(std::int32_t i, float r, float g, float b, float a)
504 {
505 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
506 StripR[i] = QuantizeChannel(r);
507 StripG[i] = QuantizeChannel(g);
508 StripB[i] = QuantizeChannel(b);
509 StripA[i] = QuantizeChannel(a);
510 }
511 }
512
513 // Whether a UV span can be mapped onto the screen at all (a zero texRect has no scale)
514 bool HasTexelStep() const { return TexRect[0] != 0.0f && TexRect[2] != 0.0f; }
515 // Maps a span in the sprite's UV space onto the quad's on-screen extent - the texel step
516 // the Outline ring taps use (logical pixels, the space the corners live in)
517 float TexelToScreenX(float uvSpan) const { return (Px[0] - Px[2]) * (uvSpan / TexRect[0]); }
518 float TexelToScreenY(float uvSpan) const { return (Py[1] - Py[0]) * (uvSpan / TexRect[2]); }
519 // The documented texel_size() built-in of the fixed_function contract: the Outline shader
520 // family carries the sprite's UV-space texel size in its instance color.xy (exactly like
521 // the GLSL derives its tap offsets), mapped into the logical pixels the corners live in
522 float TexelStepX() const { return TexelToScreenX(InstanceColor[0]); }
523 float TexelStepY() const { return TexelToScreenY(InstanceColor[1]); }
524
525 // Emits the quad at an optional screen-space offset, in the given colour
526 void Emit(float dx, float dy, float cr, float cg, float cb, float ca) const
527 {
528 const std::uint8_t r = QuantizeChannel(cr);
529 const std::uint8_t g = QuantizeChannel(cg);
530 const std::uint8_t b = QuantizeChannel(cb);
531 const std::uint8_t a = QuantizeChannel(ca);
532 // Strip order (v0, v1, v2, v3) forms the quad perimeter (v0, v1, v3, v2)
533 GX_Begin(GX_QUADS, GX_VTXFMT0, 4);
534 if (HasTexture) {
535 GX_Position3f32(Px[0] + dx, Py[0] + dy, 0.0f); GX_Color4u8(r, g, b, a); GX_TexCoord2f32(Pu[0], Pv[0]);
536 GX_Position3f32(Px[1] + dx, Py[1] + dy, 0.0f); GX_Color4u8(r, g, b, a); GX_TexCoord2f32(Pu[1], Pv[1]);
537 GX_Position3f32(Px[3] + dx, Py[3] + dy, 0.0f); GX_Color4u8(r, g, b, a); GX_TexCoord2f32(Pu[3], Pv[3]);
538 GX_Position3f32(Px[2] + dx, Py[2] + dy, 0.0f); GX_Color4u8(r, g, b, a); GX_TexCoord2f32(Pu[2], Pv[2]);
539 } else {
540 GX_Position3f32(Px[0] + dx, Py[0] + dy, 0.0f); GX_Color4u8(r, g, b, a);
541 GX_Position3f32(Px[1] + dx, Py[1] + dy, 0.0f); GX_Color4u8(r, g, b, a);
542 GX_Position3f32(Px[3] + dx, Py[3] + dy, 0.0f); GX_Color4u8(r, g, b, a);
543 GX_Position3f32(Px[2] + dx, Py[2] + dy, 0.0f); GX_Color4u8(r, g, b, a);
544 }
545 GX_End();
546 }
547
548 // A pass-level blend override bypasses ApplyRenderState(), so its cache no longer
549 // matches; the material blend is reissued as soon as a Material pass follows
550 void ApplyPassBlend(const FixedFunctionPass& pass)
551 {
552 if (pass.Blend != FixedFunctionPass::BlendMode::Material) {
553 switch (pass.Blend) {
554 case FixedFunctionPass::BlendMode::Additive:
555 GX_SetBlendMode(GX_BM_BLEND, GX_BL_ONE, GX_BL_ONE, GX_LO_CLEAR);
556 break;
557 case FixedFunctionPass::BlendMode::Alpha:
558 GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
559 break;
560 default: // Opaque
561 GX_SetBlendMode(GX_BM_NONE, GX_BL_ONE, GX_BL_ZERO, GX_LO_CLEAR);
562 break;
563 }
564 g_appliedBlendValid = false;
565 *BlendOverridden = true;
566 } else if (*BlendOverridden) {
567 GX_SetBlendMode(MaterialBlendOp, MaterialBlendSrc, MaterialBlendDst, GX_LO_CLEAR);
568 *BlendOverridden = false;
569 }
570 }
571
572 // The TEV combine a pass's intent maps onto (shared by the quad and strip submissions)
573 void ApplyPassTev(const FixedFunctionPass& pass) const
574 {
575 TevMode mode;
576 switch (pass.Tev) {
577 case FixedFunctionPass::TevPreset::Silhouette: mode = TevMode::Silhouette; break;
578 case FixedFunctionPass::TevPreset::ModulateX2: mode = TevMode::ModulateBrighten; break;
579 case FixedFunctionPass::TevPreset::ModulateX4: mode = TevMode::ModulateScaled4; break;
580 // The lerp needs the texel; without one the stage would blend toward garbage, so an
581 // untextured draw falls back to the plain interpolated colour
582 case FixedFunctionPass::TevPreset::TintMix: mode = (HasTexture ? TevMode::TintMix : TevMode::Modulate); break;
583 // LUMA_RAMP lands in the default only if it never found a base pass to merge with, and
584 // it always carries an offset colour, so both submission paths have already peeled it
585 // off into their flat-silhouette branch before reaching here
586 default: mode = TevMode::Modulate; break;
587 }
588 SetTevMode(mode);
589 }
590
591 // Loads the per-draw registers of the luminance-ramp program: the Rec.601 weights prescaled by
592 // the pass's gain (halved, because stage 3 applies the combiner's x2 output scale) plus the
593 // merged silhouette weight in KONST0's alpha, the ramp's high end in KONST1 and its low end in
594 // TEV register 1. Only three register writes, and the stage program itself stays cached.
595 void LoadLumaRampRegisters(const FixedFunctionPass& pass) const
596 {
597 const float half = 0.5f * (pass.LumaGain > 0.0f ? pass.LumaGain : 0.0f);
598 GXColor weights = {
599 QuantizeChannel(LumaWeights[0] * half), QuantizeChannel(LumaWeights[1] * half),
600 QuantizeChannel(LumaWeights[2] * half), QuantizeChannel(pass.Color[3])
601 };
602 GX_SetTevKColor(GX_KCOLOR0, weights);
603 // The ramp: pass.color.rgb is the tone at grey = 0, pass.offset_color the tone at grey = 1
604 GXColor rampHigh = {
605 QuantizeChannel(pass.OffsetColor[0]), QuantizeChannel(pass.OffsetColor[1]),
606 QuantizeChannel(pass.OffsetColor[2]), 255
607 };
608 GX_SetTevKColor(GX_KCOLOR1, rampHigh);
609 GXColor rampLow = {
610 QuantizeChannel(pass.Color[0]), QuantizeChannel(pass.Color[1]),
611 QuantizeChannel(pass.Color[2]), 255
612 };
613 GX_SetTevColor(GX_TEVREG1, rampLow);
614 }
615
616 // Whether a pass is exactly the first half the merger buffers: the default "modulate the
617 // sprite by white over the material blend" pass. The colour must be white because the fold
618 // below has no stage input left to modulate the texel by a vertex colour, and the material
619 // blend must be the standard alpha-over - the fold bakes THAT equation into the TEV.
620 bool IsMergeableBasePass(const FixedFunctionPass& pass) const
621 {
622 return HasTexture && !pass.HasOffsetColor &&
623 pass.Blend == FixedFunctionPass::BlendMode::Material &&
624 pass.Tev == FixedFunctionPass::TevPreset::Modulate &&
625 pass.ScreenOffset[0] == 0.0f && pass.ScreenOffset[1] == 0.0f &&
626 pass.Color[0] == 1.0f && pass.Color[1] == 1.0f && pass.Color[2] == 1.0f && pass.Color[3] == 1.0f &&
627 MaterialBlendOp == GX_BM_BLEND && MaterialBlendSrc == GX_BL_SRCALPHA && MaterialBlendDst == GX_BL_INVSRCALPHA;
628 }
629
630 // Whether a pass is the second half: a silhouette alpha-blended over the sprite (the
631 // FrozenMask ice pass), either flat or with its tone picked per texel from a luminance ramp.
632 // Material blend was already verified to BE alpha-over by the base matcher, so both spellings
633 // of the same equation qualify. LUMA_RAMP is the one preset that legitimately carries an offset
634 // colour (the ramp's high end), which is why the offset-colour veto is per preset.
635 bool IsMergeableSilhouettePass(const FixedFunctionPass& pass) const
636 {
637 if (pass.Blend != FixedFunctionPass::BlendMode::Material && pass.Blend != FixedFunctionPass::BlendMode::Alpha) {
638 return false;
639 }
640 if (pass.ScreenOffset[0] != 0.0f || pass.ScreenOffset[1] != 0.0f) {
641 return false;
642 }
643 if (pass.Tev == FixedFunctionPass::TevPreset::LumaRamp) {
644 return true;
645 }
646 return (!pass.HasOffsetColor && pass.Tev == FixedFunctionPass::TevPreset::Silhouette);
647 }
648
649 /*
650 The merged form of the FrozenMask pair: the buffered default modulate pass plus this
651 silhouette pass, over the same corners, as ONE draw with a two-stage TEV program.
652
653 Equivalence derivation (t = texel alpha, iceA = the silhouette pass's alpha as its
654 vertex colour would have carried it, s = t * iceA; both original passes blended
655 SRCALPHA + INVSRCALPHA over the destination dst0):
656
657 pass 0 (modulate, white): dst1 = tex.rgb*t + dst0*(1 - t)
658 pass 1 (silhouette): dst2 = ice.rgb*s + dst1*(1 - s)
659 = [ice.rgb*s + tex.rgb*t*(1 - s)] + dst0*(1 - t)*(1 - s)
660
661 A single SRCALPHA-blended draw cannot express this - its source term would need the
662 division C = [...] / A - but a PREMULTIPLIED draw can. With blend ONE + INVSRCALPHA,
663
664 dst2' = C + dst0*(1 - A)
665
666 matches dst2 exactly when
667
668 C = ice.rgb*s + tex.rgb*t*(1 - s) = mix(tex.rgb*t, ice.rgb, s)
669 A = 1 - (1 - t)*(1 - s) = mix(t, 1, s)
670
671 which is precisely the two-stage program of TevMode::ModulateSilhouetteOver: stage 0
672 computes tex.rgb*t and s = t*KONST0.a, stage 1 lerps the colour toward KONST0.rgb and
673 the alpha toward 1.0, both by s. Exact in real arithmetic for EVERY texel alpha, not
674 only the 0/1 of cutout art. (Hardware-wise the TEV rounds each stage to 8 bits where
675 the two-pass form rounded in the blender per pass, so the last bit can differ; the
676 ice colour/alpha quantization itself is the same 8 bits the vertex colour used to
677 carry. EFB destination alpha is not stored on this pipe - RGB8_Z24 - so only the
678 colour equation has to match.)
679
680 The derivation only ever assumed that ice.rgb is SOME colour the combiner can produce per
681 fragment, so it holds unchanged when the silhouette asks for a LUMA_RAMP tone instead of a
682 flat one: the six-stage program of TevMode::ModulateLumaRampOver computes exactly the same
683 C and A, with ice.rgb = mix(ramp0, ramp1, grey) evaluated per texel.
684 */
685 void SubmitMergedSilhouetteOver(const FixedFunctionPass& silhouette)
686 {
687 // The fold replaces the material's SRCALPHA + INVSRCALPHA with its premultiplied form
688 // for this one draw; the next Material pass restores it through ApplyPassBlend
689 GX_SetBlendMode(GX_BM_BLEND, GX_BL_ONE, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
690 g_appliedBlendValid = false;
691 *BlendOverridden = true;
692 if (silhouette.Tev == FixedFunctionPass::TevPreset::LumaRamp) {
693 // The ramp needs three registers instead of one, on the same per-draw terms: the tone
694 // endpoints are constants of the effect, the merged weight animates per sprite
695 LoadLumaRampRegisters(silhouette);
696 SetTevMode(TevMode::ModulateLumaRampOver);
697 } else {
698 // KONST0 carries the silhouette colour and alpha; reloaded per merged draw because the
699 // ice alpha animates per sprite (the stage program itself is cached by SetTevMode)
700 GXColor konst = {
701 QuantizeChannel(silhouette.Color[0]), QuantizeChannel(silhouette.Color[1]),
702 QuantizeChannel(silhouette.Color[2]), QuantizeChannel(silhouette.Color[3])
703 };
704 GX_SetTevKColor(GX_KCOLOR0, konst);
705 SetTevMode(TevMode::ModulateSilhouetteOver);
706 }
707 // Every stage ignores the raster colour (the colour terms live in TEXC and the registers)
708 Emit(0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f);
709 }
710
711 // Immediate single-pass submission (the pre-merger SubmitQuad, byte-identical state math)
712 void SubmitQuadDirect(const FixedFunctionPass& pass)
713 {
714 ApplyPassBlend(pass);
715
716 if (pass.HasOffsetColor) {
717 // The GX has no post-texture offset add; a pass carrying an offset colour is the
718 // silhouette form of the same intent - the sprite's shape filled flat with that
719 // colour at the pass alpha (see the TevMode::Silhouette combine). A LUMA_RAMP pass
720 // that reached here never found its base pass to merge with (no texture, or a
721 // material blend the fold cannot absorb), and degrades to the same flat silhouette
722 // filled with the ramp's high end - which is the tone every saturated texel would
723 // have picked anyway.
724 SetTevMode(TevMode::Silhouette);
725 Emit(pass.ScreenOffset[0], pass.ScreenOffset[1],
726 pass.OffsetColor[0], pass.OffsetColor[1], pass.OffsetColor[2], pass.Color[3]);
727 return;
728 }
729 ApplyPassTev(pass);
730 Emit(pass.ScreenOffset[0], pass.ScreenOffset[1],
731 pass.Color[0], pass.Color[1], pass.Color[2], pass.Color[3]);
732 }
733
734 // Submits a buffered first-half pass that never found its silhouette partner (a strip
735 // followed, or the effect function returned) - the buffered shape is exactly the default
736 // pass, in its original submission slot: nothing else was emitted since it was buffered
737 void FlushPendingQuad()
738 {
739 if (PendingBasePass) {
740 PendingBasePass = false;
741 FixedFunctionPass base;
742 SubmitQuadDirect(base);
743 }
744 }
745
746 void SubmitQuad(const FixedFunctionPass& pass)
747 {
748 // Two consecutive passes over the SAME quad that together read "sprite, then flat
749 // silhouette alpha-blended over it" (the FrozenMask pair) collapse into one draw with
750 // two TEV stages. The first half is buffered instead of submitted eagerly and flushed
751 // unmerged as soon as anything else follows; the corners cannot change between the two
752 // halves because the context is built per instance, so "same quad" holds by scope, and
753 // both matchers require zero screen offsets and a compatible blend up front.
754 if (PendingBasePass) {
755 PendingBasePass = false;
756 if (IsMergeableSilhouettePass(pass)) {
757 SubmitMergedSilhouetteOver(pass);
758 return;
759 }
760 FixedFunctionPass base;
761 SubmitQuadDirect(base);
762 } else if (IsMergeableBasePass(pass)) {
763 PendingBasePass = true;
764 return;
765 }
766 SubmitQuadDirect(pass);
767 }
768
769 // Textured strip out of the builder scratch: the pass's flat colour over the material
770 // state, drawn through the GP's native triangle strip
771 void SubmitStrip(const FixedFunctionPass& pass, std::int32_t count)
772 {
773 // A strip is different geometry - a buffered quad pass can no longer find its partner
774 FlushPendingQuad();
775 if (count > MaxStripVertices) {
776 count = MaxStripVertices;
777 }
778 if (count < 3) {
779 return;
780 }
781 ApplyPassBlend(pass);
782 float cr = pass.Color[0], cg = pass.Color[1], cb = pass.Color[2];
783 if (pass.HasOffsetColor) {
784 // Same intent mapping as SubmitQuad: no post-texture add on the GX, so an offset
785 // colour becomes the silhouette form filled flat with it at the pass alpha
786 SetTevMode(TevMode::Silhouette);
787 cr = pass.OffsetColor[0]; cg = pass.OffsetColor[1]; cb = pass.OffsetColor[2];
788 } else {
789 ApplyPassTev(pass);
790 }
791 const std::uint8_t r = QuantizeChannel(cr);
792 const std::uint8_t g = QuantizeChannel(cg);
793 const std::uint8_t b = QuantizeChannel(cb);
794 const std::uint8_t a = QuantizeChannel(pass.Color[3]);
795 const float dx = pass.ScreenOffset[0], dy = pass.ScreenOffset[1];
796 GX_Begin(GX_TRIANGLESTRIP, GX_VTXFMT0, std::uint16_t(count));
797 for (std::int32_t i = 0; i < count; i++) {
798 GX_Position3f32(StripX[i] + dx, StripY[i] + dy, 0.0f);
799 GX_Color4u8(r, g, b, a);
800 if (HasTexture) {
801 GX_TexCoord2f32(StripU[i], StripV[i]);
802 }
803 }
804 GX_End();
805 }
806
807 // Shaded (per-vertex-colour) strip out of the builder scratch. A pure gradient has no texture
808 // to modulate, so the vertex descriptor drops to the colour-only layout (whose PASSCLR combine
809 // is exactly "the interpolated vertex colour") for the strip and is restored right after,
810 // keeping later passes of the same instance intact. The exception is a pass whose TEV preset
811 // CONSUMES the texel alongside the interpolated colour (TevPreset::TintMix): that strip stays
812 // textured and carries its UVs, which is how the warp's horizon tint rides along inside the
813 // band's own draw instead of needing a second gradient pass over it.
814 void SubmitStripShaded(const FixedFunctionPass& pass, std::int32_t count)
815 {
816 // A strip is different geometry - a buffered quad pass can no longer find its partner
817 FlushPendingQuad();
818 if (count > MaxStripVertices) {
819 count = MaxStripVertices;
820 }
821 if (count < 3) {
822 return;
823 }
824 ApplyPassBlend(pass);
825 const bool textured = (HasTexture && pass.Tev == FixedFunctionPass::TevPreset::TintMix);
826 if (HasTexture) {
827 // A gradient must not carry texture coordinates and a tinted strip must; either way
828 // the format is only reprogrammed when it actually differs from the current one
829 SetVertexModeTextured(textured);
830 }
831 if (textured) {
832 // The combine is programmed AFTER any vertex-format change, which resets it
833 ApplyPassTev(pass);
834 }
835 const float dx = pass.ScreenOffset[0], dy = pass.ScreenOffset[1];
836 GX_Begin(GX_TRIANGLESTRIP, GX_VTXFMT0, std::uint16_t(count));
837 for (std::int32_t i = 0; i < count; i++) {
838 GX_Position3f32(StripX[i] + dx, StripY[i] + dy, 0.0f);
839 GX_Color4u8(StripR[i], StripG[i], StripB[i], StripA[i]);
840 if (textured) {
841 GX_TexCoord2f32(StripU[i], StripV[i]);
842 }
843 }
844 GX_End();
845 if (HasTexture && !textured) {
846 SetVertexModeTextured(true);
847 }
848 }
849 };
850 }
851
852 // The per-effect functions themselves are GENERATED: the ShaderCompiler transpiles each shader's
853 // fixed_function block into C++ over the EffectContext defined above (the type name itself is the
854 // "using EffectContext = ...;" alias the header expects - the anonymous namespace above is the same
855 // namespace the header's payload reopens within this translation unit). Included at global scope
856 // because the header opens nCine::RHI::GX itself.
857 #include "../../../../Shaders/Generated/GxGeneratedEffects.h"
858
859 namespace nCine::RHI::GX
860 {
861 const FixedFunctionGeneratedEffect* GxDevice::FindGeneratedEffect(const char* program, const char* variant)
862 {
863 // A linear scan is fine - the lookup runs once per program load, not per draw
864 for (std::size_t i = 0; i < FixedFunctionGeneratedEffectCount; i++) {
865 const FixedFunctionGeneratedEffect& e = FixedFunctionGeneratedEffects[i];
866 if (std::strcmp(e.Program, program) == 0 && std::strcmp(e.Variant, variant) == 0) {
867 return &e;
868 }
869 }
870 return nullptr;
871 }
872
873 GxDevice::BlendingState GxDevice::_blending;
874 GxDevice::DepthTestState GxDevice::_depthTest;
875 GxDevice::CullFaceState GxDevice::_cullFace;
876 GxDevice::ScissorState GxDevice::_scissor;
877 Recti GxDevice::_viewport(0, 0, 0, 0);
878 Colorf GxDevice::_clearColor(0.0f, 0.0f, 0.0f, 1.0f);
879
880 GxShaderProgram* GxDevice::_currentProgram = nullptr;
881 const GxTexture* GxDevice::_boundTextures[GxDevice::MaxTextureUnits] = {};
882 GxDevice::UniformRange GxDevice::_boundUniformRanges[GxDevice::MaxUniformBindings] = {};
883 GxRenderTarget* GxDevice::_currentRenderTarget = nullptr;
884
885 GXRModeObj* GxDevice::_rmode = nullptr;
886 void* GxDevice::_gxFifo = nullptr;
887 bool GxDevice::_gxInitialized = false;
888 std::int32_t GxDevice::_logicalWidth = 0;
889 std::int32_t GxDevice::_logicalHeight = 0;
890
891 GxTexture* GxDevice::_paletteTexture = nullptr;
892 std::uint32_t GxDevice::_paletteGeneration = 1;
893 GxDevice::TlutSlot GxDevice::_tlutSlots[GxDevice::MaxTlutSlots] = {};
894 std::uint32_t GxDevice::_tlutUseCounter = 0;
895 std::uint32_t GxDevice::_frameCounter = 0;
896
897 std::vector<GxDevice::PendingSoftwareLight> GxDevice::_pendingSoftwareLights;
898
899 std::uint8_t* GxDevice::_lightmapStore = nullptr;
900 std::size_t GxDevice::_lightmapStoreSize = 0;
901 GXTexObj GxDevice::_lightmapTexObj;
902 std::uint8_t* GxDevice::_lightmapLinear = nullptr;
903 std::size_t GxDevice::_lightmapLinearSize = 0;
904
905 // ------------------------------------------------------------------ session
906
907 void GxDevice::InitializeGx(GXRModeObj* rmode)
908 {
909 if (_gxInitialized) {
910 _rmode = rmode;
911 return;
912 }
913 _rmode = rmode;
914
915 // The FIFO must be accessed through the uncached alias, so the GP sees the commands immediately
916 _gxFifo = MEM_K0_TO_K1(memalign(32, GxFifoSize));
917 std::memset(_gxFifo, 0, GxFifoSize);
918 GX_Init(_gxFifo, GxFifoSize);
919
920 GXColor background = { 0, 0, 0, 255 };
921 GX_SetCopyClear(background, GX_MAX_Z24);
922
923 GX_SetViewport(0.0f, 0.0f, float(rmode->fbWidth), float(rmode->efbHeight), 0.0f, 1.0f);
924 GX_SetDispCopyYScale(float(rmode->xfbHeight) / float(rmode->efbHeight));
925 GX_SetScissor(0, 0, rmode->fbWidth, rmode->efbHeight);
926 GX_SetDispCopySrc(0, 0, rmode->fbWidth, rmode->efbHeight);
927 GX_SetDispCopyDst(rmode->fbWidth, rmode->xfbHeight);
928 GX_SetCopyFilter(rmode->aa, rmode->sample_pattern, GX_TRUE, rmode->vfilter);
929 GX_SetFieldMode(rmode->field_rendering, (rmode->viHeight == 2 * rmode->xfbHeight ? GX_ENABLE : GX_DISABLE));
930 GX_SetDispCopyGamma(GX_GM_1_0);
931
932 // 2D painter's-order pipeline: no depth, no culling, premultiplied ortho quads
933 GX_SetZMode(GX_FALSE, GX_LEQUAL, GX_FALSE);
934 GX_SetCullMode(GX_CULL_NONE);
935 GX_SetColorUpdate(GX_TRUE);
936
937 // Force the initial descriptor setup through the mode toggle, and start with no per-draw state
938 // assumed to be applied (a fresh GX session resets every register the caches stand in for)
939 g_vertexModeTextured = true;
940 SetVertexModeTextured(false);
941 InvalidateAppliedState();
942
943 _logicalWidth = rmode->fbWidth;
944 _logicalHeight = rmode->efbHeight;
945
946 _gxInitialized = true;
947 }
948
949 void GxDevice::ShutdownGx()
950 {
951 if (!_gxInitialized) {
952 return;
953 }
954
955 // Drop anything still queued and wait until the GP is idle. Leaving GP work in flight while the
956 // title exits keeps the graphics pipe busy after the CPU is gone, which stalls the shutdown.
957 GX_AbortFrame();
958 GX_Flush();
959 GX_DrawDone();
960
961 for (std::uint32_t i = 0; i < MaxTlutSlots; i++) {
962 if (_tlutSlots[i].Data != nullptr) {
963 free(_tlutSlots[i].Data);
964 _tlutSlots[i].Data = nullptr;
965 }
966 _tlutSlots[i].PaletteOffset = -1;
967 _tlutSlots[i].Palette = nullptr;
968 }
969
970 if (_gxFifo != nullptr) {
971 free(MEM_K1_TO_K0(_gxFifo));
972 _gxFifo = nullptr;
973 }
974
975 _rmode = nullptr;
976 _gxInitialized = false;
977 }
978
979 void GxDevice::PresentToXfb(void* xfb)
980 {
981 if (!_gxInitialized) {
982 return;
983 }
984 FlushCurrentRenderTarget();
985
986 // The display copy runs asynchronously on the GP; GX_DrawDone() after it drains the FIFO and waits
987 // until the copy has finished, so the following flip never displays a not-yet-copied buffer
988 GX_SetColorUpdate(GX_TRUE);
989 GX_CopyDisp(xfb, GX_TRUE); // The copy also clears the EFB for the next frame (GX_SetCopyClear)
990 GX_DrawDone();
991 _frameCounter++;
992 // Nothing is assumed applied across the frame boundary - the first draw of the next frame
993 // reissues projection and render state from scratch
994 InvalidateAppliedState();
995 }
996
997 void GxDevice::ResizeScreenFramebuffer(std::int32_t width, std::int32_t height)
998 {
999 if (width > 0 && height > 0) {
1000 _logicalWidth = width;
1001 _logicalHeight = height;
1002 // The logical size feeds both the ortho projection and the scissor scaling
1003 InvalidateAppliedState();
1004 }
1005 }
1006
1007 // ------------------------------------------------------------------ state
1008
1009 void GxDevice::SetBlendingEnabled(bool enabled) { _blending.Enabled = enabled; }
1010 void GxDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
1011 {
1012 _blending.SrcRgb = srcRgb;
1013 _blending.DstRgb = dstRgb;
1014 _blending.SrcAlpha = srcAlpha;
1015 _blending.DstAlpha = dstAlpha;
1016 }
1017 GxDevice::BlendingState GxDevice::GetBlendingState() { return _blending; }
1018 void GxDevice::SetBlendingState(const BlendingState& state) { _blending = state; }
1019
1020 void GxDevice::SetDepthTestEnabled(bool enabled) { _depthTest.TestEnabled = enabled; }
1021 void GxDevice::SetDepthMaskEnabled(bool enabled) { _depthTest.MaskEnabled = enabled; }
1022 GxDevice::DepthTestState GxDevice::GetDepthTestState() { return _depthTest; }
1023 void GxDevice::SetDepthTestState(const DepthTestState& state) { _depthTest = state; }
1024
1025 void GxDevice::SetCullFaceEnabled(bool enabled) { _cullFace.Enabled = enabled; }
1026 GxDevice::CullFaceState GxDevice::GetCullFaceState() { return _cullFace; }
1027 void GxDevice::SetCullFaceState(const CullFaceState& state) { _cullFace = state; }
1028
1029 GxDevice::ScissorState GxDevice::GetScissorState() { return _scissor; }
1030 void GxDevice::SetScissorState(const ScissorState& state) { _scissor = state; }
1031 void GxDevice::SetScissor(const Recti& rect)
1032 {
1033 // Same contract as the GL device: setting a rect also enables the test (callers like
1034 // RenderCommand and Viewport rely on it and restore via SetScissorState afterwards)
1035 _scissor.Enabled = true;
1036 _scissor.Rect = rect;
1037 }
1038 void GxDevice::SetScissorTestEnabled(bool enabled) { _scissor.Enabled = enabled; }
1039
1040 Recti GxDevice::GetViewport() { return _viewport; }
1041 void GxDevice::SetViewport(const Recti& rect) { _viewport = rect; }
1042 void GxDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
1043 {
1044 _viewport = Recti(x, y, width, height);
1045 }
1046
1047 Colorf GxDevice::GetClearColor() { return _clearColor; }
1048 void GxDevice::SetClearColor(const Colorf& color)
1049 {
1050 _clearColor = color;
1051 if (_gxInitialized) {
1052 GXColor c = { QuantizeChannel(color.R), QuantizeChannel(color.G), QuantizeChannel(color.B), QuantizeChannel(color.A) };
1053 GX_SetCopyClear(c, GX_MAX_Z24);
1054 }
1055 }
1056
1057 void GxDevice::Clear(ClearFlags flags)
1058 {
1059 static_cast<void>(flags);
1060 if (!_gxInitialized) {
1061 return;
1062 }
1063 // Immediate clear: a full-target flat quad (the EFB copy-clear only applies at copy time)
1064 ApplyProjection();
1065 // The direct blend-mode write below bypasses ApplyRenderState(), so its cache no longer matches
1066 g_appliedBlendValid = false;
1067 GX_SetBlendMode(GX_BM_NONE, GX_BL_ONE, GX_BL_ZERO, GX_LO_CLEAR);
1068 const std::int32_t w = (_currentRenderTarget != nullptr ? _viewport.W : _logicalWidth);
1069 const std::int32_t h = (_currentRenderTarget != nullptr ? _viewport.H : _logicalHeight);
1070 SetVertexModeTextured(false);
1071 const std::uint8_t r = QuantizeChannel(_clearColor.R), g = QuantizeChannel(_clearColor.G);
1072 const std::uint8_t b = QuantizeChannel(_clearColor.B), a = QuantizeChannel(_clearColor.A);
1073 GX_Begin(GX_QUADS, GX_VTXFMT0, 4);
1074 GX_Position3f32(0.0f, 0.0f, 0.0f); GX_Color4u8(r, g, b, a);
1075 GX_Position3f32(float(w), 0.0f, 0.0f); GX_Color4u8(r, g, b, a);
1076 GX_Position3f32(float(w), float(h), 0.0f); GX_Color4u8(r, g, b, a);
1077 GX_Position3f32(0.0f, float(h), 0.0f); GX_Color4u8(r, g, b, a);
1078 GX_End();
1079 }
1080
1081 // ------------------------------------------------------------------ per-draw state application
1082
1083 void GxDevice::ApplyProjection()
1084 {
1085 // Ortho projection over the current target's logical space; the GX viewport spans the whole EFB for
1086 // the screen (that maps the logical resolution onto the display copy = free upscale) and the target
1087 // rect for a render-target pass (rendered 1:1 into the EFB corner, then copied out)
1088 std::int32_t w, h;
1089 if (_currentRenderTarget != nullptr) {
1090 GxTexture* texture = _currentRenderTarget->GetColorTexture(0);
1091 w = (texture != nullptr ? texture->GetWidth() : _viewport.W);
1092 h = (texture != nullptr ? texture->GetHeight() : _viewport.H);
1093 } else {
1094 w = (_logicalWidth > 0 ? _logicalWidth : (_rmode != nullptr ? _rmode->fbWidth : 640));
1095 h = (_logicalHeight > 0 ? _logicalHeight : (_rmode != nullptr ? _rmode->efbHeight : 480));
1096 }
1097
1098 // The projection, viewport and position matrix only depend on the target and its logical size,
1099 // which are identical for whole runs of consecutive draws - skip the reissue when nothing changed
1100 if (g_appliedProjectionValid && g_appliedProjectionTarget == _currentRenderTarget &&
1101 g_appliedProjectionW == w && g_appliedProjectionH == h) {
1102 return;
1103 }
1104
1105 if (_currentRenderTarget != nullptr) {
1106 GX_SetViewport(0.0f, 0.0f, float(w), float(h), 0.0f, 1.0f);
1107 } else if (_rmode != nullptr) {
1108 GX_SetViewport(0.0f, 0.0f, float(_rmode->fbWidth), float(_rmode->efbHeight), 0.0f, 1.0f);
1109 }
1110 Mtx44 proj;
1111 guOrtho(proj, 0.0f, float(h), 0.0f, float(w), 0.0f, 1.0f);
1112 GX_LoadProjectionMtx(proj, GX_ORTHOGRAPHIC);
1113
1114 Mtx identity;
1115 guMtxIdentity(identity);
1116 GX_LoadPosMtxImm(identity, GX_PNMTX0);
1117 GX_SetCurrentMtx(GX_PNMTX0);
1118
1119 g_appliedProjectionValid = true;
1120 g_appliedProjectionTarget = _currentRenderTarget;
1121 g_appliedProjectionW = w;
1122 g_appliedProjectionH = h;
1123 }
1124
1125 void GxDevice::ApplyRenderState()
1126 {
1127 // The blend factors only matter while blending is enabled, so a disabled state always matches a
1128 // cached disabled one whatever factors it carries
1129 if (!g_appliedBlendValid || g_appliedBlendEnabled != _blending.Enabled ||
1130 (_blending.Enabled && (g_appliedBlendSrc != _blending.SrcRgb || g_appliedBlendDst != _blending.DstRgb))) {
1131 if (_blending.Enabled) {
1132 GX_SetBlendMode(GX_BM_BLEND, MapBlendGx(_blending.SrcRgb), MapBlendGx(_blending.DstRgb), GX_LO_CLEAR);
1133 } else {
1134 GX_SetBlendMode(GX_BM_NONE, GX_BL_ONE, GX_BL_ZERO, GX_LO_CLEAR);
1135 }
1136 g_appliedBlendValid = true;
1137 g_appliedBlendEnabled = _blending.Enabled;
1138 g_appliedBlendSrc = _blending.SrcRgb;
1139 g_appliedBlendDst = _blending.DstRgb;
1140 }
1141
1142 // The scissor mapping depends on the target (the flip and the EFB scale), so the target pointer is
1143 // part of the cache key; a disabled state always maps to the same full-EFB rect
1144 if (g_appliedScissorValid && g_appliedScissorEnabled == _scissor.Enabled &&
1145 g_appliedScissorTarget == _currentRenderTarget &&
1146 (!_scissor.Enabled || g_appliedScissorRect == _scissor.Rect)) {
1147 return;
1148 }
1149
1150 // The engine hands scissor rectangles in bottom-up (OpenGL) window coordinates of the logical
1151 // space; GX scissors in top-down EFB pixels, so flip and scale
1152 std::int32_t targetW = _logicalWidth, targetH = _logicalHeight;
1153 float scaleX = 1.0f, scaleY = 1.0f;
1154 if (_currentRenderTarget == nullptr && _rmode != nullptr && targetW > 0 && targetH > 0) {
1155 scaleX = float(_rmode->fbWidth) / float(targetW);
1156 scaleY = float(_rmode->efbHeight) / float(targetH);
1157 }
1158 if (_scissor.Enabled && targetH > 0) {
1159 // Screen passes mirror NDC (see Dispatch), so the engine's bottom-up scissor maps to raster
1160 // rows directly; render-to-texture passes keep the unmirrored top-down store and flip it
1161 const std::int32_t rasterY = (_currentRenderTarget == nullptr
1162 ? _scissor.Rect.Y : targetH - _scissor.Rect.Y - _scissor.Rect.H);
1163 GX_SetScissor(std::uint32_t(float(_scissor.Rect.X) * scaleX), std::uint32_t(float(rasterY) * scaleY),
1164 std::uint32_t(float(_scissor.Rect.W) * scaleX), std::uint32_t(float(_scissor.Rect.H) * scaleY));
1165 } else if (_rmode != nullptr) {
1166 GX_SetScissor(0, 0, _rmode->fbWidth, _rmode->efbHeight);
1167 }
1168
1169 g_appliedScissorValid = true;
1170 g_appliedScissorEnabled = _scissor.Enabled;
1171 g_appliedScissorRect = _scissor.Rect;
1172 g_appliedScissorTarget = _currentRenderTarget;
1173 }
1174
1175 void GxDevice::FlushCurrentRenderTarget()
1176 {
1177 if (_currentRenderTarget == nullptr) {
1178 return;
1179 }
1180 GxTexture* texture = _currentRenderTarget->GetColorTexture(0);
1181 if (texture == nullptr || texture->GetRenderTargetStore() == nullptr) {
1182 return;
1183 }
1184 // Copy the rendered EFB region out into the texture's tiled store (and leave the EFB cleared for
1185 // whatever pass follows)
1186 const std::uint16_t w = std::uint16_t(texture->GetWidth());
1187 const std::uint16_t h = std::uint16_t(texture->GetHeight());
1188 GX_DrawDone();
1189 GX_SetTexCopySrc(0, 0, w, h);
1190 GX_SetTexCopyDst(w, h, GX_TF_RGBA8, GX_FALSE);
1191 GX_CopyTex(texture->GetRenderTargetStore(), GX_TRUE);
1192 GX_PixModeSync();
1193 GX_InvalidateTexAll();
1194 // Whatever renders next runs against a different target context; reissue everything once
1195 InvalidateAppliedState();
1196 }
1197
1198 // ------------------------------------------------------------------ draw entry points
1199
1200 void GxDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1201 {
1202 Dispatch(primitive, firstVertex, numVertices);
1203 }
1204 void GxDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
1205 {
1206 static_cast<void>(numInstances);
1207 Dispatch(primitive, firstVertex, numVertices);
1208 }
1209 void GxDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
1210 {
1211 static_cast<void>(indexFormat);
1212 static_cast<void>(indexOffset);
1213 Dispatch(primitive, baseVertex, std::int32_t(numIndices));
1214 }
1215 void GxDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
1216 {
1217 static_cast<void>(indexFormat);
1218 static_cast<void>(indexOffset);
1219 static_cast<void>(numInstances);
1220 Dispatch(primitive, baseVertex, std::int32_t(numIndices));
1221 }
1222
1223 FenceHandle GxDevice::InsertFence()
1224 {
1225 return reinterpret_cast<FenceHandle>(std::uintptr_t(1));
1226 }
1227 void GxDevice::DeleteFence(FenceHandle& fence)
1228 {
1229 fence = nullptr;
1230 }
1231 bool GxDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
1232 {
1233 static_cast<void>(fence);
1234 static_cast<void>(timeoutNs);
1235 return true; // The FIFO is drained at present; fences signal immediately
1236 }
1237
1238 void GxDevice::SetupInitialState()
1239 {
1240 _blending = BlendingState();
1241 _depthTest = DepthTestState();
1242 _cullFace = CullFaceState();
1243 _scissor = ScissorState();
1244 }
1245
1246 // ------------------------------------------------------------------ extensions
1247
1248 void GxDevice::BindProgram(GxShaderProgram* program) { _currentProgram = program; }
1249 GxShaderProgram* GxDevice::CurrentProgram() { return _currentProgram; }
1250
1251 void GxDevice::BindTexture(std::uint32_t unit, const GxTexture* texture)
1252 {
1253 if (unit < MaxTextureUnits) {
1254 _boundTextures[unit] = texture;
1255 }
1256 }
1257
1258 void GxDevice::UnbindTexture(const GxTexture* texture)
1259 {
1260 for (std::uint32_t i = 0; i < MaxTextureUnits; i++) {
1261 if (_boundTextures[i] == texture) {
1262 _boundTextures[i] = nullptr;
1263 }
1264 }
1265 if (_paletteTexture == texture) {
1266 _paletteTexture = nullptr;
1267 }
1268 // Drop TLUTs built from the destroyed palette so a stale pointer can never match
1269 for (std::uint32_t i = 0; i < MaxTlutSlots; i++) {
1270 if (_tlutSlots[i].Palette == texture) {
1271 _tlutSlots[i].PaletteOffset = -1;
1272 _tlutSlots[i].Palette = nullptr;
1273 }
1274 }
1275 }
1276
1277 const GxTexture* GxDevice::GetBoundTexture(std::uint32_t unit)
1278 {
1279 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
1280 }
1281
1282 void GxDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
1283 {
1284 if (index < MaxUniformBindings) {
1285 _boundUniformRanges[index].Data = data;
1286 _boundUniformRanges[index].Size = size;
1287 }
1288 }
1289
1290 void GxDevice::SetRenderTarget(GxRenderTarget* renderTarget)
1291 {
1292 if (renderTarget == _currentRenderTarget) {
1293 return;
1294 }
1295 // Leaving a target resolves it into its texture before anything else renders over the EFB
1296 FlushCurrentRenderTarget();
1297 _currentRenderTarget = renderTarget;
1298 // The projection space and the scissor mapping are keyed on the target
1299 InvalidateAppliedState();
1300 }
1301
1302 void GxDevice::UnbindRenderTarget(const GxRenderTarget* renderTarget)
1303 {
1304 if (_currentRenderTarget == renderTarget) {
1305 _currentRenderTarget = nullptr;
1306 }
1307 }
1308
1309 // ------------------------------------------------------------------ palette TLUTs
1310
1311 void GxDevice::RegisterPaletteTexture(GxTexture* texture)
1312 {
1313 _paletteTexture = texture;
1314 NotifyPaletteTextureChanged(texture, 0, texture != nullptr ? texture->GetHeight() : 0);
1315 }
1316
1317 void GxDevice::NotifyPaletteTextureChanged(GxTexture* texture, std::int32_t firstRow, std::int32_t rowCount)
1318 {
1319 if (texture != _paletteTexture) {
1320 return;
1321 }
1322 _paletteGeneration++;
1323 for (std::uint32_t i = 0; i < MaxTlutSlots; i++) {
1324 if (_tlutSlots[i].PaletteOffset >= (firstRow - 1) * 256 && _tlutSlots[i].PaletteOffset < (firstRow + rowCount) * 256) {
1325 _tlutSlots[i].PaletteOffset = -1;
1326 }
1327 }
1328 }
1329
1330 std::int32_t GxDevice::AcquireTlutForRow(const GxTexture* palette, std::int32_t paletteOffset)
1331 {
1332 // The offset is a flat index into the palette texture and does not need to be row-aligned
1333 // (e.g. the gem gradients pack two palettes into a single 256-entry row). The palette is usually
1334 // the registered global one, but effects like the profile character previews bind their own
1335 // recolored palette texture instead.
1336 const std::int32_t maxOffset = palette != nullptr
1337 ? palette->GetWidth() * palette->GetHeight() - 256 : 0;
1338 if (palette == nullptr || palette->GetPixels() == nullptr ||
1339 paletteOffset < 0 || paletteOffset > maxOffset) {
1340 return -1;
1341 }
1342
1343 _tlutUseCounter++;
1344
1345 // Reuse a slot already holding this row of this palette (and its current content), or evict the
1346 // least recently used one
1347 std::int32_t slot = -1;
1348 std::uint32_t oldestUse = UINT32_MAX;
1349 std::int32_t oldestSlot = 0;
1350 for (std::uint32_t i = 0; i < MaxTlutSlots; i++) {
1351 if (_tlutSlots[i].PaletteOffset == paletteOffset && _tlutSlots[i].Palette == palette &&
1352 _tlutSlots[i].PaletteVersion == palette->GetContentVersion()) {
1353 slot = std::int32_t(i);
1354 break;
1355 }
1356 if (_tlutSlots[i].LastUse < oldestUse) {
1357 oldestUse = _tlutSlots[i].LastUse;
1358 oldestSlot = std::int32_t(i);
1359 }
1360 }
1361
1362 if (slot < 0) {
1363 slot = oldestSlot;
1364 TlutSlot& s = _tlutSlots[slot];
1365 if (s.Data == nullptr) {
1366 s.Data = static_cast<std::uint16_t*>(memalign(32, 256 * sizeof(std::uint16_t)));
1367 if (s.Data == nullptr) {
1368 return -1;
1369 }
1370 }
1371 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(
1372 palette->GetPixels()) + paletteOffset;
1373 for (std::int32_t i = 0; i < 256; i++) {
1374 s.Data[i] = Rgb5a3FromRgba(entries[i]);
1375 }
1376 DCFlushRange(s.Data, 256 * sizeof(std::uint16_t));
1377
1378 GXTlutObj tlut;
1379 GX_InitTlutObj(&tlut, s.Data, GX_TL_RGB5A3, 256);
1380 GX_LoadTlut(&tlut, GX_TLUT0 + std::uint32_t(slot));
1381 s.PaletteOffset = paletteOffset;
1382 s.Palette = palette;
1383 s.PaletteVersion = palette->GetContentVersion();
1384 }
1385
1386 _tlutSlots[slot].LastUse = _tlutUseCounter;
1387 return slot;
1388 }
1389
1390 // ------------------------------------------------------------------ lighting hook
1391
1392 void GxDevice::SetPendingSoftwareLighting(const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale,
1393 std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH, float ambR, float ambG, float ambB,
1394 bool waterActive, float waterLevelPx, float waterTime, float waterCamY)
1395 {
1396 PendingSoftwareLight light;
1397 light.Lightmap = lightmap;
1398 light.LmW = lmW;
1399 light.LmH = lmH;
1400 light.Scale = (scale > 0 ? scale : 1);
1401 light.VpX = vpX;
1402 light.VpY = vpY;
1403 light.VpW = vpW;
1404 light.VpH = vpH;
1405 light.AmbR = ambR;
1406 light.AmbG = ambG;
1407 light.AmbB = ambB;
1408 light.WaterActive = waterActive;
1409 light.WaterLevelPx = waterLevelPx;
1410 light.WaterTime = waterTime;
1411 light.WaterCamY = waterCamY;
1412 _pendingSoftwareLights.push_back(light);
1413 }
1414
1415 void GxDevice::EndFrame()
1416 {
1417 if (!_pendingSoftwareLights.empty()) {
1418 static bool warnedLeftoverLights = false;
1419 if (!warnedLeftoverLights) {
1420 warnedLeftoverLights = true;
1421 LOGW("Dropping {} unconsumed software-lighting entries", _pendingSoftwareLights.size());
1422 }
1423 _pendingSoftwareLights.clear();
1424 }
1425 }
1426
1427 void GxDevice::ApplyPendingSoftwareLighting()
1428 {
1429 if (_pendingSoftwareLights.empty()) {
1430 return;
1431 }
1432 const PendingSoftwareLight light = _pendingSoftwareLights.front();
1433 _pendingSoftwareLights.erase(_pendingSoftwareLights.begin());
1434
1435 const bool hasLighting = (light.Lightmap != nullptr && light.LmW > 0 && light.LmH > 0);
1436 const bool hasWater = light.WaterActive;
1437 if (!hasLighting && !hasWater) {
1438 return;
1439 }
1440
1441 ApplyProjection();
1442 // Both the lightmap multiply and the water bands set their blend modes directly, bypassing
1443 // ApplyRenderState() - its cache no longer matches once this hook ran
1444 g_appliedBlendValid = false;
1445 const float vpX = float(light.VpX), vpY = float(light.VpY);
1446 const float vpW = float(light.VpW), vpH = float(light.VpH);
1447
1448 if (hasLighting) {
1449 // Build the per-texel multiply factor from the CPU lightmap: out ≈ scene * (r*(1+g) + amb*(1-r))
1450 // per channel - the multiply-only approximation of the software combine (the small additive glow
1451 // term of very bright lights is dropped). Tiled RGBA8, drawn as one linear-filtered quad with a
1452 // dst*src blend over the viewport.
1453 const std::int32_t w = light.LmW, h = light.LmH;
1454 const std::size_t linearSize = std::size_t(w) * std::size_t(h) * 4;
1455 const std::size_t tiledSize = std::size_t((w + 3) & ~3) * std::size_t((h + 3) & ~3) * 4;
1456 if (_lightmapStore == nullptr || _lightmapStoreSize < tiledSize) {
1457 if (_lightmapStore != nullptr) {
1458 free(_lightmapStore);
1459 }
1460 _lightmapStore = static_cast<std::uint8_t*>(memalign(32, tiledSize));
1461 _lightmapStoreSize = tiledSize;
1462 }
1463 // The linear staging buffer persists across frames like the tiled store above - allocating
1464 // (and zero-initializing) it per lit frame is wasted work, every byte is written below
1465 if (_lightmapLinear == nullptr || _lightmapLinearSize < linearSize) {
1466 if (_lightmapLinear != nullptr) {
1467 free(_lightmapLinear);
1468 }
1469 _lightmapLinear = static_cast<std::uint8_t*>(malloc(linearSize));
1470 _lightmapLinearSize = (_lightmapLinear != nullptr ? linearSize : 0);
1471 }
1472 if (_lightmapStore != nullptr && _lightmapLinear != nullptr) {
1473 std::uint8_t* const linear = _lightmapLinear;
1474 for (std::int32_t y = 0; y < h; y++) {
1475 const float* src = light.Lightmap + std::size_t(y) * w * 2;
1476 std::uint8_t* dst = linear + std::size_t(y) * w * 4;
1477 for (std::int32_t x = 0; x < w; x++) {
1478 float r = src[x * 2];
1479 float g = src[x * 2 + 1];
1480 r = (r < 0.0f ? 0.0f : (r > 1.0f ? 1.0f : r));
1481 g = (g < 0.0f ? 0.0f : (g > 1.0f ? 1.0f : g));
1482 const float lit = r * (1.0f + g);
1483 dst[x * 4 + 0] = QuantizeChannel(lit + light.AmbR * (1.0f - r));
1484 dst[x * 4 + 1] = QuantizeChannel(lit + light.AmbG * (1.0f - r));
1485 dst[x * 4 + 2] = QuantizeChannel(lit + light.AmbB * (1.0f - r));
1486 dst[x * 4 + 3] = 255;
1487 }
1488 }
1489
1490 // Tile 4x4 RGBA8 (same layout GxTexture uses)
1491 const std::int32_t tilesX = (w + 3) / 4;
1492 const std::int32_t tilesY = (h + 3) / 4;
1493 for (std::int32_t ty = 0; ty < tilesY; ty++) {
1494 for (std::int32_t tx = 0; tx < tilesX; tx++) {
1495 std::uint8_t* tile = _lightmapStore + std::size_t(ty * tilesX + tx) * 64;
1496 for (std::int32_t row = 0; row < 4; row++) {
1497 for (std::int32_t col = 0; col < 4; col++) {
1498 const std::int32_t x = tx * 4 + col;
1499 const std::int32_t y = ty * 4 + row;
1500 std::uint8_t r = 255, g = 255, b = 255, a = 255;
1501 if (x < w && y < h) {
1502 const std::uint8_t* px = linear + (std::size_t(y) * w + x) * 4;
1503 r = px[0]; g = px[1]; b = px[2]; a = px[3];
1504 }
1505 const std::int32_t i = row * 4 + col;
1506 tile[i * 2 + 0] = a;
1507 tile[i * 2 + 1] = r;
1508 tile[32 + i * 2 + 0] = g;
1509 tile[32 + i * 2 + 1] = b;
1510 }
1511 }
1512 }
1513 }
1514 DCFlushRange(_lightmapStore, std::uint32_t(tiledSize));
1515 GX_InvalidateTexAll();
1516
1517 GX_InitTexObj(&_lightmapTexObj, _lightmapStore, std::uint16_t(w), std::uint16_t(h), GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE);
1518 GX_InitTexObjFilterMode(&_lightmapTexObj, GX_LINEAR, GX_LINEAR);
1519 GX_LoadTexObj(&_lightmapTexObj, GX_TEXMAP0);
1520
1521 SetVertexModeTextured(true);
1522 GX_SetBlendMode(GX_BM_BLEND, GX_BL_DSTCLR, GX_BL_ZERO, GX_LO_CLEAR); // out = dst * src
1523 // The lightmap's row 0 corresponds to the bottom of the displayed viewport (the software
1524 // buffer is bottom-up and flipped at present), so V runs 1 -> 0 top -> bottom
1525 GX_Begin(GX_QUADS, GX_VTXFMT0, 4);
1526 GX_Position3f32(vpX, vpY, 0.0f); GX_Color4u8(255, 255, 255, 255); GX_TexCoord2f32(0.0f, 1.0f);
1527 GX_Position3f32(vpX + vpW, vpY, 0.0f); GX_Color4u8(255, 255, 255, 255); GX_TexCoord2f32(1.0f, 1.0f);
1528 GX_Position3f32(vpX + vpW, vpY + vpH, 0.0f); GX_Color4u8(255, 255, 255, 255); GX_TexCoord2f32(1.0f, 0.0f);
1529 GX_Position3f32(vpX, vpY + vpH, 0.0f); GX_Color4u8(255, 255, 255, 255); GX_TexCoord2f32(0.0f, 0.0f);
1530 GX_End();
1531 }
1532 }
1533
1534 if (hasWater) {
1535 // Water v1: the constant underwater tint band (out = main * 0.6 + waterColor * 0.4) and the
1536 // above-deep-water darkening; the per-row wave displacement and surface glow of the software
1537 // combine are dropped (TODO(GX): reproduce them with per-row quads if it matters visually)
1538 SetVertexModeTextured(false);
1539 GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
1540 const float waterTop = vpY + light.WaterLevelPx;
1541 if (waterTop < vpY + vpH) {
1542 GX_Begin(GX_QUADS, GX_VTXFMT0, 4);
1543 GX_Position3f32(vpX, waterTop, 0.0f); GX_Color4u8(102, 153, 204, 102);
1544 GX_Position3f32(vpX + vpW, waterTop, 0.0f); GX_Color4u8(102, 153, 204, 102);
1545 GX_Position3f32(vpX + vpW, vpY + vpH, 0.0f); GX_Color4u8(102, 153, 204, 102);
1546 GX_Position3f32(vpX, vpY + vpH, 0.0f); GX_Color4u8(102, 153, 204, 102);
1547 GX_End();
1548 }
1549 const float waterLevelNorm = (vpH > 0.0f ? light.WaterLevelPx / vpH : 1.0f);
1550 if (waterLevelNorm < 0.4f && waterTop > vpY) {
1551 const std::uint8_t a = QuantizeChannel(0.4f - waterLevelNorm);
1552 GX_Begin(GX_QUADS, GX_VTXFMT0, 4);
1553 GX_Position3f32(vpX, vpY, 0.0f); GX_Color4u8(QuantizeChannel(light.AmbR), QuantizeChannel(light.AmbG), QuantizeChannel(light.AmbB), a);
1554 GX_Position3f32(vpX + vpW, vpY, 0.0f); GX_Color4u8(QuantizeChannel(light.AmbR), QuantizeChannel(light.AmbG), QuantizeChannel(light.AmbB), a);
1555 GX_Position3f32(vpX + vpW, waterTop, 0.0f); GX_Color4u8(QuantizeChannel(light.AmbR), QuantizeChannel(light.AmbG), QuantizeChannel(light.AmbB), a);
1556 GX_Position3f32(vpX, waterTop, 0.0f); GX_Color4u8(QuantizeChannel(light.AmbR), QuantizeChannel(light.AmbG), QuantizeChannel(light.AmbB), a);
1557 GX_End();
1558 }
1559 }
1560 }
1561
1562 // ------------------------------------------------------------------ draw dispatch
1563
1564 void GxDevice::DispatchTileMesh(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1565 {
1566 // A tile-layer mesh is a plain triangle list of 8-float vertices (position.xy, texcoords.uv,
1567 // color.rgba) - the layout TileMap::AppendTileQuad() writes and TileMapVs.inc declares. It is a
1568 // hard contract of this shader family exactly like the std140 instance block is of the sprite one.
1569 constexpr std::int32_t FloatsPerVertex = 8;
1570 if (primitive != PrimitiveType::Triangles || numVertices < 3) {
1571 return;
1572 }
1573
1574 const GxBuffer* vbo = _currentProgram->GetBoundVbo();
1575 if (vbo == nullptr) {
1576 return;
1577 }
1578 const std::size_t firstFloat = (std::size_t(_currentProgram->GetBoundVboOffset()) / sizeof(float)) +
1579 std::size_t(firstVertex) * FloatsPerVertex;
1580 const std::size_t floatCount = std::size_t(numVertices) * FloatsPerVertex;
1581 if ((firstFloat + floatCount) * sizeof(float) > vbo->GetSize()) {
1582 return;
1583 }
1584 const float* DEATH_RESTRICT vertices = reinterpret_cast<const float*>(vbo->HostData()) + firstFloat;
1585
1586 const GxUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1587 if (block == nullptr) {
1588 return;
1589 }
1590 std::int32_t binding = block->GetBindingIndex();
1591 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1592 binding = 0;
1593 }
1594 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1595 if (blockData == nullptr) {
1596 return;
1597 }
1598
1599 GxTexture* texture = const_cast<GxTexture*>(_boundTextures[0]);
1600 if (texture == nullptr) {
1601 return;
1602 }
1603
1604 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjectionMatrix();
1605 const std::uint8_t* viewBytes = _currentProgram->GetResolvedViewMatrix();
1606 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1607 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1608 float pv[16];
1609 Mat4Mul(projMat, viewMat, pv);
1610 Transform2D mvp;
1611 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(blockData + kModelMatrixOffset), mvp);
1612
1613 // The layer tint modulates every vertex colour, which already carries the per-tile alpha
1614 float layerColor[4];
1615 std::memcpy(layerColor, blockData + kColorOffset, sizeof(layerColor));
1616
1617 // The palette to remap with is whatever the material bound to the palette sampler; the registered
1618 // global palette is the fallback (mirrors the sprite path). TileMapMeshPalette binds
1619 // uTexturePalette in its reflection, which is exactly what UsesPalette() reports - the remap
1620 // intent needs no effect identity of its own.
1621 const bool isPaletteRemap = _currentProgram->UsesPalette();
1622 const GxTexture* paletteTex = nullptr;
1623 if (isPaletteRemap || texture->IsIndexed()) {
1624 paletteTex = _boundTextures[1];
1625 if (paletteTex == nullptr || paletteTex == texture) {
1626 paletteTex = _paletteTexture;
1627 }
1628 }
1629
1630 // Unlike a sprite batch, the whole mesh shares one texture and one palette offset, so the texture
1631 // variant (TLUT row for CI8 indices, palette-baked copy for RG8) is resolved and loaded once for
1632 // the entire layer
1633 GXTexObj* texObj = nullptr;
1634 if (texture->IsIndexed()) {
1635 // An 8bpp store can only be read through a palette, whatever it is being drawn with - the lookup
1636 // belongs to the texture read rather than to the effect. An effect that remaps takes the row from
1637 // the instance; anything else uses the base row.
1638 std::int32_t paletteOffset = 0;
1639 if (isPaletteRemap) {
1640 float palOffset = 0.0f;
1641 std::memcpy(&palOffset, blockData + kPaletteOffsetOffset, sizeof(palOffset));
1642 paletteOffset = std::int32_t(palOffset + 0.5f);
1643 }
1644 const std::int32_t slot = AcquireTlutForRow(paletteTex, paletteOffset);
1645 texObj = texture->GetTexObj();
1646 if (texObj != nullptr && slot >= 0) {
1647 GX_InitTexObjTlut(texObj, GX_TLUT0 + std::uint32_t(slot));
1648 }
1649 } else if (isPaletteRemap && texture->NeedsPaletteBake() && paletteTex != nullptr && paletteTex->GetPixels() != nullptr) {
1650 float palOffset = 0.0f;
1651 std::memcpy(&palOffset, blockData + kPaletteOffsetOffset, sizeof(palOffset));
1652 const std::uint32_t paletteOffset = std::uint32_t(std::int32_t(palOffset + 0.5f));
1653 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(
1654 paletteTex->GetPixels()) + paletteOffset;
1655 texObj = texture->EnsureBakedRgba(entries, paletteOffset,
1656 (paletteTex == _paletteTexture ? _paletteGeneration : paletteTex->GetContentVersion()), paletteTex);
1657 } else {
1658 texObj = texture->GetTexObj();
1659 }
1660 if (texObj == nullptr) {
1661 return;
1662 }
1663
1664 ApplyProjection();
1665 ApplyRenderState();
1666 SetVertexModeTextured(true);
1667 SetTevMode(TevMode::Modulate);
1668 GX_LoadTexObj(texObj, GX_TEXMAP0);
1669
1670 const bool screenPass = (_currentRenderTarget == nullptr);
1671 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1672 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1673
1674 // The NDC-to-raster mapping is affine and constant for the whole mesh, so it is folded into the
1675 // transform once instead of being reapplied per vertex - every vertex then costs one multiply-add
1676 // per axis (matching the sprite path's corner synthesis). A screen pass mirrors NDC, which is
1677 // just the sign of the Y scale.
1678 const float rasterScaleX = 0.5f * float(viewport.W);
1679 const float rasterBiasX = rasterScaleX + float(viewport.X);
1680 const float rasterScaleY = 0.5f * float(viewport.H) * (screenPass ? 1.0f : -1.0f);
1681 const float rasterBiasY = 0.5f * float(viewport.H) + float(viewport.Y);
1682 const Transform2D raster = {
1683 mvp.Xx * rasterScaleX, mvp.Xy * rasterScaleY,
1684 mvp.Yx * rasterScaleX, mvp.Yy * rasterScaleY,
1685 mvp.Tx * rasterScaleX + rasterBiasX, mvp.Ty * rasterScaleY + rasterBiasY
1686 };
1687
1688 const std::int32_t triangleCount = numVertices / 3;
1689
1690 // Tiles reach here as the six vertices of two triangles, of which the fourth repeats the first
1691 // and the fifth repeats the third. Recognizing that pattern lets a tile go out as one four-vertex
1692 // GX quad instead of two triangles, and consecutive tiles share a single GX_Begin run, so the
1693 // begin/end register writes are paid once per run instead of once per tile. GX has a hardware
1694 // scissor (applied by ApplyRenderState above), so unlike the PVR path everything is submitted
1695 // as-is and the GP clips it - no geometric clipping or bounding-box rejection is needed.
1696 auto isTileQuad = [vertices, triangleCount](std::int32_t triangle) {
1697 if (triangle + 2 > triangleCount) {
1698 return false;
1699 }
1700 const float* group = vertices + std::size_t(triangle) * 3 * FloatsPerVertex;
1701 return (group[3 * FloatsPerVertex + 0] == group[0] && group[3 * FloatsPerVertex + 1] == group[1] &&
1702 group[4 * FloatsPerVertex + 0] == group[2 * FloatsPerVertex + 0] &&
1703 group[4 * FloatsPerVertex + 1] == group[2 * FloatsPerVertex + 1]);
1704 };
1705
1706 // GX_Begin carries the vertex count in a 16-bit register, so runs are chopped below that limit
1707 constexpr std::int32_t MaxQuadsPerRun = 0x3FFF;
1708 constexpr std::int32_t MaxTrianglesPerRun = 0x5554;
1709
1710 std::int32_t triangle = 0;
1711 while (triangle < triangleCount) {
1712 if (isTileQuad(triangle)) {
1713 const std::int32_t runStart = triangle;
1714 std::int32_t quadRun = 0;
1715 do {
1716 quadRun++;
1717 triangle += 2;
1718 } while (quadRun < MaxQuadsPerRun && isTileQuad(triangle));
1719
1720 GX_Begin(GX_QUADS, GX_VTXFMT0, std::uint16_t(quadRun * 4));
1721 for (std::int32_t q = 0; q < quadRun; q++) {
1722 const float* group = vertices + std::size_t(runStart + q * 2) * 3 * FloatsPerVertex;
1723 // Every vertex of a tile carries the same colour, so it only has to be folded with the
1724 // layer tint and quantized once
1725 const std::uint8_t r = QuantizeChannel(group[4] * layerColor[0]);
1726 const std::uint8_t g = QuantizeChannel(group[5] * layerColor[1]);
1727 const std::uint8_t b = QuantizeChannel(group[6] * layerColor[2]);
1728 const std::uint8_t a = QuantizeChannel(group[7] * layerColor[3]);
1729 // Perimeter order of the tile's six strip-ordered vertices (see AppendTileQuad)
1730 static const std::int32_t QuadOrder[4] = { 0, 1, 2, 5 };
1731 for (std::int32_t i = 0; i < 4; i++) {
1732 const float* v = group + std::size_t(QuadOrder[i]) * FloatsPerVertex;
1733 GX_Position3f32(raster.Xx * v[0] + raster.Yx * v[1] + raster.Tx,
1734 raster.Xy * v[0] + raster.Yy * v[1] + raster.Ty, 0.0f);
1735 GX_Color4u8(r, g, b, a);
1736 GX_TexCoord2f32(v[2], v[3]);
1737 }
1738 }
1739 GX_End();
1740 } else {
1741 const std::int32_t runStart = triangle;
1742 std::int32_t triRun = 0;
1743 do {
1744 triRun++;
1745 triangle++;
1746 } while (triangle < triangleCount && triRun < MaxTrianglesPerRun && !isTileQuad(triangle));
1747
1748 GX_Begin(GX_TRIANGLES, GX_VTXFMT0, std::uint16_t(triRun * 3));
1749 for (std::int32_t i = 0; i < triRun * 3; i++) {
1750 const float* v = vertices + std::size_t(runStart) * 3 * FloatsPerVertex + std::size_t(i) * FloatsPerVertex;
1751 GX_Position3f32(raster.Xx * v[0] + raster.Yx * v[1] + raster.Tx,
1752 raster.Xy * v[0] + raster.Yy * v[1] + raster.Ty, 0.0f);
1753 GX_Color4u8(QuantizeChannel(v[4] * layerColor[0]), QuantizeChannel(v[5] * layerColor[1]),
1754 QuantizeChannel(v[6] * layerColor[2]), QuantizeChannel(v[7] * layerColor[3]));
1755 GX_TexCoord2f32(v[2], v[3]);
1756 }
1757 GX_End();
1758 }
1759 }
1760 }
1761
1762 void GxDevice::DispatchLineStrip(std::int32_t firstVertex, std::int32_t numVertices)
1763 {
1764 // The weapon wheel arrives as a textured line strip of 4-float vertices (position.xy,
1765 // texcoords.uv) - the layout the MeshSprite shader's attributes declare. Unlike the PVR,
1766 // the GP draws lines natively, so the strip is passed through as GX_LINESTRIP.
1767 constexpr std::int32_t FloatsPerVertex = 4;
1768 if (numVertices < 2 || numVertices > 0xFFFF) {
1769 return;
1770 }
1771
1772 const GxBuffer* vbo = _currentProgram->GetBoundVbo();
1773 if (vbo == nullptr) {
1774 return;
1775 }
1776 const std::size_t firstFloat = (std::size_t(_currentProgram->GetBoundVboOffset()) / sizeof(float)) +
1777 std::size_t(firstVertex) * FloatsPerVertex;
1778 const std::size_t floatCount = std::size_t(numVertices) * FloatsPerVertex;
1779 if ((firstFloat + floatCount) * sizeof(float) > vbo->GetSize()) {
1780 return;
1781 }
1782 const float* DEATH_RESTRICT vertices = reinterpret_cast<const float*>(vbo->HostData()) + firstFloat;
1783
1784 const GxUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1785 if (block == nullptr) {
1786 return;
1787 }
1788 std::int32_t binding = block->GetBindingIndex();
1789 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1790 binding = 0;
1791 }
1792 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1793 if (blockData == nullptr) {
1794 return;
1795 }
1796
1797 GxTexture* texture = const_cast<GxTexture*>(_boundTextures[0]);
1798 if (texture == nullptr) {
1799 return;
1800 }
1801
1802 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjectionMatrix();
1803 const std::uint8_t* viewBytes = _currentProgram->GetResolvedViewMatrix();
1804 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1805 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1806 float pv[16];
1807 Mat4Mul(projMat, viewMat, pv);
1808 Transform2D mvp;
1809 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(blockData + kModelMatrixOffset), mvp);
1810
1811 // Every vertex of the strip carries the instance colour, so it is quantized once
1812 float color[4];
1813 std::memcpy(color, blockData + kColorOffset, sizeof(color));
1814 const std::uint8_t r = QuantizeChannel(color[0]);
1815 const std::uint8_t g = QuantizeChannel(color[1]);
1816 const std::uint8_t b = QuantizeChannel(color[2]);
1817 const std::uint8_t a = QuantizeChannel(color[3]);
1818
1819 // The strip shares one texture; indexed assets read through the base TLUT row like the fonts do
1820 GXTexObj* texObj = nullptr;
1821 if (texture->IsIndexed()) {
1822 const GxTexture* paletteTex = _boundTextures[1];
1823 if (paletteTex == nullptr || paletteTex == texture) {
1824 paletteTex = _paletteTexture;
1825 }
1826 const std::int32_t slot = AcquireTlutForRow(paletteTex, 0);
1827 texObj = texture->GetTexObj();
1828 if (texObj != nullptr && slot >= 0) {
1829 GX_InitTexObjTlut(texObj, GX_TLUT0 + std::uint32_t(slot));
1830 }
1831 } else {
1832 texObj = texture->GetTexObj();
1833 }
1834 if (texObj == nullptr) {
1835 return;
1836 }
1837
1838 ApplyProjection();
1839 ApplyRenderState();
1840 SetVertexModeTextured(true);
1841 SetTevMode(TevMode::Modulate);
1842 GX_LoadTexObj(texObj, GX_TEXMAP0);
1843 // Width is in sixths of a pixel, so 6 matches the 1-wide GL lines this stands in for
1844 GX_SetLineWidth(6, GX_TO_ZERO);
1845
1846 const bool screenPass = (_currentRenderTarget == nullptr);
1847 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1848 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1849
1850 // The NDC-to-raster mapping is folded into the transform once, like the other mesh paths
1851 const float rasterScaleX = 0.5f * float(viewport.W);
1852 const float rasterBiasX = rasterScaleX + float(viewport.X);
1853 const float rasterScaleY = 0.5f * float(viewport.H) * (screenPass ? 1.0f : -1.0f);
1854 const float rasterBiasY = 0.5f * float(viewport.H) + float(viewport.Y);
1855 const Transform2D raster = {
1856 mvp.Xx * rasterScaleX, mvp.Xy * rasterScaleY,
1857 mvp.Yx * rasterScaleX, mvp.Yy * rasterScaleY,
1858 mvp.Tx * rasterScaleX + rasterBiasX, mvp.Ty * rasterScaleY + rasterBiasY
1859 };
1860
1861 GX_Begin(GX_LINESTRIP, GX_VTXFMT0, std::uint16_t(numVertices));
1862 for (std::int32_t i = 0; i < numVertices; i++) {
1863 const float* v = vertices + std::size_t(i) * FloatsPerVertex;
1864 GX_Position3f32(raster.Xx * v[0] + raster.Yx * v[1] + raster.Tx,
1865 raster.Xy * v[0] + raster.Yy * v[1] + raster.Ty, 0.0f);
1866 GX_Color4u8(r, g, b, a);
1867 GX_TexCoord2f32(v[2], v[3]);
1868 }
1869 GX_End();
1870 }
1871
1872 void GxDevice::Dispatch(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1873 {
1874 if (_currentProgram == nullptr || numVertices <= 0 || !_gxInitialized) {
1875 return;
1876 }
1877
1878 // The program's whole console identity is its generated-table entry, resolved at load from the
1879 // true (program, variant) the loaders plumbed in - a program without an entry has no
1880 // fixed_function block in its .shader file (Lighting, Blur, the Resize* family,
1881 // runtime-compiled shaders, ...) and keeps the logged, skipped draw.
1882 const FixedFunctionGeneratedEffect* generated = _currentProgram->GetGeneratedEffect();
1883 if (generated == nullptr) {
1884 if (!_currentProgram->FetchUnsupportedWarned()) {
1885 LOGW("Skipping draws of program \"{}\": No fixed_function effect declared by the shader", _currentProgram->GetObjectLabel());
1886 }
1887 return;
1888 }
1889 const FixedFunctionIntrinsic intrinsic = generated->Intrinsic;
1890
1891 // The Combine draw is the direct-tier lighting hook (see the software backend)
1892 if (intrinsic == FixedFunctionIntrinsic::LightingCombine) {
1893 ApplyPendingSoftwareLighting();
1894 return;
1895 }
1896
1897 // A whole tile layer arrives as one mesh instead of one command per tile
1898 if (intrinsic == FixedFunctionIntrinsic::TileMapMesh) {
1899 DispatchTileMesh(primitive, firstVertex, numVertices);
1900 return;
1901 }
1902
1903 // The weapon wheel is the one vertex-fed mesh on this tier, a textured line strip
1904 if (intrinsic == FixedFunctionIntrinsic::LineStripMesh) {
1905 if (primitive == PrimitiveType::LineStrip) {
1906 DispatchLineStrip(firstVertex, numVertices);
1907 } else if (!_currentProgram->FetchUnsupportedWarned()) {
1908 LOGW("Skipping draws of program \"{}\": Only the line-strip form of the mesh pipeline is supported by the GX dispatch", _currentProgram->GetObjectLabel());
1909 }
1910 return;
1911 }
1912
1913 // Everything else is the procedural sprite-quad family: a transpiled effect function
1914 // (geometry synthesis included - the iris fan and the warped background are ordinary blocks
1915 // since phase 4)
1916 const bool isQuadFamily = (generated->Fn != nullptr);
1917 if (!isQuadFamily || (primitive != PrimitiveType::TriangleStrip && primitive != PrimitiveType::Triangles)) {
1918 if (!_currentProgram->FetchUnsupportedWarned()) {
1919 LOGW("Skipping draws of program \"{}\": Effect not supported by the GX dispatch", _currentProgram->GetObjectLabel());
1920 }
1921 return;
1922 }
1923
1924 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjectionMatrix();
1925 const std::uint8_t* viewBytes = _currentProgram->GetResolvedViewMatrix();
1926 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1927 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1928
1929 const GxUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1930 if (block == nullptr) {
1931 block = _currentProgram->FindBlock("InstancesBlock");
1932 }
1933 if (block == nullptr) {
1934 return;
1935 }
1936 std::int32_t binding = block->GetBindingIndex();
1937 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1938 binding = 0;
1939 }
1940 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1941 if (blockData == nullptr) {
1942 return;
1943 }
1944
1945 const ShaderCompiler::ProgramVariant* reflection = _currentProgram->GetReflection();
1946 auto samplerUnit = [reflection](const char* name, std::int32_t def) -> std::int32_t {
1947 if (reflection != nullptr) {
1948 for (std::size_t i = 0; i < reflection->TextureCount; i++) {
1949 if (std::strcmp(reflection->Textures[i].Name, name) == 0) {
1950 return (reflection->Textures[i].Unit >= 0 ? reflection->Textures[i].Unit : def);
1951 }
1952 }
1953 }
1954 return def;
1955 };
1956 std::uint32_t instanceStride = 0;
1957 if (reflection != nullptr) {
1958 for (std::size_t i = 0; i < reflection->BlockCount; i++) {
1959 if (reflection->Blocks[i].InstanceStride > 0) {
1960 instanceStride = reflection->Blocks[i].InstanceStride;
1961 break;
1962 }
1963 }
1964 }
1965
1966 float pv[16];
1967 Mat4Mul(projMat, viewMat, pv);
1968
1969 // Batched programs are exactly the ones whose reflection declares a BATCH_SIZE-strided
1970 // InstancesBlock (non-batched programs use a flat InstanceBlock with no stride), so the
1971 // reflected stride IS the batching signal - no per-program identity needed
1972 const bool batched = (instanceStride > 0);
1973 std::int32_t numInstances = 1;
1974 if (batched) {
1975 numInstances = numVertices / 6;
1976 if (numInstances < 1) {
1977 numInstances = 1;
1978 }
1979 if (instanceStride == 0) {
1980 instanceStride = 112;
1981 }
1982 }
1983
1984 // A program samples the sprite texture exactly when its reflection binds uTexture - the
1985 // no-texture sprite programs and the Transition (which carries texRect in its block but
1986 // samples nothing, hence the separate layout flag) simply do not declare it
1987 bool hasTexture = false;
1988 if (reflection != nullptr) {
1989 for (std::size_t i = 0; i < reflection->TextureCount; i++) {
1990 if (std::strcmp(reflection->Textures[i].Name, "uTexture") == 0) {
1991 hasTexture = true;
1992 break;
1993 }
1994 }
1995 }
1996 // The instance layout follows the block's own reflected declaration rather than any effect
1997 // identity: a block that declares texRect uses the textured member offsets whether or not
1998 // the program samples a texture (the Transition carries texRect but samples nothing)
1999 bool texturedLayout = hasTexture;
2000 if (!texturedLayout && reflection != nullptr) {
2001 for (std::size_t i = 0; i < reflection->BlockCount && !texturedLayout; i++) {
2002 const ShaderCompiler::UniformBlock& b = reflection->Blocks[i];
2003 for (std::size_t j = 0; j < b.MemberCount; j++) {
2004 if (std::strcmp(b.Members[j].Name, "texRect") == 0) {
2005 texturedLayout = true;
2006 break;
2007 }
2008 }
2009 }
2010 }
2011 // Every effect that samples indexed sprites through the palette texture binds uTexturePalette
2012 // in its reflection, which is what UsesPalette() reports (PaletteRemap and the "...Palette"
2013 // variants of the actor state effects alike)
2014 const bool isPaletteRemap = _currentProgram->UsesPalette();
2015 const std::int32_t textureUnit = samplerUnit("uTexture", 0);
2016 const GxTexture* texture = (hasTexture ? _boundTextures[std::uint32_t(textureUnit) < MaxTextureUnits ? textureUnit : 0] : nullptr);
2017 if (hasTexture && texture == nullptr) {
2018 return;
2019 }
2020
2021 // The palette to remap with is whatever the material bound to the palette sampler (e.g. the
2022 // recolored preview palettes of the profile menu); the registered global palette is the fallback
2023 const GxTexture* paletteTex = nullptr;
2024 if (isPaletteRemap) {
2025 const std::int32_t paletteUnit = samplerUnit("uTexturePalette", 1);
2026 paletteTex = (std::uint32_t(paletteUnit) < MaxTextureUnits ? _boundTextures[paletteUnit] : nullptr);
2027 if (paletteTex == nullptr || paletteTex == texture) {
2028 paletteTex = _paletteTexture;
2029 }
2030 }
2031
2032 ApplyProjection();
2033 ApplyRenderState();
2034 SetVertexModeTextured(hasTexture);
2035
2036 // Bounds guard, mirroring the software device
2037 const std::uint32_t rangeSize = _boundUniformRanges[binding].Size;
2038 if (batched && rangeSize > 0 && std::uint32_t(numInstances) * instanceStride > rangeSize) {
2039 numInstances = std::int32_t(rangeSize / instanceStride);
2040 }
2041
2042 // The viewport rect maps NDC to logical pixels exactly like the software FetchVertex
2043 // The engine's NDC orientation matches the software backend, whose top-down raster is flipped at
2044 // present time; the EFB is scanned out top-down directly, so screen passes mirror NDC here instead
2045 // (+1 = bottom row). Render-to-texture passes keep the unmirrored top-down store, which is what the
2046 // sampling passes already expect.
2047 const bool screenPass = (_currentRenderTarget == nullptr);
2048
2049 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
2050 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
2051
2052 // Constant NDC-to-raster mapping, folded in once rather than reapplied for every sprite corner;
2053 // the screen-pass NDC mirror is just the sign of the Y scale
2054 const float rasterScaleX = 0.5f * float(viewport.W);
2055 const float rasterBiasX = rasterScaleX + float(viewport.X);
2056 const float rasterScaleY = 0.5f * float(viewport.H) * (screenPass ? 1.0f : -1.0f);
2057 const float rasterBiasY = 0.5f * float(viewport.H) + float(viewport.Y);
2058
2059 std::int32_t lastTlutSlot = -2;
2060 GXTexObj* loadedTexObj = nullptr;
2061
2062 // Statically computed per generated function: which optional context facilities the effect's
2063 // code can ever call. The setup gated on these flags only feeds those facilities, so skipping
2064 // it is invisible to the effect - it cannot read what it never calls - and every submitted
2065 // primitive stays bit-identical.
2066 const FixedFunctionRequirements reqs = generated->Requirements;
2067 const bool needsTexelStep = ((reqs & FixedFunctionRequirements::NeedsTexelStep) == FixedFunctionRequirements::NeedsTexelStep);
2068 const bool needsUniforms = ((reqs & FixedFunctionRequirements::NeedsUniforms) == FixedFunctionRequirements::NeedsUniforms);
2069 const bool needsStripBuilder = ((reqs & FixedFunctionRequirements::NeedsStripBuilder) == FixedFunctionRequirements::NeedsStripBuilder);
2070 const bool needsQuadAxes = ((reqs & FixedFunctionRequirements::NeedsQuadAxes) == FixedFunctionRequirements::NeedsQuadAxes);
2071
2072 // Texel sizes of the sprite texture in texture space (part of the EffectContext contract;
2073 // the effects that need an on-screen texel step derive it from the instance colour instead,
2074 // exactly like their GLSL does). Derived only for effects flagged with the texel-size
2075 // facility - everything else gets deterministic zeros without the divides.
2076 const float texelWidth = (needsTexelStep && hasTexture && texture->GetWidth() > 0 ? 1.0f / float(texture->GetWidth()) : 0.0f);
2077 const float texelHeight = (needsTexelStep && hasTexture && texture->GetHeight() > 0 ? 1.0f / float(texture->GetHeight()) : 0.0f);
2078 // The material blend arguments, mirroring what ApplyRenderState() issued above, so
2079 // EffectContext::SubmitQuad can restore them after a pass-level blend override. The override
2080 // flag outlives one instance because the material state does too.
2081 const std::uint8_t materialBlendOp = std::uint8_t(_blending.Enabled ? GX_BM_BLEND : GX_BM_NONE);
2082 const std::uint8_t materialBlendSrc = (_blending.Enabled ? MapBlendGx(_blending.SrcRgb) : std::uint8_t(GX_BL_ONE));
2083 const std::uint8_t materialBlendDst = (_blending.Enabled ? MapBlendGx(_blending.DstRgb) : std::uint8_t(GX_BL_ZERO));
2084 bool blendOverridden = false;
2085
2086 for (std::int32_t k = 0; k < numInstances; k++) {
2087 const std::uint8_t* inst = blockData + std::size_t(k) * (batched ? instanceStride : 0);
2088
2089 Transform2D mvp;
2090 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), mvp);
2091 float color[4];
2092 std::memcpy(color, inst + kColorOffset, sizeof(color));
2093 float texRect[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
2094 float spriteSize[2];
2095 if (texturedLayout) {
2096 std::memcpy(texRect, inst + kTexRectOffset, sizeof(texRect));
2097 std::memcpy(spriteSize, inst + kSpriteSizeOffset, sizeof(spriteSize));
2098 } else {
2099 std::memcpy(spriteSize, inst + kSpriteSizeNoTexOffset, sizeof(spriteSize));
2100 }
2101
2102 // Bind the instance's texture variant (TLUT row for CI8 indices, palette-baked copy for RG8)
2103 if (hasTexture) {
2104 GXTexObj* texObj = nullptr;
2105 GxTexture* mutableTexture = const_cast<GxTexture*>(texture);
2106 if (isPaletteRemap && texture->IsIndexed()) {
2107 float palOffset = 0.0f;
2108 std::memcpy(&palOffset, inst + kPaletteOffsetOffset, sizeof(palOffset));
2109 const std::int32_t paletteOffset = std::int32_t(palOffset + 0.5f);
2110 const std::int32_t slot = AcquireTlutForRow(paletteTex, paletteOffset);
2111 texObj = mutableTexture->GetTexObj();
2112 if (texObj != nullptr && slot >= 0 && slot != lastTlutSlot) {
2113 GX_InitTexObjTlut(texObj, GX_TLUT0 + std::uint32_t(slot));
2114 lastTlutSlot = slot;
2115 loadedTexObj = nullptr; // Force a reload with the new TLUT binding
2116 }
2117 } else if (isPaletteRemap && texture->NeedsPaletteBake() && paletteTex != nullptr && paletteTex->GetPixels() != nullptr) {
2118 float palOffset = 0.0f;
2119 std::memcpy(&palOffset, inst + kPaletteOffsetOffset, sizeof(palOffset));
2120 const std::uint32_t paletteOffset = std::uint32_t(std::int32_t(palOffset + 0.5f));
2121 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(
2122 paletteTex->GetPixels()) + paletteOffset;
2123 texObj = mutableTexture->EnsureBakedRgba(entries, paletteOffset,
2124 (paletteTex == _paletteTexture ? _paletteGeneration : paletteTex->GetContentVersion()), paletteTex);
2125 } else {
2126 texObj = mutableTexture->GetTexObj();
2127 }
2128 if (texObj == nullptr) {
2129 continue;
2130 }
2131 if (texObj != loadedTexObj) {
2132 GX_LoadTexObj(texObj, GX_TEXMAP0);
2133 loadedTexObj = texObj;
2134 }
2135 }
2136
2137 // Synthesize the four sprite corners exactly like the software FetchVertex, with the constant
2138 // NDC-to-raster mapping folded into the transform (see the PVR device) so a corner costs one
2139 // multiply-add per axis. The corner weights are 0 or 1, so the sprite's extent in raster space
2140 // is just the transformed axes scaled by its size, and the corners are sums of those.
2141 const float originX = mvp.Tx * rasterScaleX + rasterBiasX;
2142 const float originY = mvp.Ty * rasterScaleY + rasterBiasY;
2143 const float spanXx = mvp.Xx * rasterScaleX * spriteSize[0];
2144 const float spanXy = mvp.Xy * rasterScaleY * spriteSize[0];
2145 const float spanYx = mvp.Yx * rasterScaleX * spriteSize[1];
2146 const float spanYy = mvp.Yy * rasterScaleY * spriteSize[1];
2147 float px[4], py[4], pu[4], pvv[4];
2148 for (std::int32_t i = 0; i < 4; i++) {
2149 const float ax = ((i & ~1) == 0) ? 1.0f : 0.0f;
2150 const float ay = (i & 1) ? 1.0f : 0.0f;
2151 px[i] = originX + ax * spanXx + ay * spanYx;
2152 py[i] = originY + ax * spanXy + ay * spanYy;
2153 pu[i] = ax * texRect[0] + texRect[1];
2154 pvv[i] = ay * texRect[2] + texRect[3];
2155 }
2156
2157 // The pass descriptors the per-effect functions declare are mapped onto this instance's
2158 // corners and the surrounding material state through the context
2159 EffectContext ctx;
2160 ctx.InstanceColor = color;
2161 ctx.TexelW = texelWidth;
2162 ctx.TexelH = texelHeight;
2163 ctx.Batched = batched;
2164 ctx.Px = px;
2165 ctx.Py = py;
2166 ctx.Pu = pu;
2167 ctx.Pv = pvv;
2168 ctx.TexRect = texRect;
2169 ctx.HasTexture = hasTexture;
2170 ctx.MaterialBlendOp = materialBlendOp;
2171 ctx.MaterialBlendSrc = materialBlendSrc;
2172 ctx.MaterialBlendDst = materialBlendDst;
2173 ctx.BlendOverridden = &blendOverridden;
2174 // The optional context facilities are only wired up for effects whose static analysis
2175 // says they can call them (see reqs above); the loop-invariant conditions predict
2176 // perfectly, and members of an unused facility are simply never read
2177 if (needsQuadAxes) {
2178 ctx.OriginX = originX;
2179 ctx.OriginY = originY;
2180 ctx.AxisXx = spanXx;
2181 ctx.AxisXy = spanXy;
2182 ctx.AxisYx = spanYx;
2183 ctx.AxisYy = spanYy;
2184 }
2185 // Resolved uniforms are the only thing the context needs the program for, so effects
2186 // without the facility get no program plumbed at all (no resolution can ever run)
2187 ctx.Program = (needsUniforms ? _currentProgram : nullptr);
2188 if (needsStripBuilder) {
2189 // GX textures are not padded, so strip UVs pass through 1:1 (contract parity with the PVR)
2190 ctx.UvScaleU = 1.0f;
2191 ctx.UvScaleV = 1.0f;
2192 }
2193
2194 // Every quad-family effect is the transpiled form of its shader's fixed_function block
2195 // (masks, outline, shields, colorized, palette remap, the default sprites - batched
2196 // twins and palette variants included - and the geometry-synthesized iris fan and
2197 // warped background)
2198 generated->Fn(ctx);
2199 // The dispatch end of this instance: a pass the merger buffered but never paired
2200 // (a single default pass, or FrozenMask with a zero ice alpha) goes out unmerged
2201 ctx.FlushPendingQuad();
2202 }
2203
2204 // Leave the pipe in the default combine for the next draw
2205 SetTevMode(TevMode::Modulate);
2206 }
2207 }