Debian Codegraph @

Sources/nCine/Graphics/RHI/GXM/GxmDevice.cpp

raw
1 #include "GxmDevice.h"
2 #include "GxmBufferObject.h"
3 #include "GxmRenderTarget.h"
4 #include "GxmShaderProgram.h"
5 #include "GxmTexture.h"
6 #include "GxmDebug.h"
7 #include "GxmShaderProgram.h"
8
9 #include "../../../../Main.h"
10
11 #include <cstdlib>
12 #include <cstring>
13
14 #include <Containers/String.h>
15
16 #include <psp2/display.h>
17 #include <psp2/kernel/threadmgr.h>
18 #include <vitashark.h>
19
20 namespace nCine::RHI::GXM
21 {
22 namespace
23 {
24 // Ring buffers the context streams its command lists and per-draw uniform data through. Everything but
25 // the vertex ring keeps the SDK default; that one is enlarged because every batched draw reserves the
26 // whole declared size of its instance array (~64 KB) out of it, and the ring must not wrap back onto
27 // data the GPU has not consumed yet within one frame
28 constexpr std::uint32_t VdmRingBufferSize = SCE_GXM_DEFAULT_VDM_RING_BUFFER_SIZE;
29 // sceGxm reserves a draw's *declared* default uniform buffer, so a batched draw costs its whole
30 // instance array (~64 KB at BATCH_SIZE 585) however few instances it uses. Measured peak demand of a
31 // busy frame is ~320 KB, so this is roughly 25x headroom - enough that the ring cannot wrap within a
32 // frame and overwrite uniforms of draws the GPU has not run yet.
33 constexpr std::uint32_t VertexRingBufferSize = 8 * 1024 * 1024;
34 constexpr std::uint32_t FragmentRingBufferSize = SCE_GXM_DEFAULT_FRAGMENT_RING_BUFFER_SIZE;
35 constexpr std::uint32_t FragmentUsseRingBufferSize = SCE_GXM_DEFAULT_FRAGMENT_USSE_RING_BUFFER_SIZE;
36 constexpr std::uint32_t ContextHostMemSize = 16 * 1024;
37
38 // The shader patcher's pools. Every program variant the game loads is patched into these, so they are
39 // sized for the whole generated shader set rather than the SDK sample defaults
40 constexpr std::uint32_t PatcherBufferSize = 2 * 1024 * 1024;
41 constexpr std::uint32_t PatcherVertexUsseSize = 512 * 1024;
42 constexpr std::uint32_t PatcherFragmentUsseSize = 512 * 1024;
43
44 // Where the console keeps the Cg compiler. It is part of the firmware rather than the SDK, so a user
45 // who has not extracted it gets the explicit diagnostic in CreateSwapchain() instead of a black screen
46 constexpr const char* ShaderCompilerModulePath = "app0:/module/libshacccg.suprx";
47 constexpr const char* ShaderCompilerModulePathAlt = "ur0:/data/libshacccg.suprx";
48
49 // Built-in clear shader: a full-screen quad in clip space filled with one colour. A tile-based renderer
50 // has no "clear the surface" operation - the tile buffer simply starts undefined - so this is what a
51 // clear costs here, and what the console's OpenGL|ES drivers do internally as well
52 // Vertex inputs are declared as flat parameters rather than gathered into a struct, which is the form
53 // sceGxm's own samples use and the one `sceGxmProgramFindParameterByName()` is documented against - a
54 // struct member's reflected name is the compiler's choice, and the built-ins are not the place to bet on it
55 // The colour travels with the quad rather than in a uniform. A clear is the one draw whose colour has
56 // no other way to be checked - every clear in a frame is black except the lighting buffer's, so a colour
57 // that never arrives is invisible everywhere else - and this way it depends on nothing but the vertex
58 // stream the clear already has to bind.
59 constexpr const char* ClearVertexSource = R"(
60 void main(
61 float2 aPosition,
62 float4 aColor,
63 out float4 gl_Position : POSITION,
64 out float4 vColor : TEXCOORD0)
65 {
66 // Depth is written at the far plane, which is what makes this quad clear the depth buffer too
67 gl_Position = float4(aPosition, 1.0, 1.0);
68 vColor = aColor;
69 }
70 )";
71 constexpr const char* ClearFragmentSource = R"(
72 float4 main(float4 vColor : TEXCOORD0) : COLOR
73 {
74 return vColor;
75 }
76 )";
77
78 // Built-in present shader: the intermediate screen surface stretched over the display buffer. The V
79 // flip that turns the engine's OpenGL-convention (bottom-up) surface into the top-down one the display
80 // controller scans out is baked into the quad's texture coordinates
81 constexpr const char* PresentVertexSource = R"(
82 void main(
83 float2 aPosition,
84 float2 aTexCoords,
85 out float4 gl_Position : POSITION,
86 out float2 vTexCoords : TEXCOORD0)
87 {
88 gl_Position = float4(aPosition, 0.0, 1.0);
89 vTexCoords = aTexCoords;
90 }
91 )";
92 constexpr const char* PresentFragmentSource = R"(
93 uniform sampler2D uTexture : TEXUNIT0;
94
95 float4 main(float2 vTexCoords : TEXCOORD0) : COLOR
96 {
97 return tex2D(uTexture, vTexCoords);
98 }
99 )";
100
101 /** @brief Clip-space quad of the built-in shaders, in the order of a 4-vertex triangle strip */
102 constexpr float ClearQuad[] = {
103 -1.0f, -1.0f,
104 1.0f, -1.0f,
105 -1.0f, 1.0f,
106 1.0f, 1.0f
107 };
108
109 /** @brief One vertex of the clear quad: its clip-space corner and the colour being cleared to */
110 struct ClearVertex
111 {
112 float X, Y;
113 float R, G, B, A;
114 };
115 /**
116 @brief Clear quads a frame can have in flight
117
118 Each clear writes its own quad, because the GPU consumes a scene long after the call that recorded
119 it - overwriting one buffer per clear would hand every clear in the frame the last one's colour. A
120 frame of this pipeline issues about seven; the barrier at present time is what makes reuse safe
121 across frames.
122 */
123 constexpr std::uint32_t ClearQuadRingSize = 16;
124 /**
125 @brief The same quad with the texture coordinates that flip it vertically
126
127 Clip -Y lands on row 0 of the target (the positive-Y-scale viewport this backend programs
128 everywhere), and row 0 is the top of the scanned-out image - so the top of the display has to
129 sample the *last* row of the bottom-up screen surface, which is V = 1.
130 */
131 constexpr float PresentQuad[] = {
132 -1.0f, -1.0f, 0.0f, 1.0f,
133 1.0f, -1.0f, 1.0f, 1.0f,
134 -1.0f, 1.0f, 0.0f, 0.0f,
135 1.0f, 1.0f, 1.0f, 0.0f
136 };
137
138 /** @brief Corner attribute of the 4-vertex sprite strip (see @ref GxmDevice::GetQuadCornerStream()) */
139 constexpr float QuadCorners[] = {
140 1.0f, 0.0f,
141 1.0f, 1.0f,
142 0.0f, 0.0f,
143 0.0f, 1.0f
144 };
145 /** @brief Corner order of the batched six-vertices-per-sprite layout, repeated per sprite */
146 constexpr float BatchedCorners[6][2] = {
147 {1.0f, 1.0f},
148 {0.0f, 1.0f},
149 {0.0f, 0.0f},
150 {0.0f, 0.0f},
151 {1.0f, 0.0f},
152 {1.0f, 1.0f}
153 };
154
155 inline SceGxmPrimitiveType TranslatePrimitive(PrimitiveType primitive)
156 {
157 switch (primitive) {
158 case PrimitiveType::Points: return SCE_GXM_PRIMITIVE_POINTS;
159 case PrimitiveType::Lines: return SCE_GXM_PRIMITIVE_LINES;
160 case PrimitiveType::LineLoop:
161 case PrimitiveType::LineStrip:
162 // The GPU has no line-strip primitive, so a strip is drawn as the independent segments it
163 // means, fed by the line-strip index buffer (see EnsureLineStripIndices)
164 return SCE_GXM_PRIMITIVE_LINES;
165 case PrimitiveType::TriangleStrip: return SCE_GXM_PRIMITIVE_TRIANGLE_STRIP;
166 case PrimitiveType::TriangleFan: return SCE_GXM_PRIMITIVE_TRIANGLE_FAN;
167 default: return SCE_GXM_PRIMITIVE_TRIANGLES;
168 }
169 }
170
171 inline SceGxmBlendFactor TranslateBlendFactor(nCine::BlendingFactor factor)
172 {
173 switch (factor) {
174 case nCine::BlendingFactor::Zero: return SCE_GXM_BLEND_FACTOR_ZERO;
175 case nCine::BlendingFactor::One: return SCE_GXM_BLEND_FACTOR_ONE;
176 case nCine::BlendingFactor::SrcColor: return SCE_GXM_BLEND_FACTOR_SRC_COLOR;
177 case nCine::BlendingFactor::OneMinusSrcColor: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
178 case nCine::BlendingFactor::SrcAlpha: return SCE_GXM_BLEND_FACTOR_SRC_ALPHA;
179 case nCine::BlendingFactor::OneMinusSrcAlpha: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
180 case nCine::BlendingFactor::DstAlpha: return SCE_GXM_BLEND_FACTOR_DST_ALPHA;
181 case nCine::BlendingFactor::OneMinusDstAlpha: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
182 case nCine::BlendingFactor::DstColor: return SCE_GXM_BLEND_FACTOR_DST_COLOR;
183 case nCine::BlendingFactor::OneMinusDstColor: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
184 case nCine::BlendingFactor::SrcAlphaSaturate: return SCE_GXM_BLEND_FACTOR_SRC_ALPHA_SATURATE;
185 default: return SCE_GXM_BLEND_FACTOR_ONE;
186 }
187 }
188
189 /** @brief Hands one finished display buffer to the display controller (runs on sceGxm's own queue thread) */
190 void DisplayQueueCallback(const void* callbackData)
191 {
192 const auto* data = static_cast<const GxmDevice::DisplayQueueCallbackData*>(callbackData);
193
194 SceDisplayFrameBuf frameBuf = {};
195 frameBuf.size = sizeof(SceDisplayFrameBuf);
196 frameBuf.base = data->Address;
197 frameBuf.pitch = GxmDevice::DisplayStride;
198 frameBuf.pixelformat = SCE_DISPLAY_PIXELFORMAT_A8B8G8R8;
199 frameBuf.width = GxmDevice::DisplayWidth;
200 frameBuf.height = GxmDevice::DisplayHeight;
201 sceDisplaySetFrameBuf(&frameBuf, SCE_DISPLAY_SETBUF_NEXTFRAME);
202
203 if (data->Vsync) {
204 sceDisplayWaitSetFrameBuf();
205 }
206 }
207 }
208
209 // -- Static state --
210
211 GxmDevice::BlendingState GxmDevice::_blending;
212 GxmDevice::DepthTestState GxmDevice::_depthTest;
213 GxmDevice::CullFaceState GxmDevice::_cullFace;
214 GxmDevice::ScissorState GxmDevice::_scissor;
215 Recti GxmDevice::_viewport(0, 0, GxmDevice::DisplayWidth, GxmDevice::DisplayHeight);
216 Colorf GxmDevice::_clearColor(0.0f, 0.0f, 0.0f, 1.0f);
217
218 GxmShaderProgram* GxmDevice::_currentProgram = nullptr;
219 const GxmTexture* GxmDevice::_boundTextures[GxmDevice::MaxTextureUnits] = {};
220 GxmDevice::UniformRange GxmDevice::_boundUniformRanges[GxmDevice::MaxUniformBindings];
221 GxmRenderTarget* GxmDevice::_currentRenderTarget = nullptr;
222
223 SceGxmContext* GxmDevice::_context = nullptr;
224 SceGxmShaderPatcher* GxmDevice::_shaderPatcher = nullptr;
225 SceGxmRenderTarget* GxmDevice::_displayRenderTarget = nullptr;
226
227 GxmMemory::Block GxmDevice::_contextHostMem;
228 GxmMemory::Block GxmDevice::_vdmRingBuffer;
229 GxmMemory::Block GxmDevice::_vertexRingBuffer;
230 GxmMemory::Block GxmDevice::_fragmentRingBuffer;
231 GxmMemory::Block GxmDevice::_fragmentUsseRingBuffer;
232 GxmMemory::Block GxmDevice::_patcherBufferMem;
233 GxmMemory::Block GxmDevice::_patcherVertexUsseMem;
234 GxmMemory::Block GxmDevice::_patcherFragmentUsseMem;
235
236 GxmMemory::Block GxmDevice::_displayBuffers[GxmDevice::DisplayBufferCount];
237 SceGxmColorSurface GxmDevice::_displaySurfaces[GxmDevice::DisplayBufferCount];
238 SceGxmSyncObject* GxmDevice::_displaySyncObjects[GxmDevice::DisplayBufferCount] = {};
239 std::uint32_t GxmDevice::_backBufferIndex = 0;
240 std::uint32_t GxmDevice::_frontBufferIndex = 0;
241
242 GxmMemory::Block GxmDevice::_screenBuffer;
243 SceGxmColorSurface GxmDevice::_screenSurface;
244 SceGxmTexture GxmDevice::_screenTexture;
245 SceGxmSyncObject* GxmDevice::_screenSyncObject = nullptr;
246
247 GxmMemory::Block GxmDevice::_depthBuffer;
248 SceGxmDepthStencilSurface GxmDevice::_depthSurface;
249
250 bool GxmDevice::_initialized = false;
251 bool GxmDevice::_vsync = true;
252 bool GxmDevice::_sceneOpen = false;
253 void* GxmDevice::_sceneSurfaceData = nullptr;
254 std::uint32_t GxmDevice::_sceneCounter = 0;
255 bool GxmDevice::_sceneStateApplied = false;
256 std::int32_t GxmDevice::_sceneWidth = GxmDevice::DisplayWidth;
257 std::int32_t GxmDevice::_sceneHeight = GxmDevice::DisplayHeight;
258
259 SceGxmShaderPatcherId GxmDevice::_clearVertexId = nullptr;
260 SceGxmShaderPatcherId GxmDevice::_clearFragmentId = nullptr;
261 SceGxmVertexProgram* GxmDevice::_clearVertexProgram = nullptr;
262 SceGxmFragmentProgram* GxmDevice::_clearFragmentProgram = nullptr;
263 std::uint32_t GxmDevice::_clearQuadIndex = 0;
264 GxmMemory::Block GxmDevice::_clearVertices;
265
266 SceGxmShaderPatcherId GxmDevice::_presentVertexId = nullptr;
267 SceGxmShaderPatcherId GxmDevice::_presentFragmentId = nullptr;
268 SceGxmVertexProgram* GxmDevice::_presentVertexProgram = nullptr;
269 SceGxmFragmentProgram* GxmDevice::_presentFragmentProgram = nullptr;
270 GxmMemory::Block GxmDevice::_presentVertices;
271
272 GxmMemory::Block GxmDevice::_sequentialIndices;
273 std::uint32_t GxmDevice::_sequentialIndexCount = 0;
274 GxmMemory::Block GxmDevice::_lineStripIndices;
275 std::uint32_t GxmDevice::_lineStripVertexCount = 0;
276
277 GxmMemory::Block GxmDevice::_quadCornerStream;
278 GxmMemory::Block GxmDevice::_batchedCornerStream;
279 GxmMemory::Block GxmDevice::_retiredBlocks[GxmDevice::RetiredBlockCount];
280 SceGxmNotification GxmDevice::_sceneNotification = {};
281
282 // -- Pipeline state --
283
284 void GxmDevice::SetBlendingEnabled(bool enabled)
285 {
286 _blending.Enabled = enabled;
287 }
288
289 void GxmDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
290 {
291 _blending.SrcRgb = srcRgb;
292 _blending.DstRgb = dstRgb;
293 _blending.SrcAlpha = srcAlpha;
294 _blending.DstAlpha = dstAlpha;
295 }
296
297 GxmDevice::BlendingState GxmDevice::GetBlendingState()
298 {
299 return _blending;
300 }
301
302 void GxmDevice::SetBlendingState(const BlendingState& state)
303 {
304 _blending = state;
305 }
306
307 void GxmDevice::SetDepthTestEnabled(bool enabled)
308 {
309 _depthTest.TestEnabled = enabled;
310 }
311
312 void GxmDevice::SetDepthMaskEnabled(bool enabled)
313 {
314 _depthTest.MaskEnabled = enabled;
315 }
316
317 GxmDevice::DepthTestState GxmDevice::GetDepthTestState()
318 {
319 return _depthTest;
320 }
321
322 void GxmDevice::SetDepthTestState(const DepthTestState& state)
323 {
324 _depthTest = state;
325 }
326
327 void GxmDevice::SetCullFaceEnabled(bool enabled)
328 {
329 _cullFace.Enabled = enabled;
330 }
331
332 GxmDevice::CullFaceState GxmDevice::GetCullFaceState()
333 {
334 return _cullFace;
335 }
336
337 void GxmDevice::SetCullFaceState(const CullFaceState& state)
338 {
339 _cullFace = state;
340 }
341
342 GxmDevice::ScissorState GxmDevice::GetScissorState()
343 {
344 return _scissor;
345 }
346
347 void GxmDevice::SetScissorState(const ScissorState& state)
348 {
349 _scissor = state;
350 _sceneStateApplied = false;
351 }
352
353 void GxmDevice::SetScissor(const Recti& rect)
354 {
355 // Handing over a rectangle also *enables* the test, which is what the OpenGL backend's
356 // `GLScissorTest::Enable(rect)` does and what the D3D11 and software backends copy: the pipeline gives a
357 // command its clip rectangle (RenderCommand::Issue()) without ever enabling the test separately, so a
358 // backend that only stored the rectangle here would clip nothing at all
359 _scissor.Rect = rect;
360 _scissor.Enabled = true;
361 _sceneStateApplied = false;
362 }
363
364 void GxmDevice::SetScissorTestEnabled(bool enabled)
365 {
366 _scissor.Enabled = enabled;
367 _sceneStateApplied = false;
368 }
369
370 Recti GxmDevice::GetViewport()
371 {
372 return _viewport;
373 }
374
375 void GxmDevice::SetViewport(const Recti& rect)
376 {
377 _viewport = rect;
378 _sceneStateApplied = false;
379 }
380
381 void GxmDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
382 {
383 _viewport = Recti(x, y, width, height);
384 _sceneStateApplied = false;
385 }
386
387 Colorf GxmDevice::GetClearColor()
388 {
389 return _clearColor;
390 }
391
392 void GxmDevice::SetClearColor(const Colorf& color)
393 {
394 _clearColor = color;
395 }
396
397 void GxmDevice::SetupInitialState()
398 {
399 _blending = BlendingState();
400 _depthTest = DepthTestState();
401 _cullFace = CullFaceState();
402 _scissor = ScissorState();
403 _sceneStateApplied = false;
404 }
405
406 // -- Resource binding --
407
408 void GxmDevice::BindProgram(GxmShaderProgram* program)
409 {
410 _currentProgram = program;
411 }
412
413 GxmShaderProgram* GxmDevice::CurrentProgram()
414 {
415 return _currentProgram;
416 }
417
418 void GxmDevice::BindTexture(std::uint32_t unit, const GxmTexture* texture)
419 {
420 if (unit < MaxTextureUnits) {
421 _boundTextures[unit] = texture;
422 }
423 }
424
425 void GxmDevice::UnbindTexture(const GxmTexture* texture)
426 {
427 for (std::uint32_t i = 0; i < MaxTextureUnits; i++) {
428 if (_boundTextures[i] == texture) {
429 _boundTextures[i] = nullptr;
430 }
431 }
432 }
433
434 const GxmTexture* GxmDevice::GetBoundTexture(std::uint32_t unit)
435 {
436 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
437 }
438
439 void GxmDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
440 {
441 if (index < MaxUniformBindings) {
442 _boundUniformRanges[index].Data = data;
443 _boundUniformRanges[index].Size = size;
444 }
445 }
446
447 void GxmDevice::GetUniformRange(std::uint32_t index, const std::uint8_t*& data, std::uint32_t& size)
448 {
449 if (index < MaxUniformBindings) {
450 data = _boundUniformRanges[index].Data;
451 size = _boundUniformRanges[index].Size;
452 } else {
453 data = nullptr;
454 size = 0;
455 }
456 }
457
458 void GxmDevice::SetRenderTarget(GxmRenderTarget* renderTarget)
459 {
460 // No scene is closed here. What matters is the *surface* a scene renders into, not which framebuffer
461 // object was bound to reach it, and whether that surface really changed is decided when the next draw
462 // needs a scene (see EnsureScene()) - so layering a pass by binding several framebuffers over one
463 // texture, which is how the pipeline draws its scene, clipped and overlay layers, keeps adding to the
464 // scene already open on it instead of starting one that would discard the layers underneath
465 _currentRenderTarget = renderTarget;
466 }
467
468 void GxmDevice::UnbindRenderTarget(const GxmRenderTarget* renderTarget)
469 {
470 // Any open scene is closed, not only one belonging to this target: closing is deferred now (see
471 // SetRenderTarget()), so the scene still recording may be the one this target's surface owns even when
472 // something else has since been bound - and this runs because that target is being destroyed
473 FinishScene();
474 if (_currentRenderTarget == renderTarget) {
475 _currentRenderTarget = nullptr;
476 }
477 }
478
479 void GxmDevice::OnProgramDestroyed(const GxmShaderProgram* program)
480 {
481 if (_currentProgram == program) {
482 _currentProgram = nullptr;
483 }
484 }
485
486 SceGxmShaderPatcher* GxmDevice::GetShaderPatcher()
487 {
488 return _shaderPatcher;
489 }
490
491 SceGxmContext* GxmDevice::GetContext()
492 {
493 return _context;
494 }
495
496 std::uint32_t GxmDevice::GetSceneCounter()
497 {
498 return _sceneCounter;
499 }
500
501 const void* GxmDevice::GetQuadCornerStream()
502 {
503 return _quadCornerStream.Base;
504 }
505
506 const void* GxmDevice::GetBatchedCornerStream()
507 {
508 return _batchedCornerStream.Base;
509 }
510
511 void GxmDevice::RetireBlock(GxmMemory::Block& block)
512 {
513 if (!block.IsValid()) {
514 return;
515 }
516 // Held until the frame's barrier has passed, because a scene already recorded may still read it. The
517 // table is small and a grow-only buffer stops growing almost immediately; if it ever fills, the block
518 // is released the safe way instead.
519 for (GxmMemory::Block& retired : _retiredBlocks) {
520 if (!retired.IsValid()) {
521 retired = block;
522 block = GxmMemory::Block();
523 return;
524 }
525 }
526 FinishScene();
527 sceGxmFinish(_context);
528 GxmMemory::Free(block);
529 }
530
531 void GxmDevice::ReleaseRetiredBlocks()
532 {
533 for (GxmMemory::Block& retired : _retiredBlocks) {
534 GxmMemory::Free(retired);
535 }
536 }
537
538 void GxmDevice::SetDepthStateBothFaces(SceGxmDepthFunc func, SceGxmDepthWriteMode write)
539 {
540 sceGxmSetFrontDepthFunc(_context, func);
541 sceGxmSetBackDepthFunc(_context, func);
542 sceGxmSetFrontDepthWriteEnable(_context, write);
543 sceGxmSetBackDepthWriteEnable(_context, write);
544 }
545
546 void GxmDevice::SetFragmentProgramEnabledBothFaces(SceGxmFragmentProgramMode mode)
547 {
548 sceGxmSetFrontFragmentProgramEnable(_context, mode);
549 sceGxmSetBackFragmentProgramEnable(_context, mode);
550 }
551
552 // -- Scene management --
553
554 void GxmDevice::GetCurrentTarget(SceGxmRenderTarget*& renderTarget, SceGxmColorSurface*& colorSurface,
555 SceGxmDepthStencilSurface*& depthSurface, SceGxmSyncObject*& syncObject, std::int32_t& width, std::int32_t& height)
556 {
557 depthSurface = &_depthSurface;
558 if (_currentRenderTarget != nullptr &&
559 _currentRenderTarget->GetSceneTarget(renderTarget, colorSurface, syncObject, width, height)) {
560 return;
561 }
562
563 // The screen surface is written by the frame and sampled by the present blit, so it is a
564 // render-to-texture hand-off like any other and carries its own sync object (see
565 // GxmRenderTarget::GetSceneTarget())
566 renderTarget = _displayRenderTarget;
567 colorSurface = &_screenSurface;
568 syncObject = _screenSyncObject;
569 width = DisplayWidth;
570 height = DisplayHeight;
571 }
572
573 bool GxmDevice::EnsureScene()
574 {
575 if (_context == nullptr) {
576 return false;
577 }
578
579 SceGxmRenderTarget* renderTarget = nullptr;
580 SceGxmColorSurface* colorSurface = nullptr;
581 SceGxmDepthStencilSurface* depthSurface = nullptr;
582 SceGxmSyncObject* syncObject = nullptr;
583 std::int32_t width = 0, height = 0;
584 GetCurrentTarget(renderTarget, colorSurface, depthSurface, syncObject, width, height);
585 if (renderTarget == nullptr || colorSurface == nullptr) {
586 return false;
587 }
588
589 // Which texels the target writes is what tells one scene from another, because a scene cannot be
590 // reopened without losing what is already in it - its colour tiles start undefined rather than loaded,
591 // so a second scene over a surface publishes garbage where the first one had drawn. The pipeline hands
592 // each layer of a pass its own framebuffer object over the *same* texture and expects every layer to
593 // accumulate (they are all ClearMode::Never), which is only true here while they share one scene.
594 void* surfaceData = sceGxmColorSurfaceGetData(colorSurface);
595 if (_sceneOpen) {
596 if (surfaceData == _sceneSurfaceData) {
597 if (!_sceneStateApplied) {
598 ApplyViewportAndScissor();
599 _sceneStateApplied = true;
600 }
601 return true;
602 }
603 FinishScene();
604 }
605
606 const std::int32_t result = sceGxmBeginScene(_context, 0, renderTarget, nullptr, nullptr, syncObject,
607 colorSurface, depthSurface);
608 if (result < 0) {
609 LOGE("sceGxmBeginScene({}x{}) failed with 0x{:.8x}", width, height, std::uint32_t(result));
610 return false;
611 }
612
613 _sceneOpen = true;
614 _sceneSurfaceData = surfaceData;
615 _sceneWidth = width;
616 _sceneHeight = height;
617 ApplyViewportAndScissor();
618 _sceneStateApplied = true;
619 return true;
620 }
621
622 void GxmDevice::FinishScene()
623 {
624 if (!_sceneOpen || _context == nullptr) {
625 return;
626 }
627 // A scene's output is sampled by a later scene in the same frame all along the pipeline's chain (the
628 // blur passes read the scene view, the composite reads all of them), and sharing one context is not
629 // enough to make that hand-over safe: this scene's tile writeback is still in flight while the next one
630 // records, so the reader can sample what the surface held before. Measured on the console - waiting
631 // here is what makes the level view arrive intact, and not waiting leaves it holding just its clear.
632 //
633 // The notification is sceGxm's own answer to that: the GPU writes `value` to `address` when this
634 // scene's fragment phase completes, so the wait is for this one scene rather than for the whole
635 // pipeline the way sceGxmFinish() would be. A tighter version would wait only when the next scene
636 // really samples this surface, which needs a scene's bindings to be known before it begins.
637 _sceneNotification.value++;
638 sceGxmEndScene(_context, nullptr, &_sceneNotification);
639 sceGxmNotificationWait(&_sceneNotification);
640 _sceneOpen = false;
641 _sceneSurfaceData = nullptr;
642 _sceneStateApplied = false;
643 }
644
645 void GxmDevice::ApplyViewportAndScissor()
646 {
647 if (_context == nullptr) {
648 return;
649 }
650
651 const std::int32_t targetWidth = _sceneWidth;
652 const std::int32_t targetHeight = _sceneHeight;
653
654 // Every surface is stored bottom-up like OpenGL (see the class documentation), so a positive Y scale
655 // is what maps clip -Y onto row 0 - and the viewport's Y, being an OpenGL one measured from the
656 // bottom, is then already a row index
657 const float halfWidth = float(_viewport.W) * 0.5f;
658 const float halfHeight = float(_viewport.H) * 0.5f;
659 sceGxmSetViewport(_context,
660 float(_viewport.X) + halfWidth, halfWidth,
661 float(_viewport.Y) + halfHeight, halfHeight,
662 0.5f, 0.5f);
663
664 if (_scissor.Enabled) {
665 // The maximum of a region clip is inclusive
666 const std::int32_t xMin = (_scissor.Rect.X > 0 ? _scissor.Rect.X : 0);
667 const std::int32_t yMin = (_scissor.Rect.Y > 0 ? _scissor.Rect.Y : 0);
668 std::int32_t xMax = _scissor.Rect.X + _scissor.Rect.W - 1;
669 std::int32_t yMax = _scissor.Rect.Y + _scissor.Rect.H - 1;
670 if (xMax >= targetWidth) { xMax = targetWidth - 1; }
671 if (yMax >= targetHeight) { yMax = targetHeight - 1; }
672 if (xMax < xMin || yMax < yMin) {
673 // An empty scissor rectangle has to reject everything, which "clip outside an empty region"
674 // cannot express - a 1x1 region outside the surface is the closest equivalent
675 sceGxmSetRegionClip(_context, SCE_GXM_REGION_CLIP_OUTSIDE, 0, 0, 0, 0);
676 } else {
677 // Measured on the console: the rows of a region clip run opposite to the way this backend stores
678 // its surfaces, so the rectangle is mirrored vertically. The viewport above can express either
679 // direction because its Y scale is signed - which is what puts clip -Y on row 0 and gives every
680 // surface OpenGL's bottom-up layout - while an unsigned clip rectangle cannot, so anything handed
681 // to sceGxm as plain surface rows has to be turned over to match the rectangle `glScissor()`
682 // takes on the reference backend
683 const std::int32_t yMinClip = targetHeight - 1 - yMax;
684 const std::int32_t yMaxClip = targetHeight - 1 - yMin;
685 sceGxmSetRegionClip(_context, SCE_GXM_REGION_CLIP_OUTSIDE,
686 std::uint32_t(xMin), std::uint32_t(yMinClip), std::uint32_t(xMax), std::uint32_t(yMaxClip));
687 }
688 } else {
689 sceGxmSetRegionClip(_context, SCE_GXM_REGION_CLIP_NONE, 0, 0, 0, 0);
690 }
691 }
692
693 bool GxmDevice::EnsureSequentialIndices(std::uint32_t count)
694 {
695 if (count <= _sequentialIndexCount) {
696 return true;
697 }
698 // 16-bit indexing is limited to values below 64000 by the hardware; a single draw never comes close
699 if (count > 63999) {
700 LOGW("A draw of {} vertices exceeds the 16-bit index range and was skipped", count);
701 return false;
702 }
703
704 std::uint32_t newCount = (_sequentialIndexCount > 0 ? _sequentialIndexCount : 4096);
705 while (newCount < count) {
706 newCount *= 2;
707 }
708 if (newCount > 63999) {
709 newCount = 63999;
710 }
711
712 GxmMemory::Block block = GxmMemory::Alloc("Jazz2:SequentialIndices", newCount * sizeof(std::uint16_t), SCE_GXM_MEMORY_ATTRIB_READ);
713 if (!block.IsValid()) {
714 return false;
715 }
716
717 std::uint16_t* indices = static_cast<std::uint16_t*>(block.Base);
718 for (std::uint32_t i = 0; i < newCount; i++) {
719 indices[i] = std::uint16_t(i);
720 }
721
722 // The old buffer may still be referenced by a submitted scene, so it is retired rather than released
723 // (see RetireBlock()) - ending the scene to make freeing it safe is what used to throw away everything
724 // the pass had drawn, because the draw that follows opens a new scene over the same surface and a
725 // colour tile buffer starts undefined
726 RetireBlock(_sequentialIndices);
727 _sequentialIndices = block;
728 _sequentialIndexCount = newCount;
729 return true;
730 }
731
732 bool GxmDevice::EnsureLineStripIndices(std::uint32_t vertexCount)
733 {
734 if (vertexCount <= _lineStripVertexCount) {
735 return true;
736 }
737 if (vertexCount > 32000) {
738 LOGW("A line strip of {} vertices exceeds the 16-bit index range and was skipped", vertexCount);
739 return false;
740 }
741
742 std::uint32_t newCount = (_lineStripVertexCount > 0 ? _lineStripVertexCount : 256);
743 while (newCount < vertexCount) {
744 newCount *= 2;
745 }
746 if (newCount > 32000) {
747 newCount = 32000;
748 }
749
750 // Two indices per vertex, so the window starting at 2 * firstVertex reads (first, first+1),
751 // (first+1, first+2), ... - the segments of a strip that begins at firstVertex
752 GxmMemory::Block block = GxmMemory::Alloc("Jazz2:LineStripIndices",
753 newCount * 2u * sizeof(std::uint16_t), SCE_GXM_MEMORY_ATTRIB_READ);
754 if (!block.IsValid()) {
755 return false;
756 }
757
758 std::uint16_t* indices = static_cast<std::uint16_t*>(block.Base);
759 for (std::uint32_t i = 0; i < newCount; i++) {
760 indices[i * 2 + 0] = std::uint16_t(i);
761 indices[i * 2 + 1] = std::uint16_t(i + 1);
762 }
763
764 RetireBlock(_lineStripIndices);
765 _lineStripIndices = block;
766 _lineStripVertexCount = newCount;
767 return true;
768 }
769
770 // -- Clear --
771
772 void GxmDevice::Clear(ClearFlags flags)
773 {
774 if (flags == ClearFlags::None || !EnsureScene() || _clearVertexProgram == nullptr || _clearFragmentProgram == nullptr) {
775 return;
776 }
777 if (!EnsureSequentialIndices(4)) {
778 return;
779 }
780
781 const bool clearColor = ((std::uint32_t(flags) & std::uint32_t(ClearFlags::Color)) != 0);
782 const bool clearDepth = ((std::uint32_t(flags) & std::uint32_t(ClearFlags::Depth)) != 0);
783
784 const std::int32_t targetWidth = _sceneWidth;
785 const std::int32_t targetHeight = _sceneHeight;
786
787 // glClear covers the whole surface (modulated by the scissor test) rather than the viewport, so the
788 // quad is drawn through a full-target viewport and the tracked one is restored afterwards
789 sceGxmSetViewport(_context, float(targetWidth) * 0.5f, float(targetWidth) * 0.5f,
790 float(targetHeight) * 0.5f, float(targetHeight) * 0.5f, 0.5f, 0.5f);
791
792 sceGxmSetVertexProgram(_context, _clearVertexProgram);
793 sceGxmSetFragmentProgram(_context, _clearFragmentProgram);
794 sceGxmSetCullMode(_context, SCE_GXM_CULL_NONE);
795 SetDepthStateBothFaces(SCE_GXM_DEPTH_FUNC_ALWAYS,
796 clearDepth ? SCE_GXM_DEPTH_WRITE_ENABLED : SCE_GXM_DEPTH_WRITE_DISABLED);
797 // A colour-less clear (depth only) still has to rasterize the quad, with the colour write masked off -
798 // which the fragment program's blend info carries, so the masked variant is a separate program
799 SetFragmentProgramEnabledBothFaces(clearColor
800 ? SCE_GXM_FRAGMENT_PROGRAM_ENABLED : SCE_GXM_FRAGMENT_PROGRAM_DISABLED);
801
802 // This clear's own quad, carrying the colour with it (see ClearVertex)
803 ClearVertex* quad = static_cast<ClearVertex*>(_clearVertices.Base)
804 + (_clearQuadIndex % ClearQuadRingSize) * 4u;
805 _clearQuadIndex++;
806 for (std::uint32_t i = 0; i < 4; i++) {
807 quad[i].X = ClearQuad[i * 2 + 0];
808 quad[i].Y = ClearQuad[i * 2 + 1];
809 quad[i].R = _clearColor.R;
810 quad[i].G = _clearColor.G;
811 quad[i].B = _clearColor.B;
812 quad[i].A = _clearColor.A;
813 }
814
815 sceGxmSetVertexStream(_context, 0, quad);
816 sceGxmDraw(_context, SCE_GXM_PRIMITIVE_TRIANGLE_STRIP, SCE_GXM_INDEX_FORMAT_U16, _sequentialIndices.Base, 4);
817
818 SetFragmentProgramEnabledBothFaces(SCE_GXM_FRAGMENT_PROGRAM_ENABLED);
819 ApplyViewportAndScissor();
820 }
821
822 // -- Draw --
823
824 void GxmDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
825 {
826 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, 1, 0);
827 }
828
829 void GxmDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
830 {
831 DrawCommon(primitive, firstVertex, std::uint32_t(numVertices), false, IndexFormat::UInt16, 0, numInstances, 0);
832 }
833
834 void GxmDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
835 {
836 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, 1, baseVertex);
837 }
838
839 void GxmDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
840 {
841 DrawCommon(primitive, 0, numIndices, true, indexFormat, indexOffset, numInstances, baseVertex);
842 }
843
844 void GxmDevice::DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
845 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
846 {
847 if (count == 0 || _currentProgram == nullptr || !EnsureScene()) {
848 return;
849 }
850
851 GxmShaderProgram* program = _currentProgram;
852 SceGxmVertexProgram* vertexProgram = program->GetVertexProgram();
853 if (vertexProgram == nullptr) {
854 return;
855 }
856
857 SceGxmBlendInfo blendInfo = {};
858 const SceGxmBlendInfo* blendInfoPtr = nullptr;
859 if (_blending.Enabled) {
860 blendInfo.colorMask = SCE_GXM_COLOR_MASK_ALL;
861 blendInfo.colorFunc = SCE_GXM_BLEND_FUNC_ADD;
862 blendInfo.alphaFunc = SCE_GXM_BLEND_FUNC_ADD;
863 blendInfo.colorSrc = TranslateBlendFactor(_blending.SrcRgb);
864 blendInfo.colorDst = TranslateBlendFactor(_blending.DstRgb);
865 blendInfo.alphaSrc = TranslateBlendFactor(_blending.SrcAlpha);
866 blendInfo.alphaDst = TranslateBlendFactor(_blending.DstAlpha);
867 blendInfoPtr = &blendInfo;
868 }
869 const std::uint32_t blendKey = GxmShaderProgram::PackBlendKey(_blending.Enabled,
870 _blending.SrcRgb, _blending.DstRgb, _blending.SrcAlpha, _blending.DstAlpha);
871 SceGxmFragmentProgram* fragmentProgram = program->GetFragmentProgram(blendKey, blendInfoPtr);
872 if (fragmentProgram == nullptr) {
873 return;
874 }
875
876 sceGxmSetVertexProgram(_context, vertexProgram);
877 sceGxmSetFragmentProgram(_context, fragmentProgram);
878 // A depth-only Clear() switches the fragment stage off; make sure a real draw always has it back on
879 SetFragmentProgramEnabledBothFaces(SCE_GXM_FRAGMENT_PROGRAM_ENABLED);
880
881 // OpenGL ties depth writes to the depth test: with GL_DEPTH_TEST disabled, glDepthMask(true) still
882 // writes nothing. Keeping that coupling here matters, because a later depth-tested draw would otherwise
883 // see values this one was not supposed to leave behind
884 const bool depthWrites = (_depthTest.TestEnabled && _depthTest.MaskEnabled);
885 SetDepthStateBothFaces(_depthTest.TestEnabled ? SCE_GXM_DEPTH_FUNC_LESS_EQUAL : SCE_GXM_DEPTH_FUNC_ALWAYS,
886 depthWrites ? SCE_GXM_DEPTH_WRITE_ENABLED : SCE_GXM_DEPTH_WRITE_DISABLED);
887 if (_cullFace.Enabled) {
888 // The engine winds its front faces counter-clockwise in the OpenGL convention, which this backend
889 // preserves by storing every surface bottom-up - so the winding reaches the GPU unchanged
890 sceGxmSetCullMode(_context, _cullFace.Mode == CullFaceMode::Front ? SCE_GXM_CULL_CCW : SCE_GXM_CULL_CW);
891 } else {
892 sceGxmSetCullMode(_context, SCE_GXM_CULL_NONE);
893 }
894
895 // Uniforms: sceGxm addresses a default uniform buffer in 32-bit components, so a slot's bytes land at
896 // its resource index times four. The buffer is per draw and comes out of the context's vertex ring
897 void* vertexUniformBuffer = nullptr;
898 if (program->GetVertexUniformBufferSize() > 0) {
899 if (sceGxmReserveVertexDefaultUniformBuffer(_context, &vertexUniformBuffer) >= 0 && vertexUniformBuffer != nullptr) {
900 UploadUniforms(vertexUniformBuffer, program, program->GetVertexUniformSlots(), program->GetVertexBlockUploads());
901 } else {
902 // Drawing anyway would use whatever the ring buffer still held, which is worse than not drawing
903 static bool warned = false;
904 if (!warned) {
905 warned = true;
906 LOGW("Ran out of vertex ring buffer reserving {} bytes of uniforms; some draws were skipped",
907 program->GetVertexUniformBufferSize());
908 }
909 return;
910 }
911 }
912
913 void* fragmentUniformBuffer = nullptr;
914 if (program->GetFragmentUniformBufferSize() > 0) {
915 if (sceGxmReserveFragmentDefaultUniformBuffer(_context, &fragmentUniformBuffer) >= 0 && fragmentUniformBuffer != nullptr) {
916 UploadUniforms(fragmentUniformBuffer, program, program->GetFragmentUniformSlots(), program->GetFragmentBlockUploads());
917 } else {
918 static bool warned = false;
919 if (!warned) {
920 warned = true;
921 LOGW("Ran out of fragment ring buffer reserving {} bytes of uniforms; some draws were skipped",
922 program->GetFragmentUniformBufferSize());
923 }
924 return;
925 }
926 }
927
928 BindUniformBufferContainers(true, program->GetVertexBlockUploads());
929 BindUniformBufferContainers(false, program->GetFragmentBlockUploads());
930
931 for (const GxmShaderProgram::GxmSamplerSlot& slot : program->GetVertexSamplerSlots()) {
932 const GxmTexture* texture = GetBoundTexture(slot.EngineUnit);
933 if (texture != nullptr) {
934 if (const SceGxmTexture* gxmTexture = texture->GetGxmTexture()) {
935 sceGxmSetVertexTexture(_context, slot.TextureIndex, gxmTexture);
936 }
937 }
938 }
939 for (const GxmShaderProgram::GxmSamplerSlot& slot : program->GetFragmentSamplerSlots()) {
940 const GxmTexture* texture = GetBoundTexture(slot.EngineUnit);
941 if (texture != nullptr) {
942 if (const SceGxmTexture* gxmTexture = texture->GetGxmTexture()) {
943 sceGxmSetFragmentTexture(_context, slot.TextureIndex, gxmTexture);
944 }
945 }
946 }
947
948 // Vertex streams. The static corner stream is where the vertex-ID-free sprite shaders read their quad
949 // corner (and batched instance index) from; everything else comes from the pipeline's vertex buffer
950 if (program->UsesStaticCornerStream()) {
951 const void* stream = (program->UsesBatchedCornerStream() ? GetBatchedCornerStream() : GetQuadCornerStream());
952 if (stream == nullptr) {
953 return;
954 }
955 sceGxmSetVertexStream(_context, program->GetStaticStreamIndex(), stream);
956 }
957 // A non-indexed draw is reproduced with a window of the shared increasing-index buffer, and the window
958 // can start at the first vertex or the stream can - the pipeline suballocates its geometry out of one
959 // large buffer, so `firstVertex` is where this command's vertices begin in it and is routinely large.
960 // Advancing the *stream* keeps the indices at 0..count-1, so a draw only ever needs as many indices as
961 // it has vertices instead of as many as its offset into the buffer; the alternative reaches sceGxm's
962 // 16-bit index ceiling (63999) on a big enough buffer and silently drops the draw. Only the geometry
963 // stream can absorb it - the static corner streams are indexed from zero by definition, and the draws
964 // that read them always pass a first vertex of zero anyway.
965 const bool foldFirstVertexIntoStream = (!indexed && !program->UsesStaticCornerStream() && firstVertex > 0);
966 if (program->UsesGeometryStream()) {
967 const GxmBufferObject* vbo = program->GetBoundVbo();
968 const void* vertexData = (vbo != nullptr ? vbo->GetGpuData() : nullptr);
969 if (vertexData == nullptr) {
970 return;
971 }
972 // sceGxmDraw has no base-vertex parameter, so a base vertex shifts the stream address instead
973 const std::uint32_t stride = program->GetGeometryStride();
974 const std::uint8_t* base = static_cast<const std::uint8_t*>(vertexData) + program->GetVboOffset()
975 + std::size_t(baseVertex > 0 ? baseVertex : 0) * stride
976 + std::size_t(foldFirstVertexIntoStream ? firstVertex : 0) * stride;
977 sceGxmSetVertexStream(_context, 0, base);
978 }
979
980 const SceGxmPrimitiveType primitiveType = TranslatePrimitive(primitive);
981 const bool isLineStrip = (primitive == PrimitiveType::LineStrip || primitive == PrimitiveType::LineLoop);
982 const void* indexData = nullptr;
983 std::uint32_t indexCount = count;
984 SceGxmIndexFormat gxmIndexFormat = SCE_GXM_INDEX_FORMAT_U16;
985 if (indexed) {
986 const GxmBufferObject* ibo = program->GetBoundIbo();
987 const void* indexBase = (ibo != nullptr ? ibo->GetGpuData() : nullptr);
988 if (indexBase == nullptr) {
989 return;
990 }
991 indexData = static_cast<const std::uint8_t*>(indexBase) + indexOffset;
992 gxmIndexFormat = (indexFormat == IndexFormat::UInt32 ? SCE_GXM_INDEX_FORMAT_U32 : SCE_GXM_INDEX_FORMAT_U16);
993 } else if (isLineStrip) {
994 // A strip of N vertices is N-1 segments, which the paired index buffer spells out - from the pair
995 // that starts at the first vertex, or from the very first pair when the stream has already been
996 // advanced to it (see foldFirstVertexIntoStream above). Counting the offset in both places shifts
997 // the strip twice and it is drawn from whatever vertices happen to sit there.
998 const std::uint32_t first = (foldFirstVertexIntoStream ? 0u : std::uint32_t(firstVertex > 0 ? firstVertex : 0));
999 if (count < 2 || !EnsureLineStripIndices(first + count)) {
1000 return;
1001 }
1002 indexData = static_cast<const std::uint16_t*>(_lineStripIndices.Base) + first * 2u;
1003 indexCount = (count - 1) * 2u;
1004 } else {
1005 // There is no non-indexed draw: a window of the shared increasing-index buffer reproduces
1006 // glDrawArrays(first, count) exactly, indices included - starting at zero when the stream has
1007 // already been advanced to the first vertex (see foldFirstVertexIntoStream above)
1008 const std::uint32_t first = (foldFirstVertexIntoStream ? 0u : std::uint32_t(firstVertex > 0 ? firstVertex : 0));
1009 if (!EnsureSequentialIndices(first + count)) {
1010 return;
1011 }
1012 indexData = static_cast<const std::uint16_t*>(_sequentialIndices.Base) + first;
1013 }
1014
1015 if (numInstances > 1) {
1016 // GPU instancing would need both an index buffer whose pattern repeats per instance and a vertex
1017 // stream declared with SCE_GXM_INDEX_SOURCE_INSTANCE_*, and the engine's layouts provide neither -
1018 // it batches with the vertex-ID trick instead and never asks for an instanced draw. Rather than
1019 // silently render one instance and call it done, say so.
1020 static bool warned = false;
1021 if (!warned) {
1022 warned = true;
1023 LOGW("Instanced draws are not implemented on this backend; {} instances were drawn as one", numInstances);
1024 }
1025 }
1026 sceGxmDraw(_context, primitiveType, gxmIndexFormat, indexData, indexCount);
1027 }
1028
1029 void GxmDevice::UploadUniforms(void* uniformBuffer, GxmShaderProgram* program,
1030 const SmallVector<GxmUniformSlot, 0>& slots, const SmallVector<GxmShaderProgram::GxmBlockUpload, 0>& blocks)
1031 {
1032 // A default uniform buffer is addressed in 32-bit components, so a resolved resource index times four
1033 // is the byte offset the value belongs at (see GxmUniformSlot)
1034 std::uint8_t* base = static_cast<std::uint8_t*>(uniformBuffer);
1035 for (const GxmUniformSlot& slot : slots) {
1036 if (const std::uint8_t* value = program->ResolveUniform(slot.Name)) {
1037 std::memcpy(base + slot.ResourceIndex * 4u, value, slot.ByteSize);
1038 }
1039 }
1040
1041 for (const GxmShaderProgram::GxmBlockUpload& upload : blocks) {
1042 if (upload.Where != GxmShaderProgram::GxmBlockUpload::Destination::DefaultUniformBuffer) {
1043 continue; // bound by address instead, see BindUniformBufferContainers()
1044 }
1045 const std::uint8_t* data = nullptr;
1046 std::uint32_t size = 0;
1047 GetUniformRange(upload.BindingIndex, data, size);
1048 if (data == nullptr || size <= upload.SourceOffset) {
1049 continue;
1050 }
1051
1052 // Only what the pipeline actually bound is copied - a batched draw binds just the instances it
1053 // filled, not the whole declared array
1054 std::uint32_t bytes = size - upload.SourceOffset;
1055 if (bytes > upload.MaxByteSize) {
1056 bytes = upload.MaxByteSize;
1057 }
1058
1059 if (upload.CompiledStride != 0 && upload.SourceStride != 0
1060 && upload.CompiledStride != upload.SourceStride) {
1061 // A batched instance array the compiler packed tighter than std140 (see GxmBlockUpload): copied
1062 // as one run only its first element would land where the shader reads it, so it goes element by
1063 // element, from the pipeline's stride to the shader's
1064 const std::uint32_t elements = bytes / upload.SourceStride;
1065 const std::uint32_t elementBytes = (upload.SourceStride < upload.CompiledStride
1066 ? upload.SourceStride : upload.CompiledStride);
1067 for (std::uint32_t element = 0; element < elements; element++) {
1068 std::memcpy(base + upload.Index * 4u + element * upload.CompiledStride,
1069 data + upload.SourceOffset + element * upload.SourceStride, elementBytes);
1070 }
1071 continue;
1072 }
1073
1074 std::memcpy(base + upload.Index * 4u, data + upload.SourceOffset, bytes);
1075 }
1076 }
1077
1078 void GxmDevice::BindUniformBufferContainers(bool vertexStage, const SmallVector<GxmShaderProgram::GxmBlockUpload, 0>& blocks)
1079 {
1080 // A block too large for the uniform registers is not written anywhere - the range the pipeline filled
1081 // is handed to sceGxm as an address, which is why those buffers are GPU-visible memory. This is a
1082 // context call rather than a buffer write, so it happens whether or not a default buffer was reserved.
1083 for (const GxmShaderProgram::GxmBlockUpload& upload : blocks) {
1084 if (upload.Where != GxmShaderProgram::GxmBlockUpload::Destination::UniformBufferContainer) {
1085 continue;
1086 }
1087 const std::uint8_t* data = nullptr;
1088 std::uint32_t size = 0;
1089 GetUniformRange(upload.BindingIndex, data, size);
1090 if (data == nullptr || size <= upload.SourceOffset) {
1091 continue;
1092 }
1093 const void* base = data + upload.SourceOffset;
1094 if (vertexStage) {
1095 sceGxmSetVertexUniformBuffer(_context, upload.Index, base);
1096 } else {
1097 sceGxmSetFragmentUniformBuffer(_context, upload.Index, base);
1098 }
1099 }
1100 }
1101
1102 // -- Fences --
1103
1104 FenceHandle GxmDevice::InsertFence()
1105 {
1106 // sceGxm has no lightweight fence object; the pipeline only uses these to know when a buffer range it
1107 // wrote has been consumed, which sceGxmFinish() answers conservatively (see ClientWaitFence)
1108 return reinterpret_cast<FenceHandle>(std::uintptr_t(1));
1109 }
1110
1111 void GxmDevice::DeleteFence(FenceHandle& fence)
1112 {
1113 fence = nullptr;
1114 }
1115
1116 bool GxmDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
1117 {
1118 static_cast<void>(timeoutNs);
1119 if (fence == nullptr || _context == nullptr) {
1120 return true;
1121 }
1122 // Waiting for everything is stronger than the caller asked for, but correct - and this is only reached
1123 // when the pipeline's ring buffers have wrapped, which the enlarged vertex ring makes rare
1124 FinishScene();
1125 sceGxmFinish(_context);
1126 return true;
1127 }
1128
1129 // -- Session lifecycle --
1130
1131 bool GxmDevice::CreateBuiltinShaders()
1132 {
1133 struct BuiltinStage
1134 {
1135 const char* Source;
1136 shark_type Type;
1137 SceGxmProgram** Output;
1138 SceGxmShaderPatcherId* Id;
1139 const char* Name;
1140 };
1141
1142 static SceGxmProgram* clearVertexStage = nullptr;
1143 static SceGxmProgram* clearFragmentStage = nullptr;
1144 static SceGxmProgram* presentVertexStage = nullptr;
1145 static SceGxmProgram* presentFragmentStage = nullptr;
1146
1147 const BuiltinStage stages[] = {
1148 { ClearVertexSource, SHARK_VERTEX_SHADER, &clearVertexStage, &_clearVertexId, "clear vertex" },
1149 { ClearFragmentSource, SHARK_FRAGMENT_SHADER, &clearFragmentStage, &_clearFragmentId, "clear fragment" },
1150 { PresentVertexSource, SHARK_VERTEX_SHADER, &presentVertexStage, &_presentVertexId, "present vertex" },
1151 { PresentFragmentSource, SHARK_FRAGMENT_SHADER, &presentFragmentStage, &_presentFragmentId, "present fragment" }
1152 };
1153
1154 for (const BuiltinStage& stage : stages) {
1155 // A previous attempt that got this far and then failed left a copy behind (the failure paths tear
1156 // the session down and the window backend may try again), so release it before overwriting it
1157 std::free(*stage.Output);
1158 *stage.Output = nullptr;
1159
1160 std::uint32_t size = 0;
1161 *stage.Output = GxmShaderProgram::CompileCgStage(stage.Source, stage.Type == SHARK_VERTEX_SHADER, size);
1162 if (*stage.Output == nullptr) {
1163 LOGE("Failed to compile the built-in {} shader", stage.Name);
1164 return false;
1165 }
1166 LOGD("Compiled the built-in {} shader ({} bytes of GXP)", stage.Name, size);
1167 if (sceGxmShaderPatcherRegisterProgram(_shaderPatcher, *stage.Output, stage.Id) < 0) {
1168 LOGE("Failed to register the built-in {} shader with the shader patcher", stage.Name);
1169 return false;
1170 }
1171
1172 }
1173
1174 // Resolving an attribute that is not there hands sceGxm a null parameter, which faults rather than
1175 // failing - so every lookup below goes through the resolver that reports what the stage really declares.
1176 // When reflection cannot resolve it, the declaration order is used instead: sceGxm assigns attribute
1177 // registers in that order, and unlike the generated shaders these two have a fixed, known signature -
1178 // so a built-in shader is the one case where the convention is safe to lean on rather than a guess.
1179 const auto resolveAttribute = [](const SceGxmProgram* program, const char* name,
1180 std::uint32_t declarationIndex, std::uint16_t& regIndex) {
1181 if (const SceGxmProgramParameter* parameter = GxmShaderProgram::FindAttribute(program, name)) {
1182 regIndex = std::uint16_t(sceGxmProgramParameterGetResourceIndex(parameter));
1183 return;
1184 }
1185 LOGW("Falling back to register {} for the built-in shader's \"{}\" attribute", declarationIndex, name);
1186 regIndex = std::uint16_t(declarationIndex);
1187 };
1188
1189 // Clear: one float2 position per vertex, no blending (it overwrites the surface)
1190 SceGxmVertexAttribute clearAttribute = {};
1191 clearAttribute.streamIndex = 0;
1192 clearAttribute.offset = 0;
1193 clearAttribute.format = SCE_GXM_ATTRIBUTE_FORMAT_F32;
1194 clearAttribute.componentCount = 2;
1195 resolveAttribute(clearVertexStage, "aPosition", 0, clearAttribute.regIndex);
1196 SceGxmVertexAttribute clearColorAttribute = {};
1197 clearColorAttribute.streamIndex = 0;
1198 clearColorAttribute.offset = offsetof(ClearVertex, R);
1199 clearColorAttribute.format = SCE_GXM_ATTRIBUTE_FORMAT_F32;
1200 clearColorAttribute.componentCount = 4;
1201 resolveAttribute(clearVertexStage, "aColor", 1, clearColorAttribute.regIndex);
1202 const SceGxmVertexAttribute clearAttributes[2] = { clearAttribute, clearColorAttribute };
1203 SceGxmVertexStream clearStream = {};
1204 clearStream.stride = sizeof(ClearVertex);
1205 clearStream.indexSource = SCE_GXM_INDEX_SOURCE_INDEX_16BIT;
1206 if (sceGxmShaderPatcherCreateVertexProgram(_shaderPatcher, _clearVertexId, clearAttributes, 2,
1207 &clearStream, 1, &_clearVertexProgram) < 0 ||
1208 sceGxmShaderPatcherCreateFragmentProgram(_shaderPatcher, _clearFragmentId,
1209 SCE_GXM_OUTPUT_REGISTER_FORMAT_UCHAR4, SCE_GXM_MULTISAMPLE_NONE, nullptr, clearVertexStage,
1210 &_clearFragmentProgram) < 0) {
1211 LOGE("Failed to create the built-in clear programs");
1212 return false;
1213 }
1214
1215 // Present: position + texture coordinates, no blending
1216 SceGxmVertexAttribute presentAttributes[2] = {};
1217 presentAttributes[0].streamIndex = 0;
1218 presentAttributes[0].offset = 0;
1219 presentAttributes[0].format = SCE_GXM_ATTRIBUTE_FORMAT_F32;
1220 presentAttributes[0].componentCount = 2;
1221 presentAttributes[1].streamIndex = 0;
1222 presentAttributes[1].offset = sizeof(float) * 2;
1223 presentAttributes[1].format = SCE_GXM_ATTRIBUTE_FORMAT_F32;
1224 presentAttributes[1].componentCount = 2;
1225 resolveAttribute(presentVertexStage, "aPosition", 0, presentAttributes[0].regIndex);
1226 resolveAttribute(presentVertexStage, "aTexCoords", 1, presentAttributes[1].regIndex);
1227 SceGxmVertexStream presentStream = {};
1228 presentStream.stride = sizeof(float) * 4;
1229 presentStream.indexSource = SCE_GXM_INDEX_SOURCE_INDEX_16BIT;
1230 if (sceGxmShaderPatcherCreateVertexProgram(_shaderPatcher, _presentVertexId, presentAttributes, 2,
1231 &presentStream, 1, &_presentVertexProgram) < 0 ||
1232 sceGxmShaderPatcherCreateFragmentProgram(_shaderPatcher, _presentFragmentId,
1233 SCE_GXM_OUTPUT_REGISTER_FORMAT_UCHAR4, SCE_GXM_MULTISAMPLE_NONE, nullptr, presentVertexStage,
1234 &_presentFragmentProgram) < 0) {
1235 LOGE("Failed to create the built-in present programs");
1236 return false;
1237 }
1238
1239 // Their geometry, in GPU-visible memory like every other stream
1240 _clearVertices = GxmMemory::Alloc("Jazz2:ClearQuad",
1241 ClearQuadRingSize * 4u * sizeof(ClearVertex), SCE_GXM_MEMORY_ATTRIB_READ);
1242 _presentVertices = GxmMemory::Alloc("Jazz2:PresentQuad", sizeof(PresentQuad), SCE_GXM_MEMORY_ATTRIB_READ);
1243 if (!_clearVertices.IsValid() || !_presentVertices.IsValid()) {
1244 return false;
1245 }
1246 std::memcpy(_presentVertices.Base, PresentQuad, sizeof(PresentQuad));
1247 return true;
1248 }
1249
1250 bool GxmDevice::CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync)
1251 {
1252 static_cast<void>(windowHandle);
1253 static_cast<void>(width);
1254 static_cast<void>(height);
1255
1256 if (_initialized) {
1257 return true;
1258 }
1259 _vsync = vsync;
1260
1261 SceGxmInitializeParams initializeParams = {};
1262 initializeParams.flags = 0;
1263 initializeParams.displayQueueMaxPendingCount = DisplayBufferCount - 1;
1264 initializeParams.displayQueueCallback = DisplayQueueCallback;
1265 initializeParams.displayQueueCallbackDataSize = sizeof(DisplayQueueCallbackData);
1266 initializeParams.parameterBufferSize = SCE_GXM_DEFAULT_PARAMETER_BUFFER_SIZE;
1267 std::int32_t result = sceGxmInitialize(&initializeParams);
1268 if (result < 0) {
1269 LOGE("sceGxmInitialize() failed with 0x{:.8x}", std::uint32_t(result));
1270 return false;
1271 }
1272
1273 // From here on every failure exits through DestroySwapchain(), which needs this set to do its work. A
1274 // half-initialized device would otherwise keep opening scenes it can never present - a black screen
1275 // with no clue why, instead of the diagnostic that got us here
1276 _initialized = true;
1277
1278 // The context's ring buffers, then the context itself
1279 _contextHostMem = GxmMemory::Alloc("Jazz2:GxmContextHost", ContextHostMemSize, SCE_GXM_MEMORY_ATTRIB_RW);
1280 _vdmRingBuffer = GxmMemory::Alloc("Jazz2:GxmVdmRing", VdmRingBufferSize, SCE_GXM_MEMORY_ATTRIB_READ);
1281 _vertexRingBuffer = GxmMemory::Alloc("Jazz2:GxmVertexRing", VertexRingBufferSize, SCE_GXM_MEMORY_ATTRIB_READ);
1282 _fragmentRingBuffer = GxmMemory::Alloc("Jazz2:GxmFragmentRing", FragmentRingBufferSize, SCE_GXM_MEMORY_ATTRIB_READ);
1283 _fragmentUsseRingBuffer = GxmMemory::AllocFragmentUsse("Jazz2:GxmFragmentUsseRing", FragmentUsseRingBufferSize);
1284 if (!_contextHostMem.IsValid() || !_vdmRingBuffer.IsValid() || !_vertexRingBuffer.IsValid() ||
1285 !_fragmentRingBuffer.IsValid() || !_fragmentUsseRingBuffer.IsValid()) {
1286 LOGE("Failed to allocate the sceGxm context ring buffers");
1287 DestroySwapchain();
1288 return false;
1289 }
1290
1291 SceGxmContextParams contextParams = {};
1292 contextParams.hostMem = _contextHostMem.Base;
1293 contextParams.hostMemSize = _contextHostMem.Size;
1294 contextParams.vdmRingBufferMem = _vdmRingBuffer.Base;
1295 contextParams.vdmRingBufferMemSize = _vdmRingBuffer.Size;
1296 contextParams.vertexRingBufferMem = _vertexRingBuffer.Base;
1297 contextParams.vertexRingBufferMemSize = _vertexRingBuffer.Size;
1298 contextParams.fragmentRingBufferMem = _fragmentRingBuffer.Base;
1299 contextParams.fragmentRingBufferMemSize = _fragmentRingBuffer.Size;
1300 contextParams.fragmentUsseRingBufferMem = _fragmentUsseRingBuffer.Base;
1301 contextParams.fragmentUsseRingBufferMemSize = _fragmentUsseRingBuffer.Size;
1302 contextParams.fragmentUsseRingBufferOffset = _fragmentUsseRingBuffer.UsseOffset;
1303 result = sceGxmCreateContext(&contextParams, &_context);
1304 if (result < 0) {
1305 LOGE("sceGxmCreateContext() failed with 0x{:.8x}", std::uint32_t(result));
1306 DestroySwapchain();
1307 return false;
1308 }
1309
1310 // The render target describing the panel's tiling, shared by the screen surface and the display buffers
1311 SceGxmRenderTargetParams renderTargetParams = {};
1312 renderTargetParams.flags = 0;
1313 renderTargetParams.width = DisplayWidth;
1314 renderTargetParams.height = DisplayHeight;
1315 renderTargetParams.scenesPerFrame = 8;
1316 renderTargetParams.multisampleMode = SCE_GXM_MULTISAMPLE_NONE;
1317 renderTargetParams.multisampleLocations = 0;
1318 renderTargetParams.driverMemBlock = GxmMemory::InvalidUid;
1319 result = sceGxmCreateRenderTarget(&renderTargetParams, &_displayRenderTarget);
1320 if (result < 0) {
1321 LOGE("sceGxmCreateRenderTarget({}x{}) failed with 0x{:.8x}", DisplayWidth, DisplayHeight, std::uint32_t(result));
1322 DestroySwapchain();
1323 return false;
1324 }
1325
1326 // The display buffers the controller scans out of, with the sync object that keeps the GPU from
1327 // overwriting one still on screen
1328 const std::uint32_t displayBufferSize = std::uint32_t(DisplayStride) * std::uint32_t(DisplayHeight) * 4u;
1329 for (std::uint32_t i = 0; i < DisplayBufferCount; i++) {
1330 _displayBuffers[i] = GxmMemory::AllocCdram("Jazz2:DisplayBuffer", displayBufferSize, SCE_GXM_MEMORY_ATTRIB_RW);
1331 if (!_displayBuffers[i].IsValid()) {
1332 LOGE("Failed to allocate display buffer {}", i);
1333 DestroySwapchain();
1334 return false;
1335 }
1336 std::memset(_displayBuffers[i].Base, 0, displayBufferSize);
1337
1338 result = sceGxmColorSurfaceInit(&_displaySurfaces[i], SCE_GXM_COLOR_FORMAT_U8U8U8U8_ABGR,
1339 SCE_GXM_COLOR_SURFACE_LINEAR, SCE_GXM_COLOR_SURFACE_SCALE_NONE, SCE_GXM_OUTPUT_REGISTER_SIZE_32BIT,
1340 DisplayWidth, DisplayHeight, DisplayStride, _displayBuffers[i].Base);
1341 if (result < 0) {
1342 LOGE("sceGxmColorSurfaceInit(display {}) failed with 0x{:.8x}", i, std::uint32_t(result));
1343 DestroySwapchain();
1344 return false;
1345 }
1346 result = sceGxmSyncObjectCreate(&_displaySyncObjects[i]);
1347 if (result < 0) {
1348 LOGE("sceGxmSyncObjectCreate({}) failed with 0x{:.8x}", i, std::uint32_t(result));
1349 DestroySwapchain();
1350 return false;
1351 }
1352 }
1353
1354 // The intermediate surface every screen-targeted draw lands in, kept bottom-up like OpenGL and
1355 // flipped into a display buffer at present time
1356 _screenBuffer = GxmMemory::AllocCdram("Jazz2:ScreenSurface", displayBufferSize, SCE_GXM_MEMORY_ATTRIB_RW);
1357 if (!_screenBuffer.IsValid()) {
1358 LOGE("Failed to allocate the intermediate screen surface");
1359 DestroySwapchain();
1360 return false;
1361 }
1362 std::memset(_screenBuffer.Base, 0, displayBufferSize);
1363 result = sceGxmColorSurfaceInit(&_screenSurface, SCE_GXM_COLOR_FORMAT_U8U8U8U8_ABGR,
1364 SCE_GXM_COLOR_SURFACE_LINEAR, SCE_GXM_COLOR_SURFACE_SCALE_NONE, SCE_GXM_OUTPUT_REGISTER_SIZE_32BIT,
1365 DisplayWidth, DisplayHeight, DisplayStride, _screenBuffer.Base);
1366 if (result < 0) {
1367 LOGE("sceGxmColorSurfaceInit(screen) failed with 0x{:.8x}", std::uint32_t(result));
1368 DestroySwapchain();
1369 return false;
1370 }
1371 result = sceGxmSyncObjectCreate(&_screenSyncObject);
1372 if (result < 0) {
1373 LOGE("sceGxmSyncObjectCreate(screen) failed with 0x{:.8x}", std::uint32_t(result));
1374 _screenSyncObject = nullptr;
1375 DestroySwapchain();
1376 return false;
1377 }
1378 result = sceGxmTextureInitLinear(&_screenTexture, _screenBuffer.Base, SCE_GXM_TEXTURE_FORMAT_U8U8U8U8_ABGR,
1379 DisplayWidth, DisplayHeight, 0);
1380 if (result < 0) {
1381 LOGE("sceGxmTextureInitLinear(screen) failed with 0x{:.8x}", std::uint32_t(result));
1382 DestroySwapchain();
1383 return false;
1384 }
1385 sceGxmTextureSetMinFilter(&_screenTexture, SCE_GXM_TEXTURE_FILTER_POINT);
1386 sceGxmTextureSetMagFilter(&_screenTexture, SCE_GXM_TEXTURE_FILTER_POINT);
1387 sceGxmTextureSetUAddrMode(&_screenTexture, SCE_GXM_TEXTURE_ADDR_CLAMP);
1388 sceGxmTextureSetVAddrMode(&_screenTexture, SCE_GXM_TEXTURE_ADDR_CLAMP);
1389
1390 // One depth/stencil surface shared by every scene: the renderer is 2D and never needs a depth buffer's
1391 // contents to outlive a pass, and this stride covers any render target the pipeline creates
1392 const std::uint32_t depthBufferSize = std::uint32_t(DisplayStride) * std::uint32_t(DisplayHeight) * 4u;
1393 _depthBuffer = GxmMemory::Alloc("Jazz2:DepthSurface", depthBufferSize, SCE_GXM_MEMORY_ATTRIB_RW);
1394 if (!_depthBuffer.IsValid()) {
1395 LOGE("Failed to allocate the depth/stencil surface");
1396 DestroySwapchain();
1397 return false;
1398 }
1399 result = sceGxmDepthStencilSurfaceInit(&_depthSurface, SCE_GXM_DEPTH_STENCIL_FORMAT_DF32,
1400 SCE_GXM_DEPTH_STENCIL_SURFACE_TILED, DisplayStride, _depthBuffer.Base, nullptr);
1401 if (result < 0) {
1402 LOGE("sceGxmDepthStencilSurfaceInit() failed with 0x{:.8x}", std::uint32_t(result));
1403 DestroySwapchain();
1404 return false;
1405 }
1406 // Every scene initializes its on-chip tile depth from this value, so setting it to the far plane is
1407 // what gives each pass the cleared depth buffer an OpenGL frame starts with
1408 sceGxmDepthStencilSurfaceSetBackgroundDepth(&_depthSurface, 1.0f);
1409
1410 // The shader patcher every program's vertex/fragment programs are created through
1411 _patcherBufferMem = GxmMemory::Alloc("Jazz2:PatcherBuffer", PatcherBufferSize, SCE_GXM_MEMORY_ATTRIB_RW);
1412 _patcherVertexUsseMem = GxmMemory::AllocVertexUsse("Jazz2:PatcherVertexUsse", PatcherVertexUsseSize);
1413 _patcherFragmentUsseMem = GxmMemory::AllocFragmentUsse("Jazz2:PatcherFragmentUsse", PatcherFragmentUsseSize);
1414 if (!_patcherBufferMem.IsValid() || !_patcherVertexUsseMem.IsValid() || !_patcherFragmentUsseMem.IsValid()) {
1415 LOGE("Failed to allocate the sceGxm shader patcher pools");
1416 DestroySwapchain();
1417 return false;
1418 }
1419
1420 SceGxmShaderPatcherParams patcherParams = {};
1421 patcherParams.userData = nullptr;
1422 patcherParams.hostAllocCallback = nullptr;
1423 patcherParams.hostFreeCallback = nullptr;
1424 patcherParams.bufferAllocCallback = nullptr;
1425 patcherParams.bufferFreeCallback = nullptr;
1426 patcherParams.bufferMem = _patcherBufferMem.Base;
1427 patcherParams.bufferMemSize = _patcherBufferMem.Size;
1428 patcherParams.vertexUsseAllocCallback = nullptr;
1429 patcherParams.vertexUsseFreeCallback = nullptr;
1430 patcherParams.vertexUsseMem = _patcherVertexUsseMem.Base;
1431 patcherParams.vertexUsseMemSize = _patcherVertexUsseMem.Size;
1432 patcherParams.vertexUsseOffset = _patcherVertexUsseMem.UsseOffset;
1433 patcherParams.fragmentUsseAllocCallback = nullptr;
1434 patcherParams.fragmentUsseFreeCallback = nullptr;
1435 patcherParams.fragmentUsseMem = _patcherFragmentUsseMem.Base;
1436 patcherParams.fragmentUsseMemSize = _patcherFragmentUsseMem.Size;
1437 patcherParams.fragmentUsseOffset = _patcherFragmentUsseMem.UsseOffset;
1438 // sceGxm needs its host allocator when no callbacks are given; passing plain malloc/free keeps the
1439 // patcher's bookkeeping on the C++ heap, which is where the rest of the engine's small allocations live
1440 patcherParams.hostAllocCallback = [](void* userData, SceSize size) -> void* {
1441 static_cast<void>(userData);
1442 return std::malloc(size);
1443 };
1444 patcherParams.hostFreeCallback = [](void* userData, void* mem) {
1445 static_cast<void>(userData);
1446 std::free(mem);
1447 };
1448 result = sceGxmShaderPatcherCreate(&patcherParams, &_shaderPatcher);
1449 if (result < 0) {
1450 LOGE("sceGxmShaderPatcherCreate() failed with 0x{:.8x}", std::uint32_t(result));
1451 DestroySwapchain();
1452 return false;
1453 }
1454
1455 // sceGxm consumes compiled GXP binaries and the SDK ships no offline compiler for them, so the whole
1456 // shader set is compiled on the console by the firmware's own Cg compiler. A build that bundles the
1457 // module in its own VPK is served first, the standard shared location second
1458 if (shark_init(ShaderCompilerModulePath) < 0 && shark_init(ShaderCompilerModulePathAlt) < 0) {
1459 LOGE("Cannot initialize the runtime Cg compiler: \"libshacccg.suprx\" was not found. This backend "
1460 "compiles its shaders on the console, so that firmware module has to be extracted and placed "
1461 "in \"ur0:/data/\" (see the PS Vita section of the console documentation)");
1462 DestroySwapchain();
1463 return false;
1464 }
1465
1466 // A scene's completion notification has to be written into the driver's own notification region
1467 // (see FinishScene())
1468 _sceneNotification.address = sceGxmGetNotificationRegion();
1469 _sceneNotification.value = 0;
1470 if (_sceneNotification.address == nullptr) {
1471 LOGE("sceGxmGetNotificationRegion() returned nothing, so scene completion cannot be waited on");
1472 DestroySwapchain();
1473 return false;
1474 }
1475 *_sceneNotification.address = 0;
1476
1477 // Before the first compile of anything, so a built-in shader that fails says why
1478 GxmShaderProgram::InstallCompilerLogCallback();
1479
1480 if (!CreateBuiltinShaders()) {
1481 DestroySwapchain();
1482 return false;
1483 }
1484
1485 // The two static streams feeding the vertex-ID-free sprite layouts
1486 _quadCornerStream = GxmMemory::Alloc("Jazz2:QuadCorners", sizeof(QuadCorners), SCE_GXM_MEMORY_ATTRIB_READ);
1487 _batchedCornerStream = GxmMemory::Alloc("Jazz2:BatchedCorners", MaxBatchSize * 6u * 3u * sizeof(float), SCE_GXM_MEMORY_ATTRIB_READ);
1488 if (!_quadCornerStream.IsValid() || !_batchedCornerStream.IsValid()) {
1489 LOGE("Failed to allocate the static vertex streams");
1490 DestroySwapchain();
1491 return false;
1492 }
1493 std::memcpy(_quadCornerStream.Base, QuadCorners, sizeof(QuadCorners));
1494 float* batched = static_cast<float*>(_batchedCornerStream.Base);
1495 for (std::uint32_t instance = 0; instance < MaxBatchSize; instance++) {
1496 for (std::uint32_t corner = 0; corner < 6; corner++) {
1497 float* vertex = batched + (instance * 6u + corner) * 3u;
1498 vertex[0] = BatchedCorners[corner][0];
1499 vertex[1] = BatchedCorners[corner][1];
1500 vertex[2] = float(instance);
1501 }
1502 }
1503
1504 if (!EnsureSequentialIndices(4096)) {
1505 LOGE("Failed to allocate the shared index buffer");
1506 DestroySwapchain();
1507 return false;
1508 }
1509
1510 _backBufferIndex = 0;
1511 _frontBufferIndex = DisplayBufferCount - 1;
1512 LOGI("sceGxm initialized ({}x{}, {} display buffers, {} KB of GPU memory reserved)",
1513 DisplayWidth, DisplayHeight, DisplayBufferCount, GxmMemory::GetAllocatedBytes() / 1024);
1514 return true;
1515 }
1516
1517 void GxmDevice::DestroySwapchain()
1518 {
1519 if (!_initialized) {
1520 return;
1521 }
1522
1523 FinishScene();
1524 if (_context != nullptr) {
1525 sceGxmFinish(_context);
1526 }
1527 sceGxmDisplayQueueFinish();
1528
1529 shark_end();
1530
1531 if (_shaderPatcher != nullptr) {
1532 if (_clearVertexProgram != nullptr) { sceGxmShaderPatcherReleaseVertexProgram(_shaderPatcher, _clearVertexProgram); }
1533 if (_clearFragmentProgram != nullptr) { sceGxmShaderPatcherReleaseFragmentProgram(_shaderPatcher, _clearFragmentProgram); }
1534 if (_presentVertexProgram != nullptr) { sceGxmShaderPatcherReleaseVertexProgram(_shaderPatcher, _presentVertexProgram); }
1535 if (_presentFragmentProgram != nullptr) { sceGxmShaderPatcherReleaseFragmentProgram(_shaderPatcher, _presentFragmentProgram); }
1536 sceGxmShaderPatcherDestroy(_shaderPatcher);
1537 _shaderPatcher = nullptr;
1538 }
1539 _clearVertexProgram = nullptr;
1540 _clearFragmentProgram = nullptr;
1541 _presentVertexProgram = nullptr;
1542 _presentFragmentProgram = nullptr;
1543 _clearQuadIndex = 0;
1544
1545 for (std::uint32_t i = 0; i < DisplayBufferCount; i++) {
1546 if (_displaySyncObjects[i] != nullptr) {
1547 sceGxmSyncObjectDestroy(_displaySyncObjects[i]);
1548 _displaySyncObjects[i] = nullptr;
1549 }
1550 GxmMemory::Free(_displayBuffers[i]);
1551 }
1552 if (_screenSyncObject != nullptr) {
1553 sceGxmSyncObjectDestroy(_screenSyncObject);
1554 _screenSyncObject = nullptr;
1555 }
1556
1557 if (_displayRenderTarget != nullptr) {
1558 sceGxmDestroyRenderTarget(_displayRenderTarget);
1559 _displayRenderTarget = nullptr;
1560 }
1561 if (_context != nullptr) {
1562 sceGxmDestroyContext(_context);
1563 _context = nullptr;
1564 }
1565
1566 GxmMemory::Free(_screenBuffer);
1567 GxmMemory::Free(_depthBuffer);
1568 GxmMemory::Free(_clearVertices);
1569 GxmMemory::Free(_presentVertices);
1570 GxmMemory::Free(_quadCornerStream);
1571 GxmMemory::Free(_batchedCornerStream);
1572 GxmMemory::Free(_sequentialIndices);
1573 GxmMemory::Free(_lineStripIndices);
1574 GxmMemory::Free(_patcherBufferMem);
1575 GxmMemory::Free(_patcherVertexUsseMem);
1576 GxmMemory::Free(_patcherFragmentUsseMem);
1577 GxmMemory::Free(_fragmentUsseRingBuffer);
1578 GxmMemory::Free(_fragmentRingBuffer);
1579 GxmMemory::Free(_vertexRingBuffer);
1580 GxmMemory::Free(_vdmRingBuffer);
1581 GxmMemory::Free(_contextHostMem);
1582 _sequentialIndexCount = 0;
1583 _lineStripVertexCount = 0;
1584
1585 sceGxmTerminate();
1586 _initialized = false;
1587 }
1588
1589 void GxmDevice::ResizeSwapchain(std::int32_t width, std::int32_t height)
1590 {
1591 static_cast<void>(width);
1592 static_cast<void>(height);
1593 }
1594
1595 void GxmDevice::PresentFrame()
1596 {
1597 if (!_initialized || _context == nullptr) {
1598 return;
1599 }
1600
1601 // Close whatever the frame was still drawing into, then flip the screen surface into the buffer the
1602 // display controller will pick up next
1603 _currentRenderTarget = nullptr;
1604 FinishScene();
1605
1606 if (_presentVertexProgram != nullptr && _presentFragmentProgram != nullptr && EnsureSequentialIndices(4)) {
1607 const std::int32_t result = sceGxmBeginScene(_context, 0, _displayRenderTarget, nullptr, nullptr,
1608 _displaySyncObjects[_backBufferIndex], &_displaySurfaces[_backBufferIndex], &_depthSurface);
1609 if (result >= 0) {
1610 sceGxmSetViewport(_context, float(DisplayWidth) * 0.5f, float(DisplayWidth) * 0.5f,
1611 float(DisplayHeight) * 0.5f, float(DisplayHeight) * 0.5f, 0.5f, 0.5f);
1612 sceGxmSetRegionClip(_context, SCE_GXM_REGION_CLIP_NONE, 0, 0, 0, 0);
1613 sceGxmSetVertexProgram(_context, _presentVertexProgram);
1614 sceGxmSetFragmentProgram(_context, _presentFragmentProgram);
1615 sceGxmSetCullMode(_context, SCE_GXM_CULL_NONE);
1616 SetDepthStateBothFaces(SCE_GXM_DEPTH_FUNC_ALWAYS, SCE_GXM_DEPTH_WRITE_DISABLED);
1617 SetFragmentProgramEnabledBothFaces(SCE_GXM_FRAGMENT_PROGRAM_ENABLED);
1618 sceGxmSetFragmentTexture(_context, 0, &_screenTexture);
1619 sceGxmSetVertexStream(_context, 0, _presentVertices.Base);
1620 sceGxmDraw(_context, SCE_GXM_PRIMITIVE_TRIANGLE_STRIP, SCE_GXM_INDEX_FORMAT_U16, _sequentialIndices.Base, 4);
1621 sceGxmEndScene(_context, nullptr, nullptr);
1622 } else {
1623 LOGE("sceGxmBeginScene(present) failed with 0x{:.8x}", std::uint32_t(result));
1624 }
1625 }
1626
1627 sceGxmPadHeartbeat(&_displaySurfaces[_backBufferIndex], _displaySyncObjects[_backBufferIndex]);
1628
1629 DisplayQueueCallbackData callbackData;
1630 callbackData.Address = _displayBuffers[_backBufferIndex].Base;
1631 callbackData.Vsync = _vsync;
1632 sceGxmDisplayQueueAddEntry(_displaySyncObjects[_frontBufferIndex], _displaySyncObjects[_backBufferIndex], &callbackData);
1633
1634 // Wait for the GPU to finish reading this frame before the CPU starts writing the next one.
1635 //
1636 // This is not a nicety. The pipeline's vertex, index and uniform ring buffers ARE GPU-visible memory
1637 // that the engine writes into directly - there is no upload step and therefore no driver in between to
1638 // serialize those writes against reads still in flight, which is exactly what an OpenGL driver does for
1639 // the same code. Without this barrier the CPU runs up to `displayQueueMaxPendingCount` frames ahead and
1640 // overwrites data the GPU has not consumed, which shows up as geometry that is *almost* right and
1641 // flickers differently every frame. The per-draw default uniform buffer makes it worse: a batched draw
1642 // reserves its whole declared instance array (~64 KB) however few instances it actually uses, so the
1643 // ring turns over in a frame or two.
1644 //
1645 // The cost is real - CPU and GPU no longer overlap. Removing it means giving every per-frame buffer as
1646 // many copies as there are frames in flight and cycling them with the display queue, which is a
1647 // pipeline-wide change rather than a backend one.
1648 sceGxmFinish(_context);
1649
1650 // Everything recorded this frame has been consumed, so anything a growing buffer displaced can go
1651 ReleaseRetiredBlocks();
1652
1653 _frontBufferIndex = _backBufferIndex;
1654 _backBufferIndex = (_backBufferIndex + 1) % DisplayBufferCount;
1655 _sceneCounter++;
1656
1657 // The next frame starts with the screen surface again, and every scene re-applies the state it needs
1658 _sceneStateApplied = false;
1659 }
1660
1661 // -- Debug markers --
1662
1663 void GxmDebug::PushGroup(StringView message)
1664 {
1665 if (SceGxmContext* context = GxmDevice::GetContext()) {
1666 sceGxmPushUserMarker(context, String::nullTerminatedView(message).data());
1667 }
1668 }
1669
1670 void GxmDebug::PopGroup()
1671 {
1672 if (SceGxmContext* context = GxmDevice::GetContext()) {
1673 sceGxmPopUserMarker(context);
1674 }
1675 }
1676
1677 void GxmDebug::MessageInsert(StringView message)
1678 {
1679 if (SceGxmContext* context = GxmDevice::GetContext()) {
1680 sceGxmSetUserMarker(context, String::nullTerminatedView(message).data());
1681 }
1682 }
1683 }