Handling Vectors of Textures/Sprites # SMFL - c++

This is basically the White Square Problem when vectors of textures and sprites are used in SMFL. After fighting with it for sometime, I have come up with a code with some pointers inside but still could not get what I want.
Here is what I have in the int main()
vector<sf::Sprite> sprites;
vector<sf::Texture> textures;
// Load sprites
for(int i=0;i<3;i++){
sf::Texture texture;
texture.loadFromFile(resourcePath() + "pink_sq.png");
textures.push_back(texture);
vector <sf::Texture>::iterator it = textures.begin() + i;
sf::Sprite sprite(*it);
sprite.setPosition(i*100,i*100);
sprites.push_back(sprite);
}
// Start the game loop
while (window.isOpen())
{
window.clear();
// Draw the sprite
for(int i=0;i<sprites.size();i++)
window.draw(sprites[i]);
window.display();
}
What I am getting is only third square at (200,200) is pink. The other two are white. Somehow textures are not copied to first two sprites.
I know for this simple code, I can avoid vectors, but this code is just for demonstration. I will be using possibly 100s of sprites in the future. Let me know if you guys have an idea on how to fix this.

Have you considered using a map for your textures? It seems to not work no matter what i try with a vector, the functionality dosn't change much with a map. I usually use maps when dealing with sprites, because you can have a string as your index if you so choose, which can make your code easier to follow.
#include <map>
.
.
.
vector<sf::Sprite> sprites;
sf::Sprite sprite;
map<int, sf::Texture> textures;
// Load sprites
for(int i=0;i<3;i++){
textures[i].loadFromFile(resourcePath() + "pink_sq.png");
sprites.push_back(sprite);// loads a dummy sprite for a pushback
sprites[i].setTexture(textures[i]);
sprites[i].setPosition(i*100,i*100);
}
// Start the game loop
while (window.isOpen())
{
window.clear();
// Draw the sprite
for(int i=0;i<sprites.size();i++){
window.draw(sprites[i]);
window.display();
sf::sleep(sf::milliseconds(30)); // so the loop dosn't crash the program randomly
}
}
this way produces 3 pink boxes
hope this helps
p.s. still tinkering with the vector, will add to the post if i can find a way.

Related

Moving Sprite (SFML) in c++ using Loops

I am new to c++ and as well as SFML. I am trying to make my sprite object move down in position relative to its last position using a loop. I am looking for the animation of it sprite object falling when the program starts.
I thought implementing a the sleep function in my for loop would help solve the issue i was having where the program would just display the object at the last iteration of the loop. However my program just freezes and crashes.
Looking for some direction. Maybe the sleep function isn't the right thing to call here?
#include <SFML/Graphics.hpp>
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
// Create the window here. Calling out the dimensions
sf::RenderWindow window(sf::VideoMode(800, 600), "Example Window");
// run the program as long as the window is open
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
//close window we requested
if (event.type == sf::Event::Closed)
{
window.close();
}
}
window.clear(sf::Color::Black);
sf::Texture texture;
if (!texture.loadFromFile("c:\\abstract.png"))
{
cout<<"Failed to load image...";
}
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(20,20,30,30));
for (float i = 0; i < 30.; i++)
{
sprite.move(sf::Vector2f(5.f, i));
window.draw(sprite);
Sleep(50);
}
window.display();
}
return 0;
}
What you are doing in your for is : Processing, drawing, processing, drawing... And finally displaying what you've drawn using window.display().
Meaning that what will be displayed on your window every frames, is the result of your "Processing, drawing" thing, in other word, 30 times your sprite at different positions.
What you want is to move your sprite a bit every frames. Thus, you have to finish your current while (window.isOpen()) iteration to move your sprite, draw it, and display it, and this over and over.
What you should do is declaring your sprite outside of your game loop (Which is while (window.isOpen())), and move it in this loop.
Step by step, your program should look like:
[Start]
Initialize your context
Create a sprite
Start looping
Clear the screen
Collect inputs
Move your sprite
Draw your sprite
Display your drawing on the window
End looping
[Exit]
The last thing you will need to handle is deltaTime (The timestep). Because if you move your sprite from (x,y) every frames, it means that the faster your computer is (Able to render a lot of frames quickly), the faster your sprite will move. In order to fix this problem, you'll have to move your sprite considering the time elapsed between the current frame and the previous frame (The slower is your PC, the more your sprite will move in one frame, the faster is your PC, the less your sprite will move in one frame). Timestep will cause your sprite to move (x,y) per second instead of (x,y) per frame, which is what you want in most graphic applications.

Most efficient way to Spawn and destroy objects for endless runner game? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm currently very new to SFML and i was wonder what the most efficient way to spawn and destroy objects in a vector based on the camera position ? Currently I'm instantiating a vector of wall "points" which will be linked together after debugging. Should i be Creating and destroying them based on the the cam position or moving the already existing ones to the correct position ?
I also wouldn't mind some feedback on my code for this.
Cave Chaos.cpp
int main()
{
//get classes from CaveChaos.h
CaveChaos::Wall objWall;
CaveChaos::Player objPlayer;
//set render window size and name
sf::RenderWindow window(sf::VideoMode(800, 600), "CaveChaos");
//set the view
sf::View view1(sf::Vector2f(0.f, 0.f), sf::Vector2f(window.getSize().x, window.getSize().y));
//create the player object as a triangle
sf::CircleShape Player(20, 3);
//initialise random
srand(time(0));
//sets the player position to a good position based on camera size
objPlayer.posx = window.getSize().x / 2;
objPlayer.posy = window.getSize().y / 1.1;
Player.setPosition(objPlayer.posx, objPlayer.posy);
//used to instantiate wall points
int locationsX[numofpoints];
//add random x values to locations
for (int i = 0; i < numofpoints; i++)
{
locationsX[i] = (rand() % 50) + 1;
}
while (window.isOpen())
{
sf::Event event;
//clear the window with black color
window.clear(sf::Color::Black);
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//calls wallspawn in Walls.cpp which creates the wall points
WallSpawn(window, locationsX );
//calls playermove in Player.cpp which move the player
PlayerMove(window, Player);
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//set the player as the cam follow point
view1.setCenter(Player.getPosition().x, Player.getPosition().y - objPlayer.posy / 3);
//set the view to the player
window.setView(view1);
window.display();
}
return 0;
}
Currently when i call WallSpawn() it loops through 10 objects and spawns them, would there be a way to spawn an infinite amount of objects instead ?
Walls.cpp
void WallSpawn(sf::RenderWindow& window, int locationsX[] )
{
//initiate random
srand(time(0));
//class objects
CaveChaos::Wall objWall;
CaveChaos::Player objPlayer;
//creates a vector of circleshapes
std::vector<sf::CircleShape> points;
//defines and circle of size 5
sf::CircleShape shape(5);
//loop through all of the points
for (int i = 0; i < numofpoints; i++)
{
//set the shape position to the random variable from CaveChaos.cpp
shape.setPosition(locationsX[i], objPlayer.posy + i * 55);
//set shape color to green
shape.setFillColor(sf::Color(100, 250, 50));
// copy shape to vector
points.push_back(shape);
}
// iterate through vector
for (std::vector<sf::CircleShape>::iterator it = points.begin(); it != points.end(); ++it)
{
//draw wall points on screen
window.draw(*it);
}
}
What would be the best way to move or destroy these objects after they have been spawned ?
I want this last point to either get destroy or moved to the front when i go forward:
and when i move forward something like this to happen:
If this method is completely wrong or i shouldn't be using this method at all please let me know.
thanks for the help.
Code Review
So first of all stackoverflow is not the right site for code review. If you seek for a complete review ask on codereview. However, here are some things I noticed:
Don't use rand or srand. If you want RNG use <random> (usually uniform_int_distribution or uniform_real_distribution).
Why are you using a native array for locationsX? std::vector seems much more reasonable.
Avoid frequent allocations inside performance critical loops (ex. you call WallSpawn each game loop iteration and WallSpawn itself creates a new vector sf::CircleShape each time which canbe avoided). More on that later.
Preallocate space for std::vector using vector.reserve() if you have an estimate of the final vector size.
Why do you do you have two event loops inside the window loop instead of just one?
Using auto instead of std::vector<sf::CircleShape>::iterator improves readability.
Design
Usually a game loop looks like this:
polling window events and handling user input,
updating game state (reacting to input, applying physics, character movement, ...), and
drawing the new game state.
Your WallSpawn function, for example, shows how it shouldn't be done. You're generating new game entities (wall points) and then you draw them straight away in the same function.
I have limited expirience with SFML but I know that there is a sf::Drawable base class which can be used for everything that needs to be drawn on the window. You don't have to use it but it's designed for easier OOP development. For example, you could create a type for your wall points or for the entire wall (depending on what you actually want to do with those points):
class WallPoint : public sf::Drawable
{
public:
WallPoint(int x, int y) :
position(x, y), circle(x, y, 5)
{
}
/*
* Getter and setter for position
*/
void draw(RenderTarget& target, RenderStates states) const override
{
target.draw(circle);
}
private:
sf::Point position;
sf::CircleShape circle;
};
And then keep a collection of those points in a variable outside of your game loop.
Entity Management
Large games with thousands or millions of game entities (vehicles, trees, rocks, walls, weapons, ammo, projectiles, crowds, NPCs, ...) have the problem that they have to be very efficient when it comes to managing them. However, in your case with a few simple circle shapes, efficient management is not really a concern. Don't optimize if you don't have to.
You gave too little information about the game behavior to make a profund recommendation, so here is some guessing.
How does the game progress affect your entities? Your case (a runner game) suggests that the environment is constantly moving along one axis (left <> right, or up <> down). If this is true, this means that your wall points always spawn and despawn at the edges of the current environment. In such a case std::deque is an ideal container to store your data.
Usually std::vector is a solid allrounder when it comes to container.
Always destroy your entities when you don't need them anymore. For example, if your wall points leave the view port (and you are sure they won't enter it again) remove them for the container.
Putting Things Together
Considering everything I wrote above, your game loop could now like this:
int main()
{
// Create window and init everything you need
std::deque<WallPoint> wallPoints;
// create some initial points
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
// event handling
}
// update game state
// add new wall points
// remove old points
// move the player
// draw the new game state
window.Clear();
for (const auto& point : wallPoints)
window.draw(point);
window.draw(player);
}
}

