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 - jokoon

Pages: [1] 2 3
1
General / Making SFML work with WSL2
« on: November 13, 2021, 12:59:04 pm »
WSL2 now supports gui applications!

Since I was quite annoyed by visual studio, I decided to use WSL2 and make as a dev environnement. I've read it works on win10 not only win11.

Installing WSL is pretty straightforward, I'll let you do it. I reinstalled my WSL image and added the WSL kernel update provided by microsoft.

sudo apt install libsfml-dev
works.


My make script builds fine.

I'm now getting:

Failed to open X11 display; make sure the DISPLAY environment variable is set correctly
Aborted

I tried
export DISPLAY=:0
and other things, I installed vcxsrv.exe, and I still get the error.

Then you must do

export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0
export LIBGL_ALWAYS_INDIRECT=0

In your WSL terminal.

Then run xlaunch.exe and tick the right boxes like in the linked image.



It works!

2
The goal here is to create noise, render on a framebuffer, pull the data on the CPU (done in pull()). I don't need to do further rendering with opengl in the loop, I only need it at the beginning.

I load glad after initializing my SFML window, and my opengl code works fine.

The problem is drawing things with SFML again.

I've read the example and the tutorial but I fail to understand what is going wrong...

Here is the code.

Shader class

#ifndef SHADER_H
#define SHADER_H

#include <glad/glad.h>
#include <glm/glm.hpp>

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
namespace gl_things {
    class Shader
    {
    public:
        unsigned int ID;
        // constructor generates the shader on the fly
        // ------------------------------------------------------------------------
        Shader() {}
        Shader(const char* vertexPath, const char* fragmentPath)
        {
            // 1. retrieve the vertex/fragment source code from filePath
            std::string vertexCode;
            std::string fragmentCode;
            std::ifstream vShaderFile;
            std::ifstream fShaderFile;
            // ensure ifstream objects can throw exceptions:
            vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
            fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
            try
            {
                // open files
                vShaderFile.open(vertexPath);
                fShaderFile.open(fragmentPath);
                std::stringstream vShaderStream, fShaderStream;
                // read file's buffer contents into streams
                vShaderStream << vShaderFile.rdbuf();
                fShaderStream << fShaderFile.rdbuf();
                // close file handlers
                vShaderFile.close();
                fShaderFile.close();
                // convert stream into string
                vertexCode = vShaderStream.str();
                fragmentCode = fShaderStream.str();
            }
            catch (std::ifstream::failure e)
            {
                std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
            }
            const char* vShaderCode = vertexCode.c_str();
            const char * fShaderCode = fragmentCode.c_str();
            // 2. compile shaders
            unsigned int vertex, fragment;
            int success;
            char infoLog[512];
            // vertex shader
            vertex = glCreateShader(GL_VERTEX_SHADER);
            glShaderSource(vertex, 1, &vShaderCode, NULL);
            glCompileShader(vertex);
            checkCompileErrors(vertex, "VERTEX");
            // fragment Shader
            fragment = glCreateShader(GL_FRAGMENT_SHADER);
            glShaderSource(fragment, 1, &fShaderCode, NULL);
            glCompileShader(fragment);
            checkCompileErrors(fragment, "FRAGMENT");
            // shader Program
            ID = glCreateProgram();
            glAttachShader(ID, vertex);
            glAttachShader(ID, fragment);
            glLinkProgram(ID);
            checkCompileErrors(ID, "PROGRAM");
            // delete the shaders as they're linked into our program now and no longer necessery
            glDeleteShader(vertex);
            glDeleteShader(fragment);

        }
        // activate the shader
        // ------------------------------------------------------------------------
        void use() const
        {
            glUseProgram(ID);
        }
        // utility uniform functions
        // ------------------------------------------------------------------------
        void setBool(const std::string &name, bool value) const
        {
            glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
        }
        // ------------------------------------------------------------------------
        void setInt(const std::string &name, int value) const
        {
            glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
        }
        // ------------------------------------------------------------------------
        void setFloat(const std::string &name, float value) const
        {
            glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
        }
        // ------------------------------------------------------------------------
        void setVec2(const std::string &name, const glm::vec2 &value) const
        {
            glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
        }
        void setVec2(const std::string &name, float x, float y) const
        {
            glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
        }
        // ------------------------------------------------------------------------
        void setVec3(const std::string &name, const glm::vec3 &value) const
        {
            glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
        }
        void setVec3(const std::string &name, float x, float y, float z) const
        {
            glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
        }
        // ------------------------------------------------------------------------
        void setVec4(const std::string &name, const glm::vec4 &value) const
        {
            glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
        }
        void setVec4(const std::string &name, float x, float y, float z, float w) const
        {
            glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
        }
        // ------------------------------------------------------------------------
        void setMat2(const std::string &name, const glm::mat2 &mat) const
        {
            glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
        }
        // ------------------------------------------------------------------------
        void setMat3(const std::string &name, const glm::mat3 &mat) const
        {
            glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
        }
        // ------------------------------------------------------------------------
        void setMat4(const std::string &name, const glm::mat4 &mat) const
        {
            glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
        }

    private:
        // utility function for checking shader compilation/linking errors.
        // ------------------------------------------------------------------------
        void checkCompileErrors(GLuint shader, std::string type)
        {
            GLint success;
            GLchar infoLog[1024];
            if (type != "PROGRAM")
            {
                glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
                if (!success)
                {
                    glGetShaderInfoLog(shader, 1024, NULL, infoLog);
                    std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
                }
            }
            else
            {
                glGetProgramiv(shader, GL_LINK_STATUS, &success);
                if (!success)
                {
                    glGetProgramInfoLog(shader, 1024, NULL, infoLog);
                    std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
                }
            }
        }
    };
}
#endif

actual code

//#include "stdafx.h"
#include <algorithm>

#include <iostream>
#include <string>
#include <vector>
#include <map>

#include <SFML/Graphics.hpp>

//#include <SFML/OpenGL.hpp>
//#include <Box2D\Box2D.h>
using namespace std;
using namespace sf;

#include "glad\glad.h"
//#define GLAD_GL_IMPLEMENTATION
//#include "gl.h"

#include "shader_m.h"
#include <SFML\Window\ContextSettings.hpp>

typedef Vector2f Vec2;
typedef Vector2<double> Vec2d;
typedef Vector2i Vec2i;

#define msg(s) cout<< #s << " " << s << endl;

RenderWindow * window;
Vec2i windowsize;

namespace perlin_shading {
    gl_things::Shader ourShader;

    float vertices[] = {
        // positions          // colors           // texture coords
        // 0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f, // top right
        // 0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f, // bottom right
        //-0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f, // bottom left
        //-0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f  // top left
         1.f,  1.f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f, // top right
         1.f, -1.f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f, // bottom right
        -1.f, -1.f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f, // bottom left
        -1.f,  1.f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f  // top left
    };
    unsigned int indices[] = {
        0, 1, 3, // first triangle
        1, 2, 3  // second triangle
    };
    unsigned int VBO, VAO, EBO;
    unsigned int texture, tex32F, fbo;

    void init_geom() {
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);
        glGenBuffers(1, &EBO);

        glBindVertexArray(VAO);

        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

        // position attribute
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
        glEnableVertexAttribArray(0);
        // color attribute
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
        glEnableVertexAttribArray(1);
        // texture coord attribute
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
        glEnableVertexAttribArray(2);

    }
    void init_framebuffer() {
        // texture with internal format `GL_RGBA32F`
        //GLuint tex32F = texture;
        glGenTextures(1, &tex32F);
        glBindTexture(GL_TEXTURE_2D, tex32F);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 300, 300, 0, GL_RED, GL_FLOAT, nullptr);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        // framebuffer with attached texture
        //fbo = 0;
        glGenFramebuffers(1, &fbo);
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex32F, 0);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        {
            // In both cases you should validate the completeness of the frambuffer glCheckFramebufferStatus:
            glBindFramebuffer(GL_FRAMEBUFFER, fbo);
            int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
            if (status != GL_FRAMEBUFFER_COMPLETE) {
                glBindFramebuffer(GL_FRAMEBUFFER, 0);
                msg("glCheckFramebufferStatus error");
            }
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
        }

    }

    void pull() {
        //glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        {
            glViewport(0, 0, 300, 300);
            // bind Texture
            ourShader.use();
            glBindTexture(GL_TEXTURE_2D, texture);
            //glBindTexture(GL_TEXTURE_2D, tex32F);
            glBindVertexArray(VAO);
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        }

        //glfwSwapBuffers(window);

        // Render the image after glBindFramebuffer(GL_FRAMEBUFFER, fbo). After the rendering by the shader the image is stored in the texture object, because the texture is attached to the color plane of fbo. So at this point the texture can be read by glGetTexImage
        glBindTexture(GL_TEXTURE_2D, tex32F);

        float values[300 * 300];
        //glFinish();
        glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, values);

        float min_val = 1e20, max_val = -1e20;

        for (int i = 0; i < 300; ++i) {
            for (int j = 0; j < 300; ++j) {
                float val = values[i + 300 * j];
                max_val = max(val, max_val);
                min_val = min(val, min_val);
            }
        }
        msg(max_val);
        msg(min_val);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

    }
    int do_things() {

        window->setActive(true);
        {
            if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(sf::Context::getFunction)))
            //if (!gladLoadGL())
            {
                std::cout << "Failed to initialize GLAD" << std::endl;
                return -1;
            }
            ourShader = gl_things::Shader("shaders/quad.vs", "shaders/perlin2.fs");

            init_geom();
            init_framebuffer();
            pull();
        }
        window->setActive(false);

        window->resetGLStates();

    }
}

