World axis to local axis - c

How can I modify/rotate an axis angle from world coords to object coords?
See below:
void RotateMatrix4(float *m, float angle, float *axis);
//This function rotates a matrix in object space
void RotateLocal(float angle, float *axis) {
RotateMatrix4(m, angle, axis)
}
void RotateGlobal(float angle, float *axis) {
//Do something to axis here
RotateMatrix4(m, angle, axis)
}

You found the answer yourself - that is simply a multiplication between a tranformation matrix and a vector - you are simply transforming the axis vector into object coords.
Look at Transformation Matrix for more information on Transformation matrices.
(I would comment on your answer - but my rank is not yet high enough...)

Related

How can I transform 3D coordinates into 2D coordinates using isometric projection?

Programming Language: C
I'm currently in the process of implementing a 3D wireframe model represented through isometric projection.
My current understanding of the project is to:
parse a text map containing the x,y,z coordinates of the wireframe model
Transforming the 3D coordinates to 2D using isometric projection
Drawing the line using the Bresenham Line Algo and a few functions out of my graphic library of choice.
I'm done with Step 1 however I've been stuck on Step 2 for the last few days.
I understand that isometric projection is the process of projecting a 2D plane in a angle that it looks like it's 3D even though we are only working with x,y when drawing the lines. That is def. not the best way of describing it and if I'm incorrect please correct me.
Example of a text map:
0 0 0
0 5 0
0 0 0
My data structure of choice (implemented as array of structs)
typedef struct point
{
float x;
float y;
float z;
bool is_last;
int color; // Implemented after mandatory part
} t_point;
I pretty much just read out the rows, column and values of the text map and store them in x,y,z values respectively.
Now that I have to transform them I've tried the following formulas:
const double angle = 30 * M_PI / 180.0;
void isometric(t_dot *dot, double angle)
{
dot->x = (dot->x - dot->y) * cos(angle);
dot->y = (dot->x + dot->y) * sin(angle) - dot->z;
}
static void iso(int x, int y, int z)
{
int previous_x;
int previous_y;
previous_x = x;
previous_y = y;
x = (previous_x - previous_y) * cos(0.523599);
y = -z + (previous_x + previous_y) * sin(0.523599);
}
t_point *calc_isometric(t_point *pts, int max_pts)
{
float x;
float y;
float z;
const double angle = 30 * M_PI / 180.0;
int num_pts;
num_pts = 0;
while (num_pts < max_pts)
{
x = pts[num_pts].x;
y = pts[num_pts].y;
z = pts[num_pts].z;
printf("x: %f y: %f z: %f\n", x, y, z);
pts[num_pts].x = (x - y) * cos(angle);
pts[num_pts].y = (x + y) * sin(angle) - z;
printf("x_iso %f\ty_iso %f\n\n", pts[num_pts].x, pts[num_pts].y);
num_pts++;
}
return (pts);
}
It spits out various things which makes no sense to me. I could just go one and try to implement the Line Algo. from here and hope for the best but I would like to understand what I'm actually doing here.
Next to that I learned through me research that I need to set up my camera in a certain way to create the projection.
All in all I'm just very lost and my question boils down to this.
Please help me understand the concept of isometric projection.
How to transform 3D coordinates (x,y,z) into coordinates using isometric projection.
I see it like this:
// constants:
float deg = M_PI/180.0;
float ax = 30*deg;
float ay =150*deg;
vec2 X = vec2(cos(ax),-sin(ax)); // x axis
vec2 Y = vec2(cos(ay),-sin(ay)); // y axis
vec2 Z = vec2( 0.0,- 1.0); // z axis
vec2 O = vec2(0,0); // position of point (0,0,0) on screen
// conversion:
vec3 p=vec3(?,?,?); // input point
vec2 q=O+(p.x*X)+(p.y*Y)+(p.z*Y); // output point
the coordinatewise version:
float Xx = cos(ax);
float Xy = -sin(ax);
float Yx = cos(ay);
float Yy = -sin(ay);
float Zx = 0.0;
float Zy = - 1.0;
float Ox = 0;
float Oy = 0;
// conversion:
float px=?,py=?,pz=?; // input point
float qx=Ox+(px*Xx)+(py*Yx)+(pz*Yx); // output point
float qy=Oy+(px*Xy)+(py*Yy)+(pz*Yy); // output point
Asuming x axis going to right and y axis going down ... the O is usually set to center of screen instead of (0,0) unless you add pan capabilities of your isometric world.
In case you want to add arbitrary rotations within the "3D" XY plane see this:
How can I warp a shader matrix to match isometric perspective in a 3d scene?
So you just compute the X,Y vectors on the ellipse (beware they will not be unit anymore!!!) So if I see it right it would be:
float ax=?,ay=ax+90*deg;
float Xx = cos(ax) ;
float Xy = -sin(ax)*0.5;
float Yx = cos(ay) ;
float Yy = -sin(ay)*0.5;
where ax is the rotation angle...

