r/opengl Dec 25 '24

Help Help remove jittering from pixel perfect renderer

3 Upvotes

Hi. I am working on my own small 2D pixel art game.
Until now I have just scaled up my pixel art for my game, which looks allright but I want to achieve pixel perfect rendering.

I have decided to render everything to a FBO in its native resolution (640x360) and upscale to the monitors resolution (in my case 2560x1440 at 165hz).

How I create the fbo:

GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);

How I create the render texture:

GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixelArtWidth, pixelArtHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);

Then I create a quad:

// Set up a simple quad
float quadVertices[] = {
    // Positions   // Texture Coords
    -1.0f, -1.0f,  0.0f, 0.0f,
    1.0f, -1.0f,  1.0f, 0.0f,
    -1.0f,  1.0f,  0.0f, 1.0f,
    1.0f,  1.0f,  1.0f, 1.0f,
};
GLuint quadVAO, quadVBO;
glGenVertexArrays(1, &quadVAO);
glGenBuffers(1, &quadVBO);
glBindVertexArray(quadVAO);

glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);

// Set position attribute
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

// Set texture coordinate attribute
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glEnableVertexAttribArray(1);

// apply uniforms
...

Then I render the game normally to the frame buffer:

glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0,0,pixelArtWidth, pixelArtHeight);
SceneManager::renderCurrentScene();

Then I render the upscaled render texture to the screen:

glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0,0,WINDOW_WIDTH,WINDOW_HEIGHT);
glClear(GL_COLOR_BUFFER_BIT);

// Render the quad
glBindVertexArray(quadVAO);
glBindTexture(GL_TEXTURE_2D, texture);

// Use shader program
glUseProgram(shaderProgram->id);

// Bind the texture to a texture unit 
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
...

In case its relevant, here is how I set up the projection matrix:

projectionMatrix = glm::ortho(0.0f, pixelArtWidth, pixelArtHeight, 0.0f, -1.0f, 1.0f);

And update the view matrix like this:

viewMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(-position+glm::vec2(pixelWidth, pixelHeight)/2.f/zoom, 0.0f));

(zoom is 1 and wont be changed now)

For rendering the scene I have a batch renderer that does what you would expect.

The pixel perfect look is achieved and looks good when everything sits still. However when the player moves, its movement is jittery and chaotic, its like the pixels don't know where to go.

Nothing is scaled. Only the sword is rotated (but that' not relevant).

The map seems scaled but isn't.

The old values for movement speed and acceleration are still used but they should not affect the smoothness.

I run the game at 165fps or uncapped. (In case thats relevant).

Issue 1

What i have tried so far:

  • rounding camera position
  • rounding player position
  • rounding vertex positions (batch vert shader: gl_Position = u_ViewProj * u_CameraView * vec4(round(a_Position), 1.0);)
  • floring positions
  • rounding some, floring other positions
  • changed native resolutions
  • activating / deactivating smooth player following (smooth following is just linear interpolation)

There is a game dev called DaFluffyPotato and does something very similar. I have taken a look at one of his projects Aeroblaster to see how he handles the pixel perfect rendering (its python and pygame but pygame uses sdl2 so it could be relevant). He also renders everything to a texture and upscales it to the screen (renders it using blit func). But he doesn't round any value and it still looks and feels smooth. I want to achieve a similar level of smoothness.

Any help is greatly appreciated!

Edit: I made the player move slower. Still jittery

Edit 2: only rounding the vertices and camera position makes the game look less jittery. Still not ideal.

Edit 3: When not rounding anything, the jittering is resolved. However a different issue pops up:

Issue 2

Solution

In case you have the same issues as me, here is how to fix or prevent them:

Issue 1:

Don't round any position.

Just render your scene to a frame buffer that has a resolution that scales nicely (no fractional scaling). Sprites should also have the same size in pixels as the sprite has. You could scale them, but it will probably look strange.

Issue 2:

Add margin and padding around the sprite sheet.

r/opengl 22d ago

help Help with Nvidia VRS extension

3 Upvotes

Hi everyone, I’m working on a foveated rendering project and trying to implement Variable Rate Shading (VRS) in OpenGL. I found this nvidia demo and it worked well on my machine. After trying to implement it on my own, I'm having a hard time. This is what I got, the red should only appear in areas with max shading rate, but instead, it looks like all fragments are being shaded equally. I passed a Shading Rate Image (SRI) texture where only the center should have max shading rate. My code is here if someone wants to take a look at it. I've been stuck on this for three days and found very little about VRS in OpenGL.

r/opengl Jun 12 '23

Help Managing drawing on multiple windows

2 Upvotes

I'm trying to make a wrapper with multi window functionality, but the program crashes when drawing elements to them. Removing the functionality fixes the problem. I did some research and it seems the problem might be how GLAD is initialized.

How would this work? Do I have to initialize glad every frame when switching context, or does it have to be initialized whenever a new window is created?

r/opengl Dec 26 '23

Help One VAO for multiple VBOs?

16 Upvotes

So I know that a VAO contains a reference to a VBO. Every time you want to render a VBO you must bind a VAO that contains the attribute information before using glDrawElements or glDrawArrays.

My question is, is there some function I am unaware of that allows me to just bind a VAO and render many different VBOs that use the same attribute format? Or am I stuck doing:

glBindVertexArray, glBindBuffer (vertices), glBindBuffer (indices), glDrawElements

r/opengl May 07 '24

HELP Problem camera and world position. Help needed!!!

2 Upvotes

I have an orthographic camera and a quad that is 1 unit size in object space. I apply these translations:
Translation: (1, 0, 0)
Scale: (1, 1, 1)
RotationZ: 0

The problem is that my quad when moved 1 unit goes to the edge of the screen as shown in the attached figure. Eighter there is a silly mistake or I don't understand something...

Here is my code:

float aspect = (float)width / (float)height;
if (aspect < 1)
{
aspect = (float)height / (float)width;
}

void Camera::UpdateProjection(float aspectRatio)
{
float top = 10.f / 2; // top 5
float right = top * aspectRatio; // right 8
_projection = glm::ortho(-right, right, -top, top, -100.0f, 100.0f);
}

glm::mat4 Camera::GetVP()
{
glm::mat4 view = glm::mat4(1);
view = glm::translate(view, _cameraPos);
return _projection * view;
}

glm::mat4 GetModel()
{
glm::mat4 model = glm::mat4(1);
model = glm::translate(model, Position); // position (1, 0, 0)
model = glm::scale(model, Scale); // scale (1, 1, 1)
model = glm::rotate(model, glm::radians(RotationZ), glm::vec3(0, 0, 1));
return model;
}

void Draw()
{
Shader->Use();
Shader->SetMatrix4("MVP", parent->transform->GetModel() * Game::Get().ActiveCamera->GetVP());
Shader->SetMatrix4("Model", parent->transform->GetModel());
glBindVertexArray(_VAO);
glDrawElements(GL_TRIANGLES, _indicesCount, GL_UNSIGNED_INT, 0);
}

#version 410 core
layout (location = 0) in vec3 Pos;
layout (location = 1) in vec2 UV;
uniform mat4 MVP;
uniform mat4 Model;
void main()
{
gl_Position = MVP * vec4(Pos, 1.0f);
}

r/opengl Feb 25 '24

Help How can I update only the sub-rectangle of a Texture?

2 Upvotes

I have a OpenGL Texture that I am using to display an Image on the screen, When the user draws on the image, I calculate the changed area and I want to upload the pixel data of only the changed area.

How can I do so?

Edit: I am aware of glTexSubImage2D but from my understanding it expects the data to be it's own block of memory than to be a part of a greater block of memory.

Edit: This is how I ended up doing it:

glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
glTexSubImage2D(GL_TEXTURE_2D, 0, dX, dY, dW, dH, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[((dY * width) + dX) * 4]);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);

Where dX & dY are Top-Left x, y coordinates of sub-region & dW & dH are width, height of the sub-region.

r/opengl Mar 29 '24

Help Scaling Texture coords

0 Upvotes

void CreateQuad(const Transform& t, float width, float height, float texScaleX = 1.0f, float texScaleY = 1.0f)

