Statistiques
| Révision :

root / PyOpenGL-Demo / broken / NeHe / lesson44 / lesson44.py

Historique | Voir | Annoter | Télécharger (18,17 ko)

1
#! /usr/bin/env python3
2
# -*- coding: utf-8 -*-
3

    
4
# NeHe Tutorial Lesson: 44 - Lense Flare
5
#
6
# Ported to PyOpenGL 2.0 by Brian Leair 2004
7
#
8
# This code was created by Jeff Molofee 2000
9
#
10
# The port was based on the PyOpenGL tutorials and from 
11
# PyOpenGLContext (tests/glprint.py)
12
#
13
# If you've found this code useful, feel free to let me know 
14
# at (Brian Leair telcom_sage@yahoo.com).
15
#
16
# See original source and C based tutorial at http://nehe.gamedev.net
17
#
18
# Note:
19
# -----
20
# This code is not an ideal example of Pythonic coding or use of OO 
21
# techniques. It is a simple and direct exposition of how to use the 
22
# Open GL API in Python via the PyOpenGL package. It also uses GLUT, 
23
# a high quality platform independent library. Due to using these APIs, 
24
# this code is more like a C program using procedural programming.
25
#
26
# To run this example you will need:
27
# Python         - www.python.org (v 2.3 as of 1/2004)
28
# PyOpenGL         - pyopengl.sourceforge.net (v 2.0.1.07 as of 1/2004)
29
# Numeric Python        - (v.22 of "numpy" as of 1/2004) numpy.sourceforge.net
30
# Python Image Library        - http://www.pythonware.com/products/pil/
31
#
32
# #########################################################
33
# Please note, don't use PyOpenGL older than 2.0.1.07.
34
# Older PyOpenGL had a bug glGetFloat () that prevents this 
35
# tutorial from working.
36
#
37
#
38

    
39

    
40
from OpenGL.GL import *
41
from OpenGL.GLUT import *
42
from OpenGL.GLU import *
43
import PIL.Image                                        # PIL
44
try:
45
        import win32api                                # GetTickCount ()
46
        gHaveWin32 = 1
47
except:
48
        gHaveWin32 = 0
49
import sys
50
import time                                                # clock ()
51
import os
52

    
53
from glCamera import *
54
from glFont import *
55

    
56

    
57
# *********************** Globals *********************** 
58
# Python 2.2 defines these directly
59
#try:
60
#        True
61
#except NameError:
62
#        True = 1==1
63
#        False = 1==0
64

    
65

    
66
# Some api in the chain is translating the keystrokes to this octal string
67
# so instead of saying: ESCAPE = 27, we use the following.
68
ESCAPE = b'\033'
69

    
70
# Number of the glut window.
71
window = 0
72
base = None
73

    
74
gInfoOn = False
75
gFrames = 0
76
gStartTime = -1
77
gCurrentTime = -1
78
gFPS = -1
79
gCamera = None
80

    
81
# //##################  NEW STUFF  ##################################
82

    
83
qobj = None                                        # //the quadric for our cylinder
84
gcylList = None
85

    
86

    
87
def LoadTexture (path):
88
        """ // Load Image And Convert To A Texture
89
        path can be a relative path, or a fully qualified path.
90
        returns tuple of status and ID:
91
        returns False if the requested image couldn't loaded as a texture
92
        returns True and the texture ID if image was loaded
93
        """
94
        # Catch exception here if image file couldn't be loaded
95
        try:
96
                # Note, NYI, path specified as URL's could be access using python url lib
97
                # OleLoadPicturePath () supports url paths, but that capability isn't critcial to this tutorial.
98
                print(path)
99
                Picture = Image.open(path)
100
        except:
101
                return False, 0
102

    
103
        glMaxTexDim = glGetIntegerv (GL_MAX_TEXTURE_SIZE)
104

    
105
        WidthPixels = Picture.size[0]
106
        HeightPixels = Picture.size[1]
107

    
108
        if ((WidthPixels > glMaxTexDim) or (HeightPixels > glMaxTexDim)):
109
                # The image file is too large. Shrink it to fit within the texture dimensions
