turn a line into a rectangle - math

I have a method that draws a line between two points. This works pretty well, but now I want to make this line into a rectangle.
How can I get the points on the left and right side of each of the line points to make it into a rectangle that I can draw?
It is almost as though I need to somehow figure out how to get perpendicular lines programatically....

I'm guessing you basically want fat lines? Lets assume the line is specified by two points (x0, y0) and (x1, y1) we then have:
float dx = x1 - x0; //delta x
float dy = y1 - y0; //delta y
float linelength = sqrtf(dx * dx + dy * dy);
dx /= linelength;
dy /= linelength;
//Ok, (dx, dy) is now a unit vector pointing in the direction of the line
//A perpendicular vector is given by (-dy, dx)
const float thickness = 5.0f; //Some number
const float px = 0.5f * thickness * (-dy); //perpendicular vector with lenght thickness * 0.5
const float py = 0.5f * thickness * dx;
glBegin(GL_QUADS);
glVertex2f(x0 + px, y0 + py);
glVertex2f(x1 + px, y1 + py);
glVertex2f(x1 - px, y1 - py);
glVertex2f(x0 - px, y0 - py);
glEnd();
Since you're using OpenGL ES I guess you'll have to convert the immediate mode rendering (glBegin, glEnd, etc) to glDrawElements. You'll also have to convert the quad into two triangles.
One final thing, I'm a little tired and uncertain if the resulting quad is counterclockwise or clockwise so turn of backface culling when you try this out (glDisable(GL_CULL)).

Since you've asked this question with OpenGL taged I'll assume that you wish for a solution that is close to OpenGL.
As you know you have two points that make up a line. Lets call them x1,y1 and x2, y2
Lets also assume that x1, y1 is the top left point and x2, y2 is the bottom right.
Your 4 points to plot will be [you need to perserve order to make a rectangle with GL_LINES)
Height:y1-y1
Width: x2-x1
(x1, y1)
(x1+width, y1)
(x2, y2)
(x2-width, y2)

drawRect(x,y,w,h)
tl = (x,y)
tr = (x+w, y)
br = (x+w, y+h)
bl = (x, y+h)

Related

Sliding Two Points Along Perpendicular Slope By Distance

For my current project, a user taps 2 locations on the X,Y plane. Once the two points are tapped, the user should then click and drag to extend 2 new points starting at the original 2 locations into a perfect rectangle (90 degree corners).
The math seems super simple, I just can't seem to get the right configuration to slide these two points along the perpendicular slope (by a certain distance).
My current attempt is to find the perpendicular slope and slide it by X distance (the distance the user has dragged), but I'm stuck on translating the perp. slope by distance.
You have points A and B. Difference vector
D = (Dx, Dy) = (Bx - Ax, By - Ay)
Normalized (unit) vector
Len = Sqrt(Dx*Dx + Dy*Dy)
(dx, dy) = (Dx / Len, Dy / Len)
Perpendicular unit vector
(px, py) = (-dy, dx)
Shift by distance L
pL = (px * L, py * L)
So shifted A will have coordinates
(a'x, a'y) = (Ax +/- px * L, Bx +/- py * L)
+ or - for two possible shift directions

How to check if an infinite line intersects a rectangular prism in 3d space?

If I have a line segment defined by two points p1, p2, and then a rectangular prism defined by (x,y,z) (lowest corner point) with length/width/height (l, w, h), how can I check if the line will intersect the prism? And also get the point of intersection if there is one?
Does anyone know?
Thanks
Seems that your prism is axis-aligned box (rectangular parallelepiped).
So use any algorithm intended for line clipping - for example, 3D-version of Liang-Barsky algorithm
In short - make parametric equation for line segment
X = X1 + t * (X2 - X1)
Y = Y1 + t * (Y2 - Y1)
Z = Z1 + t * (Z2 - Z1)
find parameters t for intersection with faces: substitute X = x or X = x + l in equation, find t, check if point with this t lies inside face rectangle