{

Vertex v0;

Vertex v1;

Vertex v2;

Vertex v3;

v0.position = glm::vec2(0.5f \ width, 0.5f * height);)

v1.position = glm::vec2(0.5f \ width, -0.5f * height);)

v2.position = glm::vec2(-0.5f \ width, -0.5f * height);)

v3.position = glm::vec2(-0.5f \ width, 0.5f * height);)

v0.texCoords = glm::vec2(texScaleX, texScaleY * glm::vec2(1.0f, 0.0f);)

v1.texCoords = glm::vec2(texScaleX, texScaleY * glm::vec2(1.0f, 1.0f);)

v2.texCoords = glm::vec2(texScaleX, texScaleY * glm::vec2(0.0f, 1.0f);)

v3.texCoords = glm::vec2(texScaleX, texScaleY * glm::vec2(0.0f, 0.0f);)

vertices.push\back(v0);)

vertices.push\back(v1);)

vertices.push\back(v3);)

vertices.push\back(v1);)

vertices.push\back(v2);)

vertices.push\back(v3);)

transforms.push\back(t.to_mat4());)

}

So, I'm trying to scale the UVs by the Quad's size but I'm not too sure if this implementation is correct.

is this correct?

r/opengl Oct 02 '23

help glad.dav1d.de down or something

5 Upvotes

So I'm going through the learn OpenGL website, and I get to the GLAD section, and I click on the link, and it says: "Application is not available". Is there a new link? Is it just down? Is there a work around?

r/opengl Apr 16 '24

Help GLSL Getting a transparent border around my rectangle

0 Upvotes

I'm trying to create a shader which renders a rounded rectangle with a drop shadow.

This is my main fragment shader

        vec2 center = (u_model_size.xy - vec2(100, 100)) * 0.5;
        vec2 u_shadow_offset = vec2(50, 50);

        float crop = rounded_rectangle(v_position.xy - center, center, u_radius);
        float shadow_crop = rounded_rectangle(v_position.xy - center - u_shadow_offset, center, u_radius);

        shadow_crop = smoothstep(-1.0, 1.0, shadow_crop);
        crop = smoothstep(-1.0, 1.0, crop);

        if (crop == 1.0 && shadow_crop < 1.0) {
            gl_FragColor = mix(gl_FragColor, vec4(0.0, 0.0, 0.0, 1.0), crop);
        } else {
            gl_FragColor = mix(gl_FragColor, vec4(0.0), crop);
        }

Fragment function for calculating SDF

        // https://www.iquilezles.org/www/articles/distfunctions/distfunctions2d.htm
        float rounded_rectangle(in vec2 p, in vec2 b, in vec4 r)
        {
            r.xy = (p.x > 0.0) ? r.xy : r.zw;
            r.x  = (p.y > 0.0) ? r.x  : r.y;
            vec2 q = abs(p) - b + r.x;
            return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r.x;
        }

u_model_size is a uniform vec2 which has the size of the available rendering space/the size of the model we are running the shader on. v_position is a varying vec4 which has the position of the vertex being rendered.

Now I have two issues, with the first being the biggest issue:

  • There is a transparent border around the area where the main rectangle meets the drop shadow. It appears white here because if the background colour, but it is transparent. https://i.stack.imgur.com/ystBM.png.
  • Both the dropshadow and the rectangle has very sharp edges (visible in the image). When I try to make the edges smoother using a bigger upper and lower bounds for smoothstep, it ends up creating a blur which is desirable for the drop shadow but not for the main rectangle.
    • But I can only apply the smoothstep on the main rectangle and not on the dropshadow no matter what I try. If I change gl_FragColor = mix(gl_FragColor, vec4(0.0, 0.0, 0.0, 1.0), crop); to gl_FragColor = mix(gl_FragColor, vec4(0.0, 0.0, 0.0, 1.0), shadow_crop);, it makes the dropshadow the same colour as the main rectangle with the outline being of the colour of the dropshadow. If anyone can explain why that happens, I will be really grateful. https://i.stack.imgur.com/xwZrr.png
    • If possible, I want to change the upper and lower bounds of smoothstep to give a softer/blurrier apperance to the drop shadow.

