How to determine Scale of Line Graph based on Pixels/Height? - c++

I have a problem due to my terrible math abilities, that I cannot figure out how to scale a graph based on the maximum and minimum values so that the whole graph will fit onto the graph-area (400x420) without parts of it being off the screen (based on a given equation by user).
Let's say I have this code, and it automatically draws squares and then the line graph based on these values. What is the formula (what do I multiply) to scale it so that it fits into the small graphing area?
vector<int> m_x;
vector<int> m_y; // gets automatically filled by user equation or values
int HeightInPixels = 420;// Graphing area size!!
int WidthInPixels = 400;
int best_max_y = GetMaxOfVector(m_y);
int best_min_y = GetMinOfVector(m_y);
m_row = 0;
m_col = 0;
y_magnitude = (HeightInPixels/(best_max_y+best_min_y)); // probably won't work
x_magnitude = (WidthInPixels/(int)m_x.size());
m_col = m_row = best_max_y; // number of vertical/horizontal lines to draw
////x_magnitude = (WidthInPixels/(int)m_x.size())/2; Doesn't work well
////y_magnitude = (HeightInPixels/(int)m_y.size())/2; Doesn't work well
ready = true; // we have values, graph it
Invalidate(); // uses WM_PAINT
////////////////////////////////////////////
/// Construction of Graph layout on WM_PAINT, before painting line graph
///////////////////////////////////////////
CPen pSilver(PS_SOLID, 1, RGB(150, 150, 150) ); // silver
CPen pDarkSilver(PS_SOLID, 2, RGB(120, 120, 120) ); // dark silver
dc.SelectObject( pSilver ); // silver color
CPoint pt( 620, 620 ); // origin
int left_side = 310;
int top_side = 30;
int bottom_side = 450;
int right_side = 710; // create a rectangle border
dc.Rectangle(left_side,top_side,right_side,bottom_side);
int origin = 310;
int xshift = 30;
int yshift = 30;
// draw scaled rows and columns
for(int r = 1; r <= colrow; r++){ // draw rows
pt.x = left_side;
pt.y = (ymagnitude)*r+top_side;
dc.MoveTo( pt );
pt.x = right_side;
dc.LineTo( pt );
for(int c = 1; c <= colrow; c++){
pt.x = left_side+c*(magnitude);
pt.y = top_side;
dc.MoveTo(pt);
pt.y = bottom_side;
dc.LineTo(pt);
} // draw columns
}
// grab the center of the graph on x and y dimension
int top_center = ((right_side-left_side)/2)+left_side;
int bottom_center = ((bottom_side-top_side)/2)+top_side;

You are using ax^2 + bx + c (quadratic equation). You will get list of (X,Y) values inserted by user.
Let us say 5 points you get are
(1,1)
(2,4)
(4,1)
(5,6)
(6,7)
So, here your best_max_y will be 7 and best_min_y will be 1.
Now you have total graph area is
Dx = right_side - left_side //here, 400 (710 - 310)
Dy = bottom_side - top_side //here, 420 (450 - 30)
So, you can calculate x_magnitude and y_magnitude using following equation :
x_magnitude = WidthInPixels / Dx;
y_magnitude = HeightInPixels / Dy;

What I did was to determine how many points I had going in the x and y directions, and then divide that by the x and y dimensions, then divide that by 3, as I wanted each minimum point to be three pixels, so it could be seen.
The trick then is that you have to aggregate the data so that you are showing several points with one point, so it may be the average of them, but that depends on what you are displaying.
Without knowing more about what you are doing it is hard to make a suggestion.
For this part, subtract, don't add:
best_max_y+best_min_y as you want the difference.
The only other thing would be to divide y_magnitude and x_magnitude by 3. That was an arbitrary number I came up with, just so the users could see the points, you may find some other number to work better.

Related

Drawing a circle in SDL 2, but each circle uses CPU a lot

