DKGL2 sample codes

Texture.cpp 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #include <cstddef>
  2. #include "app.h"
  3. #include "util.h"
  4. class TextureDemo : public SampleApp
  5. {
  6. DKObject<DKWindow> window;
  7. DKObject<DKThread> renderThread;
  8. DKAtomicNumber32 runningRenderThread;
  9. public:
  10. DKObject<DKTexture> LoadTexture2D(DKCommandQueue* queue, DKData* data)
  11. {
  12. DKObject<DKImage> image = DKImage::Create(data);
  13. if (image)
  14. {
  15. DKGraphicsDevice* device = queue->Device();
  16. DKTextureDescriptor texDesc = {};
  17. texDesc.textureType = DKTexture::Type2D;
  18. texDesc.pixelFormat = DKPixelFormat::RGBA8Unorm;
  19. texDesc.width = image->Width();
  20. texDesc.height = image->Height();
  21. texDesc.depth = 1;
  22. texDesc.mipmapLevels = 1;
  23. texDesc.sampleCount = 1;
  24. texDesc.arrayLength = 1;
  25. texDesc.usage = DKTexture::UsageCopyDestination | DKTexture::UsageSampled;
  26. DKObject<DKTexture> tex = device->CreateTexture(texDesc);
  27. if (tex)
  28. {
  29. size_t bytesPerPixel = image->BytesPerPixel();
  30. uint32_t width = image->Width();
  31. uint32_t height = image->Height();
  32. size_t bufferLength = bytesPerPixel * width * height;
  33. DKObject<DKGpuBuffer> stagingBuffer = device->CreateBuffer(bufferLength, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  34. memcpy(stagingBuffer->Contents(), image->Contents(), bufferLength);
  35. stagingBuffer->Flush();
  36. DKObject<DKCommandBuffer> cb = queue->CreateCommandBuffer();
  37. DKObject<DKCopyCommandEncoder> encoder = cb->CreateCopyCommandEncoder();
  38. encoder->CopyFromBufferToTexture(stagingBuffer,
  39. { 0, uint32_t(bytesPerPixel * width), height },
  40. tex,
  41. { 0,0, 0,0,0 },
  42. { width,height,1 });
  43. encoder->EndEncoding();
  44. cb->Commit();
  45. DKLog("Texture created!");
  46. }
  47. }
  48. return nullptr;
  49. }
  50. void RenderThread(void)
  51. {
  52. DKObject<DKData> vertData = resourcePool.LoadResourceData("shaders/texture.vert.spv");
  53. DKObject<DKData> fragData = resourcePool.LoadResourceData("shaders/texture.frag.spv");
  54. DKShader vertShader(vertData);
  55. DKShader fragShader(fragData);
  56. DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
  57. DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
  58. // create texture
  59. DKObject<DKTexture> texture = LoadTexture2D(queue, resourcePool.LoadResourceData("textures/deathstar3.png"));
  60. DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
  61. DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
  62. DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
  63. DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
  64. DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
  65. DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
  66. for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
  67. {
  68. const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
  69. DKLog(" --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
  70. }
  71. struct Vertex
  72. {
  73. DKVector3 inPos;
  74. DKVector2 inUV;
  75. DKVector3 inNormal;
  76. };
  77. DKArray<Vertex> vertexData =
  78. {
  79. { { 1.0f, 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } },
  80. { { -1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } },
  81. { { -1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } },
  82. { { 1.0f, -1.0f, 0.0f }, { 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }
  83. };
  84. uint32_t vertexBufferSize = static_cast<uint32_t>(vertexData.Count()) * sizeof(Vertex);
  85. DKArray<uint32_t> indexData = { 0, 1, 2, 2, 3, 0 };
  86. uint32_t indexBufferSize = indexData.Count() * sizeof(uint32_t);
  87. DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  88. memcpy(vertexBuffer->Contents(), vertexData, vertexBufferSize);
  89. DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  90. memcpy(indexBuffer->Contents(), indexData, indexBufferSize);
  91. DKRenderPipelineDescriptor pipelineDescriptor;
  92. pipelineDescriptor.vertexFunction = vertShaderFunction;
  93. pipelineDescriptor.fragmentFunction = fragShaderFunction;
  94. pipelineDescriptor.colorAttachments.Resize(1);
  95. pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
  96. pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::Invalid; // no depth buffer
  97. pipelineDescriptor.vertexDescriptor.attributes = {
  98. { DKVertexFormat::Float3, 0, 0, 0 },
  99. { DKVertexFormat::Float2, offsetof(Vertex, inUV), 0, 1 },
  100. { DKVertexFormat::Float3, offsetof(Vertex, inNormal), 0, 2 },
  101. };
  102. pipelineDescriptor.vertexDescriptor.layouts = {
  103. { DKVertexStepRate::Vertex, sizeof(Vertex), 0 },
  104. };
  105. pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
  106. pipelineDescriptor.frontFace = DKFrontFace::CCW;
  107. pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
  108. pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
  109. pipelineDescriptor.cullMode = DKCullMode::None;
  110. pipelineDescriptor.rasterizationEnabled = true;
  111. DKPipelineReflection reflection;
  112. DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
  113. if (pipelineState)
  114. {
  115. PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
  116. }
  117. DKShaderBindingSetLayout layout;
  118. if (1)
  119. {
  120. DKShaderBinding binding = {
  121. 0,
  122. DKShader::DescriptorTypeUniformBuffer,
  123. 1,
  124. nullptr
  125. };
  126. layout.bindings.Add(binding);
  127. }
  128. DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
  129. if (bindSet)
  130. {
  131. struct
  132. {
  133. DKMatrix4 projectionMatrix;
  134. DKMatrix4 modelMatrix;
  135. DKMatrix4 viewMatrix;
  136. } ubo;
  137. DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(ubo), DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  138. if (uboBuffer)
  139. {
  140. ubo.projectionMatrix = DKMatrix4::identity;
  141. ubo.modelMatrix = DKMatrix4::identity;
  142. ubo.viewMatrix = DKMatrix4::identity;
  143. memcpy(uboBuffer->Contents(), &ubo, sizeof(ubo));
  144. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(ubo));
  145. }
  146. }
  147. DKTimer timer;
  148. timer.Reset();
  149. DKLog("Render thread begin");
  150. while (!runningRenderThread.CompareAndSet(0, 0))
  151. {
  152. DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
  153. double t = timer.Elapsed();
  154. t = (cos(t) + 1.0) * 0.5;
  155. rpd.colorAttachments.Value(0).clearColor = DKColor(t, 0.0, 0.0, 0.0);
  156. DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
  157. DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
  158. if (encoder)
  159. {
  160. encoder->SetRenderPipelineState(pipelineState);
  161. encoder->SetVertexBuffer(vertexBuffer, 0, 0);
  162. encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
  163. encoder->SetResources(0, bindSet);
  164. // draw scene!
  165. encoder->DrawIndexed(indexData.Count(), 1, 0, 0, 0);
  166. encoder->EndEncoding();
  167. buffer->Commit();
  168. swapChain->Present();
  169. }
  170. else
  171. {
  172. }
  173. DKThread::Sleep(0.01);
  174. }
  175. DKLog("RenderThread terminating...");
  176. }
  177. void OnInitialize(void) override
  178. {
  179. SampleApp::OnInitialize();
  180. DKLogD("%s", DKGL_FUNCTION_NAME);
  181. // create window
  182. window = DKWindow::Create("DefaultWindow");
  183. window->SetOrigin({ 0, 0 });
  184. window->Resize({ 320, 240 });
  185. window->Activate();
  186. window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
  187. {
  188. if (e.type == DKWindow::WindowEvent::WindowClosed)
  189. DKApplication::Instance()->Terminate(0);
  190. }), NULL, NULL);
  191. runningRenderThread = 1;
  192. renderThread = DKThread::Create(DKFunction(this, &TextureDemo::RenderThread)->Invocation());
  193. }
  194. void OnTerminate(void) override
  195. {
  196. DKLogD("%s", DKGL_FUNCTION_NAME);
  197. runningRenderThread = 0;
  198. renderThread->WaitTerminate();
  199. renderThread = NULL;
  200. window = NULL;
  201. SampleApp::OnTerminate();
  202. }
  203. };
  204. #ifdef _WIN32
  205. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  206. _In_opt_ HINSTANCE hPrevInstance,
  207. _In_ LPWSTR lpCmdLine,
  208. _In_ int nCmdShow)
  209. #else
  210. int main(int argc, const char * argv[])
  211. #endif
  212. {
  213. TextureDemo app;
  214. DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
  215. DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
  216. return app.Run();
  217. }