lightmapper_cpu.cpp 52 KB

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