C# Calucate Surface Normal Inverse Instead of Boolean Subtraction - c#

I need to do a boolean subtraction between two models in C#. One of the meshs will be entirely within the other mesh, so I was hoping to reverse the normals for the one model and add the two models together. I am at a loss on how to reverse the normals though.
This is how I'm calculating a surface normal:
//creates surface normals
Vector3D CalculateSurfaceNormal(Point3D p1, Point3D p2, Point3D p3)
{
Vector3D v1 = new Vector3D(0, 0, 0);
Vector3D v2 = new Vector3D(0, 0, 0);
Vector3D normal = new Vector3D(0, 0, 0);
// Finds The Vector Between 2 Points By Subtracting
// The x,y,z Coordinates From One Point To Another.
// Calculate The Vector From Point 2 To Point 1
v1.X = p1.X - p2.X;
v1.Y = p1.Y - p2.Y;
v1.Z = p1.Z - p2.Z;
// Calculate The Vector From Point 3 To Point 2
v2.X = p2.X - p3.X;
v2.Y = p2.Y - p3.Y;
v2.Z = p2.Z - p3.Z;
// Compute The Cross Product To Give Us A Surface Normal
normal.X = v1.Y * v2.Z - v1.Z * v2.Y; // Cross Product For Y - Z
normal.Y = v1.Z * v2.X - v1.X * v2.Z; // Cross Product For X - Z
normal.Z = v1.X * v2.Y - v1.Y * v2.X; // Cross Product For X - Y
normal.Normalize();
return normal;
}
Is there a simple way to invert the surface normal?

To flip a normal just negate it (i.e. by negating each component). This will reverse the direction it points in.
normal.X = -normal.X
normal.Y = -normal.Y
normal.Z = -normal.Z
A vector type will likely have an overloaded unary negation operator for this, so if you've got that you might be able to do simply
normal = -normal
If you're in an environment with backface culling, you'll want to reverse the winding of the vertices of each triangle (which will naturally flip the resulting computed normal). To do this just flip the order of any two vertices of the triangle.

Related

emgucv angle detection for rectangle in csharp