determine whether point lies inside triangle [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
The program needs to read the values of three coordinates
P1(x1,y1)
P2(x2,y2)
P3(x3,y3)
as well as another coordinate P(x,y) and determine whether this point is inside a triangle formed from the 3 point above.
The proper way to do this is by calculating the barycentric coordinates of the fourth point given the three points of your triangle. The formula to compute them is given at the end of the section "Converting to barycentric coordinates", but I hope to provide a less mathematics-intense explanation here.
Assume, for simplicity, that you have a struct, point, that has values x and y. You defined your points as:
point p1(x1, y1);
point p2(x2, y2);
point p3(x3, y3);
point p(x,y); // <-- You are checking if this point lies in the triangle.
Now, the barycentric coordinates, generally called alpha, beta, and gamma, are calculated as follows:
float alpha = ((p2.y - p3.y)*(p.x - p3.x) + (p3.x - p2.x)*(p.y - p3.y)) /
((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y));
float beta = ((p3.y - p1.y)*(p.x - p3.x) + (p1.x - p3.x)*(p.y - p3.y)) /
((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y));
float gamma = 1.0f - alpha - beta;
If all of alpha, beta, and gamma are greater than 0, then the point p lies within the triangle made of points p1, p2, and p3.
The explanation behind this is that a point inside a triangle can be described using the points of the triangle, and three coefficients (one for each point, in the range [0,1]):
p = (alpha)*p1 + (beta)*p2 + (gamma)*p3
Rearranging this function gives you the formula to compute barycentric coordinates, but I feel like the steps to do so might be beyond the scope of the question. They are provided on the Wikipedia page that I linked up top.
It follows that each coefficient must be greater than 0 in order for the point p to lie within the area described by the three points.
Instead of P1, P2 and P3, lets assume the points as A,B and C.
A(10,30)
/ \
/ \
/ \
/ P \ P'
/ \
B (0,0) ----------- C(20,0)
Algorithm :
1) Calculate area of the given triangle, i.e., area of the triangle ABC in the above diagram.
Area A = [ x1(y2 - y3) + x2(y3 - y1) + x3(y1-y2)]/2
2) Calculate area of the triangle PAB. We can use the same formula for this. Let this area be A1.
3) Calculate area of the triangle PBC. Let this area be A2.
4) Calculate area of the triangle PAC. Let this area be A3.
5) If P lies inside the triangle, then A1 + A2 + A3 must be equal to A.
Given below is a program in C:
#include <stdio.h>
#include <stdlib.h>
/* A utility function to calculate area of triangle formed by (x1, y1),
(x2, y2) and (x3, y3) */
float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
/* A function to check whether point P(x, y) lies inside the triangle formed
by A(x1, y1), B(x2, y2) and C(x3, y3) */
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
float A = area (x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
float A1 = area (x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
float A2 = area (x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
float A3 = area (x1, y1, x2, y2, x, y);
/* Check if sum of A1, A2 and A3 is same as A */
return (A == A1 + A2 + A3);
}
/* Driver program to test above function */
int main()
{
/* Let us check whether the point P(10, 15) lies inside the triangle
formed by A(0, 0), B(20, 0) and C(10, 30) */
if (isInside(0, 0, 20, 0, 10, 30, 10, 15))
printf ("Inside");
else
printf ("Not Inside");
return 0;
}
Time : O(1)
Space: O(1)
Take the average of the three given points. This new point P4 will always lie inside the triangle.
Now check if P and P4 lie on the same side of each of the three lines P1P2 P2P3 and P3P1. You can do this by checking the signs of the cross products (P -> P1) x (P -> P2) and (P4 -> P1) x (P4 -> P2) (where P->P1 is the vector from P to P1), and then the other two pairs.

Knowing two points of a rectangle, how can I figure out the other two?

Hey there guys, I'm learning processing.js, and I've come across a mathematical problem, which I can't seem to solve with my limited geometry and trigonometry knowledge or by help of Wikipedia.
I need to draw a rectangle. To draw this rectangle, I need to know the coordinate points of each corner. All I know is x and y for the midpoints of the top and bottom of the box, and the length of all four sides.
There is no guarantee on the orientation of the box.
Any help? This seems like it should be easy, but it is really stumping me.
If this quadrilateral is a rectangle (all four angles are 90 degrees), then it can be solved. (if it could be any quadrilateral, then it is not solvable)
if the points are (x1,y1), and (x2, y2), and if the two points are not perfectly vertical (x1 = x2) or horizontal (y1 = y2), then the slope of one edge of the rectangle is
m1 = (y2-y1) / (x2-x1)
and the slope of the other edge is:
m2 = - 1 / m1
If you know the lengths of the sides, and the midpoints of two opposite sides, then the corrner points are easily determined by adding dx, dy to the midpoints: (if L is length of the sides that the midpoints are on)
dx = Sqrt( L^2 / (1 + m2^2) ) / 2
and
dy = m2 * dx
NOTE: if the points are vertically or horizontally aligned, this technique will not work, although the obvious solution for those degenerative cases is much simpler.
If you know your quadrilateral is a rectangle, then you can use some simple vector maths to find the coordinates of the corners. The knowns are:
(x1,y1) - the coordinate of the midpoint on the top line
(x2,y2) - the coordinate of the midpoint on the bottom line
l1 - the length of the top and bottom lines
l2 - the length of the other two lines
First, we find the vector between the two known points. This vector is parallel to the side lines:
(vx, vy) = (x2 - x1, y2 - y1)
We need to normalize this vector (i.e. make it length 1) so we can use it later as a basis to find our coordinates.
vlen = sqrt(vx*vx + vy*vy)
(v1x, v1y) = (vx / vlen, vy / vlen)
Next, we rotate this vector anticlockwise by 90 degrees. The rotated vector will be parallel to the top and bottom lines. 90 degree rotation turns out to just be swapping the coordinates and negating one of them. You can see this just by trying it out on paper. Or take at look at the equations for 2D rotations and substitute in 90 degrees.
(u1x, u1y) = (-v1y, v1x)
Now we have enough information to find the 'top-left' corner. We simply start at our point (x1, y1) and move back along that side by half the side length:
(p1x, p1y) = (x1 - u1x * l1 / 2, y1 - u1y * l1 / 2)
From here we can find the remaining points just by adding the appropriate multiples of our basis vectors. When implementing this you can obviously speed it up by only calculating each unique multiplication a single time:
(p2x, p2y) = (p1x + u1x * l1, p1y + u1y * l1)
(p3x, p3y) = (p1x + v1x * l2, p1y + v1y * l2)
(p4x, p4y) = (p3x + u1x * l1, p3y + u1y * l1)
function getFirstPoint(x1,y1,x2,y2,l1,l2)
distanceV = {x2 - x1, y2 - y1}
vlen = math.sqrt(distanceV[1]^2 + distanceV[2]^2)
normalized = {distanceV[1] / vlen, distanceV[2] / vlen}
rotated = {-normalized[2], normalized[1]}
p1 = {x1 - rotated[1] * l1 / 2, y1 - rotated[2] * l1 / 2}
p2 = {p1[1] + rotated[1] * l1, p1[2] + rotated[2] * l1}
p3 = {p1[1] + normalized[1] * l2, p1[2] + normalized[2] * l2}
p4 = {p3[1] + rotated[1] * l1, p3[2] + rotated[2] * l1}
points = { p1 , p2 , p3 , p4}
return p1
end
It's definitely a rectangle? Then you know the orientation of the short sides (they're parallel to the line between your points), and hence the orientation of the long sides.
You know the orientation and length of the long sides, and you know their midpoints, so it's straightforward to find the corners from there.
Implementation is left as an exercise to the reader.
This means that there will be two lines parallel to the line between the two points you have. Get the corners by translating the line you have 1/2 the length of the top side in each direction perpendicular to the line you have.
If you know the midpoint for the top, and the length of the top, then you know that the y will stay the same for both top corners, and the x will be the midpoint plus/minus the width of the rectangle. This will also be true for the bottom.
Once you have the four corners, there is no need to worry about the side lengths, as their points are the same as those used for the top and bottom.
midpoint
x,10 10,10 x,10
*--------------------------------------------*
width = 30
mx = midpoint x.
top left corner = (w/2) - mx or 15 - 10
top left corner coords = -5,10
mx = midpoint x.
top right corner = (w/2) + mx or 15 + 10
top left corner coords = 25,10
There's a difference between a "quadrilateral" and a "rectangle".
If you have the midpoint of the top and bottom, and the sides lengths, the rest is simple.
Given:
(x1, y1) -- (top_middle_x, top_middle_y) -- (x2, y1)
(x1, y2) -- (btm_middle_x, btm_middle_y) -- (x2, y2)
and top/bottom length along with right/left length.
x1 = top_middle_x - top/bottom_length / 2;
x2 = x1 + top/bottom_length;
y1 = top_middle_y
y2 = bottom_middle_y
Obviously, that's the simplest case and assuming that the line of (tmx, tmy) (bmx, bmy) is solely along the Y axis.
We'll call that line the "mid line".
The next trick is to take the mid line, and calculate it's rotational offset off the Y axis.
Now, my trig is super rusty.
dx = tmx - bmx, dy = tmy - bmy.
So, the tangent of the angle is dy / dx. The arctangent(dy / dx) is the angle of the line.
From that you can get your orientation.
(mind, there's some games with quadrants, and signs, and stuff to get this right -- but this is the gist of it.)
Once you have the orientation, you can "rotate" the line back to the Y axis. Look up 2D graphics for the math, it's straight forward.
That gets you your normal orientation. Then calculate the rectangles points, in this new normal form, and finally, rotate them back.
Viola. Rectangle.
Other things you can do is "rotate" a line that's half the length of the "top" line to where it's 90 deg of the mid line. So, say you have a mid line that's 45 degrees. You would start this line at tmx, tmy, and rotate this line 135 degrees (90 + 45). That point would be your "top left" corner. Rotate it -45 (45 - 90) to get the "top right" point. Then do something similar with the lower points.
Calculate the angle of the line joining the two midpoints using an arc-tangent function applied to the vector you get between them.
Subtract 90 degrees from that angle to get the direction of the top edge
Starting from the top-center point, move relative (1/2 top width x sin(angle), 1/2 top width x cos(angle)) - that gets the top right corner point.
Continue around the rectangle using the sin and cos of the angles and widths as appropriate
As a test: Check you made it back to the starting point
/* rcx = center x rectangle, rcy = center y rectangle, rw = width rectangle, rh = height rectangle, rr = rotation in radian from the rectangle (around it's center point) */
function toRectObjectFromCenter(rcx, rcy, rw, rh, rr){
var a = {
x: rcx+(Math.sin((rr-degToRad(90))+Math.asin(rh/(Math.sqrt(rh*rh+rw*rw)))) * (Math.sqrt(rh*rh+rw*rw)/2)),
y: rcy-(Math.cos((rr-degToRad(90))+Math.asin(rh/(Math.sqrt(rh*rh+rw*rw)))) * (Math.sqrt(rh*rh+rw*rw)/2))
};
var b = {
x: a.x+Math.cos(rr)*rw,
y: a.y+Math.sin(rr)*rw
};
var c = {
x: b.x+Math.cos(degToRad(radToDeg(rr)+90))*rh,
y: b.y+Math.sin(degToRad(radToDeg(rr)+90))*rh
};
var d = {
x: a.x+Math.cos(degToRad(radToDeg(rr)+90))*rh,
y: a.y+Math.sin(degToRad(radToDeg(rr)+90))*rh
};
return {a:a,b:b,c:c,d:d};
}

algorithm for finding out pixel coordinates on a circumference of a circle

how do i find out pixel value at certain degree on the circumference of a circle if I know the pixel co-ordinates of the center of the circle, radius of the circle ,and perpendicular angle.
Basically, I am trying to draw the hands of a clock at various times ( 1 o clock , 2 o clock etc )
Let h be the hour as a floating point number (h=2.25 would be 02:15, etc.) between 0 and 12. (cX,cY) are the coordinates of the center. hLength and mLength are the lengths of the hour and min hands.
// Hour hand
hAngle = 2.0*Pi*h/12.0; // 0..12 mapped to 0..2*Pi
hX = cX + hLength * sin(hAngle);
hY = cY - hLength * cos(hAngle);
// Min hand
mAngle = 2.0*Pi*h; // 0..1 mapped to 0..2*Pi, etc.
mX = cX + mLength * sin(mAngle);
mY = cY - mLength * cos(mAngle);
Where the centre of the circle is (X0, Y0), the radius is R and the angle with the x-axis is theta:
X1 = (R * cos theta) + X0
and
Y1 = (R * sin theta) + Y0
If (x1,y1) is a point on the circumference and (x,y) is the center, then x1 = x + r * cos(angle) and y1 = y + r * sin(angle)
if center is at x0, y0, and 0,0 iz at bottom-left corner, then 1 o'clock is at x0 + rsin(2π/3), y0+rcos(2π/3).
Draw lines from the center to coordinates computed with sin for the y coordinates and cos for the x coordinates (both multiplied by the length of the hand).
Wikipedia has more information on how sin and cos "work".

Resources