• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // DisplayWGL.h: WGL implementation of egl::Display
8 
9 #include "libANGLE/renderer/gl/wgl/DisplayWGL.h"
10 
11 #include "common/debug.h"
12 #include "libANGLE/Config.h"
13 #include "libANGLE/Context.h"
14 #include "libANGLE/Display.h"
15 #include "libANGLE/Surface.h"
16 #include "libANGLE/renderer/gl/ContextGL.h"
17 #include "libANGLE/renderer/gl/RendererGL.h"
18 #include "libANGLE/renderer/gl/renderergl_utils.h"
19 #include "libANGLE/renderer/gl/wgl/ContextWGL.h"
20 #include "libANGLE/renderer/gl/wgl/D3DTextureSurfaceWGL.h"
21 #include "libANGLE/renderer/gl/wgl/DXGISwapChainWindowSurfaceWGL.h"
22 #include "libANGLE/renderer/gl/wgl/FunctionsWGL.h"
23 #include "libANGLE/renderer/gl/wgl/PbufferSurfaceWGL.h"
24 #include "libANGLE/renderer/gl/wgl/RendererWGL.h"
25 #include "libANGLE/renderer/gl/wgl/WindowSurfaceWGL.h"
26 #include "libANGLE/renderer/gl/wgl/wgl_utils.h"
27 #include "platform/PlatformMethods.h"
28 
29 #include <EGL/eglext.h>
30 #include <sstream>
31 #include <string>
32 
33 namespace rx
34 {
35 
36 namespace
37 {
38 
GetErrorMessage()39 std::string GetErrorMessage()
40 {
41     DWORD errorCode     = GetLastError();
42     LPSTR messageBuffer = nullptr;
43     size_t size         = FormatMessageA(
44         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
45         NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
46     std::string message(messageBuffer, size);
47     if (size == 0)
48     {
49         std::ostringstream stream;
50         stream << "Failed to get the error message for '" << errorCode << "' due to the error '"
51                << GetLastError() << "'";
52         message = stream.str();
53     }
54     if (messageBuffer != nullptr)
55     {
56         LocalFree(messageBuffer);
57     }
58     return message;
59 }
60 
61 }  // anonymous namespace
62 
63 class FunctionsGLWindows : public FunctionsGL
64 {
65   public:
FunctionsGLWindows(HMODULE openGLModule,PFNWGLGETPROCADDRESSPROC getProcAddressWGL)66     FunctionsGLWindows(HMODULE openGLModule, PFNWGLGETPROCADDRESSPROC getProcAddressWGL)
67         : mOpenGLModule(openGLModule), mGetProcAddressWGL(getProcAddressWGL)
68     {
69         ASSERT(mOpenGLModule);
70         ASSERT(mGetProcAddressWGL);
71     }
72 
~FunctionsGLWindows()73     ~FunctionsGLWindows() override {}
74 
75   private:
loadProcAddress(const std::string & function) const76     void *loadProcAddress(const std::string &function) const override
77     {
78         void *proc = reinterpret_cast<void *>(mGetProcAddressWGL(function.c_str()));
79         if (!proc)
80         {
81             proc = reinterpret_cast<void *>(GetProcAddress(mOpenGLModule, function.c_str()));
82         }
83         return proc;
84     }
85 
86     HMODULE mOpenGLModule;
87     PFNWGLGETPROCADDRESSPROC mGetProcAddressWGL;
88 };
89 
DisplayWGL(const egl::DisplayState & state)90 DisplayWGL::DisplayWGL(const egl::DisplayState &state)
91     : DisplayGL(state),
92       mRenderer(nullptr),
93       mCurrentNativeContexts(),
94       mOpenGLModule(nullptr),
95       mFunctionsWGL(nullptr),
96       mHasWGLCreateContextRobustness(false),
97       mHasRobustness(false),
98       mWindowClass(0),
99       mWindow(nullptr),
100       mDeviceContext(nullptr),
101       mPixelFormat(0),
102       mUseDXGISwapChains(false),
103       mHasDXInterop(false),
104       mDxgiModule(nullptr),
105       mD3d11Module(nullptr),
106       mD3D11DeviceHandle(nullptr),
107       mD3D11Device(nullptr),
108       mUseARBShare(true)
109 {}
110 
~DisplayWGL()111 DisplayWGL::~DisplayWGL() {}
112 
initialize(egl::Display * display)113 egl::Error DisplayWGL::initialize(egl::Display *display)
114 {
115     egl::Error error = initializeImpl(display);
116     if (error.isError())
117     {
118         destroy();
119         return error;
120     }
121 
122     return DisplayGL::initialize(display);
123 }
124 
initializeImpl(egl::Display * display)125 egl::Error DisplayWGL::initializeImpl(egl::Display *display)
126 {
127     mDisplayAttributes = display->getAttributeMap();
128 
129     mOpenGLModule = LoadLibraryExA("opengl32.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
130     if (!mOpenGLModule)
131     {
132         return egl::EglNotInitialized() << "Failed to load OpenGL library.";
133     }
134 
135     mFunctionsWGL = new FunctionsWGL();
136     mFunctionsWGL->initialize(mOpenGLModule, nullptr);
137 
138     // WGL can't grab extensions until it creates a context because it needs to load the driver's
139     // DLLs first. Create a stub context to load the driver and determine which GL versions are
140     // available.
141 
142     // Work around compile error from not defining "UNICODE" while Chromium does
143     const LPSTR idcArrow = MAKEINTRESOURCEA(32512);
144 
145     std::ostringstream stream;
146     stream << "ANGLE DisplayWGL " << gl::FmtHex(display) << " Intermediate Window Class";
147     std::string className = stream.str();
148 
149     WNDCLASSA intermediateClassDesc     = {};
150     intermediateClassDesc.style         = CS_OWNDC;
151     intermediateClassDesc.lpfnWndProc   = DefWindowProcA;
152     intermediateClassDesc.cbClsExtra    = 0;
153     intermediateClassDesc.cbWndExtra    = 0;
154     intermediateClassDesc.hInstance     = GetModuleHandle(nullptr);
155     intermediateClassDesc.hIcon         = nullptr;
156     intermediateClassDesc.hCursor       = LoadCursorA(nullptr, idcArrow);
157     intermediateClassDesc.hbrBackground = 0;
158     intermediateClassDesc.lpszMenuName  = nullptr;
159     intermediateClassDesc.lpszClassName = className.c_str();
160     mWindowClass                        = RegisterClassA(&intermediateClassDesc);
161     if (!mWindowClass)
162     {
163         return egl::EglNotInitialized()
164                << "Failed to register intermediate OpenGL window class \"" << className.c_str()
165                << "\":" << gl::FmtErr(HRESULT_CODE(GetLastError()));
166     }
167 
168     HWND placeholderWindow =
169         CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass), "ANGLE Placeholder Window",
170                         WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
171                         CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr);
172     if (!placeholderWindow)
173     {
174         return egl::EglNotInitialized() << "Failed to create placeholder OpenGL window.";
175     }
176 
177     HDC placeholderDeviceContext = GetDC(placeholderWindow);
178     if (!placeholderDeviceContext)
179     {
180         return egl::EglNotInitialized()
181                << "Failed to get the device context of the placeholder OpenGL window.";
182     }
183 
184     const PIXELFORMATDESCRIPTOR pixelFormatDescriptor = wgl::GetDefaultPixelFormatDescriptor();
185 
186     int placeholderPixelFormat =
187         ChoosePixelFormat(placeholderDeviceContext, &pixelFormatDescriptor);
188     if (placeholderPixelFormat == 0)
189     {
190         return egl::EglNotInitialized()
191                << "Could not find a compatible pixel format for the placeholder OpenGL window.";
192     }
193 
194     if (!SetPixelFormat(placeholderDeviceContext, placeholderPixelFormat, &pixelFormatDescriptor))
195     {
196         return egl::EglNotInitialized()
197                << "Failed to set the pixel format on the intermediate OpenGL window.";
198     }
199 
200     HGLRC placeholderWGLContext = mFunctionsWGL->createContext(placeholderDeviceContext);
201     if (!placeholderDeviceContext)
202     {
203         return egl::EglNotInitialized()
204                << "Failed to create a WGL context for the placeholder OpenGL window.";
205     }
206 
207     if (!mFunctionsWGL->makeCurrent(placeholderDeviceContext, placeholderWGLContext))
208     {
209         return egl::EglNotInitialized() << "Failed to make the placeholder WGL context current.";
210     }
211 
212     // Reinitialize the wgl functions to grab the extensions
213     mFunctionsWGL->initialize(mOpenGLModule, placeholderDeviceContext);
214 
215     mHasWGLCreateContextRobustness =
216         mFunctionsWGL->hasExtension("WGL_ARB_create_context_robustness");
217 
218     // Destroy the placeholder window and context
219     mFunctionsWGL->makeCurrent(placeholderDeviceContext, nullptr);
220     mFunctionsWGL->deleteContext(placeholderWGLContext);
221     ReleaseDC(placeholderWindow, placeholderDeviceContext);
222     DestroyWindow(placeholderWindow);
223 
224     const egl::AttributeMap &displayAttributes = display->getAttributeMap();
225     EGLint requestedDisplayType                = static_cast<EGLint>(displayAttributes.get(
226         EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
227     if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE &&
228         !mFunctionsWGL->hasExtension("WGL_EXT_create_context_es2_profile") &&
229         !mFunctionsWGL->hasExtension("WGL_EXT_create_context_es_profile"))
230     {
231         return egl::EglNotInitialized() << "Cannot create an OpenGL ES platform on Windows without "
232                                            "the WGL_EXT_create_context_es(2)_profile extension.";
233     }
234 
235     // Create the real intermediate context and windows
236     mWindow = CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass),
237                               "ANGLE Intermediate Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
238                               CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr,
239                               nullptr, nullptr);
240     if (!mWindow)
241     {
242         return egl::EglNotInitialized() << "Failed to create intermediate OpenGL window.";
243     }
244 
245     mDeviceContext = GetDC(mWindow);
246     if (!mDeviceContext)
247     {
248         return egl::EglNotInitialized()
249                << "Failed to get the device context of the intermediate OpenGL window.";
250     }
251 
252     if (mFunctionsWGL->choosePixelFormatARB)
253     {
254         std::vector<int> attribs = wgl::GetDefaultPixelFormatAttributes(false);
255 
256         UINT matchingFormats = 0;
257         mFunctionsWGL->choosePixelFormatARB(mDeviceContext, &attribs[0], nullptr, 1u, &mPixelFormat,
258                                             &matchingFormats);
259     }
260 
261     if (mPixelFormat == 0)
262     {
263         mPixelFormat = ChoosePixelFormat(mDeviceContext, &pixelFormatDescriptor);
264     }
265 
266     if (mPixelFormat == 0)
267     {
268         return egl::EglNotInitialized()
269                << "Could not find a compatible pixel format for the intermediate OpenGL window.";
270     }
271 
272     if (!SetPixelFormat(mDeviceContext, mPixelFormat, &pixelFormatDescriptor))
273     {
274         return egl::EglNotInitialized()
275                << "Failed to set the pixel format on the intermediate OpenGL window.";
276     }
277 
278     ANGLE_TRY(createRenderer(&mRenderer));
279     const FunctionsGL *functionsGL = mRenderer->getFunctions();
280 
281     mHasRobustness = functionsGL->getGraphicsResetStatus != nullptr;
282     if (mHasWGLCreateContextRobustness != mHasRobustness)
283     {
284         WARN() << "WGL_ARB_create_context_robustness exists but unable to create a context with "
285                   "robustness.";
286     }
287 
288     // Intel OpenGL ES drivers are not currently supported due to bugs in the driver and ANGLE
289     VendorID vendor = GetVendorID(functionsGL);
290     if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE && IsIntel(vendor))
291     {
292         return egl::EglNotInitialized() << "Intel OpenGL ES drivers are not supported.";
293     }
294 
295     // Create DXGI swap chains for windows that come from other processes.  Windows is unable to
296     // SetPixelFormat on windows from other processes when a sandbox is enabled.
297     HDC nativeDisplay = display->getNativeDisplayId();
298     HWND nativeWindow = WindowFromDC(nativeDisplay);
299     if (nativeWindow != nullptr)
300     {
301         DWORD currentProcessId = GetCurrentProcessId();
302         DWORD windowProcessId;
303         GetWindowThreadProcessId(nativeWindow, &windowProcessId);
304 
305         // AMD drivers advertise the WGL_NV_DX_interop and WGL_NV_DX_interop2 extensions but fail
306         mUseDXGISwapChains = !IsAMD(vendor) && (currentProcessId != windowProcessId);
307     }
308     else
309     {
310         mUseDXGISwapChains = false;
311     }
312 
313     mHasDXInterop = mFunctionsWGL->hasExtension("WGL_NV_DX_interop2");
314 
315     if (mUseDXGISwapChains)
316     {
317         if (mHasDXInterop)
318         {
319             ANGLE_TRY(initializeD3DDevice());
320         }
321         else
322         {
323             // Want to use DXGI swap chains but WGL_NV_DX_interop2 is not present, fail
324             // initialization
325             return egl::EglNotInitialized() << "WGL_NV_DX_interop2 is required but not present.";
326         }
327     }
328 
329     const gl::Version &maxVersion = mRenderer->getMaxSupportedESVersion();
330     if (maxVersion < gl::Version(2, 0))
331     {
332         return egl::EglNotInitialized() << "OpenGL ES 2.0 is not supportable.";
333     }
334 
335     return egl::NoError();
336 }
337 
terminate()338 void DisplayWGL::terminate()
339 {
340     DisplayGL::terminate();
341     destroy();
342 }
343 
destroy()344 void DisplayWGL::destroy()
345 {
346     releaseD3DDevice(mD3D11DeviceHandle);
347 
348     mRenderer.reset();
349 
350     if (mFunctionsWGL)
351     {
352         if (mDeviceContext)
353         {
354             mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
355         }
356     }
357     mCurrentNativeContexts.clear();
358 
359     SafeDelete(mFunctionsWGL);
360 
361     if (mDeviceContext)
362     {
363         ReleaseDC(mWindow, mDeviceContext);
364         mDeviceContext = nullptr;
365     }
366 
367     if (mWindow)
368     {
369         DestroyWindow(mWindow);
370         mWindow = nullptr;
371     }
372 
373     if (mWindowClass)
374     {
375         if (!UnregisterClassA(reinterpret_cast<const char *>(mWindowClass),
376                               GetModuleHandle(nullptr)))
377         {
378             WARN() << "Failed to unregister OpenGL window class: " << gl::FmtHex(mWindowClass);
379         }
380         mWindowClass = NULL;
381     }
382 
383     if (mOpenGLModule)
384     {
385         FreeLibrary(mOpenGLModule);
386         mOpenGLModule = nullptr;
387     }
388 
389     SafeRelease(mD3D11Device);
390 
391     if (mDxgiModule)
392     {
393         FreeLibrary(mDxgiModule);
394         mDxgiModule = nullptr;
395     }
396 
397     if (mD3d11Module)
398     {
399         FreeLibrary(mD3d11Module);
400         mD3d11Module = nullptr;
401     }
402 
403     ASSERT(mRegisteredD3DDevices.empty());
404 }
405 
createWindowSurface(const egl::SurfaceState & state,EGLNativeWindowType window,const egl::AttributeMap & attribs)406 SurfaceImpl *DisplayWGL::createWindowSurface(const egl::SurfaceState &state,
407                                              EGLNativeWindowType window,
408                                              const egl::AttributeMap &attribs)
409 {
410     EGLint orientation = static_cast<EGLint>(attribs.get(EGL_SURFACE_ORIENTATION_ANGLE, 0));
411     if (mUseDXGISwapChains)
412     {
413         egl::Error error = initializeD3DDevice();
414         if (error.isError())
415         {
416             return nullptr;
417         }
418 
419         return new DXGISwapChainWindowSurfaceWGL(
420             state, mRenderer->getStateManager(), window, mD3D11Device, mD3D11DeviceHandle,
421             mDeviceContext, mRenderer->getFunctions(), mFunctionsWGL, orientation);
422     }
423     else
424     {
425         return new WindowSurfaceWGL(state, window, mPixelFormat, mFunctionsWGL, orientation);
426     }
427 }
428 
createPbufferSurface(const egl::SurfaceState & state,const egl::AttributeMap & attribs)429 SurfaceImpl *DisplayWGL::createPbufferSurface(const egl::SurfaceState &state,
430                                               const egl::AttributeMap &attribs)
431 {
432     EGLint width          = static_cast<EGLint>(attribs.get(EGL_WIDTH, 0));
433     EGLint height         = static_cast<EGLint>(attribs.get(EGL_HEIGHT, 0));
434     bool largest          = (attribs.get(EGL_LARGEST_PBUFFER, EGL_FALSE) == EGL_TRUE);
435     EGLenum textureFormat = static_cast<EGLenum>(attribs.get(EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE));
436     EGLenum textureTarget = static_cast<EGLenum>(attribs.get(EGL_TEXTURE_TARGET, EGL_NO_TEXTURE));
437 
438     return new PbufferSurfaceWGL(state, width, height, textureFormat, textureTarget, largest,
439                                  mPixelFormat, mDeviceContext, mFunctionsWGL);
440 }
441 
createPbufferFromClientBuffer(const egl::SurfaceState & state,EGLenum buftype,EGLClientBuffer clientBuffer,const egl::AttributeMap & attribs)442 SurfaceImpl *DisplayWGL::createPbufferFromClientBuffer(const egl::SurfaceState &state,
443                                                        EGLenum buftype,
444                                                        EGLClientBuffer clientBuffer,
445                                                        const egl::AttributeMap &attribs)
446 {
447     egl::Error error = initializeD3DDevice();
448     if (error.isError())
449     {
450         return nullptr;
451     }
452 
453     return new D3DTextureSurfaceWGL(state, mRenderer->getStateManager(), buftype, clientBuffer,
454                                     this, mDeviceContext, mD3D11Device, mRenderer->getFunctions(),
455                                     mFunctionsWGL);
456 }
457 
createPixmapSurface(const egl::SurfaceState & state,NativePixmapType nativePixmap,const egl::AttributeMap & attribs)458 SurfaceImpl *DisplayWGL::createPixmapSurface(const egl::SurfaceState &state,
459                                              NativePixmapType nativePixmap,
460                                              const egl::AttributeMap &attribs)
461 {
462     UNIMPLEMENTED();
463     return nullptr;
464 }
465 
createContext(const gl::State & state,gl::ErrorSet * errorSet,const egl::Config * configuration,const gl::Context * shareContext,const egl::AttributeMap & attribs)466 rx::ContextImpl *DisplayWGL::createContext(const gl::State &state,
467                                            gl::ErrorSet *errorSet,
468                                            const egl::Config *configuration,
469                                            const gl::Context *shareContext,
470                                            const egl::AttributeMap &attribs)
471 {
472     return new ContextWGL(state, errorSet, mRenderer);
473 }
474 
generateConfigs()475 egl::ConfigSet DisplayWGL::generateConfigs()
476 {
477     egl::ConfigSet configs;
478 
479     int minSwapInterval = 1;
480     int maxSwapInterval = 1;
481     if (mFunctionsWGL->swapIntervalEXT)
482     {
483         // No defined maximum swap interval in WGL_EXT_swap_control, use a reasonable number
484         minSwapInterval = 0;
485         maxSwapInterval = 8;
486     }
487 
488     const gl::Version &maxVersion = getMaxSupportedESVersion();
489     ASSERT(maxVersion >= gl::Version(2, 0));
490     bool supportsES3 = maxVersion >= gl::Version(3, 0);
491 
492     PIXELFORMATDESCRIPTOR pixelFormatDescriptor;
493     DescribePixelFormat(mDeviceContext, mPixelFormat, sizeof(pixelFormatDescriptor),
494                         &pixelFormatDescriptor);
495 
496     auto getAttrib = [this](int attrib) {
497         return wgl::QueryWGLFormatAttrib(mDeviceContext, mPixelFormat, attrib, mFunctionsWGL);
498     };
499 
500     const EGLint optimalSurfaceOrientation =
501         mUseDXGISwapChains ? EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE : 0;
502 
503     egl::Config config;
504     config.renderTargetFormat = GL_RGBA8;  // TODO: use the bit counts to determine the format
505     config.depthStencilFormat =
506         GL_DEPTH24_STENCIL8;  // TODO: use the bit counts to determine the format
507     config.bufferSize        = pixelFormatDescriptor.cColorBits;
508     config.redSize           = pixelFormatDescriptor.cRedBits;
509     config.greenSize         = pixelFormatDescriptor.cGreenBits;
510     config.blueSize          = pixelFormatDescriptor.cBlueBits;
511     config.luminanceSize     = 0;
512     config.alphaSize         = pixelFormatDescriptor.cAlphaBits;
513     config.alphaMaskSize     = 0;
514     config.bindToTextureRGB  = (getAttrib(WGL_BIND_TO_TEXTURE_RGB_ARB) == TRUE);
515     config.bindToTextureRGBA = (getAttrib(WGL_BIND_TO_TEXTURE_RGBA_ARB) == TRUE);
516     config.colorBufferType   = EGL_RGB_BUFFER;
517     config.configCaveat      = EGL_NONE;
518     config.conformant        = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
519     config.depthSize         = pixelFormatDescriptor.cDepthBits;
520     config.level             = 0;
521     config.matchNativePixmap = EGL_NONE;
522     config.maxPBufferWidth   = getAttrib(WGL_MAX_PBUFFER_WIDTH_ARB);
523     config.maxPBufferHeight  = getAttrib(WGL_MAX_PBUFFER_HEIGHT_ARB);
524     config.maxPBufferPixels  = getAttrib(WGL_MAX_PBUFFER_PIXELS_ARB);
525     config.maxSwapInterval   = maxSwapInterval;
526     config.minSwapInterval   = minSwapInterval;
527     config.nativeRenderable  = EGL_TRUE;  // Direct rendering
528     config.nativeVisualID    = 0;
529     config.nativeVisualType  = EGL_NONE;
530     config.renderableType    = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
531     config.sampleBuffers     = 0;  // FIXME: enumerate multi-sampling
532     config.samples           = 0;
533     config.stencilSize       = pixelFormatDescriptor.cStencilBits;
534     config.surfaceType =
535         ((pixelFormatDescriptor.dwFlags & PFD_DRAW_TO_WINDOW) ? EGL_WINDOW_BIT : 0) |
536         ((getAttrib(WGL_DRAW_TO_PBUFFER_ARB) == TRUE) ? EGL_PBUFFER_BIT : 0) |
537         ((getAttrib(WGL_SWAP_METHOD_ARB) == WGL_SWAP_COPY_ARB) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT
538                                                                : 0);
539     config.optimalOrientation = optimalSurfaceOrientation;
540     config.colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
541 
542     config.transparentType       = EGL_NONE;
543     config.transparentRedValue   = 0;
544     config.transparentGreenValue = 0;
545     config.transparentBlueValue  = 0;
546 
547     configs.add(config);
548 
549     return configs;
550 }
551 
testDeviceLost()552 bool DisplayWGL::testDeviceLost()
553 {
554     return false;
555 }
556 
restoreLostDevice(const egl::Display * display)557 egl::Error DisplayWGL::restoreLostDevice(const egl::Display *display)
558 {
559     return egl::EglBadDisplay();
560 }
561 
isValidNativeWindow(EGLNativeWindowType window) const562 bool DisplayWGL::isValidNativeWindow(EGLNativeWindowType window) const
563 {
564     return (IsWindow(window) == TRUE);
565 }
566 
validateClientBuffer(const egl::Config * configuration,EGLenum buftype,EGLClientBuffer clientBuffer,const egl::AttributeMap & attribs) const567 egl::Error DisplayWGL::validateClientBuffer(const egl::Config *configuration,
568                                             EGLenum buftype,
569                                             EGLClientBuffer clientBuffer,
570                                             const egl::AttributeMap &attribs) const
571 {
572     switch (buftype)
573     {
574         case EGL_D3D_TEXTURE_ANGLE:
575         case EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE:
576             ANGLE_TRY(const_cast<DisplayWGL *>(this)->initializeD3DDevice());
577             return D3DTextureSurfaceWGL::ValidateD3DTextureClientBuffer(buftype, clientBuffer,
578                                                                         mD3D11Device);
579 
580         default:
581             return DisplayGL::validateClientBuffer(configuration, buftype, clientBuffer, attribs);
582     }
583 }
584 
initializeD3DDevice()585 egl::Error DisplayWGL::initializeD3DDevice()
586 {
587     if (mD3D11Device != nullptr)
588     {
589         return egl::NoError();
590     }
591 
592     mDxgiModule = LoadLibrary(TEXT("dxgi.dll"));
593     if (!mDxgiModule)
594     {
595         return egl::EglNotInitialized() << "Failed to load DXGI library.";
596     }
597 
598     mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
599     if (!mD3d11Module)
600     {
601         return egl::EglNotInitialized() << "Failed to load d3d11 library.";
602     }
603 
604     PFN_D3D11_CREATE_DEVICE d3d11CreateDevice = nullptr;
605     d3d11CreateDevice                         = reinterpret_cast<PFN_D3D11_CREATE_DEVICE>(
606         GetProcAddress(mD3d11Module, "D3D11CreateDevice"));
607     if (d3d11CreateDevice == nullptr)
608     {
609         return egl::EglNotInitialized() << "Could not retrieve D3D11CreateDevice address.";
610     }
611 
612     HRESULT result = d3d11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0,
613                                        D3D11_SDK_VERSION, &mD3D11Device, nullptr, nullptr);
614     if (FAILED(result))
615     {
616         return egl::EglNotInitialized() << "Could not create D3D11 device, " << gl::FmtHR(result);
617     }
618 
619     return registerD3DDevice(mD3D11Device, &mD3D11DeviceHandle);
620 }
621 
generateExtensions(egl::DisplayExtensions * outExtensions) const622 void DisplayWGL::generateExtensions(egl::DisplayExtensions *outExtensions) const
623 {
624     // Only enable the surface orientation  and post sub buffer for DXGI swap chain surfaces, they
625     // prefer to swap with inverted Y.
626     outExtensions->postSubBuffer      = mUseDXGISwapChains;
627     outExtensions->surfaceOrientation = mUseDXGISwapChains;
628 
629     outExtensions->createContextRobustness = mHasRobustness;
630 
631     outExtensions->d3dTextureClientBuffer         = mHasDXInterop;
632     outExtensions->d3dShareHandleClientBuffer     = mHasDXInterop;
633     outExtensions->surfaceD3DTexture2DShareHandle = true;
634     outExtensions->querySurfacePointer            = true;
635     outExtensions->keyedMutex                     = true;
636 
637     // Contexts are virtualized so textures and semaphores can be shared globally
638     outExtensions->displayTextureShareGroup   = true;
639     outExtensions->displaySemaphoreShareGroup = true;
640 
641     outExtensions->surfacelessContext = true;
642 
643     DisplayGL::generateExtensions(outExtensions);
644 }
645 
generateCaps(egl::Caps * outCaps) const646 void DisplayWGL::generateCaps(egl::Caps *outCaps) const
647 {
648     outCaps->textureNPOT = true;
649 }
650 
makeCurrentSurfaceless(gl::Context * context)651 egl::Error DisplayWGL::makeCurrentSurfaceless(gl::Context *context)
652 {
653     // Nothing to do because WGL always uses the same context and the previous surface can be left
654     // current.
655     return egl::NoError();
656 }
657 
waitClient(const gl::Context * context)658 egl::Error DisplayWGL::waitClient(const gl::Context *context)
659 {
660     // Unimplemented as this is not needed for WGL
661     return egl::NoError();
662 }
663 
waitNative(const gl::Context * context,EGLint engine)664 egl::Error DisplayWGL::waitNative(const gl::Context *context, EGLint engine)
665 {
666     // Unimplemented as this is not needed for WGL
667     return egl::NoError();
668 }
669 
makeCurrent(egl::Display * display,egl::Surface * drawSurface,egl::Surface * readSurface,gl::Context * context)670 egl::Error DisplayWGL::makeCurrent(egl::Display *display,
671                                    egl::Surface *drawSurface,
672                                    egl::Surface *readSurface,
673                                    gl::Context *context)
674 {
675     CurrentNativeContext &currentContext = mCurrentNativeContexts[std::this_thread::get_id()];
676 
677     HDC newDC = mDeviceContext;
678     if (drawSurface)
679     {
680         SurfaceWGL *drawSurfaceWGL = GetImplAs<SurfaceWGL>(drawSurface);
681         newDC                      = drawSurfaceWGL->getDC();
682     }
683 
684     HGLRC newContext = currentContext.glrc;
685     if (context)
686     {
687         ContextWGL *contextWGL = GetImplAs<ContextWGL>(context);
688         newContext             = contextWGL->getContext();
689     }
690     else if (!mUseDXGISwapChains)
691     {
692         newContext = 0;
693     }
694 
695     if (newDC != currentContext.dc || newContext != currentContext.glrc)
696     {
697         ASSERT(newDC != 0);
698 
699         if (!mFunctionsWGL->makeCurrent(newDC, newContext))
700         {
701             // TODO(geofflang): What error type here?
702             return egl::EglContextLost() << "Failed to make the WGL context current.";
703         }
704         currentContext.dc   = newDC;
705         currentContext.glrc = newContext;
706     }
707 
708     return DisplayGL::makeCurrent(display, drawSurface, readSurface, context);
709 }
710 
registerD3DDevice(IUnknown * device,HANDLE * outHandle)711 egl::Error DisplayWGL::registerD3DDevice(IUnknown *device, HANDLE *outHandle)
712 {
713     ASSERT(device != nullptr);
714     ASSERT(outHandle != nullptr);
715 
716     auto iter = mRegisteredD3DDevices.find(device);
717     if (iter != mRegisteredD3DDevices.end())
718     {
719         iter->second.refCount++;
720         *outHandle = iter->second.handle;
721         return egl::NoError();
722     }
723 
724     HANDLE handle = mFunctionsWGL->dxOpenDeviceNV(device);
725     if (!handle)
726     {
727         return egl::EglBadParameter() << "Failed to open D3D device.";
728     }
729 
730     device->AddRef();
731 
732     D3DObjectHandle newDeviceInfo;
733     newDeviceInfo.handle          = handle;
734     newDeviceInfo.refCount        = 1;
735     mRegisteredD3DDevices[device] = newDeviceInfo;
736 
737     *outHandle = handle;
738     return egl::NoError();
739 }
740 
releaseD3DDevice(HANDLE deviceHandle)741 void DisplayWGL::releaseD3DDevice(HANDLE deviceHandle)
742 {
743     for (auto iter = mRegisteredD3DDevices.begin(); iter != mRegisteredD3DDevices.end(); iter++)
744     {
745         if (iter->second.handle == deviceHandle)
746         {
747             iter->second.refCount--;
748             if (iter->second.refCount == 0)
749             {
750                 mFunctionsWGL->dxCloseDeviceNV(iter->second.handle);
751                 iter->first->Release();
752                 mRegisteredD3DDevices.erase(iter);
753                 break;
754             }
755         }
756     }
757 }
758 
getMaxSupportedESVersion() const759 gl::Version DisplayWGL::getMaxSupportedESVersion() const
760 {
761     return mRenderer->getMaxSupportedESVersion();
762 }
763 
destroyNativeContext(HGLRC context)764 void DisplayWGL::destroyNativeContext(HGLRC context)
765 {
766     mFunctionsWGL->deleteContext(context);
767 }
768 
initializeContextAttribs(const egl::AttributeMap & eglAttributes,HGLRC & sharedContext,bool & useARBShare,std::vector<int> & workerContextAttribs) const769 HGLRC DisplayWGL::initializeContextAttribs(const egl::AttributeMap &eglAttributes,
770                                            HGLRC &sharedContext,
771                                            bool &useARBShare,
772                                            std::vector<int> &workerContextAttribs) const
773 {
774     EGLint requestedDisplayType = static_cast<EGLint>(
775         eglAttributes.get(EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
776 
777     // Create a context of the requested version, if any.
778     gl::Version requestedVersion(static_cast<EGLint>(eglAttributes.get(
779                                      EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, EGL_DONT_CARE)),
780                                  static_cast<EGLint>(eglAttributes.get(
781                                      EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, EGL_DONT_CARE)));
782     if (static_cast<EGLint>(requestedVersion.major) != EGL_DONT_CARE &&
783         static_cast<EGLint>(requestedVersion.minor) != EGL_DONT_CARE)
784     {
785         int profileMask = 0;
786         if (requestedDisplayType != EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE &&
787             requestedVersion >= gl::Version(3, 2))
788         {
789             profileMask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
790         }
791         return createContextAttribs(requestedVersion, profileMask, sharedContext, useARBShare,
792                                     workerContextAttribs);
793     }
794 
795     // Try all the GL version in order as a workaround for Mesa context creation where the driver
796     // doesn't automatically return the highest version available.
797     for (const auto &info : GenerateContextCreationToTry(requestedDisplayType, false))
798     {
799         int profileFlag = 0;
800         if (info.type == ContextCreationTry::Type::DESKTOP_CORE)
801         {
802             profileFlag |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
803         }
804         else if (info.type == ContextCreationTry::Type::ES)
805         {
806             profileFlag |= WGL_CONTEXT_ES_PROFILE_BIT_EXT;
807         }
808 
809         HGLRC context = createContextAttribs(info.version, profileFlag, sharedContext, useARBShare,
810                                              workerContextAttribs);
811         if (context != nullptr)
812         {
813             return context;
814         }
815     }
816 
817     return nullptr;
818 }
819 
createContextAttribs(const gl::Version & version,int profileMask,HGLRC & sharedContext,bool & useARBShare,std::vector<int> & workerContextAttribs) const820 HGLRC DisplayWGL::createContextAttribs(const gl::Version &version,
821                                        int profileMask,
822                                        HGLRC &sharedContext,
823                                        bool &useARBShare,
824                                        std::vector<int> &workerContextAttribs) const
825 {
826     std::vector<int> attribs;
827 
828     if (mHasWGLCreateContextRobustness)
829     {
830         attribs.push_back(WGL_CONTEXT_FLAGS_ARB);
831         attribs.push_back(WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB);
832         attribs.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
833         attribs.push_back(WGL_LOSE_CONTEXT_ON_RESET_ARB);
834     }
835 
836     attribs.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
837     attribs.push_back(version.major);
838 
839     attribs.push_back(WGL_CONTEXT_MINOR_VERSION_ARB);
840     attribs.push_back(version.minor);
841 
842     if (profileMask != 0)
843     {
844         attribs.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
845         attribs.push_back(profileMask);
846     }
847 
848     attribs.push_back(0);
849     attribs.push_back(0);
850     HGLRC context = mFunctionsWGL->createContextAttribsARB(mDeviceContext, nullptr, &attribs[0]);
851 
852     // This shared context is never made current. It is safer than the main context to be used as
853     // a seed to create worker contexts from.
854     // It seems a WGL restriction not mentioned in MSDN, but some posts revealed it.
855     // https://www.opengl.org/discussion_boards/showthread.php/152648-wglShareLists-failing
856     // https://github.com/glfw/glfw/issues/402
857     sharedContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, context, &attribs[0]);
858     workerContextAttribs = attribs;
859     useARBShare          = true;
860     return context;
861 }
862 
createRenderer(std::shared_ptr<RendererWGL> * outRenderer)863 egl::Error DisplayWGL::createRenderer(std::shared_ptr<RendererWGL> *outRenderer)
864 {
865     HGLRC context       = nullptr;
866     HGLRC sharedContext = nullptr;
867     std::vector<int> workerContextAttribs;
868 
869     if (mFunctionsWGL->createContextAttribsARB)
870     {
871         context = initializeContextAttribs(mDisplayAttributes, sharedContext, mUseARBShare,
872                                            workerContextAttribs);
873     }
874 
875     // If wglCreateContextAttribsARB is unavailable or failed, try the standard wglCreateContext
876     if (!context)
877     {
878         // Don't have control over GL versions
879         context = mFunctionsWGL->createContext(mDeviceContext);
880     }
881 
882     if (!context)
883     {
884         return egl::EglNotInitialized()
885                << "Failed to create a WGL context for the intermediate OpenGL window."
886                << GetErrorMessage();
887     }
888 
889     if (!sharedContext)
890     {
891         sharedContext = mFunctionsWGL->createContext(mDeviceContext);
892         if (!mFunctionsWGL->shareLists(context, sharedContext))
893         {
894             mFunctionsWGL->deleteContext(sharedContext);
895             sharedContext = nullptr;
896         }
897         mUseARBShare = false;
898     }
899 
900     if (!mFunctionsWGL->makeCurrent(mDeviceContext, context))
901     {
902         return egl::EglNotInitialized() << "Failed to make the intermediate WGL context current.";
903     }
904     CurrentNativeContext &currentContext = mCurrentNativeContexts[std::this_thread::get_id()];
905     currentContext.dc                    = mDeviceContext;
906     currentContext.glrc                  = context;
907 
908     std::unique_ptr<FunctionsGL> functionsGL(
909         new FunctionsGLWindows(mOpenGLModule, mFunctionsWGL->getProcAddress));
910     functionsGL->initialize(mDisplayAttributes);
911 
912     outRenderer->reset(new RendererWGL(std::move(functionsGL), mDisplayAttributes, this, context,
913                                        sharedContext, workerContextAttribs));
914 
915     return egl::NoError();
916 }
917 
918 class WorkerContextWGL final : public WorkerContext
919 {
920   public:
921     WorkerContextWGL(FunctionsWGL *functions,
922                      HPBUFFERARB pbuffer,
923                      HDC deviceContext,
924                      HGLRC context);
925     ~WorkerContextWGL() override;
926 
927     bool makeCurrent() override;
928     void unmakeCurrent() override;
929 
930   private:
931     FunctionsWGL *mFunctionsWGL;
932     HPBUFFERARB mPbuffer;
933     HDC mDeviceContext;
934     HGLRC mContext;
935 };
936 
WorkerContextWGL(FunctionsWGL * functions,HPBUFFERARB pbuffer,HDC deviceContext,HGLRC context)937 WorkerContextWGL::WorkerContextWGL(FunctionsWGL *functions,
938                                    HPBUFFERARB pbuffer,
939                                    HDC deviceContext,
940                                    HGLRC context)
941     : mFunctionsWGL(functions), mPbuffer(pbuffer), mDeviceContext(deviceContext), mContext(context)
942 {}
943 
~WorkerContextWGL()944 WorkerContextWGL::~WorkerContextWGL()
945 {
946     mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
947     mFunctionsWGL->deleteContext(mContext);
948     mFunctionsWGL->releasePbufferDCARB(mPbuffer, mDeviceContext);
949     mFunctionsWGL->destroyPbufferARB(mPbuffer);
950 }
951 
makeCurrent()952 bool WorkerContextWGL::makeCurrent()
953 {
954     bool result = mFunctionsWGL->makeCurrent(mDeviceContext, mContext);
955     if (!result)
956     {
957         ERR() << GetErrorMessage();
958     }
959     return result;
960 }
961 
unmakeCurrent()962 void WorkerContextWGL::unmakeCurrent()
963 {
964     mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
965 }
966 
createWorkerContext(std::string * infoLog,HGLRC sharedContext,const std::vector<int> & workerContextAttribs)967 WorkerContext *DisplayWGL::createWorkerContext(std::string *infoLog,
968                                                HGLRC sharedContext,
969                                                const std::vector<int> &workerContextAttribs)
970 {
971     if (!sharedContext)
972     {
973         *infoLog += "Unable to create the shared context.";
974         return nullptr;
975     }
976 
977     HPBUFFERARB workerPbuffer = nullptr;
978     HDC workerDeviceContext   = nullptr;
979     HGLRC workerContext       = nullptr;
980 
981 #define CLEANUP_ON_ERROR()                                                          \
982     do                                                                              \
983     {                                                                               \
984         if (workerContext)                                                          \
985         {                                                                           \
986             mFunctionsWGL->deleteContext(workerContext);                            \
987         }                                                                           \
988         if (workerDeviceContext)                                                    \
989         {                                                                           \
990             mFunctionsWGL->releasePbufferDCARB(workerPbuffer, workerDeviceContext); \
991         }                                                                           \
992         if (workerPbuffer)                                                          \
993         {                                                                           \
994             mFunctionsWGL->destroyPbufferARB(workerPbuffer);                        \
995         }                                                                           \
996     } while (0)
997 
998     const int attribs[] = {0, 0};
999     workerPbuffer = mFunctionsWGL->createPbufferARB(mDeviceContext, mPixelFormat, 1, 1, attribs);
1000     if (!workerPbuffer)
1001     {
1002         *infoLog += GetErrorMessage();
1003         return nullptr;
1004     }
1005 
1006     workerDeviceContext = mFunctionsWGL->getPbufferDCARB(workerPbuffer);
1007     if (!workerDeviceContext)
1008     {
1009         *infoLog += GetErrorMessage();
1010         CLEANUP_ON_ERROR();
1011         return nullptr;
1012     }
1013 
1014     if (mUseARBShare)
1015     {
1016         workerContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, sharedContext,
1017                                                                &workerContextAttribs[0]);
1018     }
1019     else
1020     {
1021         workerContext = mFunctionsWGL->createContext(workerDeviceContext);
1022     }
1023     if (!workerContext)
1024     {
1025         GetErrorMessage();
1026         CLEANUP_ON_ERROR();
1027         return nullptr;
1028     }
1029 
1030     if (!mUseARBShare && !mFunctionsWGL->shareLists(sharedContext, workerContext))
1031     {
1032         GetErrorMessage();
1033         CLEANUP_ON_ERROR();
1034         return nullptr;
1035     }
1036 
1037 #undef CLEANUP_ON_ERROR
1038 
1039     return new WorkerContextWGL(mFunctionsWGL, workerPbuffer, workerDeviceContext, workerContext);
1040 }
1041 
initializeFrontendFeatures(angle::FrontendFeatures * features) const1042 void DisplayWGL::initializeFrontendFeatures(angle::FrontendFeatures *features) const
1043 {
1044     mRenderer->initializeFrontendFeatures(features);
1045 }
1046 
populateFeatureList(angle::FeatureList * features)1047 void DisplayWGL::populateFeatureList(angle::FeatureList *features)
1048 {
1049     mRenderer->getFeatures().populateFeatureList(features);
1050 }
1051 
getRenderer() const1052 RendererGL *DisplayWGL::getRenderer() const
1053 {
1054     return reinterpret_cast<RendererGL *>(mRenderer.get());
1055 }
1056 
1057 }  // namespace rx
1058