Problem superimposing and aligning 3D triangles - geometry

I am trying to superimpose two 3D triangles for a molecular modeling problem. It seemed simple enough. I translated the first point of each triangle to the origin, 0,0,0. I then calculated the angle I would have to rotate around the z axis to put the second point on the x axis. Using the formula for x,y,z for Rz(theta) this would be the angle where y=0,
y=xsin(theta)+ycos(theta)=0, and rearranging, tan(theta)=-y/x
The angle would be the arctan(-y/x). But, plugging this value for the angle back into the original equation above does not give zero except in the case where x=y, and the tangent is one. Seems like simple algebra - why doesn't this work?
Thanks for any help.

As the other comments suggested you most likely got confused withing projections and goniometrics. There is also safer way without goniometrics using vector math (linear algebra).
create transform matrix m0 representing aligned plane to first triangle t0
by aligned I mean one of the edges of triangle should lie in the one of the plane basis vectors. That is simple you just set one basis vector as the edge in question, origin as one of its point and exploit the cross product to get the remainding vectors.
so if our triangle has points p0,p1,p2 and our basis vectors are x,y,z with origin o then:
x = p1-p0; x /= |x|;
y = p2-p0;
z = cross(x,y); z /= |z|;
y = cross(z,x); y /= |y|;
o = p0
so just feed those to the transform matrix (see the link in bottom of answer)
create transform matrix m1 representing aligned plane to second triangle t1
its the same as #1
compute final transform matrix m converting t1 to t0
that is simple:
m = Inverse(m1)*m0
Now any point from t1 can be aligned to t0 simply by multiplying m matrix by the point. Do not forget to use homogenuous coordinates so point(x,y,z,1)
Here small C++/OpenGL example:
//---------------------------------------------------------------------------
double t0[3][3]= // 1st triangle
{
-0.5,-0.5,-1.2,
+0.5,-0.5,-0.8,
0.0,+0.5,-1.0,
};
double t1[3][3]= // 2nd triangle
{
+0.5,-0.6,-2.1,
+1.5,-0.5,-2.3,
+1.2,+0.3,-2.2,
};
double arot=0.0; // animation angle
//---------------------------------------------------------------------------
void gl_draw() // main rendering code
{
int i;
double m0[16],m1[16],m[16],x[3],y[3],z[3],t2[3][3];
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslated(0.0,0.0,-10.0);
glRotatef(arot,0.0,1.0,0.0);
// render original triangles
glBegin(GL_TRIANGLES);
glColor3f(1.0,0.0,0.0); for (i=0;i<3;i++) glVertex3dv(t0[i]);
glColor3f(0.0,0.0,1.0); for (i=0;i<3;i++) glVertex3dv(t1[i]);
glEnd();
// x,y,z = t0 plane basis vectors
vector_sub(x,t0[1],t0[0]); // x is fisrt edge
vector_one(x,x); // normalized
vector_sub(y,t0[2],t0[0]); // y is last edge
vector_mul(z,x,y); // z = cross(x,y) ... perpendicular vector to x,y
vector_one(z,z);
vector_mul(y,z,x); // y = cross(z,x) ... perpendicular vector to z,x
vector_one(y,y);
// m0 = transform matrix representing t0 plane
m0[ 3]=0.0; for (i=0;i<3;i++) m0[ 0+i]=x[i];
m0[ 7]=0.0; for (i=0;i<3;i++) m0[ 4+i]=y[i];
m0[11]=0.0; for (i=0;i<3;i++) m0[ 8+i]=z[i];
m0[15]=1.0; for (i=0;i<3;i++) m0[12+i]=t0[0][i];
// x,y,z = t1 plane basis vectors
vector_sub(x,t1[1],t1[0]); // x is fisrt edge
vector_one(x,x); // normalized
vector_sub(y,t1[2],t1[0]); // y is last edge
vector_mul(z,x,y); // z = cross(x,y) ... perpendicular vector to x,y
vector_one(z,z);
vector_mul(y,z,x); // y = cross(z,x) ... perpendicular vector to z,x
vector_one(y,y);
// m1 = transform matrix representing t1 plane
m1[ 3]=0.0; for (i=0;i<3;i++) m1[ 0+i]=x[i];
m1[ 7]=0.0; for (i=0;i<3;i++) m1[ 4+i]=y[i];
m1[11]=0.0; for (i=0;i<3;i++) m1[ 8+i]=z[i];
m1[15]=1.0; for (i=0;i<3;i++) m1[12+i]=t1[0][i];
// m = transform t1 -> t0 = Inverse(m1)*m0
matrix_inv(m,m1);
matrix_mul(m,m,m0);
// t2 = transformed t1
for (i=0;i<3;i++) matrix_mul_vector(t2[i],m,t1[i]);
// render transformed triangle
glLineWidth(2.0);
glBegin(GL_LINE_LOOP);
glColor3f(0.0,1.0,0.0); for (i=0;i<3;i++) glVertex3dv(t2[i]);
glLineWidth(1.0);
glEnd();
glFlush();
SwapBuffers(hdc);
}
//---------------------------------------------------------------------------
I used my own matrix and vector math hope the comments are enough if not see:
Understanding 4x4 homogenous transform matrices
For info about the matrices and you will find the sources and equations for the math used there too. Here preview for my test case:
Where red is t0 triangle blue is t1 triangle and green is the m*t1 transformed triangle. As you can see no need for goniometrics/euler angles at all. I rotate the stuff by arot just to visually check if the green triangle really align to the blue to prove me I did not make a silly mistake.
Now its unclear how exactly you want to align, so for example if you want maximal coverage or something either try all 3 combinations and remember the best or align to closest or largest edges of both triangles etc ...