I am using following thread to perform angle detection for a rectangle image.
Detect centre and angle of rectangles in an image using Opencv
I am stuck at following piece of code.
cv::Point2f edge1 = cv::Vec2f(rect_points[1].x, rect_points[1].y) - cv::Vec2f(rect_points[0].x, rect_points[0].y);
cv::Point2f edge2 = cv::Vec2f(rect_points[2].x, rect_points[2].y) - cv::Vec2f(rect_points[1].x, rect_points[1].y);
cv::Point2f usedEdge = edge1;
if(cv::norm(edge2) > cv::norm(edge1)) usedEdge = edge2;
cv::Point2f reference = cv::Vec2f(1,0); // horizontal edge
angle = 180.0f/CV_PI * acos((reference.x*usedEdge.x + reference.y*usedEdge.y) / (cv::norm(reference) *cv::norm(usedEdge)));
I am not able to figure out following few lines which i required to convert in emgu csharp.
cv::Point2f edge1 = cv::Vec2f(rect_points[1].x, rect_points[1].y) - cv::Vec2f(rect_points[0].x, rect_points[0].y);
cv::Point2f edge2 = cv::Vec2f(rect_points[2].x, rect_points[2].y) - cv::Vec2f(rect_points[1].x, rect_points[1].y);
angle = 180.0f/CV_PI * acos((reference.x*usedEdge.x + reference.y*usedEdge.y) / (cv::norm(reference) *cv::norm(usedEdge)));
if(cv::norm(edge2) > cv::norm(edge1)) usedEdge = edge2;
cv::Point2f reference = cv::Vec2f(1,0);
Can anyone help me how to resolve the same? Any help or suggestion will be highly appreciated?
The Point2f here are simply points, having float precision properties of X and Y, being used to store 2D vectors of I and J. Their method if declaration is setting the edges to be the vector between two points, i.e. the delta between those two points. In C#, I would write this as:
float deltaX = rect_points[1].X - rect_points[0].X;
float deltaY = rect_points[1].Y - rect_points[0].Y;
PointF edge1 = new PointF(deltaX, deltaY);
OR of course...
PointF edge1 = new PointF(rect_points[1].X - rect_points[0].X, rect_points[1].Y - rect_points[0].Y);
PointF edge2 = new PointF(rect_points[2].X - rect_points[1].X, rect_points[2].Y - rect_points[1].Y);
These PointF are now the two vectors, or edges, that join at rect_points[1]. Next, norm is performed in order to compare the magnitude of the two. This is simply Pythagoras if we perform the same manually:
edge1Magnitude = Math.Sqrt(Math.Pow(edge1.X, 2) + Math.Pow(edge1.Y, 2));
edge2Magnitude = Math.Sqrt(Math.Pow(edge2.X, 2) + Math.Pow(edge2.Y, 2));
The longer of the edges, that with the greatest magnitude, is considered the "primary", or longer edge the rectangle:
PointF primaryEdge = edge1Magnitude > edge2Magnitude ? edge1 : edge2;
double primaryMagnitude = edge1Magnitude > edge2Magnitude ? edge1Magnitude : edge2Magnitude;
Finally, to find the angle between the primaryEdge, and a horizontal vector, reference. This is the acos, of the "Dot Product", of the two, or:
PointF reference = new PointF(1,0);
double refMagnitude = 1;
double thetaRads = Math.Acos(((primaryEdge.X * reference.X) + (primaryEdge.Y * reference.Y)) / (primaryMagnitude * refMagnitude));
double thetaDeg = thetaRads * 180 / Math.PI;
Now, thetaDeg is the angle between edge1 and the horizontal, in degrees.

C# Flipping Surface Normals

