How can I make this list work - c++

I'm trying to make a simple game by just using hexagons. However the std::vector isn't working for some reason. It should be creating a list but its just NULL? What its origionaly suppost to do is add trapazoids to create a track. From that point on its mostly camera moving. I am current using a add on called SFML and its mainly used to create images like openGL.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <SFML\Graphics.hpp>
#include <iostream>
///////////////////////////////////////////////////////////////////////////////////////////////////////////
using namespace sf;
int width = 1024;
int height = 768;
char title[] = "Racing";
int roadW = 2000;
int segL = 200; //segment length
float camD = 0.84; //camera debth
int update(RenderWindow &w);
void drawQuad(RenderWindow &w, Color c, int x1, int y1, int w1, int x2, int y2, int w2);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Line
{
float x, y, z; //segment length
float X, Y, W; //screen cordinates
float scale;
Line() { x = y = z = 0; }
//from world to screen coordinates
void project(int camx, int camy, int camz)
{
scale = camD / (z - camz);
X = (1 + scale*(x - camx))*width / 2;
Y = (1 - scale*(y - camx))*height / 2;
W = scale * roadW * width / 2;
}
};
std::vector<Line> lines; //main track
int N = lines.size();
///////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
std::cout << "Starting up... \n";
std::cout << "Creating RenderWindow...(VideoMode(" << width << "," << height << "), " << title << "\n";
RenderWindow window(VideoMode(width, height), title);
window.setFramerateLimit(60);
std::cout << "Creating std::vector<Lines> lines... \n";
for (int i = 0; i < 1600; i++)
{
Line line;
line.z = i*segL;
lines.push_back(line);
}
std::cout << "Total Length[" << N << "]\n";
std::cout << "\nRunning...\n";
while (window.isOpen())
{
if (update(window) != 0) return 0;
}
return 0;
}
int update(RenderWindow &w)
{
///│LOGIC////
///└EVENTS///
Event e;
while (w.pollEvent(e))
{
if (e.type == Event::Closed) return 1;
}
///│RENDER///
///├CLEAR////
///├ROAD/////
///└CLEAR////
w.clear();
for (int n = 0; n < 300; n++)
{
Line &l = lines[n%N];
l.project(0, 1500, 0);
Color grass = (n / 3) % 2 ? Color(16, 200, 16) : Color(0, 154, 0);
Color rumble = (n / 3) % 2 ? Color(255, 255, 2555) : Color(0, 0, 0);
Color road = (n / 3) % 2 ? Color(107, 107, 107) : Color(105, 105, 105);
Line p = lines[(n - 1) % N];
drawQuad(w, grass, 0, p.Y, width, 0, l.Y, width);
drawQuad(w, rumble, p.X, p.Y, p.W*1.2, l.X, l.Y, l.W*1.2);
drawQuad(w, road, p.X, p.Y, p.W, l.X, l.Y, l.W);
}
w.display();
return 0;
}
void drawQuad(RenderWindow &w, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
{
ConvexShape shape(4);
shape.setFillColor(c);
shape.setPoint(0, Vector2f(x1 - w1, y1));
shape.setPoint(1, Vector2f(x2 - w2, y2));
shape.setPoint(2, Vector2f(x2 + w2, y2));
shape.setPoint(3, Vector2f(x1 + w1, y1));
w.draw(shape);
}
Thanks
-Logan

Apparently, N stands for zero because in the beginning of the code it gets the number of lines not whenever you call it refreshes!

Related

Im trying to figure out why my squares cant match up properly can anyone help me figure it out

I'm currently stuck because the program runs perfectly fine but when I try to eat the food it doesn't work because the food is in a weird position. What I mean by weird position is that when I go over it with the snake it doesn't register.
At first, I thought it was because I was getting a decimal so I tried to put it into an int, but apparently, that did not work.
Snake game, SDL, c++
#include <SDL.h>
#include <SDL_keycode.h>
#include <stdio.h>
#include <iostream>
using namespace std;
struct Food
{
int Height;
int Width;
int x_Pos;
int y_Pos;
void move()
{
int x_Pos = rand() % 400 + 40;//random pos
int y_Pos = rand() % 400 + 40;
}
void draw(SDL_Renderer* renderer)
{
SDL_Rect r{ x_Pos, y_Pos, 20, 20 };
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 0);
SDL_RenderFillRect(renderer, &r);
}
};
struct v2
{
int x, y;
};
v2 operator+ (const v2& a, const v2& b)
{
return v2{ a.x + b.x, a.y + b.y };
}
void operator+= (v2& a, const v2& b)
{
a.x += b.x;
a.y += b.y;
}
struct Snake
{
int Height;
int Width;
v2 pos;
v2 vel;
int vX, vY;
uint32_t accumulator;
void update(uint32_t delta_time, Food& food)
{
accumulator += delta_time;
if (accumulator > 50)// update every 50 ms
{
accumulator = 0;
pos.x += vel.x;
pos.y += vel.y;
if (pos.x == food.x_Pos && pos.y == food.y_Pos)
{
food.move();
}
}
}
void draw(SDL_Renderer* renderer)
{
SDL_Rect r{ pos.x, pos.y, 20, 20 };
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 0);
SDL_RenderFillRect(renderer, &r);
}
};
bool isRunning = true;
//Screen dimension constants
const int SCREEN_WIDTH = 700;
const int SCREEN_HEIGHT = 700;
void setup_Window(int width, int height);
void input(SDL_Renderer* renderer);
void create_Rect(SDL_Renderer* &renderer, int x, int y, int w, int h, int colorRed, int colorGreen, int colorBlue, int colorA);
int main(int argc, char** argv)
{
srand(time(NULL));
int score = 0;
setup_Window(SCREEN_WIDTH, SCREEN_HEIGHT);
return 0;
}
void Calc()
{
}
void setup_Window(int width, int height)
{
if (SDL_Init(SDL_INIT_VIDEO) == 0)
{
std::cout << "Subsystems Initialised!..." << std::endl;
//The window we'll be rendering to
SDL_Window* window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN);
// Setup renderer
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
input(renderer);
}
}
void create_Rect(SDL_Renderer* &renderer, int x, int y, int w, int h, int colorRed, int colorGreen, int colorBlue, int colorA)
{
// Creat a rect at pos ( 50, 50 ) that's 50 pixels wide and 50 pixels high.
SDL_Rect r;
r.x = x;//615
r.y = y;//0
r.w = w;//25
r.h = h;//480
// x = up and down
// y = left and right
// Set render color to blue ( rect will be rendered in this color )
SDL_SetRenderDrawColor(renderer, colorRed, colorGreen, colorBlue, colorA);
// Render rect
SDL_RenderFillRect(renderer, &r);
// Render the rect to the screen
SDL_RenderPresent(renderer);
}
void input(SDL_Renderer* renderer)
{
uint32_t current_Time = 0, previous_Time, delta_Time;
SDL_Event event;
int rando1 = rand() % 400 + 40;
int rando2 = rand() % 400 + 40;
int rando3 = rand() % 400 + 40;
int rando4 = rand() % 400 + 40;
Snake snake_Body = {};// stuct for Snake object
snake_Body.pos.x = rando1;//random pos
snake_Body.pos.y = rando2;
Food food = {}; // stuct for food object
food.move();
food.x_Pos = SCREEN_WIDTH/2;//random pos
food.y_Pos = SCREEN_HEIGHT/2;
while (isRunning)
{
previous_Time = current_Time;
current_Time = SDL_GetTicks();
delta_Time = current_Time - previous_Time;
// Set render color to black ( rect will be rendered in this color )
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
/* Clear the entire screen to our selected color. */
SDL_RenderClear(renderer);
create_Rect(renderer, 670, 0, 30, 700, 0, 255, 255, 255);// right rectangle
create_Rect(renderer, 1, 0, 30, 700, 0, 255, 255, 255);// left rectangle
create_Rect(renderer, 30, 1, 700, 30, 0, 255, 255, 255);// top rectangle
create_Rect(renderer, 1, 670, 700, 30, 0, 255, 255, 255);// Bottom rectangle
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
isRunning = false;
}
if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
{
snake_Body.vel.y = 0;
snake_Body.vel.x = -15;
cout << "Crouiser1" << endl;
break;
}
case SDLK_UP:
{
snake_Body.vel.y = -15;
snake_Body.vel.x = 0;
cout << "Crouiser2" << endl;
break;
}
case SDLK_RIGHT:
{
snake_Body.vel.y = 0;
snake_Body.vel.x = 15;
cout << "Crouiser3" << endl;
break;
}
case SDLK_DOWN:
{
snake_Body.vel.y = 15;
snake_Body.vel.x = 0;
cout << "Crouiser4" << endl;
break;
}
case SDLK_ESCAPE:
{
isRunning = false;
break;
}
default:
{
break;
}
}
}
}
snake_Body.update(delta_Time, food);
snake_Body.draw(renderer);
food.draw(renderer);
SDL_RenderPresent(renderer);
SDL_Delay(100);
}
}
The collision-check in your update-function only checks if the upper left pixel of your Snake-rectangle overlaps with the upper left pixel of your Food-Rectangle.
To solve your problem, you need to implement a proper collision-check.
This code works for me:
bool CollisionCheck(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2)
{
//x-coordinate of square 1 is positioned after x + width of square 2
bool one = x1 > (x2 + w2);
//x-coordinate of square 2 is positioned after x + width of square 1
bool two = (x1 + w1) < x2;
//y-coordinate of square 1 is positioned below y + hight of square 2
bool three = y1 > (y2 + h2);
//y-coordinate of square 2 is positioned below y + hight of square 1
bool four = (y1 + h1) < y2;
if (one || two || three || four)
{
//If one of the above rules apply, there is NO COLLISION
return false;
}
//If none of the above rules apply, there is a collision
return true;
}

C++ Sandbox Game Low Performance Difficulty

I started Learning C++ yesterday And In that time i was rewriting my java "Falling Sand" Sandbox Game code in C++ using SFML (bit simplified since i don't know C++). but Performance in C++ was much worse in than java, what could be the reason for it, I Know this is very unfocused question, but my code is simple, i probably have a newbie mistakes which should be easy to correct.
#include <SFML/Graphics.hpp>
#include <iostream>
sf::Clock sclock;
const int WIDTH = 1440, HEIGHT = 960;
const char Blank = 0, Sand = 1, Water = 2;
const char* title = "Sandbox Simulation";
char map[WIDTH*HEIGHT];
sf::Vector2i mousePos;
int dist(int x1, int x2, int y1, int y2) {
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
int localBrushSize = 48;
short halfBrush = (short)floor(localBrushSize / 2);
char chosen = Sand;
void place() {
int randY = 0;
int randX = 0;
randX = randY = 1;
for (int y = mousePos.y - halfBrush; y <= mousePos.y + halfBrush; y += randY) {
for (int x = mousePos.x - halfBrush; x <= mousePos.x + halfBrush; x += randX) {
int I = x + y * WIDTH;
int distance = dist(mousePos.x, x, mousePos.y, y);
if (distance < halfBrush && I > 0) {
map[I] = chosen;
}
}
}
}
float Delta_Time() {
return sclock.restart().asSeconds();
}
int main() {
map[11111] = 2;
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), title);
sf::Event evnt;
sf::RectangleShape pixel(sf::Vector2f(1.0f, 1.0f));
window.clear();
while (window.isOpen()) {
while (window.pollEvent(evnt)) {
switch (evnt.type) {
case sf::Event::Closed:
window.close();
break;
}
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
mousePos = sf::Mouse::getPosition(window);
place();
}
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int I = x + y * WIDTH;
switch (map[I]) {
case Sand:
pixel.setPosition(x, y);
pixel.setFillColor(sf::Color::Yellow);
window.draw(pixel);
break;
case Water:
pixel.setPosition(x, y);
pixel.setFillColor(sf::Color::Cyan);
window.draw(pixel);
break;
}
}
}
window.display();
}
return 0;
}
You might be able to make a cached / "framebuffer" like this
TOTALLY untested concept code. WIDTH/HEIGHT might be mixed up, endianess is not OK, etc.
sf::Image image;
sf:Image.create(WIDTH, HEIGHT, sf::Color(0, 0, 0));
sf::Sprite sprite;
std::array<sf::Uint8, WIDTH * HEIGHT * 4> pixels; // you can reuse this. The 4 is the size of RGBA
...
for(int y = 0; y < HEIGHT; y++) {
for(int x = 0; x < WIDTH; x++) {
int offset = (x + y * WIDTH) * 4;
pixels[offset] = sf::Color::Yellow.toInteger(); // in case BIG/Litte endian confusion you might have to do the below.
//pixels[offset + 0 ] = 255; // R?
//pixels[offset + 1 ] = 255; // G?
//pixels[offset + 2 ] = 255; // B?
//pixels[offset + 3 ] = 255; // A?
}
}
image.LoadFromPixels(WIDTH, HEIGHT, pixels);
sprite.SetImage(image);
window.Draw(sprite);
window.Display();

I am trying to display Worley Noise, does anyone understand why the output looks like this? Using SFML 2.5.1

I am trying to make a Worley noise generator based off of the tutorial by The Coding Train here
https://thecodingtrain.com/challenges/coding-in-the-cabana/004-worley-noise.html.
But running the program gives me an output like this:
Rather than
The output of std::cout << closest << "||" << dist << '\n'; looks like this:
1||50
1||51
1||51
1||52
1||53
1||54
1||55
1||34
1||34
1||34
1||34
1||34
1||34
1||34
1||34
1||34
1||34
1||34
1||35
1||35
1||35
1||36
1||36
1||36
or
0||23
0||23
0||23
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||22
0||23
#include <stdio.h>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <random>
#include <time.h>
#include <math.h>
// Gets the distance between two points
int pythagor(int x, int y, int x2, int y2)
{
int xDist = abs(x2 - x);
int yDist = abs(y2 - y);
//std::cout << sqrt((xDist * xDist) + (yDist * yDist)) << "|";
return sqrt((xDist * xDist) + (yDist * yDist));
}
// Finds the closest point.
int sort(sf::Vertex points[32], int x, int y)
{
int start[32];
for (int i = 0; i < 32; i++)
{
start[i] = i;
}
for (int i = 1; i < 33; i++)
{
int a = start[i-1];
int b = start[i];
sf::Vector2f pos = points[i-1].position;
sf::Vector2f pos2 = points[i].position;
int dist1 = pythagor(x, y, pos.x, pos.y);
int dist2 = pythagor(x, y, pos2.x, pos2.y);
if (dist1 > dist2)
{
start[i-1] = b;
start[i] = a;
}
//std::cout << dist1 << "|" << dist2 << "|" << start[i-1] << "|" << start[i] << '\n' ;
}
return start[0];
}
int main(int argc, char const *argv[])
{
// Variables.
int pointRes = 32;
int xRes = 1000, yRes = 1000;
// Classes.
sf::RenderWindow window(sf::VideoMode(xRes, yRes), "Whorley noise!");
// Shapes
sf::Vertex points[pointRes];
sf::VertexArray points2(sf::Points, xRes*yRes);
// Random number generator.
std::mt19937 gen((unsigned) time(NULL)); // Establish Seed.
std::uniform_int_distribution<> distrX(0, xRes); // Creates A Range Usabele By Gen On The X Axis.
std::uniform_int_distribution<> distrY(0, yRes); // Creates A Range Usabele By Gen On The X Axis.
// Generates initial points.
for (int i = 0; i < pointRes; i++)
{
sf::Vector2f pos;
pos.x = distrX(gen);
pos.y = distrY(gen);
points[i].position = sf::Vector2f(pos);
//std::cout << pos.x << "|" << pos.y << "|" << i << '\n';
}
// Generates pixels.
for (int i = 0; i < xRes-1; i++)
{
for (int o = 0; o < yRes-1; o++)
{
sf::Vector2f pPos = sf::Vector2f(i, o);
points2[((i+1) * yRes) - o].position = pPos;
int closest = sort(points, i, o);
int dist = pythagor(i, o, points[closest].position.x, points[closest].position.y);
points2[(i * o) + o].color = sf::Color(dist, dist, dist);
//std::cout << closest << "||" << dist << '\n';
}
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
window.clear();
window.draw(points2);
window.display();
}
return 0;
}
Reference Code (Processing)
// Worley Noise
// Coding in the Cabana
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/CodingInTheCabana/004-worley-noise.html
// https://youtu.be/4066MndcyCk
// p5 port: https://editor.p5js.org/codingtrain/sketches/QsiCWVczZ
PVector[] points = new PVector[100];
void setup() {
size(400, 400);
for (int i = 0; i < points.length; i++) {
points[i] = new PVector(random(width), random(height), random(width));
}
}
void draw() {
loadPixels();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
float[] distances = new float[points.length];
for (int i = 0; i < points.length; i++) {
PVector v = points[i];
float z = frameCount % width;
float d = dist(x, y, z, v.x, v.y, v.z);
distances[i] = d;
}
float[] sorted = sort(distances);
float r = map(sorted[0], 0, 150, 0, 255);
float g = map(sorted[1], 0, 50, 255, 0);
float b = map(sorted[2], 0, 200, 255, 0);
int index = x + y * width;
pixels[index] = color(r, g, b);
}
}
updatePixels();
//noLoop();
//for (PVector v : points) {
// stroke(0, 255, 0);
// strokeWeight(8);
// point(v.x, v.y);
// //v.x += random(-1, 1);
// //v.y += random(-1, 1);
//}
}

