CMLSC
CMLSC

Reputation: 123

How do you apply textures with pyopengl?

How do I apply textures to a set of vertices? I can't figure out what I'm doing wrong.

I can't find any tutorials or anything on this subject, so I'm mostly going off of OpenGL docs and random scripts I find, so my code may not make any sense. My script is a bit too large to post here and most of it isn't relevant.

My set up for the texture:

def read_texture(filename):
    img = Image.open(filename)
    img_data = numpy.array(list(img.getdata()), numpy.int8)
    textID = glGenTextures(1)
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, img_data)
    return textID

Which I loaded with texture_0 = read_texture('texture.png').

My setup for the cube:

generate cube's vertices

    def gen_rect_prism_vertices(xloc,yloc,zloc,x,y,z):
        x *= 0.5
        y *= 0.5
        z *= 0.5
        vertices = (
            (xloc+x, yloc-y, zloc-z),
            (xloc+x, yloc+y, zloc-z),
            (xloc-x, yloc+y, zloc-z),
            (xloc-x, yloc-y, zloc-z),
            (xloc+x, yloc-y, zloc+z),
            (xloc+x, yloc+y, zloc+z),
            (xloc-x, yloc-y, zloc+z),
            (xloc-x, yloc+y, zloc+z)
            )
        return vertices

defining the surfaces

rect_prism_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)
    )

the main function

def block(xloc,yloc,zloc,x,y,z):
    glEnable(GL_TEXTURE_2D)
    glBindTexture(GL_TEXTURE_2D,texture_0)
    vertices = gen_rect_prism_vertices(xloc,yloc,zloc,x,y,z)
    for surface in rect_prism_surfaces:
        n = 0
        glBegin(GL_QUADS)
        for vertex in surface:
            if n == 0:
                xv = 0.0
                yv = 0.0
            if n == 1:
                xv = 1.0
                yv = 0.0
            if n == 2:
                xv = 1.0
                yv = 1.0
            if n == 3:
                xv = 0.0
                yv = 1.0
            glTexCoord2f(xv,yv); glVertex3fv(vertices[vertex])
            n += 1
        glEnd()

This is the result. block

Upvotes: 1

Views: 5514

Answers (1)

CMLSC
CMLSC

Reputation: 123

@TEB answered in a comment. The texture need to be bound(with glBindTexture(GL_TEXTURE_2D,texture_0)) in read_texture() where the texture ID is generated.

Upvotes: 3

Related Questions