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