baked_light_baker.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500
  1. /*************************************************************************/
  2. /* baked_light_baker.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "baked_light_baker.h"
  31. #include "editor/editor_node.h"
  32. #include "editor/editor_settings.h"
  33. #include "io/marshalls.h"
  34. #include <stdlib.h>
  35. #include <cmath>
  36. void baked_light_baker_add_64f(double *dst, double value);
  37. void baked_light_baker_add_64i(int64_t *dst, int64_t value);
  38. //-separar en 2 testuras?
  39. //*mejorar performance y threads
  40. //*modos lineales
  41. //*saturacion
  42. _FORCE_INLINE_ static uint64_t get_uv_normal_bit(const Vector3 &p_vector) {
  43. int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 6.0 / Math_PI + 0.5));
  44. if (lat == 0) {
  45. return 60;
  46. } else if (lat == 6) {
  47. return 61;
  48. }
  49. int lon = Math::fast_ftoi(Math::floor((Math_PI + Math::atan2(p_vector.x, p_vector.z)) * 12.0 / (Math_PI * 2.0) + 0.5)) % 12;
  50. return lon + (lat - 1) * 12;
  51. }
  52. _FORCE_INLINE_ static Vector3 get_bit_normal(int p_bit) {
  53. if (p_bit == 61) {
  54. return Vector3(0, 1, 0);
  55. } else if (p_bit == 62) {
  56. return Vector3(0, -1, 0);
  57. }
  58. float latang = ((p_bit / 12) + 1) * Math_PI / 6.0;
  59. Vector2 latv(Math::sin(latang), Math::cos(latang));
  60. float lonang = ((p_bit % 12) * Math_PI * 2.0 / 12.0) - Math_PI;
  61. Vector2 lonv(Math::sin(lonang), Math::cos(lonang));
  62. return Vector3(lonv.x * latv.x, latv.y, lonv.y * latv.x).normalized();
  63. }
  64. BakedLightBaker::MeshTexture *BakedLightBaker::_get_mat_tex(const Ref<Texture> &p_tex) {
  65. if (!tex_map.has(p_tex)) {
  66. Ref<ImageTexture> imgtex = p_tex;
  67. if (imgtex.is_null())
  68. return NULL;
  69. Image image = imgtex->get_data();
  70. if (image.empty())
  71. return NULL;
  72. if (image.get_format() != Image::FORMAT_RGBA) {
  73. if (image.get_format() > Image::FORMAT_INDEXED_ALPHA) {
  74. Error err = image.decompress();
  75. if (err)
  76. return NULL;
  77. }
  78. if (image.get_format() != Image::FORMAT_RGBA)
  79. image.convert(Image::FORMAT_RGBA);
  80. }
  81. if (imgtex->get_flags() & Texture::FLAG_CONVERT_TO_LINEAR) {
  82. Image copy = image;
  83. copy.srgb_to_linear();
  84. image = copy;
  85. }
  86. DVector<uint8_t> dvt = image.get_data();
  87. DVector<uint8_t>::Read r = dvt.read();
  88. MeshTexture mt;
  89. mt.tex_w = image.get_width();
  90. mt.tex_h = image.get_height();
  91. int len = image.get_width() * image.get_height() * 4;
  92. mt.tex.resize(len);
  93. copymem(mt.tex.ptr(), r.ptr(), len);
  94. textures.push_back(mt);
  95. tex_map[p_tex] = &textures.back()->get();
  96. }
  97. return tex_map[p_tex];
  98. }
  99. void BakedLightBaker::_add_mesh(const Ref<Mesh> &p_mesh, const Ref<Material> &p_mat_override, const Transform &p_xform, int p_baked_texture) {
  100. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  101. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
  102. continue;
  103. Ref<Material> mat = p_mat_override.is_valid() ? p_mat_override : p_mesh->surface_get_material(i);
  104. MeshMaterial *matptr = NULL;
  105. int baked_tex = p_baked_texture;
  106. if (mat.is_valid()) {
  107. if (!mat_map.has(mat)) {
  108. MeshMaterial mm;
  109. Ref<FixedMaterial> fm = mat;
  110. if (fm.is_valid()) {
  111. //fixed route
  112. mm.diffuse.color = fm->get_parameter(FixedMaterial::PARAM_DIFFUSE);
  113. if (linear_color)
  114. mm.diffuse.color = mm.diffuse.color.to_linear();
  115. mm.diffuse.tex = _get_mat_tex(fm->get_texture(FixedMaterial::PARAM_DIFFUSE));
  116. mm.specular.color = fm->get_parameter(FixedMaterial::PARAM_SPECULAR);
  117. if (linear_color)
  118. mm.specular.color = mm.specular.color.to_linear();
  119. mm.specular.tex = _get_mat_tex(fm->get_texture(FixedMaterial::PARAM_SPECULAR));
  120. } else {
  121. mm.diffuse.color = Color(1, 1, 1, 1);
  122. mm.diffuse.tex = NULL;
  123. mm.specular.color = Color(0, 0, 0, 1);
  124. mm.specular.tex = NULL;
  125. }
  126. materials.push_back(mm);
  127. mat_map[mat] = &materials.back()->get();
  128. }
  129. matptr = mat_map[mat];
  130. }
  131. int facecount = 0;
  132. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  133. facecount = p_mesh->surface_get_array_index_len(i);
  134. } else {
  135. facecount = p_mesh->surface_get_array_len(i);
  136. }
  137. ERR_CONTINUE((facecount == 0 || (facecount % 3) != 0));
  138. facecount /= 3;
  139. int tbase = triangles.size();
  140. triangles.resize(facecount + tbase);
  141. Array a = p_mesh->surface_get_arrays(i);
  142. DVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  143. DVector<Vector3>::Read vr = vertices.read();
  144. DVector<Vector2> uv;
  145. DVector<Vector2>::Read uvr;
  146. DVector<Vector2> uv2;
  147. DVector<Vector2>::Read uv2r;
  148. DVector<Vector3> normal;
  149. DVector<Vector3>::Read normalr;
  150. bool read_uv = false;
  151. bool read_normal = false;
  152. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV) {
  153. uv = a[Mesh::ARRAY_TEX_UV];
  154. uvr = uv.read();
  155. read_uv = true;
  156. if (mat.is_valid() && mat->get_flag(Material::FLAG_LIGHTMAP_ON_UV2) && p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV2) {
  157. uv2 = a[Mesh::ARRAY_TEX_UV2];
  158. uv2r = uv2.read();
  159. } else {
  160. uv2r = uv.read();
  161. if (baked_light->get_transfer_lightmaps_only_to_uv2()) {
  162. baked_tex = -1;
  163. }
  164. }
  165. }
  166. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_NORMAL) {
  167. normal = a[Mesh::ARRAY_NORMAL];
  168. normalr = normal.read();
  169. read_normal = true;
  170. }
  171. Matrix3 normal_xform = p_xform.basis.inverse().transposed();
  172. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  173. DVector<int> indices = a[Mesh::ARRAY_INDEX];
  174. DVector<int>::Read ir = indices.read();
  175. for (int i = 0; i < facecount; i++) {
  176. Triangle &t = triangles[tbase + i];
  177. t.vertices[0] = p_xform.xform(vr[ir[i * 3 + 0]]);
  178. t.vertices[1] = p_xform.xform(vr[ir[i * 3 + 1]]);
  179. t.vertices[2] = p_xform.xform(vr[ir[i * 3 + 2]]);
  180. t.material = matptr;
  181. t.baked_texture = baked_tex;
  182. if (read_uv) {
  183. t.uvs[0] = uvr[ir[i * 3 + 0]];
  184. t.uvs[1] = uvr[ir[i * 3 + 1]];
  185. t.uvs[2] = uvr[ir[i * 3 + 2]];
  186. t.bake_uvs[0] = uv2r[ir[i * 3 + 0]];
  187. t.bake_uvs[1] = uv2r[ir[i * 3 + 1]];
  188. t.bake_uvs[2] = uv2r[ir[i * 3 + 2]];
  189. }
  190. if (read_normal) {
  191. t.normals[0] = normal_xform.xform(normalr[ir[i * 3 + 0]]).normalized();
  192. t.normals[1] = normal_xform.xform(normalr[ir[i * 3 + 1]]).normalized();
  193. t.normals[2] = normal_xform.xform(normalr[ir[i * 3 + 2]]).normalized();
  194. }
  195. }
  196. } else {
  197. for (int i = 0; i < facecount; i++) {
  198. Triangle &t = triangles[tbase + i];
  199. t.vertices[0] = p_xform.xform(vr[i * 3 + 0]);
  200. t.vertices[1] = p_xform.xform(vr[i * 3 + 1]);
  201. t.vertices[2] = p_xform.xform(vr[i * 3 + 2]);
  202. t.material = matptr;
  203. t.baked_texture = baked_tex;
  204. if (read_uv) {
  205. t.uvs[0] = uvr[i * 3 + 0];
  206. t.uvs[1] = uvr[i * 3 + 1];
  207. t.uvs[2] = uvr[i * 3 + 2];
  208. t.bake_uvs[0] = uv2r[i * 3 + 0];
  209. t.bake_uvs[1] = uv2r[i * 3 + 1];
  210. t.bake_uvs[2] = uv2r[i * 3 + 2];
  211. }
  212. if (read_normal) {
  213. t.normals[0] = normal_xform.xform(normalr[i * 3 + 0]).normalized();
  214. t.normals[1] = normal_xform.xform(normalr[i * 3 + 1]).normalized();
  215. t.normals[2] = normal_xform.xform(normalr[i * 3 + 2]).normalized();
  216. }
  217. }
  218. }
  219. }
  220. }
  221. void BakedLightBaker::_parse_geometry(Node *p_node) {
  222. if (p_node->cast_to<MeshInstance>()) {
  223. MeshInstance *meshi = p_node->cast_to<MeshInstance>();
  224. Ref<Mesh> mesh = meshi->get_mesh();
  225. if (mesh.is_valid()) {
  226. _add_mesh(mesh, meshi->get_material_override(), base_inv * meshi->get_global_transform(), meshi->get_baked_light_texture_id());
  227. }
  228. } else if (p_node->cast_to<Light>()) {
  229. Light *dl = p_node->cast_to<Light>();
  230. if (dl->get_bake_mode() != Light::BAKE_MODE_DISABLED) {
  231. LightData dirl;
  232. dirl.type = VS::LightType(dl->get_light_type());
  233. dirl.diffuse = dl->get_color(DirectionalLight::COLOR_DIFFUSE);
  234. dirl.specular = dl->get_color(DirectionalLight::COLOR_SPECULAR);
  235. if (linear_color)
  236. dirl.diffuse = dirl.diffuse.to_linear();
  237. if (linear_color)
  238. dirl.specular = dirl.specular.to_linear();
  239. dirl.energy = dl->get_parameter(DirectionalLight::PARAM_ENERGY);
  240. dirl.pos = dl->get_global_transform().origin;
  241. dirl.up = dl->get_global_transform().basis.get_axis(1).normalized();
  242. dirl.left = dl->get_global_transform().basis.get_axis(0).normalized();
  243. dirl.dir = -dl->get_global_transform().basis.get_axis(2).normalized();
  244. dirl.spot_angle = dl->get_parameter(DirectionalLight::PARAM_SPOT_ANGLE);
  245. dirl.spot_attenuation = dl->get_parameter(DirectionalLight::PARAM_SPOT_ATTENUATION);
  246. dirl.attenuation = dl->get_parameter(DirectionalLight::PARAM_ATTENUATION);
  247. dirl.darkening = dl->get_parameter(DirectionalLight::PARAM_SHADOW_DARKENING);
  248. dirl.radius = dl->get_parameter(DirectionalLight::PARAM_RADIUS);
  249. dirl.bake_direct = dl->get_bake_mode() == Light::BAKE_MODE_FULL;
  250. dirl.rays_thrown = 0;
  251. dirl.bake_shadow = dl->get_bake_mode() == Light::BAKE_MODE_INDIRECT_AND_SHADOWS;
  252. lights.push_back(dirl);
  253. }
  254. } else if (p_node->cast_to<Spatial>()) {
  255. Spatial *sp = p_node->cast_to<Spatial>();
  256. Array arr = p_node->call("_get_baked_light_meshes");
  257. for (int i = 0; i < arr.size(); i += 2) {
  258. Transform xform = arr[i];
  259. Ref<Mesh> mesh = arr[i + 1];
  260. _add_mesh(mesh, Ref<Material>(), base_inv * (sp->get_global_transform() * xform));
  261. }
  262. }
  263. for (int i = 0; i < p_node->get_child_count(); i++) {
  264. _parse_geometry(p_node->get_child(i));
  265. }
  266. }
  267. void BakedLightBaker::_fix_lights() {
  268. total_light_area = 0;
  269. for (int i = 0; i < lights.size(); i++) {
  270. LightData &dl = lights[i];
  271. switch (dl.type) {
  272. case VS::LIGHT_DIRECTIONAL: {
  273. float up_max = -1e10;
  274. float dir_max = -1e10;
  275. float left_max = -1e10;
  276. float up_min = 1e10;
  277. float dir_min = 1e10;
  278. float left_min = 1e10;
  279. for (int j = 0; j < triangles.size(); j++) {
  280. for (int k = 0; k < 3; k++) {
  281. Vector3 v = triangles[j].vertices[k];
  282. float up_d = dl.up.dot(v);
  283. float dir_d = dl.dir.dot(v);
  284. float left_d = dl.left.dot(v);
  285. if (up_d > up_max)
  286. up_max = up_d;
  287. if (up_d < up_min)
  288. up_min = up_d;
  289. if (left_d > left_max)
  290. left_max = left_d;
  291. if (left_d < left_min)
  292. left_min = left_d;
  293. if (dir_d > dir_max)
  294. dir_max = dir_d;
  295. if (dir_d < dir_min)
  296. dir_min = dir_d;
  297. }
  298. }
  299. //make a center point, then the upvector and leftvector
  300. dl.pos = dl.left * (left_max + left_min) * 0.5 + dl.up * (up_max + up_min) * 0.5 + dl.dir * (dir_min - (dir_max - dir_min));
  301. dl.left *= (left_max - left_min) * 0.5;
  302. dl.up *= (up_max - up_min) * 0.5;
  303. dl.length = (dir_max - dir_min) * 10; //arbitrary number to keep it in scale
  304. dl.area = dl.left.length() * 2 * dl.up.length() * 2;
  305. dl.constant = 1.0 / dl.area;
  306. } break;
  307. case VS::LIGHT_OMNI:
  308. case VS::LIGHT_SPOT: {
  309. dl.attenuation_table.resize(ATTENUATION_CURVE_LEN);
  310. for (int j = 0; j < ATTENUATION_CURVE_LEN; j++) {
  311. dl.attenuation_table[j] = 1.0 - Math::pow(j / float(ATTENUATION_CURVE_LEN), dl.attenuation);
  312. float falloff = j * dl.radius / float(ATTENUATION_CURVE_LEN);
  313. if (falloff == 0)
  314. falloff = 0.000001;
  315. float intensity = 4 * Math_PI * (falloff * falloff);
  316. //dl.attenuation_table[j]*=falloff*falloff;
  317. dl.attenuation_table[j] *= 1.0 / (3.0 / intensity);
  318. }
  319. if (dl.type == VS::LIGHT_OMNI) {
  320. dl.area = 4.0 * Math_PI * pow(dl.radius, 2.0f);
  321. dl.constant = 1.0 / 3.5;
  322. } else {
  323. float r = Math::tan(Math::deg2rad(dl.spot_angle)) * dl.radius;
  324. float c = 1.0 - (Math::deg2rad(dl.spot_angle) * 0.5 + 0.5);
  325. dl.constant = 1.0 / 3.5;
  326. dl.constant *= 1.0 / c;
  327. dl.area = Math_PI * r * r * c;
  328. }
  329. } break;
  330. }
  331. total_light_area += dl.area;
  332. }
  333. }
  334. BakedLightBaker::BVH *BakedLightBaker::_parse_bvh(BVH **p_children, int p_size, int p_depth, int &max_depth) {
  335. if (p_depth > max_depth) {
  336. max_depth = p_depth;
  337. }
  338. if (p_size == 1) {
  339. return p_children[0];
  340. } else if (p_size == 0) {
  341. return NULL;
  342. }
  343. AABB aabb;
  344. aabb = p_children[0]->aabb;
  345. for (int i = 1; i < p_size; i++) {
  346. aabb.merge_with(p_children[i]->aabb);
  347. }
  348. int li = aabb.get_longest_axis_index();
  349. switch (li) {
  350. case Vector3::AXIS_X: {
  351. SortArray<BVH *, BVHCmpX> sort_x;
  352. sort_x.nth_element(0, p_size, p_size / 2, p_children);
  353. //sort_x.sort(&p_bb[p_from],p_size);
  354. } break;
  355. case Vector3::AXIS_Y: {
  356. SortArray<BVH *, BVHCmpY> sort_y;
  357. sort_y.nth_element(0, p_size, p_size / 2, p_children);
  358. //sort_y.sort(&p_bb[p_from],p_size);
  359. } break;
  360. case Vector3::AXIS_Z: {
  361. SortArray<BVH *, BVHCmpZ> sort_z;
  362. sort_z.nth_element(0, p_size, p_size / 2, p_children);
  363. //sort_z.sort(&p_bb[p_from],p_size);
  364. } break;
  365. }
  366. BVH *left = _parse_bvh(p_children, p_size / 2, p_depth + 1, max_depth);
  367. BVH *right = _parse_bvh(&p_children[p_size / 2], p_size - p_size / 2, p_depth + 1, max_depth);
  368. BVH *_new = memnew(BVH);
  369. _new->aabb = aabb;
  370. _new->center = aabb.pos + aabb.size * 0.5;
  371. _new->children[0] = left;
  372. _new->children[1] = right;
  373. _new->leaf = NULL;
  374. return _new;
  375. }
  376. void BakedLightBaker::_make_bvh() {
  377. Vector<BVH *> bases;
  378. bases.resize(triangles.size());
  379. int max_depth = 0;
  380. for (int i = 0; i < triangles.size(); i++) {
  381. bases[i] = memnew(BVH);
  382. bases[i]->leaf = &triangles[i];
  383. bases[i]->aabb.pos = triangles[i].vertices[0];
  384. bases[i]->aabb.expand_to(triangles[i].vertices[1]);
  385. bases[i]->aabb.expand_to(triangles[i].vertices[2]);
  386. triangles[i].aabb = bases[i]->aabb;
  387. bases[i]->center = bases[i]->aabb.pos + bases[i]->aabb.size * 0.5;
  388. }
  389. bvh = _parse_bvh(bases.ptr(), bases.size(), 1, max_depth);
  390. ray_stack = memnew_arr(uint32_t, max_depth);
  391. bvh_stack = memnew_arr(BVH *, max_depth);
  392. bvh_depth = max_depth;
  393. }
  394. void BakedLightBaker::_octree_insert(int p_octant, Triangle *p_triangle, int p_depth) {
  395. uint32_t *stack = octant_stack;
  396. uint32_t *ptr_stack = octantptr_stack;
  397. Octant *octants = octant_pool.ptr();
  398. stack[0] = 0;
  399. ptr_stack[0] = 0;
  400. int stack_pos = 0;
  401. while (true) {
  402. Octant *octant = &octants[ptr_stack[stack_pos]];
  403. if (stack[stack_pos] < 8) {
  404. int i = stack[stack_pos];
  405. stack[stack_pos]++;
  406. //fit_aabb=fit_aabb.grow(bvh->aabb.size.x*0.0001);
  407. int child_idx = octant->children[i];
  408. bool encloses;
  409. if (!child_idx) {
  410. AABB aabb = octant->aabb;
  411. aabb.size *= 0.5;
  412. if (i & 1)
  413. aabb.pos.x += aabb.size.x;
  414. if (i & 2)
  415. aabb.pos.y += aabb.size.y;
  416. if (i & 4)
  417. aabb.pos.z += aabb.size.z;
  418. aabb.grow_by(cell_size * octree_extra_margin);
  419. if (!aabb.intersects(p_triangle->aabb))
  420. continue;
  421. encloses = aabb.grow(cell_size * -octree_extra_margin * 2.0).encloses(p_triangle->aabb);
  422. if (!encloses && !Face3(p_triangle->vertices[0], p_triangle->vertices[1], p_triangle->vertices[2]).intersects_aabb2(aabb))
  423. continue;
  424. } else {
  425. Octant *child = &octants[child_idx];
  426. AABB aabb = child->aabb;
  427. aabb.grow_by(cell_size * octree_extra_margin);
  428. if (!aabb.intersects(p_triangle->aabb))
  429. continue;
  430. encloses = aabb.grow(cell_size * -octree_extra_margin * 2.0).encloses(p_triangle->aabb);
  431. if (!encloses && !Face3(p_triangle->vertices[0], p_triangle->vertices[1], p_triangle->vertices[2]).intersects_aabb2(aabb))
  432. continue;
  433. }
  434. if (encloses)
  435. stack[stack_pos] = 8; // quick and dirty opt
  436. if (!child_idx) {
  437. if (octant_pool_size == octant_pool.size()) {
  438. octant_pool.resize(octant_pool_size + OCTANT_POOL_CHUNK);
  439. octants = octant_pool.ptr();
  440. octant = &octants[ptr_stack[stack_pos]];
  441. }
  442. child_idx = octant_pool_size++;
  443. octant->children[i] = child_idx;
  444. Octant *child = &octants[child_idx];
  445. child->aabb = octant->aabb;
  446. child->texture_x = 0;
  447. child->texture_y = 0;
  448. child->aabb.size *= 0.5;
  449. if (i & 1)
  450. child->aabb.pos.x += child->aabb.size.x;
  451. if (i & 2)
  452. child->aabb.pos.y += child->aabb.size.y;
  453. if (i & 4)
  454. child->aabb.pos.z += child->aabb.size.z;
  455. child->full_accum[0] = 0;
  456. child->full_accum[1] = 0;
  457. child->full_accum[2] = 0;
  458. child->sampler_ofs = 0;
  459. if (stack_pos == octree_depth - 1) {
  460. child->leaf = true;
  461. child->offset[0] = child->aabb.pos.x + child->aabb.size.x * 0.5;
  462. child->offset[1] = child->aabb.pos.y + child->aabb.size.y * 0.5;
  463. child->offset[2] = child->aabb.pos.z + child->aabb.size.z * 0.5;
  464. child->next_leaf = leaf_list;
  465. for (int ci = 0; ci < 8; ci++) {
  466. child->normal_accum[ci][0] = 0;
  467. child->normal_accum[ci][1] = 0;
  468. child->normal_accum[ci][2] = 0;
  469. }
  470. child->bake_neighbour = 0;
  471. child->first_neighbour = true;
  472. leaf_list = child_idx;
  473. cell_count++;
  474. for (int ci = 0; ci < 8; ci++) {
  475. child->light_accum[ci][0] = 0;
  476. child->light_accum[ci][1] = 0;
  477. child->light_accum[ci][2] = 0;
  478. }
  479. child->parent = ptr_stack[stack_pos];
  480. } else {
  481. child->leaf = false;
  482. for (int j = 0; j < 8; j++) {
  483. child->children[j] = 0;
  484. }
  485. }
  486. }
  487. if (!octants[child_idx].leaf) {
  488. stack_pos++;
  489. stack[stack_pos] = 0;
  490. ptr_stack[stack_pos] = child_idx;
  491. } else {
  492. Octant *child = &octants[child_idx];
  493. Vector3 n = Plane(p_triangle->vertices[0], p_triangle->vertices[1], p_triangle->vertices[2]).normal;
  494. for (int ci = 0; ci < 8; ci++) {
  495. Vector3 pos = child->aabb.pos;
  496. if (ci & 1)
  497. pos.x += child->aabb.size.x;
  498. if (ci & 2)
  499. pos.y += child->aabb.size.y;
  500. if (ci & 4)
  501. pos.z += child->aabb.size.z;
  502. pos.x = floor((pos.x + cell_size * 0.5) / cell_size);
  503. pos.y = floor((pos.y + cell_size * 0.5) / cell_size);
  504. pos.z = floor((pos.z + cell_size * 0.5) / cell_size);
  505. {
  506. Map<Vector3, Vector3>::Element *E = endpoint_normal.find(pos);
  507. if (!E) {
  508. endpoint_normal[pos] = n;
  509. } else {
  510. E->get() += n;
  511. }
  512. }
  513. {
  514. uint64_t bit = get_uv_normal_bit(n);
  515. Map<Vector3, uint64_t>::Element *E = endpoint_normal_bits.find(pos);
  516. if (!E) {
  517. endpoint_normal_bits[pos] = (1 << bit);
  518. } else {
  519. E->get() |= (1 << bit);
  520. }
  521. }
  522. }
  523. }
  524. } else {
  525. stack_pos--;
  526. if (stack_pos < 0)
  527. break;
  528. }
  529. }
  530. }
  531. void BakedLightBaker::_make_octree() {
  532. AABB base = bvh->aabb;
  533. float lal = base.get_longest_axis_size();
  534. //must be square because we want square blocks
  535. base.size.x = lal;
  536. base.size.y = lal;
  537. base.size.z = lal;
  538. base.grow_by(lal * 0.001); //for precision
  539. octree_aabb = base;
  540. cell_size = base.size.x;
  541. for (int i = 0; i < octree_depth; i++)
  542. cell_size /= 2.0;
  543. octant_stack = memnew_arr(uint32_t, octree_depth * 2);
  544. octantptr_stack = memnew_arr(uint32_t, octree_depth * 2);
  545. octant_pool.resize(OCTANT_POOL_CHUNK);
  546. octant_pool_size = 1;
  547. Octant *root = octant_pool.ptr();
  548. root->leaf = false;
  549. root->aabb = octree_aabb;
  550. root->parent = -1;
  551. for (int i = 0; i < 8; i++)
  552. root->children[i] = 0;
  553. EditorProgress ep("bake_octree", vformat(TTR("Parsing %d Triangles:"), triangles.size()), triangles.size());
  554. for (int i = 0; i < triangles.size(); i++) {
  555. _octree_insert(0, &triangles[i], octree_depth - 1);
  556. if ((i % 1000) == 0) {
  557. ep.step(TTR("Triangle #") + itos(i), i);
  558. }
  559. }
  560. {
  561. uint32_t oct_idx = leaf_list;
  562. Octant *octants = octant_pool.ptr();
  563. while (oct_idx) {
  564. BakedLightBaker::Octant *oct = &octants[oct_idx];
  565. for (int ci = 0; ci < 8; ci++) {
  566. Vector3 pos = oct->aabb.pos;
  567. if (ci & 1)
  568. pos.x += oct->aabb.size.x;
  569. if (ci & 2)
  570. pos.y += oct->aabb.size.y;
  571. if (ci & 4)
  572. pos.z += oct->aabb.size.z;
  573. pos.x = floor((pos.x + cell_size * 0.5) / cell_size);
  574. pos.y = floor((pos.y + cell_size * 0.5) / cell_size);
  575. pos.z = floor((pos.z + cell_size * 0.5) / cell_size);
  576. {
  577. Map<Vector3, Vector3>::Element *E = endpoint_normal.find(pos);
  578. if (!E) {
  579. //?
  580. print_line("lolwut?");
  581. } else {
  582. Vector3 n = E->get().normalized();
  583. oct->normal_accum[ci][0] = n.x;
  584. oct->normal_accum[ci][1] = n.y;
  585. oct->normal_accum[ci][2] = n.z;
  586. }
  587. }
  588. {
  589. Map<Vector3, uint64_t>::Element *E = endpoint_normal_bits.find(pos);
  590. if (!E) {
  591. //?
  592. print_line("lolwut?");
  593. } else {
  594. float max_aper = 0;
  595. for (uint64_t i = 0; i < 62; i++) {
  596. if (!(E->get() & (1 << i)))
  597. continue;
  598. Vector3 ang_i = get_bit_normal(i);
  599. for (uint64_t j = 0; j < 62; j++) {
  600. if (i == j)
  601. continue;
  602. if (!(E->get() & (1 << j)))
  603. continue;
  604. Vector3 ang_j = get_bit_normal(j);
  605. float ang = Math::acos(ang_i.dot(ang_j));
  606. if (ang > max_aper)
  607. max_aper = ang;
  608. }
  609. }
  610. if (max_aper > 0.75 * Math_PI) {
  611. //angle too wide prevent problems and forget
  612. oct->normal_accum[ci][0] = 0;
  613. oct->normal_accum[ci][1] = 0;
  614. oct->normal_accum[ci][2] = 0;
  615. }
  616. }
  617. }
  618. }
  619. oct_idx = oct->next_leaf;
  620. }
  621. }
  622. }
  623. void BakedLightBaker::_plot_light(ThreadStack &thread_stack, const Vector3 &p_plot_pos, const AABB &p_plot_aabb, const Color &p_light, const Color &p_tint_light, bool p_only_full, const Plane &p_plane) {
  624. //stackless version
  625. uint32_t *stack = thread_stack.octant_stack;
  626. uint32_t *ptr_stack = thread_stack.octantptr_stack;
  627. Octant *octants = octant_pool.ptr();
  628. stack[0] = 0;
  629. ptr_stack[0] = 0;
  630. int stack_pos = 0;
  631. while (true) {
  632. Octant &octant = octants[ptr_stack[stack_pos]];
  633. if (stack[stack_pos] == 0) {
  634. Vector3 pos = octant.aabb.pos + octant.aabb.size * 0.5;
  635. float md = 1 << (octree_depth - stack_pos);
  636. float r = cell_size * plot_size * md;
  637. float div = 1.0 / (md * md * md);
  638. //div=1.0;
  639. float d = p_plot_pos.distance_to(pos);
  640. if ((p_plane.distance_to(pos) > -cell_size * 1.75 * md) && d <= r) {
  641. float intensity = 1.0 - (d / r) * (d / r); //not gauss but..
  642. baked_light_baker_add_64f(&octant.full_accum[0], p_tint_light.r * intensity * div);
  643. baked_light_baker_add_64f(&octant.full_accum[1], p_tint_light.g * intensity * div);
  644. baked_light_baker_add_64f(&octant.full_accum[2], p_tint_light.b * intensity * div);
  645. }
  646. }
  647. if (octant.leaf) {
  648. //if (p_plane.normal.dot(octant.aabb.get_support(p_plane.normal)) < p_plane.d-CMP_EPSILON) { //octants behind are no go
  649. if (!p_only_full) {
  650. float r = cell_size * plot_size;
  651. for (int i = 0; i < 8; i++) {
  652. Vector3 pos = octant.aabb.pos;
  653. if (i & 1)
  654. pos.x += octant.aabb.size.x;
  655. if (i & 2)
  656. pos.y += octant.aabb.size.y;
  657. if (i & 4)
  658. pos.z += octant.aabb.size.z;
  659. float d = p_plot_pos.distance_to(pos);
  660. if ((p_plane.distance_to(pos) > -cell_size * 1.75) && d <= r) {
  661. float intensity = 1.0 - (d / r) * (d / r); //not gauss but..
  662. if (edge_damp > 0) {
  663. Vector3 normal = Vector3(octant.normal_accum[i][0], octant.normal_accum[i][1], octant.normal_accum[i][2]);
  664. if (normal.x > 0 || normal.y > 0 || normal.z > 0) {
  665. float damp = Math::abs(p_plane.normal.dot(normal));
  666. intensity *= pow(damp, edge_damp);
  667. }
  668. }
  669. //intensity*=1.0-Math::abs(p_plane.distance_to(pos))/(plot_size*cell_size);
  670. //intensity = Math::cos(d*Math_PI*0.5/r);
  671. baked_light_baker_add_64f(&octant.light_accum[i][0], p_light.r * intensity);
  672. baked_light_baker_add_64f(&octant.light_accum[i][1], p_light.g * intensity);
  673. baked_light_baker_add_64f(&octant.light_accum[i][2], p_light.b * intensity);
  674. }
  675. }
  676. }
  677. stack_pos--;
  678. } else if (stack[stack_pos] < 8) {
  679. int i = stack[stack_pos];
  680. stack[stack_pos]++;
  681. if (!octant.children[i]) {
  682. continue;
  683. }
  684. Octant &child = octants[octant.children[i]];
  685. if (!child.aabb.intersects(p_plot_aabb))
  686. continue;
  687. if (child.aabb.encloses(p_plot_aabb)) {
  688. stack[stack_pos] = 8; //don't test the rest
  689. }
  690. stack_pos++;
  691. stack[stack_pos] = 0;
  692. ptr_stack[stack_pos] = octant.children[i];
  693. } else {
  694. stack_pos--;
  695. if (stack_pos < 0)
  696. break;
  697. }
  698. }
  699. }
  700. float BakedLightBaker::_throw_ray(ThreadStack &thread_stack, bool p_bake_direct, const Vector3 &p_begin, const Vector3 &p_end, float p_rest, const Color &p_light, float *p_att_curve, float p_att_pos, int p_att_curve_len, int p_bounces, bool p_first_bounce, bool p_only_dist) {
  701. uint32_t *stack = thread_stack.ray_stack;
  702. BVH **bstack = thread_stack.bvh_stack;
  703. enum {
  704. TEST_AABB_BIT = 0,
  705. VISIT_LEFT_BIT = 1,
  706. VISIT_RIGHT_BIT = 2,
  707. VISIT_DONE_BIT = 3,
  708. };
  709. Vector3 n = (p_end - p_begin);
  710. float len = n.length();
  711. if (len == 0)
  712. return 0;
  713. n /= len;
  714. real_t d = 1e10;
  715. bool inters = false;
  716. Vector3 r_normal;
  717. Vector3 r_point;
  718. Vector3 end = p_end;
  719. Triangle *triangle = NULL;
  720. //for(int i=0;i<max_depth;i++)
  721. // stack[i]=0;
  722. int level = 0;
  723. //AABB ray_aabb;
  724. //ray_aabb.pos=p_begin;
  725. //ray_aabb.expand_to(p_end);
  726. bstack[0] = bvh;
  727. stack[0] = TEST_AABB_BIT;
  728. while (true) {
  729. uint32_t mode = stack[level];
  730. const BVH &b = *bstack[level];
  731. bool done = false;
  732. switch (mode) {
  733. case TEST_AABB_BIT: {
  734. if (b.leaf) {
  735. Face3 f3(b.leaf->vertices[0], b.leaf->vertices[1], b.leaf->vertices[2]);
  736. Vector3 res;
  737. if (f3.intersects_segment(p_begin, end, &res)) {
  738. float nd = n.dot(res);
  739. if (nd < d) {
  740. d = nd;
  741. r_point = res;
  742. end = res;
  743. len = (p_begin - end).length();
  744. r_normal = f3.get_plane().get_normal();
  745. triangle = b.leaf;
  746. inters = true;
  747. }
  748. }
  749. stack[level] = VISIT_DONE_BIT;
  750. } else {
  751. bool valid = b.aabb.smits_intersect_ray(p_begin, n, 0, len);
  752. //bool valid = b.aabb.intersects_segment(p_begin,p_end);
  753. // bool valid = b.aabb.intersects(ray_aabb);
  754. if (!valid) {
  755. stack[level] = VISIT_DONE_BIT;
  756. } else {
  757. stack[level] = VISIT_LEFT_BIT;
  758. }
  759. }
  760. }
  761. continue;
  762. case VISIT_LEFT_BIT: {
  763. stack[level] = VISIT_RIGHT_BIT;
  764. bstack[level + 1] = b.children[0];
  765. stack[level + 1] = TEST_AABB_BIT;
  766. level++;
  767. }
  768. continue;
  769. case VISIT_RIGHT_BIT: {
  770. stack[level] = VISIT_DONE_BIT;
  771. bstack[level + 1] = b.children[1];
  772. stack[level + 1] = TEST_AABB_BIT;
  773. level++;
  774. }
  775. continue;
  776. case VISIT_DONE_BIT: {
  777. if (level == 0) {
  778. done = true;
  779. break;
  780. } else
  781. level--;
  782. }
  783. continue;
  784. }
  785. if (done)
  786. break;
  787. }
  788. if (inters) {
  789. if (p_only_dist) {
  790. return p_begin.distance_to(r_point);
  791. }
  792. //should check if there is normals first
  793. Vector2 uv;
  794. if (true) {
  795. triangle->get_uv_and_normal(r_point, uv, r_normal);
  796. } else {
  797. }
  798. if (n.dot(r_normal) > 0)
  799. return -1;
  800. if (n.dot(r_normal) > 0)
  801. r_normal = -r_normal;
  802. //ok...
  803. Color diffuse_at_point(0.8, 0.8, 0.8);
  804. Color specular_at_point(0.0, 0.0, 0.0);
  805. float dist = p_begin.distance_to(r_point);
  806. AABB aabb;
  807. aabb.pos = r_point;
  808. aabb.pos -= Vector3(1, 1, 1) * cell_size * plot_size;
  809. aabb.size = Vector3(2, 2, 2) * cell_size * plot_size;
  810. Color res_light = p_light;
  811. float att = 1.0;
  812. float dp = (1.0 - normal_damp) * n.dot(-r_normal) + normal_damp;
  813. if (p_att_curve) {
  814. p_att_pos += dist;
  815. int cpos = Math::fast_ftoi((p_att_pos / p_att_curve_len) * ATTENUATION_CURVE_LEN);
  816. cpos = CLAMP(cpos, 0, ATTENUATION_CURVE_LEN - 1);
  817. att = p_att_curve[cpos];
  818. }
  819. res_light.r *= dp;
  820. res_light.g *= dp;
  821. res_light.b *= dp;
  822. //light is plotted before multiplication with diffuse, this way
  823. //the multiplication can happen with more detail in the shader
  824. if (triangle->material) {
  825. //triangle->get_uv(r_point);
  826. diffuse_at_point = triangle->material->diffuse.get_color(uv);
  827. specular_at_point = triangle->material->specular.get_color(uv);
  828. }
  829. diffuse_at_point.r = res_light.r * diffuse_at_point.r;
  830. diffuse_at_point.g = res_light.g * diffuse_at_point.g;
  831. diffuse_at_point.b = res_light.b * diffuse_at_point.b;
  832. float ret = 1e6;
  833. if (p_bounces > 0) {
  834. p_rest -= dist;
  835. if (p_rest < CMP_EPSILON)
  836. return 0;
  837. if (r_normal == -n)
  838. return 0; //todo change a little
  839. r_point += r_normal * 0.01;
  840. specular_at_point.r = res_light.r * specular_at_point.r;
  841. specular_at_point.g = res_light.g * specular_at_point.g;
  842. specular_at_point.b = res_light.b * specular_at_point.b;
  843. if (use_diffuse && (diffuse_at_point.r > CMP_EPSILON || diffuse_at_point.g > CMP_EPSILON || diffuse_at_point.b > CMP_EPSILON)) {
  844. //diffuse bounce
  845. Vector3 c1 = r_normal.cross(n).normalized();
  846. Vector3 c2 = r_normal.cross(c1).normalized();
  847. double r1 = double(rand()) / RAND_MAX;
  848. double r2 = double(rand()) / RAND_MAX;
  849. double r3 = double(rand()) / RAND_MAX;
  850. #if 0
  851. Vector3 next = - ((c1*(r1-0.5)) + (c2*(r2-0.5)) + (r_normal*(r3-0.5))).normalized()*0.5 + r_normal*0.5;
  852. if (next==Vector3())
  853. next=r_normal;
  854. Vector3 rn=next.normalized();
  855. #else
  856. Vector3 rn = ((c1 * (r1 - 0.5)) + (c2 * (r2 - 0.5)) + (r_normal * r3 * 0.5)).normalized();
  857. #endif
  858. ret = _throw_ray(thread_stack, p_bake_direct, r_point, r_point + rn * p_rest, p_rest, diffuse_at_point, p_att_curve, p_att_pos, p_att_curve_len, p_bounces - 1);
  859. }
  860. if (use_specular && (specular_at_point.r > CMP_EPSILON || specular_at_point.g > CMP_EPSILON || specular_at_point.b > CMP_EPSILON)) {
  861. //specular bounce
  862. //Vector3 c1=r_normal.cross(n).normalized();
  863. //Vector3 c2=r_normal.cross(c1).normalized();
  864. Vector3 rn = n - r_normal * r_normal.dot(n) * 2.0;
  865. _throw_ray(thread_stack, p_bake_direct, r_point, r_point + rn * p_rest, p_rest, specular_at_point, p_att_curve, p_att_pos, p_att_curve_len, p_bounces - 1);
  866. }
  867. }
  868. //specular later
  869. // _plot_light_point(r_point,octree,octree_aabb,p_light);
  870. Color plot_light = res_light.linear_interpolate(diffuse_at_point, tint);
  871. plot_light.r *= att;
  872. plot_light.g *= att;
  873. plot_light.b *= att;
  874. Color tint_light = diffuse_at_point;
  875. tint_light.r *= att;
  876. tint_light.g *= att;
  877. tint_light.b *= att;
  878. bool skip = false;
  879. if (!p_first_bounce || p_bake_direct) {
  880. float r = plot_size * cell_size * 2;
  881. if (dist < r) {
  882. //avoid accumulaiton of light on corners
  883. //plot_light=plot_light.linear_interpolate(Color(0,0,0,0),1.0-sd/plot_size*plot_size);
  884. skip = true;
  885. } else {
  886. Vector3 c1 = r_normal.cross(n).normalized();
  887. Vector3 c2 = r_normal.cross(c1).normalized();
  888. double r1 = double(rand()) / RAND_MAX;
  889. double r2 = double(rand()) / RAND_MAX;
  890. double r3 = double(rand()) / RAND_MAX;
  891. Vector3 rn = ((c1 * (r1 - 0.5)) + (c2 * (r2 - 0.5)) + (r_normal * r3 * 0.25)).normalized();
  892. float d = _throw_ray(thread_stack, p_bake_direct, r_point, r_point + rn * p_rest, p_rest, diffuse_at_point, p_att_curve, p_att_pos, p_att_curve_len, p_bounces - 1, false, true);
  893. r = plot_size * cell_size * ao_radius;
  894. if (d > 0 && d < r) {
  895. //avoid accumulaiton of light on corners
  896. //plot_light=plot_light.linear_interpolate(Color(0,0,0,0),1.0-sd/plot_size*plot_size);
  897. skip = true;
  898. } else {
  899. //plot_light=Color(0,0,0,0);
  900. }
  901. }
  902. }
  903. Plane plane(r_point, r_normal);
  904. if (!skip)
  905. _plot_light(thread_stack, r_point, aabb, plot_light, tint_light, !(!p_first_bounce || p_bake_direct), plane);
  906. return dist;
  907. }
  908. return -1;
  909. }
  910. void BakedLightBaker::_make_octree_texture() {
  911. BakedLightBaker::Octant *octants = octant_pool.ptr();
  912. //find neighbours first, to have a better idea of what amount of space is needed
  913. {
  914. Vector<OctantHash> octant_hashing;
  915. octant_hashing.resize(octant_pool_size);
  916. Vector<uint32_t> hash_table;
  917. int hash_table_size = Math::larger_prime(16384);
  918. hash_table.resize(hash_table_size);
  919. uint32_t *hashptr = hash_table.ptr();
  920. OctantHash *octhashptr = octant_hashing.ptr();
  921. for (int i = 0; i < hash_table_size; i++)
  922. hashptr[i] = 0;
  923. //step 1 add to hash table
  924. uint32_t oct_idx = leaf_list;
  925. while (oct_idx) {
  926. BakedLightBaker::Octant *oct = &octants[oct_idx];
  927. uint64_t base = 0;
  928. Vector3 pos = oct->aabb.pos - octree_aabb.pos; //make sure is always positive
  929. base = int((pos.x + cell_size * 0.5) / cell_size);
  930. base <<= 16;
  931. base |= int((pos.y + cell_size * 0.5) / cell_size);
  932. base <<= 16;
  933. base |= int((pos.z + cell_size * 0.5) / cell_size);
  934. uint32_t hash = HashMapHasherDefault::hash(base);
  935. uint32_t idx = hash % hash_table_size;
  936. octhashptr[oct_idx].next = hashptr[idx];
  937. octhashptr[oct_idx].hash = hash;
  938. octhashptr[oct_idx].value = base;
  939. hashptr[idx] = oct_idx;
  940. oct_idx = oct->next_leaf;
  941. }
  942. //step 2 find neighbours
  943. oct_idx = leaf_list;
  944. int neighbours = 0;
  945. while (oct_idx) {
  946. BakedLightBaker::Octant *oct = &octants[oct_idx];
  947. Vector3 pos = oct->aabb.pos - octree_aabb.pos; //make sure is always positive
  948. pos.x += cell_size;
  949. uint64_t base = 0;
  950. base = int((pos.x + cell_size * 0.5) / cell_size);
  951. base <<= 16;
  952. base |= int((pos.y + cell_size * 0.5) / cell_size);
  953. base <<= 16;
  954. base |= int((pos.z + cell_size * 0.5) / cell_size);
  955. uint32_t hash = HashMapHasherDefault::hash(base);
  956. uint32_t idx = hash % hash_table_size;
  957. uint32_t bucket = hashptr[idx];
  958. while (bucket) {
  959. if (octhashptr[bucket].value == base) {
  960. oct->bake_neighbour = bucket;
  961. octants[bucket].first_neighbour = false;
  962. neighbours++;
  963. break;
  964. }
  965. bucket = octhashptr[bucket].next;
  966. }
  967. oct_idx = oct->next_leaf;
  968. }
  969. print_line("octant with neighbour: " + itos(neighbours));
  970. }
  971. //ok let's try to just create a texture
  972. int otex_w = 256;
  973. while (true) {
  974. uint32_t oct_idx = leaf_list;
  975. int row = 0;
  976. print_line("begin at row " + itos(row));
  977. int longest_line_reused = 0;
  978. int col = 0;
  979. int processed = 0;
  980. //reset
  981. while (oct_idx) {
  982. BakedLightBaker::Octant *oct = &octants[oct_idx];
  983. oct->texture_x = 0;
  984. oct->texture_y = 0;
  985. oct_idx = oct->next_leaf;
  986. }
  987. oct_idx = leaf_list;
  988. //assign
  989. while (oct_idx) {
  990. BakedLightBaker::Octant *oct = &octants[oct_idx];
  991. if (oct->first_neighbour && oct->texture_x == 0 && oct->texture_y == 0) {
  992. //was not processed
  993. uint32_t current_idx = oct_idx;
  994. int reused = 0;
  995. while (current_idx) {
  996. BakedLightBaker::Octant *o = &octants[current_idx];
  997. if (col + 1 >= otex_w) {
  998. col = 0;
  999. row += 4;
  1000. }
  1001. o->texture_x = col;
  1002. o->texture_y = row;
  1003. processed++;
  1004. if (o->bake_neighbour) {
  1005. reused++;
  1006. }
  1007. col += o->bake_neighbour ? 1 : 2; //reuse neighbour
  1008. current_idx = o->bake_neighbour;
  1009. }
  1010. if (reused > longest_line_reused) {
  1011. longest_line_reused = reused;
  1012. }
  1013. }
  1014. oct_idx = oct->next_leaf;
  1015. }
  1016. row += 4;
  1017. if (otex_w < row) {
  1018. otex_w *= 2;
  1019. } else {
  1020. baked_light_texture_w = otex_w;
  1021. baked_light_texture_h = next_power_of_2(row);
  1022. print_line("w: " + itos(otex_w));
  1023. print_line("h: " + itos(row));
  1024. break;
  1025. }
  1026. }
  1027. {
  1028. otex_w = (1 << lattice_size) * (1 << lattice_size) * 2; //make sure lattice fits horizontally
  1029. Vector3 lattice_cell_size = octree_aabb.size;
  1030. for (int i = 0; i < lattice_size; i++) {
  1031. lattice_cell_size *= 0.5;
  1032. }
  1033. while (true) {
  1034. //let's plot the leafs first, given the octree is not so obvious which size it will have
  1035. int row = 4 + 4 * (1 << lattice_size);
  1036. int col = 0;
  1037. col = 0;
  1038. row += 4;
  1039. print_line("end at row " + itos(row));
  1040. //put octree, no need for recursion, just loop backwards.
  1041. int regular_octants = 0;
  1042. for (int i = octant_pool_size - 1; i >= 0; i--) {
  1043. BakedLightBaker::Octant *oct = &octants[i];
  1044. if (oct->leaf) //ignore leaf
  1045. continue;
  1046. if (oct->aabb.size.x > lattice_cell_size.x * 1.1) { //bigger than latice, skip
  1047. oct->texture_x = 0;
  1048. oct->texture_y = 0;
  1049. } else if (oct->aabb.size.x > lattice_cell_size.x * 0.8) {
  1050. //this is the initial lattice
  1051. Vector3 pos = oct->aabb.pos - octree_aabb.pos; //make sure is always positive
  1052. int x = int((pos.x + lattice_cell_size.x * 0.5) / lattice_cell_size.x);
  1053. int y = int((pos.y + lattice_cell_size.y * 0.5) / lattice_cell_size.y);
  1054. int z = int((pos.z + lattice_cell_size.z * 0.5) / lattice_cell_size.z);
  1055. //bug net
  1056. ERR_FAIL_INDEX(x, (1 << lattice_size));
  1057. ERR_FAIL_INDEX(y, (1 << lattice_size));
  1058. ERR_FAIL_INDEX(z, (1 << lattice_size));
  1059. /*int ofs = z*(1<<lattice_size)*(1<<lattice_size)+y*(1<<lattice_size)+x;
  1060. ofs*=4;
  1061. oct->texture_x=ofs%otex_w;
  1062. oct->texture_y=(ofs/otex_w)*4+4;
  1063. */
  1064. oct->texture_x = (x + (1 << lattice_size) * z) * 2;
  1065. oct->texture_y = 4 + y * 4;
  1066. //print_line("pos: "+itos(x)+","+itos(y)+","+itos(z)+" - ofs"+itos(oct->texture_x)+","+itos(oct->texture_y));
  1067. } else {
  1068. //an everyday regular octant
  1069. if (col + 2 > otex_w) {
  1070. col = 0;
  1071. row += 4;
  1072. }
  1073. oct->texture_x = col;
  1074. oct->texture_y = row;
  1075. col += 2;
  1076. regular_octants++;
  1077. }
  1078. }
  1079. print_line("octants end at row " + itos(row) + " totalling" + itos(regular_octants));
  1080. //ok evaluation.
  1081. if (otex_w <= 2048 && row > 2048) { //too big upwards, try bigger texture
  1082. otex_w *= 2;
  1083. continue;
  1084. } else {
  1085. baked_octree_texture_w = otex_w;
  1086. baked_octree_texture_h = row + 4;
  1087. break;
  1088. }
  1089. }
  1090. }
  1091. baked_octree_texture_h = next_power_of_2(baked_octree_texture_h);
  1092. print_line("RESULT! " + itos(baked_octree_texture_w) + "," + itos(baked_octree_texture_h));
  1093. }
  1094. double BakedLightBaker::get_normalization(int p_light_idx) const {
  1095. double nrg = 0;
  1096. const LightData &dl = lights[p_light_idx];
  1097. double cell_area = cell_size * cell_size;
  1098. //nrg+= /*dl.energy */ (dl.rays_thrown * cell_area / dl.area);
  1099. nrg = dl.rays_thrown * cell_area;
  1100. nrg *= (Math_PI * plot_size * plot_size) * 0.5; // damping of radial linear gradient kernel
  1101. nrg *= dl.constant;
  1102. //nrg*=5;
  1103. return nrg;
  1104. }
  1105. double BakedLightBaker::get_modifier(int p_light_idx) const {
  1106. double nrg = 0;
  1107. const LightData &dl = lights[p_light_idx];
  1108. double cell_area = cell_size * cell_size;
  1109. //nrg+= /*dl.energy */ (dl.rays_thrown * cell_area / dl.area);
  1110. nrg = cell_area;
  1111. nrg *= (Math_PI * plot_size * plot_size) * 0.5; // damping of radial linear gradient kernel
  1112. nrg *= dl.constant;
  1113. //nrg*=5;
  1114. return nrg;
  1115. }
  1116. void BakedLightBaker::throw_rays(ThreadStack &thread_stack, int p_amount) {
  1117. for (int i = 0; i < lights.size(); i++) {
  1118. LightData &dl = lights[i];
  1119. int amount = p_amount * total_light_area / dl.area;
  1120. double mod = 1.0 / double(get_modifier(i));
  1121. mod *= p_amount / float(amount);
  1122. switch (dl.type) {
  1123. case VS::LIGHT_DIRECTIONAL: {
  1124. for (int j = 0; j < amount; j++) {
  1125. Vector3 from = dl.pos;
  1126. double r1 = double(rand()) / RAND_MAX;
  1127. double r2 = double(rand()) / RAND_MAX;
  1128. from += dl.up * (r1 * 2.0 - 1.0);
  1129. from += dl.left * (r2 * 2.0 - 1.0);
  1130. Vector3 to = from + dl.dir * dl.length;
  1131. Color col = dl.diffuse;
  1132. float m = mod * dl.energy;
  1133. col.r *= m;
  1134. col.g *= m;
  1135. col.b *= m;
  1136. dl.rays_thrown++;
  1137. baked_light_baker_add_64i(&total_rays, 1);
  1138. _throw_ray(thread_stack, dl.bake_direct, from, to, dl.length, col, NULL, 0, 0, max_bounces, true);
  1139. }
  1140. } break;
  1141. case VS::LIGHT_OMNI: {
  1142. for (int j = 0; j < amount; j++) {
  1143. Vector3 from = dl.pos;
  1144. double r1 = double(rand()) / RAND_MAX;
  1145. double r2 = double(rand()) / RAND_MAX;
  1146. double r3 = double(rand()) / RAND_MAX;
  1147. #if 0
  1148. //crap is not uniform..
  1149. Vector3 dir = Vector3(r1*2.0-1.0,r2*2.0-1.0,r3*2.0-1.0).normalized();
  1150. #else
  1151. double phi = r1 * Math_PI * 2.0;
  1152. double costheta = r2 * 2.0 - 1.0;
  1153. double u = r3;
  1154. double theta = acos(costheta);
  1155. double r = 1.0 * pow(u, 1 / 3.0);
  1156. Vector3 dir(
  1157. r * sin(theta) * cos(phi),
  1158. r * sin(theta) * sin(phi),
  1159. r * cos(theta));
  1160. dir.normalize();
  1161. #endif
  1162. Vector3 to = dl.pos + dir * dl.radius;
  1163. Color col = dl.diffuse;
  1164. float m = mod * dl.energy;
  1165. col.r *= m;
  1166. col.g *= m;
  1167. col.b *= m;
  1168. dl.rays_thrown++;
  1169. baked_light_baker_add_64i(&total_rays, 1);
  1170. _throw_ray(thread_stack, dl.bake_direct, from, to, dl.radius, col, dl.attenuation_table.ptr(), 0, dl.radius, max_bounces, true);
  1171. // _throw_ray(i,from,to,dl.radius,col,NULL,0,dl.radius,max_bounces,true);
  1172. }
  1173. } break;
  1174. case VS::LIGHT_SPOT: {
  1175. for (int j = 0; j < amount; j++) {
  1176. Vector3 from = dl.pos;
  1177. double r1 = double(rand()) / RAND_MAX;
  1178. //double r2 = double(rand())/RAND_MAX;
  1179. double r3 = double(rand()) / RAND_MAX;
  1180. float d = Math::tan(Math::deg2rad(dl.spot_angle));
  1181. float x = sin(r1 * Math_PI * 2.0) * d;
  1182. float y = cos(r1 * Math_PI * 2.0) * d;
  1183. Vector3 dir = r3 * (dl.dir + dl.up * y + dl.left * x) + (1.0 - r3) * dl.dir;
  1184. dir.normalize();
  1185. Vector3 to = dl.pos + dir * dl.radius;
  1186. Color col = dl.diffuse;
  1187. float m = mod * dl.energy;
  1188. col.r *= m;
  1189. col.g *= m;
  1190. col.b *= m;
  1191. dl.rays_thrown++;
  1192. baked_light_baker_add_64i(&total_rays, 1);
  1193. _throw_ray(thread_stack, dl.bake_direct, from, to, dl.radius, col, dl.attenuation_table.ptr(), 0, dl.radius, max_bounces, true);
  1194. // _throw_ray(i,from,to,dl.radius,col,NULL,0,dl.radius,max_bounces,true);
  1195. }
  1196. } break;
  1197. }
  1198. }
  1199. }
  1200. void BakedLightBaker::bake(const Ref<BakedLight> &p_light, Node *p_node) {
  1201. if (baking)
  1202. return;
  1203. cell_count = 0;
  1204. base_inv = p_node->cast_to<Spatial>()->get_global_transform().affine_inverse();
  1205. EditorProgress ep("bake", TTR("Light Baker Setup:"), 5);
  1206. baked_light = p_light;
  1207. lattice_size = baked_light->get_initial_lattice_subdiv();
  1208. octree_depth = baked_light->get_cell_subdivision();
  1209. plot_size = baked_light->get_plot_size();
  1210. max_bounces = baked_light->get_bounces();
  1211. use_diffuse = baked_light->get_bake_flag(BakedLight::BAKE_DIFFUSE);
  1212. use_specular = baked_light->get_bake_flag(BakedLight::BAKE_SPECULAR);
  1213. use_translucency = baked_light->get_bake_flag(BakedLight::BAKE_TRANSLUCENT);
  1214. edge_damp = baked_light->get_edge_damp();
  1215. normal_damp = baked_light->get_normal_damp();
  1216. octree_extra_margin = baked_light->get_cell_extra_margin();
  1217. tint = baked_light->get_tint();
  1218. ao_radius = baked_light->get_ao_radius();
  1219. ao_strength = baked_light->get_ao_strength();
  1220. linear_color = baked_light->get_bake_flag(BakedLight::BAKE_LINEAR_COLOR);
  1221. baked_textures.clear();
  1222. for (int i = 0; i < baked_light->get_lightmaps_count(); i++) {
  1223. BakeTexture bt;
  1224. bt.width = baked_light->get_lightmap_gen_size(i).x;
  1225. bt.height = baked_light->get_lightmap_gen_size(i).y;
  1226. baked_textures.push_back(bt);
  1227. }
  1228. ep.step(TTR("Parsing Geometry"), 0);
  1229. _parse_geometry(p_node);
  1230. mat_map.clear();
  1231. tex_map.clear();
  1232. print_line("\ttotal triangles: " + itos(triangles.size()));
  1233. // no geometry
  1234. if (triangles.size() == 0) {
  1235. return;
  1236. }
  1237. ep.step(TTR("Fixing Lights"), 1);
  1238. _fix_lights();
  1239. ep.step(TTR("Making BVH"), 2);
  1240. _make_bvh();
  1241. ep.step(TTR("Creating Light Octree"), 3);
  1242. _make_octree();
  1243. ep.step(TTR("Creating Octree Texture"), 4);
  1244. _make_octree_texture();
  1245. baking = true;
  1246. _start_thread();
  1247. }
  1248. void BakedLightBaker::update_octree_sampler(DVector<int> &p_sampler) {
  1249. BakedLightBaker::Octant *octants = octant_pool.ptr();
  1250. double norm = 1.0 / double(total_rays);
  1251. if (p_sampler.size() == 0 || first_bake_to_map) {
  1252. Vector<int> tmp_smp;
  1253. tmp_smp.resize(32); //32 for header
  1254. for (int i = 0; i < 32; i++) {
  1255. tmp_smp[i] = 0;
  1256. }
  1257. for (int i = octant_pool_size - 1; i >= 0; i--) {
  1258. if (i == 0)
  1259. tmp_smp[1] = tmp_smp.size();
  1260. Octant &octant = octants[i];
  1261. octant.sampler_ofs = tmp_smp.size();
  1262. int idxcol[2] = { 0, 0 };
  1263. int r = CLAMP((octant.full_accum[0] * norm) * 2048, 0, 32767);
  1264. int g = CLAMP((octant.full_accum[1] * norm) * 2048, 0, 32767);
  1265. int b = CLAMP((octant.full_accum[2] * norm) * 2048, 0, 32767);
  1266. idxcol[0] |= r;
  1267. idxcol[1] |= (g << 16) | b;
  1268. if (octant.leaf) {
  1269. tmp_smp.push_back(idxcol[0]);
  1270. tmp_smp.push_back(idxcol[1]);
  1271. } else {
  1272. for (int j = 0; j < 8; j++) {
  1273. if (octant.children[j]) {
  1274. idxcol[0] |= (1 << (j + 16));
  1275. }
  1276. }
  1277. tmp_smp.push_back(idxcol[0]);
  1278. tmp_smp.push_back(idxcol[1]);
  1279. for (int j = 0; j < 8; j++) {
  1280. if (octant.children[j]) {
  1281. tmp_smp.push_back(octants[octant.children[j]].sampler_ofs);
  1282. if (octants[octant.children[j]].sampler_ofs == 0) {
  1283. print_line("FUUUUUUUUCK");
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. p_sampler.resize(tmp_smp.size());
  1290. DVector<int>::Write w = p_sampler.write();
  1291. int ss = tmp_smp.size();
  1292. for (int i = 0; i < ss; i++) {
  1293. w[i] = tmp_smp[i];
  1294. }
  1295. first_bake_to_map = false;
  1296. }
  1297. double gamma = baked_light->get_gamma_adjust();
  1298. double mult = baked_light->get_energy_multiplier();
  1299. float saturation = baked_light->get_saturation();
  1300. DVector<int>::Write w = p_sampler.write();
  1301. encode_uint32(octree_depth, (uint8_t *)&w[2]);
  1302. encode_uint32(linear_color, (uint8_t *)&w[3]);
  1303. encode_float(octree_aabb.pos.x, (uint8_t *)&w[4]);
  1304. encode_float(octree_aabb.pos.y, (uint8_t *)&w[5]);
  1305. encode_float(octree_aabb.pos.z, (uint8_t *)&w[6]);
  1306. encode_float(octree_aabb.size.x, (uint8_t *)&w[7]);
  1307. encode_float(octree_aabb.size.y, (uint8_t *)&w[8]);
  1308. encode_float(octree_aabb.size.z, (uint8_t *)&w[9]);
  1309. //norm*=multiplier;
  1310. for (int i = octant_pool_size - 1; i >= 0; i--) {
  1311. Octant &octant = octants[i];
  1312. int idxcol[2] = { w[octant.sampler_ofs], w[octant.sampler_ofs + 1] };
  1313. double rf = pow(octant.full_accum[0] * norm * mult, gamma);
  1314. double gf = pow(octant.full_accum[1] * norm * mult, gamma);
  1315. double bf = pow(octant.full_accum[2] * norm * mult, gamma);
  1316. double gray = (rf + gf + bf) / 3.0;
  1317. rf = gray + (rf - gray) * saturation;
  1318. gf = gray + (gf - gray) * saturation;
  1319. bf = gray + (bf - gray) * saturation;
  1320. int r = CLAMP((rf)*2048, 0, 32767);
  1321. int g = CLAMP((gf)*2048, 0, 32767);
  1322. int b = CLAMP((bf)*2048, 0, 32767);
  1323. idxcol[0] = ((idxcol[0] >> 16) << 16) | r;
  1324. idxcol[1] = (g << 16) | b;
  1325. w[octant.sampler_ofs] = idxcol[0];
  1326. w[octant.sampler_ofs + 1] = idxcol[1];
  1327. }
  1328. }
  1329. void BakedLightBaker::update_octree_images(DVector<uint8_t> &p_octree, DVector<uint8_t> &p_light) {
  1330. int len = baked_octree_texture_w * baked_octree_texture_h * 4;
  1331. p_octree.resize(len);
  1332. int ilen = baked_light_texture_w * baked_light_texture_h * 4;
  1333. p_light.resize(ilen);
  1334. DVector<uint8_t>::Write w = p_octree.write();
  1335. zeromem(w.ptr(), len);
  1336. DVector<uint8_t>::Write iw = p_light.write();
  1337. zeromem(iw.ptr(), ilen);
  1338. float gamma = baked_light->get_gamma_adjust();
  1339. float mult = baked_light->get_energy_multiplier();
  1340. for (int i = 0; i < len; i += 4) {
  1341. w[i + 0] = 0xFF;
  1342. w[i + 1] = 0;
  1343. w[i + 2] = 0xFF;
  1344. w[i + 3] = 0xFF;
  1345. }
  1346. for (int i = 0; i < ilen; i += 4) {
  1347. iw[i + 0] = 0xFF;
  1348. iw[i + 1] = 0;
  1349. iw[i + 2] = 0xFF;
  1350. iw[i + 3] = 0xFF;
  1351. }
  1352. float multiplier = 1.0;
  1353. if (baked_light->get_format() == BakedLight::FORMAT_HDR8)
  1354. multiplier = 8;
  1355. encode_uint32(baked_octree_texture_w, &w[0]);
  1356. encode_uint32(baked_octree_texture_h, &w[4]);
  1357. encode_uint32(0, &w[8]);
  1358. encode_float(1 << lattice_size, &w[12]);
  1359. encode_uint32(octree_depth - lattice_size, &w[16]);
  1360. encode_uint32(multiplier, &w[20]);
  1361. encode_uint16(baked_light_texture_w, &w[24]); //if present, use the baked light texture
  1362. encode_uint16(baked_light_texture_h, &w[26]);
  1363. encode_uint32(0, &w[28]); //baked light texture format
  1364. encode_float(octree_aabb.pos.x, &w[32]);
  1365. encode_float(octree_aabb.pos.y, &w[36]);
  1366. encode_float(octree_aabb.pos.z, &w[40]);
  1367. encode_float(octree_aabb.size.x, &w[44]);
  1368. encode_float(octree_aabb.size.y, &w[48]);
  1369. encode_float(octree_aabb.size.z, &w[52]);
  1370. BakedLightBaker::Octant *octants = octant_pool.ptr();
  1371. int octant_count = octant_pool_size;
  1372. uint8_t *ptr = w.ptr();
  1373. uint8_t *lptr = iw.ptr();
  1374. int child_offsets[8] = {
  1375. 0,
  1376. 4,
  1377. baked_octree_texture_w * 4,
  1378. baked_octree_texture_w * 4 + 4,
  1379. baked_octree_texture_w * 8 + 0,
  1380. baked_octree_texture_w * 8 + 4,
  1381. baked_octree_texture_w * 8 + baked_octree_texture_w * 4,
  1382. baked_octree_texture_w * 8 + baked_octree_texture_w * 4 + 4,
  1383. };
  1384. int lchild_offsets[8] = {
  1385. 0,
  1386. 4,
  1387. baked_light_texture_w * 4,
  1388. baked_light_texture_w * 4 + 4,
  1389. baked_light_texture_w * 8 + 0,
  1390. baked_light_texture_w * 8 + 4,
  1391. baked_light_texture_w * 8 + baked_light_texture_w * 4,
  1392. baked_light_texture_w * 8 + baked_light_texture_w * 4 + 4,
  1393. };
  1394. /*Vector<double> norm_arr;
  1395. norm_arr.resize(lights.size());
  1396. for(int i=0;i<lights.size();i++) {
  1397. norm_arr[i] = 1.0/get_normalization(i);
  1398. }
  1399. const double *normptr=norm_arr.ptr();
  1400. */
  1401. double norm = 1.0 / double(total_rays);
  1402. mult /= multiplier;
  1403. double saturation = baked_light->get_saturation();
  1404. for (int i = 0; i < octant_count; i++) {
  1405. Octant &oct = octants[i];
  1406. if (oct.texture_x == 0 && oct.texture_y == 0)
  1407. continue;
  1408. if (oct.leaf) {
  1409. int ofs = (oct.texture_y * baked_light_texture_w + oct.texture_x) << 2;
  1410. ERR_CONTINUE(ofs < 0 || ofs > ilen);
  1411. //write colors
  1412. for (int j = 0; j < 8; j++) {
  1413. //if (!oct.children[j])
  1414. // continue;
  1415. uint8_t *iptr = &lptr[ofs + lchild_offsets[j]];
  1416. float r = oct.light_accum[j][0] * norm;
  1417. float g = oct.light_accum[j][1] * norm;
  1418. float b = oct.light_accum[j][2] * norm;
  1419. r = pow(r * mult, gamma);
  1420. g = pow(g * mult, gamma);
  1421. b = pow(b * mult, gamma);
  1422. double gray = (r + g + b) / 3.0;
  1423. r = gray + (r - gray) * saturation;
  1424. g = gray + (g - gray) * saturation;
  1425. b = gray + (b - gray) * saturation;
  1426. float ic[3] = {
  1427. r,
  1428. g,
  1429. b,
  1430. };
  1431. iptr[0] = CLAMP(ic[0] * 255.0, 0, 255);
  1432. iptr[1] = CLAMP(ic[1] * 255.0, 0, 255);
  1433. iptr[2] = CLAMP(ic[2] * 255.0, 0, 255);
  1434. iptr[3] = 255;
  1435. }
  1436. } else {
  1437. int ofs = (oct.texture_y * baked_octree_texture_w + oct.texture_x) << 2;
  1438. ERR_CONTINUE(ofs < 0 || ofs > len);
  1439. //write indices
  1440. for (int j = 0; j < 8; j++) {
  1441. if (!oct.children[j])
  1442. continue;
  1443. Octant &choct = octants[oct.children[j]];
  1444. uint8_t *iptr = &ptr[ofs + child_offsets[j]];
  1445. iptr[0] = choct.texture_x >> 8;
  1446. iptr[1] = choct.texture_x & 0xFF;
  1447. iptr[2] = choct.texture_y >> 8;
  1448. iptr[3] = choct.texture_y & 0xFF;
  1449. }
  1450. }
  1451. }
  1452. }
  1453. void BakedLightBaker::_free_bvh(BVH *p_bvh) {
  1454. if (!p_bvh->leaf) {
  1455. if (p_bvh->children[0])
  1456. _free_bvh(p_bvh->children[0]);
  1457. if (p_bvh->children[1])
  1458. _free_bvh(p_bvh->children[1]);
  1459. }
  1460. memdelete(p_bvh);
  1461. }
  1462. bool BakedLightBaker::is_baking() {
  1463. return baking;
  1464. }
  1465. void BakedLightBaker::set_pause(bool p_pause) {
  1466. if (paused == p_pause)
  1467. return;
  1468. paused = p_pause;
  1469. if (paused) {
  1470. _stop_thread();
  1471. } else {
  1472. _start_thread();
  1473. }
  1474. }
  1475. bool BakedLightBaker::is_paused() {
  1476. return paused;
  1477. }
  1478. void BakedLightBaker::_bake_thread_func(void *arg) {
  1479. BakedLightBaker *ble = (BakedLightBaker *)arg;
  1480. ThreadStack thread_stack;
  1481. thread_stack.ray_stack = memnew_arr(uint32_t, ble->bvh_depth);
  1482. thread_stack.bvh_stack = memnew_arr(BVH *, ble->bvh_depth);
  1483. thread_stack.octant_stack = memnew_arr(uint32_t, ble->octree_depth * 2);
  1484. thread_stack.octantptr_stack = memnew_arr(uint32_t, ble->octree_depth * 2);
  1485. while (!ble->bake_thread_exit) {
  1486. ble->throw_rays(thread_stack, 1000);
  1487. }
  1488. memdelete_arr(thread_stack.ray_stack);
  1489. memdelete_arr(thread_stack.bvh_stack);
  1490. memdelete_arr(thread_stack.octant_stack);
  1491. memdelete_arr(thread_stack.octantptr_stack);
  1492. }
  1493. void BakedLightBaker::_start_thread() {
  1494. if (threads.size() != 0)
  1495. return;
  1496. bake_thread_exit = false;
  1497. int thread_count = EDITOR_DEF("light_baker/custom_bake_threads", 0);
  1498. if (thread_count <= 0 || thread_count > 64)
  1499. thread_count = OS::get_singleton()->get_processor_count();
  1500. //thread_count=1;
  1501. threads.resize(thread_count);
  1502. for (int i = 0; i < threads.size(); i++) {
  1503. threads[i] = Thread::create(_bake_thread_func, this);
  1504. }
  1505. }
  1506. void BakedLightBaker::_stop_thread() {
  1507. if (threads.size() == 0)
  1508. return;
  1509. bake_thread_exit = true;
  1510. for (int i = 0; i < threads.size(); i++) {
  1511. Thread::wait_to_finish(threads[i]);
  1512. memdelete(threads[i]);
  1513. }
  1514. threads.clear();
  1515. }
  1516. void BakedLightBaker::_plot_pixel_to_lightmap(int x, int y, int width, int height, uint8_t *image, const Vector3 &p_pos, const Vector3 &p_normal, double *p_norm_ptr, float mult, float gamma) {
  1517. uint8_t *ptr = &image[(y * width + x) * 4];
  1518. //int lc = lights.size();
  1519. double norm = 1.0 / double(total_rays);
  1520. Color color;
  1521. Octant *octants = octant_pool.ptr();
  1522. int octant_idx = 0;
  1523. while (true) {
  1524. Octant &octant = octants[octant_idx];
  1525. if (octant.leaf) {
  1526. Vector3 lpos = p_pos - octant.aabb.pos;
  1527. lpos /= octant.aabb.size;
  1528. Vector3 cols[8];
  1529. for (int i = 0; i < 8; i++) {
  1530. cols[i].x += octant.light_accum[i][0] * norm;
  1531. cols[i].y += octant.light_accum[i][1] * norm;
  1532. cols[i].z += octant.light_accum[i][2] * norm;
  1533. }
  1534. /*Vector3 final = (cols[0] + (cols[1] - cols[0]) * lpos.y);
  1535. final = final + ((cols[2] + (cols[3] - cols[2]) * lpos.y) - final)*lpos.x;
  1536. Vector3 final2 = (cols[4+0] + (cols[4+1] - cols[4+0]) * lpos.y);
  1537. final2 = final2 + ((cols[4+2] + (cols[4+3] - cols[4+2]) * lpos.y) - final2)*lpos.x;*/
  1538. Vector3 finala = cols[0].linear_interpolate(cols[1], lpos.x);
  1539. Vector3 finalb = cols[2].linear_interpolate(cols[3], lpos.x);
  1540. Vector3 final = finala.linear_interpolate(finalb, lpos.y);
  1541. Vector3 final2a = cols[4 + 0].linear_interpolate(cols[4 + 1], lpos.x);
  1542. Vector3 final2b = cols[4 + 2].linear_interpolate(cols[4 + 3], lpos.x);
  1543. Vector3 final2 = final2a.linear_interpolate(final2b, lpos.y);
  1544. final = final.linear_interpolate(final2, lpos.z);
  1545. if (baked_light->get_format() == BakedLight::FORMAT_HDR8)
  1546. final *= 8.0;
  1547. color.r = pow(final.x * mult, gamma);
  1548. color.g = pow(final.y * mult, gamma);
  1549. color.b = pow(final.z * mult, gamma);
  1550. color.a = 1.0;
  1551. int lc = lights.size();
  1552. LightData *lv = lights.ptr();
  1553. for (int i = 0; i < lc; i++) {
  1554. //shadow baking
  1555. if (!lv[i].bake_shadow)
  1556. continue;
  1557. Vector3 from = p_pos + p_normal * 0.01;
  1558. Vector3 to;
  1559. float att = 0;
  1560. switch (lv[i].type) {
  1561. case VS::LIGHT_DIRECTIONAL: {
  1562. to = from - lv[i].dir * lv[i].length;
  1563. } break;
  1564. case VS::LIGHT_OMNI: {
  1565. to = lv[i].pos;
  1566. float d = MIN(lv[i].radius, to.distance_to(from)) / lv[i].radius;
  1567. att = d; //1.0-d;
  1568. } break;
  1569. default: continue;
  1570. }
  1571. uint32_t *stack = ray_stack;
  1572. BVH **bstack = bvh_stack;
  1573. enum {
  1574. TEST_RAY_BIT = 0,
  1575. VISIT_LEFT_BIT = 1,
  1576. VISIT_RIGHT_BIT = 2,
  1577. VISIT_DONE_BIT = 3,
  1578. };
  1579. bool intersected = false;
  1580. int level = 0;
  1581. Vector3 n = (to - from);
  1582. float len = n.length();
  1583. if (len == 0)
  1584. continue;
  1585. n /= len;
  1586. bstack[0] = bvh;
  1587. stack[0] = TEST_RAY_BIT;
  1588. while (!intersected) {
  1589. uint32_t mode = stack[level];
  1590. const BVH &b = *bstack[level];
  1591. bool done = false;
  1592. switch (mode) {
  1593. case TEST_RAY_BIT: {
  1594. if (b.leaf) {
  1595. Face3 f3(b.leaf->vertices[0], b.leaf->vertices[1], b.leaf->vertices[2]);
  1596. Vector3 res;
  1597. if (f3.intersects_segment(from, to)) {
  1598. intersected = true;
  1599. done = true;
  1600. }
  1601. stack[level] = VISIT_DONE_BIT;
  1602. } else {
  1603. bool valid = b.aabb.smits_intersect_ray(from, n, 0, len);
  1604. //bool valid = b.aabb.intersects_segment(p_begin,p_end);
  1605. // bool valid = b.aabb.intersects(ray_aabb);
  1606. if (!valid) {
  1607. stack[level] = VISIT_DONE_BIT;
  1608. } else {
  1609. stack[level] = VISIT_LEFT_BIT;
  1610. }
  1611. }
  1612. }
  1613. continue;
  1614. case VISIT_LEFT_BIT: {
  1615. stack[level] = VISIT_RIGHT_BIT;
  1616. bstack[level + 1] = b.children[0];
  1617. stack[level + 1] = TEST_RAY_BIT;
  1618. level++;
  1619. }
  1620. continue;
  1621. case VISIT_RIGHT_BIT: {
  1622. stack[level] = VISIT_DONE_BIT;
  1623. bstack[level + 1] = b.children[1];
  1624. stack[level + 1] = TEST_RAY_BIT;
  1625. level++;
  1626. }
  1627. continue;
  1628. case VISIT_DONE_BIT: {
  1629. if (level == 0) {
  1630. done = true;
  1631. break;
  1632. } else
  1633. level--;
  1634. }
  1635. continue;
  1636. }
  1637. if (done)
  1638. break;
  1639. }
  1640. if (intersected) {
  1641. color.a = Math::lerp(MAX(0.01, lv[i].darkening), 1.0, att);
  1642. }
  1643. }
  1644. break;
  1645. } else {
  1646. Vector3 lpos = p_pos - octant.aabb.pos;
  1647. Vector3 half = octant.aabb.size * 0.5;
  1648. int ofs = 0;
  1649. if (lpos.x >= half.x)
  1650. ofs |= 1;
  1651. if (lpos.y >= half.y)
  1652. ofs |= 2;
  1653. if (lpos.z >= half.z)
  1654. ofs |= 4;
  1655. octant_idx = octant.children[ofs];
  1656. if (octant_idx == 0)
  1657. return;
  1658. }
  1659. }
  1660. ptr[0] = CLAMP(color.r * 255.0, 0, 255);
  1661. ptr[1] = CLAMP(color.g * 255.0, 0, 255);
  1662. ptr[2] = CLAMP(color.b * 255.0, 0, 255);
  1663. ptr[3] = CLAMP(color.a * 255.0, 0, 255);
  1664. }
  1665. Error BakedLightBaker::transfer_to_lightmaps() {
  1666. if (!triangles.size() || baked_textures.size() == 0)
  1667. return ERR_UNCONFIGURED;
  1668. EditorProgress ep("transfer_to_lightmaps", TTR("Transfer to Lightmaps:"), baked_textures.size() * 2 + triangles.size());
  1669. for (int i = 0; i < baked_textures.size(); i++) {
  1670. ERR_FAIL_COND_V(baked_textures[i].width <= 0 || baked_textures[i].height <= 0, ERR_UNCONFIGURED);
  1671. baked_textures[i].data.resize(baked_textures[i].width * baked_textures[i].height * 4);
  1672. zeromem(baked_textures[i].data.ptr(), baked_textures[i].data.size());
  1673. ep.step(TTR("Allocating Texture #") + itos(i + 1), i);
  1674. }
  1675. Vector<double> norm_arr;
  1676. norm_arr.resize(lights.size());
  1677. for (int i = 0; i < lights.size(); i++) {
  1678. norm_arr[i] = 1.0 / get_normalization(i);
  1679. }
  1680. float gamma = baked_light->get_gamma_adjust();
  1681. float mult = baked_light->get_energy_multiplier();
  1682. for (int i = 0; i < triangles.size(); i++) {
  1683. if (i % 200 == 0) {
  1684. ep.step(TTR("Baking Triangle #") + itos(i), i + baked_textures.size());
  1685. }
  1686. Triangle &t = triangles[i];
  1687. if (t.baked_texture < 0 || t.baked_texture >= baked_textures.size())
  1688. continue;
  1689. BakeTexture &bt = baked_textures[t.baked_texture];
  1690. Vector3 normal = Plane(t.vertices[0], t.vertices[1], t.vertices[2]).normal;
  1691. int x[3];
  1692. int y[3];
  1693. Vector3 vertices[3] = {
  1694. t.vertices[0],
  1695. t.vertices[1],
  1696. t.vertices[2]
  1697. };
  1698. for (int j = 0; j < 3; j++) {
  1699. x[j] = t.bake_uvs[j].x * bt.width;
  1700. y[j] = t.bake_uvs[j].y * bt.height;
  1701. x[j] = CLAMP(x[j], 0, bt.width - 1);
  1702. y[j] = CLAMP(y[j], 0, bt.height - 1);
  1703. }
  1704. {
  1705. // sort the points vertically
  1706. if (y[1] > y[2]) {
  1707. SWAP(x[1], x[2]);
  1708. SWAP(y[1], y[2]);
  1709. SWAP(vertices[1], vertices[2]);
  1710. }
  1711. if (y[0] > y[1]) {
  1712. SWAP(x[0], x[1]);
  1713. SWAP(y[0], y[1]);
  1714. SWAP(vertices[0], vertices[1]);
  1715. }
  1716. if (y[1] > y[2]) {
  1717. SWAP(x[1], x[2]);
  1718. SWAP(y[1], y[2]);
  1719. SWAP(vertices[1], vertices[2]);
  1720. }
  1721. double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);
  1722. double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);
  1723. double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);
  1724. double xf = x[0];
  1725. double xt = x[0] + dx_upper; // if y[0] == y[1], special case
  1726. for (int yi = y[0]; yi <= (y[2] > bt.height - 1 ? bt.height - 1 : y[2]); yi++) {
  1727. if (yi >= 0) {
  1728. for (int xi = (xf > 0 ? int(xf) : 0); xi <= (xt < bt.width ? xt : bt.width - 1); xi++) {
  1729. //pixels[int(x + y * width)] = color;
  1730. Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
  1731. Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
  1732. //vertices[2] - vertices[0];
  1733. Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
  1734. float d00 = v0.dot(v0);
  1735. float d01 = v0.dot(v1);
  1736. float d11 = v1.dot(v1);
  1737. float d20 = v2.dot(v0);
  1738. float d21 = v2.dot(v1);
  1739. float denom = (d00 * d11 - d01 * d01);
  1740. Vector3 pos;
  1741. if (denom == 0) {
  1742. pos = t.vertices[0];
  1743. } else {
  1744. float v = (d11 * d20 - d01 * d21) / denom;
  1745. float w = (d00 * d21 - d01 * d20) / denom;
  1746. float u = 1.0f - v - w;
  1747. pos = vertices[0] * u + vertices[1] * v + vertices[2] * w;
  1748. }
  1749. _plot_pixel_to_lightmap(xi, yi, bt.width, bt.height, bt.data.ptr(), pos, normal, norm_arr.ptr(), mult, gamma);
  1750. }
  1751. for (int xi = (xf < bt.width ? int(xf) : bt.width - 1); xi >= (xt > 0 ? xt : 0); xi--) {
  1752. //pixels[int(x + y * width)] = color;
  1753. Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
  1754. Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
  1755. //vertices[2] - vertices[0];
  1756. Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
  1757. float d00 = v0.dot(v0);
  1758. float d01 = v0.dot(v1);
  1759. float d11 = v1.dot(v1);
  1760. float d20 = v2.dot(v0);
  1761. float d21 = v2.dot(v1);
  1762. float denom = (d00 * d11 - d01 * d01);
  1763. Vector3 pos;
  1764. if (denom == 0) {
  1765. pos = t.vertices[0];
  1766. } else {
  1767. float v = (d11 * d20 - d01 * d21) / denom;
  1768. float w = (d00 * d21 - d01 * d20) / denom;
  1769. float u = 1.0f - v - w;
  1770. pos = vertices[0] * u + vertices[1] * v + vertices[2] * w;
  1771. }
  1772. _plot_pixel_to_lightmap(xi, yi, bt.width, bt.height, bt.data.ptr(), pos, normal, norm_arr.ptr(), mult, gamma);
  1773. }
  1774. }
  1775. xf += dx_far;
  1776. if (yi < y[1])
  1777. xt += dx_upper;
  1778. else
  1779. xt += dx_low;
  1780. }
  1781. }
  1782. }
  1783. for (int i = 0; i < baked_textures.size(); i++) {
  1784. {
  1785. ep.step(TTR("Post-Processing Texture #") + itos(i), i + baked_textures.size() + triangles.size());
  1786. BakeTexture &bt = baked_textures[i];
  1787. Vector<uint8_t> copy_data = bt.data;
  1788. uint8_t *data = bt.data.ptr();
  1789. const int max_radius = 8;
  1790. const int shadow_radius = 2;
  1791. const int max_dist = 0x7FFFFFFF;
  1792. for (int x = 0; x < bt.width; x++) {
  1793. for (int y = 0; y < bt.height; y++) {
  1794. uint8_t a = copy_data[(y * bt.width + x) * 4 + 3];
  1795. if (a > 0) {
  1796. //blur shadow
  1797. int from_x = MAX(0, x - shadow_radius);
  1798. int to_x = MIN(bt.width - 1, x + shadow_radius);
  1799. int from_y = MAX(0, y - shadow_radius);
  1800. int to_y = MIN(bt.height - 1, y + shadow_radius);
  1801. int sum = 0;
  1802. int sumc = 0;
  1803. for (int k = from_y; k <= to_y; k++) {
  1804. for (int l = from_x; l <= to_x; l++) {
  1805. const uint8_t *rp = &copy_data[(k * bt.width + l) << 2];
  1806. sum += rp[3];
  1807. sumc++;
  1808. }
  1809. }
  1810. sum /= sumc;
  1811. data[(y * bt.width + x) * 4 + 3] = sum;
  1812. } else {
  1813. int closest_dist = max_dist;
  1814. uint8_t closest_color[4];
  1815. int from_x = MAX(0, x - max_radius);
  1816. int to_x = MIN(bt.width - 1, x + max_radius);
  1817. int from_y = MAX(0, y - max_radius);
  1818. int to_y = MIN(bt.height - 1, y + max_radius);
  1819. for (int k = from_y; k <= to_y; k++) {
  1820. for (int l = from_x; l <= to_x; l++) {
  1821. int dy = y - k;
  1822. int dx = x - l;
  1823. int dist = dy * dy + dx * dx;
  1824. if (dist >= closest_dist)
  1825. continue;
  1826. const uint8_t *rp = &copy_data[(k * bt.width + l) << 2];
  1827. if (rp[3] == 0)
  1828. continue;
  1829. closest_dist = dist;
  1830. closest_color[0] = rp[0];
  1831. closest_color[1] = rp[1];
  1832. closest_color[2] = rp[2];
  1833. closest_color[3] = rp[3];
  1834. }
  1835. }
  1836. if (closest_dist != max_dist) {
  1837. data[(y * bt.width + x) * 4 + 0] = closest_color[0];
  1838. data[(y * bt.width + x) * 4 + 1] = closest_color[1];
  1839. data[(y * bt.width + x) * 4 + 2] = closest_color[2];
  1840. data[(y * bt.width + x) * 4 + 3] = closest_color[3];
  1841. }
  1842. }
  1843. }
  1844. }
  1845. }
  1846. DVector<uint8_t> dv;
  1847. dv.resize(baked_textures[i].data.size());
  1848. {
  1849. DVector<uint8_t>::Write w = dv.write();
  1850. copymem(w.ptr(), baked_textures[i].data.ptr(), baked_textures[i].data.size());
  1851. }
  1852. Image img(baked_textures[i].width, baked_textures[i].height, 0, Image::FORMAT_RGBA, dv);
  1853. Ref<ImageTexture> tex = memnew(ImageTexture);
  1854. tex->create_from_image(img);
  1855. baked_light->set_lightmap_texture(i, tex);
  1856. }
  1857. return OK;
  1858. }
  1859. void BakedLightBaker::clear() {
  1860. _stop_thread();
  1861. if (bvh)
  1862. _free_bvh(bvh);
  1863. if (ray_stack)
  1864. memdelete_arr(ray_stack);
  1865. if (octant_stack)
  1866. memdelete_arr(octant_stack);
  1867. if (octantptr_stack)
  1868. memdelete_arr(octantptr_stack);
  1869. if (bvh_stack)
  1870. memdelete_arr(bvh_stack);
  1871. /*
  1872. * ???
  1873. for(int i=0;i<octant_pool.size();i++) {
  1874. //if (octant_pool[i].leaf) {
  1875. // memdelete_arr( octant_pool[i].light );
  1876. //} Vector<double> norm_arr;
  1877. //norm_arr.resize(lights.size());
  1878. for(int i=0;i<lights.size();i++) {
  1879. norm_arr[i] = 1.0/get_normalization(i);
  1880. }
  1881. const double *normptr=norm_arr.ptr();
  1882. }
  1883. */
  1884. octant_pool.clear();
  1885. octant_pool_size = 0;
  1886. bvh = NULL;
  1887. leaf_list = 0;
  1888. cell_count = 0;
  1889. ray_stack = NULL;
  1890. octant_stack = NULL;
  1891. octantptr_stack = NULL;
  1892. bvh_stack = NULL;
  1893. materials.clear();
  1894. materials.clear();
  1895. textures.clear();
  1896. lights.clear();
  1897. triangles.clear();
  1898. endpoint_normal.clear();
  1899. endpoint_normal_bits.clear();
  1900. baked_octree_texture_w = 0;
  1901. baked_octree_texture_h = 0;
  1902. paused = false;
  1903. baking = false;
  1904. bake_thread_exit = false;
  1905. first_bake_to_map = true;
  1906. baked_light = Ref<BakedLight>();
  1907. total_rays = 0;
  1908. }
  1909. BakedLightBaker::BakedLightBaker() {
  1910. octree_depth = 9;
  1911. lattice_size = 4;
  1912. octant_pool.clear();
  1913. octant_pool_size = 0;
  1914. bvh = NULL;
  1915. leaf_list = 0;
  1916. cell_count = 0;
  1917. ray_stack = NULL;
  1918. bvh_stack = NULL;
  1919. octant_stack = NULL;
  1920. octantptr_stack = NULL;
  1921. plot_size = 2.5;
  1922. max_bounces = 2;
  1923. materials.clear();
  1924. baked_octree_texture_w = 0;
  1925. baked_octree_texture_h = 0;
  1926. paused = false;
  1927. baking = false;
  1928. bake_thread_exit = false;
  1929. total_rays = 0;
  1930. first_bake_to_map = true;
  1931. linear_color = false;
  1932. }
  1933. BakedLightBaker::~BakedLightBaker() {
  1934. clear();
  1935. }