PyOpengl: Changing gluPerspective variables makes cube flash - python

When using gluPerspective in glutReshapeFunc function, the square image flashes while resizing and is gone after a few moments.
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
width = 500
height = 500
def cube():
glBegin(GL_QUADS)
glColor3f(0, 1, 0)
glVertex3f(10, 0, 0)
glVertex3f(10, 10, 0)
glVertex3f(10, 0, 0)
glVertex3f(0, 0, 0)
glVertex3f(10, 0, 0)
glVertex3f(10, 0, 10)
glVertex3f(0, 10, 0)
glVertex3f(10, 10, 0)
glVertex3f(0, 10, 0)
glVertex3f(0, 0, 0)
glVertex3f(0, 10, 0)
glVertex3f(0, 10, 10)
glVertex3f(0, 0, 10)
glVertex3f(0, 0, 0)
glVertex3f(0, 0, 10)
glVertex3f(10, 0, 10)
glVertex3f(0, 0, 10)
glVertex3f(0, 10, 10)
glVertex3f(10, 10, 10)
glVertex3f(10, 10, 0)
glVertex3f(10, 10, 10)
glVertex3f(10, 0, 10)
glVertex3f(10, 10, 10)
glVertex3f(0, 10, 10)
glEnd()
def showScreen():
global width, height
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
cube()
glutSwapBuffers()
def mouseTracker(mousex, mousey):
print(f"Mouse pos: {mousex}, {mousey}")
def reshapeWindow(x, y):
global width, height
width = x
height = y
print(x, y)
gluPerspective(45, (width / height), 0.0001, 1000)
glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
wind = glutCreateWindow("OpenGL")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMotionFunc(mouseTracker)
glutPassiveMotionFunc(mouseTracker)
glutReshapeFunc(reshapeWindow)
gluPerspective(45, (width / height), 0.0001, 1000)
glTranslatef(0, 0, -5)
while True:
glutMainLoopEvent()
glutPostRedisplay()
If I put the gluPerspective into the showScreen function like so:
def showScreen():
global width, height
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
cube()
gluPerspective(45, (width / height), 0.0001, 1000)
glutSwapBuffers()
The square flashes without resizing but it is gone after a few moments. If I remove the gluPerspective entirely, the image turns into a triangle. Is there any way to change gluPerspective variables without making the image flash?

You have to call gluPerspective before drawing the cube. The matrix operations not only set the current matrix, but define a new matrix and multiply the current matrix by the new matrix. Therefore you must load the Identity matrix with glLoadIdentity before modifying the matrix. The legacy OpenGL provides different current matrices for the model view matrix and the projection matrix. Before changing a matrix, select the matrix mode with glMatrixMode:
Change the projection matrix in the reshape callback:
def reshapeWindow(x, y):
global width, height
width = x
height = y
print(x, y)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, (width / height), 0.0001, 1000)
glMatrixMode(GL_MODELVIEW)
Set the model view matrix before the application loop or in the application loop:
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -5)
gluPerspective defines a Viewing frustum. The center of the view is (0, 0). Hence you need to change the vertex coordinates.
I suggest enabling the Depth Test when drawing 3D meshes.
Minimale example based on your code:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time
width = 500
height = 500
vertices = [(-1,-1,-1), ( 1,-1,-1), ( 1, 1,-1), (-1, 1,-1), (-1,-1, 1), ( 1,-1, 1), ( 1, 1, 1), (-1, 1, 1)]
faces = [(4,0,3,7), (1,0,4,5), (0,1,2,3), (1,5,6,2), (3,2,6,7), (5,4,7,6)]
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1)]
def cube():
glRotatef(1, 3, 1, 1)
glBegin(GL_QUADS)
for i, face in enumerate(faces):
glColor3fv(colors[i])
for vertex in face:
glVertex3fv(vertices[vertex])
glEnd()
def showScreen():
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
cube()
glutSwapBuffers()
def mouseTracker(mousex, mousey):
print(f"Mouse pos: {mousex}, {mousey}")
def reshapeWindow(x, y):
global width, height
width = x
height = y
print(x, y)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, (width / height), 0.0001, 1000)
glMatrixMode(GL_MODELVIEW)
glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
wind = glutCreateWindow("OpenGL")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMotionFunc(mouseTracker)
glutPassiveMotionFunc(mouseTracker)
glutReshapeFunc(reshapeWindow)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -5)
glEnable(GL_DEPTH_TEST)
while True:
glutMainLoopEvent()
glutPostRedisplay()
time.sleep(0.01)

