gitea源码

polygon.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. // Copied and modified from https://github.com/issue9/identicon/ (MIT License)
  4. package identicon
  5. var (
  6. // cos(0),cos(90),cos(180),cos(270)
  7. cos = []int{1, 0, -1, 0}
  8. // sin(0),sin(90),sin(180),sin(270)
  9. sin = []int{0, 1, 0, -1}
  10. )
  11. // rotate the points by center point (x,y)
  12. // angle: [0,1,2,3] means [0,90,180,270] degree
  13. func rotate(points []int, x, y, angle int) {
  14. // the angle is only used internally, and it has been guaranteed to be 0/1/2/3, so we do not check it again
  15. for i := 0; i < len(points); i += 2 {
  16. px, py := points[i]-x, points[i+1]-y
  17. points[i] = px*cos[angle] - py*sin[angle] + x
  18. points[i+1] = px*sin[angle] + py*cos[angle] + y
  19. }
  20. }
  21. // check whether the point is inside the polygon (defined by the points)
  22. // the first and the last point must be the same
  23. func pointInPolygon(x, y int, polygonPoints []int) bool {
  24. if len(polygonPoints) < 8 { // a valid polygon must have more than 2 points
  25. return false
  26. }
  27. // reference: nonzero winding rule, https://en.wikipedia.org/wiki/Nonzero-rule
  28. // split the plane into two by the check point horizontally:
  29. // y>0,includes (x>0 && y==0)
  30. // y<0,includes (x<0 && y==0)
  31. //
  32. // then scan every point in the polygon.
  33. //
  34. // if current point and previous point are in different planes (eg: curY>0 && prevY<0),
  35. // check the clock-direction from previous point to current point (use check point as origin).
  36. // if the direction is clockwise, then r++, otherwise then r--
  37. // finally, if 2==abs(r), then the check point is inside the polygon
  38. r := 0
  39. prevX, prevY := polygonPoints[0], polygonPoints[1]
  40. prev := (prevY > y) || ((prevX > x) && (prevY == y))
  41. for i := 2; i < len(polygonPoints); i += 2 {
  42. currX, currY := polygonPoints[i], polygonPoints[i+1]
  43. curr := (currY > y) || ((currX > x) && (currY == y))
  44. if curr == prev {
  45. prevX, prevY = currX, currY
  46. continue
  47. }
  48. if mul := (prevX-x)*(currY-y) - (currX-x)*(prevY-y); mul >= 0 {
  49. r++
  50. } else { // mul < 0
  51. r--
  52. }
  53. prevX, prevY = currX, currY
  54. prev = curr
  55. }
  56. return r == 2 || r == -2
  57. }