lightmapper_cpu.cpp 54 KB

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