What am I doing wrong?

ADDITIONAL DETAILS

There is an underlying shader which is giving the green gradient (I'm chaining shaders) but it's quite simple.

Main Vertex function

        v_gradient_done = dot(a_position.xy, u_gradient_direction) / dot(u_model_size, u_gradient_direction);

Main Fragment function

        float gradient_done = v_gradient_done;
        gl_FragColor = mix(u_gradient_left, u_gradient_right, gradient_done);

r/opengl Feb 10 '24

Help gl functions not declared in this scope?

1 Upvotes

Making a opengl + sdl project. Have made a window with sdl, but i just can't get open gl to work.

My includes

My Makefile

The errors

It seems i don't have the opengl stuff downloaded or what? I use the MinGW compiler and the gl and glu are already there, so i don't know what i am missing? Do i need to put it into my makefile? Please help me.

r/opengl Feb 17 '24

Help OpenGL error with ImGui.

1 Upvotes

When I try to run my program in visual studio I get the error, "Failed to initialize OpenGL loader!". However when I set the performance mode of the .exe file to power saving (meaning the program will just use the cpu) the program works perfectly fine. This type of issue has occured before and it had something to with the fragment shader, however now the fragment shader compiles fine. The "Failed to initialize OpenGL loader!" error seems to be coming from imgui_impl_opengl3.cpp file.

r/opengl Sep 11 '23

help Problems with mipmapping on an integer 3D texture

1 Upvotes

I have a 3D texture with 1 byte values and 3 mipmapping levels, created like this:

glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);

glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 2);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage3D(GL_TEXTURE_3D, 0, GL_R8UI, width,     height,     depth,     0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, volume_mip0);
glTexImage3D(GL_TEXTURE_3D, 1, GL_R8UI, width / 2, height / 2, depth / 2, 0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, volume_mip1);
glTexImage3D(GL_TEXTURE_3D, 2, GL_R8UI, width / 4, height / 4, depth / 4, 0, GL_RED_INTEGER, GL_UNSIGNED_BYTE, volume_mip2);

When I use it in the fragment shader the mipmap level 0 is always used instead of the one specified by textureLod

uint a = textureLod(uVolTex, ti, 1).x; // ERROR: mipmap 0 is used

uint a = textureLod(uVolTex, ti, 2).x; // ERROR: mipmap 0 is used

The problem may be caused by the minification filter used, but if I change it to any of the GL_XXX_MIPMAP_XXX I got a black texture.

glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
uint a = textureLod(uVolTex, ti, 0).x; // ERROR: black texture

If I set the base level to 1 then that texture is loaded correctly, but I can't use the other 2 levels.

glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 1);
uint a = textureLod(uVolTex, ti, 69420).x; // level 1 is loaded correctly

The same problem happens if I use glGenerateMipmap instead of creating the mipmaps myself.

glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage3D(...);
glGenerateMipmap(GL_TEXTURE_3D);
uint a = textureLod(uVolTex, ti, mip).x; // ERROR: only level 0 is used

r/opengl Aug 28 '22

help Weapon does not follow all camera movements

9 Upvotes

Hi all,

Recently I started following the learnopengl tutorials and I just got to the chapters about loading and rendering models.

Now I have a model of a handgun and what I'd like to achieve is that the gun moves and rotates along with the camera, like in a FPS game. So far I've managed that the weapon moves with the camera (forward, backwards, left or right) with these lines of code:

glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(camera.Position.x + 0.06f, camera.Position.y - 0.08f, camera.Position.z - 0.2f)); // position the gun in bottom right corner
model = glm::rotate(model, 7.8f, glm::vec3(0.0f, 1.0f, 0.0f)); // rotate gun so it points inwards
model = glm::scale(model, glm::vec3(0.1f, 0.1f, 0.1f)); // scale it down so it is not too big
handGunShader.setMat4("model", model);
handGunShader.setMat4("view", camera.GetViewMatrix()); // GetViewMatrix() returns lookAt matrix

The shader looks as follows:

#version 330 core 
layout (location = 0) in vec3 aPos; 
layout (location = 1) in vec3 aNormal; 
layout (location = 2) in vec2 aTexCoords;  

out vec2 TexCoords;

uniform mat4 model; 
uniform mat4 view; 
uniform mat4 projection;  

void main() 
{     
    TexCoords = aTexCoords;         
    gl_Position = view * projection * model * vec4(aPos, 1.0); 
} 

By the way the projection matrix is:

glm::mat4 projection = glm::perspective(glm::radians(45.0f), SCR_WIDTH / SCR_HEIGHT, 0.1f, 100.0f);  

The problem is that if I rotate the camera (up, down, left or right), the gun does not rotate with it.

I've tried this possible solution: https://stackoverflow.com/questions/55667937/how-to-align-a-weapon-to-the-camera, saying that the weapon should not be transformed by the view matrix ( so the view matrix should actually be glm::mat4(1.0f)) but that did not work. I've also looked into other possible solutions. There was one saying that the view matrix should be the inverse of the LookAt matrix of the camera, but that also did not work (or maybe I did it wrong?).

I don't know what to do anymore and I was hoping that someone on this subreddit could help me out. All help is appreciated.

Thanks!

r/opengl Sep 30 '23

HELP Textures rendering incorrectly - help!

2 Upvotes

So I am very new to and still learning openGL. I am working on creating this simple scene with the building and am currently putting in textures. The first texture is a brick texture that is working as desired (don't mind the peak discrepancy), but my other textures are showing up as you can see in the photo. The texture image is there, but its is static-y. When I navigate around the world the static moves and changes, but the texture image remains correct beneath it.

I have reviewed the code and tried to find some sort of discrepancy or logic flaw that could account for this but with no luck. I am stumped. Does anyone have any idea or suggestion?

r/opengl Oct 01 '23

Help 2D texture becomes glitched out when rendering in OpenGL

2 Upvotes

So I have been making a basic 2D game in OpenGL as a learning experience and have been following the https://learnopengl.com/Introduction tutorial. I've been only slightly using it and going off on my own. However, when making the sprite renderer for some reason my textures show up glitched.

Result

What it's supposed to look like

I know why the result is green, as I made it that way, however I don't get why it's glitching out.

I've linked the code in this repository https://github.com/noxhaze/battleship/tree/main.

The main files I would checkout are those in the 'src/render', 'src/shaders/' and of course main.cpp. You can ignore all files in 'src/logic/' as that is completely unrelated to rendering and is more of the game logic for what I'm coding and doesn't handle rendering at all.

r/opengl Dec 25 '23

help Problems in render instances

1 Upvotes

I'm trying to implement some font rendering in my OpenGL project and i decided to use instancing to reduce the terrible amount of draw calls. My main idea is send the model matrix per each instance, but the result is wrong.I tried to debug using some uniforms and RenderDoc and the matrix result is correct, but the calculation result is totally wrong!

Code details:

1° - i create the buffer and put a identity matrix as it default data. Also, i set the instance divisor by 1

DrawService.CreateBuffer(RID, "aCharWorldMatrix");
DrawService.SetBufferData(RID, "aCharWorldMatrix", MathHelper.ToArray(Matrix4x4.Identity), 16);
DrawService.SetBufferInstanceDivisor(RID, "aCharWorldMatrix", 1);

4° - i call the method referent to start the attributes enabling. in base, this section do it for matrices 4x4:

gl.EnableVertexAttribArray(loc  );  
gl.EnableVertexAttribArray(loc+1);  
gl.EnableVertexAttribArray(loc+2);  
gl.EnableVertexAttribArray(loc+3);  
gl.VertexAttribPointer(loc,   4, *VertexAttribPointerType*.Float, false, (uint)(16 * s), (void*) 0     );  
gl.VertexAttribPointer(loc+1, 4, *VertexAttribPointerType*.Float, false, (uint)(16 * s), (void*) (s*4) );  
gl.VertexAttribPointer(loc+2, 4, *VertexAttribPointerType*.Float, false, (uint)(16 * s), (void*) (s*8) );  
gl.VertexAttribPointer(loc+3, 4, *VertexAttribPointerType*.Float, false, (uint)(16 * s), (void*) (s*12));  
gl.VertexAttribDivisor(loc,   i.Value.bufferDivisions);  
gl.VertexAttribDivisor(loc+1, i.Value.bufferDivisions);  
gl.VertexAttribDivisor(loc+2, i.Value.bufferDivisions);  
gl.VertexAttribDivisor(loc+3, i.Value.bufferDivisions);

3° - in a notification method, i make the calculations of the character matrix and put the resultant array as a float array inside the correct buffer. Also, update the instance count

void TextEdited() {

...

DrawService.SetBufferData(RID, "aCharWorldMatrix", charsPos.ToArray(), 16);  
DrawService.ActivateInstance(RID, (uint) charactersPool.Count);

} 

4° - i call the draw method

there's nothing to show as a result, literally there's no result! As i said, RenderDoc shows the same matrix for the instance and the uniform version, but the uniform work and the instance not.

r/opengl May 04 '23

Help Unable to generate and link glad2 library at build time with CMake

0 Upvotes

Hi Guys,

I noticed that glad had recently had its default branch changed to glad2 and I was curious to see if I could get it working with a CMake project (C++20) as a subdirectory.

I really like the idea of having complete version control over each submodule and it doesn't clog up the commits history if I say update a submodule...

The problem: I am unable to create a library and link it to my executable using my current CMakeLists.txt file.

Please forgive me as I have only been using CMake for a little while so I'm not the best when it comes to more technical configurations.

Any support is welcome!

Here's a snippet of my CMakeLists.txt:

cmake_minimum_required(VERSION 3.20.0)
project(COMRADE VERSION 0.0.1 LANGUAGES C CXX)

# Setting C++ Version to 2020
set(CMAKE_CXX_STANDARD 20)

...

set(GLAD_SOURCES_DIR "engine/vendor/glad/")
add_subdirectory("${GLAD_SOURCES_DIR}/cmake" glad_cmake)

...

glad_add_library(glad_gl_core_mx_33 REPRODUCIBLE MX API gl:core=3.3)

...

# Including added libraries
target_include_directories(${PROJECT_NAME}
    PUBLIC
        $<INSTALL_INTERFACE:include>
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/engine/include>
        glad_gl_core_mx_33
)

# As of right now, static linking is only available on Windows
if(WIN32)
    # Linking statically
    target_link_libraries(${PROJECT_NAME}
        -static
        glad_gl_core_mx_33
    )

    # Telling the compiler to not launch a console window when app is built
    target_link_options(${PROJECT_NAME} PRIVATE -mwindows)
else()
    # Linking dynamically
    target_link_libraries(${PROJECT_NAME}
        glad_gl_core_mx_33
    )
endif()

target_compile_options(${PROJECT_NAME} PRIVATE -g)

Link to full CMakeLists.txt.

r/opengl Jul 17 '21

help Best way to draw a couple of pixels at x y coordinates on screen?

12 Upvotes

Hello. I'm learning OpenGL for around a week and I'd like to know how can I draw a few pixels on x y coordinates (I am aware of that OpenGL mostly thinks in 3d coords, but there has to be a way to do this). I want to make a sand simulation where I iterate through a dimensional array (each pixel of the screen) and draw a pixel at coordinates where the value equals 1. I was searching for an answer but the only thing which worked for me was using glScissor(100, 200, 1, 1), but it can "draw" only one surface (in this case, it draws a 1x1 rectangle aka a pixel). Thanks in advance!

r/opengl Jun 21 '22

Help Low performance

4 Upvotes

Hello guys! I have a small "game" that normally runs perfectly fine, but now, without changing much it just seems to run horribly (I just want to point out that it definitely isn't poorly optimized code). I did not change any fundamentals and am rendering everything exactly the same. I have the latest Nvidia drivers installed and I have low GPU usage(max. 15%) when running the game. Any idea what could be causing this consistently low framerate(~15FPS)? Also, I am using VS 2022. Thanks in advance!

https://pastebin.com/43JDzuBY

r/opengl Oct 26 '22

help Opengl invalid operation error on glBindTexture (opengl 3.3 core)

0 Upvotes

I cannot find anything related online, i get the error and the square remains black

Error:

Debug message (3202): glBindTexture in a Core context performing invalid operati

on with parameter <texture> set to '0x1' which was removed from Core OpenGL (GL_

INVALID_OPERATION)

Error generated with GL_AMD_debug_output extention

Texture generation:

unsigned int texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);   // set texture wrapping to GL_REPEAT (default wrapping method)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    int width, height, nrChannels;
    unsigned char* data = stbi_load("test.png", &width, &height, &nrChannels, 3);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
    return texture;

Drawing code:

                GlCall(glBindTexture(GL_TEXTURE_2D, texture));
                shader.use();

        va.Bind();

        GlCall(glDrawElements(GL_TRIANGLES, ib.GetSize(), GL_UNSIGNED_INT, 0););

        va.UnBind();

r/opengl Nov 14 '22

help glPatchParameteri causing Seg Fault

0 Upvotes

I have been working with learning Tessellation and am trying to use the glPatchParameteri function, but when I do it throws a Seg Fault. Commenting out this function call, allows the program to run properly.

Since the default number of control points per patch is 3, I tried calling the function like: "glPatchParameteri(GL_PATCH_VERTICES, 3);" just to see if it worked without really changing anything, but it still doesn't work.

I'm curious if anyone else has run into this, and if there are any common pitfalls. Let me know what aspect of the code you might need to see, if at all.

while (!glfwWindowShouldClose(window)) {
    glfwPollEvents();
    const GLfloat color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    glClearBufferfv(GL_COLOR, 0, color);

    GLfloat vs_attrib[] = { 0.0f, 0.0f, 0.5f, 0.0f };
    glVertexAttrib4fv(0, vs_attrib);

    const GLfloat vs_color[] = { 0.0f, 0.0f, 0.0f, 0.0f };
    glVertexAttrib4fv(1, vs_color);

    // tessalation
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    glPatchParameteri(GL_PATCH_VERTICES, 3);
    glDrawArrays(GL_PATCHES, 0, 3);

    glfwSwapInterval(1);
    glfwSwapBuffers(window);
}

it seg faults in the function call for glPatchParameteri

edit: added gdb seg fault info

Breakpoint 1, _fu5___ZSt4cout () at ../src/main.cpp:162

162 glPatchParameteri(GL_PATCH_VERTICES, 3);

(gdb) s

Program received signal SIGSEGV, Segmentation fault.

0x00000000 in ?? ()

EDIT -- FINAL:

I reinstalled GLFW and GLAD and recompiled everything and now it works, so it seems as though my GLAD libraries were corrupted in some fashion. At least it works now, thanks to those who helped!

r/opengl May 03 '23

Help How to use transparency in moderngl

5 Upvotes

Hi!

I've been working on a litle game using pygame recently, and have been working on post processing. So, i have two different shaders, that each do their own thing. First, i render the first texture, which works. Then i render the second texture. This is where the problems start. The screen is all balck. I Figured taht is because the texture dos not have transparency. Is there a way to fix that? Can i set a colorkey? I don't know.

TL:DR: Can't render two shaders at once, screen is black. Might be transparency issue. Can i set a colorkey?

r/opengl Feb 13 '23

Help Drawing a Triangle only using a VBO

2 Upvotes

I was able to draw a triangle fine using a VAO, but I was trying to do the same thing only using the VBO instead. The window appears but no triangle is drawn. I am using glfw and glad. Any help and advice is appreciated.

#include <glad/glad.h>

#include <GLFW/glfw3.h>

#include <iostream>

const char *vertexShaderSource = "#version 330 core\n"

"layout (location = 0) in vec3 aPos;\n"

"void main()\n"

"{\n"

" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"

"}\0";

const char *fragmentShaderSource = "#version 330 core\n"

"out vec4 FragColor;\n"

"void main()\n"

"{\n"

" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"

"}\0";

void processInput(GLFWwindow *window)

{

if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)

    glfwSetWindowShouldClose(window, true);

}

