geometry_2d.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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/misc/clipper.hpp"
  32. #include "thirdparty/misc/polypartition.h"
  33. #define STB_RECT_PACK_IMPLEMENTATION
  34. #include "thirdparty/misc/stb_rect_pack.h"
  35. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  36. Vector<Vector<Vector2>> Geometry2D::decompose_polygon_in_convex(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.size() == 0);
  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 ClipperLib;
  167. ClipType op = ctUnion;
  168. switch (p_op) {
  169. case OPERATION_UNION:
  170. op = ctUnion;
  171. break;
  172. case OPERATION_DIFFERENCE:
  173. op = ctDifference;
  174. break;
  175. case OPERATION_INTERSECTION:
  176. op = ctIntersection;
  177. break;
  178. case OPERATION_XOR:
  179. op = ctXor;
  180. break;
  181. }
  182. Path path_a, path_b;
  183. // Need to scale points (Clipper's requirement for robust computation).
  184. for (int i = 0; i != p_polypath_a.size(); ++i) {
  185. path_a << IntPoint(p_polypath_a[i].x * (real_t)SCALE_FACTOR, p_polypath_a[i].y * (real_t)SCALE_FACTOR);
  186. }
  187. for (int i = 0; i != p_polypath_b.size(); ++i) {
  188. path_b << IntPoint(p_polypath_b[i].x * (real_t)SCALE_FACTOR, p_polypath_b[i].y * (real_t)SCALE_FACTOR);
  189. }
  190. Clipper clp;
  191. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  192. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  193. Paths paths;
  194. if (is_a_open) {
  195. PolyTree tree; // Needed to populate polylines.
  196. clp.Execute(op, tree);
  197. OpenPathsFromPolyTree(tree, paths);
  198. } else {
  199. clp.Execute(op, paths); // Works on closed polygons only.
  200. }
  201. // Have to scale points down now.
  202. Vector<Vector<Point2>> polypaths;
  203. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  204. Vector<Vector2> polypath;
  205. const Path &scaled_path = paths[i];
  206. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  207. polypath.push_back(Point2(
  208. static_cast<real_t>(scaled_path[j].X) / (real_t)SCALE_FACTOR,
  209. static_cast<real_t>(scaled_path[j].Y) / (real_t)SCALE_FACTOR));
  210. }
  211. polypaths.push_back(polypath);
  212. }
  213. return polypaths;
  214. }
  215. Vector<Vector<Point2>> Geometry2D::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  216. using namespace ClipperLib;
  217. JoinType jt = jtSquare;
  218. switch (p_join_type) {
  219. case JOIN_SQUARE:
  220. jt = jtSquare;
  221. break;
  222. case JOIN_ROUND:
  223. jt = jtRound;
  224. break;
  225. case JOIN_MITER:
  226. jt = jtMiter;
  227. break;
  228. }
  229. EndType et = etClosedPolygon;
  230. switch (p_end_type) {
  231. case END_POLYGON:
  232. et = etClosedPolygon;
  233. break;
  234. case END_JOINED:
  235. et = etClosedLine;
  236. break;
  237. case END_BUTT:
  238. et = etOpenButt;
  239. break;
  240. case END_SQUARE:
  241. et = etOpenSquare;
  242. break;
  243. case END_ROUND:
  244. et = etOpenRound;
  245. break;
  246. }
  247. ClipperOffset co(2.0, 0.25f * (real_t)SCALE_FACTOR); // Defaults from ClipperOffset.
  248. Path path;
  249. // Need to scale points (Clipper's requirement for robust computation).
  250. for (int i = 0; i != p_polypath.size(); ++i) {
  251. path << IntPoint(p_polypath[i].x * (real_t)SCALE_FACTOR, p_polypath[i].y * (real_t)SCALE_FACTOR);
  252. }
  253. co.AddPath(path, jt, et);
  254. Paths paths;
  255. co.Execute(paths, p_delta * (real_t)SCALE_FACTOR); // Inflate/deflate.
  256. // Have to scale points down now.
  257. Vector<Vector<Point2>> polypaths;
  258. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  259. Vector<Vector2> polypath;
  260. const Path &scaled_path = paths[i];
  261. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  262. polypath.push_back(Point2(
  263. static_cast<real_t>(scaled_path[j].X) / (real_t)SCALE_FACTOR,
  264. static_cast<real_t>(scaled_path[j].Y) / (real_t)SCALE_FACTOR));
  265. }
  266. polypaths.push_back(polypath);
  267. }
  268. return polypaths;
  269. }
  270. Vector<Vector3i> Geometry2D::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  271. Vector<stbrp_node> nodes;
  272. nodes.resize(p_atlas_size.width);
  273. memset(nodes.ptrw(), 0, sizeof(stbrp_node) * nodes.size());
  274. stbrp_context context;
  275. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  276. Vector<stbrp_rect> rects;
  277. rects.resize(p_sizes.size());
  278. for (int i = 0; i < p_sizes.size(); i++) {
  279. rects.write[i].id = i;
  280. rects.write[i].w = p_sizes[i].width;
  281. rects.write[i].h = p_sizes[i].height;
  282. rects.write[i].x = 0;
  283. rects.write[i].y = 0;
  284. rects.write[i].was_packed = 0;
  285. }
  286. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  287. Vector<Vector3i> ret;
  288. ret.resize(p_sizes.size());
  289. for (int i = 0; i < p_sizes.size(); i++) {
  290. ret.write[rects[i].id] = Vector3i(rects[i].x, rects[i].y, rects[i].was_packed != 0 ? 1 : 0);
  291. }
  292. return ret;
  293. }