簡體   English   中英

OpenGL 3.3-2個三角形的不同旋轉

[英]OpenGL 3.3 - Different rotation for 2 triangles

我遵循的是opengl-tutorial.org系列,第3篇教程在屏幕上繪制了一個三角形。代碼使用頂點着色器通過向其提供ModelViewProjection(MVP)矩陣進行頂點轉換。

我可以使三角形在每個循環中繞其原點旋轉。 我無法解決的是添加第二個三角形時,如何使其中一個旋轉,而另一個保持靜態。 着色器中的整個頂點轉換與主循環一起使我感到困惑。

這是直接來自教程的部分代碼:

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,
};
static const GLushort g_element_buffer_data[] = { 0, 1, 2 };

GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);

glm::mat4 View       = glm::lookAt(
                            glm::vec3(0,0,3), 
                            glm::vec3(0,0,0), 
                            glm::vec3(0,1,0));

glm::mat4 Model      = glm::mat4(1.0f);

glm::mat4 MVP        = Projection * View * Model; 

do{

    // Clear the screen
    glClear( GL_COLOR_BUFFER_BIT );

    // Use our shader
    glUseProgram(programID);

    // Send our transformation to the currently bound shader, 
    // in the "MVP" uniform
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

    // 1rst attribute buffer : vertices
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(
        0,                 
        3,                  // size
        GL_FLOAT,           // type
        GL_FALSE,           // normalized?
        0,                  // stride
        (void*)0            // array buffer offset
    );

    // Draw the triangle !
    glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle

    glDisableVertexAttribArray(0);

    // Swap buffers
    glfwSwapBuffers(window);
    glfwPollEvents();

}

要旋轉,我使用的是:

glm::mat4 Model      = glm::mat4(1.0f);

rot=rot+0.01f;
glm::vec3 myRotationAxis( 0, 0, 1);
Model = glm::rotate( Model, rot, myRotationAxis );

glm::mat4 MVP        = Projection * View * Model; 

我通過修改頂部的頂點緩沖區來繪制第二個三角形:

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,
     1.5f, 0.0f, -5.0f,
     2.5f, 0.0f, -5.0f,
     2.0f, 1.0f, -5.0f
};

然后畫我的兩個三角形:

glDrawArrays(GL_TRIANGLES, 0, 6); // 3 indices starting at 0 -> 1 triangle

頂點着色器顯然正在變換所有6個頂點。 我將如何制作此程序,以便僅第二個三角形旋轉?

您將通過相同的頂點着色器使用相同的參數發送兩個三角形。 您可以使用不同的參數分別通過着色器發送它們,也可以根據要執行的操作通過不同的着色器發送它們。 最簡單的方法可能是這樣的:

// Draw the first triangle like you did above
glDrawArrays (GL_TRIANGLES, 0, 3);

// ... set up the matrix for the second triangle here ... 

// Tell the shader about the new matrix
glUniformMatrix (MatrixID, 1, GL_FALSE, &MVP[0][0]);

// And draw starting at the second triangle
glDrawArrays (GL_TRIANGLES, 3, 3);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM