Check if point belongs to square - c

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

Related

How to calculate the distance between two points in C

I'm stuck on a problem where I'm suppose to create a function to calculate the distance between two points. This is the code we were given in class:
typedef struct Point3D {
double x;
double y;
double z;
} point3d_t;
// Structure for a triangle in 3d
typedef struct Triangle3D {
point3d_t pts[3]; // Lines between points implicit
} triangle3d_t;
// Distance between two points
double distance(point3d_t *p1, point3d_t *p2){
}
Initially I thought that the code in double distance was going to be the following, but I couldn't compile:
distance = (sqrt((p2-p1)*(p2-p1)));
Anyone what should be in double distance?
Getting a distance in 3D space is not much different than in 2D space:
you have 3 vectors, dx, dy, dz. The distance is sqrt(dx^2 + dy^2 + dz^2)
Your code didn't compile because it doesn't balance parenthesis, but it is also incorrect as it only accounts for 2 dimensions and multiplies instead of adds.
For you code, you need to do a simple calculation to get dx, dy, dz:
double distance(point3d_t *p1, point3d_t *p2){
double dx,dy,dz;
dx = p2->x - p1->x;
dy = p2->y - p1->y;
dz = p2->z - p1->z;
return sqrt(dx*dx + dy*dy + dz*dz);
}
Note, sign doesn't matter on our deltas, since they get squared and will always be positive.
For a quick proof of the distance formula, you start with Pythagorean theorem, and then realize that any two vectors (say, dx and dy) form a right triangle, with sqrt(dx^2 + dy^2) as the length of hypotenuse. The hypotenuse forms another right triangle with dz, so applying pythagorean theorem again, we get:
sqrt(sqrt(dx^2 + dy^2) ^ 2 + dz^2)
which simplifies to:
sqrt( dx^2 + dy^2 + dz^2 )

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.)

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.

Doubts in converting spherical coordinates

I'm trying to convert spherical coordinates (namely latitude and longitude from a GPS device) into Cartesian coordinates. I'm following this simple conversion derived from the polar coordinates conversion equations.
Then I'm calculating the distance between the two point applying the euclidean distance but the value I'm finding is not always the same as the distance I can calculate using the haversine formula. In particular I'm noticing that given different longitudes but same latitudes leads to the same distances computed by the two algorithms, whereas having the same longitude and changing the latitude carries different values.
Here is the C code I am using:
double ComputeDistance(double lat1,double lon1, double lat2, double lon2)
{
double dlon, dlat, a, c;
dlon = lon2- lon1;
dlat = lat2 - lat1;
a = pow(sin(dlat/2),2) + cos(lat1) * cos(lat2) * pow(sin(dlon/2),2);
c = 2 * atan2(sqrt(a), sqrt(1-a));
return 6378140 * c; /* 6378140 is the radius of the Earth in meters*/
}
int main (int argc, const char * argv[]) {
double lat1 = 41.788251028649575;
double lat2 = 41.788251028649575;
double long1 = -118.1457209154;
double long2 = -118.1407209154;//just ~10 meters distant
lat1 = DEGREES_TO_RADIANS(lat1);
lat2 = DEGREES_TO_RADIANS(lat2);
long1 = DEGREES_TO_RADIANS(long1);
long2 = DEGREES_TO_RADIANS(long2);
//transform in cartesian coordinates
double x = 6378140 * cos(lat1) * cos(long1);
double y = 6378140 * cos(lat1) * sin(long1);
double x2 = 6378140 * cos(lat2) * cos(long2);
double y2 = 6378140 * cos(lat2) * sin(long2);
double dist = sqrt(pow(x2 - x, 2) + pow(y2 - y, 2));
printf("DIST %lf\n", dist);
printf("NDIST %lf\n", ComputeDistance(lat1, long1, lat2, long2));
return 0;
}
Am I doing something incorrect or there is some math behind it I am not seeing (and maybe ask this on Mathoverflow boards?). UPDATE It is not necessary to cross boards, as someone correctly pointed this conversion is not meaningful for computing the exact distance between two points (the distance between the two poles is zero). So I am reformulating it as: why at small deltas (0.0001 which corresponds to 10 mts more or less) of latitudes the distance appear to be so different from the haversine formula (20-25%)?
UPDATE 2:
As Oli Charlesworth pointed out, not considering the z axis makes this conversion a projection that does not mind the north-south difference. This is also the cause of the difference in deltas I was pointing out. In fact, in the correct transform the z is related to the latitude and if you consider it , then compute the euclidean distance between the two points (in a 3d space now), both latitude and longitude will lead to a good approximation for small deltas.
For Example for a degree of latitude the error is ~ 1.41 meters.
From this, there is no 2D map projection where distance is preserved. Calculating the distance from the 2D projection of points is useless.

Intersection of two lines defined in (rho/theta ) parameterization

Have created a c++ implementation of the Hough transform for detecting lines in images. Found lines are represented using rho, theta, as described on wikipedia:
"The parameter r represents the distance between the line and the origin, while θ is the angle of the vector from the origin to this closest point "
How can i find the intersection point in x, y space for two lines described using r, θ?
For reference here are my current functions for converting in and out of hough space:
//get 'r' (length of a line from pole (corner, 0,0, distance from center) perpendicular to a line intersecting point x,y at a given angle) given the point and the angle (in radians)
inline float point2Hough(int x, int y, float theta) {
return((((float)x)*cosf(theta))+((float)y)*sinf(theta));
}
//get point y for a line at angle theta with a distance from the pole of r intersecting x? bad explanation! >_<
inline float hough2Point(int x, int r, float theta) {
float y;
if(theta!=0) {
y=(-cosf(theta)/sinf(theta))*x+((float)r/sinf(theta));
} else {
y=(float)r; //wth theta may == 0?!
}
return(y);
}
sorry in advance if this is something obvious..
Looking at the Wikipedia page, I see that the equation of a straight line corresponding to a given given r, θ pair is
r = x cosθ + y sinθ
Thus, if I understand, given two pairs r1, θ1 and r2, θ2, to find the intersection you must solve for the unknowns x,y the following linear 2x2 system:
x cos θ1 + y sin θ1 = r1
x cos θ2 + y sin θ2 = r2
that is AX = b, where
A = [cos θ1 sin θ1] b = |r1| X = |x|
[cos θ2 sin θ2] |r2| |y|
Had never encountered matrix maths before, so took a bit of research and experimentation to work out the proceedure for Fredrico's answer. Thanks, needed to learn about matrices anyway. ^^
function to find where two parameterized lines intersect:
//Find point (x,y) where two parameterized lines intersect :p Returns 0 if lines are parallel
int parametricIntersect(float r1, float t1, float r2, float t2, int *x, int *y) {
float ct1=cosf(t1); //matrix element a
float st1=sinf(t1); //b
float ct2=cosf(t2); //c
float st2=sinf(t2); //d
float d=ct1*st2-st1*ct2; //determinative (rearranged matrix for inverse)
if(d!=0.0f) {
*x=(int)((st2*r1-st1*r2)/d);
*y=(int)((-ct2*r1+ct1*r2)/d);
return(1);
} else { //lines are parallel and will NEVER intersect!
return(0);
}
}

Resources