I am trying to correct this C# code which should create an offset line without self intersection. It calculates its offset from probed points(x,y coordinates) and an inputted offset distance. The Y offset component works but the X does not. Any help or insight would be infinitely appreciated.
Here is the section of code that executes this process.
private void OffsetData(double R)
{
double Increment = 0.01;
X2 = (double[])X.Clone(); // copy original
// apply a circle to every measured point and
// push neighbor points out beyond the circle
for (int i = 0; i < Npts; i++)
{
// offset forward
double k = i + Increment;
while (k < Npts - 1)
{
// determine how far away the neighbor is in Y
double dy = (k - i) * DeltaY;
// compute extent outward in X
double d = R * R - dy * dy;
if (d < 0) break; // beyond circel radius - no need to go further
double dx = Math.Sqrt(d);
//interpolate to find X[k] where K is a fraction
int ki = (int)k;
double Xk = X[ki] + (X[ki + 1] - X[ki]) * (k - ki);
// if x value is within circle push out
if (X2[i] < Xk + dx) X2[i] = Xk + dx;
k += Increment;
}
// offset backward
k = i - Increment;
while (k > 0)
{
// determine how far away the neighbor is in Y
double dy = (k - i) * DeltaY;
// compute extent outward in X
double d = R * R - dy * dy;
if (d < 0) break;
// beyond circle radius - no need to go further
double dx = Math.Sqrt(d);
//interpolate to find X[k] where K is a fraction
int ki = (int)k;
double Xk = X[ki] + (X[ki + 1] - X[ki]) * (k - ki);
// if x value is within circle push out
if (X2[i] < Xk + dx) X2[i] = Xk + dx;
k -= Increment;
}
}
}
Related
When i call my funtion with a startingAngle=0 it produce a good shape with the correct size.
Example:
var points = GetPolygonVertices(sides:4, radius:5, center:(5, 5), startingAngle:0), produces:
points[0] = {X = 10 Y = 5}
points[1] = {X = 5 Y = 0}
points[2] = {X = 0 Y = 5}
points[3] = {X = 5 Y = 10}
As observed the side length is 10px, which is correct, but produce a rotated square at 45º from human eye prespective.
To fix this i added a switch/case to offset the startAngle so it will put the square at correct angle for human eye, by rotating 45º. The rotation works, but the shape is no longer a square of 10x10px, instead i lose 1 to 2px from sides:
[0] = {X = 9 Y = 1}
[1] = {X = 1 Y = 1}
[2] = {X = 1 Y = 9}
[3] = {X = 9 Y = 9}
and become worse as radius grow, for example with radius=10:
[0] = {X = 17 Y = 3}
[1] = {X = 3 Y = 3}
[2] = {X = 3 Y = 17}
[3] = {X = 17 Y = 17}
I tried with both floor and ceil instead of round, but it always end in lose 1 or 2px...
Is there a way to improve the function to keep the shape size equal no matter the number of sides and rotation angle?
My function:
public static Point[] GetPolygonVertices(int sides, int radius, Point center, double startingAngle = 0)
{
if (sides < 3)
throw new ArgumentException("Polygons can't have less than 3 sides...", nameof(sides));
// Fix rotation
switch (sides)
{
case 3:
startingAngle += 90;
break;
case 4:
startingAngle += 45;
break;
case 5:
startingAngle += 22.5;
break;
}
var points = new Point[sides];
var step = 360.0 / sides;
int i = 0;
for (var angle = startingAngle; angle < startingAngle + 360.0; angle += step) //go in a circle
{
if (i == sides) break; // Fix floating problem
double radians = angle * Math.PI / 180.0;
points[i++] = new(
(int) Math.Round(Math.Cos(radians) * radius + center.X),
(int) Math.Round(Math.Sin(-radians) * radius + center.Y)
);
}
return points;
}
EDIT: I updated the function to get rid of the switch condition and product shapes in correct orientation for human eye when angle is not given. Still it suffer from same "problem"
public static Point[] GetPolygonVertices(int sides, int radius, Point center, double startingAngle = 0, bool flipHorizontally = false, bool flipVertically = false)
{
if (sides < 3)
throw new ArgumentException("Polygons can't have less than 3 sides...", nameof(sides));
var vertices = new Point[sides];
double deg = 360.0 / sides;//calculate the rotation angle
var rad = Math.PI / 180.0;
var x0 = center.X + radius * Math.Cos(-(((180 - deg) / 2) + startingAngle) * rad);
var y0 = center.Y - radius * Math.Sin(-(((180 - deg) / 2) + startingAngle) * rad);
var x1 = center.X + radius * Math.Cos(-(((180 - deg) / 2) + deg + startingAngle) * rad);
var y1 = center.Y - radius * Math.Sin(-(((180 - deg) / 2) + deg + startingAngle) * rad);
vertices[0] = new(
(int) Math.Round(x0),
(int) Math.Round(y0)
);
vertices[1] = new(
(int) Math.Round(x1),
(int) Math.Round(y1)
);
for (int i = 0; i < sides - 2; i++)
{
double dsinrot = Math.Sin((deg * (i + 1)) * rad);
double dcosrot = Math.Cos((deg * (i + 1)) * rad);
vertices[i + 2] = new(
(int)Math.Round(center.X + dcosrot * (x1 - center.X) - dsinrot * (y1 - center.Y)),
(int)Math.Round(center.Y + dsinrot * (x1 - center.X) + dcosrot * (y1 - center.Y))
);
}
if (flipHorizontally)
{
var startX = center.X - radius;
var endX = center.X + radius;
for (int i = 0; i < sides; i++)
{
vertices[i].X = endX - (vertices[i].X - startX);
}
}
if (flipVertically)
{
var startY = center.Y - radius;
var endY = center.Y + radius;
for (int i = 0; i < sides; i++)
{
vertices[i].Y = endY - (vertices[i].Y - startY);
}
}
return vertices;
}
EDIT 2: From Tim Roberts anwser here the functions to calculate side length from radius and radius from side length, this solve my problem. Thanks!
public static double CalculatePolygonSideLengthFromRadius(double radius, int sides)
{
return 2 * radius * Math.Sin(Math.PI / sides);
}
public static double CalculatePolygonVerticalLengthFromRadius(double radius, int sides)
{
return radius * Math.Cos(Math.PI / sides);
}
public static double CalculatePolygonRadiusFromSideLength(double length, int sides)
{
var theta = 360.0 / sides;
return length / (2 * Math.Cos((90 - theta / 2) * Math.PI / 180.0));
}
Your problem is one of mathematics. You said "As observed, the side length is 10px". It very definitely is not 10px. The distance from (10,5) to (5,0) is sqrt(5*5 + 5*5), which is 7.07. That's exactly what we expect for a square that is inscribed in a circle of radius 5: 5 x sqrt(2).
And that's what the other squares are as well.
FOLLOWUP
As an added bonus, here is a function that returns the radius of the circle that circumscribes a regular polygon with N sides of length L:
import math
def rad(length,nsides):
theta = 360/nsides
r = length / (2 * math.cos( (90-theta/2) * math.pi / 180))
return r
for s in range(3,9):
print(s, rad(10,s))
I am attempting to understand how a 3D mesh has been constructed from a heightmap stored as a one dimensional float array. The only examples I have seen previously have made use of a 2D float array, and I am struggling to wrap my head around the math involved here. Any insight into it would be appreciated. I have commented the code which I do not quite understand yet for your convenience.
Source of code: https://github.com/SebLague/Hydraulic-Erosion
public void ContructMesh () {
Vector3[] verts = new Vector3[mapSize * mapSize];
int[] triangles = new int[(mapSize - 1) * (mapSize - 1) * 6];
int t = 0;
//Note that default mapSize is 255
for (int i = 0; i < mapSize * mapSize; i++) {
//Following code is not properly understood
int x = i % mapSize;
int y = i / mapSize;
int meshMapIndex = y * mapSize + x;
Vector2 percent = new Vector2 (x / (mapSize - 1f), y / (mapSize - 1f));
Vector3 pos = new Vector3 (percent.x * 2 - 1, 0, percent.y * 2 - 1) * scale;
pos += Vector3.up * map[meshMapIndex] * elevationScale; //Elevation scale is 20 by default
verts[meshMapIndex] = pos;
//End of misunderstood code
if (x != mapSize - 1 && y != mapSize - 1) {
t = (y * (mapSize - 1) + x) * 3 * 2;
triangles[t + 0] = meshMapIndex + mapSize;
triangles[t + 1] = meshMapIndex + mapSize + 1;
triangles[t + 2] = meshMapIndex;
triangles[t + 3] = meshMapIndex + mapSize + 1;
triangles[t + 4] = meshMapIndex + 1;
triangles[t + 5] = meshMapIndex;
t += 6;
}
}
Mesh mesh = new Mesh();
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.vertices = verts;
mesh.triangles = triangles;
mesh.RecalculateNormals ();
What specifically do you not understand?
int x = i % mapSize; // Get the x location of the current point
int y = i / mapSize; // Get the y location of the current point
// This should be equal to i, IDK why this is even calculated
int meshMapIndex = y * mapSize + x;
// How far along either direction are we?
Vector2 percent = new Vector2 (x / (mapSize - 1f), y / (mapSize - 1f));
// Make a new vector that scales the X and Y coordinates up.
// The Y coordinate is set to the Z element in this vector
// Presumably because whatever you use to render uses the Y element as "up"
// And the X-Z plane is the horizontal plane
// Also normalize X and Z to lie between -1*scale and 1*scale
Vector3 pos = new Vector3 (percent.x * 2 - 1, 0, percent.y * 2 - 1) * scale;
// Add the value at the current index, times the scale, as the Y element of pos
pos += Vector3.up * map[meshMapIndex] * elevationScale; //Elevation scale is 20 by default
// The X-Z values of pos give you the location of the vertex in the horizontal plane
// The Y value of pos gives you the height
// save the newly calculated pos in verts
verts[meshMapIndex] = pos;
I'm developing a small project, which is a grid of 100 x 100 hexagons.
In the script below, I paint my hexagons with the perlin noise, but the format I want to island does not go away.
I'll leave my code and 2 examples as my map stays and how I wish it to stay.
My island
My Island
As i need
Im Need
int getColor(float x, float z)
{
xTO = (int)x / terrainWidth - 30;
zTO = (int)z / terrainHeight - 30;
float v = Mathf.PerlinNoise((xTO + x + seed) * freq, (zTO + z) * freq);
// v += 0.001f;
float form = formWorld(x, z);
if (v < 0.25f)
{
//water
return 0;
}
else if (v < 0.5f)
{
//sand
return 1;
}
else if (v < 0.75f)
{
//grass
return 2;
}
else
{
//Trees / Forest
MakeNewTree(new Vector3(xx, 0, z * 7.5f));
return 2;
}
}
If you want your image to look more like the second one, the best option is going to be adding a circular gradient which offsets your Perlin Noise.
The easiest way to do this is to measure the distance from the center and combine that with the perlin noise.
Here's some untested code.
int getColor(float x, float z)
{
xTO = (int)x / terrainWidth - 30;
zTO = (int)z / terrainHeight - 30;
float v = Mathf.PerlinNoise((xTO + x + seed) * freq, (zTO + z) * freq);
// v += 0.001f;
v -= CircleOffset(x,z)/2; //Change the two to make the island bigger.
float form = formWorld(x, z);
if (v < 0.25f)
{
//water
return 0;
}
else if (v < 0.5f)
{
//sand
return 1;
}
else if (v < 0.75f)
{
//grass
return 2;
}
else
{
//Trees / Forest
MakeNewTree(new Vector3(xx, 0, z * 7.5f));
return 2;
}
}
float CircleOffset(float x, float y)
{
Vector2 center = new Vector2(terrainWidth/2,terrainHeight/2);
float distance = Mathf.Sqrt((center.x - x)*(center.x - x) + (center.y - y) * (center.y - y));
return distance/terrainWidth;
}
Hope this helps!
I want to rasterize a line using Bresenham's algorihm. My interpolated vertices shouldn't consist of diagonal steps. I did some search on StackOverflow and this topic seems to pretty much the thing I need.
The only problem I have with it is that I need to get the Same result if I changed the order of inputs, I mean if I swap the startPoint and endPoint of line I need to get the same set of interpolated vertices.
//the Method definition
List<Point> plotPoints(Point startPoint, Point endPoint);
//The thing I'm looking for
plotPoints(startPoint, endPoint)==plotPoints(endPoint, startPoint)
The code is almost same as The answer. However I did a bit customization for my purpose:
private float step=0.5;
public static List<Vector3> plotPoints(float x0, float y0, float x1, float y1) {
List<Vector3> plottedPoints = new List<Vector3>();
float dx = Mathf.Abs(x1 - x0), sx = x0 < x1 ? step : -step;
float dy = -Mathf.Abs(y1 - y0), sy = y0 < y1 ? step: -step;
float err = dx + dy, e2; /* error value e_xy */
for (; ; ) { /* loop */
if (x0 == x1 && y0 == y1) break;
plottedPoints.Add(new Vector3(x0,0, y0));
e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; } /* e_xy+e_x > 0 */
else if (e2 <= dx) { err += dx; y0 += sy; } /* e_xy+e_y < 0 */
}
return plottedPoints;
}
As said in the comments, a trick is to normalize the input so that if you swap the endpoints, they will be swapped back automatically.
A possible way is by enforcing that the endpoints are lexicographically ordered (the smallest X first and in case of a tie, the smallest Y).
There is no such problem with the DDA algorithm, which can be formulated explicitly as
X = X0 + (k.DX) rnd D
Y = Y0 + (k.DY) rnd D
where D = max(|DX|, |DY|), rnd is a rounding operation and k goes from 0 to D.
If you swap the endpoints, the deltas change sign and you trade
Y0 + (k.DY) rnd D
for
Y1 + ((D-k).(-DY)) rnd D = Y1 - DY + (k.DY) rnd D = Y0 + (k.DY) rnd D.
This means that the algorithm is naturally "reversible".
For this to be true, the rnd operation must enjoy a translation invariance property, rnd(x+n) = rnd(x)+n, which corresponds to (k.DY) rnd D = floor((k.DY + S) / D) where S is some rounding offset (typically 0 or D>>1).
I have a simulation with multiple circles moving in 2D space, with elastic collisions between them.
I'd like to add an attraction force between particles, so that particles move towards other particles depending on mass, etc. How would I go about this?
My collision management function looks like this:
void manageCollision(Particle particleA, Particle particleB)
{
float distanceX = particleA.Position.X - particleB.Position.X;
float distanceY = particleA.Position.Y - particleB.Position.Y;
double collisionAngle = Math.Atan2(distanceY, distanceX);
double pA_magnitude = Math.Sqrt(particleA.Velocity.X * particleA.Velocity.X + particleA.Velocity.Y * particleA.Velocity.Y);
double pB_magnitude = Math.Sqrt(particleB.Velocity.X * particleB.Velocity.X + particleB.Velocity.Y * particleB.Velocity.Y);
double pA_direction = Math.Atan2(particleA.Velocity.Y, particleA.Velocity.X);
double pB_direction = Math.Atan2(particleB.Velocity.Y, particleB.Velocity.X);
double pA_newVelocityX = pA_magnitude * Math.Cos(pA_direction - collisionAngle);
double pA_newVelocityY = pA_magnitude * Math.Sin(pA_direction - collisionAngle);
double pB_newVelocityX = pB_magnitude * Math.Cos(pB_direction - collisionAngle);
double pB_newVelocityY = pB_magnitude * Math.Sin(pB_direction - collisionAngle);
double pA_finalVelocityX = ((particleA.Mass - particleB.Mass) * pA_newVelocityX + (particleB.Mass + particleB.Mass) * pB_newVelocityX) / (particleA.Mass + particleB.Mass);
double pB_finalVelocityX = ((particleA.Mass + particleA.Mass) * pA_newVelocityX + (particleB.Mass - particleA.Mass) * pB_newVelocityX) / (particleA.Mass + particleB.Mass);
double pA_finalVelocityY = pA_newVelocityY;
double pB_finalVelocityY = pB_newVelocityY;
particleA.Velocity = new Vector2((float)(Math.Cos(collisionAngle) * pA_finalVelocityX + Math.Cos(collisionAngle + Math.PI / 2) * pA_finalVelocityY), (float)(Math.Sin(collisionAngle) * pA_finalVelocityX + Math.Sin(collisionAngle + Math.PI / 2) * pA_finalVelocityY));
particleB.Velocity = new Vector2((float)(Math.Cos(collisionAngle) * pB_finalVelocityX + Math.Cos(collisionAngle + Math.PI / 2) * pB_finalVelocityY), (float)(Math.Sin(collisionAngle) * pB_finalVelocityX + Math.Sin(collisionAngle + Math.PI / 2) * pB_finalVelocityY));
}
Each ball or particle spawns with a random mass and radius.
The function is called within an update type of method, like this:
Vector2 globalGravity = new Vector2(0f, gravityScale / 6000);
for (int i = 0; i < particles.Count(); i++)
{
particles[i].Update((float)updateTimer.Interval, globalGravity);
Vector2 position = particles[i].Position;
Vector2 velocity = particles[i].Velocity;
collisionWallCheck(ref position, ref velocity, particles[i].Radius);
particles[i].Position = position;
particles[i].Velocity = velocity;
Particle pA = particles[i];
for (int k = i + 1; k < particles.Count(); k++)
{
Particle pB = particles[k];
Vector2 delta = pA.Position - pB.Position;
float dist = delta.Length();
if (dist < particles[i].Radius + particles[k].Radius && !particles[i].Colliding && !particles[k].Colliding)
{
particles[i].Colliding = true;
particles[k].Colliding = true;
manageCollision(particles[i], particles[k]);
particles[i].initColorTable(); // Upon collision, change the color
particles[k].initColorTable();
totalCollisions++;
}
else
{
particles[i].Colliding = false;
particles[k].Colliding = false;
}
}
}
I'm storing the initial position, velocity and masses of each ball.
What I apparently need to do, and don't know how to implement, is:
Calculate the magnitude and direction of the gravitational force.
Knowing the force, you can calculate the acceleration of each body.
Knowing the acceleration you can calculate the new velocity.
Knowing the velocity you can calculate the new position.
I'm shaky with the equations for it essentially, and I'd like to start off by making an attraction force between just two balls.
Using Steven's suggestion, this is the new integrated code.
void updateTimer_Tick(object sender, EventArgs e)
{
const double G = 6.67398 * 0.00000000001;
for (int i = 0; i < particles.Count(); i++)
{
double sumX = 0;
double sumY = 0;
Particle pA = particles[i];
for (int k = i + 1; k < particles.Count(); k++)
{
Particle pB = particles[k];
Vector2 delta = pA.Position - pB.Position;
float dist = delta.Length();
if (dist < particles[i].Radius + particles[k].Radius && !particles[i].Colliding && !particles[k].Colliding)
{
particles[i].Colliding = true;
particles[k].Colliding = true;
manageCollision(particles[i], particles[k]);
particles[i].initColorTable();
particles[k].initColorTable();
totalCollisions++;
particles[i].Colliding = false;
particles[k].Colliding = false;
}
else
{
double distanceX = particles[i].Position.X - particles[k].Position.X;
double distanceY = particles[i].Position.Y - particles[k].Position.Y;
double r = Math.Sqrt(Math.Pow(distanceX, 2) + Math.Pow(distanceY, 2));
double force = G * particles[i].Mass * particles[k].Mass / (r * r);
double theta = Math.Tan(distanceY / distanceX);
sumX += force * Math.Cos(theta);
sumY += force * Math.Sin(theta);
particles[i].Colliding = false;
particles[k].Colliding = false;
}
}
double netForce = Math.Sqrt(Math.Pow(sumX, 2) + Math.Pow(sumY, 2));
double a = netForce / particles[i].Mass;
double aTheta = Math.Tan(sumY / sumX);
// Here we get accelerations for X and Y. You can probably figure out velocities from here.
double aX = a * Math.Cos(aTheta);
double aY = a * Math.Sin(aTheta);
Vector2 accel = new Vector2((float)aX, (float)aY);
particles[i].Update((float)updateTimer.Interval, accel);
//particles[i].Update((float)updateTimer.Interval, globalGravity);
Vector2 position = particles[i].Position;
Vector2 velocity = particles[i].Velocity;
collisionWallCheck(ref position, ref velocity, particles[i].Radius);
particles[i].Position = position;
particles[i].Velocity = velocity + accel;
}
Draw();
}
The Update function for the particles is simple, and before it used a global gravity Vector which was 0,0.
public void Update(float timeStep, Vector2 gravity)
{
velocity = velocity + timeStep * gravity;
position = position + timeStep * velocity;
}
I'm now unsure how to deal with the cases of 0.
Start by calculating the force of gravity acting on each object. This is given by
F = Gm1m2/r*r
where m1 and m2 are the masses of two objects, G is the gravitational constant, and r is the distance between the two objects.
Now, r is a vector, so you may want to split this up into separate components - Fx and Fy. You can do this as follows:
Fx = F * cos(theta)
Fy = F * sin(theta)
For each mass, calculate the force of gravity acting on it and every other object. Sum the vectors to get the net force of gravity. (Note - that link is available for your interest, but takes a long time to get to the point). At this point you will have a net force on each object, from which you can calculate acceleration. Here's the code to get to this point:
const double G = 6.67398 * 0.00000000001;
for (int i = 0; i < particles.Count(); i++)
{
double sumX = 0;
double sumY = 0;
for (int j = 0; j < particles.Count(); j++)
{
// Don't add attraction to self
if (i == j)
continue;
double distanceX = particles[i].Position.X - particles[j].Position.X;
double distanceY = particles[i].Position.Y - particles[j].Position.Y;
double r = Math.Sqrt(Math.Pow(distanceX, 2) + Math.Pow(distanceY, 2));
double force = G * particles[i].Mass * particles[j].Mass / (r * r);
double theta = Math.Tan(distanceY / distanceX);
sumX += force * Math.Cos(theta);
sumY += force * Math.Sin(theta);
}
double netForce = Math.Sqrt(Math.Pow(sumX, 2) + Math.Pow(sumY, 2));
double a = netForce / particles[i].Mass;
double aTheta = Math.Tan(sumY / sumX);
// Here we get accelerations for X and Y. You can probably figure out velocities from here.
double aX = a * Math.Cos(aTheta);
double aY = a * Math.Sin(aTheta);
}
NOTES
This doesn't take stuff like 0-values into account - you'll have to clean up this code to deal with special cases before it will run without crashing.
Don't update any positions until you've calculated all the forces, or else you'll be off for later elements in the list.
Another thing worth noting: This algorithm is O(n^2), so if you have more than a few bodies it's going to take a lot of crunching. That's unfortunately just the way it is; if you find a fast way to calculate gravitational attraction for a large number of bodies, you should probably call NASA.
Depending on your coordinate system, you may find the y-vectors getting reversed. This is because Euclidean geometry thinks of positive values of y as "going up" whereas programmers tend to measure y in positive units "going down" from the top of the screen. This can play havoc with your angles and things.
Knowing the position all the balls and their masses, you can calculate the vector of the force felt between any two bodies. Find the vector from ball 'A' to all other balls - 'A' to ball 'B', 'A' to 'C', 'A' to 'D', etc. Then, simple add all of A's vectors up to get a final vector of force acting on A. Repeat for B -> A, B -> C, etc to find B's vector. Do this for all, calculate the new velocity, and adjust the positions for the amount of time between steps.