// initializing the window
void init_window() {
    Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) };

    windowsize = Vec2i(0.5f*screen_resolution.x, 0.9f*screen_resolution.y);

    // placing the window on the desktop
    Vec2i windowpos;
    VideoMode::getDesktopMode().height;

    windowpos = Vec2i(
        screen_resolution.x - windowsize.x - 10,
        screen_resolution.y - windowsize.y - 40
    );
    //auto opengl = cfg.getvar<Vec2i>("opengl");
    // ContextSettings::Core
    //ContextSettings settings(0, 0, 0, 4, 5);
    ContextSettings settings(0, 0, 0, 3, 3);

    window = new sf::RenderWindow(sf::VideoMode(windowsize.x, windowsize.y), "perlin shader");
    //window = new sf::RenderWindow(sf::VideoMode(windowsize.x, windowsize.y), "perlin shader", 7, settings);
    window->setFramerateLimit(60);
    //frame_duration = 1.0f / 60;
    window->setPosition(windowpos);
}
RectangleShape dadaism;

void draw() {

    window->pushGLStates();
    window->draw(dadaism);
    window->popGLStates();
}

void loop() {

    while (window->isOpen())
    {
        sf::Event event;
        while (window->pollEvent(event))
        {
            switch (event.type)
            {
            case sf::Event::KeyPressed:
                if (event.key.code == sf::Keyboard::Escape)
                    window->close();
                break;
            case sf::Event::Closed:
                window->close();
                break;
            default:
                break;
            }
        }

        window->clear(Color(16, 16, 16));
       
        window->pushGLStates();
        draw();
        window->popGLStates();
       
        window->display();
    }
}
int main(int argc, char*argv[]) {

    dadaism = RectangleShape({ 50,50 });
    init_window();
    perlin_shading::do_things();


    loop();
    return 0;
}
 
fragment shader
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main()
{
    gl_Position = vec4(aPos, 1.0);
    ourColor = aColor;
    TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}
 
vertex shader
#version 330 core
out vec4 FragColor;
// out float FragColor;

in vec3 ourColor;
in vec2 TexCoord;


void main(){
    vec3 debugged = vec3(TexCoord.xy,0);
    FragColor = vec4(0.34,0,0, 1.0f);
    // FragColor = 0.34;
}
 



3
I wrote a shader that generates noise, it uses gl_TexCoord[0].xy (a thing generated by SFML) as input and outputs a float for every pixel.

I want the data on the CPU, as an array of 32bits float.

Here is what I'm doing:

    //using opengl 3.0 (I also tried 3.2)
    ContextSettings settings(0, 0, 0, 3, 0);
    sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y),
        "yada", 7, settings
    );


Here I overwrite the texture after the texture is created:

 
#ifndef GL_R32F
#define GL_R32F 0x822E // found this in glad.h for opengl 3.0, easy guess is that this value doesn't change across opengl versions
#endif
auto handle = sprite_perlin.getTexture()->getNativeHandle();
glBindTexture(GL_TEXTURE_2D, handle);
auto size = sprite_perlin.getTexture()->getSize();
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, size.x, size.y, 0, GL_RED, GL_FLOAT, NULL);
        }

Here I read the texture data into values:

       
float values[4096];
// whole_size is the size of the texture, here it is 60
if(whole_size*whole_size < 4096)
    glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, values);

Image brought_back;
brought_back.create(whole_size, whole_size, Color::Red);

float mi = 1e20, ma = -1e20;

for (int i = 0; i < whole_size; ++i) {
    for (int j = 0; j < whole_size; ++j) {
        brought_back.setPixel(i, j, { 0,Uint8(255.f*values[whole_size*i + j]),0 });
        ma = max(values[whole_size*i + j], ma);
        mi = min(values[whole_size*i + j], mi);
    }
}


 

mi and ma are both to 0.0f;

Here is the noise generated when showed on a sprite with the shader (with some color function that takes a float) The shader works as intended, I would just like to retrieve the data as float on the CPU.



Here is a simplified version of the shader:
uniform int texture_size;

float get_value_at(ivec2 pixel_coord) {
    //dummy value
    return 0.34f;
}

void main(){
    ivec2 pix_pos = ivec2(gl_TexCoord[0].xy*texture_size);

    float val = get_value_at(pix_pos);

    gl_FragColor = vec4(val,0,0,1);
}


