Difference between revisions of "User:Crond/sandbox/openglExample"

From CEGUI Wiki - Crazy Eddie's GUI System (Open Source)
Jump to: navigation, search
m (1)
 
m (Requirements: superfluous)
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Base app ==
+
{{VersionBadge|0.7}} {{VersionAtLeast|0.7.5}}
I will provide a little base application below so you know the basics of how to use CEGUI in python environment. OpenGL is used in the base app.
+
<br /><br /><br /><br />
  
Also, note that this script assumes that the default CEGUI resources (lua_scripts, schemes, xml_schemas, etc) are located in a directory named 'datafiles', which itself is located in the same directory as the script itself. That is to say, if the script path is '/home/foo/script.py', there needs to be a path '/home/foo/datafiles' which contains all the resources.
+
== Introduction ==
 +
This presents a minimal PyCEGUI application, using OpenGL as the renderer. The goal is to familiarize the reader with the basics of how to get PyCEGUI up and running, and to provide a few pointers along the way.
  
 +
== Requirements ==
 +
* Python 2.6
 +
* PyCEGUI
 +
* PyOpenGL
 +
 +
== Notes ==
 +
This example assumes you have the CEGUI resources located in the same directory as the script; change `PATH_RESOURCES` if they are elsewhere.
 +
 +
== Source ==
 
<source lang="python">
 
<source lang="python">
import os, sys
+
#!/usr/bin/env python
 +
#
 +
#
 +
# example.py
 +
 
 +
 
 +
# Import: std
 +
import sys, os
  
 +
# Import: PyOpenGL
 
from OpenGL.GL import *
 
from OpenGL.GL import *
 
from OpenGL.GLU import *
 
from OpenGL.GLU import *
 
from OpenGL.GLUT import *
 
from OpenGL.GLUT import *
  
# you must have PyCEGUI python package installed (see pypi repository)
+
# Import: PyCEGUI
# or you must make it work yourself using binary bindings from SDK
+
 
import PyCEGUI
 
import PyCEGUI
import PyCEGUIOpenGLRenderer
+
from PyCEGUIOpenGLRenderer import OpenGLRenderer as Renderer
  
CEGUI_PATH = "./"
+
# Constants
 +
PATH_RESOURCES = './'
  
class BaseApp(object):
+
 
 +
# Application
 +
class Application(object):
 +
 
 +
    # Constructor
 
     def __init__(self):
 
     def __init__(self):
         glutInit(sys.argv)
+
         super(Application, self).__init__()
         glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA)
+
        self.lastFrameTime = 0
         glutInitWindowSize(1280, 1024)
+
        self.updateFPS = 0
         glutInitWindowPosition(100, 100)
+
        return
 +
 
 +
    # Initialize: OpenGL
 +
    # - A full list of values for `glutInitDisplayMode` can be found in the GLUT
 +
    #  documentation.
 +
    def initializeOpenGL(self):
 +
        glutInit()
 +
         glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
 +
         glutInitWindowSize(1024, 768)
 +
         glutInitWindowPosition(-1, -1) # Let the windowing system figure it out
 
         glutCreateWindow("Crazy Eddie's GUI Mk-2 - glut Base Application")
 
         glutCreateWindow("Crazy Eddie's GUI Mk-2 - glut Base Application")
 
         glutSetCursor(GLUT_CURSOR_NONE)
 
         glutSetCursor(GLUT_CURSOR_NONE)
          
+
         return
        glutDisplayFunc(self.displayFunc)
+
        glutReshapeFunc(self.reshapeFunc)
+
        glutMouseFunc(self.mouseFunc)
+
        glutMotionFunc(self.mouseMotionFunc)
+
        glutPassiveMotionFunc(self.mouseMotionFunc)
+
   
+
        PyCEGUIOpenGLRenderer.OpenGLRenderer.bootstrapSystem()
+
       
+
    def __del__(self):
+
        PyCEGUIOpenGLRenderer.OpenGLRenderer.destroySystem()
+
       
+
    def initialiseResources(self):
+
        rp = PyCEGUI.System.getSingleton().getResourceProvider()
+
  
        rp.setResourceGroupDirectory("schemes", CEGUI_PATH + "datafiles/schemes")
+
    # Initialize: Handlers
        rp.setResourceGroupDirectory("imagesets", CEGUI_PATH + "datafiles/imagesets")
