voxel_light_baker.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427
  1. /*************************************************************************/
  2. /* voxel_light_baker.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "voxel_light_baker.h"
  31. #include "core/os/os.h"
  32. #include "core/os/threaded_array_processor.h"
  33. #include <stdlib.h>
  34. #define FINDMINMAX(x0, x1, x2, min, max) \
  35. min = max = x0; \
  36. if (x1 < min) min = x1; \
  37. if (x1 > max) max = x1; \
  38. if (x2 < min) min = x2; \
  39. if (x2 > max) max = x2;
  40. static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) {
  41. int q;
  42. Vector3 vmin, vmax;
  43. for (q = 0; q <= 2; q++) {
  44. if (normal[q] > 0.0f) {
  45. vmin[q] = -maxbox[q];
  46. vmax[q] = maxbox[q];
  47. } else {
  48. vmin[q] = maxbox[q];
  49. vmax[q] = -maxbox[q];
  50. }
  51. }
  52. if (normal.dot(vmin) + d > 0.0f) return false;
  53. if (normal.dot(vmax) + d >= 0.0f) return true;
  54. return false;
  55. }
  56. /*======================== X-tests ========================*/
  57. #define AXISTEST_X01(a, b, fa, fb) \
  58. p0 = a * v0.y - b * v0.z; \
  59. p2 = a * v2.y - b * v2.z; \
  60. if (p0 < p2) { \
  61. min = p0; \
  62. max = p2; \
  63. } else { \
  64. min = p2; \
  65. max = p0; \
  66. } \
  67. rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
  68. if (min > rad || max < -rad) return false;
  69. #define AXISTEST_X2(a, b, fa, fb) \
  70. p0 = a * v0.y - b * v0.z; \
  71. p1 = a * v1.y - b * v1.z; \
  72. if (p0 < p1) { \
  73. min = p0; \
  74. max = p1; \
  75. } else { \
  76. min = p1; \
  77. max = p0; \
  78. } \
  79. rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
  80. if (min > rad || max < -rad) return false;
  81. /*======================== Y-tests ========================*/
  82. #define AXISTEST_Y02(a, b, fa, fb) \
  83. p0 = -a * v0.x + b * v0.z; \
  84. p2 = -a * v2.x + b * v2.z; \
  85. if (p0 < p2) { \
  86. min = p0; \
  87. max = p2; \
  88. } else { \
  89. min = p2; \
  90. max = p0; \
  91. } \
  92. rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
  93. if (min > rad || max < -rad) return false;
  94. #define AXISTEST_Y1(a, b, fa, fb) \
  95. p0 = -a * v0.x + b * v0.z; \
  96. p1 = -a * v1.x + b * v1.z; \
  97. if (p0 < p1) { \
  98. min = p0; \
  99. max = p1; \
  100. } else { \
  101. min = p1; \
  102. max = p0; \
  103. } \
  104. rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
  105. if (min > rad || max < -rad) return false;
  106. /*======================== Z-tests ========================*/
  107. #define AXISTEST_Z12(a, b, fa, fb) \
  108. p1 = a * v1.x - b * v1.y; \
  109. p2 = a * v2.x - b * v2.y; \
  110. if (p2 < p1) { \
  111. min = p2; \
  112. max = p1; \
  113. } else { \
  114. min = p1; \
  115. max = p2; \
  116. } \
  117. rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
  118. if (min > rad || max < -rad) return false;
  119. #define AXISTEST_Z0(a, b, fa, fb) \
  120. p0 = a * v0.x - b * v0.y; \
  121. p1 = a * v1.x - b * v1.y; \
  122. if (p0 < p1) { \
  123. min = p0; \
  124. max = p1; \
  125. } else { \
  126. min = p1; \
  127. max = p0; \
  128. } \
  129. rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
  130. if (min > rad || max < -rad) return false;
  131. static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) {
  132. /* use separating axis theorem to test overlap between triangle and box */
  133. /* need to test for overlap in these directions: */
  134. /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
  135. /* we do not even need to test these) */
  136. /* 2) normal of the triangle */
  137. /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
  138. /* this gives 3x3=9 more tests */
  139. Vector3 v0, v1, v2;
  140. float min, max, d, p0, p1, p2, rad, fex, fey, fez;
  141. Vector3 normal, e0, e1, e2;
  142. /* This is the fastest branch on Sun */
  143. /* move everything so that the boxcenter is in (0,0,0) */
  144. v0 = triverts[0] - boxcenter;
  145. v1 = triverts[1] - boxcenter;
  146. v2 = triverts[2] - boxcenter;
  147. /* compute triangle edges */
  148. e0 = v1 - v0; /* tri edge 0 */
  149. e1 = v2 - v1; /* tri edge 1 */
  150. e2 = v0 - v2; /* tri edge 2 */
  151. /* Bullet 3: */
  152. /* test the 9 tests first (this was faster) */
  153. fex = Math::abs(e0.x);
  154. fey = Math::abs(e0.y);
  155. fez = Math::abs(e0.z);
  156. AXISTEST_X01(e0.z, e0.y, fez, fey);
  157. AXISTEST_Y02(e0.z, e0.x, fez, fex);
  158. AXISTEST_Z12(e0.y, e0.x, fey, fex);
  159. fex = Math::abs(e1.x);
  160. fey = Math::abs(e1.y);
  161. fez = Math::abs(e1.z);
  162. AXISTEST_X01(e1.z, e1.y, fez, fey);
  163. AXISTEST_Y02(e1.z, e1.x, fez, fex);
  164. AXISTEST_Z0(e1.y, e1.x, fey, fex);
  165. fex = Math::abs(e2.x);
  166. fey = Math::abs(e2.y);
  167. fez = Math::abs(e2.z);
  168. AXISTEST_X2(e2.z, e2.y, fez, fey);
  169. AXISTEST_Y1(e2.z, e2.x, fez, fex);
  170. AXISTEST_Z12(e2.y, e2.x, fey, fex);
  171. /* Bullet 1: */
  172. /* first test overlap in the {x,y,z}-directions */
  173. /* find min, max of the triangle each direction, and test for overlap in */
  174. /* that direction -- this is equivalent to testing a minimal AABB around */
  175. /* the triangle against the AABB */
  176. /* test in X-direction */
  177. FINDMINMAX(v0.x, v1.x, v2.x, min, max);
  178. if (min > boxhalfsize.x || max < -boxhalfsize.x) return false;
  179. /* test in Y-direction */
  180. FINDMINMAX(v0.y, v1.y, v2.y, min, max);
  181. if (min > boxhalfsize.y || max < -boxhalfsize.y) return false;
  182. /* test in Z-direction */
  183. FINDMINMAX(v0.z, v1.z, v2.z, min, max);
  184. if (min > boxhalfsize.z || max < -boxhalfsize.z) return false;
  185. /* Bullet 2: */
  186. /* test if the box intersects the plane of the triangle */
  187. /* compute plane equation of triangle: normal*x+d=0 */
  188. normal = e0.cross(e1);
  189. d = -normal.dot(v0); /* plane eq: normal.x+d=0 */
  190. if (!planeBoxOverlap(normal, d, boxhalfsize)) return false;
  191. return true; /* box and triangle overlaps */
  192. }
  193. static _FORCE_INLINE_ void get_uv_and_normal(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv, const Vector3 *p_normal, Vector2 &r_uv, Vector3 &r_normal) {
  194. if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2) {
  195. r_uv = p_uv[0];
  196. r_normal = p_normal[0];
  197. return;
  198. }
  199. if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2) {
  200. r_uv = p_uv[1];
  201. r_normal = p_normal[1];
  202. return;
  203. }
  204. if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2) {
  205. r_uv = p_uv[2];
  206. r_normal = p_normal[2];
  207. return;
  208. }
  209. Vector3 v0 = p_vtx[1] - p_vtx[0];
  210. Vector3 v1 = p_vtx[2] - p_vtx[0];
  211. Vector3 v2 = p_pos - p_vtx[0];
  212. float d00 = v0.dot(v0);
  213. float d01 = v0.dot(v1);
  214. float d11 = v1.dot(v1);
  215. float d20 = v2.dot(v0);
  216. float d21 = v2.dot(v1);
  217. float denom = (d00 * d11 - d01 * d01);
  218. if (denom == 0) {
  219. r_uv = p_uv[0];
  220. r_normal = p_normal[0];
  221. return;
  222. }
  223. float v = (d11 * d20 - d01 * d21) / denom;
  224. float w = (d00 * d21 - d01 * d20) / denom;
  225. float u = 1.0f - v - w;
  226. r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
  227. r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
  228. }
  229. void VoxelLightBaker::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 *p_vtx, const Vector3 *p_normal, const Vector2 *p_uv, const MaterialCache &p_material, const AABB &p_aabb) {
  230. if (p_level == cell_subdiv - 1) {
  231. //plot the face by guessing its albedo and emission value
  232. //find best axis to map to, for scanning values
  233. int closest_axis = 0;
  234. float closest_dot = 0;
  235. Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
  236. Vector3 normal = plane.normal;
  237. for (int i = 0; i < 3; i++) {
  238. Vector3 axis;
  239. axis[i] = 1.0;
  240. float dot = ABS(normal.dot(axis));
  241. if (i == 0 || dot > closest_dot) {
  242. closest_axis = i;
  243. closest_dot = dot;
  244. }
  245. }
  246. Vector3 axis;
  247. axis[closest_axis] = 1.0;
  248. Vector3 t1;
  249. t1[(closest_axis + 1) % 3] = 1.0;
  250. Vector3 t2;
  251. t2[(closest_axis + 2) % 3] = 1.0;
  252. t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width);
  253. t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width);
  254. Color albedo_accum;
  255. Color emission_accum;
  256. Vector3 normal_accum;
  257. float alpha = 0.0;
  258. //map to a grid average in the best axis for this face
  259. for (int i = 0; i < color_scan_cell_width; i++) {
  260. Vector3 ofs_i = float(i) * t1;
  261. for (int j = 0; j < color_scan_cell_width; j++) {
  262. Vector3 ofs_j = float(j) * t2;
  263. Vector3 from = p_aabb.position + ofs_i + ofs_j;
  264. Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
  265. Vector3 half = (to - from) * 0.5;
  266. //is in this cell?
  267. if (!fast_tri_box_overlap(from + half, half, p_vtx)) {
  268. continue; //face does not span this cell
  269. }
  270. //go from -size to +size*2 to avoid skipping collisions
  271. Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
  272. Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
  273. if (normal.dot(ray_from - ray_to) < 0) {
  274. SWAP(ray_from, ray_to);
  275. }
  276. Vector3 intersection;
  277. if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
  278. if (ABS(plane.distance_to(ray_from)) < ABS(plane.distance_to(ray_to))) {
  279. intersection = plane.project(ray_from);
  280. } else {
  281. intersection = plane.project(ray_to);
  282. }
  283. }
  284. intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
  285. Vector2 uv;
  286. Vector3 lnormal;
  287. get_uv_and_normal(intersection, p_vtx, p_uv, p_normal, uv, lnormal);
  288. if (lnormal == Vector3()) //just in case normal as nor provided
  289. lnormal = normal;
  290. int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  291. int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  292. int ofs = uv_y * bake_texture_size + uv_x;
  293. albedo_accum.r += p_material.albedo[ofs].r;
  294. albedo_accum.g += p_material.albedo[ofs].g;
  295. albedo_accum.b += p_material.albedo[ofs].b;
  296. albedo_accum.a += p_material.albedo[ofs].a;
  297. emission_accum.r += p_material.emission[ofs].r;
  298. emission_accum.g += p_material.emission[ofs].g;
  299. emission_accum.b += p_material.emission[ofs].b;
  300. normal_accum += lnormal;
  301. alpha += 1.0;
  302. }
  303. }
  304. if (alpha == 0) {
  305. //could not in any way get texture information.. so use closest point to center
  306. Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
  307. Vector3 inters = f.get_closest_point_to(p_aabb.position + p_aabb.size * 0.5);
  308. Vector3 lnormal;
  309. Vector2 uv;
  310. get_uv_and_normal(inters, p_vtx, p_uv, p_normal, uv, normal);
  311. if (lnormal == Vector3()) //just in case normal as nor provided
  312. lnormal = normal;
  313. int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  314. int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
  315. int ofs = uv_y * bake_texture_size + uv_x;
  316. alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  317. albedo_accum.r = p_material.albedo[ofs].r * alpha;
  318. albedo_accum.g = p_material.albedo[ofs].g * alpha;
  319. albedo_accum.b = p_material.albedo[ofs].b * alpha;
  320. albedo_accum.a = p_material.albedo[ofs].a * alpha;
  321. emission_accum.r = p_material.emission[ofs].r * alpha;
  322. emission_accum.g = p_material.emission[ofs].g * alpha;
  323. emission_accum.b = p_material.emission[ofs].b * alpha;
  324. normal_accum = lnormal * alpha;
  325. } else {
  326. float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  327. alpha *= accdiv;
  328. albedo_accum.r *= accdiv;
  329. albedo_accum.g *= accdiv;
  330. albedo_accum.b *= accdiv;
  331. albedo_accum.a *= accdiv;
  332. emission_accum.r *= accdiv;
  333. emission_accum.g *= accdiv;
  334. emission_accum.b *= accdiv;
  335. normal_accum *= accdiv;
  336. }
  337. //put this temporarily here, corrected in a later step
  338. bake_cells.write[p_idx].albedo[0] += albedo_accum.r;
  339. bake_cells.write[p_idx].albedo[1] += albedo_accum.g;
  340. bake_cells.write[p_idx].albedo[2] += albedo_accum.b;
  341. bake_cells.write[p_idx].emission[0] += emission_accum.r;
  342. bake_cells.write[p_idx].emission[1] += emission_accum.g;
  343. bake_cells.write[p_idx].emission[2] += emission_accum.b;
  344. bake_cells.write[p_idx].normal[0] += normal_accum.x;
  345. bake_cells.write[p_idx].normal[1] += normal_accum.y;
  346. bake_cells.write[p_idx].normal[2] += normal_accum.z;
  347. bake_cells.write[p_idx].alpha += alpha;
  348. } else {
  349. //go down
  350. int half = (1 << (cell_subdiv - 1)) >> (p_level + 1);
  351. for (int i = 0; i < 8; i++) {
  352. AABB aabb = p_aabb;
  353. aabb.size *= 0.5;
  354. int nx = p_x;
  355. int ny = p_y;
  356. int nz = p_z;
  357. if (i & 1) {
  358. aabb.position.x += aabb.size.x;
  359. nx += half;
  360. }
  361. if (i & 2) {
  362. aabb.position.y += aabb.size.y;
  363. ny += half;
  364. }
  365. if (i & 4) {
  366. aabb.position.z += aabb.size.z;
  367. nz += half;
  368. }
  369. //make sure to not plot beyond limits
  370. if (nx < 0 || nx >= axis_cell_size[0] || ny < 0 || ny >= axis_cell_size[1] || nz < 0 || nz >= axis_cell_size[2])
  371. continue;
  372. {
  373. AABB test_aabb = aabb;
  374. //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
  375. Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
  376. if (!fast_tri_box_overlap(test_aabb.position + qsize, qsize, p_vtx)) {
  377. //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
  378. //does not fit in child, go on
  379. continue;
  380. }
  381. }
  382. if (bake_cells[p_idx].children[i] == CHILD_EMPTY) {
  383. //sub cell must be created
  384. uint32_t child_idx = bake_cells.size();
  385. bake_cells.write[p_idx].children[i] = child_idx;
  386. bake_cells.resize(bake_cells.size() + 1);
  387. bake_cells.write[child_idx].level = p_level + 1;
  388. }
  389. _plot_face(bake_cells[p_idx].children[i], p_level + 1, nx, ny, nz, p_vtx, p_normal, p_uv, p_material, aabb);
  390. }
  391. }
  392. }
  393. Vector<Color> VoxelLightBaker::_get_bake_texture(Ref<Image> p_image, const Color &p_color_mul, const Color &p_color_add) {
  394. Vector<Color> ret;
  395. if (p_image.is_null() || p_image->empty()) {
  396. ret.resize(bake_texture_size * bake_texture_size);
  397. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  398. ret.write[i] = p_color_add;
  399. }
  400. return ret;
  401. }
  402. p_image = p_image->duplicate();
  403. if (p_image->is_compressed()) {
  404. p_image->decompress();
  405. }
  406. p_image->convert(Image::FORMAT_RGBA8);
  407. p_image->resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
  408. PoolVector<uint8_t>::Read r = p_image->get_data().read();
  409. ret.resize(bake_texture_size * bake_texture_size);
  410. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  411. Color c;
  412. c.r = (r[i * 4 + 0] / 255.0) * p_color_mul.r + p_color_add.r;
  413. c.g = (r[i * 4 + 1] / 255.0) * p_color_mul.g + p_color_add.g;
  414. c.b = (r[i * 4 + 2] / 255.0) * p_color_mul.b + p_color_add.b;
  415. c.a = r[i * 4 + 3] / 255.0;
  416. ret.write[i] = c;
  417. }
  418. return ret;
  419. }
  420. VoxelLightBaker::MaterialCache VoxelLightBaker::_get_material_cache(Ref<Material> p_material) {
  421. //this way of obtaining materials is inaccurate and also does not support some compressed formats very well
  422. Ref<SpatialMaterial> mat = p_material;
  423. Ref<Material> material = mat; //hack for now
  424. if (material_cache.has(material)) {
  425. return material_cache[material];
  426. }
  427. MaterialCache mc;
  428. if (mat.is_valid()) {
  429. Ref<Texture> albedo_tex = mat->get_texture(SpatialMaterial::TEXTURE_ALBEDO);
  430. Ref<Image> img_albedo;
  431. if (albedo_tex.is_valid()) {
  432. img_albedo = albedo_tex->get_data();
  433. mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo(), Color(0, 0, 0)); // albedo texture, color is multiplicative
  434. } else {
  435. mc.albedo = _get_bake_texture(img_albedo, Color(1, 1, 1), mat->get_albedo()); // no albedo texture, color is additive
  436. }
  437. Ref<Texture> emission_tex = mat->get_texture(SpatialMaterial::TEXTURE_EMISSION);
  438. Color emission_col = mat->get_emission();
  439. float emission_energy = mat->get_emission_energy();
  440. Ref<Image> img_emission;
  441. if (emission_tex.is_valid()) {
  442. img_emission = emission_tex->get_data();
  443. }
  444. if (mat->get_emission_operator() == SpatialMaterial::EMISSION_OP_ADD) {
  445. mc.emission = _get_bake_texture(img_emission, Color(1, 1, 1) * emission_energy, emission_col * emission_energy);
  446. } else {
  447. mc.emission = _get_bake_texture(img_emission, emission_col * emission_energy, Color(0, 0, 0));
  448. }
  449. } else {
  450. Ref<Image> empty;
  451. mc.albedo = _get_bake_texture(empty, Color(0, 0, 0), Color(1, 1, 1));
  452. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  453. }
  454. material_cache[p_material] = mc;
  455. return mc;
  456. }
  457. void VoxelLightBaker::plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material> > &p_materials, const Ref<Material> &p_override_material) {
  458. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  459. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
  460. continue; //only triangles
  461. Ref<Material> src_material;
  462. if (p_override_material.is_valid()) {
  463. src_material = p_override_material;
  464. } else if (i < p_materials.size() && p_materials[i].is_valid()) {
  465. src_material = p_materials[i];
  466. } else {
  467. src_material = p_mesh->surface_get_material(i);
  468. }
  469. MaterialCache material = _get_material_cache(src_material);
  470. Array a = p_mesh->surface_get_arrays(i);
  471. PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  472. PoolVector<Vector3>::Read vr = vertices.read();
  473. PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
  474. PoolVector<Vector2>::Read uvr;
  475. PoolVector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  476. PoolVector<Vector3>::Read nr;
  477. PoolVector<int> index = a[Mesh::ARRAY_INDEX];
  478. bool read_uv = false;
  479. bool read_normals = false;
  480. if (uv.size()) {
  481. uvr = uv.read();
  482. read_uv = true;
  483. }
  484. if (normals.size()) {
  485. read_normals = true;
  486. nr = normals.read();
  487. }
  488. if (index.size()) {
  489. int facecount = index.size() / 3;
  490. PoolVector<int>::Read ir = index.read();
  491. for (int j = 0; j < facecount; j++) {
  492. Vector3 vtxs[3];
  493. Vector2 uvs[3];
  494. Vector3 normal[3];
  495. for (int k = 0; k < 3; k++) {
  496. vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
  497. }
  498. if (read_uv) {
  499. for (int k = 0; k < 3; k++) {
  500. uvs[k] = uvr[ir[j * 3 + k]];
  501. }
  502. }
  503. if (read_normals) {
  504. for (int k = 0; k < 3; k++) {
  505. normal[k] = nr[ir[j * 3 + k]];
  506. }
  507. }
  508. //test against original bounds
  509. if (!fast_tri_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs))
  510. continue;
  511. //plot
  512. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  513. }
  514. } else {
  515. int facecount = vertices.size() / 3;
  516. for (int j = 0; j < facecount; j++) {
  517. Vector3 vtxs[3];
  518. Vector2 uvs[3];
  519. Vector3 normal[3];
  520. for (int k = 0; k < 3; k++) {
  521. vtxs[k] = p_xform.xform(vr[j * 3 + k]);
  522. }
  523. if (read_uv) {
  524. for (int k = 0; k < 3; k++) {
  525. uvs[k] = uvr[j * 3 + k];
  526. }
  527. }
  528. if (read_normals) {
  529. for (int k = 0; k < 3; k++) {
  530. normal[k] = nr[j * 3 + k];
  531. }
  532. }
  533. //test against original bounds
  534. if (!fast_tri_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs))
  535. continue;
  536. //plot face
  537. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  538. }
  539. }
  540. }
  541. max_original_cells = bake_cells.size();
  542. }
  543. void VoxelLightBaker::_init_light_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, uint32_t p_parent) {
  544. bake_light.write[p_idx].x = p_x;
  545. bake_light.write[p_idx].y = p_y;
  546. bake_light.write[p_idx].z = p_z;
  547. if (p_level == cell_subdiv - 1) {
  548. bake_light.write[p_idx].next_leaf = first_leaf;
  549. first_leaf = p_idx;
  550. } else {
  551. //go down
  552. int half = (1 << (cell_subdiv - 1)) >> (p_level + 1);
  553. for (int i = 0; i < 8; i++) {
  554. uint32_t child = bake_cells[p_idx].children[i];
  555. if (child == CHILD_EMPTY)
  556. continue;
  557. int nx = p_x;
  558. int ny = p_y;
  559. int nz = p_z;
  560. if (i & 1)
  561. nx += half;
  562. if (i & 2)
  563. ny += half;
  564. if (i & 4)
  565. nz += half;
  566. _init_light_plot(child, p_level + 1, nx, ny, nz, p_idx);
  567. }
  568. }
  569. }
  570. void VoxelLightBaker::begin_bake_light(BakeQuality p_quality, BakeMode p_bake_mode, float p_propagation, float p_energy) {
  571. _check_init_light();
  572. propagation = p_propagation;
  573. bake_quality = p_quality;
  574. bake_mode = p_bake_mode;
  575. energy = p_energy;
  576. }
  577. void VoxelLightBaker::_check_init_light() {
  578. if (bake_light.size() == 0) {
  579. direct_lights_baked = false;
  580. leaf_voxel_count = 0;
  581. _fixup_plot(0, 0); //pre fixup, so normal, albedo, emission, etc. work for lighting.
  582. bake_light.resize(bake_cells.size());
  583. print_line("bake light size: " + itos(bake_light.size()));
  584. //zeromem(bake_light.ptrw(), bake_light.size() * sizeof(Light));
  585. first_leaf = -1;
  586. _init_light_plot(0, 0, 0, 0, 0, CHILD_EMPTY);
  587. }
  588. }
  589. static float _get_normal_advance(const Vector3 &p_normal) {
  590. Vector3 normal = p_normal;
  591. Vector3 unorm = normal.abs();
  592. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  593. // x code
  594. unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
  595. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  596. // y code
  597. unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
  598. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  599. // z code
  600. unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
  601. } else {
  602. // oh-no we messed up code
  603. // has to be
  604. unorm = Vector3(1.0, 0.0, 0.0);
  605. }
  606. return 1.0 / normal.dot(unorm);
  607. }
  608. static const Vector3 aniso_normal[6] = {
  609. Vector3(-1, 0, 0),
  610. Vector3(1, 0, 0),
  611. Vector3(0, -1, 0),
  612. Vector3(0, 1, 0),
  613. Vector3(0, 0, -1),
  614. Vector3(0, 0, 1)
  615. };
  616. uint32_t VoxelLightBaker::_find_cell_at_pos(const Cell *cells, int x, int y, int z) {
  617. uint32_t cell = 0;
  618. int ofs_x = 0;
  619. int ofs_y = 0;
  620. int ofs_z = 0;
  621. int size = 1 << (cell_subdiv - 1);
  622. int half = size / 2;
  623. if (x < 0 || x >= size)
  624. return -1;
  625. if (y < 0 || y >= size)
  626. return -1;
  627. if (z < 0 || z >= size)
  628. return -1;
  629. for (int i = 0; i < cell_subdiv - 1; i++) {
  630. const Cell *bc = &cells[cell];
  631. int child = 0;
  632. if (x >= ofs_x + half) {
  633. child |= 1;
  634. ofs_x += half;
  635. }
  636. if (y >= ofs_y + half) {
  637. child |= 2;
  638. ofs_y += half;
  639. }
  640. if (z >= ofs_z + half) {
  641. child |= 4;
  642. ofs_z += half;
  643. }
  644. cell = bc->children[child];
  645. if (cell == CHILD_EMPTY)
  646. return CHILD_EMPTY;
  647. half >>= 1;
  648. }
  649. return cell;
  650. }
  651. void VoxelLightBaker::plot_light_directional(const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, bool p_direct) {
  652. _check_init_light();
  653. float max_len = Vector3(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]).length() * 1.1;
  654. if (p_direct)
  655. direct_lights_baked = true;
  656. Vector3 light_axis = p_direction;
  657. Plane clip[3];
  658. int clip_planes = 0;
  659. Light *light_data = bake_light.ptrw();
  660. const Cell *cells = bake_cells.ptr();
  661. for (int i = 0; i < 3; i++) {
  662. if (ABS(light_axis[i]) < CMP_EPSILON)
  663. continue;
  664. clip[clip_planes].normal[i] = 1.0;
  665. if (light_axis[i] < 0) {
  666. clip[clip_planes].d = axis_cell_size[i] + 1;
  667. } else {
  668. clip[clip_planes].d -= 1.0;
  669. }
  670. clip_planes++;
  671. }
  672. float distance_adv = _get_normal_advance(light_axis);
  673. int success_count = 0;
  674. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  675. int idx = first_leaf;
  676. while (idx >= 0) {
  677. Light *light = &light_data[idx];
  678. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  679. to += -light_axis.sign() * 0.47; //make it more likely to receive a ray
  680. Vector3 from = to - max_len * light_axis;
  681. for (int j = 0; j < clip_planes; j++) {
  682. clip[j].intersects_segment(from, to, &from);
  683. }
  684. float distance = (to - from).length();
  685. distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
  686. from = to - light_axis * distance;
  687. uint32_t result = 0xFFFFFFFF;
  688. while (distance > -distance_adv) { //use this to avoid precision errors
  689. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  690. if (result != 0xFFFFFFFF) {
  691. break;
  692. }
  693. from += light_axis * distance_adv;
  694. distance -= distance_adv;
  695. }
  696. if (result == idx) {
  697. //cell hit itself! hooray!
  698. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  699. if (normal == Vector3()) {
  700. for (int i = 0; i < 6; i++) {
  701. light->accum[i][0] += light_energy.x * cells[idx].albedo[0];
  702. light->accum[i][1] += light_energy.y * cells[idx].albedo[1];
  703. light->accum[i][2] += light_energy.z * cells[idx].albedo[2];
  704. }
  705. } else {
  706. for (int i = 0; i < 6; i++) {
  707. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  708. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s;
  709. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s;
  710. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s;
  711. }
  712. }
  713. if (p_direct) {
  714. for (int i = 0; i < 6; i++) {
  715. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  716. light->direct_accum[i][0] += light_energy.x * s;
  717. light->direct_accum[i][1] += light_energy.y * s;
  718. light->direct_accum[i][2] += light_energy.z * s;
  719. }
  720. }
  721. success_count++;
  722. }
  723. idx = light_data[idx].next_leaf;
  724. }
  725. }
  726. void VoxelLightBaker::plot_light_omni(const Vector3 &p_pos, const Color &p_color, float p_energy, float p_indirect_energy, float p_radius, float p_attenutation, bool p_direct) {
  727. _check_init_light();
  728. if (p_direct)
  729. direct_lights_baked = true;
  730. Plane clip[3];
  731. int clip_planes = 0;
  732. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  733. Vector3 light_pos = to_cell_space.xform(p_pos) + Vector3(0.5, 0.5, 0.5);
  734. //Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
  735. float local_radius = to_cell_space.basis.xform(Vector3(0, 0, 1)).length() * p_radius;
  736. Light *light_data = bake_light.ptrw();
  737. const Cell *cells = bake_cells.ptr();
  738. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  739. int idx = first_leaf;
  740. while (idx >= 0) {
  741. Light *light = &light_data[idx];
  742. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  743. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  744. Vector3 light_axis = (to - light_pos).normalized();
  745. float distance_adv = _get_normal_advance(light_axis);
  746. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  747. if (normal != Vector3() && normal.dot(-light_axis) < 0.001) {
  748. idx = light_data[idx].next_leaf;
  749. continue;
  750. }
  751. float att = 1.0;
  752. {
  753. float d = light_pos.distance_to(to);
  754. if (d + distance_adv > local_radius) {
  755. idx = light_data[idx].next_leaf;
  756. continue; // too far away
  757. }
  758. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  759. att *= powf(1.0 - dt, p_attenutation);
  760. }
  761. clip_planes = 0;
  762. for (int c = 0; c < 3; c++) {
  763. if (ABS(light_axis[c]) < CMP_EPSILON)
  764. continue;
  765. clip[clip_planes].normal[c] = 1.0;
  766. if (light_axis[c] < 0) {
  767. clip[clip_planes].d = (1 << (cell_subdiv - 1)) + 1;
  768. } else {
  769. clip[clip_planes].d -= 1.0;
  770. }
  771. clip_planes++;
  772. }
  773. Vector3 from = light_pos;
  774. for (int j = 0; j < clip_planes; j++) {
  775. clip[j].intersects_segment(from, to, &from);
  776. }
  777. float distance = (to - from).length();
  778. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  779. from = to - light_axis * distance;
  780. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  781. uint32_t result = 0xFFFFFFFF;
  782. while (distance > -distance_adv) { //use this to avoid precision errors
  783. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  784. if (result != 0xFFFFFFFF) {
  785. break;
  786. }
  787. from += light_axis * distance_adv;
  788. distance -= distance_adv;
  789. }
  790. if (result == idx) {
  791. //cell hit itself! hooray!
  792. if (normal == Vector3()) {
  793. for (int i = 0; i < 6; i++) {
  794. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * att;
  795. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * att;
  796. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * att;
  797. }
  798. } else {
  799. for (int i = 0; i < 6; i++) {
  800. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  801. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s * att;
  802. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s * att;
  803. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s * att;
  804. }
  805. }
  806. if (p_direct) {
  807. for (int i = 0; i < 6; i++) {
  808. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  809. light->direct_accum[i][0] += light_energy.x * s * att;
  810. light->direct_accum[i][1] += light_energy.y * s * att;
  811. light->direct_accum[i][2] += light_energy.z * s * att;
  812. }
  813. }
  814. }
  815. idx = light_data[idx].next_leaf;
  816. }
  817. }
  818. void VoxelLightBaker::plot_light_spot(const Vector3 &p_pos, const Vector3 &p_axis, const Color &p_color, float p_energy, float p_indirect_energy, float p_radius, float p_attenutation, float p_spot_angle, float p_spot_attenuation, bool p_direct) {
  819. _check_init_light();
  820. if (p_direct)
  821. direct_lights_baked = true;
  822. Plane clip[3];
  823. int clip_planes = 0;
  824. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  825. Vector3 light_pos = to_cell_space.xform(p_pos) + Vector3(0.5, 0.5, 0.5);
  826. Vector3 spot_axis = to_cell_space.basis.xform(p_axis).normalized();
  827. float local_radius = to_cell_space.basis.xform(Vector3(0, 0, 1)).length() * p_radius;
  828. Light *light_data = bake_light.ptrw();
  829. const Cell *cells = bake_cells.ptr();
  830. Vector3 light_energy = Vector3(p_color.r, p_color.g, p_color.b) * p_energy * p_indirect_energy;
  831. int idx = first_leaf;
  832. while (idx >= 0) {
  833. Light *light = &light_data[idx];
  834. Vector3 to(light->x + 0.5, light->y + 0.5, light->z + 0.5);
  835. Vector3 light_axis = (to - light_pos).normalized();
  836. float distance_adv = _get_normal_advance(light_axis);
  837. Vector3 normal(cells[idx].normal[0], cells[idx].normal[1], cells[idx].normal[2]);
  838. if (normal != Vector3() && normal.dot(-light_axis) < 0.001) {
  839. idx = light_data[idx].next_leaf;
  840. continue;
  841. }
  842. float angle = Math::rad2deg(Math::acos(light_axis.dot(-spot_axis)));
  843. if (angle > p_spot_angle) {
  844. idx = light_data[idx].next_leaf;
  845. continue; // too far away
  846. }
  847. float att = Math::pow(1.0f - angle / p_spot_angle, p_spot_attenuation);
  848. {
  849. float d = light_pos.distance_to(to);
  850. if (d + distance_adv > local_radius) {
  851. idx = light_data[idx].next_leaf;
  852. continue; // too far away
  853. }
  854. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  855. att *= powf(1.0 - dt, p_attenutation);
  856. }
  857. clip_planes = 0;
  858. for (int c = 0; c < 3; c++) {
  859. if (ABS(light_axis[c]) < CMP_EPSILON)
  860. continue;
  861. clip[clip_planes].normal[c] = 1.0;
  862. if (light_axis[c] < 0) {
  863. clip[clip_planes].d = (1 << (cell_subdiv - 1)) + 1;
  864. } else {
  865. clip[clip_planes].d -= 1.0;
  866. }
  867. clip_planes++;
  868. }
  869. Vector3 from = light_pos;
  870. for (int j = 0; j < clip_planes; j++) {
  871. clip[j].intersects_segment(from, to, &from);
  872. }
  873. float distance = (to - from).length();
  874. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  875. from = to - light_axis * distance;
  876. uint32_t result = 0xFFFFFFFF;
  877. while (distance > -distance_adv) { //use this to avoid precision errors
  878. result = _find_cell_at_pos(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)));
  879. if (result != 0xFFFFFFFF) {
  880. break;
  881. }
  882. from += light_axis * distance_adv;
  883. distance -= distance_adv;
  884. }
  885. if (result == idx) {
  886. //cell hit itself! hooray!
  887. if (normal == Vector3()) {
  888. for (int i = 0; i < 6; i++) {
  889. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * att;
  890. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * att;
  891. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * att;
  892. }
  893. } else {
  894. for (int i = 0; i < 6; i++) {
  895. float s = MAX(0.0, aniso_normal[i].dot(-normal));
  896. light->accum[i][0] += light_energy.x * cells[idx].albedo[0] * s * att;
  897. light->accum[i][1] += light_energy.y * cells[idx].albedo[1] * s * att;
  898. light->accum[i][2] += light_energy.z * cells[idx].albedo[2] * s * att;
  899. }
  900. }
  901. if (p_direct) {
  902. for (int i = 0; i < 6; i++) {
  903. float s = MAX(0.0, aniso_normal[i].dot(-light_axis)); //light depending on normal for direct
  904. light->direct_accum[i][0] += light_energy.x * s * att;
  905. light->direct_accum[i][1] += light_energy.y * s * att;
  906. light->direct_accum[i][2] += light_energy.z * s * att;
  907. }
  908. }
  909. }
  910. idx = light_data[idx].next_leaf;
  911. }
  912. }
  913. void VoxelLightBaker::_fixup_plot(int p_idx, int p_level) {
  914. if (p_level == cell_subdiv - 1) {
  915. leaf_voxel_count++;
  916. float alpha = bake_cells[p_idx].alpha;
  917. bake_cells.write[p_idx].albedo[0] /= alpha;
  918. bake_cells.write[p_idx].albedo[1] /= alpha;
  919. bake_cells.write[p_idx].albedo[2] /= alpha;
  920. //transfer emission to light
  921. bake_cells.write[p_idx].emission[0] /= alpha;
  922. bake_cells.write[p_idx].emission[1] /= alpha;
  923. bake_cells.write[p_idx].emission[2] /= alpha;
  924. bake_cells.write[p_idx].normal[0] /= alpha;
  925. bake_cells.write[p_idx].normal[1] /= alpha;
  926. bake_cells.write[p_idx].normal[2] /= alpha;
  927. Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
  928. if (n.length() < 0.01) {
  929. //too much fight over normal, zero it
  930. bake_cells.write[p_idx].normal[0] = 0;
  931. bake_cells.write[p_idx].normal[1] = 0;
  932. bake_cells.write[p_idx].normal[2] = 0;
  933. } else {
  934. n.normalize();
  935. bake_cells.write[p_idx].normal[0] = n.x;
  936. bake_cells.write[p_idx].normal[1] = n.y;
  937. bake_cells.write[p_idx].normal[2] = n.z;
  938. }
  939. bake_cells.write[p_idx].alpha = 1.0;
  940. /*if (bake_light.size()) {
  941. for(int i=0;i<6;i++) {
  942. }
  943. }*/
  944. } else {
  945. //go down
  946. bake_cells.write[p_idx].emission[0] = 0;
  947. bake_cells.write[p_idx].emission[1] = 0;
  948. bake_cells.write[p_idx].emission[2] = 0;
  949. bake_cells.write[p_idx].normal[0] = 0;
  950. bake_cells.write[p_idx].normal[1] = 0;
  951. bake_cells.write[p_idx].normal[2] = 0;
  952. bake_cells.write[p_idx].albedo[0] = 0;
  953. bake_cells.write[p_idx].albedo[1] = 0;
  954. bake_cells.write[p_idx].albedo[2] = 0;
  955. if (bake_light.size()) {
  956. for (int j = 0; j < 6; j++) {
  957. bake_light.write[p_idx].accum[j][0] = 0;
  958. bake_light.write[p_idx].accum[j][1] = 0;
  959. bake_light.write[p_idx].accum[j][2] = 0;
  960. }
  961. }
  962. float alpha_average = 0;
  963. int children_found = 0;
  964. for (int i = 0; i < 8; i++) {
  965. uint32_t child = bake_cells[p_idx].children[i];
  966. if (child == CHILD_EMPTY)
  967. continue;
  968. _fixup_plot(child, p_level + 1);
  969. alpha_average += bake_cells[child].alpha;
  970. if (bake_light.size() > 0) {
  971. for (int j = 0; j < 6; j++) {
  972. bake_light.write[p_idx].accum[j][0] += bake_light[child].accum[j][0];
  973. bake_light.write[p_idx].accum[j][1] += bake_light[child].accum[j][1];
  974. bake_light.write[p_idx].accum[j][2] += bake_light[child].accum[j][2];
  975. }
  976. bake_cells.write[p_idx].emission[0] += bake_cells[child].emission[0];
  977. bake_cells.write[p_idx].emission[1] += bake_cells[child].emission[1];
  978. bake_cells.write[p_idx].emission[2] += bake_cells[child].emission[2];
  979. }
  980. children_found++;
  981. }
  982. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  983. if (bake_light.size() && children_found) {
  984. float divisor = Math::lerp(8, children_found, propagation);
  985. for (int j = 0; j < 6; j++) {
  986. bake_light.write[p_idx].accum[j][0] /= divisor;
  987. bake_light.write[p_idx].accum[j][1] /= divisor;
  988. bake_light.write[p_idx].accum[j][2] /= divisor;
  989. }
  990. bake_cells.write[p_idx].emission[0] /= divisor;
  991. bake_cells.write[p_idx].emission[1] /= divisor;
  992. bake_cells.write[p_idx].emission[2] /= divisor;
  993. }
  994. }
  995. }
  996. //make sure any cell (save for the root) has an empty cell previous to it, so it can be interpolated into
  997. void VoxelLightBaker::_plot_triangle(Vector2 *vertices, Vector3 *positions, Vector3 *normals, LightMap *pixels, int width, int height) {
  998. int x[3];
  999. int y[3];
  1000. for (int j = 0; j < 3; j++) {
  1001. x[j] = vertices[j].x * width;
  1002. y[j] = vertices[j].y * height;
  1003. //x[j] = CLAMP(x[j], 0, bt.width - 1);
  1004. //y[j] = CLAMP(y[j], 0, bt.height - 1);
  1005. }
  1006. // sort the points vertically
  1007. if (y[1] > y[2]) {
  1008. SWAP(x[1], x[2]);
  1009. SWAP(y[1], y[2]);
  1010. SWAP(positions[1], positions[2]);
  1011. SWAP(normals[1], normals[2]);
  1012. }
  1013. if (y[0] > y[1]) {
  1014. SWAP(x[0], x[1]);
  1015. SWAP(y[0], y[1]);
  1016. SWAP(positions[0], positions[1]);
  1017. SWAP(normals[0], normals[1]);
  1018. }
  1019. if (y[1] > y[2]) {
  1020. SWAP(x[1], x[2]);
  1021. SWAP(y[1], y[2]);
  1022. SWAP(positions[1], positions[2]);
  1023. SWAP(normals[1], normals[2]);
  1024. }
  1025. double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);
  1026. double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);
  1027. double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);
  1028. double xf = x[0];
  1029. double xt = x[0] + dx_upper; // if y[0] == y[1], special case
  1030. for (int yi = y[0]; yi <= (y[2] > height - 1 ? height - 1 : y[2]); yi++) {
  1031. if (yi >= 0) {
  1032. for (int xi = (xf > 0 ? int(xf) : 0); xi <= (xt < width ? xt : width - 1); xi++) {
  1033. //pixels[int(x + y * width)] = color;
  1034. Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
  1035. Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
  1036. //vertices[2] - vertices[0];
  1037. Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
  1038. float d00 = v0.dot(v0);
  1039. float d01 = v0.dot(v1);
  1040. float d11 = v1.dot(v1);
  1041. float d20 = v2.dot(v0);
  1042. float d21 = v2.dot(v1);
  1043. float denom = (d00 * d11 - d01 * d01);
  1044. Vector3 pos;
  1045. Vector3 normal;
  1046. if (denom == 0) {
  1047. pos = positions[0];
  1048. normal = normals[0];
  1049. } else {
  1050. float v = (d11 * d20 - d01 * d21) / denom;
  1051. float w = (d00 * d21 - d01 * d20) / denom;
  1052. float u = 1.0f - v - w;
  1053. pos = positions[0] * u + positions[1] * v + positions[2] * w;
  1054. normal = normals[0] * u + normals[1] * v + normals[2] * w;
  1055. }
  1056. int ofs = yi * width + xi;
  1057. pixels[ofs].normal = normal;
  1058. pixels[ofs].pos = pos;
  1059. }
  1060. for (int xi = (xf < width ? int(xf) : width - 1); xi >= (xt > 0 ? xt : 0); xi--) {
  1061. //pixels[int(x + y * width)] = color;
  1062. Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
  1063. Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
  1064. //vertices[2] - vertices[0];
  1065. Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
  1066. float d00 = v0.dot(v0);
  1067. float d01 = v0.dot(v1);
  1068. float d11 = v1.dot(v1);
  1069. float d20 = v2.dot(v0);
  1070. float d21 = v2.dot(v1);
  1071. float denom = (d00 * d11 - d01 * d01);
  1072. Vector3 pos;
  1073. Vector3 normal;
  1074. if (denom == 0) {
  1075. pos = positions[0];
  1076. normal = normals[0];
  1077. } else {
  1078. float v = (d11 * d20 - d01 * d21) / denom;
  1079. float w = (d00 * d21 - d01 * d20) / denom;
  1080. float u = 1.0f - v - w;
  1081. pos = positions[0] * u + positions[1] * v + positions[2] * w;
  1082. normal = normals[0] * u + normals[1] * v + normals[2] * w;
  1083. }
  1084. int ofs = yi * width + xi;
  1085. pixels[ofs].normal = normal;
  1086. pixels[ofs].pos = pos;
  1087. }
  1088. }
  1089. xf += dx_far;
  1090. if (yi < y[1])
  1091. xt += dx_upper;
  1092. else
  1093. xt += dx_low;
  1094. }
  1095. }
  1096. void VoxelLightBaker::_sample_baked_octree_filtered_and_anisotropic(const Vector3 &p_posf, const Vector3 &p_direction, float p_level, Vector3 &r_color, float &r_alpha) {
  1097. int size = 1 << (cell_subdiv - 1);
  1098. int clamp_v = size - 1;
  1099. //first of all, clamp
  1100. Vector3 pos;
  1101. pos.x = CLAMP(p_posf.x, 0, clamp_v);
  1102. pos.y = CLAMP(p_posf.y, 0, clamp_v);
  1103. pos.z = CLAMP(p_posf.z, 0, clamp_v);
  1104. float level = (cell_subdiv - 1) - p_level;
  1105. int target_level;
  1106. float level_filter;
  1107. if (level <= 0.0) {
  1108. level_filter = 0;
  1109. target_level = 0;
  1110. } else {
  1111. target_level = Math::ceil(level);
  1112. level_filter = target_level - level;
  1113. }
  1114. const Cell *cells = bake_cells.ptr();
  1115. const Light *light = bake_light.ptr();
  1116. Vector3 color[2][8];
  1117. float alpha[2][8];
  1118. zeromem(alpha, sizeof(float) * 2 * 8);
  1119. //find cell at given level first
  1120. for (int c = 0; c < 2; c++) {
  1121. int current_level = MAX(0, target_level - c);
  1122. int level_cell_size = (1 << (cell_subdiv - 1)) >> current_level;
  1123. for (int n = 0; n < 8; n++) {
  1124. int x = int(pos.x);
  1125. int y = int(pos.y);
  1126. int z = int(pos.z);
  1127. if (n & 1)
  1128. x += level_cell_size;
  1129. if (n & 2)
  1130. y += level_cell_size;
  1131. if (n & 4)
  1132. z += level_cell_size;
  1133. int ofs_x = 0;
  1134. int ofs_y = 0;
  1135. int ofs_z = 0;
  1136. x = CLAMP(x, 0, clamp_v);
  1137. y = CLAMP(y, 0, clamp_v);
  1138. z = CLAMP(z, 0, clamp_v);
  1139. int half = size / 2;
  1140. uint32_t cell = 0;
  1141. for (int i = 0; i < current_level; i++) {
  1142. const Cell *bc = &cells[cell];
  1143. int child = 0;
  1144. if (x >= ofs_x + half) {
  1145. child |= 1;
  1146. ofs_x += half;
  1147. }
  1148. if (y >= ofs_y + half) {
  1149. child |= 2;
  1150. ofs_y += half;
  1151. }
  1152. if (z >= ofs_z + half) {
  1153. child |= 4;
  1154. ofs_z += half;
  1155. }
  1156. cell = bc->children[child];
  1157. if (cell == CHILD_EMPTY)
  1158. break;
  1159. half >>= 1;
  1160. }
  1161. if (cell == CHILD_EMPTY) {
  1162. alpha[c][n] = 0;
  1163. } else {
  1164. alpha[c][n] = cells[cell].alpha;
  1165. for (int i = 0; i < 6; i++) {
  1166. //anisotropic read light
  1167. float amount = p_direction.dot(aniso_normal[i]);
  1168. if (amount < 0)
  1169. amount = 0;
  1170. color[c][n].x += light[cell].accum[i][0] * amount;
  1171. color[c][n].y += light[cell].accum[i][1] * amount;
  1172. color[c][n].z += light[cell].accum[i][2] * amount;
  1173. }
  1174. color[c][n].x += cells[cell].emission[0];
  1175. color[c][n].y += cells[cell].emission[1];
  1176. color[c][n].z += cells[cell].emission[2];
  1177. }
  1178. }
  1179. }
  1180. float target_level_size = size >> target_level;
  1181. Vector3 pos_fract[2];
  1182. pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  1183. pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  1184. pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  1185. target_level_size = size >> MAX(0, target_level - 1);
  1186. pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  1187. pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  1188. pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  1189. float alpha_interp[2];
  1190. Vector3 color_interp[2];
  1191. for (int i = 0; i < 2; i++) {
  1192. Vector3 color_x00 = color[i][0].linear_interpolate(color[i][1], pos_fract[i].x);
  1193. Vector3 color_xy0 = color[i][2].linear_interpolate(color[i][3], pos_fract[i].x);
  1194. Vector3 blend_z0 = color_x00.linear_interpolate(color_xy0, pos_fract[i].y);
  1195. Vector3 color_x0z = color[i][4].linear_interpolate(color[i][5], pos_fract[i].x);
  1196. Vector3 color_xyz = color[i][6].linear_interpolate(color[i][7], pos_fract[i].x);
  1197. Vector3 blend_z1 = color_x0z.linear_interpolate(color_xyz, pos_fract[i].y);
  1198. color_interp[i] = blend_z0.linear_interpolate(blend_z1, pos_fract[i].z);
  1199. float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
  1200. float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
  1201. float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);
  1202. float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
  1203. float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
  1204. float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);
  1205. alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
  1206. }
  1207. r_color = color_interp[0].linear_interpolate(color_interp[1], level_filter);
  1208. r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);
  1209. }
  1210. Vector3 VoxelLightBaker::_voxel_cone_trace(const Vector3 &p_pos, const Vector3 &p_normal, float p_aperture) {
  1211. float bias = 2.5;
  1212. float max_distance = (Vector3(1, 1, 1) * (1 << (cell_subdiv - 1))).length();
  1213. float dist = bias;
  1214. float alpha = 0.0;
  1215. Vector3 color;
  1216. Vector3 scolor;
  1217. float salpha;
  1218. while (dist < max_distance && alpha < 0.95) {
  1219. float diameter = MAX(1.0, 2.0 * p_aperture * dist);
  1220. _sample_baked_octree_filtered_and_anisotropic(p_pos + dist * p_normal, p_normal, log2(diameter), scolor, salpha);
  1221. float a = (1.0 - alpha);
  1222. color += scolor * a;
  1223. alpha += a * salpha;
  1224. dist += diameter * 0.5;
  1225. }
  1226. /*if (blend_ambient) {
  1227. color.rgb = mix(ambient,color.rgb,min(1.0,alpha/0.95));
  1228. }*/
  1229. return color;
  1230. }
  1231. Vector3 VoxelLightBaker::_compute_pixel_light_at_pos(const Vector3 &p_pos, const Vector3 &p_normal) {
  1232. //find arbitrary tangent and bitangent, then build a matrix
  1233. Vector3 v0 = Math::abs(p_normal.z) < 0.999 ? Vector3(0, 0, 1) : Vector3(0, 1, 0);
  1234. Vector3 tangent = v0.cross(p_normal).normalized();
  1235. Vector3 bitangent = tangent.cross(p_normal).normalized();
  1236. Basis normal_xform = Basis(tangent, bitangent, p_normal).transposed();
  1237. const Vector3 *cone_dirs = NULL;
  1238. const float *cone_weights = NULL;
  1239. int cone_dir_count = 0;
  1240. float cone_aperture = 0;
  1241. switch (bake_quality) {
  1242. case BAKE_QUALITY_LOW: {
  1243. //default quality
  1244. static const Vector3 dirs[4] = {
  1245. Vector3(0.707107, 0, 0.707107),
  1246. Vector3(0, 0.707107, 0.707107),
  1247. Vector3(-0.707107, 0, 0.707107),
  1248. Vector3(0, -0.707107, 0.707107)
  1249. };
  1250. static const float weights[4] = { 0.25, 0.25, 0.25, 0.25 };
  1251. cone_dirs = dirs;
  1252. cone_dir_count = 4;
  1253. cone_aperture = 1.0; // tan(angle) 90 degrees
  1254. cone_weights = weights;
  1255. } break;
  1256. case BAKE_QUALITY_MEDIUM: {
  1257. //default quality
  1258. static const Vector3 dirs[6] = {
  1259. Vector3(0, 0, 1),
  1260. Vector3(0.866025, 0, 0.5),
  1261. Vector3(0.267617, 0.823639, 0.5),
  1262. Vector3(-0.700629, 0.509037, 0.5),
  1263. Vector3(-0.700629, -0.509037, 0.5),
  1264. Vector3(0.267617, -0.823639, 0.5)
  1265. };
  1266. static const float weights[6] = { 0.25f, 0.15f, 0.15f, 0.15f, 0.15f, 0.15f };
  1267. //
  1268. cone_dirs = dirs;
  1269. cone_dir_count = 6;
  1270. cone_aperture = 0.577; // tan(angle) 60 degrees
  1271. cone_weights = weights;
  1272. } break;
  1273. case BAKE_QUALITY_HIGH: {
  1274. //high qualily
  1275. static const Vector3 dirs[10] = {
  1276. Vector3(0.8781648411741658, 0.0, 0.478358141694643),
  1277. Vector3(0.5369754325592234, 0.6794204427701518, 0.5000452447267606),
  1278. Vector3(-0.19849436573466497, 0.8429904390140635, 0.49996710542041645),
  1279. Vector3(-0.7856196499811189, 0.3639120321329737, 0.5003696617825604),
  1280. Vector3(-0.7856196499811189, -0.3639120321329737, 0.5003696617825604),
  1281. Vector3(-0.19849436573466497, -0.8429904390140635, 0.49996710542041645),
  1282. Vector3(0.5369754325592234, -0.6794204427701518, 0.5000452447267606),
  1283. Vector3(-0.4451656858129485, 0.0, 0.8954482185892644),
  1284. Vector3(0.19124006749743122, 0.39355745585016605, 0.8991883926788214),
  1285. Vector3(0.19124006749743122, -0.39355745585016605, 0.8991883926788214),
  1286. };
  1287. static const float weights[10] = { 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.08571f, 0.133333f, 0.133333f, 0.13333f };
  1288. cone_dirs = dirs;
  1289. cone_dir_count = 10;
  1290. cone_aperture = 0.404; // tan(angle) 45 degrees
  1291. cone_weights = weights;
  1292. } break;
  1293. }
  1294. Vector3 accum;
  1295. for (int i = 0; i < cone_dir_count; i++) {
  1296. Vector3 dir = normal_xform.xform(cone_dirs[i]).normalized(); //normal may not completely correct when transformed to cell
  1297. accum += _voxel_cone_trace(p_pos, dir, cone_aperture) * cone_weights[i];
  1298. }
  1299. return accum;
  1300. }
  1301. _ALWAYS_INLINE_ uint32_t xorshift32(uint32_t *state) {
  1302. /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
  1303. uint32_t x = *state;
  1304. x ^= x << 13;
  1305. x ^= x >> 17;
  1306. x ^= x << 5;
  1307. *state = x;
  1308. return x;
  1309. }
  1310. Vector3 VoxelLightBaker::_compute_ray_trace_at_pos(const Vector3 &p_pos, const Vector3 &p_normal) {
  1311. int samples_per_quality[3] = { 48, 128, 512 };
  1312. int samples = samples_per_quality[bake_quality];
  1313. //create a basis in Z
  1314. Vector3 v0 = Math::abs(p_normal.z) < 0.999 ? Vector3(0, 0, 1) : Vector3(0, 1, 0);
  1315. Vector3 tangent = v0.cross(p_normal).normalized();
  1316. Vector3 bitangent = tangent.cross(p_normal).normalized();
  1317. Basis normal_xform = Basis(tangent, bitangent, p_normal).transposed();
  1318. float bias = 1.5;
  1319. int max_level = cell_subdiv - 1;
  1320. int size = 1 << max_level;
  1321. Vector3 accum;
  1322. float spread = Math::deg2rad(80.0);
  1323. const Light *light = bake_light.ptr();
  1324. const Cell *cells = bake_cells.ptr();
  1325. uint32_t local_rng_state = rand(); //needs to be fixed again
  1326. for (int i = 0; i < samples; i++) {
  1327. float random_angle1 = (((xorshift32(&local_rng_state) % 65535) / 65535.0) * 2.0 - 1.0) * spread;
  1328. Vector3 axis(0, sin(random_angle1), cos(random_angle1));
  1329. float random_angle2 = ((xorshift32(&local_rng_state) % 65535) / 65535.0) * Math_PI * 2.0;
  1330. Basis rot(Vector3(0, 0, 1), random_angle2);
  1331. axis = rot.xform(axis);
  1332. Vector3 direction = normal_xform.xform(axis).normalized();
  1333. Vector3 advance = direction * _get_normal_advance(direction);
  1334. Vector3 pos = p_pos /*+ Vector3(0.5, 0.5, 0.5)*/ + advance * bias;
  1335. uint32_t cell = CHILD_EMPTY;
  1336. while (cell == CHILD_EMPTY) {
  1337. int x = int(pos.x);
  1338. int y = int(pos.y);
  1339. int z = int(pos.z);
  1340. int ofs_x = 0;
  1341. int ofs_y = 0;
  1342. int ofs_z = 0;
  1343. int half = size / 2;
  1344. if (x < 0 || x >= size)
  1345. break;
  1346. if (y < 0 || y >= size)
  1347. break;
  1348. if (z < 0 || z >= size)
  1349. break;
  1350. //int level_limit = max_level;
  1351. cell = 0; //start from root
  1352. for (int i = 0; i < max_level; i++) {
  1353. const Cell *bc = &cells[cell];
  1354. int child = 0;
  1355. if (x >= ofs_x + half) {
  1356. child |= 1;
  1357. ofs_x += half;
  1358. }
  1359. if (y >= ofs_y + half) {
  1360. child |= 2;
  1361. ofs_y += half;
  1362. }
  1363. if (z >= ofs_z + half) {
  1364. child |= 4;
  1365. ofs_z += half;
  1366. }
  1367. cell = bc->children[child];
  1368. if (unlikely(cell == CHILD_EMPTY))
  1369. break;
  1370. half >>= 1;
  1371. }
  1372. pos += advance;
  1373. }
  1374. if (unlikely(cell != CHILD_EMPTY)) {
  1375. for (int i = 0; i < 6; i++) {
  1376. //anisotropic read light
  1377. float amount = direction.dot(aniso_normal[i]);
  1378. if (amount <= 0)
  1379. continue;
  1380. accum.x += light[cell].accum[i][0] * amount;
  1381. accum.y += light[cell].accum[i][1] * amount;
  1382. accum.z += light[cell].accum[i][2] * amount;
  1383. }
  1384. accum.x += cells[cell].emission[0];
  1385. accum.y += cells[cell].emission[1];
  1386. accum.z += cells[cell].emission[2];
  1387. }
  1388. }
  1389. // Make sure we don't reset this thread's RNG state
  1390. return accum / samples;
  1391. }
  1392. void VoxelLightBaker::_lightmap_bake_point(uint32_t p_x, LightMap *p_line) {
  1393. LightMap *pixel = &p_line[p_x];
  1394. if (pixel->pos == Vector3())
  1395. return;
  1396. switch (bake_mode) {
  1397. case BAKE_MODE_CONE_TRACE: {
  1398. pixel->light = _compute_pixel_light_at_pos(pixel->pos, pixel->normal) * energy;
  1399. } break;
  1400. case BAKE_MODE_RAY_TRACE: {
  1401. pixel->light = _compute_ray_trace_at_pos(pixel->pos, pixel->normal) * energy;
  1402. } break;
  1403. }
  1404. }
  1405. Error VoxelLightBaker::make_lightmap(const Transform &p_xform, Ref<Mesh> &p_mesh, LightMapData &r_lightmap, bool (*p_bake_time_func)(void *, float, float), void *p_bake_time_ud) {
  1406. //transfer light information to a lightmap
  1407. Ref<Mesh> mesh = p_mesh;
  1408. int width = mesh->get_lightmap_size_hint().x;
  1409. int height = mesh->get_lightmap_size_hint().y;
  1410. //step 1 - create lightmap
  1411. Vector<LightMap> lightmap;
  1412. lightmap.resize(width * height);
  1413. Transform xform = to_cell_space * p_xform;
  1414. //step 2 plot faces to lightmap
  1415. for (int i = 0; i < mesh->get_surface_count(); i++) {
  1416. Array arrays = mesh->surface_get_arrays(i);
  1417. PoolVector<Vector3> vertices = arrays[Mesh::ARRAY_VERTEX];
  1418. PoolVector<Vector3> normals = arrays[Mesh::ARRAY_NORMAL];
  1419. PoolVector<Vector2> uv2 = arrays[Mesh::ARRAY_TEX_UV2];
  1420. PoolVector<int> indices = arrays[Mesh::ARRAY_INDEX];
  1421. ERR_FAIL_COND_V(vertices.size() == 0, ERR_INVALID_PARAMETER);
  1422. ERR_FAIL_COND_V(normals.size() == 0, ERR_INVALID_PARAMETER);
  1423. ERR_FAIL_COND_V(uv2.size() == 0, ERR_INVALID_PARAMETER);
  1424. int vc = vertices.size();
  1425. PoolVector<Vector3>::Read vr = vertices.read();
  1426. PoolVector<Vector3>::Read nr = normals.read();
  1427. PoolVector<Vector2>::Read u2r = uv2.read();
  1428. PoolVector<int>::Read ir;
  1429. int ic = 0;
  1430. if (indices.size()) {
  1431. ic = indices.size();
  1432. ir = indices.read();
  1433. }
  1434. int faces = ic ? ic / 3 : vc / 3;
  1435. for (int i = 0; i < faces; i++) {
  1436. Vector3 vertex[3];
  1437. Vector3 normal[3];
  1438. Vector2 uv[3];
  1439. for (int j = 0; j < 3; j++) {
  1440. int idx = ic ? ir[i * 3 + j] : i * 3 + j;
  1441. vertex[j] = xform.xform(vr[idx]);
  1442. normal[j] = xform.basis.xform(nr[idx]).normalized();
  1443. uv[j] = u2r[idx];
  1444. }
  1445. _plot_triangle(uv, vertex, normal, lightmap.ptrw(), width, height);
  1446. }
  1447. }
  1448. //step 3 perform voxel cone trace on lightmap pixels
  1449. {
  1450. LightMap *lightmap_ptr = lightmap.ptrw();
  1451. uint64_t begin_time = OS::get_singleton()->get_ticks_usec();
  1452. volatile int lines = 0;
  1453. // make sure our OS-level rng is seeded
  1454. for (int i = 0; i < height; i++) {
  1455. thread_process_array(width, this, &VoxelLightBaker::_lightmap_bake_point, &lightmap_ptr[i * width]);
  1456. lines = MAX(lines, i); //for multithread
  1457. if (p_bake_time_func) {
  1458. uint64_t elapsed = OS::get_singleton()->get_ticks_usec() - begin_time;
  1459. float elapsed_sec = double(elapsed) / 1000000.0;
  1460. float remaining = lines < 1 ? 0 : (elapsed_sec / lines) * (height - lines - 1);
  1461. if (p_bake_time_func(p_bake_time_ud, remaining, lines / float(height))) {
  1462. return ERR_SKIP;
  1463. }
  1464. }
  1465. }
  1466. if (bake_mode == BAKE_MODE_RAY_TRACE) {
  1467. //blur
  1468. //gauss kernel, 7 step sigma 2
  1469. static const float gauss_kernel[4] = { 0.214607f, 0.189879f, 0.131514f, 0.071303f };
  1470. //horizontal pass
  1471. for (int i = 0; i < height; i++) {
  1472. for (int j = 0; j < width; j++) {
  1473. if (lightmap_ptr[i * width + j].normal == Vector3()) {
  1474. continue; //empty
  1475. }
  1476. float gauss_sum = gauss_kernel[0];
  1477. Vector3 accum = lightmap_ptr[i * width + j].light * gauss_kernel[0];
  1478. for (int k = 1; k < 4; k++) {
  1479. int new_x = j + k;
  1480. if (new_x >= width || lightmap_ptr[i * width + new_x].normal == Vector3())
  1481. break;
  1482. gauss_sum += gauss_kernel[k];
  1483. accum += lightmap_ptr[i * width + new_x].light * gauss_kernel[k];
  1484. }
  1485. for (int k = 1; k < 4; k++) {
  1486. int new_x = j - k;
  1487. if (new_x < 0 || lightmap_ptr[i * width + new_x].normal == Vector3())
  1488. break;
  1489. gauss_sum += gauss_kernel[k];
  1490. accum += lightmap_ptr[i * width + new_x].light * gauss_kernel[k];
  1491. }
  1492. lightmap_ptr[i * width + j].pos = accum /= gauss_sum;
  1493. }
  1494. }
  1495. //vertical pass
  1496. for (int i = 0; i < height; i++) {
  1497. for (int j = 0; j < width; j++) {
  1498. if (lightmap_ptr[i * width + j].normal == Vector3())
  1499. continue; //empty, don't write over it anyway
  1500. float gauss_sum = gauss_kernel[0];
  1501. Vector3 accum = lightmap_ptr[i * width + j].pos * gauss_kernel[0];
  1502. for (int k = 1; k < 4; k++) {
  1503. int new_y = i + k;
  1504. if (new_y >= height || lightmap_ptr[new_y * width + j].normal == Vector3())
  1505. break;
  1506. gauss_sum += gauss_kernel[k];
  1507. accum += lightmap_ptr[new_y * width + j].pos * gauss_kernel[k];
  1508. }
  1509. for (int k = 1; k < 4; k++) {
  1510. int new_y = i - k;
  1511. if (new_y < 0 || lightmap_ptr[new_y * width + j].normal == Vector3())
  1512. break;
  1513. gauss_sum += gauss_kernel[k];
  1514. accum += lightmap_ptr[new_y * width + j].pos * gauss_kernel[k];
  1515. }
  1516. lightmap_ptr[i * width + j].light = accum /= gauss_sum;
  1517. }
  1518. }
  1519. }
  1520. //add directional light (do this after blur)
  1521. {
  1522. LightMap *lightmap_ptr = lightmap.ptrw();
  1523. const Cell *cells = bake_cells.ptr();
  1524. const Light *light = bake_light.ptr();
  1525. #ifdef _OPENMP
  1526. #pragma omp parallel
  1527. #endif
  1528. for (int i = 0; i < height; i++) {
  1529. #ifdef _OPENMP
  1530. #pragma omp parallel for schedule(dynamic, 1)
  1531. #endif
  1532. for (int j = 0; j < width; j++) {
  1533. //if (i == 125 && j == 280) {
  1534. LightMap *pixel = &lightmap_ptr[i * width + j];
  1535. if (pixel->pos == Vector3())
  1536. continue; //unused, skipe
  1537. int x = int(pixel->pos.x) - 1;
  1538. int y = int(pixel->pos.y) - 1;
  1539. int z = int(pixel->pos.z) - 1;
  1540. Color accum;
  1541. int size = 1 << (cell_subdiv - 1);
  1542. int found = 0;
  1543. for (int k = 0; k < 8; k++) {
  1544. int ofs_x = x;
  1545. int ofs_y = y;
  1546. int ofs_z = z;
  1547. if (k & 1)
  1548. ofs_x++;
  1549. if (k & 2)
  1550. ofs_y++;
  1551. if (k & 4)
  1552. ofs_z++;
  1553. if (x < 0 || x >= size)
  1554. continue;
  1555. if (y < 0 || y >= size)
  1556. continue;
  1557. if (z < 0 || z >= size)
  1558. continue;
  1559. uint32_t cell = _find_cell_at_pos(cells, ofs_x, ofs_y, ofs_z);
  1560. if (cell == CHILD_EMPTY)
  1561. continue;
  1562. for (int l = 0; l < 6; l++) {
  1563. float s = pixel->normal.dot(aniso_normal[l]);
  1564. if (s < 0)
  1565. s = 0;
  1566. accum.r += light[cell].direct_accum[l][0] * s;
  1567. accum.g += light[cell].direct_accum[l][1] * s;
  1568. accum.b += light[cell].direct_accum[l][2] * s;
  1569. }
  1570. found++;
  1571. }
  1572. if (found) {
  1573. accum /= found;
  1574. pixel->light.x += accum.r;
  1575. pixel->light.y += accum.g;
  1576. pixel->light.z += accum.b;
  1577. }
  1578. }
  1579. }
  1580. }
  1581. {
  1582. //fill gaps with neighbour vertices to avoid filter fades to black on edges
  1583. for (int i = 0; i < height; i++) {
  1584. for (int j = 0; j < width; j++) {
  1585. if (lightmap_ptr[i * width + j].normal != Vector3()) {
  1586. continue; //filled, skip
  1587. }
  1588. //this can't be made separatable..
  1589. int closest_i = -1, closest_j = 1;
  1590. float closest_dist = 1e20;
  1591. const int margin = 3;
  1592. for (int y = i - margin; y <= i + margin; y++) {
  1593. for (int x = j - margin; x <= j + margin; x++) {
  1594. if (x == j && y == i)
  1595. continue;
  1596. if (x < 0 || x >= width)
  1597. continue;
  1598. if (y < 0 || y >= height)
  1599. continue;
  1600. if (lightmap_ptr[y * width + x].normal == Vector3())
  1601. continue; //also ensures that blitted stuff is not reused
  1602. float dist = Vector2(i - y, j - x).length();
  1603. if (dist > closest_dist)
  1604. continue;
  1605. closest_dist = dist;
  1606. closest_i = y;
  1607. closest_j = x;
  1608. }
  1609. }
  1610. if (closest_i != -1) {
  1611. lightmap_ptr[i * width + j].light = lightmap_ptr[closest_i * width + closest_j].light;
  1612. }
  1613. }
  1614. }
  1615. }
  1616. {
  1617. //fill the lightmap data
  1618. r_lightmap.width = width;
  1619. r_lightmap.height = height;
  1620. r_lightmap.light.resize(lightmap.size() * 3);
  1621. PoolVector<float>::Write w = r_lightmap.light.write();
  1622. for (int i = 0; i < lightmap.size(); i++) {
  1623. w[i * 3 + 0] = lightmap[i].light.x;
  1624. w[i * 3 + 1] = lightmap[i].light.y;
  1625. w[i * 3 + 2] = lightmap[i].light.z;
  1626. }
  1627. }
  1628. // Enable for debugging
  1629. #if 0
  1630. {
  1631. PoolVector<uint8_t> img;
  1632. int ls = lightmap.size();
  1633. img.resize(ls * 3);
  1634. {
  1635. PoolVector<uint8_t>::Write w = img.write();
  1636. for (int i = 0; i < ls; i++) {
  1637. w[i * 3 + 0] = CLAMP(lightmap_ptr[i].light.x * 255, 0, 255);
  1638. w[i * 3 + 1] = CLAMP(lightmap_ptr[i].light.y * 255, 0, 255);
  1639. w[i * 3 + 2] = CLAMP(lightmap_ptr[i].light.z * 255, 0, 255);
  1640. //w[i * 3 + 0] = CLAMP(lightmap_ptr[i].normal.x * 255, 0, 255);
  1641. //w[i * 3 + 1] = CLAMP(lightmap_ptr[i].normal.y * 255, 0, 255);
  1642. //w[i * 3 + 2] = CLAMP(lightmap_ptr[i].normal.z * 255, 0, 255);
  1643. //w[i * 3 + 0] = CLAMP(lightmap_ptr[i].pos.x / (1 << (cell_subdiv - 1)) * 255, 0, 255);
  1644. //w[i * 3 + 1] = CLAMP(lightmap_ptr[i].pos.y / (1 << (cell_subdiv - 1)) * 255, 0, 255);
  1645. //w[i * 3 + 2] = CLAMP(lightmap_ptr[i].pos.z / (1 << (cell_subdiv - 1)) * 255, 0, 255);
  1646. }
  1647. }
  1648. Ref<Image> image;
  1649. image.instance();
  1650. image->create(width, height, false, Image::FORMAT_RGB8, img);
  1651. String name = p_mesh->get_name();
  1652. if (name == "") {
  1653. name = "Mesh" + itos(p_mesh->get_instance_id());
  1654. }
  1655. image->save_png(name + ".png");
  1656. }
  1657. #endif
  1658. }
  1659. return OK;
  1660. }
  1661. void VoxelLightBaker::begin_bake(int p_subdiv, const AABB &p_bounds) {
  1662. original_bounds = p_bounds;
  1663. cell_subdiv = p_subdiv;
  1664. bake_cells.resize(1);
  1665. material_cache.clear();
  1666. //find out the actual real bounds, power of 2, which gets the highest subdivision
  1667. po2_bounds = p_bounds;
  1668. int longest_axis = po2_bounds.get_longest_axis_index();
  1669. axis_cell_size[longest_axis] = (1 << (cell_subdiv - 1));
  1670. leaf_voxel_count = 0;
  1671. for (int i = 0; i < 3; i++) {
  1672. if (i == longest_axis)
  1673. continue;
  1674. axis_cell_size[i] = axis_cell_size[longest_axis];
  1675. float axis_size = po2_bounds.size[longest_axis];
  1676. //shrink until fit subdiv
  1677. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  1678. axis_size /= 2.0;
  1679. axis_cell_size[i] >>= 1;
  1680. }
  1681. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  1682. }
  1683. Transform to_bounds;
  1684. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  1685. to_bounds.origin = po2_bounds.position;
  1686. Transform to_grid;
  1687. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  1688. to_cell_space = to_grid * to_bounds.affine_inverse();
  1689. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  1690. }
  1691. void VoxelLightBaker::end_bake() {
  1692. _fixup_plot(0, 0);
  1693. }
  1694. //create the data for visual server
  1695. PoolVector<int> VoxelLightBaker::create_gi_probe_data() {
  1696. PoolVector<int> data;
  1697. data.resize(16 + (8 + 1 + 1 + 1 + 1) * bake_cells.size()); //4 for header, rest for rest.
  1698. {
  1699. PoolVector<int>::Write w = data.write();
  1700. uint32_t *w32 = (uint32_t *)w.ptr();
  1701. w32[0] = 0; //version
  1702. w32[1] = cell_subdiv; //subdiv
  1703. w32[2] = axis_cell_size[0];
  1704. w32[3] = axis_cell_size[1];
  1705. w32[4] = axis_cell_size[2];
  1706. w32[5] = bake_cells.size();
  1707. w32[6] = leaf_voxel_count;
  1708. int ofs = 16;
  1709. for (int i = 0; i < bake_cells.size(); i++) {
  1710. for (int j = 0; j < 8; j++) {
  1711. w32[ofs++] = bake_cells[i].children[j];
  1712. }
  1713. { //albedo
  1714. uint32_t rgba = uint32_t(CLAMP(bake_cells[i].albedo[0] * 255.0, 0, 255)) << 16;
  1715. rgba |= uint32_t(CLAMP(bake_cells[i].albedo[1] * 255.0, 0, 255)) << 8;
  1716. rgba |= uint32_t(CLAMP(bake_cells[i].albedo[2] * 255.0, 0, 255)) << 0;
  1717. w32[ofs++] = rgba;
  1718. }
  1719. { //emission
  1720. Vector3 e(bake_cells[i].emission[0], bake_cells[i].emission[1], bake_cells[i].emission[2]);
  1721. float l = e.length();
  1722. if (l > 0) {
  1723. e.normalize();
  1724. l = CLAMP(l / 8.0, 0, 1.0);
  1725. }
  1726. uint32_t em = uint32_t(CLAMP(e[0] * 255, 0, 255)) << 24;
  1727. em |= uint32_t(CLAMP(e[1] * 255, 0, 255)) << 16;
  1728. em |= uint32_t(CLAMP(e[2] * 255, 0, 255)) << 8;
  1729. em |= uint32_t(CLAMP(l * 255, 0, 255));
  1730. w32[ofs++] = em;
  1731. }
  1732. //w32[ofs++]=bake_cells[i].used_sides;
  1733. { //normal
  1734. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  1735. n = n * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
  1736. uint32_t norm = 0;
  1737. norm |= uint32_t(CLAMP(n.x * 255.0, 0, 255)) << 16;
  1738. norm |= uint32_t(CLAMP(n.y * 255.0, 0, 255)) << 8;
  1739. norm |= uint32_t(CLAMP(n.z * 255.0, 0, 255)) << 0;
  1740. w32[ofs++] = norm;
  1741. }
  1742. {
  1743. uint16_t alpha = CLAMP(uint32_t(bake_cells[i].alpha * 65535.0), 0, 65535);
  1744. uint16_t level = bake_cells[i].level;
  1745. w32[ofs++] = (uint32_t(level) << 16) | uint32_t(alpha);
  1746. }
  1747. }
  1748. }
  1749. return data;
  1750. }
  1751. void VoxelLightBaker::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx, DebugMode p_mode) {
  1752. if (p_level == cell_subdiv - 1) {
  1753. Vector3 center = p_aabb.position + p_aabb.size * 0.5;
  1754. Transform xform;
  1755. xform.origin = center;
  1756. xform.basis.scale(p_aabb.size * 0.5);
  1757. p_multimesh->set_instance_transform(idx, xform);
  1758. Color col;
  1759. if (p_mode == DEBUG_ALBEDO) {
  1760. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  1761. } else if (p_mode == DEBUG_LIGHT) {
  1762. for (int i = 0; i < 6; i++) {
  1763. col.r += bake_light[p_idx].accum[i][0];
  1764. col.g += bake_light[p_idx].accum[i][1];
  1765. col.b += bake_light[p_idx].accum[i][2];
  1766. col.r += bake_light[p_idx].direct_accum[i][0];
  1767. col.g += bake_light[p_idx].direct_accum[i][1];
  1768. col.b += bake_light[p_idx].direct_accum[i][2];
  1769. }
  1770. }
  1771. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  1772. p_multimesh->set_instance_color(idx, col);
  1773. idx++;
  1774. } else {
  1775. for (int i = 0; i < 8; i++) {
  1776. uint32_t child = bake_cells[p_idx].children[i];
  1777. if (child == CHILD_EMPTY || child >= max_original_cells)
  1778. continue;
  1779. AABB aabb = p_aabb;
  1780. aabb.size *= 0.5;
  1781. if (i & 1)
  1782. aabb.position.x += aabb.size.x;
  1783. if (i & 2)
  1784. aabb.position.y += aabb.size.y;
  1785. if (i & 4)
  1786. aabb.position.z += aabb.size.z;
  1787. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx, p_mode);
  1788. }
  1789. }
  1790. }
  1791. Ref<MultiMesh> VoxelLightBaker::create_debug_multimesh(DebugMode p_mode) {
  1792. Ref<MultiMesh> mm;
  1793. ERR_FAIL_COND_V(p_mode == DEBUG_LIGHT && bake_light.size() == 0, mm);
  1794. mm.instance();
  1795. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  1796. mm->set_color_format(MultiMesh::COLOR_8BIT);
  1797. mm->set_instance_count(leaf_voxel_count);
  1798. Ref<ArrayMesh> mesh;
  1799. mesh.instance();
  1800. {
  1801. Array arr;
  1802. arr.resize(Mesh::ARRAY_MAX);
  1803. PoolVector<Vector3> vertices;
  1804. PoolVector<Color> colors;
  1805. #define ADD_VTX(m_idx) \
  1806. ; \
  1807. vertices.push_back(face_points[m_idx]); \
  1808. colors.push_back(Color(1, 1, 1, 1));
  1809. for (int i = 0; i < 6; i++) {
  1810. Vector3 face_points[4];
  1811. for (int j = 0; j < 4; j++) {
  1812. float v[3];
  1813. v[0] = 1.0;
  1814. v[1] = 1 - 2 * ((j >> 1) & 1);
  1815. v[2] = v[1] * (1 - 2 * (j & 1));
  1816. for (int k = 0; k < 3; k++) {
  1817. if (i < 3)
  1818. face_points[j][(i + k) % 3] = v[k];
  1819. else
  1820. face_points[3 - j][(i + k) % 3] = -v[k];
  1821. }
  1822. }
  1823. //tri 1
  1824. ADD_VTX(0);
  1825. ADD_VTX(1);
  1826. ADD_VTX(2);
  1827. //tri 2
  1828. ADD_VTX(2);
  1829. ADD_VTX(3);
  1830. ADD_VTX(0);
  1831. }
  1832. arr[Mesh::ARRAY_VERTEX] = vertices;
  1833. arr[Mesh::ARRAY_COLOR] = colors;
  1834. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  1835. }
  1836. {
  1837. Ref<SpatialMaterial> fsm;
  1838. fsm.instance();
  1839. fsm->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  1840. fsm->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  1841. fsm->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  1842. fsm->set_albedo(Color(1, 1, 1, 1));
  1843. mesh->surface_set_material(0, fsm);
  1844. }
  1845. mm->set_mesh(mesh);
  1846. int idx = 0;
  1847. _debug_mesh(0, 0, po2_bounds, mm, idx, p_mode);
  1848. return mm;
  1849. }
  1850. struct VoxelLightBakerOctree {
  1851. enum {
  1852. CHILD_EMPTY = 0xFFFFFFFF
  1853. };
  1854. uint16_t light[6][3]; //anisotropic light
  1855. float alpha;
  1856. uint32_t children[8];
  1857. };
  1858. PoolVector<uint8_t> VoxelLightBaker::create_capture_octree(int p_subdiv) {
  1859. p_subdiv = MIN(p_subdiv, cell_subdiv); // use the smaller one
  1860. Vector<uint32_t> remap;
  1861. int bc = bake_cells.size();
  1862. remap.resize(bc);
  1863. Vector<uint32_t> demap;
  1864. int new_size = 0;
  1865. for (int i = 0; i < bc; i++) {
  1866. uint32_t c = CHILD_EMPTY;
  1867. if (bake_cells[i].level < p_subdiv) {
  1868. c = new_size;
  1869. new_size++;
  1870. demap.push_back(i);
  1871. }
  1872. remap.write[i] = c;
  1873. }
  1874. Vector<VoxelLightBakerOctree> octree;
  1875. octree.resize(new_size);
  1876. for (int i = 0; i < new_size; i++) {
  1877. octree.write[i].alpha = bake_cells[demap[i]].alpha;
  1878. for (int j = 0; j < 6; j++) {
  1879. for (int k = 0; k < 3; k++) {
  1880. float l = bake_light[demap[i]].accum[j][k]; //add anisotropic light
  1881. l += bake_cells[demap[i]].emission[k]; //add emission
  1882. octree.write[i].light[j][k] = CLAMP(l * 1024, 0, 65535); //give two more bits to octree
  1883. }
  1884. }
  1885. for (int j = 0; j < 8; j++) {
  1886. uint32_t child = bake_cells[demap[i]].children[j];
  1887. octree.write[i].children[j] = child == CHILD_EMPTY ? CHILD_EMPTY : remap[child];
  1888. }
  1889. }
  1890. PoolVector<uint8_t> ret;
  1891. int ret_bytes = octree.size() * sizeof(VoxelLightBakerOctree);
  1892. ret.resize(ret_bytes);
  1893. {
  1894. PoolVector<uint8_t>::Write w = ret.write();
  1895. copymem(w.ptr(), octree.ptr(), ret_bytes);
  1896. }
  1897. return ret;
  1898. }
  1899. float VoxelLightBaker::get_cell_size() const {
  1900. return cell_size;
  1901. }
  1902. Transform VoxelLightBaker::get_to_cell_space_xform() const {
  1903. return to_cell_space;
  1904. }
  1905. VoxelLightBaker::VoxelLightBaker() {
  1906. color_scan_cell_width = 4;
  1907. bake_texture_size = 128;
  1908. propagation = 0.85;
  1909. energy = 1.0;
  1910. }