Here is an updated code, which is using rendertexture to test things out (sorry it's 417 lines, but it should work as is):

//#include "stdafx.h"
#include <random>
#include <algorithm>

#include <iostream>
#include <string>
#include <vector>
#include <map>

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/OpenGL.hpp>
//#include <Box2D\Box2D.h>
using namespace std;
using namespace sf;

typedef Vector2f Vec2;
typedef Vector2<double> Vec2d;
typedef Vector2i Vec2i;

float interp(float start, float end, float coef) { return (end - start)*coef + start; }
Vec2 interp(Vec2 start, Vec2 end, float coef) { return coef * (end - start) + start; }

vector<float> seeded_rand_float(unsigned int seed, int many) {
    vector<float> ret;
    std::mt19937 rr;
    std::uniform_real_distribution<float> dist(0, 1.0);

    rr.seed(seed);

    for (int j = 0; j < many; ++j)
        ret.push_back(dist(rr));
    return ret;
}
vector<Vec2> seeded_rand_vec2(unsigned int seed, int many) {
    auto coeffs1 = seeded_rand_float(seed, many * 2);
    vector<Vec2> pushere;
    for (int i = 0; i < many; ++i)
        pushere.push_back(Vec2(coeffs1[2 * i], coeffs1[2 * i + 1]));
    return pushere;
}
#define msg(s) cout<< #s << " " << s << endl;

RenderWindow * window;
RenderTarget * target;
namespace labground {
    Vec2 winsize, wincenter;
    Vec2i windowsize;
    Vec2 mpos_abs, mpos;


    //logfile lf;
    //configfile cfg;
    Transform transf_glob;

    Vec2 tr(Vec2 p) {
        return transf_glob.transformPoint(p);
    };
    Vec2 untr(Vec2 p) {
        return transf_glob.getInverse().transformPoint(p);
    };

    View view, ui_view;
   
    // zooming
    float zoom_mult = 1.5f;
    float zoom_div = 1.0f / zoom_mult;
    float zoomlevel = 1;

    void zoom (Event&e) {
        using namespace labground;
        mpos_abs = window->mapPixelToCoords(Vec2i(mpos), view);

        // msg(view.getSize());
        // msg(view.getCenter());

        //view = window->getView();
        if (e.mouseWheel.delta < 0) {
            zoomlevel *= zoom_mult;
            view.setSize(view.getSize()*zoom_mult);
            auto center = interp(mpos_abs, view.getCenter(), zoom_mult);
            center = Vec2(Vec2i(center));
            view.setCenter(center);
        }
        if (e.mouseWheel.delta > 0) {
            zoomlevel *= zoom_div;
            view.setSize(view.getSize()*zoom_div);
            auto center = interp(mpos_abs, view.getCenter(), zoom_div);
            view.setCenter(center);
        }
        window->setView(view);
    };
}

namespace perlin_shading {
    Shader perlin_shader;

    sf::Texture texture_shader, texture_broughtback;
    sf::Sprite sprite_perlin, sprite_broughtback, sprite_rtext;
    Image img_back;
    typedef Vec2i ivec2;
    typedef Vec2 vec2;

    float sprite_scale;

    int grad_size, grad_quant, whole_size;
    Vec2 gradients[16];
    Vec2 gradients_ctype[4096];
    RenderTexture rtext;

    void init_perlin() {
        perlin_shader.loadFromFile("shaders/perlin-better.frag", sf::Shader::Fragment);
        //perlin_shader.loadFromFile("shaders/" + cfg.getstr("shader_file"), sf::Shader::Fragment);
        //perlin_shader.loadFromFile("shaders/noisebench.vert", "shaders/" + cfg.getstr("shader_file"));
        perlin_shader.setUniform("grad_size", grad_size);
        perlin_shader.setUniform("grad_quant", grad_quant);

        //perlin_shader.setUniformArray("gradients", gradients, grad_quant*grad_quant);
        perlin_shader.setUniformArray("gradients", gradients_ctype, grad_quant*grad_quant);

        //texture.loadFromFile("pics/orxqx6B.png");

        //sprite_perlin.move(wincenter);

        Image img;
        //img.create(400, 400, Color::Black);
        img.create(whole_size, whole_size, Color::Red);
        for (int i = 0; i < 10; ++i) {
            img.setPixel(i * 2, i, Color::Green);
            img.setPixel(i, i * 2, Color::Red);
            img.setPixel(i, i, Color::Yellow);
            img.setPixel(i / 2, i, Color::Cyan);
            img.setPixel(i, i / 2, Color::Magenta);
        }
        texture_shader.loadFromImage(img);
        //shader.setUniform("texture", sf::Shader::CurrentTexture);
        //perlin_shader.setUniform("v_texCoord4D", Glsl::Vec4(1,1,1,1));

        sprite_perlin.setTexture(texture_shader);
        {
#ifndef GL_R32F
#define GL_R32F 0x822E
#endif
            auto handle = sprite_perlin.getTexture()->getNativeHandle();
            glBindTexture(GL_TEXTURE_2D, handle);
            auto size = sprite_perlin.getTexture()->getSize();
            glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, size.x, size.y, 0, GL_RED, GL_FLOAT, NULL);
        }
        sprite_perlin.move(labground::wincenter);
        sprite_perlin.setScale(sprite_scale, sprite_scale);


        //sprite_perlin.setScale(sprite_scale, sprite_scale);
    }

    void pull_data() {
        using namespace perlin_shading;

        float values[4096];
        /*
        void glGetTexImage(
            GLenum target,
            GLint level,
            GLenum format,
            GLenum type,
            GLvoid * pixels);

        void glTexImage2D(      GLenum target,
            GLint level,
            GLint internalformat,
            GLsizei width,
            GLsizei height,
            GLint border,
            GLenum format,
            GLenum type,
            const GLvoid * data);

        void glReadPixels(      GLint x,
            GLint y,
            GLsizei width,
            GLsizei height,
            GLenum format,
            GLenum type,
            GLvoid * data);


            */

        float mi = 1e20, ma = -1e20;

        // format = GL_RED, type = GL_FLOAT
        //window->clear();
        //window->draw(sprite_broughtback);
        if (false) {
            if (whole_size*whole_size < 4096)
            {
                //glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, values);
                //glReadPixels(0, 0, whole_size, whole_size, GL_RED, GL_FLOAT, values);
            }
            Image brought_back;
            brought_back.create(whole_size, whole_size, Color::Red);


            for (int i = 0; i < whole_size; ++i) {
                for (int j = 0; j < whole_size; ++j) {
                    ma = max(values[whole_size*i + j], ma);
                    mi = min(values[whole_size*i + j], mi);
                }
            }
            msg(ma);
            msg(mi);
       
        }

        //texture_broughtback.loadFromImage(brought_back);
        rtext.create(whole_size, whole_size);
       
        {
            rtext.clear();
            rtext.display();
            rtext.draw(sprite_perlin, &perlin_shader);

            sprite_rtext.setTexture(rtext.getTexture());

            glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, values);
        }

        for (int i = 0; i < whole_size; ++i) {
            for (int j = 0; j < whole_size; ++j) {
                ma = max(values[whole_size*i + j], ma);
                mi = min(values[whole_size*i + j], mi);
            }
        }
        msg(ma);
        msg(mi);

        //img_back = rtext.getTexture().copyToImage();
        //texture_broughtback.loadFromImage(img_back);

        //sprite_broughtback.setTexture(texture_broughtback);
       
        // scales and positions
        sprite_broughtback.setScale(sprite_scale, sprite_scale);
        sprite_rtext.setScale(sprite_scale, sprite_scale);
       
        sprite_broughtback.move({ 0,labground::wincenter.y });
        sprite_rtext.move({ labground::wincenter.x,0 });
       
        auto error = glGetError();
        msg(error);
    }

    void init() {
        grad_size = 20;
        grad_quant = 4;
        whole_size = grad_size * (grad_quant - 1);

        if (grad_quant*grad_quant > 4096) { msg("can't send gradients, please allocate a large C-type array in the code below!"); return; }
        {
            int seed = 43123;
            auto rand_v = seeded_rand_vec2(seed, grad_quant*grad_quant);
            for (int i = 0; i < grad_quant*grad_quant; ++i) {
                gradients_ctype[i] = 2.0f*rand_v[i] - Vec2{ 1.f, 1.0f };
            }

        }

        msg(grad_size);
        msg(grad_quant);
        msg(whole_size);

        auto smallest_size = min(labground:: windowsize.x, labground::windowsize.y);
        sprite_scale = 0.5f* smallest_size / whole_size;
        init_perlin();
        pull_data();
    }

    void draw(RenderTarget * target) {
        //target->draw(sprite_perlin, &perlin_shader);
        target->draw(sprite_perlin, &perlin_shader);
        target->draw(sprite_broughtback);
        target->draw(sprite_rtext);
    }
    void mouse_moved(Vec2 mpos_abs) {
        auto pixel = ivec2(mpos_abs / sprite_scale);
        pixel.x = max(0, min(whole_size - 1, pixel.x));
        pixel.y = max(0, min(whole_size - 1, pixel.y));
    }
}

