7

我在简单的 opengl(通过 GLFW3)应用程序中遇到了奇怪的口吃。尽管启用了垂直同步(帧速率几乎稳定为 60 fps),但旋转三角形的运动并不总是平滑 - 就像有时会跳过某些帧一样。我尝试查看连续调用 glSwapBuffers() 之间的时间差,但这些看起来非常一致。

难道我做错了什么?我应该使用某种运动模糊过滤使其看起来更平滑吗?

编码:

#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cfloat>
#include <cassert>
#include <minmax.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#include <Windows.h>
#include <GL/glew.h>
#include <gl/GLU.h>
//#include <GL/GL.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp> 

#ifdef _WIN32
#pragma warning(disable:4996)
#endif

static int swap_interval;
static double frame_rate;


GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path){

    // Create the shaders
    GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

    // Read the Vertex Shader code from the file
    std::string VertexShaderCode;
    std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
    if(VertexShaderStream.is_open()){
        std::string Line = "";
        while(getline(VertexShaderStream, Line))
            VertexShaderCode += "\n" + Line;
        VertexShaderStream.close();
    }else{
        printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertex_file_path);
        return 0;
    }

    // Read the Fragment Shader code from the file
    std::string FragmentShaderCode;
    std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
    if(FragmentShaderStream.is_open()){
        std::string Line = "";
        while(getline(FragmentShaderStream, Line))
            FragmentShaderCode += "\n" + Line;
        FragmentShaderStream.close();
    }

    GLint Result = GL_FALSE;
    int InfoLogLength;

    // Compile Vertex Shader
    printf("Compiling shader : %s\n", vertex_file_path);
    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
    glCompileShader(VertexShaderID);

    // Check Vertex Shader
    glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
    if (Result != GL_TRUE)
    {
        glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
        if ( InfoLogLength > 0 ){
            std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
            glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
            printf("%s\n", &VertexShaderErrorMessage[0]);
        }
    }


    // Compile Fragment Shader
    printf("Compiling shader : %s\n", fragment_file_path);
    char const * FragmentSourcePointer = FragmentShaderCode.c_str();
    glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
    glCompileShader(FragmentShaderID);

    // Check Fragment Shader
    glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
    if (Result != GL_TRUE)
    {
        glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
        if ( InfoLogLength > 0 ){
            std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
            glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
            printf("%s\n", &FragmentShaderErrorMessage[0]);
        }
    }

    // Link the program
    printf("Linking program\n");
    GLuint ProgramID = glCreateProgram();
    glAttachShader(ProgramID, VertexShaderID);
    glAttachShader(ProgramID, FragmentShaderID);
    glLinkProgram(ProgramID);

    // Check the program
    glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
    if (Result != GL_TRUE)
    {
        glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
        if ( InfoLogLength > 0 ){
            std::vector<char> ProgramErrorMessage(InfoLogLength+1);
            glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
            printf("%s\n", &ProgramErrorMessage[0]);
        }
    }
#ifdef _DEBUG
    glValidateProgram(ProgramID);
#endif

    glDeleteShader(VertexShaderID);
    glDeleteShader(FragmentShaderID);

    return ProgramID;
}


static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

static void set_swap_interval(GLFWwindow* window, int interval)
{
    swap_interval = interval;
    glfwSwapInterval(swap_interval);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_SPACE && action == GLFW_PRESS)
        set_swap_interval(window, 1 - swap_interval);
}

static bool init(GLFWwindow** win)
{
    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);

    // creating a window using the monitor param will open it full screen
    const bool useFullScreen = false;
    GLFWmonitor* monitor = useFullScreen ? glfwGetPrimaryMonitor() : NULL;
    *win = glfwCreateWindow(640, 480, "", monitor, NULL);
    if (!(*win))
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(*win);

    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
        printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
        return false;
    }
    //Make sure OpenGL 2.1 is supported
    if( !GLEW_VERSION_2_1 )
    {
        printf( "OpenGL 2.1 not supported!\n" );
        return false; 
    }

    glfwMakeContextCurrent(*win);
    glfwSetFramebufferSizeCallback(*win, framebuffer_size_callback);
    glfwSetKeyCallback(*win, key_callback);

    // get version info
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf("Renderer: %s\n", renderer);
    printf("OpenGL version supported %s\n", version);

    return true;
}
std::string string_format(const std::string fmt, ...) {
    int size = 100;
    std::string str;
    va_list ap;
    while (1) {
        str.resize(size);
        va_start(ap, fmt);
        int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap);
        va_end(ap);
        if (n > -1 && n < size) {
            str.resize(n);
            return str;
        }
        if (n > -1)
            size = n + 1;
        else
            size *= 2;
    }
    return str;
}
int main(int argc, char* argv[])
{
    srand(9); // constant seed, for deterministic results

    unsigned long frame_count = 0;

    GLFWwindow* window;
    init(&window);

    // An array of 3 vectors which represents 3 vertices
    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
    };

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    // acclocate GPU memory and copy data
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    unsigned int vao = 0;
    glGenVertexArrays (1, &vao);
    glBindVertexArray (vao);
    glEnableVertexAttribArray (0);
    glBindBuffer (GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    // Create and compile our GLSL program from the shaders
    GLuint programID = LoadShaders( "1.vert", "1.frag" );

    // Use our shader
    glUseProgram(programID);

    GLint locPosition = glGetAttribLocation(programID, "vertex");
    assert(locPosition != -1);

    glm::mat4 world(1.0f);
    GLint locWorld = glGetUniformLocation(programID, "gWorld");
    assert(locWorld != -1 && "Error getting address (was it optimized out?)!");
    glUniformMatrix4fv(locWorld, 1, GL_FALSE, glm::value_ptr(world));
    GLenum err = glGetError();

    GLint loc = glGetUniformLocation(programID, "time");
    assert(loc != -1 && "Error getting uniform address (was it optimized out?)!");

    bool isRunning = true;
    while (isRunning)
    {
        static float time = 0.0f;
        static float oldTime = 0.0f;
        static float fpsLastUpdateTime = 0.0f;
        oldTime = time;
        time = (float)glfwGetTime();
        static std::string fps;

        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glUseProgram (programID);
        glUniform1f(loc, time);
        glBindVertexArray (vao);
        glDrawArrays (GL_TRIANGLES, 0, 3);
        glfwSwapBuffers(window);
        glfwPollEvents();
        isRunning = !glfwWindowShouldClose(window);

        float dT = time-oldTime;
        if (time-fpsLastUpdateTime > 0.5)
        {
            static const char* fmt = "frame rate: %.1f frames per second";      
            glfwSetWindowTitle(window, string_format(fmt, 1.0f/(dT)).c_str());
            fpsLastUpdateTime = time;
        }
    }

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}