+
    # - Setup the methods which will be called when events happen.
        rp.setResourceGroupDirectory("fonts", CEGUI_PATH + "datafiles/fonts")
+
    def initializeHandlers(self):
         rp.setResourceGroupDirectory("layouts", CEGUI_PATH + "datafiles/layouts")
+
         glutDisplayFunc(self.handlerDisplay)
        rp.setResourceGroupDirectory("looknfeels", CEGUI_PATH + "datafiles/looknfeel")
+
         glutReshapeFunc(self.handlerResize)
         rp.setResourceGroupDirectory("schemas", CEGUI_PATH + "datafiles/xml_schemas")
+
         glutMouseFunc(self.handlerMouse)
       
+
         glutMotionFunc(self.handlerMouseMotion)
        PyCEGUI.Imageset.setDefaultResourceGroup("imagesets")
+
         glutPassiveMotionFunc(self.handlerMouseMotion)
         PyCEGUI.Font.setDefaultResourceGroup("fonts")
+
         return
        PyCEGUI.Scheme.setDefaultResourceGroup("schemes")
+
         PyCEGUI.WidgetLookManager.setDefaultResourceGroup("looknfeels")
+
        PyCEGUI.WindowManager.setDefaultResourceGroup("layouts")
+
          
+
        parser = PyCEGUI.System.getSingleton().getXMLParser()
+
        if parser.isPropertyPresent("SchemaDefaultResourceGroup"):
+
            parser.setProperty("SchemaDefaultResourceGroup", "schemas")   
+
       
+
    def setupUI(self):
+
        PyCEGUI.SchemeManager.getSingleton().create("VanillaSkin.scheme")
+
         PyCEGUI.SchemeManager.getSingleton().create("TaharezLook.scheme")
+
        PyCEGUI.System.getSingleton().setDefaultMouseCursor("Vanilla-Images", "MouseArrow")
+
  
         root = PyCEGUI.WindowManager.getSingleton().loadWindowLayout("VanillaWindows.layout")
+
    # Initialize: PyCEGUI
         PyCEGUI.System.getSingleton().setGUISheet(root)
+
    # - Store some components; saves a lot of typing.
          
+
    def initializePyCEGUI(self):
         self.wnd = PyCEGUI.WindowManager.getSingleton().createWindow("TaharezLook/FrameWindow", "Demo Window")
+
         Renderer.bootstrapSystem()
         root.addChildWindow(self.wnd)
+
        self.sys = PyCEGUI.System.getSingleton()
       
+
        self.rp = self.sys.getResourceProvider()
     def run(self):
+
        self.scheme = PyCEGUI.SchemeManager.getSingleton()
         self.initialiseResources()
+
         self.wm = PyCEGUI.WindowManager.getSingleton()
         self.setupUI()
+
        return
   
+
 
         self.lastFrameTime = glutGet(GLUT_ELAPSED_TIME)
+
    # Initialize: Defaults
         self.updateFPS = 0
+
    # - Resource locations.
         glutMainLoop()
+
    def initializeDefaults(self):
          
+
         self.rp.setResourceGroupDirectory('schemes', os.path.join(PATH_RESOURCES, 'datafiles/schemes'))
     def displayFunc(self):
+
         self.rp.setResourceGroupDirectory('imagesets', os.path.join(PATH_RESOURCES, 'datafiles/imagesets'))
         thisTime = glutGet(GLUT_ELAPSED_TIME)
+
        self.rp.setResourceGroupDirectory('fonts', os.path.join(PATH_RESOURCES, 'datafiles/fonts'))
         elapsed = (thisTime - self.lastFrameTime) / 1000.0
+
        self.rp.setResourceGroupDirectory('layouts', os.path.join(PATH_RESOURCES, 'datafiles/layouts'))
         self.lastFrameTime = thisTime
