code.gitea.io/gitea@v1.19.3/modules/avatar/identicon/polygon.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  // Copied and modified from https://github.com/issue9/identicon/ (MIT License)
     5  
     6  package identicon
     7  
     8  var (
     9  	// cos(0),cos(90),cos(180),cos(270)
    10  	cos = []int{1, 0, -1, 0}
    11  
    12  	// sin(0),sin(90),sin(180),sin(270)
    13  	sin = []int{0, 1, 0, -1}
    14  )
    15  
    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
    24  	}
    25  }
    26  
    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
    31  		return false
    32  	}
    33  
    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)
    38  	//
    39  	// then scan every point in the polygon.
    40  	//
    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
    45  
    46  	r := 0
    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))
    52  
    53  		if curr == prev {
    54  			prevX, prevY = currX, currY
    55  			continue
    56  		}
    57  
    58  		if mul := (prevX-x)*(currY-y) - (currX-x)*(prevY-y); mul >= 0 {
    59  			r++
    60  		} else { // mul < 0
    61  			r--
    62  		}
    63  		prevX, prevY = currX, currY
    64  		prev = curr
    65  	}
    66  
    67  	return r == 2 || r == -2
    68  }