geometry_2d.cpp 10 KB

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