// treating SFML events
void mouse_moved(Vec2 pos) {
};
void mouse_click (sf::Mouse::Button button) {
};
void mouse_release (sf::Mouse::Button button) {
    if (button == Mouse::Button::Left) {
    }
};
void treat_other_event (Event&e) {
    if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta){
        labground::zoom(e);
    }
};
void treat_key_event(Keyboard::Key k) {
    switch (k)
    {
    case Keyboard::E:
        break;
    case Keyboard::I:

        break;
    case Keyboard::Q:
        break;
    case Keyboard::BackSpace:
        break;

    case Keyboard::Space:
        break;

    case Keyboard::S:
        break;
    case Keyboard::Num1:
        break;
    case Keyboard::Num2:
    case Keyboard::Num3:
    case Keyboard::Num4:
    case Keyboard::Num5:
        break;
    }
};
#include <SFML\Window\ContextSettings.hpp>
// initializing the window
void init_window() {
    using namespace labground;
    Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) };

    windowsize = Vec2i(0.5f*screen_resolution.x, 0.9f*screen_resolution.y);
    //winsize = Vec2(windowsize);
    wincenter = 0.5f*Vec2(windowsize);
   
    // placing the window on the desktop
    Vec2i windowpos;
    VideoMode::getDesktopMode().height;

    windowpos = Vec2i(
        screen_resolution.x - windowsize.x - 10,
        screen_resolution.y - windowsize.y - 40
    );
    //auto opengl = cfg.getvar<Vec2i>("opengl");
    // ContextSettings::Core
    //ContextSettings settings(0, 0, 0, 4, 5);
    ContextSettings settings(0, 0, 0, 3, 0);

    //sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y), "perlin shader");
    window = new sf::RenderWindow(sf::VideoMode(windowsize.x, windowsize.y), "perlin shader", 7, settings);
    window->setFramerateLimit(60);
    //frame_duration = 1.0f / 60;

    window->setPosition(windowpos);

    ui_view = view = window->getDefaultView();

}

