Beispiel #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
Beispiel #2
0
    def setContext(cls,
                   major_version: int,
                   minor_version: int,
                   core=False,
                   profile=None):
        new_format = QSurfaceFormat()
        new_format.setMajorVersion(major_version)
        new_format.setMinorVersion(minor_version)
        if core:
            profile_ = QSurfaceFormat.CoreProfile
        else:
            profile_ = QSurfaceFormat.CompatibilityProfile
        if profile is not None:
            profile_ = profile
        new_format.setProfile(profile_)

        new_context = QOpenGLContext()
        new_context.setFormat(new_format)
        success = new_context.create()
        if success:
            return new_context
        else:
            Logger.log(
                "e", "Failed creating OpenGL context (%d, %d, core=%s)" %
                (major_version, minor_version, core))
            return None
Beispiel #3
0
    def setContext(cls,
                   major_version: int,
                   minor_version: int,
                   core=False,
                   profile=None):
        """Set OpenGL context, given major, minor version + core using QOpenGLContext
        Unfortunately, what you get back does not have to be the requested version.
        """
        new_format = QSurfaceFormat()
        new_format.setMajorVersion(major_version)
        new_format.setMinorVersion(minor_version)
        if core:
            profile_ = QSurfaceFormat.CoreProfile
        else:
            profile_ = QSurfaceFormat.CompatibilityProfile
        if profile is not None:
            profile_ = profile
        new_format.setProfile(profile_)

        new_context = QOpenGLContext()
        new_context.setFormat(new_format)
        success = new_context.create()
        if success:
            return new_context
        else:
            Logger.log(
                "e", "Failed creating OpenGL context (%d, %d, core=%s)" %
                (major_version, minor_version, core))
            return None
Beispiel #4
0
    def setDefaultFormat(cls,
                         major_version: int,
                         minor_version: int,
                         core=False,
                         profile=None) -> None:
        """Set the default format for each new OpenGL context
        :param major_version:
        :param minor_version:
        :param core: (optional) True for QSurfaceFormat.CoreProfile, False for CompatibilityProfile
        :param profile: (optional) QSurfaceFormat.CoreProfile, CompatibilityProfile or NoProfile, overrules option core
        """
        new_format = QSurfaceFormat()
        new_format.setMajorVersion(major_version)
        new_format.setMinorVersion(minor_version)
        if core:
            profile_ = QSurfaceFormat.CoreProfile
        else:
            profile_ = QSurfaceFormat.CompatibilityProfile
        if profile is not None:
            profile_ = profile
        new_format.setProfile(profile_)

        QSurfaceFormat.setDefaultFormat(new_format)
        cls.major_version = major_version
        cls.minor_version = minor_version
        cls.profile = profile_
Beispiel #5
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
Beispiel #6
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
Beispiel #7
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))
Beispiel #8
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)
Beispiel #10
0
    def setDefaultFormat(cls, major_version, minor_version, core = False, profile = None):
        new_format = QSurfaceFormat()
        new_format.setMajorVersion(major_version)
        new_format.setMinorVersion(minor_version)
        if core:
            profile_ = QSurfaceFormat.CoreProfile
        else:
            profile_ = QSurfaceFormat.CompatibilityProfile
        if profile is not None:
            profile_ = profile
        new_format.setProfile(profile_)

        QSurfaceFormat.setDefaultFormat(new_format)
        cls.major_version = major_version
        cls.minor_version = minor_version
        cls.profile = profile_
Beispiel #11
0
    def setDefaultFormat(cls, major_version, minor_version, core = False, profile = None):
        new_format = QSurfaceFormat()
        new_format.setMajorVersion(major_version)
        new_format.setMinorVersion(minor_version)
        if core:
            profile_ = QSurfaceFormat.CoreProfile
        else:
            profile_ = QSurfaceFormat.CompatibilityProfile
        if profile is not None:
            profile_ = profile
        new_format.setProfile(profile_)

        QSurfaceFormat.setDefaultFormat(new_format)
        cls.major_version = major_version
        cls.minor_version = minor_version
        cls.profile = profile_
Beispiel #12
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
Beispiel #13
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")
Beispiel #14
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
Beispiel #15
0
    def setContext(cls, major_version, minor_version, core = False, profile = None):
        new_format = QSurfaceFormat()
        new_format.setMajorVersion(major_version)
        new_format.setMinorVersion(minor_version)
        if core:
            profile_ = QSurfaceFormat.CoreProfile
        else:
            profile_ = QSurfaceFormat.CompatibilityProfile
        if profile is not None:
            profile_ = profile
        new_format.setProfile(profile_)

        new_context = QOpenGLContext()
        new_context.setFormat(new_format)
        success = new_context.create()
        if success:
            return new_context
        else:
            Logger.log("e", "Failed creating OpenGL context (%d, %d, core=%s)" % (major_version, minor_version, core))
            return None
