Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Messages - fallahn

Pages: 1 2 [3] 4 5 ... 32
Graphics / Re: Resizing of an Image in SFML 2.5
« on: February 15, 2022, 04:20:21 pm »
Once you have your sprite and have resized it you can draw it to sf::RenderTexture then use sf::RenderTexture::getTexture()::copyToImage() to get it back to an image object. It can be slow but might be fast enough for what you need.

General / Re: Rectangle bottom collision issues
« on: February 06, 2022, 04:48:33 pm »
Detecting the collision and stopping falling is not enough on its own. You also have to calculate how much overlap (aka penetration) the collision created and move the character back by that much, so that it lines up with the platform. I wrote a post about simple collision detection some time back, it may be useful here.


Graphics / Re: unefficient drawing
« on: February 05, 2022, 12:38:26 pm »
You can probably alleviate the drawing a bit by rendering each point as a vertex in a vertex array, with the primitive type set to points.

    sf::VertexArray vertexArray(sf::PrimitiveType::Points);

            if((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Enter) && (!fullscreen)) {
            fullscreen = true;
            window.create(VideoMode(1920, 1080), nameProject, (fullscreen ? Style::Fullscreen : Style::Resize|Style::Close));
            else if((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Escape) && (fullscreen)) {
            fullscreen = false;
            window.create(VideoMode(1920, 1080), nameProject, (fullscreen ? Style::Fullscreen : Style::Resize|Style::Close));
            if((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Space) && (fullscreen)) {
                pause = !pause;
            if(event.type == Event::Closed){

        float dt = gameClock.getElapsedTime().asSeconds();


        for(int i=0; i<player.size(); i++){
            if(fullscreen && !pause){

                if(player.x < player.r){
                    player.x += 2*(player.r-player.x);
                    player.vx *= -1;
                else if(player.x > window.getSize().x-player.r){
                    player.x += 2*(window.getSize().x-player.r-player.x);
                    player.vx *= -1;
                if(player.y < player.r){
                    player.y += 2*(player.r-player.y);
                    player.vy *= -1;
                else if(player.y > window.getSize().y-player.r){
                    player.y += 2*(window.getSize().y-player.r-player.y);
                    player.vy *= -1;
                player.body.setPosition(player.x-player.r, player.y-player.r);
                vertexArray.append(sf::Vertex(sf::Vector2f(player.x-player.r, player.y-player.r)));


This will batch all of your points into a single draw call.

I've managed to render 3D models using the SFML graphics module with some shader trickery, and by forcing normal/depth data into the colour property of sf::VertexArray - and made a couple of games with that technique:


The gist of it is to replace the model/view/projection matrices with your own in a custom vertex shader, and to store the normal vector in the vertex RGB channel, and vertex z-depth as a normalised value in the vertex alpha channel. It kinda works, although to be honest the amount of OpenGL you need to learn to understand how SFML works under the hood means it's probably not worth the effort (other than the learning exercise) and I should probably just use OpenGL directly for the performance gain  ;D

If you're curious source is available here: https://github.com/fallahn/osgc/tree/master/did and here https://github.com/fallahn/osgc/tree/master/lightmapper for a model format converter I made to go with it (yes, I even went as far as to create a specific model format...)

You most likely want to use getTransform() (inherited from sf::Transformable) with your RenderStates used to draw the array:


Your best bet is to add 2 uniforms for texture size and texture rect size, and set them each time you draw a sprite. This is probably also applicable if you try to build on mac (and possibly linux) as they require a core version of OpenGL and a declaration of #version 120 at the top of your shader. (Windows drivers often supply a 'compatibility' context which is why your current solution works for you) textureSize() requires #version 130 or greater, and would therefore become unavailable.

If you want to use the graphics module on OS X, you are limited to using a legacy context which implies OpenGL version 2.1.


#version 120

uniform sampler2D source;
uniform sampler2D noiseTexture;
uniform float dissolveAmount;
uniform vec2 u_textureSize;
uniform vec2 u_rectSize;

void main()
        vec2 textureCoordinates = gl_TexCoord[0].xy;
        float edgeThickness = 0.1;
        vec4 edgeColor = vec4(255, 0, 0, 100);
        float noiseTiling = 0.8;
        vec2 textureScale = u_textureSize / u_rectSize;



Thats an image buffer of
uint8_t * pixels
a. Copy image buffer to Texture
void sf::Texture::update        (       const Uint8 *   pixels  )

b. Render using SFML to texture

c. Copy sf::Texture to sf::Image

a. Use sf::Image with you buffer copied to sf::Image
b. Copy sf::Image to sf::Texture
c. Copy sf::Texture to sf::Image

Are these the two options you described ?

That's correct. SFML uses glGetTexImage under the hood:

(or glReadPixels if using GLES)

and glTexSubImage2D for uploading

This might be fine for your needs (I've used it for rendering the output of emulators for example) but it will of course start to suffer with larger video resolutions. You can only really know for sure by testing it out  8)

Graphics / Re: How to draw a buffer as a line
« on: October 10, 2021, 04:56:44 pm »
Assuming your buffer is a vector or an array of bytes you can use sf::Texture::update()


to upload it to a texture.

This should actually behave as you expect - the vertex colours are multiplied (after being normalised) with the texture colours. So a vertex alpha of 0.5 (127) should make a texture colour alpha 0.5 (if it started  as 1 aka 255), 0.25 if it was 0.5 and so on. If the alpha of the texture is already 0 it should remain so (0 * 0.5 == 0).

Are you using the correct blend mode, which should be sf::BlendAlpha?

Sharing some of your code might also help

If you can, use the sf::Image as the buffer, it is essentally a wrapper for std::vector<uint8>, or update an sf::Texture directly from your existing buffer, to prevent making an unnecessary copy of it:


Once your buffer is copied to the texture it can be rendered in the same way as any other sf::Texture/sf::Sprite combo, presumably including your video overlays.

You can return the render texture to an image with sf::Texture::copyToImage() although it's not particularly swift:


At this point I'd be tempted to use some OpenGL directly to copy the output stright to your buffer - although it's worth trying first to see what kind of performance you get.

Graphics / Re: sf::Text::setString() doesn't work for inconstant integers
« on: October 09, 2021, 11:00:01 am »
FPS = to_string(int(1.f / *dt))

Even if that's not the solution it always helps to be explicit with your constant types (1, 1u, 1ul, 1.f, 1.0 etc...) to be better sure than implicit conversions like this.

As a side note it's not really necessary to pass dt as a pointer, when passing by value will do, if only because it'll be copying a smaller 32bit float float instead of a 64bit pointer  ;) Here is an interesting discussion on the topic: https://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference and one, for when you do pass by reference, on const correctness: https://isocpp.org/wiki/faq/const-correctness

As a side note a comparison should be

    gameNotStarted == true


    gameNotStarted = true

 otherwise you're just assigning the value of true to the variable.

Graphics / Re: Drawing Visual Noise Quickly
« on: September 05, 2021, 11:57:46 am »
Much of game making boils down to 'faking it' quite often ;) However the fastest way to do something like this programatically (and most fun way imo, cos shaders are awesome  8) ) is to use a noise shader like this:

    const std::string GreyFrag = R"(
        #version 120
        #define GREY


    const std::string ColourFrag = R"(
        #version 120


    const std::string NoiseFrag = R"(
        uniform float u_time;

        float rand(vec2 pos)
            return fract(sin(dot(pos, vec2(12.9898, 4.1414) + u_time)) * 43758.5453);

        void main()
#if defined (GREY)
            gl_FragColor.rgb = vec3(rand(floor((gl_FragCoord.xy))));
            // these are arbitrary numbers just to provide an offset.
            // you could use uniform values here for a variable effect
            gl_FragColor.r = rand(floor((gl_FragCoord.xy + 17.034765)));
            gl_FragColor.g = 1.0 - rand(floor((gl_FragCoord.xy)));
            gl_FragColor.b = rand(floor((gl_FragCoord.xy + 0.145)));

            gl_FragColor.a = 1.0;

int main()
    sf::RenderWindow window(sf::VideoMode(400, 200), "SFML works!");
    sf::CircleShape shape(100.f);

    sf::Shader greyShader;
    greyShader.loadFromMemory(GreyFrag + NoiseFrag, sf::Shader::Fragment);

    sf::Shader colourShader;
    colourShader.loadFromMemory(ColourFrag + NoiseFrag, sf::Shader::Fragment);

    sf::Clock shaderClock;

    while (window.isOpen())
        sf::Event event;
        while (window.pollEvent(event))
            if (event.type == sf::Event::Closed)

        float shaderTime = shaderClock.getElapsedTime().asSeconds();
        greyShader.setUniform("u_time", shaderTime);
        colourShader.setUniform("u_time", shaderTime);

        shape.setPosition(0.f, 0.f);
        window.draw(shape, &greyShader);
        shape.setPosition(200.f, 0.f);
        window.draw(shape, &colourShader);

    return 0;

General / Re: Project Files Organization
« on: May 29, 2021, 11:02:12 am »
That's an interesting question. In the world of C++ which is peppered with people preaching best practices and codes of conduct, I've never really seen an article or heard someone talk about file organisation. That's not to say no one ever has, I've just never met them :)

Personally I think it's down to preference, although the type of project does influence how I lay out my source directory. For instance both of my libraries have a relatively oragnised structure with files placed in directories based on what they do, eg graphics or audio. The header files are arranged like this too (much in the same way as SFML's) because it makes it much easier to include them in another project.

On the other hand, for projects which use those libraries I tend to dump all the files in a  single src folder, or possibly split them into src/include. This is mostly down to laziness as I tend to assume that, unlike libraries, I'll be the only person that ever really uses them :)

SFML projects / Re: Purcitop Garden - A mini adventure game
« on: May 12, 2021, 11:35:17 am »
Thanks for giving it a play!

You're quite right to point out all the mazes can get very repetitive. When I first started this project it was actually just to test to some procedural generation theory - originally it was just a never ending series of mazes! However, once I'd poured some significant time into it (this was back at the beginning of the first lockdown) I decided it was a waste to let it disappear into my bucket of unfinished projects which is when I started adding the story to it.

Originally I was looking at making it something like Alice in Wonderland, or one of the studio Ghibli stories. In fact the lead character was actually blonde to start with, but I changed her hair colour to make make her stand out more against the background. It also made her look more like American McGee's Alice, rather than Disney's  ;) The character of the daughter is loosely based on Chihiro from Spirited Away. Coincidentally it also made the characters look a bit like friends of mine, which, as it turns out, influenced the game further down the line...
I'd also read somewhere a quote from Steven Spielberg who had said one of the keys to making a fantasy story believable is to start it founded in real life - before dropping your characters down a rabbit hole (or into a talking TV ;) ), which is where the train ride comes from (that and, again, Spirited Away). The character of the Professor is actually an extension of an invisible character in another one of my games Mow Problem - I had actually considered making the entire experience basically one large advert for it, but wisely decided not to in the end  ;D

With this in mind it was a fairly logical step to add more mini-games, platform sections and collectibles and so on, to try and break the mazes up as much as possible. It worked to a certain extent, but I never finished some of the planned features such as the 'greenhouse' mode, where you could plant the seeds found in the main game, and nurture them in an entirely separate context - kind of like a plant based Tamagotchi. I may revisit this idea sometime in the future and add it via an update.

In the end it was just a fun project to make, and has proven quite popular with people who play it with their children - possibly because it only takes an hour or so to complete and can be done with a short attention span  8)

If I add any new features, I'll be sure to post them here!

Pages: 1 2 [3] 4 5 ... 32