Exemplo n.º 1
0
	def __init__(self, scene, projection=None, navigation=None, parent=None):
		# super init
		super().__init__(parent)
		fmt = QSurfaceFormat()
		fmt.setVersion(*opengl_version)
		fmt.setProfile(QSurfaceFormat.CoreProfile)
		fmt.setSamples(4)
		self.setFormat(fmt)
		self.setFocusPolicy(Qt.StrongFocus)
		self.setAttribute(Qt.WA_AcceptTouchEvents, True)
		
		# interaction methods
		self.projection = projection or globals()[settings.scene['projection']]()
		self.navigation = navigation or globals()[settings.controls['navigation']]()
		self.tool = [Tool(self.navigation.tool, self)] # tool stack, the last tool is used for input events, until it is removed 
		
		# render parameters
		self.scene = scene if isinstance(scene, Scene) else Scene(scene)
		self.uniforms = {'proj':fmat4(1), 'view':fmat4(1), 'projview':fmat4(1)}	# last frame rendering constants
		self.targets = []
		self.steps = []
		self.step = 0
		self.stepi = 0
		
		# dump targets
		self.map_depth = None
		self.map_idents = None
		self.fresh = set()	# set of refreshed internal variables since the last render
Exemplo n.º 2
0
 def __init__(self, scene, camera, light):
     super().__init__()
     fmt = QSurfaceFormat()
     fmt.setVersion(3, 3)
     fmt.setProfile(QSurfaceFormat.CoreProfile)
     fmt.setStencilBufferSize(8)
     self.setFormat(fmt)
     self.scene, self.camera, self.light = scene, camera, light
Exemplo n.º 3
0
def create_format():
    fmt = QSurfaceFormat()
    fmt.setProfile(QSurfaceFormat.CoreProfile)
    fmt.setVersion(3, 3)  #vmware max opengl version is 3.3
    fmt.setAlphaBufferSize(8)
    fmt.setStencilBufferSize(8)
    fmt.setDepthBufferSize(24)
    fmt.setOption(QSurfaceFormat.DebugContext)
    return fmt
Exemplo n.º 4
0
Arquivo: app.py Projeto: Ylannl/povipy
    def __init__(self, parent=None, **kwargs):
        super(ViewerWindow, self).__init__(parent)
        self.setSurfaceType(QWindow.OpenGLSurface)

        format = QSurfaceFormat()
        format.setVersion(3, 3)
        format.setProfile(QSurfaceFormat.CoreProfile)
        format.setStereo(False)
        format.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
        format.setDepthBufferSize(24)
        format.setSamples(16)
        
        self.context = QOpenGLContext(self)
        self.context.setFormat(format)
        if not self.context.create():
            raise Exception('self.context.create() failed')
        self.create()

        size = 720, 720
        self.resize(*size)

        self.context.makeCurrent(self)
        self.hud_program = CrossHairProgram()

        self.default_view = np.eye(4, dtype=np.float32)
        self.view = self.default_view
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.layer_manager = LayerManager()

        self.visibility_toggle_listeners = []
        self.multiview = True

        self.rotation = q.quaternion()
        self.scale = 0.6
        self.translation = np.zeros(3)

        self.radius = 0.5 * min(*size)
        self.fov = 5.
        self.camera_position = -12.
        self.near_clip = .1
        if 'near_clip' in kwargs:
            self.near_clip = kwargs['near_clip']
        self.far_clip = 100.
        if 'far_clip' in kwargs:
            self.far_clip = kwargs['far_clip']
        

        self.projection_mode = 'perspective' # 'orthographic'

        self.size = size
        self.bg_white = False
        self.viewpoint_dict = {}

        print((self.instructions))
