I have to draw an arc between two points at the edge of a circle. Assuming that the arc is drawn always in the shortest distance possible(edit2: sweep flag set to 0), I need to know if the arc is drawn clockwise or anticlockwise.
I got the following inputs:
start point (point1)
end point (point2)
center point
radius
Edit1: This question is related to arcs in svg. Hence its belongs to programming.
The answer is SVG supports both clockwise and anticlockwise arcs. You switch between them by changing the "sweep" flag in an arc (A) command.
If you want to learn how SVG arcs work, the place to look is the Paths arcs section of the SVG specification.
Having described data, you can find what arc is smaller - CCW or CW one.
Just check sign of cross product of vectors point1-center and point2-center to reveal shortest arc orientation:
cp = (p1.x-c.x)*(p2.y-c.y)-(p1.y-c.y)*(p2.x-c.x)
For cp>0 you have to set sweep parameter to 0, otherwise to 1 (perhaps vice versa), whilst large-arc-flag should be always 0.
After discussing with a mathematician, I found an answer to this and based on that I wrote the following code:
public static bool IsClockWise(Point point1, Point point2, Circle circle)
{
var dxPoint1 = point1.X - circle.CenterX;
var dyPoint1 = point1.Y - circle.CenterY;
var dxPoint2 = point2.X - circle.CenterX;
var dyPoint2 = point2.Y - circle.CenterY;
double thetaPoint1 = 0, thetaPoint2 = 0;
if (dxPoint1 > 0 && dyPoint1 >= 0)
thetaPoint1 = Math.Asin(dyPoint1 / circle.Radius);
else if (dxPoint1 <= 0 && dyPoint1 > 0)
thetaPoint1 = Math.PI - Math.Asin(dyPoint1 / circle.Radius);
else if (dxPoint1 < 0 && dyPoint1 <= 0)
thetaPoint1 = Math.Abs(Math.Asin(dyPoint1 / circle.Radius)) + Math.PI;
else if (dxPoint1 >= 0 && dyPoint1 < 0)
thetaPoint1 = 2 * Math.PI - Math.Abs(Math.Asin(dyPoint1 / circle.Radius));
if (dxPoint2 > 0 && dyPoint2 >= 0)
thetaPoint2 = Math.Asin(dyPoint2 / circle.Radius);
else if (dxPoint2 <= 0 && dyPoint2 > 0)
thetaPoint2 = Math.PI - Math.Asin(dyPoint2 / circle.Radius);
else if (dxPoint2 < 0 && dyPoint2 <= 0)
thetaPoint2 = Math.Abs(Math.Asin(dyPoint2 / circle.Radius)) + Math.PI;
else if (dxPoint2 >= 0 && dyPoint2 < 0)
thetaPoint2 = 2 * Math.PI - Math.Abs(Math.Asin(dyPoint2 / circle.Radius));
if (thetaPoint1 > thetaPoint2)
{
return !(thetaPoint1 - thetaPoint2 <= Math.PI);
}
return thetaPoint2 - thetaPoint1 <= Math.PI;
}
I am trying to extract the axis of rotation and the angle of rotation from a 3x3 rotation
matrix. I am currently using this method but am unsure if I am on track. I am running into issues elsewhere in my program and am thinking this may be a cause but have been unable to verify this myself.
I am working with the XNA framework, if that helps. I looked into using Matrix.Decompose() which returns the scale (vec3) translation(vec3) and rotation(quaternion) but I am not sure that I can extract the data data I need from these values.
public static void MatrixRotationAxisAngle(Matrix m, ref float theta, ref Vector3 rot_axis) {
float trace = m.M11 + m.M22 + m.M33;
float cos_theta = 0.5f * (trace - 1.0f);
if (cos_theta > 0.999999875f) {
//allow some epsilon value
theta = 0.0f;
rot_axis = new Vector3(1.0f, 0.0f, 0.0f);
} else if (cos_theta > -0.999999875f) {
theta = (float)Math.Acos(cos_theta);
rot_axis.X = (m.Up.Z - m.Forward.Y);
rot_axis.Y = (m.Forward.X - m.Right.Z);
rot_axis.Z = (m.Right.Y - m.Up.X);
rot_axis.Normalize();
} else { //angle within PI limits
theta = (float)Math.PI;
//find index of largest diag term in matrix
int index = 0;
if (m.M11 > m.M22 && m.M11 > m.M33) {
index = 0;
}
if (m.M22 > m.M11 && m.M22 > m.M33) {
index = 1;
}
if (m.M33 > m.M11 && m.M33 > m.M22) {
index = 2;
}
switch (index) {
case 0:
float ix = 1.0f / rot_axis.X;
rot_axis.X = (float)Math.Sqrt(m.M11 + 1.0f);
rot_axis.Y = m.M12 * ix;
rot_axis.X = m.M13 * ix;
break;
case 1:
float iy = 1.0f / rot_axis.Y;
rot_axis.Y = (float)Math.Sqrt(m.M22 + 1.0f);
rot_axis.X = m.M21 * iy;
rot_axis.Z = m.M23 * iy;
break;
case 2:
float iz = 1.0f / rot_axis.Y;
rot_axis.Z = (float)Math.Sqrt(m.M33 + 1.0f);
rot_axis.X = m.M31 * iz;
rot_axis.Y = m.M32 * iz;
break;
}
rot_axis.Normalize();
}
}
I suggest to take a look into the pseudocode from this mathematical explanation (pdf), Chapter 2.1 (depending on your matrix). I have successfully used the code in one of my projects, and it returned valid results in my case.
See the matrix in http://en.wikipedia.org/wiki/Rotation_matrix#General_rotations .
As you can see finding theta is pretty easy. Use that in other equations to find the other angles.
I'm trying to determine if a point is inside a polygon. the Polygon is defined by an array of Point objects. I can easily figure out if the point is inside the bounded box of the polygon, but I'm not sure how to tell if it's inside the actual polygon or not. If possible, I'd like to only use C# and WinForms. I'd rather not call on OpenGL or something to do this simple task.
Here's the code I have so far:
private void CalculateOuterBounds()
{
//m_aptVertices is a Point[] which holds the vertices of the polygon.
// and X/Y min/max are just ints
Xmin = Xmax = m_aptVertices[0].X;
Ymin = Ymax = m_aptVertices[0].Y;
foreach(Point pt in m_aptVertices)
{
if(Xmin > pt.X)
Xmin = pt.X;
if(Xmax < pt.X)
Xmax = pt.X;
if(Ymin > pt.Y)
Ymin = pt.Y;
if(Ymax < pt.Y)
Ymax = pt.Y;
}
}
public bool Contains(Point pt)
{
bool bContains = true; //obviously wrong at the moment :)
if(pt.X < Xmin || pt.X > Xmax || pt.Y < Ymin || pt.Y > Ymax)
bContains = false;
else
{
//figure out if the point is in the polygon
}
return bContains;
}
I've checked codes here and all have problems.
The best method is:
/// <summary>
/// Determines if the given point is inside the polygon
/// </summary>
/// <param name="polygon">the vertices of polygon</param>
/// <param name="testPoint">the given point</param>
/// <returns>true if the point is inside the polygon; otherwise, false</returns>
public static bool IsPointInPolygon4(PointF[] polygon, PointF testPoint)
{
bool result = false;
int j = polygon.Count() - 1;
for (int i = 0; i < polygon.Count(); i++)
{
if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y)
{
if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X)
{
result = !result;
}
}
j = i;
}
return result;
}
The accepted answer did not work for me in my project. I ended up using the code found here.
public static bool IsInPolygon(Point[] poly, Point p)
{
Point p1, p2;
bool inside = false;
if (poly.Length < 3)
{
return inside;
}
var oldPoint = new Point(
poly[poly.Length - 1].X, poly[poly.Length - 1].Y);
for (int i = 0; i < poly.Length; i++)
{
var newPoint = new Point(poly[i].X, poly[i].Y);
if (newPoint.X > oldPoint.X)
{
p1 = oldPoint;
p2 = newPoint;
}
else
{
p1 = newPoint;
p2 = oldPoint;
}
if ((newPoint.X < p.X) == (p.X <= oldPoint.X)
&& (p.Y - (long) p1.Y)*(p2.X - p1.X)
< (p2.Y - (long) p1.Y)*(p.X - p1.X))
{
inside = !inside;
}
oldPoint = newPoint;
}
return inside;
}
See this it's in c++ and can be done in c# in a same way.
for convex polygon is too easy:
If the polygon is convex then one can
consider the polygon as a "path" from
the first vertex. A point is on the
interior of this polygons if it is
always on the same side of all the
line segments making up the path.
Given a line segment between P0
(x0,y0) and P1 (x1,y1), another point
P (x,y) has the following relationship
to the line segment. Compute (y - y0)
(x1 - x0) - (x - x0) (y1 - y0)
if it is less than 0 then P is to the
right of the line segment, if greater
than 0 it is to the left, if equal to
0 then it lies on the line segment.
Here is its code in c#, I didn't check edge cases.
public static bool IsInPolygon(Point[] poly, Point point)
{
var coef = poly.Skip(1).Select((p, i) =>
(point.Y - poly[i].Y)*(p.X - poly[i].X)
- (point.X - poly[i].X) * (p.Y - poly[i].Y))
.ToList();
if (coef.Any(p => p == 0))
return true;
for (int i = 1; i < coef.Count(); i++)
{
if (coef[i] * coef[i - 1] < 0)
return false;
}
return true;
}
I test it with simple rectangle works fine:
Point[] pts = new Point[] { new Point { X = 1, Y = 1 },
new Point { X = 1, Y = 3 },
new Point { X = 3, Y = 3 },
new Point { X = 3, Y = 1 } };
IsInPolygon(pts, new Point { X = 2, Y = 2 }); ==> true
IsInPolygon(pts, new Point { X = 1, Y = 2 }); ==> true
IsInPolygon(pts, new Point { X = 0, Y = 2 }); ==> false
Explanation on the linq query:
poly.Skip(1) ==> creates a new list started from position 1 of the poly list and then by
(point.Y - poly[i].Y)*(p.X - poly[i].X) - (point.X - poly[i].X) * (p.Y - poly[i].Y) we'll going to calculate the direction (which mentioned in referenced paragraph).
similar example (with another operation):
lst = 2,4,8,12,7,19
lst.Skip(1) ==> 4,8,12,7,19
lst.Skip(1).Select((p,i)=>p-lst[i]) ==> 2,4,4,-5,12
meowNET anwser does not include Polygon vertices in the polygon and points exactly on horizontal edges. If you need an exact "inclusive" algorithm:
public static bool IsInPolygon(this Point point, IEnumerable<Point> polygon)
{
bool result = false;
var a = polygon.Last();
foreach (var b in polygon)
{
if ((b.X == point.X) && (b.Y == point.Y))
return true;
if ((b.Y == a.Y) && (point.Y == a.Y))
{
if ((a.X <= point.X) && (point.X <= b.X))
return true;
if ((b.X <= point.X) && (point.X <= a.X))
return true;
}
if ((b.Y < point.Y) && (a.Y >= point.Y) || (a.Y < point.Y) && (b.Y >= point.Y))
{
if (b.X + (point.Y - b.Y) / (a.Y - b.Y) * (a.X - b.X) <= point.X)
result = !result;
}
a = b;
}
return result;
}
You can use the ray casting algorithm. It is well-described in the wikipedia page for the Point in polygon problem.
It's as simple as counting the number of times a ray from outside to that point touches the polygon boundaries. If it touches an even number of times, the point is outside the polygon. If it touches an odd number of times, the point is inside.
To count the number of times the ray touches, you check intersections between the ray and all of the polygon sides.
My answer is taken from here:Link
I took the C code and converted it to C# and made it work
static bool pnpoly(PointD[] poly, PointD pnt )
{
int i, j;
int nvert = poly.Length;
bool c = false;
for (i = 0, j = nvert - 1; i < nvert; j = i++)
{
if (((poly[i].Y > pnt.Y) != (poly[j].Y > pnt.Y)) &&
(pnt.X < (poly[j].X - poly[i].X) * (pnt.Y - poly[i].Y) / (poly[j].Y - poly[i].Y) + poly[i].X))
c = !c;
}
return c;
}
You can test it with this example:
PointD[] pts = new PointD[] { new PointD { X = 1, Y = 1 },
new PointD { X = 1, Y = 2 },
new PointD { X = 2, Y = 2 },
new PointD { X = 2, Y = 3 },
new PointD { X = 3, Y = 3 },
new PointD { X = 3, Y = 1 }};
List<bool> lst = new List<bool>();
lst.Add(pnpoly(pts, new PointD { X = 2, Y = 2 }));
lst.Add(pnpoly(pts, new PointD { X = 2, Y = 1.9 }));
lst.Add(pnpoly(pts, new PointD { X = 2.5, Y = 2.5 }));
lst.Add(pnpoly(pts, new PointD { X = 1.5, Y = 2.5 }));
lst.Add(pnpoly(pts, new PointD { X = 5, Y = 5 }));
My business critical implementation of PointInPolygon function working on integers (as OP seems to be using) is unit tested for horizontal, vertical and diagonal lines, points on the line are included in the test (function returns true).
This seems to be an old question but all previous examples of tracing have some flaws: do not consider horizontal or vertical polygon lines, polygon boundary line or the order of edges (clockwise, counterclockwise).
The following function passes the tests I came up with (square, rhombus, diagonal cross, total 124 tests) with points on edges, vertices and just inside and outside edge and vertex.
The code does the following for every consecutive pair of polygon coordinates:
Checks if polygon vertex equals the point
Checks if the point is on a horizontal or vertical line
Calculates (as double) and collects intersects with conversion to integer
Sorts intersects so the order of edges is not affecting the algorithm
Checks if the point is on the even intersect (equals - in polygon)
Checks if the number of intersects before point x coordinate is odd - in polygon
Algorithm can be easily adapted for floats and doubles if necessary.
As a side note - I wonder how much software was created in the past nearly 10 years which check for a point in polygon and fail in some cases.
public static bool IsPointInPolygon(Point point, IList<Point> polygon)
{
var intersects = new List<int>();
var a = polygon.Last();
foreach (var b in polygon)
{
if (b.X == point.X && b.Y == point.Y)
{
return true;
}
if (b.X == a.X && point.X == a.X && point.X >= Math.Min(a.Y, b.Y) && point.Y <= Math.Max(a.Y, b.Y))
{
return true;
}
if (b.Y == a.Y && point.Y == a.Y && point.X >= Math.Min(a.X, b.X) && point.X <= Math.Max(a.X, b.X))
{
return true;
}
if ((b.Y < point.Y && a.Y >= point.Y) || (a.Y < point.Y && b.Y >= point.Y))
{
var px = (int)(b.X + 1.0 * (point.Y - b.Y) / (a.Y - b.Y) * (a.X - b.X));
intersects.Add(px);
}
a = b;
}
intersects.Sort();
return intersects.IndexOf(point.X) % 2 == 0 || intersects.Count(x => x < point.X) % 2 == 1;
}
Complete algorithm along with C code is available at http://alienryderflex.com/polygon/
Converting it to c# / winforms would be trivial.
For those using NET Core, Region.IsVisible is available from NET Core 3.0. After adding package System.Drawing.Common,
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Example
{
class Program
{
static bool IsPointInsidePolygon(Point[] polygon, Point point)
{
var path = new GraphicsPath();
path.AddPolygon(polygon);
var region = new Region(path);
return region.IsVisible(point);
}
static void Main(string[] args)
{
Point vt1 = new Point(0, 0);
Point vt2 = new Point(100, 0);
Point vt3 = new Point(100, 100);
Point vt4 = new Point(0, 100);
Point[] polygon = { vt1, vt2, vt3, vt4 };
Point pt = new Point(50, 50);
bool isPointInsidePolygon = IsPointInsidePolygon(polygon, pt);
Console.WriteLine(isPointInsidePolygon);
}
}
}
Of lesser importance is that, adding System.Drawing.Common package increased size of publish folder by 400 KB. Maybe compared to custom code, this implementation could also be slower (above function timed to be 18 ms on i7-8665u). But still, I prefer this, for one less thing to worry about.
All you really need are 4 lines to implement the winding number method. But first, reference the System.Numerics to use complex library. The code below assumes that you have translate a loop of points (stored in cpyArr) so that your candidate point stands at 0,0.
For each point pair, create a complex number c1 using the first point and c2 using the 2nd point ( the first 2 lines within the loop)
Now here is some complex number theory. Think of c1 and c2 as complex number representation of vectors. To get from vector c1 to vector c2, you can multiply c1 by a complex number Z (c1Z=c2). Z rotates c1 so that it points at c2. Then it also stretches or squishes c1 so that it matces c2. To get such a magical number Z, you divide c2 by c1 (since c1Z=c2, Z=c2/c1). You can look up your high school notes on dividing complex number or use that method provided by Microsoft. After you get that number, all we really care is the phase angle.
To use the winding method, we add up all the phases and we should +/- 2 pi if the point is within the area. Otherwise, the sum should be 0
I added edge cases, 'literally'. If your phase angle is +/- pi, you're right on the edge between the points pair. In that case, I'd say the point is a part of the area and break out of the loop
/// <param name="cpyArr">An array of 2 coordinates (points)</param>
public static bool IsOriginInPolygon(double[,] cpyArr)
{
var sum = 0.0;
var tolerance = 1e-4;
var length = cpyArr.GetLength(0);
for (var i = 0; i < length-1; i++)
{
//convert vertex point pairs to complex numbers for simplified coding
var c2 = new Complex(cpyArr[i+1, 0], cpyArr[i+1, 1]);
var c1 = new Complex(cpyArr[i, 0], cpyArr[i, 1]);
//find the rotation angle from c1 to c2 when viewed from the origin
var phaseDiff = Complex.Divide(c2, c1).Phase;
//add the rotation angle to the sum
sum += phaseDiff;
//immediately exit the loop if the origin is on the edge of polygon or it is one of the vertices of the polygon
if (Math.Abs(Math.Abs(phaseDiff) - Math.PI) < tolerance || c1.Magnitude < tolerance || c2.Magnitude < tolerance)
{
sum = Math.PI * 2;
break;
}
}
return Math.Abs((Math.PI*2 ) - Math.Abs(sum)) < tolerance;
}
I recommend this wonderful 15-page paper by Kai Hormann (University of Erlangen) and Alexander Agathos (University of Athens). It consolidates all the best algorithms and will allow you to detect both winding and ray-casting solutions.
The Point in Polygon Problem for Arbitrary Polygons
The algorithm is interesting to implement, and well worth it. However, it is so complex that it is pointless for me to any portion of it directly. I'll instead stick with saying that if you want THE most efficient and versatile algorithm, I am certain this is it.
The algorithm gets complex because is is very highly optimized, so it will require a lot of reading to understand and implement. However, it combines the benefits of both the ray-cast and winding number algorithms and the result is a single number that provides both answers at once. If the result is greater than zero and odd, then the point is completely contained, but if the result is an even number, then the point is contained in a section of the polygon that folds back on itself.
Good luck.
This is an old question, but I optimized Saeed answer:
public static bool IsInPolygon(this List<Point> poly, Point point)
{
var coef = poly.Skip(1).Select((p, i) =>
(point.y - poly[i].y) * (p.x - poly[i].x)
- (point.x - poly[i].x) * (p.y - poly[i].y));
var coefNum = coef.GetEnumerator();
if (coef.Any(p => p == 0))
return true;
int lastCoef = coefNum.Current,
count = coef.Count();
coefNum.MoveNext();
do
{
if (coefNum.Current - lastCoef < 0)
return false;
lastCoef = coefNum.Current;
}
while (coefNum.MoveNext());
return true;
}
Using IEnumerators and IEnumerables.
If you are drawing Shapes on a Canvas this is a quick and easy Solution.
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.OriginalSource is Polygon)
{
//do something
}
}
"Polygon" can be any shape from System.Windows.Shapes.
Here's some modern C# code:
public record Point(double X, double Y);
public record Box(Point LowerLeft, Point UpperRight)
{
public Box(Point[] points)
: this(
new Point(
points.Select(x => x.X).Min(),
points.Select(x => x.Y).Min()),
new Point(
points.Select(x => x.X).Max(),
points.Select(x => x.Y).Max()))
{
}
public bool ContainsPoint(Point point)
{
return point.X >= LowerLeft.X
&& point.X <= UpperRight.X
&& point.Y >= LowerLeft.Y
&& point.Y <= UpperRight.Y;
}
}
public record Polygon(Point[] Points, Box Box)
{
public Polygon(Point[] points)
: this(points, new(points))
{
}
public bool ContainsPoint(Point point)
{
do
{
if (Box.ContainsPoint(point) == false)
{
break;
}
bool result = false;
int j = Points.Length - 1;
for (int i = 0; i < Points.Length; i++)
{
if ((Points[i].Y < point.Y && Points[j].Y >= point.Y)
|| (Points[j].Y < point.Y && Points[i].Y >= point.Y))
{
if (Points[i].X +
((point.Y - Points[i].Y) / (Points[j].Y - Points[i].Y) * (Points[j].X - Points[i].X))
< point.X)
{
result = !result;
}
}
j = i;
}
return result;
}
while (false);
return false;
}
}
I have a few sets of information available to me, currently:
position on screen (Point)
orientation of point (double, say 15 degrees)
distance (length from point)
What I want to do is pick X (less than 6 I think) number of points in an angular spread facing the same orientation as the position with a distance of distance so that they are always on screen.
I can do this, but my implementation does not take into account the fact that some of the points end up off the screen, and all my attempts are quite poor and overly complex.
Does anyone have a good way of doing this?
EDIT: Added graphic to show what im after...
A simple way of "projecting" a point (X1, Y1) along a trajectory/orientation for a distance to X2, Y2 you can use the following;
X2 = X1 + (int)(Math.Sin(orientation) * distance);
Y2 = Y1 + (int)(Math.Cos(orientation) * distance);
Where orientation is a radian double value. You may want to round the result since (int) is a brutal way to convert to int.
If you want to pick a point X/Y that is atleast distance d from point pX, pY then you know that the hypotenuse ( SquareRoot ( (X-pX)^2 + (Y-pY)^2 ) is less than d^2.
Is X/Y less than d from pX/pY?
bool isTooClose = ( ((X - pY)*(X - pY)) + ((Y - pY)*(Y - pY)) < (d*d));
If you know the screen size, then just check the boundaries.
bool isOnScreen = ( (pY > 0) && (pX > 0) && (pX < Screen.Width) && (pY < Screen.Height));
If you want to know that a circle is completely on screen, use the above isOnScreen and subtract/add the radius of the circle to the boundary. For example
bool isCircleOnScreen = ( (pY > r) && (pX > r) && (pX < (Screen.Width - r)) && (pY < (Screen.Height - r)));
To pick a point (X2, Y2) on a circle you can use the formula at the top.
This ended up being my implementation:
private static int[] DetermineTagPointsRange(Point location, double orientation, float distance)
{
const int screenWidth = 1024;
const int screenHieght = 768;
const int sampleCount = 10;
const int totalAngleSpread = 360;
const int angleInc = totalAngleSpread / sampleCount;
var lowestAngle = -1;
var highestAngle = -1;
for (var i = 0; i < sampleCount; i++)
{
var thisAngle = angleInc*i;
var endPointX = location.X + (int)(Math.Sin(ToRad(thisAngle)) * distance);
var endPointY = location.Y - (int)(Math.Cos(ToRad(thisAngle)) * distance);
bool isOnScreen = ((endPointY > 0) && (endPointX > 0) && (endPointX < screenWidth) && (endPointY < screenHieght));
if (isOnScreen)
{
if (thisAngle <= lowestAngle || lowestAngle == -1)
lowestAngle = thisAngle;
if (thisAngle >= highestAngle || highestAngle == -1)
highestAngle = thisAngle;
}
}
return new int[] {lowestAngle, highestAngle};
}
Thanks for the help