Home > Back-end >  PyopenGL Square Texture
PyopenGL Square Texture

Time:10-02

I'm trying to load a minecraft texture in OpenGL, can someone help me? texture:

My Code:

import sys
from OpenGL.GLUT import *
from OpenGL.GL import *

def color(r, g, b):
    return (r/255, g/255, b/255)

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glColor3f(*color(40, 101, 212))
    glBegin(GL_QUADS)
    glVertex3f(-0.5, -0.5, 0.0)
    glVertex3f(0.5, -0.5, 0.0)
    glVertex(0.5, 0.5, 0.0)
    glVertex(-0.5, 0.5, 0.0)
    glEnd()
    glFlush()


glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(400, 400)
glutCreateWindow("Square Test")
glutDisplayFunc(display)
glutMainLoop()

I would try to avoid using pygame

CodePudding user response:

Use Pillow to load the image:

from PIL import Image
pil_image = Image.open('texture.jpg')

Create the texture object:

pil_image = Image.open('d:/temp/texture.jpg')
texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) 
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) 
format = GL_RGBA if pil_image.mode == 'RGBA' else GL_RGB
glTexImage2D(GL_TEXTURE_2D, 0, format, *pil_image.size, 0, format, GL_UNSIGNED_BYTE, pil_image.tobytes())

Enable 2 dimensional texturing:

glEnable(GL_TEXTURE_2D)

Draw the geometry with the texture coordinates:

glColor3f(1, 1, 1)
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(-0.5, -0.5, 0.0)
glTexCoord2f(1, 0)
glVertex3f(0.5, -0.5, 0.0)
glTexCoord2f(1, 1)
glVertex(0.5, 0.5, 0.0)
glTexCoord2f(0, 1)
glVertex(-0.5, 0.5, 0.0)
glEnd()

Complete example:

import sys
from OpenGL.GLUT import *
from OpenGL.GL import *
from PIL import Image

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glColor3f(1, 1, 1)
    glBegin(GL_QUADS)
    glTexCoord2f(0, 0)
    glVertex3f(-0.5, -0.5, 0.0)
    glTexCoord2f(1, 0)
    glVertex3f(0.5, -0.5, 0.0)
    glTexCoord2f(1, 1)
    glVertex(0.5, 0.5, 0.0)
    glTexCoord2f(0, 1)
    glVertex(-0.5, 0.5, 0.0)
    glEnd()
    glFlush()

glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(400, 400)
glutCreateWindow("Square Test")

pil_image = Image.open('texture.jpg')
texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) 
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) 
format = GL_RGBA if pil_image.mode == 'RGBA' else GL_RGB
glTexImage2D(GL_TEXTURE_2D, 0, format, *pil_image.size, 0, format, GL_UNSIGNED_BYTE, pil_image.tobytes())

glEnable(GL_TEXTURE_2D)

glutDisplayFunc(display)
glutMainLoop()
  • Related