+
        self.rp.setResourceGroupDirectory('looknfeels', os.path.join(PATH_RESOURCES, 'datafiles/looknfeel'))
 +
        self.rp.setResourceGroupDirectory('schemas', os.path.join(PATH_RESOURCES, 'datafiles/xml_schemas'))
 +
        PyCEGUI.Imageset.setDefaultResourceGroup('imagesets')
 +
        PyCEGUI.Font.setDefaultResourceGroup('fonts')
 +
        PyCEGUI.Scheme.setDefaultResourceGroup('schemes')
 +
        PyCEGUI.WidgetLookManager.setDefaultResourceGroup('looknfeels')
 +
        PyCEGUI.WindowManager.setDefaultResourceGroup('layouts')
 +
        parser = self.sys.getXMLParser()
 +
        if parser.isPropertyPresent('SchemaDefaultResourceGroup'):
 +
            parser.setProperty('SchemaDefaultResourceGroup', 'schemas')
 +
        return
 +
 
 +
    # Initialize: GUI
 +
    # - This is where we are actually setting up the windows we will see.
 +
    def initializeGUI(self):
 +
        self.scheme.create('VanillaSkin.scheme')
 +
        self.scheme.create('TaharezLook.scheme')
 +
 
 +
        # GUISheet
 +
        self.rootWindow = self.wm.loadWindowLayout('VanillaWindows.layout')
 +
        self.sys.setGUISheet(self.rootWindow)
 +
 
 +
        # Cursor
 +
        self.sys.setDefaultMouseCursor('Vanilla-Images', 'MouseArrow')
 +
 
 +
        # An extra window
 +
        w = self.wm.createWindow('TaharezLook/FrameWindow', 'Demo window')
 +
         self.rootWindow.addChildWindow(w)
 +
        return
 +
 
 +
    # Initialize
 +
     def Initialize(self):
 +
         self.initializeOpenGL()
 +
         self.initializeHandlers()
 +
         self.initializePyCEGUI()
 +
         self.initializeDefaults()
 +
         self.initializeGUI()
 +
         return
 +
 
 +
    # Handler: Display
 +
     def handlerDisplay(self):
 +
 
 +
        # Injecting the time allows CEGUI to know how much time has passed, and
 +
        # use that to coordinate certain activities - fading, animation, tooltips,
 +
        # etc.
 +
         now = glutGet(GLUT_ELAPSED_TIME)
 +
         elapsed = (now - self.lastFrameTime) / 1000.0
 +
         self.lastFrameTime = now
 
         self.updateFPS = self.updateFPS - elapsed
 
         self.updateFPS = self.updateFPS - elapsed
          
+
         self.sys.injectTimePulse(elapsed)
        PyCEGUI.System.getSingleton().injectTimePulse(elapsed)
+
  
         # do rendering for this frame.
+
         # Actual rendering
 +
        # - `renderGUI` updates CEGUI's picture of the GUI.
 +
        # - `glutPostRedisplay` is what actually marks the window as needing to
 +
        #  be redrawn by OpenGL.
 
         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
 
         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
         PyCEGUI.System.getSingleton().renderGUI()
+
         self.sys.renderGUI()
 
         glutPostRedisplay()
 
         glutPostRedisplay()
 
         glutSwapBuffers()
 
         glutSwapBuffers()
      
+
        return
     def reshapeFunc(self, width, height):
+
 
 +
    # Handler: Resize
 +
     # - `glViewport` modifies the OpenGL viewport to whatever the window size is.
 +
     def handlerResize(self, width, height):
 
         glViewport(0, 0, width, height)
 
         glViewport(0, 0, width, height)
         glMatrixMode(GL_PROJECTION)
+
         self.sys.notifyDisplaySizeChanged(PyCEGUI.Size(width, height))
        glLoadIdentity()
+
         return
        gluPerspective(60.0, width / height, 1.0, 50.0)
+
 
        glMatrixMode(GL_MODELVIEW)
+
    # Handler: Mouse buttons
        PyCEGUI.System.getSingleton().notifyDisplaySizeChanged(PyCEGUI.Size(width, height))
+
     def handlerMouse(self, button, state, x, y):
          
+
     def mouseFunc(self, button, state, x, y):
+
 
         if button == GLUT_LEFT_BUTTON:
 
         if button == GLUT_LEFT_BUTTON:
 
             if state == GLUT_UP:
 
             if state == GLUT_UP:
                 PyCEGUI.System.getSingleton().injectMouseButtonUp(PyCEGUI.LeftButton)
+
                 self.sys.injectMouseButtonUp(PyCEGUI.LeftButton)
 
             else:
 
             else:
                 PyCEGUI.System.getSingleton().injectMouseButtonDown(PyCEGUI.LeftButton)
