Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. //lines are represented in ax+by+c = 0 form in an array [a,b,c]. Coordinates in [x,y]
  2. var coords = [
  3. [1, 0],
  4. [1, 1],
  5. [0, 0.5],
  6. [-1, 1],
  7. [-1, 0]
  8. ];
  9. var point = [0, 0.6];
  10.  
  11. function polygon() {
  12. for (var i = 0, n = coords.length; n > 3; n = coords.length) {
  13. //if the i+1 point(point next to current anchor) is convex, then it is our new anchor point.
  14. var array = [coords[(i + n - 1) % n], coords[i % n], coords[(i + 1) % n], coords[(i + 2) % n], coords[(i + 3) % n]];
  15. if (isConvex(array)) {
  16. i++;
  17. }
  18. // checks if given point is inside the triangle formed by i(anchor), i+1 and i+2. If not, i+1th point is removed.
  19. var array = [coords[i % n], coords[(i + 1) % n], coords[(i + 2) % n]];
  20. if (inTri(array)) {
  21. return true;
  22. } else {
  23. coords.splice(i + 1, 1);
  24. }
  25. }
  26. return (inTri(coords) ? true : false);
  27. }
  28.  
  29. //checks if same side or on the line
  30. function sameSide(line, pointA, pointB) {
  31. if ((pointA[0] * line[0] + line[1] * pointA[1] + line[2]) * (pointB[0] * line[0] + line[1] * pointB[1] + line[2]) >= 0) {
  32. return true;
  33. } else {
  34. return false;
  35. }
  36. }
  37.  
  38. function inTri(vertices) {
  39. for (var i = 0; i < 3; i++) {
  40. if (!sameSide(findLine(vertices[i], vertices[(i + 1) % 3]), point, vertices[(i + 2) % 3])) {
  41. return false;
  42. }
  43. }
  44.  
  45. // this one handles zero area triangles
  46. var length1 = Math.sqrt(Math.pow((vertices[0][0] - vertices[1][0]), 2) + Math.pow((vertices[0][1] - vertices[1][1]), 2));
  47. var length2 = Math.sqrt(Math.pow((vertices[0][0] - vertices[2][0]), 2) + Math.pow((vertices[0][1] - vertices[2][1]), 2));
  48. var length3 = Math.sqrt(Math.pow((vertices[1][0] - vertices[2][0]), 2) + Math.pow((vertices[1][1] - vertices[2][1]), 2));
  49. if (length1 + length2 == length3 || Math.abs(length1 - length2) == length3) {
  50. return false;
  51. }
  52. return true;
  53. }
  54. // finds out whether the middle element of a five element array is convex
  55. function isConvex(vertices) {
  56. if (sameSide(findLine(vertices[2], vertices[3]), vertices[4], vertices[1])) {
  57. return false;
  58. }
  59. if (sameSide(findLine(vertices[2], vertices[1]), vertices[0], vertices[3])) {
  60. return false;
  61. }
  62. return true;
  63. }
  64.  
  65. function findLine(pointA, pointB) {
  66. var a = pointB[1] - pointA[1];
  67. var b = pointA[0] - pointB[0];
  68. var c = -a * pointA[0] - b * pointA[1];
  69. return [a, b, c];
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement