lightmapper_rd.cpp 85 KB

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