+
                 self.sys.injectMouseButtonDown(PyCEGUI.LeftButton)
               
+
 
         elif button == GLUT_RIGHT_BUTTON:
 
         elif button == GLUT_RIGHT_BUTTON:
 
             if state == GLUT_UP:
 
             if state == GLUT_UP:
                 PyCEGUI.System.getSingleton().injectMouseButtonUp(PyCEGUI.RightButton)
+
                 self.sys.injectMouseButtonUp(PyCEGUI.RightButton)
 
             else:
 
             else:
                 PyCEGUI.System.getSingleton().injectMouseButtonDown(PyCEGUI.RightButton)
+
                 self.sys.injectMouseButtonDown(PyCEGUI.RightButton)
          
+
         return
    def mouseMotionFunc(self, x, y):
+
        PyCEGUI.System.getSingleton().injectMousePosition(x, y)
+
  
app = BaseApp()
+
    # Handler: Mouse motion
app.run()
+
    def handlerMouseMotion(self, x, y):
del app
+
        self.sys.injectMousePosition(x, y)
</source>
+
        return
  
I must say that this app isn't perfect or complete but it will get you going. You might want to make it exception safe and add keyboard injection. If you do that, please post it back here for others to benefit.
+
    # Run
 +
    def Run(self):
 +
        self.lastFrameTime = glutGet(GLUT_ELAPSED_TIME)
 +
        glutMainLoop()
 +
        return
 +
 
 +
 
 +
# Main
 +
def main():
 +
    app = Application()
 +
    app.Initialize()
 +
    app.Run()
 +
    return 0
 +
 
 +
 
 +
# Guard
 +
if __name__ == '__main__':
 +
    sys.exit(main())
 +
</source>

Latest revision as of 15:50, 20 June 2011

Written for CEGUI 0.7


Works with versions 0.7.x (obsolete)

Requires at least version
0.7.5





Introduction

This presents a minimal PyCEGUI application, using OpenGL as the renderer. The goal is to familiarize the reader with the basics of how to get PyCEGUI up and running, and to provide a few pointers along the way.

Requirements

  • Python 2.6
  • PyCEGUI
  • PyOpenGL

Notes

This example assumes you have the CEGUI resources located in the same directory as the script; change `PATH_RESOURCES` if they are elsewhere.

Source

#!/usr/bin/env python
#
#
# example.py
 
 
# Import: std
import sys, os
 
# Import: PyOpenGL
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
 
# Import: PyCEGUI
import PyCEGUI
from PyCEGUIOpenGLRenderer import OpenGLRenderer as Renderer
 
# Constants
PATH_RESOURCES = './'
 
 
# Application
class Application(object):
 
    # Constructor
    def __init__(self):
        super(Application, self).__init__()
        self.lastFrameTime = 0
        self.updateFPS = 0
        return
 
    # Initialize: OpenGL
    # - A full list of values for `glutInitDisplayMode` can be found in the GLUT
    #   documentation.
    def initializeOpenGL(self):
        glutInit()
        glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
        glutInitWindowSize(1024, 768)
        glutInitWindowPosition(-1, -1) # Let the windowing system figure it out
        glutCreateWindow("Crazy Eddie's GUI Mk-2 - glut Base Application")
        glutSetCursor(GLUT_CURSOR_NONE)
        return
 
    # Initialize: Handlers
    # - Setup the methods which will be called when events happen.
    def initializeHandlers(self):
        glutDisplayFunc(self.handlerDisplay)
        glutReshapeFunc(self.handlerResize)
        glutMouseFunc(self.handlerMouse)
        glutMotionFunc(self.handlerMouseMotion)
        glutPassiveMotionFunc(self.handlerMouseMotion)
        return
 
    # Initialize: PyCEGUI
    # - Store some components; saves a lot of typing.
    def initializePyCEGUI(self):
        Renderer.bootstrapSystem()
        self.sys = PyCEGUI.System.getSingleton()
        self.rp = self.sys.getResourceProvider()
        self.scheme = PyCEGUI.SchemeManager.getSingleton()
        self.wm = PyCEGUI.WindowManager.getSingleton()
        return
 
    # Initialize: Defaults
    # - Resource locations.
    def initializeDefaults(self):
        self.rp.setResourceGroupDirectory('schemes', os.path.join(PATH_RESOURCES, 'datafiles/schemes'))
        self.rp.setResourceGroupDirectory('imagesets', os.path.join(PATH_RESOURCES, 'datafiles/imagesets'))
        self.rp.setResourceGroupDirectory('fonts', os.path.join(PATH_RESOURCES, 'datafiles/fonts'))
        self.rp.setResourceGroupDirectory('layouts', os.path.join(PATH_RESOURCES, 'datafiles/layouts'))
        self.rp.setResourceGroupDirectory('looknfeels', os.path.join(PATH_RESOURCES, 'datafiles/looknfeel'))
        self.rp.setResourceGroupDirectory('schemas', os.path.join(PATH_RESOURCES, 'datafiles/xml_schemas'))
        PyCEGUI.Imageset.setDefaultResourceGroup('imagesets')
        PyCEGUI.Font.setDefaultResourceGroup('fonts')
        PyCEGUI.Scheme.setDefaultResourceGroup('schemes')
        PyCEGUI.WidgetLookManager.setDefaultResourceGroup('looknfeels')
        PyCEGUI.WindowManager.setDefaultResourceGroup('layouts')
        parser = self.sys.getXMLParser()
        if parser.isPropertyPresent('SchemaDefaultResourceGroup'):
            parser.setProperty('SchemaDefaultResourceGroup', 'schemas')
        return
 
    # Initialize: GUI
    # - This is where we are actually setting up the windows we will see.
    def initializeGUI(self):
        self.scheme.create('VanillaSkin.scheme')
        self.scheme.create('TaharezLook.scheme')
 
        # GUISheet
        self.rootWindow = self.wm.loadWindowLayout('VanillaWindows.layout')
        self.sys.setGUISheet(self.rootWindow)
 
        # Cursor
        self.sys.setDefaultMouseCursor('Vanilla-Images', 'MouseArrow')
 
        # An extra window
        w = self.wm.createWindow('TaharezLook/FrameWindow', 'Demo window')
        self.rootWindow.addChildWindow(w)
        return
 
    # Initialize
    def Initialize(self):
        self.initializeOpenGL()
        self.initializeHandlers()
        self.initializePyCEGUI()
        self.initializeDefaults()
        self.initializeGUI()
        return
 
    # Handler: Display
    def handlerDisplay(self):
 
        # Injecting the time allows CEGUI to know how much time has passed, and
        # use that to coordinate certain activities - fading, animation, tooltips,
        # etc.
        now = glutGet(GLUT_ELAPSED_TIME)
        elapsed = (now - self.lastFrameTime) / 1000.0
        self.lastFrameTime = now
        self.updateFPS = self.updateFPS - elapsed
        self.sys.injectTimePulse(elapsed)
 
        # Actual rendering
        # - `renderGUI` updates CEGUI's picture of the GUI.
        # - `glutPostRedisplay` is what actually marks the window as needing to
        #   be redrawn by OpenGL.
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        self.sys.renderGUI()
        glutPostRedisplay()
        glutSwapBuffers()
        return
 
    # Handler: Resize
    # - `glViewport` modifies the OpenGL viewport to whatever the window size is.
    def handlerResize(self, width, height):
        glViewport(0, 0, width, height)
        self.sys.notifyDisplaySizeChanged(PyCEGUI.Size(width, height))
        return
 
    # Handler: Mouse buttons
    def handlerMouse(self, button, state, x, y):
        if button == GLUT_LEFT_BUTTON:
            if state == GLUT_UP:
                self.sys.injectMouseButtonUp(PyCEGUI.LeftButton)
            else:
                self.sys.injectMouseButtonDown(PyCEGUI.LeftButton)
        elif button == GLUT_RIGHT_BUTTON:
            if state == GLUT_UP:
                self.sys.injectMouseButtonUp(PyCEGUI.RightButton)
            else:
                self.sys.injectMouseButtonDown(PyCEGUI.RightButton)
        return
 
    # Handler: Mouse motion
    def handlerMouseMotion(self, x, y):
        self.sys.injectMousePosition(x, y)
        return
 
    # Run
    def Run(self):
        self.lastFrameTime = glutGet(GLUT_ELAPSED_TIME)
        glutMainLoop()
        return
 
 
# Main
def main():
    app = Application()
    app.Initialize()
    app.Run()
    return 0
 
 
# Guard
if __name__ == '__main__':
    sys.exit(main())