110
                # support by our rendering context for a GL texture.
111
                # Note, Feel free to experiemnt and force a resize by placing a small val into
112
                # glMaxTexDim (e.g. 32,64,128).
113
                print("Texture image (%d by %d) is larger than supported by GL %d." % (WidthPixels, HeightPixels, glMaxTexDim))
114

    
115
        # Create a raw string from the image data - data will be unsigned bytes
116
        # RGBpad, no stride (0), and first line is top of image (-1)
117
        pBits = Picture.tobytes("raw", "RGBX", 0, -1)
118

    
119
        # // Typical Texture Generation Using Data From The Bitmap
120
        texid = glGenTextures(1);                                                                                        # // Create The Texture
121
        glBindTexture(GL_TEXTURE_2D, texid);                                                                # // Bind To The Texture ID
122
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);                # // (Modify This For The Type Of Filtering You Want)
123
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);     # // (Modify This For The Type Of Filtering You Want)
124

    
125
        # // (Modify This If You Want Mipmaps)
126
        glTexImage2D(GL_TEXTURE_2D, 0, 3, WidthPixels, HeightPixels, 0, GL_RGBA, GL_UNSIGNED_BYTE, pBits);
127

    
128
        # Cleanup (this would all happen automatically upon return... just spelling it out)
129
        # // Decrements IPicture Reference Count
130
        Picture = None
131
        return True, texid                                        # // Return True (All Good)
132

    
133

    
134
# A general OpenGL initialization function.  Sets all of the initial parameters. 
135
def InitGL(Width, Height):                                # We call this right after our OpenGL window is created.
136
        global gFont, gCamera, gStartTime, gcylList, qobj
137

    
138
        glShadeModel(GL_SMOOTH)                                # Enables Smooth Color Shading
139
        glClearColor(0.0, 0.0, 0.0, 0.5)        # This Will Clear The Background Color To Black
140
        glClearDepth(1.0)                                        # Enables Clearing Of The Depth Buffer
141
        glEnable(GL_DEPTH_TEST)                                # Enables Depth Testing
142
        glDepthFunc(GL_LEQUAL)                                # The Type Of Depth Test To Do
143
        glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) # Really Nice Perspective Calculations
144

    
145
        status, tex = LoadTexture (os.path.join("Art","Font.bmp"))
146
        if (status):
147
                gFont = glFont ()
148
                gFont.SetFontTexture (tex)
149
                gFont.SetWindowSize (1024, 768)
150
                gFont.BuildFont (1.0)
151
        else:
152
                print("Failed to build font 'Art/Font.bmp'")
153

    
154

    
155
        gCamera = glCamera ()
156
        gCamera.m_MaxHeadingRate = 1.0;                        # // Set our Maximum rates for the camera
157
        gCamera.m_MaxPitchRate = 1.0;                        # // Set our Maximum rates for the camera
158
        gCamera.m_HeadingDegrees = 0.0;                        # // Set our Maximum rates for the camera
159

    
160
        # // Try and load the HardGlow texture tell the user if we can't find it then quit
161
        status, gCamera.m_GlowTexture = LoadTexture(os.path.join("Art","HardGlow2.bmp"));
162
        if (not status):
163
                print("Failed to load Hard Glow texture.")
164

    
165
        # // Try and load the BigGlow texture tell the user if we can't find it then quit
166
        status, gCamera.m_BigGlowTexture = LoadTexture(os.path.join("Art","BigGlow3.bmp"))
167
        if (not status):
168
                print("Failed to load Big Glow texture.")
169

    
170
        # // Try and load the Halo texture tell the user if we can't find it then quit
171
        status, gCamera.m_HaloTexture = LoadTexture(os.path.join("Art","Halo3.bmp"))
172
        if (not status):
173
                print("Failed to load Halo texture.")
174
        
175
        # // Try and load the Streaks texture tell the user if we can't find it then quit
176
        status, gCamera.m_StreakTexture = LoadTexture(os.path.join("Art","Streaks4.bmp"))
177
        if (not status):
178
                print("Failed to load Streaks texture.")
179

    
180
        # //##################  NEW STUFF  ##################################
