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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
|
# Copyright (c) 2022 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Dict, Optional, Tuple, Any
from PyQt6.QtGui import QOpenGLContext, QSurfaceFormat, QWindow, QSurface
from PyQt6.QtOpenGL import QOpenGLVersionProfile, QOpenGLVersionFunctionsFactory
from UM.Logger import Logger
from UM.Platform import Platform
class OpenGLContext:
class OpenGlVersionDetect:
Autodetect = "autodetect"
ForceLegacy = "force_legacy"
ForceModern = "force_modern"
@classmethod
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.OpenGLContextProfile.CoreProfile
else:
profile_ = QSurfaceFormat.OpenGLContextProfile.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
@classmethod
def hasExtension(cls, extension_name: str, ctx = None) -> bool:
"""Check to see if the current OpenGL implementation has a certain OpenGL extension.
:param extension_name: :type{string} The name of the extension to query for.
:param ctx: optionally provide context object to be used, or current context will be used.
:return: True if the extension is available, False if not.
"""
if ctx is None:
ctx = QOpenGLContext.currentContext()
if ctx is None:
# We failed to get the current context.
# The typing claims that this doesn't happen, yet results in the field indicate
# that it does. See sentry crash CURA-87
return False
return ctx.hasExtension(bytearray(extension_name, "utf-8"))
@classmethod
def supportsVertexArrayObjects(cls, ctx = None) -> bool:
"""Return if the current (or provided) context supports Vertex Array Objects
:param ctx: (optional) context.
"""
if ctx is None:
ctx = QOpenGLContext.currentContext()
result = False
if cls.major_version == 4 and cls.minor_version >= 1:
result = True
if not result and cls.major_version > 4:
result = True
if not result and cls.hasExtension("GL_ARB_vertex_array_object", ctx = ctx):
result = True
cls.properties["supportsVertexArrayObjects"] = result
return result
@classmethod
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.OpenGLContextProfile.CoreProfile, False for CompatibilityProfile
:param profile: (optional) QSurfaceFormat.OpenGLContextProfile.CoreProfile, CompatibilityProfile or NoProfile, overrules option core
"""
new_format = QSurfaceFormat()
new_format.setMajorVersion(major_version)
new_format.setMinorVersion(minor_version)
if core:
profile_ = QSurfaceFormat.OpenGLContextProfile.CoreProfile
else:
profile_ = QSurfaceFormat.OpenGLContextProfile.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_
@classmethod
def isLegacyOpenGL(cls) -> bool:
"""Return if the OpenGL context version we ASKED for is legacy or not"""
if cls.major_version < 4:
return True
if cls.major_version == 4 and cls.minor_version < 1:
return True
return False
@classmethod
def detectBestOpenGLVersion(cls, force_compatability: bool) -> Tuple[Optional[int], Optional[int], Optional[int]]:
"""Return "best" OpenGL to use, 4.1 core or 2.0.
result is <major_version>, <minor_version>, <profile>
The version depends on what versions are supported in Qt (4.1 and 2.0) and what
the GPU supports. If creating a context fails at all, (None, None, None) is returned
Note that PyQt only supports 4.1, 2.1 and 2.0. Cura omits support for 2.1, so the
only returned options are 4.1 and 2.0.
"""
cls.detect_ogl_context = None
if not force_compatability:
Logger.log("d", "Trying OpenGL context 4.1...")
cls.detect_ogl_context = cls.setContext(4, 1, core = True)
if cls.detect_ogl_context is not None:
fmt = cls.detect_ogl_context.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.OpenGLContextProfile.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
# Check for OS, Since this only seems to happen on specific versions of Mac OSX and
# the workaround (which involves the deletion of an OpenGL context) is a problem for some Intel drivers.
if not Platform.isOSX():
return major_version, minor_version, QSurfaceFormat.OpenGLContextProfile.CoreProfile
cls.gl_window = QWindow()
cls.gl_window.setSurfaceType(QSurface.SurfaceType.OpenGLSurface)
cls.gl_window.showMinimized()
cls.detect_ogl_context.makeCurrent(cls.gl_window)
gl_profile = QOpenGLVersionProfile()
gl_profile.setVersion(major_version, minor_version)
gl_profile.setProfile(profile)
gl = QOpenGLVersionFunctionsFactory.get(gl_profile, cls.detect_ogl_context)
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 PyQt6.
# This workaround makes the code fall back to a "Unknown" renderer in these cases.
try:
gpu_type = gl.glGetString(gl.GL_RENDERER)
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)
# Leaving this assigned to QWindow() causes a second small window to open in the background
cls.gl_window = None
if "software" in gpu_type.lower():
Logger.log("w", "Unfortunately OpenGL 4.1 uses software rendering")
else:
return major_version, minor_version, QSurfaceFormat.OpenGLContextProfile.CoreProfile
else:
Logger.log("d", "Failed to create OpenGL context 4.1.")
# Fallback: check min spec
Logger.log("d", "Trying OpenGL context 2.0...")
cls.detect_ogl_context = cls.setContext(2, 0, profile = QSurfaceFormat.OpenGLContextProfile.NoProfile)
if cls.detect_ogl_context is not None:
fmt = cls.detect_ogl_context.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.OpenGLContextProfile.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
@classmethod
def versionAsText(cls, major_version: int, minor_version: int, profile) -> str:
"""Return OpenGL version number and profile as a nice formatted string"""
if profile == QSurfaceFormat.OpenGLContextProfile.CompatibilityProfile:
xtra = "Compatibility profile"
elif profile == QSurfaceFormat.OpenGLContextProfile.CoreProfile:
xtra = "Core profile"
elif profile == QSurfaceFormat.OpenGLContextProfile.NoProfile:
xtra = "No profile"
else:
xtra = "Unknown profile"
return "%s.%s %s" % (major_version, minor_version, xtra)
# Global values, OpenGL context versions we ASKED for (not per se what we got)
major_version = 0
minor_version = 0
profile = None # type: QSurfaceFormat
# Keep already created context in memory, as some drivers (Intel) have trouble deleting OpenGL-contexts:
detect_ogl_context = None #type: Optional[QOpenGLContext]
gl_window: Any = None
# To be filled by helper functions
properties = {} # type: Dict[str, bool]
|