Beispiel #16
0
    def detectBestOpenGLVersion(cls):
        Logger.log("d", "Trying OpenGL context 4.1...")
        ctx = cls.setContext(4, 1, core=True)
        if ctx is not None:
            fmt = ctx.format()
            profile = fmt.profile()

            # First test: we hope for this
            if ((fmt.majorVersion() == 4 and fmt.minorVersion() >= 1) or
                (fmt.majorVersion() >
                 4)) and profile == QSurfaceFormat.CoreProfile:
                Logger.log(
                    "d", "Yay, we got at least OpenGL 4.1 core: %s",
                    cls.versionAsText(fmt.majorVersion(), fmt.minorVersion(),
                                      profile))

                # https://riverbankcomputing.com/pipermail/pyqt/2017-January/038640.html
                # PyQt currently only implements 2.0, 2.1 and 4.1Core
                # If eg 4.5Core would be detected and used here, PyQt would not be able to handle it.
                major_version = 4
                minor_version = 1

                # CURA-6092: Check if we're not using software backed 4.1 context; A software 4.1 context
                # is much slower than a hardware backed 2.0 context
                gl_window = QWindow()
                gl_window.setSurfaceType(QWindow.OpenGLSurface)
                gl_window.showMinimized()

                gl_format = QSurfaceFormat()
                gl_format.setMajorVersion(major_version)
                gl_format.setMinorVersion(minor_version)
                gl_format.setProfile(profile)

                gl_context = QOpenGLContext()
                gl_context.setFormat(gl_format)
                gl_context.create()
                gl_context.makeCurrent(gl_window)

                gl_profile = QOpenGLVersionProfile()
                gl_profile.setVersion(major_version, minor_version)
                gl_profile.setProfile(profile)

                gl = gl_context.versionFunctions(
                    gl_profile
                )  # type: Any #It's actually a protected class in PyQt that depends on the requested profile and the implementation of your graphics card.

                gpu_type = "Unknown"  # type: str

                result = None
                if gl:
                    result = gl.initializeOpenGLFunctions()

                if not result:
                    Logger.log("e",
                               "Could not initialize OpenGL to get gpu type")
                else:
                    # WORKAROUND: Cura/#1117 Cura-packaging/12
                    # Some Intel GPU chipsets return a string, which is not undecodable via PyQt5.
                    # This workaround makes the code fall back to a "Unknown" renderer in these cases.
                    try:
                        gpu_type = gl.glGetString(gl.GL_RENDERER)  #type: str
                    except UnicodeDecodeError:
                        Logger.log(
                            "e",
                            "DecodeError while getting GL_RENDERER via glGetString!"
                        )

                Logger.log("d",
                           "OpenGL renderer type for this OpenGL version: %s",
                           gpu_type)
                if "software" in gpu_type.lower():
                    Logger.log(
                        "w",
                        "Unfortunately OpenGL 4.1 uses software rendering")
                else:
                    return major_version, minor_version, QSurfaceFormat.CoreProfile
        else:
            Logger.log("d", "Failed to create OpenGL context 4.1.")

        # Fallback: check min spec
        Logger.log("d", "Trying OpenGL context 2.0...")
        ctx = cls.setContext(2, 0, profile=QSurfaceFormat.NoProfile)
        if ctx is not None:
            fmt = ctx.format()
            profile = fmt.profile()

            if fmt.majorVersion() >= 2 and fmt.minorVersion() >= 0:
                Logger.log(
                    "d", "We got at least OpenGL context 2.0: %s",
                    cls.versionAsText(fmt.majorVersion(), fmt.minorVersion(),
                                      profile))
                return 2, 0, QSurfaceFormat.NoProfile
            else:
                Logger.log(
                    "d", "Current OpenGL context is too low: %s" %
                    cls.versionAsText(fmt.majorVersion(), fmt.minorVersion(),
                                      profile))
                return None, None, None
        else:
            Logger.log("d", "Failed to create OpenGL context 2.0.")
            return None, None, None
Beispiel #17
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)
Beispiel #18
0
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)
	view.setResizeMode(QQuickView.SizeRootObjectToView)  # Set for the object to resize correctly
	view.setSource(QUrl('ModelWindow.qml'))
	view.show()

	app.exec()
Beispiel #19
0
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
Beispiel #20
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
Beispiel #21
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)
      self.translate = False

  def wheelEvent(self,event) :
    numPixels = event.pixelDelta();

    if  numPixels.x() > 0  :
      self.modelPos.m_z += self.ZOOM

    elif  numPixels.x() < 0 :
      self.modelPos.m_z -= self.ZOOM
    self.update();


if __name__ == '__main__':
  app = QApplication(sys.argv)
  format=QSurfaceFormat()
  format.setSamples(4);
  format.setMajorVersion(4);
  format.setMinorVersion(1);
  format.setProfile(QSurfaceFormat.CoreProfile);
  # now set the depth buffer to 24 bits
  format.setDepthBufferSize(24);
  # set that as the default format for all windows
  QSurfaceFormat.setDefaultFormat(format);

  window = MainWindow()
  window.setFormat(format)
  window.resize(1024,720)
  window.show()
  sys.exit(app.exec_())
Beispiel #23
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_())
Beispiel #24
0
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)
        self.keys = np.full(256, False)
Beispiel #25
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_())
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()
Beispiel #27
0
                self.spinYFace = 0
                self.modelPos.set(Vec3.zero())
            elif key == Qt.Key.Key_L:
                self.transformLight ^= True
            self.update()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    format = QSurfaceFormat()
    format.setSamples(4)
    format.setMajorVersion(4)
    format.setMinorVersion(1)
    print(format.profile())
    if PyQtVersion == 5:
        format.setProfile(QSurfaceFormat.CoreProfile)
    else:
        format.setProfile(QSurfaceFormat.OpenGLContextProfile.CoreProfile)

    # now set the depth buffer to 24 bits
    format.setDepthBufferSize(24)
    # set that as the default format for all windows
    QSurfaceFormat.setDefaultFormat(format)

    window = MainWindow()
    window.setFormat(format)
    window.resize(1024, 720)
    window.show()
    if PyQtVersion == 5:
        sys.exit(app.exec_())
    else: