-
(first of all, sorry for my bad english, its not my native language)
Hi!
I'm using SFML v2.3, Mingw32 v4.7.1 (Code::Blocks default) and Windows 10.
I'm trying to make an application to test the sf::Image class and render single pixels, but everytime i try to do a simple loop using sf::Image::setPixel it crashes...
#include <SFML/Graphics.hpp>
#include <iostream>
int loopCount = 0;
const int Largura = 800;
const int Altura = 600;
int main()
{
//Setup Window
sf::RenderWindow window(sf::VideoMode(Largura, Altura), "yay");
window.setVerticalSyncEnabled(true);
// create an empty 800x600 texture
sf::Texture texture;
if (!texture.create(800, 600))
{
std::cout << "Fail to create the texture";
}
// create an black image
sf::Image image;
image.create(800, 600, sf::Color::Black);
// Set the texture to be the image and create the Sprite to render
texture.update(image);
sf::Sprite sprite;
sprite.setTexture(texture);
//the loop that is crashing the program
//it should create a diagonal line of white pixels
for(int i=0; i<=600; i++){
image.setPixel(i, i, sf::Color::White);
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//The actual Rendering
window.clear();
texture.update(image);
window.draw(sprite);
window.display();
}
return 0;
}
What am i doing wrong? I am not suposed to manipulate pixels like that?
-
for(int i=0; i<=600; i++){
image.setPixel(i, i, sf::Color::White);
}
Why <= ?
-
If its not <= its going to loop forever, i just want it to draw a line inside the boundaries of the window (600 pixels high)
-
First, IIRK,
texture.update(image);
copies pixels from image, so all changes on images after that do not change texture.
Second, you have 800x600 pixel matrix, so because first index of array is 0 (zero), calling image.setPixel(600, 600, sf::Color::White);
will go out of bounds...
-
Thanks! this
image.setPixel(600, 600, sf::Color::White);
was the thing crashing, just changing the <= to < has done it.
and...
texture.update(image);
it will change the texture because its on the main loop, so it will be called every frame...
but is there's any alternatives to this function?
-
If its not <= its going to loop forever, i just want it to draw a line inside the boundaries of the window (600 pixels high)
Then it should be "<600" or "<=599". By going from 0 to 600 you are drawing 601 pixels in total and thus you end up writing outside the available memory.
-
texture.update(image);
it will change the texture because its on the main loop, so it will be called every frame...
but is there's any alternatives to this function?
This updates the texture with the image so is what you're looking for.
However, it only needs to be called after changing the image so it can be called once, after the image manipulation (before the loop)