我的 PyOpenGl 程序有问题。我正在学习,所以我正在阅读 github LearnOpenGL。 我在主题 6.PBR sub 2.1.2.ibl_irradiance。
尝试在 PyOpengl 中引用该程序。我能够很好地再现球体和辐照度照明。但我在渲染立方体贴图时遇到问题。我不知道为什么我的一侧是黑色的。 (背景是白色的,所以我看不到背景。我看到的是侧面,但没有照明)。 (您可以从here查看原始代码en c) 这是我到目前为止的代码。
from OpenGL.GL.shaders import compileProgram, compileShader
from camera import Camera
from OpenGL.GL import *
from PIL import Image
import glfw.GLFW as GLFW_CONSTANTS
import numpy as np
import pyrr
import math
import glfw
import cv2
import glm
# settings
WIDTH = 1600
HEIGHT = 900
# camera
CAMERA = Camera( position = pyrr.vector3.Vector3( [ 0.0, 0.0, 0.0 ] ) )
lastX = 800.0 / 2.0
lastY = 600.0 / 2.0
firstMouse = True
# timing
deltaTime = 0.0
lastFrame = 0.0
class Texture:
def __init__(self, filepath, idx):
extension = filepath.split('.')[-1]
self.idx = idx
self.texture = glGenTextures(1)
glBindTexture( GL_TEXTURE_2D, self.texture )
if 'hdr' in extension:
image = (cv2.imread(filepath, flags=cv2.IMREAD_ANYDEPTH))
h, w, = image.shape[:2]
image = cv2.cvtColor( image, cv2.COLOR_BGR2RGB )
image = np.float16(image) #.flatten()
#image_data = bytes(image.tobytes())
glGenerateMipmap(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_FLOAT, image)
else:
with Image.open( filepath, mode = 'r') as image:
w, h = image.size
image = image.convert("RGBA")
image_data = bytes(image.tobytes())
glTexImage2D(GL_TEXTURE_2D,0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data)
glGenerateMipmap(GL_TEXTURE_2D)
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
def Use(self):
glActiveTexture( GL_TEXTURE0 + self.idx )
glBindTexture(GL_TEXTURE_2D, self.texture)
def Destroy(self):
glDeleteTextures(1, (self.texture,))
sphereVAO = -1
indexCount = 0
def renderSphere():
global sphereVAO, indexCount
if sphereVAO == -1:
positions = []
uv = []
normals = []
X_SEGMENTS = 64
Y_SEGMENTS = 64
PI = 3.14159265359
data = []
for x in range(X_SEGMENTS + 1):
for y in range(Y_SEGMENTS + 1):
xSegment = x / X_SEGMENTS
ySegment = y / Y_SEGMENTS
xPos = math.cos(xSegment * 2.0 * PI) * math.sin(ySegment * PI)
yPos = math.cos(ySegment * PI)
zPos = math.sin(xSegment * 2.0 * PI) * math.sin(ySegment * PI)
positions.append(pyrr.vector3.Vector3([xPos, zPos, yPos]))
uv.append(pyrr.vector3.Vector3([ySegment, xSegment, 0]))
normals.append(pyrr.vector3.Vector3([xPos, zPos, yPos ]))
oddRow = False
indices = []
for y in range(Y_SEGMENTS):
if not oddRow:
for x in range(X_SEGMENTS+1):
indices.append( y*(X_SEGMENTS+1)+x )
indices.append( (y+1)*(X_SEGMENTS+1)+x )
else:
for x in range(X_SEGMENTS, -1, -1):
indices.append( (y+1)*(X_SEGMENTS+1)+x )
indices.append( y*(X_SEGMENTS+1)+x )
oddRow = not oddRow
data = []
for i in range(len( indices )-2):
'''
f point1 point2 point3
f point2 point3 point4
f point3 point4 ...
'''
idx1, idx2, idx3 = indices[i:i+3]
data += [positions[idx1].x, positions[idx1].y, positions[idx1].z,
normals[idx1].x, normals[idx1].y, normals[idx1].z,
uv[idx1].x, uv[idx1].y, ]
data += [positions[idx2].x, positions[idx2].y, positions[idx2].z,
normals[idx2].x, normals[idx2].y, normals[idx2].z,
uv[idx2].x, uv[idx2].y, ]
data += [positions[idx3].x, positions[idx3].y, positions[idx3].z,
normals[idx3].x, normals[idx3].y, normals[idx3].z,
uv[idx3].x, uv[idx3].y, ]
data = np.array( data , np.float32 )
indexCount = len(data) // 8
print(data.max(), data.min(), )
# indexCount = len( indices )
sphereVAO = glGenVertexArrays(1)
vbo = glGenBuffers(1)
ebo = glGenBuffers(1)
glBindVertexArray( sphereVAO )
glBindBuffer( GL_ARRAY_BUFFER, vbo)
glBufferData( GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(data), data, GL_STATIC_DRAW)
indices = np.array(indices, dtype='uint32')
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices), indices, GL_STATIC_DRAW)
stride = (3 + 2 + 3) * 4
glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(0))
glEnableVertexAttribArray(1)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(12))
glEnableVertexAttribArray(2)
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(24))
else:
glBindVertexArray(sphereVAO)
# glDrawElements(GL_TRIANGLE_STRIP, indexCount, GL_UNSIGNED_INT, 0)
glDrawArrays(GL_TRIANGLES, 0, indexCount )
class Shader():
def __init__(self, vertex_path, fragment_path):
with open( vertex_path, 'r') as f:
vertex_src = f.readlines()
with open( fragment_path, 'r') as f:
fragment_src = f.readlines()
self.shader = compileProgram(
compileShader( vertex_src, GL_VERTEX_SHADER),
compileShader( fragment_src, GL_FRAGMENT_SHADER)
)
self.variables = {}
def addMap(self, variable, texture_id ):
glUniform1i( glGetUniformLocation(self.shader, variable ), texture_id )
def addVar( self, variable, dtype ):
self.variables[variable] = [ glGetUniformLocation(self.shader, variable ), dtype ]
def setValue(self, variable, values):
assert variable in self.variables.keys(), 'Variable not founded'
var = self.variables[variable][0]
if self.variables[variable][1] == 'vec3':
glUniform3fv( var, 1, values )
elif self.variables[variable][1] == 'float':
glUniform1f( var, values )
elif self.variables[variable][1] == 'int':
glUniform1i( var, values )
elif self.variables[variable][1] == 'mat4':
glUniformMatrix4fv( var, 1, GL_FALSE, np.float32(values) )
elif self.variables[variable][1] == 'mat3':
glUniformMatrix3fv( var, 1, GL_FALSE, np.float32(values) )
else:
print( 'error' , var , self.variables[variable][1] )
def use(self ):
glUseProgram( self.shader )
def setVec3( self, variable , *values ):
self.Verify( variable , 'vec3' )
glUniform3fv( self.variables[variable][0], 1, np.array(values).astype('float32') )
def setFloat( self, variable, values ):
self.Verify( variable , 'float' )
glUniform1f( self.variables[variable][0], values )
def setInt( self, variable, value ):
self.Verify( variable , 'int' )
glUniform1i( self.variables[variable][0], value )
def setMat4( self, variable , values ):
self.Verify( variable , 'mat4' )
glUniformMatrix4fv( self.variables[variable][0], 1, GL_FALSE, np.float32(values) )
def setMat3( self, variable, values ):
self.Verify( variable , 'mat3' )
glUniformMatrix3fv( self.variables[variable][0], 1, GL_FALSE, np.float32(values) )
def Verify( self, variable , dtype):
if variable not in self.variables.keys(): # nueva variable
self.addVar( variable, dtype )
def main():
global deltaTime, lastFrame, CAMERA, lastX, lastY, firstMouse
# glfw: initialize and configure
glfw.init()
glfw.window_hint(GLFW_CONSTANTS.GLFW_CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(GLFW_CONSTANTS.GLFW_CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(GLFW_CONSTANTS.GLFW_SAMPLES, 4)
glfw.window_hint(GLFW_CONSTANTS.GLFW_OPENGL_PROFILE, GLFW_CONSTANTS.GLFW_OPENGL_CORE_PROFILE)
glfw.window_hint( GLFW_CONSTANTS.GLFW_DOUBLEBUFFER, GL_TRUE )
window = glfw.create_window(WIDTH, HEIGHT, "pyopengl", None, None)
glfw.make_context_current(window)
if window is None:
print('Window Could not be loaded')
glfw.terminate()
glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
glfw.set_cursor_pos_callback(window, mouse_callback)
glfw.set_scroll_callback(window, scroll_callback)
glfw.set_input_mode(window, GLFW_CONSTANTS.GLFW_CURSOR, GLFW_CONSTANTS.GLFW_CURSOR_DISABLED)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
shader_pbr = Shader("shaders/2.1.2.pbr.vs", "shaders/2.1.2.pbr.fs")
shader_rectangular = Shader("shaders/2.1.2.cubemap.vs", "shaders/2.1.2.equirectangular_to_cubemap.fs")
shader_irradiance = Shader("shaders/2.1.2.cubemap.vs", "shaders/2.1.2.irradiance_convolution.fs")
shader_background = Shader("shaders/2.1.2.background.vs", "shaders/2.1.2.background.fs")
shader_pbr.use()
shader_pbr.setInt("irradianceMap", 0)
shader_pbr.setVec3("albedo", 0.5, 0.0, 0.0)
shader_pbr.setFloat("ao", 1.0)
shader_background.use()
shader_background.setInt("environmentMap", 0)
lightPositions = [
np.array([0.0, 0.0, 0.0]).astype('float32'),
]
lightColors = [
np.array([50.0, 50.0, 50.0]).astype('float32'),
]
nrRows = 7
nrColumns = 7
spacing = 2.5
captureFBO = glGenFramebuffers(1,)
captureRBO = glGenRenderbuffers(1,)
glBindFramebuffer(GL_FRAMEBUFFER, captureFBO)
glBindRenderbuffer(GL_RENDERBUFFER, captureRBO)
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, captureRBO)
hdrTexture = Texture( 'hdr/newport_loft.hdr', 0 )
eye = pyrr.Vector3([ 0.0, 0.0, 0.0])
captureViews = [
# Vista 1: mirando hacia la derecha
pyrr.matrix44.create_look_at(eye,
pyrr.Vector3([1.0, 0.0, 0.0]),
pyrr.Vector3([0.0, -1.0, 0.0])),
# Vista 2: mirando hacia la izquierda
pyrr.matrix44.create_look_at(eye,
pyrr.Vector3([-1.0, 0.0, 0.0]),
pyrr.Vector3([0.0, -1.0, 0.0])),
# Vista 3: mirando hacia arriba
pyrr.matrix44.create_look_at(eye,
pyrr.Vector3([0.0, 1.0, 0.0]),
pyrr.Vector3([0.0, 0.0, 1.0])),
# Vista 4: mirando hacia abajo
pyrr.matrix44.create_look_at(eye,
pyrr.Vector3([0.0, -1.0, 0.0]),
pyrr.Vector3([0.0, 0.0, -1.0])),
# Vista 5: mirando hacia adelante
pyrr.matrix44.create_look_at(eye,
pyrr.Vector3([0.0, 0.0, 1.0]),
pyrr.Vector3([0.0, -1.0, 0.0])),
# Vista 6: mirando hacia atrás
pyrr.matrix44.create_look_at(eye,
pyrr.Vector3([0.0, 0.0, -1.0]),
pyrr.Vector3([0.0, -1.0, 0.0])),
]
envCubemap = glGenTextures(1, )
glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap)
for i in range( len(captureViews) ):
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 512, 512, 0, GL_RGB, GL_FLOAT, None)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
captureProjection = projection = pyrr.matrix44.create_perspective_projection(
fovy = 90, aspect = 1, near=0.1, far = 10, dtype = np.float32,
)
shader_rectangular.use()
shader_rectangular.setInt("equirectangularMap", 0)
shader_rectangular.setMat4("projection", captureProjection)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, hdrTexture.texture)
glViewport(0, 0, 512, 512)
glBindFramebuffer(GL_FRAMEBUFFER, captureFBO)
for i in range(len(captureViews)):
shader_rectangular.setMat4("view", captureViews[i])
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, envCubemap, 0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
renderCube()
glBindFramebuffer(GL_FRAMEBUFFER, 0)
irradianceMap = glGenTextures(1,)
glBindTexture(GL_TEXTURE_CUBE_MAP, irradianceMap)
for i in range(len(captureViews)):
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 32, 32, 0, GL_RGB, GL_FLOAT, None)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glBindFramebuffer(GL_FRAMEBUFFER, captureFBO)
glBindRenderbuffer(GL_RENDERBUFFER, captureRBO)
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 32, 32)
shader_irradiance.use()
shader_irradiance.setInt("environmentMap", 0)
shader_irradiance.setMat4("projection", captureProjection)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap)
glViewport(0, 0, 32, 32)
glBindFramebuffer(GL_FRAMEBUFFER, captureFBO)
# 5 abajo
# 4 arriba
# 3 frente
# 2 atras
# 1 derecha
# 0 derecha
for i in range(len(captureViews)):
shader_irradiance.setMat4("view", captureViews[i])
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, irradianceMap, 0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
renderCube()
glBindFramebuffer(GL_FRAMEBUFFER, 0)
# --------------------------------------------------------------
projection = pyrr.matrix44.create_perspective_projection(
fovy = CAMERA.Zoom, aspect = WIDTH/HEIGHT, near=0.1, far = 100, dtype = np.float32,
)
shader_pbr.use()
shader_pbr.setMat4("projection", projection)
shader_background.use()
shader_background.setMat4("projection", projection)
scrWidth, scrHeight = glfw.get_framebuffer_size(window)
glViewport(0, 0, scrWidth, scrHeight)
while not glfw.window_should_close(window):
currentFrame = float( glfw.get_time() )
deltaTime = currentFrame - lastFrame
lastFrame = currentFrame
processInput(window)
glClearColor(1.0, 1.0, 1.0, 1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
shader_pbr.use()
view = CAMERA.GetViewMatrix()
shader_pbr.setMat4("view", view)
shader_pbr.setVec3("camPos", CAMERA.Position )
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_CUBE_MAP, irradianceMap)
for i in range(nrRows):
shader_pbr.setFloat("metallic", 0.8)
for i in range(nrColumns):
shader_pbr.setFloat("roughness", 0.2)
model = pyrr.matrix44.create_identity()
translation = pyrr.vector3.Vector3( [ 0, -3, 0 ] )
model = pyrr.matrix44.multiply( m1 = model, m2 = pyrr.matrix44.create_from_translation( vec = translation, dtype=np.float32,) )
model_normal = pyrr.matrix33.create_from_matrix44( model )
model_normal = pyrr.matrix33.inverse( model_normal ).T
for i , (light_pos, light_color) in enumerate(zip(lightPositions, lightColors)):
newPos = np.array(translation).astype('float32')
# newPos = np.array( [newPos[0], newPos[2], newPos[1]+1.5] ).astype('float32')
newPos = np.array( [0,3,0] ).astype('float32')
color = light_color
shader_pbr.setVec3("lightPositions[" + str(i) + "]", newPos)
shader_pbr.setVec3("lightColors[" +str(i)+ "]", color*1 )
shader_pbr.setMat4("model", model)
shader_pbr.setMat3("normalMatrix", model_normal )
renderSphere()
break
break
break
shader_background.use()
shader_background.setMat4("view", view)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap)
renderCube()
glfw.swap_buffers(window)
glfw.poll_events()
def scroll_callback( _, xoffset, yoffset ):
CAMERA.ProcessMouseScroll( np.float32(yoffset) )
def mouse_callback( _, xposIn, yposIn):
global firstMouse, lastX, lastY
xpos = np.float32(xposIn)
ypos = np.float32(yposIn)
if firstMouse:
lastX = xpos
lastY = ypos
firstMouse = False
xoffset = xpos - lastX
yoffset = lastY - ypos
lastX = xpos
lastY = ypos
CAMERA.ProcessMouseMovement(xoffset, yoffset)
def framebuffer_size_callback():
glViewport(0, 0, WIDTH, HEIGHT)
def processInput(window):
if glfw.get_key(window, GLFW_CONSTANTS.GLFW_KEY_ESCAPE) == GLFW_CONSTANTS.GLFW_PRESS:
# global render
# render = False
glfw.set_window_should_close(window, True)
if glfw.get_key(window, GLFW_CONSTANTS.GLFW_KEY_W) == GLFW_CONSTANTS.GLFW_PRESS:
CAMERA.ProcessKeyboard('FORWARD', deltaTime)
if glfw.get_key(window, GLFW_CONSTANTS.GLFW_KEY_S) == GLFW_CONSTANTS.GLFW_PRESS:
CAMERA.ProcessKeyboard('BACKWARD', deltaTime)
if glfw.get_key(window, GLFW_CONSTANTS.GLFW_KEY_A) == GLFW_CONSTANTS.GLFW_PRESS:
CAMERA.ProcessKeyboard('LEFT', deltaTime)
if glfw.get_key(window, GLFW_CONSTANTS.GLFW_KEY_D) == GLFW_CONSTANTS.GLFW_PRESS:
CAMERA.ProcessKeyboard('RIGHT', deltaTime)
cubeVAO = -1
cubeVBO = 0
def renderCube():
global cubeVAO, cubeVBO
if (cubeVAO == -1):
vertices = [
-1.0, -1.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,
1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 1.0,
1.0, -1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 0.0,
1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 1.0,
-1.0, -1.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,
-1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 0.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0,
1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0,
-1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
-1.0, 1.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0,
-1.0, 1.0, -1.0, -1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0,
-1.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0,
-1.0, -1.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0,
-1.0, 1.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0,
1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0,
1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0,
1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0,
1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0,
1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0,
1.0, -1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0,
-1.0, -1.0, -1.0, 0.0, -1.0, 0.0, 0.0, 1.0,
1.0, -1.0, -1.0, 0.0, -1.0, 0.0, 1.0, 1.0,
1.0, -1.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0,
1.0, -1.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0,
-1.0, -1.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0,
-1.0, -1.0, -1.0, 0.0, -1.0, 0.0, 0.0, 1.0,
-1.0, 1.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0,
1.0, 1.0 , 1.0, 0.0, 1.0, 0.0, 1.0, 0.0,
1.0, 1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.0,
1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0,
-1.0, 1.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0,
-1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0
]
vertices = np.array( vertices ).astype('float32')
cubeVAO = glGenVertexArrays(1, )
cubeVBO = glGenBuffers(1, )
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
glBindVertexArray(cubeVAO)
# position xp, yp, zp
glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0))
#texture vt xt, yt
glEnableVertexAttribArray(2)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12))
# normal data nx, ny, nz
glEnableVertexAttribArray(2)
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(24))
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)
else:
glBindVertexArray(cubeVAO)
glDrawArrays(GL_TRIANGLES, 0, 36)
glBindVertexArray(0)
if __name__=='__main__':
main()
这是我的相机功能
import numpy as np
import glm
import math
import pyrr
deltaTime = 0.0
lastFrame = 0.0
# Valores por defecto de la cámara
YAW = -90.0
PITCH = 0.0
SPEED = 2.5*3
SENSITIVITY = 0.1
ZOOM = 45.0
# Clase Camera
class Camera:
def __init__(self, position, up=None, yaw=YAW, pitch=PITCH):
position = np.array(position).astype('float32')
up = np.array([0.0, 0.0, 1.0]).astype('float32')
self.Position = position
self.WorldUp = up
self.Yaw = yaw
self.Pitch = pitch
self.MovementSpeed = SPEED
self.MouseSensitivity = SENSITIVITY
self.Zoom = ZOOM
self.Front = np.array([0.0, 0.0, 0.0])
self.__updateCameraVectors()
def GetViewMatrix(self):
return pyrr.matrix44.create_look_at( eye = self.Position,
target = self.Position + self.Front,
up = self.Up,
dtype = np.float32)
def ProcessKeyboard(self, direction, deltaTime):
velocity = self.MovementSpeed * deltaTime
if direction == 'FORWARD':
self.Position += self.Front * velocity
elif direction == 'BACKWARD':
self.Position -= self.Front * velocity
elif direction == 'LEFT':
self.Position -= self.Right * velocity
elif direction == 'RIGHT':
self.Position += self.Right * velocity
def ProcessMouseMovement(self, xoffset, yoffset, constrainPitch=True):
xoffset *= self.MouseSensitivity
yoffset *= self.MouseSensitivity
self.Yaw -= xoffset
self.Pitch += yoffset
if constrainPitch:
if self.Pitch > 89.0:
self.Pitch = 89.0
elif self.Pitch < -89.0:
self.Pitch = -89.0
self.__updateCameraVectors()
def ProcessMouseScroll(self, yoffset):
self.Zoom -= yoffset
if self.Zoom < 1.0:
self.Zoom = 1.0
elif self.Zoom > 45.0:
self.Zoom = 45.0
def __updateCameraVectors(self):
# front = np.array([0.0, 0.0, 0.0]).astype('float32')
# front.x = math.cos(np.radians(self.Yaw)) * math.cos(np.radians(self.Pitch))
# front.y = math.sin(np.radians(self.Pitch))
# front.z = math.sin(np.radians(self.Yaw)) * math.cos(np.radians(self.Pitch))
self.Front = np.array(
[
np.cos(np.deg2rad(self.Yaw)) * np.cos(np.deg2rad(self.Pitch)),
np.sin(np.deg2rad(self.Yaw)) * np.cos(np.deg2rad(self.Pitch)),
np.sin(np.deg2rad(self.Pitch)),
]
)
global_up = np.array([0,0,1], dtype = np.float32)
# self.Front = glm.normalize(front)
self.Right = np.cross(self.Front, global_up)
self.Up = np.cross(self.Right, self.Front)
这是我的输出。 5 张面孔带有 hdr 图像,但其中一张是黑色的。
此外,我正在使用 github 存储库提供的着色器。如果有人能帮助我发现我的错误,我将不胜感激。谢谢你
我想了解更多有关使用 python 的 PyOpenGL 的信息。