i wrote a code that draw filled circle, but it uses CPU a lot.
The thing is i draw pixel by pixel, first outter circle with radius n the second circle with radius n-1 and so on while n is not equal to 0.
I'm drawing 4 pixel in e cycle, for each circle part. Every part, as i thought, has ~ Pi/(2*R) pixels, but it is not enough and circle fill wrong, so i used Pi/(4*R) and now circle fills normaly.
Deg0 = 0;
Deg90 = M_PI / 2;
DegStep = Deg90 / (R * 4);
CurrDeg = Deg0;
OffsetX = R;
OffsetY = 0;
TmpR = R;
while(TmpR>0 )
{
while(CurrDeg < Deg90)
{
OffsetX = cos(CurrDeg) * TmpR;
OffsetY = sin(CurrDeg) * TmpR;
SDL_RenderDrawPoint(Renderer, CX+(int)OffsetX, CY+(int)OffsetY);
SDL_RenderDrawPoint(Renderer, CX-(int)OffsetY, CY+(int)OffsetX);
SDL_RenderDrawPoint(Renderer, CX-(int)OffsetX, CY-(int)OffsetY);
SDL_RenderDrawPoint(Renderer, CX+(int)OffsetY, CY-(int)OffsetX);
CurrDeg+=DegStep;
}
CurrDeg = Deg0;
TmpR-=1;
}
So, is there any way to improve my realisation?
You could use the circle drawing capabilities of SDL, or you could optimize your own code by not actually using cos and sin. Use lookup tables instead.

Not all of my lines are drawing in sfml vertexArray

So I have been working on a project with a friend but I've hit a dead end with the following code.
// The initial angle (for the first vertex)
double angle = PI / 2;
//double angle=0;
int scale = 220;
int centerX = 300;
int centerY = 250;
// Calculate the location of each vertex
for(int iii = 0; iii < vertices.getVertexCount(); iii++) {
// Adds the vertices to the diagram
vertices[iii].position = sf::Vector2f(centerX + cos(angle) * scale, centerY - sin(angle) * scale);
vertices[iii].color = sf::Color::White;
// Calculates the angle that the next point will be at
angle += q*(TAU / p);
}
// Draws the lines on the diagram
sf::VertexArray lines = sf::VertexArray(sf::Lines, vertices.getVertexCount());
for(int iii = 0; iii < lines.getVertexCount()-1; iii+=2) {
lines[iii] = vertices[iii];
lines[iii+1] = vertices[iii+1];
lines[iii].color = sf::Color(255,(iii)*50,255,255);//sf::Color::White;
lines[iii+1].color = sf::Color(255,(iii+1)*50,255,255);//sf::Color::White;
}
return lines;
The compiler doesn't give any errors but when I run the code exactly half of the lines show up, but only if p is an even number (p is the number of vertices in the polygon.) For example when I try to draw a square p=4 2 lines will show up if I try to draw a pentagon p=5 all of the lines show up.
On a different forum someone suggested adding 0.5f to the coordinates of all vertices to change how openGl rounds. I tried this but it didn't work.
Always provide a screenshot of what you are seeing and a Paint drawing of what you want to achieve
Change
sf::VertexArray lines = sf::VertexArray(sf::Lines, vertices.getVertexCount());
for(int iii = 0; iii < lines.getVertexCount()-1; iii+=2) {
lines[iii] = vertices[iii];
lines[iii+1] = vertices[iii+1];
lines[iii].color = sf::Color(255,(iii)*50,255,255);//sf::Color::White;
lines[iii+1].color = sf::Color(255,(iii+1)*50,255,255);//sf::Color::White;
}
to
sf::VertexArray lines = sf::VertexArray(sf::LinesStrip, vertices.getVertexCount());
for(int iii = 0; iii < lines.getVertexCount(); iii+=1) {
lines[iii] = vertices[iii];
lines[iii].color = sf::Color(255,(iii)*50,255,255);//sf::Color::White;
}
As the primitive type sf::Lines require 2x points than lines you draw. sf::LinesStrip should do the trick in VertexArray.

Optimizing a simple 2D Tile engine (+potential bugfix)