Related

Drawing a house using python opengl does not display

I want to draw a house with Python OpenGL.
It should look like this:
filled:
unfilled:
Further information: The house should rotate via key input around the x- and y-axis. By pressing the F-key, it should switch between filled and unfilled mode.
My Problem: The window opens up, but I don't see anything on it. I'm not sure what exactly is wrong here or what I'm missing for drawing. Can somebody explain it?
This is my code:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
# from OpenGL.GL import shaders
# from OpenGL.arrays import vbo
# import numpy as np
# general all vertices needed
vertices = (
# front wall
(2, 0, -1, 2, 1, -1, -2, 1, -1, -2, 0, -1),
# back wall
(2, 0, 1, 2, 1, 1, -2, 1, 1, -2, 0, 1, 2, 2, 0, -2, 2, 0),
# roof ridge
(2.2, 2, 0, -2.2, 2, 0),
# roof edges
(2.2, 0.9, -1.1, -2.2, 0.9, -1.1, 2.2, 0.9, 1.1, -2.2, 0.9, 1.1),
# chimney
(1, 0, 0.5, 1.25, 0, 0.5, 1.25, 0, 0.25, 1, 0, 0.25,
1, 2.5, 0.5, 1.25, 2.5, 0.5, 1.25, 2.5, 0.25, 1, 2.5, 0.25)
)
def DrawHouse():
# house
# back wall
glBegin(GL_LINES)
glColor3f(0.5, 0.5, 0.5)
glVertex3f(2, 0, -1) # top left
glVertex3f(2, 1, -1) # top right
glVertex3f(-2, 1, -1) # bottom right
glVertex3f(-2, 0, -1) # bottom left
glEnd()
# front wall
glBegin(GL_LINES)
glColor3f(0.5, 0.5, 0.5)
glVertex3f(2, 0, 1) # top left
glVertex3f(2, 1, 1) # top right
glVertex3f(-2, 1, 1) # bottom right
glVertex3f(-2, 0, 1) # bottom right
glVertex3f(2, 2, 0) # rooftop
glVertex3f(-2, 2, 0) # rooftop
glEnd()
# roof
glBegin(GL_LINES)
# roof ridge
glColor3f(0, 0, 0)
glVertex3f(2.2, 2, 0)
glVertex3f(-2.2, 2, 0)
glEnd()
# roof edges
glBegin(GL_TRIANGLES)
glColor3f(0, 0, 0)
glVertex3f(2.2, 0.9, -1.1)
glVertex3f(-2.2, 0.9, -1.1)
glVertex3f(2.2, 0.9, 1.1)
glVertex3f(-2.2, 0.9, 1.1)
glEnd()
# chimney
glBegin(GL_POLYGON)
glColor3f(1, 1, 0)
glVertex3f(1, 0, 0.5)
glVertex3f(1.25, 0, 0.5)
glVertex3f(1.25, 0, 0.25)
glVertex3f(1, 0, 0.25)
glVertex3f(1, 2.5, 0.5)
glVertex3f(1.25, 2.5, 0.5)
glVertex3f(1.25, 2.5, 0.25)
glVertex3f(1, 2.5, 0.25)
glEnd()
def init():
# Switch on z-buffer for calculation of hidden surfaces
glEnable(GL_DEPTH_TEST)
# Display front and back of polygons as border lines only
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
def reshape():
# initialize projection matrix, to 60 degrees horizontal field of view
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, 1.0, 1.0, 200.0) # angle, aspect, near and far clip
# make modelview matrix the current matrix again
glMatrixMode(GL_MODELVIEW)
def main():
pygame.init()
window = (800, 800)
display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
pygame.display.set_caption('Haus')
clock = pygame.time.Clock()
# GLUT.glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE) # request render context with z-buffer, doublebuffer for rgb mode
gluOrtho2D(0, 800, 0, 800)
rotX = 0.0
rotY = 0.0
polygonMode = GL_LINE
while True:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed() # checking pressed keys
if keys[pygame.K_d]: # The keys 'a' and 'd' should rotate the house around the y-axis
rotX -= 5
if keys[pygame.K_a]:
rotX += 5
if keys[pygame.K_w]: # the keys 'w' and 'd' should rotate the house around the x-axis
rotY -= 5
if keys[pygame.K_d]:
rotY += 5
if keys[pygame.K_f]: # Key 'f' is to switch between wireframe and filled surfaces
if polygonMode is GL_FILL:
polygonMode = GL_LINE
else:
polygonMode = GL_FILL
# Switch polygon display between outline and filled
glPolygonMode(GL_FRONT_AND_BACK, polygonMode)
# GLUT.glutPostRedisplay() # render image again
# remove Framebuffer and Z-Buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# initialise Modelview Matrix
glLoadIdentity()
# execute Modeltransformation
glTranslatef(0, 0, -3) # shift by -3 in z-direction
glRotatef(rotY, 0, 1, 0) # rotate y-achse
glRotatef(rotX, 1, 0, 0) # rotate x-achse
glTranslatef(-0.5, -0.5, -0.5) # shift by -0.5 in all directions
# copy Back-Buffer in Front-Buffer
# swapBuffers()
DrawHouse()
# Show the screen
pygame.display.flip()
# callback functions
# glutReshapeFunc(reshape)
if __name__ == "__main__":
main()
The coordinates of your geometry are in range [-2.2, 2.2]. However you set an orthographic projection in range [0, 800]:
gluOrtho2D(0, 800, 0, 800)
Actually there are 3 reasons why you don't see anything
That results in only a few pixels being drawn on the bottom left of the screen.
gluOrtho2D creates an orthographic projection with a near plane of -1 and a far plane of 1. This will clip your geometry.
You need to choose the GL_PROJECTION for the current matrix. Later in your code, the model view matrix is set to the identity matrix with glLoadIdentity.
def main():
pygame.init()
window = (800, 800)
display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
pygame.display.set_caption('Haus')
clock = pygame.time.Clock()
# gluOrtho2D(0, 800, 0, 800)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-5, 5, -5, 5, -5, 5)
glMatrixMode(GL_MODELVIEW)
# [...]
Alternatively you can use the perspective projection from the reshape function:
def main():
pygame.init()
window = (800, 800)
display = pygame.display.set_mode(window, DOUBLEBUF | OPENGL)
pygame.display.set_caption('Haus')
clock = pygame.time.Clock()
# gluOrtho2D(0, 800, 0, 800)
reshape()
# [...]

