shader_rd.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. /*************************************************************************/
  2. /* shader_rd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 "renderer_compositor_rd.h"
  35. #include "servers/rendering/rendering_device.h"
  36. #include "thirdparty/misc/smolv.h"
  37. void ShaderRD::_add_stage(const char *p_code, StageType p_stage_type) {
  38. Vector<String> lines = String(p_code).split("\n");
  39. String text;
  40. for (int i = 0; i < lines.size(); i++) {
  41. String l = lines[i];
  42. bool push_chunk = false;
  43. StageTemplate::Chunk chunk;
  44. if (l.begins_with("#VERSION_DEFINES")) {
  45. chunk.type = StageTemplate::Chunk::TYPE_VERSION_DEFINES;
  46. push_chunk = true;
  47. } else if (l.begins_with("#GLOBALS")) {
  48. switch (p_stage_type) {
  49. case STAGE_TYPE_VERTEX:
  50. chunk.type = StageTemplate::Chunk::TYPE_VERTEX_GLOBALS;
  51. break;
  52. case STAGE_TYPE_FRAGMENT:
  53. chunk.type = StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS;
  54. break;
  55. case STAGE_TYPE_COMPUTE:
  56. chunk.type = StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS;
  57. break;
  58. default: {
  59. }
  60. }
  61. push_chunk = true;
  62. } else if (l.begins_with("#MATERIAL_UNIFORMS")) {
  63. chunk.type = StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS;
  64. push_chunk = true;
  65. } else if (l.begins_with("#CODE")) {
  66. chunk.type = StageTemplate::Chunk::TYPE_CODE;
  67. push_chunk = true;
  68. chunk.code = l.replace_first("#CODE", String()).replace(":", "").strip_edges().to_upper();
  69. } else {
  70. text += l + "\n";
  71. }
  72. if (push_chunk) {
  73. if (!text.is_empty()) {
  74. StageTemplate::Chunk text_chunk;
  75. text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;
  76. text_chunk.text = text.utf8();
  77. stage_templates[p_stage_type].chunks.push_back(text_chunk);
  78. text = String();
  79. }
  80. stage_templates[p_stage_type].chunks.push_back(chunk);
  81. }
  82. }
  83. if (!text.is_empty()) {
  84. StageTemplate::Chunk text_chunk;
  85. text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;
  86. text_chunk.text = text.utf8();
  87. stage_templates[p_stage_type].chunks.push_back(text_chunk);
  88. text = String();
  89. }
  90. }
  91. void ShaderRD::setup(const char *p_vertex_code, const char *p_fragment_code, const char *p_compute_code, const char *p_name) {
  92. name = p_name;
  93. if (p_compute_code) {
  94. _add_stage(p_compute_code, STAGE_TYPE_COMPUTE);
  95. is_compute = true;
  96. } else {
  97. is_compute = false;
  98. if (p_vertex_code) {
  99. _add_stage(p_vertex_code, STAGE_TYPE_VERTEX);
  100. }
  101. if (p_fragment_code) {
  102. _add_stage(p_fragment_code, STAGE_TYPE_FRAGMENT);
  103. }
  104. }
  105. StringBuilder tohash;
  106. tohash.append("[SpirvCacheKey]");
  107. tohash.append(RenderingDevice::get_singleton()->shader_get_spirv_cache_key());
  108. tohash.append("[BinaryCacheKey]");
  109. tohash.append(RenderingDevice::get_singleton()->shader_get_binary_cache_key());
  110. tohash.append("[Vertex]");
  111. tohash.append(p_vertex_code ? p_vertex_code : "");
  112. tohash.append("[Fragment]");
  113. tohash.append(p_fragment_code ? p_fragment_code : "");
  114. tohash.append("[Compute]");
  115. tohash.append(p_compute_code ? p_compute_code : "");
  116. base_sha256 = tohash.as_string().sha256_text();
  117. }
  118. RID ShaderRD::version_create() {
  119. //initialize() was never called
  120. ERR_FAIL_COND_V(variant_defines.size() == 0, RID());
  121. Version version;
  122. version.dirty = true;
  123. version.valid = false;
  124. version.initialize_needed = true;
  125. version.variants = nullptr;
  126. return version_owner.make_rid(version);
  127. }
  128. void ShaderRD::_clear_version(Version *p_version) {
  129. //clear versions if they exist
  130. if (p_version->variants) {
  131. for (int i = 0; i < variant_defines.size(); i++) {
  132. if (variants_enabled[i]) {
  133. RD::get_singleton()->free(p_version->variants[i]);
  134. }
  135. }
  136. memdelete_arr(p_version->variants);
  137. if (p_version->variant_data) {
  138. memdelete_arr(p_version->variant_data);
  139. }
  140. p_version->variants = nullptr;
  141. }
  142. }
  143. void ShaderRD::_build_variant_code(StringBuilder &builder, uint32_t p_variant, const Version *p_version, const StageTemplate &p_template) {
  144. for (uint32_t i = 0; i < p_template.chunks.size(); i++) {
  145. const StageTemplate::Chunk &chunk = p_template.chunks[i];
  146. switch (chunk.type) {
  147. case StageTemplate::Chunk::TYPE_VERSION_DEFINES: {
  148. builder.append("\n"); //make sure defines begin at newline
  149. builder.append(general_defines.get_data());
  150. builder.append(variant_defines[p_variant].get_data());
  151. for (int j = 0; j < p_version->custom_defines.size(); j++) {
  152. builder.append(p_version->custom_defines[j].get_data());
  153. }
  154. builder.append("\n"); //make sure defines begin at newline
  155. if (p_version->uniforms.size()) {
  156. builder.append("#define MATERIAL_UNIFORMS_USED\n");
  157. }
  158. for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {
  159. builder.append(String("#define ") + String(E.key) + "_CODE_USED\n");
  160. }
  161. #if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
  162. builder.append("#define MOLTENVK_USED\n");
  163. #endif
  164. } break;
  165. case StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS: {
  166. builder.append(p_version->uniforms.get_data()); //uniforms (same for vertex and fragment)
  167. } break;
  168. case StageTemplate::Chunk::TYPE_VERTEX_GLOBALS: {
  169. builder.append(p_version->vertex_globals.get_data()); // vertex globals
  170. } break;
  171. case StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS: {
  172. builder.append(p_version->fragment_globals.get_data()); // fragment globals
  173. } break;
  174. case StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS: {
  175. builder.append(p_version->compute_globals.get_data()); // compute globals
  176. } break;
  177. case StageTemplate::Chunk::TYPE_CODE: {
  178. if (p_version->code_sections.has(chunk.code)) {
  179. builder.append(p_version->code_sections[chunk.code].get_data());
  180. }
  181. } break;
  182. case StageTemplate::Chunk::TYPE_TEXT: {
  183. builder.append(chunk.text.get_data());
  184. } break;
  185. }
  186. }
  187. }
  188. void ShaderRD::_compile_variant(uint32_t p_variant, Version *p_version) {
  189. if (!variants_enabled[p_variant]) {
  190. return; //variant is disabled, return
  191. }
  192. Vector<RD::ShaderStageSPIRVData> stages;
  193. String error;
  194. String current_source;
  195. RD::ShaderStage current_stage = RD::SHADER_STAGE_VERTEX;
  196. bool build_ok = true;
  197. if (!is_compute) {
  198. //vertex stage
  199. StringBuilder builder;
  200. _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_VERTEX]);
  201. current_source = builder.as_string();
  202. RD::ShaderStageSPIRVData stage;
  203. stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_VERTEX, current_source, RD::SHADER_LANGUAGE_GLSL, &error);
  204. if (stage.spir_v.size() == 0) {
  205. build_ok = false;
  206. } else {
  207. stage.shader_stage = RD::SHADER_STAGE_VERTEX;
  208. stages.push_back(stage);
  209. }
  210. }
  211. if (!is_compute && build_ok) {
  212. //fragment stage
  213. current_stage = RD::SHADER_STAGE_FRAGMENT;
  214. StringBuilder builder;
  215. _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_FRAGMENT]);
  216. current_source = builder.as_string();
  217. RD::ShaderStageSPIRVData stage;
  218. stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_FRAGMENT, current_source, RD::SHADER_LANGUAGE_GLSL, &error);
  219. if (stage.spir_v.size() == 0) {
  220. build_ok = false;
  221. } else {
  222. stage.shader_stage = RD::SHADER_STAGE_FRAGMENT;
  223. stages.push_back(stage);
  224. }
  225. }
  226. if (is_compute) {
  227. //compute stage
  228. current_stage = RD::SHADER_STAGE_COMPUTE;
  229. StringBuilder builder;
  230. _build_variant_code(builder, p_variant, p_version, stage_templates[STAGE_TYPE_COMPUTE]);
  231. current_source = builder.as_string();
  232. RD::ShaderStageSPIRVData stage;
  233. stage.spir_v = RD::get_singleton()->shader_compile_spirv_from_source(RD::SHADER_STAGE_COMPUTE, current_source, RD::SHADER_LANGUAGE_GLSL, &error);
  234. if (stage.spir_v.size() == 0) {
  235. build_ok = false;
  236. } else {
  237. stage.shader_stage = RD::SHADER_STAGE_COMPUTE;
  238. stages.push_back(stage);
  239. }
  240. }
  241. if (!build_ok) {
  242. MutexLock lock(variant_set_mutex); //properly print the errors
  243. ERR_PRINT("Error compiling " + String(current_stage == RD::SHADER_STAGE_COMPUTE ? "Compute " : (current_stage == RD::SHADER_STAGE_VERTEX ? "Vertex" : "Fragment")) + " shader, variant #" + itos(p_variant) + " (" + variant_defines[p_variant].get_data() + ").");
  244. ERR_PRINT(error);
  245. #ifdef DEBUG_ENABLED
  246. ERR_PRINT("code:\n" + current_source.get_with_code_lines());
  247. #endif
  248. return;
  249. }
  250. Vector<uint8_t> shader_data = RD::get_singleton()->shader_compile_binary_from_spirv(stages, name + ":" + itos(p_variant));
  251. ERR_FAIL_COND(shader_data.size() == 0);
  252. RID shader = RD::get_singleton()->shader_create_from_bytecode(shader_data);
  253. {
  254. MutexLock lock(variant_set_mutex);
  255. p_version->variants[p_variant] = shader;
  256. p_version->variant_data[p_variant] = shader_data;
  257. }
  258. }
  259. RS::ShaderNativeSourceCode ShaderRD::version_get_native_source_code(RID p_version) {
  260. Version *version = version_owner.get_or_null(p_version);
  261. RS::ShaderNativeSourceCode source_code;
  262. ERR_FAIL_COND_V(!version, source_code);
  263. source_code.versions.resize(variant_defines.size());
  264. for (int i = 0; i < source_code.versions.size(); i++) {
  265. if (!is_compute) {
  266. //vertex stage
  267. StringBuilder builder;
  268. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_VERTEX]);
  269. RS::ShaderNativeSourceCode::Version::Stage stage;
  270. stage.name = "vertex";
  271. stage.code = builder.as_string();
  272. source_code.versions.write[i].stages.push_back(stage);
  273. }
  274. if (!is_compute) {
  275. //fragment stage
  276. StringBuilder builder;
  277. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_FRAGMENT]);
  278. RS::ShaderNativeSourceCode::Version::Stage stage;
  279. stage.name = "fragment";
  280. stage.code = builder.as_string();
  281. source_code.versions.write[i].stages.push_back(stage);
  282. }
  283. if (is_compute) {
  284. //compute stage
  285. StringBuilder builder;
  286. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_COMPUTE]);
  287. RS::ShaderNativeSourceCode::Version::Stage stage;
  288. stage.name = "compute";
  289. stage.code = builder.as_string();
  290. source_code.versions.write[i].stages.push_back(stage);
  291. }
  292. }
  293. return source_code;
  294. }
  295. String ShaderRD::_version_get_sha1(Version *p_version) const {
  296. StringBuilder hash_build;
  297. hash_build.append("[uniforms]");
  298. hash_build.append(p_version->uniforms.get_data());
  299. hash_build.append("[vertex_globals]");
  300. hash_build.append(p_version->vertex_globals.get_data());
  301. hash_build.append("[fragment_globals]");
  302. hash_build.append(p_version->fragment_globals.get_data());
  303. hash_build.append("[compute_globals]");
  304. hash_build.append(p_version->compute_globals.get_data());
  305. Vector<StringName> code_sections;
  306. for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {
  307. code_sections.push_back(E.key);
  308. }
  309. code_sections.sort_custom<StringName::AlphCompare>();
  310. for (int i = 0; i < code_sections.size(); i++) {
  311. hash_build.append(String("[code:") + String(code_sections[i]) + "]");
  312. hash_build.append(p_version->code_sections[code_sections[i]].get_data());
  313. }
  314. for (int i = 0; i < p_version->custom_defines.size(); i++) {
  315. hash_build.append("[custom_defines:" + itos(i) + "]");
  316. hash_build.append(p_version->custom_defines[i].get_data());
  317. }
  318. return hash_build.as_string().sha1_text();
  319. }
  320. static const char *shader_file_header = "GDSC";
  321. static const uint32_t cache_file_version = 2;
  322. bool ShaderRD::_load_from_cache(Version *p_version) {
  323. String sha1 = _version_get_sha1(p_version);
  324. String path = shader_cache_dir.path_join(name).path_join(base_sha256).path_join(sha1) + ".cache";
  325. Ref<FileAccess> f = FileAccess::open(path, FileAccess::READ);
  326. if (f.is_null()) {
  327. return false;
  328. }
  329. char header[5] = { 0, 0, 0, 0, 0 };
  330. f->get_buffer((uint8_t *)header, 4);
  331. ERR_FAIL_COND_V(header != String(shader_file_header), false);
  332. uint32_t file_version = f->get_32();
  333. if (file_version != cache_file_version) {
  334. return false; // wrong version
  335. }
  336. uint32_t variant_count = f->get_32();
  337. ERR_FAIL_COND_V(variant_count != (uint32_t)variant_defines.size(), false); //should not happen but check
  338. for (uint32_t i = 0; i < variant_count; i++) {
  339. uint32_t variant_size = f->get_32();
  340. ERR_FAIL_COND_V(variant_size == 0 && variants_enabled[i], false);
  341. if (!variants_enabled[i]) {
  342. continue;
  343. }
  344. Vector<uint8_t> variant_bytes;
  345. variant_bytes.resize(variant_size);
  346. uint32_t br = f->get_buffer(variant_bytes.ptrw(), variant_size);
  347. ERR_FAIL_COND_V(br != variant_size, false);
  348. p_version->variant_data[i] = variant_bytes;
  349. }
  350. for (uint32_t i = 0; i < variant_count; i++) {
  351. if (!variants_enabled[i]) {
  352. MutexLock lock(variant_set_mutex);
  353. p_version->variants[i] = RID();
  354. continue;
  355. }
  356. RID shader = RD::get_singleton()->shader_create_from_bytecode(p_version->variant_data[i]);
  357. if (shader.is_null()) {
  358. for (uint32_t j = 0; j < i; j++) {
  359. RD::get_singleton()->free(p_version->variants[i]);
  360. }
  361. ERR_FAIL_COND_V(shader.is_null(), false);
  362. }
  363. {
  364. MutexLock lock(variant_set_mutex);
  365. p_version->variants[i] = shader;
  366. }
  367. }
  368. memdelete_arr(p_version->variant_data); //clear stages
  369. p_version->variant_data = nullptr;
  370. p_version->valid = true;
  371. return true;
  372. }
  373. void ShaderRD::_save_to_cache(Version *p_version) {
  374. String sha1 = _version_get_sha1(p_version);
  375. String path = shader_cache_dir.path_join(name).path_join(base_sha256).path_join(sha1) + ".cache";
  376. Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE);
  377. ERR_FAIL_COND(f.is_null());
  378. f->store_buffer((const uint8_t *)shader_file_header, 4);
  379. f->store_32(cache_file_version); //file version
  380. uint32_t variant_count = variant_defines.size();
  381. f->store_32(variant_count); //variant count
  382. for (uint32_t i = 0; i < variant_count; i++) {
  383. f->store_32(p_version->variant_data[i].size()); //stage count
  384. f->store_buffer(p_version->variant_data[i].ptr(), p_version->variant_data[i].size());
  385. }
  386. }
  387. void ShaderRD::_compile_version(Version *p_version) {
  388. _clear_version(p_version);
  389. p_version->valid = false;
  390. p_version->dirty = false;
  391. p_version->variants = memnew_arr(RID, variant_defines.size());
  392. typedef Vector<uint8_t> ShaderStageData;
  393. p_version->variant_data = memnew_arr(ShaderStageData, variant_defines.size());
  394. if (shader_cache_dir_valid) {
  395. if (_load_from_cache(p_version)) {
  396. return;
  397. }
  398. }
  399. #if 1
  400. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &ShaderRD::_compile_variant, p_version, variant_defines.size(), -1, true, SNAME("ShaderCompilation"));
  401. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  402. #else
  403. for (int i = 0; i < variant_defines.size(); i++) {
  404. _compile_variant(i, p_version);
  405. }
  406. #endif
  407. bool all_valid = true;
  408. for (int i = 0; i < variant_defines.size(); i++) {
  409. if (!variants_enabled[i]) {
  410. continue; //disabled
  411. }
  412. if (p_version->variants[i].is_null()) {
  413. all_valid = false;
  414. break;
  415. }
  416. }
  417. if (!all_valid) {
  418. //clear versions if they exist
  419. for (int i = 0; i < variant_defines.size(); i++) {
  420. if (!variants_enabled[i]) {
  421. continue; //disabled
  422. }
  423. if (!p_version->variants[i].is_null()) {
  424. RD::get_singleton()->free(p_version->variants[i]);
  425. }
  426. }
  427. memdelete_arr(p_version->variants);
  428. if (p_version->variant_data) {
  429. memdelete_arr(p_version->variant_data);
  430. }
  431. p_version->variants = nullptr;
  432. p_version->variant_data = nullptr;
  433. return;
  434. } else if (shader_cache_dir_valid) {
  435. //save shader cache
  436. _save_to_cache(p_version);
  437. }
  438. memdelete_arr(p_version->variant_data); //clear stages
  439. p_version->variant_data = nullptr;
  440. p_version->valid = true;
  441. }
  442. 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) {
  443. ERR_FAIL_COND(is_compute);
  444. Version *version = version_owner.get_or_null(p_version);
  445. ERR_FAIL_COND(!version);
  446. version->vertex_globals = p_vertex_globals.utf8();
  447. version->fragment_globals = p_fragment_globals.utf8();
  448. version->uniforms = p_uniforms.utf8();
  449. version->code_sections.clear();
  450. for (const KeyValue<String, String> &E : p_code) {
  451. version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();
  452. }
  453. version->custom_defines.clear();
  454. for (int i = 0; i < p_custom_defines.size(); i++) {
  455. version->custom_defines.push_back(p_custom_defines[i].utf8());
  456. }
  457. version->dirty = true;
  458. if (version->initialize_needed) {
  459. _compile_version(version);
  460. version->initialize_needed = false;
  461. }
  462. }
  463. 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) {
  464. ERR_FAIL_COND(!is_compute);
  465. Version *version = version_owner.get_or_null(p_version);
  466. ERR_FAIL_COND(!version);
  467. version->compute_globals = p_compute_globals.utf8();
  468. version->uniforms = p_uniforms.utf8();
  469. version->code_sections.clear();
  470. for (const KeyValue<String, String> &E : p_code) {
  471. version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();
  472. }
  473. version->custom_defines.clear();
  474. for (int i = 0; i < p_custom_defines.size(); i++) {
  475. version->custom_defines.push_back(p_custom_defines[i].utf8());
  476. }
  477. version->dirty = true;
  478. if (version->initialize_needed) {
  479. _compile_version(version);
  480. version->initialize_needed = false;
  481. }
  482. }
  483. bool ShaderRD::version_is_valid(RID p_version) {
  484. Version *version = version_owner.get_or_null(p_version);
  485. ERR_FAIL_COND_V(!version, false);
  486. if (version->dirty) {
  487. _compile_version(version);
  488. }
  489. return version->valid;
  490. }
  491. bool ShaderRD::version_free(RID p_version) {
  492. if (version_owner.owns(p_version)) {
  493. Version *version = version_owner.get_or_null(p_version);
  494. _clear_version(version);
  495. version_owner.free(p_version);
  496. } else {
  497. return false;
  498. }
  499. return true;
  500. }
  501. void ShaderRD::set_variant_enabled(int p_variant, bool p_enabled) {
  502. ERR_FAIL_COND(version_owner.get_rid_count() > 0); //versions exist
  503. ERR_FAIL_INDEX(p_variant, variants_enabled.size());
  504. variants_enabled.write[p_variant] = p_enabled;
  505. }
  506. bool ShaderRD::is_variant_enabled(int p_variant) const {
  507. ERR_FAIL_INDEX_V(p_variant, variants_enabled.size(), false);
  508. return variants_enabled[p_variant];
  509. }
  510. bool ShaderRD::shader_cache_cleanup_on_start = false;
  511. ShaderRD::ShaderRD() {
  512. // Do not feel forced to use this, in most cases it makes little to no difference.
  513. bool use_32_threads = false;
  514. if (RD::get_singleton()->get_device_vendor_name() == "NVIDIA") {
  515. use_32_threads = true;
  516. }
  517. String base_compute_define_text;
  518. if (use_32_threads) {
  519. 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";
  520. } else {
  521. 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";
  522. }
  523. base_compute_defines = base_compute_define_text.ascii();
  524. }
  525. void ShaderRD::initialize(const Vector<String> &p_variant_defines, const String &p_general_defines) {
  526. ERR_FAIL_COND(variant_defines.size());
  527. ERR_FAIL_COND(p_variant_defines.size() == 0);
  528. general_defines = p_general_defines.utf8();
  529. for (int i = 0; i < p_variant_defines.size(); i++) {
  530. variant_defines.push_back(p_variant_defines[i].utf8());
  531. variants_enabled.push_back(true);
  532. }
  533. if (!shader_cache_dir.is_empty()) {
  534. StringBuilder hash_build;
  535. hash_build.append("[base_hash]");
  536. hash_build.append(base_sha256);
  537. hash_build.append("[general_defines]");
  538. hash_build.append(general_defines.get_data());
  539. for (int i = 0; i < variant_defines.size(); i++) {
  540. hash_build.append("[variant_defines:" + itos(i) + "]");
  541. hash_build.append(variant_defines[i].get_data());
  542. }
  543. base_sha256 = hash_build.as_string().sha256_text();
  544. Ref<DirAccess> d = DirAccess::open(shader_cache_dir);
  545. ERR_FAIL_COND(d.is_null());
  546. if (d->change_dir(name) != OK) {
  547. Error err = d->make_dir(name);
  548. ERR_FAIL_COND(err != OK);
  549. d->change_dir(name);
  550. }
  551. //erase other versions?
  552. if (shader_cache_cleanup_on_start) {
  553. }
  554. //
  555. if (d->change_dir(base_sha256) != OK) {
  556. Error err = d->make_dir(base_sha256);
  557. ERR_FAIL_COND(err != OK);
  558. }
  559. shader_cache_dir_valid = true;
  560. print_verbose("Shader '" + name + "' SHA256: " + base_sha256);
  561. }
  562. }
  563. void ShaderRD::set_shader_cache_dir(const String &p_dir) {
  564. shader_cache_dir = p_dir;
  565. }
  566. void ShaderRD::set_shader_cache_save_compressed(bool p_enable) {
  567. shader_cache_save_compressed = p_enable;
  568. }
  569. void ShaderRD::set_shader_cache_save_compressed_zstd(bool p_enable) {
  570. shader_cache_save_compressed_zstd = p_enable;
  571. }
  572. void ShaderRD::set_shader_cache_save_debug(bool p_enable) {
  573. shader_cache_save_debug = p_enable;
  574. }
  575. String ShaderRD::shader_cache_dir;
  576. bool ShaderRD::shader_cache_save_compressed = true;
  577. bool ShaderRD::shader_cache_save_compressed_zstd = true;
  578. bool ShaderRD::shader_cache_save_debug = true;
  579. ShaderRD::~ShaderRD() {
  580. List<RID> remaining;
  581. version_owner.get_owned_list(&remaining);
  582. if (remaining.size()) {
  583. ERR_PRINT(itos(remaining.size()) + " shaders of type " + name + " were never freed");
  584. while (remaining.size()) {
  585. version_free(remaining.front()->get());
  586. remaining.pop_front();
  587. }
  588. }
  589. }