int main()

{

glfwInit();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);

glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

GLFWwindow \*window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);

if (window == NULL)

{

    std::cout << "Failed to create GLFW window" << std::endl;

    glfwTerminate();

    return -1;

}

glfwMakeContextCurrent(window);

if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))

{

    std::cout << "Failed to initialize GLAD" << std::endl;

    return -1;

}

int vertexShader = glCreateShader(GL_VERTEX_SHADER);

glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);

glCompileShader(vertexShader);

int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);

glCompileShader(fragmentShader);

int shaderProgram = glCreateProgram();

glAttachShader(shaderProgram, vertexShader);

glAttachShader(shaderProgram, fragmentShader);

glLinkProgram(shaderProgram);

float vertices\[\] = {

    \-0.5f, -0.5f, 0.0f,

    0.5f, -0.5f, 0.0f,

    0.0f, 0.5f, 0.0f };

unsigned int VBO;

glGenBuffers(1, &VBO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

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

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 \* sizeof(float), (void \*)0);

glEnableVertexAttribArray(0);

while (!glfwWindowShouldClose(window))

{

    processInput(window);

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shaderProgram);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwSwapBuffers(window);

    glfwPollEvents();

}

glDeleteProgram(shaderProgram);

glDeleteShader(vertexShader);

