2
0

lightmapper_cpu.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. /*************************************************************************/
  2. /* lightmapper_cpu.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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_cpu.h"
  31. #include "core/math/geometry.h"
  32. #include "core/os/os.h"
  33. #include "core/os/threaded_array_processor.h"
  34. #include "core/project_settings.h"
  35. #include "modules/raycast/lightmap_raycaster.h"
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/editor_settings.h"
  38. #endif
  39. Error LightmapperCPU::_layout_atlas(int p_max_size, Vector2i *r_atlas_size, int *r_atlas_slices) {
  40. Vector2i atlas_size;
  41. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  42. if (mesh_instances[i].generate_lightmap) {
  43. Vector2i size = mesh_instances[i].size;
  44. atlas_size.width = MAX(atlas_size.width, size.width + 2);
  45. atlas_size.height = MAX(atlas_size.height, size.height + 2);
  46. }
  47. }
  48. int max = nearest_power_of_2_templated(atlas_size.width);
  49. max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
  50. if (max > p_max_size) {
  51. return ERR_INVALID_DATA;
  52. }
  53. Vector2i best_atlas_size;
  54. int best_atlas_slices = 0;
  55. int best_atlas_memory = 0x7FFFFFFF;
  56. float best_atlas_mem_utilization = 0;
  57. Vector<AtlasOffset> best_atlas_offsets;
  58. Vector<Vector2i> best_scaled_sizes;
  59. int first_try_mem_occupied = 0;
  60. int first_try_mem_used = 0;
  61. for (int recovery_percent = 0; recovery_percent <= 100; recovery_percent += 10) {
  62. // These only make sense from the second round of the loop
  63. float recovery_scale = 1;
  64. int target_mem_occupied = 0;
  65. if (recovery_percent != 0) {
  66. target_mem_occupied = first_try_mem_occupied + (first_try_mem_used - first_try_mem_occupied) * recovery_percent * 0.01f;
  67. float new_squared_recovery_scale = static_cast<float>(target_mem_occupied) / first_try_mem_occupied;
  68. if (new_squared_recovery_scale > 1.0f) {
  69. recovery_scale = Math::sqrt(new_squared_recovery_scale);
  70. }
  71. }
  72. atlas_size = Vector2i(max, max);
  73. while (atlas_size.x <= p_max_size && atlas_size.y <= p_max_size) {
  74. if (recovery_percent != 0) {
  75. // Find out how much memory is not recoverable (because of lightmaps that can't grow),
  76. // to compute a greater recovery scale for those that can.
  77. int mem_unrecoverable = 0;
  78. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  79. if (mesh_instances[i].generate_lightmap) {
  80. Vector2i scaled_size = Vector2i(
  81. static_cast<int>(recovery_scale * mesh_instances[i].size.x),
  82. static_cast<int>(recovery_scale * mesh_instances[i].size.y));
  83. if (scaled_size.x + 2 > atlas_size.x || scaled_size.y + 2 > atlas_size.y) {
  84. mem_unrecoverable += scaled_size.x * scaled_size.y - mesh_instances[i].size.x * mesh_instances[i].size.y;
  85. }
  86. }
  87. }
  88. float new_squared_recovery_scale = static_cast<float>(target_mem_occupied - mem_unrecoverable) / (first_try_mem_occupied - mem_unrecoverable);
  89. if (new_squared_recovery_scale > 1.0f) {
  90. recovery_scale = Math::sqrt(new_squared_recovery_scale);
  91. }
  92. }
  93. Vector<Vector2i> scaled_sizes;
  94. scaled_sizes.resize(mesh_instances.size());
  95. {
  96. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  97. if (mesh_instances[i].generate_lightmap) {
  98. if (recovery_percent == 0) {
  99. scaled_sizes.write[i] = mesh_instances[i].size;
  100. } else {
  101. Vector2i scaled_size = Vector2i(
  102. static_cast<int>(recovery_scale * mesh_instances[i].size.x),
  103. static_cast<int>(recovery_scale * mesh_instances[i].size.y));
  104. if (scaled_size.x + 2 <= atlas_size.x && scaled_size.y + 2 <= atlas_size.y) {
  105. scaled_sizes.write[i] = scaled_size;
  106. } else {
  107. scaled_sizes.write[i] = mesh_instances[i].size;
  108. }
  109. }
  110. } else {
  111. // Don't consider meshes with no generated lightmap here; will compensate later
  112. scaled_sizes.write[i] = Vector2i();
  113. }
  114. }
  115. }
  116. Vector<Vector2i> source_sizes;
  117. source_sizes.resize(scaled_sizes.size());
  118. Vector<int> source_indices;
  119. source_indices.resize(scaled_sizes.size());
  120. for (int i = 0; i < source_sizes.size(); i++) {
  121. source_sizes.write[i] = scaled_sizes[i] + Vector2i(2, 2); // Add padding between lightmaps
  122. source_indices.write[i] = i;
  123. }
  124. Vector<AtlasOffset> curr_atlas_offsets;
  125. curr_atlas_offsets.resize(source_sizes.size());
  126. int slices = 0;
  127. while (source_sizes.size() > 0) {
  128. Vector<Geometry::PackRectsResult> offsets = Geometry::partial_pack_rects(source_sizes, atlas_size);
  129. Vector<int> new_indices;
  130. Vector<Vector2i> new_sources;
  131. for (int i = 0; i < offsets.size(); i++) {
  132. Geometry::PackRectsResult ofs = offsets[i];
  133. int sidx = source_indices[i];
  134. if (ofs.packed) {
  135. curr_atlas_offsets.write[sidx] = { slices, ofs.x + 1, ofs.y + 1 };
  136. } else {
  137. new_indices.push_back(sidx);
  138. new_sources.push_back(source_sizes[i]);
  139. }
  140. }
  141. source_sizes = new_sources;
  142. source_indices = new_indices;
  143. slices++;
  144. }
  145. int mem_used = atlas_size.x * atlas_size.y * slices;
  146. int mem_occupied = 0;
  147. for (int i = 0; i < curr_atlas_offsets.size(); i++) {
  148. mem_occupied += scaled_sizes[i].x * scaled_sizes[i].y;
  149. }
  150. float mem_utilization = static_cast<float>(mem_occupied) / mem_used;
  151. if (slices * atlas_size.y < 16384) { // Maximum Image size
  152. if (mem_used < best_atlas_memory || (mem_used == best_atlas_memory && mem_utilization > best_atlas_mem_utilization)) {
  153. best_atlas_size = atlas_size;
  154. best_atlas_offsets = curr_atlas_offsets;
  155. best_atlas_slices = slices;
  156. best_atlas_memory = mem_used;
  157. best_atlas_mem_utilization = mem_utilization;
  158. best_scaled_sizes = scaled_sizes;
  159. }
  160. }
  161. if (recovery_percent == 0) {
  162. first_try_mem_occupied = mem_occupied;
  163. first_try_mem_used = mem_used;
  164. }
  165. if (atlas_size.width == atlas_size.height) {
  166. atlas_size.width *= 2;
  167. } else {
  168. atlas_size.height *= 2;
  169. }
  170. }
  171. }
  172. if (best_atlas_size == Vector2i()) {
  173. return ERR_INVALID_DATA;
  174. }
  175. *r_atlas_size = best_atlas_size;
  176. *r_atlas_slices = best_atlas_slices;
  177. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  178. if (best_scaled_sizes[i] != Vector2i()) {
  179. mesh_instances[i].size = best_scaled_sizes[i];
  180. mesh_instances[i].offset = Vector2i(best_atlas_offsets[i].x, best_atlas_offsets[i].y);
  181. mesh_instances[i].slice = best_atlas_offsets[i].slice;
  182. }
  183. }
  184. return OK;
  185. }
  186. void LightmapperCPU::_thread_func_callback(void *p_thread_data) {
  187. ThreadData *thread_data = reinterpret_cast<ThreadData *>(p_thread_data);
  188. #ifdef TOOLS_ENABLED
  189. const int num_threads = EDITOR_GET("editors/3d/lightmap_baking_number_of_cpu_threads");
  190. #else
  191. const int num_threads = 0;
  192. #endif
  193. thread_process_array(thread_data->count, thread_data->instance, &LightmapperCPU::_thread_func_wrapper, thread_data, num_threads);
  194. }
  195. void LightmapperCPU::_thread_func_wrapper(uint32_t p_idx, ThreadData *p_thread_data) {
  196. if (thread_cancelled) {
  197. return;
  198. }
  199. (p_thread_data->instance->*p_thread_data->thread_func)(p_idx, p_thread_data->userdata);
  200. thread_progress++;
  201. }
  202. bool LightmapperCPU::_parallel_run(int p_count, const String &p_description, BakeThreadFunc p_thread_func, void *p_userdata, BakeStepFunc p_substep_func) {
  203. bool cancelled = false;
  204. if (p_substep_func) {
  205. cancelled = p_substep_func(0.0f, vformat("%s (%d/%d)", p_description, 0, p_count), nullptr, false);
  206. }
  207. thread_progress = 0;
  208. thread_cancelled = false;
  209. #ifdef NO_THREAD
  210. for (int i = 0; !cancelled && i < p_count; i++) {
  211. (this->*p_thread_func)(i, p_userdata);
  212. float p = float(i) / p_count;
  213. if (p_substep_func) {
  214. cancelled = p_substep_func(p, vformat("%s (%d/%d)", p_description, i + 1, p_count), nullptr, false);
  215. }
  216. }
  217. #else
  218. if (p_count == 0) {
  219. return cancelled;
  220. }
  221. ThreadData td;
  222. td.instance = this;
  223. td.count = p_count;
  224. td.thread_func = p_thread_func;
  225. td.userdata = p_userdata;
  226. Thread runner_thread;
  227. runner_thread.start(_thread_func_callback, &td);
  228. int progress = thread_progress;
  229. while (!cancelled && progress < p_count) {
  230. float p = float(progress) / p_count;
  231. if (p_substep_func) {
  232. cancelled = p_substep_func(p, vformat("%s (%d/%d)", p_description, progress + 1, p_count), nullptr, false);
  233. }
  234. progress = thread_progress;
  235. }
  236. thread_cancelled = cancelled;
  237. runner_thread.wait_to_finish();
  238. #endif
  239. thread_cancelled = false;
  240. return cancelled;
  241. }
  242. void LightmapperCPU::_generate_buffer(uint32_t p_idx, void *p_unused) {
  243. const Size2i &size = mesh_instances[p_idx].size;
  244. int buffer_size = size.x * size.y;
  245. LocalVector<LightmapTexel> &lightmap = scene_lightmaps[p_idx];
  246. LocalVector<int> &lightmap_indices = scene_lightmap_indices[p_idx];
  247. lightmap_indices.resize(buffer_size);
  248. for (unsigned int i = 0; i < lightmap_indices.size(); i++) {
  249. lightmap_indices[i] = -1;
  250. }
  251. MeshData &md = mesh_instances[p_idx].data;
  252. LocalVector<Ref<Image>> albedo_images;
  253. LocalVector<Ref<Image>> emission_images;
  254. for (int surface_id = 0; surface_id < md.albedo.size(); surface_id++) {
  255. albedo_images.push_back(_init_bake_texture(md.albedo[surface_id], albedo_textures, Image::FORMAT_RGBA8));
  256. emission_images.push_back(_init_bake_texture(md.emission[surface_id], emission_textures, Image::FORMAT_RGBH));
  257. }
  258. int surface_id = 0;
  259. int surface_facecount = 0;
  260. const Vector3 *points_ptr = md.points.ptr();
  261. const Vector3 *normals_ptr = md.normal.ptr();
  262. const Vector2 *uvs_ptr = md.uv.empty() ? nullptr : md.uv.ptr();
  263. const Vector2 *uv2s_ptr = md.uv2.ptr();
  264. for (int i = 0; i < md.points.size() / 3; i++) {
  265. Ref<Image> albedo = albedo_images[surface_id];
  266. Ref<Image> emission = emission_images[surface_id];
  267. albedo->lock();
  268. emission->lock();
  269. _plot_triangle(&(uv2s_ptr[i * 3]), &(points_ptr[i * 3]), &(normals_ptr[i * 3]), uvs_ptr ? &(uvs_ptr[i * 3]) : nullptr, albedo, emission, size, lightmap, lightmap_indices);
  270. albedo->unlock();
  271. emission->unlock();
  272. surface_facecount++;
  273. if (surface_facecount == md.surface_facecounts[surface_id]) {
  274. surface_id++;
  275. surface_facecount = 0;
  276. }
  277. }
  278. }
  279. Ref<Image> LightmapperCPU::_init_bake_texture(const MeshData::TextureDef &p_texture_def, const Map<RID, Ref<Image>> &p_tex_cache, Image::Format p_default_format) {
  280. Ref<Image> ret;
  281. if (p_texture_def.tex_rid.is_valid()) {
  282. ret = p_tex_cache[p_texture_def.tex_rid]->duplicate();
  283. ret->lock();
  284. for (int j = 0; j < ret->get_height(); j++) {
  285. for (int i = 0; i < ret->get_width(); i++) {
  286. ret->set_pixel(i, j, ret->get_pixel(i, j) * p_texture_def.mul + p_texture_def.add);
  287. }
  288. }
  289. ret->unlock();
  290. } else {
  291. ret.instance();
  292. ret->create(8, 8, false, p_default_format);
  293. ret->fill(p_texture_def.add * p_texture_def.mul);
  294. }
  295. return ret;
  296. }
  297. Color LightmapperCPU::_bilinear_sample(const Ref<Image> &p_img, const Vector2 &p_uv, bool p_clamp_x, bool p_clamp_y) {
  298. int width = p_img->get_width();
  299. int height = p_img->get_height();
  300. Vector2 uv;
  301. uv.x = p_clamp_x ? p_uv.x : Math::fposmod(p_uv.x, 1.0f);
  302. uv.y = p_clamp_y ? p_uv.y : Math::fposmod(p_uv.y, 1.0f);
  303. float xf = uv.x * width;
  304. float yf = uv.y * height;
  305. int xi = (int)xf;
  306. int yi = (int)yf;
  307. Color texels[4];
  308. for (int i = 0; i < 4; i++) {
  309. int sample_x = xi + i % 2;
  310. int sample_y = yi + i / 2;
  311. sample_x = CLAMP(sample_x, 0, width - 1);
  312. sample_y = CLAMP(sample_y, 0, height - 1);
  313. texels[i] = p_img->get_pixel(sample_x, sample_y);
  314. }
  315. float tx = xf - xi;
  316. float ty = yf - yi;
  317. Color c = Color(0, 0, 0, 0);
  318. for (int i = 0; i < 4; i++) {
  319. c[i] = Math::lerp(Math::lerp(texels[0][i], texels[1][i], tx), Math::lerp(texels[2][i], texels[3][i], tx), ty);
  320. }
  321. return c;
  322. }
  323. Vector3 LightmapperCPU::_fix_sample_position(const Vector3 &p_position, const Vector3 &p_texel_center, const Vector3 &p_normal, const Vector3 &p_tangent, const Vector3 &p_bitangent, const Vector2 &p_texel_size) {
  324. Basis tangent_basis(p_tangent, p_bitangent, p_normal);
  325. tangent_basis.orthonormalize();
  326. Vector2 half_size = p_texel_size / 2.0f;
  327. Vector3 corrected = p_position;
  328. for (int i = -1; i <= 1; i += 1) {
  329. for (int j = -1; j <= 1; j += 1) {
  330. if (i == 0 && j == 0) {
  331. continue;
  332. }
  333. Vector3 offset = Vector3(half_size.x * i, half_size.y * j, 0.0);
  334. Vector3 rotated_offset = tangent_basis.xform_inv(offset);
  335. Vector3 target = p_texel_center + rotated_offset;
  336. Vector3 ray_vector = target - corrected;
  337. Vector3 ray_back_offset = -ray_vector.normalized() * parameters.bias / 2.0;
  338. Vector3 ray_origin = corrected + ray_back_offset;
  339. ray_vector = target - ray_origin;
  340. float ray_length = ray_vector.length();
  341. LightmapRaycaster::Ray ray(ray_origin + p_normal * parameters.bias, ray_vector.normalized(), 0.0f, ray_length + parameters.bias / 2.0);
  342. bool hit = raycaster->intersect(ray);
  343. if (hit) {
  344. ray.normal.normalize();
  345. if (ray.normal.dot(ray_vector.normalized()) > 0.0f) {
  346. corrected = ray_origin + ray.dir * ray.tfar + ray.normal * (parameters.bias * 2.0f);
  347. }
  348. }
  349. }
  350. }
  351. return corrected;
  352. }
  353. void LightmapperCPU::_plot_triangle(const Vector2 *p_vertices, const Vector3 *p_positions, const Vector3 *p_normals, const Vector2 *p_uvs, const Ref<Image> &p_albedo, const Ref<Image> &p_emission, Vector2i p_size, LocalVector<LightmapTexel> &r_lightmap, LocalVector<int> &r_lightmap_indices) {
  354. Vector2 pv0 = p_vertices[0];
  355. Vector2 pv1 = p_vertices[1];
  356. Vector2 pv2 = p_vertices[2];
  357. Vector2 v0 = pv0 * p_size;
  358. Vector2 v1 = pv1 * p_size;
  359. Vector2 v2 = pv2 * p_size;
  360. Vector3 p0 = p_positions[0];
  361. Vector3 p1 = p_positions[1];
  362. Vector3 p2 = p_positions[2];
  363. Vector3 n0 = p_normals[0];
  364. Vector3 n1 = p_normals[1];
  365. Vector3 n2 = p_normals[2];
  366. Vector2 uv0 = p_uvs == nullptr ? Vector2(0.5f, 0.5f) : p_uvs[0];
  367. Vector2 uv1 = p_uvs == nullptr ? Vector2(0.5f, 0.5f) : p_uvs[1];
  368. Vector2 uv2 = p_uvs == nullptr ? Vector2(0.5f, 0.5f) : p_uvs[2];
  369. #define edgeFunction(a, b, c) ((c)[0] - (a)[0]) * ((b)[1] - (a)[1]) - ((c)[1] - (a)[1]) * ((b)[0] - (a)[0])
  370. if (edgeFunction(v0, v1, v2) < 0.0) {
  371. SWAP(pv1, pv2);
  372. SWAP(v1, v2);
  373. SWAP(p1, p2);
  374. SWAP(n1, n2);
  375. SWAP(uv1, uv2);
  376. }
  377. Vector3 edge1 = p1 - p0;
  378. Vector3 edge2 = p2 - p0;
  379. Vector2 uv_edge1 = pv1 - pv0;
  380. Vector2 uv_edge2 = pv2 - pv0;
  381. float r = 1.0f / (uv_edge1.x * uv_edge2.y - uv_edge1.y * uv_edge2.x);
  382. Vector3 tangent = (edge1 * uv_edge2.y - edge2 * uv_edge1.y) * r;
  383. Vector3 bitangent = (edge2 * uv_edge1.x - edge1 * uv_edge2.x) * r;
  384. tangent.normalize();
  385. bitangent.normalize();
  386. // Compute triangle bounding box
  387. Vector2 bbox_min = Vector2(MIN(v0.x, MIN(v1.x, v2.x)), MIN(v0.y, MIN(v1.y, v2.y)));
  388. Vector2 bbox_max = Vector2(MAX(v0.x, MAX(v1.x, v2.x)), MAX(v0.y, MAX(v1.y, v2.y)));
  389. bbox_min = bbox_min.floor();
  390. bbox_max = bbox_max.ceil();
  391. uint32_t min_x = MAX(bbox_min.x - 2, 0);
  392. uint32_t min_y = MAX(bbox_min.y - 2, 0);
  393. uint32_t max_x = MIN(bbox_max.x, p_size.x - 1);
  394. uint32_t max_y = MIN(bbox_max.y, p_size.y - 1);
  395. Vector2 texel_size;
  396. Vector2 centroid = (v0 + v1 + v2) / 3.0f;
  397. Vector3 centroid_pos = (p0 + p1 + p2) / 3.0f;
  398. for (int i = 0; i < 2; i++) {
  399. Vector2 p = centroid;
  400. p[i] += 1;
  401. Vector3 bary = Geometry::barycentric_coordinates_2d(p, v0, v1, v2);
  402. if (bary.length() <= 1.0) {
  403. Vector3 pos = p0 * bary[0] + p1 * bary[1] + p2 * bary[2];
  404. texel_size[i] = centroid_pos.distance_to(pos);
  405. }
  406. }
  407. Vector<Vector2> pixel_polygon;
  408. pixel_polygon.resize(4);
  409. static const Vector2 corners[4] = { Vector2(0, 0), Vector2(0, 1), Vector2(1, 1), Vector2(1, 0) };
  410. Vector<Vector2> triangle_polygon;
  411. triangle_polygon.push_back(v0);
  412. triangle_polygon.push_back(v1);
  413. triangle_polygon.push_back(v2);
  414. for (uint32_t j = min_y; j <= max_y; ++j) {
  415. for (uint32_t i = min_x; i <= max_x; i++) {
  416. int ofs = j * p_size.x + i;
  417. int texel_idx = r_lightmap_indices[ofs];
  418. if (texel_idx >= 0 && r_lightmap[texel_idx].area_coverage >= 0.5f) {
  419. continue;
  420. }
  421. Vector3 barycentric_coords;
  422. float area_coverage = 0.0f;
  423. bool intersected = false;
  424. for (int k = 0; k < 4; k++) {
  425. pixel_polygon.write[k] = Vector2(i, j) + corners[k];
  426. }
  427. const float max_dist = 0.05;
  428. bool v0eqv1 = v0.distance_squared_to(v1) < max_dist;
  429. bool v1eqv2 = v1.distance_squared_to(v2) < max_dist;
  430. bool v2eqv0 = v2.distance_squared_to(v0) < max_dist;
  431. if (v0eqv1 && v1eqv2 && v2eqv0) {
  432. intersected = true;
  433. barycentric_coords = Vector3(1, 0, 0);
  434. } else if (v0eqv1 || v1eqv2 || v2eqv0) {
  435. Vector<Vector2> segment;
  436. segment.resize(2);
  437. if (v0eqv1) {
  438. segment.write[0] = v0;
  439. segment.write[1] = v2;
  440. } else if (v1eqv2) {
  441. segment.write[0] = v1;
  442. segment.write[1] = v0;
  443. } else {
  444. segment.write[0] = v0;
  445. segment.write[1] = v1;
  446. }
  447. Vector<Vector<Vector2>> intersected_segments = Geometry::intersect_polyline_with_polygon_2d(segment, pixel_polygon);
  448. ERR_FAIL_COND_MSG(intersected_segments.size() > 1, "[Lightmapper] Itersecting a segment and a convex polygon should give at most one segment.");
  449. if (!intersected_segments.empty()) {
  450. const Vector<Vector2> &intersected_segment = intersected_segments[0];
  451. ERR_FAIL_COND_MSG(intersected_segment.size() != 2, "[Lightmapper] Itersecting a segment and a convex polygon should give at most one segment.");
  452. Vector2 sample_pos = (intersected_segment[0] + intersected_segment[1]) / 2.0f;
  453. float u = (segment[0].distance_to(sample_pos)) / (segment[0].distance_to(segment[1]));
  454. float v = (1.0f - u) / 2.0f;
  455. intersected = true;
  456. if (v0eqv1) {
  457. barycentric_coords = Vector3(v, v, u);
  458. } else if (v1eqv2) {
  459. barycentric_coords = Vector3(u, v, v);
  460. } else {
  461. barycentric_coords = Vector3(v, u, v);
  462. }
  463. }
  464. } else if (edgeFunction(v0, v1, v2) < 0.005) {
  465. Vector2 direction = v0 - v1;
  466. Vector2 perpendicular = Vector2(direction.y, -direction.x);
  467. Vector<Vector2> line;
  468. int middle_vertex;
  469. if (SGN(edgeFunction(v0, v0 + perpendicular, v1)) != SGN(edgeFunction(v0, v0 + perpendicular, v2))) {
  470. line.push_back(v1);
  471. line.push_back(v2);
  472. middle_vertex = 0;
  473. } else if (SGN(edgeFunction(v1, v1 + perpendicular, v0)) != SGN(edgeFunction(v1, v1 + perpendicular, v2))) {
  474. line.push_back(v0);
  475. line.push_back(v2);
  476. middle_vertex = 1;
  477. } else {
  478. line.push_back(v0);
  479. line.push_back(v1);
  480. middle_vertex = 2;
  481. }
  482. Vector<Vector<Vector2>> intersected_lines = Geometry::intersect_polyline_with_polygon_2d(line, pixel_polygon);
  483. ERR_FAIL_COND_MSG(intersected_lines.size() > 1, "[Lightmapper] Itersecting a line and a convex polygon should give at most one line.");
  484. if (!intersected_lines.empty()) {
  485. intersected = true;
  486. const Vector<Vector2> &intersected_line = intersected_lines[0];
  487. Vector2 sample_pos = (intersected_line[0] + intersected_line[1]) / 2.0f;
  488. float line_length = line[0].distance_to(line[1]);
  489. float norm = line[0].distance_to(sample_pos) / line_length;
  490. if (middle_vertex == 0) {
  491. barycentric_coords = Vector3(0.0f, 1.0f - norm, norm);
  492. } else if (middle_vertex == 1) {
  493. barycentric_coords = Vector3(1.0f - norm, 0.0f, norm);
  494. } else {
  495. barycentric_coords = Vector3(1.0f - norm, norm, 0.0f);
  496. }
  497. }
  498. } else {
  499. Vector<Vector<Vector2>> intersected_polygons = Geometry::intersect_polygons_2d(pixel_polygon, triangle_polygon);
  500. ERR_FAIL_COND_MSG(intersected_polygons.size() > 1, "[Lightmapper] Itersecting two convex polygons should give at most one polygon.");
  501. if (!intersected_polygons.empty()) {
  502. const Vector<Vector2> &intersected_polygon = intersected_polygons[0];
  503. // do centroid sampling
  504. Vector2 sample_pos = intersected_polygon[0];
  505. Vector2 area_center = Vector2(i, j) + Vector2(0.5f, 0.5f);
  506. float intersected_area = (intersected_polygon[0] - area_center).cross(intersected_polygon[intersected_polygon.size() - 1] - area_center);
  507. for (int k = 1; k < intersected_polygon.size(); k++) {
  508. sample_pos += intersected_polygon[k];
  509. intersected_area += (intersected_polygon[k] - area_center).cross(intersected_polygon[k - 1] - area_center);
  510. }
  511. if (intersected_area != 0.0f) {
  512. sample_pos /= intersected_polygon.size();
  513. barycentric_coords = Geometry::barycentric_coordinates_2d(sample_pos, v0, v1, v2);
  514. intersected = true;
  515. area_coverage = ABS(intersected_area) / 2.0f;
  516. }
  517. }
  518. if (!intersected) {
  519. for (int k = 0; k < 4; ++k) {
  520. for (int l = 0; l < 3; ++l) {
  521. Vector2 intersection_point;
  522. if (Geometry::segment_intersects_segment_2d(pixel_polygon[k], pixel_polygon[(k + 1) % 4], triangle_polygon[l], triangle_polygon[(l + 1) % 3], &intersection_point)) {
  523. intersected = true;
  524. barycentric_coords = Geometry::barycentric_coordinates_2d(intersection_point, v0, v1, v2);
  525. break;
  526. }
  527. }
  528. if (intersected) {
  529. break;
  530. }
  531. }
  532. }
  533. }
  534. if (texel_idx >= 0 && area_coverage < r_lightmap[texel_idx].area_coverage) {
  535. continue; // A previous triangle gives better pixel coverage
  536. }
  537. Vector2 pixel = Vector2(i, j);
  538. if (!intersected && v0.floor() == pixel) {
  539. intersected = true;
  540. barycentric_coords = Vector3(1, 0, 0);
  541. }
  542. if (!intersected && v1.floor() == pixel) {
  543. intersected = true;
  544. barycentric_coords = Vector3(0, 1, 0);
  545. }
  546. if (!intersected && v2.floor() == pixel) {
  547. intersected = true;
  548. barycentric_coords = Vector3(0, 0, 1);
  549. }
  550. if (!intersected) {
  551. continue;
  552. }
  553. if (Math::is_nan(barycentric_coords.x) || Math::is_nan(barycentric_coords.y) || Math::is_nan(barycentric_coords.z)) {
  554. continue;
  555. }
  556. if (Math::is_inf(barycentric_coords.x) || Math::is_inf(barycentric_coords.y) || Math::is_inf(barycentric_coords.z)) {
  557. continue;
  558. }
  559. r_lightmap_indices[ofs] = r_lightmap.size();
  560. Vector3 pos = p0 * barycentric_coords[0] + p1 * barycentric_coords[1] + p2 * barycentric_coords[2];
  561. Vector3 normal = n0 * barycentric_coords[0] + n1 * barycentric_coords[1] + n2 * barycentric_coords[2];
  562. Vector2 uv = uv0 * barycentric_coords[0] + uv1 * barycentric_coords[1] + uv2 * barycentric_coords[2];
  563. Color c = _bilinear_sample(p_albedo, uv);
  564. Color e = _bilinear_sample(p_emission, uv);
  565. Vector2 texel_center = Vector2(i, j) + Vector2(0.5f, 0.5f);
  566. Vector3 texel_center_bary = Geometry::barycentric_coordinates_2d(texel_center, v0, v1, v2);
  567. if (texel_center_bary.length_squared() <= 1.3 && !Math::is_nan(texel_center_bary.x) && !Math::is_nan(texel_center_bary.y) && !Math::is_nan(texel_center_bary.z) && !Math::is_inf(texel_center_bary.x) && !Math::is_inf(texel_center_bary.y) && !Math::is_inf(texel_center_bary.z)) {
  568. Vector3 texel_center_pos = p0 * texel_center_bary[0] + p1 * texel_center_bary[1] + p2 * texel_center_bary[2];
  569. pos = _fix_sample_position(pos, texel_center_pos, normal, tangent, bitangent, texel_size);
  570. }
  571. LightmapTexel texel;
  572. texel.normal = normal.normalized();
  573. texel.pos = pos;
  574. texel.albedo = Vector3(c.r, c.g, c.b);
  575. texel.alpha = c.a;
  576. texel.emission = Vector3(e.r, e.g, e.b);
  577. texel.area_coverage = area_coverage;
  578. r_lightmap.push_back(texel);
  579. }
  580. }
  581. }
  582. _ALWAYS_INLINE_ float uniform_rand() {
  583. /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
  584. static thread_local uint32_t state = Math::rand();
  585. state ^= state << 13;
  586. state ^= state >> 17;
  587. state ^= state << 5;
  588. /* implicit conversion from 'unsigned int' to 'float' changes value from 4294967295 to 4294967296 */
  589. return float(state) / float(UINT32_MAX);
  590. }
  591. void LightmapperCPU::_compute_direct_light(uint32_t p_idx, void *r_lightmap) {
  592. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  593. for (unsigned int i = 0; i < lights.size(); ++i) {
  594. const Light &light = lights[i];
  595. Vector3 normal = lightmap[p_idx].normal;
  596. Vector3 position = lightmap[p_idx].pos;
  597. Color c = light.color;
  598. Vector3 light_energy = Vector3(c.r, c.g, c.b) * light.energy;
  599. Vector3 light_to_point = light.direction;
  600. if (light.type == LIGHT_TYPE_OMNI || light.type == LIGHT_TYPE_SPOT) {
  601. light_to_point = (position - light.position).normalized();
  602. }
  603. if (normal.dot(light_to_point) >= 0.0) {
  604. continue;
  605. }
  606. float dist;
  607. float attenuation;
  608. float soft_shadowing_disk_size;
  609. if (light.type == LIGHT_TYPE_OMNI || light.type == LIGHT_TYPE_SPOT) {
  610. dist = position.distance_to(light.position);
  611. if (dist > light.range) {
  612. continue;
  613. }
  614. soft_shadowing_disk_size = light.size / dist;
  615. if (light.type == LIGHT_TYPE_OMNI) {
  616. attenuation = powf(1.0 - dist / light.range, light.attenuation);
  617. } else /* (light.type == LIGHT_TYPE_SPOT) */ {
  618. float angle = Math::acos(light.direction.dot(light_to_point));
  619. if (angle > light.spot_angle) {
  620. continue;
  621. }
  622. float normalized_dist = dist * (1.0f / MAX(0.001f, light.range));
  623. float norm_light_attenuation = Math::pow(MAX(1.0f - normalized_dist, 0.001f), light.attenuation);
  624. float spot_cutoff = Math::cos(light.spot_angle);
  625. float scos = MAX(light_to_point.dot(light.direction), spot_cutoff);
  626. float spot_rim = (1.0f - scos) / (1.0f - spot_cutoff);
  627. attenuation = norm_light_attenuation * (1.0f - pow(MAX(spot_rim, 0.001f), light.spot_attenuation));
  628. }
  629. } else /*if (light.type == LIGHT_TYPE_DIRECTIONAL)*/ {
  630. dist = INFINITY;
  631. attenuation = 1.0f;
  632. soft_shadowing_disk_size = light.size;
  633. }
  634. float penumbra = 0.0f;
  635. if (light.size > 0.0) {
  636. Vector3 light_to_point_tan;
  637. Vector3 light_to_point_bitan;
  638. if (light.type == LIGHT_TYPE_OMNI || light.type == LIGHT_TYPE_SPOT) {
  639. light_to_point = (position - light.position).normalized();
  640. Vector3 aux = light_to_point.y < 0.777 ? Vector3(0, 1, 0) : Vector3(1, 0, 0);
  641. light_to_point_tan = light_to_point.cross(aux).normalized();
  642. light_to_point_bitan = light_to_point.cross(light_to_point_tan).normalized();
  643. } else /*if (light.type == LIGHT_TYPE_DIRECTIONAL)*/ {
  644. Vector3 aux = light_to_point.y < 0.777 ? Vector3(0, 1, 0) : Vector3(1, 0, 0);
  645. light_to_point_tan = light_to_point.cross(aux).normalized();
  646. light_to_point_bitan = light_to_point.cross(light_to_point_tan).normalized();
  647. }
  648. const static int shadowing_rays_check_penumbra_denom = 2;
  649. int shadowing_ray_count = parameters.samples;
  650. int hits = 0;
  651. Vector3 light_disk_to_point = light_to_point;
  652. for (int j = 0; j < shadowing_ray_count; j++) {
  653. // Optimization:
  654. // Once already casted an important proportion of rays, if all are hits or misses,
  655. // assume we're not in the penumbra so we can infer the rest would have the same result
  656. if (j == shadowing_ray_count / shadowing_rays_check_penumbra_denom) {
  657. if (hits == j) {
  658. // Assume totally lit
  659. hits = shadowing_ray_count;
  660. break;
  661. } else if (hits == 0) {
  662. // Assume totally dark
  663. hits = 0;
  664. break;
  665. }
  666. }
  667. float r = uniform_rand();
  668. float a = uniform_rand() * Math_TAU;
  669. Vector2 disk_sample = (r * Vector2(Math::cos(a), Math::sin(a))) * soft_shadowing_disk_size;
  670. light_disk_to_point = (light_to_point + disk_sample.x * light_to_point_tan + disk_sample.y * light_to_point_bitan).normalized();
  671. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_disk_to_point, parameters.bias, dist);
  672. if (raycaster->intersect(ray)) {
  673. continue;
  674. }
  675. hits++;
  676. }
  677. penumbra = (float)hits / shadowing_ray_count;
  678. } else {
  679. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_to_point, parameters.bias, dist);
  680. if (!raycaster->intersect(ray)) {
  681. penumbra = 1.0f;
  682. }
  683. }
  684. Vector3 final_energy = attenuation * penumbra * light_energy * MAX(0, normal.dot(-light_to_point));
  685. lightmap[p_idx].direct_light += final_energy * light.indirect_multiplier;
  686. if (light.bake_direct) {
  687. lightmap[p_idx].output_light += final_energy;
  688. }
  689. }
  690. }
  691. void LightmapperCPU::_compute_indirect_light(uint32_t p_idx, void *r_lightmap) {
  692. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  693. LightmapTexel &texel = lightmap[p_idx];
  694. Vector3 accum;
  695. const Vector3 const_forward = Vector3(0, 0, 1);
  696. const Vector3 const_up = Vector3(0, 1, 0);
  697. for (int i = 0; i < parameters.samples; i++) {
  698. Vector3 color;
  699. Vector3 throughput = Vector3(1.0f, 1.0f, 1.0f);
  700. Vector3 position = texel.pos;
  701. Vector3 normal = texel.normal;
  702. Vector3 direction;
  703. for (int depth = 0; depth < parameters.bounces; depth++) {
  704. Vector3 tangent = const_forward.cross(normal);
  705. if (unlikely(tangent.length_squared() < 0.005f)) {
  706. tangent = const_up.cross(normal);
  707. }
  708. tangent.normalize();
  709. Vector3 bitangent = tangent.cross(normal);
  710. bitangent.normalize();
  711. Basis normal_xform = Basis(tangent, bitangent, normal);
  712. normal_xform.transpose();
  713. float u1 = uniform_rand();
  714. float u2 = uniform_rand();
  715. float radius = Math::sqrt(u1);
  716. float theta = Math_TAU * u2;
  717. Vector3 axis = Vector3(radius * Math::cos(theta), radius * Math::sin(theta), Math::sqrt(MAX(0.0f, 1.0f - u1)));
  718. direction = normal_xform.xform(axis);
  719. // We can skip multiplying throughput by cos(theta) because de sampling PDF is also cos(theta) and they cancel each other
  720. //float pdf = normal.dot(direction);
  721. //throughput *= normal.dot(direction)/pdf;
  722. LightmapRaycaster::Ray ray(position, direction, parameters.bias);
  723. bool hit = raycaster->intersect(ray);
  724. if (!hit) {
  725. if (parameters.environment_panorama.is_valid()) {
  726. direction = parameters.environment_transform.xform_inv(direction);
  727. Vector2 st = Vector2(Math::atan2(direction.z, direction.x), Math::acos(direction.y));
  728. if (Math::is_nan(st.y)) {
  729. st.y = direction.y > 0.0 ? 0.0 : Math_PI;
  730. }
  731. st.x += Math_PI;
  732. st /= Vector2(Math_TAU, Math_PI);
  733. st.x = Math::fmod(st.x + 0.75, 1.0);
  734. Color c = _bilinear_sample(parameters.environment_panorama, st, false, true);
  735. color += throughput * Vector3(c.r, c.g, c.b) * c.a;
  736. }
  737. break;
  738. }
  739. unsigned int hit_mesh_id = ray.geomID;
  740. const Vector2i &size = mesh_instances[hit_mesh_id].size;
  741. int x = CLAMP(ray.u * size.x, 0, size.x - 1);
  742. int y = CLAMP(ray.v * size.y, 0, size.y - 1);
  743. const int idx = scene_lightmap_indices[hit_mesh_id][y * size.x + x];
  744. if (idx < 0) {
  745. break;
  746. }
  747. const LightmapTexel &sample = scene_lightmaps[hit_mesh_id][idx];
  748. if (sample.normal.dot(ray.dir) > 0.0 && !no_shadow_meshes.has(hit_mesh_id)) {
  749. // We hit a back-face
  750. break;
  751. }
  752. color += throughput * sample.emission;
  753. throughput *= sample.albedo;
  754. color += throughput * sample.direct_light * parameters.bounce_indirect_energy;
  755. // Russian Roulette
  756. // https://computergraphics.stackexchange.com/questions/2316/is-russian-roulette-really-the-answer
  757. const float p = throughput[throughput.max_axis()];
  758. if (uniform_rand() > p) {
  759. break;
  760. }
  761. throughput *= 1.0f / p;
  762. position = sample.pos;
  763. normal = sample.normal;
  764. }
  765. accum += color;
  766. }
  767. texel.output_light += accum / parameters.samples;
  768. }
  769. void LightmapperCPU::_post_process(uint32_t p_idx, void *r_output) {
  770. const MeshInstance &mesh = mesh_instances[p_idx];
  771. if (!mesh.generate_lightmap) {
  772. return;
  773. }
  774. LocalVector<int> &indices = scene_lightmap_indices[p_idx];
  775. LocalVector<LightmapTexel> &lightmap = scene_lightmaps[p_idx];
  776. Vector3 *output = ((LocalVector<Vector3> *)r_output)[p_idx].ptr();
  777. Vector2i size = mesh.size;
  778. // Blit texels to buffer
  779. const int margin = 4;
  780. for (int i = 0; i < size.y; i++) {
  781. for (int j = 0; j < size.x; j++) {
  782. int idx = indices[i * size.x + j];
  783. if (idx >= 0) {
  784. output[i * size.x + j] = lightmap[idx].output_light;
  785. continue; // filled, skip
  786. }
  787. int closest_idx = -1;
  788. float closest_dist = 1e20;
  789. for (int y = i - margin; y <= i + margin; y++) {
  790. for (int x = j - margin; x <= j + margin; x++) {
  791. if (x == j && y == i) {
  792. continue;
  793. }
  794. if (x < 0 || x >= size.x) {
  795. continue;
  796. }
  797. if (y < 0 || y >= size.y) {
  798. continue;
  799. }
  800. int cell_idx = indices[y * size.x + x];
  801. if (cell_idx < 0) {
  802. continue; //also ensures that blitted stuff is not reused
  803. }
  804. float dist = Vector2(i - y, j - x).length_squared();
  805. if (dist < closest_dist) {
  806. closest_dist = dist;
  807. closest_idx = cell_idx;
  808. }
  809. }
  810. }
  811. if (closest_idx != -1) {
  812. output[i * size.x + j] = lightmap[closest_idx].output_light;
  813. }
  814. }
  815. }
  816. lightmap.clear();
  817. LocalVector<UVSeam> seams;
  818. _compute_seams(mesh, seams);
  819. _fix_seams(seams, output, size);
  820. _dilate_lightmap(output, indices, size, margin);
  821. if (parameters.use_denoiser) {
  822. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  823. if (denoiser.is_valid()) {
  824. int data_size = size.x * size.y * sizeof(Vector3);
  825. Ref<Image> current_image;
  826. current_image.instance();
  827. {
  828. PoolByteArray data;
  829. data.resize(data_size);
  830. PoolByteArray::Write w = data.write();
  831. memcpy(w.ptr(), output, data_size);
  832. current_image->create(size.x, size.y, false, Image::FORMAT_RGBF, data);
  833. }
  834. Ref<Image> denoised_image = denoiser->denoise_image(current_image);
  835. PoolByteArray denoised_data = denoised_image->get_data();
  836. denoised_image.unref();
  837. PoolByteArray::Read r = denoised_data.read();
  838. memcpy(output, r.ptr(), data_size);
  839. }
  840. }
  841. _dilate_lightmap(output, indices, size, margin);
  842. _fix_seams(seams, output, size);
  843. _dilate_lightmap(output, indices, size, margin);
  844. indices.clear();
  845. }
  846. void LightmapperCPU::_compute_seams(const MeshInstance &p_mesh, LocalVector<UVSeam> &r_seams) {
  847. float max_uv_distance = 1.0f / MAX(p_mesh.size.x, p_mesh.size.y);
  848. max_uv_distance *= max_uv_distance; // We use distance_to_squared(), so we need to square the max distance as well
  849. float max_pos_distance = 0.00025f;
  850. float max_normal_distance = 0.05f;
  851. const Vector<Vector3> &points = p_mesh.data.points;
  852. const Vector<Vector2> &uv2s = p_mesh.data.uv2;
  853. const Vector<Vector3> &normals = p_mesh.data.normal;
  854. LocalVector<SeamEdge> edges;
  855. edges.resize(points.size()); // One edge per vertex
  856. for (int i = 0; i < points.size(); i += 3) {
  857. Vector3 triangle_vtxs[3] = { points[i + 0], points[i + 1], points[i + 2] };
  858. Vector2 triangle_uvs[3] = { uv2s[i + 0], uv2s[i + 1], uv2s[i + 2] };
  859. Vector3 triangle_normals[3] = { normals[i + 0], normals[i + 1], normals[i + 2] };
  860. for (int k = 0; k < 3; k++) {
  861. int idx[2];
  862. idx[0] = k;
  863. idx[1] = (k + 1) % 3;
  864. if (triangle_vtxs[idx[1]] < triangle_vtxs[idx[0]]) {
  865. SWAP(idx[0], idx[1]);
  866. }
  867. SeamEdge e;
  868. for (int l = 0; l < 2; ++l) {
  869. e.pos[l] = triangle_vtxs[idx[l]];
  870. e.uv[l] = triangle_uvs[idx[l]];
  871. e.normal[l] = triangle_normals[idx[l]];
  872. }
  873. edges[i + k] = e;
  874. }
  875. }
  876. edges.sort();
  877. for (unsigned int j = 0; j < edges.size(); j++) {
  878. const SeamEdge &edge0 = edges[j];
  879. if (edge0.uv[0].distance_squared_to(edge0.uv[1]) < 0.001) {
  880. continue;
  881. }
  882. if (edge0.pos[0].distance_squared_to(edge0.pos[1]) < 0.001) {
  883. continue;
  884. }
  885. for (unsigned int k = j + 1; k < edges.size() && edges[k].pos[0].x < (edge0.pos[0].x + max_pos_distance * 1.1f); k++) {
  886. const SeamEdge &edge1 = edges[k];
  887. if (edge1.uv[0].distance_squared_to(edge1.uv[1]) < 0.001) {
  888. continue;
  889. }
  890. if (edge1.pos[0].distance_squared_to(edge1.pos[1]) < 0.001) {
  891. continue;
  892. }
  893. if (edge0.uv[0].distance_squared_to(edge1.uv[0]) < max_uv_distance && edge0.uv[1].distance_squared_to(edge1.uv[1]) < max_uv_distance) {
  894. continue;
  895. }
  896. if (edge0.pos[0].distance_squared_to(edge1.pos[0]) > max_pos_distance || edge0.pos[1].distance_squared_to(edge1.pos[1]) > max_pos_distance) {
  897. continue;
  898. }
  899. if (edge0.normal[0].distance_squared_to(edge1.normal[0]) > max_normal_distance || edge0.normal[1].distance_squared_to(edge1.normal[1]) > max_normal_distance) {
  900. continue;
  901. }
  902. UVSeam s;
  903. s.edge0[0] = edge0.uv[0];
  904. s.edge0[1] = edge0.uv[1];
  905. s.edge1[0] = edge1.uv[0];
  906. s.edge1[1] = edge1.uv[1];
  907. r_seams.push_back(s);
  908. }
  909. }
  910. }
  911. void LightmapperCPU::_fix_seams(const LocalVector<UVSeam> &p_seams, Vector3 *r_lightmap, Vector2i p_size) {
  912. LocalVector<Vector3> extra_buffer;
  913. extra_buffer.resize(p_size.x * p_size.y);
  914. memcpy(extra_buffer.ptr(), r_lightmap, p_size.x * p_size.y * sizeof(Vector3));
  915. Vector3 *read_ptr = extra_buffer.ptr();
  916. Vector3 *write_ptr = r_lightmap;
  917. for (int i = 0; i < 5; i++) {
  918. for (unsigned int j = 0; j < p_seams.size(); j++) {
  919. _fix_seam(p_seams[j].edge0[0], p_seams[j].edge0[1], p_seams[j].edge1[0], p_seams[j].edge1[1], read_ptr, write_ptr, p_size);
  920. _fix_seam(p_seams[j].edge1[0], p_seams[j].edge1[1], p_seams[j].edge0[0], p_seams[j].edge0[1], read_ptr, write_ptr, p_size);
  921. }
  922. memcpy(read_ptr, write_ptr, p_size.x * p_size.y * sizeof(Vector3));
  923. }
  924. }
  925. void LightmapperCPU::_fix_seam(const Vector2 &p_pos0, const Vector2 &p_pos1, const Vector2 &p_uv0, const Vector2 &p_uv1, const Vector3 *p_read_buffer, Vector3 *r_write_buffer, const Vector2i &p_size) {
  926. Vector2 line[2];
  927. line[0] = p_pos0 * p_size;
  928. line[1] = p_pos1 * p_size;
  929. const Vector2i start_pixel = line[0].floor();
  930. const Vector2i end_pixel = line[1].floor();
  931. Vector2 seam_dir = (line[1] - line[0]).normalized();
  932. Vector2 t_delta = Vector2(1.0f / Math::abs(seam_dir.x), 1.0f / Math::abs(seam_dir.y));
  933. Vector2i step = Vector2(seam_dir.x > 0 ? 1 : (seam_dir.x < 0 ? -1 : 0), seam_dir.y > 0 ? 1 : (seam_dir.y < 0 ? -1 : 0));
  934. Vector2 t_next = Vector2(Math::fmod(line[0].x, 1.0f), Math::fmod(line[0].y, 1.0f));
  935. if (step.x == 1) {
  936. t_next.x = 1.0f - t_next.x;
  937. }
  938. if (step.y == 1) {
  939. t_next.y = 1.0f - t_next.y;
  940. }
  941. t_next.x /= Math::abs(seam_dir.x);
  942. t_next.y /= Math::abs(seam_dir.y);
  943. if (Math::is_nan(t_next.x)) {
  944. t_next.x = 1e20f;
  945. }
  946. if (Math::is_nan(t_next.y)) {
  947. t_next.y = 1e20f;
  948. }
  949. Vector2i pixel = start_pixel;
  950. Vector2 start_p = start_pixel;
  951. float line_length = line[0].distance_to(line[1]);
  952. if (line_length == 0.0f) {
  953. return;
  954. }
  955. while (start_p.distance_to(pixel) < line_length + 1.0f) {
  956. Vector2 current_point = Vector2(pixel) + Vector2(0.5f, 0.5f);
  957. current_point = Geometry::get_closest_point_to_segment_2d(current_point, line);
  958. float t = line[0].distance_to(current_point) / line_length;
  959. Vector2 current_uv = p_uv0 * (1.0 - t) + p_uv1 * t;
  960. Vector2i sampled_point = (current_uv * p_size).floor();
  961. Vector3 current_color = r_write_buffer[pixel.y * p_size.x + pixel.x];
  962. Vector3 sampled_color = p_read_buffer[sampled_point.y * p_size.x + sampled_point.x];
  963. r_write_buffer[pixel.y * p_size.x + pixel.x] = current_color * 0.6f + sampled_color * 0.4f;
  964. if (pixel == end_pixel) {
  965. break;
  966. }
  967. if (t_next.x < t_next.y) {
  968. pixel.x += step.x;
  969. t_next.x += t_delta.x;
  970. } else {
  971. pixel.y += step.y;
  972. t_next.y += t_delta.y;
  973. }
  974. }
  975. }
  976. void LightmapperCPU::_dilate_lightmap(Vector3 *r_lightmap, const LocalVector<int> p_indices, Vector2i p_size, int margin) {
  977. for (int i = 0; i < p_size.y; i++) {
  978. for (int j = 0; j < p_size.x; j++) {
  979. int idx = p_indices[i * p_size.x + j];
  980. if (idx >= 0) {
  981. continue; //filled, skip
  982. }
  983. Vector2i closest;
  984. float closest_dist = 1e20;
  985. for (int y = i - margin; y <= i + margin; y++) {
  986. for (int x = j - margin; x <= j + margin; x++) {
  987. if (x == j && y == i) {
  988. continue;
  989. }
  990. if (x < 0 || x >= p_size.x) {
  991. continue;
  992. }
  993. if (y < 0 || y >= p_size.y) {
  994. continue;
  995. }
  996. int cell_idx = p_indices[y * p_size.x + x];
  997. if (cell_idx < 0) {
  998. continue; //also ensures that blitted stuff is not reused
  999. }
  1000. float dist = Vector2(i - y, j - x).length_squared();
  1001. if (dist < closest_dist) {
  1002. closest_dist = dist;
  1003. closest = Vector2(x, y);
  1004. }
  1005. }
  1006. }
  1007. if (closest_dist < 1e20) {
  1008. r_lightmap[i * p_size.x + j] = r_lightmap[closest.y * p_size.x + closest.x];
  1009. }
  1010. }
  1011. }
  1012. }
  1013. void LightmapperCPU::_blit_lightmap(const Vector<Vector3> &p_src, const Vector2i &p_size, Ref<Image> &p_dst, int p_x, int p_y, bool p_with_padding) {
  1014. int padding = p_with_padding ? 1 : 0;
  1015. ERR_FAIL_COND(p_x < padding || p_y < padding);
  1016. ERR_FAIL_COND(p_x + p_size.x > p_dst->get_width() - padding);
  1017. ERR_FAIL_COND(p_y + p_size.y > p_dst->get_height() - padding);
  1018. p_dst->lock();
  1019. for (int y = 0; y < p_size.y; y++) {
  1020. const Vector3 *__restrict src = p_src.ptr() + y * p_size.x;
  1021. for (int x = 0; x < p_size.x; x++) {
  1022. p_dst->set_pixel(p_x + x, p_y + y, Color(src->x, src->y, src->z));
  1023. src++;
  1024. }
  1025. }
  1026. if (p_with_padding) {
  1027. for (int y = -1; y < p_size.y + 1; y++) {
  1028. int yy = CLAMP(y, 0, p_size.y - 1);
  1029. int idx_left = yy * p_size.x;
  1030. int idx_right = idx_left + p_size.x - 1;
  1031. p_dst->set_pixel(p_x - 1, p_y + y, Color(p_src[idx_left].x, p_src[idx_left].y, p_src[idx_left].z));
  1032. p_dst->set_pixel(p_x + p_size.x, p_y + y, Color(p_src[idx_right].x, p_src[idx_right].y, p_src[idx_right].z));
  1033. }
  1034. for (int x = -1; x < p_size.x + 1; x++) {
  1035. int xx = CLAMP(x, 0, p_size.x - 1);
  1036. int idx_top = xx;
  1037. int idx_bot = idx_top + (p_size.y - 1) * p_size.x;
  1038. p_dst->set_pixel(p_x + x, p_y - 1, Color(p_src[idx_top].x, p_src[idx_top].y, p_src[idx_top].z));
  1039. p_dst->set_pixel(p_x + x, p_y + p_size.y, Color(p_src[idx_bot].x, p_src[idx_bot].y, p_src[idx_bot].z));
  1040. }
  1041. }
  1042. p_dst->unlock();
  1043. }
  1044. LightmapperCPU::BakeError LightmapperCPU::bake(BakeQuality p_quality, bool p_use_denoiser, int p_bounces, float p_bounce_indirect_energy, float p_bias, bool p_generate_atlas, int p_max_texture_size, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata, BakeStepFunc p_substep_function) {
  1045. if (p_step_function) {
  1046. bool cancelled = p_step_function(0.0, TTR("Begin Bake"), p_bake_userdata, true);
  1047. if (cancelled) {
  1048. return BAKE_ERROR_USER_ABORTED;
  1049. }
  1050. }
  1051. raycaster = LightmapRaycaster::create();
  1052. ERR_FAIL_COND_V(raycaster.is_null(), BAKE_ERROR_NO_RAYCASTER);
  1053. // Collect parameters
  1054. parameters.use_denoiser = p_use_denoiser;
  1055. parameters.bias = p_bias;
  1056. parameters.bounces = p_bounces;
  1057. parameters.bounce_indirect_energy = p_bounce_indirect_energy;
  1058. parameters.environment_transform = p_environment_transform;
  1059. parameters.environment_panorama = p_environment_panorama;
  1060. switch (p_quality) {
  1061. case BAKE_QUALITY_LOW: {
  1062. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/low_quality_ray_count");
  1063. } break;
  1064. case BAKE_QUALITY_MEDIUM: {
  1065. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/medium_quality_ray_count");
  1066. } break;
  1067. case BAKE_QUALITY_HIGH: {
  1068. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/high_quality_ray_count");
  1069. } break;
  1070. case BAKE_QUALITY_ULTRA: {
  1071. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/ultra_quality_ray_count");
  1072. } break;
  1073. }
  1074. bake_textures.clear();
  1075. if (p_step_function) {
  1076. bool cancelled = p_step_function(0.1, TTR("Preparing data structures"), p_bake_userdata, true);
  1077. if (cancelled) {
  1078. return BAKE_ERROR_USER_ABORTED;
  1079. }
  1080. }
  1081. bool has_baked_mesh = false;
  1082. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1083. if (mesh_instances[i].generate_lightmap) {
  1084. has_baked_mesh = true;
  1085. }
  1086. raycaster->add_mesh(mesh_instances[i].data.points, mesh_instances[i].data.normal, mesh_instances[i].data.uv2, i);
  1087. }
  1088. if (!has_baked_mesh) {
  1089. return BAKE_ERROR_NO_MESHES;
  1090. }
  1091. raycaster->commit();
  1092. scene_lightmaps.resize(mesh_instances.size());
  1093. scene_lightmap_indices.resize(mesh_instances.size());
  1094. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1095. if (!mesh_instances[i].cast_shadows) {
  1096. no_shadow_meshes.insert(i);
  1097. }
  1098. }
  1099. raycaster->set_mesh_filter(no_shadow_meshes);
  1100. Vector2i atlas_size = Vector2i(-1, -1);
  1101. int atlas_slices = -1;
  1102. if (p_generate_atlas) {
  1103. Error err = _layout_atlas(p_max_texture_size, &atlas_size, &atlas_slices);
  1104. if (err != OK) {
  1105. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  1106. }
  1107. }
  1108. if (p_step_function) {
  1109. bool cancelled = p_step_function(0.2, TTR("Generate buffers"), p_bake_userdata, true);
  1110. if (cancelled) {
  1111. return BAKE_ERROR_USER_ABORTED;
  1112. }
  1113. }
  1114. if (_parallel_run(mesh_instances.size(), "Rasterizing meshes", &LightmapperCPU::_generate_buffer, nullptr, p_substep_function)) {
  1115. return BAKE_ERROR_USER_ABORTED;
  1116. }
  1117. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1118. const Size2i &size = mesh_instances[i].size;
  1119. bool has_alpha = false;
  1120. PoolVector<uint8_t> alpha_data;
  1121. alpha_data.resize(size.x * size.y);
  1122. {
  1123. PoolVector<uint8_t>::Write w = alpha_data.write();
  1124. for (unsigned int j = 0; j < scene_lightmap_indices[i].size(); ++j) {
  1125. int idx = scene_lightmap_indices[i][j];
  1126. uint8_t alpha = 0;
  1127. if (idx >= 0) {
  1128. alpha = CLAMP(scene_lightmaps[i][idx].alpha * 255, 0, 255);
  1129. if (alpha < 255) {
  1130. has_alpha = true;
  1131. }
  1132. }
  1133. w[j] = alpha;
  1134. }
  1135. }
  1136. if (has_alpha) {
  1137. Ref<Image> alpha_texture;
  1138. alpha_texture.instance();
  1139. alpha_texture->create(size.x, size.y, false, Image::FORMAT_L8, alpha_data);
  1140. raycaster->set_mesh_alpha_texture(alpha_texture, i);
  1141. }
  1142. }
  1143. albedo_textures.clear();
  1144. emission_textures.clear();
  1145. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1146. if (p_step_function) {
  1147. float p = float(i) / mesh_instances.size();
  1148. bool cancelled = p_step_function(0.2 + p * 0.2, vformat("%s (%d/%d)", TTR("Direct lighting"), i, mesh_instances.size()), p_bake_userdata, false);
  1149. if (cancelled) {
  1150. return BAKE_ERROR_USER_ABORTED;
  1151. }
  1152. }
  1153. if (_parallel_run(scene_lightmaps[i].size(), "Computing direct light", &LightmapperCPU::_compute_direct_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1154. return BAKE_ERROR_USER_ABORTED;
  1155. }
  1156. }
  1157. raycaster->clear_mesh_filter();
  1158. int n_lit_meshes = 0;
  1159. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1160. if (mesh_instances[i].generate_lightmap) {
  1161. n_lit_meshes++;
  1162. }
  1163. }
  1164. if (parameters.environment_panorama.is_valid()) {
  1165. parameters.environment_panorama->lock();
  1166. }
  1167. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1168. if (!mesh_instances[i].generate_lightmap) {
  1169. continue;
  1170. }
  1171. if (p_step_function) {
  1172. float p = float(i) / n_lit_meshes;
  1173. bool cancelled = p_step_function(0.4 + p * 0.4, vformat("%s (%d/%d)", TTR("Indirect lighting"), i, mesh_instances.size()), p_bake_userdata, false);
  1174. if (cancelled) {
  1175. return BAKE_ERROR_USER_ABORTED;
  1176. }
  1177. }
  1178. if (!scene_lightmaps[i].empty()) {
  1179. if (_parallel_run(scene_lightmaps[i].size(), "Computing indirect light", &LightmapperCPU::_compute_indirect_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1180. return BAKE_ERROR_USER_ABORTED;
  1181. }
  1182. }
  1183. }
  1184. if (parameters.environment_panorama.is_valid()) {
  1185. parameters.environment_panorama->unlock();
  1186. }
  1187. raycaster.unref(); // Not needed anymore, free some memory.
  1188. LocalVector<LocalVector<Vector3>> lightmaps_data;
  1189. lightmaps_data.resize(mesh_instances.size());
  1190. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1191. if (mesh_instances[i].generate_lightmap) {
  1192. const Vector2i size = mesh_instances[i].size;
  1193. lightmaps_data[i].resize(size.x * size.y);
  1194. }
  1195. }
  1196. if (p_step_function) {
  1197. bool cancelled = p_step_function(0.8, TTR("Post processing"), p_bake_userdata, true);
  1198. if (cancelled) {
  1199. return BAKE_ERROR_USER_ABORTED;
  1200. }
  1201. }
  1202. if (_parallel_run(mesh_instances.size(), "Denoise & fix seams", &LightmapperCPU::_post_process, lightmaps_data.ptr(), p_substep_function)) {
  1203. return BAKE_ERROR_USER_ABORTED;
  1204. }
  1205. if (p_generate_atlas) {
  1206. bake_textures.resize(atlas_slices);
  1207. for (int i = 0; i < atlas_slices; i++) {
  1208. Ref<Image> image;
  1209. image.instance();
  1210. image->create(atlas_size.x, atlas_size.y, false, Image::FORMAT_RGBH);
  1211. bake_textures[i] = image;
  1212. }
  1213. } else {
  1214. bake_textures.resize(mesh_instances.size());
  1215. Set<String> used_mesh_names;
  1216. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1217. if (!mesh_instances[i].generate_lightmap) {
  1218. continue;
  1219. }
  1220. String mesh_name = mesh_instances[i].node_name;
  1221. if (mesh_name == "" || mesh_name.find(":") != -1 || mesh_name.find("/") != -1) {
  1222. mesh_name = "LightMap";
  1223. }
  1224. if (used_mesh_names.has(mesh_name)) {
  1225. int idx = 2;
  1226. String base = mesh_name;
  1227. while (true) {
  1228. mesh_name = base + itos(idx);
  1229. if (!used_mesh_names.has(mesh_name)) {
  1230. break;
  1231. }
  1232. idx++;
  1233. }
  1234. }
  1235. used_mesh_names.insert(mesh_name);
  1236. Ref<Image> image;
  1237. image.instance();
  1238. image->create(mesh_instances[i].size.x, mesh_instances[i].size.y, false, Image::FORMAT_RGBH);
  1239. image->set_name(mesh_name);
  1240. bake_textures[i] = image;
  1241. }
  1242. }
  1243. if (p_step_function) {
  1244. bool cancelled = p_step_function(0.9, TTR("Plotting lightmaps"), p_bake_userdata, true);
  1245. if (cancelled) {
  1246. return BAKE_ERROR_USER_ABORTED;
  1247. }
  1248. }
  1249. {
  1250. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1251. if (!mesh_instances[i].generate_lightmap) {
  1252. continue;
  1253. }
  1254. if (p_generate_atlas) {
  1255. _blit_lightmap(lightmaps_data[i], mesh_instances[i].size, bake_textures[mesh_instances[i].slice], mesh_instances[i].offset.x, mesh_instances[i].offset.y, true);
  1256. } else {
  1257. _blit_lightmap(lightmaps_data[i], mesh_instances[i].size, bake_textures[i], 0, 0, false);
  1258. }
  1259. }
  1260. }
  1261. return BAKE_OK;
  1262. }
  1263. int LightmapperCPU::get_bake_texture_count() const {
  1264. return bake_textures.size();
  1265. }
  1266. Ref<Image> LightmapperCPU::get_bake_texture(int p_index) const {
  1267. ERR_FAIL_INDEX_V(p_index, (int)bake_textures.size(), Ref<Image>());
  1268. return bake_textures[p_index];
  1269. }
  1270. int LightmapperCPU::get_bake_mesh_count() const {
  1271. return mesh_instances.size();
  1272. }
  1273. Variant LightmapperCPU::get_bake_mesh_userdata(int p_index) const {
  1274. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1275. return mesh_instances[p_index].data.userdata;
  1276. }
  1277. Rect2 LightmapperCPU::get_bake_mesh_uv_scale(int p_index) const {
  1278. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1279. Rect2 uv_ofs;
  1280. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1281. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1282. uv_ofs.size = Vector2(mesh_instances[p_index].size) / atlas_size;
  1283. return uv_ofs;
  1284. }
  1285. int LightmapperCPU::get_bake_mesh_texture_slice(int p_index) const {
  1286. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1287. return mesh_instances[p_index].slice;
  1288. }
  1289. void LightmapperCPU::add_albedo_texture(Ref<Texture> p_texture) {
  1290. if (p_texture.is_null()) {
  1291. return;
  1292. }
  1293. RID texture_rid = p_texture->get_rid();
  1294. if (!texture_rid.is_valid() || albedo_textures.has(texture_rid)) {
  1295. return;
  1296. }
  1297. Ref<Image> texture_data = p_texture->get_data();
  1298. if (texture_data.is_null()) {
  1299. return;
  1300. }
  1301. if (texture_data->is_compressed()) {
  1302. texture_data->decompress();
  1303. }
  1304. texture_data->convert(Image::FORMAT_RGBA8);
  1305. albedo_textures.insert(texture_rid, texture_data);
  1306. }
  1307. void LightmapperCPU::add_emission_texture(Ref<Texture> p_texture) {
  1308. if (p_texture.is_null()) {
  1309. return;
  1310. }
  1311. RID texture_rid = p_texture->get_rid();
  1312. if (!texture_rid.is_valid() || emission_textures.has(texture_rid)) {
  1313. return;
  1314. }
  1315. Ref<Image> texture_data = p_texture->get_data();
  1316. if (texture_data.is_null()) {
  1317. return;
  1318. }
  1319. if (texture_data->is_compressed()) {
  1320. texture_data->decompress();
  1321. }
  1322. texture_data->convert(Image::FORMAT_RGBH);
  1323. emission_textures.insert(texture_rid, texture_data);
  1324. }
  1325. void LightmapperCPU::add_mesh(const MeshData &p_mesh, Vector2i p_size) {
  1326. ERR_FAIL_COND(p_mesh.points.size() == 0);
  1327. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.uv2.size());
  1328. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.normal.size());
  1329. ERR_FAIL_COND(!p_mesh.uv.empty() && p_mesh.points.size() != p_mesh.uv.size());
  1330. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.albedo.size());
  1331. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.emission.size());
  1332. MeshInstance mi;
  1333. mi.data = p_mesh;
  1334. mi.size = p_size;
  1335. mi.generate_lightmap = true;
  1336. mi.cast_shadows = true;
  1337. mi.node_name = "";
  1338. Dictionary userdata = p_mesh.userdata;
  1339. if (userdata.has("cast_shadows")) {
  1340. mi.cast_shadows = userdata["cast_shadows"];
  1341. }
  1342. if (userdata.has("generate_lightmap")) {
  1343. mi.generate_lightmap = userdata["generate_lightmap"];
  1344. }
  1345. if (userdata.has("node_name")) {
  1346. mi.node_name = userdata["node_name"];
  1347. }
  1348. mesh_instances.push_back(mi);
  1349. }
  1350. void LightmapperCPU::add_directional_light(bool p_bake_direct, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_multiplier, float p_size) {
  1351. Light l;
  1352. l.type = LIGHT_TYPE_DIRECTIONAL;
  1353. l.direction = p_direction;
  1354. l.color = p_color;
  1355. l.energy = p_energy;
  1356. l.indirect_multiplier = p_indirect_multiplier;
  1357. l.bake_direct = p_bake_direct;
  1358. l.size = p_size;
  1359. lights.push_back(l);
  1360. }
  1361. void LightmapperCPU::add_omni_light(bool p_bake_direct, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_multiplier, float p_range, float p_attenuation, float p_size) {
  1362. Light l;
  1363. l.type = LIGHT_TYPE_OMNI;
  1364. l.position = p_position;
  1365. l.range = p_range;
  1366. l.attenuation = p_attenuation;
  1367. l.color = p_color;
  1368. l.energy = p_energy;
  1369. l.indirect_multiplier = p_indirect_multiplier;
  1370. l.bake_direct = p_bake_direct;
  1371. l.size = p_size;
  1372. lights.push_back(l);
  1373. }
  1374. void LightmapperCPU::add_spot_light(bool p_bake_direct, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_multiplier, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size) {
  1375. Light l;
  1376. l.type = LIGHT_TYPE_SPOT;
  1377. l.position = p_position;
  1378. l.direction = p_direction;
  1379. l.range = p_range;
  1380. l.attenuation = p_attenuation;
  1381. l.spot_angle = Math::deg2rad(p_spot_angle);
  1382. l.spot_attenuation = p_spot_attenuation;
  1383. l.color = p_color;
  1384. l.energy = p_energy;
  1385. l.indirect_multiplier = p_indirect_multiplier;
  1386. l.bake_direct = p_bake_direct;
  1387. l.size = p_size;
  1388. lights.push_back(l);
  1389. }
  1390. LightmapperCPU::LightmapperCPU() {
  1391. thread_progress = 0;
  1392. thread_cancelled = false;
  1393. }