Shader.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /**
  2. * Copyright (c) 2006-2024 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "graphics/vertex.h"
  21. #include "Shader.h"
  22. #include "Graphics.h"
  23. #include "common/Range.h"
  24. #include "libraries/glslang/glslang/Public/ShaderLang.h"
  25. #include "libraries/glslang/glslang/Public/ResourceLimits.h"
  26. #include "libraries/glslang/SPIRV/GlslangToSpv.h"
  27. #include <array>
  28. namespace love
  29. {
  30. namespace graphics
  31. {
  32. namespace vulkan
  33. {
  34. static const uint32_t DESCRIPTOR_POOL_SIZE = 1000;
  35. class BindingMapper
  36. {
  37. public:
  38. BindingMapper(spv::Decoration decoration)
  39. : decoration(decoration)
  40. {}
  41. uint32_t operator()(spirv_cross::CompilerGLSL &comp, std::vector<uint32_t> &spirv, const std::string &name, int count, const spirv_cross::ID &id)
  42. {
  43. auto it = bindingMappings.find(name);
  44. if (it == bindingMappings.end())
  45. {
  46. auto binding = comp.get_decoration(id, decoration);
  47. if (isFreeBinding(binding, count))
  48. {
  49. bindingMappings[name] = Range(binding, count);
  50. return binding;
  51. }
  52. else
  53. {
  54. uint32_t freeBinding = getFreeBinding(count);
  55. uint32_t binaryBindingOffset;
  56. if (!comp.get_binary_offset_for_decoration(id, decoration, binaryBindingOffset))
  57. throw love::Exception("could not get binary offset for uniform %s binding", name.c_str());
  58. spirv[binaryBindingOffset] = freeBinding;
  59. bindingMappings[name] = Range(freeBinding, count);
  60. return freeBinding;
  61. }
  62. }
  63. else
  64. {
  65. auto binding = (uint32_t)it->second.getOffset();
  66. uint32_t binaryBindingOffset;
  67. if (!comp.get_binary_offset_for_decoration(id, decoration, binaryBindingOffset))
  68. throw love::Exception("could not get binary offset for uniform %s binding", name.c_str());
  69. spirv[binaryBindingOffset] = binding;
  70. return binding;
  71. }
  72. };
  73. private:
  74. uint32_t getFreeBinding(int count)
  75. {
  76. for (uint32_t i = 0;; i++)
  77. {
  78. if (isFreeBinding(i, count))
  79. return i;
  80. }
  81. }
  82. bool isFreeBinding(uint32_t binding, int count)
  83. {
  84. Range r(binding, count);
  85. for (const auto &entry : bindingMappings)
  86. {
  87. if (entry.second.intersects(r))
  88. return false;
  89. }
  90. return true;
  91. }
  92. spv::Decoration decoration;
  93. std::map<std::string, Range> bindingMappings;
  94. };
  95. static VkShaderStageFlagBits getStageBit(ShaderStageType type)
  96. {
  97. switch (type)
  98. {
  99. case SHADERSTAGE_VERTEX:
  100. return VK_SHADER_STAGE_VERTEX_BIT;
  101. case SHADERSTAGE_PIXEL:
  102. return VK_SHADER_STAGE_FRAGMENT_BIT;
  103. case SHADERSTAGE_COMPUTE:
  104. return VK_SHADER_STAGE_COMPUTE_BIT;
  105. default:
  106. throw love::Exception("invalid type");
  107. }
  108. }
  109. static VkShaderStageFlags getStageFlags(ShaderStageMask mask)
  110. {
  111. VkShaderStageFlags flags = 0;
  112. if (mask & SHADERSTAGEMASK_VERTEX)
  113. flags |= VK_SHADER_STAGE_VERTEX_BIT;
  114. if (mask & SHADERSTAGEMASK_PIXEL)
  115. flags |= VK_SHADER_STAGE_FRAGMENT_BIT;
  116. if (mask & SHADERSTAGEMASK_COMPUTE)
  117. flags |= VK_SHADER_STAGE_COMPUTE_BIT;
  118. return flags;
  119. }
  120. static EShLanguage getGlslShaderType(ShaderStageType stage)
  121. {
  122. switch (stage)
  123. {
  124. case SHADERSTAGE_VERTEX:
  125. return EShLangVertex;
  126. case SHADERSTAGE_PIXEL:
  127. return EShLangFragment;
  128. case SHADERSTAGE_COMPUTE:
  129. return EShLangCompute;
  130. default:
  131. throw love::Exception("unkonwn shader stage type");
  132. }
  133. }
  134. static bool usesLocalUniformData(const graphics::Shader::UniformInfo *info)
  135. {
  136. return info->baseType == graphics::Shader::UNIFORM_BOOL ||
  137. info->baseType == graphics::Shader::UNIFORM_FLOAT ||
  138. info->baseType == graphics::Shader::UNIFORM_INT ||
  139. info->baseType == graphics::Shader::UNIFORM_MATRIX ||
  140. info->baseType == graphics::Shader::UNIFORM_UINT;
  141. }
  142. Shader::Shader(StrongRef<love::graphics::ShaderStage> stages[], const CompileOptions &options)
  143. : graphics::Shader(stages, options)
  144. , builtinUniformInfo()
  145. {
  146. auto gfx = Module::getInstance<Graphics>(Module::ModuleType::M_GRAPHICS);
  147. vgfx = dynamic_cast<Graphics*>(gfx);
  148. loadVolatile();
  149. }
  150. bool Shader::loadVolatile()
  151. {
  152. device = vgfx->getDevice();
  153. computePipeline = VK_NULL_HANDLE;
  154. for (int i = 0; i < BUILTIN_MAX_ENUM; i++)
  155. builtinUniformInfo[i] = nullptr;
  156. compileShaders();
  157. createDescriptorSetLayout();
  158. createPipelineLayout();
  159. createDescriptorPoolSizes();
  160. descriptorPools.resize(MAX_FRAMES_IN_FLIGHT);
  161. currentFrame = 0;
  162. newFrame();
  163. return true;
  164. }
  165. void Shader::unloadVolatile()
  166. {
  167. if (shaderModules.empty())
  168. return;
  169. vgfx->queueCleanUp([shaderModules = std::move(shaderModules), device = device, descriptorSetLayout = descriptorSetLayout, pipelineLayout = pipelineLayout,
  170. descriptorPools = descriptorPools, computePipeline = computePipeline,
  171. graphicsPipelinesCore = std::move(graphicsPipelinesDynamicState), graphicsPipelinesFull = std::move(graphicsPipelinesNoDynamicState)]() {
  172. for (const auto &pools : descriptorPools)
  173. {
  174. for (const auto pool : pools)
  175. vkDestroyDescriptorPool(device, pool, nullptr);
  176. }
  177. for (const auto shaderModule : shaderModules)
  178. vkDestroyShaderModule(device, shaderModule, nullptr);
  179. vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
  180. vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
  181. if (computePipeline != VK_NULL_HANDLE)
  182. vkDestroyPipeline(device, computePipeline, nullptr);
  183. for (const auto &kvp : graphicsPipelinesCore)
  184. vkDestroyPipeline(device, kvp.second, nullptr);
  185. for (const auto &kvp : graphicsPipelinesFull)
  186. vkDestroyPipeline(device, kvp.second, nullptr);
  187. });
  188. shaderModules.clear();
  189. shaderStages.clear();
  190. descriptorPools.clear();
  191. }
  192. const std::vector<VkPipelineShaderStageCreateInfo> &Shader::getShaderStages() const
  193. {
  194. return shaderStages;
  195. }
  196. const VkPipelineLayout Shader::getGraphicsPipelineLayout() const
  197. {
  198. return pipelineLayout;
  199. }
  200. VkPipeline Shader::getComputePipeline() const
  201. {
  202. return computePipeline;
  203. }
  204. void Shader::newFrame()
  205. {
  206. currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
  207. currentDescriptorPool = 0;
  208. currentDescriptorSet = VK_NULL_HANDLE;
  209. resourceDescriptorsDirty = true;
  210. for (VkDescriptorPool pool : descriptorPools[currentFrame])
  211. vkResetDescriptorPool(device, pool, 0);
  212. }
  213. void Shader::cmdPushDescriptorSets(VkCommandBuffer commandBuffer, VkPipelineBindPoint bindPoint)
  214. {
  215. bool useLocalUniformOffset = false;
  216. uint32 localUniformOffset = 0;
  217. if (!localUniformData.empty())
  218. {
  219. if (builtinUniformDataOffset.hasValue)
  220. {
  221. auto builtinData = vgfx->getCurrentBuiltinUniformData();
  222. auto dst = (BuiltinUniformData *) (localUniformData.data() + builtinUniformDataOffset.value);
  223. memcpy(dst, &builtinData, sizeof(builtinData));
  224. }
  225. VkDescriptorBufferInfo info = {};
  226. vgfx->mapLocalUniformData(localUniformData.data(), localUniformData.size(), info);
  227. // This is a dynamic uniform buffer, so the offset is specified in BindDescriptorSets
  228. // and it only needs to update the descriptor sets if the buffer changes.
  229. if (info.buffer != descriptorBuffers[0].buffer)
  230. resourceDescriptorsDirty = true;
  231. descriptorBuffers[0].buffer = info.buffer;
  232. descriptorBuffers[0].range = info.range;
  233. descriptorBuffers[0].offset = 0;
  234. useLocalUniformOffset = true;
  235. localUniformOffset = info.offset;
  236. }
  237. // Sampler updates need to happen here because the handles may change after sendTextures.
  238. for (const auto &u : reflection.sampledTextures)
  239. {
  240. const auto &info = u.second;
  241. if (!info.active)
  242. continue;
  243. for (int i = 0; i < info.count; i++)
  244. {
  245. auto vkTexture = dynamic_cast<Texture*>(activeTextures[info.resourceIndex + i]);
  246. if (vkTexture == nullptr)
  247. throw love::Exception("uniform variable %s is not set.", info.name.c_str());
  248. auto sampler = (VkSampler)vkTexture->getSamplerHandle();
  249. VkDescriptorImageInfo &imageInfo = descriptorImages[info.bindingStartIndex + i];
  250. if (sampler != imageInfo.sampler)
  251. {
  252. imageInfo.sampler = sampler;
  253. resourceDescriptorsDirty = true;
  254. }
  255. }
  256. }
  257. if (resourceDescriptorsDirty || currentDescriptorSet == VK_NULL_HANDLE)
  258. {
  259. currentDescriptorSet = allocateDescriptorSet();
  260. for (auto &write : descriptorWrites)
  261. write.dstSet = currentDescriptorSet;
  262. vkUpdateDescriptorSets(device, descriptorWrites.size(), descriptorWrites.data(), 0, nullptr);
  263. resourceDescriptorsDirty = false;
  264. }
  265. vkCmdBindDescriptorSets(commandBuffer, bindPoint, pipelineLayout, 0, 1, &currentDescriptorSet, useLocalUniformOffset ? 1 : 0, &localUniformOffset);
  266. }
  267. Shader::~Shader()
  268. {
  269. unloadVolatile();
  270. }
  271. void Shader::attach()
  272. {
  273. if (!isCompute)
  274. {
  275. if (Shader::current != this)
  276. {
  277. Graphics::flushBatchedDrawsGlobal();
  278. Shader::current = this;
  279. Vulkan::shaderSwitch();
  280. }
  281. }
  282. else
  283. vgfx->setComputeShader(this);
  284. }
  285. int Shader::getVertexAttributeIndex(const std::string &name)
  286. {
  287. auto it = attributes.find(name);
  288. return it == attributes.end() ? -1 : it->second.index;
  289. }
  290. const Shader::UniformInfo *Shader::getUniformInfo(BuiltinUniform builtin) const
  291. {
  292. return builtinUniformInfo[builtin];
  293. }
  294. void Shader::updateUniform(const UniformInfo *info, int count)
  295. {
  296. if (current == this)
  297. Graphics::flushBatchedDrawsGlobal();
  298. count = std::min(count, info->count);
  299. if (info->data != nullptr)
  300. {
  301. size_t offset = (const uint8*)info->data - localUniformStagingData.data();
  302. uint8 *dst = localUniformData.data() + offset;
  303. copyToUniformBuffer(info, info->data, dst, count);
  304. }
  305. }
  306. void Shader::applyTexture(const UniformInfo *info, int i, love::graphics::Texture *texture, UniformType /*basetype*/, bool isdefault)
  307. {
  308. setTextureDescriptor(info, (isdefault && (info->access & ACCESS_WRITE) != 0) ? nullptr : texture, i);
  309. }
  310. void Shader::applyBuffer(const UniformInfo *info, int i, love::graphics::Buffer *buffer, UniformType /*basetype*/, bool isdefault)
  311. {
  312. setBufferDescriptor(info, (isdefault && (info->access & ACCESS_WRITE) != 0) ? nullptr : buffer, i);
  313. }
  314. void Shader::buildLocalUniforms(spirv_cross::Compiler &comp, const spirv_cross::SPIRType &type, size_t baseoff, const std::string &basename)
  315. {
  316. using namespace spirv_cross;
  317. const auto &membertypes = type.member_types;
  318. for (size_t uindex = 0; uindex < membertypes.size(); uindex++)
  319. {
  320. const auto &memberType = comp.get_type(membertypes[uindex]);
  321. size_t memberSize = comp.get_declared_struct_member_size(type, uindex);
  322. size_t offset = baseoff + comp.type_struct_member_offset(type, uindex);
  323. std::string name = basename + comp.get_member_name(type.self, uindex);
  324. switch (memberType.basetype)
  325. {
  326. case SPIRType::Struct:
  327. if (memberType.op == spv::OpTypeArray)
  328. {
  329. size_t arraystride = comp.type_struct_member_array_stride(type, uindex);
  330. for (uint32 i = 0; i < memberType.array[0]; i++)
  331. {
  332. std::string structname = name + "[" + std::to_string(i) + "].";
  333. buildLocalUniforms(comp, memberType, offset + i * arraystride, structname);
  334. }
  335. }
  336. else
  337. {
  338. std::string structname = name + ".";
  339. buildLocalUniforms(comp, memberType, offset, structname);
  340. }
  341. continue;
  342. case SPIRType::Int:
  343. case SPIRType::UInt:
  344. case SPIRType::Float:
  345. break;
  346. default:
  347. continue;
  348. }
  349. name = canonicaliizeUniformName(name);
  350. auto uniformit = reflection.allUniforms.find(name);
  351. if (uniformit == reflection.allUniforms.end())
  352. {
  353. handleUnknownUniformName(name.c_str());
  354. continue;
  355. }
  356. UniformInfo &u = *(uniformit->second);
  357. u.active = true;
  358. u.dataSize = memberSize;
  359. u.data = localUniformStagingData.data() + offset;
  360. const auto &valuesit = reflection.localUniformInitializerValues.find(name);
  361. if (valuesit != reflection.localUniformInitializerValues.end())
  362. {
  363. const auto &values = valuesit->second;
  364. if (!values.empty())
  365. {
  366. memcpy(
  367. u.data,
  368. values.data(),
  369. std::min(u.dataSize, values.size() * sizeof(LocalUniformValue)));
  370. uint8 *dst = localUniformData.data() + offset;
  371. copyToUniformBuffer(&u, u.data, dst, u.count);
  372. }
  373. }
  374. BuiltinUniform builtin = BUILTIN_MAX_ENUM;
  375. if (getConstant(u.name.c_str(), builtin))
  376. {
  377. if (builtin == BUILTIN_UNIFORMS_PER_DRAW)
  378. builtinUniformDataOffset = offset;
  379. builtinUniformInfo[builtin] = &u;
  380. }
  381. }
  382. }
  383. void Shader::compileShaders()
  384. {
  385. using namespace glslang;
  386. using namespace spirv_cross;
  387. std::vector<std::unique_ptr<TShader>> glslangShaders;
  388. auto program = std::make_unique<TProgram>();
  389. const auto &enabledExtensions = vgfx->getEnabledOptionalDeviceExtensions();
  390. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  391. {
  392. if (!stages[i])
  393. continue;
  394. auto stage = (ShaderStageType)i;
  395. if (stage == SHADERSTAGE_COMPUTE)
  396. isCompute = true;
  397. auto glslangShaderStage = getGlslShaderType(stage);
  398. auto tshader = std::make_unique<TShader>(glslangShaderStage);
  399. tshader->setEnvInput(EShSourceGlsl, glslangShaderStage, EShClientVulkan, 450);
  400. tshader->setEnvClient(EShClientVulkan, EShTargetVulkan_1_2);
  401. if (enabledExtensions.spirv14)
  402. tshader->setEnvTarget(EshTargetSpv, EShTargetSpv_1_4);
  403. else
  404. tshader->setEnvTarget(EshTargetSpv, EShTargetSpv_1_0);
  405. tshader->setAutoMapLocations(true);
  406. tshader->setAutoMapBindings(true);
  407. tshader->setEnvInputVulkanRulesRelaxed();
  408. tshader->setGlobalUniformBinding(0);
  409. tshader->setGlobalUniformSet(0);
  410. auto &glsl = stages[i]->getSource();
  411. const char *csrc = glsl.c_str();
  412. const int sourceLength = static_cast<int>(glsl.length());
  413. tshader->setStringsWithLengths(&csrc, &sourceLength, 1);
  414. int defaultVersion = 450;
  415. EProfile defaultProfile = ECoreProfile;
  416. bool forceDefault = false;
  417. bool forwardCompat = true;
  418. if (!tshader->parse(GetResources(), defaultVersion, defaultProfile, forceDefault, forwardCompat, EShMsgSuppressWarnings))
  419. {
  420. const char *stageName = "unknown";
  421. ShaderStage::getConstant(stage, stageName);
  422. std::string err = "Error parsing " + std::string(stageName) + " shader:\n\n"
  423. + std::string(tshader->getInfoLog()) + "\n"
  424. + std::string(tshader->getInfoDebugLog());
  425. throw love::Exception("%s", err.c_str());
  426. }
  427. program->addShader(tshader.get());
  428. glslangShaders.push_back(std::move(tshader));
  429. }
  430. if (!program->link(EShMsgDefault))
  431. throw love::Exception("link failed! %s\n", program->getInfoLog());
  432. if (!program->mapIO())
  433. throw love::Exception("mapIO failed");
  434. BindingMapper bindingMapper(spv::DecorationBinding);
  435. BindingMapper ioLocationMapper(spv::DecorationLocation);
  436. BindingMapper vertexInputLocationMapper(spv::DecorationLocation);
  437. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  438. {
  439. auto shaderStage = (ShaderStageType)i;
  440. auto glslangStage = getGlslShaderType(shaderStage);
  441. auto intermediate = program->getIntermediate(glslangStage);
  442. if (intermediate == nullptr)
  443. continue;
  444. spv::SpvBuildLogger logger;
  445. glslang::SpvOptions opt;
  446. opt.validate = true;
  447. std::vector<uint32> spirv;
  448. GlslangToSpv(*intermediate, spirv, &logger, &opt);
  449. auto compiler = std::make_unique<spirv_cross::CompilerGLSL>(spirv);
  450. auto &comp = *compiler;
  451. // We aren't recompiling the SPIR-V to something else, so
  452. // set_enabled_interface_variables wouldn't do much.
  453. // Vulkan has various rules about making sure bindings to inputs and
  454. // resources are valid, so we can't skip inactive ones here.
  455. // Unfortunately GlslangToSpv doesn't strip unused resources even
  456. // though it knows about them...
  457. auto active = compiler->get_active_interface_variables();
  458. auto shaderResources = comp.get_shader_resources();
  459. for (const auto &resource : shaderResources.uniform_buffers)
  460. {
  461. // TODO: Do something smarter here.
  462. if (active.find(resource.id) == active.end())
  463. continue;
  464. if (resource.name == "gl_DefaultUniformBlock")
  465. {
  466. const auto &type = comp.get_type(resource.base_type_id);
  467. size_t defaultUniformBlockSize = comp.get_declared_struct_size(type);
  468. localUniformStagingData.resize(defaultUniformBlockSize);
  469. localUniformData.resize(defaultUniformBlockSize);
  470. localUniformLocation = bindingMapper(comp, spirv, resource.name, 1, resource.id);
  471. memset(localUniformStagingData.data(), 0, defaultUniformBlockSize);
  472. memset(localUniformData.data(), 0, defaultUniformBlockSize);
  473. std::string basename("");
  474. buildLocalUniforms(comp, type, 0, basename);
  475. }
  476. else
  477. throw love::Exception("unimplemented: non default uniform blocks.");
  478. }
  479. for (const auto &r : shaderResources.sampled_images)
  480. {
  481. // TODO: Do something smarter here.
  482. if (active.find(r.id) == active.end())
  483. continue;
  484. std::string name = canonicaliizeUniformName(r.name);
  485. auto uniformit = reflection.allUniforms.find(name);
  486. if (uniformit == reflection.allUniforms.end())
  487. {
  488. handleUnknownUniformName(name.c_str());
  489. continue;
  490. }
  491. UniformInfo &u = *(uniformit->second);
  492. u.active = true;
  493. u.location = bindingMapper(comp, spirv, name, u.count, r.id);
  494. BuiltinUniform builtin;
  495. if (getConstant(name.c_str(), builtin))
  496. builtinUniformInfo[builtin] = &u;
  497. }
  498. for (const auto &r : shaderResources.storage_buffers)
  499. {
  500. // TODO: Do something smarter here.
  501. if (active.find(r.id) == active.end())
  502. continue;
  503. std::string name = canonicaliizeUniformName(r.name);
  504. const auto &uniformit = reflection.storageBuffers.find(name);
  505. if (uniformit == reflection.storageBuffers.end())
  506. {
  507. handleUnknownUniformName(name.c_str());
  508. continue;
  509. }
  510. UniformInfo &u = uniformit->second;
  511. u.active = true;
  512. u.location = bindingMapper(comp, spirv, name, u.count, r.id);
  513. }
  514. for (const auto &r : shaderResources.storage_images)
  515. {
  516. // TODO: Do something smarter here.
  517. if (active.find(r.id) == active.end())
  518. continue;
  519. std::string name = canonicaliizeUniformName(r.name);
  520. const auto &uniformit = reflection.storageTextures.find(name);
  521. if (uniformit == reflection.storageTextures.end())
  522. {
  523. handleUnknownUniformName(name.c_str());
  524. continue;
  525. }
  526. UniformInfo &u = uniformit->second;
  527. u.active = true;
  528. u.location = bindingMapper(comp, spirv, name, u.count, r.id);
  529. }
  530. if (shaderStage == SHADERSTAGE_VERTEX)
  531. {
  532. // Use the mapper on known used inputs first, so their bindings get
  533. // put into the map without being changed.
  534. for (const auto &r : shaderResources.stage_inputs)
  535. {
  536. auto it = reflection.vertexInputs.find(r.name);
  537. if (it != reflection.vertexInputs.end() && it->second >= 0)
  538. vertexInputLocationMapper(comp, spirv, r.name, 1, r.id);
  539. }
  540. for (const auto &r : shaderResources.stage_inputs)
  541. {
  542. // Don't skip unused inputs, vulkan still needs to have valid
  543. // bindings for them. This will also avoid shuffling intentional
  544. // used bindings because of the earlier loop.
  545. int index = (int)vertexInputLocationMapper(comp, spirv, r.name, 1, r.id);
  546. DataBaseType basetype = DATA_BASETYPE_FLOAT;
  547. switch (comp.get_type(r.base_type_id).basetype)
  548. {
  549. case spirv_cross::SPIRType::Int:
  550. basetype = DATA_BASETYPE_INT;
  551. break;
  552. case spirv_cross::SPIRType::UInt:
  553. basetype = DATA_BASETYPE_UINT;
  554. break;
  555. default:
  556. break;
  557. }
  558. attributes[r.name] = { index, basetype };
  559. }
  560. for (const auto &r : shaderResources.stage_outputs)
  561. {
  562. const auto &type = comp.get_type(r.base_type_id);
  563. int count = type.array.empty() ? 1 : type.array[0];
  564. if (type.op == spv::OpTypeMatrix)
  565. count *= type.columns;
  566. ioLocationMapper(comp, spirv, r.name, count, r.id);
  567. }
  568. }
  569. else if (shaderStage == SHADERSTAGE_PIXEL)
  570. {
  571. for (const auto &r : shaderResources.stage_inputs)
  572. {
  573. const auto &type = comp.get_type(r.base_type_id);
  574. int count = type.array.empty() ? 1 : type.array[0];
  575. if (type.op == spv::OpTypeMatrix)
  576. count *= type.columns;
  577. ioLocationMapper(comp, spirv, r.name, count, r.id);
  578. }
  579. }
  580. VkShaderModuleCreateInfo createInfo{};
  581. createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  582. createInfo.codeSize = spirv.size() * sizeof(uint32_t);
  583. createInfo.pCode = spirv.data();
  584. VkShaderModule shaderModule;
  585. if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS)
  586. throw love::Exception("failed to create shader module");
  587. std::string debugname = getShaderStageDebugName(shaderStage);
  588. if (!debugname.empty() && vgfx->getEnabledOptionalInstanceExtensions().debugInfo)
  589. {
  590. auto device = vgfx->getDevice();
  591. VkDebugUtilsObjectNameInfoEXT nameInfo{};
  592. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  593. nameInfo.objectType = VK_OBJECT_TYPE_SHADER_MODULE;
  594. nameInfo.objectHandle = (uint64_t)shaderModule;
  595. nameInfo.pObjectName = debugname.c_str();
  596. vkSetDebugUtilsObjectNameEXT(device, &nameInfo);
  597. }
  598. shaderModules.push_back(shaderModule);
  599. VkPipelineShaderStageCreateInfo shaderStageInfo{};
  600. shaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  601. shaderStageInfo.stage = getStageBit((ShaderStageType)i);
  602. shaderStageInfo.module = shaderModule;
  603. shaderStageInfo.pName = "main";
  604. shaderStages.push_back(shaderStageInfo);
  605. }
  606. int numBuffers = 0;
  607. int numTextures = 0;
  608. int numBufferViews = 0;
  609. if (localUniformData.size() > 0)
  610. numBuffers++;
  611. for (const auto &kvp : reflection.allUniforms)
  612. {
  613. if (!kvp.second->active)
  614. continue;
  615. switch (kvp.second->baseType)
  616. {
  617. case UNIFORM_SAMPLER:
  618. case UNIFORM_STORAGETEXTURE:
  619. numTextures += kvp.second->count;
  620. break;
  621. case UNIFORM_STORAGEBUFFER:
  622. numBuffers += kvp.second->count;
  623. break;
  624. case UNIFORM_TEXELBUFFER:
  625. numBufferViews += kvp.second->count;
  626. break;
  627. default:
  628. continue;
  629. }
  630. }
  631. descriptorWrites.clear();
  632. descriptorBuffers.clear();
  633. descriptorBuffers.reserve(numBuffers);
  634. descriptorImages.clear();
  635. descriptorImages.reserve(numTextures);
  636. descriptorBufferViews.clear();
  637. descriptorBufferViews.reserve(numBufferViews);
  638. if (localUniformData.size() > 0)
  639. {
  640. VkDescriptorBufferInfo bufferInfo{};
  641. bufferInfo.range = localUniformData.size();
  642. descriptorBuffers.push_back(bufferInfo);
  643. VkWriteDescriptorSet write{};
  644. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  645. write.dstBinding = localUniformLocation;
  646. write.dstArrayElement = 0;
  647. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  648. write.descriptorCount = 1;
  649. write.pBufferInfo = &descriptorBuffers.back();
  650. descriptorWrites.push_back(write);
  651. }
  652. for (auto &u : reflection.sampledTextures)
  653. {
  654. UniformInfo &info = u.second;
  655. if (!info.active)
  656. continue;
  657. info.bindingStartIndex = (int)descriptorImages.size();
  658. for (int i = 0; i < info.count; i++)
  659. {
  660. VkDescriptorImageInfo imageInfo{};
  661. descriptorImages.push_back(imageInfo);
  662. auto texture = activeTextures[info.resourceIndex + i];
  663. if (texture != nullptr)
  664. setTextureDescriptor(&info, texture, i);
  665. }
  666. VkWriteDescriptorSet write{};
  667. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  668. write.dstBinding = info.location;
  669. write.dstArrayElement = 0;
  670. write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  671. write.descriptorCount = static_cast<uint32_t>(info.count);
  672. write.pImageInfo = &descriptorImages[info.bindingStartIndex];
  673. descriptorWrites.push_back(write);
  674. }
  675. for (auto &u : reflection.storageTextures)
  676. {
  677. UniformInfo &info = u.second;
  678. if (!info.active)
  679. continue;
  680. info.bindingStartIndex = (int)descriptorImages.size();
  681. for (int i = 0; i < info.count; i++)
  682. {
  683. VkDescriptorImageInfo imageInfo{};
  684. descriptorImages.push_back(imageInfo);
  685. auto texture = activeTextures[info.resourceIndex + i];
  686. if (texture != nullptr)
  687. setTextureDescriptor(&info, texture, i);
  688. }
  689. VkWriteDescriptorSet write{};
  690. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  691. write.dstBinding = info.location;
  692. write.dstArrayElement = 0;
  693. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  694. write.descriptorCount = static_cast<uint32_t>(info.count);
  695. write.pImageInfo = &descriptorImages[info.bindingStartIndex];
  696. descriptorWrites.push_back(write);
  697. }
  698. for (auto &u : reflection.texelBuffers)
  699. {
  700. UniformInfo &info = u.second;
  701. if (!info.active)
  702. continue;
  703. info.bindingStartIndex = (int)descriptorBufferViews.size();
  704. for (int i = 0; i < info.count; i++)
  705. {
  706. descriptorBufferViews.push_back(VK_NULL_HANDLE);
  707. auto buffer = activeBuffers[info.resourceIndex + i];
  708. if (buffer != nullptr)
  709. setBufferDescriptor(&info, buffer, i);
  710. }
  711. VkWriteDescriptorSet write{};
  712. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  713. write.dstBinding = info.location;
  714. write.dstArrayElement = 0;
  715. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  716. write.descriptorCount = info.count;
  717. write.pTexelBufferView = &descriptorBufferViews[info.bindingStartIndex];
  718. descriptorWrites.push_back(write);
  719. }
  720. for (auto &u : reflection.storageBuffers)
  721. {
  722. UniformInfo &info = u.second;
  723. if (!info.active)
  724. continue;
  725. info.bindingStartIndex = (int)descriptorBuffers.size();
  726. for (int i = 0; i < info.count; i++)
  727. {
  728. VkDescriptorBufferInfo bufferInfo{};
  729. descriptorBuffers.push_back(bufferInfo);
  730. auto buffer = activeBuffers[info.resourceIndex + i];
  731. if (buffer != nullptr)
  732. setBufferDescriptor(&info, buffer, i);
  733. }
  734. VkWriteDescriptorSet write{};
  735. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  736. write.dstBinding = info.location;
  737. write.dstArrayElement = 0;
  738. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  739. write.descriptorCount = info.count;
  740. write.pBufferInfo = &descriptorBuffers[info.bindingStartIndex];
  741. descriptorWrites.push_back(write);
  742. }
  743. resourceDescriptorsDirty = true;
  744. }
  745. void Shader::createDescriptorSetLayout()
  746. {
  747. std::vector<VkDescriptorSetLayoutBinding> bindings;
  748. for (auto const &entry : reflection.allUniforms)
  749. {
  750. if (!entry.second->active)
  751. continue;
  752. auto type = Vulkan::getDescriptorType(entry.second->baseType);
  753. if (type != VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC)
  754. {
  755. VkDescriptorSetLayoutBinding layoutBinding{};
  756. layoutBinding.binding = entry.second->location;
  757. layoutBinding.descriptorType = type;
  758. layoutBinding.descriptorCount = entry.second->count;
  759. layoutBinding.stageFlags = getStageFlags((ShaderStageMask)entry.second->stageMask);
  760. bindings.push_back(layoutBinding);
  761. }
  762. }
  763. if (!localUniformStagingData.empty())
  764. {
  765. VkDescriptorSetLayoutBinding uniformBinding{};
  766. uniformBinding.binding = localUniformLocation;
  767. uniformBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  768. uniformBinding.descriptorCount = 1;
  769. if (isCompute)
  770. uniformBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
  771. else
  772. uniformBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
  773. bindings.push_back(uniformBinding);
  774. }
  775. VkDescriptorSetLayoutCreateInfo layoutInfo{};
  776. layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  777. layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
  778. layoutInfo.pBindings = bindings.data();
  779. if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS)
  780. throw love::Exception("failed to create descriptor set layout");
  781. }
  782. void Shader::createPipelineLayout()
  783. {
  784. VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
  785. pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  786. pipelineLayoutInfo.setLayoutCount = 1;
  787. pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
  788. pipelineLayoutInfo.pushConstantRangeCount = 0;
  789. if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS)
  790. throw love::Exception("failed to create pipeline layout");
  791. if (isCompute)
  792. {
  793. assert(shaderStages.size() == 1);
  794. VkComputePipelineCreateInfo computeInfo{};
  795. computeInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  796. computeInfo.stage = shaderStages.at(0);
  797. computeInfo.layout = pipelineLayout;
  798. if (vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &computeInfo, nullptr, &computePipeline) != VK_SUCCESS)
  799. throw love::Exception("failed to create compute pipeline");
  800. }
  801. }
  802. void Shader::createDescriptorPoolSizes()
  803. {
  804. if (!localUniformData.empty())
  805. {
  806. VkDescriptorPoolSize size{};
  807. size.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  808. size.descriptorCount = 1;
  809. descriptorPoolSizes.push_back(size);
  810. }
  811. for (const auto &entry : reflection.allUniforms)
  812. {
  813. if (!entry.second->active)
  814. continue;
  815. VkDescriptorPoolSize size{};
  816. auto type = Vulkan::getDescriptorType(entry.second->baseType);
  817. if (type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC)
  818. continue;
  819. size.type = type;
  820. size.descriptorCount = entry.second->count;
  821. descriptorPoolSizes.push_back(size);
  822. }
  823. }
  824. void Shader::setMainTex(graphics::Texture *texture)
  825. {
  826. const UniformInfo *u = builtinUniformInfo[BUILTIN_TEXTURE_MAIN];
  827. if (u != nullptr)
  828. {
  829. auto prevtexture = activeTextures[u->resourceIndex];
  830. if (texture != nullptr)
  831. texture->retain();
  832. if (prevtexture)
  833. prevtexture->release();
  834. activeTextures[u->resourceIndex] = texture;
  835. if (texture != prevtexture)
  836. setTextureDescriptor(u, texture, 0);
  837. }
  838. }
  839. void Shader::setTextureDescriptor(const UniformInfo *info, love::graphics::Texture *texture, int index)
  840. {
  841. auto vkTexture = dynamic_cast<Texture*>(texture);
  842. VkDescriptorImageInfo &imageInfo = descriptorImages[info->bindingStartIndex + index];
  843. // Samplers may change after this call, so they're set just before the
  844. // descriptor set is used instead of here.
  845. VkImageView view = vkTexture != nullptr ? (VkImageView)vkTexture->getRenderTargetHandle() : VK_NULL_HANDLE;
  846. if (view != imageInfo.imageView)
  847. {
  848. imageInfo.imageLayout = vkTexture != nullptr ? vkTexture->getImageLayout() : VK_IMAGE_LAYOUT_UNDEFINED;
  849. imageInfo.imageView = view;
  850. resourceDescriptorsDirty = true;
  851. }
  852. }
  853. void Shader::setBufferDescriptor(const UniformInfo *info, love::graphics::Buffer *buffer, int index)
  854. {
  855. if (info->baseType == UNIFORM_STORAGEBUFFER)
  856. {
  857. VkDescriptorBufferInfo &bufferInfo = descriptorBuffers[info->bindingStartIndex + index];
  858. VkBuffer vkbuffer = buffer != nullptr ? (VkBuffer)buffer->getHandle() : VK_NULL_HANDLE;
  859. VkDeviceSize range = buffer != nullptr ? buffer->getSize() : 0;
  860. if (vkbuffer != bufferInfo.buffer || bufferInfo.offset != 0 || range != bufferInfo.range)
  861. {
  862. bufferInfo.buffer = vkbuffer;
  863. bufferInfo.offset = 0;
  864. bufferInfo.range = range;
  865. resourceDescriptorsDirty = true;
  866. }
  867. }
  868. else if (info->baseType == UNIFORM_TEXELBUFFER)
  869. {
  870. VkBufferView view = buffer != nullptr ? (VkBufferView)buffer->getTexelBufferHandle() : VK_NULL_HANDLE;
  871. if (view != descriptorBufferViews[info->bindingStartIndex + index])
  872. {
  873. descriptorBufferViews[info->bindingStartIndex + index] = view;
  874. resourceDescriptorsDirty = true;
  875. }
  876. }
  877. }
  878. void Shader::createDescriptorPool()
  879. {
  880. VkDescriptorPoolCreateInfo createInfo{};
  881. createInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  882. createInfo.maxSets = DESCRIPTOR_POOL_SIZE;
  883. createInfo.poolSizeCount = static_cast<uint32_t>(descriptorPoolSizes.size());
  884. createInfo.pPoolSizes = descriptorPoolSizes.data();
  885. VkDescriptorPool pool;
  886. if (vkCreateDescriptorPool(device, &createInfo, nullptr, &pool) != VK_SUCCESS)
  887. throw love::Exception("failed to create descriptor pool");
  888. descriptorPools[currentFrame].push_back(pool);
  889. }
  890. VkDescriptorSet Shader::allocateDescriptorSet()
  891. {
  892. if (descriptorPools[currentFrame].empty())
  893. createDescriptorPool();
  894. while (true)
  895. {
  896. VkDescriptorSetAllocateInfo allocInfo{};
  897. allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  898. allocInfo.descriptorPool = descriptorPools[currentFrame][currentDescriptorPool];
  899. allocInfo.descriptorSetCount = 1;
  900. allocInfo.pSetLayouts = &descriptorSetLayout;
  901. VkDescriptorSet descriptorSet;
  902. VkResult result = vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet);
  903. switch (result)
  904. {
  905. case VK_SUCCESS:
  906. return descriptorSet;
  907. case VK_ERROR_OUT_OF_POOL_MEMORY:
  908. currentDescriptorPool++;
  909. if (descriptorPools[currentFrame].size() <= currentDescriptorPool)
  910. createDescriptorPool();
  911. continue;
  912. default:
  913. throw love::Exception("failed to allocate descriptor set");
  914. }
  915. }
  916. }
  917. VkPipeline Shader::getCachedGraphicsPipeline(Graphics *vgfx, const GraphicsPipelineConfigurationCore &configuration)
  918. {
  919. auto it = graphicsPipelinesDynamicState.find(configuration);
  920. if (it != graphicsPipelinesDynamicState.end())
  921. return it->second;
  922. VkPipeline pipeline = vgfx->createGraphicsPipeline(this, configuration, nullptr);
  923. graphicsPipelinesDynamicState.insert({ configuration, pipeline });
  924. return pipeline;
  925. }
  926. VkPipeline Shader::getCachedGraphicsPipeline(Graphics *vgfx, const GraphicsPipelineConfigurationFull &configuration)
  927. {
  928. auto it = graphicsPipelinesNoDynamicState.find(configuration);
  929. if (it != graphicsPipelinesNoDynamicState.end())
  930. return it->second;
  931. VkPipeline pipeline = vgfx->createGraphicsPipeline(this, configuration.core, &configuration.noDynamicState);
  932. graphicsPipelinesNoDynamicState.insert({ configuration, pipeline });
  933. return pipeline;
  934. }
  935. } // vulkan
  936. } // graphics
  937. } // love