Preface
Yes, there is plenty to cover here... but I'll do my best to keep this as well-organized, informative and straight-to-the-point as I possibly can!
Using the HGE library in C++, I have created a simple tile engine.
And thus far, I have implemented the following designs:
A CTile class, representing a single tile within a CTileLayer, containing row/column information as well as an HGE::hgeQuad (which stores vertex, color and texture information, see here for details).
A CTileLayer class, representing a two-dimensional 'plane' of tiles (which are stored as a one-dimensional array of CTile objects), containing the # of rows/columns, X/Y world-coordinate information, tile pixel width/height information, and the layer's overall width/height in pixels.
A CTileLayer is responsible for rendering any tiles which are either fully or partially visible within the boundaries of a virtual camera 'viewport', and to avoid doing so for any tiles which are outside of this visible range. Upon creation, it pre-calculates all information to be stored within each CTile object, so the core of engine has more room to breathe and can focus strictly on the render loop. Of course, it also handles proper deallocation of each contained tile.
Issues
The problem I am now facing essentially boils down to the following architectural/optimization issues:
In my render loop, even though I am not rendering any tiles which are outside of visible range, I am still looping through all of the tiles, which seems to have a major performance impact for larger tilemaps (i.e., any thing above 100x100 rows/columns # 64x64 tile dimensions still drops the framerate down by 50% or more).
Eventually, I intend to create a fancy tilemap editor to coincide with this engine.
However, since I am storing all two-dimensional information inside one or more 1D arrays, I don't have any idea how possible it would be to implement some sort of rectangular-select & copy/paste feature, without some MAJOR performance hit -- involving looping through every tile twice per frame. And yet if I used 2D arrays, there would be a slightly less but more universal FPS drop!
Bug
As stated before... In my render code for a CTileLayer object, I have optimized which tiles are to be drawn based upon whether or not they are within viewing range. This works great, and for larger maps I noticed only a 3-8 FPS drop (compared to a 100+ FPS drop without this optimization).
But I think I'm calculating this range incorrectly, because after scrolling halfway through the map you can start to see a gap (on the topmost & leftmost sides) where tiles aren't being rendered, as if the clipping range is increasing faster than the camera can move (even though they both move at the same speed).
This gap gradually increases in size the further along into the X & Y axis you go, eventually eating up nearly half of the top & left sides of the screen on a large map.
My render code for this is shown below...
Code
//
// [Allocate]
// For pre-calculating tile information
// - Rows/Columns = Map Dimensions (in tiles)
// - Width/Height = Tile Dimensions (in pixels)
//
void CTileLayer::Allocate(UINT numColumns, UINT numRows, float tileWidth, float tileHeight)
{
m_nColumns = numColumns;
m_nRows = numRows;
float x, y;
UINT column = 0, row = 0;
const ULONG nTiles = m_nColumns * m_nRows;
hgeQuad quad;
m_tileWidth = tileWidth;
m_tileHeight = tileHeight;
m_layerWidth = m_tileWidth * m_nColumns;
m_layerHeight = m_tileHeight * m_nRows;
if(m_tiles != NULL) Free();
m_tiles = new CTile[nTiles];
for(ULONG l = 0; l < nTiles; l++)
{
m_tiles[l] = CTile();
m_tiles[l].column = column;
m_tiles[l].row = row;
x = (float(column) * m_tileWidth) + m_offsetX;
y = (float(row) * m_tileHeight) + m_offsetY;
quad.blend = BLEND_ALPHAADD | BLEND_COLORMUL | BLEND_ZWRITE;
quad.tex = HTEXTURE(nullptr); //Replaced for the sake of brevity (in the engine's code, I used a globally allocated texture array and did some random tile generation here)
for(UINT i = 0; i < 4; i++)
{
quad.v[i].z = 0.5f;
quad.v[i].col = 0xFF7F7F7F;
}
quad.v[0].x = x;
quad.v[0].y = y;
quad.v[0].tx = 0;
quad.v[0].ty = 0;
quad.v[1].x = x + m_tileWidth;
quad.v[1].y = y;
quad.v[1].tx = 1.0;
quad.v[1].ty = 0;
quad.v[2].x = x + m_tileWidth;
quad.v[2].y = y + m_tileHeight;
quad.v[2].tx = 1.0;
quad.v[2].ty = 1.0;
quad.v[3].x = x;
quad.v[3].y = y + m_tileHeight;
quad.v[3].tx = 0;
quad.v[3].ty = 1.0;
memcpy(&m_tiles[l].quad, &quad, sizeof(hgeQuad));
if(++column > m_nColumns - 1) {
column = 0;
row++;
}
}
}
//
// [Render]
// For drawing the entire tile layer
// - X/Y = world position
// - Top/Left = screen 'clipping' position
// - Width/Height = screen 'clipping' dimensions
//
bool CTileLayer::Render(HGE* hge, float cameraX, float cameraY, float cameraTop, float cameraLeft, float cameraWidth, float cameraHeight)
{
// Calculate the current number of tiles
const ULONG nTiles = m_nColumns * m_nRows;
// Calculate min & max X/Y world pixel coordinates
const float scalarX = cameraX / m_layerWidth; // This is how far (from 0 to 1, in world coordinates) along the X-axis we are within the layer
const float scalarY = cameraY / m_layerHeight; // This is how far (from 0 to 1, in world coordinates) along the Y-axis we are within the layer
const float minX = cameraTop + (scalarX * float(m_nColumns) - m_tileWidth); // Leftmost pixel coordinate within the world
const float minY = cameraLeft + (scalarY * float(m_nRows) - m_tileHeight); // Topmost pixel coordinate within the world
const float maxX = minX + cameraWidth + m_tileWidth; // Rightmost pixel coordinate within the world
const float maxY = minY + cameraHeight + m_tileHeight; // Bottommost pixel coordinate within the world
// Loop through all tiles in the map
for(ULONG l = 0; l < nTiles; l++)
{
CTile tile = m_tiles[l];
// Calculate this tile's X/Y world pixel coordinates
float tileX = (float(tile.column) * m_tileWidth) - cameraX;
float tileY = (float(tile.row) * m_tileHeight) - cameraY;
// Check if this tile is within the boundaries of the current camera view
if(tileX > minX && tileY > minY && tileX < maxX && tileY < maxY) {
// It is, so draw it!
hge->Gfx_RenderQuad(&tile.quad, -cameraX, -cameraY);
}
}
return false;
}
//
// [Free]
// Gee, I wonder what this does? lol...
//
void CTileLayer::Free()
{
delete [] m_tiles;
m_tiles = NULL;
}
Questions
What can be done to fix those architectural/optimization issues, without greatly impacting any other rendering optimizations?
Why is that bug occurring? How can it be fixed?
Thank you for your time!
Optimising the iterating of the map is fairly straight forward.
Given a visible rect in world coordinates (left, top, right, bottom) it's fairly trivial to work out the tile positions, simply by dividing by the tile size.
Once you have those tile coordinates (tl, tt, tr, tb) you can very easily calculate the first visible tile in your 1D array. (The way you calculate any tile index from a 2D coordinate is (y*width)+x - remember to make sure the input coordinate is valid first though.) You then just have a double for loop to iterate the visible tiles:
int visiblewidth = tr - tl + 1;
int visibleheight = tb - tt + 1;
for( int rowidx = ( tt * layerwidth ) + tl; visibleheight--; rowidx += layerwidth )
{
for( int tileidx = rowidx, cx = visiblewidth; cx--; tileidx++ )
{
// render m_Tiles[ tileidx ]...
}
}
You can use a similar system for selecting a block of tiles. Just store the selection coordinates and calculate the actual tiles in exactly the same way.
As for your bug, why do you have x, y, left, right, width, height for the camera? Just store camera position (x,y) and calculate the visible rect from the dimensions of your screen/viewport along with any zoom factor you have defined.
This is a pseudo codish example, geometry variables are in 2d vectors. Both the camera object and the tilemap has a center-position and a extent (half size). The math is just the same even if you decide to stick with pure numbers. Even if you don't use center coordinates and extent, perhaps you'll get an idea on the math. All of this code is in the render function, and is rather simplified. Also, this example assume you already got a 2D array -like object that holds the tiles.
So, first a full example, and I'll explain each part further down.
// x and y are counters, sx is a placeholder for x start value as x will
// be in the inner loop and need to be reset each iteration.
// mx and my will be the values x and y will count towards too.
x=0,
y=0,
sx=0,
mx=total_number_of_tiles_on_x_axis,
my=total_number_of_tiles_on_y_axis
// calculate the lowest and highest worldspace values of the cam
min = cam.center - cam.extent
max = cam.center + cam.extent
// subtract with tilemap corners and divide by tilesize to get
// the anount of tiles that is outside of the cameras scoop
floor = Math.floor( min - ( tilemap.center - tilemap.extent ) / tilesize)
ceil = Math.ceil( max - ( tilemap.center + tilemap.extent ) / tilesize)
if(floor.x > 0)
sx+=floor.x
if(floor.y > 0)
y+=floor.y
if(ceil.x < 0)
mx+=ceil.x
if(ceil.y < 0)
my+=ceil.y
for(; y<my; y++)
// x need to be reset each y iteration, start value are stored in sx
for(x=sx; x<mx; x++)
// render tile x in tilelayer y
Explained bit by bit. First thing in the render function, we will use a few variables.
// x and y are counters, sx is a placeholder for x start value as x will
// be in the inner loop and need to be reset each iteration.
// mx and my will be the values x and y will count towards too.
x=0,
y=0,
sx=0,
mx=total_number_of_tiles_on_x_axis,
my=total_number_of_tiles_on_y_axis
To prevent rendering all tiles, you need to provide either a camera-like object or information on where the visible area starts and stops (in worldspace if the scene is movable)
In this example I'm providing a camera object to the render function which has a center and an extent stored as 2d vectors.
// calculate the lowest and highest worldspace values of the cam
min = cam.center - cam.extent
max = cam.center + cam.extent
// subtract with tilemap corners and divide by tilesize to get
// the anount of tiles that is outside of the cameras scoop
floor = Math.floor( min - ( tilemap.center - tilemap.extent ) / tilesize)
ceil = Math.ceil( max - ( tilemap.center + tilemap.extent ) / tilesize)
// floor & ceil is 2D vectors
Now, if floor is higher than 0 or ceil is lower than 0 on any axis, it means that there just as many tiles outside of the camera scoop.
// check if there is any tiles outside to the left or above of camera
if(floor.x > 0)
sx+=floor.x// set start number of sx to amount of tiles outside of camera
if(floor.y > 0)
y+=floor.y // set startnumber of y to amount of tiles outside of camera
// test if there is any tiles outisde to the right or below the camera
if(ceil.x < 0)
mx+=ceil.x // then add the negative value to mx (max x)
if(ceil.y < 0)
my+=ceil.y // then add the negative value to my (max y)
A normal render of the tilemap would go from 0 to number of tiles that axis, this using a loop within a loop to account for both axis. But thanks to the above code x and y will always stick to the space within the border of the camera.
// will loop through only the visible tiles
for(; y<my; y++)
// x need to be reset each y iteration, start value are stored in sx
for(x=sx; x<mx; x++)
// render tile x in tilelayer y
Hope this helps!

How to draw a filled circle?

I'm creating bitmap/bmp files according to the specifications with my C code and I would like to draw simple primitives on my bitmap. The following code shows how I draw a rectangle on my bitmap:
if(curline->type == 1) // draw a rectangle
{
int xstart = curline->x;
int ystart = curline->y;
int width = curline->width + xstart;
int height = curline->height + ystart;
int x = 0;
int y = 0;
for(y = ystart; y < height; y++)
{
for(x = xstart; x < width; x++)
{
arr[x][y].blue = curline->blue;
arr[x][y].green = curline->green;
arr[x][y].red = curline->red;
}
}
printf("rect drawn.\n");
}
...
save_bitmap();
Example output:
So basically I'm setting the red, green and blue values for all pixels within the given x and y field.
Now I'd like to fill a circle by knowing its midpoint and radius. But how do I know which pixels are inside this circle and which pixels ain't? Any help would be appreciated, thanks for reading.
A point lies within the bounds of a circle if the distance from the point to the center of the circle is less than the radius of the circle.
Consider a point (x1,y1) compared to a circle with center (x2,y2) and radius r:
int dx = x2 - x1; // horizontal offset
int dy = y2 - y1; // vertical offset
if ( (dx*dx + dy*dy) <= (r*r) )
{
// set pixel color
}
You can also try the midpoint algorithm, here on wikipedia.

Drawing circles on a diagonal line in C++

I've been working on this for about an hour now and I can't figure out what I'm doing wrong. This is the problem statement for the problem:
Draw a series of circles along one diagonal of a window. The circles
should be different colors and each circle should touch (but not
overlap) the one above and below it. Allow the program user to
determine how many circles are to be drawn.
These are some hints that have been given to me:
You will find the geometry involved in putting geometric elements on
the diagonals easier if you make your window square. Rather than using
getmaxheight() and getmaxwidth(), consider using getmaxheight() for
both dimensions.
Don't forget the Pythagorean theorem when working out distances in
your code such as the length of the diagonal. Keep in mind, though,
that the units on the screen are pixels, so fractions in the
computations are not too useful. This is definitely a place for
integer arithmetic.
Use the number of elements you are going to draw (squares, circles,
etc) to divide up the total length into steps for your loops to work
with.
Use for loops to draw figures when you know how many to draw, and what
size they are to be. Determine the count and size before the loop.
So far this is the code that I have created. Inputting 4 circles only draws 3 on screen, with the third one partially off screen. The circles also do not touch, which makes no sense to me because moving the center of the next circle down and over by the length of the diameter should have to the two circles touching. This is the code I have:
#include <graphics.h>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int foreColor;
int diagLength;
int radius,diameter;
int centerX = 0, centerY = 0;
int numCircles; // number of circles.
int width, height; // screen width and height
cout << "Enter number of circles: ";
cin >> numCircles;
width = getmaxheight();
height = getmaxheight();
initwindow(width, height, "Circles");
diagLength = sqrt((width * width) + (height * height));
diameter = diagLength / numCircles;
radius = diameter / 2;
centerX = radius;
centerY = radius;
for (int i = 1; i <= numCircles; i++)
{
foreColor = i % 16; // 0 <= foreColor <= 15
setcolor(foreColor);
setfillstyle(i % 12, foreColor); // Set fill style
fillellipse(centerX, centerY, radius, radius);
centerX = centerX + diameter;
centerY = centerY + diameter;
}
getch(); // pause for user
closegraph();
}
Here's a diagram of what I think you want:
The basic problem comes down to determining
What the diameter D of each circle is
Where the center of each circle is.
The diameter is easy. First calculate the length L of the diagonal using Pythagoras' theorem, then divide by the desired number of circles N. Of course, if you need the radius just divide again by 2.
L = Sqrt(Width * Width + Height * Height);
D = L / N;
The trick to working out the position of the circle centers is to realise that the X are evenly spaced along the X axis, and same with the Y coordinates - so you can work out the distances I've labelled Dx and Dy really easily using the same division:
Dx = Width / N;
Dy = Height / N;
From there the center of each circle is easily calculated:
for (i = 0; i < N; i++)
{
centerX = (Dx / 2) + i * Dx;
centerY = (Dy / 2) + i * Dy;
/* Draw the circle at (centerX, centerY) with diameter D */
}
That's all there is to it!
By the way, if you were wondering why your code was drawing circles further apart than they should be, the reason is because you were adding D to centerX and centerY rather than Dx and Dy.