2
0

lightmapper_cpu.cpp 51 KB

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