DKGL2 sample codes

Triangle.cpp 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. #include "app.h"
  2. DKString ShaderStageNames(uint32_t s)
  3. {
  4. DKArray<const char*> stages;
  5. if (s & (uint32_t)DKShaderStage::Vertex)
  6. stages.Add("Vertex");
  7. if (s & (uint32_t)DKShaderStage::TessellationControl)
  8. stages.Add("TessCtrl");
  9. if (s & (uint32_t)DKShaderStage::TessellationEvaluation)
  10. stages.Add("TessEval");
  11. if (s & (uint32_t)DKShaderStage::Geometry)
  12. stages.Add("Geometry");
  13. if (s & (uint32_t)DKShaderStage::Fragment)
  14. stages.Add("Fragment");
  15. if (s & (uint32_t)DKShaderStage::Compute)
  16. stages.Add("Compute");
  17. if (stages.IsEmpty())
  18. return "";
  19. DKString str = stages.Value(0);
  20. for (int i = 1; i < stages.Count(); ++i)
  21. str += DKString::Format(", %ls", stages.Value(i));
  22. return str;
  23. }
  24. const char* ShaderDataTypeStr(DKShaderDataType t)
  25. {
  26. switch (t) {
  27. case DKShaderDataType::Unknown: return "Unknown";
  28. case DKShaderDataType::None: return "None";
  29. case DKShaderDataType::Struct: return "Struct";
  30. case DKShaderDataType::Texture: return "Texture";
  31. case DKShaderDataType::Sampler: return "Sampler";
  32. case DKShaderDataType::Float: return "Float";
  33. case DKShaderDataType::Float2: return "Float2";
  34. case DKShaderDataType::Float3: return "Float3";
  35. case DKShaderDataType::Float4: return "Float4";
  36. case DKShaderDataType::Float2x2: return "Float2x2";
  37. case DKShaderDataType::Float2x3: return "Float2x3";
  38. case DKShaderDataType::Float2x4: return "Float2x4";
  39. case DKShaderDataType::Float3x2: return "Float3x2";
  40. case DKShaderDataType::Float3x3: return "Float3x3";
  41. case DKShaderDataType::Float3x4: return "Float3x4";
  42. case DKShaderDataType::Float4x2: return "Float4x2";
  43. case DKShaderDataType::Float4x3: return "Float4x3";
  44. case DKShaderDataType::Float4x4: return "Float4x4";
  45. case DKShaderDataType::Half: return "Half";
  46. case DKShaderDataType::Half2: return "Half2";
  47. case DKShaderDataType::Half3: return "Half3";
  48. case DKShaderDataType::Half4: return "Half4";
  49. case DKShaderDataType::Half2x2: return "Half2x2";
  50. case DKShaderDataType::Half2x3: return "Half2x3";
  51. case DKShaderDataType::Half2x4: return "Half2x4";
  52. case DKShaderDataType::Half3x2: return "Half3x2";
  53. case DKShaderDataType::Half3x3: return "Half3x3";
  54. case DKShaderDataType::Half3x4: return "Half3x4";
  55. case DKShaderDataType::Half4x2: return "Half4x2";
  56. case DKShaderDataType::Half4x3: return "Half4x3";
  57. case DKShaderDataType::Half4x4: return "Half4x4";
  58. case DKShaderDataType::Int: return "Int";
  59. case DKShaderDataType::Int2: return "Int2";
  60. case DKShaderDataType::Int3: return "Int3";
  61. case DKShaderDataType::Int4: return "Int4";
  62. case DKShaderDataType::UInt: return "UInt";
  63. case DKShaderDataType::UInt2: return "UInt2";
  64. case DKShaderDataType::UInt3: return "UInt3";
  65. case DKShaderDataType::UInt4: return "UInt4";
  66. case DKShaderDataType::Short: return "Short";
  67. case DKShaderDataType::Short2: return "Short2";
  68. case DKShaderDataType::Short3: return "Short3";
  69. case DKShaderDataType::Short4: return "Short4";
  70. case DKShaderDataType::UShort: return "UShort";
  71. case DKShaderDataType::UShort2: return "UShort2";
  72. case DKShaderDataType::UShort3: return "UShort3";
  73. case DKShaderDataType::UShort4: return "UShort4";
  74. case DKShaderDataType::Char: return "Char";
  75. case DKShaderDataType::Char2: return "Char2";
  76. case DKShaderDataType::Char3: return "Char3";
  77. case DKShaderDataType::Char4: return "Char4";
  78. case DKShaderDataType::UChar: return "UChar";
  79. case DKShaderDataType::UChar2: return "UChar2";
  80. case DKShaderDataType::UChar3: return "UChar3";
  81. case DKShaderDataType::UChar4: return "UChar4";
  82. case DKShaderDataType::Bool: return "Bool";
  83. case DKShaderDataType::Bool2: return "Bool2";
  84. case DKShaderDataType::Bool3: return "Bool3";
  85. case DKShaderDataType::Bool4: return "Bool4";
  86. }
  87. return "Error";
  88. }
  89. void PrintShaderResource(const DKShaderResource& res, DKLogCategory c = DKLogCategory::Info)
  90. {
  91. struct MemberPrinter
  92. {
  93. const DKShaderResource& res;
  94. int indent;
  95. DKLogCategory c;
  96. void operator()(const DKShaderResourceStruct& str) const
  97. {
  98. DKString indentStr = "";
  99. for (int i = 0; i < indent; ++i)
  100. {
  101. indentStr += " ";
  102. }
  103. for (const DKShaderResourceStructMember& mem : str.members)
  104. {
  105. if (mem.count > 1)
  106. {
  107. DKLog(c, " %ls+ %ls[%d] (%s, Offset: %d, Stride: %d)",
  108. (const wchar_t*)indentStr,
  109. (const wchar_t*)mem.name,
  110. mem.count,
  111. ShaderDataTypeStr(mem.dataType),
  112. mem.offset, mem.stride);
  113. }
  114. else
  115. {
  116. DKLog(c, " %ls+ %ls (%s, Offset: %d)",
  117. (const wchar_t*)indentStr,
  118. (const wchar_t*)mem.name,
  119. ShaderDataTypeStr(mem.dataType),
  120. mem.offset);
  121. }
  122. auto* p = res.structTypeMemberMap.Find(mem.typeInfoKey);
  123. if (p)
  124. {
  125. DKLog(c, " %ls Struct \"%ls\"",
  126. (const wchar_t*)indentStr,
  127. (const wchar_t*)mem.typeInfoKey);
  128. MemberPrinter{ res, indent + 1, c}.operator()(p->value);
  129. }
  130. }
  131. }
  132. };
  133. if (res.count > 1)
  134. DKLog(c, "ShaderResource: %ls[%d] (set=%d, binding=%d, stages=%ls)",
  135. (const wchar_t*)res.name, res.count, res.set, res.binding,
  136. (const wchar_t*)ShaderStageNames(res.stages));
  137. else
  138. DKLog(c, "ShaderResource: %ls (set=%d, binding=%d, stages=%ls)",
  139. (const wchar_t*)res.name, res.set, res.binding,
  140. (const wchar_t*)ShaderStageNames(res.stages));
  141. const char* type = "Unknown (ERROR)";
  142. switch (res.type)
  143. {
  144. case DKShaderResource::TypeBuffer: type = "Buffer"; break;
  145. case DKShaderResource::TypeTexture: type = "Texture"; break;
  146. case DKShaderResource::TypeSampler: type = "Sampler"; break;
  147. case DKShaderResource::TypeTextureSampler: type = "SampledTexture"; break;
  148. }
  149. const char* access = "Unknown (ERROR)";
  150. switch (res.access)
  151. {
  152. case DKShaderResource::AccessReadOnly: access = "ReadOnly"; break;
  153. case DKShaderResource::AccessWriteOnly: access = "WriteOnly"; break;
  154. case DKShaderResource::AccessReadWrite: access = "ReadWrite"; break;
  155. }
  156. if (res.type == DKShaderResource::TypeBuffer)
  157. {
  158. DKLog(c, " Type:%s, Access:%s, Enabled:%d, Size:%d",
  159. type,
  160. access,
  161. int(res.enabled),
  162. res.typeInfo.buffer.size);
  163. }
  164. else
  165. {
  166. DKLog(c, " Type:%s, Access:%s, Enabled:%d",
  167. type,
  168. access,
  169. int(res.enabled));
  170. }
  171. if (res.typeInfoKey.Length() > 0)
  172. DKLog(c, " Struct \"%ls\"", (const wchar_t*)res.typeInfoKey);
  173. if (res.type == DKShaderResource::TypeBuffer)
  174. {
  175. auto p = res.structTypeMemberMap.Find(res.typeInfoKey);
  176. if (p)
  177. MemberPrinter{ res, 1 , c}.operator()(p->value);
  178. }
  179. }
  180. void PrintPipelineReflection(const DKPipelineReflection* reflection, DKLogCategory c = DKLogCategory::Error)
  181. {
  182. DKLog(c, "=========================================================");
  183. DKLog(c, "PipelineReflection.InputAttributes: %d", reflection->inputAttributes.Count());
  184. for (int i = 0; i < reflection->inputAttributes.Count(); ++i)
  185. {
  186. const DKShaderAttribute& attr = reflection->inputAttributes.Value(i);
  187. DKLog(c, " [in] ShaderAttribute[%d]: \"%ls\" (location:%u)",
  188. i, (const wchar_t*)attr.name, attr.location);
  189. }
  190. DKLog(c, "---------------------------------------------------------");
  191. DKLog(c, "PipelineReflection.Resources: %d", reflection->resources.Count());
  192. for (auto& arg : reflection->resources)
  193. PrintShaderResource(arg, c);
  194. for (int i = 0; i < reflection->pushConstantLayouts.Count(); ++i)
  195. {
  196. const DKShaderPushConstantLayout& layout = reflection->pushConstantLayouts.Value(i);
  197. DKLog(c, " PushConstant:%d \"%ls\" (offset:%u, size:%u, stages:%ls)",
  198. i, (const wchar_t*)layout.name, layout.offset, layout.size,
  199. (const wchar_t*)ShaderStageNames(layout.stages));
  200. }
  201. DKLog(c, "=========================================================");
  202. }
  203. class TestApp1 : public DKApplication
  204. {
  205. DKObject<DKWindow> window;
  206. DKObject<DKThread> renderThread;
  207. DKResourcePool resourcePool;
  208. DKAtomicNumber32 runningRenderThread;
  209. public:
  210. void RenderThread(void)
  211. {
  212. DKObject<DKData> vertData = resourcePool.LoadResourceData("triangle.vert.spv");
  213. DKObject<DKData> fragData = resourcePool.LoadResourceData("triangle.frag.spv");
  214. DKShader vertShader(vertData);
  215. DKShader fragShader(fragData);
  216. DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
  217. DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
  218. DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
  219. DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
  220. DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
  221. DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
  222. DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
  223. DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
  224. for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
  225. {
  226. const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
  227. DKLog(" --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
  228. }
  229. struct Vertex
  230. {
  231. DKVector3 position;
  232. DKVector3 color;
  233. };
  234. DKArray<Vertex> vertexData =
  235. {
  236. { { 0.0f, -0.5f, 0.0f },{ 1.0f, 1.0f, 1.0f } },
  237. { { 0.5f, 0.5f, 0.0f },{ 0.0f, 1.0f, 0.0f } },
  238. { { -0.5f, 0.5f, 0.0f },{ 0.0f, 0.0f, 1.0f } }
  239. };
  240. uint32_t vertexBufferSize = static_cast<uint32_t>(vertexData.Count()) * sizeof(Vertex);
  241. DKArray<uint32_t> indexData = { 0, 1, 2 };
  242. uint32_t indexBufferSize = indexData.Count() * sizeof(uint32_t);
  243. DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeDefault);
  244. memcpy(vertexBuffer->Lock(), vertexData, vertexBufferSize);
  245. vertexBuffer->Unlock();
  246. DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeDefault);
  247. memcpy(indexBuffer->Lock(), indexData, indexBufferSize);
  248. indexBuffer->Unlock();
  249. DKRenderPipelineDescriptor pipelineDescriptor;
  250. pipelineDescriptor.vertexFunction = vertShaderFunction;
  251. pipelineDescriptor.fragmentFunction = fragShaderFunction;
  252. pipelineDescriptor.colorAttachments.Resize(1);
  253. pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
  254. pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::Invalid; // no depth buffer
  255. pipelineDescriptor.vertexDescriptor.attributes = {
  256. { DKVertexFormat::Float3, 0, 0, 0 },
  257. { DKVertexFormat::Float3, sizeof(DKVector3), 0, 1 },
  258. };
  259. pipelineDescriptor.vertexDescriptor.layouts = {
  260. { DKVertexStepRate::Vertex, sizeof(Vertex), 0 },
  261. };
  262. pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
  263. pipelineDescriptor.frontFace = DKFrontFace::CCW;
  264. pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
  265. pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
  266. pipelineDescriptor.cullMode = DKCullMode::None;
  267. pipelineDescriptor.rasterizationEnabled = true;
  268. DKPipelineReflection reflection;
  269. DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
  270. if (pipelineState)
  271. {
  272. PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
  273. }
  274. DKShaderBindingSetLayout layout;
  275. if (1)
  276. {
  277. DKShaderBinding binding = {
  278. 0,
  279. DKShader::DescriptorTypeUniformBuffer,
  280. 1,
  281. nullptr
  282. };
  283. layout.bindings.Add(binding);
  284. }
  285. DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
  286. if (bindSet)
  287. {
  288. struct
  289. {
  290. DKMatrix4 projectionMatrix;
  291. DKMatrix4 modelMatrix;
  292. DKMatrix4 viewMatrix;
  293. } ubo;
  294. DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(ubo), DKGpuBuffer::StorageModeShared, DKCpuCacheModeDefault);
  295. if (uboBuffer)
  296. {
  297. ubo.projectionMatrix = DKMatrix4::identity;
  298. ubo.modelMatrix = DKMatrix4::identity;
  299. ubo.viewMatrix = DKMatrix4::identity;
  300. void* p = uboBuffer->Lock(0);
  301. if (p)
  302. {
  303. memcpy(p, &ubo, sizeof(ubo));
  304. uboBuffer->Unlock();
  305. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(ubo));
  306. }
  307. else
  308. {
  309. DKLogE("GpuBuffer Lock failed!");
  310. }
  311. }
  312. }
  313. DKTimer timer;
  314. timer.Reset();
  315. DKLog("Render thread begin");
  316. while (!runningRenderThread.CompareAndSet(0, 0))
  317. {
  318. DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
  319. double t = timer.Elapsed();
  320. t = (cos(t) + 1.0) * 0.5;
  321. rpd.colorAttachments.Value(0).clearColor = DKColor(t, 0.0, 0.0, 0.0);
  322. DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
  323. DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
  324. if (encoder)
  325. {
  326. encoder->SetRenderPipelineState(pipelineState);
  327. encoder->SetVertexBuffer(vertexBuffer, 0, 0);
  328. encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
  329. encoder->SetResources(0, bindSet);
  330. // draw scene!
  331. encoder->DrawIndexed(indexData.Count(), 1, 0, 0, 1);
  332. encoder->EndEncoding();
  333. buffer->Commit();
  334. swapChain->Present();
  335. }
  336. else
  337. {
  338. }
  339. DKThread::Sleep(0.01);
  340. }
  341. DKLog("RenderThread terminating...");
  342. }
  343. void OnInitialize(void) override
  344. {
  345. DKLogD("%s", DKGL_FUNCTION_NAME);
  346. DKString resPath = DefaultPath(SystemPath::AppResource);
  347. resPath = resPath.FilePathStringByAppendingPath("Data");
  348. DKLog("resPath: %ls", (const wchar_t*)resPath);
  349. resourcePool.AddLocatorForPath(resPath);
  350. window = DKWindow::Create("DefaultWindow");
  351. window->SetOrigin({ 0, 0 });
  352. window->Resize({ 320, 240 });
  353. window->Activate();
  354. window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
  355. {
  356. if (e.type == DKWindow::WindowEvent::WindowClosed)
  357. DKApplication::Instance()->Terminate(0);
  358. }), NULL, NULL);
  359. runningRenderThread = 1;
  360. renderThread = DKThread::Create(DKFunction(this, &TestApp1::RenderThread)->Invocation());
  361. }
  362. void OnTerminate(void) override
  363. {
  364. DKLogD("%s", DKGL_FUNCTION_NAME);
  365. runningRenderThread = 0;
  366. renderThread->WaitTerminate();
  367. renderThread = NULL;
  368. window = NULL;
  369. DKLogI("Memory Pool Statistics");
  370. size_t numBuckets = DKMemoryPoolNumberOfBuckets();
  371. DKMemoryPoolBucketStatus* buckets = new DKMemoryPoolBucketStatus[numBuckets];
  372. DKMemoryPoolQueryAllocationStatus(buckets, numBuckets);
  373. size_t usedBytes = 0;
  374. for (int i = 0; i < numBuckets; ++i)
  375. {
  376. if (buckets[i].totalChunks > 0)
  377. {
  378. DKLogI("--> %5lu: %5lu/%5lu, usage: %.1f%%, used: %.1fKB, total: %.1fKB",
  379. buckets[i].chunkSize,
  380. buckets[i].usedChunks, buckets[i].totalChunks,
  381. double(buckets[i].usedChunks) / double(buckets[i].totalChunks) * 100.0,
  382. double(buckets[i].chunkSize * buckets[i].usedChunks) / 1024.0,
  383. double(buckets[i].chunkSize * buckets[i].totalChunks) / 1024.0
  384. );
  385. usedBytes += buckets[i].chunkSize * buckets[i].usedChunks;
  386. }
  387. }
  388. DKLogI("MemoryPool Usage: %.1fMB / %.1fMB", double(usedBytes) / (1024 * 1024), double(DKMemoryPoolSize()) / (1024 * 1024));
  389. delete[] buckets;
  390. }
  391. };
  392. #ifdef _WIN32
  393. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  394. _In_opt_ HINSTANCE hPrevInstance,
  395. _In_ LPWSTR lpCmdLine,
  396. _In_ int nCmdShow)
  397. #else
  398. int main(int argc, const char * argv[])
  399. #endif
  400. {
  401. TestApp1 app;
  402. DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
  403. DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
  404. return app.Run();
  405. }