Algorithm to detect intersection between an axis-aligned rectangle and an oriented superellipse

I am in the process of writing a function to test for the intersection of a rectangle with a superellipse.
The rectangle will always be axis-aligned whereas the superellipse may be oriented with an angle of rotation alpha.
In the case of an axis-aligned rectangle intersecting an axis-aligned superellipse I have written these two short functions that work beautifully.
The code is concise, clear and efficient. If possible, I would like to keep a similar structure for the new more general function.
Here is what I have for detecting if an axis-aligned rectangle intersects an axis-aligned superellipse:
double fclamp(double x, double min, double max)
{
if (x <= min) return min;
if (x >= max) return max;
return x;
}
bool rect_intersects_superellipse(const t_rect *rect, double cx, double cy, double rx, double ry, double exponent)
{
t_pt closest;
closest.x = fclamp(cx, rect->x, rect->x + rect->width);
closest.y = fclamp(cy, rect->y, rect->y + rect->height);
return point_inside_superellipse(&closest, cx, cy, rx, ry, exponent);
}
bool point_inside_superellipse(const t_pt *pt, double cx, double cy, double rx, double ry, double exponent)
{
double dx = fabs(pt->x - cx);
double dy = fabs(pt->y - cy);
double dxp = pow(dx, exponent);
double dyp = pow(dy, exponent);
double rxp = pow(rx, exponent);
double ryp = pow(ry, exponent);
return (dxp * ryp + dyp * rxp) <= (rxp * ryp);
}
This works correctly but - as I said - only for an axis-aligned superellipse.
Now I would like to generalize it to an oriented superellipse, keeping the algorithm structure as close to the above as possible.
The obvious expansion of the previous two functions would then become something like:
bool rect_intersects_oriented_superellipse(const t_rect *rect, double cx, double cy, double rx, double ry, double exponent, double radians)
{
t_pt closest;
closest.x = fclamp(cx, rect->x, rect->x + rect->width);
closest.y = fclamp(cy, rect->y, rect->y + rect->height);
return point_inside_oriented_superellipse(&closest, cx, cy, rx, ry, exponent, radians);
}
bool point_inside_oriented_superellipse(const t_pt *pt, double cx, double cy, double rx, double ry, double exponent, double radians)
{
double dx = pt->x - cx;
double dy = pt->y - cy;
if (radians) {
double c = cos(radians);
double s = sin(radians);
double new_x = dx * c - dy * s;
double new_y = dx * s + dy * c;
dx = new_x;
dy = new_y;
}
double dxp = pow(fabs(dx), exponent);
double dyp = pow(fabs(dy), exponent);
double rxp = pow(rx, exponent);
double ryp = pow(ry, exponent);
return (dxp * ryp + dyp * rxp) < (rxp * ryp);
}
For an oriented superellipse, the above doesn’t work correctly, even though point_inside_oriented_superellipse() by itself works as expected. I cannot use the above functions to test for an intersection with an axis-aligned rectangle. I have been researching online for about a week now and I have found some solutions requiring an inverse matrix transform to equalize the superellipse axes and bring its origin at (0, 0). The tradeoff is that now my rectangle won’t be a rectangle anymore and certainly not axis-aligned. I would like to avoid going down that route.
My question is to show how to make the above algorithm work keeping its structure more or less unaltered. If it is not possible to keep the same algorithmic structure, please show the simplest, most efficient algorithm to test for the intersection between an axis-aligned rectangle and an oriented superellipse. I only need to know if the intersection occurred or not (boolean result).
The range of the exponent parameter can vary from 0.25 to 100.0.
Thanks for any assistance.
Take a look at point 2 in this source. In simple terms, you will need to do the following tests:
1. Are there any rectangle vertexes in the ellipse?
2. Is a rectangle edge intersecting the ellipse?
3. Is the center of the ellipse inside the rectangle?
The ellipse and the rectangle intersect each-other if any of the questions above can be answered with a yes, so, your function should return something like this:
return areVertexesInsideEllipse(/*params*/) || areRectangleEdgesIntersectingEllipse(/*params*/) || isEllipseCenterInsideRectangle(/*params*/);
The doc even has an example of implementation, which is reasonably close to yours.
To check whether any of the vertex is inside the ellipse, you can compute their coordinates against the inequality of the ellipse. To check whether an edge overlaps the ellipse, you will need to check whether its line goes through the ellipse or touches it. If so, you will need to check whether the segment where the line goes through the ellipse or touches it intersects the segment defined by the edge. To check whether the center of the ellipse is inside the rectangle you will need to check the center against the inequalities of the rectangle.
Note, that these are very general terms, they do not even assume that your rectangle is axis oriented, yet alone your ellipse.
First you should rule out the obvious non-intersecting cases using the separating axis theorem -- The super-ellipse has possibly two bounding boxes (cases where exponent n>1) and case where n<=1.
In the SAT, all vertices in Bounding Box ABCD are compared against all (directed) edges in the BB(abcd) of super-ellipse; then vice versa. If the signed distances to the separating axis are all positive (i.e. outside), the objects don't collide.
b
a
A------B
| | d
| | c
C------D
The exponent n==1 divides the cases further -- n<=1 makes the super-ellipsoid concave, in which case ABCD intersects abcd only, if one or more points are inside the super-ellipsoid.
When n>1, one must solve the intersection point of the line segment in AABB and the super-ellipsoid, which may have to be approximated by splines or another proxy must be found. After all, the actual intersection point is not of interest, but putting the equations to wolfram alpha failed to produce any results in standard execution time.

Angle to Quaternion - Making an object facing another object

i have two Objects in a 3D World and want to make the one object facing the other object. I already calculated all the angles and stuff (pitch angle and yaw angle).
The problem is i have no functions to set the yaw or pitch individually which means that i have to do it by a quaternion. As the only function i have is: SetEnetyQuaternion(float x, float y, float z, float w). This is my pseudocode i have yet:
float px, py, pz;
float tx, ty, tz;
float distance;
GetEnetyCoordinates(ObjectMe, &px, &py, &pz);
GetEnetyCoordinates(TargetObject, &tx, &ty, &tz);
float yaw, pitch;
float deltaX, deltaY, deltaZ;
deltaX = tx - px;
deltaY = ty - py;
deltaZ = tz - pz;
float hyp = SQRT((deltaX*deltaX) + (deltaY*deltaY) + (deltaZ*deltaZ));
yaw = (ATAN2(deltaY, deltaX));
if(yaw < 0) { yaw += 360; }
pitch = ATAN2(-deltaZ, hyp);
if (pitch < 0) { pitch += 360; }
//here is the part where i need to do a calculation to convert the angles
SetEnetyQuaternion(ObjectMe, pitch, 0, yaw, 0);
What i tried yet was calculating the sinus from those angles devided with 2 but this didnt work - i think this is for euler angles or something like that but didnt help me. The roll(y axis) and the w argument can be left out i think as i dont want my object to have a roll. Thats why i put 0 in.
If anyone has any idea i would really appreciate help.
Thank you in advance :)
Let's suppose that the quaternion you want describes the attitude of the player relative to some reference attitude. It is then essential to know what the reference attitude is.
Moreover, you need to understand that an object's attitude comprises more than just its facing -- it also comprises the object's orientation around that facing. For example, imagine the player facing directly in the positive x direction of the position coordinate system. This affords many different attitudes, from the one where the player is standing straight up to ones where he is horizontal on either his left or right side, to one where he is standing on his head, and all those in between.
Let's suppose that the appropriate reference attitude is the one facing parallel to the positive x direction, and with "up" parallel to the positive z direction (we'll call this "vertical"). Let's also suppose that among the attitudes in which the player is facing the target, you want the one having "up" most nearly vertical. We can imagine the wanted attitude change being performed in two steps: a rotation about the coordinate y axis followed by a rotation about the coordinate z axis. We can write a unit quaternion for each of these, and the desired quaternion for the overall rotation is the Hamilton product of these quaternions.
The quaternion for a rotation of angle θ around the unit vector described by coordinates (x, y, z) is (cos θ/2, x sin θ/2, y sin θ/2, z sin θ/2). Consider then, the first quaternion you want, corresponding to the pitch. You have
double semiRadius = sqrt(deltaX * deltaX + deltaY * deltaY);
double cosPitch = semiRadius / hyp;
double sinPitch = deltaZ / hyp; // but note that we don't actually need this
. But you need the sine and cosine of half that angle. The half-angle formulae come in handy here:
double sinHalfPitch = sqrt((1 - cosPitch) / 2) * ((deltaZ < 0) ? -1 : 1);
double cosHalfPitch = sqrt((1 + cosPitch) / 2);
The cosine will always be nonnegative because the pitch angle must be in the first or fourth quadrant; the sine will be positive if the object is above the player, or negative if it is below. With all that being done, the first quaternion is
(cosHalfPitch, 0, sinHalfPitch, 0)
Similar analysis applies to the second quaternion. The cosine and sine of the full rotation angle are
double cosYaw = deltaX / semiRadius;
double sinYaw = deltaY / semiRadius; // again, we don't actually need this
We can again apply the half-angle formulae, but now we need to account for the full angle to be in any quadrant. The half angle, however, can be only in quadrant 1 or 2, so its sine is necessarily non-negative:
double sinHalfYaw = sqrt((1 - cosYaw) / 2);
double cosHalfYaw = sqrt((1 + cosYaw) / 2) * ((deltaY < 0) ? -1 : 1);
That gives us an overall second quaternion of
(cosHalfYaw, 0, 0, sinHalfYaw)
The quaternion you want is the Hamilton product of these two, and you must take care to compute it with the correct operand order (qYaw * qPitch), because the Hamilton product is not commutative. All the zeroes in the two factors make the overall expression much simpler than it otherwise would be, however:
(cosHalfYaw * cosHalfPitch,
-sinHalfYaw * sinHalfPitch,
cosHalfYaw * sinHalfPitch,
sinHalfYaw * cosHalfPitch)
At this point I remind you that we started with an assumption about the reference attitude for the quaternion system, and the this result depends on that choice. I also remind you that I made an assumption about the wanted attitude, and that also affects this result.
Finally, I observe that this approach breaks down where the target object is very nearly directly above or directly below the player (corresponding to semiRadius taking a value very near zero) and where the player is very nearly on top of the target (corresponding to hyp taking a value very near zero). There is a non-zero chance of causing a division by zero if you use these formulae exactly as given, so you'll want to think about how to deal with that.)