Pyopengl: Creating cube with GLSL fills screen

When I try to draw a cube using the GLSL programmable pipeline of OpenGL I get a fully yellow screen, which is the color of the cube, and even if I used glTranslatef() and tried to zoom out by any value, the screen is just fully yellow. How can I zoom out so I can see the entire cube, not just a pure yellow screen?
Full replicable code:
import time
import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL.shaders import *
import numpy
width = 500
height = 500
vertices = [(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)]
faces = [(4, 0, 3, 7), (1, 0, 4, 5), (0, 1, 2, 3), (1, 5, 6, 2), (3, 2, 6, 7), (5, 4, 7, 6)]
def draw_shapes():
cube = []
for i, face in enumerate(faces):
for vertex in face:
cube.append(vertices[vertex])
cube = numpy.array(cube, dtype=numpy.float32)
vertex_shader = """
#version 140
in vec4 position;
void main(){
gl_Position = position;
}
"""
frag_shader = """
#version 140
void main(){
gl_FragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f);
}
"""
shaders = compileProgram(compileShader(vertex_shader, GL_VERTEX_SHADER),
compileShader(frag_shader, GL_FRAGMENT_SHADER))
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, 192, cube, GL_STATIC_DRAW)
position = glGetAttribLocation(shaders, "position")
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, None)
glEnableVertexAttribArray(position)
glUseProgram(shaders)
def showScreen():
global width, height
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glDrawArrays(GL_TRIANGLES, 0, 24)
draw_shapes()
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glLightfv(GL_LIGHT0, GL_POSITION, (0, 0, 0, 1)) # point light from the left, top, front
glLightfv(GL_LIGHT0, GL_AMBIENT, (1, 1, 1, 1))
glutSwapBuffers()
def reshapeWindow(x, y):
global width, height
width = x
height = y
print(x, y)
glutReshapeWindow(width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, (width / height), 0.0001, 1000)
glViewport(0, 0, width, height)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -5)
glRotatef(3, 1, 0, 0)
glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
wind = glutCreateWindow("OpenGL")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutReshapeFunc(reshapeWindow)
gluPerspective(45, (width / height), 0.0001, 100)
while True:
glutMainLoopEvent()
glutPostRedisplay()
time.sleep(0.01)
As already indicated in the comments by user253751 and derhass, the code mixes the fixed pipeline OpenGL approach with the programmable shader stages approach of modern OpengL, while it should be either one or the other. The legacy functions currently have no effect. It's probably best to start over using a book or tutorial on modern OpenGL, instead of converting a legacy project.
A modern OpenGL version of this project will involve:
Defining the transformation matrices (model/view/projection) on the CPU.
Uploading one or more transformation matrices as uniforms to the GPU.
Uploading the light parameters as uniforms to the GPU.
Multiplying each vertex with the transformation matrix using the vertex shader.
Manually programming the lighting/shading calculations in the vertex shader (for Gouraud shading) or fragment shader (for Blinn-Phong/Phong shading).

Pyopengl: Texture color not the same while being rendered

The color of the texture changes when it is being rendered by OpenGL, and I have no other color predefined in the code, except during the glClear and once during the cube() function. Note: changing the glTexImage2D format parameter from GL_RGB to GL_BGR only swaps colors.
Original texture:
Rendered Texture:
Full code:
import time
import numpy
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from PIL import Image
width = 500
height = 500
vertices = [(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)]
faces = [(4, 0, 3, 7), (1, 0, 4, 5), (0, 1, 2, 3), (1, 5, 6, 2), (3, 2, 6, 7), (5, 4, 7, 6)]
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1)]
def cube():
glRotatef(1, 3, 1, 1)
glColor3fv((1, 1, 1))
glBegin(GL_QUADS)
for i, face in enumerate(faces):
for surftex, vertex in enumerate(face):
if surftex == 0:
glTexCoord2f(0.0, 0.0)
elif surftex == 1:
glTexCoord2f(0.0, 1.0)
elif surftex == 2:
glTexCoord2f(1.0, 1.0)
elif surftex == 3:
glTexCoord2f(1.0, 0.0)
glVertex3fv(vertices[vertex])
glEnd()
def textureBind():
img = Image.open('Image.png')
img_data = numpy.array(list(img.getdata()), numpy.int8)
glEnable(GL_TEXTURE_2D)
texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture_id)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.size[0], img.size[1],
0, GL_RGB, GL_FLOAT, img_data)
return texture_id
def showScreen():
global width, height
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
cube()
glEnable(GL_DEPTH_TEST)
glutSwapBuffers()
def mouseTracker(mousex, mousey):
print(f"Mouse pos: {mousex}, {mousey}")
def reshapeWindow(x, y):
global width, height
width = x
height = y
print(x, y)
glutReshapeWindow(width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, (width / height), 0.0001, 1000)
glViewport(0, 0, width, height)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -5)
glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
wind = glutCreateWindow("OpenGL")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMotionFunc(mouseTracker)
glutPassiveMotionFunc(mouseTracker)
glutReshapeFunc(reshapeWindow)
gluPerspective(45, (width / height), 0.0001, 1000)
textureBind()
while True:
glutMainLoopEvent()
glutPostRedisplay()
time.sleep(0.001)
The format of this texture is BGR, but not RGB. Use GL_BGR instead of GL_RGB:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.size[0], img.size[1],0, GL_RGB, GL_FLOAT, img_data)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.size[0], img.size[1],
0, GL_BGR, GL_FLOAT, img_data)
The format of the image is stored in the mode attribute of the PIL.Image.Image object. See Mode.

