voxelizer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /**************************************************************************/
  2. /* voxelizer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "voxelizer.h"
  31. #include "core/config/project_settings.h"
  32. 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) {
  33. if (p_pos.is_equal_approx(p_vtx[0])) {
  34. r_uv = p_uv[0];
  35. r_normal = p_normal[0];
  36. return;
  37. }
  38. if (p_pos.is_equal_approx(p_vtx[1])) {
  39. r_uv = p_uv[1];
  40. r_normal = p_normal[1];
  41. return;
  42. }
  43. if (p_pos.is_equal_approx(p_vtx[2])) {
  44. r_uv = p_uv[2];
  45. r_normal = p_normal[2];
  46. return;
  47. }
  48. Vector3 v0 = p_vtx[1] - p_vtx[0];
  49. Vector3 v1 = p_vtx[2] - p_vtx[0];
  50. Vector3 v2 = p_pos - p_vtx[0];
  51. real_t d00 = v0.dot(v0);
  52. real_t d01 = v0.dot(v1);
  53. real_t d11 = v1.dot(v1);
  54. real_t d20 = v2.dot(v0);
  55. real_t d21 = v2.dot(v1);
  56. real_t denom = (d00 * d11 - d01 * d01);
  57. if (denom == 0) {
  58. r_uv = p_uv[0];
  59. r_normal = p_normal[0];
  60. return;
  61. }
  62. real_t v = (d11 * d20 - d01 * d21) / denom;
  63. real_t w = (d00 * d21 - d01 * d20) / denom;
  64. real_t u = 1.0f - v - w;
  65. r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
  66. r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
  67. }
  68. void Voxelizer::_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) {
  69. if (p_level == cell_subdiv) {
  70. //plot the face by guessing its albedo and emission value
  71. //find best axis to map to, for scanning values
  72. int closest_axis = 0;
  73. real_t closest_dot = 0;
  74. Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
  75. Vector3 normal = plane.normal;
  76. for (int i = 0; i < 3; i++) {
  77. Vector3 axis;
  78. axis[i] = 1.0;
  79. real_t dot = ABS(normal.dot(axis));
  80. if (i == 0 || dot > closest_dot) {
  81. closest_axis = i;
  82. closest_dot = dot;
  83. }
  84. }
  85. Vector3 axis;
  86. axis[closest_axis] = 1.0;
  87. Vector3 t1;
  88. t1[(closest_axis + 1) % 3] = 1.0;
  89. Vector3 t2;
  90. t2[(closest_axis + 2) % 3] = 1.0;
  91. t1 *= p_aabb.size[(closest_axis + 1) % 3] / real_t(color_scan_cell_width);
  92. t2 *= p_aabb.size[(closest_axis + 2) % 3] / real_t(color_scan_cell_width);
  93. Color albedo_accum;
  94. Color emission_accum;
  95. Vector3 normal_accum;
  96. float alpha = 0.0;
  97. //map to a grid average in the best axis for this face
  98. for (int i = 0; i < color_scan_cell_width; i++) {
  99. Vector3 ofs_i = real_t(i) * t1;
  100. for (int j = 0; j < color_scan_cell_width; j++) {
  101. Vector3 ofs_j = real_t(j) * t2;
  102. Vector3 from = p_aabb.position + ofs_i + ofs_j;
  103. Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
  104. Vector3 half = (to - from) * 0.5;
  105. //is in this cell?
  106. if (!Geometry3D::triangle_box_overlap(from + half, half, p_vtx)) {
  107. continue; //face does not span this cell
  108. }
  109. //go from -size to +size*2 to avoid skipping collisions
  110. Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
  111. Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
  112. if (normal.dot(ray_from - ray_to) < 0) {
  113. SWAP(ray_from, ray_to);
  114. }
  115. Vector3 intersection;
  116. if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
  117. if (ABS(plane.distance_to(ray_from)) < ABS(plane.distance_to(ray_to))) {
  118. intersection = plane.project(ray_from);
  119. } else {
  120. intersection = plane.project(ray_to);
  121. }
  122. }
  123. intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
  124. Vector2 uv;
  125. Vector3 lnormal;
  126. get_uv_and_normal(intersection, p_vtx, p_uv, p_normal, uv, lnormal);
  127. if (lnormal == Vector3()) { //just in case normal is not provided
  128. lnormal = normal;
  129. }
  130. int uv_x = CLAMP(int(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
  131. int uv_y = CLAMP(int(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
  132. int ofs = uv_y * bake_texture_size + uv_x;
  133. albedo_accum.r += p_material.albedo[ofs].r;
  134. albedo_accum.g += p_material.albedo[ofs].g;
  135. albedo_accum.b += p_material.albedo[ofs].b;
  136. albedo_accum.a += p_material.albedo[ofs].a;
  137. emission_accum.r += p_material.emission[ofs].r;
  138. emission_accum.g += p_material.emission[ofs].g;
  139. emission_accum.b += p_material.emission[ofs].b;
  140. normal_accum += lnormal;
  141. alpha += 1.0;
  142. }
  143. }
  144. if (alpha == 0) {
  145. //could not in any way get texture information.. so use closest point to center
  146. Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
  147. Vector3 inters = f.get_closest_point_to(p_aabb.get_center());
  148. Vector3 lnormal;
  149. Vector2 uv;
  150. get_uv_and_normal(inters, p_vtx, p_uv, p_normal, uv, normal);
  151. if (lnormal == Vector3()) { //just in case normal is not provided
  152. lnormal = normal;
  153. }
  154. int uv_x = CLAMP(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
  155. int uv_y = CLAMP(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
  156. int ofs = uv_y * bake_texture_size + uv_x;
  157. alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  158. albedo_accum.r = p_material.albedo[ofs].r * alpha;
  159. albedo_accum.g = p_material.albedo[ofs].g * alpha;
  160. albedo_accum.b = p_material.albedo[ofs].b * alpha;
  161. albedo_accum.a = p_material.albedo[ofs].a * alpha;
  162. emission_accum.r = p_material.emission[ofs].r * alpha;
  163. emission_accum.g = p_material.emission[ofs].g * alpha;
  164. emission_accum.b = p_material.emission[ofs].b * alpha;
  165. normal_accum = lnormal * alpha;
  166. } else {
  167. float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
  168. alpha *= accdiv;
  169. albedo_accum.r *= accdiv;
  170. albedo_accum.g *= accdiv;
  171. albedo_accum.b *= accdiv;
  172. albedo_accum.a *= accdiv;
  173. emission_accum.r *= accdiv;
  174. emission_accum.g *= accdiv;
  175. emission_accum.b *= accdiv;
  176. normal_accum *= accdiv;
  177. }
  178. //put this temporarily here, corrected in a later step
  179. bake_cells.write[p_idx].albedo[0] += albedo_accum.r;
  180. bake_cells.write[p_idx].albedo[1] += albedo_accum.g;
  181. bake_cells.write[p_idx].albedo[2] += albedo_accum.b;
  182. bake_cells.write[p_idx].emission[0] += emission_accum.r;
  183. bake_cells.write[p_idx].emission[1] += emission_accum.g;
  184. bake_cells.write[p_idx].emission[2] += emission_accum.b;
  185. bake_cells.write[p_idx].normal[0] += normal_accum.x;
  186. bake_cells.write[p_idx].normal[1] += normal_accum.y;
  187. bake_cells.write[p_idx].normal[2] += normal_accum.z;
  188. bake_cells.write[p_idx].alpha += alpha;
  189. } else {
  190. //go down
  191. int half = (1 << cell_subdiv) >> (p_level + 1);
  192. for (int i = 0; i < 8; i++) {
  193. AABB aabb = p_aabb;
  194. aabb.size *= 0.5;
  195. int nx = p_x;
  196. int ny = p_y;
  197. int nz = p_z;
  198. if (i & 1) {
  199. aabb.position.x += aabb.size.x;
  200. nx += half;
  201. }
  202. if (i & 2) {
  203. aabb.position.y += aabb.size.y;
  204. ny += half;
  205. }
  206. if (i & 4) {
  207. aabb.position.z += aabb.size.z;
  208. nz += half;
  209. }
  210. //make sure to not plot beyond limits
  211. if (nx < 0 || nx >= axis_cell_size[0] || ny < 0 || ny >= axis_cell_size[1] || nz < 0 || nz >= axis_cell_size[2]) {
  212. continue;
  213. }
  214. {
  215. AABB test_aabb = aabb;
  216. //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
  217. Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
  218. if (!Geometry3D::triangle_box_overlap(test_aabb.position + qsize, qsize, p_vtx)) {
  219. //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
  220. //does not fit in child, go on
  221. continue;
  222. }
  223. }
  224. if (bake_cells[p_idx].children[i] == CHILD_EMPTY) {
  225. //sub cell must be created
  226. uint32_t child_idx = bake_cells.size();
  227. bake_cells.write[p_idx].children[i] = child_idx;
  228. bake_cells.resize(bake_cells.size() + 1);
  229. bake_cells.write[child_idx].level = p_level + 1;
  230. bake_cells.write[child_idx].x = nx / half;
  231. bake_cells.write[child_idx].y = ny / half;
  232. bake_cells.write[child_idx].z = nz / half;
  233. }
  234. _plot_face(bake_cells[p_idx].children[i], p_level + 1, nx, ny, nz, p_vtx, p_normal, p_uv, p_material, aabb);
  235. }
  236. }
  237. }
  238. Vector<Color> Voxelizer::_get_bake_texture(Ref<Image> p_image, const Color &p_color_mul, const Color &p_color_add) {
  239. Vector<Color> ret;
  240. if (p_image.is_null() || p_image->is_empty()) {
  241. ret.resize(bake_texture_size * bake_texture_size);
  242. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  243. ret.write[i] = p_color_add;
  244. }
  245. return ret;
  246. }
  247. p_image = p_image->duplicate();
  248. if (p_image->is_compressed()) {
  249. p_image->decompress();
  250. }
  251. p_image->convert(Image::FORMAT_RGBA8);
  252. p_image->resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
  253. const uint8_t *r = p_image->get_data().ptr();
  254. ret.resize(bake_texture_size * bake_texture_size);
  255. for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
  256. Color c;
  257. c.r = (r[i * 4 + 0] / 255.0) * p_color_mul.r + p_color_add.r;
  258. c.g = (r[i * 4 + 1] / 255.0) * p_color_mul.g + p_color_add.g;
  259. c.b = (r[i * 4 + 2] / 255.0) * p_color_mul.b + p_color_add.b;
  260. c.a = r[i * 4 + 3] / 255.0;
  261. ret.write[i] = c;
  262. }
  263. return ret;
  264. }
  265. Voxelizer::MaterialCache Voxelizer::_get_material_cache(Ref<Material> p_material) {
  266. // This way of obtaining materials is inaccurate and also does not support some compressed formats very well.
  267. Ref<BaseMaterial3D> mat = p_material;
  268. Ref<Material> material = mat; //hack for now
  269. if (material_cache.has(material)) {
  270. return material_cache[material];
  271. }
  272. MaterialCache mc;
  273. if (mat.is_valid()) {
  274. Ref<Texture2D> albedo_tex = mat->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
  275. Ref<Image> img_albedo;
  276. if (albedo_tex.is_valid()) {
  277. img_albedo = albedo_tex->get_image();
  278. mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo(), Color(0, 0, 0)); // albedo texture, color is multiplicative
  279. } else {
  280. mc.albedo = _get_bake_texture(img_albedo, Color(1, 1, 1), mat->get_albedo()); // no albedo texture, color is additive
  281. }
  282. if (mat->get_feature(BaseMaterial3D::FEATURE_EMISSION)) {
  283. Ref<Texture2D> emission_tex = mat->get_texture(BaseMaterial3D::TEXTURE_EMISSION);
  284. Color emission_col = mat->get_emission();
  285. float emission_energy = mat->get_emission_energy_multiplier() * exposure_normalization;
  286. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  287. emission_energy *= mat->get_emission_intensity();
  288. }
  289. Ref<Image> img_emission;
  290. if (emission_tex.is_valid()) {
  291. img_emission = emission_tex->get_image();
  292. }
  293. if (mat->get_emission_operator() == BaseMaterial3D::EMISSION_OP_ADD) {
  294. mc.emission = _get_bake_texture(img_emission, Color(1, 1, 1) * emission_energy, emission_col * emission_energy);
  295. } else {
  296. mc.emission = _get_bake_texture(img_emission, emission_col * emission_energy, Color(0, 0, 0));
  297. }
  298. } else {
  299. Ref<Image> empty;
  300. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  301. }
  302. } else {
  303. Ref<Image> empty;
  304. mc.albedo = _get_bake_texture(empty, Color(0, 0, 0), Color(1, 1, 1));
  305. mc.emission = _get_bake_texture(empty, Color(0, 0, 0), Color(0, 0, 0));
  306. }
  307. material_cache[p_material] = mc;
  308. return mc;
  309. }
  310. void Voxelizer::plot_mesh(const Transform3D &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material) {
  311. ERR_FAIL_COND_MSG(!p_xform.is_finite(), "Invalid mesh bake transform.");
  312. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  313. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  314. continue; //only triangles
  315. }
  316. Ref<Material> src_material;
  317. if (p_override_material.is_valid()) {
  318. src_material = p_override_material;
  319. } else if (i < p_materials.size() && p_materials[i].is_valid()) {
  320. src_material = p_materials[i];
  321. } else {
  322. src_material = p_mesh->surface_get_material(i);
  323. }
  324. MaterialCache material = _get_material_cache(src_material);
  325. Array a = p_mesh->surface_get_arrays(i);
  326. Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  327. const Vector3 *vr = vertices.ptr();
  328. Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
  329. const Vector2 *uvr = nullptr;
  330. Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  331. const Vector3 *nr = nullptr;
  332. Vector<int> index = a[Mesh::ARRAY_INDEX];
  333. if (uv.size()) {
  334. uvr = uv.ptr();
  335. }
  336. if (normals.size()) {
  337. nr = normals.ptr();
  338. }
  339. if (index.size()) {
  340. int facecount = index.size() / 3;
  341. const int *ir = index.ptr();
  342. for (int j = 0; j < facecount; j++) {
  343. Vector3 vtxs[3];
  344. Vector2 uvs[3];
  345. Vector3 normal[3];
  346. for (int k = 0; k < 3; k++) {
  347. vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
  348. }
  349. if (uvr) {
  350. for (int k = 0; k < 3; k++) {
  351. uvs[k] = uvr[ir[j * 3 + k]];
  352. }
  353. }
  354. if (nr) {
  355. for (int k = 0; k < 3; k++) {
  356. normal[k] = nr[ir[j * 3 + k]];
  357. }
  358. }
  359. //test against original bounds
  360. if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
  361. continue;
  362. }
  363. //plot
  364. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  365. }
  366. } else {
  367. int facecount = vertices.size() / 3;
  368. for (int j = 0; j < facecount; j++) {
  369. Vector3 vtxs[3];
  370. Vector2 uvs[3];
  371. Vector3 normal[3];
  372. for (int k = 0; k < 3; k++) {
  373. vtxs[k] = p_xform.xform(vr[j * 3 + k]);
  374. }
  375. if (uvr) {
  376. for (int k = 0; k < 3; k++) {
  377. uvs[k] = uvr[j * 3 + k];
  378. }
  379. }
  380. if (nr) {
  381. for (int k = 0; k < 3; k++) {
  382. normal[k] = nr[j * 3 + k];
  383. }
  384. }
  385. //test against original bounds
  386. if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
  387. continue;
  388. }
  389. //plot face
  390. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  391. }
  392. }
  393. }
  394. max_original_cells = bake_cells.size();
  395. }
  396. void Voxelizer::_sort() {
  397. // cells need to be sorted by level and coordinates
  398. // it is important that level has more priority (for compute), and that Z has the least,
  399. // given it may aid older implementations plot using GPU
  400. Vector<CellSort> sorted_cells;
  401. uint32_t cell_count = bake_cells.size();
  402. sorted_cells.resize(cell_count);
  403. {
  404. CellSort *sort_cellsp = sorted_cells.ptrw();
  405. const Cell *bake_cellsp = bake_cells.ptr();
  406. for (uint32_t i = 0; i < cell_count; i++) {
  407. sort_cellsp[i].x = bake_cellsp[i].x;
  408. sort_cellsp[i].y = bake_cellsp[i].y;
  409. sort_cellsp[i].z = bake_cellsp[i].z;
  410. sort_cellsp[i].level = bake_cellsp[i].level;
  411. sort_cellsp[i].index = i;
  412. }
  413. }
  414. sorted_cells.sort();
  415. //verify just in case, index 0 must be level 0
  416. ERR_FAIL_COND(sorted_cells[0].level != 0);
  417. Vector<Cell> new_bake_cells;
  418. new_bake_cells.resize(cell_count);
  419. Vector<uint32_t> reverse_map;
  420. {
  421. reverse_map.resize(cell_count);
  422. const CellSort *sort_cellsp = sorted_cells.ptr();
  423. uint32_t *reverse_mapp = reverse_map.ptrw();
  424. for (uint32_t i = 0; i < cell_count; i++) {
  425. reverse_mapp[sort_cellsp[i].index] = i;
  426. }
  427. }
  428. {
  429. const CellSort *sort_cellsp = sorted_cells.ptr();
  430. const Cell *bake_cellsp = bake_cells.ptr();
  431. const uint32_t *reverse_mapp = reverse_map.ptr();
  432. Cell *new_bake_cellsp = new_bake_cells.ptrw();
  433. for (uint32_t i = 0; i < cell_count; i++) {
  434. //copy to new cell
  435. new_bake_cellsp[i] = bake_cellsp[sort_cellsp[i].index];
  436. //remap children
  437. for (uint32_t j = 0; j < 8; j++) {
  438. if (new_bake_cellsp[i].children[j] != CHILD_EMPTY) {
  439. new_bake_cellsp[i].children[j] = reverse_mapp[new_bake_cellsp[i].children[j]];
  440. }
  441. }
  442. }
  443. }
  444. bake_cells = new_bake_cells;
  445. sorted = true;
  446. }
  447. void Voxelizer::_fixup_plot(int p_idx, int p_level) {
  448. if (p_level == cell_subdiv) {
  449. leaf_voxel_count++;
  450. float alpha = bake_cells[p_idx].alpha;
  451. bake_cells.write[p_idx].albedo[0] /= alpha;
  452. bake_cells.write[p_idx].albedo[1] /= alpha;
  453. bake_cells.write[p_idx].albedo[2] /= alpha;
  454. //transfer emission to light
  455. bake_cells.write[p_idx].emission[0] /= alpha;
  456. bake_cells.write[p_idx].emission[1] /= alpha;
  457. bake_cells.write[p_idx].emission[2] /= alpha;
  458. bake_cells.write[p_idx].normal[0] /= alpha;
  459. bake_cells.write[p_idx].normal[1] /= alpha;
  460. bake_cells.write[p_idx].normal[2] /= alpha;
  461. Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
  462. if (n.length() < 0.01) {
  463. //too much fight over normal, zero it
  464. bake_cells.write[p_idx].normal[0] = 0;
  465. bake_cells.write[p_idx].normal[1] = 0;
  466. bake_cells.write[p_idx].normal[2] = 0;
  467. } else {
  468. n.normalize();
  469. bake_cells.write[p_idx].normal[0] = n.x;
  470. bake_cells.write[p_idx].normal[1] = n.y;
  471. bake_cells.write[p_idx].normal[2] = n.z;
  472. }
  473. bake_cells.write[p_idx].alpha = 1.0;
  474. /*if (bake_light.size()) {
  475. for(int i=0;i<6;i++) {
  476. }
  477. }*/
  478. } else {
  479. //go down
  480. bake_cells.write[p_idx].emission[0] = 0;
  481. bake_cells.write[p_idx].emission[1] = 0;
  482. bake_cells.write[p_idx].emission[2] = 0;
  483. bake_cells.write[p_idx].normal[0] = 0;
  484. bake_cells.write[p_idx].normal[1] = 0;
  485. bake_cells.write[p_idx].normal[2] = 0;
  486. bake_cells.write[p_idx].albedo[0] = 0;
  487. bake_cells.write[p_idx].albedo[1] = 0;
  488. bake_cells.write[p_idx].albedo[2] = 0;
  489. float alpha_average = 0;
  490. for (int i = 0; i < 8; i++) {
  491. uint32_t child = bake_cells[p_idx].children[i];
  492. if (child == CHILD_EMPTY) {
  493. continue;
  494. }
  495. _fixup_plot(child, p_level + 1);
  496. alpha_average += bake_cells[child].alpha;
  497. }
  498. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  499. }
  500. }
  501. void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds, float p_exposure_normalization) {
  502. sorted = false;
  503. original_bounds = p_bounds;
  504. cell_subdiv = p_subdiv;
  505. exposure_normalization = p_exposure_normalization;
  506. bake_cells.resize(1);
  507. material_cache.clear();
  508. //find out the actual real bounds, power of 2, which gets the highest subdivision
  509. po2_bounds = p_bounds;
  510. int longest_axis = po2_bounds.get_longest_axis_index();
  511. axis_cell_size[longest_axis] = 1 << cell_subdiv;
  512. leaf_voxel_count = 0;
  513. for (int i = 0; i < 3; i++) {
  514. if (i == longest_axis) {
  515. continue;
  516. }
  517. axis_cell_size[i] = axis_cell_size[longest_axis];
  518. real_t axis_size = po2_bounds.size[longest_axis];
  519. //shrink until fit subdiv
  520. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  521. axis_size /= 2.0;
  522. axis_cell_size[i] >>= 1;
  523. }
  524. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  525. }
  526. Transform3D to_bounds;
  527. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  528. to_bounds.origin = po2_bounds.position;
  529. Transform3D to_grid;
  530. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  531. to_cell_space = to_grid * to_bounds.affine_inverse();
  532. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  533. }
  534. void Voxelizer::end_bake() {
  535. if (!sorted) {
  536. _sort();
  537. }
  538. _fixup_plot(0, 0);
  539. }
  540. //create the data for rendering server
  541. int Voxelizer::get_voxel_gi_octree_depth() const {
  542. return cell_subdiv;
  543. }
  544. Vector3i Voxelizer::get_voxel_gi_octree_size() const {
  545. return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
  546. }
  547. int Voxelizer::get_voxel_gi_cell_count() const {
  548. return bake_cells.size();
  549. }
  550. Vector<uint8_t> Voxelizer::get_voxel_gi_octree_cells() const {
  551. Vector<uint8_t> data;
  552. data.resize((8 * 4) * bake_cells.size()); //8 uint32t values
  553. {
  554. uint8_t *w = data.ptrw();
  555. uint32_t *children_cells = (uint32_t *)w;
  556. const Cell *cells = bake_cells.ptr();
  557. uint32_t cell_count = bake_cells.size();
  558. for (uint32_t i = 0; i < cell_count; i++) {
  559. for (uint32_t j = 0; j < 8; j++) {
  560. children_cells[i * 8 + j] = cells[i].children[j];
  561. }
  562. }
  563. }
  564. return data;
  565. }
  566. Vector<uint8_t> Voxelizer::get_voxel_gi_data_cells() const {
  567. Vector<uint8_t> data;
  568. data.resize((4 * 4) * bake_cells.size()); //8 uint32t values
  569. {
  570. uint8_t *w = data.ptrw();
  571. uint32_t *dataptr = (uint32_t *)w;
  572. const Cell *cells = bake_cells.ptr();
  573. uint32_t cell_count = bake_cells.size();
  574. for (uint32_t i = 0; i < cell_count; i++) {
  575. { //position
  576. uint32_t x = cells[i].x;
  577. uint32_t y = cells[i].y;
  578. uint32_t z = cells[i].z;
  579. uint32_t position = x;
  580. position |= y << 11;
  581. position |= z << 21;
  582. dataptr[i * 4 + 0] = position;
  583. }
  584. { //albedo + alpha
  585. uint32_t rgba = uint32_t(CLAMP(cells[i].alpha * 255.0, 0, 255)) << 24; //a
  586. rgba |= uint32_t(CLAMP(cells[i].albedo[2] * 255.0, 0, 255)) << 16; //b
  587. rgba |= uint32_t(CLAMP(cells[i].albedo[1] * 255.0, 0, 255)) << 8; //g
  588. rgba |= uint32_t(CLAMP(cells[i].albedo[0] * 255.0, 0, 255)); //r
  589. dataptr[i * 4 + 1] = rgba;
  590. }
  591. { //emission, as rgbe9995
  592. Color emission = Color(cells[i].emission[0], cells[i].emission[1], cells[i].emission[2]);
  593. dataptr[i * 4 + 2] = emission.to_rgbe9995();
  594. }
  595. { //normal
  596. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  597. n.normalize();
  598. uint32_t normal = uint32_t(uint8_t(int8_t(CLAMP(n.x * 127.0, -128, 127))));
  599. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.y * 127.0, -128, 127)))) << 8;
  600. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.z * 127.0, -128, 127)))) << 16;
  601. dataptr[i * 4 + 3] = normal;
  602. }
  603. }
  604. }
  605. return data;
  606. }
  607. Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
  608. uint32_t cell_count = bake_cells.size();
  609. const Cell *cells = bake_cells.ptr();
  610. Vector<int> level_count;
  611. level_count.resize(cell_subdiv + 1); //remember, always x+1 levels for x subdivisions
  612. {
  613. int *w = level_count.ptrw();
  614. for (int i = 0; i < cell_subdiv + 1; i++) {
  615. w[i] = 0;
  616. }
  617. for (uint32_t i = 0; i < cell_count; i++) {
  618. w[cells[i].level]++;
  619. }
  620. }
  621. return level_count;
  622. }
  623. // euclidean distance computation based on:
  624. // https://prideout.net/blog/distance_fields/
  625. #define square(m_s) ((m_s) * (m_s))
  626. #define INF 1e20
  627. /* dt of 1d function using squared distance */
  628. static void edt(float *f, int stride, int n) {
  629. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  630. int *v = reinterpret_cast<int *>(&(d[n]));
  631. float *z = reinterpret_cast<float *>(&v[n]);
  632. int k = 0;
  633. v[0] = 0;
  634. z[0] = -INF;
  635. z[1] = +INF;
  636. for (int q = 1; q <= n - 1; q++) {
  637. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  638. while (s <= z[k]) {
  639. k--;
  640. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  641. }
  642. k++;
  643. v[k] = q;
  644. z[k] = s;
  645. z[k + 1] = +INF;
  646. }
  647. k = 0;
  648. for (int q = 0; q <= n - 1; q++) {
  649. while (z[k + 1] < q) {
  650. k++;
  651. }
  652. d[q] = square(q - v[k]) + f[v[k] * stride];
  653. }
  654. for (int i = 0; i < n; i++) {
  655. f[i * stride] = d[i];
  656. }
  657. }
  658. #undef square
  659. Vector<uint8_t> Voxelizer::get_sdf_3d_image() const {
  660. Vector3i octree_size = get_voxel_gi_octree_size();
  661. uint32_t float_count = octree_size.x * octree_size.y * octree_size.z;
  662. float *work_memory = memnew_arr(float, float_count);
  663. for (uint32_t i = 0; i < float_count; i++) {
  664. work_memory[i] = INF;
  665. }
  666. uint32_t y_mult = octree_size.x;
  667. uint32_t z_mult = y_mult * octree_size.y;
  668. //plot solid cells
  669. {
  670. const Cell *cells = bake_cells.ptr();
  671. uint32_t cell_count = bake_cells.size();
  672. for (uint32_t i = 0; i < cell_count; i++) {
  673. if (cells[i].level < (cell_subdiv - 1)) {
  674. continue; //do not care about this level
  675. }
  676. work_memory[cells[i].x + cells[i].y * y_mult + cells[i].z * z_mult] = 0;
  677. }
  678. }
  679. //process in each direction
  680. //xy->z
  681. for (int i = 0; i < octree_size.x; i++) {
  682. for (int j = 0; j < octree_size.y; j++) {
  683. edt(&work_memory[i + j * y_mult], z_mult, octree_size.z);
  684. }
  685. }
  686. //xz->y
  687. for (int i = 0; i < octree_size.x; i++) {
  688. for (int j = 0; j < octree_size.z; j++) {
  689. edt(&work_memory[i + j * z_mult], y_mult, octree_size.y);
  690. }
  691. }
  692. //yz->x
  693. for (int i = 0; i < octree_size.y; i++) {
  694. for (int j = 0; j < octree_size.z; j++) {
  695. edt(&work_memory[i * y_mult + j * z_mult], 1, octree_size.x);
  696. }
  697. }
  698. Vector<uint8_t> image3d;
  699. image3d.resize(float_count);
  700. {
  701. uint8_t *w = image3d.ptrw();
  702. for (uint32_t i = 0; i < float_count; i++) {
  703. uint32_t d = uint32_t(Math::sqrt(work_memory[i]));
  704. if (d == 0) {
  705. w[i] = 0;
  706. } else {
  707. w[i] = MIN(d, 254u) + 1;
  708. }
  709. }
  710. }
  711. memdelete_arr(work_memory);
  712. return image3d;
  713. }
  714. #undef INF
  715. void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx) {
  716. if (p_level == cell_subdiv - 1) {
  717. Vector3 center = p_aabb.get_center();
  718. Transform3D xform;
  719. xform.origin = center;
  720. xform.basis.scale(p_aabb.size * 0.5);
  721. p_multimesh->set_instance_transform(idx, xform);
  722. Color col;
  723. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  724. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  725. p_multimesh->set_instance_color(idx, col);
  726. idx++;
  727. } else {
  728. for (int i = 0; i < 8; i++) {
  729. uint32_t child = bake_cells[p_idx].children[i];
  730. if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells) {
  731. continue;
  732. }
  733. AABB aabb = p_aabb;
  734. aabb.size *= 0.5;
  735. if (i & 1) {
  736. aabb.position.x += aabb.size.x;
  737. }
  738. if (i & 2) {
  739. aabb.position.y += aabb.size.y;
  740. }
  741. if (i & 4) {
  742. aabb.position.z += aabb.size.z;
  743. }
  744. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx);
  745. }
  746. }
  747. }
  748. Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
  749. Ref<MultiMesh> mm;
  750. mm.instantiate();
  751. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  752. mm->set_use_colors(true);
  753. mm->set_instance_count(leaf_voxel_count);
  754. Ref<ArrayMesh> mesh;
  755. mesh.instantiate();
  756. {
  757. Array arr;
  758. arr.resize(Mesh::ARRAY_MAX);
  759. Vector<Vector3> vertices;
  760. Vector<Color> colors;
  761. #define ADD_VTX(m_idx) \
  762. vertices.push_back(face_points[m_idx]); \
  763. colors.push_back(Color(1, 1, 1, 1));
  764. for (int i = 0; i < 6; i++) {
  765. Vector3 face_points[4];
  766. for (int j = 0; j < 4; j++) {
  767. real_t v[3];
  768. v[0] = 1.0;
  769. v[1] = 1 - 2 * ((j >> 1) & 1);
  770. v[2] = v[1] * (1 - 2 * (j & 1));
  771. for (int k = 0; k < 3; k++) {
  772. if (i < 3) {
  773. face_points[j][(i + k) % 3] = v[k];
  774. } else {
  775. face_points[3 - j][(i + k) % 3] = -v[k];
  776. }
  777. }
  778. }
  779. //tri 1
  780. ADD_VTX(0);
  781. ADD_VTX(1);
  782. ADD_VTX(2);
  783. //tri 2
  784. ADD_VTX(2);
  785. ADD_VTX(3);
  786. ADD_VTX(0);
  787. }
  788. arr[Mesh::ARRAY_VERTEX] = vertices;
  789. arr[Mesh::ARRAY_COLOR] = colors;
  790. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  791. }
  792. {
  793. Ref<StandardMaterial3D> fsm;
  794. fsm.instantiate();
  795. fsm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  796. fsm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  797. fsm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  798. fsm->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  799. fsm->set_albedo(Color(1, 1, 1, 1));
  800. mesh->surface_set_material(0, fsm);
  801. }
  802. mm->set_mesh(mesh);
  803. int idx = 0;
  804. _debug_mesh(0, 0, po2_bounds, mm, idx);
  805. return mm;
  806. }
  807. Transform3D Voxelizer::get_to_cell_space_xform() const {
  808. return to_cell_space;
  809. }
  810. Voxelizer::Voxelizer() {
  811. }