voxelizer.cpp 30 KB

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