xref: /aosp_15_r20/external/angle/src/libANGLE/renderer/gl/glx/DisplayGLX.cpp (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1 //
2 // Copyright 2015 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // DisplayGLX.cpp: GLX implementation of egl::Display
8 
9 #include <algorithm>
10 #include <cstring>
11 #include <fstream>
12 
13 #include "common/debug.h"
14 #include "common/system_utils.h"
15 #include "libANGLE/Config.h"
16 #include "libANGLE/Context.h"
17 #include "libANGLE/Display.h"
18 #include "libANGLE/Surface.h"
19 #include "libANGLE/renderer/gl/ContextGL.h"
20 #include "libANGLE/renderer/gl/RendererGL.h"
21 #include "libANGLE/renderer/gl/renderergl_utils.h"
22 
23 #include "libANGLE/renderer/gl/glx/DisplayGLX.h"
24 
25 #include <EGL/eglext.h>
26 
27 #include "libANGLE/renderer/gl/glx/DisplayGLX_api.h"
28 #include "libANGLE/renderer/gl/glx/PbufferSurfaceGLX.h"
29 #include "libANGLE/renderer/gl/glx/PixmapSurfaceGLX.h"
30 #include "libANGLE/renderer/gl/glx/WindowSurfaceGLX.h"
31 #include "libANGLE/renderer/gl/glx/glx_utils.h"
32 
33 namespace
34 {
35 
GetRobustnessVideoMemoryPurge(const egl::AttributeMap & attribs)36 rx::RobustnessVideoMemoryPurgeStatus GetRobustnessVideoMemoryPurge(const egl::AttributeMap &attribs)
37 {
38     return static_cast<rx::RobustnessVideoMemoryPurgeStatus>(
39         attribs.get(GLX_GENERATE_RESET_ON_VIDEO_MEMORY_PURGE_NV, GL_FALSE));
40 }
41 
42 }  // anonymous namespace
43 
44 namespace rx
45 {
46 
IgnoreX11Errors(Display *,XErrorEvent *)47 static int IgnoreX11Errors(Display *, XErrorEvent *)
48 {
49     return 0;
50 }
51 
52 class FunctionsGLGLX : public FunctionsGL
53 {
54   public:
FunctionsGLGLX(PFNGETPROCPROC getProc)55     FunctionsGLGLX(PFNGETPROCPROC getProc) : mGetProc(getProc) {}
56 
~FunctionsGLGLX()57     ~FunctionsGLGLX() override {}
58 
59   private:
loadProcAddress(const std::string & function) const60     void *loadProcAddress(const std::string &function) const override
61     {
62         return reinterpret_cast<void *>(mGetProc(function.c_str()));
63     }
64 
65     PFNGETPROCPROC mGetProc;
66 };
67 
DisplayGLX(const egl::DisplayState & state)68 DisplayGLX::DisplayGLX(const egl::DisplayState &state)
69     : DisplayGL(state),
70       mRequestedVisual(-1),
71       mContextConfig(nullptr),
72       mContext(nullptr),
73       mCurrentNativeContexts(),
74       mInitPbuffer(0),
75       mUsesNewXDisplay(false),
76       mIsMesa(false),
77       mHasMultisample(false),
78       mHasARBCreateContext(false),
79       mHasARBCreateContextProfile(false),
80       mHasARBCreateContextRobustness(false),
81       mHasEXTCreateContextES2Profile(false),
82       mHasNVRobustnessVideoMemoryPurge(false),
83       mSwapControl(SwapControl::Absent),
84       mMinSwapInterval(0),
85       mMaxSwapInterval(0),
86       mCurrentSwapInterval(-1),
87       mCurrentDrawable(0),
88       mXDisplay(nullptr),
89       mEGLDisplay(nullptr)
90 {}
91 
~DisplayGLX()92 DisplayGLX::~DisplayGLX() {}
93 
initialize(egl::Display * display)94 egl::Error DisplayGLX::initialize(egl::Display *display)
95 {
96     mEGLDisplay           = display;
97     mXDisplay             = reinterpret_cast<Display *>(display->getNativeDisplayId());
98     const auto &attribMap = display->getAttributeMap();
99 
100     // ANGLE_platform_angle allows the creation of a default display
101     // using EGL_DEFAULT_DISPLAY (= nullptr). In this case just open
102     // the display specified by the DISPLAY environment variable.
103     if (mXDisplay == reinterpret_cast<Display *>(EGL_DEFAULT_DISPLAY))
104     {
105         mUsesNewXDisplay = true;
106         mXDisplay        = XOpenDisplay(nullptr);
107         if (!mXDisplay)
108         {
109             return egl::EglNotInitialized() << "Could not open the default X display.";
110         }
111     }
112 
113     std::string glxInitError;
114     if (!mGLX.initialize(mXDisplay, DefaultScreen(mXDisplay), &glxInitError))
115     {
116         return egl::EglNotInitialized() << glxInitError;
117     }
118 
119     mHasMultisample             = mGLX.minorVersion > 3 || mGLX.hasExtension("GLX_ARB_multisample");
120     mHasARBCreateContext        = mGLX.hasExtension("GLX_ARB_create_context");
121     mHasARBCreateContextProfile = mGLX.hasExtension("GLX_ARB_create_context_profile");
122     mHasARBCreateContextRobustness   = mGLX.hasExtension("GLX_ARB_create_context_robustness");
123     mHasEXTCreateContextES2Profile   = mGLX.hasExtension("GLX_EXT_create_context_es2_profile");
124     mHasNVRobustnessVideoMemoryPurge = mGLX.hasExtension("GLX_NV_robustness_video_memory_purge");
125 
126     std::string clientVendor = mGLX.getClientString(GLX_VENDOR);
127     mIsMesa                  = clientVendor.find("Mesa") != std::string::npos;
128 
129     // Choose the swap_control extension to use, if any.
130     // The EXT version is better as it allows glXSwapInterval to be called per
131     // window, while we'll potentially need to change the swap interval on each
132     // swap buffers when using the SGI or MESA versions.
133     if (mGLX.hasExtension("GLX_EXT_swap_control"))
134     {
135         mSwapControl = SwapControl::EXT;
136 
137         // In GLX_EXT_swap_control querying these is done on a GLXWindow so we just
138         // set default values.
139         mMinSwapInterval = 0;
140         mMaxSwapInterval = 4;
141     }
142     else if (mGLX.hasExtension("GLX_MESA_swap_control"))
143     {
144         // If we have the Mesa or SGI extension, assume that you can at least set
145         // a swap interval of 0 or 1.
146         mSwapControl     = SwapControl::Mesa;
147         mMinSwapInterval = 0;
148         mMinSwapInterval = 1;
149     }
150     else if (mGLX.hasExtension("GLX_SGI_swap_control"))
151     {
152         mSwapControl     = SwapControl::SGI;
153         mMinSwapInterval = 0;
154         mMinSwapInterval = 1;
155     }
156     else
157     {
158         mSwapControl     = SwapControl::Absent;
159         mMinSwapInterval = 1;
160         mMinSwapInterval = 1;
161     }
162 
163     if (attribMap.contains(EGL_X11_VISUAL_ID_ANGLE))
164     {
165         mRequestedVisual = static_cast<EGLint>(attribMap.get(EGL_X11_VISUAL_ID_ANGLE, -1));
166         // There is no direct way to get the GLXFBConfig matching an X11 visual ID
167         // so we have to iterate over all the GLXFBConfigs to find the right one.
168         int nConfigs;
169         int attribList[] = {
170             None,
171         };
172         glx::FBConfig *allConfigs = mGLX.chooseFBConfig(attribList, &nConfigs);
173 
174         for (int i = 0; i < nConfigs; ++i)
175         {
176             if (getGLXFBConfigAttrib(allConfigs[i], GLX_VISUAL_ID) == mRequestedVisual)
177             {
178                 mContextConfig = allConfigs[i];
179                 break;
180             }
181         }
182         XFree(allConfigs);
183 
184         if (mContextConfig == nullptr)
185         {
186             return egl::EglNotInitialized() << "Invalid visual ID requested.";
187         }
188     }
189     else
190     {
191         // When glXMakeCurrent is called, the context and the surface must be
192         // compatible which in glX-speak means that their config have the same
193         // color buffer type, are both RGBA or ColorIndex, and their buffers have
194         // the same depth, if they exist.
195         // Since our whole EGL implementation is backed by only one GL context, this
196         // context must be compatible with all the GLXFBConfig corresponding to the
197         // EGLconfigs that we will be exposing.
198         int nConfigs;
199         int attribList[]          = {// We want RGBA8 and DEPTH24_STENCIL8
200                             GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8,
201                             GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8,
202                             // We want RGBA rendering (vs COLOR_INDEX) and doublebuffer
203                             GLX_RENDER_TYPE, GLX_RGBA_BIT,
204                             // Double buffer is not strictly required as a non-doublebuffer
205                             // context can work with a doublebuffered surface, but it still
206                             // flickers and all applications want doublebuffer anyway.
207                             GLX_DOUBLEBUFFER, True,
208                             // All of these must be supported for full EGL support
209                             GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT | GLX_PBUFFER_BIT | GLX_PIXMAP_BIT,
210                             // This makes sure the config have an associated visual Id
211                             GLX_X_RENDERABLE, True, GLX_CONFIG_CAVEAT, GLX_NONE, None};
212         glx::FBConfig *candidates = mGLX.chooseFBConfig(attribList, &nConfigs);
213         if (nConfigs == 0)
214         {
215             XFree(candidates);
216             return egl::EglNotInitialized()
217                    << "Could not find a decent GLX FBConfig to create the context.";
218         }
219         mContextConfig = candidates[0];
220         XFree(candidates);
221     }
222 
223     const auto &eglAttributes = display->getAttributeMap();
224     if (mHasARBCreateContext)
225     {
226         egl::Error error = initializeContext(mContextConfig, eglAttributes, &mContext);
227         if (error.isError())
228         {
229             return error;
230         }
231     }
232     else
233     {
234         if (eglAttributes.get(EGL_PLATFORM_ANGLE_TYPE_ANGLE,
235                               EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE) ==
236             EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE)
237         {
238             return egl::EglNotInitialized() << "Cannot create an OpenGL ES platform on GLX without "
239                                                "the GLX_ARB_create_context extension.";
240         }
241 
242         XVisualInfo visualTemplate;
243         visualTemplate.visualid = getGLXFBConfigAttrib(mContextConfig, GLX_VISUAL_ID);
244 
245         int numVisuals = 0;
246         XVisualInfo *visuals =
247             XGetVisualInfo(mXDisplay, VisualIDMask, &visualTemplate, &numVisuals);
248         if (numVisuals <= 0)
249         {
250             return egl::EglNotInitialized() << "Could not get the visual info from the fb config";
251         }
252         ASSERT(numVisuals == 1);
253 
254         mContext = mGLX.createContext(&visuals[0], nullptr, true);
255         XFree(visuals);
256 
257         if (!mContext)
258         {
259             return egl::EglNotInitialized() << "Could not create GL context.";
260         }
261     }
262     ASSERT(mContext);
263 
264     mCurrentNativeContexts[angle::GetCurrentThreadUniqueId()] = mContext;
265 
266     // FunctionsGL and DisplayGL need to make a few GL calls, for example to
267     // query the version of the context so we need to make the context current.
268     // glXMakeCurrent requires a GLXDrawable so we create a temporary Pbuffer
269     // (of size 1, 1) for the duration of these calls.
270     // Ideally we would want to unset the current context and destroy the pbuffer
271     // before going back to the application but this is TODO
272     // We could use a pbuffer of size (0, 0) but it fails on the Intel Mesa driver
273     // as commented on https://bugs.freedesktop.org/show_bug.cgi?id=38869 so we
274     // use (1, 1) instead.
275 
276     int initPbufferAttribs[] = {
277         GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, None,
278     };
279     mInitPbuffer = mGLX.createPbuffer(mContextConfig, initPbufferAttribs);
280     if (!mInitPbuffer)
281     {
282         return egl::EglNotInitialized() << "Could not create the initialization pbuffer.";
283     }
284 
285     if (!mGLX.makeCurrent(mInitPbuffer, mContext))
286     {
287         return egl::EglNotInitialized() << "Could not make the initialization pbuffer current.";
288     }
289 
290     std::unique_ptr<FunctionsGL> functionsGL(new FunctionsGLGLX(mGLX.getProc));
291     functionsGL->initialize(eglAttributes);
292     if (mHasNVRobustnessVideoMemoryPurge)
293     {
294         GLenum status = functionsGL->getGraphicsResetStatus();
295         if (status != GL_NO_ERROR && status != GL_PURGED_CONTEXT_RESET_NV)
296         {
297             return egl::EglNotInitialized() << "Context lost for unknown reason.";
298         }
299     }
300     // TODO(cwallez, angleproject:1303) Disable the OpenGL ES backend on Linux NVIDIA and Intel as
301     // it has problems on our automated testing. An OpenGL ES backend might not trigger this test if
302     // there is no Desktop OpenGL support, but that's not the case in our automated testing.
303     VendorID vendor = GetVendorID(functionsGL.get());
304     bool isOpenGLES =
305         eglAttributes.get(EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE) ==
306         EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE;
307     if (isOpenGLES && (IsIntel(vendor) || IsNvidia(vendor)))
308     {
309         return egl::EglNotInitialized() << "Intel or NVIDIA OpenGL ES drivers are not supported.";
310     }
311 
312     syncXCommands(false);
313 
314     mRenderer.reset(new RendererGL(std::move(functionsGL), eglAttributes, this));
315     const gl::Version &maxVersion = mRenderer->getMaxSupportedESVersion();
316     if (maxVersion < gl::Version(2, 0))
317     {
318         return egl::EglNotInitialized() << "OpenGL ES 2.0 is not supportable.";
319     }
320 
321     return DisplayGL::initialize(display);
322 }
323 
terminate()324 void DisplayGLX::terminate()
325 {
326     DisplayGL::terminate();
327 
328     if (mInitPbuffer)
329     {
330         mGLX.destroyPbuffer(mInitPbuffer);
331         mInitPbuffer = 0;
332     }
333 
334     mCurrentNativeContexts.clear();
335 
336     if (mContext)
337     {
338         mGLX.destroyContext(mContext);
339         mContext = nullptr;
340     }
341 
342     mGLX.terminate();
343 
344     mRenderer.reset();
345 
346     if (mUsesNewXDisplay)
347     {
348         XCloseDisplay(mXDisplay);
349     }
350 }
351 
makeCurrent(egl::Display * display,egl::Surface * drawSurface,egl::Surface * readSurface,gl::Context * context)352 egl::Error DisplayGLX::makeCurrent(egl::Display *display,
353                                    egl::Surface *drawSurface,
354                                    egl::Surface *readSurface,
355                                    gl::Context *context)
356 {
357     glx::Drawable newDrawable =
358         (drawSurface ? GetImplAs<SurfaceGLX>(drawSurface)->getDrawable() : mInitPbuffer);
359     glx::Context newContext = mContext;
360     // If the thread calling makeCurrent does not have the correct context current (either mContext
361     // or 0), we need to set it current.
362     if (!context)
363     {
364         newDrawable = 0;
365         newContext  = 0;
366     }
367     if (newDrawable != mCurrentDrawable ||
368         newContext != mCurrentNativeContexts[angle::GetCurrentThreadUniqueId()])
369     {
370         if (mGLX.makeCurrent(newDrawable, newContext) != True)
371         {
372             return egl::EglContextLost() << "Failed to make the GLX context current";
373         }
374         mCurrentNativeContexts[angle::GetCurrentThreadUniqueId()] = newContext;
375         mCurrentDrawable                                          = newDrawable;
376     }
377 
378     return DisplayGL::makeCurrent(display, drawSurface, readSurface, context);
379 }
380 
createWindowSurface(const egl::SurfaceState & state,EGLNativeWindowType window,const egl::AttributeMap & attribs)381 SurfaceImpl *DisplayGLX::createWindowSurface(const egl::SurfaceState &state,
382                                              EGLNativeWindowType window,
383                                              const egl::AttributeMap &attribs)
384 {
385     ASSERT(configIdToGLXConfig.count(state.config->configID) > 0);
386     glx::FBConfig fbConfig = configIdToGLXConfig[state.config->configID];
387 
388     return new WindowSurfaceGLX(state, mGLX, this, window, mGLX.getDisplay(), fbConfig);
389 }
390 
createPbufferSurface(const egl::SurfaceState & state,const egl::AttributeMap & attribs)391 SurfaceImpl *DisplayGLX::createPbufferSurface(const egl::SurfaceState &state,
392                                               const egl::AttributeMap &attribs)
393 {
394     ASSERT(configIdToGLXConfig.count(state.config->configID) > 0);
395     glx::FBConfig fbConfig = configIdToGLXConfig[state.config->configID];
396 
397     EGLint width  = static_cast<EGLint>(attribs.get(EGL_WIDTH, 0));
398     EGLint height = static_cast<EGLint>(attribs.get(EGL_HEIGHT, 0));
399     bool largest  = (attribs.get(EGL_LARGEST_PBUFFER, EGL_FALSE) == EGL_TRUE);
400 
401     return new PbufferSurfaceGLX(state, width, height, largest, mGLX, fbConfig);
402 }
403 
createPbufferFromClientBuffer(const egl::SurfaceState & state,EGLenum buftype,EGLClientBuffer clientBuffer,const egl::AttributeMap & attribs)404 SurfaceImpl *DisplayGLX::createPbufferFromClientBuffer(const egl::SurfaceState &state,
405                                                        EGLenum buftype,
406                                                        EGLClientBuffer clientBuffer,
407                                                        const egl::AttributeMap &attribs)
408 {
409     UNIMPLEMENTED();
410     return nullptr;
411 }
412 
createPixmapSurface(const egl::SurfaceState & state,NativePixmapType nativePixmap,const egl::AttributeMap & attribs)413 SurfaceImpl *DisplayGLX::createPixmapSurface(const egl::SurfaceState &state,
414                                              NativePixmapType nativePixmap,
415                                              const egl::AttributeMap &attribs)
416 {
417     ASSERT(configIdToGLXConfig.count(state.config->configID) > 0);
418     glx::FBConfig fbConfig = configIdToGLXConfig[state.config->configID];
419     return new PixmapSurfaceGLX(state, nativePixmap, mGLX.getDisplay(), mGLX, fbConfig);
420 }
421 
validatePixmap(const egl::Config * config,EGLNativePixmapType pixmap,const egl::AttributeMap & attributes) const422 egl::Error DisplayGLX::validatePixmap(const egl::Config *config,
423                                       EGLNativePixmapType pixmap,
424                                       const egl::AttributeMap &attributes) const
425 {
426     Window rootWindow;
427     int x                    = 0;
428     int y                    = 0;
429     unsigned int width       = 0;
430     unsigned int height      = 0;
431     unsigned int borderWidth = 0;
432     unsigned int depth       = 0;
433     int status = XGetGeometry(mGLX.getDisplay(), pixmap, &rootWindow, &x, &y, &width, &height,
434                               &borderWidth, &depth);
435     if (!status)
436     {
437         return egl::EglBadNativePixmap() << "Invalid native pixmap, XGetGeometry failed: "
438                                          << x11::XErrorToString(mXDisplay, status);
439     }
440 
441     return egl::NoError();
442 }
443 
createContext(const gl::State & state,gl::ErrorSet * errorSet,const egl::Config * configuration,const gl::Context * shareContext,const egl::AttributeMap & attribs)444 ContextImpl *DisplayGLX::createContext(const gl::State &state,
445                                        gl::ErrorSet *errorSet,
446                                        const egl::Config *configuration,
447                                        const gl::Context *shareContext,
448                                        const egl::AttributeMap &attribs)
449 {
450     RobustnessVideoMemoryPurgeStatus robustnessVideoMemoryPurgeStatus =
451         GetRobustnessVideoMemoryPurge(attribs);
452     return new ContextGL(state, errorSet, mRenderer, robustnessVideoMemoryPurgeStatus);
453 }
454 
initializeContext(glx::FBConfig config,const egl::AttributeMap & eglAttributes,glx::Context * context)455 egl::Error DisplayGLX::initializeContext(glx::FBConfig config,
456                                          const egl::AttributeMap &eglAttributes,
457                                          glx::Context *context)
458 {
459     int profileMask = 0;
460 
461     EGLint requestedDisplayType = static_cast<EGLint>(
462         eglAttributes.get(EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
463     if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE)
464     {
465         if (!mHasEXTCreateContextES2Profile)
466         {
467             return egl::EglNotInitialized() << "Cannot create an OpenGL ES platform on GLX without "
468                                                "the GLX_EXT_create_context_es_profile extension.";
469         }
470 
471         ASSERT(mHasARBCreateContextProfile);
472         profileMask |= GLX_CONTEXT_ES2_PROFILE_BIT_EXT;
473     }
474 
475     // Create a context of the requested version, if any.
476     gl::Version requestedVersion(static_cast<EGLint>(eglAttributes.get(
477                                      EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, EGL_DONT_CARE)),
478                                  static_cast<EGLint>(eglAttributes.get(
479                                      EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, EGL_DONT_CARE)));
480     if (static_cast<EGLint>(requestedVersion.major) != EGL_DONT_CARE &&
481         static_cast<EGLint>(requestedVersion.minor) != EGL_DONT_CARE)
482     {
483         if (!(profileMask & GLX_CONTEXT_ES2_PROFILE_BIT_EXT) &&
484             requestedVersion >= gl::Version(3, 2))
485         {
486             profileMask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
487         }
488         return createContextAttribs(config, requestedVersion, profileMask, context);
489     }
490 
491     // The only way to get a core profile context of the highest version using
492     // glXCreateContextAttrib is to try creationg contexts in decreasing version
493     // numbers. It might look that asking for a core context of version (0, 0)
494     // works on some driver but it create a _compatibility_ context of the highest
495     // version instead. The cost of failing a context creation is small (< 0.1 ms)
496     // on Mesa but is unfortunately a bit expensive on the Nvidia driver (~3ms).
497     // Also try to get any Desktop GL context, but if that fails fallback to
498     // asking for OpenGL ES contexts.
499 
500     // NOTE: below we return as soon as we're able to create a context so the
501     // "error" variable is EGL_SUCCESS when returned contrary to the common idiom
502     // of returning "error" when there is an actual error.
503     for (const auto &info : GenerateContextCreationToTry(requestedDisplayType, mIsMesa))
504     {
505         int profileFlag = 0;
506         if (info.type == ContextCreationTry::Type::DESKTOP_CORE)
507         {
508             profileFlag |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
509         }
510         else if (info.type == ContextCreationTry::Type::ES)
511         {
512             profileFlag |= GLX_CONTEXT_ES2_PROFILE_BIT_EXT;
513         }
514 
515         egl::Error error = createContextAttribs(config, info.version, profileFlag, context);
516         if (!error.isError())
517         {
518             return error;
519         }
520     }
521 
522     return egl::EglNotInitialized() << "Could not create a backing OpenGL context.";
523 }
524 
generateConfigs()525 egl::ConfigSet DisplayGLX::generateConfigs()
526 {
527     egl::ConfigSet configs;
528     configIdToGLXConfig.clear();
529 
530     const gl::Version &maxVersion = getMaxSupportedESVersion();
531     ASSERT(maxVersion >= gl::Version(2, 0));
532     bool supportsES3 = maxVersion >= gl::Version(3, 0);
533 
534     int contextRedSize   = getGLXFBConfigAttrib(mContextConfig, GLX_RED_SIZE);
535     int contextGreenSize = getGLXFBConfigAttrib(mContextConfig, GLX_GREEN_SIZE);
536     int contextBlueSize  = getGLXFBConfigAttrib(mContextConfig, GLX_BLUE_SIZE);
537     int contextAlphaSize = getGLXFBConfigAttrib(mContextConfig, GLX_ALPHA_SIZE);
538 
539     int contextDepthSize   = getGLXFBConfigAttrib(mContextConfig, GLX_DEPTH_SIZE);
540     int contextStencilSize = getGLXFBConfigAttrib(mContextConfig, GLX_STENCIL_SIZE);
541 
542     int contextSamples = mHasMultisample ? getGLXFBConfigAttrib(mContextConfig, GLX_SAMPLES) : 0;
543     int contextSampleBuffers =
544         mHasMultisample ? getGLXFBConfigAttrib(mContextConfig, GLX_SAMPLE_BUFFERS) : 0;
545 
546     int contextAccumRedSize   = getGLXFBConfigAttrib(mContextConfig, GLX_ACCUM_RED_SIZE);
547     int contextAccumGreenSize = getGLXFBConfigAttrib(mContextConfig, GLX_ACCUM_GREEN_SIZE);
548     int contextAccumBlueSize  = getGLXFBConfigAttrib(mContextConfig, GLX_ACCUM_BLUE_SIZE);
549     int contextAccumAlphaSize = getGLXFBConfigAttrib(mContextConfig, GLX_ACCUM_ALPHA_SIZE);
550 
551     int attribList[] = {
552         GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_RENDERABLE, True, GLX_DOUBLEBUFFER, True, None,
553     };
554 
555     int glxConfigCount;
556     glx::FBConfig *glxConfigs = mGLX.chooseFBConfig(attribList, &glxConfigCount);
557 
558     for (int i = 0; i < glxConfigCount; i++)
559     {
560         glx::FBConfig glxConfig = glxConfigs[i];
561         egl::Config config;
562 
563         // Native stuff
564         config.nativeVisualID   = getGLXFBConfigAttrib(glxConfig, GLX_VISUAL_ID);
565         config.nativeVisualType = getGLXFBConfigAttrib(glxConfig, GLX_X_VISUAL_TYPE);
566         config.nativeRenderable = EGL_TRUE;
567 
568         // When a visual ID has been specified with EGL_ANGLE_x11_visual we should
569         // only return configs with this visual: it will maximize performance by avoid
570         // blits in the driver when showing the window on the screen.
571         if (mRequestedVisual != -1 && config.nativeVisualID != mRequestedVisual)
572         {
573             continue;
574         }
575 
576         // Buffer sizes
577         config.redSize     = getGLXFBConfigAttrib(glxConfig, GLX_RED_SIZE);
578         config.greenSize   = getGLXFBConfigAttrib(glxConfig, GLX_GREEN_SIZE);
579         config.blueSize    = getGLXFBConfigAttrib(glxConfig, GLX_BLUE_SIZE);
580         config.alphaSize   = getGLXFBConfigAttrib(glxConfig, GLX_ALPHA_SIZE);
581         config.depthSize   = getGLXFBConfigAttrib(glxConfig, GLX_DEPTH_SIZE);
582         config.stencilSize = getGLXFBConfigAttrib(glxConfig, GLX_STENCIL_SIZE);
583 
584         // We require RGBA8 and the D24S8 (or no DS buffer)
585         if (config.redSize != contextRedSize || config.greenSize != contextGreenSize ||
586             config.blueSize != contextBlueSize || config.alphaSize != contextAlphaSize)
587         {
588             continue;
589         }
590         // The GLX spec says that it is ok for a whole buffer to not be present
591         // however the Mesa Intel driver (and probably on other Mesa drivers)
592         // fails to make current when the Depth stencil doesn't exactly match the
593         // configuration.
594         bool hasSameDepthStencil =
595             config.depthSize == contextDepthSize && config.stencilSize == contextStencilSize;
596         bool hasNoDepthStencil = config.depthSize == 0 && config.stencilSize == 0;
597         if (!hasSameDepthStencil && (mIsMesa || !hasNoDepthStencil))
598         {
599             continue;
600         }
601 
602         config.colorBufferType = EGL_RGB_BUFFER;
603         config.luminanceSize   = 0;
604         config.alphaMaskSize   = 0;
605 
606         config.bufferSize = config.redSize + config.greenSize + config.blueSize + config.alphaSize;
607 
608         // Multisample and accumulation buffers
609         int samples = mHasMultisample ? getGLXFBConfigAttrib(glxConfig, GLX_SAMPLES) : 0;
610         int sampleBuffers =
611             mHasMultisample ? getGLXFBConfigAttrib(glxConfig, GLX_SAMPLE_BUFFERS) : 0;
612 
613         int accumRedSize   = getGLXFBConfigAttrib(glxConfig, GLX_ACCUM_RED_SIZE);
614         int accumGreenSize = getGLXFBConfigAttrib(glxConfig, GLX_ACCUM_GREEN_SIZE);
615         int accumBlueSize  = getGLXFBConfigAttrib(glxConfig, GLX_ACCUM_BLUE_SIZE);
616         int accumAlphaSize = getGLXFBConfigAttrib(glxConfig, GLX_ACCUM_ALPHA_SIZE);
617 
618         if (samples != contextSamples || sampleBuffers != contextSampleBuffers ||
619             accumRedSize != contextAccumRedSize || accumGreenSize != contextAccumGreenSize ||
620             accumBlueSize != contextAccumBlueSize || accumAlphaSize != contextAccumAlphaSize)
621         {
622             continue;
623         }
624 
625         config.samples       = samples;
626         config.sampleBuffers = sampleBuffers;
627 
628         // Transparency
629         if (getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_TYPE) == GLX_TRANSPARENT_RGB)
630         {
631             config.transparentType     = EGL_TRANSPARENT_RGB;
632             config.transparentRedValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_RED_VALUE);
633             config.transparentGreenValue =
634                 getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_GREEN_VALUE);
635             config.transparentBlueValue =
636                 getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_BLUE_VALUE);
637         }
638         else
639         {
640             config.transparentType = EGL_NONE;
641         }
642 
643         // Pbuffer
644         config.maxPBufferWidth  = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_WIDTH);
645         config.maxPBufferHeight = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_HEIGHT);
646         config.maxPBufferPixels = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_PIXELS);
647 
648         // Caveat
649         config.configCaveat = EGL_NONE;
650 
651         int caveat = getGLXFBConfigAttrib(glxConfig, GLX_CONFIG_CAVEAT);
652         if (caveat == GLX_SLOW_CONFIG)
653         {
654             config.configCaveat = EGL_SLOW_CONFIG;
655         }
656         else if (caveat == GLX_NON_CONFORMANT_CONFIG)
657         {
658             continue;
659         }
660 
661         // Misc
662         config.level = getGLXFBConfigAttrib(glxConfig, GLX_LEVEL);
663 
664         config.minSwapInterval = mMinSwapInterval;
665         config.maxSwapInterval = mMaxSwapInterval;
666 
667         // TODO(cwallez) wildly guessing these formats, another TODO says they should be removed
668         // anyway
669         config.renderTargetFormat = GL_RGBA8;
670         config.depthStencilFormat = GL_DEPTH24_STENCIL8;
671 
672         config.conformant     = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
673         config.renderableType = config.conformant;
674 
675         // TODO(cwallez) I have no idea what this is
676         config.matchNativePixmap = EGL_NONE;
677 
678         config.colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
679 
680         // GLX doesn't support binding pbuffers to textures and there is no way to differentiate in
681         // EGL that pixmaps can be bound but pbuffers cannot.  If both pixmaps and pbuffers are
682         // supported, generate extra configs with either pbuffer or pixmap support.
683         int glxDrawable     = getGLXFBConfigAttrib(glxConfig, GLX_DRAWABLE_TYPE);
684         bool pbufferSupport = (glxDrawable & EGL_PBUFFER_BIT) != 0;
685         bool pixmapSupport  = (glxDrawable & GLX_PIXMAP_BIT) != 0;
686         bool pixmapBindToTextureSupport =
687             pixmapSupport && mGLX.hasExtension("GLX_EXT_texture_from_pixmap");
688 
689         if (pbufferSupport && pixmapBindToTextureSupport)
690         {
691             // Generate the pixmap-only config
692             config.surfaceType = (glxDrawable & GLX_WINDOW_BIT ? EGL_WINDOW_BIT : 0) |
693                                  (pixmapSupport ? EGL_PIXMAP_BIT : 0);
694 
695             config.bindToTextureRGB = getGLXFBConfigAttrib(glxConfig, GLX_BIND_TO_TEXTURE_RGB_EXT);
696             config.bindToTextureRGBA =
697                 getGLXFBConfigAttrib(glxConfig, GLX_BIND_TO_TEXTURE_RGBA_EXT);
698             config.yInverted = getGLXFBConfigAttrib(glxConfig, GLX_Y_INVERTED_EXT);
699 
700             int id                  = configs.add(config);
701             configIdToGLXConfig[id] = glxConfig;
702         }
703 
704         // Generate the pbuffer config. It can support pixmaps but not bind-to-texture.
705         config.surfaceType = (glxDrawable & GLX_WINDOW_BIT ? EGL_WINDOW_BIT : 0) |
706                              (pbufferSupport ? EGL_PBUFFER_BIT : 0) |
707                              (pixmapSupport ? EGL_PIXMAP_BIT : 0);
708 
709         config.bindToTextureRGB  = false;
710         config.bindToTextureRGBA = false;
711         config.yInverted         = false;
712 
713         int id                  = configs.add(config);
714         configIdToGLXConfig[id] = glxConfig;
715     }
716 
717     XFree(glxConfigs);
718 
719     return configs;
720 }
721 
testDeviceLost()722 bool DisplayGLX::testDeviceLost()
723 {
724     return false;
725 }
726 
restoreLostDevice(const egl::Display * display)727 egl::Error DisplayGLX::restoreLostDevice(const egl::Display *display)
728 {
729     return egl::EglBadDisplay();
730 }
731 
isValidNativeWindow(EGLNativeWindowType window) const732 bool DisplayGLX::isValidNativeWindow(EGLNativeWindowType window) const
733 {
734 
735     // Check the validity of the window by calling a getter function on the window that
736     // returns a status code. If the window is bad the call return a status of zero. We
737     // need to set a temporary X11 error handler while doing this because the default
738     // X11 error handler exits the program on any error.
739     auto oldErrorHandler = XSetErrorHandler(IgnoreX11Errors);
740     XWindowAttributes attributes;
741     int status = XGetWindowAttributes(mXDisplay, window, &attributes);
742     XSetErrorHandler(oldErrorHandler);
743 
744     return status != 0;
745 }
746 
waitClient(const gl::Context * context)747 egl::Error DisplayGLX::waitClient(const gl::Context *context)
748 {
749     mGLX.waitGL();
750     return egl::NoError();
751 }
752 
waitNative(const gl::Context * context,EGLint engine)753 egl::Error DisplayGLX::waitNative(const gl::Context *context, EGLint engine)
754 {
755     // eglWaitNative is used to notify the driver of changes in X11 for the current surface, such as
756     // changes of the window size. We use this event to update the child window of WindowSurfaceGLX
757     // to match its parent window's size.
758     // Handling eglWaitNative this way helps the application control when resize happens. This is
759     // important because drivers have a tendency to clobber the back buffer when the windows are
760     // resized. See http://crbug.com/326995
761     egl::Surface *drawSurface = context->getCurrentDrawSurface();
762     egl::Surface *readSurface = context->getCurrentReadSurface();
763     if (drawSurface != nullptr)
764     {
765         SurfaceGLX *glxDrawSurface = GetImplAs<SurfaceGLX>(drawSurface);
766         ANGLE_TRY(glxDrawSurface->checkForResize());
767     }
768 
769     if (readSurface != drawSurface && readSurface != nullptr)
770     {
771         SurfaceGLX *glxReadSurface = GetImplAs<SurfaceGLX>(readSurface);
772         ANGLE_TRY(glxReadSurface->checkForResize());
773     }
774 
775     // We still need to forward the resizing of the child window to the driver.
776     mGLX.waitX();
777     return egl::NoError();
778 }
779 
getMaxSupportedESVersion() const780 gl::Version DisplayGLX::getMaxSupportedESVersion() const
781 {
782     return mRenderer->getMaxSupportedESVersion();
783 }
784 
syncXCommands(bool alwaysSync) const785 void DisplayGLX::syncXCommands(bool alwaysSync) const
786 {
787     if (mUsesNewXDisplay || alwaysSync)
788     {
789         XSync(mGLX.getDisplay(), False);
790     }
791 }
792 
setSwapInterval(glx::Drawable drawable,SwapControlData * data)793 void DisplayGLX::setSwapInterval(glx::Drawable drawable, SwapControlData *data)
794 {
795     ASSERT(data != nullptr);
796 
797     // TODO(cwallez) error checking?
798     if (mSwapControl == SwapControl::EXT)
799     {
800         // Prefer the EXT extension, it gives per-drawable swap intervals, which will
801         // minimize the number of driver calls.
802         if (data->maxSwapInterval < 0)
803         {
804             unsigned int maxSwapInterval = 0;
805             mGLX.queryDrawable(drawable, GLX_MAX_SWAP_INTERVAL_EXT, &maxSwapInterval);
806             data->maxSwapInterval = static_cast<int>(maxSwapInterval);
807         }
808 
809         // When the egl configs were generated we had to guess what the max swap interval
810         // was because we didn't have a window to query it one (and that this max could
811         // depend on the monitor). This means that the target interval might be higher
812         // than the max interval and needs to be clamped.
813         const int realInterval = std::min(data->targetSwapInterval, data->maxSwapInterval);
814         if (data->currentSwapInterval != realInterval)
815         {
816             mGLX.swapIntervalEXT(drawable, realInterval);
817             data->currentSwapInterval = realInterval;
818         }
819     }
820     else if (mCurrentSwapInterval != data->targetSwapInterval)
821     {
822         // With the Mesa or SGI extensions we can still do per-drawable swap control
823         // manually but it is more expensive in number of driver calls.
824         if (mSwapControl == SwapControl::Mesa)
825         {
826             mGLX.swapIntervalMESA(data->targetSwapInterval);
827         }
828         else if (mSwapControl == SwapControl::SGI)
829         {
830             mGLX.swapIntervalSGI(data->targetSwapInterval);
831         }
832         mCurrentSwapInterval = data->targetSwapInterval;
833     }
834 }
835 
isWindowVisualIdSpecified() const836 bool DisplayGLX::isWindowVisualIdSpecified() const
837 {
838     return mRequestedVisual != -1;
839 }
840 
isMatchingWindowVisualId(unsigned long visualId) const841 bool DisplayGLX::isMatchingWindowVisualId(unsigned long visualId) const
842 {
843     return isWindowVisualIdSpecified() && static_cast<unsigned long>(mRequestedVisual) == visualId;
844 }
845 
generateExtensions(egl::DisplayExtensions * outExtensions) const846 void DisplayGLX::generateExtensions(egl::DisplayExtensions *outExtensions) const
847 {
848     outExtensions->createContextRobustness = mHasARBCreateContextRobustness;
849 
850     // Contexts are virtualized so textures ans semaphores can be shared globally
851     outExtensions->displayTextureShareGroup   = true;
852     outExtensions->displaySemaphoreShareGroup = true;
853 
854     outExtensions->surfacelessContext = true;
855 
856     if (!mRenderer->getFeatures().disableSyncControlSupport.enabled)
857     {
858         const bool hasSyncControlOML        = mGLX.hasExtension("GLX_OML_sync_control");
859         outExtensions->syncControlCHROMIUM  = hasSyncControlOML;
860         outExtensions->syncControlRateANGLE = hasSyncControlOML;
861     }
862 
863     outExtensions->textureFromPixmapNOK = mGLX.hasExtension("GLX_EXT_texture_from_pixmap");
864 
865     outExtensions->robustnessVideoMemoryPurgeNV = mHasNVRobustnessVideoMemoryPurge;
866 
867     DisplayGL::generateExtensions(outExtensions);
868 }
869 
generateCaps(egl::Caps * outCaps) const870 void DisplayGLX::generateCaps(egl::Caps *outCaps) const
871 {
872     outCaps->textureNPOT = true;
873 }
874 
makeCurrentSurfaceless(gl::Context * context)875 egl::Error DisplayGLX::makeCurrentSurfaceless(gl::Context *context)
876 {
877     // Nothing to do because GLX always uses the same context and the previous surface can be left
878     // current.
879     return egl::NoError();
880 }
881 
getGLXFBConfigAttrib(glx::FBConfig config,int attrib) const882 int DisplayGLX::getGLXFBConfigAttrib(glx::FBConfig config, int attrib) const
883 {
884     int result;
885     mGLX.getFBConfigAttrib(config, attrib, &result);
886     return result;
887 }
888 
createContextAttribs(glx::FBConfig,const Optional<gl::Version> & version,int profileMask,glx::Context * context) const889 egl::Error DisplayGLX::createContextAttribs(glx::FBConfig,
890                                             const Optional<gl::Version> &version,
891                                             int profileMask,
892                                             glx::Context *context) const
893 {
894     std::vector<int> attribs;
895 
896     if (mHasARBCreateContextRobustness)
897     {
898         attribs.push_back(GLX_CONTEXT_FLAGS_ARB);
899         attribs.push_back(GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB);
900         attribs.push_back(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
901         attribs.push_back(GLX_LOSE_CONTEXT_ON_RESET_ARB);
902         if (mHasNVRobustnessVideoMemoryPurge)
903         {
904             attribs.push_back(GLX_GENERATE_RESET_ON_VIDEO_MEMORY_PURGE_NV);
905             attribs.push_back(GL_TRUE);
906         }
907     }
908 
909     if (version.valid())
910     {
911         attribs.push_back(GLX_CONTEXT_MAJOR_VERSION_ARB);
912         attribs.push_back(version.value().major);
913 
914         attribs.push_back(GLX_CONTEXT_MINOR_VERSION_ARB);
915         attribs.push_back(version.value().minor);
916     }
917 
918     if (profileMask != 0 && mHasARBCreateContextProfile)
919     {
920         attribs.push_back(GLX_CONTEXT_PROFILE_MASK_ARB);
921         attribs.push_back(profileMask);
922     }
923 
924     attribs.push_back(None);
925 
926     // When creating a context with glXCreateContextAttribsARB, a variety of X11 errors can
927     // be generated. To prevent these errors from crashing our process, we simply ignore
928     // them and only look if GLXContext was created.
929     // Process all events before setting the error handler to avoid desynchronizing XCB instances
930     // (the error handler is NOT per-display).
931     XSync(mXDisplay, False);
932     auto oldErrorHandler = XSetErrorHandler(IgnoreX11Errors);
933     *context = mGLX.createContextAttribsARB(mContextConfig, nullptr, True, attribs.data());
934     XSetErrorHandler(oldErrorHandler);
935 
936     if (!*context)
937     {
938         return egl::EglNotInitialized() << "Could not create GL context.";
939     }
940 
941     return egl::NoError();
942 }
943 
initializeFrontendFeatures(angle::FrontendFeatures * features) const944 void DisplayGLX::initializeFrontendFeatures(angle::FrontendFeatures *features) const
945 {
946     mRenderer->initializeFrontendFeatures(features);
947 }
948 
populateFeatureList(angle::FeatureList * features)949 void DisplayGLX::populateFeatureList(angle::FeatureList *features)
950 {
951     mRenderer->getFeatures().populateFeatureList(features);
952 }
953 
getRenderer() const954 RendererGL *DisplayGLX::getRenderer() const
955 {
956     return mRenderer.get();
957 }
958 
getWindowSystem() const959 angle::NativeWindowSystem DisplayGLX::getWindowSystem() const
960 {
961     return angle::NativeWindowSystem::X11;
962 }
963 
CreateGLXDisplay(const egl::DisplayState & state)964 DisplayImpl *CreateGLXDisplay(const egl::DisplayState &state)
965 {
966     return new DisplayGLX(state);
967 }
968 
969 }  // namespace rx
970