[英]OpenGL : How can I pass multiple texture to a shader with one variable?
我根據此代碼( https://github.com/Bly7/OBJ-Loader )從 Obj 文件中加載了材質和紋理信息。 現在我想加載 Sponza 並渲染它。 但是,紋理有10個甚至更多,即使全部都傳遞給着色器,也需要對應適當的頂點。 查看從 Obj 文件加載的結果,紋理被分配給每個部分。
例子。
Mesh 0 : Pillar
position0(x, y, z), position1(x, y, z), uv0(x, y) ...
diffuse texture : tex0.png
Mesh 1 : Wall
position0(x, y, z), position1(x, y, z), uv0(x, y) ...
diffuse texture : tex1.png
.
.
.
紋理保存為一個數組,每個紋理都有一個對應的網格索引。 在我看來,將頂點信息傳遞給着色器時,如果將其除以網格數並同時傳遞紋理,則效果很好。 但是,我不確定這個想法是否正確,我嘗試了幾種方法但都不起作用。
這是當前的簡單代碼。
main.cpp :
do {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture[i]); // texture[] : Array of textures loaded from obj file.
glUniform1i(glGetUniformLocation(shaderID, "myTex"), 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertex_position);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, texCoord);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element);
glDrawElements(GL_TRIANGLES, element_indices.size(), GL_UNSIGNED_INT, (void*)0);
} while(glfwWindowShouldClose(window) == 0);
Fragment shader :
layout(location = 0) out vec4 out_color;
// from vertex shader
in vec2 texCoord;
uniform sampler2D myTex;
void main() {
out_color = texture(myTex, texCoord);
}
我想對應上面代碼中加載了“i”的網格索引。 請讓我知道我的想法是錯誤的還是有其他方法。
由於您的模型每個網格只有一個紋理,我可以建議使用以下簡單代碼:
do {
glActiveTexture(GL_TEXTURE0);
glUniform1i(glGetUniformLocation(shaderID, "myTex"), 0);
for (unsigned int i = 0; i < mesh_count; i++) {
glcall(glBindTexture(type, texture[i]));
// Bind vertex and index (or element) buffer and setup vertex attribute pointers
// Draw mesh
}
} while (window_open);
代碼一目了然。 它首先激活紋理槽 0,然后為每個網格綁定紋理、頂點緩沖區、索引或元素緩沖區,並執行繪制網格所需的任何准備工作。 然后它發出繪制調用。
請注意,這是非常基本的示例。 大多數模型使用此代碼看起來很奇怪。 我會推薦 LearnOpenGL 的本教程,它更廣泛但更簡單地解釋了這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.