Exemplo n.º 5
0
    def __init__(self, parent=None, **kwargs):
        super(ViewerWindow, self).__init__(parent)
        self.setSurfaceType(QWindow.OpenGLSurface)

        format = QSurfaceFormat()
        format.setVersion(3, 3)
        format.setProfile(QSurfaceFormat.CoreProfile)
        format.setStereo(False)
        format.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
        format.setDepthBufferSize(24)
        format.setSamples(16)

        self.context = QOpenGLContext(self)
        self.context.setFormat(format)
        if not self.context.create():
            raise Exception('self.context.create() failed')
        self.create()

        size = 720, 720
        self.resize(*size)

        self.context.makeCurrent(self)
        self.hud_program = CrossHairProgram()

        self.default_view = np.eye(4, dtype=np.float32)
        self.view = self.default_view
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.layer_manager = LayerManager()

        self.visibility_toggle_listeners = []
        self.multiview = True

        self.rotation = q.quaternion()
        self.scale = 0.6
        self.translation = np.zeros(3)

        self.radius = 0.5 * min(*size)
        self.fov = 5.
        self.camera_position = -12.
        self.near_clip = .1
        if 'near_clip' in kwargs:
            self.near_clip = kwargs['near_clip']
        self.far_clip = 100.
        if 'far_clip' in kwargs:
            self.far_clip = kwargs['far_clip']

        self.projection_mode = 'perspective'  # 'orthographic'

        self.size = size
        self.bg_white = False
        self.viewpoint_dict = {}

        print((self.instructions))
    def __init__(self,
                 args,
                 glWidget=QOpenGLWidget,
                 requestedGLVersion=(2, 1)):
        super(_TestApplication, self).__init__(args)

        glType = QOpenGLContext.openGLModuleType()

        format = QSurfaceFormat()
        format.setDepthBufferSize(24)

        if glType == QOpenGLContext.LibGL:
            info("OPENGL MODULE TYPE", "LibGL")
            format.setVersion(requestedGLVersion[0], requestedGLVersion[1])
            format.setProfile(QSurfaceFormat.CompatibilityProfile)
            format.setOption(QSurfaceFormat.DebugContext)
            QSurfaceFormat.setDefaultFormat(format)
        else:
            info(
                "OPENGL MODULE TYPE",
                "Unknown or LibGLES  <--- this is likely to cause problems down the line"
            )

        self.debugMembers = False

        self.mainWin = QWidget()

        if glWidget == QOpenGLWidget:
            # Only hard code size if we're not using a canvas
            self.mainWin.resize(600, 600)

        self.mainWin.setWindowTitle('TestApplication')

        self.mainWidget = glWidget()

        self.layout = QHBoxLayout(self.mainWin)
        self.layout.addWidget(self.mainWidget)

        self.mainWin.show()

        ctx = QOpenGLContext.currentContext()
        info("GL CURRENT CONTEXT", ctx)

        format = ctx.format()

        info("EFFECTIVE GL VERSION", ctx.format().version())

        self.aboutToQuit.connect(self.applicationClosing)
Exemplo n.º 7
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        fmt = QSurfaceFormat()
        fmt.setVersion(3, 3)
        fmt.setProfile(QSurfaceFormat.CoreProfile)
        # fmt.setDepthBufferSize(24)
        self.setFormat(fmt)

        timer = QTimer(self)
        timer.timeout.connect(self.update)
        timer.start(1000/60) # 60 FPS

        self.rotation_speed = np.zeros(3)

        self.last_update = None
        self.last_pos = None
Exemplo n.º 8
0
    def __init__(self):
        super().__init__()

        fmt = QSurfaceFormat()
        fmt.setVersion(2, 0)
        fmt.setProfile(QSurfaceFormat.CompatibilityProfile)
        fmt.setStereo(False)
        fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer)

        self.setSurfaceType(QWindow.OpenGLSurface)
        self.context = QOpenGLContext()
        self.context.setFormat(fmt)

        if not self.context.create():
            raise Exception("Unable to create context")

        self.create()
        self.setTitle("OpenGL")
Exemplo n.º 9
0
    def __init__(self, scene, projection=None, navigation=None, parent=None):
        # super init
        super(QOpenGLWidget, self).__init__(parent)
        fmt = QSurfaceFormat()
        fmt.setVersion(*opengl_version)
        fmt.setProfile(QSurfaceFormat.CoreProfile)
        fmt.setSamples(4)
        self.setFormat(fmt)

        # ugly trick to receive interaction events in a different function than QOpenGLWidget.event (that one is locking the GIL during the whole rendering, killing any possibility of having a computing thread aside)
        # that event reception should be in the current widget ...
        self.handler = GhostWidget(self)
        self.handler.setFocusPolicy(Qt.StrongFocus)
        self.handler.setAttribute(Qt.WA_AcceptTouchEvents, True)

        ViewCommon.__init__(self, scene, projection=None, navigation=None)
        self.tool = [
            Tool(self.navigation.tool, self)
        ]  # tool stack, the last tool is used for input events, until it is removed
