OSDN Git Service

548e42310ec77b693079a6d6bd923cf89351dcf7
[meshio/pymeshio.git] / examples / opengl / texture.py
1 #!/usr/bin/python
2 # coding: utf-8
3
4 from PIL import Image
5 from OpenGL.GL import *
6
7
8 class Texture(object):
9
10     def __init__(self, path):
11         self.path=path
12         self.image=None
13
14     def onInitialize(self):
15         if not self.image:
16             self.loadImage()
17
18         assert(self.image)
19         if self.createTexture():
20             return True
21
22     def loadImage(self):
23         self.image=Image.open(self.path)
24         if self.image:
25             print("load image:", self.path)
26             return True
27         else:
28             print("failt to load image:", self.path)
29             return False
30
31     def createTexture(self):
32         self.texture=glGenTextures(1)
33         if self.texture==0:
34             print("fail to glGenTextures")
35             return False
36
37         channels=len(self.image.getbands())
38         w, h=self.image.size
39         glBindTexture(GL_TEXTURE_2D, self.texture)
40         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
41         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
42         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
43         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
44         if channels==4:
45             print("RGBA")
46             glPixelStorei(GL_UNPACK_ALIGNMENT, 4)
47             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 
48                     0, GL_RGBA, GL_UNSIGNED_BYTE, self.image.tostring())
49         elif channels==3:
50             print("RGB")
51             glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
52             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 
53                     0, GL_RGB, GL_UNSIGNED_BYTE, self.image.tostring())
54
55     def begin(self):
56         glEnable(GL_TEXTURE_2D)
57         glBindTexture(GL_TEXTURE_2D, self.texture)
58
59     def end(self):
60         glDisable(GL_TEXTURE_2D)
61
62