Debian Codegraph @

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

raw
1 #pragma once
2
3 #include "GxmMemory.h"
4 #include "GxmShaderProgram.h"
5 #include "../RhiTypes.h"
6 #include "../../../Primitives/Rect.h"
7 #include "../../../Primitives/Colorf.h"
8
9 #include <cstdint>
10
11 #include <Containers/SmallVector.h>
12
13 #include <psp2/gxm.h>
14
15 using namespace Death::Containers;
16
17 namespace nCine::RHI::GXM
18 {
19 class GxmShaderProgram;
20 class GxmRenderTarget;
21 class GxmTexture;
22
23 /**
24 @brief Pipeline-state and draw-call facade of the sceGxm backend (aliased as `RHI::Device`)
25
26 Exposes the OpenGL device's surface (blending, depth, cull, scissor, viewport, clear and the draw
27 calls) so the backend-neutral render pipeline drives it unchanged, and owns the whole sceGxm session
28 behind it: the rendering context and its ring buffers, the shader patcher, the display buffers with
29 their sync objects and the display queue that scans them out.
30
31 Three properties of the hardware shape everything below.
32
33 **sceGxm renders in scenes.** The PowerVR SGX is a tile-based deferred renderer: primitives are
34 binned, then each 32x32 tile is shaded once and written out. A scene (`sceGxmBeginScene()` ...
35 `sceGxmEndScene()`) is one such pass over one surface, so a scene is opened lazily by the first clear
36 or draw that follows a target change (@ref EnsureScene()) and closed when the target changes again or
37 the frame is presented. Because the tile buffer's colour starts undefined rather than loaded, there
38 is no "clear the surface" operation to issue mid-scene: @ref Clear() draws a full-screen quad with a
39 built-in shader, which is what the clear costs on this architecture (and what OpenGL|ES drivers do
40 here internally too).
41
42 That undefined start is also why re-entering a surface within a frame would silently discard what an
43 earlier scene drew into it. The pipeline does not do this - measured on the console, the screen
44 surface takes exactly one scene per frame, and a render target takes one per pass it is the target of
45 - but it is the constraint any change to the viewport chain has to respect.
46
47 **sceGxm only draws indexed.** There is no `glDrawArrays` equivalent - every `sceGxmDraw()` consumes
48 index data - so the device keeps one shared, GPU-visible buffer of increasing indices (0, 1, 2, ...)
49 and hands a window of it to the non-indexed draws, which reproduces `glDrawArrays(first, count)`
50 exactly. The two vertex-ID-free sprite layouts are served the same way: the shaders the Cg emitter
51 produces read the quad corner (and the batched instance index) from vertex attributes rather than
52 `gl_VertexID`, so the device also owns the two small static streams that feed them (see
53 @ref GetQuadCornerStream()).
54
55 **The display scans out top-down.** The engine renders in the OpenGL convention, and this backend
56 replays it faithfully: every viewport is programmed with a positive Y scale, so clip -Y lands on row
57 0 and every surface - the screen and each off-screen render target - is stored bottom-up exactly like
58 OpenGL. That is what keeps a texture's V axis and its viewport's Y axis pointing the same way, so an
59 off-screen round trip does not flip the image (the property that makes the scene composite and the
60 directly drawn HUD agree). The scan-out then needs the one correction that convention implies:
61 "screen" (no render target bound) is an intermediate surface, and @ref PresentFrame() flips it into
62 the display buffer with a built-in shader - the same single OpenGL-to-native flip the Direct3D 11
63 backend does with its present blit, which also scales the logical resolution up to the panel for free.
64 */
65 class GxmDevice
66 {
67 public:
68 GxmDevice() = delete;
69 ~GxmDevice() = delete;
70
71 struct ScissorState
72 {
73 bool Enabled = false;
74 Recti Rect = Recti(0, 0, 0, 0);
75 };
76
77 struct BlendingState
78 {
79 bool Enabled = false;
80 nCine::BlendingFactor SrcRgb = nCine::BlendingFactor::One;
81 nCine::BlendingFactor DstRgb = nCine::BlendingFactor::Zero;
82 nCine::BlendingFactor SrcAlpha = nCine::BlendingFactor::One;
83 nCine::BlendingFactor DstAlpha = nCine::BlendingFactor::Zero;
84 };
85
86 struct DepthTestState
87 {
88 bool TestEnabled = false;
89 bool MaskEnabled = true;
90 };
91
92 struct CullFaceState
93 {
94 bool Enabled = false;
95 CullFaceMode Mode = CullFaceMode::Back;
96 };
97
98 static void SetBlendingEnabled(bool enabled);
99 static void SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha);
100 static BlendingState GetBlendingState();
101 static void SetBlendingState(const BlendingState& state);
102
103 static void SetDepthTestEnabled(bool enabled);
104 static void SetDepthMaskEnabled(bool enabled);
105 static DepthTestState GetDepthTestState();
106 static void SetDepthTestState(const DepthTestState& state);
107
108 static void SetCullFaceEnabled(bool enabled);
109 static CullFaceState GetCullFaceState();
110 static void SetCullFaceState(const CullFaceState& state);
111
112 static ScissorState GetScissorState();
113 static void SetScissorState(const ScissorState& state);
114 static void SetScissor(const Recti& rect);
115 static void SetScissorTestEnabled(bool enabled);
116
117 static Recti GetViewport();
118 static void SetViewport(const Recti& rect);
119 static void InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height);
120
121 static Colorf GetClearColor();
122 static void SetClearColor(const Colorf& color);
123 static void Clear(ClearFlags flags);
124
125 static void DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
126 static void DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances);
127 static void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex);
128 static inline void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t baseVertex) {
129 DrawElements(primitive, numIndices, IndexFormat::UInt16, indexOffset, baseVertex);
130 }
131 static void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex);
132 static inline void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex) {
133 DrawElementsInstanced(primitive, numIndices, IndexFormat::UInt16, indexOffset, numInstances, baseVertex);
134 }
135
136 static FenceHandle InsertFence();
137 static void DeleteFence(FenceHandle& fence);
138 static bool ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs);
139
140 static void SetupInitialState();
141
142 // -- Backend extensions (called by the resource types) --
143
144 /** @brief Records the currently bound shader program */
145 static void BindProgram(GxmShaderProgram* program);
146 /** @brief Returns the currently bound shader program */
147 static GxmShaderProgram* CurrentProgram();
148 /** @brief Records the texture bound to a texture unit */
149 static void BindTexture(std::uint32_t unit, const GxmTexture* texture);
150 /** @brief Clears a texture from every unit it is bound to (called from ~GxmTexture to avoid a dangling pointer) */
151 static void UnbindTexture(const GxmTexture* texture);
152 /** @brief Returns the texture bound to a texture unit */
153 static const GxmTexture* GetBoundTexture(std::uint32_t unit);
154 /** @brief Records the host data range bound to a uniform binding point */
155 static void BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size);
156 /** @brief Returns the host data range bound to a uniform binding point (read by the draw path) */
157 static void GetUniformRange(std::uint32_t index, const std::uint8_t*& data, std::uint32_t& size);
158 /** @brief Clears a render target from the device if it is the current one (called from ~GxmRenderTarget) */
159 static void UnbindRenderTarget(const GxmRenderTarget* renderTarget);
160 /** @brief Records the current draw render target (its bound color attachments receive the pixels) */
161 static void SetRenderTarget(GxmRenderTarget* renderTarget);
162 /** @brief Clears a destroyed program from the device's current-program tracking (called from ~GxmShaderProgram) */
163 static void OnProgramDestroyed(const GxmShaderProgram* program);
164
165 /**
166 @brief Ends the scene currently being recorded, if any
167
168 Called whenever what the following draws render into changes - a render-target switch, the frame's
169 presentation, or a resource the open scene still references going away.
170 */
171 static void FinishScene();
172
173 /** @brief Returns the shader patcher every program creates its vertex/fragment programs through */
174 static SceGxmShaderPatcher* GetShaderPatcher();
175 /** @brief Returns the rendering context, or `nullptr` before @ref CreateSwapchain() */
176 static SceGxmContext* GetContext();
177
178 /** @brief Monotonic count of presented frames (used to detect resources still referenced by the current frame) */
179 static std::uint32_t GetSceneCounter();
180
181 /**
182 @brief Returns the static vertex stream feeding `aQuadCorner` for the 4-vertex sprite strip
183
184 The corners are in the order of the single-quad `TRIANGLE_STRIP` draw - {(1,0), (1,1), (0,0),
185 (0,1)} - which is what the Cg emitter's rewrite of the engine's `gl_VertexID` corner formula
186 expects (see `ShaderCompiler::VertexIdRewrite`). Two floats per vertex.
187 */
188 static const void* GetQuadCornerStream();
189 /**
190 @brief Returns the static vertex stream feeding `aQuadCorner` + `aInstanceIndex` for batched sprites
191
192 Six vertices per sprite (two triangles) carrying the batched corner order {(1,1), (0,1), (0,0),
193 (0,0), (1,0), (1,1)} and the sprite's index within the batch, so a batched draw of `6 * n`
194 vertices reproduces the `gl_VertexID / 6` instance lookup and the corner formula the emitter
195 rewrote. Three floats per vertex; covers @ref MaxBatchSize sprites.
196 */
197 static const void* GetBatchedCornerStream();
198 /** @brief Largest batch the @ref GetBatchedCornerStream() covers (the 64 KB uniform-block budget divided by the smallest instance stride) */
199 static constexpr std::uint32_t MaxBatchSize = 682;
200
201 // -- sceGxm session lifecycle (called by the window backend) --
202
203 /**
204 @brief Brings up the whole sceGxm session and the display queue
205
206 @param windowHandle Ignored (the Vita has one fixed display, so there is no window to attach to);
207 accepted only to keep the uniform swap-chain contract of the other backends
208 @param width Ignored, the panel is always 960x544
209 @param height Ignored
210 @param vsync Whether @ref PresentFrame() waits for the display swap to be picked up
211 @returns `true` if sceGxm, the context, the surfaces and the built-in shaders all came up
212 */
213 static bool CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync);
214 /** @brief Tears the session down (finishes the display queue, then releases everything in creation order) */
215 static void DestroySwapchain();
216 /** @brief No-op: the panel resolution is fixed (the logical resolution is a render-target size, not a swap-chain one) */
217 static void ResizeSwapchain(std::int32_t width, std::int32_t height);
218 /** @brief Flips the intermediate screen surface into the next display buffer and queues it for scan-out */
219 static void PresentFrame();
220
221 // The Vita has no multi-window support at all, so the ImGui multi-viewport hooks are inert here
222 /** @brief Not supported on this platform (returns `nullptr`) */
223 static inline void* CreateSecondarySwapchain(void* windowHandle, std::int32_t width, std::int32_t height) {
224 static_cast<void>(windowHandle);
225 static_cast<void>(width);
226 static_cast<void>(height);
227 return nullptr;
228 }
229 /** @brief Not supported on this platform */
230 static inline void DestroySecondarySwapchain(void* handle) {
231 static_cast<void>(handle);
232 }
233 /** @brief Not supported on this platform */
234 static inline void ResizeSecondarySwapchain(void* handle, std::int32_t width, std::int32_t height) {
235 static_cast<void>(handle);
236 static_cast<void>(width);
237 static_cast<void>(height);
238 }
239 /** @brief Not supported on this platform */
240 static inline void BeginSecondaryFrame(void* handle, bool clear) {
241 static_cast<void>(handle);
242 static_cast<void>(clear);
243 }
244 /** @brief Not supported on this platform */
245 static inline void EndSecondaryFrame() {}
246 /** @brief Not supported on this platform */
247 static inline void PresentSecondaryFrame(void* handle) {
248 static_cast<void>(handle);
249 }
250
251 /** @brief The panel's fixed width in pixels */
252 static constexpr std::int32_t DisplayWidth = 960;
253 /** @brief The panel's fixed height in pixels */
254 static constexpr std::int32_t DisplayHeight = 544;
255 /** @brief Stride of a display buffer in pixels (the display controller requires a 64-pixel aligned stride) */
256 static constexpr std::int32_t DisplayStride = 960;
257
258 /**
259 @brief Returns the largest supported 2D texture dimension
260
261 4096 is the SGX543's limit; it only feeds the tileset chunking in `ContentResolver` and the
262 texture-load assert, both of which the console's content stays well below.
263 */
264 static constexpr std::int32_t GetMaxTextureDimension() {
265 return 4096;
266 }
267 /** @brief Byte alignment the engine suballocates bound uniform ranges with (one std140 `vec4`) */
268 static constexpr std::int32_t GetUniformBufferOffsetAlignment() {
269 return 16;
270 }
271
272 /**
273 @brief What the display-queue callback needs to hand one finished buffer to the display controller
274
275 sceGxm copies this into its own queue and passes it back to the callback on the queue thread, so it
276 has to be a plain trivially-copyable structure - and public, because the callback is a free function.
277 */
278 struct DisplayQueueCallbackData
279 {
280 void* Address;
281 bool Vsync;
282 };
283
284 private:
285 static constexpr std::uint32_t MaxTextureUnits = 8;
286 static constexpr std::uint32_t MaxUniformBindings = 8;
287 // Display buffers cycled by the display queue. Two is enough to keep the GPU and the scan-out from
288 // fighting over one surface; a third only helps when a frame occasionally overruns its vblank
289 static constexpr std::uint32_t DisplayBufferCount = 3;
290
291 struct UniformRange
292 {
293 const std::uint8_t* Data = nullptr;
294 std::uint32_t Size = 0;
295 };
296
297 static BlendingState _blending;
298 static DepthTestState _depthTest;
299 static CullFaceState _cullFace;
300 static ScissorState _scissor;
301 static Recti _viewport;
302 static Colorf _clearColor;
303
304 static GxmShaderProgram* _currentProgram;
305 static const GxmTexture* _boundTextures[MaxTextureUnits];
306 static UniformRange _boundUniformRanges[MaxUniformBindings];
307 static GxmRenderTarget* _currentRenderTarget;
308
309 // -- Real sceGxm objects (owned) --
310
311 static SceGxmContext* _context;
312 static SceGxmShaderPatcher* _shaderPatcher;
313 // One render target covers both the intermediate screen surface and the display buffers: they share
314 // the panel's dimensions, and a sceGxmRenderTarget only describes the tiling of a size, not a surface
315 static SceGxmRenderTarget* _displayRenderTarget;
316
317 static GxmMemory::Block _contextHostMem;
318 static GxmMemory::Block _vdmRingBuffer;
319 static GxmMemory::Block _vertexRingBuffer;
320 static GxmMemory::Block _fragmentRingBuffer;
321 static GxmMemory::Block _fragmentUsseRingBuffer;
322 static GxmMemory::Block _patcherBufferMem;
323 static GxmMemory::Block _patcherVertexUsseMem;
324 static GxmMemory::Block _patcherFragmentUsseMem;
325
326 static GxmMemory::Block _displayBuffers[DisplayBufferCount];
327 static SceGxmColorSurface _displaySurfaces[DisplayBufferCount];
328 static SceGxmSyncObject* _displaySyncObjects[DisplayBufferCount];
329 static std::uint32_t _backBufferIndex;
330 static std::uint32_t _frontBufferIndex;
331
332 // The intermediate surface every draw that is not aimed at a render target lands in, kept bottom-up
333 // like OpenGL and flipped into the display buffer at present time (see the class documentation)
334 static GxmMemory::Block _screenBuffer;
335 static SceGxmColorSurface _screenSurface;
336 static SceGxmTexture _screenTexture;
337 // Serializes the frame's writes to the screen surface against the present blit that samples them
338 static SceGxmSyncObject* _screenSyncObject;
339
340 static GxmMemory::Block _depthBuffer;
341 static SceGxmDepthStencilSurface _depthSurface;
342
343 static bool _initialized;
344 static bool _vsync;
345 static bool _sceneOpen;
346 // Texels the open scene renders into, which is what identifies it: a target change that lands on the
347 // same surface goes on adding to this scene rather than starting one that would discard it (see
348 // EnsureScene())
349 static void* _sceneSurfaceData;
350 static std::uint32_t _sceneCounter;
351 // State that has to be re-applied after a scene begins (sceGxmBeginScene resets the pipeline state)
352 static bool _sceneStateApplied;
353
354 // Dimensions of the surface the open scene renders into, recorded when it begins. The viewport and
355 // region clip are derived from them, and reading them back from the render target instead would mean
356 // re-entering GxmRenderTarget::GetSceneTarget() - which is allowed to end the very scene being set up
357 static std::int32_t _sceneWidth;
358 static std::int32_t _sceneHeight;
359
360 // -- Built-in shaders --
361
362 // Clear: a full-screen quad in clip space filled with a uniform colour, the tile-based renderer's
363 // equivalent of glClear (see the class documentation)
364 static SceGxmShaderPatcherId _clearVertexId;
365 static SceGxmShaderPatcherId _clearFragmentId;
366 static SceGxmVertexProgram* _clearVertexProgram;
367 static SceGxmFragmentProgram* _clearFragmentProgram;
368 // Next slot of the clear quad ring, so concurrent clears in one frame keep their own colours
369 static std::uint32_t _clearQuadIndex;
370 static GxmMemory::Block _clearVertices;
371
372 // Present: the screen surface sampled with a flipped V into the display buffer
373 static SceGxmShaderPatcherId _presentVertexId;
374 static SceGxmShaderPatcherId _presentFragmentId;
375 static SceGxmVertexProgram* _presentVertexProgram;
376 static SceGxmFragmentProgram* _presentFragmentProgram;
377 static GxmMemory::Block _presentVertices;
378
379 // Shared 0, 1, 2, ... index buffer standing in for the missing non-indexed draw. Grown on demand by
380 // the largest DrawArrays() the frame issues
381 static GxmMemory::Block _sequentialIndices;
382 static std::uint32_t _sequentialIndexCount;
383 // The same trick for the missing line-strip primitive: pairs (0,1), (1,2), (2,3), ... so a window of
384 // this buffer turns a strip of N vertices into the N-1 independent line segments it means
385 static GxmMemory::Block _lineStripIndices;
386 static std::uint32_t _lineStripVertexCount;
387
388 // The two static streams feeding the vertex-ID-free sprite shaders (see GetQuadCornerStream())
389 static GxmMemory::Block _quadCornerStream;
390 static GxmMemory::Block _batchedCornerStream;
391
392 /** @brief Opens a scene on the current target if none is open, and (re)applies the pipeline state it reset */
393 static bool EnsureScene();
394 /** @brief Programs the viewport and region clip of the current target from the tracked engine state */
395 static void ApplyViewportAndScissor();
396 /**
397 @brief Programs the depth function and depth write mask for **both** facings
398
399 sceGxm keeps the depth (and stencil, and fragment-program-enable) state separately per facing,
400 while OpenGL - whose semantics this backend reproduces - has no per-face depth state at all. The
401 engine leaves face culling off, so both facings rasterize, and which one a quad lands on is not
402 something the pipeline controls: it follows from the winding the geometry happens to have after the
403 bottom-up viewport transform, and the two sprite layouts (a 4-vertex strip, six vertices per
404 batched sprite) do not even agree on it.
405
406 Programming only the front face therefore leaves half the geometry on sceGxm's defaults -
407 `LESS_EQUAL` with depth writes *enabled* - which is a silent, order-dependent depth test the engine
408 never asked for. With everything drawn a few layer steps apart inside a 2D scene, that rejects
409 whatever loses the comparison by a rounding error: individual glyphs of a string vanishing and
410 reappearing between frames, a lighting pass that flickers between correct, black and blown out, and
411 half of a full-screen quad (one triangle of the pair) missing along the diagonal.
412 */
413 static void SetDepthStateBothFaces(SceGxmDepthFunc func, SceGxmDepthWriteMode write);
414 /** @brief Enables or disables the fragment stage for **both** facings (see @ref SetDepthStateBothFaces()) */
415 static void SetFragmentProgramEnabledBothFaces(SceGxmFragmentProgramMode mode);
416 /** @brief Returns the color surface, depth surface and dimensions the current target renders into */
417 static void GetCurrentTarget(SceGxmRenderTarget*& renderTarget, SceGxmColorSurface*& colorSurface,
418 SceGxmDepthStencilSurface*& depthSurface, SceGxmSyncObject*& syncObject, std::int32_t& width, std::int32_t& height);
419 // Written by the GPU when a scene's fragment phase completes, so the next scene can be held off until
420 // the surface it may sample is really there (see FinishScene())
421 static SceGxmNotification _sceneNotification;
422
423 /** @brief Blocks displaced by a grown buffer, freed once the frame that may still read them is done */
424 static constexpr std::uint32_t RetiredBlockCount = 8;
425 static GxmMemory::Block _retiredBlocks[RetiredBlockCount];
426 /** @brief Holds @p block until the end of the frame instead of releasing it now, and invalidates it */
427 static void RetireBlock(GxmMemory::Block& block);
428 /** @brief Frees every retired block (called after the frame's barrier) */
429 static void ReleaseRetiredBlocks();
430
431 /** @brief Returns `true` if @ref _sequentialIndices covers @p count indices, growing it if it does not */
432 static bool EnsureSequentialIndices(std::uint32_t count);
433 /** @brief Returns `true` if @ref _lineStripIndices covers a strip of @p vertexCount vertices, growing it if it does not */
434 static bool EnsureLineStripIndices(std::uint32_t vertexCount);
435 /** @brief Compiles a built-in Cg shader pair and registers it with the patcher */
436 static bool CreateBuiltinShaders();
437 /** @brief Writes a stage's loose uniforms and bound uniform-block ranges into its default uniform buffer */
438 static void UploadUniforms(void* uniformBuffer, GxmShaderProgram* program,
439 const SmallVector<GxmUniformSlot, 0>& slots, const SmallVector<GxmShaderProgram::GxmBlockUpload, 0>& blocks);
440 /** @brief Points a stage's uniform-buffer containers at the ranges the pipeline bound (no copy) */
441 static void BindUniformBufferContainers(bool vertexStage, const SmallVector<GxmShaderProgram::GxmBlockUpload, 0>& blocks);
442 /** @brief Shared body of the draw calls: binds the program, its resources and state, then issues the draw */
443 static void DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
444 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex);
445 /** @brief Draws the full-screen quad of a built-in shader pair into the current scene */
446 static void DrawFullscreenQuad(SceGxmVertexProgram* vertexProgram, SceGxmFragmentProgram* fragmentProgram,
447 const void* vertices, const Colorf* color, const SceGxmTexture* texture);
448 };
449 }