I need to do a boolean subtraction between two models in C#. One of the meshs will be entirely within the other mesh, so I was hoping to reverse the normals for the one model and add the two models together. I am at a loss on how to invert the normals though.
This is how I'm calculating a surface normal:
//creates surface normals
Vector3D CalculateSurfaceNormal(Point3D p1, Point3D p2, Point3D p3)
{
Vector3D v1 = new Vector3D(0, 0, 0); // Vector 1 (x,y,z) & Vector 2 (x,y,z)
Vector3D v2 = new Vector3D(0, 0, 0);
Vector3D normal = new Vector3D(0, 0, 0);
// Finds The Vector Between 2 Points By Subtracting
// The x,y,z Coordinates From One Point To Another.
// Calculate The Vector From Point 2 To Point 1
v1.X = p1.X - p2.X;
v1.Y = p1.Y - p2.Y;
v1.Z = p1.Z - p2.Z;
// Calculate The Vector From Point 3 To Point 2
v2.X = p2.X - p3.X;
v2.Y = p2.Y - p3.Y;
v2.Z = p2.Z - p3.Z;
// Compute The Cross Product To Give Us A Surface Normal
normal.X = v1.Y * v2.Z - v1.Z * v2.Y; // Cross Product For Y - Z
normal.Y = v1.Z * v2.X - v1.X * v2.Z; // Cross Product For X - Z
normal.Z = v1.X * v2.Y - v1.Y * v2.X; // Cross Product For X - Y
normal.Normalize();
return normal;
}
I was advised to reverse the normal by negating it:
n = CalculateSurfaceNormal(p1, p2, p3);
n = new Vector3D(-1 * n.X, -1 * n.Y, -1 * n.Z);
I find the values are negated, but when I view the model in a 3D program, there is no change in the model.
Another suggestion was to try backface culling by changing the order of the vectors. I tried this by swapping the order of v1 and v2:
//creates invertedsurface normals
Vector3D CalculateInvertedSurfaceNormal(Point3D p1, Point3D p2, Point3D p3)
{
Vector3D v1 = new Vector3D(0, 0, 0); // Vector 1 (x,y,z) & Vector 2 (x,y,z)
Vector3D v2 = new Vector3D(0, 0, 0);
Vector3D normal = new Vector3D(0, 0, 0);
// Finds The Vector Between 2 Points By Subtracting
// The x,y,z Coordinates From One Point To Another.
// Calculate The Vector From Point 2 To Point 1
v2.X = p1.X - p2.X;
v2.Y = p1.Y - p2.Y;
v2.Z = p1.Z - p2.Z;
// Calculate The Vector From Point 3 To Point 2
v1.X = p2.X - p3.X;
v1.Y = p2.Y - p3.Y;
v1.Z = p2.Z - p3.Z;
// Compute The Cross Product To Give Us A Surface Normal
normal.X = v1.Y * v2.Z - v1.Z * v2.Y; // Cross Product For Y - Z
normal.Y = v1.Z * v2.X - v1.X * v2.Z; // Cross Product For X - Z
normal.Z = v1.X * v2.Y - v1.Y * v2.X; // Cross Product For X - Y
normal.Normalize();
return normal;
}
No change in the model.
Here is the whole code:
private void SaveMoldMeshtoStlFile(MeshGeometry3D mesh, string filename)
{
if (mesh == null)
return;
if (File.Exists(filename))
{
File.SetAttributes(filename, FileAttributes.Normal);
File.Delete(filename);
}
Point3DCollection vertexes = mesh.Positions;
Int32Collection indexes = mesh.TriangleIndices;
Point3D p1, p2, p3;
Vector3D n;
string text;
using (TextWriter writer = new StreamWriter(filename))
{
writer.WriteLine("solid Bolus");
for (int v = 0; v < mesh.TriangleIndices.Count(); v += 3)
{
//gather the 3 points for the face and the normal
p1 = vertexes[indexes[v]];
p2 = vertexes[indexes[v + 1]];
p3 = vertexes[indexes[v + 2]];
n = CalculateInvertedSurfaceNormal(p1, p2, p3);
text = string.Format("facet normal {0} {1} {2}", n.X,n.Y, n.Z);
writer.WriteLine(text);
writer.WriteLine("outer loop");
text = String.Format("vertex {0} {1} {2}", p1.X, p1.Y, p1.Z);
writer.WriteLine(text);
text = String.Format("vertex {0} {1} {2}", p2.X, p2.Y, p2.Z);
writer.WriteLine(text);
text = String.Format("vertex {0} {1} {2}", p3.X, p3.Y, p3.Z);
writer.WriteLine(text);
writer.WriteLine("endloop");
writer.WriteLine("endfacet");
}
}
}
//creates inverted surface normals
Vector3D CalculateInvertedSurfaceNormal(Point3D p1, Point3D p2, Point3D p3)
{
Vector3D v1 = new Vector3D(0, 0, 0); // Vector 1 (x,y,z) & Vector 2 (x,y,z)
Vector3D v2 = new Vector3D(0, 0, 0);
Vector3D normal = new Vector3D(0, 0, 0);
// Finds The Vector Between 2 Points By Subtracting
// The x,y,z Coordinates From One Point To Another.
// Calculate The Vector From Point 2 To Point 1
v2.X = p1.X - p2.X;
v2.Y = p1.Y - p2.Y;
v2.Z = p1.Z - p2.Z;
// Calculate The Vector From Point 3 To Point 2
v1.X = p2.X - p3.X;
v1.Y = p2.Y - p3.Y;
v1.Z = p2.Z - p3.Z;
// Compute The Cross Product To Give Us A Surface Normal
normal.X = v1.Y * v2.Z - v1.Z * v2.Y; // Cross Product For Y - Z
normal.Y = v1.Z * v2.X - v1.X * v2.Z; // Cross Product For X - Z
normal.Z = v1.X * v2.Y - v1.Y * v2.X; // Cross Product For X - Y
normal.Normalize();
return normal;
}
Is there an error with my code? Am I missing something? I've tried out the exported models in a few different programs, and all are showing the exported model still has the normals facing outwards. I tried flipping the normals in Blender and found the other programs also showed the normals flipped, so I'm fairly sure it's a problem with my program.
Figured out the solution.
The order of points for each triangle is crucial. If the order of points doesn't support the normal's direction, I'm finding other programs will automatically correct the normal.
Where I had this:
//gather the 3 points for the face and the normal
p1 = vertexes[indexes[v]];
p2 = vertexes[indexes[v + 1]];
p3 = vertexes[indexes[v + 2]];
n = CalculateInvertedSurfaceNormal(p1, p2, p3);
I instead reversed the direction of the points by changed to this:
//gather the 3 points for the face and the normal
p3 = vertexes[indexes[v]];
p2 = vertexes[indexes[v + 1]];
p1 = vertexes[indexes[v + 2]];
n = CalculateInvertedSurfaceNormal(p1, p2, p3);
That solved my problem.

