geometry_2d.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /**************************************************************************/
  2. /* geometry_2d.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 "geometry_2d.h"
  31. #include "thirdparty/clipper2/include/clipper2/clipper.h"
  32. #include "thirdparty/misc/polypartition.h"
  33. #define STB_RECT_PACK_IMPLEMENTATION
  34. #include "thirdparty/misc/stb_rect_pack.h"
  35. const int clipper_precision = 5; // Based on CMP_EPSILON.
  36. const double clipper_scale = Math::pow(10.0, clipper_precision);
  37. void Geometry2D::merge_many_polygons(const Vector<Vector<Vector2>> &p_polygons, Vector<Vector<Vector2>> &r_out_polygons, Vector<Vector<Vector2>> &r_out_holes) {
  38. using namespace Clipper2Lib;
  39. PathsD subjects;
  40. for (const Vector<Vector2> &polygon : p_polygons) {
  41. PathD path(polygon.size());
  42. for (int i = 0; i < polygon.size(); i++) {
  43. const Vector2 &point = polygon[i];
  44. path[i] = PointD(point.x, point.y);
  45. }
  46. subjects.push_back(path);
  47. }
  48. PathsD solution = Union(subjects, FillRule::NonZero);
  49. solution = SimplifyPaths(solution, 0.01);
  50. r_out_polygons.clear();
  51. r_out_holes.clear();
  52. for (PathsD::size_type i = 0; i < solution.size(); ++i) {
  53. PathD &path = solution[i];
  54. Vector<Point2> output_polygon;
  55. output_polygon.resize(path.size());
  56. for (PathsD::size_type j = 0; j < path.size(); ++j) {
  57. output_polygon.set(j, Vector2(static_cast<real_t>(path[j].x), static_cast<real_t>(path[j].y)));
  58. }
  59. if (IsPositive(path)) {
  60. r_out_polygons.push_back(output_polygon);
  61. } else {
  62. r_out_holes.push_back(output_polygon);
  63. }
  64. }
  65. }
  66. Vector<Vector<Vector2>> Geometry2D::decompose_many_polygons_in_convex(const Vector<Vector<Point2>> &p_polygons, const Vector<Vector<Point2>> &p_holes) {
  67. Vector<Vector<Vector2>> decomp;
  68. List<TPPLPoly> in_poly, out_poly;
  69. for (const Vector<Vector2> &polygon : p_polygons) {
  70. TPPLPoly inp;
  71. inp.Init(polygon.size());
  72. for (int i = 0; i < polygon.size(); i++) {
  73. inp.GetPoint(i) = polygon[i];
  74. }
  75. inp.SetOrientation(TPPL_ORIENTATION_CCW);
  76. in_poly.push_back(inp);
  77. }
  78. for (const Vector<Vector2> &polygon : p_holes) {
  79. TPPLPoly inp;
  80. inp.Init(polygon.size());
  81. for (int i = 0; i < polygon.size(); i++) {
  82. inp.GetPoint(i) = polygon[i];
  83. }
  84. inp.SetOrientation(TPPL_ORIENTATION_CW);
  85. inp.SetHole(true);
  86. in_poly.push_back(inp);
  87. }
  88. TPPLPartition tpart;
  89. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  90. ERR_PRINT("Convex decomposing failed!");
  91. return decomp;
  92. }
  93. decomp.resize(out_poly.size());
  94. int idx = 0;
  95. for (TPPLPoly &tp : out_poly) {
  96. decomp.write[idx].resize(tp.GetNumPoints());
  97. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  98. decomp.write[idx].write[i] = tp.GetPoint(i);
  99. }
  100. idx++;
  101. }
  102. return decomp;
  103. }
  104. Vector<Vector<Vector2>> Geometry2D::decompose_polygon_in_convex(const Vector<Point2> &p_polygon) {
  105. return Geometry2D::decompose_many_polygons_in_convex({ p_polygon }, {});
  106. }
  107. struct _AtlasWorkRect {
  108. Size2i s;
  109. Point2i p;
  110. int idx = 0;
  111. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; }
  112. };
  113. struct _AtlasWorkRectResult {
  114. Vector<_AtlasWorkRect> result;
  115. int max_w = 0;
  116. int max_h = 0;
  117. };
  118. void Geometry2D::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  119. // Super simple, almost brute force scanline stacking fitter.
  120. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  121. // resulting atlas is somehow square. This is necessary because video cards have limits
  122. // on texture size (usually 2048 or 4096), so the squarer a texture, the more the chances
  123. // that it will work in every hardware.
  124. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  125. // 256x8192 atlas (won't work anywhere).
  126. ERR_FAIL_COND(p_rects.is_empty());
  127. for (int i = 0; i < p_rects.size(); i++) {
  128. ERR_FAIL_COND(p_rects[i].width <= 0);
  129. ERR_FAIL_COND(p_rects[i].height <= 0);
  130. }
  131. Vector<_AtlasWorkRect> wrects;
  132. wrects.resize(p_rects.size());
  133. for (int i = 0; i < p_rects.size(); i++) {
  134. wrects.write[i].s = p_rects[i];
  135. wrects.write[i].idx = i;
  136. }
  137. wrects.sort();
  138. int widest = wrects[0].s.width;
  139. Vector<_AtlasWorkRectResult> results;
  140. for (int i = 0; i <= 12; i++) {
  141. int w = 1 << i;
  142. int max_h = 0;
  143. int max_w = 0;
  144. if (w < widest) {
  145. continue;
  146. }
  147. Vector<int> hmax;
  148. hmax.resize(w);
  149. for (int j = 0; j < w; j++) {
  150. hmax.write[j] = 0;
  151. }
  152. // Place them.
  153. int ofs = 0;
  154. int limit_h = 0;
  155. for (int j = 0; j < wrects.size(); j++) {
  156. if (ofs + wrects[j].s.width > w) {
  157. ofs = 0;
  158. }
  159. int from_y = 0;
  160. for (int k = 0; k < wrects[j].s.width; k++) {
  161. if (hmax[ofs + k] > from_y) {
  162. from_y = hmax[ofs + k];
  163. }
  164. }
  165. wrects.write[j].p.x = ofs;
  166. wrects.write[j].p.y = from_y;
  167. int end_h = from_y + wrects[j].s.height;
  168. int end_w = ofs + wrects[j].s.width;
  169. if (ofs == 0) {
  170. limit_h = end_h;
  171. }
  172. for (int k = 0; k < wrects[j].s.width; k++) {
  173. hmax.write[ofs + k] = end_h;
  174. }
  175. if (end_h > max_h) {
  176. max_h = end_h;
  177. }
  178. if (end_w > max_w) {
  179. max_w = end_w;
  180. }
  181. if (ofs == 0 || end_h > limit_h) { // While h limit not reached, keep stacking.
  182. ofs += wrects[j].s.width;
  183. }
  184. }
  185. _AtlasWorkRectResult result;
  186. result.result = wrects;
  187. result.max_h = max_h;
  188. result.max_w = max_w;
  189. results.push_back(result);
  190. }
  191. // Find the result with the best aspect ratio.
  192. int best = -1;
  193. real_t best_aspect = 1e20;
  194. for (int i = 0; i < results.size(); i++) {
  195. real_t h = next_power_of_2(results[i].max_h);
  196. real_t w = next_power_of_2(results[i].max_w);
  197. real_t aspect = h > w ? h / w : w / h;
  198. if (aspect < best_aspect) {
  199. best = i;
  200. best_aspect = aspect;
  201. }
  202. }
  203. r_result.resize(p_rects.size());
  204. for (int i = 0; i < p_rects.size(); i++) {
  205. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  206. }
  207. r_size = Size2(results[best].max_w, results[best].max_h);
  208. }
  209. Vector<Vector<Point2>> Geometry2D::_polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open) {
  210. using namespace Clipper2Lib;
  211. ClipType op = ClipType::Union;
  212. switch (p_op) {
  213. case OPERATION_UNION:
  214. op = ClipType::Union;
  215. break;
  216. case OPERATION_DIFFERENCE:
  217. op = ClipType::Difference;
  218. break;
  219. case OPERATION_INTERSECTION:
  220. op = ClipType::Intersection;
  221. break;
  222. case OPERATION_XOR:
  223. op = ClipType::Xor;
  224. break;
  225. }
  226. PathD path_a(p_polypath_a.size());
  227. for (int i = 0; i != p_polypath_a.size(); ++i) {
  228. path_a[i] = PointD(p_polypath_a[i].x, p_polypath_a[i].y);
  229. }
  230. PathD path_b(p_polypath_b.size());
  231. for (int i = 0; i != p_polypath_b.size(); ++i) {
  232. path_b[i] = PointD(p_polypath_b[i].x, p_polypath_b[i].y);
  233. }
  234. ClipperD clp(clipper_precision); // Scale points up internally to attain the desired precision.
  235. clp.PreserveCollinear(false); // Remove redundant vertices.
  236. if (is_a_open) {
  237. clp.AddOpenSubject({ path_a });
  238. } else {
  239. clp.AddSubject({ path_a });
  240. }
  241. clp.AddClip({ path_b });
  242. PathsD paths;
  243. if (is_a_open) {
  244. PolyTreeD tree; // Needed to populate polylines.
  245. clp.Execute(op, FillRule::EvenOdd, tree, paths);
  246. } else {
  247. clp.Execute(op, FillRule::EvenOdd, paths); // Works on closed polygons only.
  248. }
  249. Vector<Vector<Point2>> polypaths;
  250. for (PathsD::size_type i = 0; i < paths.size(); ++i) {
  251. const PathD &path = paths[i];
  252. Vector<Vector2> polypath;
  253. for (PathsD::size_type j = 0; j < path.size(); ++j) {
  254. polypath.push_back(Point2(static_cast<real_t>(path[j].x), static_cast<real_t>(path[j].y)));
  255. }
  256. polypaths.push_back(polypath);
  257. }
  258. return polypaths;
  259. }
  260. Vector<Vector<Point2>> Geometry2D::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  261. using namespace Clipper2Lib;
  262. JoinType jt = JoinType::Square;
  263. switch (p_join_type) {
  264. case JOIN_SQUARE:
  265. jt = JoinType::Square;
  266. break;
  267. case JOIN_ROUND:
  268. jt = JoinType::Round;
  269. break;
  270. case JOIN_MITER:
  271. jt = JoinType::Miter;
  272. break;
  273. }
  274. EndType et = EndType::Polygon;
  275. switch (p_end_type) {
  276. case END_POLYGON:
  277. et = EndType::Polygon;
  278. break;
  279. case END_JOINED:
  280. et = EndType::Joined;
  281. break;
  282. case END_BUTT:
  283. et = EndType::Butt;
  284. break;
  285. case END_SQUARE:
  286. et = EndType::Square;
  287. break;
  288. case END_ROUND:
  289. et = EndType::Round;
  290. break;
  291. }
  292. PathD polypath(p_polypath.size());
  293. for (int i = 0; i != p_polypath.size(); ++i) {
  294. polypath[i] = PointD(p_polypath[i].x, p_polypath[i].y);
  295. }
  296. // Inflate/deflate.
  297. PathsD paths = InflatePaths({ polypath }, p_delta, jt, et, 2.0, clipper_precision, 0.25 * clipper_scale);
  298. // Here the points are scaled up internally and
  299. // the arc_tolerance is scaled accordingly
  300. // to attain the desired precision.
  301. Vector<Vector<Point2>> polypaths;
  302. for (PathsD::size_type i = 0; i < paths.size(); ++i) {
  303. const PathD &path = paths[i];
  304. Vector<Vector2> polypath2;
  305. for (PathsD::size_type j = 0; j < path.size(); ++j) {
  306. polypath2.push_back(Point2(static_cast<real_t>(path[j].x), static_cast<real_t>(path[j].y)));
  307. }
  308. polypaths.push_back(polypath2);
  309. }
  310. return polypaths;
  311. }
  312. Vector<Vector3i> Geometry2D::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  313. Vector<stbrp_node> nodes;
  314. nodes.resize(p_atlas_size.width);
  315. memset(nodes.ptrw(), 0, sizeof(stbrp_node) * nodes.size());
  316. stbrp_context context;
  317. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  318. Vector<stbrp_rect> rects;
  319. rects.resize(p_sizes.size());
  320. for (int i = 0; i < p_sizes.size(); i++) {
  321. rects.write[i].id = i;
  322. rects.write[i].w = p_sizes[i].width;
  323. rects.write[i].h = p_sizes[i].height;
  324. rects.write[i].x = 0;
  325. rects.write[i].y = 0;
  326. rects.write[i].was_packed = 0;
  327. }
  328. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  329. Vector<Vector3i> ret;
  330. ret.resize(p_sizes.size());
  331. for (int i = 0; i < p_sizes.size(); i++) {
  332. ret.write[rects[i].id] = Vector3i(rects[i].x, rects[i].y, rects[i].was_packed != 0 ? 1 : 0);
  333. }
  334. return ret;
  335. }