How to compute the Rotation-Matrix based on a Direction-Vector? - java

In my 3D world implementation I use Direction-Vectors (unit vector) to decide the orientation of my 3D-objects.
Each 3D-object has its own Direction-Vector which by default has the orientation V3(1, 0, 0) with Origin at V3(0,0,0).
This is how I apply the directional Rotation-Matrix "D" (the matrix "A" is used to rotate 3D-objects around their Direction-Vector as an axis, this seems to work fine):
Model3D model = actor.model;
// Loops through all the edges in the model
for (int i = 0; i < model.edges.length; i++) {
M3 D = directionMatrix(actor);
M3 R = rotationMatrix(actor);
// Draws a line based on each edge in the model.
// Each line consists of two points a and b.
// The matrix R rotates the points around a given axis.
// The D matrix rotates the points towards a given axis - not around it.
S.drawLine(g,
D.mul(R.mul(model.points[model.edges[i].a])).scale(actor.scale),
D.mul(R.mul(model.points[model.edges[i].b])).scale(actor.scale)
);
}
This is how I calculate my current directional Rotation-Matrix "D":
public M3 directionalRotationMatrix(c_Actor3D actor) {
double x = Math.atan2(actor.direction.z, actor.direction.y);
double y = Math.atan2(actor.direction.x, actor.direction.z);
double z = Math.atan2(actor.direction.y, actor.direction.x);
double sin_x = Math.sin(x), sin_y = Math.sin(y), sin_z = Math.sin(z);
double cos_x = Math.cos(x), cos_y = Math.cos(y), cos_z = Math.cos(z);
return new M3(
cos_x * cos_y, (cos_x * sin_y * sin_z) - (sin_x * cos_z),
(cos_x * sin_y * cos_z) + (sin_x * sin_z), sin_x * cos_y, (sin_x * sin_y * sin_z) + (cos_x * cos_z),
(sin_x * sin_y * cos_z) - (cos_x * sin_z), -sin_y, cos_y * sin_z, cos_y * cos_z);
}
My problem is to create the correct directional Rotation-Matrix that rotates the 3D-objects in the direction of their respective Direction-Vectors.
I'm not sure at all what I do wrong... My idea is to first rotate the cube towards a direction, then rotate the cube around the axis of the direction. After all that comes position transformation etc.
Thank you for your help guys!

Sounds like you are trying to move a 3D object in the direction of it's forward facing vector. To do this you will need the position of the object (x,y,z) and 3 vectors (forward, up, and right). You can rotate the 3 vectors using pitch yaw and roll based vector math(see below link). For the forward movement you then add the position of the object plus the speed multiplied by the forward vector, ie: position += speed * forward
Use the following complete example code posted here to figure out how to implemented your own version. http://cs.lmu.edu/~ray/notes/flightsimulator/

Related

Degree doesnt get calculated correctly, where did i go wrong?

Im writing a program, that takes 3d coordinates and places them on a 3d globe, projected onto a 2d screen. To turn the coordinates around an axis, i wanted to use the normal of the two points (start- and end- point (of the flight)), to turn it onto the x3 axis and then turn the rest of the points in the same manner, to eventually calculate the points, that i need to animate a point, that goes from point A to point B. the matrix I use to put the points onto the globe is:
public double[] genXYZ(double phi, double theta) {
double[] coords3D = new double[3];
phi = Math.toRadians(phi);
theta = Math.toRadians(theta);
coords3D[0] = Math.cos(theta) * Math.cos(phi);
coords3D[1] = Math.cos(theta) * Math.sin(phi);
coords3D[2] = Math.sin(theta);
return coords3D;
}
everything works just fine. Until I try to calculate the phi and theta angles of the normal (after I calculate the normal correctly).
public double[] getNAngles(double[] ncoords) {
double[] NAngles = new double[2];
NAngles[1] = Math.asin(Math.toRadians(ncoords[2]));
NAngles[0] = Math.acos(ncoords[0] / Math.cos(NAngles[1]));
NAngles[0] = Math.toDegrees(NAngles[0]);
NAngles[1] = Math.toDegrees(NAngles[1]);
System.out.println("N phi: " + NAngles[0]);
System.out.println("N theta: " + NAngles[1]);
return NAngles;
}
Globe
Cyan: start (Greenwich)
Magenta: end (Istanbul)
Black: normal
Pink: what the code calculated, what angles black has.
Thanks in advance!
Remove Math.toRadians call because coords are not angles, they are dimensionless values in range -1..1
NAngles[1] = Math.asin(ncoords[2]);
Also consider using atan2 function for NAngles[0] calculation to exclude sign effects and arccosine angle limit (0..Pi).
NAngles[0] = Math.atan2(ncoords[1], ncoords[0]);