Is angle between 2 vectors reflex? (C#)

I need to be able to check whether the angle between three points (A, B and C) which make up part of a shape is reflex (> PI radians), as in the diagram below (sorry for poor paint skills!):
My points should always be anti-clockwise, and I always want to measure the angle on the inside of the shape.
I am currently doing this using the following code:
//triangle[] is an array of the three points I am testing, corresponding
// to [A, B, C] on the diagram above
//Vectors from B to A and C
PointF toA = PointFVectorTools.difference(triangle[0], triangle[1]);
PointF toC = PointFVectorTools.difference(triangle[2], triangle[1]);
double angle = Math.Atan2(toB.Y, toB.X) - Math.Atan2(toA.Y, toA.X);
//Put angle in range 0 to 2 PI
if (angle < 0) angle += 2 * Math.PI;
return angle > Math.PI;
This has worked in all the cases I have tried up until now, but with these co-ords it does not work:
(Where B=(2,3) )
The angle I get back is ~-0.5, whereas I would expect ~+0.5. Any ideas why this is wrong?
UPDATE
I've attempted to implement Nico's solution, and while I understand it in theory I'm getting a real headache trying to implement it. Here is the code so far:
//Vector A -> B
float dx = triangle[1].X - triangle[0].X;
float dy = triangle[1].Y - triangle[0].Y;
//Left normal = (y, -x)
PointF leftDir = new PointF(dy, -dx);
//Vector B -> C
dx = triangle[2].X - triangle[1].X;
dy = triangle[2].Y - triangle[1].Y;
//Dot product of B->C and Left normal
float dot = dx * leftDir.X + dy * leftDir.Y;
return dot < 0;
In the following, I assume that the x-axis points to the right and the y-axis points upwards. If this is not the case in your scenario, you might need to switch some signs.
If you have the line segment (x1, y1) - (x2, y2) and points are sorted counter-clockwise, you know that the shape is left of the line segment. The orthogonal direction vector that points to the line segment's left is:
leftDir = (y1 - y2, x2 - x1)
Together with the line segment, this direction defines a half space. If the following angle is convex, the third point must lie in this half space. If that's not the case, the angle is concave (which you apparently call reflex):
You can determine if the point lies in the same half space with the dot product:
isConcave = dot(p3 - p2, leftDir) < 0
In code:
float dx = x3 - x2;
float dy = y3 - y2;
float dot = dx * leftDir.x + dy * leftDir.y
return dot < 0;
I'm not sure how toB in your code is defined, and also I'm not familar with PointF.
Anyway you should use the cosine rule c^2 = a^2 + b^2 - 2ab cos(C) (where a,b,c are the lengths of the sides of the triangle, and C is the angle subtending c):
public bool IsReflex(... triangle)
{
var a = GetVectorLength(triangle[0].x, triangle[0].y, triangle[1].x, triangle[1].y);
var b = GetVectorLength(triangle[1].x, triangle[1].y, triangle[2].x, triangle[2].y);
var c = GetVectorLength(triangle[2].x, triangle[2].y, triangle[0].x, triangle[0].y);
var cosC = (c*c - a*a - b*b) / (2*a*b);
var C = Math.Acos(cosC); // this returns a value between 0 and pi
return Math.Abs(C) > (Math.PI/2);
}
private double GetVectorLength(double x0, double y0, double x1, double y1)
{
// using Pythagoras
var sideX = x0 - x1;
var sideY = y0 - y1;
return Math.Sqrt(sideX*sideX + sideY*sideY);
}

Draw 2D trail of ship. XNA

I've been looking for a solution to this for some time now and already have many elements to work with but not really how to piece them together.
Objective: Draw a trail for the player's ship.
So far: Since the ship's direction is unpredictable I have only the previous positions of the player's ship to work with. To draw the trail I could simply draw a pixel (or a texture) at the previous position of the player but this is memory expensive and it doesn't draw curves, it won't achieve a pleasing to the eye curved effect.
I've been looking into Beziers Paths and Cathmull Rom for solutions.
Now I can get the control points for a given point, then from 2 points and 2 control points calculate a curve, from here I make an array of VertexPositionColor with a distance between points to make a triangleStrip from the curve.
These are the main functions I have so far:
public Vector2[] GetControlPoints(Vector2 p0, Vector2 p1, Vector2 p2, float tension = 0.5f)
{
// get length of lines [p0-p1] and [p1-p2]
float d01 = Vector2.Distance(p0, p1);
float d12 = Vector2.Distance(p1, p2);
// calculate scaling factors as fractions of total
float sa = tension * d01 / (d01 + d12);
float sb = tension * d12 / (d01 + d12);
// left control point
float c1x = p1.X - sa * (p2.X - p0.X);
float c1y = p1.Y - sa * (p2.Y - p0.Y);
// right control point
float c2x = p1.X + sb * (p2.X - p0.X);
float c2y = p1.Y + sb * (p2.Y - p0.Y);
return new Vector2[] {new Vector2(c1x, c1y), new Vector2(c2x, c2y) };
}
// Given 2 points and 2 control points
public static VertexPositionColor[] bezierCurve(Vector2 start, Vector2 end, Vector2 c1, Vector2 c2)
{
VertexPositionColor[] points = new VertexPositionColor[SUBDIVISIONS + 2];
float fraction;
for (int i = 0; i < SUBDIVISIONS + 2; i++)
{
fraction = i * (1f / (float)SUBDIVISIONS);
points[i] = new VertexPositionColor(new Vector3((float)((start.X * Math.Pow((1 - fraction), 3))
+(c1.X * 3 * fraction * Math.Pow(1-fraction, 2))
+(c2.X * 3 * Math.Pow(fraction,2) * (1-fraction))
+(end.X * Math.Pow(fraction,3))),
(float)((start.Y * Math.Pow((1 - fraction), 3))
+ (c1.Y * 3 * fraction * Math.Pow(1 - fraction, 2))
+ (c2.Y * 3 * Math.Pow(fraction, 2) * (1 - fraction))
+ (end.Y * Math.Pow(fraction, 3))), 0), UNLIT);
}
return points;
}
/*
* This function treats the curve as a series of straight lines and calculates points on a line perpendicular to each point, resulting in two points THICKNESS appart.
* Requires THICKNESS to be set
*/
public static VertexPositionColor[] curveToStrip(VertexPositionColor[] curve)
{
VertexPositionColor[] strip = new VertexPositionColor[curve.Length * 2];
VertexPositionColor[] new1 = new VertexPositionColor[curve.Length];
VertexPositionColor[] new2 = new VertexPositionColor[curve.Length];
for (int i = 0; i < curve.Length; i++)
{
if (i < curve.Length-1)
{
Vector2 p1 = new Vector2(curve[i].Position.X, curve[i].Position.Y);
Vector2 p2 = new Vector2(curve[i + 1].Position.X, curve[i + 1].Position.Y);
Vector2 perpPoint = perpendicularPoint(p1, p2);
new1[i] = new VertexPositionColor(new Vector3(distanceToPoint(p1, perpPoint, THICKNESS / 2), 0), UNLIT);
new2[i] = new VertexPositionColor(new Vector3(distanceToPoint(p1, perpPoint, -1 * THICKNESS / 2), 0), UNLIT);
}
else
{
Vector2 p1 = new Vector2(curve[i].Position.X, curve[i].Position.Y);
Vector2 p2 = new Vector2(curve[i - 1].Position.X, curve[i - 1].Position.Y);
Vector2 perpPoint = perpendicularPoint(p1, p2);
new1[i] = new VertexPositionColor(new Vector3(distanceToPoint(p1, perpPoint, -1 * THICKNESS / 2), 0), UNLIT);
new2[i] = new VertexPositionColor(new Vector3(distanceToPoint(p1, perpPoint, THICKNESS / 2), 0), UNLIT);
}
}
I thought about calling the functions on the draw phase but this seems very expensive just to make a tiny curve and to draw a bigger Beziers path I imagine it worse. Since I would get a point at each frame, each function would be called to calculate the curve between points just to draw 1 curve of 3 pixels (or less).
How can I proceed? Any suggestions?
I am still a beginner on this kind of stuff!
All this I got from several sources:
CathmullRom
Beziers and Triangle strip
http://www.imagehosting.cz/images/trails.gif
I will just briefly explain how this works:
It is function that receives position, it is called each time you want add next segment of trail.
When function is called it adds two vertices on position, look at tangent vector from previous step, creates normal vector to current position and place vertices along that normal according to trail width.
Next it looks to at previous two vertexes and align them according to average of current and previous tangent, creating trapezoid.
I suggest to leave calculation of fading on GPU (effectively using approach of GPU particles).
If you know velocity vector of object when you are calling update of trail you can use it to optimize that algorithm. Use of dynamic vertex buffer is probably without saying (just use your own vertex format that will include current time at moment when you create those vertices so you can fade it on GPU).
One way could be that you create a list of trails/particles, and you init that on every frame or how much you like. i will try to explain in pseudo code below. i also rotate a bit every trail, and use different size and color of smoke texture, and added a bit of ofsset +- 5 pixels on init.
class Trail
position as vector2d
duration as single
velocity as vector2d
fade as integer = 1
active = true
end class
class Trails
inherits list of Trail
sub Init(position as vector2d, velocity as vector2d)
// add trail to list
end sub
sub Update()
for each trail in me.findAll(function(c) c.active))
position += velocity
fade -= .05 // or some value
end for
me.removeAll(function(c) not(c.active)) // remove from list when unused
end sub
sub Draw()
for each trail in me.findAll(function(c) c.active))
draw(smokeTexture, position, size, rotate, color * trail.fade)
end for
end sub
end class
by this i have achieved this effect, it's barely visible but it gives effect.