Related

How do you calculate the x,y points of all corners of a square from two only a pair of x,y points (see pic)

I have the green x,y points, how would I get the missing red?
You can rotate the two known points of 90° around their midpoint.
In pseudo code:
// Evaluate the midpoint from the coordinates of points a and b,
h_x = (b_x - a_x) / 2;
h_y = (b_y - a_y) / 2;
m_x = a_x + h_x;
m_y = a_y + h_y;
// Apply a rotation of 90 degree around the midpoint to find c and d
c_x = m_x - h_y;
c_y = m_y + h_x;
d_x = m_x + h_y;
d_y = m_y - h_x;
This result can be formally derived in terms of homogeneous coordinates and transfomation matrices.
The midpoint m, expressed in homogeneous coordinates, can be calculated as
To rotate a vector around the origin of an angle α, we apply a rotation matrix like
If another center of rotation is needed (the midpoint, in our case), we need to translate from the original position to the origin, apply the rotation and translate back again. The translation matrices are
The complete transformation can be expressed as
Where
So that we can evaluate, let's say d, with
Q.e.d.

Turning a circle collision function into a 3d cylinder function

I've got a function to return any points at which a line segment intersects a circle (up to two results, but potentially zero):
bool Math::GetLineCircleIntersections(Point theCenter, float theRadius, Point theLineA, Point theLineB, Array<Point>& theResults)
{
theResults.Reset();
Point aBA=theLineB-theLineA;
Point aCA=theCenter-theLineA;
float aA=aBA.mX*aBA.mX+aBA.mY*aBA.mY;
float aBBy2=aBA.mX*aCA.mX+aBA.mY*aCA.mY;
float aC=aCA.mX*aCA.mX+aCA.mY*aCA.mY-theRadius*theRadius;
float aPBy2=aBBy2/aA;
float aQ=aC/aA;
float aDisc=aPBy2*aPBy2-aQ;
if (aDisc<0) return false;
float aTmpSqrt=(float)sqrt(aDisc);
float aABScalingFactor1=-aPBy2+aTmpSqrt;
float aABScalingFactor2=-aPBy2-aTmpSqrt;
int aRSpot=0;
if (aABScalingFactor1<=0.0f && aABScalingFactor1>=-1.0f) theResults[aRSpot++]=Point(theLineA.mX-aBA.mX*aABScalingFactor1,theLineA.mY-aBA.mY*aABScalingFactor1);
if (aDisc==0) return true;
if (aABScalingFactor2<=0.0f && aABScalingFactor2>=-1.0f) theResults[aRSpot++]=Point(theLineA.mX-aBA.mX*aABScalingFactor2,theLineA.mY-aBA.mY*aABScalingFactor2);
return true;
}
I want to convert this to a 3D line, with an infinite cylinder-- with the added complication that the 3D cylinder has a tilt axis. I understand that what I'm really doing is intersecting with a sphere that is centered on the cylinder center where the plane of the line cuts it... but... how do I do that? How do I choose the best point to center the sphere, and then having done that, what's my change to turn line->circle intersections into line->sphere?
(I have a vector class that is exactly like the point class)
(Edit) I did manage to convert to a sphere function, only to discover that duh, no, a sphere won't work because a line that's tilted will not enter and exit the same way it would enter and exit a cylinder.
So, question is the same-- how can I convert this to collide with an infinite cylinder given an origin and axis for the cylinder?
I do not think sphere is usable for this...
However why not convert your 3D line into 2D by projecting it on to plane paralel with the cylinder base.
So you got 3D line in form of 2 endpoint p0,p1 and cylinder in form any point on its axis p , its radius r and axis unit direction vector d.
You need 2 unit basis vectors u,v describing cylinder base
so exploit cross product and cylinder axis for example:
// set u as any unit and non paralel vector to d
u = (1,0,0)
if (abs(dot(u,d))>0.75) u=(0,1,0)
// v set as perpendicular to u,d
v = cross(d,u)
// and make u perpendicular to v,d too
u = cross(v,d)
Project the problem into 2D
p0' = vec2( p0*dot(p0,u) , p0*dot(p0,v) )
p1' = vec2( p1*dot(p1,u) , p1*dot(p1,v) )
p' = vec2( p *dot(p ,u) , p *dot(p ,v) )
Solve the problem
now you just use 2D points p0',p1',p' and solve your problem using function you already have...

