Plot the centroid of four values on a radar chart - javascript

04/09/15
Update: I know now how to mathematically get the coordinates that I needed. Now the issue is how to code it.
Calculate the centroid of four x,y coordinates
Find the centroid of triangle 1
(x1+x2+x4)/3
(y1+y2+y4)/3
The result will be a coordinate such as (12,10.6). Fractions are possible.
Find the centroid of triangle 2
(x2+x3+x4)/3
(y2+y3+y4)/3
The result will be a coordinate such as (8.3,7.0). Fractions are possibly and should be limited to one digit.
Find the midpoint of the line between the centroids of triangle 1 and triangle 2
(x1+x2)/2
(y1+y2)/2
The result will be a coordinate that represents the centroid of the four original x,y coordinates.
Original post content below here>>
I would like to plot the centroid of four values, which are stored in mysql, on a radar chart (which forms a quadrilateral). The values are all between 0 and 100.
The following sample radar chart shows values of A=80 (18,18) B=30 (13,7) C=40 (6,6) and D=70 (3,17), (x=0 and y=0) in the lower left corner.
I can manually find location of the centroid by creating two triangles, finding the centroid of those, then drawing a line between them, the center point of that line is the centroid. Using this method the centroid of these values is approximately (10,12).
How can this be coded to determine that the plot point is (10,12)?

Related

3D Calculating the Z position of a point in a triangle

To create my three-dimensional engine, I used rasterization: dividing the triangles at their points.
However to carry out the rasterization I convert the points into the 2 dimensions. I then add the dot to a list that will render them later. To rearrange them, however, I need to know the Z position of the points.
So my question is: I have a triangle in 3 dimensions. I then convert it into the 2 dimensions. For each single point, how do I know the Z position, knowing its position of the 2 dimensions?
I tried a weird formula, which based on the distance from the points averaged the Z positions, but it's not working; Can you help me?

Resolve colliding rotated rectangles by moving along vector

I have a javascript program that places rectangles one at a time along walls in a room in counter-clockwise order. I use the coordinates of the rectangles corners for collision detection. It skips the placement of a rectangle if it intersects with another rectangle in the room.
(the room can be any shape so collisions can happen on any side of the rectangle)
However, I want to move the rectangle along the wall until it is no longer colliding instead of skipping it. My current idea is to move the rectangle 1 coordinate at a time in a loop until it no longer intersects, but it does not seem like a good solution for performance.
Is there a way to mathematically know how far in a given direction the rotated rectangle needs to be moved in order to no longer intersect another rotated rectangle?
Consider using of Separating Axis Theorem.
Two boxes (polygons in wide sense) don't intersect, if there exists some axis parallel to some box side, separating boxes, so the lie at distinct sides of this axis.
I've got arbitrary paper with good picture. At pages 16-17 we can see two boxes and some formulas to check for intersection.
You can express T - difference vector between box center as
T.x = pb.x - pa.x + t * dx
T.y = pb.y - pa.y + t * dy
where t is parameter (0 in the starting moment), and (dx, dy) is direction vector for B box moving (along the slanted wall at your picture).
Substituting T components into formula (note I changed > sign to =) we can get equation for parameter t corresponding to moment when Ax becomes separating axis.
| T • Ax | = WA + | ( WB*Bx ) • Ax | + |( HB*By ) • Ax |
If we make the same for other axes (Ay, Bx, By), we get 4 values of t, and the smallest positive one corresponds to minimal diplacement needed to separate the boxes.
Note that right part contains only constant values (for given setup), and we can easily calculate it using abs function, but left part contains variable, so we have to consider two cases (negative and positive dot product T • Ax) to find solution(s). Two possible solutions correspond to "left and right" box separation (anyway, you need smaller positive result)

Representing Points on a Circular Radar Math approach

I am coding a simple app that can show you what friends are around you, but not in the normal map but on a really circular radar like UI:
(http://i.imgur.com/9Epw0Xh.png)
Like this, where i have every users latitude, longitude, and of course my own being the center.
I also measure the distance of every user to position them so the data I know is their lat, longitude and distance to me.
For mathematical reasons let's say the radar is 100 pixels radius, I can distance them by the distance from me using the left or right positioning, but in terms of top or bottom it gets a litte trickier, since i try to convert their latitude - my latitude into a percentual result and then put them on the radar... but I think there are maybe better ways with polar to cartesian coordinates, but im really kinda clueless.
Is there a best approach with these types of interfaces or anything implemented around there?
convert long,lat of all points to cartesian 3D space coordinates
it is conversion spherical -> cartesian 3D space. Math behind is here. After this all points (long,lat,alt) will became (x,y,z) where (0,0,0) is center of the Earth
X axis is lat=0,long=0 [rad]
Y axis is lat=0,long=+PI/2 [rad]
Z axis is North
XY plane is equator
If you want more precision handle Earth as ellipsoid instead of sphere
long = < 0 , +2*PI > [rad]
lat = < -PI/2 , +PI/2 > [rad]
alt = altitude above sea level [m]
Re =6378141.4; [m]
Rp =6356755.0; [m]
R=alt+sqrt( (Re*cos(lat))^2 + (Rp*sin(lat))^2 )
x=R*cos(lat)*cos(long)
y=R*cos(lat)*sin(long)
z=R*sin(lat)
create RADAR local cartesian coordinate system
Basically you need to obtain 3D vectors for X,Y,Z axises. They must be perpendicular to each other and pointing to the right direction from RADAR origin point (P0).
You can use vector multiplication for that because it creates perpendicular vector to its multiplicants. Direction is dependent on the order of multiplicants so experiment a little.
//altitude this one is easy
Z = P0
//north (chose one that is non zero, resp. bigger to avoid accuracy problems)
X = (1,0,0) x Z // old X axis * Altitude
X = (0,1,0) x Z // old Y axis * Altitude
//east is now also easy
Y = X x Z
// now normalize all of them to unit vectors
X = X / |X|
Y = Y / |Y|
Z = Z / |Z|
// and check if they are not negative (X,Y)
// if they are then swap multiplicants or multiply by -1
// do not forget that X is computed by two methods so swap the correct one
here is math behind constructing an 4x4 transform matrix
here you can see on an image difference between homogenous 4x4 and direct 3x3 3D transform matrices and math
convert all points to RADAR coordinate system
just multiply all points by RADAR transform matrix M
Q(i) = P(i)*M
so the points Q(i) are now local to RADAR
(0,0,0) means radar origin (center)
(1,0,0) points to north
(0,1,0) points to east
(0,0,1) points up
so now just multiply all cordinates by RADAR scale
scale = RADAR_radius/RADAR_range;
RADAR_radius is size of you RADAR on screen in pixels or units of coordinates
RADAR_range is the max distance the RADAR biggest circle represents [m]
after this just draw the dot to RADAR (swap x,y because I use X as North not Y) and also you can discard all points that are more distant then range. Also you can add 3D RADAR like in old Elite by adding Z coordinate to vertical axis (or draw an L line)
Hope it helps a little and was not too much confusing...

How to divide an ellipse to equal segments?

This calculates vertex coordinates on ellipse:
function calculateEllipse(a, b, angle)
{
var alpha = angle * (Math.PI / 180) ;
var sinalpha = Math.sin(alpha);
var cosalpha = Math.cos(alpha);
var X = a * cosalpha - b * sinalpha;
var Y = a * cosalpha + b * sinalpha;
}
But how can I calculate the "angle" to get equal or roughly equal circumference segments?
So from what Jozi's said in the OP's comments, what's needed isn't how to subdivide an ellipse into equal segments (which would require a whole bunch of horrible integrals), it's to construct an ellipse from line segments of roughly equal length.
There are a whole pile of ways to do that, but I think the best suited for the OP's purposes would be the concentric circle method, listed on the page as 'the draftman's method'. If you don't mind installing the Mathematica player, there's a neat lil' app here which illustrates it interactively.
The problem with those methods is that the segment lengths are only roughly equal at low eccentricities. If you're dealing in extreme eccentricities, things get a lot more complicated. The simplest solution I can think of is to linearly approximate the length of a line segment within each quadrant, and then solve for the positions of the endpoints in that quadrant exactly.
In detail: this is an ellipse quadrant with parameters a = 5, b = 1:
And this is a plot of the length of the arc subtended by an infinitesimal change in the angle, at each angle:
The x axis is the angle, in radians, and the y axis is the length of the arc that would be subtended by a change in angle of 1 radian. The formula, which can be derived using the equations in the Wikipedia article I just linked, is y = Sqrt(a^2 Sin^2(x) + b^2 Cos^2(x)). The important thing to note though is that the integral of this function - the area under this curve - is the length of the arc in the whole quadrant.
Now, we can approximate it by a straight line:
which has gradient m = (a-b) / (Pi/2) and y intercept c = b. Using simple geometry, we can deduce that the area under the red curve is A = (a+b)*Pi/4.
Using this knowledge, and the knowledge that the area under the curve is the total length of the curve, the problem of constructing an approximation to the ellipse reduces to finding say a midpoint-rule quadrature (other quadratures would work too, but this is the simplest) of the red line such that each rectangle has equal area.
Converting that sentence to an equation, and representing the position of a rectangle in a quadrature by it's left hand boundary x and its width w, we get that:
(v*m)*w^2 + (m*x+c)*w - A/k == 0
where k is the number of pieces we want to use to approximate the quadrant, and v is a weighting function I'll come to shortly. This can be used to construct the quadrature by first setting x0 = 0 and solving for w0, which is then used to set x1 = w0 and solve for w1. Then set x2 = w1, etc etc until you've got all k left-hand boundary points. The k+1th boundary point is obviously Pi/2.
The weighting function v effectively represents where the rectangle crosses the red line. A constant v = 0.5 is equivalent to it crossing in the middle, and gets you this with 10 points:
but you can play around with it to see what better balances the points. Ideally it should stay in the range [0, 1] and the sum of the values you use should be k/2.
If you want an even better approximation without messing around with weighting functions, you could try least-squares fitting a line rather than just fitting it to the endpoints, or you could try fitting a cubic polynomial to the blue curve instead of a linear polynomial. It'll entail solving quartics but if you've a maths package on hand that shouldn't be a problem.
Too long for a comment, so I suppose this has to be an answer ...
Here's a mathematically simple approach to forming a first order approximation. Pick one quadrant. You can generate the data for the other quadrants by reflection in the X and Y axis. Calculate (x,y) for the angle = 0 degrees, 1 degree, ... 90 degrees. Now you want the little lengths joining consecutive points. If (x_n, y_n) are the coordinates at angle = n, then Pythagoras tells us the distance D between points (x_n, y_n) and (x_n+1, y_n+1) is D = sqrt((x_n+1 - x_n)^2 + (y_n+1 - y_n)^2). Use this formula to produce a table of cumulative distances around the ellipse for angles from 0 degrees to 90 degrees. This is the inverse of the function you seek. Of course, you don't have to pick a stepsize of 1 degree; you could use any angle which exactly divides 90 degrees.
If you want to find the angle which corresponds to a perimeter step size of x, find the largest angle n in your table producing a partial perimeter less than or equal to x. The partial perimeter of angle n+1 will be larger than x. Use linear interpolation to find the fractional angle which corresponds to x.
All we are doing is approximating the ellipse with straight line segments and using them instead of the original curve; its a first order approximation. You could do somewhat better by using Simpson's rule or similar instead of linear interpolation.
Yes, you have to calculate the table in advance. But once you have the table, the calculations are easy. If you don't need too much accuracy, this is pretty simple both mathematically and coding-wise.

Could you use Html 5 canvas to calculate the distance you travelled along a river?

My thought was that you could draw a line that traversed the river and then if you knew the total distance of the river you divide the line's pixel length by the distance.
So if your line was 760px and the distance of the river was 20 miles then 760 / 20 = 38px = 1 mile.
Of course if my line was just a straight line or a series of lines this would be fairly simple. However, I would like my line to reflect the contours of the river and as such would be curved in places.
Firstly, is this a good method for plotting distance travelled along a river? If not what would work better (i have a feeling my maths is wrong!).
If this is a good method how would i take into account the curved nature of the line and how this might affect the pixel length of the line?
Calculating the length of a river is similar to calculating the Length of an Arc
.
Even if you draw the river exactly as you want it in an canvas(or in any Raster Image for that matter), and then count the amount of blue pixels, you would only be able to get an approximate answer as close as canvaswidth / riverdistance.
I wouldn't use miles (because its too crude). Use something shorter instead (I'd use meters, but ymmv).
Then just draw a line along the curvature of the river and count the pixels of that line, every pixel represents a given distance. (e.G. one pixel could represent 150 meters)

Categories

Resources