How to fix vertical artifact lines in a vertex array in SFML, WITH pixel perfect zoom/move?

I have been working on a 2D top-down game solely in SFML and C++, that has a tilemap. I cannot rid the tilemap of vertical line artifacts when zooming in and out or moving the render view at different zoom levels. I attached an image below of the problem; circled in red.
[edit]
There are a lot of factors that make this bug inconsistent.
If I use a tile_atlas from only one tile, there is no artifacts. If I map each texture to a tile a.k.a not using vertex arrays; I did not see any artifacts but it is anywhere from 10x to 15x slower with the same number of tiles on the screen. I have tried finding zoom levels that don't cause artifacts, and there are some. but the levels are almost random and makes zoom in and out, not smooth and choppy.
I have tried numerous tutorials and forum "fixes" that have not completely worked. I have completely rewrote the underlying tile engine 4 separate times to no avail.
https://en.sfml-dev.org/forums/index.php?topic=15747.0
topic=14504
topic=5952
topic=13637.15
https://www.sfml-dev.org/tutorials/2.5/graphics-view.php
https://www.binpress.com/creating-city-building-game-with-sfml/
https://www.sfml-dev.org/tutorials/2.5/graphics-vertex-array.php
[edit]
I have read the Terreria scaling issue, the fix to make extra large textures then scale, or multiple textures, one for each zoom level. seem exhaustive. I am looking for a programmatic way of achieving the scaling correctly.
This is post is my last attempt to fix the code, otherwise I will need to change languages.
I believe the main issue comes from the zoom in/out functions of the program.
I have tried many, variations/attempt to get this to work +0.5f offset,+0.375f offset, not pixel perfect
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
{
float zoom_in = 0.995f;
float nz = last_sq * zoom_in;
nz = std::floor(nz);
float now = nz / last_sq;
if (nz <= 10)
continue;
last_sq = nz;
std::cout << now << std::endl;
cam.zoom(now);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
cam.move(0.f, -0.02f);
float x = cam.getCenter().x;
float y = cam.getCenter().y;
x = std::floor(x);
y = std::floor(y);
//std::cout << "x: " << x << "\ty: " << y << std::endl;
cam.setCenter(x, y);
}
Here is the entire code.
main.cpp
#include "chunk_map.h"
#include "tile_atlas.h"
#include <vector>
//#include "main.h"
#include "map.h"
#include <iostream>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>
#include "animation_handler.h"
int main(int argc, char* argv[])
{
sf::RenderWindow app(sf::VideoMode(600, 600), "Tilemap Example");
// Hard set fps to monitor refresh rate.
// textures to load.
/*text_mgr.loadTexture("grass", "grass.png");
text_mgr.loadTexture("high_grass", "high_grass.png");
Animation staticAnim(0, 0, 1.0f);
tileAtlas["grass"] = Tile(32, 1, text_mgr.getRef("grass"),{ staticAnim },
TileType::GRASS, 50, 0, 1);
tileAtlas["high_grass"] = Tile(32, 1, text_mgr.getRef("high_grass"),{ staticAnim },
TileType::HIGH_GRASS, 100, 0, 1);*/
//Map map;
//map.load(50, 50, tileAtlas);
#ifdef NDEBUG
app.setVerticalSyncEnabled(true);
std::cout << "#################\n";
#endif // DEBUG
//app.setVerticalSyncEnabled(true);
sf::View cam = app.getDefaultView();
tile_atlas atlas = tile_atlas();
std::vector<chunk_map> map;
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
map.push_back(chunk_map());
map.back().set_texture(atlas.get_atlas());
map.back().set_position(10 * x, 10 * y, 10 * (x + 1), 10 * (y + 1));
map.back().load_tiles();
}
}
sf::Clock clock;
int checked = 0;
int last_sq = 600;
while (app.isOpen())
{
//sf::Time elapsed = clock.restart();
//float dt = elapsed.asSeconds();
sf::Event eve;
while (app.pollEvent(eve))
if (eve.type == sf::Event::Closed)
app.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::P))
std::cout << "view x: " << cam.getSize().x << "\tview y: " << cam.getSize().y << std::endl;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
{
float zoom_out = 1.005f;
float nz = last_sq * zoom_out;
nz = std::ceil(nz);
float now = nz / last_sq;
last_sq = nz;
std::cout << now << std::endl;
cam.zoom(now);
//float x = cam.getCenter().x;
//float y = cam.getCenter().y;
//x = std::floor(x);
//y = std::floor(y);
////std::cout << "x: " << x << "\ty: " << y << std::endl;
//cam.setCenter(x, y);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
{
float zoom_in = 0.995f;
float nz = last_sq * zoom_in;
nz = std::floor(nz);
float now = nz / last_sq;
if (nz <= 10)
continue;
last_sq = nz;
std::cout << now << std::endl;
cam.zoom(now);
//float x = cam.getCenter().x;
//float y = cam.getCenter().y;
//x = std::floor(x);
//y = std::floor(y);
////std::cout << "x: " << x << "\ty: " << y << std::endl;
//cam.setCenter(x, y);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
cam.move(0.f, -0.02f);
float x = cam.getCenter().x;
float y = cam.getCenter().y;
x = std::floor(x);
y = std::floor(y);
//std::cout << "x: " << x << "\ty: " << y << std::endl;
cam.setCenter(x, y);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
cam.move(-0.02f, 0.f);
float x = cam.getCenter().x;
float y = cam.getCenter().y;
x = std::floor(x);
y = std::floor(y);
//std::cout << "x: " << x << "\ty: " << y << std::endl;
cam.setCenter(x, y);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
cam.move(0.f, 0.02f);
float x = cam.getCenter().x;
float y = cam.getCenter().y;
x = std::ceil(x);
y = std::ceil(y);
//std::cout << "x: " << x << "\ty: " << y << std::endl;
cam.setCenter(x, y);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
cam.move(0.02f, 0.f);
float x = cam.getCenter().x;
float y = cam.getCenter().y;
x = std::ceil(x);
y = std::ceil(y);
//std::cout << "x: " << x << "\ty: " << y << std::endl;
cam.setCenter(x, y);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
sf::Time elapsed = clock.getElapsedTime();
float t = elapsed.asSeconds();
int time = std::floor(t);
if (checked < time)
{
checked = time;
cam.move(0.01f, 0.f);
float x = cam.getCenter().x;
float y = cam.getCenter().y;
x = std::ceil(x);
y = std::ceil(y);
std::cout << "x: " << x << "\ty: " << y << std::endl;
cam.setCenter(x, y);
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
app.close();
app.setView(cam);
#ifdef _DEBUG
app.clear();
#endif // DEBUG
//map.draw(app, dt);
for (int i = 0; i < 25; i++)
{
app.draw(map.at(i));
}
app.display();
}
}
chunk_map.h
#pragma once
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <vector>
class chunk_map : public sf::Drawable
{
private:
//change values of these to match your needs and improve performance
enum { tilesize = 32, chunksize = 32};
//tile size float
float tile_size_float = 32.0f;
// Draw chunk
virtual void draw(sf::RenderTarget& target, sf::RenderStates states)const;
// texture for chunk
sf::Texture m_texture;
// chunk dimensions
int tiles_per_chunk_x;
int tiles_per_chunk_y;
//start x and y and ending x and y scaled to tile size. a.k.a.
// 1,1 = tile 1,1. 10,10, equals tile 10,10
int chunk_start_x;
int chunk_start_y;
int chunk_end_x;
int chunk_end_y;
// Vertex array of positions of tiles in chunk
std::vector<std::vector<sf::VertexArray> > m_chunks;
// Append tiles.
void append_tile(int gx, int gy, sf::VertexArray& garr);
public:
chunk_map();
~chunk_map();
void load_tiles();
void set_texture(sf::Texture);
void set_position(int chunk_start_x, int chunk_start_y,
int chunk_end_x, int chunk_end_y);
};
chunk_map.cpp
#include "chunk_map.h"
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Vertex.hpp>
chunk_map::chunk_map()
{
}
chunk_map::~chunk_map()
{
}
void chunk_map::load_tiles()
{
/*
Tile loading this is were the tiles are added to the Quadrantics of the tilemap.
this is the entire chunk_map loop
*/
if ((chunk_end_x * chunk_end_y) == 0)//empty map - possibly forgotten to fill data struct
{
//to stop displaying at all after failed loading:
tiles_per_chunk_x = 0;
tiles_per_chunk_y = 0;
m_chunks.clear();
return;
}
chunk_map::tiles_per_chunk_x = (chunk_end_x / chunksize) + 1;
chunk_map::tiles_per_chunk_y = (chunk_end_y / chunksize) + 1;
m_chunks.assign(tiles_per_chunk_x, std::vector<sf::VertexArray>(tiles_per_chunk_y, sf::VertexArray(sf::Quads)));//ready up empty 2d arrays
for (int iy = chunk_start_y; iy < chunk_end_y; ++iy)
{
for (int ix = chunk_start_x; ix < chunk_end_x; ++ix)
{
append_tile(ix, iy, m_chunks[ix / chunksize][iy / chunksize]);
}
}
}
void chunk_map::append_tile(int gx, int gy, sf::VertexArray& garr)
{
/*
This is the specific tile vertex, broken from the other function to decrease complexitity.
*/
int tile_selection_index_x = rand() % 2;
int tile_selection_index_y = 0;
float f_tx = tile_selection_index_x * tile_size_float;
float f_ty = tile_selection_index_y * tile_size_float;
sf::Vertex ver;
//____________________________________________________________________________________________________________
ver.position = sf::Vector2f(gx * tile_size_float, gy * tile_size_float);
//texture in position of text atlas
//top left corner
//ver.texCoords = sf::Vector2f( 0.f, 0.f);
ver.texCoords = sf::Vector2f(f_tx, f_ty);
garr.append(ver);
//____________________________________________________________________________________________________________
ver.position = sf::Vector2f(gx * tile_size_float + tile_size_float, gy * tile_size_float);
//texture in position of text atlas
//top right corner
//ver.texCoords = sf::Vector2f( tile_size_float, 0.f);
ver.texCoords = sf::Vector2f(f_tx + tile_size_float, f_ty);
garr.append(ver);
//____________________________________________________________________________________________________________
ver.position = sf::Vector2f(gx * tile_size_float + tile_size_float, gy * tile_size_float + tile_size_float);
//texture in position of text atlas
//bottom right corner
//ver.texCoords = sf::Vector2f( tile_size_float, tile_size_float);
ver.texCoords = sf::Vector2f(f_tx + tile_size_float, f_ty + tile_size_float);
garr.append(ver);
//____________________________________________________________________________________________________________
ver.position = sf::Vector2f(gx * tile_size_float, gy * tile_size_float + tile_size_float);
//texture in position of text atlas
//bottom left corner
//ver.texCoords = sf::Vector2f( 0.f, tile_size_float);
ver.texCoords = sf::Vector2f(f_tx, f_ty + tile_size_float);
garr.append(ver);
}
void chunk_map::set_texture(sf::Texture t)
{
/*
Sets the texture data for this chunk map from the texture atlas.
*/
m_texture = t;
// TODO test this feature
// Attempt to optimize tearing on zooming to a different view.
//m_texture.setSmooth(true);
}
void chunk_map::set_position(int chunk_start_x, int chunk_start_y,
int chunk_end_x, int chunk_end_y)
{
/*
Initialize the accordinates of the start of the chunk_map to the end.
*/
chunk_map::chunk_start_x = chunk_start_x;
chunk_map::chunk_start_y = chunk_start_y;
chunk_map::chunk_end_x = chunk_end_x;
chunk_map::chunk_end_y = chunk_end_y;
}
void chunk_map::draw(sf::RenderTarget& target, sf::RenderStates states)const
{
/*
The actual draw call to this specific chunk_map
*/
// position variables for this draw.
int left = 0;
int right = 0;
int top = 0;
int bottom = 0;
//get top left point of view
sf::Vector2f temp = target.getView().getCenter() - (target.getView().getSize() / 2.f);
//get top left point of view
left = static_cast<int>(temp.x / (chunksize * tilesize));
top = static_cast<int>(temp.y / (chunksize * tilesize));
//get bottom right point of view
temp += target.getView().getSize();
right = 1 + static_cast<int>(temp.x / (chunksize * tilesize));
bottom = 1 + static_cast<int>(temp.y / (chunksize * tilesize));
//clamp these to fit into array bounds:
left = std::max(0, std::min(left, tiles_per_chunk_x));
top = std::max(0, std::min(top, tiles_per_chunk_y));
right = std::max(0, std::min(right, tiles_per_chunk_x));
bottom = std::max(0, std::min(bottom, tiles_per_chunk_y));
//set texture and draw visible chunks:
states.texture = &m_texture;
for (int ix = left; ix < right; ++ix)
{
for (int iy = top; iy < bottom; ++iy)
{
target.draw(m_chunks[ix][iy], states);
}
}
}
tile_atlas.h
#pragma once
#include <SFML/Graphics/Texture.hpp>
class tile_atlas
{
private:
sf::Texture atlas_texture;
public:
tile_atlas();
~tile_atlas();
sf::Texture& get_atlas();
};
tile_atlas.cpp
#include "tile_atlas.h"
#include <iostream>
#include <string>
tile_atlas::tile_atlas()
{
std::string file_string = "tilemap_test.png";
if (!atlas_texture.loadFromFile(file_string))
{
std::cout << "Failed loading file: " << file_string << std::endl;
exit(1);
}
}
tile_atlas::~tile_atlas()
{
}
sf::Texture& tile_atlas::get_atlas()
{
return atlas_texture;
}
I am trying to fix this code to remove vertical artifacts so the above image will always look like this no matter if moving the view or zooming in/out.
[code for answer]
Using #Mario's answer this is the code I wrote (at the bottom of main.cpp) that completely fixed the artifacts.
here is a great link showing an example.
https://www.sfml-dev.org/tutorials/2.5/graphics-draw.php#off-screen-drawing
#ifdef _DEBUG
app.clear();
#endif // DEBUG
//map.draw(app, dt);
/*-----------------------------------------------------------*/
// Draw the texture
//rt.clear();
rt.draw(map.at(0));
rt.display();
if (cam.getSize().x < 500)
{
rt.setSmooth(false);
}
else
{
rt.setSmooth(true);
}
//// get the target texture (where the stuff has been drawn)
const sf::Texture& texture = rt.getTexture();
sf::Sprite sprite(texture);
app.draw(sprite);
//app.draw(map.at(0));
/*-----------------------------------------------------------*/
app.display();
Simple, yet effective:
Render your pixels 1:1 without scaling to a render texture and then upscale that instead.
Might be a bit tricky to determine the correct position, zoom, etc. but it can be done.

Gradient Descent for Linear Regression not minimizing perfectly

I am trying to implement the basic gradient descent algorithm on my uniformly distributed training set. As the data is uniform so the partition line should be diagonal, but i am getting a line as in below figure. In the figure circles are my data points and the line represent the cost function(h(x)).
I am using OpenCV just for output nothing else. I am using below equation:-
#include <iostream>
#include <unistd.h>
#include <cv.h>
#include <highgui.h>
#define WIN_WIDTH 500
#define WIN_HEIGHT 500
#define MAX_POINTS 500
using namespace std;
using namespace cv;
void getPoints(vector<Point> &randPoints, int size)
{
for (int i = 20; i < WIN_HEIGHT; i+=20)
{
for (int j = 20; j < WIN_WIDTH; j+=20)
{
int x = i;
int y = j;
Point pt = Point(x, y);
randPoints.push_back(pt);
}
}
}
void gradientDescent( double &th1, double &th2, double &alpha, vector<Point> &pointVec)
{
int size = pointVec.size();
double sum1 = 0.0, sum2 = 0.0;
for (int i = 0; i < size; i++)
{
sum1 += (th1 + th2 * pointVec[i].x) - pointVec[i].y;
sum2 += ((th1 + th2 * pointVec[i].x) - pointVec[i].y) * pointVec[i].x;
}
th1 = th1 - ((alpha/( double)size) * sum1);
th2 = th2 - ((alpha/( double)size) * sum2);
}
int main(int argc, char**argv)
{
Mat img(WIN_WIDTH, WIN_HEIGHT, CV_8UC3);
img = Scalar(255, 255, 255);
vector<Point> randPoints;
getPoints(randPoints, MAX_POINTS);
int size = randPoints.size();
cout << "Training size = " << randPoints.size() << endl;
for (int i = 0; i < size; i++)
circle(img, randPoints[i], 4, Scalar(255, 0, 0), 1, 8);
double theta1 = 0, theta2 = 0.25, alpha = 0.0000001;
if (argc > 2)
{
theta1 = atof(argv[1]);
theta2 = atof(argv[2]);
}
int countConv = 0, prevY = 0;
cout << "Theta0 = " << theta1 << " Theta1 = " << theta2 << endl;
cout << "Learning rate = " << alpha << endl;
Mat tmpImg(WIN_WIDTH, WIN_HEIGHT, CV_8UC3);
while(1)
{
gradientDescent(theta1, theta2, alpha, randPoints);
int x = WIN_WIDTH+WIN_HEIGHT;
int y = theta1 + (theta2 * x);
int x1 = WIN_WIDTH-200;
int y1 = theta1 + theta2*x1;
img.copyTo(tmpImg);
circle(tmpImg, Point(x1, y1), 4, Scalar(0, 0, 255), -1, 8);
char text[64];
sprintf(text, "(%d, %d)", x1, y1);
putText(tmpImg, text, Point(x1+3, y1+3), FONT_HERSHEY_SCRIPT_SIMPLEX, 0.4, Scalar(0, 255, 0), 1, 8);
line(tmpImg, Point(0, theta1), Point(x, y), Scalar(0, 0, 255));
imshow("Gradient Descent", tmpImg);
waitKey(33);
}
imshow("Gradient Descent", tmpImg);
waitKey(0);
return 0;
}