Exemplo n.º 10
0
class OpenGLApp(QMainWindow):
    """Main window."""
    def __init__(self, versionprofile=None, *args, **kwargs):
        """Initialize with an OpenGL Widget."""
        super(OpenGLApp, self).__init__(*args, **kwargs)

        self.widget = QOpenGLControllerWidget(versionprofile=versionprofile)
        self.setMinimumSize(400, 400)
        self.setCentralWidget(self.widget)
        self.show()


if __name__ == '__main__':
    import sys

    fmt = QSurfaceFormat()
    fmt.setVersion(4, 1)
    fmt.setProfile(QSurfaceFormat.CoreProfile)
    fmt.setSamples(4)
    fmt.setSwapInterval(0)
    QSurfaceFormat.setDefaultFormat(fmt)

    vp = QOpenGLVersionProfile()
    vp.setVersion(4, 1)
    vp.setProfile(QSurfaceFormat.CoreProfile)

    app = QApplication(sys.argv)
    window = OpenGLApp(versionprofile=vp)
    window.show()
    sys.exit(app.exec_())
Exemplo n.º 11
0
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication, QOpenGLVersionProfile, QSurfaceFormat
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import qmlRegisterType

from _004_3d_loading_model_and_rotating.object import ModelUnderlay
import platform

if __name__ == '__main__':
	# Not working in Ubuntu 16.04, result in 1282 error for simple calling like glViewport(...)
	# TODO

	if platform.uname().system == 'Darwin':
		f = QSurfaceFormat()
		f.setVersion(4, 1)
		f.setDepthBufferSize(1)  # fix depth buffer error
		f.setStencilBufferSize(1)  # fix stencil buffer error

		# If CoreProfile is used, all the other QML rendering will fail, because they only use 2.1
		f.setProfile(QSurfaceFormat.CompatibilityProfile)
		QSurfaceFormat.setDefaultFormat(f)

	qmlRegisterType(ModelUnderlay, 'OpenGLUnderQml', 1, 0, 'ModelUnderlay')

	app = QGuiApplication(sys.argv)

	view = QQuickView()
	# view.setFormat(f)
	view.setPersistentSceneGraph(True)
	view.setPersistentOpenGLContext(True)
Exemplo n.º 12
0
import sys

from PyQt5.QtGui import QSurfaceFormat
from PyQt5.QtWidgets import QApplication
from mcjsontool.ui.ui import JSONToolUI
import mcjsontool.plugin

if __name__ == "__main__":
    app = QApplication(sys.argv)
    format_ = QSurfaceFormat()
    format_.setVersion(4, 3)
    format_.setDepthBufferSize(24)
    format_.setProfile(QSurfaceFormat.CoreProfile)
    QSurfaceFormat.setDefaultFormat(format_)
    # temp: setup temp workspac

    w = JSONToolUI()
    w.show()

    sys.exit(app.exec_())
Exemplo n.º 13
0
                         QSurfaceFormat, QWindow)
from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem, QAbstractItemView, QDockWidget

from OpenGL import GL as gl
import ctypes
import numpy as np
import math

from .linalg import quaternion as q
from .transforms import *
from .gloo import *

# import threading

DEFAULT_FORMAT = QSurfaceFormat()
DEFAULT_FORMAT.setVersion(3, 3)
DEFAULT_FORMAT.setProfile(QSurfaceFormat.CoreProfile)
DEFAULT_FORMAT.setStereo(False)
DEFAULT_FORMAT.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
DEFAULT_FORMAT.setDepthBufferSize(24)
DEFAULT_FORMAT.setSamples(4)


class OpenGLWindow(QWindow):
    def __init__(self, parent=None):
        super(OpenGLWindow, self).__init__(parent)

        self.m_update_pending = False
        self.m_animating = False
        self.m_context = None
        self.m_gl = None
Exemplo n.º 14
0
from PyQt5.QtGui import QSurfaceFormat

format = QSurfaceFormat()
format.setDepthBufferSize(24)
format.setStencilBufferSize(8)
format.setVersion(3, 3)
format.setProfile(QSurfaceFormat.CoreProfile)
QSurfaceFormat.setDefaultFormat(format)
Exemplo n.º 15
0
def init():
    ''' Startup initialisation of OpenGL. '''
    if gl is None:
        version, profile = get_profile_settings()
        # Initialise application-wide GL version
        fmt = QSurfaceFormat()
        fmt.setVersion(*version)
        # profile = QSurfaceFormat.CoreProfile if sys.platform == 'darwin' else QSurfaceFormat.CompatibilityProfile

        fmt.setProfile(profile or QSurfaceFormat.CompatibilityProfile)
        QSurfaceFormat.setDefaultFormat(fmt)

        if profile is not None:
            # Use a dummy context to get GL functions
            glprofile = QOpenGLVersionProfile(fmt)
            ctx = QOpenGLContext()
            globals()['gl'] = ctx.versionFunctions(glprofile)
            # Check and set OpenGL capabilities
            if not glprofile.hasProfiles():
                raise RuntimeError(
                    'No OpenGL version >= 3.3 support detected for this system!'
                )
        else:
            # If profile was none, PyQt5 is not shipped with any OpenGL function modules. Use PyOpenGL instead
            print(
                "Couldn't find OpenGL functions in Qt. Falling back to PyOpenGL"
            )
            globals()['gl'] = importlib.import_module('OpenGL.GL')

        globals()['_glvar_sizes'] = {
            gl.GL_FLOAT: 1,
            gl.GL_FLOAT_VEC2: 2,
            gl.GL_FLOAT_VEC3: 3,
            gl.GL_FLOAT_VEC4: 4,
            gl.GL_FLOAT_MAT2: 4,
            gl.GL_FLOAT_MAT3: 9,
            gl.GL_FLOAT_MAT4: 16,
            gl.GL_FLOAT_MAT2x3: 6,
            gl.GL_FLOAT_MAT2x4: 8,
            gl.GL_FLOAT_MAT3x2: 6,
            gl.GL_FLOAT_MAT3x4: 12,
            gl.GL_FLOAT_MAT4x2: 8,
            gl.GL_FLOAT_MAT4x3: 12,
            gl.GL_INT: 1,
            gl.GL_INT_VEC2: 2,
            gl.GL_INT_VEC3: 3,
            gl.GL_INT_VEC4: 4,
            gl.GL_UNSIGNED_INT: 1,
            gl.GL_UNSIGNED_INT_VEC2: 2,
            gl.GL_UNSIGNED_INT_VEC3: 3,
            gl.GL_UNSIGNED_INT_VEC4: 4,
            gl.GL_DOUBLE: 1,
            gl.GL_DOUBLE_VEC2: 2,
            gl.GL_DOUBLE_VEC3: 3,
            gl.GL_DOUBLE_VEC4: 4,
            gl.GL_DOUBLE_MAT2: 4,
            gl.GL_DOUBLE_MAT3: 9,
            gl.GL_DOUBLE_MAT4: 16,
            gl.GL_DOUBLE_MAT2x3: 6,
            gl.GL_DOUBLE_MAT2x4: 8,
            gl.GL_DOUBLE_MAT3x2: 6,
            gl.GL_DOUBLE_MAT3x4: 12,
            gl.GL_DOUBLE_MAT4x2: 8,
            gl.GL_DOUBLE_MAT4x3: 12
        }

    return gl