VertexArray of circles

I am wondering if it is possible to create a VertexArray of circles in SFML. I have looked for answers but I didn't find anything that could help. Moreover, I don't understand the part on the SFML documentation where it is written that I can create my own entities, I think this is maybe what I want to do in fact.
EDIT : I want to do that because I have to draw a lot of circles.
Thanks for helping me
While #nvoigt answer is correct, I found it useful in my implementations to work with vectors (see http://en.cppreference.com/w/cpp/container/vector for more details, look up "c++ containers", there are several types of containers to optimize read/write times).
You probably do not need it for the above described use case, but you could need it in future implementations and consider this for a good coding practice.
#include <SFML/Graphics.hpp>
#include <vector>
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// clear the window with black color
window.clear(sf::Color::Black);
// initialize myvector
std::vector<sf::CircleShape> myvector;
// add 10 circles
for (int i = 0; i < 10; i++)
{
sf::CircleShape shape(50);
// draw a circle every 100 pixels
shape.setPosition(i * 100, 25);
shape.setFillColor(sf::Color(100, 250, 50));
// copy shape to vector
myvector.push_back(shape);
}
// iterate through vector
for (std::vector<sf::CircleShape>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
{
// draw all circles
window.draw(*it);
}
window.display();
}
return 0;
}
sf::CircleShape is already using a vertex array (thanks to being inherited from sf::Shape). There is nothing extra you need to do.
If you have a lot of circles, try using sf::CircleShape first and only optimize when you have a real use-case that you can measure your solution against.
In addition two previous answers I will try to explain why there is no default VertexArray of circles.
By ideology of computer graphics (and SFML in our case) vertex is a smallest drawing primitive with least necessary functionality. Classical example of vertices are point, line, triange, guad, and polygone. The first four are really simple for your videocard to store and to draw. Polygon can be any geometrical figure, but it will be heavier to process, that's why e.g in 3D grapichs polygons are triangles.
Circle is a bit more complicated. For example videocard doesn't know how much points she need to draw your circle smooth enough. So, as #nvoigt answered there exists a sf::CircleShape that is being built from more primitive verticies.

Flickering when drawing the background outside of the main loop

