geometry_2d.cpp 10 KB

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