Exemplo n.º 16
0
def main():
    # make the Python warnings go to Friture logger
    logging.captureWarnings(True)

    logFormat = "%(asctime)s %(levelname)s %(name)s: %(message)s"
    formatter = logging.Formatter(logFormat)

    logFileName = "friture.log.txt"
    dirs = appdirs.AppDirs("Friture", "")
    logDir = dirs.user_data_dir
    try:
        os.makedirs(logDir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    logFilePath = os.path.join(logDir, logFileName)

    # log to file
    fileHandler = logging.handlers.RotatingFileHandler(logFilePath,
                                                       maxBytes=100000,
                                                       backupCount=5)
    fileHandler.setLevel(logging.DEBUG)
    fileHandler.setFormatter(formatter)

    rootLogger = logging.getLogger()
    rootLogger.setLevel(logging.DEBUG)
    rootLogger.addHandler(fileHandler)

    if hasattr(sys, "frozen"):
        # redirect stdout and stderr to the logger if this is a pyinstaller bundle
        sys.stdout = StreamToLogger(logging.getLogger('STDOUT'), logging.INFO)
        sys.stderr = StreamToLogger(logging.getLogger('STDERR'), logging.ERROR)
    else:
        # log to console if this is not a pyinstaller bundle
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(formatter)
        rootLogger.addHandler(console)

    # make Qt logs go to Friture logger
    QtCore.qInstallMessageHandler(qt_message_handler)

    logger = logging.getLogger(__name__)

    logger.info("Friture %s starting on %s (%s)", friture.__version__,
                platform.system(), sys.platform)

    # make sure Qt loads the desktop OpenGL stack, rather than OpenGL ES or a software OpenGL
    # only the former option is compatible with the use of PyOpenGL
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseDesktopOpenGL)

    if platform.system() == "Windows":
        logger.info("Applying Windows-specific setup")

        # enable automatic scaling for high-DPI screens
        os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"

        # set the App ID for Windows 7 to properly display the icon in the
        # taskbar.
        import ctypes
        myappid = 'Friture.Friture.Friture.current'  # arbitrary string
        try:
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                myappid)
        except:
            logger.error(
                "Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal."
            )

    app = QApplication(sys.argv)

    if platform.system() == "Darwin":
        logger.info("Applying Mac OS-specific setup")
        # help the packaged application find the Qt plugins (imageformats and platforms)
        pluginsPath = os.path.normpath(
            os.path.join(QApplication.applicationDirPath(), os.path.pardir,
                         'PlugIns'))
        logger.info("Adding the following to the Library paths: %s",
                    pluginsPath)
        QApplication.addLibraryPath(pluginsPath)

        # on macOS, OpenGL 2.1 does not work well
        # request a 3.2 Core context instead
        format = QSurfaceFormat()
        format.setDepthBufferSize(24)
        format.setStencilBufferSize(8)
        format.setVersion(3, 2)
        format.setProfile(QSurfaceFormat.CoreProfile)
        QSurfaceFormat.setDefaultFormat(format)

    # Splash screen
    #pixmap = QPixmap(":/images/splash.png")
    #splash = QSplashScreen(pixmap)
    #splash.show()
    #splash.showMessage("Initializing the audio subsystem")
    app.processEvents()

    window = Friture()
    window.show()
    #splash.finish(window)

    profile = "no"  # "python" or "kcachegrind" or anything else to disable

    if len(sys.argv) > 1:
        if sys.argv[1] == "--python":
            profile = "python"
        elif sys.argv[1] == "--kcachegrind":
            profile = "kcachegrind"
        elif sys.argv[1] == "--no":
            profile = "no"
        else:
            logger.info("command-line arguments (%s) not recognized",
                        sys.argv[1:])

    return_code = 0
    if profile == "python":
        import cProfile
        import pstats

        # friture.cprof can be visualized with SnakeViz
        # http://jiffyclub.github.io/snakeviz/
        # snakeviz friture.cprof
        cProfile.runctx('app.exec_()',
                        globals(),
                        locals(),
                        filename="friture.cprof")

        logger.info("Profile saved to '%s'", "friture.cprof")

        stats = pstats.Stats("friture.cprof")
        stats.strip_dirs().sort_stats('time').print_stats(20)
        stats.strip_dirs().sort_stats('cumulative').print_stats(20)
    elif profile == "kcachegrind":
        import cProfile
        import lsprofcalltree

        p = cProfile.Profile()
        p.run('app.exec_()')

        k = lsprofcalltree.KCacheGrind(p)
        with open('cachegrind.out.00000', 'wb') as data:
            k.output(data)
    else:
        return_code = app.exec_()

    # explicitly delete the main windows instead of waiting for the interpreter shutdown
    # tentative to prevent errors on exit on macos
    del window

    sys.exit(return_code)
