voxelizer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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 = Math::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 (Math::abs(plane.distance_to(ray_from)) < Math::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_CACHED(bool, "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. int Voxelizer::get_bake_steps(Ref<Mesh> &p_mesh) const {
  311. int bake_total = 0;
  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. Array a = p_mesh->surface_get_arrays(i);
  317. Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  318. Vector<int> index = a[Mesh::ARRAY_INDEX];
  319. bake_total += (index.size() > 0 ? index.size() : vertices.size()) / 3;
  320. }
  321. return bake_total;
  322. }
  323. Voxelizer::BakeResult Voxelizer::plot_mesh(const Transform3D &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material, BakeStepFunc p_bake_step_func) {
  324. ERR_FAIL_COND_V_MSG(!p_xform.is_finite(), BAKE_RESULT_INVALID_PARAMETER, "Invalid mesh bake transform.");
  325. // Precalculate for transforming vertex normals
  326. Basis normal_xform = p_xform.basis.inverse().transposed();
  327. int bake_total = get_bake_steps(p_mesh), bake_current = 0;
  328. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  329. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  330. continue; //only triangles
  331. }
  332. Ref<Material> src_material;
  333. if (p_override_material.is_valid()) {
  334. src_material = p_override_material;
  335. } else if (i < p_materials.size() && p_materials[i].is_valid()) {
  336. src_material = p_materials[i];
  337. } else {
  338. src_material = p_mesh->surface_get_material(i);
  339. }
  340. MaterialCache material = _get_material_cache(src_material);
  341. Array a = p_mesh->surface_get_arrays(i);
  342. Vector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
  343. const Vector3 *vr = vertices.ptr();
  344. Vector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
  345. const Vector2 *uvr = nullptr;
  346. Vector<Vector3> normals = a[Mesh::ARRAY_NORMAL];
  347. const Vector3 *nr = nullptr;
  348. Vector<int> index = a[Mesh::ARRAY_INDEX];
  349. if (uv.size()) {
  350. uvr = uv.ptr();
  351. }
  352. if (normals.size()) {
  353. nr = normals.ptr();
  354. }
  355. if (index.size()) {
  356. int facecount = index.size() / 3;
  357. const int *ir = index.ptr();
  358. for (int j = 0; j < facecount; j++) {
  359. Vector3 vtxs[3];
  360. Vector2 uvs[3];
  361. Vector3 normal[3];
  362. bake_current++;
  363. if (p_bake_step_func != nullptr && (bake_current & 2047) == 1) {
  364. if (p_bake_step_func(bake_current, bake_total)) {
  365. return BAKE_RESULT_CANCELLED;
  366. }
  367. }
  368. for (int k = 0; k < 3; k++) {
  369. vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
  370. }
  371. if (uvr) {
  372. for (int k = 0; k < 3; k++) {
  373. uvs[k] = uvr[ir[j * 3 + k]];
  374. }
  375. }
  376. if (nr) {
  377. for (int k = 0; k < 3; k++) {
  378. normal[k] = normal_xform.xform(nr[ir[j * 3 + k]]).normalized();
  379. }
  380. }
  381. //test against original bounds
  382. if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
  383. continue;
  384. }
  385. //plot
  386. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  387. }
  388. } else {
  389. int facecount = vertices.size() / 3;
  390. for (int j = 0; j < facecount; j++) {
  391. Vector3 vtxs[3];
  392. Vector2 uvs[3];
  393. Vector3 normal[3];
  394. bake_current++;
  395. if (p_bake_step_func != nullptr && (bake_current & 2047) == 1) {
  396. if (p_bake_step_func(bake_current, bake_total)) {
  397. return BAKE_RESULT_CANCELLED;
  398. }
  399. }
  400. for (int k = 0; k < 3; k++) {
  401. vtxs[k] = p_xform.xform(vr[j * 3 + k]);
  402. }
  403. if (uvr) {
  404. for (int k = 0; k < 3; k++) {
  405. uvs[k] = uvr[j * 3 + k];
  406. }
  407. }
  408. if (nr) {
  409. for (int k = 0; k < 3; k++) {
  410. normal[k] = nr[j * 3 + k];
  411. }
  412. }
  413. //test against original bounds
  414. if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
  415. continue;
  416. }
  417. //plot face
  418. _plot_face(0, 0, 0, 0, 0, vtxs, normal, uvs, material, po2_bounds);
  419. }
  420. }
  421. }
  422. max_original_cells = bake_cells.size();
  423. return BAKE_RESULT_OK;
  424. }
  425. void Voxelizer::_sort() {
  426. // cells need to be sorted by level and coordinates
  427. // it is important that level has more priority (for compute), and that Z has the least,
  428. // given it may aid older implementations plot using GPU
  429. Vector<CellSort> sorted_cells;
  430. uint32_t cell_count = bake_cells.size();
  431. sorted_cells.resize(cell_count);
  432. {
  433. CellSort *sort_cellsp = sorted_cells.ptrw();
  434. const Cell *bake_cellsp = bake_cells.ptr();
  435. for (uint32_t i = 0; i < cell_count; i++) {
  436. sort_cellsp[i].x = bake_cellsp[i].x;
  437. sort_cellsp[i].y = bake_cellsp[i].y;
  438. sort_cellsp[i].z = bake_cellsp[i].z;
  439. sort_cellsp[i].level = bake_cellsp[i].level;
  440. sort_cellsp[i].index = i;
  441. }
  442. }
  443. sorted_cells.sort();
  444. //verify just in case, index 0 must be level 0
  445. ERR_FAIL_COND(sorted_cells[0].level != 0);
  446. Vector<Cell> new_bake_cells;
  447. new_bake_cells.resize(cell_count);
  448. Vector<uint32_t> reverse_map;
  449. {
  450. reverse_map.resize(cell_count);
  451. const CellSort *sort_cellsp = sorted_cells.ptr();
  452. uint32_t *reverse_mapp = reverse_map.ptrw();
  453. for (uint32_t i = 0; i < cell_count; i++) {
  454. reverse_mapp[sort_cellsp[i].index] = i;
  455. }
  456. }
  457. {
  458. const CellSort *sort_cellsp = sorted_cells.ptr();
  459. const Cell *bake_cellsp = bake_cells.ptr();
  460. const uint32_t *reverse_mapp = reverse_map.ptr();
  461. Cell *new_bake_cellsp = new_bake_cells.ptrw();
  462. for (uint32_t i = 0; i < cell_count; i++) {
  463. //copy to new cell
  464. new_bake_cellsp[i] = bake_cellsp[sort_cellsp[i].index];
  465. //remap children
  466. for (uint32_t j = 0; j < 8; j++) {
  467. if (new_bake_cellsp[i].children[j] != CHILD_EMPTY) {
  468. new_bake_cellsp[i].children[j] = reverse_mapp[new_bake_cellsp[i].children[j]];
  469. }
  470. }
  471. }
  472. }
  473. bake_cells = new_bake_cells;
  474. sorted = true;
  475. }
  476. void Voxelizer::_fixup_plot(int p_idx, int p_level) {
  477. if (p_level == cell_subdiv) {
  478. leaf_voxel_count++;
  479. float alpha = bake_cells[p_idx].alpha;
  480. bake_cells.write[p_idx].albedo[0] /= alpha;
  481. bake_cells.write[p_idx].albedo[1] /= alpha;
  482. bake_cells.write[p_idx].albedo[2] /= alpha;
  483. //transfer emission to light
  484. bake_cells.write[p_idx].emission[0] /= alpha;
  485. bake_cells.write[p_idx].emission[1] /= alpha;
  486. bake_cells.write[p_idx].emission[2] /= alpha;
  487. bake_cells.write[p_idx].normal[0] /= alpha;
  488. bake_cells.write[p_idx].normal[1] /= alpha;
  489. bake_cells.write[p_idx].normal[2] /= alpha;
  490. Vector3 n(bake_cells[p_idx].normal[0], bake_cells[p_idx].normal[1], bake_cells[p_idx].normal[2]);
  491. if (n.length() < 0.01) {
  492. //too much fight over normal, zero it
  493. bake_cells.write[p_idx].normal[0] = 0;
  494. bake_cells.write[p_idx].normal[1] = 0;
  495. bake_cells.write[p_idx].normal[2] = 0;
  496. } else {
  497. n.normalize();
  498. bake_cells.write[p_idx].normal[0] = n.x;
  499. bake_cells.write[p_idx].normal[1] = n.y;
  500. bake_cells.write[p_idx].normal[2] = n.z;
  501. }
  502. bake_cells.write[p_idx].alpha = 1.0;
  503. /*if (bake_light.size()) {
  504. for(int i=0;i<6;i++) {
  505. }
  506. }*/
  507. } else {
  508. //go down
  509. bake_cells.write[p_idx].emission[0] = 0;
  510. bake_cells.write[p_idx].emission[1] = 0;
  511. bake_cells.write[p_idx].emission[2] = 0;
  512. bake_cells.write[p_idx].normal[0] = 0;
  513. bake_cells.write[p_idx].normal[1] = 0;
  514. bake_cells.write[p_idx].normal[2] = 0;
  515. bake_cells.write[p_idx].albedo[0] = 0;
  516. bake_cells.write[p_idx].albedo[1] = 0;
  517. bake_cells.write[p_idx].albedo[2] = 0;
  518. float alpha_average = 0;
  519. for (int i = 0; i < 8; i++) {
  520. uint32_t child = bake_cells[p_idx].children[i];
  521. if (child == CHILD_EMPTY) {
  522. continue;
  523. }
  524. _fixup_plot(child, p_level + 1);
  525. alpha_average += bake_cells[child].alpha;
  526. }
  527. bake_cells.write[p_idx].alpha = alpha_average / 8.0;
  528. }
  529. }
  530. void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds, float p_exposure_normalization) {
  531. sorted = false;
  532. original_bounds = p_bounds;
  533. cell_subdiv = p_subdiv;
  534. exposure_normalization = p_exposure_normalization;
  535. bake_cells.resize(1);
  536. material_cache.clear();
  537. //find out the actual real bounds, power of 2, which gets the highest subdivision
  538. po2_bounds = p_bounds;
  539. int longest_axis = po2_bounds.get_longest_axis_index();
  540. axis_cell_size[longest_axis] = 1 << cell_subdiv;
  541. leaf_voxel_count = 0;
  542. for (int i = 0; i < 3; i++) {
  543. if (i == longest_axis) {
  544. continue;
  545. }
  546. axis_cell_size[i] = axis_cell_size[longest_axis];
  547. real_t axis_size = po2_bounds.size[longest_axis];
  548. //shrink until fit subdiv
  549. while (axis_size / 2.0 >= po2_bounds.size[i]) {
  550. axis_size /= 2.0;
  551. axis_cell_size[i] >>= 1;
  552. }
  553. po2_bounds.size[i] = po2_bounds.size[longest_axis];
  554. }
  555. Transform3D to_bounds;
  556. to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
  557. to_bounds.origin = po2_bounds.position;
  558. Transform3D to_grid;
  559. to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
  560. to_cell_space = to_grid * to_bounds.affine_inverse();
  561. cell_size = po2_bounds.size[longest_axis] / axis_cell_size[longest_axis];
  562. }
  563. void Voxelizer::end_bake() {
  564. if (!sorted) {
  565. _sort();
  566. }
  567. _fixup_plot(0, 0);
  568. }
  569. //create the data for rendering server
  570. int Voxelizer::get_voxel_gi_octree_depth() const {
  571. return cell_subdiv;
  572. }
  573. Vector3i Voxelizer::get_voxel_gi_octree_size() const {
  574. return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
  575. }
  576. int Voxelizer::get_voxel_gi_cell_count() const {
  577. return bake_cells.size();
  578. }
  579. Vector<uint8_t> Voxelizer::get_voxel_gi_octree_cells() const {
  580. Vector<uint8_t> data;
  581. data.resize((8 * 4) * bake_cells.size()); //8 uint32t values
  582. {
  583. uint8_t *w = data.ptrw();
  584. uint32_t *children_cells = (uint32_t *)w;
  585. const Cell *cells = bake_cells.ptr();
  586. uint32_t cell_count = bake_cells.size();
  587. for (uint32_t i = 0; i < cell_count; i++) {
  588. for (uint32_t j = 0; j < 8; j++) {
  589. children_cells[i * 8 + j] = cells[i].children[j];
  590. }
  591. }
  592. }
  593. return data;
  594. }
  595. Vector<uint8_t> Voxelizer::get_voxel_gi_data_cells() const {
  596. Vector<uint8_t> data;
  597. data.resize((4 * 4) * bake_cells.size()); //8 uint32t values
  598. {
  599. uint8_t *w = data.ptrw();
  600. uint32_t *dataptr = (uint32_t *)w;
  601. const Cell *cells = bake_cells.ptr();
  602. uint32_t cell_count = bake_cells.size();
  603. for (uint32_t i = 0; i < cell_count; i++) {
  604. { //position
  605. uint32_t x = cells[i].x;
  606. uint32_t y = cells[i].y;
  607. uint32_t z = cells[i].z;
  608. uint32_t position = x;
  609. position |= y << 11;
  610. position |= z << 21;
  611. dataptr[i * 4 + 0] = position;
  612. }
  613. { //albedo + alpha
  614. uint32_t rgba = uint32_t(CLAMP(cells[i].alpha * 255.0, 0, 255)) << 24; //a
  615. rgba |= uint32_t(CLAMP(cells[i].albedo[2] * 255.0, 0, 255)) << 16; //b
  616. rgba |= uint32_t(CLAMP(cells[i].albedo[1] * 255.0, 0, 255)) << 8; //g
  617. rgba |= uint32_t(CLAMP(cells[i].albedo[0] * 255.0, 0, 255)); //r
  618. dataptr[i * 4 + 1] = rgba;
  619. }
  620. { //emission, as rgbe9995
  621. Color emission = Color(cells[i].emission[0], cells[i].emission[1], cells[i].emission[2]);
  622. dataptr[i * 4 + 2] = emission.to_rgbe9995();
  623. }
  624. { //normal
  625. Vector3 n(bake_cells[i].normal[0], bake_cells[i].normal[1], bake_cells[i].normal[2]);
  626. n.normalize();
  627. uint32_t normal = uint32_t(uint8_t(int8_t(CLAMP(n.x * 127.0, -128, 127))));
  628. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.y * 127.0, -128, 127)))) << 8;
  629. normal |= uint32_t(uint8_t(int8_t(CLAMP(n.z * 127.0, -128, 127)))) << 16;
  630. dataptr[i * 4 + 3] = normal;
  631. }
  632. }
  633. }
  634. return data;
  635. }
  636. Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
  637. uint32_t cell_count = bake_cells.size();
  638. const Cell *cells = bake_cells.ptr();
  639. Vector<int> level_count;
  640. level_count.resize(cell_subdiv + 1); //remember, always x+1 levels for x subdivisions
  641. {
  642. int *w = level_count.ptrw();
  643. for (int i = 0; i < cell_subdiv + 1; i++) {
  644. w[i] = 0;
  645. }
  646. for (uint32_t i = 0; i < cell_count; i++) {
  647. w[cells[i].level]++;
  648. }
  649. }
  650. return level_count;
  651. }
  652. // euclidean distance computation based on:
  653. // https://prideout.net/blog/distance_fields/
  654. #define square(m_s) ((m_s) * (m_s))
  655. /* dt of 1d function using squared distance */
  656. static void edt(float *f, int stride, int n) {
  657. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  658. int *v = reinterpret_cast<int *>(&(d[n]));
  659. float *z = reinterpret_cast<float *>(&v[n]);
  660. int k = 0;
  661. v[0] = 0;
  662. z[0] = -Math::INF;
  663. z[1] = +Math::INF;
  664. for (int q = 1; q <= n - 1; q++) {
  665. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  666. while (s <= z[k]) {
  667. k--;
  668. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  669. }
  670. k++;
  671. v[k] = q;
  672. z[k] = s;
  673. z[k + 1] = +Math::INF;
  674. }
  675. k = 0;
  676. for (int q = 0; q <= n - 1; q++) {
  677. while (z[k + 1] < q) {
  678. k++;
  679. }
  680. d[q] = square(q - v[k]) + f[v[k] * stride];
  681. }
  682. for (int i = 0; i < n; i++) {
  683. f[i * stride] = d[i];
  684. }
  685. }
  686. #undef square
  687. Voxelizer::BakeResult Voxelizer::get_sdf_3d_image(Vector<uint8_t> &r_image, BakeStepFunc p_bake_step_function) const {
  688. Vector3i octree_size = get_voxel_gi_octree_size();
  689. uint32_t float_count = octree_size.x * octree_size.y * octree_size.z;
  690. float *work_memory = memnew_arr(float, float_count);
  691. for (uint32_t i = 0; i < float_count; i++) {
  692. work_memory[i] = Math::INF;
  693. }
  694. uint32_t y_mult = octree_size.x;
  695. uint32_t z_mult = y_mult * octree_size.y;
  696. //plot solid cells
  697. {
  698. const Cell *cells = bake_cells.ptr();
  699. uint32_t cell_count = bake_cells.size();
  700. for (uint32_t i = 0; i < cell_count; i++) {
  701. if (cells[i].level < cell_subdiv) {
  702. continue; //do not care about this level
  703. }
  704. work_memory[cells[i].x + cells[i].y * y_mult + cells[i].z * z_mult] = 0;
  705. }
  706. }
  707. //process in each direction
  708. int bake_total = octree_size.x * 2 + octree_size.y, bake_current = 0;
  709. //xy->z
  710. for (int i = 0; i < octree_size.x; i++, bake_current++) {
  711. if (p_bake_step_function) {
  712. if (p_bake_step_function(bake_current, bake_total)) {
  713. memdelete_arr(work_memory);
  714. return BAKE_RESULT_CANCELLED;
  715. }
  716. }
  717. for (int j = 0; j < octree_size.y; j++) {
  718. edt(&work_memory[i + j * y_mult], z_mult, octree_size.z);
  719. }
  720. }
  721. //xz->y
  722. for (int i = 0; i < octree_size.x; i++, bake_current++) {
  723. if (p_bake_step_function) {
  724. if (p_bake_step_function(bake_current, bake_total)) {
  725. memdelete_arr(work_memory);
  726. return BAKE_RESULT_CANCELLED;
  727. }
  728. }
  729. for (int j = 0; j < octree_size.z; j++) {
  730. edt(&work_memory[i + j * z_mult], y_mult, octree_size.y);
  731. }
  732. }
  733. //yz->x
  734. for (int i = 0; i < octree_size.y; i++, bake_current++) {
  735. if (p_bake_step_function) {
  736. if (p_bake_step_function(bake_current, bake_total)) {
  737. memdelete_arr(work_memory);
  738. return BAKE_RESULT_CANCELLED;
  739. }
  740. }
  741. for (int j = 0; j < octree_size.z; j++) {
  742. edt(&work_memory[i * y_mult + j * z_mult], 1, octree_size.x);
  743. }
  744. }
  745. r_image.resize(float_count);
  746. {
  747. uint8_t *w = r_image.ptrw();
  748. for (uint32_t i = 0; i < float_count; i++) {
  749. uint32_t d = uint32_t(Math::sqrt(work_memory[i]));
  750. if (d == 0) {
  751. w[i] = 0;
  752. } else {
  753. w[i] = MIN(d, 254u) + 1;
  754. }
  755. }
  756. }
  757. memdelete_arr(work_memory);
  758. return BAKE_RESULT_OK;
  759. }
  760. void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx) {
  761. if (p_level == cell_subdiv - 1) {
  762. Vector3 center = p_aabb.get_center();
  763. Transform3D xform;
  764. xform.origin = center;
  765. xform.basis.scale(p_aabb.size * 0.5);
  766. p_multimesh->set_instance_transform(idx, xform);
  767. Color col;
  768. col = Color(bake_cells[p_idx].albedo[0], bake_cells[p_idx].albedo[1], bake_cells[p_idx].albedo[2]);
  769. //Color col = Color(bake_cells[p_idx].emission[0], bake_cells[p_idx].emission[1], bake_cells[p_idx].emission[2]);
  770. p_multimesh->set_instance_color(idx, col);
  771. idx++;
  772. } else {
  773. for (int i = 0; i < 8; i++) {
  774. uint32_t child = bake_cells[p_idx].children[i];
  775. if (child == CHILD_EMPTY || child >= (uint32_t)max_original_cells) {
  776. continue;
  777. }
  778. AABB aabb = p_aabb;
  779. aabb.size *= 0.5;
  780. if (i & 1) {
  781. aabb.position.x += aabb.size.x;
  782. }
  783. if (i & 2) {
  784. aabb.position.y += aabb.size.y;
  785. }
  786. if (i & 4) {
  787. aabb.position.z += aabb.size.z;
  788. }
  789. _debug_mesh(bake_cells[p_idx].children[i], p_level + 1, aabb, p_multimesh, idx);
  790. }
  791. }
  792. }
  793. Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
  794. Ref<MultiMesh> mm;
  795. mm.instantiate();
  796. mm->set_transform_format(MultiMesh::TRANSFORM_3D);
  797. mm->set_use_colors(true);
  798. mm->set_instance_count(leaf_voxel_count);
  799. Ref<ArrayMesh> mesh;
  800. mesh.instantiate();
  801. {
  802. Array arr;
  803. arr.resize(Mesh::ARRAY_MAX);
  804. Vector<Vector3> vertices;
  805. Vector<Color> colors;
  806. #define ADD_VTX(m_idx) \
  807. vertices.push_back(face_points[m_idx]); \
  808. colors.push_back(Color(1, 1, 1, 1));
  809. for (int i = 0; i < 6; i++) {
  810. Vector3 face_points[4];
  811. for (int j = 0; j < 4; j++) {
  812. real_t v[3];
  813. v[0] = 1.0;
  814. v[1] = 1 - 2 * ((j >> 1) & 1);
  815. v[2] = v[1] * (1 - 2 * (j & 1));
  816. for (int k = 0; k < 3; k++) {
  817. if (i < 3) {
  818. face_points[j][(i + k) % 3] = v[k];
  819. } else {
  820. face_points[3 - j][(i + k) % 3] = -v[k];
  821. }
  822. }
  823. }
  824. //tri 1
  825. ADD_VTX(0);
  826. ADD_VTX(1);
  827. ADD_VTX(2);
  828. //tri 2
  829. ADD_VTX(2);
  830. ADD_VTX(3);
  831. ADD_VTX(0);
  832. }
  833. arr[Mesh::ARRAY_VERTEX] = vertices;
  834. arr[Mesh::ARRAY_COLOR] = colors;
  835. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  836. }
  837. {
  838. Ref<StandardMaterial3D> fsm;
  839. fsm.instantiate();
  840. fsm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  841. fsm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  842. fsm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  843. fsm->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  844. fsm->set_albedo(Color(1, 1, 1, 1));
  845. mesh->surface_set_material(0, fsm);
  846. }
  847. mm->set_mesh(mesh);
  848. int idx = 0;
  849. _debug_mesh(0, 0, po2_bounds, mm, idx);
  850. return mm;
  851. }
  852. Transform3D Voxelizer::get_to_cell_space_xform() const {
  853. return to_cell_space;
  854. }
  855. Voxelizer::Voxelizer() {
  856. }