delaunay_3d.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /**************************************************************************/
  2. /* delaunay_3d.h */
  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. #pragma once
  31. #include "core/math/aabb.h"
  32. #include "core/math/projection.h"
  33. #include "core/math/vector3.h"
  34. #include "core/templates/list.h"
  35. #include "core/templates/local_vector.h"
  36. #include "core/templates/oa_hash_map.h"
  37. #include "core/templates/vector.h"
  38. #include "thirdparty/misc/r128.h"
  39. class Delaunay3D {
  40. struct Simplex;
  41. enum {
  42. ACCEL_GRID_SIZE = 16,
  43. QUANTIZATION_MAX = 1 << 16 // A power of two smaller than the 23 bit significand of a float.
  44. };
  45. struct GridPos {
  46. Vector3i pos;
  47. List<Simplex *>::Element *E = nullptr;
  48. };
  49. struct Simplex {
  50. uint32_t points[4];
  51. R128 circum_center_x;
  52. R128 circum_center_y;
  53. R128 circum_center_z;
  54. R128 circum_r2;
  55. LocalVector<GridPos> grid_positions;
  56. List<Simplex *>::Element *SE = nullptr;
  57. _FORCE_INLINE_ Simplex() {}
  58. _FORCE_INLINE_ Simplex(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d) {
  59. points[0] = p_a;
  60. points[1] = p_b;
  61. points[2] = p_c;
  62. points[3] = p_d;
  63. }
  64. };
  65. struct Triangle {
  66. uint32_t triangle[3];
  67. bool bad = false;
  68. _FORCE_INLINE_ bool operator==(const Triangle &p_triangle) const {
  69. return triangle[0] == p_triangle.triangle[0] && triangle[1] == p_triangle.triangle[1] && triangle[2] == p_triangle.triangle[2];
  70. }
  71. _FORCE_INLINE_ Triangle() {}
  72. _FORCE_INLINE_ Triangle(uint32_t p_a, uint32_t p_b, uint32_t p_c) {
  73. if (p_a > p_b) {
  74. SWAP(p_a, p_b);
  75. }
  76. if (p_b > p_c) {
  77. SWAP(p_b, p_c);
  78. }
  79. if (p_a > p_b) {
  80. SWAP(p_a, p_b);
  81. }
  82. triangle[0] = p_a;
  83. triangle[1] = p_b;
  84. triangle[2] = p_c;
  85. }
  86. };
  87. struct TriangleHasher {
  88. _FORCE_INLINE_ static uint32_t hash(const Triangle &p_triangle) {
  89. uint32_t h = hash_djb2_one_32(p_triangle.triangle[0]);
  90. h = hash_djb2_one_32(p_triangle.triangle[1], h);
  91. return hash_fmix32(hash_djb2_one_32(p_triangle.triangle[2], h));
  92. }
  93. };
  94. _FORCE_INLINE_ static void circum_sphere_compute(const Vector3 *p_points, Simplex *p_simplex) {
  95. // The only part in the algorithm where there may be precision errors is this one,
  96. // so ensure that we do it with the maximum precision possible.
  97. R128 v0_x = p_points[p_simplex->points[0]].x;
  98. R128 v0_y = p_points[p_simplex->points[0]].y;
  99. R128 v0_z = p_points[p_simplex->points[0]].z;
  100. R128 v1_x = p_points[p_simplex->points[1]].x;
  101. R128 v1_y = p_points[p_simplex->points[1]].y;
  102. R128 v1_z = p_points[p_simplex->points[1]].z;
  103. R128 v2_x = p_points[p_simplex->points[2]].x;
  104. R128 v2_y = p_points[p_simplex->points[2]].y;
  105. R128 v2_z = p_points[p_simplex->points[2]].z;
  106. R128 v3_x = p_points[p_simplex->points[3]].x;
  107. R128 v3_y = p_points[p_simplex->points[3]].y;
  108. R128 v3_z = p_points[p_simplex->points[3]].z;
  109. // Create the rows of our "unrolled" 3x3 matrix.
  110. R128 row1_x = v1_x - v0_x;
  111. R128 row1_y = v1_y - v0_y;
  112. R128 row1_z = v1_z - v0_z;
  113. R128 row2_x = v2_x - v0_x;
  114. R128 row2_y = v2_y - v0_y;
  115. R128 row2_z = v2_z - v0_z;
  116. R128 row3_x = v3_x - v0_x;
  117. R128 row3_y = v3_y - v0_y;
  118. R128 row3_z = v3_z - v0_z;
  119. R128 sq_length1 = row1_x * row1_x + row1_y * row1_y + row1_z * row1_z;
  120. R128 sq_length2 = row2_x * row2_x + row2_y * row2_y + row2_z * row2_z;
  121. R128 sq_length3 = row3_x * row3_x + row3_y * row3_y + row3_z * row3_z;
  122. // Compute the determinant of said matrix.
  123. R128 determinant = row1_x * (row2_y * row3_z - row3_y * row2_z) - row2_x * (row1_y * row3_z - row3_y * row1_z) + row3_x * (row1_y * row2_z - row2_y * row1_z);
  124. // Compute the volume of the tetrahedron, and precompute a scalar quantity for reuse in the formula.
  125. R128 volume = determinant / R128(6.f);
  126. R128 i12volume = R128(1.f) / (volume * R128(12.f));
  127. R128 center_x = v0_x + i12volume * ((row2_y * row3_z - row3_y * row2_z) * sq_length1 - (row1_y * row3_z - row3_y * row1_z) * sq_length2 + (row1_y * row2_z - row2_y * row1_z) * sq_length3);
  128. R128 center_y = v0_y + i12volume * (-(row2_x * row3_z - row3_x * row2_z) * sq_length1 + (row1_x * row3_z - row3_x * row1_z) * sq_length2 - (row1_x * row2_z - row2_x * row1_z) * sq_length3);
  129. R128 center_z = v0_z + i12volume * ((row2_x * row3_y - row3_x * row2_y) * sq_length1 - (row1_x * row3_y - row3_x * row1_y) * sq_length2 + (row1_x * row2_y - row2_x * row1_y) * sq_length3);
  130. // Once we know the center, the radius is clearly the distance to any vertex.
  131. R128 rel1_x = center_x - v0_x;
  132. R128 rel1_y = center_y - v0_y;
  133. R128 rel1_z = center_z - v0_z;
  134. R128 radius1 = rel1_x * rel1_x + rel1_y * rel1_y + rel1_z * rel1_z;
  135. p_simplex->circum_center_x = center_x;
  136. p_simplex->circum_center_y = center_y;
  137. p_simplex->circum_center_z = center_z;
  138. p_simplex->circum_r2 = radius1;
  139. }
  140. _FORCE_INLINE_ static bool simplex_contains(const Vector3 *p_points, const Simplex &p_simplex, uint32_t p_vertex) {
  141. R128 v_x = p_points[p_vertex].x;
  142. R128 v_y = p_points[p_vertex].y;
  143. R128 v_z = p_points[p_vertex].z;
  144. R128 rel2_x = p_simplex.circum_center_x - v_x;
  145. R128 rel2_y = p_simplex.circum_center_y - v_y;
  146. R128 rel2_z = p_simplex.circum_center_z - v_z;
  147. R128 radius2 = rel2_x * rel2_x + rel2_y * rel2_y + rel2_z * rel2_z;
  148. return radius2 < (p_simplex.circum_r2 - R128(0.0000000001));
  149. // When this tolerance is too big, it can result in overlapping simplices.
  150. // When it's too small, large amounts of planar simplices are created.
  151. }
  152. static bool simplex_is_coplanar(const Vector3 *p_points, const Simplex &p_simplex) {
  153. // Checking every possible distance like this is overkill, but only checking
  154. // one is not enough. If the simplex is almost planar then the vectors p1-p2
  155. // and p1-p3 can be practically collinear, which makes Plane unreliable.
  156. for (uint32_t i = 0; i < 4; i++) {
  157. Plane p(p_points[p_simplex.points[i]], p_points[p_simplex.points[(i + 1) % 4]], p_points[p_simplex.points[(i + 2) % 4]]);
  158. // This tolerance should not be smaller than the one used with
  159. // Plane::has_point() when creating the LightmapGI probe BSP tree.
  160. if (Math::abs(p.distance_to(p_points[p_simplex.points[(i + 3) % 4]])) < 0.001) {
  161. return true;
  162. }
  163. }
  164. return false;
  165. }
  166. public:
  167. struct OutputSimplex {
  168. uint32_t points[4];
  169. };
  170. static Vector<OutputSimplex> tetrahedralize(const Vector<Vector3> &p_points) {
  171. uint32_t point_count = p_points.size();
  172. Vector3 *points = (Vector3 *)memalloc(sizeof(Vector3) * (point_count + 4));
  173. const Vector3 *src_points = p_points.ptr();
  174. Vector3 proportions;
  175. {
  176. AABB rect;
  177. for (uint32_t i = 0; i < point_count; i++) {
  178. Vector3 point = src_points[i];
  179. if (i == 0) {
  180. rect.position = point;
  181. } else {
  182. rect.expand_to(point);
  183. }
  184. }
  185. real_t longest_axis = rect.size[rect.get_longest_axis_index()];
  186. proportions = Vector3(longest_axis, longest_axis, longest_axis) / rect.size;
  187. for (uint32_t i = 0; i < point_count; i++) {
  188. // Scale points to the unit cube to better utilize R128 precision
  189. // and quantize to stabilize triangulation over a wide range of
  190. // distances.
  191. points[i] = Vector3(Vector3i((src_points[i] - rect.position) / longest_axis * QUANTIZATION_MAX)) / QUANTIZATION_MAX;
  192. }
  193. const real_t delta_max = Math::sqrt(2.0) * 100.0;
  194. Vector3 center = Vector3(0.5, 0.5, 0.5);
  195. // The larger the root simplex is, the more likely it is that the
  196. // triangulation is convex. If it's not absolutely huge, there can
  197. // be missing simplices that are not created for the outermost faces
  198. // of the point cloud if the point density is very low there.
  199. points[point_count + 0] = center + Vector3(0, 1, 0) * delta_max;
  200. points[point_count + 1] = center + Vector3(0, -1, 1) * delta_max;
  201. points[point_count + 2] = center + Vector3(1, -1, -1) * delta_max;
  202. points[point_count + 3] = center + Vector3(-1, -1, -1) * delta_max;
  203. }
  204. List<Simplex *> acceleration_grid[ACCEL_GRID_SIZE][ACCEL_GRID_SIZE][ACCEL_GRID_SIZE];
  205. List<Simplex *> simplex_list;
  206. {
  207. //create root simplex
  208. Simplex *root = memnew(Simplex(point_count + 0, point_count + 1, point_count + 2, point_count + 3));
  209. root->SE = simplex_list.push_back(root);
  210. for (uint32_t i = 0; i < ACCEL_GRID_SIZE; i++) {
  211. for (uint32_t j = 0; j < ACCEL_GRID_SIZE; j++) {
  212. for (uint32_t k = 0; k < ACCEL_GRID_SIZE; k++) {
  213. GridPos gp;
  214. gp.E = acceleration_grid[i][j][k].push_back(root);
  215. gp.pos = Vector3i(i, j, k);
  216. root->grid_positions.push_back(gp);
  217. }
  218. }
  219. }
  220. circum_sphere_compute(points, root);
  221. }
  222. OAHashMap<Triangle, uint32_t, TriangleHasher> triangles_inserted;
  223. LocalVector<Triangle> triangles;
  224. for (uint32_t i = 0; i < point_count; i++) {
  225. bool unique = true;
  226. for (uint32_t j = i + 1; j < point_count; j++) {
  227. if (points[i] == points[j]) {
  228. unique = false;
  229. break;
  230. }
  231. }
  232. if (!unique) {
  233. continue;
  234. }
  235. Vector3i grid_pos = Vector3i(points[i] * proportions * ACCEL_GRID_SIZE);
  236. grid_pos = grid_pos.clampi(0, ACCEL_GRID_SIZE - 1);
  237. for (List<Simplex *>::Element *E = acceleration_grid[grid_pos.x][grid_pos.y][grid_pos.z].front(); E;) {
  238. List<Simplex *>::Element *N = E->next(); //may be deleted
  239. Simplex *simplex = E->get();
  240. if (simplex_contains(points, *simplex, i)) {
  241. static const uint32_t triangle_order[4][3] = {
  242. { 0, 1, 2 },
  243. { 0, 1, 3 },
  244. { 0, 2, 3 },
  245. { 1, 2, 3 },
  246. };
  247. for (uint32_t k = 0; k < 4; k++) {
  248. Triangle t = Triangle(simplex->points[triangle_order[k][0]], simplex->points[triangle_order[k][1]], simplex->points[triangle_order[k][2]]);
  249. uint32_t *p = triangles_inserted.lookup_ptr(t);
  250. if (p) {
  251. // This Delaunay implementation uses the Bowyer-Watson algorithm.
  252. // The rule is that you don't reuse any triangles that were
  253. // shared by any of the retriangulated simplices.
  254. triangles[*p].bad = true;
  255. } else {
  256. triangles_inserted.insert(t, triangles.size());
  257. triangles.push_back(t);
  258. }
  259. }
  260. simplex_list.erase(simplex->SE);
  261. for (const GridPos &gp : simplex->grid_positions) {
  262. Vector3i p = gp.pos;
  263. acceleration_grid[p.x][p.y][p.z].erase(gp.E);
  264. }
  265. memdelete(simplex);
  266. }
  267. E = N;
  268. }
  269. for (const Triangle &triangle : triangles) {
  270. if (triangle.bad) {
  271. continue;
  272. }
  273. Simplex *new_simplex = memnew(Simplex(triangle.triangle[0], triangle.triangle[1], triangle.triangle[2], i));
  274. circum_sphere_compute(points, new_simplex);
  275. new_simplex->SE = simplex_list.push_back(new_simplex);
  276. {
  277. Vector3 center;
  278. center.x = double(new_simplex->circum_center_x);
  279. center.y = double(new_simplex->circum_center_y);
  280. center.z = double(new_simplex->circum_center_z);
  281. const real_t radius2 = Math::sqrt(double(new_simplex->circum_r2)) + 0.0001;
  282. Vector3 extents = Vector3(radius2, radius2, radius2);
  283. Vector3i from = Vector3i((center - extents) * proportions * ACCEL_GRID_SIZE);
  284. Vector3i to = Vector3i((center + extents) * proportions * ACCEL_GRID_SIZE);
  285. from = from.clampi(0, ACCEL_GRID_SIZE - 1);
  286. to = to.clampi(0, ACCEL_GRID_SIZE - 1);
  287. for (int32_t x = from.x; x <= to.x; x++) {
  288. for (int32_t y = from.y; y <= to.y; y++) {
  289. for (int32_t z = from.z; z <= to.z; z++) {
  290. GridPos gp;
  291. gp.pos = Vector3(x, y, z);
  292. gp.E = acceleration_grid[x][y][z].push_back(new_simplex);
  293. new_simplex->grid_positions.push_back(gp);
  294. }
  295. }
  296. }
  297. }
  298. }
  299. triangles.clear();
  300. triangles_inserted.clear();
  301. }
  302. //print_line("end with simplices: " + itos(simplex_list.size()));
  303. Vector<OutputSimplex> ret_simplices;
  304. ret_simplices.resize(simplex_list.size());
  305. OutputSimplex *ret_simplicesw = ret_simplices.ptrw();
  306. uint32_t simplices_written = 0;
  307. for (Simplex *simplex : simplex_list) {
  308. bool invalid = false;
  309. for (int j = 0; j < 4; j++) {
  310. if (simplex->points[j] >= point_count) {
  311. invalid = true;
  312. break;
  313. }
  314. }
  315. if (invalid || simplex_is_coplanar(src_points, *simplex)) {
  316. memdelete(simplex);
  317. continue;
  318. }
  319. ret_simplicesw[simplices_written].points[0] = simplex->points[0];
  320. ret_simplicesw[simplices_written].points[1] = simplex->points[1];
  321. ret_simplicesw[simplices_written].points[2] = simplex->points[2];
  322. ret_simplicesw[simplices_written].points[3] = simplex->points[3];
  323. simplices_written++;
  324. memdelete(simplex);
  325. }
  326. ret_simplices.resize(simplices_written);
  327. memfree(points);
  328. return ret_simplices;
  329. }
  330. };