簡體   English   中英

彼此相鄰的實例化立方體 OpenGL

[英]Instancing cubes next to each other OpenGL

我嘗試將許多立方體並排放置。

我的理解是,我需要為每個立方體創建一個MVP矩陣並綁定它,然后以某種方式更改 position。 然后在 for 循環中運行它以獲得您想要的多維數據集。

這是我嘗試過的:

while (!glfwWindowShouldClose(window)) {
    glClearColor(0.0f / 255.0f, 170.0f / 255.0f, 204.0f / 255.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programID);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(
        0,
        3, GL_FLOAT, GL_FALSE,
        0,
        (void*)0
    );

    computeMatricesFromInputs();
    glm::mat4 ProjectionMatrix = getProjectionMatrix();
    glm::mat4 ViewMatrix = getViewMatrix();
    glm::mat4 ModelMatrix = glm::mat4(1.0);
    glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

    for (int i = 0; i == cubes; i++) {
        GLuint MatrixID = glGetUniformLocation(programID, "MVP");
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
        glDrawArraysInstanced(GL_TRIANGLES, 0, 1, i);
    }

    //GLuint MatrixID = glGetUniformLocation(programID, "MVP");
    //glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
    //glDrawArrays(GL_TRIANGLES, 0, 12*3);
    glDisableVertexAttribArray(0);

    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, texturebuffer);
    glVertexAttribPointer(
        1,
        2,
        GL_FLOAT,
        GL_FALSE,
        0,
        (void*)0
    );
    glfwSwapBuffers(window);
    glfwPollEvents();
}

這根本不會繪制任何立方體,我不知道如何將每個立方體的 position 更改為並排。 那么為什么這段代碼不繪制實例立方體,我如何能夠將每個立方體的 position 更改為彼此相鄰的 rest?

glDrawArraysInstanced的第 3 個參數是要分別繪制立方體的頂點數(就像glDrawArrays一樣),第 4 個參數是 1 個繪制調用要繪制的實例數,而不是實例的索引。

無論如何,您根本不需要glDrawArraysInstanced ,因為您分別繪制每個立方體。 改用glDrawArrays

for (int i = 0; i < cubes; i++) {
    GLuint MatrixID = glGetUniformLocation(programID, "MVP");
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
    glDrawArrays(GL_TRIANGLES, 0, noOfVertices);
}

這可以用glDrawArraysInstanced代替:

glDrawArraysInstanced(GL_TRIANGLES, 0, noOfVertices, cubes); 

這將一次繪制所有立方體cubes 為了實現這一點,您必須找到一種方法來為每個實例使用不同的 model 矩陣。
一種可能性是使用着色器存儲緩沖區 Object (SSBO)將所有 model 矩陣存儲在一個數組中。 在頂點着色器中,實例的索引(立方體的索引)可以通過內置輸入gl_InstanceID獲得。 該變量可用於從數組中獲取實例的正確 model 矩陣。

例如:

layout(std430) buffer Matrices
{
    mat4 mvpArray[];
};

void main()
{
    mat4 mvp = mvpArray[gl_InstanceID];

    // [...]
}

暫無
暫無

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

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