Welcome, guest | Sign In | My Account | Store | Cart
2

An OpenGL example in Python using PyOpenGL and PyGame modules to render a spinning triangle while the FPS (Frames Per Second) is displayed in the upper right hand corner using a TrueType font.

Python, 146 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""
    font.py -- Displays FPS in OpenGL using TrueType fonts.

    Copyright (c) 2002. Nelson Rush. All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
"""

from OpenGL.GL import *
from OpenGL.GLU import *

from pygame.locals import *
from pygame.display import *
from pygame.event import *
from pygame.key import *
from pygame.mouse import *
from pygame.font import *
from pygame.image import *
from pygame.time import *
from pygame import *
import sys

class Engine:
    def __init__(self,w,h):
        init()
        display.init()
        display.set_mode([w,h], DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE)
        self.initgl()
        self.resize(w,h)
        mouse.set_visible(0)
        self.w = w
        self.h = h
        font.init()
        if not font.get_init():
            print 'Could not render font.'
            sys.exit(0)
        self.font = font.Font('font.ttf',18)
        self.char = []
        for c in range(256):
            self.char.append(self.CreateCharacter(chr(c)))
        self.char = tuple(self.char)
        self.lw = self.char[ord('0')][1]
        self.lh = self.char[ord('0')][2]
        self.angle = 0.0
        self.frames = self.t = self.t_start = self.fps = 0
    def initgl(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClearDepth(1.0)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LEQUAL)
        glShadeModel(GL_SMOOTH)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
    def resize(self,w,h):
        if h == 0: h = 1
        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(w) / float(h), 0.5, 150.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
    def CreateCharacter(self, s):
        try:
            letter_render = self.font.render(s, 1, (255,255,255), (0,0,0))
            letter = image.tostring(letter_render, 'RGBA', 1)
            letter_w, letter_h = letter_render.get_size()
        except:
            letter = None
            letter_w = 0
            letter_h = 0
        return (letter, letter_w, letter_h)
    def textView(self):
        glViewport(0,0,self.w,self.h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0.0, self.w - 1.0, 0.0, self.h - 1.0, -1.0, 1.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
    def Print(self,s,x,y):
        s = str(s)
        i = 0
        lx = 0
        length = len(s)
        self.textView()
        glPushMatrix()
        while i < length:
            glRasterPos2i(x + lx, y)
            ch = self.char[ ord( s[i] ) ]
            glDrawPixels(ch[1], ch[2], GL_RGBA, GL_UNSIGNED_BYTE, ch[0])
            lx += ch[1]
            i += 1
        glPopMatrix()
    def DrawFPS(self, x, y):
        self.t = time.get_ticks()
        self.frames += 1
        if self.t - self.t_start > 1000:
            self.fps = self.frames * 1000 / (self.t - self.t_start)
            self.t_start = self.t
            self.frames = 0
        self.Print(self.fps, x, y)
    def draw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        self.resize(self.w,self.h)
        glTranslatef(0.0, 0.0, -6.0)
        glPushMatrix()
        glRotatef(self.angle, 0.0, 1.0, 0.0)
        glBegin(GL_TRIANGLES)
        glColor3f(0.0, 0.0, 1.0)
        glVertex3f(0.0, 1.0, 0.0)
        glVertex3f(-1.0, -1.0, 0.0)
        glVertex3f(1.0, -1.0, 0.0)
        glEnd()
        glPopMatrix()

        self.DrawFPS(self.w - (self.lw * 3), self.h - self.lh)

        self.angle += 1.0
    def run(self):
        while 1:
            e = event.poll()
            k = key.get_pressed()
            if e.type == KEYDOWN and e.key == K_ESCAPE: break
            self.draw()
            display.flip()

if __name__ == '__main__':
    engine = Engine(640,480)
    engine.run()
    font.quit()
    display.quit()

It buffers the TTF into memory and draws to any position specified in the framebuffer. Useful for displaying stats, general info., FPS, and text in a drop down console.

Disadvantage: Color/style cannot be changed on the fly without re-rendering entire character chart. And I haven't figured out just yet how to make the background transparent.

1 comment

Drew Perttula 11 years, 4 months ago  # | flag

how to make the background transparent. I didn't read the above example very carefully, but I do know how to draw a transparent-background pygame surface with opengl. Here's the relevant code from my program:

glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)

rendered=pygamefont.render(text,1,[int(c*255) for c in color])
txtsize=txtdata.get_size()
txtdata=pygame.image.tostring(rendered,"RGBA",1)

glRasterPos2d(*pos)
glPixelZoom(1,1)
glDrawPixels(txtsize[0],txtsize[1],
             GL_RGBA, GL_UNSIGNED_BYTE, txtdata)

Add a comment

Sign in to comment