181

    
182
        # // Just create a cylinder that will be used as occluder object
183
        gcylList = glGenLists(1);
184
        qobj = gluNewQuadric();
185
        gluQuadricDrawStyle(qobj, GLU_FILL); 
186
        gluQuadricNormals(qobj, GLU_SMOOTH);
187
        glNewList(gcylList, GL_COMPILE);
188
        # List Start
189
        glEnable(GL_COLOR_MATERIAL);
190
        glColor3f(0.0, 0.0, 1.0);
191
        glEnable(GL_LIGHT0);
192
        glEnable(GL_LIGHTING);
193
        glTranslatef(0.0,0.0,-2.0);
194
        gluCylinder(qobj, 0.5, 0.5, 4.0, 15, 5);
195
        glDisable(GL_LIGHTING);
196
        glDisable(GL_LIGHT0);
197
        glDisable(GL_COLOR_MATERIAL);
198
        glEndList();
199
        # List End
200

    
201
        # if (gHaveWin32):
202
        #        gStartTime = win32api.GetTickCount ()         # // Get the time the app started
203
        gStartTime = time.clock ();                                         # // Get the time the app started
204

    
205
        return True                                                                        # // Initialization Went OK
206
        
207

    
208
# The function called when our window is resized (which shouldn't happen if you enable fullscreen, below)
209
def ReSizeGLScene(Width, Height):
210
        if Height == 0:                                                # Prevent A Divide By Zero If The Window Is Too Small 
211
                Height = 1
212

    
213
        glViewport(0, 0, Width, Height)                # Reset The Current Viewport And Perspective Transformation
214
        glMatrixMode(GL_PROJECTION)
215
        glLoadIdentity()
216
        # // field of view, aspect ratio, near and far
217
        # This will squash and stretch our objects as the window is resized.
218
        # Note that the near clip plane is 1 (hither) and the far plane is 1000 (yon)
219
        gluPerspective(45.0, float(Width)/float(Height), 1, 1000.0)
220

    
221
        glMatrixMode(GL_MODELVIEW)
222
        glLoadIdentity()
223

    
224
def DrawGLInfo ():
225
        global gCamera, gFont, gFrames, gCurrentTime, gCurrentTime, gStartTime, gFPS
226

    
227
        projMatrix = glGetFloatv(GL_PROJECTION_MATRIX);                                        # // Grab the projection matrix
228
        modelMatrix = glGetFloatv(GL_MODELVIEW_MATRIX);                                # // Grab the modelview matrix
229

    
230
        # // Print out the cameras position
231
        glColor4f(1.0, 1.0, 1.0, 1.0);
232
        String = "m_Position............. = %.02f, %.02f, %.02f" % (gCamera.m_Position.x, gCamera.m_Position.y, gCamera.m_Position.z)
233
        gFont.glPrintf(10, 720, 1, String);
234
        
235
        # // Print out the cameras direction
236
        String = "m_DirectionVector...... = %.02f, %.02f, %.02f" % (gCamera.m_DirectionVector.i, gCamera.m_DirectionVector.j, gCamera.m_DirectionVector.k);
237
        gFont.glPrintf(10, 700, 1, String);
238
        
239
        # // Print out the light sources position
240
        String = "m_LightSourcePos....... = %.02f, %.02f, %.02f" % (gCamera.m_LightSourcePos.x, gCamera.m_LightSourcePos.y, gCamera.m_LightSourcePos.z);
241
        gFont.glPrintf(10, 680, 1, String);
242

    
243
        # // Print out the intersection point
244
        String = "ptIntersect............ = %.02f, %.02f, %.02f" % (gCamera.m_ptIntersect.x, gCamera.m_ptIntersect.y, gCamera.m_ptIntersect.z);
245
        gFont.glPrintf(10, 660, 1, String);
246

    
247
        # // Print out the vector that points from the light source to the camera
248
        String = "vLightSourceToCamera... = %.02f, %.02f, %.02f" % (gCamera.vLightSourceToCamera.i, gCamera.vLightSourceToCamera.j, gCamera.vLightSourceToCamera.k);
249
        gFont.glPrintf(10, 640, 1, String);
250

    
251
        # // Print out the vector that points from the light source to the intersection point.
252
        String = "vLightSourceToIntersect = %.02f, %.02f, %.02f" % (gCamera.vLightSourceToIntersect.i, gCamera.vLightSourceToIntersect.j, gCamera.vLightSourceToIntersect.k);
253
        gFont.glPrintf(10, 620, 1, String);
254

    
255
        # // Let everyone know the below matrix is the model view matrix
256
        String = "GL_MODELVIEW_MATRIX";
257
        gFont.glPrintf(10, 580, 1, String);
258
        
259
        # // Print out row 1 of the model view matrix
260
        String = "%.02f, %.02f, %.02f, %.02f" % (modelMatrix[0][0], modelMatrix[0][1], modelMatrix[0][2], modelMatrix[0][3]);
261
        gFont.glPrintf(10, 560, 1, String);
262

    
263
        # // Print out row 2 of the model view matrix
264
        String = "%.02f, %.02f, %.02f, %.02f" % (modelMatrix[1][0], modelMatrix[1][1], modelMatrix[1][2], modelMatrix[1][3]);
265
        gFont.glPrintf(10, 540, 1, String);
266

    
267
        # // Print out row 3 of the model view matrix
268
        String = "%.02f, %.02f, %.02f, %.02f" % (modelMatrix[2][0], modelMatrix[2][1], modelMatrix[2][2], modelMatrix[2][3]);
269
        gFont.glPrintf(10, 520, 1, String);
270

    
271
        # // Print out row 4 of the model view matrix
272
        String = "%.02f, %.02f, %.02f, %.02f" % (modelMatrix[3][0], modelMatrix[3][1], modelMatrix[3][2], modelMatrix[3][3]);
273
        gFont.glPrintf(10, 500, 1, String);
274

    
275
        # // Let everyone know the below matrix is the projection matrix
276
        String = "GL_PROJECTION_MATRIX";
277
        gFont.glPrintf(10, 460, 1, String);
278
        
279
        # // Print out row 1 of the projection view matrix
280
        String = "%.02f, %.02f, %.02f, %.02f" % (projMatrix[0][0], projMatrix[0][1], projMatrix[0][2], projMatrix[0][3]);
281
        gFont.glPrintf(10, 440, 1, String);
282

    
283
        # // Print out row 2 of the projection view matrix
284
        String = "%.02f, %.02f, %.02f, %.02f" % (projMatrix[1][0], projMatrix[1][1], projMatrix[1][2], projMatrix[1][3]);
285
        gFont.glPrintf(10, 420, 1, String);
286

    
287
        # // Print out row 3 of the projection view matrix
288
        String = "%.02f, %.02f, %.03f, %.03f" % (projMatrix[2][0], projMatrix[2][1], projMatrix[2][2], projMatrix[2][3]);
289
        gFont.glPrintf(10, 400, 1, String);
290

    
291
        # // Print out row 4 of the projection view matrix
292
        String = "%.02f, %.02f, %.03f, %.03f" % (projMatrix[3][0], projMatrix[3][1], projMatrix[3][2], projMatrix[3][3]);
293
        gFont.glPrintf(10, 380, 1, String);
294

    
295
        # // Let everyone know the below values are the Frustum clipping planes
296
        gFont.glPrintf(10, 320, 1, "FRUSTUM CLIPPING PLANES");
297

    
298
        # // Print out the right clipping plane
299
        String = "%.02f, %.02f, %.02f, %.02f" % (gCamera.m_Frustum[0][0], gCamera.m_Frustum[0][1], gCamera.m_Frustum[0][2], gCamera.m_Frustum[0][3]);
300
        gFont.glPrintf(10, 300, 1, String);
301

    
302
        # // Print out the left clipping plane
303
        String = "%.02f, %.02f, %.02f, %.02f" % (gCamera.m_Frustum[1][0], gCamera.m_Frustum[1][1], gCamera.m_Frustum[1][2], gCamera.m_Frustum[1][3]);
304
        gFont.glPrintf(10, 280, 1, String);
305

    
306
        # // Print out the bottom clipping plane
307
        String = "%.02f, %.02f, %.02f, %.02f" % (gCamera.m_Frustum[2][0], gCamera.m_Frustum[2][1], gCamera.m_Frustum[2][2], gCamera.m_Frustum[2][3]);
308
        gFont.glPrintf(10, 260, 1, String);
309

    
310
        # // Print out the top clipping plane
311
        String = "%.02f, %.02f, %.02f, %.02f" % (gCamera.m_Frustum[3][0], gCamera.m_Frustum[3][1], gCamera.m_Frustum[3][2], gCamera.m_Frustum[3][3]);
312
        gFont.glPrintf(10, 240, 1, String);
313

    
314
        # // Print out the far clipping plane
315
        String = "%.02f, %.02f, %.02f, %.02f" % (gCamera.m_Frustum[4][0], gCamera.m_Frustum[4][1], gCamera.m_Frustum[4][2], gCamera.m_Frustum[4][3]);
316
        gFont.glPrintf(10, 220, 1, String);
317

    
318
        # // Print out the near clipping plane
319
        String = "%.02f, %.02f, %.02f, %.02f" % (gCamera.m_Frustum[5][0], gCamera.m_Frustum[5][1], gCamera.m_Frustum[5][2], gCamera.m_Frustum[5][3]);
320
        gFont.glPrintf(10, 200, 1, String);
321

    
322
        if(gFrames >= 100):                                                                                        # // if we are due for another FPS update
323
                # gCurrentTime = win32api.GetTickCount ();                                        # // Get the current time
324
                gCurrentTime = time.clock ();                                                        # // Get the current time
325
                DiffTime = gCurrentTime - gStartTime;                                        # // Find the difference between the start and end times
326
                # gFPS = (gFrames / float (DiffTime)) * 1000.0;                                        # // Compute the FPS
327
                gFPS = (gFrames / float (DiffTime));                                        # // Compute the FPS
328
                gStartTime = gCurrentTime;                                                                # // Set the current start time to the current time
329
                gFrames = 1;                                                                                        # // Set the number of frames to 1
330
        else:
331
                gFrames += 1;                                                                                        # // We are not due to for another update so add one to the frame count
332
        
333
        # // Print out the FPS
334
        String = "FPS %.02f" % (gFPS);
335
        gFont.glPrintf(10, 160, 1, String);
336
        return
337

    
338

    
339
def DrawGLScene ():
340
        """ // Here's Where We Do All The Drawing """
341
        global gCamera, gcylList, ginfoOn
342

    
343
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);                # // Clear Screen And Depth Buffer
344
        glLoadIdentity();                                                                                # // Reset The Current Modelview Matrix
345

    
346
        # // We want our light source to be 50 units if front 
347
        # // of the camera all the time to make it look like 
348
        # // it is infinately far away from the camera. We only
349
        # // do this to the z coordinate because we want to see
350
        # // the flares adjust if we fly in a straight line.
351
        gCamera.m_LightSourcePos.z = gCamera.m_Position.z - 50.0;
352

    
353

    
354
        # //##################### NEW STUFF ##########################
355
        # // Draw our cylinder and make it "do something"
356
        # // Of course we do that BEFORE testing for occlusion
357
        # // We need our depth buffer to be filled to check against occluder objects
358
        glPushMatrix();
359
        glLoadIdentity();
360
        glTranslatef(0.0, 0.0, -20.0);
361
        # glRotatef(win32api.GetTickCount () / 50.0, 0.3, 0.0, 0.0);
362
        # glRotatef(win32api.GetTickCount () / 50.0, 0.0, 0.5, 0.0);
363
        glRotatef((time.clock () * 1000.0) / 50.0, 0.3, 0.0, 0.0);
364
        glRotatef((time.clock () * 1000.0) / 50.0, 0.0, 0.5, 0.0);
365
        glCallList(gcylList);
366
        glPopMatrix();
367

    
368
        gCamera.SetPrespective();                                                # // Set our perspective/oriention on the world
369
        gCamera.RenderLensFlare();                                                # // Render the lens flare
370
        gCamera.UpdateFrustumFaster();                                        # // Update the frustum as fast as possible.
371
        