////////////////////////////////////////
// 1.frag
////////////////////////////////////////
#version 330 core

// Ouput data
out vec3 color;

void main()
{
    // Output color = red
    color = vec3(1,0,0);
}

//////////////////////////////////////////////
// 1.vert
//////////////////////////////////////////////
#version 330 core

// Input vertex data, different for all executions of this shader.
in vec3 vertex;

uniform mat4 gWorld;
uniform float time;

void main()
{
    gl_Position = gWorld * vec4(vertex, 1.0f);
    gl_Position.x += sin(time);
    gl_Position.y += cos(time)/2.0f;
    gl_Position.w = 1.0;
}

好的。我回到家做了更多的测试。

首先我试图禁用垂直同步,但我做不到!我必须禁用 Windows 的桌面效果(Aero)才能这样做,你瞧——一旦禁用 Aero,口吃就消失了(打开 V-Sync)。

然后我在关闭 V-Sync 的情况下对其进行了测试,当然,我得到了更高的帧速率,偶尔会出现预期的撕裂。

然后我全屏测试它。使用 Aero 和没有它的渲染都很流畅。

我找不到其他分享这个问题的人。你认为这是 GLFW3 的错误吗?驱动程序/硬件问题(我有带有最新驱动程序的 GTS450)?

谢谢大家的回答。我学到了很多,但我的问题仍然没有解决。

4

3 回答 3

5

It's a strange Windows dwm (Desktop Window Manager) composition mode and glfwSwapBuffers() interaction problem. I didn't got down to the root of the problem yet. But you can workaround the stuttering by doing one of the following:

  • go fullscreen
  • disable dwm window composition (see my answer to Linear movement stutter)
  • enable multi sampling: glfwWindowHint(GLFW_SAMPLES, 4);
于 2014-02-09T18:27:30.610 回答
3

Without seeing this stutter problem it is difficult to say what the problem is. But the first impression of your program is ok.
So I guess you observe that a frame once in a while is shown twice. Leading to a very small stutter. This happens usually when you try to output 60 frames on 60Hz Monitor with vsync.
In such a setup you must not miss one vsync period or you will see a stutter, because of the frame shown twice.
On the other hand it is nearly impossible to guarantee this because the scheduler on a windows platforms schedules threads for 15ms(about that I don't know the correct value by heart).
So it is possible that a higher priority thread will use the CPU and your presenting thread is not able to swap the buffers for a new frame in time. When you increase the values e.g. 120 frames on 120 Hz monitor you will see those stutters even more often.
So I don't know any solution how you can prevent this on the windows platform. But If someone else knows I would be happy to know it too.

于 2013-08-12T09:06:29.530 回答
2

It's hard to tell without visualizing your problem but unless we are talking about some severe stuttering it's rarely a rendering issue. The motion/physics in your program is handled/processed by the CPU. The way you are implementing your animation, is handled in a way that is solely depended on the CPU.

What this means is that:

Say you are rotating your triangle by a fixed amount every CPU cycle. This is very depended on the time a CPU cycle takes to complete. Things like cpu workload can have huge impact on your screen result (not necessarily though). And it doesn't even take huge CPU occupation to notice a difference. All it takes is a background process to wake up and query for updates. This could result in a 'spike' of which could be observed as a tiny pause in your animation flow (due to the small delay the CPU can cause in your animation cycle). This can be interpreted as a stutter.

Now understanding the above there are a few ways to solve your issue (but in my opinion it doesn't worth investing for what you are trying to do above). You need to find a way to have consistent animation steps (with a small margin for variation).

This is a great article to explore: http://gafferongames.com/game-physics/fix-your-timestep/

Ultimately most of the methods implemented above will result in a better rendering flow. But still not all of them guarantee physics-rendering precision. Without trying it out myself yet, i would say that one would have to go as far as implementing interpolation in his/her rendering process to guarantee smooth drawing as best as possible.

Now what i wanted to explain to you most, is that stuttering is usually caused by the CPU because it intervenes directly with your way of handling physics. But overall, using time for handling your physics and interpolating inside your rendering cycles is a topic definitely worth to explore.

于 2013-08-12T11:39:00.703 回答