Find angle of rotation, inverted y axis, between two points in 2D

Background :
I am implementing an application where I need to do affine transformations on a selected line. Line is represented using 2 points. All the code is done in mouse events.
void mousePressEvent(){
lastPoint = event.point();
}
void mouseMoveEvent(){
currentPoint = event.point();
//Do transformations here.
translate_factor = currentPoint - lastPoint
scale_factor = currentPoint / lastPoint
rotation_angle = f(current_point,last_point) //FIND f
//Apply transformation
lastPoint = currentPoint
}
I have two points, p1 and p2. The X axis increases from left to right. Y axis increases top to bottom. I have a point d around which I want to rotate a set of points p_set .
How do I find the angle of rotation from p1 to p2 about d .
What I am doing is translate p1 , p2 by -d and calculate theta by using atan2f as shown in the following code.
Note that y is inverted : goes from top to bottom.
Here is the code
const auto about = stroke->getMidPoint();
Eigen::Affine2f t1(Eigen::Translation2f(0-about.x(),0-about.y()));
Eigen::Vector3f p1 = t1.matrix()*Eigen::Vector3f(lastPoint.x(),lastPoint.y(),1.0);
Eigen::Vector3f p2 = t1.matrix()*Eigen::Vector3f(currentPoint.x(),currentPoint.y(),1.0);
float theta = atan2f(p2[1]-p1[1],p2[0]-p1[0]);
When I transform using this, I get very weird rotations.
What I want is to find angle as a function of current and last points
It seems to me that you're finding the slope of the vector p2-p1.
If I understood correctly, you want the difference of the slopes of the two vectors p2-d and p1-d, so the rotation angle is something like atan((p2.y-d.y)/(p2.x-d.x)) - atan((p1.y-d.y)/(p1.x-d.x))

How to find the orientation of a plane?

I have three non-colinear 3D points, let's say pt1, pt2, pt3. I've computed the plane P using the sympy.Plane. How can I find the orientation of this plane(P) i.e. RPY(euler angles) or in quaternion?
I never used sympy, but you should be able to find a function to get the angle between 2 vectors (your normal vector and the world Y axis.)
theta = yaxis.angle_between(P.normal_vector)
then get the rotation axis, which is the normalized cross product of those same vectors.
axis = yaxis.cross(P.normal_vector).normal()
Then construct a quaternion from the axis and angle
q = Quaternion.from_axis_angle(axis, theta)

