lightmapper_rd.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  1. /**************************************************************************/
  2. /* lightmapper_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 "lightmapper_rd.h"
  31. #include "lm_blendseams.glsl.gen.h"
  32. #include "lm_compute.glsl.gen.h"
  33. #include "lm_raster.glsl.gen.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/io/dir_access.h"
  36. #include "core/math/geometry_2d.h"
  37. #include "editor/editor_paths.h"
  38. #include "editor/editor_settings.h"
  39. #include "servers/rendering/rendering_device_binds.h"
  40. #if defined(VULKAN_ENABLED)
  41. #include "drivers/vulkan/rendering_context_driver_vulkan.h"
  42. #endif
  43. //uncomment this if you want to see textures from all the process saved
  44. //#define DEBUG_TEXTURES
  45. void LightmapperRD::add_mesh(const MeshData &p_mesh) {
  46. ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
  47. ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
  48. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
  49. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
  50. ERR_FAIL_COND(p_mesh.points.is_empty());
  51. MeshInstance mi;
  52. mi.data = p_mesh;
  53. mesh_instances.push_back(mi);
  54. }
  55. void LightmapperRD::add_directional_light(bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_angular_distance, float p_shadow_blur) {
  56. Light l;
  57. l.type = LIGHT_TYPE_DIRECTIONAL;
  58. l.direction[0] = p_direction.x;
  59. l.direction[1] = p_direction.y;
  60. l.direction[2] = p_direction.z;
  61. l.color[0] = p_color.r;
  62. l.color[1] = p_color.g;
  63. l.color[2] = p_color.b;
  64. l.energy = p_energy;
  65. l.indirect_energy = p_indirect_energy;
  66. l.static_bake = p_static;
  67. l.size = Math::tan(Math::deg_to_rad(p_angular_distance));
  68. l.shadow_blur = p_shadow_blur;
  69. lights.push_back(l);
  70. }
  71. void LightmapperRD::add_omni_light(bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) {
  72. Light l;
  73. l.type = LIGHT_TYPE_OMNI;
  74. l.position[0] = p_position.x;
  75. l.position[1] = p_position.y;
  76. l.position[2] = p_position.z;
  77. l.range = p_range;
  78. l.attenuation = p_attenuation;
  79. l.color[0] = p_color.r;
  80. l.color[1] = p_color.g;
  81. l.color[2] = p_color.b;
  82. l.energy = p_energy;
  83. l.indirect_energy = p_indirect_energy;
  84. l.static_bake = p_static;
  85. l.size = p_size;
  86. l.shadow_blur = p_shadow_blur;
  87. lights.push_back(l);
  88. }
  89. void LightmapperRD::add_spot_light(bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) {
  90. Light l;
  91. l.type = LIGHT_TYPE_SPOT;
  92. l.position[0] = p_position.x;
  93. l.position[1] = p_position.y;
  94. l.position[2] = p_position.z;
  95. l.direction[0] = p_direction.x;
  96. l.direction[1] = p_direction.y;
  97. l.direction[2] = p_direction.z;
  98. l.range = p_range;
  99. l.attenuation = p_attenuation;
  100. l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));
  101. l.inv_spot_attenuation = 1.0f / p_spot_attenuation;
  102. l.color[0] = p_color.r;
  103. l.color[1] = p_color.g;
  104. l.color[2] = p_color.b;
  105. l.energy = p_energy;
  106. l.indirect_energy = p_indirect_energy;
  107. l.static_bake = p_static;
  108. l.size = p_size;
  109. l.shadow_blur = p_shadow_blur;
  110. lights.push_back(l);
  111. }
  112. void LightmapperRD::add_probe(const Vector3 &p_position) {
  113. Probe probe;
  114. probe.position[0] = p_position.x;
  115. probe.position[1] = p_position.y;
  116. probe.position[2] = p_position.z;
  117. probe.position[3] = 0;
  118. probe_positions.push_back(probe);
  119. }
  120. void LightmapperRD::_plot_triangle_into_triangle_index_list(int p_size, const Vector3i &p_ofs, const AABB &p_bounds, const Vector3 p_points[3], uint32_t p_triangle_index, LocalVector<TriangleSort> &p_triangles_sort, uint32_t p_grid_size) {
  121. int half_size = p_size / 2;
  122. for (int i = 0; i < 8; i++) {
  123. AABB aabb = p_bounds;
  124. aabb.size *= 0.5;
  125. Vector3i n = p_ofs;
  126. if (i & 1) {
  127. aabb.position.x += aabb.size.x;
  128. n.x += half_size;
  129. }
  130. if (i & 2) {
  131. aabb.position.y += aabb.size.y;
  132. n.y += half_size;
  133. }
  134. if (i & 4) {
  135. aabb.position.z += aabb.size.z;
  136. n.z += half_size;
  137. }
  138. {
  139. Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
  140. if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
  141. //does not fit in child, go on
  142. continue;
  143. }
  144. }
  145. if (half_size == 1) {
  146. //got to the end
  147. TriangleSort ts;
  148. ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
  149. ts.triangle_index = p_triangle_index;
  150. ts.triangle_aabb.position = p_points[0];
  151. ts.triangle_aabb.size = Vector3();
  152. ts.triangle_aabb.expand_to(p_points[1]);
  153. ts.triangle_aabb.expand_to(p_points[2]);
  154. p_triangles_sort.push_back(ts);
  155. } else {
  156. _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, p_triangles_sort, p_grid_size);
  157. }
  158. }
  159. }
  160. void LightmapperRD::_sort_triangle_clusters(uint32_t p_cluster_size, uint32_t p_cluster_index, uint32_t p_index_start, uint32_t p_count, LocalVector<TriangleSort> &p_triangle_sort, LocalVector<ClusterAABB> &p_cluster_aabb) {
  161. if (p_count == 0) {
  162. return;
  163. }
  164. // Compute AABB for all triangles in the range.
  165. SortArray<TriangleSort, TriangleSortAxis<0>> triangle_sorter_x;
  166. SortArray<TriangleSort, TriangleSortAxis<1>> triangle_sorter_y;
  167. SortArray<TriangleSort, TriangleSortAxis<2>> triangle_sorter_z;
  168. AABB cluster_aabb = p_triangle_sort[p_index_start].triangle_aabb;
  169. for (uint32_t i = 1; i < p_count; i++) {
  170. cluster_aabb.merge_with(p_triangle_sort[p_index_start + i].triangle_aabb);
  171. }
  172. if (p_count > p_cluster_size) {
  173. int longest_axis_index = cluster_aabb.get_longest_axis_index();
  174. switch (longest_axis_index) {
  175. case 0:
  176. triangle_sorter_x.sort(&p_triangle_sort[p_index_start], p_count);
  177. break;
  178. case 1:
  179. triangle_sorter_y.sort(&p_triangle_sort[p_index_start], p_count);
  180. break;
  181. case 2:
  182. triangle_sorter_z.sort(&p_triangle_sort[p_index_start], p_count);
  183. break;
  184. default:
  185. DEV_ASSERT(false && "Invalid axis returned by AABB.");
  186. break;
  187. }
  188. uint32_t left_cluster_count = next_power_of_2(p_count / 2);
  189. left_cluster_count = MAX(left_cluster_count, p_cluster_size);
  190. left_cluster_count = MIN(left_cluster_count, p_count);
  191. _sort_triangle_clusters(p_cluster_size, p_cluster_index, p_index_start, left_cluster_count, p_triangle_sort, p_cluster_aabb);
  192. if (left_cluster_count < p_count) {
  193. uint32_t cluster_index_right = p_cluster_index + (left_cluster_count / p_cluster_size);
  194. _sort_triangle_clusters(p_cluster_size, cluster_index_right, p_index_start + left_cluster_count, p_count - left_cluster_count, p_triangle_sort, p_cluster_aabb);
  195. }
  196. } else {
  197. ClusterAABB &aabb = p_cluster_aabb[p_cluster_index];
  198. Vector3 aabb_end = cluster_aabb.get_end();
  199. aabb.min_bounds[0] = cluster_aabb.position.x;
  200. aabb.min_bounds[1] = cluster_aabb.position.y;
  201. aabb.min_bounds[2] = cluster_aabb.position.z;
  202. aabb.max_bounds[0] = aabb_end.x;
  203. aabb.max_bounds[1] = aabb_end.y;
  204. aabb.max_bounds[2] = aabb_end.z;
  205. }
  206. }
  207. Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, int p_denoiser_range, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, BakeStepFunc p_step_function, void *p_bake_userdata) {
  208. Vector<Size2i> sizes;
  209. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  210. MeshInstance &mi = mesh_instances.write[m_i];
  211. Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
  212. sizes.push_back(s);
  213. atlas_size = atlas_size.max(s + Size2i(2, 2));
  214. }
  215. int max = nearest_power_of_2_templated(atlas_size.width);
  216. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  217. if (max > p_max_texture_size) {
  218. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  219. }
  220. if (p_step_function) {
  221. p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true);
  222. }
  223. atlas_size = Size2i(max, max);
  224. Size2i best_atlas_size;
  225. int best_atlas_slices = 0;
  226. int best_atlas_memory = 0x7FFFFFFF;
  227. Vector<Vector3i> best_atlas_offsets;
  228. //determine best texture array atlas size by bruteforce fitting
  229. while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
  230. Vector<Vector2i> source_sizes;
  231. Vector<int> source_indices;
  232. source_sizes.resize(sizes.size());
  233. source_indices.resize(sizes.size());
  234. for (int i = 0; i < source_indices.size(); i++) {
  235. source_sizes.write[i] = sizes[i] + Vector2i(2, 2).maxi(p_denoiser_range); // Add padding between lightmaps
  236. source_indices.write[i] = i;
  237. }
  238. Vector<Vector3i> atlas_offsets;
  239. atlas_offsets.resize(source_sizes.size());
  240. int slices = 0;
  241. while (source_sizes.size() > 0) {
  242. Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
  243. Vector<int> new_indices;
  244. Vector<Vector2i> new_sources;
  245. for (int i = 0; i < offsets.size(); i++) {
  246. Vector3i ofs = offsets[i];
  247. int sidx = source_indices[i];
  248. if (ofs.z > 0) {
  249. //valid
  250. ofs.z = slices;
  251. atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region
  252. } else {
  253. new_indices.push_back(sidx);
  254. new_sources.push_back(source_sizes[i]);
  255. }
  256. }
  257. source_sizes = new_sources;
  258. source_indices = new_indices;
  259. slices++;
  260. }
  261. int mem_used = atlas_size.x * atlas_size.y * slices;
  262. if (mem_used < best_atlas_memory) {
  263. best_atlas_size = atlas_size;
  264. best_atlas_offsets = atlas_offsets;
  265. best_atlas_slices = slices;
  266. best_atlas_memory = mem_used;
  267. }
  268. if (atlas_size.width == atlas_size.height) {
  269. atlas_size.width *= 2;
  270. } else {
  271. atlas_size.height *= 2;
  272. }
  273. }
  274. atlas_size = best_atlas_size;
  275. atlas_slices = best_atlas_slices;
  276. // apply the offsets and slice to all images, and also blit albedo and emission
  277. albedo_images.resize(atlas_slices);
  278. emission_images.resize(atlas_slices);
  279. if (p_step_function) {
  280. p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true);
  281. }
  282. for (int i = 0; i < atlas_slices; i++) {
  283. Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
  284. albedo->set_as_black();
  285. albedo_images.write[i] = albedo;
  286. Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
  287. emission->set_as_black();
  288. emission_images.write[i] = emission;
  289. }
  290. //assign uv positions
  291. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  292. MeshInstance &mi = mesh_instances.write[m_i];
  293. mi.offset.x = best_atlas_offsets[m_i].x;
  294. mi.offset.y = best_atlas_offsets[m_i].y;
  295. mi.slice = best_atlas_offsets[m_i].z;
  296. albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);
  297. emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);
  298. }
  299. return BAKE_OK;
  300. }
  301. void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, uint32_t p_cluster_size, Vector<Probe> &p_probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &r_triangle_indices_buffer, RID &r_cluster_indices_buffer, RID &r_cluster_aabbs_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
  302. HashMap<Vertex, uint32_t, VertexHash> vertex_map;
  303. //fill triangles array and vertex array
  304. LocalVector<Triangle> triangles;
  305. LocalVector<Vertex> vertex_array;
  306. LocalVector<Seam> seams;
  307. slice_triangle_count.resize(atlas_slices);
  308. slice_seam_count.resize(atlas_slices);
  309. for (int i = 0; i < atlas_slices; i++) {
  310. slice_triangle_count.write[i] = 0;
  311. slice_seam_count.write[i] = 0;
  312. }
  313. bounds = AABB();
  314. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  315. if (p_step_function) {
  316. float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1;
  317. p_step_function(0.3 + p, vformat(RTR("Plotting mesh into acceleration structure %d/%d"), m_i + 1, mesh_instances.size()), p_bake_userdata, false);
  318. }
  319. HashMap<Edge, EdgeUV2, EdgeHash> edges;
  320. MeshInstance &mi = mesh_instances.write[m_i];
  321. Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
  322. Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
  323. if (m_i == 0) {
  324. bounds.position = mi.data.points[0];
  325. }
  326. for (int i = 0; i < mi.data.points.size(); i += 3) {
  327. Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
  328. Vector2 uvs[3] = { mi.data.uv2[i + 0] * uv_scale + uv_offset, mi.data.uv2[i + 1] * uv_scale + uv_offset, mi.data.uv2[i + 2] * uv_scale + uv_offset };
  329. Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
  330. AABB taabb;
  331. Triangle t;
  332. t.slice = mi.slice;
  333. for (int k = 0; k < 3; k++) {
  334. bounds.expand_to(vtxs[k]);
  335. Vertex v;
  336. v.position[0] = vtxs[k].x;
  337. v.position[1] = vtxs[k].y;
  338. v.position[2] = vtxs[k].z;
  339. v.uv[0] = uvs[k].x;
  340. v.uv[1] = uvs[k].y;
  341. v.normal_xy[0] = normal[k].x;
  342. v.normal_xy[1] = normal[k].y;
  343. v.normal_z = normal[k].z;
  344. uint32_t *indexptr = vertex_map.getptr(v);
  345. if (indexptr) {
  346. t.indices[k] = *indexptr;
  347. } else {
  348. uint32_t new_index = vertex_map.size();
  349. t.indices[k] = new_index;
  350. vertex_map[v] = new_index;
  351. vertex_array.push_back(v);
  352. }
  353. if (k == 0) {
  354. taabb.position = vtxs[k];
  355. } else {
  356. taabb.expand_to(vtxs[k]);
  357. }
  358. }
  359. //compute seams that will need to be blended later
  360. for (int k = 0; k < 3; k++) {
  361. int n = (k + 1) % 3;
  362. Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
  363. Vector2i edge_indices(t.indices[k], t.indices[n]);
  364. EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
  365. if (edge.b == edge.a) {
  366. continue; //degenerate, somehow
  367. }
  368. if (edge.b < edge.a) {
  369. SWAP(edge.a, edge.b);
  370. SWAP(edge.na, edge.nb);
  371. SWAP(uv2.a, uv2.b);
  372. SWAP(uv2.indices.x, uv2.indices.y);
  373. SWAP(edge_indices.x, edge_indices.y);
  374. }
  375. EdgeUV2 *euv2 = edges.getptr(edge);
  376. if (!euv2) {
  377. edges[edge] = uv2;
  378. } else {
  379. if (*euv2 == uv2) {
  380. continue; // seam shared UV space, no need to blend
  381. }
  382. if (euv2->seam_found) {
  383. continue; //bad geometry
  384. }
  385. Seam seam;
  386. seam.a = edge_indices;
  387. seam.b = euv2->indices;
  388. seam.slice = mi.slice;
  389. seams.push_back(seam);
  390. slice_seam_count.write[mi.slice]++;
  391. euv2->seam_found = true;
  392. }
  393. }
  394. t.min_bounds[0] = taabb.position.x;
  395. t.min_bounds[1] = taabb.position.y;
  396. t.min_bounds[2] = taabb.position.z;
  397. t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
  398. t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
  399. t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
  400. t.pad0 = t.pad1 = 0; //make valgrind not complain
  401. triangles.push_back(t);
  402. slice_triangle_count.write[t.slice]++;
  403. }
  404. }
  405. //also consider probe positions for bounds
  406. for (int i = 0; i < p_probe_positions.size(); i++) {
  407. Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]);
  408. bounds.expand_to(pp);
  409. }
  410. bounds.grow_by(0.1); //grow a bit to avoid numerical error
  411. triangles.sort(); //sort by slice
  412. seams.sort();
  413. if (p_step_function) {
  414. p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);
  415. }
  416. //fill list of triangles in grid
  417. LocalVector<TriangleSort> triangle_sort;
  418. for (uint32_t i = 0; i < triangles.size(); i++) {
  419. const Triangle &t = triangles[i];
  420. Vector3 face[3] = {
  421. Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
  422. Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
  423. Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
  424. };
  425. _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
  426. }
  427. //sort it
  428. triangle_sort.sort();
  429. LocalVector<uint32_t> cluster_indices;
  430. LocalVector<ClusterAABB> cluster_aabbs;
  431. Vector<uint32_t> triangle_indices;
  432. triangle_indices.resize(triangle_sort.size());
  433. Vector<uint32_t> grid_indices;
  434. grid_indices.resize(grid_size * grid_size * grid_size * 2);
  435. memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));
  436. {
  437. // Fill grid with cell indices.
  438. uint32_t last_cell = 0xFFFFFFFF;
  439. uint32_t *giw = grid_indices.ptrw();
  440. uint32_t cluster_count = 0;
  441. uint32_t solid_cell_count = 0;
  442. for (uint32_t i = 0; i < triangle_sort.size(); i++) {
  443. uint32_t cell = triangle_sort[i].cell_index;
  444. if (cell != last_cell) {
  445. giw[cell * 2 + 1] = solid_cell_count;
  446. solid_cell_count++;
  447. }
  448. if ((giw[cell * 2] % p_cluster_size) == 0) {
  449. // Add an extra cluster every time the triangle counter reaches a multiple of the cluster size.
  450. cluster_count++;
  451. }
  452. giw[cell * 2]++;
  453. last_cell = cell;
  454. }
  455. // Build fixed-size triangle clusters for all the cells to speed up the traversal. A cell can hold multiple clusters that each contain a fixed
  456. // amount of triangles and an AABB. The tracer will check against the AABBs first to know whether it needs to visit the cell's triangles.
  457. //
  458. // The building algorithm will divide the triangles recursively contained inside each cell, sorting by the longest axis of the AABB on each step.
  459. //
  460. // - If the amount of triangles is less or equal to the cluster size, the AABB will be stored and the algorithm stops.
  461. //
  462. // - The division by two is increased to the next power of two of half the amount of triangles (with cluster size as the minimum value) to
  463. // ensure the first half always fills the cluster.
  464. cluster_indices.resize(solid_cell_count * 2);
  465. cluster_aabbs.resize(cluster_count);
  466. uint32_t i = 0;
  467. uint32_t cluster_index = 0;
  468. uint32_t solid_cell_index = 0;
  469. uint32_t *tiw = triangle_indices.ptrw();
  470. while (i < triangle_sort.size()) {
  471. cluster_indices[solid_cell_index * 2] = cluster_index;
  472. cluster_indices[solid_cell_index * 2 + 1] = i;
  473. uint32_t cell = triangle_sort[i].cell_index;
  474. uint32_t triangle_count = giw[cell * 2];
  475. uint32_t cell_cluster_count = (triangle_count + p_cluster_size - 1) / p_cluster_size;
  476. _sort_triangle_clusters(p_cluster_size, cluster_index, i, triangle_count, triangle_sort, cluster_aabbs);
  477. for (uint32_t j = 0; j < triangle_count; j++) {
  478. tiw[i + j] = triangle_sort[i + j].triangle_index;
  479. }
  480. i += triangle_count;
  481. cluster_index += cell_cluster_count;
  482. solid_cell_index++;
  483. }
  484. }
  485. #if 0
  486. for (int i = 0; i < grid_size; i++) {
  487. for (int j = 0; j < grid_size; j++) {
  488. for (int k = 0; k < grid_size; k++) {
  489. uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
  490. grid_indices.write[index * 2] = float(i) / grid_size * 255;
  491. grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
  492. }
  493. }
  494. }
  495. #endif
  496. #if 0
  497. for (int i = 0; i < grid_size; i++) {
  498. Vector<uint8_t> grid_usage;
  499. grid_usage.resize(grid_size * grid_size);
  500. for (int j = 0; j < grid_usage.size(); j++) {
  501. uint32_t ofs = i * grid_size * grid_size + j;
  502. uint32_t count = grid_indices[ofs * 2];
  503. grid_usage.write[j] = count > 0 ? 255 : 0;
  504. }
  505. Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
  506. img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
  507. }
  508. #endif
  509. /*****************************/
  510. /*** CREATE GPU STRUCTURES ***/
  511. /*****************************/
  512. lights.sort();
  513. Vector<Vector2i> seam_buffer_vec;
  514. seam_buffer_vec.resize(seams.size() * 2);
  515. for (uint32_t i = 0; i < seams.size(); i++) {
  516. seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
  517. seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
  518. }
  519. { //buffers
  520. Vector<uint8_t> vb = vertex_array.to_byte_array();
  521. vertex_buffer = rd->storage_buffer_create(vb.size(), vb);
  522. Vector<uint8_t> tb = triangles.to_byte_array();
  523. triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
  524. Vector<uint8_t> tib = triangle_indices.to_byte_array();
  525. r_triangle_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
  526. Vector<uint8_t> cib = cluster_indices.to_byte_array();
  527. r_cluster_indices_buffer = rd->storage_buffer_create(cib.size(), cib);
  528. Vector<uint8_t> cab = cluster_aabbs.to_byte_array();
  529. r_cluster_aabbs_buffer = rd->storage_buffer_create(cab.size(), cab);
  530. Vector<uint8_t> lb = lights.to_byte_array();
  531. if (lb.size() == 0) {
  532. lb.resize(sizeof(Light)); //even if no lights, the buffer must exist
  533. }
  534. lights_buffer = rd->storage_buffer_create(lb.size(), lb);
  535. Vector<uint8_t> sb = seam_buffer_vec.to_byte_array();
  536. if (sb.size() == 0) {
  537. sb.resize(sizeof(Vector2i) * 2); //even if no seams, the buffer must exist
  538. }
  539. seams_buffer = rd->storage_buffer_create(sb.size(), sb);
  540. Vector<uint8_t> pb = p_probe_positions.to_byte_array();
  541. if (pb.size() == 0) {
  542. pb.resize(sizeof(Probe));
  543. }
  544. probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
  545. }
  546. { //grid
  547. RD::TextureFormat tf;
  548. tf.width = grid_size;
  549. tf.height = grid_size;
  550. tf.depth = grid_size;
  551. tf.texture_type = RD::TEXTURE_TYPE_3D;
  552. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  553. Vector<Vector<uint8_t>> texdata;
  554. texdata.resize(1);
  555. //grid and indices
  556. tf.format = RD::DATA_FORMAT_R32G32_UINT;
  557. texdata.write[0] = grid_indices.to_byte_array();
  558. grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
  559. }
  560. }
  561. void LightmapperRD::_raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform) {
  562. Vector<RID> framebuffers;
  563. for (int i = 0; i < atlas_slices; i++) {
  564. RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
  565. RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
  566. RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
  567. Vector<RID> fb;
  568. fb.push_back(slice_pos_tex);
  569. fb.push_back(slice_norm_tex);
  570. fb.push_back(slice_unoc_tex);
  571. fb.push_back(raster_depth_buffer);
  572. framebuffers.push_back(rd->framebuffer_create(fb));
  573. }
  574. RD::PipelineDepthStencilState ds;
  575. ds.enable_depth_test = true;
  576. ds.enable_depth_write = true;
  577. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
  578. RID raster_pipeline = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);
  579. RID raster_pipeline_wire;
  580. {
  581. RD::PipelineRasterizationState rw;
  582. rw.wireframe = true;
  583. raster_pipeline_wire = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, rw, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);
  584. }
  585. uint32_t triangle_offset = 0;
  586. Vector<Color> clear_colors;
  587. clear_colors.push_back(Color(0, 0, 0, 0));
  588. clear_colors.push_back(Color(0, 0, 0, 0));
  589. clear_colors.push_back(Color(0, 0, 0, 0));
  590. for (int i = 0; i < atlas_slices; i++) {
  591. RasterPushConstant raster_push_constant;
  592. raster_push_constant.atlas_size[0] = atlas_size.x;
  593. raster_push_constant.atlas_size[1] = atlas_size.y;
  594. raster_push_constant.base_triangle = triangle_offset;
  595. raster_push_constant.to_cell_offset[0] = bounds.position.x;
  596. raster_push_constant.to_cell_offset[1] = bounds.position.y;
  597. raster_push_constant.to_cell_offset[2] = bounds.position.z;
  598. raster_push_constant.bias = p_bias;
  599. raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  600. raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  601. raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  602. raster_push_constant.grid_size[0] = grid_size;
  603. raster_push_constant.grid_size[1] = grid_size;
  604. raster_push_constant.grid_size[2] = grid_size;
  605. // Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels.
  606. // This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to
  607. // be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>.
  608. raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x);
  609. raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y);
  610. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_STORE, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  611. //draw opaque
  612. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
  613. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  614. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  615. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  616. //draw wire
  617. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
  618. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  619. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  620. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  621. rd->draw_list_end();
  622. triangle_offset += slice_triangle_count[i];
  623. }
  624. }
  625. static Vector<RD::Uniform> dilate_or_denoise_common_uniforms(RID &p_source_light_tex, RID &p_dest_light_tex) {
  626. Vector<RD::Uniform> uniforms;
  627. {
  628. RD::Uniform u;
  629. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  630. u.binding = 0;
  631. u.append_id(p_dest_light_tex);
  632. uniforms.push_back(u);
  633. }
  634. {
  635. RD::Uniform u;
  636. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  637. u.binding = 1;
  638. u.append_id(p_source_light_tex);
  639. uniforms.push_back(u);
  640. }
  641. return uniforms;
  642. }
  643. LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) {
  644. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
  645. RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));
  646. ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  647. RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
  648. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
  649. RD::ComputeListID compute_list = rd->compute_list_begin();
  650. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
  651. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  652. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  653. push_constant.region_ofs[0] = 0;
  654. push_constant.region_ofs[1] = 0;
  655. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
  656. for (int i = 0; i < atlas_slices; i++) {
  657. push_constant.atlas_slice = i;
  658. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  659. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  660. //no barrier, let them run all together
  661. }
  662. rd->compute_list_end();
  663. rd->free(compute_shader_dilate);
  664. #ifdef DEBUG_TEXTURES
  665. for (int i = 0; i < atlas_slices; i++) {
  666. Vector<uint8_t> s = rd->texture_get_data(source_light_tex, i);
  667. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  668. img->convert(Image::FORMAT_RGBA8);
  669. img->save_png("res://5_dilated_" + itos(i) + ".png");
  670. }
  671. #endif
  672. return BAKE_OK;
  673. }
  674. Error LightmapperRD::_store_pfm(RenderingDevice *p_rd, RID p_atlas_tex, int p_index, const Size2i &p_atlas_size, const String &p_name) {
  675. Vector<uint8_t> data = p_rd->texture_get_data(p_atlas_tex, p_index);
  676. Ref<Image> img = Image::create_from_data(p_atlas_size.width, p_atlas_size.height, false, Image::FORMAT_RGBAH, data);
  677. img->convert(Image::FORMAT_RGBF);
  678. Vector<uint8_t> data_float = img->get_data();
  679. Error err = OK;
  680. Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::WRITE, &err);
  681. ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PFN at path: '%s'.", p_name));
  682. file->store_line("PF");
  683. file->store_line(vformat("%d %d", img->get_width(), img->get_height()));
  684. #ifdef BIG_ENDIAN_ENABLED
  685. file->store_line("1.0");
  686. #else
  687. file->store_line("-1.0");
  688. #endif
  689. file->store_buffer(data_float);
  690. file->close();
  691. return OK;
  692. }
  693. Ref<Image> LightmapperRD::_read_pfm(const String &p_name) {
  694. Error err = OK;
  695. Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::READ, &err);
  696. ERR_FAIL_COND_V_MSG(err, Ref<Image>(), vformat("Can't load PFM at path: '%s'.", p_name));
  697. ERR_FAIL_COND_V(file->get_line() != "PF", Ref<Image>());
  698. Vector<String> new_size = file->get_line().split(" ");
  699. ERR_FAIL_COND_V(new_size.size() != 2, Ref<Image>());
  700. int new_width = new_size[0].to_int();
  701. int new_height = new_size[1].to_int();
  702. float endian = file->get_line().to_float();
  703. Vector<uint8_t> new_data = file->get_buffer(file->get_length() - file->get_position());
  704. file->close();
  705. #ifdef BIG_ENDIAN_ENABLED
  706. if (unlikely(endian < 0.0)) {
  707. uint32_t count = new_data.size() / 4;
  708. uint16_t *dst = (uint16_t *)new_data.ptrw();
  709. for (uint32_t j = 0; j < count; j++) {
  710. dst[j * 4] = BSWAP32(dst[j * 4]);
  711. }
  712. }
  713. #else
  714. if (unlikely(endian > 0.0)) {
  715. uint32_t count = new_data.size() / 4;
  716. uint16_t *dst = (uint16_t *)new_data.ptrw();
  717. for (uint32_t j = 0; j < count; j++) {
  718. dst[j * 4] = BSWAP32(dst[j * 4]);
  719. }
  720. }
  721. #endif
  722. Ref<Image> img = Image::create_from_data(new_width, new_height, false, Image::FORMAT_RGBF, new_data);
  723. img->convert(Image::FORMAT_RGBAH);
  724. return img;
  725. }
  726. LightmapperRD::BakeError LightmapperRD::_denoise_oidn(RenderingDevice *p_rd, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, const String &p_exe) {
  727. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  728. for (int i = 0; i < p_atlas_slices; i++) {
  729. String fname_norm_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_norm_%d.pfm", i));
  730. _store_pfm(p_rd, p_source_normal_tex, i, p_atlas_size, fname_norm_in);
  731. for (int j = 0; j < (p_bake_sh ? 4 : 1); j++) {
  732. int index = i * (p_bake_sh ? 4 : 1) + j;
  733. String fname_light_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_light_%d.pfm", index));
  734. String fname_out = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_denoised_%d.pfm", index));
  735. _store_pfm(p_rd, p_source_light_tex, index, p_atlas_size, fname_light_in);
  736. List<String> args;
  737. args.push_back("--device");
  738. args.push_back("default");
  739. args.push_back("--filter");
  740. args.push_back("RTLightmap");
  741. args.push_back("--hdr");
  742. args.push_back(fname_light_in);
  743. args.push_back("--nrm");
  744. args.push_back(fname_norm_in);
  745. args.push_back("--output");
  746. args.push_back(fname_out);
  747. String str;
  748. int exitcode = 0;
  749. Error err = OS::get_singleton()->execute(p_exe, args, &str, &exitcode, true);
  750. da->remove(fname_light_in);
  751. if (err != OK || exitcode != 0) {
  752. da->remove(fname_out);
  753. print_verbose(str);
  754. ERR_FAIL_V_MSG(BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, vformat("OIDN denoiser failed, return code: %d", exitcode));
  755. }
  756. Ref<Image> img = _read_pfm(fname_out);
  757. da->remove(fname_out);
  758. ERR_FAIL_COND_V(img.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  759. Vector<uint8_t> old_data = p_rd->texture_get_data(p_source_light_tex, index);
  760. Vector<uint8_t> new_data = img->get_data();
  761. img.unref(); // Avoid copy on write.
  762. uint32_t count = old_data.size() / 2;
  763. const uint16_t *src = (const uint16_t *)old_data.ptr();
  764. uint16_t *dst = (uint16_t *)new_data.ptrw();
  765. for (uint32_t k = 0; k < count; k += 4) {
  766. dst[k + 3] = src[k + 3];
  767. }
  768. p_rd->texture_update(p_dest_light_tex, index, new_data);
  769. }
  770. da->remove(fname_norm_in);
  771. }
  772. return BAKE_OK;
  773. }
  774. LightmapperRD::BakeError LightmapperRD::_denoise(RenderingDevice *p_rd, Ref<RDShaderFile> &p_compute_shader, const RID &p_compute_base_uniform_set, PushConstant &p_push_constant, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, float p_denoiser_strength, int p_denoiser_range, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, BakeStepFunc p_step_function) {
  775. RID denoise_params_buffer = p_rd->uniform_buffer_create(sizeof(DenoiseParams));
  776. DenoiseParams denoise_params;
  777. denoise_params.spatial_bandwidth = 5.0f;
  778. denoise_params.light_bandwidth = p_denoiser_strength;
  779. denoise_params.albedo_bandwidth = 1.0f;
  780. denoise_params.normal_bandwidth = 0.1f;
  781. denoise_params.filter_strength = 10.0f;
  782. denoise_params.half_search_window = p_denoiser_range;
  783. p_rd->buffer_update(denoise_params_buffer, 0, sizeof(DenoiseParams), &denoise_params);
  784. Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(p_source_light_tex, p_dest_light_tex);
  785. {
  786. RD::Uniform u;
  787. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  788. u.binding = 2;
  789. u.append_id(p_source_normal_tex);
  790. uniforms.push_back(u);
  791. }
  792. {
  793. RD::Uniform u;
  794. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  795. u.binding = 3;
  796. u.append_id(denoise_params_buffer);
  797. uniforms.push_back(u);
  798. }
  799. RID compute_shader_denoise = p_rd->shader_create_from_spirv(p_compute_shader->get_spirv_stages("denoise"));
  800. ERR_FAIL_COND_V(compute_shader_denoise.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  801. RID compute_shader_denoise_pipeline = p_rd->compute_pipeline_create(compute_shader_denoise);
  802. RID denoise_uniform_set = p_rd->uniform_set_create(uniforms, compute_shader_denoise, 1);
  803. // We denoise in fixed size regions and synchronize execution to avoid GPU timeouts.
  804. // We use a region with 1/4 the amount of pixels if we're denoising SH lightmaps, as
  805. // all four of them are denoised in the shader in one dispatch.
  806. const int max_region_size = p_bake_sh ? 512 : 1024;
  807. int x_regions = Math::division_round_up(p_atlas_size.width, max_region_size);
  808. int y_regions = Math::division_round_up(p_atlas_size.height, max_region_size);
  809. for (int s = 0; s < p_atlas_slices; s++) {
  810. p_push_constant.atlas_slice = s;
  811. for (int i = 0; i < x_regions; i++) {
  812. for (int j = 0; j < y_regions; j++) {
  813. int x = i * max_region_size;
  814. int y = j * max_region_size;
  815. int w = MIN((i + 1) * max_region_size, p_atlas_size.width) - x;
  816. int h = MIN((j + 1) * max_region_size, p_atlas_size.height) - y;
  817. p_push_constant.region_ofs[0] = x;
  818. p_push_constant.region_ofs[1] = y;
  819. RD::ComputeListID compute_list = p_rd->compute_list_begin();
  820. p_rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_denoise_pipeline);
  821. p_rd->compute_list_bind_uniform_set(compute_list, p_compute_base_uniform_set, 0);
  822. p_rd->compute_list_bind_uniform_set(compute_list, denoise_uniform_set, 1);
  823. p_rd->compute_list_set_push_constant(compute_list, &p_push_constant, sizeof(PushConstant));
  824. p_rd->compute_list_dispatch(compute_list, Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  825. p_rd->compute_list_end();
  826. p_rd->submit();
  827. p_rd->sync();
  828. }
  829. }
  830. }
  831. p_rd->free(compute_shader_denoise);
  832. p_rd->free(denoise_params_buffer);
  833. return BAKE_OK;
  834. }
  835. LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, float p_denoiser_strength, int p_denoiser_range, int p_bounces, float p_bounce_indirect_energy, float p_bias, int p_max_texture_size, bool p_bake_sh, bool p_texture_for_bounces, GenerateProbes p_generate_probes, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata, float p_exposure_normalization) {
  836. int denoiser = GLOBAL_GET("rendering/lightmapping/denoising/denoiser");
  837. String oidn_path = EDITOR_GET("filesystem/tools/oidn/oidn_denoise_path");
  838. if (p_use_denoiser && denoiser == 1) {
  839. // OIDN (external).
  840. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  841. if (da->dir_exists(oidn_path)) {
  842. if (OS::get_singleton()->get_name() == "Windows") {
  843. oidn_path = oidn_path.path_join("oidnDenoise.exe");
  844. } else {
  845. oidn_path = oidn_path.path_join("oidnDenoise");
  846. }
  847. }
  848. ERR_FAIL_COND_V_MSG(oidn_path.is_empty() || !da->file_exists(oidn_path), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, "OIDN denoiser is selected in the project settings, but no or invalid OIDN executable path is configured in the editor settings.");
  849. }
  850. if (p_step_function) {
  851. p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);
  852. }
  853. bake_textures.clear();
  854. int grid_size = 128;
  855. /* STEP 1: Fetch material textures and compute the bounds */
  856. AABB bounds;
  857. Size2i atlas_size;
  858. int atlas_slices;
  859. Vector<Ref<Image>> albedo_images;
  860. Vector<Ref<Image>> emission_images;
  861. BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, p_denoiser_range, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_step_function, p_bake_userdata);
  862. if (bake_error != BAKE_OK) {
  863. return bake_error;
  864. }
  865. #ifdef DEBUG_TEXTURES
  866. for (int i = 0; i < atlas_slices; i++) {
  867. albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
  868. emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
  869. }
  870. #endif
  871. // Attempt to create a local device by requesting it from rendering server first.
  872. // If that fails because the current renderer is not implemented on top of RD, we fall back to creating
  873. // a local rendering device manually depending on the current platform.
  874. Error err;
  875. RenderingContextDriver *rcd = nullptr;
  876. RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device();
  877. if (rd == nullptr) {
  878. #if defined(RD_ENABLED)
  879. #if defined(VULKAN_ENABLED)
  880. rcd = memnew(RenderingContextDriverVulkan);
  881. rd = memnew(RenderingDevice);
  882. #endif
  883. #endif
  884. if (rcd != nullptr && rd != nullptr) {
  885. err = rcd->initialize();
  886. if (err == OK) {
  887. err = rd->initialize(rcd);
  888. }
  889. if (err != OK) {
  890. memdelete(rd);
  891. memdelete(rcd);
  892. rd = nullptr;
  893. rcd = nullptr;
  894. }
  895. }
  896. }
  897. ERR_FAIL_NULL_V(rd, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  898. RID albedo_array_tex;
  899. RID emission_array_tex;
  900. RID normal_tex;
  901. RID position_tex;
  902. RID unocclude_tex;
  903. RID light_source_tex;
  904. RID light_dest_tex;
  905. RID light_accum_tex;
  906. RID light_accum_tex2;
  907. RID light_environment_tex;
  908. #define FREE_TEXTURES \
  909. rd->free(albedo_array_tex); \
  910. rd->free(emission_array_tex); \
  911. rd->free(normal_tex); \
  912. rd->free(position_tex); \
  913. rd->free(unocclude_tex); \
  914. rd->free(light_source_tex); \
  915. rd->free(light_accum_tex2); \
  916. rd->free(light_accum_tex); \
  917. rd->free(light_environment_tex);
  918. { // create all textures
  919. Vector<Vector<uint8_t>> albedo_data;
  920. Vector<Vector<uint8_t>> emission_data;
  921. for (int i = 0; i < atlas_slices; i++) {
  922. albedo_data.push_back(albedo_images[i]->get_data());
  923. emission_data.push_back(emission_images[i]->get_data());
  924. }
  925. RD::TextureFormat tf;
  926. tf.width = atlas_size.width;
  927. tf.height = atlas_size.height;
  928. tf.array_layers = atlas_slices;
  929. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  930. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  931. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  932. albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
  933. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  934. emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
  935. //this will be rastered to
  936. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  937. normal_tex = rd->texture_create(tf, RD::TextureView());
  938. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  939. position_tex = rd->texture_create(tf, RD::TextureView());
  940. unocclude_tex = rd->texture_create(tf, RD::TextureView());
  941. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  942. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  943. light_source_tex = rd->texture_create(tf, RD::TextureView());
  944. rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  945. if (p_bake_sh) {
  946. tf.array_layers *= 4;
  947. }
  948. light_accum_tex = rd->texture_create(tf, RD::TextureView());
  949. rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  950. light_dest_tex = rd->texture_create(tf, RD::TextureView());
  951. rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  952. light_accum_tex2 = light_dest_tex;
  953. //env
  954. {
  955. Ref<Image> panorama_tex;
  956. if (p_environment_panorama.is_valid()) {
  957. panorama_tex = p_environment_panorama;
  958. panorama_tex->convert(Image::FORMAT_RGBAF);
  959. } else {
  960. panorama_tex.instantiate();
  961. panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);
  962. panorama_tex->fill(Color(0, 0, 0, 1));
  963. }
  964. RD::TextureFormat tfp;
  965. tfp.width = panorama_tex->get_width();
  966. tfp.height = panorama_tex->get_height();
  967. tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  968. tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  969. Vector<Vector<uint8_t>> tdata;
  970. tdata.push_back(panorama_tex->get_data());
  971. light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
  972. #ifdef DEBUG_TEXTURES
  973. panorama_tex->save_exr("res://0_panorama.exr", false);
  974. #endif
  975. }
  976. }
  977. /* STEP 2: create the acceleration structure for the GPU*/
  978. Vector<int> slice_triangle_count;
  979. RID bake_parameters_buffer;
  980. RID vertex_buffer;
  981. RID triangle_buffer;
  982. RID lights_buffer;
  983. RID triangle_indices_buffer;
  984. RID cluster_indices_buffer;
  985. RID cluster_aabbs_buffer;
  986. RID grid_texture;
  987. RID seams_buffer;
  988. RID probe_positions_buffer;
  989. Vector<int> slice_seam_count;
  990. #define FREE_BUFFERS \
  991. rd->free(bake_parameters_buffer); \
  992. rd->free(vertex_buffer); \
  993. rd->free(triangle_buffer); \
  994. rd->free(lights_buffer); \
  995. rd->free(triangle_indices_buffer); \
  996. rd->free(cluster_indices_buffer); \
  997. rd->free(cluster_aabbs_buffer); \
  998. rd->free(grid_texture); \
  999. rd->free(seams_buffer); \
  1000. rd->free(probe_positions_buffer);
  1001. const uint32_t cluster_size = 16;
  1002. _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, cluster_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_indices_buffer, cluster_indices_buffer, cluster_aabbs_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
  1003. // Create global bake parameters buffer.
  1004. BakeParameters bake_parameters;
  1005. bake_parameters.world_size[0] = bounds.size.x;
  1006. bake_parameters.world_size[1] = bounds.size.y;
  1007. bake_parameters.world_size[2] = bounds.size.z;
  1008. bake_parameters.bias = p_bias;
  1009. bake_parameters.to_cell_offset[0] = bounds.position.x;
  1010. bake_parameters.to_cell_offset[1] = bounds.position.y;
  1011. bake_parameters.to_cell_offset[2] = bounds.position.z;
  1012. bake_parameters.grid_size = grid_size;
  1013. bake_parameters.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  1014. bake_parameters.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  1015. bake_parameters.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  1016. bake_parameters.light_count = lights.size();
  1017. bake_parameters.env_transform[0] = p_environment_transform.rows[0][0];
  1018. bake_parameters.env_transform[1] = p_environment_transform.rows[1][0];
  1019. bake_parameters.env_transform[2] = p_environment_transform.rows[2][0];
  1020. bake_parameters.env_transform[3] = 0.0f;
  1021. bake_parameters.env_transform[4] = p_environment_transform.rows[0][1];
  1022. bake_parameters.env_transform[5] = p_environment_transform.rows[1][1];
  1023. bake_parameters.env_transform[6] = p_environment_transform.rows[2][1];
  1024. bake_parameters.env_transform[7] = 0.0f;
  1025. bake_parameters.env_transform[8] = p_environment_transform.rows[0][2];
  1026. bake_parameters.env_transform[9] = p_environment_transform.rows[1][2];
  1027. bake_parameters.env_transform[10] = p_environment_transform.rows[2][2];
  1028. bake_parameters.env_transform[11] = 0.0f;
  1029. bake_parameters.atlas_size[0] = atlas_size.width;
  1030. bake_parameters.atlas_size[1] = atlas_size.height;
  1031. bake_parameters.exposure_normalization = p_exposure_normalization;
  1032. bake_parameters.bounces = p_bounces;
  1033. bake_parameters.bounce_indirect_energy = p_bounce_indirect_energy;
  1034. bake_parameters_buffer = rd->uniform_buffer_create(sizeof(BakeParameters));
  1035. rd->buffer_update(bake_parameters_buffer, 0, sizeof(BakeParameters), &bake_parameters);
  1036. if (p_step_function) {
  1037. p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true);
  1038. }
  1039. //shaders
  1040. Ref<RDShaderFile> raster_shader;
  1041. raster_shader.instantiate();
  1042. err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
  1043. if (err != OK) {
  1044. raster_shader->print_errors("raster_shader");
  1045. FREE_TEXTURES
  1046. FREE_BUFFERS
  1047. memdelete(rd);
  1048. if (rcd != nullptr) {
  1049. memdelete(rcd);
  1050. }
  1051. }
  1052. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1053. RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());
  1054. ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
  1055. RID sampler;
  1056. {
  1057. RD::SamplerState s;
  1058. s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  1059. s.min_filter = RD::SAMPLER_FILTER_LINEAR;
  1060. s.max_lod = 0;
  1061. sampler = rd->sampler_create(s);
  1062. }
  1063. Vector<RD::Uniform> base_uniforms;
  1064. {
  1065. {
  1066. RD::Uniform u;
  1067. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1068. u.binding = 0;
  1069. u.append_id(bake_parameters_buffer);
  1070. base_uniforms.push_back(u);
  1071. }
  1072. {
  1073. RD::Uniform u;
  1074. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1075. u.binding = 1;
  1076. u.append_id(vertex_buffer);
  1077. base_uniforms.push_back(u);
  1078. }
  1079. {
  1080. RD::Uniform u;
  1081. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1082. u.binding = 2;
  1083. u.append_id(triangle_buffer);
  1084. base_uniforms.push_back(u);
  1085. }
  1086. {
  1087. RD::Uniform u;
  1088. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1089. u.binding = 3;
  1090. u.append_id(triangle_indices_buffer);
  1091. base_uniforms.push_back(u);
  1092. }
  1093. {
  1094. RD::Uniform u;
  1095. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1096. u.binding = 4;
  1097. u.append_id(lights_buffer);
  1098. base_uniforms.push_back(u);
  1099. }
  1100. {
  1101. RD::Uniform u;
  1102. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1103. u.binding = 5;
  1104. u.append_id(seams_buffer);
  1105. base_uniforms.push_back(u);
  1106. }
  1107. {
  1108. RD::Uniform u;
  1109. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1110. u.binding = 6;
  1111. u.append_id(probe_positions_buffer);
  1112. base_uniforms.push_back(u);
  1113. }
  1114. {
  1115. RD::Uniform u;
  1116. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1117. u.binding = 7;
  1118. u.append_id(grid_texture);
  1119. base_uniforms.push_back(u);
  1120. }
  1121. {
  1122. RD::Uniform u;
  1123. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1124. u.binding = 8;
  1125. u.append_id(albedo_array_tex);
  1126. base_uniforms.push_back(u);
  1127. }
  1128. {
  1129. RD::Uniform u;
  1130. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1131. u.binding = 9;
  1132. u.append_id(emission_array_tex);
  1133. base_uniforms.push_back(u);
  1134. }
  1135. {
  1136. RD::Uniform u;
  1137. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  1138. u.binding = 10;
  1139. u.append_id(sampler);
  1140. base_uniforms.push_back(u);
  1141. }
  1142. {
  1143. RD::Uniform u;
  1144. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1145. u.binding = 11;
  1146. u.append_id(cluster_indices_buffer);
  1147. base_uniforms.push_back(u);
  1148. }
  1149. {
  1150. RD::Uniform u;
  1151. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1152. u.binding = 12;
  1153. u.append_id(cluster_aabbs_buffer);
  1154. base_uniforms.push_back(u);
  1155. }
  1156. }
  1157. RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
  1158. RID raster_depth_buffer;
  1159. {
  1160. RD::TextureFormat tf;
  1161. tf.width = atlas_size.width;
  1162. tf.height = atlas_size.height;
  1163. tf.depth = 1;
  1164. tf.texture_type = RD::TEXTURE_TYPE_2D;
  1165. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1166. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  1167. raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
  1168. }
  1169. rd->submit();
  1170. rd->sync();
  1171. /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
  1172. _raster_geometry(rd, atlas_size, atlas_slices, grid_size, bounds, p_bias, slice_triangle_count, position_tex, unocclude_tex, normal_tex, raster_depth_buffer, rasterize_shader, raster_base_uniform);
  1173. #ifdef DEBUG_TEXTURES
  1174. for (int i = 0; i < atlas_slices; i++) {
  1175. Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
  1176. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
  1177. img->save_exr("res://1_position_" + itos(i) + ".exr", false);
  1178. s = rd->texture_get_data(normal_tex, i);
  1179. img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1180. img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
  1181. }
  1182. #endif
  1183. #define FREE_RASTER_RESOURCES \
  1184. rd->free(rasterize_shader); \
  1185. rd->free(sampler); \
  1186. rd->free(raster_depth_buffer);
  1187. /* Plot direct light */
  1188. Ref<RDShaderFile> compute_shader;
  1189. String defines = "";
  1190. defines += "\n#define CLUSTER_SIZE " + uitos(cluster_size) + "\n";
  1191. if (p_bake_sh) {
  1192. defines += "\n#define USE_SH_LIGHTMAPS\n";
  1193. }
  1194. if (p_texture_for_bounces) {
  1195. defines += "\n#define USE_LIGHT_TEXTURE_FOR_BOUNCES\n";
  1196. }
  1197. compute_shader.instantiate();
  1198. err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, defines);
  1199. if (err != OK) {
  1200. FREE_TEXTURES
  1201. FREE_BUFFERS
  1202. FREE_RASTER_RESOURCES
  1203. memdelete(rd);
  1204. if (rcd != nullptr) {
  1205. memdelete(rcd);
  1206. }
  1207. compute_shader->print_errors("compute_shader");
  1208. }
  1209. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1210. // Unoccluder
  1211. RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));
  1212. ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  1213. RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
  1214. // Direct light
  1215. RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));
  1216. ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  1217. RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
  1218. // Indirect light
  1219. RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));
  1220. ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  1221. RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
  1222. // Light probes
  1223. RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));
  1224. ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  1225. RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
  1226. RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
  1227. #define FREE_COMPUTE_RESOURCES \
  1228. rd->free(compute_shader_unocclude); \
  1229. rd->free(compute_shader_primary); \
  1230. rd->free(compute_shader_secondary); \
  1231. rd->free(compute_shader_light_probes);
  1232. Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1);
  1233. rd->submit();
  1234. rd->sync();
  1235. if (p_step_function) {
  1236. p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true);
  1237. }
  1238. PushConstant push_constant;
  1239. /* UNOCCLUDE */
  1240. {
  1241. Vector<RD::Uniform> uniforms;
  1242. {
  1243. {
  1244. RD::Uniform u;
  1245. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1246. u.binding = 0;
  1247. u.append_id(position_tex);
  1248. uniforms.push_back(u);
  1249. }
  1250. {
  1251. RD::Uniform u;
  1252. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1253. u.binding = 1;
  1254. u.append_id(unocclude_tex); //will be unused
  1255. uniforms.push_back(u);
  1256. }
  1257. }
  1258. RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
  1259. RD::ComputeListID compute_list = rd->compute_list_begin();
  1260. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
  1261. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1262. rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
  1263. for (int i = 0; i < atlas_slices; i++) {
  1264. push_constant.atlas_slice = i;
  1265. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1266. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1267. //no barrier, let them run all together
  1268. }
  1269. rd->compute_list_end(); //done
  1270. }
  1271. if (p_step_function) {
  1272. p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true);
  1273. }
  1274. // Set ray count to the quality used for direct light and bounces.
  1275. switch (p_quality) {
  1276. case BAKE_QUALITY_LOW: {
  1277. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");
  1278. } break;
  1279. case BAKE_QUALITY_MEDIUM: {
  1280. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");
  1281. } break;
  1282. case BAKE_QUALITY_HIGH: {
  1283. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");
  1284. } break;
  1285. case BAKE_QUALITY_ULTRA: {
  1286. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");
  1287. } break;
  1288. }
  1289. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1290. /* PRIMARY (direct) LIGHT PASS */
  1291. {
  1292. Vector<RD::Uniform> uniforms;
  1293. {
  1294. {
  1295. RD::Uniform u;
  1296. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1297. u.binding = 0;
  1298. u.append_id(light_source_tex);
  1299. uniforms.push_back(u);
  1300. }
  1301. {
  1302. RD::Uniform u;
  1303. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1304. u.binding = 1;
  1305. u.append_id(light_dest_tex); //will be unused
  1306. uniforms.push_back(u);
  1307. }
  1308. {
  1309. RD::Uniform u;
  1310. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1311. u.binding = 2;
  1312. u.append_id(position_tex);
  1313. uniforms.push_back(u);
  1314. }
  1315. {
  1316. RD::Uniform u;
  1317. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1318. u.binding = 3;
  1319. u.append_id(normal_tex);
  1320. uniforms.push_back(u);
  1321. }
  1322. {
  1323. RD::Uniform u;
  1324. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1325. u.binding = 4;
  1326. u.append_id(light_accum_tex);
  1327. uniforms.push_back(u);
  1328. }
  1329. }
  1330. RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
  1331. RD::ComputeListID compute_list = rd->compute_list_begin();
  1332. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
  1333. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1334. rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
  1335. for (int i = 0; i < atlas_slices; i++) {
  1336. push_constant.atlas_slice = i;
  1337. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1338. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1339. //no barrier, let them run all together
  1340. }
  1341. rd->compute_list_end(); //done
  1342. }
  1343. #ifdef DEBUG_TEXTURES
  1344. for (int i = 0; i < atlas_slices; i++) {
  1345. Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
  1346. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1347. img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
  1348. }
  1349. #endif
  1350. /* SECONDARY (indirect) LIGHT PASS(ES) */
  1351. if (p_step_function) {
  1352. p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true);
  1353. }
  1354. if (p_bounces > 0) {
  1355. Vector<RD::Uniform> uniforms;
  1356. {
  1357. {
  1358. // Unused.
  1359. RD::Uniform u;
  1360. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1361. u.binding = 0;
  1362. u.append_id(light_dest_tex);
  1363. uniforms.push_back(u);
  1364. }
  1365. {
  1366. RD::Uniform u;
  1367. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1368. u.binding = 1;
  1369. u.append_id(light_source_tex);
  1370. uniforms.push_back(u);
  1371. }
  1372. {
  1373. RD::Uniform u;
  1374. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1375. u.binding = 2;
  1376. u.append_id(position_tex);
  1377. uniforms.push_back(u);
  1378. }
  1379. {
  1380. RD::Uniform u;
  1381. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1382. u.binding = 3;
  1383. u.append_id(normal_tex);
  1384. uniforms.push_back(u);
  1385. }
  1386. {
  1387. RD::Uniform u;
  1388. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1389. u.binding = 4;
  1390. u.append_id(light_accum_tex);
  1391. uniforms.push_back(u);
  1392. }
  1393. {
  1394. RD::Uniform u;
  1395. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1396. u.binding = 5;
  1397. u.append_id(light_environment_tex);
  1398. uniforms.push_back(u);
  1399. }
  1400. }
  1401. RID secondary_uniform_set;
  1402. secondary_uniform_set = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1403. int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  1404. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
  1405. int x_regions = Math::division_round_up(atlas_size.width, max_region_size);
  1406. int y_regions = Math::division_round_up(atlas_size.height, max_region_size);
  1407. int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
  1408. rd->submit();
  1409. rd->sync();
  1410. int count = 0;
  1411. for (int s = 0; s < atlas_slices; s++) {
  1412. push_constant.atlas_slice = s;
  1413. for (int i = 0; i < x_regions; i++) {
  1414. for (int j = 0; j < y_regions; j++) {
  1415. int x = i * max_region_size;
  1416. int y = j * max_region_size;
  1417. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1418. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1419. push_constant.region_ofs[0] = x;
  1420. push_constant.region_ofs[1] = y;
  1421. group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
  1422. for (int k = 0; k < ray_iterations; k++) {
  1423. RD::ComputeListID compute_list = rd->compute_list_begin();
  1424. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
  1425. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1426. rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set, 1);
  1427. push_constant.ray_from = k * max_rays;
  1428. push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
  1429. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1430. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1431. rd->compute_list_end();
  1432. rd->submit();
  1433. rd->sync();
  1434. count++;
  1435. if (p_step_function) {
  1436. int total = (atlas_slices * x_regions * y_regions * ray_iterations);
  1437. int percent = count * 100 / total;
  1438. float p = float(count) / total * 0.1;
  1439. p_step_function(0.6 + p, vformat(RTR("Integrate indirect lighting %d%%"), percent), p_bake_userdata, false);
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. }
  1446. /* LIGHTPROBES */
  1447. RID light_probe_buffer;
  1448. if (probe_positions.size()) {
  1449. light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
  1450. if (p_step_function) {
  1451. p_step_function(0.7, RTR("Baking lightprobes"), p_bake_userdata, true);
  1452. }
  1453. Vector<RD::Uniform> uniforms;
  1454. {
  1455. {
  1456. RD::Uniform u;
  1457. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1458. u.binding = 0;
  1459. u.append_id(light_probe_buffer);
  1460. uniforms.push_back(u);
  1461. }
  1462. {
  1463. RD::Uniform u;
  1464. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1465. u.binding = 1;
  1466. u.append_id(light_source_tex);
  1467. uniforms.push_back(u);
  1468. }
  1469. {
  1470. RD::Uniform u;
  1471. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1472. u.binding = 2;
  1473. u.append_id(light_environment_tex);
  1474. uniforms.push_back(u);
  1475. }
  1476. }
  1477. RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
  1478. switch (p_quality) {
  1479. case BAKE_QUALITY_LOW: {
  1480. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
  1481. } break;
  1482. case BAKE_QUALITY_MEDIUM: {
  1483. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
  1484. } break;
  1485. case BAKE_QUALITY_HIGH: {
  1486. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
  1487. } break;
  1488. case BAKE_QUALITY_ULTRA: {
  1489. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
  1490. } break;
  1491. }
  1492. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1493. push_constant.probe_count = probe_positions.size();
  1494. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
  1495. int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
  1496. for (int i = 0; i < ray_iterations; i++) {
  1497. RD::ComputeListID compute_list = rd->compute_list_begin();
  1498. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
  1499. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1500. rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
  1501. push_constant.ray_from = i * max_rays;
  1502. push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
  1503. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1504. rd->compute_list_dispatch(compute_list, Math::division_round_up((int)probe_positions.size(), 64), 1, 1);
  1505. rd->compute_list_end(); //done
  1506. rd->submit();
  1507. rd->sync();
  1508. if (p_step_function) {
  1509. int percent = i * 100 / ray_iterations;
  1510. float p = float(i) / ray_iterations * 0.1;
  1511. p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false);
  1512. }
  1513. }
  1514. }
  1515. #if 0
  1516. for (int i = 0; i < probe_positions.size(); i++) {
  1517. Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);
  1518. for (int j = 0; j < 6; j++) {
  1519. Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
  1520. Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);
  1521. img2->convert(Image::FORMAT_RGB8);
  1522. img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
  1523. }
  1524. img->save_png("res://3_light_probe_" + itos(i) + ".png");
  1525. }
  1526. #endif
  1527. /* DENOISE */
  1528. if (p_use_denoiser) {
  1529. if (p_step_function) {
  1530. p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true);
  1531. }
  1532. {
  1533. BakeError error;
  1534. if (denoiser == 1) {
  1535. // OIDN (external).
  1536. error = _denoise_oidn(rd, light_accum_tex, normal_tex, light_accum_tex, atlas_size, atlas_slices, p_bake_sh, oidn_path);
  1537. } else {
  1538. // JNLM (built-in).
  1539. SWAP(light_accum_tex, light_accum_tex2);
  1540. error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, normal_tex, light_accum_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, p_bake_sh, p_step_function);
  1541. }
  1542. if (unlikely(error != BAKE_OK)) {
  1543. return error;
  1544. }
  1545. }
  1546. }
  1547. {
  1548. SWAP(light_accum_tex, light_accum_tex2);
  1549. BakeError error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices * (p_bake_sh ? 4 : 1));
  1550. if (unlikely(error != BAKE_OK)) {
  1551. return error;
  1552. }
  1553. }
  1554. #ifdef DEBUG_TEXTURES
  1555. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1556. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1557. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1558. img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
  1559. }
  1560. #endif
  1561. /* BLEND SEAMS */
  1562. //shaders
  1563. Ref<RDShaderFile> blendseams_shader;
  1564. blendseams_shader.instantiate();
  1565. err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
  1566. if (err != OK) {
  1567. FREE_TEXTURES
  1568. FREE_BUFFERS
  1569. FREE_RASTER_RESOURCES
  1570. FREE_COMPUTE_RESOURCES
  1571. memdelete(rd);
  1572. if (rcd != nullptr) {
  1573. memdelete(rcd);
  1574. }
  1575. blendseams_shader->print_errors("blendseams_shader");
  1576. }
  1577. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1578. RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
  1579. ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1580. RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
  1581. ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1582. #define FREE_BLENDSEAMS_RESOURCES \
  1583. rd->free(blendseams_line_raster_shader); \
  1584. rd->free(blendseams_triangle_raster_shader);
  1585. {
  1586. //pre copy
  1587. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1588. rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
  1589. }
  1590. Vector<RID> framebuffers;
  1591. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1592. RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
  1593. Vector<RID> fb;
  1594. fb.push_back(slice_tex);
  1595. fb.push_back(raster_depth_buffer);
  1596. framebuffers.push_back(rd->framebuffer_create(fb));
  1597. }
  1598. Vector<RD::Uniform> uniforms;
  1599. {
  1600. {
  1601. RD::Uniform u;
  1602. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1603. u.binding = 0;
  1604. u.append_id(light_accum_tex2);
  1605. uniforms.push_back(u);
  1606. }
  1607. }
  1608. RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
  1609. bool debug = false;
  1610. RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
  1611. bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1612. bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1613. RD::PipelineDepthStencilState ds;
  1614. ds.enable_depth_test = true;
  1615. ds.enable_depth_write = true;
  1616. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
  1617. RID blendseams_line_raster_pipeline = rd->render_pipeline_create(blendseams_line_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);
  1618. RID blendseams_triangle_raster_pipeline = rd->render_pipeline_create(blendseams_triangle_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);
  1619. uint32_t seam_offset = 0;
  1620. uint32_t triangle_offset = 0;
  1621. Vector<Color> clear_colors;
  1622. clear_colors.push_back(Color(0, 0, 0, 1));
  1623. for (int i = 0; i < atlas_slices; i++) {
  1624. int subslices = (p_bake_sh ? 4 : 1);
  1625. if (slice_seam_count[i] == 0) {
  1626. continue;
  1627. }
  1628. for (int k = 0; k < subslices; k++) {
  1629. RasterSeamsPushConstant seams_push_constant;
  1630. seams_push_constant.slice = uint32_t(i * subslices + k);
  1631. seams_push_constant.debug = debug;
  1632. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i * subslices + k], RD::INITIAL_ACTION_LOAD, RD::FINAL_ACTION_STORE, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1633. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  1634. rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
  1635. const int uv_offset_count = 9;
  1636. static const Vector3 uv_offsets[uv_offset_count] = {
  1637. Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
  1638. Vector3(0, 1, 0.2),
  1639. Vector3(0, -1, 0.2),
  1640. Vector3(1, 0, 0.2),
  1641. Vector3(-1, 0, 0.2),
  1642. Vector3(-1, -1, 0.1),
  1643. Vector3(1, -1, 0.1),
  1644. Vector3(1, 1, 0.1),
  1645. Vector3(-1, 1, 0.1),
  1646. };
  1647. /* step 1 use lines to blend the edges */
  1648. {
  1649. seams_push_constant.base_index = seam_offset;
  1650. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1651. seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width);
  1652. seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height);
  1653. seams_push_constant.blend = uv_offsets[0].z;
  1654. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1655. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1656. }
  1657. /* step 2 use triangles to mask the interior */
  1658. {
  1659. seams_push_constant.base_index = triangle_offset;
  1660. rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
  1661. seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
  1662. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1663. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  1664. }
  1665. /* step 3 blend around the triangle */
  1666. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1667. for (int j = 1; j < uv_offset_count; j++) {
  1668. seams_push_constant.base_index = seam_offset;
  1669. seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width);
  1670. seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height);
  1671. seams_push_constant.blend = uv_offsets[0].z;
  1672. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1673. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1674. }
  1675. rd->draw_list_end();
  1676. }
  1677. seam_offset += slice_seam_count[i];
  1678. triangle_offset += slice_triangle_count[i];
  1679. }
  1680. }
  1681. #ifdef DEBUG_TEXTURES
  1682. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1683. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1684. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1685. img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
  1686. }
  1687. #endif
  1688. if (p_step_function) {
  1689. p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
  1690. }
  1691. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1692. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1693. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1694. img->convert(Image::FORMAT_RGBH); //remove alpha
  1695. bake_textures.push_back(img);
  1696. }
  1697. if (probe_positions.size() > 0) {
  1698. probe_values.resize(probe_positions.size() * 9);
  1699. Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
  1700. memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
  1701. rd->free(light_probe_buffer);
  1702. #ifdef DEBUG_TEXTURES
  1703. {
  1704. Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
  1705. img2->save_exr("res://6_lightprobes.exr", false);
  1706. }
  1707. #endif
  1708. }
  1709. FREE_TEXTURES
  1710. FREE_BUFFERS
  1711. FREE_RASTER_RESOURCES
  1712. FREE_COMPUTE_RESOURCES
  1713. FREE_BLENDSEAMS_RESOURCES
  1714. memdelete(rd);
  1715. if (rcd != nullptr) {
  1716. memdelete(rcd);
  1717. }
  1718. return BAKE_OK;
  1719. }
  1720. int LightmapperRD::get_bake_texture_count() const {
  1721. return bake_textures.size();
  1722. }
  1723. Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
  1724. ERR_FAIL_INDEX_V(p_index, bake_textures.size(), Ref<Image>());
  1725. return bake_textures[p_index];
  1726. }
  1727. int LightmapperRD::get_bake_mesh_count() const {
  1728. return mesh_instances.size();
  1729. }
  1730. Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
  1731. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1732. return mesh_instances[p_index].data.userdata;
  1733. }
  1734. Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
  1735. ERR_FAIL_COND_V(bake_textures.is_empty(), Rect2());
  1736. Rect2 uv_ofs;
  1737. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1738. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1739. uv_ofs.size = Vector2(mesh_instances[p_index].data.albedo_on_uv2->get_width(), mesh_instances[p_index].data.albedo_on_uv2->get_height()) / atlas_size;
  1740. return uv_ofs;
  1741. }
  1742. int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
  1743. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1744. return mesh_instances[p_index].slice;
  1745. }
  1746. int LightmapperRD::get_bake_probe_count() const {
  1747. return probe_positions.size();
  1748. }
  1749. Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
  1750. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
  1751. return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
  1752. }
  1753. Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
  1754. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
  1755. Vector<Color> ret;
  1756. ret.resize(9);
  1757. memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
  1758. return ret;
  1759. }
  1760. LightmapperRD::LightmapperRD() {
  1761. }