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