shade border of 2D polygon differently

we are programming a 2D game in XNA. Now we have polygons which define our level elements. They are triangulated such that we can easily render them. Now I would like to write a shader which renders the polygons as outlined textures. So in the middle of the polygon one would see the texture and on the border it should somehow glow.
My first idea was to walk along the polygon and draw a quad on each line segment with a specific texture. This works but looks strange for small corners where the textures are forced to overlap.
My second approach was to mark all border vertices with some kind of normal pointing out of the polygon. Passing this to the shader would interpolate the normals across edges of the triangulation and I could use the interpolated "normal" as a value for shading. I could not test it yet but would that work? A special property of the triangulation is that all vertices are on the border so there are no vertices inside the polygon.
Do you guys have a better idea for what I want to achieve?
Here A picture of what it looks right now with the quad solution:
You could render your object twice. A bigger stretched version behind the first one. Not that ideal since a complex object cannot be streched uniformly to create a border.
If you have access to your screen buffer you can render your glow components into a rendertarget and align a full-screen quad to your viewport and add a fullscreen 2D silhouette filter to it.
This way you gain perfect control over the edge by defining its radius, colour, blur. With additional output values such as the RGB values from the object render pass you can even have different advanced glows.
I think rendermonkey had some examples in their shader editor. Its definetly a good starting point to work with and try out things.
Propaply you want calclulate new border vertex list (easy fill example with triangle strip with originals). If you use constant border width and convex polygon its just:
B_new = B - (BtoA.normalised() + BtoC.normalised()).normalised() * width;
If not then it can go more complicated, there is my old but pretty universal solution:
//Helper function. To working right, need that v1 is before v2 in vetex list and vertexes are going to (anti???) cloclwise!
float vectorAngle(Vector2 v1, Vector2 v2){
float alfa;
if (!v1.isNormalised())
v1.normalise();
if (!v2.isNormalised())
v2.normalise();
alfa = v1.dotProduct(v2);
float help = v1.x;
v1.x = v1.y;
v1.y = -help;
float angle = Math::ACos(alfa);
if (v1.dotProduct(v2) < 0){
angle = -angle;
}
return angle;
}
//Normally dont use directly this!
Vector2 calculateBorderPoint(Vector2 vec1, Vector2 vec2, float width1, float width2){
vec1.normalise();
vec2.normalise();
float cos = vec1.dotProduct(vec2); //Calculates actually cosini of two (normalised) vectors (remember math lessons)
float csc = 1.0f / Math::sqrt(1.0f-cos*cos); //Calculates cosecant of angle, This return NaN if angle is 180!!!
//And rest of the magic
Vector2 difrence = (vec1 * csc * width2) + (vec2 * csc * width1);
//If you use just convex polygons (all angles < 180, = 180 not allowed in this case) just return value, and if not you need some more magic.
//Both of next things need ordered vertex lists!
//Output vector is always to in side of angle, so if this angle is.
if (Math::vectorAngle(vec1, vec2) > 180.0f) //Note that this kind of function can know is your function can know that angle is over 180 ONLY if you use ordered vertexes (all vertexes goes always (anti???) cloclwise!)
difrence = -difrence;
//Ok and if angle was 180...
//Note that this can fix your situation ONLY if you use ordered vertexes (all vertexes goes always (anti???) cloclwise!)
if (difrence.isNaN()){
float width = (width1 + width2) / 2.0; //If angle is 180 and border widths are difrent, you cannot get perfect answer ;)
difrence = vec1 * width;
//Just turn vector -90 degrees
float swapHelp = difrence.y
difrence.y = -difrence.x;
difrence.x = swapHelp;
}
//If you don't want output to be inside of old polygon but outside, just: "return -difrence;"
return difrence;
}
//Use this =)
Vector2 calculateBorderPoint(Vector2 A, Vector2 B, Vector2 C, float widthA, float widthB){
return B + calculateBorderPoint(A-B, C-B, widthA, widthB);
}
Your second approach can be possible...
mark the outer vertex (in border) with 1 and the inner vertex (inside) with 0.
in the pixel shader you can choose to highlight, those that its value is greater than 0.9f or 0.8f.
it should work.

Resources