shader_rd.cpp 23 KB

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