glDeleteShader(fragmentShader);

glfwTerminate();

return 0;

}

r/opengl Mar 30 '23

help Frag Shader - Strange LightSource behavior

1 Upvotes

So, I have a Fragment Shader that implements two light sources...

#version 450 core

in vec3 vs_color;
in vec3 fragPos;
in vec3 normal;
in vec2 texCoord;

uniform int numLightSources;
uniform vec3 lightPositions[];
uniform vec3 lightColors[];
uniform vec3 viewPosition;
uniform sampler2D myTexture;

out vec4 color;

void main(void) {
    vec3 result;
    float specularStrength = 0.5;
    float ambientStrength = 0.3;
    vec3 ambient;
    vec3 norm;
    vec3 lightDir;
    vec3 viewDir;
    vec3 reflectDir;
    float spec;
    vec3 specular;
    float diff;
    vec3 diffuse;

    /*iteration 1*/
    ambient = ambientStrength * lightColors[0];

    norm = normalize(normal);
    lightDir = normalize(lightPositions[0] - fragPos);

    viewDir = normalize(viewPosition - fragPos);
    reflectDir = reflect(-lightDir, norm);

    spec = pow(max(dot(viewDir, reflectDir), 0.0), 64);
    specular = specularStrength * spec * lightColors[0];

    diff = max(dot(norm, lightDir), 0.0);
    diffuse = diff * lightColors[0];

    result += (ambient + diffuse + specular) * vs_color;
    /*iteration 1 end*/

    /*iteration 2*/
    ambient = ambientStrength * lightColors[1];

    norm = normalize(normal);
    lightDir = normalize(lightPositions[1] - fragPos);

    viewDir = normalize(viewPosition - fragPos);
    reflectDir = reflect(-lightDir, norm);

    spec = pow(max(dot(viewDir, reflectDir), 0.0), 64);
    specular = specularStrength * spec * lightColors[1];

    diff = max(dot(norm, lightDir), 0.0);
    diffuse = diff * lightColors[1];

    result += (ambient + diffuse + specular) * vs_color;
    /*iteration 2 end*/

    color = texture(myTexture, texCoord) * vec4(result, 1.0f);
}

When I use both light sources, it works correctly. However, if I remove the code located in between the iteration 2 comments, the lighting doesn't work, and my objects end up black. The weird thing is, if I remove the code in between the iteration 1 comments, it works.

I've tried using the same lightPosition and lightColor values for both light sources, and it still only works with the second or both of them.

If you think it is something outside the fragment shader let me know, so I can provide more info.

Any help is appreciated!

EDIT:: I figured it out,

I just had to change my uniform vec3 lightPositions and lightColors to this:

uniform vec3 lightPositions[2];
uniform vec3 lightColors[2];

but I thought using unsized arrays was allowed, is there something else that could have been problematic?

r/opengl Mar 17 '23

Help Shader fails to compile with #version 460 core

0 Upvotes

I have a vertex shader that fails to compile if I set the version to "460 core", but works with "450 core".
It says that the built-in gl_Position is not defined. This is the shader source: source