### Shader and Render Target Setup Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Functions for binding shaders, uniform buffers, storage buffers, textures, images, and render targets. ```APIDOC ## Shader and Render Target Setup ### `dkCmdBufBindShaders` Binds shaders to the command buffer. ### Method void ### Endpoint dkCmdBufBindShaders(DkCmdBuf obj, uint32_t stageMask, DkShader const* const shaders[], uint32_t numShaders) ### `dkCmdBufBindUniformBuffers` Binds uniform buffers for a specific stage. ### Method void ### Endpoint dkCmdBufBindUniformBuffers(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkBufExtents const buffers[], uint32_t numBuffers) ### `dkCmdBufBindStorageBuffers` Binds storage buffers for a specific stage. ### Method void ### Endpoint dkCmdBufBindStorageBuffers(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkBufExtents const buffers[], uint32_t numBuffers) ### `dkCmdBufBindTextures` Binds textures for a specific stage. ### Method void ### Endpoint dkCmdBufBindTextures(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkResHandle const handles[], uint32_t numHandles) ### `dkCmdBufBindImages` Binds images for a specific stage. ### Method void ### Endpoint dkCmdBufBindImages(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkResHandle const handles[], uint32_t numHandles) ### `dkCmdBufBindImageDescriptorSet` Binds an image descriptor set. ### Method void ### Endpoint dkCmdBufBindImageDescriptorSet(DkCmdBuf obj, DkGpuAddr setAddr, uint32_t numDescriptors) ### `dkCmdBufBindSamplerDescriptorSet` Binds a sampler descriptor set. ### Method void ### Endpoint dkCmdBufBindSamplerDescriptorSet(DkCmdBuf obj, DkGpuAddr setAddr, uint32_t numDescriptors) ### `dkCmdBufBindRenderTargets` Binds color and depth targets for rendering. ### Method void ### Endpoint dkCmdBufBindRenderTargets(DkCmdBuf obj, DkImageView const* const colorTargets[], uint32_t numColorTargets, DkImageView const* depthTarget) ``` -------------------------------- ### Shader and Render Target Setup Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Configure shaders, uniform buffers, storage buffers, textures, images, and render targets for rendering operations. Ensure correct resource binding and descriptor set configurations. ```c void dkCmdBufBindShaders(DkCmdBuf obj, uint32_t stageMask, DkShader const* const shaders[], uint32_t numShaders); ``` ```c void dkCmdBufBindUniformBuffers(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkBufExtents const buffers[], uint32_t numBuffers); ``` ```c void dkCmdBufBindStorageBuffers(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkBufExtents const buffers[], uint32_t numBuffers); ``` ```c void dkCmdBufBindTextures(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkResHandle const handles[], uint32_t numHandles); ``` ```c void dkCmdBufBindImages(DkCmdBuf obj, DkStage stage, uint32_t firstId, DkResHandle const handles[], uint32_t numHandles); ``` ```c void dkCmdBufBindImageDescriptorSet(DkCmdBuf obj, DkGpuAddr setAddr, uint32_t numDescriptors); ``` ```c void dkCmdBufBindSamplerDescriptorSet(DkCmdBuf obj, DkGpuAddr setAddr, uint32_t numDescriptors); ``` ```c void dkCmdBufBindRenderTargets(DkCmdBuf obj, DkImageView const* const colorTargets[], uint32_t numColorTargets, DkImageView const* depthTarget); ``` -------------------------------- ### Initialize deko3d Sampler and Descriptor (C++) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md In C++, samplers can be configured using setter methods, and sampler descriptors are initialized subsequently. This example sets linear filtering for both minification and magnification. ```cpp // Initialize a sampler dk::Sampler sampler; sampler.setFilter(DkMipFilter_Linear, DkMipFilter_Linear); // Initialize a sample descriptor using our sampler dk::SamplerDescriptor descr; descr.initialize(sampler); ``` -------------------------------- ### Create and Record Command Buffer (C API) Source: https://context7.com/devkitpro/deko3d/llms.txt Creates a command buffer and records GPU commands using the C API. Add backing memory, record commands like clearing color, and finish recording to get a command list. The command buffer can be cleared for reuse. ```c // C API - Create command buffer and record commands DkCmdBufMaker cmdBufMaker; dkCmdBufMakerDefaults(&cmdBufMaker, device); DkCmdBuf cmdBuf = dkCmdBufCreate(&cmdBufMaker); // Add backing memory (must be aligned to DK_CMDMEM_ALIGNMENT) dkCmdBufAddMemory(cmdBuf, cmdMemBlock, 0, 0x10000); // Record clear command float clearColor[] = { 0.2f, 0.3f, 0.8f, 1.0f }; dkCmdBufClearColor(cmdBuf, 0, DkColorMask_RGBA, clearColor); // Finish recording and get command list handle DkCmdList cmdList = dkCmdBufFinishList(cmdBuf); // Clear the command buffer for reuse dkCmdBufClear(cmdBuf); dkCmdBufDestroy(cmdBuf); ``` -------------------------------- ### Create deko3d Device with Unique Pointer (C++) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md This C++ example utilizes `dk::UniqueDevice` for automatic handle management, ensuring the device is destroyed when the object goes out of scope. ```cpp // Create the device // dk::UniqueDevice contains a destructor which will automatically call destroy() dk::UniqueDevice device = dk::DeviceMaker{} .setFlags(DkDeviceFlags_OriginLowerLeft) .create(); ``` -------------------------------- ### Set Viewport Configuration Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Configure viewport swizzles and viewports for rendering. The `firstId` parameter specifies the starting index for the provided arrays. ```c struct DkViewportSwizzle; struct DkViewport; void dkCmdBufSetViewportSwizzles(DkCmdBuf obj, uint32_t firstId, DkViewportSwizzle const swizzles[], uint32_t numSwizzles); void dkCmdBufSetViewports(DkCmdBuf obj, uint32_t firstId, DkViewport const viewports[], uint32_t numViewports); ``` -------------------------------- ### Bind Blend and Color Write States Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Binds blend states and the color write state to the command buffer. Multiple blend states can be bound starting from a specific ID. ```c struct DkBlendState; struct DkColorWriteState; void dkCmdBufBindBlendStates(DkCmdBuf obj, uint32_t firstId, DkBlendState const states[], uint32_t numStates); void dkCmdBufBindColorWriteState(DkCmdBuf obj, DkColorWriteState const* state); ``` -------------------------------- ### Create Swapchain and Render Loop Source: https://context7.com/devkitpro/deko3d/llms.txt Creates swapchains for presenting rendered images to the display and manages the render loop. Initializes framebuffer images, creates the swapchain, and handles image acquisition, rendering, and presentation. ```cpp // C++ API - Create swapchain and render loop // Create framebuffer images static const int NumFramebuffers = 2; dk::Image framebuffers[NumFramebuffers]; DkImage const* fbPointers[NumFramebuffers]; for (int i = 0; i < NumFramebuffers; i++) { framebuffers[i].initialize(fbLayout, fbMemBlock, i * fbSize); fbPointers[i] = &framebuffers[i]; } // Create swapchain dk::UniqueSwapchain swapchain = dk::SwapchainMaker{device, nwindowGetDefault(), fbPointers, NumFramebuffers} .create(); swapchain.setSwapInterval(1); // VSync // Render loop while (appletMainLoop()) { // Acquire next image int slot = queue.acquireImage(swapchain); // Record rendering commands for this frame dk::ImageView target{framebuffers[slot]}; cmdBuf.bindRenderTargets({ &target }); cmdBuf.clearColor(0, DkColorMask_RGBA, 0.0f, 0.0f, 0.0f, 1.0f); // ... more rendering ... DkCmdList cmds = cmdBuf.finishList(); queue.submitCommands(cmds); // Present the rendered image queue.presentImage(swapchain, slot); cmdBuf.clear(); } ``` -------------------------------- ### Initialize deko3d Shader (C++) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md The C++ wrapper allows for one-step shader initialization using `dk::ShaderMaker`. Pass the memory block and offset to the maker. ```cpp // Initialize the shader in one go dk::Shader shader; dk::ShaderMaker{codeMemBlock, codeOffset}.initialize(shader); ``` -------------------------------- ### Create deko3d Device (C++) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md This C++ code demonstrates creating a deko3d device using the wrapper's factory pattern. It allows for fluent setting of flags before creation. ```cpp // Create the device in one go // In the C++ wrapper, Maker objects follow the factory pattern dk::Device device = dk::DeviceMaker{} .setFlags(DkDeviceFlags_OriginLowerLeft) .create(); ``` -------------------------------- ### Initialize deko3d Sampler and Descriptor (C) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md This C code shows how to initialize a deko3d sampler with filter settings and then initialize a sampler descriptor using that sampler. ```c // Initialize a sampler DkSampler sampler; dkSamplerDefaults(&sampler); sampler.minFilter = DkMipFilter_Linear; sampler.magFilter = DkMipFilter_Linear; // Initialize a sample descriptor using our sampler DkSamplerDescriptor descr; dkSamplerDescriptorInitialize(&descr, &sampler); ``` -------------------------------- ### Create Queue with Custom Settings (C++ API) Source: https://context7.com/devkitpro/deko3d/llms.txt Initializes a GPU queue with custom flags, command memory size, and per-warp scratch memory. This C++ API offers a more streamlined approach to queue configuration. ```cpp // C++ API - Queue with custom settings dk::UniqueQueue queue = dk::QueueMaker{device} .setFlags(DkQueueFlags_Graphics | DkQueueFlags_Compute | DkQueueFlags_HighPrio) .setCommandMemorySize(0x20000) .setPerWarpScratchMemorySize(0x1000) .create(); queue.submitCommands(cmdList); queue.flush(); queue.waitIdle(); ``` -------------------------------- ### Initialize Multiple Shaders and Bind (C++ API) Source: https://context7.com/devkitpro/deko3d/llms.txt Initializes multiple shaders from a memory block and binds them to a command buffer for specified stages. Ensure the offsets for each shader are correctly calculated. ```cpp // C++ API - Initialize multiple shaders dk::Shader vertexShader, fragmentShader; // Load vertex shader at offset 0 dk::ShaderMaker{codeMemBlock, 0}.initialize(vertexShader); // Load fragment shader at offset after vertex shader dk::ShaderMaker{codeMemBlock, vertexShaderSize}.initialize(fragmentShader); // Bind shaders to command buffer DkShader const* shaders[] = { &vertexShader, &fragmentShader }; cmdBuf.bindShaders(DkStageFlag_Vertex | DkStageFlag_Fragment, shaders); ``` -------------------------------- ### Load and Initialize Shader (C API) Source: https://context7.com/devkitpro/deko3d/llms.txt Loads a shader from a DKSH file into memory and then initializes a DkShader object. It's crucial to verify the shader's validity and stage after initialization. ```c // C API - Load and initialize a shader // First, load DKSH file into code memory block FILE* f = fopen("romfs:/shaders/vertex.dksh", "rb"); fread(dkMemBlockGetCpuAddr(codeMemBlock), 1, shaderSize, f); fclose(f); // Initialize shader from loaded code DkShaderMaker shaderMaker; dkShaderMakerDefaults(&shaderMaker, codeMemBlock, 0); DkShader vertexShader; dkShaderInitialize(&vertexShader, &shaderMaker); // Verify shader is valid and check stage if (dkShaderIsValid(&vertexShader)) { DkStage stage = dkShaderGetStage(&vertexShader); // stage == DkStage_Vertex } ``` -------------------------------- ### Shader Structure and Initialization Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Defines the DkShader structure and its initialization function. Use dkShaderInitialize to set up a shader object with provided metadata. ```c struct DkShaderMaker; void dkShaderInitialize(DkShader* obj, DkShaderMaker const* maker); ``` -------------------------------- ### Create Image Views and Bind Render Targets (C++ API) Source: https://context7.com/devkitpro/deko3d/llms.txt Creates image views for color and depth images, optionally customizing their format, mip levels, and layers. These views are then bound as render targets, and the viewport and scissor rectangles are set to match the target dimensions. ```cpp // C++ API - Create views and bind render targets dk::Image colorImage, depthImage; // ... initialize images ... // Create views for the images dk::ImageView colorView{colorImage}; dk::ImageView depthView{depthImage}; // Optionally customize the view colorView .setFormat(DkImageFormat_RGBA8_Unorm) // explicit format .setMipLevels(0, 1) // mip level 0 only .setLayers(0, 1); // layer 0 only // Bind as render targets DkImageView const* colorTargets[] = { &colorView }; cmdBuf.bindRenderTargets(colorTargets, &depthView); // Set viewport to match render target size DkViewport viewport = { 0.0f, 0.0f, 1280.0f, 720.0f, 0.0f, 1.0f }; cmdBuf.setViewports(0, { viewport }); DkScissor scissor = { 0, 0, 1280, 720 }; cmdBuf.setScissors(0, { scissor }); ``` -------------------------------- ### Shader Initialization and Information Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Functions for initializing, validating, and retrieving information about DkShader objects. ```APIDOC ## DkShader Object ### Description Shaders are programs that run on the GPU, processing different stages of the graphics pipeline. In deko3d, they are represented by the opaque `DkShader` object, which contains metadata for GPU execution setup. Deko3d accepts shaders in the DKSH format, bundling GPU machine code with metadata. > **Note**: Deko3d exclusively supports native GPU code (SASS for Shader Model 5.3). Runtime compilation languages like GLSL or SPIR-V are not supported. Users must target Maxwell 2nd gen ISA (SM53) if runtime JIT compilation is needed. ### Fields - `codeMem` (memory block) - Memory block where shader code resides. - `control` (pointer) - Optional pointer to the DKSH control section. - `codeOffset` (integer) - Offset into the memory block where shader code resides; must be a multiple of `DK_SHADER_CODE_ALIGNMENT`. - `programId` (integer) - Index of the shader program to initialize; defaults to 0. > **Note**: While the DKSH format supports multiple programs, the current deko3d compiler does not. It is advised to leave `programId` at its default value of 0. ### Functions #### `dkShaderInitialize` - **Description**: Initializes a `DkShader` object with the provided `DkShaderMaker` configuration. - **Method**: `void` - **Parameters**: - `obj` (*DkShader*) - Pointer to the `DkShader` object to initialize. - `maker` (*DkShaderMaker const*) - Pointer to the `DkShaderMaker` containing shader configuration. #### `dkShaderIsValid` - **Description**: Checks if a `DkShader` object holds a valid shader. - **Method**: `bool` - **Parameters**: - `obj` (*DkShader const*) - Pointer to the `DkShader` object to check. - **Returns**: `true` if the shader is valid, `false` otherwise. #### `dkShaderGetStage` - **Description**: Retrieves the stage at which the shader executes. - **Method**: `DkStage` - **Parameters**: - `obj` (*DkShader const*) - Pointer to the `DkShader` object. - **Returns**: The `DkStage` of the shader (e.g., vertex, fragment). ``` -------------------------------- ### Create Graphics+Compute Queue (C API) Source: https://context7.com/devkitpro/deko3d/llms.txt Creates a GPU queue for graphics and compute workloads with medium priority. Ensure to check for errors after submission and flush commands for execution. The queue must be destroyed when no longer needed. ```c // C API - Create a graphics+compute queue DkQueueMaker queueMaker; dkQueueMakerDefaults(&queueMaker, device); queueMaker.flags = DkQueueFlags_Graphics | DkQueueFlags_Compute | DkQueueFlags_MediumPrio; queueMaker.commandMemorySize = DK_QUEUE_MIN_CMDMEM_SIZE; DkQueue queue = dkQueueCreate(&queueMaker); // Submit command list to queue dkQueueSubmitCommands(queue, cmdList); // Flush to start GPU execution dkQueueFlush(queue); // Wait for all submitted work to complete dkQueueWaitIdle(queue); // Check for GPU errors if (dkQueueIsInErrorState(queue)) { // Handle error - queue is no longer usable } dkQueueDestroy(queue); ``` -------------------------------- ### Initialize deko3d Variable Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Use `dkVariableInitialize` to set up a deko3d variable, linking it to a specific memory block and offset. ```c void dkVariableInitialize(DkVariable* obj, DkMemBlock mem, uint32_t offset); ``` -------------------------------- ### Create and Bind Texture Sampler and Descriptors Source: https://context7.com/devkitpro/deko3d/llms.txt Configures texture filtering and wrap modes, initializes image and sampler descriptors, and binds them for GPU access. Texture handles are created and bound to the fragment shader stage. ```cpp // C++ API - Create sampler with linear filtering dk::Sampler sampler; sampler .setFilter(DkFilter_Linear, DkFilter_Linear, DkMipFilter_Linear) .setWrapMode(DkWrapMode_Repeat, DkWrapMode_Repeat, DkWrapMode_Repeat) .setLodClamp(0.0f, 10.0f) .setMaxAnisotropy(8.0f); // Initialize descriptors in GPU memory dk::ImageDescriptor imageDescriptor; dk::SamplerDescriptor samplerDescriptor; dk::ImageView texView{textureImage}; imageDescriptor.initialize(texView); samplerDescriptor.initialize(sampler); // Copy descriptors to descriptor memory block memcpy((uint8_t*)descriptorMemBlock.getCpuAddr() + imageDescOffset, &imageDescriptor, sizeof(imageDescriptor)); memcpy((uint8_t*)descriptorMemBlock.getCpuAddr() + samplerDescOffset, &samplerDescriptor, sizeof(samplerDescriptor)); // Bind descriptor sets DkGpuAddr descriptorAddr = descriptorMemBlock.getGpuAddr(); cmdBuf.bindImageDescriptorSet(descriptorAddr + imageDescOffset, 1); cmdBuf.bindSamplerDescriptorSet(descriptorAddr + samplerDescOffset, 1); // Bind texture to shader stage (combines image and sampler IDs) DkResHandle texHandle = dkMakeTextureHandle(0, 0); // imageId=0, samplerId=0 cmdBuf.bindTextures(DkStage_Fragment, 0, { texHandle }); ``` -------------------------------- ### Command Capture and Replay Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Capture raw GPU commands into a user-provided buffer and replay them with zero computational overhead. This can optimize rendering of complex scenes by avoiding repeated CPU computations. ```APIDOC ## Command Capture and Replay API ### Description This API allows for capturing GPU commands into a buffer and replaying them later. This is useful for optimizing the rendering of complex scenes by reducing CPU overhead. ### Functions - `dkCmdBufBeginCaptureCmds(DkCmdBuf obj, uint32_t* storage, uint32_t max_words)`: Begins capturing commands into the provided storage buffer. - `dkCmdBufEndCaptureCmds(DkCmdBuf obj)`: Ends capture mode and returns the number of words captured. - `dkCmdBufReplayCmds(DkCmdBuf obj, const uint32_t* words, uint32_t num_words)`: Replays captured commands from the provided buffer. ### Limitations Capture mode has limitations, including: - Running out of storage results in an error. - Disallowed operations: Command buffer management (`dkCmdBufAddMemory`, `dkCmdBufFinishList`, `dkCmdBufClear`), compute pipeline commands, fence commands, indirect draw/dispatch commands, `dkCmdBufBarrier` with `DkBarrier_Full`, and `dkCmdBufCallList`. ### Warning `dkCmdBufReplayCmds` allows injecting arbitrary GPU commands. Exercise caution. Captured commands may not be compatible across different deko3d versions. ``` -------------------------------- ### Create and Record Command Buffer (C++ API) Source: https://context7.com/devkitpro/deko3d/llms.txt Creates and records commands to a command buffer using the C++ API's fluent interface. Supports methods for clearing color and depth-stencil buffers. The `finishList` method returns a command list. ```cpp // C++ API - Command buffer with fluent interface dk::UniqueCmdBuf cmdBuf = dk::CmdBufMaker{device}.create(); cmdBuf.addMemory(cmdMemBlock, 0, cmdMemBlock.getSize()); // Record render commands cmdBuf.clearColor(0, DkColorMask_RGBA, 0.1f, 0.1f, 0.1f, 1.0f); cmdBuf.clearDepthStencil(true, 1.0f, 0xFF, 0); DkCmdList cmdList = cmdBuf.finishList(); ``` -------------------------------- ### Configure Vertex Buffer and Attributes Source: https://context7.com/devkitpro/deko3d/llms.txt Sets up vertex attribute formats, buffer strides, and divisors for instanced rendering. This configures how vertex data is interpreted by the GPU. ```cpp // C++ API - Set up vertex attributes and buffers // Define vertex format: position (3 floats) + color (4 floats) static const DkVtxAttribState attribState[] = { { .bufferId = 0, .offset = 0, .size = DkVtxAttribSize_3x32, .type = DkVtxAttribType_Float }, { .bufferId = 0, .offset = 12, .size = DkVtxAttribSize_4x32, .type = DkVtxAttribType_Float }, }; static const DkVtxBufferState bufferState[] = { { .stride = 28, .divisor = 0 }, // 28 bytes per vertex, no instancing }; cmdBuf.bindVtxAttribState(attribState); cmdBuf.bindVtxBufferState(bufferState); // Bind vertex buffer DkGpuAddr vtxAddr = vertexMemBlock.getGpuAddr(); uint32_t vtxSize = vertexCount * 28; cmdBuf.bindVtxBuffer(0, vtxAddr, vtxSize); // Optional: bind index buffer for indexed drawing cmdBuf.bindIdxBuffer(DkIdxFormat_Uint16, indexMemBlock.getGpuAddr()); ``` -------------------------------- ### Sample Processing Commands Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Commands for configuring multisample operations, alpha test, depth bounds test, and late depth/stencil tests. ```APIDOC ## Sample processing ### Description Configures various aspects of sample processing including sample mask, alpha to coverage, coverage modulation, alpha test, depth bounds test, late depth and stencil test, and coverage to color operations. ### Method Various (functions are bound to a command buffer) ### Endpoint N/A (These are function calls within a command buffer) ### Parameters #### `dkCmdBufBindColorState` - **obj** (DkCmdBuf) - The command buffer object. - **state** (DkColorState const*) - Pointer to the color state structure. #### `dkCmdBufBindDepthStencilState` - **obj** (DkCmdBuf) - The command buffer object. - **state** (DkDepthStencilState const*) - Pointer to the depth-stencil state structure. #### `dkCmdBufSetSampleMask` - **obj** (DkCmdBuf) - The command buffer object. - **mask** (uint32_t) - The sample mask value. #### `dkCmdBufSetCoverageModulationTable` - **obj** (DkCmdBuf) - The command buffer object. - **table** (float const[16]) - Pointer to the coverage modulation table. #### `dkCmdBufSetAlphaRef` - **obj** (DkCmdBuf) - The command buffer object. - **ref** (float) - The alpha reference value. #### `dkCmdBufSetDepthBounds` - **obj** (DkCmdBuf) - The command buffer object. - **enable** (bool) - Whether to enable depth bounds testing. - **near** (float) - The near depth bound. - **far** (float) - The far depth bound. #### `dkCmdBufSetStencil` - **obj** (DkCmdBuf) - The command buffer object. - **face** (DkFace) - The face to apply the stencil test to (front, back, or front and back). - **mask** (uint8_t) - The stencil mask. - **funcRef** (uint8_t) - The stencil function reference value. - **funcMask** (uint8_t) - The stencil function mask. ### Request Example ```c // Example for setting sample mask dkCmdBufSetSampleMask(cmdBuf, 0xFFFFFFFF); // Example for setting alpha reference dkCmdBufSetAlphaRef(cmdBuf, 0.5f); // Example for setting depth bounds dkCmdBufSetDepthBounds(cmdBuf, true, 0.1f, 0.9f); // Example for setting stencil test dkCmdBufSetStencil(cmdBuf, DK_FACE_FRONT, 0xFF, 0x00, 0xFF); ``` ### Response N/A (These commands modify the command buffer state) ``` -------------------------------- ### Initialize deko3d Shader (C) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md This C code initializes a deko3d shader object using a `DkShaderMaker`. Ensure `codeMemBlock` and `codeOffset` are correctly provided. ```c // Describe the shader we're about to initialize DkShaderMaker maker; dkShaderMakerDefaults(&maker, codeMemBlock, codeOffset); // Initialize the shader DkShader shader; dkShaderInitialize(&shader, &maker); ``` -------------------------------- ### Create deko3d Device (C) Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Use this C code to create a deko3d device handle. Ensure to set the desired flags before creation. ```c // Describe the device we're about to make DkDeviceMaker maker; dkDeviceMakerDefaults(&maker); maker.flags = DkDeviceFlags_OriginLowerLeft; // Create the device DkDevice device = dkDeviceCreate(&maker); ``` -------------------------------- ### Create GPU Device (C++ API) Source: https://context7.com/devkitpro/deko3d/llms.txt Creates a GPU device using the C++ API's builder pattern. The `dk::UniqueDevice` ensures automatic cleanup when the object goes out of scope. ```cpp // C++ API - Create device using builder pattern with automatic cleanup dk::UniqueDevice device = dk::DeviceMaker{} .setFlags(DkDeviceFlags_DepthZeroToOne | DkDeviceFlags_OriginUpperLeft) .create(); // Device automatically destroyed when UniqueDevice goes out of scope ``` -------------------------------- ### Create 2D Render Target Image Layout (C API) Source: https://context7.com/devkitpro/deko3d/llms.txt Defines the properties for a 2D image, specifying format, usage flags, dimensions, and mip levels. After initialization, retrieve the required size and alignment for memory allocation. ```c // C API - Create a 2D render target image DkImageLayoutMaker layoutMaker; dkImageLayoutMakerDefaults(&layoutMaker, device); layoutMaker.type = DkImageType_2D; layoutMaker.format = DkImageFormat_RGBA8_Unorm; layoutMaker.flags = DkImageFlags_UsageRender | DkImageFlags_HwCompression; layoutMaker.dimensions[0] = 1280; // width layoutMaker.dimensions[1] = 720; // height layoutMaker.dimensions[2] = 0; // depth (unused for 2D) layoutMaker.mipLevels = 1; DkImageLayout layout; dkImageLayoutInitialize(&layout, &layoutMaker); // Get required memory size and alignment uint64_t imageSize = dkImageLayoutGetSize(&layout); uint32_t imageAlign = dkImageLayoutGetAlignment(&layout); // Initialize image in memory block DkImage image; dkImageInitialize(&image, &layout, imageMemBlock, 0); DkGpuAddr imageAddr = dkImageGetGpuAddr(&image); ``` -------------------------------- ### Create GPU Device (C API) Source: https://context7.com/devkitpro/deko3d/llms.txt Creates the root GPU device object using the C API. Configure device flags for depth and origin orientation. The device is the parent for most other deko3d objects. ```c // C API - Create a device with default settings DkDeviceMaker maker; dkDeviceMakerDefaults(&maker); maker.flags = DkDeviceFlags_DepthZeroToOne | DkDeviceFlags_OriginUpperLeft; DkDevice device = dkDeviceCreate(&maker); // Use the device... // Cleanup dkDeviceDestroy(device); ``` -------------------------------- ### Import External GPU Synchronization Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Use `dkFenceImport` to synchronize deko3d with external engines via Host1x syncpoints. The `id` and `value` parameters are typically managed by the driver. ```c void dkFenceImport(DkFence* obj, uint32_t id, uint32_t value); ``` -------------------------------- ### Buffer to Image and Image to Buffer Copies Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Handles copying data between buffers and images in both directions. Requires specifying source/destination views, rectangles, and flags. ```c void dkCmdBufCopyBufferToImage(DkCmdBuf obj, DkCopyBuf const* src, DkImageView const* dstView, DkImageRect const* dstRect, uint32_t flags); void dkCmdBufCopyImageToBuffer(DkCmdBuf obj, DkImageView const* srcView, DkImageRect const* srcRect, DkCopyBuf const* dst, uint32_t flags); ``` -------------------------------- ### Queue Creation and Management Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Functions for creating, destroying, and checking the status of queues. ```APIDOC ## Queue Creation and Management ### Description Functions for creating, destroying, and checking the status of queues. ### `dkQueueMakerDefaults` #### Description Initializes a `DkQueueMaker` struct with default values. #### Method `void dkQueueMakerDefaults(DkQueueMaker* maker, DkDevice device)` #### Parameters - **maker** (DkQueueMaker*) - Output - Pointer to the `DkQueueMaker` struct to initialize. - **device** (DkDevice) - The parent device. ### `dkQueueCreate` #### Description Creates a new queue with the specified properties. #### Method `DkQueue dkQueueCreate(DkQueueMaker const* maker)` #### Parameters - **maker** (DkQueueMaker const*) - Input - Pointer to the `DkQueueMaker` struct defining the queue properties. #### Request Body ```json { "maker": { "device": "DkDevice", "flags": "uint32_t", "commandMemorySize": "uint32_t", "flushThreshold": "uint32_t", "perWarpScratchMemorySize": "uint32_t", "maxConcurrentComputeJobs": "uint32_t" } } ``` ### `dkQueueDestroy` #### Description Destroys a queue and releases its resources. #### Method `void dkQueueDestroy(DkQueue obj)` #### Parameters - **obj** (DkQueue) - The queue object to destroy. ### `dkQueueIsInErrorState` #### Description Checks if the queue is in an error state. #### Method `bool dkQueueIsInErrorState(DkQueue obj)` #### Parameters - **obj** (DkQueue) - The queue object to check. ### `DkQueueMaker` Struct Fields #### Description Defines the properties for creating a queue. #### Fields - **device** (DkDevice) - Required - Parent device. - **flags** (uint32_t) - Optional - Queue creation flags (e.g., `DkQueueFlags_Graphics`, `DkQueueFlags_Compute`). Defaults to `Graphics | Compute | MediumPrio | EnableZcull`. - **commandMemorySize** (uint32_t) - Optional - Internal command memory size in bytes. Defaults to `DK_QUEUE_MIN_CMDMEM_SIZE`. Must be at least `DK_QUEUE_MIN_CMDMEM_SIZE`. - **flushThreshold** (uint32_t) - Optional - Threshold for flushing internal command memory. Defaults to `DK_QUEUE_MIN_CMDMEM_SIZE/8`. Must be at least `DK_MEMBLOCK_ALIGNMENT` and not more than `commandMemorySize`. - **perWarpScratchMemorySize** (uint32_t) - Optional - Scratch memory allocated to each warp in bytes. Defaults to `4*DK_PER_WARP_SCRATCH_MEM_ALIGNMENT`. Must be a multiple of `DK_PER_WARP_SCRATCH_MEM_ALIGNMENT` (can be 0 if scratch memory is not needed). - **maxConcurrentComputeJobs** (uint32_t) - Optional - For compute-capable queues: maximum number of concurrent compute dispatch jobs. Defaults to `DK_DEFAULT_MAX_COMPUTE_CONCURRENT_JOBS`. Must be at least 1, ignored otherwise. ### `DkQueueFlags` #### Description Queue creation flags. #### Flags - **`DkQueueFlags_Graphics`**: The queue can execute graphics commands. Default: Yes. - **`DkQueueFlags_Compute`**: The queue can execute compute commands. Default: Yes. - **`DkQueueFlags_MediumPrio`**: The queue has medium priority. Default: Yes. - **`DkQueueFlags_HighPrio`**: The queue has high priority. - **`DkQueueFlags_LowPrio`**: The queue has low priority. - **`DkQueueFlags_EnableZcull`**: Zcull is enabled. Default: Yes. - **`DkQueueFlags_DisableZcull`**: Zcull is disabled. ``` -------------------------------- ### Wait on GPU Fence Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Use `dkFenceWait` to block the CPU or GPU until a fence is signaled. Initialize fences to zero if they might be waited on before being signaled. ```c struct DkFence; DkResult dkFenceWait(DkFence* obj, int64_t timeout_ns); ``` -------------------------------- ### Full Barrier Synchronization Source: https://context7.com/devkitpro/deko3d/llms.txt Completes all previous GPU work and disables prefetching. Use for comprehensive synchronization. ```cpp cmdBuf.barrier(DkBarrier_Full, DkInvalidateFlags_Image | DkInvalidateFlags_Shader); ``` -------------------------------- ### Bind Color and Depth-Stencil States Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Binds the color and depth-stencil states to the command buffer. Ensure the state objects are properly initialized before binding. ```c struct DkColorState; struct DkDepthStencilState; void dkCmdBufBindColorState(DkCmdBuf obj, DkColorState const* state); void dkCmdBufBindDepthStencilState(DkCmdBuf obj, DkDepthStencilState const* state); ``` -------------------------------- ### Create Depth Buffer Image Layout (C++ API) Source: https://context7.com/devkitpro/deko3d/llms.txt Initializes a depth buffer image layout with specified dimensions and format. This C++ API provides a fluent interface for setting image properties. ```cpp // C++ API - Create depth buffer dk::ImageLayout depthLayout; dk::ImageLayoutMaker{device} .setType(DkImageType_2D) .setFormat(DkImageFormat_Z24S8) .setFlags(DkImageFlags_UsageRender | DkImageFlags_HwCompression) .setDimensions(1280, 720) .initialize(depthLayout); dk::Image depthImage; depthImage.initialize(depthLayout, imageMemBlock, colorImageSize); ``` -------------------------------- ### Capture GPU Commands with deko3d Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Use these functions to capture raw GPU commands into a user-provided buffer for later replay. This can reduce CPU overhead for complex scenes. Ensure sufficient storage is allocated, as running out of space will cause an error. ```c void dkCmdBufBeginCaptureCmds(DkCmdBuf obj, uint32_t* storage, uint32_t max_words); uint32_t dkCmdBufEndCaptureCmds(DkCmdBuf obj); void dkCmdBufReplayCmds(DkCmdBuf obj, const uint32_t* words, uint32_t num_words); ``` -------------------------------- ### Synchronization Primitives Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Use these functions to manage synchronization between command buffers using fences and variables. Fences provide a signaling mechanism, while variables allow for conditional execution based on GPU state. ```c void dkCmdBufWaitFence(DkCmdBuf obj, DkFence* fence); void dkCmdBufSignalFence(DkCmdBuf obj, DkFence* fence, bool flush); ``` ```c void dkCmdBufWaitVariable(DkCmdBuf obj, DkVariable const* var, DkVarCompareOp op, uint32_t value); void dkCmdBufSignalVariable(DkCmdBuf obj, DkVariable const* var, DkVarOp op, uint32_t value, DkPipelinePos pos); ``` ```c void dkCmdBufBarrier(DkCmdBuf obj, DkBarrier mode, uint32_t invalidateFlags); ``` -------------------------------- ### Compute Pipeline Commands Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Commands for dispatching compute shaders. ```APIDOC ## The compute pipeline ### Description Commands for dispatching compute work. ### Method Various (functions are bound to a command buffer) ### Endpoint N/A (These are function calls within a command buffer) ### Parameters #### `dkCmdBufDispatchCompute` - **obj** (DkCmdBuf) - The command buffer object. - **numGroupsX** (uint32_t) - The number of workgroups to dispatch in the X dimension. - **numGroupsY** (uint32_t) - The number of workgroups to dispatch in the Y dimension. - **numGroupsZ** (uint32_t) - The number of workgroups to dispatch in the Z dimension. #### `dkCmdBufDispatchComputeIndirect` - **obj** (DkCmdBuf) - The command buffer object. - **indirect** (DkGpuAddr) - GPU address of the indirect dispatch buffer. ### Request Example ```c // Example for dispatching compute work dkCmdBufDispatchCompute(cmdBuf, 64, 1, 1); // Example for indirect compute dispatch dkCmdBufDispatchComputeIndirect(cmdBuf, indirectBufferGpuAddress); ``` ### Response N/A (These commands modify the command buffer state) ``` -------------------------------- ### Vertex Shader Pipeline Configuration Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Functions for configuring tessellation patch size and tessellation levels. ```APIDOC ## Vertex Shader Pipeline Configuration ### Description Functions to configure tessellation parameters for the vertex shader pipeline. ### Method - `dkCmdBufSetPatchSize` - `dkCmdBufSetTessOuterLevels` - `dkCmdBufSetTessInnerLevels` ### Endpoint N/A (These are function calls within a command buffer) ### Parameters #### `dkCmdBufSetPatchSize` - **obj** (DkCmdBuf) - The command buffer object. - **size** (uint32_t) - The patch size for tessellation. #### `dkCmdBufSetTessOuterLevels` - **obj** (DkCmdBuf) - The command buffer object. - **level0** (float) - The first outer tessellation level. - **level1** (float) - The second outer tessellation level. - **level2** (float) - The third outer tessellation level. - **level3** (float) - The fourth outer tessellation level. #### `dkCmdBufSetTessInnerLevels` - **obj** (DkCmdBuf) - The command buffer object. - **level0** (float) - The first inner tessellation level. - **level1** (float) - The second inner tessellation level. ### Request Example ```c // Example for setting tessellation levels dkCmdBufSetPatchSize(cmdBuffer, 3); dkCmdBufSetTessOuterLevels(cmdBuffer, 1.0f, 1.0f, 1.0f, 1.0f); dkCmdBufSetTessInnerLevels(cmdBuffer, 1.0f, 1.0f); ``` ### Response N/A (These functions modify the command buffer state) ``` -------------------------------- ### DkDevice Object and Creation Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Defines the DkDeviceMaker structure for device creation and provides functions to create, destroy, and query the device. ```APIDOC ## DkDevice Object `DkDevice` is the root object from which most other deko3d objects can be traced back. It represents the GPU device with a private virtual GPU address space, and provides optional mechanisms for customizing the error handling or memory allocation behavior. ### DkDeviceMaker Structure This structure is used to configure the device upon creation. #### Fields - **userData** (void*) - Optional - User specified data to be passed to the callbacks. - **cbError** (DkErrorFunc) - Optional - Callback for error handling. - **cbAlloc** (DkAllocFunc) - Optional - Callback used when deko3d needs to allocate memory. - **cbFree** (DkFreeFunc) - Optional - Callback used when deko3d needs to free allocated memory. - **flags** (uint32_t) - Device creation flags. ### Device Creation and Management Functions - **dkDeviceMakerDefaults**: Initializes a `DkDeviceMaker` structure with default values. - **dkDeviceCreate**: Creates a new `DkDevice` object based on the provided `DkDeviceMaker` configuration. - **dkDeviceDestroy**: Destroys an existing `DkDevice` object. - **dkDeviceGetCurrentTimestamp**: Queries the current GPU tick without queuing a command buffer. - **dkDeviceGetCurrentTimestampInNs**: Queries the current GPU tick in nanoseconds without queuing a command buffer. ``` -------------------------------- ### Blending, Logical Operations, and Write Masks Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Commands for configuring blend states, color write states, and blend constants. ```APIDOC ## Blending, Logical Operations, and Write Masks ### Description Commands for binding blend states, color write states, and setting blend constants. ### Method Various (functions are bound to a command buffer) ### Endpoint N/A (These are function calls within a command buffer) ### Parameters #### `dkCmdBufBindColorState` - **obj** (DkCmdBuf) - The command buffer object. - **state** (DkColorState const*) - Pointer to the color state structure. #### `dkCmdBufBindDepthStencilState` - **obj** (DkCmdBuf) - The command buffer object. - **state** (DkDepthStencilState const*) - Pointer to the depth-stencil state structure. #### `dkCmdBufBindBlendStates` - **obj** (DkCmdBuf) - The command buffer object. - **firstId** (uint32_t) - The starting index for binding blend states. - **states** (DkBlendState const[]) - Array of blend state structures. - **numStates** (uint32_t) - The number of blend states to bind. #### `dkCmdBufBindColorWriteState` - **obj** (DkCmdBuf) - The command buffer object. - **state** (DkColorWriteState const*) - Pointer to the color write state structure. #### `dkCmdBufSetBlendConst` - **obj** (DkCmdBuf) - The command buffer object. - **red** (float) - The red component of the blend constant. - **green** (float) - The green component of the blend constant. - **blue** (float) - The blue component of the blend constant. - **alpha** (float) - The alpha component of the blend constant. ### Request Example ```c // Example for binding blend states DkBlendState blendStates[1]; // Initialize blendStates[0] here... dkCmdBufBindBlendStates(cmdBuf, 0, blendStates, 1); // Example for setting blend constant dkCmdBufSetBlendConst(cmdBuf, 0.5f, 0.5f, 0.5f, 0.5f); ``` ### Response N/A (These commands modify the command buffer state) ``` -------------------------------- ### Barriers and Synchronization Source: https://github.com/devkitpro/deko3d/blob/master/Primer.md Functions for managing barriers and synchronization primitives within command buffers. ```APIDOC ## Barriers and Synchronization ### `dkCmdBufWaitFence` Waits for a fence to be signaled. ### Method void ### Endpoint dkCmdBufWaitFence(DkCmdBuf obj, DkFence* fence) ### `dkCmdBufSignalFence` Signals a fence. ### Method void ### Endpoint dkCmdBufSignalFence(DkCmdBuf obj, DkFence* fence, bool flush) ### `dkCmdBufWaitVariable` Waits for a variable to meet a specific condition. ### Method void ### Endpoint dkCmdBufWaitVariable(DkCmdBuf obj, DkVariable const* var, DkVarCompareOp op, uint32_t value) ### `dkCmdBufSignalVariable` Signals a variable, potentially changing its value. ### Method void ### Endpoint dkCmdBufSignalVariable(DkCmdBuf obj, DkVariable const* var, DkVarOp op, uint32_t value, DkPipelinePos pos) ### `dkCmdBufBarrier` Inserts a barrier into the command buffer. ### Method void ### Endpoint dkCmdBufBarrier(DkCmdBuf obj, DkBarrier mode, uint32_t invalidateFlags) ```