Exemplo n.º 17
0
#!/usr/bin/env python3

import sys

# Check if we're in a virtual environment.
if sys.prefix == sys.base_prefix:
    raise Exception('Not using a virtual environment! (See README.md)')

from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QSurfaceFormat

from widgets import *

if __name__ == '__main__':
    qsf = QSurfaceFormat()
    qsf.setRenderableType(QSurfaceFormat.OpenGL)
    qsf.setProfile(QSurfaceFormat.CoreProfile)
    qsf.setVersion(4, 1)
    QSurfaceFormat.setDefaultFormat(qsf)

    app = QApplication(sys.argv)

    imp = IMPWindow()

    sys.exit(app.exec_())
Exemplo n.º 18
0
def initialize_opengl():
    surface_format = QSurfaceFormat()
    surface_format.setProfile(QSurfaceFormat.CoreProfile)
    surface_format.setVersion(4, 5)
    surface_format.setSamples(4)
    QSurfaceFormat.setDefaultFormat(surface_format)
Exemplo n.º 19
0
from OpenGL import GL
from PIL import Image
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtGui import QSurfaceFormat
from PyQt5.QtWidgets import QFormLayout, QHBoxLayout, QInputDialog, QLabel, QLineEdit
from PyQt5.QtWidgets import QMessageBox, QOpenGLWidget, QPushButton, QVBoxLayout
from PyQt5.QtWidgets import QWidget
from strike_with_a_pose.scene import Scene
from strike_with_a_pose.settings import INITIAL_PARAMS, MODEL, TRUE_CLASS

INSTRUCTIONS_F = pkg_resources.resource_filename("strike_with_a_pose",
                                                 "instructions.html")
ABOUT_F = pkg_resources.resource_filename("strike_with_a_pose", "about.html")

fmt = QSurfaceFormat()
fmt.setVersion(3, 3)
fmt.setProfile(QSurfaceFormat.CoreProfile)
fmt.setSwapInterval(1)
fmt.setDepthBufferSize(24)
fmt.setSamples(3)
QSurfaceFormat.setDefaultFormat(fmt)


class WindowInfo:
    def __init__(self):
        self.size = (0, 0)
        self.mouse = (0, 0)
        self.wheel = 0
        self.time = 0
        self.ratio = 1.0
        self.viewport = (0, 0, 0, 0)
Exemplo n.º 20
0
class OpenGLWindow(QWindow):
    def __init__(self, parent=None):
        super(OpenGLWindow, self).__init__(parent)
        self.m_update_pending = False
        self.m_animating = False
        self.m_context = None
        self.setSurfaceType(QWindow.OpenGLSurface)

    def initialize(self):
        pass

    def setAnimating(self, animating):
        self.m_animating = animating
        if animating:
            self.renderLater()

    def renderLater(self):
        if not self.m_update_pending:
            self.m_update_pending = True
            QGuiApplication.postEvent(self, QEvent(QEvent.UpdateRequest))

    def renderNow(self):
        if not self.isExposed():
            return

        self.m_update_pending = False

        needsInitialize = False

        if self.m_context is None:
            self.m_context = QOpenGLContext(self)
            self.surface_format = QSurfaceFormat()
            self.surface_format.setVersion(4, 1)
            self.surface_format.setProfile(QSurfaceFormat.CoreProfile)
            self.m_context.setFormat(self.surface_format)
            self.m_context.create()
            needsInitialize = True

        self.m_context.makeCurrent(self)

        if needsInitialize:
            self.initialize()

        self.render()

        self.m_context.swapBuffers(self)

        if self.m_animating:
            self.renderLater()

    def event(self, event):
        if event.type() == QEvent.UpdateRequest:
            self.renderNow()
            return True
        return super(OpenGLWindow, self).event(event)

    def exposeEvent(self, event):
        self.renderNow()

    def resizeEvent(self, event):
        self.renderNow()