慕的地6264312
2023-06-27 13:21:11
我正在嘗試為三角形添加木質(zhì)紋理。代碼僅適用于三角形。但當我嘗試添加紋理時會出現(xiàn)錯誤。我認為問題出在 GLSL 或創(chuàng)建 EBO/VBO 中(不確定)。整個屏幕保持黑色。這是完整的代碼。我在這里做錯了什么?from OpenGL.GL import *from OpenGL.GLU import *from OpenGL.GL import shadersimport glfwimport numpy as npfrom PIL import ImageVERTEX_SHADER = """#version 330 layout (location = 0) in vec4 position; in vec2 InTexCoords; out vec2 OutTexCoords; void main(){ gl_Position = position; OutTexCoords = InTexCoords; }"""FRAGMENT_SHADER = """#version 330 out vec4 FragColor; uniform vec4 triangleColor; in vec2 OutTexCoords; uniform sampler2D sampleTex; void main() { FragColor = texture(sampleTex,OutTexCoords); }"""shaderProgram = Nonedef initialize(): global VERTEXT_SHADER global FRAGMENT_SHADER global shaderProgram #compiling shaders vertexshader = shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER) fragmentshader = shaders.compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER) #creating shaderProgram shaderProgram = shaders.compileProgram(vertexshader, fragmentshader) #vertex and indices data #triangle #texture vertices = [-0.5, -0.5, 0.0, 0.0,0.0, 0.5, -0.5, 0.0, 1.0,0.0, 0.0, 0.5, 0.0, 0.5,1.0] indices = [0,1,2] vertices = np.array(vertices, dtype=np.float32) indices = np.array(vertices, dtype=np.float32) #add vertices to buffer VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) #add indices to buffer EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW) position = 0 glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position)我試圖遵循本教程learnopengl。但教程是用 C++ 編寫的。此外,我的方法略有不同。我沒有在頂點中添加顏色代碼。但我不認為這是添加紋理的方式的問題。
1 回答

呼啦一陣風
TA貢獻1802條經(jīng)驗 獲得超6個贊
的 stride 參數(shù)glVertexAttribPointer
指定連續(xù)通用頂點屬性之間的字節(jié)偏移量。您的屬性由具有 3 個分量的頂點坐標和具有 2 個分量的紋理坐標組成。因此,你的步幅參數(shù)必須為 20(5 * 4 字節(jié))而不是 24:
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))
glVertexAttribPointer(position,?3,?GL_FLOAT,?GL_FALSE,?20,?ctypes.c_void_p(0))
glVertexAttribPointer(texCoords,2, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))
glVertexAttribPointer(texCoords,2,?GL_FLOAT,?GL_FALSE,?20,?ctypes.c_void_p(12))
索引的數(shù)據(jù)類型必須是整數(shù)。繪制調(diào)用 ( ) 中的類型glDrawElements(..., ..., GL_UNSIGNED_INT, ...)
必須與此類型匹配。使用uint32
而不是float
(和vertices
->?indices
):
indices?=?np.array(indices,?dtype=np.uint32)
將通用頂點屬性索引與命名屬性變量 ( ) 關聯(lián)起來必須在鏈接程序之前(在 之前)glBindAttribLocation
完成。我建議通過布局限定符?設置屬性索引:glLinkProgram
layout?(location?=?0)?in?vec4?position; layout?(location?=?1)?in?vec2?InTexCoords;
添加回答
舉報
0/150
提交
取消