lightmapper_cpu.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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. void LightmapperCPU::_compute_direct_light(uint32_t p_idx, void *r_lightmap) {
  575. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  576. for (unsigned int i = 0; i < lights.size(); ++i) {
  577. const Light &light = lights[i];
  578. Vector3 normal = lightmap[p_idx].normal;
  579. Vector3 position = lightmap[p_idx].pos;
  580. Vector3 final_energy;
  581. Color c = light.color;
  582. Vector3 light_energy = Vector3(c.r, c.g, c.b) * light.energy;
  583. if (light.type == LIGHT_TYPE_OMNI) {
  584. Vector3 light_direction = (position - light.position).normalized();
  585. if (normal.dot(light_direction) >= 0.0) {
  586. continue;
  587. }
  588. float dist = position.distance_to(light.position);
  589. if (dist <= light.range) {
  590. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_direction, parameters.bias, dist - parameters.bias);
  591. if (raycaster->intersect(ray)) {
  592. continue;
  593. }
  594. float att = powf(1.0 - dist / light.range, light.attenuation);
  595. final_energy = light_energy * att * MAX(0, normal.dot(-light_direction));
  596. }
  597. }
  598. if (light.type == LIGHT_TYPE_SPOT) {
  599. Vector3 light_direction = (position - light.position).normalized();
  600. if (normal.dot(light_direction) >= 0.0) {
  601. continue;
  602. }
  603. float angle = Math::acos(light.direction.dot(light_direction));
  604. if (angle > light.spot_angle) {
  605. continue;
  606. }
  607. float dist = position.distance_to(light.position);
  608. if (dist > light.range) {
  609. continue;
  610. }
  611. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position, -light_direction, parameters.bias, dist);
  612. if (raycaster->intersect(ray)) {
  613. continue;
  614. }
  615. float normalized_dist = dist * (1.0f / MAX(0.001f, light.range));
  616. float norm_light_attenuation = Math::pow(MAX(1.0f - normalized_dist, 0.001f), light.attenuation);
  617. float spot_cutoff = Math::cos(light.spot_angle);
  618. float scos = MAX(light_direction.dot(light.direction), spot_cutoff);
  619. float spot_rim = (1.0f - scos) / (1.0f - spot_cutoff);
  620. norm_light_attenuation *= 1.0f - pow(MAX(spot_rim, 0.001f), light.spot_attenuation);
  621. final_energy = light_energy * norm_light_attenuation * MAX(0, normal.dot(-light_direction));
  622. }
  623. if (light.type == LIGHT_TYPE_DIRECTIONAL) {
  624. if (normal.dot(light.direction) >= 0.0) {
  625. continue;
  626. }
  627. LightmapRaycaster::Ray ray = LightmapRaycaster::Ray(position + normal * parameters.bias, -light.direction, parameters.bias);
  628. if (raycaster->intersect(ray)) {
  629. continue;
  630. }
  631. final_energy = light_energy * MAX(0, normal.dot(-light.direction));
  632. }
  633. lightmap[p_idx].direct_light += final_energy * light.indirect_multiplier;
  634. if (light.bake_direct) {
  635. lightmap[p_idx].output_light += final_energy;
  636. }
  637. }
  638. }
  639. _ALWAYS_INLINE_ float uniform_rand() {
  640. /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
  641. static thread_local uint32_t state = Math::rand();
  642. state ^= state << 13;
  643. state ^= state >> 17;
  644. state ^= state << 5;
  645. /* implicit conversion from 'unsigned int' to 'float' changes value from 4294967295 to 4294967296 */
  646. return float(state) / float(UINT32_MAX);
  647. }
  648. void LightmapperCPU::_compute_indirect_light(uint32_t p_idx, void *r_lightmap) {
  649. LightmapTexel *lightmap = (LightmapTexel *)r_lightmap;
  650. LightmapTexel &texel = lightmap[p_idx];
  651. Vector3 accum;
  652. const Vector3 const_forward = Vector3(0, 0, 1);
  653. const Vector3 const_up = Vector3(0, 1, 0);
  654. for (int i = 0; i < parameters.samples; i++) {
  655. Vector3 color;
  656. Vector3 throughput = Vector3(1.0f, 1.0f, 1.0f);
  657. Vector3 position = texel.pos;
  658. Vector3 normal = texel.normal;
  659. Vector3 direction;
  660. for (int depth = 0; depth < parameters.bounces; depth++) {
  661. Vector3 tangent = const_forward.cross(normal);
  662. if (unlikely(tangent.length_squared() < 0.005f)) {
  663. tangent = const_up.cross(normal);
  664. }
  665. tangent.normalize();
  666. Vector3 bitangent = tangent.cross(normal);
  667. bitangent.normalize();
  668. Basis normal_xform = Basis(tangent, bitangent, normal);
  669. normal_xform.transpose();
  670. float u1 = uniform_rand();
  671. float u2 = uniform_rand();
  672. float radius = Math::sqrt(u1);
  673. float theta = Math_TAU * u2;
  674. Vector3 axis = Vector3(radius * Math::cos(theta), radius * Math::sin(theta), Math::sqrt(MAX(0.0f, 1.0f - u1)));
  675. direction = normal_xform.xform(axis);
  676. // We can skip multiplying throughput by cos(theta) because de sampling PDF is also cos(theta) and they cancel each other
  677. //float pdf = normal.dot(direction);
  678. //throughput *= normal.dot(direction)/pdf;
  679. LightmapRaycaster::Ray ray(position, direction, parameters.bias);
  680. bool hit = raycaster->intersect(ray);
  681. if (!hit) {
  682. if (parameters.environment_panorama.is_valid()) {
  683. direction = parameters.environment_transform.xform_inv(direction);
  684. Vector2 st = Vector2(Math::atan2(direction.z, direction.x), Math::acos(direction.y));
  685. if (Math::is_nan(st.y)) {
  686. st.y = direction.y > 0.0 ? 0.0 : Math_PI;
  687. }
  688. st.x += Math_PI;
  689. st /= Vector2(Math_TAU, Math_PI);
  690. st.x = Math::fmod(st.x + 0.75, 1.0);
  691. Color c = _bilinear_sample(parameters.environment_panorama, st, false, true);
  692. color += throughput * Vector3(c.r, c.g, c.b) * c.a;
  693. }
  694. break;
  695. }
  696. unsigned int hit_mesh_id = ray.geomID;
  697. const Vector2i &size = mesh_instances[hit_mesh_id].size;
  698. int x = CLAMP(ray.u * size.x, 0, size.x - 1);
  699. int y = CLAMP(ray.v * size.y, 0, size.y - 1);
  700. const int idx = scene_lightmap_indices[hit_mesh_id][y * size.x + x];
  701. if (idx < 0) {
  702. break;
  703. }
  704. const LightmapTexel &sample = scene_lightmaps[hit_mesh_id][idx];
  705. if (sample.normal.dot(ray.dir) > 0.0 && !no_shadow_meshes.has(hit_mesh_id)) {
  706. // We hit a back-face
  707. break;
  708. }
  709. color += throughput * sample.emission;
  710. throughput *= sample.albedo;
  711. color += throughput * sample.direct_light;
  712. // Russian Roulette
  713. // https://computergraphics.stackexchange.com/questions/2316/is-russian-roulette-really-the-answer
  714. const float p = throughput[throughput.max_axis()];
  715. if (uniform_rand() > p) {
  716. break;
  717. }
  718. throughput *= 1.0f / p;
  719. position = sample.pos;
  720. normal = sample.normal;
  721. }
  722. accum += color;
  723. }
  724. texel.output_light += accum / parameters.samples;
  725. }
  726. void LightmapperCPU::_post_process(uint32_t p_idx, void *r_output) {
  727. const MeshInstance &mesh = mesh_instances[p_idx];
  728. if (!mesh.generate_lightmap) {
  729. return;
  730. }
  731. LocalVector<int> &indices = scene_lightmap_indices[p_idx];
  732. LocalVector<LightmapTexel> &lightmap = scene_lightmaps[p_idx];
  733. Vector3 *output = ((LocalVector<Vector3> *)r_output)[p_idx].ptr();
  734. Vector2i size = mesh.size;
  735. // Blit texels to buffer
  736. const int margin = 4;
  737. for (int i = 0; i < size.y; i++) {
  738. for (int j = 0; j < size.x; j++) {
  739. int idx = indices[i * size.x + j];
  740. if (idx >= 0) {
  741. output[i * size.x + j] = lightmap[idx].output_light;
  742. continue; // filled, skip
  743. }
  744. int closest_idx = -1;
  745. float closest_dist = 1e20;
  746. for (int y = i - margin; y <= i + margin; y++) {
  747. for (int x = j - margin; x <= j + margin; x++) {
  748. if (x == j && y == i) {
  749. continue;
  750. }
  751. if (x < 0 || x >= size.x) {
  752. continue;
  753. }
  754. if (y < 0 || y >= size.y) {
  755. continue;
  756. }
  757. int cell_idx = indices[y * size.x + x];
  758. if (cell_idx < 0) {
  759. continue; //also ensures that blitted stuff is not reused
  760. }
  761. float dist = Vector2(i - y, j - x).length_squared();
  762. if (dist < closest_dist) {
  763. closest_dist = dist;
  764. closest_idx = cell_idx;
  765. }
  766. }
  767. }
  768. if (closest_idx != -1) {
  769. output[i * size.x + j] = lightmap[closest_idx].output_light;
  770. }
  771. }
  772. }
  773. lightmap.clear();
  774. LocalVector<UVSeam> seams;
  775. _compute_seams(mesh, seams);
  776. _fix_seams(seams, output, size);
  777. _dilate_lightmap(output, indices, size, margin);
  778. if (parameters.use_denoiser) {
  779. Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
  780. if (denoiser.is_valid()) {
  781. int data_size = size.x * size.y * sizeof(Vector3);
  782. Ref<Image> current_image;
  783. current_image.instance();
  784. {
  785. PoolByteArray data;
  786. data.resize(data_size);
  787. PoolByteArray::Write w = data.write();
  788. memcpy(w.ptr(), output, data_size);
  789. current_image->create(size.x, size.y, false, Image::FORMAT_RGBF, data);
  790. }
  791. Ref<Image> denoised_image = denoiser->denoise_image(current_image);
  792. PoolByteArray denoised_data = denoised_image->get_data();
  793. denoised_image.unref();
  794. PoolByteArray::Read r = denoised_data.read();
  795. memcpy(output, r.ptr(), data_size);
  796. }
  797. }
  798. _dilate_lightmap(output, indices, size, margin);
  799. _fix_seams(seams, output, size);
  800. _dilate_lightmap(output, indices, size, margin);
  801. indices.clear();
  802. }
  803. void LightmapperCPU::_compute_seams(const MeshInstance &p_mesh, LocalVector<UVSeam> &r_seams) {
  804. float max_uv_distance = 1.0f / MAX(p_mesh.size.x, p_mesh.size.y);
  805. max_uv_distance *= max_uv_distance; // We use distance_to_squared(), so we need to square the max distance as well
  806. float max_pos_distance = 0.00025f;
  807. float max_normal_distance = 0.05f;
  808. const Vector<Vector3> &points = p_mesh.data.points;
  809. const Vector<Vector2> &uv2s = p_mesh.data.uv2;
  810. const Vector<Vector3> &normals = p_mesh.data.normal;
  811. LocalVector<SeamEdge> edges;
  812. edges.resize(points.size()); // One edge per vertex
  813. for (int i = 0; i < points.size(); i += 3) {
  814. Vector3 triangle_vtxs[3] = { points[i + 0], points[i + 1], points[i + 2] };
  815. Vector2 triangle_uvs[3] = { uv2s[i + 0], uv2s[i + 1], uv2s[i + 2] };
  816. Vector3 triangle_normals[3] = { normals[i + 0], normals[i + 1], normals[i + 2] };
  817. for (int k = 0; k < 3; k++) {
  818. int idx[2];
  819. idx[0] = k;
  820. idx[1] = (k + 1) % 3;
  821. if (triangle_vtxs[idx[1]] < triangle_vtxs[idx[0]]) {
  822. SWAP(idx[0], idx[1]);
  823. }
  824. SeamEdge e;
  825. for (int l = 0; l < 2; ++l) {
  826. e.pos[l] = triangle_vtxs[idx[l]];
  827. e.uv[l] = triangle_uvs[idx[l]];
  828. e.normal[l] = triangle_normals[idx[l]];
  829. }
  830. edges[i + k] = e;
  831. }
  832. }
  833. edges.sort();
  834. for (unsigned int j = 0; j < edges.size(); j++) {
  835. const SeamEdge &edge0 = edges[j];
  836. if (edge0.uv[0].distance_squared_to(edge0.uv[1]) < 0.001) {
  837. continue;
  838. }
  839. if (edge0.pos[0].distance_squared_to(edge0.pos[1]) < 0.001) {
  840. continue;
  841. }
  842. for (unsigned int k = j + 1; k < edges.size() && edges[k].pos[0].x < (edge0.pos[0].x + max_pos_distance * 1.1f); k++) {
  843. const SeamEdge &edge1 = edges[k];
  844. if (edge1.uv[0].distance_squared_to(edge1.uv[1]) < 0.001) {
  845. continue;
  846. }
  847. if (edge1.pos[0].distance_squared_to(edge1.pos[1]) < 0.001) {
  848. continue;
  849. }
  850. 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) {
  851. continue;
  852. }
  853. 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) {
  854. continue;
  855. }
  856. 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) {
  857. continue;
  858. }
  859. UVSeam s;
  860. s.edge0[0] = edge0.uv[0];
  861. s.edge0[1] = edge0.uv[1];
  862. s.edge1[0] = edge1.uv[0];
  863. s.edge1[1] = edge1.uv[1];
  864. r_seams.push_back(s);
  865. }
  866. }
  867. }
  868. void LightmapperCPU::_fix_seams(const LocalVector<UVSeam> &p_seams, Vector3 *r_lightmap, Vector2i p_size) {
  869. LocalVector<Vector3> extra_buffer;
  870. extra_buffer.resize(p_size.x * p_size.y);
  871. memcpy(extra_buffer.ptr(), r_lightmap, p_size.x * p_size.y * sizeof(Vector3));
  872. Vector3 *read_ptr = extra_buffer.ptr();
  873. Vector3 *write_ptr = r_lightmap;
  874. for (int i = 0; i < 5; i++) {
  875. for (unsigned int j = 0; j < p_seams.size(); j++) {
  876. _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);
  877. _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);
  878. }
  879. memcpy(read_ptr, write_ptr, p_size.x * p_size.y * sizeof(Vector3));
  880. }
  881. }
  882. 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) {
  883. Vector2 line[2];
  884. line[0] = p_pos0 * p_size;
  885. line[1] = p_pos1 * p_size;
  886. const Vector2i start_pixel = line[0].floor();
  887. const Vector2i end_pixel = line[1].floor();
  888. Vector2 seam_dir = (line[1] - line[0]).normalized();
  889. Vector2 t_delta = Vector2(1.0f / Math::abs(seam_dir.x), 1.0f / Math::abs(seam_dir.y));
  890. 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));
  891. Vector2 t_next = Vector2(Math::fmod(line[0].x, 1.0f), Math::fmod(line[0].y, 1.0f));
  892. if (step.x == 1) {
  893. t_next.x = 1.0f - t_next.x;
  894. }
  895. if (step.y == 1) {
  896. t_next.y = 1.0f - t_next.y;
  897. }
  898. t_next.x /= Math::abs(seam_dir.x);
  899. t_next.y /= Math::abs(seam_dir.y);
  900. if (Math::is_nan(t_next.x)) {
  901. t_next.x = 1e20f;
  902. }
  903. if (Math::is_nan(t_next.y)) {
  904. t_next.y = 1e20f;
  905. }
  906. Vector2i pixel = start_pixel;
  907. Vector2 start_p = start_pixel;
  908. float line_length = line[0].distance_to(line[1]);
  909. if (line_length == 0.0f) {
  910. return;
  911. }
  912. while (start_p.distance_to(pixel) < line_length + 1.0f) {
  913. Vector2 current_point = Vector2(pixel) + Vector2(0.5f, 0.5f);
  914. current_point = Geometry::get_closest_point_to_segment_2d(current_point, line);
  915. float t = line[0].distance_to(current_point) / line_length;
  916. Vector2 current_uv = p_uv0 * (1.0 - t) + p_uv1 * t;
  917. Vector2i sampled_point = (current_uv * p_size).floor();
  918. Vector3 current_color = r_write_buffer[pixel.y * p_size.x + pixel.x];
  919. Vector3 sampled_color = p_read_buffer[sampled_point.y * p_size.x + sampled_point.x];
  920. r_write_buffer[pixel.y * p_size.x + pixel.x] = current_color * 0.6f + sampled_color * 0.4f;
  921. if (pixel == end_pixel) {
  922. break;
  923. }
  924. if (t_next.x < t_next.y) {
  925. pixel.x += step.x;
  926. t_next.x += t_delta.x;
  927. } else {
  928. pixel.y += step.y;
  929. t_next.y += t_delta.y;
  930. }
  931. }
  932. }
  933. void LightmapperCPU::_dilate_lightmap(Vector3 *r_lightmap, const LocalVector<int> p_indices, Vector2i p_size, int margin) {
  934. for (int i = 0; i < p_size.y; i++) {
  935. for (int j = 0; j < p_size.x; j++) {
  936. int idx = p_indices[i * p_size.x + j];
  937. if (idx >= 0) {
  938. continue; //filled, skip
  939. }
  940. Vector2i closest;
  941. float closest_dist = 1e20;
  942. for (int y = i - margin; y <= i + margin; y++) {
  943. for (int x = j - margin; x <= j + margin; x++) {
  944. if (x == j && y == i) {
  945. continue;
  946. }
  947. if (x < 0 || x >= p_size.x) {
  948. continue;
  949. }
  950. if (y < 0 || y >= p_size.y) {
  951. continue;
  952. }
  953. int cell_idx = p_indices[y * p_size.x + x];
  954. if (cell_idx < 0) {
  955. continue; //also ensures that blitted stuff is not reused
  956. }
  957. float dist = Vector2(i - y, j - x).length_squared();
  958. if (dist < closest_dist) {
  959. closest_dist = dist;
  960. closest = Vector2(x, y);
  961. }
  962. }
  963. }
  964. if (closest_dist < 1e20) {
  965. r_lightmap[i * p_size.x + j] = r_lightmap[closest.y * p_size.x + closest.x];
  966. }
  967. }
  968. }
  969. }
  970. 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) {
  971. int padding = p_with_padding ? 1 : 0;
  972. ERR_FAIL_COND(p_x < padding || p_y < padding);
  973. ERR_FAIL_COND(p_x + p_size.x > p_dst->get_width() - padding);
  974. ERR_FAIL_COND(p_y + p_size.y > p_dst->get_height() - padding);
  975. p_dst->lock();
  976. for (int y = 0; y < p_size.y; y++) {
  977. const Vector3 *__restrict src = p_src.ptr() + y * p_size.x;
  978. for (int x = 0; x < p_size.x; x++) {
  979. p_dst->set_pixel(p_x + x, p_y + y, Color(src->x, src->y, src->z));
  980. src++;
  981. }
  982. }
  983. if (p_with_padding) {
  984. for (int y = -1; y < p_size.y + 1; y++) {
  985. int yy = CLAMP(y, 0, p_size.y - 1);
  986. int idx_left = yy * p_size.x;
  987. int idx_right = idx_left + p_size.x - 1;
  988. 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));
  989. 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));
  990. }
  991. for (int x = -1; x < p_size.x + 1; x++) {
  992. int xx = CLAMP(x, 0, p_size.x - 1);
  993. int idx_top = xx;
  994. int idx_bot = idx_top + (p_size.y - 1) * p_size.x;
  995. 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));
  996. 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));
  997. }
  998. }
  999. p_dst->unlock();
  1000. }
  1001. 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) {
  1002. if (p_step_function) {
  1003. bool cancelled = p_step_function(0.0, TTR("Begin Bake"), p_bake_userdata, true);
  1004. if (cancelled) {
  1005. return BAKE_ERROR_USER_ABORTED;
  1006. }
  1007. }
  1008. raycaster = LightmapRaycaster::create();
  1009. ERR_FAIL_COND_V(raycaster.is_null(), BAKE_ERROR_NO_RAYCASTER);
  1010. // Collect parameters
  1011. parameters.use_denoiser = p_use_denoiser;
  1012. parameters.bias = p_bias;
  1013. parameters.bounces = p_bounces;
  1014. parameters.environment_transform = p_environment_transform;
  1015. parameters.environment_panorama = p_environment_panorama;
  1016. switch (p_quality) {
  1017. case BAKE_QUALITY_LOW: {
  1018. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/low_quality_ray_count");
  1019. } break;
  1020. case BAKE_QUALITY_MEDIUM: {
  1021. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/medium_quality_ray_count");
  1022. } break;
  1023. case BAKE_QUALITY_HIGH: {
  1024. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/high_quality_ray_count");
  1025. } break;
  1026. case BAKE_QUALITY_ULTRA: {
  1027. parameters.samples = GLOBAL_GET("rendering/cpu_lightmapper/quality/ultra_quality_ray_count");
  1028. } break;
  1029. }
  1030. bake_textures.clear();
  1031. if (p_step_function) {
  1032. bool cancelled = p_step_function(0.1, TTR("Preparing data structures"), p_bake_userdata, true);
  1033. if (cancelled) {
  1034. return BAKE_ERROR_USER_ABORTED;
  1035. }
  1036. }
  1037. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1038. raycaster->add_mesh(mesh_instances[i].data.points, mesh_instances[i].data.normal, mesh_instances[i].data.uv2, i);
  1039. }
  1040. raycaster->commit();
  1041. scene_lightmaps.resize(mesh_instances.size());
  1042. scene_lightmap_indices.resize(mesh_instances.size());
  1043. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1044. if (!mesh_instances[i].cast_shadows) {
  1045. no_shadow_meshes.insert(i);
  1046. }
  1047. }
  1048. raycaster->set_mesh_filter(no_shadow_meshes);
  1049. Vector2i atlas_size = Vector2i(-1, -1);
  1050. int atlas_slices = -1;
  1051. if (p_generate_atlas) {
  1052. Error err = _layout_atlas(p_max_texture_size, &atlas_size, &atlas_slices);
  1053. if (err != OK) {
  1054. return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
  1055. }
  1056. }
  1057. if (p_step_function) {
  1058. bool cancelled = p_step_function(0.2, TTR("Generate buffers"), p_bake_userdata, true);
  1059. if (cancelled) {
  1060. return BAKE_ERROR_USER_ABORTED;
  1061. }
  1062. }
  1063. if (_parallel_run(mesh_instances.size(), "Rasterizing meshes", &LightmapperCPU::_generate_buffer, nullptr, p_substep_function)) {
  1064. return BAKE_ERROR_USER_ABORTED;
  1065. }
  1066. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1067. const Size2i &size = mesh_instances[i].size;
  1068. bool has_alpha = false;
  1069. PoolVector<uint8_t> alpha_data;
  1070. alpha_data.resize(size.x * size.y);
  1071. {
  1072. PoolVector<uint8_t>::Write w = alpha_data.write();
  1073. for (unsigned int j = 0; j < scene_lightmap_indices[i].size(); ++j) {
  1074. int idx = scene_lightmap_indices[i][j];
  1075. uint8_t alpha = 0;
  1076. if (idx >= 0) {
  1077. alpha = CLAMP(scene_lightmaps[i][idx].alpha * 255, 0, 255);
  1078. if (alpha < 255) {
  1079. has_alpha = true;
  1080. }
  1081. }
  1082. w[j] = alpha;
  1083. }
  1084. }
  1085. if (has_alpha) {
  1086. Ref<Image> alpha_texture;
  1087. alpha_texture.instance();
  1088. alpha_texture->create(size.x, size.y, false, Image::FORMAT_L8, alpha_data);
  1089. raycaster->set_mesh_alpha_texture(alpha_texture, i);
  1090. }
  1091. }
  1092. albedo_textures.clear();
  1093. emission_textures.clear();
  1094. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1095. if (p_step_function) {
  1096. float p = float(i) / mesh_instances.size();
  1097. 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);
  1098. if (cancelled) {
  1099. return BAKE_ERROR_USER_ABORTED;
  1100. }
  1101. }
  1102. if (_parallel_run(scene_lightmaps[i].size(), "Computing direct light", &LightmapperCPU::_compute_direct_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1103. return BAKE_ERROR_USER_ABORTED;
  1104. }
  1105. }
  1106. raycaster->clear_mesh_filter();
  1107. int n_lit_meshes = 0;
  1108. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1109. if (mesh_instances[i].generate_lightmap) {
  1110. n_lit_meshes++;
  1111. }
  1112. }
  1113. if (parameters.environment_panorama.is_valid()) {
  1114. parameters.environment_panorama->lock();
  1115. }
  1116. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1117. if (!mesh_instances[i].generate_lightmap) {
  1118. continue;
  1119. }
  1120. if (p_step_function) {
  1121. float p = float(i) / n_lit_meshes;
  1122. 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);
  1123. if (cancelled) {
  1124. return BAKE_ERROR_USER_ABORTED;
  1125. }
  1126. }
  1127. if (!scene_lightmaps[i].empty()) {
  1128. if (_parallel_run(scene_lightmaps[i].size(), "Computing indirect light", &LightmapperCPU::_compute_indirect_light, scene_lightmaps[i].ptr(), p_substep_function)) {
  1129. return BAKE_ERROR_USER_ABORTED;
  1130. }
  1131. }
  1132. }
  1133. if (parameters.environment_panorama.is_valid()) {
  1134. parameters.environment_panorama->unlock();
  1135. }
  1136. raycaster.unref(); // Not needed anymore, free some memory.
  1137. LocalVector<LocalVector<Vector3>> lightmaps_data;
  1138. lightmaps_data.resize(mesh_instances.size());
  1139. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1140. if (mesh_instances[i].generate_lightmap) {
  1141. const Vector2i size = mesh_instances[i].size;
  1142. lightmaps_data[i].resize(size.x * size.y);
  1143. }
  1144. }
  1145. if (p_step_function) {
  1146. bool cancelled = p_step_function(0.8, TTR("Post processing"), p_bake_userdata, true);
  1147. if (cancelled) {
  1148. return BAKE_ERROR_USER_ABORTED;
  1149. }
  1150. }
  1151. if (_parallel_run(mesh_instances.size(), "Denoise & fix seams", &LightmapperCPU::_post_process, lightmaps_data.ptr(), p_substep_function)) {
  1152. return BAKE_ERROR_USER_ABORTED;
  1153. }
  1154. if (p_generate_atlas) {
  1155. bake_textures.resize(atlas_slices);
  1156. for (int i = 0; i < atlas_slices; i++) {
  1157. Ref<Image> image;
  1158. image.instance();
  1159. image->create(atlas_size.x, atlas_size.y, false, Image::FORMAT_RGBH);
  1160. bake_textures[i] = image;
  1161. }
  1162. } else {
  1163. bake_textures.resize(mesh_instances.size());
  1164. Set<String> used_mesh_names;
  1165. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1166. if (!mesh_instances[i].generate_lightmap) {
  1167. continue;
  1168. }
  1169. String mesh_name = mesh_instances[i].node_name;
  1170. if (mesh_name == "" || mesh_name.find(":") != -1 || mesh_name.find("/") != -1) {
  1171. mesh_name = "LightMap";
  1172. }
  1173. if (used_mesh_names.has(mesh_name)) {
  1174. int idx = 2;
  1175. String base = mesh_name;
  1176. while (true) {
  1177. mesh_name = base + itos(idx);
  1178. if (!used_mesh_names.has(mesh_name)) {
  1179. break;
  1180. }
  1181. idx++;
  1182. }
  1183. }
  1184. used_mesh_names.insert(mesh_name);
  1185. Ref<Image> image;
  1186. image.instance();
  1187. image->create(mesh_instances[i].size.x, mesh_instances[i].size.y, false, Image::FORMAT_RGBH);
  1188. image->set_name(mesh_name);
  1189. bake_textures[i] = image;
  1190. }
  1191. }
  1192. if (p_step_function) {
  1193. bool cancelled = p_step_function(0.9, TTR("Plotting lightmaps"), p_bake_userdata, true);
  1194. if (cancelled) {
  1195. return BAKE_ERROR_USER_ABORTED;
  1196. }
  1197. }
  1198. {
  1199. int j = 0;
  1200. for (unsigned int i = 0; i < mesh_instances.size(); i++) {
  1201. if (!mesh_instances[i].generate_lightmap) {
  1202. continue;
  1203. }
  1204. if (p_generate_atlas) {
  1205. _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);
  1206. } else {
  1207. _blit_lightmap(lightmaps_data[i], mesh_instances[i].size, bake_textures[j], 0, 0, false);
  1208. }
  1209. j++;
  1210. }
  1211. }
  1212. return BAKE_OK;
  1213. }
  1214. int LightmapperCPU::get_bake_texture_count() const {
  1215. return bake_textures.size();
  1216. }
  1217. Ref<Image> LightmapperCPU::get_bake_texture(int p_index) const {
  1218. ERR_FAIL_INDEX_V(p_index, (int)bake_textures.size(), Ref<Image>());
  1219. return bake_textures[p_index];
  1220. }
  1221. int LightmapperCPU::get_bake_mesh_count() const {
  1222. return mesh_instances.size();
  1223. }
  1224. Variant LightmapperCPU::get_bake_mesh_userdata(int p_index) const {
  1225. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1226. return mesh_instances[p_index].data.userdata;
  1227. }
  1228. Rect2 LightmapperCPU::get_bake_mesh_uv_scale(int p_index) const {
  1229. ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
  1230. Rect2 uv_ofs;
  1231. Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
  1232. uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
  1233. uv_ofs.size = Vector2(mesh_instances[p_index].size) / atlas_size;
  1234. return uv_ofs;
  1235. }
  1236. int LightmapperCPU::get_bake_mesh_texture_slice(int p_index) const {
  1237. ERR_FAIL_INDEX_V(p_index, (int)mesh_instances.size(), Variant());
  1238. return mesh_instances[p_index].slice;
  1239. }
  1240. void LightmapperCPU::add_albedo_texture(Ref<Texture> p_texture) {
  1241. if (p_texture.is_null()) {
  1242. return;
  1243. }
  1244. RID texture_rid = p_texture->get_rid();
  1245. if (!texture_rid.is_valid() || albedo_textures.has(texture_rid)) {
  1246. return;
  1247. }
  1248. Ref<Image> texture_data = p_texture->get_data();
  1249. if (texture_data.is_null()) {
  1250. return;
  1251. }
  1252. if (texture_data->is_compressed()) {
  1253. texture_data->decompress();
  1254. }
  1255. texture_data->convert(Image::FORMAT_RGBA8);
  1256. albedo_textures.insert(texture_rid, texture_data);
  1257. }
  1258. void LightmapperCPU::add_emission_texture(Ref<Texture> p_texture) {
  1259. if (p_texture.is_null()) {
  1260. return;
  1261. }
  1262. RID texture_rid = p_texture->get_rid();
  1263. if (!texture_rid.is_valid() || emission_textures.has(texture_rid)) {
  1264. return;
  1265. }
  1266. Ref<Image> texture_data = p_texture->get_data();
  1267. if (texture_data.is_null()) {
  1268. return;
  1269. }
  1270. if (texture_data->is_compressed()) {
  1271. texture_data->decompress();
  1272. }
  1273. texture_data->convert(Image::FORMAT_RGBH);
  1274. emission_textures.insert(texture_rid, texture_data);
  1275. }
  1276. void LightmapperCPU::add_mesh(const MeshData &p_mesh, Vector2i p_size) {
  1277. ERR_FAIL_COND(p_mesh.points.size() == 0);
  1278. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.uv2.size());
  1279. ERR_FAIL_COND(p_mesh.points.size() != p_mesh.normal.size());
  1280. ERR_FAIL_COND(!p_mesh.uv.empty() && p_mesh.points.size() != p_mesh.uv.size());
  1281. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.albedo.size());
  1282. ERR_FAIL_COND(p_mesh.surface_facecounts.size() != p_mesh.emission.size());
  1283. MeshInstance mi;
  1284. mi.data = p_mesh;
  1285. mi.size = p_size;
  1286. mi.generate_lightmap = true;
  1287. mi.cast_shadows = true;
  1288. mi.node_name = "";
  1289. Dictionary userdata = p_mesh.userdata;
  1290. if (userdata.has("cast_shadows")) {
  1291. mi.cast_shadows = userdata["cast_shadows"];
  1292. }
  1293. if (userdata.has("generate_lightmap")) {
  1294. mi.generate_lightmap = userdata["generate_lightmap"];
  1295. }
  1296. if (userdata.has("node_name")) {
  1297. mi.node_name = userdata["node_name"];
  1298. }
  1299. mesh_instances.push_back(mi);
  1300. }
  1301. void LightmapperCPU::add_directional_light(bool p_bake_direct, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_multiplier) {
  1302. Light l;
  1303. l.type = LIGHT_TYPE_DIRECTIONAL;
  1304. l.direction = p_direction;
  1305. l.color = p_color;
  1306. l.energy = p_energy;
  1307. l.indirect_multiplier = p_indirect_multiplier;
  1308. l.bake_direct = p_bake_direct;
  1309. lights.push_back(l);
  1310. }
  1311. 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) {
  1312. Light l;
  1313. l.type = LIGHT_TYPE_OMNI;
  1314. l.position = p_position;
  1315. l.range = p_range;
  1316. l.attenuation = p_attenuation;
  1317. l.color = p_color;
  1318. l.energy = p_energy;
  1319. l.indirect_multiplier = p_indirect_multiplier;
  1320. l.bake_direct = p_bake_direct;
  1321. lights.push_back(l);
  1322. }
  1323. 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) {
  1324. Light l;
  1325. l.type = LIGHT_TYPE_SPOT;
  1326. l.position = p_position;
  1327. l.direction = p_direction;
  1328. l.range = p_range;
  1329. l.attenuation = p_attenuation;
  1330. l.spot_angle = Math::deg2rad(p_spot_angle);
  1331. l.spot_attenuation = p_spot_attenuation;
  1332. l.color = p_color;
  1333. l.energy = p_energy;
  1334. l.indirect_multiplier = p_indirect_multiplier;
  1335. l.bake_direct = p_bake_direct;
  1336. lights.push_back(l);
  1337. }
  1338. LightmapperCPU::LightmapperCPU() {
  1339. thread_progress = 0;
  1340. thread_cancelled = false;
  1341. }