Here's my CODE:
#include <SFML\Graphics.hpp>
sf::RenderWindow renderWindow(sf::VideoMode(300, 300), "The Problem");
int main()
{
sf::Texture tX;
tX.loadFromFile("Recursos/Fondo.png");
sf::Sprite tXt(tX);
renderWindow.draw(tXt);
while (true) // main loop
{
renderWindow.display();
}
}
tX is a large sprite (think: background), so I want to avoid redrawing it every frame.
When I try this, I get flickering, and I have no idea where it's coming from.
Your code, simplified, pseudo:
Initialize();
Draw();
Loop {
Display();
}
What you're doing is drawing the scene to a buffer (without clearing it first, by the way), and then displaying it in a loop (without redrawing anything).
I think the reason you have flickering is due to double-buffering (v-sync).
What ends up happening is that you drew to one buffer, but left the other one empty. When you display the active buffer, they get flipped (so the next time you display, it's an empty buffer).
You really should draw inside the loop.
Alternatively, you can disable multiple-buffering, or try drawing, displaying, drawing again, and then looping (so that you draw to both buffers, assuming there are only two).
Both solutions are not elegant.
If drawing the background really needs optimization, I'm afraid SFML won't give you that granularity. You might want to look in to OpemGL Stencil wizardry.

SFML Drawing Pixel Array

I found this (http://lodev.org/cgtutor/raycasting.html) tutorial on the Internet and was interested and wanted to make my own. I wanted to do it in SFML though, and I wanted to extend it, and make a 3D version, so there could be different levels the player can walk on. Thus, you would need 1 ray for every pixel, and thus each pixel would have to be drawn independently. I found this (http://www.sfml-dev.org/tutorials/2.1/graphics-vertex-array.php) tutorial, and it seemed easy enough to have the array be of individual vertices. To start, I figured the best thing to do would be to create a class that could read the pixels returned by the rays, and draw them to the screen. I used the VertexArray, but things were not working for some reason. I tried to isolate the problem, but I've had little success. I wrote a simple vertex array of just green pixels that should fill up part of the screen, and still there are problems. The pixels only show my code and the pic. of what I mean.
#include "SFML/Graphics.hpp"
int main() {
sf::RenderWindow window(sf::VideoMode(400, 240), "Test Window");
window.setFramerateLimit(30);
sf::VertexArray pointmap(sf::Points, 400 * 10);
for(register int a = 0;a < 400 * 10;a++) {
pointmap[a].position = sf::Vector2f(a % 400,a / 400);
pointmap[a].color = sf::Color::Green;
}
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(pointmap);
//</debug>
window.display();
}
return 0;
}
I meant for this to just fill in the top 10 rows with Green, but apparently that is not what I did... I think if I can figure out what is causing this not to work, I can probably fix the main problem. Also if you think there is a better way to do this instead, you could let me know :)
Thanks!
I think you misused the vertex array. Take a look at the sf::Quads primitive in the tutorial's table : you need to define 4 points (coordinates) to draw a quad, and a pixel is just a quad of side length 1.
So what you need is to create a vertex array of size 400*10*4, and set the same position to every following four vertices.
You can also use another method provided by SFML : draw directly a texture pixel by pixel and display it. It may not be the most efficient thing to do (you'll have to compare with vertices) but it has the advantage of being rather simple.
const unsigned int W = 400;
const unsigned int H = 10; // you can change this to full window size later
sf::UInt8* pixels = new sf::UInt8[W*H*4];
sf::Texture texture;
texture.create(W, H);
sf::Sprite sprite(texture); // needed to draw the texture on screen
// ...
for(register int i = 0; i < W*H*4; i += 4) {
pixels[i] = r; // obviously, assign the values you need here to form your color
pixels[i+1] = g;
pixels[i+2] = b;
pixels[i+3] = a;
}
texture.update(pixels);
// ...
window.draw(sprite);
The sf::Texture::update function accepts an array of sf::UInt8. They represent the color of each pixel of the texture. But as the pixels need to be 32bit RGBA, 4 following sf::UInt8 are the RGBA composants of the pixel.
Replace the line:
pointmap[a].position = sf::Vector2f(a % 400,a / 400);
With:
pointmap[a].position = sf::Vector2f(a % 400,(a/400) % 400);