Check if point belongs to square

I want to check if a point P(x1,y1) belongs , is inside , a square with center C(x,y) and horizontal diagonal r.
Square with the above characteristics:
Function that calculates the distance between two points
float calculate_distance (float x1,float y1,float x2 ,float y2)
{
float distance;
float distance_x = x1-x2;
float distance_y = y1- y2;
distance = sqrt( (distance_x * distance_x) + (distance_y * distance_y));
return distance;
}
You don't need the Euclidian distance between points here.
Just as for a circle (at the origin) you know that x2+y2 is some constant (r2), here you know that |x|+|y| is some constant (r again), which is even simpler. Actually you can interpolate between these shapes by using exponents between 1 and 2.
So to check whether a point (x,y) is inside the diamond (which without loss of generality can be assumed to be centered on the origin), just test
fabsf(x)+fabsf(y) <= r

Finding the angle a vector makes over variable axes

The typical way to find the angle a vector makes from the x axis (assuming the x axis runs left to right, and the y axis runs bottom to top) is:
double vector_angle = atan2( y , x )
However, I want my axes to have their origin at a point on a circle so that the x axis runs from the point on the edge of the circle through the centre of the circle, and the y axis runs tangent to the circle at that point (which would thus be perpendicular to the x axis).
Assumedly the code would still be the same, but now adjusted by a distance k and an angle theta, perhaps:
double y_position = ( y + k ) * theta;
double x_position = ( x + k ) * theta;
double vector_angle = atan2( y_position, x_position );
But I'm not sure about this. This is a generalised problem for a touch-based application where I would like to have a general way to move a sprite (in cocos2d) using swipe motions which is always a constant distance from the center of a circle.
Here, B is the origin of the vector which could be transformed by a rotation theta. For example, if we transformed the circle and point B by 90 degrees, B would be at (4, 0) and the line B->A would be along the axis at 4 (y = 4). I would like to get the angle in node-space of point B, when under transform.
Arctan returns the correct angle for the vector where the "x axis" is the line perpendicular to your tangent.

Resources