polygon_sorter.gd 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2018 George Marques
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. # Sorter for polygon vertices
  23. tool
  24. extends Reference
  25. var center
  26. # Sort the vertices of a convex polygon to clockwise order
  27. # Receives a PoolVector2Array and returns a new one
  28. func sort_polygon(vertices):
  29. vertices = Array(vertices)
  30. var centroid = Vector2()
  31. var size = vertices.size()
  32. for i in range(0, size):
  33. centroid += vertices[i]
  34. centroid /= size
  35. center = centroid
  36. vertices.sort_custom(self, "is_less")
  37. return PoolVector2Array(vertices)
  38. # Sorter function, determines which of the poins should come first
  39. func is_less(a, b):
  40. if a.x - center.x >= 0 and b.x - center.x < 0:
  41. return false
  42. elif a.x - center.x < 0 and b.x - center.x >= 0:
  43. return true
  44. elif a.x - center.x == 0 and b.x - center.x == 0:
  45. if a.y - center.y >= 0 or b.y - center.y >= 0:
  46. return a.y < b.y
  47. return a.y > b.y
  48. var det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y)
  49. if det > 0:
  50. return true
  51. elif det < 0:
  52. return false
  53. var d1 = (a - center).length_squared()
  54. var d2 = (b - center).length_squared()
  55. return d1 < d2