372
        # // Check to see if info has been toggled by 1,2
373
        if (gInfoOn):
374
                DrawGLInfo();                                                                # // Info is on so draw the GL information.                                                                
375

    
376
        glutSwapBuffers()
377
        return True
378

    
379

    
380
# The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y)  
381
def keyPressed(*args):
382
        global window, gCamera, gInfoOn, gFont, gcylList, qobj
383
        # If escape is pressed, kill everything.
384
        key = args[0]
385
        if key == ESCAPE:
386
                gFont.release()
387
                gCamera.release()
388
                gluDeleteQuadric(qobj)
389
                glDeleteLists(gcylList, 1)
390
                sys.exit()
391

    
392
        if key == b'W' or key == b'w':
393
                gCamera.ChangePitch(-0.2);                                                # // Pitch the camera up 0.2 degrees
394

    
395
        if key == b'S' or key == b's':
396
                gCamera.ChangePitch(0.2);                                                # // Pitch the camera down 0.2 degrees
397
        
398
        if key == b'D' or key == b'd':
399
                gCamera.ChangeHeading(0.2);                                                # // Yaw the camera to the left
400
        
401
        if key == b'A' or key == b'a':
402
                gCamera.ChangeHeading(-0.2);                                        # // Yaw the camera to the right
403
        
404
        if key == b'Z' or key == b'z':
405
                gCamera.m_ForwardVelocity = 0.01;                                # // Start moving the camera forward 0.01 units every frame
406

    
407
        if key == b'C' or key == b'c':
408
                gCamera.m_ForwardVelocity = -0.01;                                # // Start moving the camera backwards 0.01 units every frame
409
        
410
        if key == b'X' or key == b'x':
411
                gCamera.m_ForwardVelocity = 0.0;                                # // Stop the camera from moving.
412

    
413
        if args[0] == '1':
414
                gInfoOn = True;                                                                        # // Toggle info on
415
        
416
        if args[0] == '2':
417
                gInfoOn = False;                                                        # // Toggle info off
418

    
419

    
420
def main():
421
        global window
422
        # pass arguments to init
423
        glutInit(sys.argv)
424

    
425
        # Select type of Display mode:   
426
        #  Double buffer 
427
        #  RGBA color
428
        # Alpha components supported 
429
        # Depth buffer
430
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
431
        
432
        # get a 640 x 480 window 
433
        glutInitWindowSize(640, 480)
434
        
435
        # the window starts at the upper left corner of the screen 
436
        glutInitWindowPosition(0, 0)
437
        
438
        # Okay, like the C version we retain the window id to use when closing, but for those of you new
439
        # to Python, remember this assignment would make the variable local and not global
440
        # if it weren't for the global declaration at the start of main.
441
        window = glutCreateWindow(b"Lens Flare Tutorial")
442

    
443
        # Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to
444
        # set the function pointer and invoke a function to actually register the callback, otherwise it
445
        # would be very much like the C version of the code.        
446
        glutDisplayFunc(DrawGLScene)
447
        
448
        # Uncomment this line to get full screen.
449
        #glutFullScreen()
450

    
451
        # When we are doing nothing, redraw the scene.
452
        glutIdleFunc(DrawGLScene)
453
        
454
        # Register the function called when our window is resized.
455
        glutReshapeFunc(ReSizeGLScene)
456
        
457
        # Register the function called when the keyboard is pressed.  
458
        glutKeyboardFunc(keyPressed)
459

    
460
        # We've told Glut the type of window we want, and we've told glut about
461
        # various functions that we want invoked (idle, resizing, keyboard events).
462
        # Glut has done the hard work of building up thw windows DC context and 
463
        # tying in a rendering context, so we are ready to start making immediate mode
464
        # GL calls.
465
        # Call to perform inital GL setup (the clear colors, enabling modes, and most releveant -
466
        # consturct the displays lists for the bitmap font.
467
        InitGL(640, 480)
468

    
469
        # Start Event Processing Engine        
470
        glutMainLoop()
471

    
472
# Print message to console, and kick off the main to get it rolling.
473
if __name__ == "__main__":
474
        print("Hit ESC key to quit.")
475
        main()
476