void draw() {
    using namespace labground;
    window->setView(view);
    //////////////// OBJECTS THAT CAN BE ZOOMED ////////////////

    perlin_shading::draw(window);

    //////////////// OBJECTS THAT CANNOT BE ZOOMED ////////////////
   
    window->setView(ui_view);
}
void loop() {
    using namespace labground;
    while (window->isOpen())
    {
        sf::Event event;
        while (window->pollEvent(event))
        {
            switch (event.type)
            {
            case sf::Event::KeyPressed:
                if (event.key.code == sf::Keyboard::Escape)
                    window->close();
                treat_key_event(event.key.code);
                break;
            case sf::Event::Closed:
                window->close();
                break;
            case sf::Event::MouseButtonPressed:
                mouse_click(event.mouseButton.button);
                break;
            case sf::Event::MouseButtonReleased:
                mouse_release(event.mouseButton.button);
                break;
            case sf::Event::MouseMoved:
                mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
                mpos_abs = window->mapPixelToCoords(Vec2i(mpos), view);
                mouse_moved(mpos);
                break;
            default:
                treat_other_event(event);
                break;
            }
        }

        window->clear(Color(16,16,16));
        //update();
        draw();
        window->display();
    }

}
int main(int argc, char*argv[]) {
    init_window();
    perlin_shading::init();
    loop();
}

4
Feature requests / Re: Add .setSmooth() for text
« on: December 07, 2018, 12:00:28 pm »


I'm having a similar issue, I'm zooming using a sf::View, is it possible to have font textures not smoothed?

5
Feature requests / Re: Making SFML work with web assembly?
« on: July 06, 2018, 06:49:54 pm »
I think WASM doesn't really allow OpenGL calls directly, at least not through the C API, but through WebGL calls.

I don't really know how you make JS calls from WASM and vice versa, but obviously that would be painful to adapt SFML to WASM since you would add js code to make WASM work.

I don't think WASM will allow direct C OpenGL calls in the future (but I really wish it could happen), seen how complex it is to map C functions to system/driver calls. Peeking at what glad/glew does is enough to understand that things are not simple, seen the multiple opengl versions, core or compatibility, chip bugs, etc.

So in short, my former question was naive and uninformed, but there might be details I'm not aware about.

6
Python / Re: Building pysfml on windows?
« on: May 13, 2018, 11:34:25 pm »
Ok so I finally did it.


What needed to be changed:

line 60 add line

self.compiler.include_dirs.append(os.path.join(self.build_temp, 'C:\\_code\\libs\\SFML-2.5.0\\include\\'))

line 78, change line

library_dirs=[os.path.join('extlibs', 'libs-msvc-universal', arch)]+['C:\\_code\\libs\\SFML-2.5.0\\lib\\'] if sys.hexversion >= 0x03050000 else [],

line 126, change line

dlls = [("Lib\\site-packages\\sfml", glob('extlibs\\' + arch + '\\openal32.dll'))]+[("sfml\\", glob('C:\\_code\\libs\\SFML-2.5.0\\bin\\*'))]

The catch is that the DLLs will be copied to /sfml instead of Libs/site-package/sfml


Here is my final setup.py

import sys, os, platform
import os.path, shutil
from glob import glob
from subprocess import call
from setuptools import setup, Command, Extension

try:
    from Cython.Distutils import build_ext
except ImportError:
    print("Please install cython and try again.")
    raise SystemExit

if platform.architecture()[0] == "32bit":
        arch = "x86"
elif platform.architecture()[0] == "64bit":
        arch = "x64"