How to calc a cyclic arc through 3 points and parameterize it 0..1 in 3d

How can i calculate an arc through 3 points A, B, C in 3d. from A to C passing B (order is taken care of).
Most robot arms have this kind of move command. I need to simulate it and apply different speed dynamics to it and need therefore a parameter 0..1 which moves a position from A to C.
EDIT:
what i have is radius and center of the arc, but how can i parameterize the circle in 3d if i know the start and end angle?
EDIT2:
getting closer. if i have two unit length perpendicular vectors v1 and v2 on the plane in which the circle lies, i can do a parameterization like: x(t) = c + r * cos(t) * v1 + r * sin(t) * v2
so i take v1 = a-c and i only need to find v2 now. any ideas?
Martin Doms recently wrote a blog entry about splines and bezier curves that you might find useful.
Part of his post describes how to get a 2D curve defined by the three control points P0, P1, and P2. The curve is parameterized by a value t that ranges from 0 to 1:
F(t) = (1-t)2 P0 + 2t (1-t) P1 + t2 P2
It seems likely that you could adapt that to 3D with a little thought. (Of course, bezier curves don't necessarily go through the control points. This may not work if that's a deal-breaker for you.)
As an aside, Jason Davies put together a nice little animation of curve interpolation.
Got back to this one and it was quite tricky. The code is as short as possible, but still much more than i thought.
You can create an instance of this class and call the SolveArc method with the 3 positions (in the right order) to set up the class. Then the Arc Method will give you the positions on the circular arc from 0..1 in linear velocity. If you find a shorter solution, please let me know.
class ArcSolver
{
public Vector3D Center { get; private set; }
public double Radius { get; private set; }
public double Angle { get; private set; }
Vector3D FDirP1, FDirP2;
//get arc position at t [0..1]
public Vector3D Arc(double t)
{
var x = t*Angle;
return Center + Radius * Math.Cos(x) * FDirP1 + Radius * Math.Sin(x) * FDirP2;
}
//Set the points, the arc will go from P1 to P3 though P2.
public bool SolveArc(Vector3D P1, Vector3D P2, Vector3D P3)
{
//to read this code you need to know that the Vector3D struct has
//many overloaded operators:
//~ normalize
//| dot product
//& cross product, left handed
//! length
Vector3D O = (P2 + P3) / 2;
Vector3D C = (P1 + P3) / 2;
Vector3D X = (P2 - P1) / -2;
Vector3D N = (P3 - P1).CrossRH(P2 - P1);
Vector3D D = ~N.CrossRH(P2 - O);
Vector3D V = ~(P1 - C);
double check = D|V;
Angle = Math.PI;
var exist = false;
if (check != 0)
{
double t = (X|V) / check;
Center = O + D*t;
Radius = !(Center - P1);
Vector3D V1 = ~(P1 - Center);
//vector from center to P1
FDirP1 = V1;
Vector3D V2 = ~(P3 - Center);
Angle = Math.Acos(V1|V2);
if (Angle != 0)
{
exist = true;
V1 = P2-P1;
V2 = P2-P3;
if ((V1|V2) > 0)
{
Angle = Math.PI * 2 - Angle;
}
}
}
//vector from center to P2
FDirP2 = ~(-N.CrossRH(P1 - Center));
return exist;
}
}
So this answer is part of the story, given that the code is in Mathematica rather than C#, but certainly all of the maths (with perhaps one minor exception) should all be relatively easy to translate to any language.
The basic approach presented is to:
Project the three points (A, B, C) onto the plane that those points lie in. It should have a normal AB x BC. This reduces the problem from three dimensions to two.
Use your favourite technique for finding the center of the circle that passes through the three projected points.
Unproject the center of the circle back into three dimensions.
Use an appropriate spherical interpolation strategy (slerp is used in the sample, but I believe it would have been better to use quaternions).
The one caveat is that you need to work out which direction you are rotating in, I'm sure there are smarter ways, but with only two alternatives, rejection testing is sufficient. I'm using reduce, but you'd probably need to do something slightly different to do this in C#
No guarantees that this is the most numerically stable or robust way to do this, or that there are any corner cases that have been missed.
(* Perpendicular vector in 2 dimensions *)
Perp2d[v_] := {-v[[2]], v[[1]]};
(* Spherical linear interpolation. From wikipedia \
http://en.wikipedia.org/wiki/Slerp *)
slerp[p0_, p1_, t_, rev_] :=
Module[{\[CapitalOmega], v},
\[CapitalOmega] = ArcCos[Dot[p0, p1]];
\[CapitalOmega] =
If[rev == 0, 2 Pi - \[CapitalOmega], \[CapitalOmega]];
v = (Sin[(1 - t) \[CapitalOmega]]/
Sin[\[CapitalOmega]]) p0 + (Sin[t \[CapitalOmega]]/
Sin[\[CapitalOmega]]) p1;
Return[v]
];
(* Based on the expressions from mathworld \
http://mathworld.wolfram.com/Line-LineIntersection.html *)
IntersectionLineLine[{x1_, y1_}, {x2_, y2_}, {x3_, y3_}, {x4_, y4_}] :=
Module[{x, y, A, B, C},
A = Det[{{x1, y1}, {x2, y2}}];
B = Det[{{x3, y3}, {x4, y4}}];
C = Det[{{x1 - x2, y1 - y2}, {x3 - x4, y3 - y4}}];
x = Det[{{A, x1 - x2}, {B, x3 - x4}}]/C;
y = Det[{{A, y1 - y2}, {B, y3 - y4}}]/C;
Return[{x, y}]
]
(* Based on Paul Bourke's Notes \
http://local.wasp.uwa.edu.au/~pbourke/geometry/circlefrom3/ *)
CircleFromThreePoints2D[v1_, v2_, v3_] :=
Module[{v12, v23, mid12, mid23, v12perp, v23perp, c, r},
v12 = v2 - v1;
v23 = v3 - v2;
mid12 = Mean[{v1, v2}];
mid23 = Mean[{v2, v3}];
c = IntersectionLineLine[
mid12, mid12 + Perp2d[v12],
mid23, mid23 + Perp2d[v23]
];
r = Norm[c - v1];
Assert[r == Norm[c - v2]];
Assert[r == Norm[c - v3]];
Return[{c, r}]
]
(* Projection from 3d to 2d *)
CircleFromThreePoints3D[v1_, v2_, v3_] :=
Module[{v12, v23, vnorm, b1, b2, va, vb, vc, xc, xr, yc, yr},
v12 = v2 - v1;
v23 = v3 - v2;
vnorm = Cross[v12, v23];
b1 = Normalize[v12];
b2 = Normalize[Cross[v12, vnorm]];
va = {0, 0};
vb = {Dot[v2, b1], Dot[v2, b2]};
vc = {Dot[v3, b1], Dot[v3, b2]};
{xc, xr} = CircleFromThreePoints2D[va, vb, vc];
yc = xc[[1]] b1 + xc[[2]] b2;
yr = Norm[v1 - yc];
Return[{yc, yr, b1, b2}]
]
v1 = {0, 0, 0};
v2 = {5, 3, 7};
v3 = {6, 4, 2};
(* calculate the center of the circle, radius, and basis vectors b1 \
and b2 *)
{yc, yr, b1, b2} = CircleFromThreePoints3D[v1, v2, v3];
(* calculate the path of motion, given an arbitrary direction *)
path = Function[{t, d},
yc + yr slerp[(v1 - yc)/yr, (v3 - yc)/yr, t, d]];
(* correct the direction of rotation if necessary *)
dirn = If[
TrueQ[Reduce[{path[t, 1] == v2, t >= 0 && t <= 1}, t] == False], 0,
1]
(* Plot Results *)
gr1 = ParametricPlot3D[path[t, dirn], {t, 0.0, 1.0}];
gr2 = ParametricPlot3D[Circle3d[b1, b2, yc, yr][t], {t, 0, 2 Pi}];
Show[
gr1,
Graphics3D[Line[{v1, v1 + b1}]],
Graphics3D[Line[{v1, v1 + b2}]],
Graphics3D[Sphere[v1, 0.1]],
Graphics3D[Sphere[v2, 0.1]],
Graphics3D[{Green, Sphere[v3, 0.1]}],
Graphics3D[Sphere[yc, 0.2]],
PlotRange -> Transpose[{yc - 1.2 yr, yc + 1.2 yr}]
]
Which looks something like this:

Categories