How do I add an image as texture of my 3D cube in pyopengl

How do I add an image as texture in my cube:
I want to add my self-provided image as the surfaces of my cube while still having some lighting
I am using Visual Studio Code as my compiler
here is the code I copied:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
verticies = (
( 1, -1, -1), # 0
( 1, 1, -1), # 1
(-1, 1, -1), # 2
(-1, -1, -1), # 3
( 1, -1, 1), # 4
( 1, 1, 1), # 5
(-1, -1, 1), # 6
(-1, 1, 1), # 7
)
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6),
)
normals = [
( 0, 0, -1), # surface 0
(-1, 0, 0), # surface 1
( 0, 0, 1), # surface 2
( 1, 0, 0), # surface 3
( 0, 1, 0), # surface 4
( 0, -1, 0) # surface 5
]
colors = (
(1,1,1),
(0,1,0),
(0,0,1),
(0,1,0),
(0,0,1),
(1,0,1),
(0,1,0),
(1,0,1),
(0,1,0),
(0,0,1),
)
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7),
)
def Cube():
glBegin(GL_QUADS)
for i_surface, surface in enumerate(surfaces):
x = 0
glNormal3fv(normals[i_surface])
for vertex in surface:
x+=1
glColor3fv(colors[x])
glVertex3fv(verticies[vertex])
glEnd()
glColor3fv(colors[0])
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def main():
global surfaces
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
clock = pygame.time.Clock()
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glTranslatef(0, 0, -5)
#glLight(GL_LIGHT0, GL_POSITION, (0, 0, 1, 0)) # directional light from the front
glLight(GL_LIGHT0, GL_POSITION, (5, 5, 5, 1)) # point light from the left, top, front
glLightfv(GL_LIGHT0, GL_AMBIENT, (0, 0, 0, 1))
glLightfv(GL_LIGHT0, GL_DIFFUSE, (1, 1, 1, 1))
glEnable(GL_DEPTH_TEST)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE )
glRotatef(1, 3, 1, 1)
Cube()
glDisable(GL_LIGHT0)
glDisable(GL_LIGHTING)
glDisable(GL_COLOR_MATERIAL)
pygame.display.flip()
clock.tick(60)
main()
The program displays a rotating cube with just colors as its surface
how can I change the surface?
Define the array of texture coordinates:
textureCoordinates = ((0, 0), (0, 1), (1, 1), (1, 0))
Set a white color, but specify the texture coordinates when you draw the cube:
def Cube():
glColor3f(1, 1, 1)
glBegin(GL_QUADS)
for i_surface, surface in enumerate(surfaces):
x = 0
glNormal3fv(normals[i_surface])
for i_vertex, vertex in enumerate(surface):
x+=1
#
glTexCoord2fv(textureCoordinates[i_vertex])
glVertex3fv(verticies[vertex])
glEnd()
Load an image with pygame.image.load(), create the texture object and enable 2 dimensional texturing before the application loop:
def main():
# [...]
image = pygame.image.load('image.png')
datas = pygame.image.tostring(image, 'RGBA')
texID = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texID)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.get_width(), image.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, datas)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glEnable(GL_TEXTURE_2D)
while True:
# [...]
Complete example:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
verticies = (
( 1, -1, -1), # 0
( 1, 1, -1), # 1
(-1, 1, -1), # 2
(-1, -1, -1), # 3
( 1, -1, 1), # 4
( 1, 1, 1), # 5
(-1, -1, 1), # 6
(-1, 1, 1), # 7
)
textureCoordinates = ((0, 0), (0, 1), (1, 1), (1, 0))
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6),
)
normals = [
( 0, 0, -1), # surface 0
(-1, 0, 0), # surface 1
( 0, 0, 1), # surface 2
( 1, 0, 0), # surface 3
( 0, 1, 0), # surface 4
( 0, -1, 0) # surface 5
]
colors = (
(1,1,1),
(0,1,0),
(0,0,1),
(0,1,0),
(0,0,1),
(1,0,1),
(0,1,0),
(1,0,1),
(0,1,0),
(0,0,1),
)
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7),
)
def Cube():
glColor3f(1, 1, 1)
glBegin(GL_QUADS)
for i_surface, surface in enumerate(surfaces):
x = 0
glNormal3fv(normals[i_surface])
for i_vertex, vertex in enumerate(surface):
x+=1
#
glTexCoord2fv(textureCoordinates[i_vertex])
glVertex3fv(verticies[vertex])
glEnd()
glColor3fv(colors[0])
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def main():
global surfaces
pygame.init()
display = (400, 300)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
clock = pygame.time.Clock()
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glTranslatef(0, 0, -5)
#glLight(GL_LIGHT0, GL_POSITION, (0, 0, 1, 0)) # directional light from the front
glLight(GL_LIGHT0, GL_POSITION, (5, 5, 5, 1)) # point light from the left, top, front
glLightfv(GL_LIGHT0, GL_AMBIENT, (0, 0, 0, 1))
glLightfv(GL_LIGHT0, GL_DIFFUSE, (1, 1, 1, 1))
glEnable(GL_DEPTH_TEST)
image = pygame.image.load('image.png')
datas = pygame.image.tostring(image, 'RGBA')
texID = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texID)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.get_width(), image.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, datas)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glEnable(GL_TEXTURE_2D)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE )
glRotatef(1, 3, 1, 1)
Cube()
glDisable(GL_LIGHT0)
glDisable(GL_LIGHTING)
glDisable(GL_COLOR_MATERIAL)
pygame.display.flip()
clock.tick(60)
main()