class CythonBuildExt(build_ext):
    """ Updated version of cython build_ext command to deal with the
        generated API headers. C/C++ header files are all moved to the
        temporary build directory before being properly installed on
        the system.
    """


    def cython_sources(self, sources, extension):

        # cythonize .pxd source files
        ret = build_ext.cython_sources(self, sources, extension)

        # should result the module name; e.g, graphics[.pyx]
        module = os.path.basename(sources[0])[:-4]

        # prepare a list with all header files related to the module (*.hpp, *_api.h, *.h)
        header_files = glob(os.path.join('src', 'sfml', module, '*.hpp'))

        header_files.append(os.path.join('src', 'sfml', module, module + '.h'))
        header_files.append(os.path.join('src', 'sfml', module, module + '_api.h'))

        # deal with exceptions
        if module == "network":
            header_files.remove(os.path.join('src', 'sfml', module, module + '.h'))
            header_files.remove(os.path.join('src', 'sfml', module, module + '_api.h'))

        # create the temporary destination in the build directory
        destination = os.path.join(self.build_temp, 'include', 'pysfml', module)

        if not os.path.exists(destination):
            os.makedirs(destination)

        # move all header files to the build directory
        for header_file in header_files:
            if os.path.isfile(header_file):
                try:
                    shutil.copy(header_file, destination)
                except shutil.Error:
                    pass

        # add the temporary header directory to compilation options
        self.compiler.include_dirs.append(os.path.join(self.build_temp, 'include'))
        self.compiler.include_dirs.append(os.path.join(self.build_temp, 'C:\\_code\\libs\\SFML-2.5.0\\include\\'))

        # update data_files to install the files on the system

        # On Windows: C:\Python27\include\pysfml\*_api.h
        # On Unix: /usr/local/include/pysfml/*_api.h
        install_directory = os.path.join(sys.exec_prefix, 'include', 'pysfml', module)
        files_to_install = [os.path.join(self.build_temp, 'include', 'pysfml', module, os.path.basename(header_file)) for header_file in header_files]
        data_files.append((install_directory, files_to_install))

        return ret

modules = ['system', 'window', 'graphics', 'audio', 'network']

extension = lambda name, files, libs: Extension(
        name='sfml.' + name,
        sources= [os.path.join('src', 'sfml', name, filename) for filename in files],
        include_dirs=[os.path.join('include', 'Includes')],
        library_dirs=[os.path.join('extlibs', 'libs-msvc-universal', arch)]+['C:\\_code\\libs\\SFML-2.5.0\\lib\\'] if sys.hexversion >= 0x03050000 else [],
        language='c++',
        libraries=libs,
        define_macros=[('SFML_STATIC', '1')] if platform.system() == 'Windows' else [])

if platform.system() == 'Windows':
        system_libs   = ['winmm', 'sfml-system-s']
        window_libs   = ['user32', 'advapi32', 'winmm', 'sfml-system-s', 'gdi32', 'opengl32', 'sfml-window-s']
        graphics_libs = ['user32', 'advapi32', 'winmm', 'sfml-system-s', 'gdi32', 'opengl32', 'sfml-window-s', 'freetype', 'jpeg', 'sfml-graphics-s']
        audio_libs    = ['winmm', 'sfml-system-s', 'flac', 'vorbisenc', 'vorbisfile', 'vorbis', 'ogg', 'openal32', 'sfml-audio-s']
        network_libs  = ['ws2_32', 'sfml-system-s', 'sfml-network-s']
else:
        system_libs   = ['sfml-system']
        window_libs   = ['sfml-system', 'sfml-window']
        graphics_libs = ['sfml-system', 'sfml-window', 'sfml-graphics']
        audio_libs    = ['sfml-system', 'sfml-audio']
        network_libs  = ['sfml-system', 'sfml-network']


system = extension(
    'system',
    ['system.pyx', 'error.cpp', 'hacks.cpp', 'NumericObject.cpp'],
    system_libs)

window = extension(
    'window',
    ['window.pyx', 'DerivableWindow.cpp'],
    window_libs)

graphics = extension(
    'graphics',
    ['graphics.pyx', 'DerivableRenderWindow.cpp', 'DerivableDrawable.cpp', 'NumericObject.cpp'],
    graphics_libs)

audio = extension(
    'audio',
    ['audio.pyx', 'DerivableSoundRecorder.cpp', 'DerivableSoundStream.cpp'],
    audio_libs)

network = extension(
    'network',
    ['network.pyx'],
    network_libs)

major, minor, _, _ , _ = sys.version_info

data_files = []
if platform.system() == 'Windows':
    dlls = [("Lib\\site-packages\\sfml", glob('extlibs\\' + arch + '\\openal32.dll'))]+[("sfml\\", glob('C:\\_code\\libs\\SFML-2.5.0\\bin\\*'))]
    data_files += dlls

with open('README.md', 'r') as f:
    long_description = f.read()

ext_modules=[system, window, graphics, audio, network]

install_requires = []

if sys.version_info < (3, 4):
    install_requires.append('enum34')

kwargs = dict(
            name='pySFML',
            ext_modules=ext_modules,
            package_dir={'': 'src'},
            packages=['sfml'],
            data_files=data_files,
            version='2.3.2.dev1',
            description='Python bindings for SFML',
            long_description=long_description,
            author='Jonathan de Wachter',
            author_email='dewachter.jonathan@gmail.com',
            url='http://python-sfml.org',
            classifiers=['Development Status :: 5 - Production/Stable',
                        'Intended Audience :: Developers',
                        'License :: OSI Approved :: zlib/libpng License',
                        'Operating System :: OS Independent',
                        'Programming Language :: Python :: 2',
                        'Programming Language :: Python :: 3',
                        'Programming Language :: Cython',
                        'Programming Language :: C++',
                        'Programming Language :: Python',
                        'Programming Language :: Python :: Implementation :: CPython',
                        'Topic :: Games/Entertainment',
                        'Topic :: Multimedia',
                        'Topic :: Software Development :: Libraries :: Python Modules'],
            keywords='sfml SFML simple fast multimedia system window graphics audio network pySFML PySFML python-sfml',
            install_requires=install_requires,
            cmdclass={'build_ext': CythonBuildExt})