Why isn't this code allowing me to connect the vertices of the drawing?

I'm meant to draw a pentagon with lines going from the vertices to the centre. These 'arms' are being drawn correctly but when I try to connect the vertices it is being drawn incorrectly. To connect the lines I placed another draw function in the loop as below, which should take the end point coordinates of the first line drawn as the starting point, and the end point coordinates of the next 'arm' that is drawn in the iteration, as its end point. Am I missing something here? Am I wrong the use 'i+angle' in the second draw?
for (int i = 0; i < arms; i += angle) {
double endPointX = armLength * Math.cos(i*angle-Math.PI/2);
double endPointY = armLength * Math.sin(i*angle-Math.PI/2);
double endPointX2 = armLength * Math.cos((i+angle)*angle-Math.PI/2);
double endPointY2 = armLength * Math.sin((i+angle)*angle-Math.PI/2);
g2d.drawLine(centreX, centreY,centreX+ (int) endPointX,centreY+ (int) endPointY);
g2d.drawLine(centreX+ (int) endPointX,centreY+ (int) endPointY, (int) endPointX2,(int) endPointY2);
}
I have a solution for this here in PolygonFactory
Abstractly, the way to generate a regular polygon with n points is to put these points on the unit circle. So:
Calculate your angle step, which is 2 * pi / #vertices
Calculate your radius
Starting at angle 0 (or an offset if you want) use Math.sin(angle) and Math.cos(angle) to calculate the x and y coordinates of your vertices
Store the vertex points somewhere / somehow. If you look at the Polygon class or the class I wrote, you can get some ideas on how to do this in a way that is friendly to converting to a java.awt.Polygon.

Getting the marker rotation angle from a matrix

I'm developing an augmented reality application using the ARToolkit. I would like to add a feature where I would control an object's size, or control the volume of a played song, by rotating a specific marker. I've found an example of an application, which is returning a 4x4 matrix that contains position and rotation information of the marker.
An example of such a matrix:
000,1878 -000,9442 -000,2707 -002,2898
-000,6210 000,0994 -000,7775 117,8998
-000,7610 -000,3141 000,5677 -530,6667
000,0000 000,0000 000,0000 001,0000
I've found a formula and a corresponding java method for the decomposition of the matrix to all three rotation angles, but I'm confused by the returned angle values.
The java method:
/** this conversion uses conventions as described on page:
* http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm
* Coordinate System: right hand
* Positive angle: right hand
* Order of euler angles: heading first, then attitude, then bank
* matrix row column ordering:
* [m00 m01 m02]
* [m10 m11 m12]
* [m20 m21 m22]*/
public final void rotate(matrix m) {
// Assuming the angles are in radians.
if (m.m10 > 0.998) { // singularity at north pole
heading = Math.atan2(m.m02,m.m22);
attitude = Math.PI/2;
bank = 0;
return;
}
if (m.m10 < -0.998) { // singularity at south pole
heading = Math.atan2(m.m02,m.m22);
attitude = -Math.PI/2;
bank = 0;
return;
}
heading = Math.atan2(-m.m20,m.m00);
bank = Math.atan2(-m.m12,m.m11);
attitude = Math.asin(m.m10);
}
Example of the returned values:
Heading: 1.384716377951241,
Bank: 1.3919044985590532
Attitude: -0.7751361901097762
So the result, obviously, isn't in degrees, which I would want. I'm I doing this the right way? What am I doing wrong?

Tracking a specific points' x & y position on an image during rotation in Java

I'm trying to create rope physics for a 2D game, so as a starting point I have a small rotating image and I need to add another piece of rope to the end of it. Unfortunately I'm having trouble trying to track the bottom part of the image as the rotation occurs at the top of it. I've managed to track the (0,0) coordinate of the image using the following code but I need to be able to track point (32,57). This is what I have so far:
xr = xm + (xPos - xm) * Math.cos(a) - (yPos - ym) * Math.sin(a);
yr = ym + (xPos - xm) * Math.sin(a) + (yPos - ym) * Math.cos(a);
Any help is appreciated!
EDIT:
So hey, I got it working =D Using polar coordinates turned out to be a lot easier then whatever I had going on before.
The top 2 variables are constant and stay the same:
theta0 = Math.atan2(y, x);
r = 25;
theta = theta0 + a;
xr = (r * Math.cos(theta)) + xm;
yr = (r * Math.sin(theta)) + ym;
xm and ym are the positions of my image.
Use polar coordinates. Set your origin at the point of rotation of your image, and pick your favorite angular reference (say 0 degrees is directly to the right, and positive rotations go counterclockwise from there).
Compute the polar coordinates of your desired point (32, 57) relative to this coordinate system. Say the answer is (r, theta).
Now, the only thing that's changing as you spin the image around is the value of theta. Now you can go back to x-y coordinates with your new value of theta.
Hope this helps.

Perspective Projection: determine the 2D screen coordinates (x,y) of points in 3D space (x,y,z)

I wish to determine the 2D screen coordinates (x,y) of points in 3D space (x,y,z).
The points I wish to project are real-world points represented by GPS coordinates and elevation above sea level.
For example:
Point (Lat:49.291882, Long:-123.131676, Height: 14m)
The camera position and height can also be determined as a x,y,z point. I also have the heading of the camera (compass degrees), its degree of tilt (above/below horizon) and the roll (around the z axis).
I have no experience of 3D programming, therefore, I have read around the subject of perspective projection and learnt that it requires knowledge of matrices, transformations etc - all of which completely confuse me at present.
I have been told that OpenGL may be of use to construct a 3D model of the real-world points, set up the camera orientation and retrieve the 2D coordinates of the 3D points.
However, I am not sure if using OpenGL is the best solution to this problem and even if it is I have no idea how to create models, set up cameras etc
Could someone suggest the best method to solve my problem? If OpenGL is a feasible solution i'd have to use OpenGL ES if that makes any difference. Oh and whatever solution I choose it must execute quickly.
Here's a very general answer. Say the camera's at (Xc, Yc, Zc) and the point you want to project is P = (X, Y, Z). The distance from the camera to the 2D plane onto which you are projecting is F (so the equation of the plane is Z-Zc=F). The 2D coordinates of P projected onto the plane are (X', Y').
Then, very simply:
X' = ((X - Xc) * (F/Z)) + Xc
Y' = ((Y - Yc) * (F/Z)) + Yc
If your camera is the origin, then this simplifies to:
X' = X * (F/Z)
Y' = Y * (F/Z)
You do indeed need a perspective projection and matrix operations greatly simplify doing so. I assume you are already aware that your spherical coordinates must be transformed to Cartesian coordinates for these calculations.
Using OpenGL would likely save you a lot of work over rolling your own software rasterizer. So, I would advise trying it first. You can prototype your system on a PC since OpenGL ES is not too different as long as you keep it simple.
If just need to compute coordinates of some points, you should only need some algebra skills, not 3D programming with openGL.
Moreover openGL does not deal with Geographic coordinates
First get some doc about WGS84 and geodesic coordinates, you have first to convert your GPS data into a cartesian frame ( for instance the earth centric cartesian frame in which is defined the WGS84 ellipsoid ).
Then the computations with matrix can take place.
The chain of transformations is roughly :
WGS84
earth centric coordinates
some local frame
camera frame
2D projection
For the first conversion see this
The last involves a projection matrix
The others are only coordinates rotations and translation.
The "some local frame" is the local cartesian frame with origin as your camera location
tangent to the ellipsoid.
I'd recommend "Mathematics for 3D Game Programming and Computer Graphics" by Eric Lengyel. It covers matrices, transformations, the view frustum, perspective projection and more.
There is also a good chapter in The OpenGL Programming Guide (red book) on viewing transformations and setting up a camera (including how to use gluLookAt).
If you aren't interested in displaying the 3D scene and are limited to using OpenGL ES then it may be better to just write your own code to do the mapping from 3D to 2D window coords. As a starting point you could download Mesa 3D, an open source implementation of OpenGL, to see how they implement gluPerspective (to set a projection matrix), gluLookAt (to set a camera transformation) and gluProject (to project a 3D point to 2D window coords).
return [((fol/v[2])*v[0]+x),((fol/v[2])*v[1]+y)];
Point at [0,0,1] will be x=0 and y=0, unless you add center screen xy - it's not camera xy. fol is focal length, derived from fov angle and screen width - how high is the triangle (tangent). This method will not match three.js perspective matrix, which is why am I looking for that.
I should not be looking for it. I matched xy on openGL, perfectly like super glue! But I cannot get it to work right in java. THAT Perfect match follows.
var pmat = [0,0,0,0,0,0,0,0,0,0,
(farclip + nearclip) / (nearclip - farclip),-1,0,0,
2*farclip*nearclip / (nearclip - farclip),0 ];
void setpmat() {
double fl; // = tan(dtor(90-fovx/aspect/2)); /// UNIT focal length
fl = 1/tan(dtor(fov/Aspect/2)); /// same number
pmat[0] = fl/Aspect;
pmat[5] = fl;
}
void fovmat(double v[],double p[]) {
int cx = (int)(_Width/2),cy = (int)(_Height/2);
double pnt2[4], pnt[4] = { 0,0,0,1 } ;
COPYVECTOR(pnt,p);NORMALIZE(pnt);
popmatrix4(pnt2,pmat,pnt);
COPYVECTOR(v,pnt2);
v[0] *= -cx; v[1] *= -cy;
v[0] += cx; v[1] += cy;
} // world to screen matrix
void w2sm(int xy[],double p[]) {
double v[3]; fovmat(v,p);
xy[0] = (int)v[0];
xy[1] = (int)v[1];
}
I have one more way to match three.js xy, til I get the matrix working, just one condition. must run at Aspect of 2
function w2s(fol,v,x,y) {
var a = width / height;
var b = height/width ;
/// b = .5 // a = 2
var f = 1/Math.tan(dtor(_fov/a)) * x * b;
return [intr((f/v[2])*v[0]+x),intr((f/v[2])*v[1]+y)];
}
Use it with the inverted camera matrix, you will need invert_matrix().
v = orbital(i);
v = subv(v,campos);
v3 = popmatrix(wmatrix,v); //inverted mat
if (v3[2] > 0) {
xy = w2s(flen,v3,cx,cy);
Finally here it is, (everyone ought to know by now), the no-matrix match, any aspect.
function angle2fol(deg,centerx) {
var b = width / height;
var a = dtor(90 - (clamp(deg,0.0001,174.0) / 2));
return asa_sin(PI_5,centerx,a) / b;
}
function asa_sin(a,s,b) {
return Math.sin(b) * (s / Math.sin(PI-(a+b)));
} // ASA solve opposing side of angle2 (b)
function w2s(fol,v,x,y) {
return [intr((fol/v[2])*v[0]+x),intr((fol/v[2])*v[1]+y)];
}
Updated the image for the proof. Input _fov gets you 1.5 that, "approximately." To see the FOV readout correctly, redo the triangle with the new focal length.
function afov(deg,centerx) {
var f = angle2fol(deg,centerx);
return rtod(2 * sss_cos(f,centerx,sas_cos(f,PI_5,centerx)));
}
function sas_cos(s,a,ss) {
return Math.sqrt((Math.pow(s,2)+Math.pow(ss,2))-(2*s*ss*Math.cos(a)));
} // Side Angle Side - solve length of missing side
function sss_cos(a,b,c) {
with (Math) {
return acos((pow(a,2)+pow(c,2)-pow(b,2))/(2*a*c));
}
} // SSS solve angle opposite side2 (b)
Star library confirmed the perspective, then possible to measure the VIEW! http://innerbeing.epizy.com/cwebgl/perspective.jpg
I can explain the 90 deg correction to moon's north pole in one word precession. So what is the current up vector. pnt? radec?
function ininorths() {
if (0) {
var c = ctime;
var v = LunarPos(jdm(c));
c += secday();
var vv = LunarPos(jdm(c));
vv = crossprod(v,vv);
v = eyeradec(vv);
echo(v,vv);
v = [266.86-90,65.64]; //old
}
var v = [282.6425,65.8873]; /// new.
// ...
}
I have yet to explain the TWO sets of vectors: Three.milkyway.matrix and the 3D to 2D drawing. They ARE:
function drawmilkyway() {
var v2 = radec2pos(dtor(192.8595), dtor(27.1283),75000000);
// gcenter 266.4168 -29.0078
var v3 = radec2pos(dtor(266.4168), dtor(-29.0078),75000000);
// ...
}
function initmwmat() {
var r,u,e;
e = radec2pos(dtor(156.35), dtor(12.7),1);
u = radec2pos(dtor(60.1533), dtor(25.5935),1);
r = normaliz(crossprod(u,e));
u = normaliz(crossprod(e,r));
e = normaliz(crossprod(r,u));
var m = MilkyWayMatrix;
m[0]=r[0];m[1]=r[1];m[2]=r[2];m[3]=0.0;
m[4]=u[0];m[5]=u[1];m[6]=u[2];m[7]=0.0;
m[8]=e[0];m[9]=e[1];m[10]=e[2];m[11]=0.0;
m[12]=0.0;m[13]=0.0;m[14]=0.0;m[15]=1.0;
}
/// draw vectors and matrix were the same in C !
void initmwmat(double m[16]) {
double r[3], u[3], e[3];
radec2pos(e,dtor(192.8595), dtor(27.1283),1); //up
radec2pos(u,dtor(266.4051), dtor(-28.9362),-1); //eye
}

Categories