shader_rd.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. /**************************************************************************/
  2. /* shader_rd.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "shader_rd.h"
  31. #include "core/io/compression.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/io/file_access.h"
  34. #include "core/object/worker_thread_pool.h"
  35. #include "core/version.h"
  36. #include "renderer_compositor_rd.h"
  37. #include "servers/rendering/rendering_device.h"
  38. #include "thirdparty/misc/smolv.h"
  39. void ShaderRD::_add_stage(const char *p_code, StageType p_stage_type) {
  40. Vector<String> lines = String(p_code).split("\n");
  41. String text;
  42. for (int i = 0; i < lines.size(); i++) {
  43. const String &l = lines[i];
  44. bool push_chunk = false;
  45. StageTemplate::Chunk chunk;
  46. if (l.begins_with("#VERSION_DEFINES")) {
  47. chunk.type = StageTemplate::Chunk::TYPE_VERSION_DEFINES;
  48. push_chunk = true;
  49. } else if (l.begins_with("#GLOBALS")) {
  50. switch (p_stage_type) {
  51. case STAGE_TYPE_VERTEX:
  52. chunk.type = StageTemplate::Chunk::TYPE_VERTEX_GLOBALS;
  53. break;
  54. case STAGE_TYPE_FRAGMENT:
  55. chunk.type = StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS;
  56. break;
  57. case STAGE_TYPE_COMPUTE:
  58. chunk.type = StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS;
  59. break;
  60. default: {
  61. }
  62. }
  63. push_chunk = true;
  64. } else if (l.begins_with("#MATERIAL_UNIFORMS")) {
  65. chunk.type = StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS;
  66. push_chunk = true;
  67. } else if (l.begins_with("#CODE")) {
  68. chunk.type = StageTemplate::Chunk::TYPE_CODE;
  69. push_chunk = true;
  70. chunk.code = l.replace_first("#CODE", String()).replace(":", "").strip_edges().to_upper();
  71. } else {
  72. text += l + "\n";
  73. }
  74. if (push_chunk) {
  75. if (!text.is_empty()) {
  76. StageTemplate::Chunk text_chunk;
  77. text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;
  78. text_chunk.text = text.utf8();
  79. stage_templates[p_stage_type].chunks.push_back(text_chunk);
  80. text = String();
  81. }
  82. stage_templates[p_stage_type].chunks.push_back(chunk);
  83. }
  84. }
  85. if (!text.is_empty()) {
  86. StageTemplate::Chunk text_chunk;
  87. text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;
  88. text_chunk.text = text.utf8();
  89. stage_templates[p_stage_type].chunks.push_back(text_chunk);
  90. text = String();
  91. }
  92. }
  93. void ShaderRD::setup(const char *p_vertex_code, const char *p_fragment_code, const char *p_compute_code, const char *p_name) {
  94. name = p_name;
  95. if (p_compute_code) {
  96. _add_stage(p_compute_code, STAGE_TYPE_COMPUTE);
  97. is_compute = true;
  98. } else {
  99. is_compute = false;
  100. if (p_vertex_code) {
  101. _add_stage(p_vertex_code, STAGE_TYPE_VERTEX);
  102. }
  103. if (p_fragment_code) {
  104. _add_stage(p_fragment_code, STAGE_TYPE_FRAGMENT);
  105. }
  106. }
  107. StringBuilder tohash;
  108. tohash.append("[GodotVersionNumber]");
  109. tohash.append(VERSION_NUMBER);
  110. tohash.append("[GodotVersionHash]");
  111. tohash.append(VERSION_HASH);
  112. tohash.append("[SpirvCacheKey]");
  113. tohash.append(RenderingDevice::get_singleton()->shader_get_spirv_cache_key());
  114. tohash.append("[BinaryCacheKey]");
  115. tohash.append(RenderingDevice::get_singleton()->shader_get_binary_cache_key());
  116. tohash.append("[Vertex]");
  117. tohash.append(p_vertex_code ? p_vertex_code : "");
  118. tohash.append("[Fragment]");
  119. tohash.append(p_fragment_code ? p_fragment_code : "");
  120. tohash.append("[Compute]");
  121. tohash.append(p_compute_code ? p_compute_code : "");
  122. base_sha256 = tohash.as_string().sha256_text();
  123. }
  124. RID ShaderRD::version_create() {
  125. //initialize() was never called
  126. ERR_FAIL_COND_V(group_to_variant_map.is_empty(), RID());
  127. Version version;
  128. version.dirty = true;
  129. version.valid = false;
  130. version.initialize_needed = true;
  131. version.variants = nullptr;
  132. return version_owner.make_rid(version);
  133. }
  134. void ShaderRD::_initialize_version(Version *p_version) {
  135. _clear_version(p_version);
  136. p_version->valid = false;
  137. p_version->dirty = false;
  138. p_version->variants = memnew_arr(RID, variant_defines.size());
  139. }
  140. void ShaderRD::_clear_version(Version *p_version) {
  141. // Clear versions if they exist.
  142. if (p_version->variants) {
  143. for (int i = 0; i < variant_defines.size(); i++) {
  144. if (p_version->variants[i].is_valid()) {
  145. RD::get_singleton()->free(p_version->variants[i]);
  146. }
  147. }
  148. memdelete_arr(p_version->variants);
  149. if (p_version->variant_data) {
  150. memdelete_arr(p_version->variant_data);
  151. }
  152. p_version->variants = nullptr;
  153. }
  154. }
  155. void ShaderRD::_build_variant_code(StringBuilder &builder, uint32_t p_variant, const Version *p_version, const StageTemplate &p_template) {
  156. for (const StageTemplate::Chunk &chunk : p_template.chunks) {
  157. switch (chunk.type) {
  158. case StageTemplate::Chunk::TYPE_VERSION_DEFINES: {
  159. builder.append("\n"); //make sure defines begin at newline
  160. builder.append(general_defines.get_data());
  161. builder.append(variant_defines[p_variant].text.get_data());
  162. for (int j = 0; j < p_version->custom_defines.size(); j++) {
  163. builder.append(p_version->custom_defines[j].get_data());
  164. }
  165. builder.append("\n"); //make sure defines begin at newline
  166. if (p_version->uniforms.size()) {
  167. builder.append("#define MATERIAL_UNIFORMS_USED\n");
  168. }
  169. for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {
  170. builder.append(String("#define ") + String(E.key) + "_CODE_USED\n");
  171. }
  172. #if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
  173. builder.append("#define MOLTENVK_USED\n");
  174. #endif
  175. builder.append(String("#define RENDER_DRIVER_") + OS::get_singleton()->get_current_rendering_driver_name().to_upper() + "\n");
  176. } break;
  177. case StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS: {
  178. builder.append(p_version->uniforms.get_data()); //uniforms (same for vertex and fragment)
  179. } break;
  180. case StageTemplate::Chunk::TYPE_VERTEX_GLOBALS: {
  181. builder.append(p_version->vertex_globals.get_data()); // vertex globals
  182. } break;
  183. case StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS: {
  184. builder.append(p_version->fragment_globals.get_data()); // fragment globals
  185. } break;
  186. case StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS: {
  187. builder.append(p_version->compute_globals.get_data()); // compute globals
  188. } break;
  189. case StageTemplate::Chunk::TYPE_CODE: {
  190. if (p_version->code_sections.has(chunk.code)) {
  191. builder.append(p_version->code_sections[chunk.code].get_data());
  192. }
  193. } break;
  194. case StageTemplate::Chunk::TYPE_TEXT: {
  195. builder.append(chunk.text.get_data());
  196. } break;
  197. }
  198. }
  199. }
  200. void ShaderRD::_compile_variant(uint32_t p_variant, const CompileData *p_data) {
  201. uint32_t variant = group_to_variant_map[p_data->group][p_variant];
  202. if (!variants_enabled[variant]) {
  203. return; // Variant is disabled, return.
  204. }
  205. Vector<RD::ShaderStageSPIRVData> stages;
  206. String error;
  207. String current_source;
  208. RD::ShaderStage current_stage = RD::SHADER_STAGE_VERTEX;
  209. bool build_ok = true;
  210. if (!is_compute) {
  211. //vertex stage
  212. StringBuilder builder;
  213. _build_variant_code(builder, variant, p_data->version, stage_templates[STAGE_TYPE_VERTEX]);
  214. current_source = builder.as_string();
  215. RD::ShaderStageSPIRVData stage;
  216. stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_VERTEX, current_source, RD::SHADER_LANGUAGE_GLSL, &error);
  217. if (stage.spirv.size() == 0) {
  218. build_ok = false;
  219. } else {
  220. stage.shader_stage = RD::SHADER_STAGE_VERTEX;
  221. stages.push_back(stage);
  222. }
  223. }
  224. if (!is_compute && build_ok) {
  225. //fragment stage
  226. current_stage = RD::SHADER_STAGE_FRAGMENT;
  227. StringBuilder builder;
  228. _build_variant_code(builder, variant, p_data->version, stage_templates[STAGE_TYPE_FRAGMENT]);
  229. current_source = builder.as_string();
  230. RD::ShaderStageSPIRVData stage;
  231. stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_FRAGMENT, current_source, RD::SHADER_LANGUAGE_GLSL, &error);
  232. if (stage.spirv.size() == 0) {
  233. build_ok = false;
  234. } else {
  235. stage.shader_stage = RD::SHADER_STAGE_FRAGMENT;
  236. stages.push_back(stage);
  237. }
  238. }
  239. if (is_compute) {
  240. //compute stage
  241. current_stage = RD::SHADER_STAGE_COMPUTE;
  242. StringBuilder builder;
  243. _build_variant_code(builder, variant, p_data->version, stage_templates[STAGE_TYPE_COMPUTE]);
  244. current_source = builder.as_string();
  245. RD::ShaderStageSPIRVData stage;
  246. stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_COMPUTE, current_source, RD::SHADER_LANGUAGE_GLSL, &error);
  247. if (stage.spirv.size() == 0) {
  248. build_ok = false;
  249. } else {
  250. stage.shader_stage = RD::SHADER_STAGE_COMPUTE;
  251. stages.push_back(stage);
  252. }
  253. }
  254. if (!build_ok) {
  255. MutexLock lock(variant_set_mutex); //properly print the errors
  256. ERR_PRINT("Error compiling " + String(current_stage == RD::SHADER_STAGE_COMPUTE ? "Compute " : (current_stage == RD::SHADER_STAGE_VERTEX ? "Vertex" : "Fragment")) + " shader, variant #" + itos(variant) + " (" + variant_defines[variant].text.get_data() + ").");
  257. ERR_PRINT(error);
  258. #ifdef DEBUG_ENABLED
  259. ERR_PRINT("code:\n" + current_source.get_with_code_lines());
  260. #endif
  261. return;
  262. }
  263. Vector<uint8_t> shader_data = RD::get_singleton()->shader_compile_binary_from_spirv(stages, name + ":" + itos(variant));
  264. ERR_FAIL_COND(shader_data.is_empty());
  265. {
  266. MutexLock lock(variant_set_mutex);
  267. p_data->version->variants[variant] = RD::get_singleton()->shader_create_from_bytecode(shader_data, p_data->version->variants[variant]);
  268. p_data->version->variant_data[variant] = shader_data;
  269. }
  270. }
  271. RS::ShaderNativeSourceCode ShaderRD::version_get_native_source_code(RID p_version) {
  272. Version *version = version_owner.get_or_null(p_version);
  273. RS::ShaderNativeSourceCode source_code;
  274. ERR_FAIL_NULL_V(version, source_code);
  275. source_code.versions.resize(variant_defines.size());
  276. for (int i = 0; i < source_code.versions.size(); i++) {
  277. if (!is_compute) {
  278. //vertex stage
  279. StringBuilder builder;
  280. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_VERTEX]);
  281. RS::ShaderNativeSourceCode::Version::Stage stage;
  282. stage.name = "vertex";
  283. stage.code = builder.as_string();
  284. source_code.versions.write[i].stages.push_back(stage);
  285. }
  286. if (!is_compute) {
  287. //fragment stage
  288. StringBuilder builder;
  289. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_FRAGMENT]);
  290. RS::ShaderNativeSourceCode::Version::Stage stage;
  291. stage.name = "fragment";
  292. stage.code = builder.as_string();
  293. source_code.versions.write[i].stages.push_back(stage);
  294. }
  295. if (is_compute) {
  296. //compute stage
  297. StringBuilder builder;
  298. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_COMPUTE]);
  299. RS::ShaderNativeSourceCode::Version::Stage stage;
  300. stage.name = "compute";
  301. stage.code = builder.as_string();
  302. source_code.versions.write[i].stages.push_back(stage);
  303. }
  304. }
  305. return source_code;
  306. }
  307. String ShaderRD::_version_get_sha1(Version *p_version) const {
  308. StringBuilder hash_build;
  309. hash_build.append("[uniforms]");
  310. hash_build.append(p_version->uniforms.get_data());
  311. hash_build.append("[vertex_globals]");
  312. hash_build.append(p_version->vertex_globals.get_data());
  313. hash_build.append("[fragment_globals]");
  314. hash_build.append(p_version->fragment_globals.get_data());
  315. hash_build.append("[compute_globals]");
  316. hash_build.append(p_version->compute_globals.get_data());
  317. Vector<StringName> code_sections;
  318. for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {
  319. code_sections.push_back(E.key);
  320. }
  321. code_sections.sort_custom<StringName::AlphCompare>();
  322. for (int i = 0; i < code_sections.size(); i++) {
  323. hash_build.append(String("[code:") + String(code_sections[i]) + "]");
  324. hash_build.append(p_version->code_sections[code_sections[i]].get_data());
  325. }
  326. for (int i = 0; i < p_version->custom_defines.size(); i++) {
  327. hash_build.append("[custom_defines:" + itos(i) + "]");
  328. hash_build.append(p_version->custom_defines[i].get_data());
  329. }
  330. return hash_build.as_string().sha1_text();
  331. }
  332. static const char *shader_file_header = "GDSC";
  333. static const uint32_t cache_file_version = 3;
  334. String ShaderRD::_get_cache_file_path(Version *p_version, int p_group) {
  335. const String &sha1 = _version_get_sha1(p_version);
  336. const String &api_safe_name = String(RD::get_singleton()->get_device_api_name()).validate_filename().to_lower();
  337. const String &path = shader_cache_dir.path_join(name).path_join(group_sha256[p_group]).path_join(sha1) + "." + api_safe_name + ".cache";
  338. return path;
  339. }
  340. bool ShaderRD::_load_from_cache(Version *p_version, int p_group) {
  341. const String &path = _get_cache_file_path(p_version, p_group);
  342. Ref<FileAccess> f = FileAccess::open(path, FileAccess::READ);
  343. if (f.is_null()) {
  344. return false;
  345. }
  346. char header[5] = { 0, 0, 0, 0, 0 };
  347. f->get_buffer((uint8_t *)header, 4);
  348. ERR_FAIL_COND_V(header != String(shader_file_header), false);
  349. uint32_t file_version = f->get_32();
  350. if (file_version != cache_file_version) {
  351. return false; // wrong version
  352. }
  353. uint32_t variant_count = f->get_32();
  354. ERR_FAIL_COND_V(variant_count != (uint32_t)group_to_variant_map[p_group].size(), false); //should not happen but check
  355. for (uint32_t i = 0; i < variant_count; i++) {
  356. int variant_id = group_to_variant_map[p_group][i];
  357. uint32_t variant_size = f->get_32();
  358. ERR_FAIL_COND_V(variant_size == 0 && variants_enabled[variant_id], false);
  359. if (!variants_enabled[variant_id]) {
  360. continue;
  361. }
  362. Vector<uint8_t> variant_bytes;
  363. variant_bytes.resize(variant_size);
  364. uint32_t br = f->get_buffer(variant_bytes.ptrw(), variant_size);
  365. ERR_FAIL_COND_V(br != variant_size, false);
  366. p_version->variant_data[variant_id] = variant_bytes;
  367. }
  368. for (uint32_t i = 0; i < variant_count; i++) {
  369. int variant_id = group_to_variant_map[p_group][i];
  370. if (!variants_enabled[variant_id]) {
  371. MutexLock lock(variant_set_mutex);
  372. p_version->variants[variant_id] = RID();
  373. continue;
  374. }
  375. {
  376. MutexLock lock(variant_set_mutex);
  377. RID shader = RD::get_singleton()->shader_create_from_bytecode(p_version->variant_data[variant_id], p_version->variants[variant_id]);
  378. if (shader.is_null()) {
  379. for (uint32_t j = 0; j < i; j++) {
  380. int variant_free_id = group_to_variant_map[p_group][j];
  381. RD::get_singleton()->free(p_version->variants[variant_free_id]);
  382. }
  383. ERR_FAIL_COND_V(shader.is_null(), false);
  384. }
  385. p_version->variants[variant_id] = shader;
  386. }
  387. }
  388. memdelete_arr(p_version->variant_data); //clear stages
  389. p_version->variant_data = nullptr;
  390. p_version->valid = true;
  391. return true;
  392. }
  393. void ShaderRD::_save_to_cache(Version *p_version, int p_group) {
  394. ERR_FAIL_COND(!shader_cache_dir_valid);
  395. const String &path = _get_cache_file_path(p_version, p_group);
  396. Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE);
  397. ERR_FAIL_COND(f.is_null());
  398. f->store_buffer((const uint8_t *)shader_file_header, 4);
  399. f->store_32(cache_file_version); // File version.
  400. uint32_t variant_count = group_to_variant_map[p_group].size();
  401. f->store_32(variant_count); // Variant count.
  402. for (uint32_t i = 0; i < variant_count; i++) {
  403. int variant_id = group_to_variant_map[p_group][i];
  404. f->store_32(p_version->variant_data[variant_id].size()); // Stage count.
  405. f->store_buffer(p_version->variant_data[variant_id].ptr(), p_version->variant_data[variant_id].size());
  406. }
  407. }
  408. void ShaderRD::_allocate_placeholders(Version *p_version, int p_group) {
  409. ERR_FAIL_NULL(p_version->variants);
  410. for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {
  411. int variant_id = group_to_variant_map[p_group][i];
  412. RID shader = RD::get_singleton()->shader_create_placeholder();
  413. {
  414. MutexLock lock(variant_set_mutex);
  415. p_version->variants[variant_id] = shader;
  416. }
  417. }
  418. }
  419. // Try to compile all variants for a given group.
  420. // Will skip variants that are disabled.
  421. void ShaderRD::_compile_version(Version *p_version, int p_group) {
  422. if (!group_enabled[p_group]) {
  423. return;
  424. }
  425. typedef Vector<uint8_t> ShaderStageData;
  426. p_version->variant_data = memnew_arr(ShaderStageData, variant_defines.size());
  427. p_version->dirty = false;
  428. if (shader_cache_dir_valid) {
  429. if (_load_from_cache(p_version, p_group)) {
  430. return;
  431. }
  432. }
  433. CompileData compile_data;
  434. compile_data.version = p_version;
  435. compile_data.group = p_group;
  436. #if 1
  437. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &ShaderRD::_compile_variant, &compile_data, group_to_variant_map[p_group].size(), -1, true, SNAME("ShaderCompilation"));
  438. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  439. #else
  440. for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {
  441. _compile_variant(i, &compile_data);
  442. }
  443. #endif
  444. bool all_valid = true;
  445. for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {
  446. int variant_id = group_to_variant_map[p_group][i];
  447. if (!variants_enabled[variant_id]) {
  448. continue; // Disabled.
  449. }
  450. if (p_version->variants[variant_id].is_null()) {
  451. all_valid = false;
  452. break;
  453. }
  454. }
  455. if (!all_valid) {
  456. // Clear versions if they exist.
  457. for (int i = 0; i < variant_defines.size(); i++) {
  458. if (!variants_enabled[i] || !group_enabled[variant_defines[i].group]) {
  459. continue; // Disabled.
  460. }
  461. if (!p_version->variants[i].is_null()) {
  462. RD::get_singleton()->free(p_version->variants[i]);
  463. }
  464. }
  465. memdelete_arr(p_version->variants);
  466. if (p_version->variant_data) {
  467. memdelete_arr(p_version->variant_data);
  468. }
  469. p_version->variants = nullptr;
  470. p_version->variant_data = nullptr;
  471. return;
  472. } else if (shader_cache_dir_valid) {
  473. // Save shader cache.
  474. _save_to_cache(p_version, p_group);
  475. }
  476. memdelete_arr(p_version->variant_data); //clear stages
  477. p_version->variant_data = nullptr;
  478. p_version->valid = true;
  479. }
  480. void ShaderRD::version_set_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_vertex_globals, const String &p_fragment_globals, const Vector<String> &p_custom_defines) {
  481. ERR_FAIL_COND(is_compute);
  482. Version *version = version_owner.get_or_null(p_version);
  483. ERR_FAIL_NULL(version);
  484. version->vertex_globals = p_vertex_globals.utf8();
  485. version->fragment_globals = p_fragment_globals.utf8();
  486. version->uniforms = p_uniforms.utf8();
  487. version->code_sections.clear();
  488. for (const KeyValue<String, String> &E : p_code) {
  489. version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();
  490. }
  491. version->custom_defines.clear();
  492. for (int i = 0; i < p_custom_defines.size(); i++) {
  493. version->custom_defines.push_back(p_custom_defines[i].utf8());
  494. }
  495. version->dirty = true;
  496. if (version->initialize_needed) {
  497. _initialize_version(version);
  498. for (int i = 0; i < group_enabled.size(); i++) {
  499. if (!group_enabled[i]) {
  500. _allocate_placeholders(version, i);
  501. continue;
  502. }
  503. _compile_version(version, i);
  504. }
  505. version->initialize_needed = false;
  506. }
  507. }
  508. void ShaderRD::version_set_compute_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_compute_globals, const Vector<String> &p_custom_defines) {
  509. ERR_FAIL_COND(!is_compute);
  510. Version *version = version_owner.get_or_null(p_version);
  511. ERR_FAIL_NULL(version);
  512. version->compute_globals = p_compute_globals.utf8();
  513. version->uniforms = p_uniforms.utf8();
  514. version->code_sections.clear();
  515. for (const KeyValue<String, String> &E : p_code) {
  516. version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();
  517. }
  518. version->custom_defines.clear();
  519. for (int i = 0; i < p_custom_defines.size(); i++) {
  520. version->custom_defines.push_back(p_custom_defines[i].utf8());
  521. }
  522. version->dirty = true;
  523. if (version->initialize_needed) {
  524. _initialize_version(version);
  525. for (int i = 0; i < group_enabled.size(); i++) {
  526. if (!group_enabled[i]) {
  527. _allocate_placeholders(version, i);
  528. continue;
  529. }
  530. _compile_version(version, i);
  531. }
  532. version->initialize_needed = false;
  533. }
  534. }
  535. bool ShaderRD::version_is_valid(RID p_version) {
  536. Version *version = version_owner.get_or_null(p_version);
  537. ERR_FAIL_NULL_V(version, false);
  538. if (version->dirty) {
  539. _initialize_version(version);
  540. for (int i = 0; i < group_enabled.size(); i++) {
  541. if (!group_enabled[i]) {
  542. _allocate_placeholders(version, i);
  543. continue;
  544. }
  545. _compile_version(version, i);
  546. }
  547. }
  548. return version->valid;
  549. }
  550. bool ShaderRD::version_free(RID p_version) {
  551. if (version_owner.owns(p_version)) {
  552. Version *version = version_owner.get_or_null(p_version);
  553. _clear_version(version);
  554. version_owner.free(p_version);
  555. } else {
  556. return false;
  557. }
  558. return true;
  559. }
  560. void ShaderRD::set_variant_enabled(int p_variant, bool p_enabled) {
  561. ERR_FAIL_COND(version_owner.get_rid_count() > 0); //versions exist
  562. ERR_FAIL_INDEX(p_variant, variants_enabled.size());
  563. variants_enabled.write[p_variant] = p_enabled;
  564. }
  565. bool ShaderRD::is_variant_enabled(int p_variant) const {
  566. ERR_FAIL_INDEX_V(p_variant, variants_enabled.size(), false);
  567. return variants_enabled[p_variant];
  568. }
  569. void ShaderRD::enable_group(int p_group) {
  570. ERR_FAIL_INDEX(p_group, group_enabled.size());
  571. if (group_enabled[p_group]) {
  572. // Group already enabled, do nothing.
  573. return;
  574. }
  575. group_enabled.write[p_group] = true;
  576. // Compile all versions again to include the new group.
  577. List<RID> all_versions;
  578. version_owner.get_owned_list(&all_versions);
  579. for (const RID &E : all_versions) {
  580. Version *version = version_owner.get_or_null(E);
  581. _compile_version(version, p_group);
  582. }
  583. }
  584. bool ShaderRD::is_group_enabled(int p_group) const {
  585. return group_enabled[p_group];
  586. }
  587. bool ShaderRD::shader_cache_cleanup_on_start = false;
  588. ShaderRD::ShaderRD() {
  589. // Do not feel forced to use this, in most cases it makes little to no difference.
  590. bool use_32_threads = false;
  591. if (RD::get_singleton()->get_device_vendor_name() == "NVIDIA") {
  592. use_32_threads = true;
  593. }
  594. String base_compute_define_text;
  595. if (use_32_threads) {
  596. base_compute_define_text = "\n#define NATIVE_LOCAL_GROUP_SIZE 32\n#define NATIVE_LOCAL_SIZE_2D_X 8\n#define NATIVE_LOCAL_SIZE_2D_Y 4\n";
  597. } else {
  598. base_compute_define_text = "\n#define NATIVE_LOCAL_GROUP_SIZE 64\n#define NATIVE_LOCAL_SIZE_2D_X 8\n#define NATIVE_LOCAL_SIZE_2D_Y 8\n";
  599. }
  600. base_compute_defines = base_compute_define_text.ascii();
  601. }
  602. void ShaderRD::initialize(const Vector<String> &p_variant_defines, const String &p_general_defines) {
  603. ERR_FAIL_COND(variant_defines.size());
  604. ERR_FAIL_COND(p_variant_defines.is_empty());
  605. general_defines = p_general_defines.utf8();
  606. // When initialized this way, there is just one group and its always enabled.
  607. group_to_variant_map.insert(0, LocalVector<int>{});
  608. group_enabled.push_back(true);
  609. for (int i = 0; i < p_variant_defines.size(); i++) {
  610. variant_defines.push_back(VariantDefine(0, p_variant_defines[i], true));
  611. variants_enabled.push_back(true);
  612. group_to_variant_map[0].push_back(i);
  613. }
  614. if (!shader_cache_dir.is_empty()) {
  615. group_sha256.resize(1);
  616. _initialize_cache();
  617. }
  618. }
  619. void ShaderRD::_initialize_cache() {
  620. for (const KeyValue<int, LocalVector<int>> &E : group_to_variant_map) {
  621. StringBuilder hash_build;
  622. hash_build.append("[base_hash]");
  623. hash_build.append(base_sha256);
  624. hash_build.append("[general_defines]");
  625. hash_build.append(general_defines.get_data());
  626. hash_build.append("[group_id]");
  627. hash_build.append(itos(E.key));
  628. for (uint32_t i = 0; i < E.value.size(); i++) {
  629. hash_build.append("[variant_defines:" + itos(E.value[i]) + "]");
  630. hash_build.append(variant_defines[E.value[i]].text.get_data());
  631. }
  632. group_sha256[E.key] = hash_build.as_string().sha256_text();
  633. Ref<DirAccess> d = DirAccess::open(shader_cache_dir);
  634. ERR_FAIL_COND(d.is_null());
  635. if (d->change_dir(name) != OK) {
  636. Error err = d->make_dir(name);
  637. ERR_FAIL_COND(err != OK);
  638. d->change_dir(name);
  639. }
  640. // Erase other versions?
  641. if (shader_cache_cleanup_on_start) {
  642. }
  643. //
  644. if (d->change_dir(group_sha256[E.key]) != OK) {
  645. Error err = d->make_dir(group_sha256[E.key]);
  646. ERR_FAIL_COND(err != OK);
  647. }
  648. shader_cache_dir_valid = true;
  649. print_verbose("Shader '" + name + "' (group " + itos(E.key) + ") SHA256: " + group_sha256[E.key]);
  650. }
  651. }
  652. // Same as above, but allows specifying shader compilation groups.
  653. void ShaderRD::initialize(const Vector<VariantDefine> &p_variant_defines, const String &p_general_defines) {
  654. ERR_FAIL_COND(variant_defines.size());
  655. ERR_FAIL_COND(p_variant_defines.is_empty());
  656. general_defines = p_general_defines.utf8();
  657. int max_group_id = 0;
  658. for (int i = 0; i < p_variant_defines.size(); i++) {
  659. // Fill variant array.
  660. variant_defines.push_back(p_variant_defines[i]);
  661. variants_enabled.push_back(true);
  662. // Map variant array index to group id, so we can iterate over groups later.
  663. if (!group_to_variant_map.has(p_variant_defines[i].group)) {
  664. group_to_variant_map.insert(p_variant_defines[i].group, LocalVector<int>{});
  665. }
  666. group_to_variant_map[p_variant_defines[i].group].push_back(i);
  667. // Track max size.
  668. if (p_variant_defines[i].group > max_group_id) {
  669. max_group_id = p_variant_defines[i].group;
  670. }
  671. }
  672. // Set all to groups to false, then enable those that should be default.
  673. group_enabled.resize_zeroed(max_group_id + 1);
  674. bool *enabled_ptr = group_enabled.ptrw();
  675. for (int i = 0; i < p_variant_defines.size(); i++) {
  676. if (p_variant_defines[i].default_enabled) {
  677. enabled_ptr[p_variant_defines[i].group] = true;
  678. }
  679. }
  680. if (!shader_cache_dir.is_empty()) {
  681. group_sha256.resize(max_group_id + 1);
  682. _initialize_cache();
  683. }
  684. }
  685. void ShaderRD::set_shader_cache_dir(const String &p_dir) {
  686. shader_cache_dir = p_dir;
  687. }
  688. void ShaderRD::set_shader_cache_save_compressed(bool p_enable) {
  689. shader_cache_save_compressed = p_enable;
  690. }
  691. void ShaderRD::set_shader_cache_save_compressed_zstd(bool p_enable) {
  692. shader_cache_save_compressed_zstd = p_enable;
  693. }
  694. void ShaderRD::set_shader_cache_save_debug(bool p_enable) {
  695. shader_cache_save_debug = p_enable;
  696. }
  697. String ShaderRD::shader_cache_dir;
  698. bool ShaderRD::shader_cache_save_compressed = true;
  699. bool ShaderRD::shader_cache_save_compressed_zstd = true;
  700. bool ShaderRD::shader_cache_save_debug = true;
  701. ShaderRD::~ShaderRD() {
  702. List<RID> remaining;
  703. version_owner.get_owned_list(&remaining);
  704. if (remaining.size()) {
  705. ERR_PRINT(itos(remaining.size()) + " shaders of type " + name + " were never freed");
  706. while (remaining.size()) {
  707. version_free(remaining.front()->get());
  708. remaining.pop_front();
  709. }
  710. }
  711. }