setup(**kwargs)

7
Python / Building pysfml on windows?
« on: May 12, 2018, 04:45:37 pm »
Since python is one of my favorite languages and I use it for quick prototyping, I wanted to build pysfml on windows.

I did this on windows 10, with visual studio 2015 and python 3.5.something.

WARNING I am not a maintainer and by no means a build system guru, so if this sounds dirty, it's normal.

swig http://www.swig.org/download.html (windows version) (add its directory in your path so that setup.py can later call it) (required to build cython)

a pre compiled version of sfml, I chose the 64 version

Installing cython

pip install cython

cloning the pysfml repo

git clone https://github.com/Sonkun/python-sfml

and building it

python setup.py install

Editing setup.py

The script needs a few adjustments

line 60 add the include folder line this:

self.compiler.include_dirs.append(os.path.join(self.build_temp, 'C:\\_code\\libs\\SFML-2.5.0\\include'))

and line 81:

library_dirs=[os.path.join('extlibs', 'libs-msvc-universal', arch)]+[os.path.join('C:\\_code\\libs\\SFML-2.5.0\\lib')] if sys.hexversion >= 0x03050000 else [],

Everything builds fine when I run:

python setup.py install

when importing sf, I now have

ImportError: DLL load failed: The specified module could not be found.

8
Feature requests / Making SFML work with web assembly?
« on: November 14, 2017, 02:54:01 pm »
Have anybody tried to build SFML to the WASM format? I've seen that wasm allows opengl calls.

It would be really cool to have SFML run in a browser :)

9
Feature requests / C++ modules for SFML
« on: March 12, 2016, 02:49:59 pm »
I've seen some video presentations of modules. It seems they're available in VS2015, and I guess they are also available with clang.

I just wanted to know if some of you guys tried them, and to poke around to see how cumbersome it would be to build sfml as modules (for VS2015 is seems to revolve around those .ifc files) for vs2015, clang or both. No idea if GCC support them though...

Reminder: modules essentially allows for much faster building times, and in some way are a "standardized" precompiled header.

Usually, instead of

#include <vector>
#include "SFML/Graphics.hpp"

you do

import std.vector
import sf.graphics

I did not try them yet, so I don't know how trivial it would be to use them for a library like SFML...

What do you think?

10
General / Re: Are the examples supposed to work?
« on: November 08, 2014, 02:26:06 pm »
I thought there was some example manager class or something like that...

I also thought the example were deprecated because the cmake script returned some error...

My fault :p

11
General / Re: Are the examples supposed to work?
« on: November 08, 2014, 08:34:09 am »
Oh yes, sorry.

(I did not scroll the entire .cpp file)

12
General / Re: Are the examples supposed to work?
« on: November 07, 2014, 09:55:54 pm »
If you want to know parameters of a function, check out the API documentation.

Don't use SFML 1.6, it's outdated, buggy, unmaintained and lacks a lot of features.

If you want to build the examples, just check the SFML_BUILD_EXAMPLES when building SFML.

You did not understand my question.

Where is the main() in the examples ? I could not find it.

13
General / Are the examples supposed to work?
« on: November 06, 2014, 03:55:35 pm »
I was trying to learn how to use shader in SFML, I encountered the Effect virtual class, and I wanted to know what were the argument of the update() function and where was it called.

I tried to setup the examples using CMake, I got an error:

CMake Error at ftp/CMakeLists.txt:8 (sfml_add_example):
  Unknown CMake command "sfml_add_example".

I could not find the source of SFML 1.6 either.

So how are those effects class used ? Where can I see the full code of those examples, meaning the main() ?

14
General / Re: clion and sfml?
« on: September 10, 2014, 02:23:40 pm »
Yeah, heard of clion too, I wonder how good it is.

I'm tempted to use it, as I use both MSVC and xcode for the same code. XCode's autocomplete is slow (and I don't like XCode in general), and MSVC2012 doesn't support variadic templates. Since jetbrains support both clang and GCC and gdb, I guess it would be nice. I hope the debugger is as good as MSVC's.

I guess I'll try some day. Although I'm not sure if I'd pay for an IDE. If it's over 30 euros or 30 dollars I don't think I would buy it.

Any C++ jet brain user ?

First question, do you have to recompile SFML ? I guess not, since the SFML libs use stdlib++

15
General / Re: Specializing the << operator for SFML types
« on: August 21, 2014, 06:21:26 pm »
A nice clue was to demangle those symbols. Use either demangle.com or the c++filt command. That helped me narrowing it.

Pages: [1] 2 3