DKComputeShader 101

1. Get the ComputeCommandQueue from the Device

for sure

   1 DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
   2 DKObject<DKCommandQueue> computeQueue = device->CreateCommandQueue(DKCommandQueue::Compute);

2. Prepare the Gpu resources

1. Texture

Texture usage decription should has one of these flags.

   1 DKTexture::UsageStorage // Recommended
   2 DKTexture::UsageShaderWrite // Could be deprecated soon
   3 

Texutre Decriptor Example

   1 DKTextureDescriptor texDesc = {};
   2 texDesc.textureType = DKTexture::Type2D;
   3 texDesc.pixelFormat = DKPixelFormat::BGRA8Unorm;
   4 texDesc.width = w;
   5 texDesc.height = h;
   6 texDesc.depth = 1;
   7 texDesc.mipmapLevels = 1;
   8 texDesc.sampleCount = 1;
   9 texDesc.arrayLength = 1;
  10 texDesc.usage = DKTexture::UsageStorage                               // For Compute Shader
  11               | DKTexture::UsageSampled | DKTexture::UsageShaderRead; // For Fragment Shader
  12 textureTarget = device->CreateTexture(texDesc);

2. Shader

In DKGL2, we use same class for all type of shaders.

1. LoadResourceData From the resource path

   1 DKObject<DKData> computeShaderData = resourcePool.LoadResourceData("shaders/ComputeShader.comp.spv");

2. Create Function from data above step

   1 DKGraphicsDevice* device = queue->Device();
   2 DKShader shader(shaderData);
   3 DKObject<DKShaderModule> shaderModule = device->CreateShaderModule(&shader);
   4 DKObject<DKShaderFunction> shaderFunc = shaderModule->CreateFunction(shaderModule->FunctionNames().Value(0));

3. Prepare Uniformbuffers and BindSet

TODO

4. Prepare the Pipeline

Ususally compute shader need only setting for compute function. Set the shader function to the Pipeline Descriptor

   1 DKComputePipelineDescriptor computePipelineDescriptor;
   2 computePipelineDescriptor.computeFunction = csFunction; // csFunction as DKShaderFunction
   3 auto computePipeLine = device->CreateComputePipeline(computePipelineDescriptor);

5. CommandBuffer Encoding

   1 DKObject<DKCommandBuffer> computeCmdbuffer = computeQueue->CreateCommandBuffer();
   2 DKObject<DKComputeCommandEncoder> computeEncoder = computeCmdbuffer->CreateComputeCommandEncoder();
   3 if (computeEncoder)
   4 {
   5     if (computebindSet)
   6     {
   7         computebindSet->SetTexture(0, texture);
   8         computebindSet->SetTexture(1, targetTex);
   9     }
  10     computeEncoder->SetComputePipelineState(computePipeLine);
  11     computeEncoder->SetResources(0, computebindSet);
  12     computeEncoder->Dispatch(width / 16, height / 16, 1);
  13     computeEncoder->EndEncoding();
  14 }

DKComputeShader101 (last edited 2019-05-07 03:39:39 by Arkiny)