lightmapper_rd.cpp 75 KB

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