1 module libs.utils.geometry_calculators; 2 3 import std.math; 4 5 import libs.utils.point; 6 7 /// Calculates the area of given polygon 8 /// using the Shoelace formula. 9 double polygonArea(Point[] pts) 10 { 11 // Number of vertices of the polygon 12 const n = cast(int) pts.length; 13 14 // Initialize area 15 double area = 0; 16 int j; 17 18 for (int k = 0; k < n; k++) 19 { 20 j = (k + 1) % n; 21 area += pts[k].x * pts[j].y; 22 area -= pts[j].x * pts[k].y; 23 } 24 25 area = abs(area) / 2; 26 27 return area; 28 } 29 30 /// Calculates the total perimeter of a given polygon 31 double polygonPerimeter(Point[] pts) 32 { 33 // Initialize perimeter 34 double perimeter = 0; 35 36 // Number of vertices of the polygon 37 int n = cast(int) pts.length; 38 39 Point p1, p2; 40 41 for (int i = 0; i < (n - 1); i++) 42 { 43 p1 = pts[i]; 44 p2 = pts[i + 1]; 45 perimeter += distanceBetweenTwoPoints(p1, p2); 46 } 47 48 return perimeter; 49 } 50 51 /// Implementation of distance between 2 points. 52 double distanceBetweenTwoPoints(Point p1, Point p2) 53 { 54 float x1, y1, x2, y2; 55 x1 = p1.x; 56 y1 = p1.y; 57 x2 = p2.x; 58 y2 = p2.y; 59 return sqrt(pow((y2 - y1), 2) + pow((x2 - x1), 2)); 60 }