lightmapper_rd.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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/math/geometry_2d.h"
  36. #include "servers/rendering/rendering_device_binds.h"
  37. //uncomment this if you want to see textures from all the process saved
  38. //#define DEBUG_TEXTURES
  39. void LightmapperRD::add_mesh(const MeshData &p_mesh) {
  40. ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
  41. ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
  42. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
  43. ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
  44. ERR_FAIL_COND(p_mesh.points.size() == 0);
  45. MeshInstance mi;
  46. mi.data = p_mesh;
  47. mesh_instances.push_back(mi);
  48. }
  49. void LightmapperRD::add_directional_light(bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_angular_distance, float p_shadow_blur) {
  50. Light l;
  51. l.type = LIGHT_TYPE_DIRECTIONAL;
  52. l.direction[0] = p_direction.x;
  53. l.direction[1] = p_direction.y;
  54. l.direction[2] = p_direction.z;
  55. l.color[0] = p_color.r;
  56. l.color[1] = p_color.g;
  57. l.color[2] = p_color.b;
  58. l.energy = p_energy;
  59. l.static_bake = p_static;
  60. l.size = Math::tan(Math::deg_to_rad(p_angular_distance));
  61. l.shadow_blur = p_shadow_blur;
  62. lights.push_back(l);
  63. }
  64. void LightmapperRD::add_omni_light(bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) {
  65. Light l;
  66. l.type = LIGHT_TYPE_OMNI;
  67. l.position[0] = p_position.x;
  68. l.position[1] = p_position.y;
  69. l.position[2] = p_position.z;
  70. l.range = p_range;
  71. l.attenuation = p_attenuation;
  72. l.color[0] = p_color.r;
  73. l.color[1] = p_color.g;
  74. l.color[2] = p_color.b;
  75. l.energy = p_energy;
  76. l.static_bake = p_static;
  77. l.size = p_size;
  78. l.shadow_blur = p_shadow_blur;
  79. lights.push_back(l);
  80. }
  81. 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_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) {
  82. Light l;
  83. l.type = LIGHT_TYPE_SPOT;
  84. l.position[0] = p_position.x;
  85. l.position[1] = p_position.y;
  86. l.position[2] = p_position.z;
  87. l.direction[0] = p_direction.x;
  88. l.direction[1] = p_direction.y;
  89. l.direction[2] = p_direction.z;
  90. l.range = p_range;
  91. l.attenuation = p_attenuation;
  92. l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));
  93. l.inv_spot_attenuation = 1.0f / p_spot_attenuation;
  94. l.color[0] = p_color.r;
  95. l.color[1] = p_color.g;
  96. l.color[2] = p_color.b;
  97. l.energy = p_energy;
  98. l.static_bake = p_static;
  99. l.size = p_size;
  100. l.shadow_blur = p_shadow_blur;
  101. lights.push_back(l);
  102. }
  103. void LightmapperRD::add_probe(const Vector3 &p_position) {
  104. Probe probe;
  105. probe.position[0] = p_position.x;
  106. probe.position[1] = p_position.y;
  107. probe.position[2] = p_position.z;
  108. probe.position[3] = 0;
  109. probe_positions.push_back(probe);
  110. }
  111. 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> &triangles, uint32_t p_grid_size) {
  112. int half_size = p_size / 2;
  113. for (int i = 0; i < 8; i++) {
  114. AABB aabb = p_bounds;
  115. aabb.size *= 0.5;
  116. Vector3i n = p_ofs;
  117. if (i & 1) {
  118. aabb.position.x += aabb.size.x;
  119. n.x += half_size;
  120. }
  121. if (i & 2) {
  122. aabb.position.y += aabb.size.y;
  123. n.y += half_size;
  124. }
  125. if (i & 4) {
  126. aabb.position.z += aabb.size.z;
  127. n.z += half_size;
  128. }
  129. {
  130. Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
  131. if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
  132. //does not fit in child, go on
  133. continue;
  134. }
  135. }
  136. if (half_size == 1) {
  137. //got to the end
  138. TriangleSort ts;
  139. ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
  140. ts.triangle_index = p_triangle_index;
  141. triangles.push_back(ts);
  142. } else {
  143. _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, triangles, p_grid_size);
  144. }
  145. }
  146. }
  147. Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, 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) {
  148. Vector<Size2i> sizes;
  149. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  150. MeshInstance &mi = mesh_instances.write[m_i];
  151. Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
  152. sizes.push_back(s);
  153. atlas_size.width = MAX(atlas_size.width, s.width + 2);
  154. atlas_size.height = MAX(atlas_size.height, s.height + 2);
  155. }
  156. int max = nearest_power_of_2_templated(atlas_size.width);
  157. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  158. if (max > p_max_texture_size) {
  159. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  160. }
  161. if (p_step_function) {
  162. p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true);
  163. }
  164. atlas_size = Size2i(max, max);
  165. Size2i best_atlas_size;
  166. int best_atlas_slices = 0;
  167. int best_atlas_memory = 0x7FFFFFFF;
  168. Vector<Vector3i> best_atlas_offsets;
  169. //determine best texture array atlas size by bruteforce fitting
  170. while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
  171. Vector<Vector2i> source_sizes;
  172. Vector<int> source_indices;
  173. source_sizes.resize(sizes.size());
  174. source_indices.resize(sizes.size());
  175. for (int i = 0; i < source_indices.size(); i++) {
  176. source_sizes.write[i] = sizes[i] + Vector2i(2, 2); // Add padding between lightmaps
  177. source_indices.write[i] = i;
  178. }
  179. Vector<Vector3i> atlas_offsets;
  180. atlas_offsets.resize(source_sizes.size());
  181. int slices = 0;
  182. while (source_sizes.size() > 0) {
  183. Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
  184. Vector<int> new_indices;
  185. Vector<Vector2i> new_sources;
  186. for (int i = 0; i < offsets.size(); i++) {
  187. Vector3i ofs = offsets[i];
  188. int sidx = source_indices[i];
  189. if (ofs.z > 0) {
  190. //valid
  191. ofs.z = slices;
  192. atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region
  193. } else {
  194. new_indices.push_back(sidx);
  195. new_sources.push_back(source_sizes[i]);
  196. }
  197. }
  198. source_sizes = new_sources;
  199. source_indices = new_indices;
  200. slices++;
  201. }
  202. int mem_used = atlas_size.x * atlas_size.y * slices;
  203. if (mem_used < best_atlas_memory) {
  204. best_atlas_size = atlas_size;
  205. best_atlas_offsets = atlas_offsets;
  206. best_atlas_slices = slices;
  207. best_atlas_memory = mem_used;
  208. }
  209. if (atlas_size.width == atlas_size.height) {
  210. atlas_size.width *= 2;
  211. } else {
  212. atlas_size.height *= 2;
  213. }
  214. }
  215. atlas_size = best_atlas_size;
  216. atlas_slices = best_atlas_slices;
  217. // apply the offsets and slice to all images, and also blit albedo and emission
  218. albedo_images.resize(atlas_slices);
  219. emission_images.resize(atlas_slices);
  220. if (p_step_function) {
  221. p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true);
  222. }
  223. for (int i = 0; i < atlas_slices; i++) {
  224. Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
  225. albedo->set_as_black();
  226. albedo_images.write[i] = albedo;
  227. Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
  228. emission->set_as_black();
  229. emission_images.write[i] = emission;
  230. }
  231. //assign uv positions
  232. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  233. MeshInstance &mi = mesh_instances.write[m_i];
  234. mi.offset.x = best_atlas_offsets[m_i].x;
  235. mi.offset.y = best_atlas_offsets[m_i].y;
  236. mi.slice = best_atlas_offsets[m_i].z;
  237. albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);
  238. emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);
  239. }
  240. return BAKE_OK;
  241. }
  242. void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_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 &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
  243. HashMap<Vertex, uint32_t, VertexHash> vertex_map;
  244. //fill triangles array and vertex array
  245. LocalVector<Triangle> triangles;
  246. LocalVector<Vertex> vertex_array;
  247. LocalVector<Seam> seams;
  248. slice_triangle_count.resize(atlas_slices);
  249. slice_seam_count.resize(atlas_slices);
  250. for (int i = 0; i < atlas_slices; i++) {
  251. slice_triangle_count.write[i] = 0;
  252. slice_seam_count.write[i] = 0;
  253. }
  254. bounds = AABB();
  255. for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
  256. if (p_step_function) {
  257. float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1;
  258. 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);
  259. }
  260. HashMap<Edge, EdgeUV2, EdgeHash> edges;
  261. MeshInstance &mi = mesh_instances.write[m_i];
  262. Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
  263. Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
  264. if (m_i == 0) {
  265. bounds.position = mi.data.points[0];
  266. }
  267. for (int i = 0; i < mi.data.points.size(); i += 3) {
  268. Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
  269. 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 };
  270. Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
  271. AABB taabb;
  272. Triangle t;
  273. t.slice = mi.slice;
  274. for (int k = 0; k < 3; k++) {
  275. bounds.expand_to(vtxs[k]);
  276. Vertex v;
  277. v.position[0] = vtxs[k].x;
  278. v.position[1] = vtxs[k].y;
  279. v.position[2] = vtxs[k].z;
  280. v.uv[0] = uvs[k].x;
  281. v.uv[1] = uvs[k].y;
  282. v.normal_xy[0] = normal[k].x;
  283. v.normal_xy[1] = normal[k].y;
  284. v.normal_z = normal[k].z;
  285. uint32_t *indexptr = vertex_map.getptr(v);
  286. if (indexptr) {
  287. t.indices[k] = *indexptr;
  288. } else {
  289. uint32_t new_index = vertex_map.size();
  290. t.indices[k] = new_index;
  291. vertex_map[v] = new_index;
  292. vertex_array.push_back(v);
  293. }
  294. if (k == 0) {
  295. taabb.position = vtxs[k];
  296. } else {
  297. taabb.expand_to(vtxs[k]);
  298. }
  299. }
  300. //compute seams that will need to be blended later
  301. for (int k = 0; k < 3; k++) {
  302. int n = (k + 1) % 3;
  303. Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
  304. Vector2i edge_indices(t.indices[k], t.indices[n]);
  305. EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
  306. if (edge.b == edge.a) {
  307. continue; //degenerate, somehow
  308. }
  309. if (edge.b < edge.a) {
  310. SWAP(edge.a, edge.b);
  311. SWAP(edge.na, edge.nb);
  312. SWAP(uv2.a, uv2.b);
  313. SWAP(edge_indices.x, edge_indices.y);
  314. }
  315. EdgeUV2 *euv2 = edges.getptr(edge);
  316. if (!euv2) {
  317. edges[edge] = uv2;
  318. } else {
  319. if (*euv2 == uv2) {
  320. continue; // seam shared UV space, no need to blend
  321. }
  322. if (euv2->seam_found) {
  323. continue; //bad geometry
  324. }
  325. Seam seam;
  326. seam.a = edge_indices;
  327. seam.b = euv2->indices;
  328. seam.slice = mi.slice;
  329. seams.push_back(seam);
  330. slice_seam_count.write[mi.slice]++;
  331. euv2->seam_found = true;
  332. }
  333. }
  334. t.min_bounds[0] = taabb.position.x;
  335. t.min_bounds[1] = taabb.position.y;
  336. t.min_bounds[2] = taabb.position.z;
  337. t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
  338. t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
  339. t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
  340. t.pad0 = t.pad1 = 0; //make valgrind not complain
  341. triangles.push_back(t);
  342. slice_triangle_count.write[t.slice]++;
  343. }
  344. }
  345. //also consider probe positions for bounds
  346. for (int i = 0; i < p_probe_positions.size(); i++) {
  347. Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]);
  348. bounds.expand_to(pp);
  349. }
  350. bounds.grow_by(0.1); //grow a bit to avoid numerical error
  351. triangles.sort(); //sort by slice
  352. seams.sort();
  353. if (p_step_function) {
  354. p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);
  355. }
  356. //fill list of triangles in grid
  357. LocalVector<TriangleSort> triangle_sort;
  358. for (uint32_t i = 0; i < triangles.size(); i++) {
  359. const Triangle &t = triangles[i];
  360. Vector3 face[3] = {
  361. Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
  362. Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
  363. Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
  364. };
  365. _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
  366. }
  367. //sort it
  368. triangle_sort.sort();
  369. Vector<uint32_t> triangle_indices;
  370. triangle_indices.resize(triangle_sort.size());
  371. Vector<uint32_t> grid_indices;
  372. grid_indices.resize(grid_size * grid_size * grid_size * 2);
  373. memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));
  374. Vector<bool> solid;
  375. solid.resize(grid_size * grid_size * grid_size);
  376. memset(solid.ptrw(), 0, solid.size() * sizeof(bool));
  377. {
  378. uint32_t *tiw = triangle_indices.ptrw();
  379. uint32_t last_cell = 0xFFFFFFFF;
  380. uint32_t *giw = grid_indices.ptrw();
  381. bool *solidw = solid.ptrw();
  382. for (uint32_t i = 0; i < triangle_sort.size(); i++) {
  383. uint32_t cell = triangle_sort[i].cell_index;
  384. if (cell != last_cell) {
  385. //cell changed, update pointer to indices
  386. giw[cell * 2 + 1] = i;
  387. solidw[cell] = true;
  388. }
  389. tiw[i] = triangle_sort[i].triangle_index;
  390. giw[cell * 2]++; //update counter
  391. last_cell = cell;
  392. }
  393. }
  394. #if 0
  395. for (int i = 0; i < grid_size; i++) {
  396. for (int j = 0; j < grid_size; j++) {
  397. for (int k = 0; k < grid_size; k++) {
  398. uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
  399. grid_indices.write[index * 2] = float(i) / grid_size * 255;
  400. grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
  401. }
  402. }
  403. }
  404. #endif
  405. #if 0
  406. for (int i = 0; i < grid_size; i++) {
  407. Vector<uint8_t> grid_usage;
  408. grid_usage.resize(grid_size * grid_size);
  409. for (int j = 0; j < grid_usage.size(); j++) {
  410. uint32_t ofs = i * grid_size * grid_size + j;
  411. uint32_t count = grid_indices[ofs * 2];
  412. grid_usage.write[j] = count > 0 ? 255 : 0;
  413. }
  414. Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
  415. img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
  416. }
  417. #endif
  418. /*****************************/
  419. /*** CREATE GPU STRUCTURES ***/
  420. /*****************************/
  421. lights.sort();
  422. Vector<Vector2i> seam_buffer_vec;
  423. seam_buffer_vec.resize(seams.size() * 2);
  424. for (uint32_t i = 0; i < seams.size(); i++) {
  425. seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
  426. seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
  427. }
  428. { //buffers
  429. Vector<uint8_t> vb = vertex_array.to_byte_array();
  430. vertex_buffer = rd->storage_buffer_create(vb.size(), vb);
  431. Vector<uint8_t> tb = triangles.to_byte_array();
  432. triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
  433. Vector<uint8_t> tib = triangle_indices.to_byte_array();
  434. triangle_cell_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
  435. Vector<uint8_t> lb = lights.to_byte_array();
  436. if (lb.size() == 0) {
  437. lb.resize(sizeof(Light)); //even if no lights, the buffer must exist
  438. }
  439. lights_buffer = rd->storage_buffer_create(lb.size(), lb);
  440. Vector<uint8_t> sb = seam_buffer_vec.to_byte_array();
  441. if (sb.size() == 0) {
  442. sb.resize(sizeof(Vector2i) * 2); //even if no seams, the buffer must exist
  443. }
  444. seams_buffer = rd->storage_buffer_create(sb.size(), sb);
  445. Vector<uint8_t> pb = p_probe_positions.to_byte_array();
  446. if (pb.size() == 0) {
  447. pb.resize(sizeof(Probe));
  448. }
  449. probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
  450. }
  451. { //grid
  452. RD::TextureFormat tf;
  453. tf.width = grid_size;
  454. tf.height = grid_size;
  455. tf.depth = grid_size;
  456. tf.texture_type = RD::TEXTURE_TYPE_3D;
  457. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  458. Vector<Vector<uint8_t>> texdata;
  459. texdata.resize(1);
  460. //grid and indices
  461. tf.format = RD::DATA_FORMAT_R32G32_UINT;
  462. texdata.write[0] = grid_indices.to_byte_array();
  463. grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
  464. }
  465. }
  466. 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) {
  467. Vector<RID> framebuffers;
  468. for (int i = 0; i < atlas_slices; i++) {
  469. RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
  470. RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
  471. RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
  472. Vector<RID> fb;
  473. fb.push_back(slice_pos_tex);
  474. fb.push_back(slice_norm_tex);
  475. fb.push_back(slice_unoc_tex);
  476. fb.push_back(raster_depth_buffer);
  477. framebuffers.push_back(rd->framebuffer_create(fb));
  478. }
  479. RD::PipelineDepthStencilState ds;
  480. ds.enable_depth_test = true;
  481. ds.enable_depth_write = true;
  482. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
  483. 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);
  484. RID raster_pipeline_wire;
  485. {
  486. RD::PipelineRasterizationState rw;
  487. rw.wireframe = true;
  488. 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);
  489. }
  490. uint32_t triangle_offset = 0;
  491. Vector<Color> clear_colors;
  492. clear_colors.push_back(Color(0, 0, 0, 0));
  493. clear_colors.push_back(Color(0, 0, 0, 0));
  494. clear_colors.push_back(Color(0, 0, 0, 0));
  495. for (int i = 0; i < atlas_slices; i++) {
  496. RasterPushConstant raster_push_constant;
  497. raster_push_constant.atlas_size[0] = atlas_size.x;
  498. raster_push_constant.atlas_size[1] = atlas_size.y;
  499. raster_push_constant.base_triangle = triangle_offset;
  500. raster_push_constant.to_cell_offset[0] = bounds.position.x;
  501. raster_push_constant.to_cell_offset[1] = bounds.position.y;
  502. raster_push_constant.to_cell_offset[2] = bounds.position.z;
  503. raster_push_constant.bias = p_bias;
  504. raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  505. raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  506. raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  507. raster_push_constant.grid_size[0] = grid_size;
  508. raster_push_constant.grid_size[1] = grid_size;
  509. raster_push_constant.grid_size[2] = grid_size;
  510. // Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels.
  511. // This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to
  512. // be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>.
  513. raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x);
  514. raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y);
  515. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  516. //draw opaque
  517. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
  518. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  519. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  520. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  521. //draw wire
  522. rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
  523. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  524. rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
  525. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  526. rd->draw_list_end();
  527. triangle_offset += slice_triangle_count[i];
  528. }
  529. }
  530. 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) {
  531. Vector<RD::Uniform> uniforms;
  532. {
  533. {
  534. RD::Uniform u;
  535. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  536. u.binding = 0;
  537. u.append_id(dest_light_tex);
  538. uniforms.push_back(u);
  539. }
  540. {
  541. RD::Uniform u;
  542. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  543. u.binding = 1;
  544. u.append_id(source_light_tex);
  545. uniforms.push_back(u);
  546. }
  547. }
  548. RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));
  549. ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  550. RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
  551. RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
  552. RD::ComputeListID compute_list = rd->compute_list_begin();
  553. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
  554. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  555. rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
  556. push_constant.region_ofs[0] = 0;
  557. push_constant.region_ofs[1] = 0;
  558. Vector3i group_size((atlas_size.x - 1) / 8 + 1, (atlas_size.y - 1) / 8 + 1, 1); //restore group size
  559. for (int i = 0; i < atlas_slices; i++) {
  560. push_constant.atlas_slice = i;
  561. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  562. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  563. //no barrier, let them run all together
  564. }
  565. rd->compute_list_end();
  566. rd->free(compute_shader_dilate);
  567. #ifdef DEBUG_TEXTURES
  568. for (int i = 0; i < atlas_slices; i++) {
  569. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  570. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  571. img->convert(Image::FORMAT_RGBA8);
  572. img->save_png("res://5_dilated_" + itos(i) + ".png");
  573. }
  574. #endif
  575. return BAKE_OK;
  576. }
  577. LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, int p_bounces, float p_bias, int p_max_texture_size, bool p_bake_sh, 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) {
  578. if (p_step_function) {
  579. p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);
  580. }
  581. bake_textures.clear();
  582. int grid_size = 128;
  583. /* STEP 1: Fetch material textures and compute the bounds */
  584. AABB bounds;
  585. Size2i atlas_size;
  586. int atlas_slices;
  587. Vector<Ref<Image>> albedo_images;
  588. Vector<Ref<Image>> emission_images;
  589. BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_step_function, p_bake_userdata);
  590. if (bake_error != BAKE_OK) {
  591. return bake_error;
  592. }
  593. #ifdef DEBUG_TEXTURES
  594. for (int i = 0; i < atlas_slices; i++) {
  595. albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
  596. emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
  597. }
  598. #endif
  599. RenderingDevice *rd = RenderingDevice::get_singleton()->create_local_device();
  600. RID albedo_array_tex;
  601. RID emission_array_tex;
  602. RID normal_tex;
  603. RID position_tex;
  604. RID unocclude_tex;
  605. RID light_source_tex;
  606. RID light_dest_tex;
  607. RID light_accum_tex;
  608. RID light_accum_tex2;
  609. RID light_primary_dynamic_tex;
  610. RID light_environment_tex;
  611. #define FREE_TEXTURES \
  612. rd->free(albedo_array_tex); \
  613. rd->free(emission_array_tex); \
  614. rd->free(normal_tex); \
  615. rd->free(position_tex); \
  616. rd->free(unocclude_tex); \
  617. rd->free(light_source_tex); \
  618. rd->free(light_accum_tex2); \
  619. rd->free(light_accum_tex); \
  620. rd->free(light_primary_dynamic_tex); \
  621. rd->free(light_environment_tex);
  622. { // create all textures
  623. Vector<Vector<uint8_t>> albedo_data;
  624. Vector<Vector<uint8_t>> emission_data;
  625. for (int i = 0; i < atlas_slices; i++) {
  626. albedo_data.push_back(albedo_images[i]->get_data());
  627. emission_data.push_back(emission_images[i]->get_data());
  628. }
  629. RD::TextureFormat tf;
  630. tf.width = atlas_size.width;
  631. tf.height = atlas_size.height;
  632. tf.array_layers = atlas_slices;
  633. tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
  634. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  635. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  636. albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
  637. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  638. emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
  639. //this will be rastered to
  640. 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;
  641. normal_tex = rd->texture_create(tf, RD::TextureView());
  642. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  643. position_tex = rd->texture_create(tf, RD::TextureView());
  644. unocclude_tex = rd->texture_create(tf, RD::TextureView());
  645. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  646. 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;
  647. light_source_tex = rd->texture_create(tf, RD::TextureView());
  648. rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  649. light_primary_dynamic_tex = rd->texture_create(tf, RD::TextureView());
  650. rd->texture_clear(light_primary_dynamic_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
  651. if (p_bake_sh) {
  652. tf.array_layers *= 4;
  653. }
  654. light_accum_tex = rd->texture_create(tf, RD::TextureView());
  655. rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  656. light_dest_tex = rd->texture_create(tf, RD::TextureView());
  657. rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
  658. light_accum_tex2 = light_dest_tex;
  659. //env
  660. {
  661. Ref<Image> panorama_tex;
  662. if (p_environment_panorama.is_valid()) {
  663. panorama_tex = p_environment_panorama;
  664. panorama_tex->convert(Image::FORMAT_RGBAF);
  665. } else {
  666. panorama_tex.instantiate();
  667. panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);
  668. panorama_tex->fill(Color(0, 0, 0, 1));
  669. }
  670. RD::TextureFormat tfp;
  671. tfp.width = panorama_tex->get_width();
  672. tfp.height = panorama_tex->get_height();
  673. tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
  674. tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  675. Vector<Vector<uint8_t>> tdata;
  676. tdata.push_back(panorama_tex->get_data());
  677. light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
  678. #ifdef DEBUG_TEXTURES
  679. panorama_tex->save_exr("res://0_panorama.exr", false);
  680. #endif
  681. }
  682. }
  683. /* STEP 2: create the acceleration structure for the GPU*/
  684. Vector<int> slice_triangle_count;
  685. RID vertex_buffer;
  686. RID triangle_buffer;
  687. RID lights_buffer;
  688. RID triangle_cell_indices_buffer;
  689. RID grid_texture;
  690. RID seams_buffer;
  691. RID probe_positions_buffer;
  692. Vector<int> slice_seam_count;
  693. #define FREE_BUFFERS \
  694. rd->free(vertex_buffer); \
  695. rd->free(triangle_buffer); \
  696. rd->free(lights_buffer); \
  697. rd->free(triangle_cell_indices_buffer); \
  698. rd->free(grid_texture); \
  699. rd->free(seams_buffer); \
  700. rd->free(probe_positions_buffer);
  701. _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
  702. if (p_step_function) {
  703. p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true);
  704. }
  705. //shaders
  706. Ref<RDShaderFile> raster_shader;
  707. raster_shader.instantiate();
  708. Error err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
  709. if (err != OK) {
  710. raster_shader->print_errors("raster_shader");
  711. FREE_TEXTURES
  712. FREE_BUFFERS
  713. memdelete(rd);
  714. }
  715. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  716. RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());
  717. ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
  718. RID sampler;
  719. {
  720. RD::SamplerState s;
  721. s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  722. s.min_filter = RD::SAMPLER_FILTER_LINEAR;
  723. s.max_lod = 0;
  724. sampler = rd->sampler_create(s);
  725. }
  726. Vector<RD::Uniform> base_uniforms;
  727. {
  728. {
  729. RD::Uniform u;
  730. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  731. u.binding = 1;
  732. u.append_id(vertex_buffer);
  733. base_uniforms.push_back(u);
  734. }
  735. {
  736. RD::Uniform u;
  737. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  738. u.binding = 2;
  739. u.append_id(triangle_buffer);
  740. base_uniforms.push_back(u);
  741. }
  742. {
  743. RD::Uniform u;
  744. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  745. u.binding = 3;
  746. u.append_id(triangle_cell_indices_buffer);
  747. base_uniforms.push_back(u);
  748. }
  749. {
  750. RD::Uniform u;
  751. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  752. u.binding = 4;
  753. u.append_id(lights_buffer);
  754. base_uniforms.push_back(u);
  755. }
  756. {
  757. RD::Uniform u;
  758. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  759. u.binding = 5;
  760. u.append_id(seams_buffer);
  761. base_uniforms.push_back(u);
  762. }
  763. {
  764. RD::Uniform u;
  765. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  766. u.binding = 6;
  767. u.append_id(probe_positions_buffer);
  768. base_uniforms.push_back(u);
  769. }
  770. {
  771. RD::Uniform u;
  772. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  773. u.binding = 7;
  774. u.append_id(grid_texture);
  775. base_uniforms.push_back(u);
  776. }
  777. {
  778. RD::Uniform u;
  779. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  780. u.binding = 8;
  781. u.append_id(albedo_array_tex);
  782. base_uniforms.push_back(u);
  783. }
  784. {
  785. RD::Uniform u;
  786. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  787. u.binding = 9;
  788. u.append_id(emission_array_tex);
  789. base_uniforms.push_back(u);
  790. }
  791. {
  792. RD::Uniform u;
  793. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  794. u.binding = 10;
  795. u.append_id(sampler);
  796. base_uniforms.push_back(u);
  797. }
  798. }
  799. RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
  800. RID raster_depth_buffer;
  801. {
  802. RD::TextureFormat tf;
  803. tf.width = atlas_size.width;
  804. tf.height = atlas_size.height;
  805. tf.depth = 1;
  806. tf.texture_type = RD::TEXTURE_TYPE_2D;
  807. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  808. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  809. raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
  810. }
  811. rd->submit();
  812. rd->sync();
  813. /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
  814. _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);
  815. #ifdef DEBUG_TEXTURES
  816. for (int i = 0; i < atlas_slices; i++) {
  817. Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
  818. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
  819. img->save_exr("res://1_position_" + itos(i) + ".exr", false);
  820. s = rd->texture_get_data(normal_tex, i);
  821. img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  822. img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
  823. }
  824. #endif
  825. #define FREE_RASTER_RESOURCES \
  826. rd->free(rasterize_shader); \
  827. rd->free(sampler); \
  828. rd->free(raster_depth_buffer);
  829. /* Plot direct light */
  830. Ref<RDShaderFile> compute_shader;
  831. compute_shader.instantiate();
  832. err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, p_bake_sh ? "\n#define USE_SH_LIGHTMAPS\n" : "");
  833. if (err != OK) {
  834. FREE_TEXTURES
  835. FREE_BUFFERS
  836. FREE_RASTER_RESOURCES
  837. memdelete(rd);
  838. compute_shader->print_errors("compute_shader");
  839. }
  840. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  841. // Unoccluder
  842. RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));
  843. ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  844. RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
  845. // Direct light
  846. RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));
  847. ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
  848. RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
  849. // Indirect light
  850. RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));
  851. ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  852. RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
  853. // Light probes
  854. RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));
  855. ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
  856. RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
  857. RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
  858. #define FREE_COMPUTE_RESOURCES \
  859. rd->free(compute_shader_unocclude); \
  860. rd->free(compute_shader_primary); \
  861. rd->free(compute_shader_secondary); \
  862. rd->free(compute_shader_light_probes);
  863. PushConstant push_constant;
  864. {
  865. //set defaults
  866. push_constant.atlas_size[0] = atlas_size.width;
  867. push_constant.atlas_size[1] = atlas_size.height;
  868. push_constant.world_size[0] = bounds.size.x;
  869. push_constant.world_size[1] = bounds.size.y;
  870. push_constant.world_size[2] = bounds.size.z;
  871. push_constant.to_cell_offset[0] = bounds.position.x;
  872. push_constant.to_cell_offset[1] = bounds.position.y;
  873. push_constant.to_cell_offset[2] = bounds.position.z;
  874. push_constant.bias = p_bias;
  875. push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
  876. push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
  877. push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
  878. push_constant.light_count = lights.size();
  879. push_constant.grid_size = grid_size;
  880. push_constant.atlas_slice = 0;
  881. push_constant.region_ofs[0] = 0;
  882. push_constant.region_ofs[1] = 0;
  883. push_constant.environment_xform[0] = p_environment_transform.rows[0][0];
  884. push_constant.environment_xform[1] = p_environment_transform.rows[1][0];
  885. push_constant.environment_xform[2] = p_environment_transform.rows[2][0];
  886. push_constant.environment_xform[3] = 0;
  887. push_constant.environment_xform[4] = p_environment_transform.rows[0][1];
  888. push_constant.environment_xform[5] = p_environment_transform.rows[1][1];
  889. push_constant.environment_xform[6] = p_environment_transform.rows[2][1];
  890. push_constant.environment_xform[7] = 0;
  891. push_constant.environment_xform[8] = p_environment_transform.rows[0][2];
  892. push_constant.environment_xform[9] = p_environment_transform.rows[1][2];
  893. push_constant.environment_xform[10] = p_environment_transform.rows[2][2];
  894. push_constant.environment_xform[11] = 0;
  895. }
  896. Vector3i group_size((atlas_size.x - 1) / 8 + 1, (atlas_size.y - 1) / 8 + 1, 1);
  897. rd->submit();
  898. rd->sync();
  899. if (p_step_function) {
  900. p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true);
  901. }
  902. /* UNOCCLUDE */
  903. {
  904. Vector<RD::Uniform> uniforms;
  905. {
  906. {
  907. RD::Uniform u;
  908. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  909. u.binding = 0;
  910. u.append_id(position_tex);
  911. uniforms.push_back(u);
  912. }
  913. {
  914. RD::Uniform u;
  915. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  916. u.binding = 1;
  917. u.append_id(unocclude_tex); //will be unused
  918. uniforms.push_back(u);
  919. }
  920. }
  921. RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
  922. RD::ComputeListID compute_list = rd->compute_list_begin();
  923. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
  924. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  925. rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
  926. for (int i = 0; i < atlas_slices; i++) {
  927. push_constant.atlas_slice = i;
  928. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  929. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  930. //no barrier, let them run all together
  931. }
  932. rd->compute_list_end(); //done
  933. }
  934. if (p_step_function) {
  935. p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true);
  936. }
  937. /* PRIMARY (direct) LIGHT PASS */
  938. {
  939. Vector<RD::Uniform> uniforms;
  940. {
  941. {
  942. RD::Uniform u;
  943. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  944. u.binding = 0;
  945. u.append_id(light_source_tex);
  946. uniforms.push_back(u);
  947. }
  948. {
  949. RD::Uniform u;
  950. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  951. u.binding = 1;
  952. u.append_id(light_dest_tex); //will be unused
  953. uniforms.push_back(u);
  954. }
  955. {
  956. RD::Uniform u;
  957. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  958. u.binding = 2;
  959. u.append_id(position_tex);
  960. uniforms.push_back(u);
  961. }
  962. {
  963. RD::Uniform u;
  964. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  965. u.binding = 3;
  966. u.append_id(normal_tex);
  967. uniforms.push_back(u);
  968. }
  969. {
  970. RD::Uniform u;
  971. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  972. u.binding = 4;
  973. u.append_id(light_accum_tex);
  974. uniforms.push_back(u);
  975. }
  976. {
  977. RD::Uniform u;
  978. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  979. u.binding = 5;
  980. u.append_id(light_primary_dynamic_tex);
  981. uniforms.push_back(u);
  982. }
  983. }
  984. RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
  985. switch (p_quality) {
  986. case BAKE_QUALITY_LOW: {
  987. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");
  988. } break;
  989. case BAKE_QUALITY_MEDIUM: {
  990. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");
  991. } break;
  992. case BAKE_QUALITY_HIGH: {
  993. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");
  994. } break;
  995. case BAKE_QUALITY_ULTRA: {
  996. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");
  997. } break;
  998. }
  999. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1000. RD::ComputeListID compute_list = rd->compute_list_begin();
  1001. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
  1002. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1003. rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
  1004. push_constant.environment_xform[11] = p_exposure_normalization;
  1005. for (int i = 0; i < atlas_slices; i++) {
  1006. push_constant.atlas_slice = i;
  1007. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1008. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1009. //no barrier, let them run all together
  1010. }
  1011. rd->compute_list_end(); //done
  1012. push_constant.environment_xform[11] = 0.0;
  1013. }
  1014. #ifdef DEBUG_TEXTURES
  1015. for (int i = 0; i < atlas_slices; i++) {
  1016. Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
  1017. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1018. img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
  1019. }
  1020. #endif
  1021. /* SECONDARY (indirect) LIGHT PASS(ES) */
  1022. if (p_step_function) {
  1023. p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true);
  1024. }
  1025. if (p_bounces > 0) {
  1026. Vector<RD::Uniform> uniforms;
  1027. {
  1028. {
  1029. RD::Uniform u;
  1030. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1031. u.binding = 0;
  1032. u.append_id(light_dest_tex);
  1033. uniforms.push_back(u);
  1034. }
  1035. {
  1036. RD::Uniform u;
  1037. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1038. u.binding = 1;
  1039. u.append_id(light_source_tex);
  1040. uniforms.push_back(u);
  1041. }
  1042. {
  1043. RD::Uniform u;
  1044. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1045. u.binding = 2;
  1046. u.append_id(position_tex);
  1047. uniforms.push_back(u);
  1048. }
  1049. {
  1050. RD::Uniform u;
  1051. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1052. u.binding = 3;
  1053. u.append_id(normal_tex);
  1054. uniforms.push_back(u);
  1055. }
  1056. {
  1057. RD::Uniform u;
  1058. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1059. u.binding = 4;
  1060. u.append_id(light_accum_tex);
  1061. uniforms.push_back(u);
  1062. }
  1063. {
  1064. RD::Uniform u;
  1065. u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
  1066. u.binding = 5;
  1067. u.append_id(unocclude_tex); //reuse unocclude tex
  1068. uniforms.push_back(u);
  1069. }
  1070. {
  1071. RD::Uniform u;
  1072. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1073. u.binding = 6;
  1074. u.append_id(light_environment_tex);
  1075. uniforms.push_back(u);
  1076. }
  1077. }
  1078. RID secondary_uniform_set[2];
  1079. secondary_uniform_set[0] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1080. uniforms.write[0].set_id(0, light_source_tex);
  1081. uniforms.write[1].set_id(0, light_dest_tex);
  1082. secondary_uniform_set[1] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
  1083. int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
  1084. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
  1085. int x_regions = (atlas_size.width - 1) / max_region_size + 1;
  1086. int y_regions = (atlas_size.height - 1) / max_region_size + 1;
  1087. int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
  1088. rd->submit();
  1089. rd->sync();
  1090. for (int b = 0; b < p_bounces; b++) {
  1091. int count = 0;
  1092. if (b > 0) {
  1093. SWAP(light_source_tex, light_dest_tex);
  1094. SWAP(secondary_uniform_set[0], secondary_uniform_set[1]);
  1095. }
  1096. for (int s = 0; s < atlas_slices; s++) {
  1097. push_constant.atlas_slice = s;
  1098. for (int i = 0; i < x_regions; i++) {
  1099. for (int j = 0; j < y_regions; j++) {
  1100. int x = i * max_region_size;
  1101. int y = j * max_region_size;
  1102. int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
  1103. int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
  1104. push_constant.region_ofs[0] = x;
  1105. push_constant.region_ofs[1] = y;
  1106. group_size = Vector3i((w - 1) / 8 + 1, (h - 1) / 8 + 1, 1);
  1107. for (int k = 0; k < ray_iterations; k++) {
  1108. RD::ComputeListID compute_list = rd->compute_list_begin();
  1109. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
  1110. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1111. rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set[0], 1);
  1112. push_constant.ray_from = k * max_rays;
  1113. push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
  1114. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1115. rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
  1116. rd->compute_list_end(); //done
  1117. rd->submit();
  1118. rd->sync();
  1119. count++;
  1120. if (p_step_function) {
  1121. int total = (atlas_slices * x_regions * y_regions * ray_iterations);
  1122. int percent = count * 100 / total;
  1123. float p = float(count) / total * 0.1;
  1124. p_step_function(0.6 + p, vformat(RTR("Bounce %d/%d: Integrate indirect lighting %d%%"), b + 1, p_bounces, percent), p_bake_userdata, false);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. if (b == 0) {
  1131. // This disables the environment for subsequent bounces
  1132. push_constant.environment_xform[3] = -99.0f;
  1133. }
  1134. }
  1135. // Restore the correct environment transform
  1136. push_constant.environment_xform[3] = 0.0f;
  1137. }
  1138. /* LIGHTPROBES */
  1139. RID light_probe_buffer;
  1140. if (probe_positions.size()) {
  1141. light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
  1142. if (p_step_function) {
  1143. p_step_function(0.7, RTR("Baking lightprobes"), p_bake_userdata, true);
  1144. }
  1145. Vector<RD::Uniform> uniforms;
  1146. {
  1147. {
  1148. RD::Uniform u;
  1149. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1150. u.binding = 0;
  1151. u.append_id(light_probe_buffer);
  1152. uniforms.push_back(u);
  1153. }
  1154. {
  1155. RD::Uniform u;
  1156. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1157. u.binding = 1;
  1158. u.append_id(light_dest_tex);
  1159. uniforms.push_back(u);
  1160. }
  1161. {
  1162. RD::Uniform u;
  1163. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1164. u.binding = 2;
  1165. u.append_id(light_primary_dynamic_tex);
  1166. uniforms.push_back(u);
  1167. }
  1168. {
  1169. RD::Uniform u;
  1170. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1171. u.binding = 3;
  1172. u.append_id(light_environment_tex);
  1173. uniforms.push_back(u);
  1174. }
  1175. }
  1176. RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
  1177. switch (p_quality) {
  1178. case BAKE_QUALITY_LOW: {
  1179. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
  1180. } break;
  1181. case BAKE_QUALITY_MEDIUM: {
  1182. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
  1183. } break;
  1184. case BAKE_QUALITY_HIGH: {
  1185. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
  1186. } break;
  1187. case BAKE_QUALITY_ULTRA: {
  1188. push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
  1189. } break;
  1190. }
  1191. push_constant.atlas_size[0] = probe_positions.size();
  1192. push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
  1193. int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
  1194. int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
  1195. for (int i = 0; i < ray_iterations; i++) {
  1196. RD::ComputeListID compute_list = rd->compute_list_begin();
  1197. rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
  1198. rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
  1199. rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
  1200. push_constant.ray_from = i * max_rays;
  1201. push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
  1202. rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
  1203. rd->compute_list_dispatch(compute_list, (probe_positions.size() - 1) / 64 + 1, 1, 1);
  1204. rd->compute_list_end(); //done
  1205. rd->submit();
  1206. rd->sync();
  1207. if (p_step_function) {
  1208. int percent = i * 100 / ray_iterations;
  1209. float p = float(i) / ray_iterations * 0.1;
  1210. p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false);
  1211. }
  1212. }
  1213. push_constant.atlas_size[0] = atlas_size.x; //restore
  1214. }
  1215. #if 0
  1216. for (int i = 0; i < probe_positions.size(); i++) {
  1217. Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);
  1218. for (int j = 0; j < 6; j++) {
  1219. Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
  1220. Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);
  1221. img2->convert(Image::FORMAT_RGB8);
  1222. img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
  1223. }
  1224. img->save_png("res://3_light_probe_" + itos(i) + ".png");
  1225. }
  1226. #endif
  1227. {
  1228. SWAP(light_accum_tex, light_accum_tex2);
  1229. 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));
  1230. if (unlikely(error != BAKE_OK)) {
  1231. return error;
  1232. }
  1233. }
  1234. /* DENOISE */
  1235. if (p_use_denoiser) {
  1236. if (p_step_function) {
  1237. p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true);
  1238. }
  1239. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  1240. if (denoiser.is_valid()) {
  1241. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1242. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1243. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1244. Ref<Image> denoised = denoiser->denoise_image(img);
  1245. if (denoised != img) {
  1246. denoised->convert(Image::FORMAT_RGBAH);
  1247. Vector<uint8_t> ds = denoised->get_data();
  1248. denoised.unref(); //avoid copy on write
  1249. { //restore alpha
  1250. uint32_t count = s.size() / 2; //uint16s
  1251. const uint16_t *src = (const uint16_t *)s.ptr();
  1252. uint16_t *dst = (uint16_t *)ds.ptrw();
  1253. for (uint32_t j = 0; j < count; j += 4) {
  1254. dst[j + 3] = src[j + 3];
  1255. }
  1256. }
  1257. rd->texture_update(light_accum_tex, i, ds);
  1258. }
  1259. }
  1260. }
  1261. {
  1262. SWAP(light_accum_tex, light_accum_tex2);
  1263. 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));
  1264. if (unlikely(error != BAKE_OK)) {
  1265. return error;
  1266. }
  1267. }
  1268. }
  1269. #ifdef DEBUG_TEXTURES
  1270. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1271. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1272. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1273. img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
  1274. }
  1275. #endif
  1276. /* BLEND SEAMS */
  1277. //shaders
  1278. Ref<RDShaderFile> blendseams_shader;
  1279. blendseams_shader.instantiate();
  1280. err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
  1281. if (err != OK) {
  1282. FREE_TEXTURES
  1283. FREE_BUFFERS
  1284. FREE_RASTER_RESOURCES
  1285. FREE_COMPUTE_RESOURCES
  1286. memdelete(rd);
  1287. blendseams_shader->print_errors("blendseams_shader");
  1288. }
  1289. ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1290. RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
  1291. ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1292. RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
  1293. ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
  1294. #define FREE_BLENDSEAMS_RESOURCES \
  1295. rd->free(blendseams_line_raster_shader); \
  1296. rd->free(blendseams_triangle_raster_shader);
  1297. {
  1298. //pre copy
  1299. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1300. rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
  1301. }
  1302. Vector<RID> framebuffers;
  1303. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1304. RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
  1305. Vector<RID> fb;
  1306. fb.push_back(slice_tex);
  1307. fb.push_back(raster_depth_buffer);
  1308. framebuffers.push_back(rd->framebuffer_create(fb));
  1309. }
  1310. Vector<RD::Uniform> uniforms;
  1311. {
  1312. {
  1313. RD::Uniform u;
  1314. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  1315. u.binding = 0;
  1316. u.append_id(light_accum_tex2);
  1317. uniforms.push_back(u);
  1318. }
  1319. }
  1320. RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
  1321. bool debug = false;
  1322. RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
  1323. bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
  1324. bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1325. RD::PipelineDepthStencilState ds;
  1326. ds.enable_depth_test = true;
  1327. ds.enable_depth_write = true;
  1328. ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
  1329. 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);
  1330. 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);
  1331. uint32_t seam_offset = 0;
  1332. uint32_t triangle_offset = 0;
  1333. Vector<Color> clear_colors;
  1334. clear_colors.push_back(Color(0, 0, 0, 1));
  1335. for (int i = 0; i < atlas_slices; i++) {
  1336. int subslices = (p_bake_sh ? 4 : 1);
  1337. if (slice_seam_count[i] == 0) {
  1338. continue;
  1339. }
  1340. for (int k = 0; k < subslices; k++) {
  1341. RasterSeamsPushConstant seams_push_constant;
  1342. seams_push_constant.slice = uint32_t(i * subslices + k);
  1343. seams_push_constant.debug = debug;
  1344. RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1345. rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
  1346. rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
  1347. const int uv_offset_count = 9;
  1348. static const Vector3 uv_offsets[uv_offset_count] = {
  1349. Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
  1350. Vector3(0, 1, 0.2),
  1351. Vector3(0, -1, 0.2),
  1352. Vector3(1, 0, 0.2),
  1353. Vector3(-1, 0, 0.2),
  1354. Vector3(-1, -1, 0.1),
  1355. Vector3(1, -1, 0.1),
  1356. Vector3(1, 1, 0.1),
  1357. Vector3(-1, 1, 0.1),
  1358. };
  1359. /* step 1 use lines to blend the edges */
  1360. {
  1361. seams_push_constant.base_index = seam_offset;
  1362. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1363. seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width);
  1364. seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height);
  1365. seams_push_constant.blend = uv_offsets[0].z;
  1366. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1367. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1368. }
  1369. /* step 2 use triangles to mask the interior */
  1370. {
  1371. seams_push_constant.base_index = triangle_offset;
  1372. rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
  1373. seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
  1374. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1375. rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
  1376. }
  1377. /* step 3 blend around the triangle */
  1378. rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
  1379. for (int j = 1; j < uv_offset_count; j++) {
  1380. seams_push_constant.base_index = seam_offset;
  1381. seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width);
  1382. seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height);
  1383. seams_push_constant.blend = uv_offsets[0].z;
  1384. rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
  1385. rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
  1386. }
  1387. rd->draw_list_end();
  1388. }
  1389. seam_offset += slice_seam_count[i];
  1390. triangle_offset += slice_triangle_count[i];
  1391. }
  1392. }
  1393. #ifdef DEBUG_TEXTURES
  1394. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1395. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1396. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1397. img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
  1398. }
  1399. #endif
  1400. if (p_step_function) {
  1401. p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
  1402. }
  1403. for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
  1404. Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
  1405. Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
  1406. img->convert(Image::FORMAT_RGBH); //remove alpha
  1407. bake_textures.push_back(img);
  1408. }
  1409. if (probe_positions.size() > 0) {
  1410. probe_values.resize(probe_positions.size() * 9);
  1411. Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
  1412. memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
  1413. rd->free(light_probe_buffer);
  1414. #ifdef DEBUG_TEXTURES
  1415. {
  1416. Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
  1417. img2->save_exr("res://6_lightprobes.exr", false);
  1418. }
  1419. #endif
  1420. }
  1421. FREE_TEXTURES
  1422. FREE_BUFFERS
  1423. FREE_RASTER_RESOURCES
  1424. FREE_COMPUTE_RESOURCES
  1425. FREE_BLENDSEAMS_RESOURCES
  1426. memdelete(rd);
  1427. return BAKE_OK;
  1428. }
  1429. int LightmapperRD::get_bake_texture_count() const {
  1430. return bake_textures.size();
  1431. }
  1432. Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
  1433. ERR_FAIL_INDEX_V(p_index, bake_textures.size(), Ref<Image>());
  1434. return bake_textures[p_index];
  1435. }
  1436. int LightmapperRD::get_bake_mesh_count() const {
  1437. return mesh_instances.size();
  1438. }
  1439. Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
  1440. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1441. return mesh_instances[p_index].data.userdata;
  1442. }
  1443. Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
  1444. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1445. Rect2 uv_ofs;
  1446. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1447. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1448. 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;
  1449. return uv_ofs;
  1450. }
  1451. int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
  1452. ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
  1453. return mesh_instances[p_index].slice;
  1454. }
  1455. int LightmapperRD::get_bake_probe_count() const {
  1456. return probe_positions.size();
  1457. }
  1458. Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
  1459. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
  1460. return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
  1461. }
  1462. Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
  1463. ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
  1464. Vector<Color> ret;
  1465. ret.resize(9);
  1466. memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
  1467. return ret;
  1468. }
  1469. LightmapperRD::LightmapperRD() {
  1470. }