Adding different textures to differents objects using PyOpenGL

I feel kind of stupid for asking this, but I've tried almost every example and proved every solution.
I'm trying to create a endless runner game using pyOpenGL and pygames, and facing many troubles, one of them is the following: I'm trying to render 2 textures for differents objects using pyOpenGL glBindTexture(GL_TEXTURE_2D, id). I have a main object, that is a cube, called cube and I also have an array of cube. I want to render a texture in cube and a different one all the cubes in the array, but everytime I try to do this the last texture "rendered" overlaps the previus one. What could I do?
Here is my code:
# Execute with Python 3
import os
import pygame
import random
import math
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
camera_x = 0
camera_z = 0
camera_y = 0
x = 0
Vertices = [
[1, -1, 1],
[-1, -1, 1],
[-1, -1, -1],
[1, -1, -1],
[1, 1, -1],
[-1, 1, -1],
[-1, 1, 1],
[1, 1, 1]
]
textureSurface = pygame.image.load('./textures/ursa.png'), pygame.image.load('./textures/caja.png')
textureData = pygame.image.tostring(textureSurface[0], "RGBA"), pygame.image.tostring(textureSurface[1], "RGBA")
width = textureSurface[0].get_width(), textureSurface[1].get_width()
height = textureSurface[0].get_height(), textureSurface[1].get_height()
class Ground:
global camera_z
def __init__(self):
self.ground_vertices = (
(-11, -2.01, 20),
(11, -2.01, 20),
(11, -2.01, -300),
(-11, -2.01, -300)
)
def draw(self):
glPushMatrix()
glTranslatef(0, 0, camera_z)
glBegin(GL_QUADS)
for vertex in self.ground_vertices:
glColor3fv((0, 0.5, 0.5))
glVertex3fv(vertex)
glEnd()
glPopMatrix()
class Cube:
def __init__(self, texture=False):
self.vertices = [
[1, -1, 1],
[-1, -1, 1],
[-1, -1, -1],
[1, -1, -1],
[1, 1, -1],
[-1, 1, -1],
[-1, 1, 1],
[1, 1, 1]
]
self.surfaces = (
(0, 1, 6, 7),
(0, 1, 2, 3),
(0, 3, 4, 7),
(1, 2, 6, 5),
(2, 3, 4, 5),
(4, 5, 6, 7)
)
self.colors = (
(105 / 255, 210 / 255, 231 / 255),
(167 / 255, 219 / 255, 216 / 255),
(224 / 255, 228 / 255, 204 / 255),
(243 / 255, 134 / 255, 48 / 255)
)
self.vertices_texture = (
(0.0, 0.0),
(1.0, 0.0),
(1.0, 1.0),
(0.0, 1.0),
)
self.texture = texture
self.center = [0, 0, 0]
def draw(self):
if self.texture:
glEnable(GL_TEXTURE_2D)
glColor3f(1, 1, 1)
glBegin(GL_QUADS)
if self.texture:
for surface in self.surfaces:
for x, vertex in enumerate(surface):
glTexCoord2fv(self.vertices_texture[x])
glVertex3fv(self.vertices[vertex])
else:
for surface in self.surfaces:
for x, vertex in enumerate(surface):
glColor3fv(self.colors[x])
glVertex3fv(self.vertices[vertex])
self.center = [
(self.vertices[2][0]+self.vertices[7][0])/2,
(self.vertices[2][1]+self.vertices[7][1])/2,
(self.vertices[2][2]+self.vertices[7][2])/2
]
glEnd()
if self.texture:
glDisable(GL_TEXTURE_2D)
def set_vertices(self, max_distance, min_distance=-40):
x_value_change = random.randrange(-10, 10)
y_value_change = -1
z_value_change = random.randrange(-1 * max_distance, min_distance)
new_vertices = []
for vertex in Vertices:
new_vertex = []
new_x = vertex[0] + x_value_change
new_y = vertex[1] + y_value_change
new_z = vertex[2] + z_value_change
new_vertex.append(new_x)
new_vertex.append(new_y)
new_vertex.append(new_z)
new_vertices.append(new_vertex)
self.vertices = new_vertices
def rotate(self):
glPushMatrix()
glRotatef(25, 1, 0, 0)
glPopMatrix()
def loadTexture(self, file):
glEnable(GL_TEXTURE_2D)
id = [0]*2
glGenTextures(2, id)
if file == 0:
glBindTexture(GL_TEXTURE_2D, id[0])
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width[0], height[0], 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData[0])
if file == 1:
glBindTexture(GL_TEXTURE_2D, id[1])
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width[1], height[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData[1])
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_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glDisable(GL_TEXTURE_2D)
#return texid
def leave(event):
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
quit()
def main():
global camera_x, camera_y, camera_z, x
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL | OPENGLBLIT)
max_distance = 300
gluPerspective(45, (display[0] / display[1]), 0.1, max_distance)
glEnable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glTranslatef(0, -10 / 2.4, -50)
ground = Ground()
cube = Cube(True)
cube.loadTexture(0)
my_cubes = []
for i in range(20):
tmp_cube = Cube(True)
tmp_cube.loadTexture(1)
tmp_cube.set_vertices(max_distance)
my_cubes.append(tmp_cube)
while True:
for event in pygame.event.get():
leave(event)
# movInverse(event)
M = glGetDoublev(GL_MODELVIEW_MATRIX)
# print(M)
camera_x = M[3][0]
camera_y = M[3][1]
camera_z = M[3][2]
glTranslatef(0, 0, 1.5)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
ground.draw()
glPushMatrix()
if(math.fabs(x) < 11):
glTranslatef(x, -1.5, camera_z-20)
glScalef(1 / 2, 1 / 2, 0)
cube.draw()
glPopMatrix()
for tmp_cube in my_cubes:
tmp_cube.draw()
print(tmp_cube.center)
for tmp_cube in my_cubes:
if camera_z <= tmp_cube.vertices[0][2]:
new_max = int(-1 * (camera_z - max_distance * 2))
tmp_cube.set_vertices(new_max, int(camera_z - max_distance))
pygame.display.flip()
if __name__ == '__main__':
main()
The method loadTexture is supposed to choose what texture is going to apply, but it doesn't, I don't know why. I hope someone could help me. Thanks!
When each cube has its own texture, then add an attribute self.id , which holds the texture for the cube.
Create this texture object and load the texture in the method loadTexture():
class Cube:
# [...]
def loadTexture(self, file):
self.id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width[file], height[file], 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData[file])
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_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
Bind the texture before the cube is draw (glBindTexture):
class Cube:
# [...]
def draw(self):
if self.texture:
glEnable(GL_TEXTURE_2D)
glColor3f(1, 1, 1)
glBindTexture(GL_TEXTURE_2D, self.id) # <-----
glBegin(GL_QUADS)
# [...]

Categories

Resources