lightmap_gi.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. /**************************************************************************/
  2. /* lightmap_gi.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 "lightmap_gi.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/config_file.h"
  33. #include "core/math/delaunay_3d.h"
  34. #include "lightmap_probe.h"
  35. #include "scene/3d/mesh_instance_3d.h"
  36. #include "scene/resources/camera_attributes.h"
  37. #include "scene/resources/environment.h"
  38. #include "scene/resources/image_texture.h"
  39. #include "scene/resources/sky.h"
  40. void LightmapGIData::add_user(const NodePath &p_path, const Rect2 &p_uv_scale, int p_slice_index, int32_t p_sub_instance) {
  41. User user;
  42. user.path = p_path;
  43. user.uv_scale = p_uv_scale;
  44. user.slice_index = p_slice_index;
  45. user.sub_instance = p_sub_instance;
  46. users.push_back(user);
  47. }
  48. int LightmapGIData::get_user_count() const {
  49. return users.size();
  50. }
  51. NodePath LightmapGIData::get_user_path(int p_user) const {
  52. ERR_FAIL_INDEX_V(p_user, users.size(), NodePath());
  53. return users[p_user].path;
  54. }
  55. int32_t LightmapGIData::get_user_sub_instance(int p_user) const {
  56. ERR_FAIL_INDEX_V(p_user, users.size(), -1);
  57. return users[p_user].sub_instance;
  58. }
  59. Rect2 LightmapGIData::get_user_lightmap_uv_scale(int p_user) const {
  60. ERR_FAIL_INDEX_V(p_user, users.size(), Rect2());
  61. return users[p_user].uv_scale;
  62. }
  63. int LightmapGIData::get_user_lightmap_slice_index(int p_user) const {
  64. ERR_FAIL_INDEX_V(p_user, users.size(), -1);
  65. return users[p_user].slice_index;
  66. }
  67. void LightmapGIData::clear_users() {
  68. users.clear();
  69. }
  70. void LightmapGIData::_set_user_data(const Array &p_data) {
  71. ERR_FAIL_COND(p_data.is_empty());
  72. ERR_FAIL_COND((p_data.size() % 4) != 0);
  73. for (int i = 0; i < p_data.size(); i += 4) {
  74. add_user(p_data[i + 0], p_data[i + 1], p_data[i + 2], p_data[i + 3]);
  75. }
  76. }
  77. Array LightmapGIData::_get_user_data() const {
  78. Array ret;
  79. for (int i = 0; i < users.size(); i++) {
  80. ret.push_back(users[i].path);
  81. ret.push_back(users[i].uv_scale);
  82. ret.push_back(users[i].slice_index);
  83. ret.push_back(users[i].sub_instance);
  84. }
  85. return ret;
  86. }
  87. void LightmapGIData::set_lightmap_textures(const TypedArray<TextureLayered> &p_data) {
  88. storage_light_textures = p_data;
  89. if (p_data.is_empty()) {
  90. combined_light_texture = Ref<TextureLayered>();
  91. _reset_lightmap_textures();
  92. return;
  93. }
  94. if (p_data.size() == 1) {
  95. combined_light_texture = p_data[0];
  96. } else {
  97. Vector<Ref<Image>> images;
  98. for (int i = 0; i < p_data.size(); i++) {
  99. Ref<TextureLayered> texture = p_data[i];
  100. ERR_FAIL_COND_MSG(texture.is_null(), vformat("Invalid TextureLayered at index %d.", i));
  101. for (int j = 0; j < texture->get_layers(); j++) {
  102. images.push_back(texture->get_layer_data(j));
  103. }
  104. }
  105. Ref<Texture2DArray> combined_texture;
  106. combined_texture.instantiate();
  107. combined_texture->create_from_images(images);
  108. combined_light_texture = combined_texture;
  109. }
  110. _reset_lightmap_textures();
  111. }
  112. TypedArray<TextureLayered> LightmapGIData::get_lightmap_textures() const {
  113. return storage_light_textures;
  114. }
  115. RID LightmapGIData::get_rid() const {
  116. return lightmap;
  117. }
  118. void LightmapGIData::clear() {
  119. users.clear();
  120. }
  121. void LightmapGIData::_reset_lightmap_textures() {
  122. RS::get_singleton()->lightmap_set_textures(lightmap, combined_light_texture.is_valid() ? combined_light_texture->get_rid() : RID(), uses_spherical_harmonics);
  123. }
  124. void LightmapGIData::set_uses_spherical_harmonics(bool p_enable) {
  125. uses_spherical_harmonics = p_enable;
  126. _reset_lightmap_textures();
  127. }
  128. bool LightmapGIData::is_using_spherical_harmonics() const {
  129. return uses_spherical_harmonics;
  130. }
  131. void LightmapGIData::_set_uses_packed_directional(bool p_enable) {
  132. _uses_packed_directional = p_enable;
  133. }
  134. bool LightmapGIData::_is_using_packed_directional() const {
  135. return _uses_packed_directional;
  136. }
  137. void LightmapGIData::set_capture_data(const AABB &p_bounds, bool p_interior, const PackedVector3Array &p_points, const PackedColorArray &p_point_sh, const PackedInt32Array &p_tetrahedra, const PackedInt32Array &p_bsp_tree, float p_baked_exposure) {
  138. if (p_points.size()) {
  139. int pc = p_points.size();
  140. ERR_FAIL_COND(pc * 9 != p_point_sh.size());
  141. ERR_FAIL_COND((p_tetrahedra.size() % 4) != 0);
  142. ERR_FAIL_COND((p_bsp_tree.size() % 6) != 0);
  143. RS::get_singleton()->lightmap_set_probe_capture_data(lightmap, p_points, p_point_sh, p_tetrahedra, p_bsp_tree);
  144. RS::get_singleton()->lightmap_set_probe_bounds(lightmap, p_bounds);
  145. RS::get_singleton()->lightmap_set_probe_interior(lightmap, p_interior);
  146. } else {
  147. RS::get_singleton()->lightmap_set_probe_capture_data(lightmap, PackedVector3Array(), PackedColorArray(), PackedInt32Array(), PackedInt32Array());
  148. RS::get_singleton()->lightmap_set_probe_bounds(lightmap, AABB());
  149. RS::get_singleton()->lightmap_set_probe_interior(lightmap, false);
  150. }
  151. RS::get_singleton()->lightmap_set_baked_exposure_normalization(lightmap, p_baked_exposure);
  152. baked_exposure = p_baked_exposure;
  153. interior = p_interior;
  154. bounds = p_bounds;
  155. }
  156. PackedVector3Array LightmapGIData::get_capture_points() const {
  157. return RS::get_singleton()->lightmap_get_probe_capture_points(lightmap);
  158. }
  159. PackedColorArray LightmapGIData::get_capture_sh() const {
  160. return RS::get_singleton()->lightmap_get_probe_capture_sh(lightmap);
  161. }
  162. PackedInt32Array LightmapGIData::get_capture_tetrahedra() const {
  163. return RS::get_singleton()->lightmap_get_probe_capture_tetrahedra(lightmap);
  164. }
  165. PackedInt32Array LightmapGIData::get_capture_bsp_tree() const {
  166. return RS::get_singleton()->lightmap_get_probe_capture_bsp_tree(lightmap);
  167. }
  168. AABB LightmapGIData::get_capture_bounds() const {
  169. return bounds;
  170. }
  171. bool LightmapGIData::is_interior() const {
  172. return interior;
  173. }
  174. float LightmapGIData::get_baked_exposure() const {
  175. return baked_exposure;
  176. }
  177. void LightmapGIData::_set_probe_data(const Dictionary &p_data) {
  178. ERR_FAIL_COND(!p_data.has("bounds"));
  179. ERR_FAIL_COND(!p_data.has("points"));
  180. ERR_FAIL_COND(!p_data.has("tetrahedra"));
  181. ERR_FAIL_COND(!p_data.has("bsp"));
  182. ERR_FAIL_COND(!p_data.has("sh"));
  183. ERR_FAIL_COND(!p_data.has("interior"));
  184. ERR_FAIL_COND(!p_data.has("baked_exposure"));
  185. set_capture_data(p_data["bounds"], p_data["interior"], p_data["points"], p_data["sh"], p_data["tetrahedra"], p_data["bsp"], p_data["baked_exposure"]);
  186. }
  187. Dictionary LightmapGIData::_get_probe_data() const {
  188. Dictionary d;
  189. d["bounds"] = get_capture_bounds();
  190. d["points"] = get_capture_points();
  191. d["tetrahedra"] = get_capture_tetrahedra();
  192. d["bsp"] = get_capture_bsp_tree();
  193. d["sh"] = get_capture_sh();
  194. d["interior"] = is_interior();
  195. d["baked_exposure"] = get_baked_exposure();
  196. return d;
  197. }
  198. #ifndef DISABLE_DEPRECATED
  199. void LightmapGIData::set_light_texture(const Ref<TextureLayered> &p_light_texture) {
  200. TypedArray<TextureLayered> arr;
  201. arr.append(p_light_texture);
  202. set_lightmap_textures(arr);
  203. }
  204. Ref<TextureLayered> LightmapGIData::get_light_texture() const {
  205. if (storage_light_textures.is_empty()) {
  206. return Ref<TextureLayered>();
  207. }
  208. return storage_light_textures.get(0);
  209. }
  210. void LightmapGIData::_set_light_textures_data(const Array &p_data) {
  211. set_lightmap_textures(p_data);
  212. }
  213. Array LightmapGIData::_get_light_textures_data() const {
  214. return Array(storage_light_textures);
  215. }
  216. #endif
  217. void LightmapGIData::_bind_methods() {
  218. ClassDB::bind_method(D_METHOD("_set_user_data", "data"), &LightmapGIData::_set_user_data);
  219. ClassDB::bind_method(D_METHOD("_get_user_data"), &LightmapGIData::_get_user_data);
  220. ClassDB::bind_method(D_METHOD("set_lightmap_textures", "light_textures"), &LightmapGIData::set_lightmap_textures);
  221. ClassDB::bind_method(D_METHOD("get_lightmap_textures"), &LightmapGIData::get_lightmap_textures);
  222. ClassDB::bind_method(D_METHOD("set_uses_spherical_harmonics", "uses_spherical_harmonics"), &LightmapGIData::set_uses_spherical_harmonics);
  223. ClassDB::bind_method(D_METHOD("is_using_spherical_harmonics"), &LightmapGIData::is_using_spherical_harmonics);
  224. ClassDB::bind_method(D_METHOD("_set_uses_packed_directional", "_uses_packed_directional"), &LightmapGIData::_set_uses_packed_directional);
  225. ClassDB::bind_method(D_METHOD("_is_using_packed_directional"), &LightmapGIData::_is_using_packed_directional);
  226. ClassDB::bind_method(D_METHOD("add_user", "path", "uv_scale", "slice_index", "sub_instance"), &LightmapGIData::add_user);
  227. ClassDB::bind_method(D_METHOD("get_user_count"), &LightmapGIData::get_user_count);
  228. ClassDB::bind_method(D_METHOD("get_user_path", "user_idx"), &LightmapGIData::get_user_path);
  229. ClassDB::bind_method(D_METHOD("clear_users"), &LightmapGIData::clear_users);
  230. ClassDB::bind_method(D_METHOD("_set_probe_data", "data"), &LightmapGIData::_set_probe_data);
  231. ClassDB::bind_method(D_METHOD("_get_probe_data"), &LightmapGIData::_get_probe_data);
  232. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "lightmap_textures", PROPERTY_HINT_ARRAY_TYPE, "TextureLayered", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY), "set_lightmap_textures", "get_lightmap_textures");
  233. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "uses_spherical_harmonics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_uses_spherical_harmonics", "is_using_spherical_harmonics");
  234. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "user_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_user_data", "_get_user_data");
  235. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "probe_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_probe_data", "_get_probe_data");
  236. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "_uses_packed_directional", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_uses_packed_directional", "_is_using_packed_directional");
  237. #ifndef DISABLE_DEPRECATED
  238. ClassDB::bind_method(D_METHOD("set_light_texture", "light_texture"), &LightmapGIData::set_light_texture);
  239. ClassDB::bind_method(D_METHOD("get_light_texture"), &LightmapGIData::get_light_texture);
  240. ClassDB::bind_method(D_METHOD("_set_light_textures_data", "data"), &LightmapGIData::_set_light_textures_data);
  241. ClassDB::bind_method(D_METHOD("_get_light_textures_data"), &LightmapGIData::_get_light_textures_data);
  242. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_texture", PROPERTY_HINT_RESOURCE_TYPE, "TextureLayered", PROPERTY_USAGE_NONE), "set_light_texture", "get_light_texture");
  243. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "light_textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_INTERNAL), "_set_light_textures_data", "_get_light_textures_data");
  244. #endif
  245. }
  246. LightmapGIData::LightmapGIData() {
  247. lightmap = RS::get_singleton()->lightmap_create();
  248. }
  249. LightmapGIData::~LightmapGIData() {
  250. ERR_FAIL_NULL(RenderingServer::get_singleton());
  251. RS::get_singleton()->free(lightmap);
  252. }
  253. ///////////////////////////
  254. void LightmapGI::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound> &meshes, Vector<LightsFound> &lights, Vector<Vector3> &probes) {
  255. MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_at_node);
  256. if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_STATIC && mi->is_visible_in_tree()) {
  257. Ref<Mesh> mesh = mi->get_mesh();
  258. if (mesh.is_valid()) {
  259. bool all_have_uv2_and_normal = true;
  260. bool surfaces_found = false;
  261. for (int i = 0; i < mesh->get_surface_count(); i++) {
  262. if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  263. continue;
  264. }
  265. if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV2)) {
  266. all_have_uv2_and_normal = false;
  267. break;
  268. }
  269. if (!(mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_NORMAL)) {
  270. all_have_uv2_and_normal = false;
  271. break;
  272. }
  273. surfaces_found = true;
  274. }
  275. if (surfaces_found && all_have_uv2_and_normal) {
  276. //READY TO BAKE! size hint could be computed if not found, actually..
  277. MeshesFound mf;
  278. mf.xform = get_global_transform().affine_inverse() * mi->get_global_transform();
  279. mf.node_path = get_path_to(mi);
  280. mf.subindex = -1;
  281. mf.mesh = mesh;
  282. mf.lightmap_scale = mi->get_lightmap_texel_scale();
  283. Ref<Material> all_override = mi->get_material_override();
  284. for (int i = 0; i < mesh->get_surface_count(); i++) {
  285. if (all_override.is_valid()) {
  286. mf.overrides.push_back(all_override);
  287. } else {
  288. mf.overrides.push_back(mi->get_surface_override_material(i));
  289. }
  290. }
  291. meshes.push_back(mf);
  292. }
  293. }
  294. }
  295. Node3D *s = Object::cast_to<Node3D>(p_at_node);
  296. if (!mi && s) {
  297. Array bmeshes = p_at_node->call("get_bake_meshes");
  298. if (bmeshes.size() && (bmeshes.size() & 1) == 0) {
  299. Transform3D xf = get_global_transform().affine_inverse() * s->get_global_transform();
  300. for (int i = 0; i < bmeshes.size(); i += 2) {
  301. Ref<Mesh> mesh = bmeshes[i];
  302. if (!mesh.is_valid()) {
  303. continue;
  304. }
  305. MeshesFound mf;
  306. Transform3D mesh_xf = bmeshes[i + 1];
  307. mf.xform = xf * mesh_xf;
  308. mf.node_path = get_path_to(s);
  309. mf.subindex = i / 2;
  310. mf.lightmap_scale = 1.0;
  311. mf.mesh = mesh;
  312. meshes.push_back(mf);
  313. }
  314. }
  315. }
  316. Light3D *light = Object::cast_to<Light3D>(p_at_node);
  317. if (light && light->get_bake_mode() != Light3D::BAKE_DISABLED) {
  318. LightsFound lf;
  319. lf.xform = get_global_transform().affine_inverse() * light->get_global_transform();
  320. lf.light = light;
  321. lights.push_back(lf);
  322. }
  323. LightmapProbe *probe = Object::cast_to<LightmapProbe>(p_at_node);
  324. if (probe) {
  325. Transform3D xf = get_global_transform().affine_inverse() * probe->get_global_transform();
  326. probes.push_back(xf.origin);
  327. }
  328. for (int i = 0; i < p_at_node->get_child_count(); i++) {
  329. Node *child = p_at_node->get_child(i);
  330. if (!child->get_owner()) {
  331. continue; //maybe a helper
  332. }
  333. _find_meshes_and_lights(child, meshes, lights, probes);
  334. }
  335. }
  336. int LightmapGI::_bsp_get_simplex_side(const Vector<Vector3> &p_points, const LocalVector<BSPSimplex> &p_simplices, const Plane &p_plane, uint32_t p_simplex) const {
  337. int over = 0;
  338. int under = 0;
  339. const BSPSimplex &s = p_simplices[p_simplex];
  340. for (int i = 0; i < 4; i++) {
  341. const Vector3 v = p_points[s.vertices[i]];
  342. // The tolerance used here comes from experiments on scenes up to
  343. // 1000x1000x100 meters. If it's any smaller, some simplices will
  344. // appear to self-intersect due to a lack of precision in Plane.
  345. if (p_plane.has_point(v, 1.0 / (1 << 13))) {
  346. // Coplanar.
  347. } else if (p_plane.is_point_over(v)) {
  348. over++;
  349. } else {
  350. under++;
  351. }
  352. }
  353. ERR_FAIL_COND_V(under == 0 && over == 0, -2); //should never happen, we discarded flat simplices before, but in any case drop it from the bsp tree and throw an error
  354. if (under == 0) {
  355. return 1; // all over
  356. } else if (over == 0) {
  357. return -1; // all under
  358. } else {
  359. return 0; // crossing
  360. }
  361. }
  362. //#define DEBUG_BSP
  363. int32_t LightmapGI::_compute_bsp_tree(const Vector<Vector3> &p_points, const LocalVector<Plane> &p_planes, LocalVector<int32_t> &planes_tested, const LocalVector<BSPSimplex> &p_simplices, const LocalVector<int32_t> &p_simplex_indices, LocalVector<BSPNode> &bsp_nodes) {
  364. ERR_FAIL_COND_V(p_simplex_indices.size() < 2, -1);
  365. int32_t node_index = (int32_t)bsp_nodes.size();
  366. bsp_nodes.push_back(BSPNode());
  367. //test with all the simplex planes
  368. Plane best_plane;
  369. float best_plane_score = -1.0;
  370. for (const int idx : p_simplex_indices) {
  371. const BSPSimplex &s = p_simplices[idx];
  372. for (int j = 0; j < 4; j++) {
  373. uint32_t plane_index = s.planes[j];
  374. if (planes_tested[plane_index] == node_index) {
  375. continue; //tested this plane already
  376. }
  377. planes_tested[plane_index] = node_index;
  378. static const int face_order[4][3] = {
  379. { 0, 1, 2 },
  380. { 0, 2, 3 },
  381. { 0, 1, 3 },
  382. { 1, 2, 3 }
  383. };
  384. // despite getting rid of plane duplicates, we should still use here the actual plane to avoid numerical error
  385. // from thinking this same simplex is intersecting rather than on a side
  386. Vector3 v0 = p_points[s.vertices[face_order[j][0]]];
  387. Vector3 v1 = p_points[s.vertices[face_order[j][1]]];
  388. Vector3 v2 = p_points[s.vertices[face_order[j][2]]];
  389. Plane plane(v0, v1, v2);
  390. //test with all the simplices
  391. int over_count = 0;
  392. int under_count = 0;
  393. for (const int &index : p_simplex_indices) {
  394. int side = _bsp_get_simplex_side(p_points, p_simplices, plane, index);
  395. if (side == -2) {
  396. continue; //this simplex is invalid, skip for now
  397. } else if (side < 0) {
  398. under_count++;
  399. } else if (side > 0) {
  400. over_count++;
  401. }
  402. }
  403. if (under_count == 0 && over_count == 0) {
  404. continue; //most likely precision issue with a flat simplex, do not try this plane
  405. }
  406. if (under_count > over_count) { //make sure under is always less than over, so we can compute the same ratio
  407. SWAP(under_count, over_count);
  408. }
  409. float score = 0; //by default, score is 0 (worst)
  410. if (over_count > 0) {
  411. // Simplices that are intersected by the plane are moved into both the over
  412. // and under subtrees which makes the entire tree deeper, so the best plane
  413. // will have the least intersections while separating the simplices evenly.
  414. float balance = float(under_count) / over_count;
  415. float separation = float(over_count + under_count) / p_simplex_indices.size();
  416. score = balance * separation * separation;
  417. }
  418. if (score > best_plane_score) {
  419. best_plane = plane;
  420. best_plane_score = score;
  421. }
  422. }
  423. }
  424. // We often end up with two (or on rare occasions, three) simplices that are
  425. // either disjoint or share one vertex and don't have a separating plane
  426. // among their faces. The fallback is to loop through new planes created
  427. // with one vertex of the first simplex and two vertices of the second until
  428. // we find a winner.
  429. if (best_plane_score == 0) {
  430. const BSPSimplex &simplex0 = p_simplices[p_simplex_indices[0]];
  431. const BSPSimplex &simplex1 = p_simplices[p_simplex_indices[1]];
  432. for (uint32_t i = 0; i < 4 && !best_plane_score; i++) {
  433. Vector3 v0 = p_points[simplex0.vertices[i]];
  434. for (uint32_t j = 0; j < 3 && !best_plane_score; j++) {
  435. if (simplex0.vertices[i] == simplex1.vertices[j]) {
  436. break;
  437. }
  438. Vector3 v1 = p_points[simplex1.vertices[j]];
  439. for (uint32_t k = j + 1; k < 4; k++) {
  440. if (simplex0.vertices[i] == simplex1.vertices[k]) {
  441. break;
  442. }
  443. Vector3 v2 = p_points[simplex1.vertices[k]];
  444. Plane plane = Plane(v0, v1, v2);
  445. if (plane == Plane()) { // When v0, v1, and v2 are collinear, they can't form a plane.
  446. continue;
  447. }
  448. int32_t side0 = _bsp_get_simplex_side(p_points, p_simplices, plane, p_simplex_indices[0]);
  449. int32_t side1 = _bsp_get_simplex_side(p_points, p_simplices, plane, p_simplex_indices[1]);
  450. if ((side0 == 1 && side1 == -1) || (side0 == -1 && side1 == 1)) {
  451. best_plane = plane;
  452. best_plane_score = 1.0;
  453. break;
  454. }
  455. }
  456. }
  457. }
  458. }
  459. LocalVector<int32_t> indices_over;
  460. LocalVector<int32_t> indices_under;
  461. //split again, but add to list
  462. for (const uint32_t index : p_simplex_indices) {
  463. int side = _bsp_get_simplex_side(p_points, p_simplices, best_plane, index);
  464. if (side == -2) {
  465. continue; //simplex sits on the plane, does not make sense to use it
  466. }
  467. if (side <= 0) {
  468. indices_under.push_back(index);
  469. }
  470. if (side >= 0) {
  471. indices_over.push_back(index);
  472. }
  473. }
  474. #ifdef DEBUG_BSP
  475. print_line("node " + itos(node_index) + " found plane: " + best_plane + " score:" + rtos(best_plane_score) + " - over " + itos(indices_over.size()) + " under " + itos(indices_under.size()) + " intersecting " + itos(intersecting));
  476. #endif
  477. if (best_plane_score < 0.0 || indices_over.size() == p_simplex_indices.size() || indices_under.size() == p_simplex_indices.size()) {
  478. // Failed to separate the tetrahedrons using planes
  479. // this means Delaunay broke at some point.
  480. // Luckily, because we are using tetrahedrons, we can resort to
  481. // less precise but still working ways to generate the separating plane
  482. // this will most likely look bad when interpolating, but at least it will not crash.
  483. // and the artifact will most likely also be very small, so too difficult to notice.
  484. //find the longest axis
  485. WARN_PRINT("Inconsistency found in triangulation while building BSP, probe interpolation quality may degrade a bit.");
  486. LocalVector<Vector3> centers;
  487. AABB bounds_all;
  488. for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
  489. AABB bounds;
  490. for (uint32_t j = 0; j < 4; j++) {
  491. Vector3 p = p_points[p_simplices[p_simplex_indices[i]].vertices[j]];
  492. if (j == 0) {
  493. bounds.position = p;
  494. } else {
  495. bounds.expand_to(p);
  496. }
  497. }
  498. if (i == 0) {
  499. centers.push_back(bounds.get_center());
  500. } else {
  501. bounds_all.merge_with(bounds);
  502. }
  503. }
  504. Vector3::Axis longest_axis = Vector3::Axis(bounds_all.get_longest_axis_index());
  505. //find the simplex that will go under
  506. uint32_t min_d_idx = 0xFFFFFFFF;
  507. float min_d_dist = 1e20;
  508. for (uint32_t i = 0; i < centers.size(); i++) {
  509. if (centers[i][longest_axis] < min_d_dist) {
  510. min_d_idx = i;
  511. min_d_dist = centers[i][longest_axis];
  512. }
  513. }
  514. //rebuild best_plane and over/under arrays
  515. best_plane = Plane();
  516. best_plane.normal[longest_axis] = 1.0;
  517. best_plane.d = min_d_dist;
  518. indices_under.clear();
  519. indices_under.push_back(min_d_idx);
  520. indices_over.clear();
  521. for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
  522. if (i == min_d_idx) {
  523. continue;
  524. }
  525. indices_over.push_back(p_simplex_indices[i]);
  526. }
  527. }
  528. BSPNode node;
  529. node.plane = best_plane;
  530. if (indices_under.size() == 0) {
  531. //nothing to do here
  532. node.under = BSPNode::EMPTY_LEAF;
  533. } else if (indices_under.size() == 1) {
  534. node.under = -(indices_under[0] + 1);
  535. } else {
  536. node.under = _compute_bsp_tree(p_points, p_planes, planes_tested, p_simplices, indices_under, bsp_nodes);
  537. }
  538. if (indices_over.size() == 0) {
  539. //nothing to do here
  540. node.over = BSPNode::EMPTY_LEAF;
  541. } else if (indices_over.size() == 1) {
  542. node.over = -(indices_over[0] + 1);
  543. } else {
  544. node.over = _compute_bsp_tree(p_points, p_planes, planes_tested, p_simplices, indices_over, bsp_nodes);
  545. }
  546. bsp_nodes[node_index] = node;
  547. return node_index;
  548. }
  549. bool LightmapGI::_lightmap_bake_step_function(float p_completion, const String &p_text, void *ud, bool p_refresh) {
  550. BakeStepUD *bsud = (BakeStepUD *)ud;
  551. bool ret = false;
  552. if (bsud->func) {
  553. ret = bsud->func(bsud->from_percent + p_completion * (bsud->to_percent - bsud->from_percent), p_text, bsud->ud, p_refresh);
  554. }
  555. return ret;
  556. }
  557. void LightmapGI::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_cell_size, const Vector3 *p_triangle) {
  558. for (int i = 0; i < 8; i++) {
  559. Vector3i pos = p_cell->offset;
  560. uint32_t half_size = p_cell->size / 2;
  561. if (i & 1) {
  562. pos.x += half_size;
  563. }
  564. if (i & 2) {
  565. pos.y += half_size;
  566. }
  567. if (i & 4) {
  568. pos.z += half_size;
  569. }
  570. AABB subcell;
  571. subcell.position = Vector3(pos) * p_cell_size;
  572. subcell.size = Vector3(half_size, half_size, half_size) * p_cell_size;
  573. if (!Geometry3D::triangle_box_overlap(subcell.get_center(), subcell.size * 0.5, p_triangle)) {
  574. continue;
  575. }
  576. if (p_cell->children[i] == nullptr) {
  577. GenProbesOctree *child = memnew(GenProbesOctree);
  578. child->offset = pos;
  579. child->size = half_size;
  580. p_cell->children[i] = child;
  581. }
  582. if (half_size > 1) {
  583. //still levels missing
  584. _plot_triangle_into_octree(p_cell->children[i], p_cell_size, p_triangle);
  585. }
  586. }
  587. }
  588. void LightmapGI::_gen_new_positions_from_octree(const GenProbesOctree *p_cell, float p_cell_size, const Vector<Vector3> &probe_positions, LocalVector<Vector3> &new_probe_positions, HashMap<Vector3i, bool> &positions_used, const AABB &p_bounds) {
  589. for (int i = 0; i < 8; i++) {
  590. Vector3i pos = p_cell->offset;
  591. if (i & 1) {
  592. pos.x += p_cell->size;
  593. }
  594. if (i & 2) {
  595. pos.y += p_cell->size;
  596. }
  597. if (i & 4) {
  598. pos.z += p_cell->size;
  599. }
  600. if (p_cell->size == 1 && !positions_used.has(pos)) {
  601. //new position to insert!
  602. Vector3 real_pos = p_bounds.position + Vector3(pos) * p_cell_size;
  603. //see if a user submitted probe is too close
  604. int ppcount = probe_positions.size();
  605. const Vector3 *pp = probe_positions.ptr();
  606. bool exists = false;
  607. for (int j = 0; j < ppcount; j++) {
  608. if (pp[j].distance_to(real_pos) < (p_cell_size * 0.5f)) {
  609. exists = true;
  610. break;
  611. }
  612. }
  613. if (!exists) {
  614. new_probe_positions.push_back(real_pos);
  615. }
  616. positions_used[pos] = true;
  617. }
  618. if (p_cell->children[i] != nullptr) {
  619. _gen_new_positions_from_octree(p_cell->children[i], p_cell_size, probe_positions, new_probe_positions, positions_used, p_bounds);
  620. }
  621. }
  622. }
  623. LightmapGI::BakeError LightmapGI::_save_and_reimport_atlas_textures(const Ref<Lightmapper> p_lightmapper, const String &p_base_name, TypedArray<TextureLayered> &r_textures, bool p_compress) const {
  624. Vector<Ref<Image>> images;
  625. images.resize(p_lightmapper->get_bake_texture_count());
  626. for (int i = 0; i < images.size(); i++) {
  627. images.set(i, p_lightmapper->get_bake_texture(i));
  628. }
  629. const int slice_count = images.size();
  630. const int slice_width = images[0]->get_width();
  631. const int slice_height = images[0]->get_height();
  632. const int slices_per_texture = Image::MAX_HEIGHT / slice_height;
  633. const int texture_count = Math::ceil(slice_count / (float)slices_per_texture);
  634. const int last_count = slice_count % slices_per_texture;
  635. r_textures.resize(texture_count);
  636. for (int i = 0; i < texture_count; i++) {
  637. const int texture_slice_count = (i == texture_count - 1 && last_count != 0) ? last_count : slices_per_texture;
  638. Ref<Image> texture_image = Image::create_empty(slice_width, slice_height * texture_slice_count, false, images[0]->get_format());
  639. for (int j = 0; j < texture_slice_count; j++) {
  640. texture_image->blit_rect(images[i * slices_per_texture + j], Rect2i(0, 0, slice_width, slice_height), Point2i(0, slice_height * j));
  641. }
  642. const String atlas_path = (texture_count > 1 ? p_base_name + "_" + itos(i) : p_base_name) + ".exr";
  643. const String config_path = atlas_path + ".import";
  644. Ref<ConfigFile> config;
  645. config.instantiate();
  646. // Load an import configuration if present.
  647. if (FileAccess::exists(config_path)) {
  648. config->load(config_path);
  649. }
  650. config->set_value("remap", "importer", "2d_array_texture");
  651. config->set_value("remap", "type", "CompressedTexture2DArray");
  652. if (!config->has_section_key("params", "compress/mode")) {
  653. // Do not override an existing compression mode.
  654. config->set_value("params", "compress/mode", p_compress ? 2 : 3);
  655. }
  656. config->set_value("params", "compress/channel_pack", 1);
  657. config->set_value("params", "mipmaps/generate", false);
  658. config->set_value("params", "slices/horizontal", 1);
  659. config->set_value("params", "slices/vertical", texture_slice_count);
  660. config->save(config_path);
  661. // Save the file.
  662. Error save_err = texture_image->save_exr(atlas_path, false);
  663. ERR_FAIL_COND_V(save_err, LightmapGI::BAKE_ERROR_CANT_CREATE_IMAGE);
  664. // Reimport the file.
  665. ResourceLoader::import(atlas_path);
  666. Ref<TextureLayered> t = ResourceLoader::load(atlas_path); // If already loaded, it will be updated on refocus?
  667. ERR_FAIL_COND_V(t.is_null(), LightmapGI::BAKE_ERROR_CANT_CREATE_IMAGE);
  668. // Store the atlas in the array.
  669. r_textures[i] = t;
  670. }
  671. return LightmapGI::BAKE_ERROR_OK;
  672. }
  673. LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_path, Lightmapper::BakeStepFunc p_bake_step, void *p_bake_userdata) {
  674. if (p_image_data_path.is_empty()) {
  675. if (get_light_data().is_null()) {
  676. return BAKE_ERROR_NO_SAVE_PATH;
  677. }
  678. p_image_data_path = get_light_data()->get_path();
  679. if (!p_image_data_path.is_resource_file()) {
  680. return BAKE_ERROR_NO_SAVE_PATH;
  681. }
  682. }
  683. Ref<Lightmapper> lightmapper = Lightmapper::create();
  684. ERR_FAIL_COND_V(lightmapper.is_null(), BAKE_ERROR_NO_LIGHTMAPPER);
  685. BakeStepUD bsud;
  686. bsud.func = p_bake_step;
  687. bsud.ud = p_bake_userdata;
  688. bsud.from_percent = 0.2;
  689. bsud.to_percent = 0.8;
  690. if (p_bake_step) {
  691. p_bake_step(0.0, RTR("Finding meshes, lights and probes"), p_bake_userdata, true);
  692. }
  693. /* STEP 1, FIND MESHES, LIGHTS AND PROBES */
  694. Vector<Lightmapper::MeshData> mesh_data;
  695. Vector<LightsFound> lights_found;
  696. Vector<Vector3> probes_found;
  697. AABB bounds;
  698. {
  699. Vector<MeshesFound> meshes_found;
  700. _find_meshes_and_lights(p_from_node ? p_from_node : get_parent(), meshes_found, lights_found, probes_found);
  701. if (meshes_found.size() == 0) {
  702. return BAKE_ERROR_NO_MESHES;
  703. }
  704. // create mesh data for insert
  705. //get the base material textures, help compute atlas size and bounds
  706. for (int m_i = 0; m_i < meshes_found.size(); m_i++) {
  707. if (p_bake_step) {
  708. float p = (float)(m_i) / meshes_found.size();
  709. p_bake_step(p * 0.1, vformat(RTR("Preparing geometry %d/%d"), m_i, meshes_found.size()), p_bake_userdata, false);
  710. }
  711. MeshesFound &mf = meshes_found.write[m_i];
  712. Size2i mesh_lightmap_size = mf.mesh->get_lightmap_size_hint();
  713. if (mesh_lightmap_size == Size2i(0, 0)) {
  714. // TODO we should compute a size if no lightmap hint is set, as we did in 3.x.
  715. // For now set to basic size to avoid crash.
  716. mesh_lightmap_size = Size2i(64, 64);
  717. }
  718. Size2i lightmap_size = Size2i(Size2(mesh_lightmap_size) * mf.lightmap_scale * texel_scale);
  719. ERR_FAIL_COND_V(lightmap_size.x == 0 || lightmap_size.y == 0, BAKE_ERROR_LIGHTMAP_TOO_SMALL);
  720. TypedArray<RID> overrides;
  721. overrides.resize(mf.overrides.size());
  722. for (int i = 0; i < mf.overrides.size(); i++) {
  723. if (mf.overrides[i].is_valid()) {
  724. overrides[i] = mf.overrides[i]->get_rid();
  725. }
  726. }
  727. TypedArray<Image> images = RS::get_singleton()->bake_render_uv2(mf.mesh->get_rid(), overrides, lightmap_size);
  728. ERR_FAIL_COND_V(images.is_empty(), BAKE_ERROR_CANT_CREATE_IMAGE);
  729. Ref<Image> albedo = images[RS::BAKE_CHANNEL_ALBEDO_ALPHA];
  730. Ref<Image> orm = images[RS::BAKE_CHANNEL_ORM];
  731. //multiply albedo by metal
  732. Lightmapper::MeshData md;
  733. {
  734. Dictionary d;
  735. d["path"] = mf.node_path;
  736. if (mf.subindex >= 0) {
  737. d["subindex"] = mf.subindex;
  738. }
  739. md.userdata = d;
  740. }
  741. {
  742. if (albedo->get_format() != Image::FORMAT_RGBA8) {
  743. albedo->convert(Image::FORMAT_RGBA8);
  744. }
  745. if (orm->get_format() != Image::FORMAT_RGBA8) {
  746. orm->convert(Image::FORMAT_RGBA8);
  747. }
  748. Vector<uint8_t> albedo_alpha = albedo->get_data();
  749. Vector<uint8_t> orm_data = orm->get_data();
  750. Vector<uint8_t> albedom;
  751. uint32_t len = albedo_alpha.size();
  752. albedom.resize(len);
  753. const uint8_t *r_aa = albedo_alpha.ptr();
  754. const uint8_t *r_orm = orm_data.ptr();
  755. uint8_t *w_albedo = albedom.ptrw();
  756. for (uint32_t i = 0; i < len; i += 4) {
  757. w_albedo[i + 0] = uint8_t(CLAMP(float(r_aa[i + 0]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
  758. w_albedo[i + 1] = uint8_t(CLAMP(float(r_aa[i + 1]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
  759. w_albedo[i + 2] = uint8_t(CLAMP(float(r_aa[i + 2]) * (1.0 - float(r_orm[i + 2] / 255.0)), 0, 255));
  760. w_albedo[i + 3] = 255;
  761. }
  762. md.albedo_on_uv2.instantiate();
  763. md.albedo_on_uv2->set_data(lightmap_size.width, lightmap_size.height, false, Image::FORMAT_RGBA8, albedom);
  764. }
  765. md.emission_on_uv2 = images[RS::BAKE_CHANNEL_EMISSION];
  766. if (md.emission_on_uv2->get_format() != Image::FORMAT_RGBAH) {
  767. md.emission_on_uv2->convert(Image::FORMAT_RGBAH);
  768. }
  769. //get geometry
  770. Basis normal_xform = mf.xform.basis.inverse().transposed();
  771. for (int i = 0; i < mf.mesh->get_surface_count(); i++) {
  772. if (mf.mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  773. continue;
  774. }
  775. Array a = mf.mesh->surface_get_arrays(i);
  776. Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  777. const Vector3 *vr = vertices.ptr();
  778. Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV2];
  779. const Vector2 *uvr = nullptr;
  780. Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  781. const Vector3 *nr = nullptr;
  782. Vector<int> index = a[Mesh::ARRAY_INDEX];
  783. ERR_CONTINUE(uv.size() == 0);
  784. ERR_CONTINUE(normals.size() == 0);
  785. uvr = uv.ptr();
  786. nr = normals.ptr();
  787. int facecount;
  788. const int *ir = nullptr;
  789. if (index.size()) {
  790. facecount = index.size() / 3;
  791. ir = index.ptr();
  792. } else {
  793. facecount = vertices.size() / 3;
  794. }
  795. for (int j = 0; j < facecount; j++) {
  796. uint32_t vidx[3];
  797. if (ir) {
  798. for (int k = 0; k < 3; k++) {
  799. vidx[k] = ir[j * 3 + k];
  800. }
  801. } else {
  802. for (int k = 0; k < 3; k++) {
  803. vidx[k] = j * 3 + k;
  804. }
  805. }
  806. for (int k = 0; k < 3; k++) {
  807. Vector3 v = mf.xform.xform(vr[vidx[k]]);
  808. if (bounds == AABB()) {
  809. bounds.position = v;
  810. } else {
  811. bounds.expand_to(v);
  812. }
  813. md.points.push_back(v);
  814. md.uv2.push_back(uvr[vidx[k]]);
  815. md.normal.push_back(normal_xform.xform(nr[vidx[k]]).normalized());
  816. }
  817. }
  818. }
  819. mesh_data.push_back(md);
  820. }
  821. }
  822. /* STEP 2, CREATE PROBES */
  823. if (p_bake_step) {
  824. p_bake_step(0.3, RTR("Creating probes"), p_bake_userdata, true);
  825. }
  826. //bounds need to include the user probes
  827. for (int i = 0; i < probes_found.size(); i++) {
  828. bounds.expand_to(probes_found[i]);
  829. }
  830. bounds.grow_by(bounds.size.length() * 0.001);
  831. if (gen_probes == GENERATE_PROBES_DISABLED) {
  832. // generate 8 probes on bound endpoints
  833. for (int i = 0; i < 8; i++) {
  834. probes_found.push_back(bounds.get_endpoint(i));
  835. }
  836. } else {
  837. // detect probes from geometry
  838. static const int subdiv_values[6] = { 0, 4, 8, 16, 32 };
  839. int subdiv = subdiv_values[gen_probes];
  840. float subdiv_cell_size;
  841. Vector3i bound_limit;
  842. {
  843. int longest_axis = bounds.get_longest_axis_index();
  844. subdiv_cell_size = bounds.size[longest_axis] / subdiv;
  845. int axis_n1 = (longest_axis + 1) % 3;
  846. int axis_n2 = (longest_axis + 2) % 3;
  847. bound_limit[longest_axis] = subdiv;
  848. bound_limit[axis_n1] = int(Math::ceil(bounds.size[axis_n1] / subdiv_cell_size));
  849. bound_limit[axis_n2] = int(Math::ceil(bounds.size[axis_n2] / subdiv_cell_size));
  850. //compensate bounds
  851. bounds.size[axis_n1] = bound_limit[axis_n1] * subdiv_cell_size;
  852. bounds.size[axis_n2] = bound_limit[axis_n2] * subdiv_cell_size;
  853. }
  854. GenProbesOctree octree;
  855. octree.size = subdiv;
  856. for (int i = 0; i < mesh_data.size(); i++) {
  857. if (p_bake_step) {
  858. float p = (float)(i) / mesh_data.size();
  859. p_bake_step(0.3 + p * 0.1, vformat(RTR("Creating probes from mesh %d/%d"), i, mesh_data.size()), p_bake_userdata, false);
  860. }
  861. for (int j = 0; j < mesh_data[i].points.size(); j += 3) {
  862. Vector3 points[3] = { mesh_data[i].points[j + 0] - bounds.position, mesh_data[i].points[j + 1] - bounds.position, mesh_data[i].points[j + 2] - bounds.position };
  863. _plot_triangle_into_octree(&octree, subdiv_cell_size, points);
  864. }
  865. }
  866. LocalVector<Vector3> new_probe_positions;
  867. HashMap<Vector3i, bool> positions_used;
  868. for (uint32_t i = 0; i < 8; i++) { //insert bounding endpoints
  869. Vector3i pos;
  870. if (i & 1) {
  871. pos.x += bound_limit.x;
  872. }
  873. if (i & 2) {
  874. pos.y += bound_limit.y;
  875. }
  876. if (i & 4) {
  877. pos.z += bound_limit.z;
  878. }
  879. positions_used[pos] = true;
  880. Vector3 real_pos = bounds.position + Vector3(pos) * subdiv_cell_size; //use same formula for numerical stability
  881. new_probe_positions.push_back(real_pos);
  882. }
  883. //skip first level, since probes are always added at bounds endpoints anyway (code above this)
  884. for (int i = 0; i < 8; i++) {
  885. if (octree.children[i]) {
  886. _gen_new_positions_from_octree(octree.children[i], subdiv_cell_size, probes_found, new_probe_positions, positions_used, bounds);
  887. }
  888. }
  889. for (const Vector3 &position : new_probe_positions) {
  890. probes_found.push_back(position);
  891. }
  892. }
  893. // Add everything to lightmapper
  894. const bool use_physical_light_units = GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units");
  895. if (p_bake_step) {
  896. p_bake_step(0.4, RTR("Preparing Lightmapper"), p_bake_userdata, true);
  897. }
  898. {
  899. for (int i = 0; i < mesh_data.size(); i++) {
  900. lightmapper->add_mesh(mesh_data[i]);
  901. }
  902. for (int i = 0; i < lights_found.size(); i++) {
  903. Light3D *light = lights_found[i].light;
  904. if (light->is_editor_only()) {
  905. // Don't include editor-only lights in the lightmap bake,
  906. // as this results in inconsistent visuals when running the project.
  907. continue;
  908. }
  909. Transform3D xf = lights_found[i].xform;
  910. // For the lightmapper, the indirect energy represents the multiplier for the indirect bounces caused by the light, so the value is not converted when using physical units.
  911. float indirect_energy = light->get_param(Light3D::PARAM_INDIRECT_ENERGY);
  912. Color linear_color = light->get_color().srgb_to_linear();
  913. float energy = light->get_param(Light3D::PARAM_ENERGY);
  914. if (use_physical_light_units) {
  915. energy *= light->get_param(Light3D::PARAM_INTENSITY);
  916. linear_color *= light->get_correlated_color().srgb_to_linear();
  917. }
  918. if (Object::cast_to<DirectionalLight3D>(light)) {
  919. DirectionalLight3D *l = Object::cast_to<DirectionalLight3D>(light);
  920. if (l->get_sky_mode() != DirectionalLight3D::SKY_MODE_SKY_ONLY) {
  921. lightmapper->add_directional_light(light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, energy, indirect_energy, l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
  922. }
  923. } else if (Object::cast_to<OmniLight3D>(light)) {
  924. OmniLight3D *l = Object::cast_to<OmniLight3D>(light);
  925. if (use_physical_light_units) {
  926. energy *= (1.0 / (Math_PI * 4.0));
  927. }
  928. lightmapper->add_omni_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, linear_color, energy, indirect_energy, l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
  929. } else if (Object::cast_to<SpotLight3D>(light)) {
  930. SpotLight3D *l = Object::cast_to<SpotLight3D>(light);
  931. if (use_physical_light_units) {
  932. energy *= (1.0 / Math_PI);
  933. }
  934. lightmapper->add_spot_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, energy, indirect_energy, l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SPOT_ANGLE), l->get_param(Light3D::PARAM_SPOT_ATTENUATION), l->get_param(Light3D::PARAM_SIZE), l->get_param(Light3D::PARAM_SHADOW_BLUR));
  935. }
  936. }
  937. for (int i = 0; i < probes_found.size(); i++) {
  938. lightmapper->add_probe(probes_found[i]);
  939. }
  940. }
  941. Ref<Image> environment_image;
  942. Basis environment_transform;
  943. // Add everything to lightmapper
  944. if (environment_mode != ENVIRONMENT_MODE_DISABLED) {
  945. if (p_bake_step) {
  946. p_bake_step(4.1, RTR("Preparing Environment"), p_bake_userdata, true);
  947. }
  948. environment_transform = get_global_transform().basis;
  949. switch (environment_mode) {
  950. case ENVIRONMENT_MODE_DISABLED: {
  951. //nothing
  952. } break;
  953. case ENVIRONMENT_MODE_SCENE: {
  954. Ref<World3D> world = get_world_3d();
  955. if (world.is_valid()) {
  956. Ref<Environment> env = world->get_environment();
  957. if (env.is_null()) {
  958. env = world->get_fallback_environment();
  959. }
  960. if (env.is_valid()) {
  961. environment_image = RS::get_singleton()->environment_bake_panorama(env->get_rid(), true, Size2i(128, 64));
  962. environment_transform = Basis::from_euler(env->get_sky_rotation()).inverse();
  963. }
  964. }
  965. } break;
  966. case ENVIRONMENT_MODE_CUSTOM_SKY: {
  967. if (environment_custom_sky.is_valid()) {
  968. environment_image = RS::get_singleton()->sky_bake_panorama(environment_custom_sky->get_rid(), environment_custom_energy, true, Size2i(128, 64));
  969. }
  970. } break;
  971. case ENVIRONMENT_MODE_CUSTOM_COLOR: {
  972. environment_image.instantiate();
  973. environment_image->initialize_data(128, 64, false, Image::FORMAT_RGBAF);
  974. Color c = environment_custom_color;
  975. c.r *= environment_custom_energy;
  976. c.g *= environment_custom_energy;
  977. c.b *= environment_custom_energy;
  978. environment_image->fill(c);
  979. } break;
  980. }
  981. }
  982. float exposure_normalization = 1.0;
  983. if (camera_attributes.is_valid()) {
  984. exposure_normalization = camera_attributes->get_exposure_multiplier();
  985. if (use_physical_light_units) {
  986. exposure_normalization = camera_attributes->calculate_exposure_normalization();
  987. }
  988. }
  989. Lightmapper::BakeError bake_err = lightmapper->bake(Lightmapper::BakeQuality(bake_quality), use_denoiser, denoiser_strength, denoiser_range, bounces, bounce_indirect_energy, bias, max_texture_size, directional, use_texture_for_bounces, Lightmapper::GenerateProbes(gen_probes), environment_image, environment_transform, _lightmap_bake_step_function, &bsud, exposure_normalization);
  990. if (bake_err == Lightmapper::BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE) {
  991. return BAKE_ERROR_TEXTURE_SIZE_TOO_SMALL;
  992. } else if (bake_err == Lightmapper::BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES) {
  993. return BAKE_ERROR_MESHES_INVALID;
  994. } else if (bake_err == Lightmapper::BAKE_ERROR_ATLAS_TOO_SMALL) {
  995. return BAKE_ERROR_ATLAS_TOO_SMALL;
  996. } else if (bake_err == Lightmapper::BAKE_ERROR_USER_ABORTED) {
  997. return BAKE_ERROR_USER_ABORTED;
  998. }
  999. // POSTBAKE: Save Textures.
  1000. TypedArray<TextureLayered> lightmap_textures;
  1001. const String texture_filename = p_image_data_path.get_basename();
  1002. // Save the lightmap atlases.
  1003. BakeError save_err = _save_and_reimport_atlas_textures(lightmapper, texture_filename, lightmap_textures, false);
  1004. ERR_FAIL_COND_V(save_err != BAKE_ERROR_OK, save_err);
  1005. // POSTBAKE: Save Light Data.
  1006. Ref<LightmapGIData> gi_data;
  1007. if (get_light_data().is_valid()) {
  1008. gi_data = get_light_data();
  1009. set_light_data(Ref<LightmapGIData>()); // Clear.
  1010. gi_data->clear();
  1011. } else {
  1012. gi_data.instantiate();
  1013. }
  1014. gi_data->set_lightmap_textures(lightmap_textures);
  1015. gi_data->set_uses_spherical_harmonics(directional);
  1016. gi_data->_set_uses_packed_directional(directional); // New SH lightmaps are packed automatically.
  1017. for (int i = 0; i < lightmapper->get_bake_mesh_count(); i++) {
  1018. Dictionary d = lightmapper->get_bake_mesh_userdata(i);
  1019. NodePath np = d["path"];
  1020. int32_t subindex = -1;
  1021. if (d.has("subindex")) {
  1022. subindex = d["subindex"];
  1023. }
  1024. Rect2 uv_scale = lightmapper->get_bake_mesh_uv_scale(i);
  1025. int slice_index = lightmapper->get_bake_mesh_texture_slice(i);
  1026. gi_data->add_user(np, uv_scale, slice_index, subindex);
  1027. }
  1028. {
  1029. // create tetrahedrons
  1030. Vector<Vector3> points;
  1031. Vector<Color> sh;
  1032. points.resize(lightmapper->get_bake_probe_count());
  1033. sh.resize(lightmapper->get_bake_probe_count() * 9);
  1034. for (int i = 0; i < lightmapper->get_bake_probe_count(); i++) {
  1035. points.write[i] = lightmapper->get_bake_probe_point(i);
  1036. Vector<Color> colors = lightmapper->get_bake_probe_sh(i);
  1037. ERR_CONTINUE(colors.size() != 9);
  1038. for (int j = 0; j < 9; j++) {
  1039. sh.write[i * 9 + j] = colors[j];
  1040. }
  1041. }
  1042. //Obtain solved simplices
  1043. if (p_bake_step) {
  1044. p_bake_step(0.8, RTR("Generating Probe Volumes"), p_bake_userdata, true);
  1045. }
  1046. Vector<Delaunay3D::OutputSimplex> solved_simplices = Delaunay3D::tetrahedralize(points);
  1047. LocalVector<BSPSimplex> bsp_simplices;
  1048. LocalVector<Plane> bsp_planes;
  1049. LocalVector<int32_t> bsp_simplex_indices;
  1050. PackedInt32Array tetrahedrons;
  1051. for (int i = 0; i < solved_simplices.size(); i++) {
  1052. //Prepare a special representation of the simplex, which uses a BSP Tree
  1053. BSPSimplex bsp_simplex;
  1054. for (int j = 0; j < 4; j++) {
  1055. bsp_simplex.vertices[j] = solved_simplices[i].points[j];
  1056. }
  1057. for (int j = 0; j < 4; j++) {
  1058. static const int face_order[4][3] = {
  1059. { 0, 1, 2 },
  1060. { 0, 2, 3 },
  1061. { 0, 1, 3 },
  1062. { 1, 2, 3 }
  1063. };
  1064. Vector3 a = points[solved_simplices[i].points[face_order[j][0]]];
  1065. Vector3 b = points[solved_simplices[i].points[face_order[j][1]]];
  1066. Vector3 c = points[solved_simplices[i].points[face_order[j][2]]];
  1067. //store planes in an array, but ensure they are reused, to speed up processing
  1068. Plane p(a, b, c);
  1069. int plane_index = -1;
  1070. for (uint32_t k = 0; k < bsp_planes.size(); k++) {
  1071. if (bsp_planes[k].is_equal_approx_any_side(p)) {
  1072. plane_index = k;
  1073. break;
  1074. }
  1075. }
  1076. if (plane_index == -1) {
  1077. plane_index = bsp_planes.size();
  1078. bsp_planes.push_back(p);
  1079. }
  1080. bsp_simplex.planes[j] = plane_index;
  1081. //also fill simplex array
  1082. tetrahedrons.push_back(solved_simplices[i].points[j]);
  1083. }
  1084. bsp_simplex_indices.push_back(bsp_simplices.size());
  1085. bsp_simplices.push_back(bsp_simplex);
  1086. }
  1087. //#define DEBUG_SIMPLICES_AS_OBJ_FILE
  1088. #ifdef DEBUG_SIMPLICES_AS_OBJ_FILE
  1089. {
  1090. Ref<FileAccess> f = FileAccess::open("res://bsp.obj", FileAccess::WRITE);
  1091. for (uint32_t i = 0; i < bsp_simplices.size(); i++) {
  1092. f->store_line("o Simplex" + itos(i));
  1093. for (int j = 0; j < 4; j++) {
  1094. f->store_line(vformat("v %f %f %f", points[bsp_simplices[i].vertices[j]].x, points[bsp_simplices[i].vertices[j]].y, points[bsp_simplices[i].vertices[j]].z));
  1095. }
  1096. static const int face_order[4][3] = {
  1097. { 1, 2, 3 },
  1098. { 1, 3, 4 },
  1099. { 1, 2, 4 },
  1100. { 2, 3, 4 }
  1101. };
  1102. for (int j = 0; j < 4; j++) {
  1103. f->store_line(vformat("f %d %d %d", 4 * i + face_order[j][0], 4 * i + face_order[j][1], 4 * i + face_order[j][2]));
  1104. }
  1105. }
  1106. }
  1107. #endif
  1108. LocalVector<BSPNode> bsp_nodes;
  1109. LocalVector<int32_t> planes_tested;
  1110. planes_tested.resize(bsp_planes.size());
  1111. for (int &index : planes_tested) {
  1112. index = 0x7FFFFFFF;
  1113. }
  1114. if (p_bake_step) {
  1115. p_bake_step(0.9, RTR("Generating Probe Acceleration Structures"), p_bake_userdata, true);
  1116. }
  1117. _compute_bsp_tree(points, bsp_planes, planes_tested, bsp_simplices, bsp_simplex_indices, bsp_nodes);
  1118. PackedInt32Array bsp_array;
  1119. bsp_array.resize(bsp_nodes.size() * 6); // six 32 bits values used for each BSP node
  1120. {
  1121. float *fptr = (float *)bsp_array.ptrw();
  1122. int32_t *iptr = (int32_t *)bsp_array.ptrw();
  1123. for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
  1124. fptr[i * 6 + 0] = bsp_nodes[i].plane.normal.x;
  1125. fptr[i * 6 + 1] = bsp_nodes[i].plane.normal.y;
  1126. fptr[i * 6 + 2] = bsp_nodes[i].plane.normal.z;
  1127. fptr[i * 6 + 3] = bsp_nodes[i].plane.d;
  1128. iptr[i * 6 + 4] = bsp_nodes[i].over;
  1129. iptr[i * 6 + 5] = bsp_nodes[i].under;
  1130. }
  1131. //#define DEBUG_BSP_TREE
  1132. #ifdef DEBUG_BSP_TREE
  1133. Ref<FileAccess> f = FileAccess::open("res://bsp.txt", FileAccess::WRITE);
  1134. for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
  1135. f->store_line(itos(i) + " - plane: " + bsp_nodes[i].plane + " over: " + itos(bsp_nodes[i].over) + " under: " + itos(bsp_nodes[i].under));
  1136. }
  1137. #endif
  1138. }
  1139. /* Obtain the colors from the images, they will be re-created as cubemaps on the server, depending on the driver */
  1140. gi_data->set_capture_data(bounds, interior, points, sh, tetrahedrons, bsp_array, exposure_normalization);
  1141. /* Compute a BSP tree of the simplices, so it's easy to find the exact one */
  1142. }
  1143. gi_data->set_path(p_image_data_path, true);
  1144. Error err = ResourceSaver::save(gi_data);
  1145. if (err != OK) {
  1146. return BAKE_ERROR_CANT_CREATE_IMAGE;
  1147. }
  1148. set_light_data(gi_data);
  1149. return BAKE_ERROR_OK;
  1150. }
  1151. void LightmapGI::_notification(int p_what) {
  1152. switch (p_what) {
  1153. case NOTIFICATION_POST_ENTER_TREE: {
  1154. if (light_data.is_valid()) {
  1155. ERR_FAIL_COND_MSG(
  1156. light_data->is_using_spherical_harmonics() && !light_data->_is_using_packed_directional(),
  1157. vformat(
  1158. "%s (%s): The directional lightmap textures are stored in a format that isn't supported anymore. Please bake lightmaps again to make lightmaps display from this node again.",
  1159. get_light_data()->get_path(), get_name()));
  1160. _assign_lightmaps();
  1161. }
  1162. } break;
  1163. case NOTIFICATION_EXIT_TREE: {
  1164. if (light_data.is_valid()) {
  1165. _clear_lightmaps();
  1166. }
  1167. } break;
  1168. }
  1169. }
  1170. void LightmapGI::_assign_lightmaps() {
  1171. ERR_FAIL_COND(!light_data.is_valid());
  1172. for (int i = 0; i < light_data->get_user_count(); i++) {
  1173. Node *node = get_node(light_data->get_user_path(i));
  1174. int instance_idx = light_data->get_user_sub_instance(i);
  1175. if (instance_idx >= 0) {
  1176. RID instance_id = node->call("get_bake_mesh_instance", instance_idx);
  1177. if (instance_id.is_valid()) {
  1178. RS::get_singleton()->instance_geometry_set_lightmap(instance_id, get_instance(), light_data->get_user_lightmap_uv_scale(i), light_data->get_user_lightmap_slice_index(i));
  1179. }
  1180. } else {
  1181. VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(node);
  1182. ERR_CONTINUE(!vi);
  1183. RS::get_singleton()->instance_geometry_set_lightmap(vi->get_instance(), get_instance(), light_data->get_user_lightmap_uv_scale(i), light_data->get_user_lightmap_slice_index(i));
  1184. }
  1185. }
  1186. }
  1187. void LightmapGI::_clear_lightmaps() {
  1188. ERR_FAIL_COND(!light_data.is_valid());
  1189. for (int i = 0; i < light_data->get_user_count(); i++) {
  1190. Node *node = get_node(light_data->get_user_path(i));
  1191. int instance_idx = light_data->get_user_sub_instance(i);
  1192. if (instance_idx >= 0) {
  1193. RID instance_id = node->call("get_bake_mesh_instance", instance_idx);
  1194. if (instance_id.is_valid()) {
  1195. RS::get_singleton()->instance_geometry_set_lightmap(instance_id, RID(), Rect2(), 0);
  1196. }
  1197. } else {
  1198. VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(node);
  1199. ERR_CONTINUE(!vi);
  1200. RS::get_singleton()->instance_geometry_set_lightmap(vi->get_instance(), RID(), Rect2(), 0);
  1201. }
  1202. }
  1203. }
  1204. void LightmapGI::set_light_data(const Ref<LightmapGIData> &p_data) {
  1205. if (light_data.is_valid()) {
  1206. if (is_inside_tree()) {
  1207. _clear_lightmaps();
  1208. }
  1209. set_base(RID());
  1210. }
  1211. light_data = p_data;
  1212. if (light_data.is_valid()) {
  1213. set_base(light_data->get_rid());
  1214. if (is_inside_tree()) {
  1215. _assign_lightmaps();
  1216. }
  1217. }
  1218. update_gizmos();
  1219. }
  1220. Ref<LightmapGIData> LightmapGI::get_light_data() const {
  1221. return light_data;
  1222. }
  1223. void LightmapGI::set_bake_quality(BakeQuality p_quality) {
  1224. bake_quality = p_quality;
  1225. }
  1226. LightmapGI::BakeQuality LightmapGI::get_bake_quality() const {
  1227. return bake_quality;
  1228. }
  1229. AABB LightmapGI::get_aabb() const {
  1230. return AABB();
  1231. }
  1232. void LightmapGI::set_use_denoiser(bool p_enable) {
  1233. use_denoiser = p_enable;
  1234. notify_property_list_changed();
  1235. }
  1236. bool LightmapGI::is_using_denoiser() const {
  1237. return use_denoiser;
  1238. }
  1239. void LightmapGI::set_denoiser_strength(float p_denoiser_strength) {
  1240. denoiser_strength = p_denoiser_strength;
  1241. }
  1242. float LightmapGI::get_denoiser_strength() const {
  1243. return denoiser_strength;
  1244. }
  1245. void LightmapGI::set_denoiser_range(int p_denoiser_range) {
  1246. denoiser_range = p_denoiser_range;
  1247. }
  1248. int LightmapGI::get_denoiser_range() const {
  1249. return denoiser_range;
  1250. }
  1251. void LightmapGI::set_directional(bool p_enable) {
  1252. directional = p_enable;
  1253. }
  1254. bool LightmapGI::is_directional() const {
  1255. return directional;
  1256. }
  1257. void LightmapGI::set_use_texture_for_bounces(bool p_enable) {
  1258. use_texture_for_bounces = p_enable;
  1259. }
  1260. bool LightmapGI::is_using_texture_for_bounces() const {
  1261. return use_texture_for_bounces;
  1262. }
  1263. void LightmapGI::set_interior(bool p_enable) {
  1264. interior = p_enable;
  1265. }
  1266. bool LightmapGI::is_interior() const {
  1267. return interior;
  1268. }
  1269. void LightmapGI::set_environment_mode(EnvironmentMode p_mode) {
  1270. environment_mode = p_mode;
  1271. notify_property_list_changed();
  1272. }
  1273. LightmapGI::EnvironmentMode LightmapGI::get_environment_mode() const {
  1274. return environment_mode;
  1275. }
  1276. void LightmapGI::set_environment_custom_sky(const Ref<Sky> &p_sky) {
  1277. environment_custom_sky = p_sky;
  1278. }
  1279. Ref<Sky> LightmapGI::get_environment_custom_sky() const {
  1280. return environment_custom_sky;
  1281. }
  1282. void LightmapGI::set_environment_custom_color(const Color &p_color) {
  1283. environment_custom_color = p_color;
  1284. }
  1285. Color LightmapGI::get_environment_custom_color() const {
  1286. return environment_custom_color;
  1287. }
  1288. void LightmapGI::set_environment_custom_energy(float p_energy) {
  1289. environment_custom_energy = p_energy;
  1290. }
  1291. float LightmapGI::get_environment_custom_energy() const {
  1292. return environment_custom_energy;
  1293. }
  1294. void LightmapGI::set_bounces(int p_bounces) {
  1295. ERR_FAIL_COND(p_bounces < 0 || p_bounces > 16);
  1296. bounces = p_bounces;
  1297. }
  1298. int LightmapGI::get_bounces() const {
  1299. return bounces;
  1300. }
  1301. void LightmapGI::set_bounce_indirect_energy(float p_indirect_energy) {
  1302. ERR_FAIL_COND(p_indirect_energy < 0.0);
  1303. bounce_indirect_energy = p_indirect_energy;
  1304. }
  1305. float LightmapGI::get_bounce_indirect_energy() const {
  1306. return bounce_indirect_energy;
  1307. }
  1308. void LightmapGI::set_bias(float p_bias) {
  1309. ERR_FAIL_COND(p_bias < 0.00001);
  1310. bias = p_bias;
  1311. }
  1312. float LightmapGI::get_bias() const {
  1313. return bias;
  1314. }
  1315. void LightmapGI::set_texel_scale(float p_multiplier) {
  1316. ERR_FAIL_COND(p_multiplier < (0.01 - CMP_EPSILON));
  1317. texel_scale = p_multiplier;
  1318. }
  1319. float LightmapGI::get_texel_scale() const {
  1320. return texel_scale;
  1321. }
  1322. void LightmapGI::set_max_texture_size(int p_size) {
  1323. ERR_FAIL_COND_MSG(p_size < 2048, vformat("The LightmapGI maximum texture size supplied (%d) is too small. The minimum allowed value is 2048.", p_size));
  1324. ERR_FAIL_COND_MSG(p_size > 16384, vformat("The LightmapGI maximum texture size supplied (%d) is too large. The maximum allowed value is 16384.", p_size));
  1325. max_texture_size = p_size;
  1326. }
  1327. int LightmapGI::get_max_texture_size() const {
  1328. return max_texture_size;
  1329. }
  1330. void LightmapGI::set_generate_probes(GenerateProbes p_generate_probes) {
  1331. gen_probes = p_generate_probes;
  1332. }
  1333. LightmapGI::GenerateProbes LightmapGI::get_generate_probes() const {
  1334. return gen_probes;
  1335. }
  1336. void LightmapGI::set_camera_attributes(const Ref<CameraAttributes> &p_camera_attributes) {
  1337. camera_attributes = p_camera_attributes;
  1338. }
  1339. Ref<CameraAttributes> LightmapGI::get_camera_attributes() const {
  1340. return camera_attributes;
  1341. }
  1342. PackedStringArray LightmapGI::get_configuration_warnings() const {
  1343. PackedStringArray warnings = VisualInstance3D::get_configuration_warnings();
  1344. #ifdef MODULE_LIGHTMAPPER_RD_ENABLED
  1345. if (!DisplayServer::get_singleton()->can_create_rendering_device()) {
  1346. warnings.push_back(vformat(RTR("Lightmaps can only be baked from a GPU that supports the RenderingDevice backends.\nYour GPU (%s) does not support RenderingDevice, as it does not support Vulkan, Direct3D 12, or Metal.\nLightmap baking will not be available on this device, although rendering existing baked lightmaps will work."), RenderingServer::get_singleton()->get_video_adapter_name()));
  1347. return warnings;
  1348. }
  1349. #elif defined(ANDROID_ENABLED) || defined(IOS_ENABLED)
  1350. warnings.push_back(vformat(RTR("Lightmaps cannot be baked on %s. Rendering existing baked lightmaps will still work."), OS::get_singleton()->get_name()));
  1351. #else
  1352. warnings.push_back(RTR("Lightmaps cannot be baked, as the `lightmapper_rd` module was disabled at compile-time. Rendering existing baked lightmaps will still work."));
  1353. #endif
  1354. return warnings;
  1355. }
  1356. void LightmapGI::_validate_property(PropertyInfo &p_property) const {
  1357. if (p_property.name == "environment_custom_sky" && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
  1358. p_property.usage = PROPERTY_USAGE_NONE;
  1359. }
  1360. if (p_property.name == "environment_custom_color" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR) {
  1361. p_property.usage = PROPERTY_USAGE_NONE;
  1362. }
  1363. if (p_property.name == "environment_custom_energy" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
  1364. p_property.usage = PROPERTY_USAGE_NONE;
  1365. }
  1366. if (p_property.name == "denoiser_strength" && !use_denoiser) {
  1367. p_property.usage = PROPERTY_USAGE_NONE;
  1368. }
  1369. if (p_property.name == "denoiser_range" && !use_denoiser) {
  1370. p_property.usage = PROPERTY_USAGE_NONE;
  1371. }
  1372. }
  1373. void LightmapGI::_bind_methods() {
  1374. ClassDB::bind_method(D_METHOD("set_light_data", "data"), &LightmapGI::set_light_data);
  1375. ClassDB::bind_method(D_METHOD("get_light_data"), &LightmapGI::get_light_data);
  1376. ClassDB::bind_method(D_METHOD("set_bake_quality", "bake_quality"), &LightmapGI::set_bake_quality);
  1377. ClassDB::bind_method(D_METHOD("get_bake_quality"), &LightmapGI::get_bake_quality);
  1378. ClassDB::bind_method(D_METHOD("set_bounces", "bounces"), &LightmapGI::set_bounces);
  1379. ClassDB::bind_method(D_METHOD("get_bounces"), &LightmapGI::get_bounces);
  1380. ClassDB::bind_method(D_METHOD("set_bounce_indirect_energy", "bounce_indirect_energy"), &LightmapGI::set_bounce_indirect_energy);
  1381. ClassDB::bind_method(D_METHOD("get_bounce_indirect_energy"), &LightmapGI::get_bounce_indirect_energy);
  1382. ClassDB::bind_method(D_METHOD("set_generate_probes", "subdivision"), &LightmapGI::set_generate_probes);
  1383. ClassDB::bind_method(D_METHOD("get_generate_probes"), &LightmapGI::get_generate_probes);
  1384. ClassDB::bind_method(D_METHOD("set_bias", "bias"), &LightmapGI::set_bias);
  1385. ClassDB::bind_method(D_METHOD("get_bias"), &LightmapGI::get_bias);
  1386. ClassDB::bind_method(D_METHOD("set_environment_mode", "mode"), &LightmapGI::set_environment_mode);
  1387. ClassDB::bind_method(D_METHOD("get_environment_mode"), &LightmapGI::get_environment_mode);
  1388. ClassDB::bind_method(D_METHOD("set_environment_custom_sky", "sky"), &LightmapGI::set_environment_custom_sky);
  1389. ClassDB::bind_method(D_METHOD("get_environment_custom_sky"), &LightmapGI::get_environment_custom_sky);
  1390. ClassDB::bind_method(D_METHOD("set_environment_custom_color", "color"), &LightmapGI::set_environment_custom_color);
  1391. ClassDB::bind_method(D_METHOD("get_environment_custom_color"), &LightmapGI::get_environment_custom_color);
  1392. ClassDB::bind_method(D_METHOD("set_environment_custom_energy", "energy"), &LightmapGI::set_environment_custom_energy);
  1393. ClassDB::bind_method(D_METHOD("get_environment_custom_energy"), &LightmapGI::get_environment_custom_energy);
  1394. ClassDB::bind_method(D_METHOD("set_texel_scale", "texel_scale"), &LightmapGI::set_texel_scale);
  1395. ClassDB::bind_method(D_METHOD("get_texel_scale"), &LightmapGI::get_texel_scale);
  1396. ClassDB::bind_method(D_METHOD("set_max_texture_size", "max_texture_size"), &LightmapGI::set_max_texture_size);
  1397. ClassDB::bind_method(D_METHOD("get_max_texture_size"), &LightmapGI::get_max_texture_size);
  1398. ClassDB::bind_method(D_METHOD("set_use_denoiser", "use_denoiser"), &LightmapGI::set_use_denoiser);
  1399. ClassDB::bind_method(D_METHOD("is_using_denoiser"), &LightmapGI::is_using_denoiser);
  1400. ClassDB::bind_method(D_METHOD("set_denoiser_strength", "denoiser_strength"), &LightmapGI::set_denoiser_strength);
  1401. ClassDB::bind_method(D_METHOD("get_denoiser_strength"), &LightmapGI::get_denoiser_strength);
  1402. ClassDB::bind_method(D_METHOD("set_denoiser_range", "denoiser_range"), &LightmapGI::set_denoiser_range);
  1403. ClassDB::bind_method(D_METHOD("get_denoiser_range"), &LightmapGI::get_denoiser_range);
  1404. ClassDB::bind_method(D_METHOD("set_interior", "enable"), &LightmapGI::set_interior);
  1405. ClassDB::bind_method(D_METHOD("is_interior"), &LightmapGI::is_interior);
  1406. ClassDB::bind_method(D_METHOD("set_directional", "directional"), &LightmapGI::set_directional);
  1407. ClassDB::bind_method(D_METHOD("is_directional"), &LightmapGI::is_directional);
  1408. ClassDB::bind_method(D_METHOD("set_use_texture_for_bounces", "use_texture_for_bounces"), &LightmapGI::set_use_texture_for_bounces);
  1409. ClassDB::bind_method(D_METHOD("is_using_texture_for_bounces"), &LightmapGI::is_using_texture_for_bounces);
  1410. ClassDB::bind_method(D_METHOD("set_camera_attributes", "camera_attributes"), &LightmapGI::set_camera_attributes);
  1411. ClassDB::bind_method(D_METHOD("get_camera_attributes"), &LightmapGI::get_camera_attributes);
  1412. // ClassDB::bind_method(D_METHOD("bake", "from_node"), &LightmapGI::bake, DEFVAL(Variant()));
  1413. ADD_GROUP("Tweaks", "");
  1414. ADD_PROPERTY(PropertyInfo(Variant::INT, "quality", PROPERTY_HINT_ENUM, "Low,Medium,High,Ultra"), "set_bake_quality", "get_bake_quality");
  1415. ADD_PROPERTY(PropertyInfo(Variant::INT, "bounces", PROPERTY_HINT_RANGE, "0,6,1,or_greater"), "set_bounces", "get_bounces");
  1416. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bounce_indirect_energy", PROPERTY_HINT_RANGE, "0,2,0.01"), "set_bounce_indirect_energy", "get_bounce_indirect_energy");
  1417. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "directional"), "set_directional", "is_directional");
  1418. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_texture_for_bounces"), "set_use_texture_for_bounces", "is_using_texture_for_bounces");
  1419. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior");
  1420. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_denoiser"), "set_use_denoiser", "is_using_denoiser");
  1421. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "denoiser_strength", PROPERTY_HINT_RANGE, "0.001,0.2,0.001,or_greater"), "set_denoiser_strength", "get_denoiser_strength");
  1422. ADD_PROPERTY(PropertyInfo(Variant::INT, "denoiser_range", PROPERTY_HINT_RANGE, "1,20"), "set_denoiser_range", "get_denoiser_range");
  1423. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bias", PROPERTY_HINT_RANGE, "0.00001,0.1,0.00001,or_greater"), "set_bias", "get_bias");
  1424. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "texel_scale", PROPERTY_HINT_RANGE, "0.01,100.0,0.01"), "set_texel_scale", "get_texel_scale");
  1425. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_texture_size", PROPERTY_HINT_RANGE, "2048,16384,1"), "set_max_texture_size", "get_max_texture_size");
  1426. ADD_GROUP("Environment", "environment_");
  1427. ADD_PROPERTY(PropertyInfo(Variant::INT, "environment_mode", PROPERTY_HINT_ENUM, "Disabled,Scene,Custom Sky,Custom Color"), "set_environment_mode", "get_environment_mode");
  1428. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment_custom_sky", PROPERTY_HINT_RESOURCE_TYPE, "Sky"), "set_environment_custom_sky", "get_environment_custom_sky");
  1429. ADD_PROPERTY(PropertyInfo(Variant::COLOR, "environment_custom_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_environment_custom_color", "get_environment_custom_color");
  1430. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "environment_custom_energy", PROPERTY_HINT_RANGE, "0,64,0.01"), "set_environment_custom_energy", "get_environment_custom_energy");
  1431. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "camera_attributes", PROPERTY_HINT_RESOURCE_TYPE, "CameraAttributesPractical,CameraAttributesPhysical"), "set_camera_attributes", "get_camera_attributes");
  1432. ADD_GROUP("Gen Probes", "generate_probes_");
  1433. ADD_PROPERTY(PropertyInfo(Variant::INT, "generate_probes_subdiv", PROPERTY_HINT_ENUM, "Disabled,4,8,16,32"), "set_generate_probes", "get_generate_probes");
  1434. ADD_GROUP("Data", "");
  1435. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_data", PROPERTY_HINT_RESOURCE_TYPE, "LightmapGIData"), "set_light_data", "get_light_data");
  1436. BIND_ENUM_CONSTANT(BAKE_QUALITY_LOW);
  1437. BIND_ENUM_CONSTANT(BAKE_QUALITY_MEDIUM);
  1438. BIND_ENUM_CONSTANT(BAKE_QUALITY_HIGH);
  1439. BIND_ENUM_CONSTANT(BAKE_QUALITY_ULTRA);
  1440. BIND_ENUM_CONSTANT(GENERATE_PROBES_DISABLED);
  1441. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_4);
  1442. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_8);
  1443. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_16);
  1444. BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_32);
  1445. BIND_ENUM_CONSTANT(BAKE_ERROR_OK);
  1446. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SCENE_ROOT);
  1447. BIND_ENUM_CONSTANT(BAKE_ERROR_FOREIGN_DATA);
  1448. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_LIGHTMAPPER);
  1449. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SAVE_PATH);
  1450. BIND_ENUM_CONSTANT(BAKE_ERROR_NO_MESHES);
  1451. BIND_ENUM_CONSTANT(BAKE_ERROR_MESHES_INVALID);
  1452. BIND_ENUM_CONSTANT(BAKE_ERROR_CANT_CREATE_IMAGE);
  1453. BIND_ENUM_CONSTANT(BAKE_ERROR_USER_ABORTED);
  1454. BIND_ENUM_CONSTANT(BAKE_ERROR_TEXTURE_SIZE_TOO_SMALL);
  1455. BIND_ENUM_CONSTANT(BAKE_ERROR_LIGHTMAP_TOO_SMALL);
  1456. BIND_ENUM_CONSTANT(BAKE_ERROR_ATLAS_TOO_SMALL);
  1457. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_DISABLED);
  1458. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_SCENE);
  1459. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_SKY);
  1460. BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_COLOR);
  1461. }
  1462. LightmapGI::LightmapGI() {
  1463. }