1 //
2 // Copyright 2012 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 // Renderer11.cpp: Implements a back-end specific class for the D3D11 renderer.
8 
9 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
10 
11 #include <EGL/eglext.h>
12 #include <versionhelpers.h>
13 #include <sstream>
14 
15 #include "common/tls.h"
16 #include "common/utilities.h"
17 #include "libANGLE/Buffer.h"
18 #include "libANGLE/Context.h"
19 #include "libANGLE/Display.h"
20 #include "libANGLE/Framebuffer.h"
21 #include "libANGLE/FramebufferAttachment.h"
22 #include "libANGLE/Program.h"
23 #include "libANGLE/State.h"
24 #include "libANGLE/Surface.h"
25 #include "libANGLE/formatutils.h"
26 #include "libANGLE/histogram_macros.h"
27 #include "libANGLE/renderer/d3d/CompilerD3D.h"
28 #include "libANGLE/renderer/d3d/DeviceD3D.h"
29 #include "libANGLE/renderer/d3d/DisplayD3D.h"
30 #include "libANGLE/renderer/d3d/FramebufferD3D.h"
31 #include "libANGLE/renderer/d3d/IndexDataManager.h"
32 #include "libANGLE/renderer/d3d/RenderbufferD3D.h"
33 #include "libANGLE/renderer/d3d/ShaderD3D.h"
34 #include "libANGLE/renderer/d3d/SurfaceD3D.h"
35 #include "libANGLE/renderer/d3d/TextureD3D.h"
36 #include "libANGLE/renderer/d3d/VertexDataManager.h"
37 #include "libANGLE/renderer/d3d/d3d11/Blit11.h"
38 #include "libANGLE/renderer/d3d/d3d11/Buffer11.h"
39 #include "libANGLE/renderer/d3d/d3d11/Clear11.h"
40 #include "libANGLE/renderer/d3d/d3d11/Context11.h"
41 #include "libANGLE/renderer/d3d/d3d11/ExternalImageSiblingImpl11.h"
42 #include "libANGLE/renderer/d3d/d3d11/Fence11.h"
43 #include "libANGLE/renderer/d3d/d3d11/Framebuffer11.h"
44 #include "libANGLE/renderer/d3d/d3d11/Image11.h"
45 #include "libANGLE/renderer/d3d/d3d11/IndexBuffer11.h"
46 #include "libANGLE/renderer/d3d/d3d11/PixelTransfer11.h"
47 #include "libANGLE/renderer/d3d/d3d11/Program11.h"
48 #include "libANGLE/renderer/d3d/d3d11/Query11.h"
49 #include "libANGLE/renderer/d3d/d3d11/RenderTarget11.h"
50 #include "libANGLE/renderer/d3d/d3d11/ShaderExecutable11.h"
51 #include "libANGLE/renderer/d3d/d3d11/StreamProducerD3DTexture.h"
52 #include "libANGLE/renderer/d3d/d3d11/SwapChain11.h"
53 #include "libANGLE/renderer/d3d/d3d11/TextureStorage11.h"
54 #include "libANGLE/renderer/d3d/d3d11/TransformFeedback11.h"
55 #include "libANGLE/renderer/d3d/d3d11/Trim11.h"
56 #include "libANGLE/renderer/d3d/d3d11/VertexArray11.h"
57 #include "libANGLE/renderer/d3d/d3d11/VertexBuffer11.h"
58 #include "libANGLE/renderer/d3d/d3d11/formatutils11.h"
59 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
60 #include "libANGLE/renderer/d3d/d3d11/texture_format_table.h"
61 #include "libANGLE/renderer/d3d/driver_utils_d3d.h"
62 #include "libANGLE/renderer/driver_utils.h"
63 #include "libANGLE/renderer/dxgi_support_table.h"
64 #include "libANGLE/renderer/renderer_utils.h"
65 #include "libANGLE/trace.h"
66 
67 #ifdef ANGLE_ENABLE_WINDOWS_UWP
68 #    include "libANGLE/renderer/d3d/d3d11/winrt/NativeWindow11WinRT.h"
69 #else
70 #    include "libANGLE/renderer/d3d/d3d11/win32/NativeWindow11Win32.h"
71 #endif
72 
73 #ifdef ANGLE_ENABLE_D3D11_COMPOSITOR_NATIVE_WINDOW
74 #    include "libANGLE/renderer/d3d/d3d11/converged/CompositorNativeWindow11.h"
75 #endif
76 
77 // Enable ANGLE_SKIP_DXGI_1_2_CHECK if there is not a possibility of using cross-process
78 // HWNDs or the Windows 7 Platform Update (KB2670838) is expected to be installed.
79 #ifndef ANGLE_SKIP_DXGI_1_2_CHECK
80 #    define ANGLE_SKIP_DXGI_1_2_CHECK 0
81 #endif
82 
83 namespace rx
84 {
85 
86 namespace
87 {
88 
89 enum
90 {
91     MAX_TEXTURE_IMAGE_UNITS_VTF_SM4 = 16
92 };
93 
94 enum ANGLEFeatureLevel
95 {
96     ANGLE_FEATURE_LEVEL_INVALID,
97     ANGLE_FEATURE_LEVEL_9_3,
98     ANGLE_FEATURE_LEVEL_10_0,
99     ANGLE_FEATURE_LEVEL_10_1,
100     ANGLE_FEATURE_LEVEL_11_0,
101     ANGLE_FEATURE_LEVEL_11_1,
102     NUM_ANGLE_FEATURE_LEVELS
103 };
104 
GetANGLEFeatureLevel(D3D_FEATURE_LEVEL d3dFeatureLevel)105 ANGLEFeatureLevel GetANGLEFeatureLevel(D3D_FEATURE_LEVEL d3dFeatureLevel)
106 {
107     switch (d3dFeatureLevel)
108     {
109         case D3D_FEATURE_LEVEL_9_3:
110             return ANGLE_FEATURE_LEVEL_9_3;
111         case D3D_FEATURE_LEVEL_10_0:
112             return ANGLE_FEATURE_LEVEL_10_0;
113         case D3D_FEATURE_LEVEL_10_1:
114             return ANGLE_FEATURE_LEVEL_10_1;
115         case D3D_FEATURE_LEVEL_11_0:
116             return ANGLE_FEATURE_LEVEL_11_0;
117         case D3D_FEATURE_LEVEL_11_1:
118             return ANGLE_FEATURE_LEVEL_11_1;
119         default:
120             return ANGLE_FEATURE_LEVEL_INVALID;
121     }
122 }
123 
SetLineLoopIndices(GLuint * dest,size_t count)124 void SetLineLoopIndices(GLuint *dest, size_t count)
125 {
126     for (size_t i = 0; i < count; i++)
127     {
128         dest[i] = static_cast<GLuint>(i);
129     }
130     dest[count] = 0;
131 }
132 
133 template <typename T>
CopyLineLoopIndices(const void * indices,GLuint * dest,size_t count)134 void CopyLineLoopIndices(const void *indices, GLuint *dest, size_t count)
135 {
136     const T *srcPtr = static_cast<const T *>(indices);
137     for (size_t i = 0; i < count; ++i)
138     {
139         dest[i] = static_cast<GLuint>(srcPtr[i]);
140     }
141     dest[count] = static_cast<GLuint>(srcPtr[0]);
142 }
143 
SetTriangleFanIndices(GLuint * destPtr,size_t numTris)144 void SetTriangleFanIndices(GLuint *destPtr, size_t numTris)
145 {
146     for (size_t i = 0; i < numTris; i++)
147     {
148         destPtr[i * 3 + 0] = 0;
149         destPtr[i * 3 + 1] = static_cast<GLuint>(i) + 1;
150         destPtr[i * 3 + 2] = static_cast<GLuint>(i) + 2;
151     }
152 }
153 
GetLineLoopIndices(const void * indices,gl::DrawElementsType indexType,GLuint count,bool usePrimitiveRestartFixedIndex,std::vector<GLuint> * bufferOut)154 void GetLineLoopIndices(const void *indices,
155                         gl::DrawElementsType indexType,
156                         GLuint count,
157                         bool usePrimitiveRestartFixedIndex,
158                         std::vector<GLuint> *bufferOut)
159 {
160     if (indexType != gl::DrawElementsType::InvalidEnum && usePrimitiveRestartFixedIndex)
161     {
162         size_t indexCount = GetLineLoopWithRestartIndexCount(indexType, count,
163                                                              static_cast<const uint8_t *>(indices));
164         bufferOut->resize(indexCount);
165         switch (indexType)
166         {
167             case gl::DrawElementsType::UnsignedByte:
168                 CopyLineLoopIndicesWithRestart<GLubyte, GLuint>(
169                     count, static_cast<const uint8_t *>(indices),
170                     reinterpret_cast<uint8_t *>(bufferOut->data()));
171                 break;
172             case gl::DrawElementsType::UnsignedShort:
173                 CopyLineLoopIndicesWithRestart<GLushort, GLuint>(
174                     count, static_cast<const uint8_t *>(indices),
175                     reinterpret_cast<uint8_t *>(bufferOut->data()));
176                 break;
177             case gl::DrawElementsType::UnsignedInt:
178                 CopyLineLoopIndicesWithRestart<GLuint, GLuint>(
179                     count, static_cast<const uint8_t *>(indices),
180                     reinterpret_cast<uint8_t *>(bufferOut->data()));
181                 break;
182             default:
183                 UNREACHABLE();
184                 break;
185         }
186         return;
187     }
188 
189     // For non-primitive-restart draws, the index count is static.
190     bufferOut->resize(static_cast<size_t>(count) + 1);
191 
192     switch (indexType)
193     {
194         // Non-indexed draw
195         case gl::DrawElementsType::InvalidEnum:
196             SetLineLoopIndices(&(*bufferOut)[0], count);
197             break;
198         case gl::DrawElementsType::UnsignedByte:
199             CopyLineLoopIndices<GLubyte>(indices, &(*bufferOut)[0], count);
200             break;
201         case gl::DrawElementsType::UnsignedShort:
202             CopyLineLoopIndices<GLushort>(indices, &(*bufferOut)[0], count);
203             break;
204         case gl::DrawElementsType::UnsignedInt:
205             CopyLineLoopIndices<GLuint>(indices, &(*bufferOut)[0], count);
206             break;
207         default:
208             UNREACHABLE();
209             break;
210     }
211 }
212 
213 template <typename T>
CopyTriangleFanIndices(const void * indices,GLuint * destPtr,size_t numTris)214 void CopyTriangleFanIndices(const void *indices, GLuint *destPtr, size_t numTris)
215 {
216     const T *srcPtr = static_cast<const T *>(indices);
217 
218     for (size_t i = 0; i < numTris; i++)
219     {
220         destPtr[i * 3 + 0] = static_cast<GLuint>(srcPtr[0]);
221         destPtr[i * 3 + 1] = static_cast<GLuint>(srcPtr[i + 1]);
222         destPtr[i * 3 + 2] = static_cast<GLuint>(srcPtr[i + 2]);
223     }
224 }
225 
226 template <typename T>
CopyTriangleFanIndicesWithRestart(const void * indices,GLuint indexCount,gl::DrawElementsType indexType,std::vector<GLuint> * bufferOut)227 void CopyTriangleFanIndicesWithRestart(const void *indices,
228                                        GLuint indexCount,
229                                        gl::DrawElementsType indexType,
230                                        std::vector<GLuint> *bufferOut)
231 {
232     GLuint restartIndex    = gl::GetPrimitiveRestartIndex(indexType);
233     GLuint d3dRestartIndex = gl::GetPrimitiveRestartIndex(gl::DrawElementsType::UnsignedInt);
234     const T *srcPtr        = static_cast<const T *>(indices);
235     Optional<GLuint> vertexA;
236     Optional<GLuint> vertexB;
237 
238     bufferOut->clear();
239 
240     for (size_t indexIdx = 0; indexIdx < indexCount; ++indexIdx)
241     {
242         GLuint value = static_cast<GLuint>(srcPtr[indexIdx]);
243 
244         if (value == restartIndex)
245         {
246             bufferOut->push_back(d3dRestartIndex);
247             vertexA.reset();
248             vertexB.reset();
249         }
250         else
251         {
252             if (!vertexA.valid())
253             {
254                 vertexA = value;
255             }
256             else if (!vertexB.valid())
257             {
258                 vertexB = value;
259             }
260             else
261             {
262                 bufferOut->push_back(vertexA.value());
263                 bufferOut->push_back(vertexB.value());
264                 bufferOut->push_back(value);
265                 vertexB = value;
266             }
267         }
268     }
269 }
270 
GetTriFanIndices(const void * indices,gl::DrawElementsType indexType,GLuint count,bool usePrimitiveRestartFixedIndex,std::vector<GLuint> * bufferOut)271 void GetTriFanIndices(const void *indices,
272                       gl::DrawElementsType indexType,
273                       GLuint count,
274                       bool usePrimitiveRestartFixedIndex,
275                       std::vector<GLuint> *bufferOut)
276 {
277     if (indexType != gl::DrawElementsType::InvalidEnum && usePrimitiveRestartFixedIndex)
278     {
279         switch (indexType)
280         {
281             case gl::DrawElementsType::UnsignedByte:
282                 CopyTriangleFanIndicesWithRestart<GLubyte>(indices, count, indexType, bufferOut);
283                 break;
284             case gl::DrawElementsType::UnsignedShort:
285                 CopyTriangleFanIndicesWithRestart<GLushort>(indices, count, indexType, bufferOut);
286                 break;
287             case gl::DrawElementsType::UnsignedInt:
288                 CopyTriangleFanIndicesWithRestart<GLuint>(indices, count, indexType, bufferOut);
289                 break;
290             default:
291                 UNREACHABLE();
292                 break;
293         }
294         return;
295     }
296 
297     // For non-primitive-restart draws, the index count is static.
298     GLuint numTris = count - 2;
299     bufferOut->resize(numTris * 3);
300 
301     switch (indexType)
302     {
303         // Non-indexed draw
304         case gl::DrawElementsType::InvalidEnum:
305             SetTriangleFanIndices(&(*bufferOut)[0], numTris);
306             break;
307         case gl::DrawElementsType::UnsignedByte:
308             CopyTriangleFanIndices<GLubyte>(indices, &(*bufferOut)[0], numTris);
309             break;
310         case gl::DrawElementsType::UnsignedShort:
311             CopyTriangleFanIndices<GLushort>(indices, &(*bufferOut)[0], numTris);
312             break;
313         case gl::DrawElementsType::UnsignedInt:
314             CopyTriangleFanIndices<GLuint>(indices, &(*bufferOut)[0], numTris);
315             break;
316         default:
317             UNREACHABLE();
318             break;
319     }
320 }
321 
IsArrayRTV(ID3D11RenderTargetView * rtv)322 bool IsArrayRTV(ID3D11RenderTargetView *rtv)
323 {
324     D3D11_RENDER_TARGET_VIEW_DESC desc;
325     rtv->GetDesc(&desc);
326     if (desc.ViewDimension == D3D11_RTV_DIMENSION_TEXTURE1DARRAY &&
327         desc.Texture1DArray.ArraySize > 1)
328         return true;
329     if (desc.ViewDimension == D3D11_RTV_DIMENSION_TEXTURE2DARRAY &&
330         desc.Texture2DArray.ArraySize > 1)
331         return true;
332     if (desc.ViewDimension == D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY &&
333         desc.Texture2DMSArray.ArraySize > 1)
334         return true;
335     return false;
336 }
337 
GetAdjustedInstanceCount(const ProgramD3D * program,GLsizei instanceCount)338 GLsizei GetAdjustedInstanceCount(const ProgramD3D *program, GLsizei instanceCount)
339 {
340     if (!program->getState().usesMultiview())
341     {
342         return instanceCount;
343     }
344     if (instanceCount == 0)
345     {
346         return program->getState().getNumViews();
347     }
348     return program->getState().getNumViews() * instanceCount;
349 }
350 
351 const uint32_t ScratchMemoryBufferLifetime = 1000;
352 
PopulateFormatDeviceCaps(ID3D11Device * device,DXGI_FORMAT format,UINT * outSupport,UINT * outMaxSamples)353 void PopulateFormatDeviceCaps(ID3D11Device *device,
354                               DXGI_FORMAT format,
355                               UINT *outSupport,
356                               UINT *outMaxSamples)
357 {
358     if (FAILED(device->CheckFormatSupport(format, outSupport)))
359     {
360         *outSupport = 0;
361     }
362 
363     *outMaxSamples = 0;
364     for (UINT sampleCount = 2; sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; sampleCount *= 2)
365     {
366         UINT qualityCount = 0;
367         if (FAILED(device->CheckMultisampleQualityLevels(format, sampleCount, &qualityCount)) ||
368             qualityCount == 0)
369         {
370             break;
371         }
372 
373         *outMaxSamples = sampleCount;
374     }
375 }
376 
GetTextureD3DResourceFromStorageOrImage(const gl::Context * context,TextureD3D * texture,const gl::ImageIndex & index,const TextureHelper11 ** outResource,UINT * outSubresource)377 angle::Result GetTextureD3DResourceFromStorageOrImage(const gl::Context *context,
378                                                       TextureD3D *texture,
379                                                       const gl::ImageIndex &index,
380                                                       const TextureHelper11 **outResource,
381                                                       UINT *outSubresource)
382 {
383     // If the storage exists, use it. Otherwise, copy directly from the images to avoid
384     // allocating a new storage.
385     if (texture->hasStorage())
386     {
387         TextureStorage *storage = nullptr;
388         ANGLE_TRY(texture->getNativeTexture(context, &storage));
389 
390         TextureStorage11 *storage11 = GetAs<TextureStorage11>(storage);
391         ANGLE_TRY(storage11->getResource(context, outResource));
392         ANGLE_TRY(storage11->getSubresourceIndex(context, index, outSubresource));
393     }
394     else
395     {
396         ImageD3D *image  = texture->getImage(index);
397         Image11 *image11 = GetAs<Image11>(image);
398         ANGLE_TRY(image11->getStagingTexture(context, outResource, outSubresource));
399     }
400 
401     return angle::Result::Continue;
402 }
403 
404 }  // anonymous namespace
405 
406 Renderer11DeviceCaps::Renderer11DeviceCaps() = default;
407 
Renderer11(egl::Display * display)408 Renderer11::Renderer11(egl::Display *display)
409     : RendererD3D(display),
410       mCreateDebugDevice(false),
411       mStateCache(),
412       mStateManager(this),
413       mLastHistogramUpdateTime(
414           ANGLEPlatformCurrent()->monotonicallyIncreasingTime(ANGLEPlatformCurrent())),
415       mDebug(nullptr),
416       mScratchMemoryBuffer(ScratchMemoryBufferLifetime)
417 {
418     mLineLoopIB    = nullptr;
419     mTriangleFanIB = nullptr;
420 
421     mBlit          = nullptr;
422     mPixelTransfer = nullptr;
423 
424     mClear = nullptr;
425 
426     mTrim = nullptr;
427 
428     mRenderer11DeviceCaps.supportsClearView                      = false;
429     mRenderer11DeviceCaps.supportsConstantBufferOffsets          = false;
430     mRenderer11DeviceCaps.supportsVpRtIndexWriteFromVertexShader = false;
431     mRenderer11DeviceCaps.supportsDXGI1_2                        = false;
432     mRenderer11DeviceCaps.allowES3OnFL10_0                       = false;
433     mRenderer11DeviceCaps.B5G6R5support                          = 0;
434     mRenderer11DeviceCaps.B4G4R4A4support                        = 0;
435     mRenderer11DeviceCaps.B5G5R5A1support                        = 0;
436 
437     mD3d11Module          = nullptr;
438     mD3d12Module          = nullptr;
439     mDxgiModule           = nullptr;
440     mDCompModule          = nullptr;
441     mCreatedWithDeviceEXT = false;
442 
443     mDevice         = nullptr;
444     mDeviceContext  = nullptr;
445     mDeviceContext1 = nullptr;
446     mDeviceContext3 = nullptr;
447     mDxgiAdapter    = nullptr;
448     mDxgiFactory    = nullptr;
449 
450     ZeroMemory(&mAdapterDescription, sizeof(mAdapterDescription));
451 
452     const auto &attributes = mDisplay->getAttributeMap();
453 
454     if (mDisplay->getPlatform() == EGL_PLATFORM_ANGLE_ANGLE)
455     {
456         EGLint requestedMajorVersion = static_cast<EGLint>(
457             attributes.get(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, EGL_DONT_CARE));
458         EGLint requestedMinorVersion = static_cast<EGLint>(
459             attributes.get(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, EGL_DONT_CARE));
460 
461         if (requestedMajorVersion == EGL_DONT_CARE || requestedMajorVersion >= 11)
462         {
463             if (requestedMinorVersion == EGL_DONT_CARE || requestedMinorVersion >= 1)
464             {
465                 // This could potentially lead to failed context creation if done on a system
466                 // without the platform update which installs DXGI 1.2. Currently, for Chrome users
467                 // D3D11 contexts are only created if the platform update is available, so this
468                 // should not cause any issues.
469                 mAvailableFeatureLevels.push_back(D3D_FEATURE_LEVEL_11_1);
470             }
471             if (requestedMinorVersion == EGL_DONT_CARE || requestedMinorVersion >= 0)
472             {
473                 mAvailableFeatureLevels.push_back(D3D_FEATURE_LEVEL_11_0);
474             }
475         }
476 
477         if (requestedMajorVersion == EGL_DONT_CARE || requestedMajorVersion >= 10)
478         {
479             if (requestedMinorVersion == EGL_DONT_CARE || requestedMinorVersion >= 1)
480             {
481                 mAvailableFeatureLevels.push_back(D3D_FEATURE_LEVEL_10_1);
482             }
483             if (requestedMinorVersion == EGL_DONT_CARE || requestedMinorVersion >= 0)
484             {
485                 mAvailableFeatureLevels.push_back(D3D_FEATURE_LEVEL_10_0);
486             }
487         }
488 
489         if (requestedMajorVersion == 9 && requestedMinorVersion == 3)
490         {
491             mAvailableFeatureLevels.push_back(D3D_FEATURE_LEVEL_9_3);
492         }
493 
494         EGLint requestedDeviceType = static_cast<EGLint>(attributes.get(
495             EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE));
496         switch (requestedDeviceType)
497         {
498             case EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE:
499                 mRequestedDriverType = D3D_DRIVER_TYPE_HARDWARE;
500                 break;
501 
502             case EGL_PLATFORM_ANGLE_DEVICE_TYPE_D3D_WARP_ANGLE:
503                 mRequestedDriverType = D3D_DRIVER_TYPE_WARP;
504                 break;
505 
506             case EGL_PLATFORM_ANGLE_DEVICE_TYPE_D3D_REFERENCE_ANGLE:
507                 mRequestedDriverType = D3D_DRIVER_TYPE_REFERENCE;
508                 break;
509 
510             case EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE:
511                 mRequestedDriverType = D3D_DRIVER_TYPE_NULL;
512                 break;
513 
514             default:
515                 UNREACHABLE();
516         }
517 
518         mCreateDebugDevice = ShouldUseDebugLayers(attributes);
519     }
520     else if (mDisplay->getPlatform() == EGL_PLATFORM_DEVICE_EXT)
521     {
522         ASSERT(mDisplay->getDevice() != nullptr);
523         mCreatedWithDeviceEXT = true;
524 
525         // Also set EGL_PLATFORM_ANGLE_ANGLE variables, in case they're used elsewhere in ANGLE
526         // mAvailableFeatureLevels defaults to empty
527         mRequestedDriverType = D3D_DRIVER_TYPE_UNKNOWN;
528     }
529 
530     const EGLenum presentPath = static_cast<EGLenum>(attributes.get(
531         EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE, EGL_EXPERIMENTAL_PRESENT_PATH_COPY_ANGLE));
532     mPresentPathFastEnabled   = (presentPath == EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE);
533 }
534 
~Renderer11()535 Renderer11::~Renderer11()
536 {
537     release();
538 }
539 
540 #ifndef __d3d11_1_h__
541 #    define D3D11_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET ((D3D11_MESSAGE_ID)3146081)
542 #endif
543 
initialize()544 egl::Error Renderer11::initialize()
545 {
546     HRESULT result = S_OK;
547 
548     ANGLE_TRY(initializeD3DDevice());
549 
550 #if !defined(ANGLE_ENABLE_WINDOWS_UWP)
551 #    if !ANGLE_SKIP_DXGI_1_2_CHECK
552     {
553         ANGLE_TRACE_EVENT0("gpu.angle", "Renderer11::initialize (DXGICheck)");
554         // In order to create a swap chain for an HWND owned by another process, DXGI 1.2 is
555         // required.
556         // The easiest way to check is to query for a IDXGIDevice2.
557         bool requireDXGI1_2 = false;
558         HWND hwnd           = WindowFromDC(mDisplay->getNativeDisplayId());
559         if (hwnd)
560         {
561             DWORD currentProcessId = GetCurrentProcessId();
562             DWORD wndProcessId;
563             GetWindowThreadProcessId(hwnd, &wndProcessId);
564             requireDXGI1_2 = (currentProcessId != wndProcessId);
565         }
566         else
567         {
568             requireDXGI1_2 = true;
569         }
570 
571         if (requireDXGI1_2)
572         {
573             IDXGIDevice2 *dxgiDevice2 = nullptr;
574             result = mDevice->QueryInterface(__uuidof(IDXGIDevice2), (void **)&dxgiDevice2);
575             if (FAILED(result))
576             {
577                 return egl::EglNotInitialized(D3D11_INIT_INCOMPATIBLE_DXGI)
578                        << "DXGI 1.2 required to present to HWNDs owned by another process.";
579             }
580             SafeRelease(dxgiDevice2);
581         }
582     }
583 #    endif
584 #endif
585 
586     {
587         ANGLE_TRACE_EVENT0("gpu.angle", "Renderer11::initialize (ComQueries)");
588         // Cast the DeviceContext to a DeviceContext1 and DeviceContext3.
589         // This could fail on Windows 7 without the Platform Update.
590         // Don't error in this case- just don't use mDeviceContext1 or mDeviceContext3.
591         mDeviceContext1 = d3d11::DynamicCastComObject<ID3D11DeviceContext1>(mDeviceContext);
592         mDeviceContext3 = d3d11::DynamicCastComObject<ID3D11DeviceContext3>(mDeviceContext);
593 
594         IDXGIDevice *dxgiDevice = nullptr;
595         result = mDevice->QueryInterface(__uuidof(IDXGIDevice), (void **)&dxgiDevice);
596 
597         if (FAILED(result))
598         {
599             return egl::EglNotInitialized(D3D11_INIT_OTHER_ERROR) << "Could not query DXGI device.";
600         }
601 
602         result = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&mDxgiAdapter);
603 
604         if (FAILED(result))
605         {
606             return egl::EglNotInitialized(D3D11_INIT_OTHER_ERROR)
607                    << "Could not retrieve DXGI adapter";
608         }
609 
610         SafeRelease(dxgiDevice);
611 
612         IDXGIAdapter2 *dxgiAdapter2 = d3d11::DynamicCastComObject<IDXGIAdapter2>(mDxgiAdapter);
613 
614         // On D3D_FEATURE_LEVEL_9_*, IDXGIAdapter::GetDesc returns "Software Adapter" for the
615         // description string.
616         // If DXGI1.2 is available then IDXGIAdapter2::GetDesc2 can be used to get the actual
617         // hardware values.
618         if (mRenderer11DeviceCaps.featureLevel <= D3D_FEATURE_LEVEL_9_3 && dxgiAdapter2 != nullptr)
619         {
620             DXGI_ADAPTER_DESC2 adapterDesc2 = {};
621             result                          = dxgiAdapter2->GetDesc2(&adapterDesc2);
622             if (SUCCEEDED(result))
623             {
624                 // Copy the contents of the DXGI_ADAPTER_DESC2 into mAdapterDescription (a
625                 // DXGI_ADAPTER_DESC).
626                 memcpy(mAdapterDescription.Description, adapterDesc2.Description,
627                        sizeof(mAdapterDescription.Description));
628                 mAdapterDescription.VendorId              = adapterDesc2.VendorId;
629                 mAdapterDescription.DeviceId              = adapterDesc2.DeviceId;
630                 mAdapterDescription.SubSysId              = adapterDesc2.SubSysId;
631                 mAdapterDescription.Revision              = adapterDesc2.Revision;
632                 mAdapterDescription.DedicatedVideoMemory  = adapterDesc2.DedicatedVideoMemory;
633                 mAdapterDescription.DedicatedSystemMemory = adapterDesc2.DedicatedSystemMemory;
634                 mAdapterDescription.SharedSystemMemory    = adapterDesc2.SharedSystemMemory;
635                 mAdapterDescription.AdapterLuid           = adapterDesc2.AdapterLuid;
636             }
637         }
638         else
639         {
640             result = mDxgiAdapter->GetDesc(&mAdapterDescription);
641         }
642 
643         SafeRelease(dxgiAdapter2);
644 
645         if (FAILED(result))
646         {
647             return egl::EglNotInitialized(D3D11_INIT_OTHER_ERROR)
648                    << "Could not read DXGI adaptor description.";
649         }
650 
651         memset(mDescription, 0, sizeof(mDescription));
652         wcstombs(mDescription, mAdapterDescription.Description, sizeof(mDescription) - 1);
653 
654         result = mDxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&mDxgiFactory);
655 
656         if (!mDxgiFactory || FAILED(result))
657         {
658             return egl::EglNotInitialized(D3D11_INIT_OTHER_ERROR)
659                    << "Could not create DXGI factory.";
660         }
661     }
662 
663     // Disable some spurious D3D11 debug warnings to prevent them from flooding the output log
664     if (mCreateDebugDevice)
665     {
666         ANGLE_TRACE_EVENT0("gpu.angle", "Renderer11::initialize (HideWarnings)");
667         ID3D11InfoQueue *infoQueue;
668         result = mDevice->QueryInterface(__uuidof(ID3D11InfoQueue), (void **)&infoQueue);
669 
670         if (SUCCEEDED(result))
671         {
672             D3D11_MESSAGE_ID hideMessages[] = {
673                 D3D11_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET,
674 
675                 // Robust access behaviour makes out of bounds messages safe
676                 D3D11_MESSAGE_ID_DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL,
677             };
678 
679             D3D11_INFO_QUEUE_FILTER filter = {};
680             filter.DenyList.NumIDs         = static_cast<unsigned int>(ArraySize(hideMessages));
681             filter.DenyList.pIDList        = hideMessages;
682 
683             infoQueue->AddStorageFilterEntries(&filter);
684             SafeRelease(infoQueue);
685         }
686     }
687 
688 #if !defined(NDEBUG)
689     mDebug = d3d11::DynamicCastComObject<ID3D11Debug>(mDevice);
690 #endif
691 
692     ANGLE_TRY(initializeDevice());
693 
694     return egl::NoError();
695 }
696 
callD3D11CreateDevice(PFN_D3D11_CREATE_DEVICE createDevice,bool debug)697 HRESULT Renderer11::callD3D11CreateDevice(PFN_D3D11_CREATE_DEVICE createDevice, bool debug)
698 {
699     angle::ComPtr<IDXGIAdapter> adapter;
700 
701     const egl::AttributeMap &attributes = mDisplay->getAttributeMap();
702     long high = static_cast<long>(attributes.get(EGL_PLATFORM_ANGLE_D3D_LUID_HIGH_ANGLE, 0));
703     unsigned long low =
704         static_cast<unsigned long>(attributes.get(EGL_PLATFORM_ANGLE_D3D_LUID_LOW_ANGLE, 0));
705 
706     if (high != 0 || low != 0)
707     {
708         angle::ComPtr<IDXGIFactory1> factory;
709         if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))
710         {
711             angle::ComPtr<IDXGIAdapter> temp;
712             for (UINT i = 0; SUCCEEDED(factory->EnumAdapters(i, &temp)); i++)
713             {
714                 DXGI_ADAPTER_DESC desc;
715                 if (SUCCEEDED(temp->GetDesc(&desc)) && desc.AdapterLuid.HighPart == high &&
716                     desc.AdapterLuid.LowPart == low)
717                 {
718                     adapter = temp;
719                     break;
720                 }
721             }
722         }
723     }
724 
725     // If adapter is not nullptr, the driver type must be D3D_DRIVER_TYPE_UNKNOWN or
726     // D3D11CreateDevice will return E_INVALIDARG.
727     return createDevice(
728         adapter.Get(), adapter ? D3D_DRIVER_TYPE_UNKNOWN : mRequestedDriverType, nullptr,
729         debug ? D3D11_CREATE_DEVICE_DEBUG : 0, mAvailableFeatureLevels.data(),
730         static_cast<unsigned int>(mAvailableFeatureLevels.size()), D3D11_SDK_VERSION, &mDevice,
731         &(mRenderer11DeviceCaps.featureLevel), &mDeviceContext);
732 }
733 
callD3D11On12CreateDevice(PFN_D3D12_CREATE_DEVICE createDevice12,PFN_D3D11ON12_CREATE_DEVICE createDevice11on12,bool debug)734 HRESULT Renderer11::callD3D11On12CreateDevice(PFN_D3D12_CREATE_DEVICE createDevice12,
735                                               PFN_D3D11ON12_CREATE_DEVICE createDevice11on12,
736                                               bool debug)
737 {
738     angle::ComPtr<IDXGIFactory4> factory;
739     HRESULT result = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
740     if (FAILED(result))
741     {
742         return result;
743     }
744 
745     if (mRequestedDriverType == D3D_DRIVER_TYPE_WARP)
746     {
747         angle::ComPtr<IDXGIAdapter> warpAdapter;
748         result = factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter));
749         if (SUCCEEDED(result))
750         {
751             result = createDevice12(warpAdapter.Get(), mAvailableFeatureLevels[0],
752                                     IID_PPV_ARGS(&mDevice12));
753         }
754     }
755     else
756     {
757         // Passing nullptr into pAdapter chooses the default adapter which will be the hardware
758         // adapter if it exists.
759         result = createDevice12(nullptr, mAvailableFeatureLevels[0], IID_PPV_ARGS(&mDevice12));
760     }
761 
762     if (SUCCEEDED(result))
763     {
764         D3D12_COMMAND_QUEUE_DESC queueDesc = {};
765         queueDesc.Flags                    = D3D12_COMMAND_QUEUE_FLAG_NONE;
766         queueDesc.Type                     = D3D12_COMMAND_LIST_TYPE_DIRECT;
767         result = mDevice12->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&mCommandQueue));
768     }
769 
770     if (SUCCEEDED(result))
771     {
772         result = createDevice11on12(
773             mDevice12.Get(), debug ? D3D11_CREATE_DEVICE_DEBUG : 0, mAvailableFeatureLevels.data(),
774             static_cast<unsigned int>(mAvailableFeatureLevels.size()),
775             reinterpret_cast<IUnknown **>(mCommandQueue.GetAddressOf()), 1 /* NumQueues */,
776             0 /* NodeMask */, &mDevice, &mDeviceContext, &(mRenderer11DeviceCaps.featureLevel));
777     }
778 
779     return result;
780 }
781 
initializeD3DDevice()782 egl::Error Renderer11::initializeD3DDevice()
783 {
784     HRESULT result             = S_OK;
785     bool createD3D11on12Device = false;
786 
787     if (!mCreatedWithDeviceEXT)
788     {
789 #if !defined(ANGLE_ENABLE_WINDOWS_UWP)
790         PFN_D3D11_CREATE_DEVICE D3D11CreateDevice         = nullptr;
791         PFN_D3D12_CREATE_DEVICE D3D12CreateDevice         = nullptr;
792         PFN_D3D11ON12_CREATE_DEVICE D3D11On12CreateDevice = nullptr;
793         {
794             ANGLE_TRACE_EVENT0("gpu.angle", "Renderer11::initialize (Load DLLs)");
795             mDxgiModule  = LoadLibrary(TEXT("dxgi.dll"));
796             mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
797             mDCompModule = LoadLibrary(TEXT("dcomp.dll"));
798 
799             // create the D3D11 device
800             ASSERT(mDevice == nullptr);
801 
802             const egl::AttributeMap &attributes = mDisplay->getAttributeMap();
803             createD3D11on12Device =
804                 attributes.get(EGL_PLATFORM_ANGLE_D3D11ON12_ANGLE, EGL_FALSE) == EGL_TRUE;
805 
806             if (createD3D11on12Device)
807             {
808                 mD3d12Module = LoadLibrary(TEXT("d3d12.dll"));
809                 if (mD3d12Module == nullptr)
810                 {
811                     return egl::EglNotInitialized(D3D11_INIT_MISSING_DEP)
812                            << "Could not load D3D12 library.";
813                 }
814 
815                 D3D12CreateDevice = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
816                     GetProcAddress(mD3d12Module, "D3D12CreateDevice"));
817                 if (D3D12CreateDevice == nullptr)
818                 {
819                     return egl::EglNotInitialized(D3D11_INIT_MISSING_DEP)
820                            << "Could not retrieve D3D12CreateDevice address.";
821                 }
822 
823                 D3D11On12CreateDevice = reinterpret_cast<PFN_D3D11ON12_CREATE_DEVICE>(
824                     GetProcAddress(mD3d11Module, "D3D11On12CreateDevice"));
825                 if (D3D11On12CreateDevice == nullptr)
826                 {
827                     return egl::EglNotInitialized(D3D11_INIT_MISSING_DEP)
828                            << "Could not retrieve D3D11On12CreateDevice address.";
829                 }
830             }
831             else
832             {
833                 if (mD3d11Module == nullptr || mDxgiModule == nullptr)
834                 {
835                     return egl::EglNotInitialized(D3D11_INIT_MISSING_DEP)
836                            << "Could not load D3D11 or DXGI library.";
837                 }
838 
839                 D3D11CreateDevice = reinterpret_cast<PFN_D3D11_CREATE_DEVICE>(
840                     GetProcAddress(mD3d11Module, "D3D11CreateDevice"));
841 
842                 if (D3D11CreateDevice == nullptr)
843                 {
844                     return egl::EglNotInitialized(D3D11_INIT_MISSING_DEP)
845                            << "Could not retrieve D3D11CreateDevice address.";
846                 }
847             }
848         }
849 #endif
850 
851         if (mCreateDebugDevice)
852         {
853             ANGLE_TRACE_EVENT0("gpu.angle", "D3D11CreateDevice (Debug)");
854             if (createD3D11on12Device)
855             {
856                 result = callD3D11On12CreateDevice(D3D12CreateDevice, D3D11On12CreateDevice, true);
857             }
858             else
859             {
860                 result = callD3D11CreateDevice(D3D11CreateDevice, true);
861             }
862 
863             if (result == E_INVALIDARG && mAvailableFeatureLevels.size() > 1u &&
864                 mAvailableFeatureLevels[0] == D3D_FEATURE_LEVEL_11_1)
865             {
866                 // On older Windows platforms, D3D11.1 is not supported which returns E_INVALIDARG.
867                 // Try again without passing D3D_FEATURE_LEVEL_11_1 in case we have other feature
868                 // levels to fall back on.
869                 mAvailableFeatureLevels.erase(mAvailableFeatureLevels.begin());
870                 if (createD3D11on12Device)
871                 {
872                     result =
873                         callD3D11On12CreateDevice(D3D12CreateDevice, D3D11On12CreateDevice, true);
874                 }
875                 else
876                 {
877                     result = callD3D11CreateDevice(D3D11CreateDevice, true);
878                 }
879             }
880 
881             if (!mDevice || FAILED(result))
882             {
883                 WARN() << "Failed creating Debug D3D11 device - falling back to release runtime.";
884             }
885         }
886 
887         if (!mDevice || FAILED(result))
888         {
889             ANGLE_TRACE_EVENT0("gpu.angle", "D3D11CreateDevice");
890             if (createD3D11on12Device)
891             {
892                 result = callD3D11On12CreateDevice(D3D12CreateDevice, D3D11On12CreateDevice, false);
893             }
894             else
895             {
896                 result = callD3D11CreateDevice(D3D11CreateDevice, false);
897             }
898 
899             if (result == E_INVALIDARG && mAvailableFeatureLevels.size() > 1u &&
900                 mAvailableFeatureLevels[0] == D3D_FEATURE_LEVEL_11_1)
901             {
902                 // On older Windows platforms, D3D11.1 is not supported which returns E_INVALIDARG.
903                 // Try again without passing D3D_FEATURE_LEVEL_11_1 in case we have other feature
904                 // levels to fall back on.
905                 mAvailableFeatureLevels.erase(mAvailableFeatureLevels.begin());
906                 if (createD3D11on12Device)
907                 {
908                     result =
909                         callD3D11On12CreateDevice(D3D12CreateDevice, D3D11On12CreateDevice, false);
910                 }
911                 else
912                 {
913                     result = callD3D11CreateDevice(D3D11CreateDevice, false);
914                 }
915             }
916 
917             // Cleanup done by destructor
918             if (!mDevice || FAILED(result))
919             {
920                 ANGLE_HISTOGRAM_SPARSE_SLOWLY("GPU.ANGLE.D3D11CreateDeviceError",
921                                               static_cast<int>(result));
922                 return egl::EglNotInitialized(D3D11_INIT_CREATEDEVICE_ERROR)
923                        << "Could not create D3D11 device.";
924             }
925         }
926     }
927     else
928     {
929         DeviceD3D *deviceD3D = GetImplAs<DeviceD3D>(mDisplay->getDevice());
930         ASSERT(deviceD3D != nullptr);
931 
932         // We should use the inputted D3D11 device instead
933         void *device = nullptr;
934         ANGLE_TRY(deviceD3D->getAttribute(mDisplay, EGL_D3D11_DEVICE_ANGLE, &device));
935 
936         ID3D11Device *d3dDevice = static_cast<ID3D11Device *>(device);
937         if (FAILED(d3dDevice->GetDeviceRemovedReason()))
938         {
939             return egl::EglNotInitialized() << "Inputted D3D11 device has been lost.";
940         }
941 
942         if (d3dDevice->GetFeatureLevel() < D3D_FEATURE_LEVEL_9_3)
943         {
944             return egl::EglNotInitialized()
945                    << "Inputted D3D11 device must be Feature Level 9_3 or greater.";
946         }
947 
948         // The Renderer11 adds a ref to the inputted D3D11 device, like D3D11CreateDevice does.
949         mDevice = d3dDevice;
950         mDevice->AddRef();
951         mDevice->GetImmediateContext(&mDeviceContext);
952         mRenderer11DeviceCaps.featureLevel = mDevice->GetFeatureLevel();
953     }
954 
955     mResourceManager11.setAllocationsInitialized(mCreateDebugDevice);
956 
957     d3d11::SetDebugName(mDeviceContext, "DeviceContext");
958 
959     mAnnotator.initialize(mDeviceContext);
960     gl::InitializeDebugAnnotations(&mAnnotator);
961 
962     return egl::NoError();
963 }
964 
setGlobalDebugAnnotator()965 void Renderer11::setGlobalDebugAnnotator()
966 {
967     gl::InitializeDebugAnnotations(&mAnnotator);
968 }
969 
970 // do any one-time device initialization
971 // NOTE: this is also needed after a device lost/reset
972 // to reset the scene status and ensure the default states are reset.
initializeDevice()973 egl::Error Renderer11::initializeDevice()
974 {
975     ANGLE_TRACE_EVENT0("gpu.angle", "Renderer11::initializeDevice");
976 
977     populateRenderer11DeviceCaps();
978 
979     mStateCache.clear();
980 
981     ASSERT(!mBlit);
982     mBlit = new Blit11(this);
983 
984     ASSERT(!mClear);
985     mClear = new Clear11(this);
986 
987     const auto &attributes = mDisplay->getAttributeMap();
988     // If automatic trim is enabled, DXGIDevice3::Trim( ) is called for the application
989     // automatically when an application is suspended by the OS. This feature is currently
990     // only supported for Windows Store applications.
991     EGLint enableAutoTrim = static_cast<EGLint>(
992         attributes.get(EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_FALSE));
993 
994     if (enableAutoTrim == EGL_TRUE)
995     {
996         ASSERT(!mTrim);
997         mTrim = new Trim11(this);
998     }
999 
1000     ASSERT(!mPixelTransfer);
1001     mPixelTransfer = new PixelTransfer11(this);
1002 
1003     // Gather stats on DXGI and D3D feature level
1004     ANGLE_HISTOGRAM_BOOLEAN("GPU.ANGLE.SupportsDXGI1_2", mRenderer11DeviceCaps.supportsDXGI1_2);
1005 
1006     ANGLEFeatureLevel angleFeatureLevel = GetANGLEFeatureLevel(mRenderer11DeviceCaps.featureLevel);
1007 
1008     // We don't actually request a 11_1 device, because of complications with the platform
1009     // update. Instead we check if the mDeviceContext1 pointer cast succeeded.
1010     // Note: we should support D3D11_0 always, but we aren't guaranteed to be at FL11_0
1011     // because the app can specify a lower version (such as 9_3) on Display creation.
1012     if (mDeviceContext1 != nullptr)
1013     {
1014         angleFeatureLevel = ANGLE_FEATURE_LEVEL_11_1;
1015     }
1016 
1017     ANGLE_HISTOGRAM_ENUMERATION("GPU.ANGLE.D3D11FeatureLevel", angleFeatureLevel,
1018                                 NUM_ANGLE_FEATURE_LEVELS);
1019 
1020     return egl::NoError();
1021 }
1022 
populateRenderer11DeviceCaps()1023 void Renderer11::populateRenderer11DeviceCaps()
1024 {
1025     HRESULT hr = S_OK;
1026 
1027     LARGE_INTEGER version;
1028     hr = mDxgiAdapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &version);
1029     if (FAILED(hr))
1030     {
1031         mRenderer11DeviceCaps.driverVersion.reset();
1032         ERR() << "Error querying driver version from DXGI Adapter.";
1033     }
1034     else
1035     {
1036         mRenderer11DeviceCaps.driverVersion = version;
1037     }
1038 
1039     if (mDeviceContext1)
1040     {
1041         D3D11_FEATURE_DATA_D3D11_OPTIONS d3d11Options;
1042         HRESULT result = mDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &d3d11Options,
1043                                                       sizeof(D3D11_FEATURE_DATA_D3D11_OPTIONS));
1044         if (SUCCEEDED(result))
1045         {
1046             mRenderer11DeviceCaps.supportsClearView = (d3d11Options.ClearView != FALSE);
1047             mRenderer11DeviceCaps.supportsConstantBufferOffsets =
1048                 (d3d11Options.ConstantBufferOffsetting != FALSE);
1049         }
1050     }
1051 
1052     if (mDeviceContext3)
1053     {
1054         D3D11_FEATURE_DATA_D3D11_OPTIONS3 d3d11Options3;
1055         HRESULT result = mDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &d3d11Options3,
1056                                                       sizeof(D3D11_FEATURE_DATA_D3D11_OPTIONS3));
1057         if (SUCCEEDED(result))
1058         {
1059             mRenderer11DeviceCaps.supportsVpRtIndexWriteFromVertexShader =
1060                 (d3d11Options3.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer == TRUE);
1061         }
1062     }
1063 
1064     mRenderer11DeviceCaps.supportsMultisampledDepthStencilSRVs =
1065         mRenderer11DeviceCaps.featureLevel > D3D_FEATURE_LEVEL_10_0;
1066 
1067     if (getFeatures().disableB5G6R5Support.enabled)
1068     {
1069         mRenderer11DeviceCaps.B5G6R5support    = 0;
1070         mRenderer11DeviceCaps.B5G6R5maxSamples = 0;
1071     }
1072     else
1073     {
1074         PopulateFormatDeviceCaps(mDevice, DXGI_FORMAT_B5G6R5_UNORM,
1075                                  &mRenderer11DeviceCaps.B5G6R5support,
1076                                  &mRenderer11DeviceCaps.B5G6R5maxSamples);
1077     }
1078 
1079     if (getFeatures().allowES3OnFL10_0.enabled)
1080     {
1081         mRenderer11DeviceCaps.allowES3OnFL10_0 = true;
1082     }
1083 
1084     PopulateFormatDeviceCaps(mDevice, DXGI_FORMAT_B4G4R4A4_UNORM,
1085                              &mRenderer11DeviceCaps.B4G4R4A4support,
1086                              &mRenderer11DeviceCaps.B4G4R4A4maxSamples);
1087     PopulateFormatDeviceCaps(mDevice, DXGI_FORMAT_B5G5R5A1_UNORM,
1088                              &mRenderer11DeviceCaps.B5G5R5A1support,
1089                              &mRenderer11DeviceCaps.B5G5R5A1maxSamples);
1090 
1091     IDXGIAdapter2 *dxgiAdapter2 = d3d11::DynamicCastComObject<IDXGIAdapter2>(mDxgiAdapter);
1092     mRenderer11DeviceCaps.supportsDXGI1_2 = (dxgiAdapter2 != nullptr);
1093     SafeRelease(dxgiAdapter2);
1094 }
1095 
generateSampleSetForEGLConfig(const gl::TextureCaps & colorBufferFormatCaps,const gl::TextureCaps & depthStencilBufferFormatCaps) const1096 gl::SupportedSampleSet Renderer11::generateSampleSetForEGLConfig(
1097     const gl::TextureCaps &colorBufferFormatCaps,
1098     const gl::TextureCaps &depthStencilBufferFormatCaps) const
1099 {
1100     gl::SupportedSampleSet sampleCounts;
1101 
1102     // Generate a new set from the set intersection of sample counts between the color and depth
1103     // format caps.
1104     std::set_intersection(colorBufferFormatCaps.sampleCounts.begin(),
1105                           colorBufferFormatCaps.sampleCounts.end(),
1106                           depthStencilBufferFormatCaps.sampleCounts.begin(),
1107                           depthStencilBufferFormatCaps.sampleCounts.end(),
1108                           std::inserter(sampleCounts, sampleCounts.begin()));
1109 
1110     // Format of GL_NONE results in no supported sample counts.
1111     // Add back the color sample counts to the supported sample set.
1112     if (depthStencilBufferFormatCaps.sampleCounts.empty())
1113     {
1114         sampleCounts = colorBufferFormatCaps.sampleCounts;
1115     }
1116     else if (colorBufferFormatCaps.sampleCounts.empty())
1117     {
1118         // Likewise, add back the depth sample counts to the supported sample set.
1119         sampleCounts = depthStencilBufferFormatCaps.sampleCounts;
1120     }
1121 
1122     // Always support 0 samples
1123     sampleCounts.insert(0);
1124 
1125     return sampleCounts;
1126 }
1127 
generateConfigs()1128 egl::ConfigSet Renderer11::generateConfigs()
1129 {
1130     std::vector<GLenum> colorBufferFormats;
1131 
1132     // 32-bit supported formats
1133     colorBufferFormats.push_back(GL_BGRA8_EXT);
1134     colorBufferFormats.push_back(GL_RGBA8_OES);
1135 
1136     // 24-bit supported formats
1137     colorBufferFormats.push_back(GL_RGB8_OES);
1138 
1139     if (mRenderer11DeviceCaps.featureLevel >= D3D_FEATURE_LEVEL_10_0)
1140     {
1141         // Additional high bit depth formats added in D3D 10.0
1142         // https://msdn.microsoft.com/en-us/library/windows/desktop/bb173064.aspx
1143         colorBufferFormats.push_back(GL_RGBA16F);
1144         colorBufferFormats.push_back(GL_RGB10_A2);
1145     }
1146 
1147     if (!mPresentPathFastEnabled)
1148     {
1149         // 16-bit supported formats
1150         // These aren't valid D3D11 swapchain formats, so don't expose them as configs
1151         // if present path fast is active
1152         colorBufferFormats.push_back(GL_RGBA4);
1153         colorBufferFormats.push_back(GL_RGB5_A1);
1154         colorBufferFormats.push_back(GL_RGB565);
1155     }
1156 
1157     static const GLenum depthStencilBufferFormats[] = {
1158         GL_NONE,           GL_DEPTH24_STENCIL8_OES, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT16,
1159         GL_STENCIL_INDEX8,
1160     };
1161 
1162     const gl::Caps &rendererCaps                  = getNativeCaps();
1163     const gl::TextureCapsMap &rendererTextureCaps = getNativeTextureCaps();
1164 
1165     const EGLint optimalSurfaceOrientation =
1166         mPresentPathFastEnabled ? 0 : EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE;
1167 
1168     egl::ConfigSet configs;
1169     for (GLenum colorBufferInternalFormat : colorBufferFormats)
1170     {
1171         const gl::TextureCaps &colorBufferFormatCaps =
1172             rendererTextureCaps.get(colorBufferInternalFormat);
1173         if (!colorBufferFormatCaps.renderbuffer)
1174         {
1175             ASSERT(!colorBufferFormatCaps.textureAttachment);
1176             continue;
1177         }
1178 
1179         for (GLenum depthStencilBufferInternalFormat : depthStencilBufferFormats)
1180         {
1181             const gl::TextureCaps &depthStencilBufferFormatCaps =
1182                 rendererTextureCaps.get(depthStencilBufferInternalFormat);
1183             if (!depthStencilBufferFormatCaps.renderbuffer &&
1184                 depthStencilBufferInternalFormat != GL_NONE)
1185             {
1186                 ASSERT(!depthStencilBufferFormatCaps.textureAttachment);
1187                 continue;
1188             }
1189 
1190             const gl::InternalFormat &colorBufferFormatInfo =
1191                 gl::GetSizedInternalFormatInfo(colorBufferInternalFormat);
1192             const gl::InternalFormat &depthStencilBufferFormatInfo =
1193                 gl::GetSizedInternalFormatInfo(depthStencilBufferInternalFormat);
1194             const gl::Version &maxVersion = getMaxSupportedESVersion();
1195 
1196             const gl::SupportedSampleSet sampleCounts =
1197                 generateSampleSetForEGLConfig(colorBufferFormatCaps, depthStencilBufferFormatCaps);
1198 
1199             for (GLuint sampleCount : sampleCounts)
1200             {
1201                 egl::Config config;
1202                 config.renderTargetFormat = colorBufferInternalFormat;
1203                 config.depthStencilFormat = depthStencilBufferInternalFormat;
1204                 config.bufferSize         = colorBufferFormatInfo.pixelBytes * 8;
1205                 config.redSize            = colorBufferFormatInfo.redBits;
1206                 config.greenSize          = colorBufferFormatInfo.greenBits;
1207                 config.blueSize           = colorBufferFormatInfo.blueBits;
1208                 config.luminanceSize      = colorBufferFormatInfo.luminanceBits;
1209                 config.alphaSize          = colorBufferFormatInfo.alphaBits;
1210                 config.alphaMaskSize      = 0;
1211                 config.bindToTextureRGB =
1212                     ((colorBufferFormatInfo.format == GL_RGB) && (sampleCount <= 1));
1213                 config.bindToTextureRGBA = (((colorBufferFormatInfo.format == GL_RGBA) ||
1214                                              (colorBufferFormatInfo.format == GL_BGRA_EXT)) &&
1215                                             (sampleCount <= 1));
1216                 config.colorBufferType   = EGL_RGB_BUFFER;
1217                 config.configCaveat      = EGL_NONE;
1218                 config.configID          = static_cast<EGLint>(configs.size() + 1);
1219 
1220                 // PresentPathFast may not be conformant
1221                 config.conformant = 0;
1222                 if (!mPresentPathFastEnabled)
1223                 {
1224                     // Can only support a conformant ES2 with feature level greater than 10.0.
1225                     if (mRenderer11DeviceCaps.featureLevel >= D3D_FEATURE_LEVEL_10_0)
1226                     {
1227                         config.conformant |= EGL_OPENGL_ES2_BIT;
1228                     }
1229 
1230                     // We can only support conformant ES3 on FL 10.1+
1231                     if (maxVersion.major >= 3)
1232                     {
1233                         config.conformant |= EGL_OPENGL_ES3_BIT_KHR;
1234                     }
1235                 }
1236 
1237                 config.depthSize         = depthStencilBufferFormatInfo.depthBits;
1238                 config.level             = 0;
1239                 config.matchNativePixmap = EGL_NONE;
1240                 config.maxPBufferWidth   = rendererCaps.max2DTextureSize;
1241                 config.maxPBufferHeight  = rendererCaps.max2DTextureSize;
1242                 config.maxPBufferPixels =
1243                     rendererCaps.max2DTextureSize * rendererCaps.max2DTextureSize;
1244                 config.maxSwapInterval  = 4;
1245                 config.minSwapInterval  = 0;
1246                 config.nativeRenderable = EGL_FALSE;
1247                 config.nativeVisualID   = 0;
1248                 config.nativeVisualType = EGL_NONE;
1249 
1250                 // Can't support ES3 at all without feature level 10.1
1251                 config.renderableType = EGL_OPENGL_ES2_BIT;
1252                 if (maxVersion.major >= 3)
1253                 {
1254                     config.renderableType |= EGL_OPENGL_ES3_BIT_KHR;
1255                 }
1256 
1257                 config.sampleBuffers = (sampleCount == 0) ? 0 : 1;
1258                 config.samples       = sampleCount;
1259                 config.stencilSize   = depthStencilBufferFormatInfo.stencilBits;
1260                 config.surfaceType =
1261                     EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
1262                 config.transparentType       = EGL_NONE;
1263                 config.transparentRedValue   = 0;
1264                 config.transparentGreenValue = 0;
1265                 config.transparentBlueValue  = 0;
1266                 config.optimalOrientation    = optimalSurfaceOrientation;
1267                 config.colorComponentType    = gl_egl::GLComponentTypeToEGLColorComponentType(
1268                     colorBufferFormatInfo.componentType);
1269 
1270                 configs.add(config);
1271             }
1272         }
1273     }
1274 
1275     ASSERT(configs.size() > 0);
1276     return configs;
1277 }
1278 
generateDisplayExtensions(egl::DisplayExtensions * outExtensions) const1279 void Renderer11::generateDisplayExtensions(egl::DisplayExtensions *outExtensions) const
1280 {
1281     outExtensions->createContextRobustness = true;
1282 
1283     if (getShareHandleSupport())
1284     {
1285         outExtensions->d3dShareHandleClientBuffer     = true;
1286         outExtensions->surfaceD3DTexture2DShareHandle = true;
1287     }
1288     outExtensions->d3dTextureClientBuffer = true;
1289     outExtensions->imageD3D11Texture      = true;
1290 
1291     outExtensions->keyedMutex          = true;
1292     outExtensions->querySurfacePointer = true;
1293     outExtensions->windowFixedSize     = true;
1294 
1295     // If present path fast is active then the surface orientation extension isn't supported
1296     outExtensions->surfaceOrientation = !mPresentPathFastEnabled;
1297 
1298     // D3D11 does not support present with dirty rectangles until DXGI 1.2.
1299     outExtensions->postSubBuffer = mRenderer11DeviceCaps.supportsDXGI1_2;
1300 
1301     outExtensions->image                 = true;
1302     outExtensions->imageBase             = true;
1303     outExtensions->glTexture2DImage      = true;
1304     outExtensions->glTextureCubemapImage = true;
1305     outExtensions->glRenderbufferImage   = true;
1306 
1307     outExtensions->stream                     = true;
1308     outExtensions->streamConsumerGLTexture    = true;
1309     outExtensions->streamConsumerGLTextureYUV = true;
1310     outExtensions->streamProducerD3DTexture   = true;
1311 
1312     outExtensions->flexibleSurfaceCompatibility = true;
1313     outExtensions->directComposition            = !!mDCompModule;
1314 
1315     // Contexts are virtualized so textures and semaphores can be shared globally
1316     outExtensions->displayTextureShareGroup   = true;
1317     outExtensions->displaySemaphoreShareGroup = true;
1318 
1319     // syncControlCHROMIUM requires direct composition.
1320     outExtensions->syncControlCHROMIUM = outExtensions->directComposition;
1321 
1322     // D3D11 can be used without a swap chain
1323     outExtensions->surfacelessContext = true;
1324 
1325     // All D3D feature levels support robust resource init
1326     outExtensions->robustResourceInitialization = true;
1327 
1328 #ifdef ANGLE_ENABLE_D3D11_COMPOSITOR_NATIVE_WINDOW
1329     // Compositor Native Window capabilies require WinVer >= 1803
1330     if (CompositorNativeWindow11::IsSupportedWinRelease())
1331     {
1332         outExtensions->windowsUIComposition = true;
1333     }
1334 #endif
1335 }
1336 
flush(Context11 * context11)1337 angle::Result Renderer11::flush(Context11 *context11)
1338 {
1339     mDeviceContext->Flush();
1340     return angle::Result::Continue;
1341 }
1342 
finish(Context11 * context11)1343 angle::Result Renderer11::finish(Context11 *context11)
1344 {
1345     if (!mSyncQuery.valid())
1346     {
1347         D3D11_QUERY_DESC queryDesc;
1348         queryDesc.Query     = D3D11_QUERY_EVENT;
1349         queryDesc.MiscFlags = 0;
1350 
1351         ANGLE_TRY(allocateResource(context11, queryDesc, &mSyncQuery));
1352     }
1353 
1354     mDeviceContext->End(mSyncQuery.get());
1355 
1356     HRESULT result       = S_OK;
1357     unsigned int attempt = 0;
1358     do
1359     {
1360         unsigned int flushFrequency = 100;
1361         UINT flags = (attempt % flushFrequency == 0) ? 0 : D3D11_ASYNC_GETDATA_DONOTFLUSH;
1362         attempt++;
1363 
1364         result = mDeviceContext->GetData(mSyncQuery.get(), nullptr, 0, flags);
1365         ANGLE_TRY_HR(context11, result, "Failed to get event query data");
1366 
1367         if (result == S_FALSE)
1368         {
1369             // Keep polling, but allow other threads to do something useful first
1370             ScheduleYield();
1371         }
1372 
1373         // Attempt is incremented before checking if we should test for device loss so that device
1374         // loss is not checked on the first iteration
1375         bool checkDeviceLost = (attempt % kPollingD3DDeviceLostCheckFrequency) == 0;
1376         if (checkDeviceLost && testDeviceLost())
1377         {
1378             mDisplay->notifyDeviceLost();
1379             ANGLE_CHECK(context11, false, "Device was lost while waiting for sync.",
1380                         GL_OUT_OF_MEMORY);
1381         }
1382     } while (result == S_FALSE);
1383 
1384     return angle::Result::Continue;
1385 }
1386 
isValidNativeWindow(EGLNativeWindowType window) const1387 bool Renderer11::isValidNativeWindow(EGLNativeWindowType window) const
1388 {
1389 #if defined(ANGLE_ENABLE_WINDOWS_UWP)
1390     if (NativeWindow11WinRT::IsValidNativeWindow(window))
1391     {
1392         return true;
1393     }
1394 #else
1395     if (NativeWindow11Win32::IsValidNativeWindow(window))
1396     {
1397         return true;
1398     }
1399 #endif
1400 
1401 #ifdef ANGLE_ENABLE_D3D11_COMPOSITOR_NATIVE_WINDOW
1402     static_assert(sizeof(ABI::Windows::UI::Composition::SpriteVisual *) == sizeof(HWND),
1403                   "Pointer size must match Window Handle size");
1404     if (CompositorNativeWindow11::IsValidNativeWindow(window))
1405     {
1406         return true;
1407     }
1408 #endif
1409 
1410     return false;
1411 }
1412 
createNativeWindow(EGLNativeWindowType window,const egl::Config * config,const egl::AttributeMap & attribs) const1413 NativeWindowD3D *Renderer11::createNativeWindow(EGLNativeWindowType window,
1414                                                 const egl::Config *config,
1415                                                 const egl::AttributeMap &attribs) const
1416 {
1417 #if defined(ANGLE_ENABLE_WINDOWS_UWP)
1418     if (window == nullptr || NativeWindow11WinRT::IsValidNativeWindow(window))
1419     {
1420         return new NativeWindow11WinRT(window, config->alphaSize > 0);
1421     }
1422 #else
1423     if (window == nullptr || NativeWindow11Win32::IsValidNativeWindow(window))
1424     {
1425         return new NativeWindow11Win32(
1426             window, config->alphaSize > 0,
1427             attribs.get(EGL_DIRECT_COMPOSITION_ANGLE, EGL_FALSE) == EGL_TRUE);
1428     }
1429 #endif
1430 
1431 #ifdef ANGLE_ENABLE_D3D11_COMPOSITOR_NATIVE_WINDOW
1432     if (CompositorNativeWindow11::IsValidNativeWindow(window))
1433     {
1434         return new CompositorNativeWindow11(window, config->alphaSize > 0);
1435     }
1436 #endif
1437 
1438     UNREACHABLE();
1439     return nullptr;
1440 }
1441 
getD3DTextureInfo(const egl::Config * configuration,IUnknown * texture,const egl::AttributeMap & attribs,EGLint * width,EGLint * height,GLsizei * samples,gl::Format * glFormat,const angle::Format ** angleFormat,UINT * arraySlice) const1442 egl::Error Renderer11::getD3DTextureInfo(const egl::Config *configuration,
1443                                          IUnknown *texture,
1444                                          const egl::AttributeMap &attribs,
1445                                          EGLint *width,
1446                                          EGLint *height,
1447                                          GLsizei *samples,
1448                                          gl::Format *glFormat,
1449                                          const angle::Format **angleFormat,
1450                                          UINT *arraySlice) const
1451 {
1452     angle::ComPtr<ID3D11Texture2D> d3dTexture =
1453         d3d11::DynamicCastComObjectToComPtr<ID3D11Texture2D>(texture);
1454     if (d3dTexture == nullptr)
1455     {
1456         return egl::EglBadParameter() << "client buffer is not a ID3D11Texture2D";
1457     }
1458 
1459     angle::ComPtr<ID3D11Device> textureDevice;
1460     d3dTexture->GetDevice(&textureDevice);
1461     if (textureDevice.Get() != mDevice)
1462     {
1463         return egl::EglBadParameter() << "Texture's device does not match.";
1464     }
1465 
1466     D3D11_TEXTURE2D_DESC desc = {};
1467     d3dTexture->GetDesc(&desc);
1468 
1469     EGLint imageWidth  = static_cast<EGLint>(desc.Width);
1470     EGLint imageHeight = static_cast<EGLint>(desc.Height);
1471 
1472     GLsizei sampleCount = static_cast<GLsizei>(desc.SampleDesc.Count);
1473     if (configuration && (configuration->samples != sampleCount))
1474     {
1475         // Both the texture and EGL config sample count may not be the same when multi-sampling
1476         // is disabled. The EGL sample count can be 0 but a D3D texture is always 1. Therefore,
1477         // we must only check for a invalid match when the EGL config is non-zero or the texture is
1478         // not one.
1479         if (configuration->samples != 0 || sampleCount != 1)
1480         {
1481             return egl::EglBadParameter() << "Texture's sample count does not match.";
1482         }
1483     }
1484 
1485     const angle::Format *textureAngleFormat = nullptr;
1486     GLenum sizedInternalFormat              = GL_NONE;
1487 
1488     // From table egl.restrictions in EGL_ANGLE_d3d_texture_client_buffer.
1489     if (desc.Format == DXGI_FORMAT_NV12 || desc.Format == DXGI_FORMAT_P010 ||
1490         desc.Format == DXGI_FORMAT_P016)
1491     {
1492         if (!attribs.contains(EGL_D3D11_TEXTURE_PLANE_ANGLE))
1493         {
1494             return egl::EglBadParameter()
1495                    << "EGL_D3D11_TEXTURE_PLANE_ANGLE must be specified for YUV textures.";
1496         }
1497 
1498         EGLint plane = attribs.getAsInt(EGL_D3D11_TEXTURE_PLANE_ANGLE);
1499 
1500         // P010 and P016 have the same memory layout, SRV/RTV format, etc.
1501         const bool isNV12 = (desc.Format == DXGI_FORMAT_NV12);
1502         if (plane == 0)
1503         {
1504             textureAngleFormat = isNV12 ? &angle::Format::Get(angle::FormatID::R8_UNORM)
1505                                         : &angle::Format::Get(angle::FormatID::R16_UNORM);
1506         }
1507         else if (plane == 1)
1508         {
1509             textureAngleFormat = isNV12 ? &angle::Format::Get(angle::FormatID::R8G8_UNORM)
1510                                         : &angle::Format::Get(angle::FormatID::R16G16_UNORM);
1511             imageWidth /= 2;
1512             imageHeight /= 2;
1513         }
1514         else
1515         {
1516             return egl::EglBadParameter() << "Invalid client buffer texture plane: " << plane;
1517         }
1518 
1519         ASSERT(textureAngleFormat);
1520         sizedInternalFormat = textureAngleFormat->glInternalFormat;
1521     }
1522     else
1523     {
1524         switch (desc.Format)
1525         {
1526             case DXGI_FORMAT_R8G8B8A8_UNORM:
1527             case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
1528             case DXGI_FORMAT_R8G8B8A8_TYPELESS:
1529             case DXGI_FORMAT_B8G8R8A8_UNORM:
1530             case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
1531             case DXGI_FORMAT_B8G8R8A8_TYPELESS:
1532             case DXGI_FORMAT_R16G16B16A16_FLOAT:
1533             case DXGI_FORMAT_R32G32B32A32_FLOAT:
1534             case DXGI_FORMAT_R10G10B10A2_UNORM:
1535                 break;
1536 
1537             default:
1538                 return egl::EglBadParameter()
1539                        << "Invalid client buffer texture format: " << desc.Format;
1540         }
1541 
1542         textureAngleFormat = &d3d11_angle::GetFormat(desc.Format);
1543         ASSERT(textureAngleFormat);
1544 
1545         sizedInternalFormat = textureAngleFormat->glInternalFormat;
1546 
1547         if (attribs.contains(EGL_TEXTURE_INTERNAL_FORMAT_ANGLE))
1548         {
1549             const GLenum internalFormat =
1550                 static_cast<GLenum>(attribs.get(EGL_TEXTURE_INTERNAL_FORMAT_ANGLE));
1551             switch (internalFormat)
1552             {
1553                 case GL_RGBA:
1554                 case GL_BGRA_EXT:
1555                 case GL_RGB:
1556                     break;
1557                 default:
1558                     return egl::EglBadParameter()
1559                            << "Invalid client buffer texture internal format: " << std::hex
1560                            << internalFormat;
1561             }
1562 
1563             const GLenum type = gl::GetSizedInternalFormatInfo(sizedInternalFormat).type;
1564 
1565             const auto format = gl::Format(internalFormat, type);
1566             if (!format.valid())
1567             {
1568                 return egl::EglBadParameter()
1569                        << "Invalid client buffer texture internal format: " << std::hex
1570                        << internalFormat;
1571             }
1572 
1573             sizedInternalFormat = format.info->sizedInternalFormat;
1574         }
1575     }
1576 
1577     UINT textureArraySlice =
1578         static_cast<UINT>(attribs.getAsInt(EGL_D3D11_TEXTURE_ARRAY_SLICE_ANGLE, 0));
1579     if (textureArraySlice >= desc.ArraySize)
1580     {
1581         return egl::EglBadParameter()
1582                << "Invalid client buffer texture array slice: " << textureArraySlice;
1583     }
1584 
1585     if (width)
1586     {
1587         *width = imageWidth;
1588     }
1589     if (height)
1590     {
1591         *height = imageHeight;
1592     }
1593 
1594     if (samples)
1595     {
1596         // EGL samples 0 corresponds to D3D11 sample count 1.
1597         *samples = sampleCount != 1 ? sampleCount : 0;
1598     }
1599 
1600     if (glFormat)
1601     {
1602         *glFormat = gl::Format(sizedInternalFormat);
1603     }
1604 
1605     if (angleFormat)
1606     {
1607         *angleFormat = textureAngleFormat;
1608     }
1609 
1610     if (arraySlice)
1611     {
1612         *arraySlice = textureArraySlice;
1613     }
1614 
1615     return egl::NoError();
1616 }
1617 
validateShareHandle(const egl::Config * config,HANDLE shareHandle,const egl::AttributeMap & attribs) const1618 egl::Error Renderer11::validateShareHandle(const egl::Config *config,
1619                                            HANDLE shareHandle,
1620                                            const egl::AttributeMap &attribs) const
1621 {
1622     if (shareHandle == nullptr)
1623     {
1624         return egl::EglBadParameter() << "NULL share handle.";
1625     }
1626 
1627     ID3D11Resource *tempResource11 = nullptr;
1628     HRESULT result = mDevice->OpenSharedResource(shareHandle, __uuidof(ID3D11Resource),
1629                                                  (void **)&tempResource11);
1630     if (FAILED(result))
1631     {
1632         return egl::EglBadParameter() << "Failed to open share handle, " << gl::FmtHR(result);
1633     }
1634 
1635     ID3D11Texture2D *texture2D = d3d11::DynamicCastComObject<ID3D11Texture2D>(tempResource11);
1636     SafeRelease(tempResource11);
1637 
1638     if (texture2D == nullptr)
1639     {
1640         return egl::EglBadParameter()
1641                << "Failed to query ID3D11Texture2D object from share handle.";
1642     }
1643 
1644     D3D11_TEXTURE2D_DESC desc = {};
1645     texture2D->GetDesc(&desc);
1646     SafeRelease(texture2D);
1647 
1648     EGLint width  = attribs.getAsInt(EGL_WIDTH, 0);
1649     EGLint height = attribs.getAsInt(EGL_HEIGHT, 0);
1650     ASSERT(width != 0 && height != 0);
1651 
1652     const d3d11::Format &backbufferFormatInfo =
1653         d3d11::Format::Get(config->renderTargetFormat, getRenderer11DeviceCaps());
1654 
1655     if (desc.Width != static_cast<UINT>(width) || desc.Height != static_cast<UINT>(height) ||
1656         desc.Format != backbufferFormatInfo.texFormat || desc.MipLevels != 1 || desc.ArraySize != 1)
1657     {
1658         return egl::EglBadParameter() << "Invalid texture parameters in share handle texture.";
1659     }
1660 
1661     return egl::NoError();
1662 }
1663 
createSwapChain(NativeWindowD3D * nativeWindow,HANDLE shareHandle,IUnknown * d3dTexture,GLenum backBufferFormat,GLenum depthBufferFormat,EGLint orientation,EGLint samples)1664 SwapChainD3D *Renderer11::createSwapChain(NativeWindowD3D *nativeWindow,
1665                                           HANDLE shareHandle,
1666                                           IUnknown *d3dTexture,
1667                                           GLenum backBufferFormat,
1668                                           GLenum depthBufferFormat,
1669                                           EGLint orientation,
1670                                           EGLint samples)
1671 {
1672     return new SwapChain11(this, GetAs<NativeWindow11>(nativeWindow), shareHandle, d3dTexture,
1673                            backBufferFormat, depthBufferFormat, orientation, samples);
1674 }
1675 
getD3DDevice()1676 void *Renderer11::getD3DDevice()
1677 {
1678     return mDevice;
1679 }
1680 
drawWithGeometryShaderAndTransformFeedback(Context11 * context11,gl::PrimitiveMode mode,UINT instanceCount,UINT vertexCount)1681 angle::Result Renderer11::drawWithGeometryShaderAndTransformFeedback(Context11 *context11,
1682                                                                      gl::PrimitiveMode mode,
1683                                                                      UINT instanceCount,
1684                                                                      UINT vertexCount)
1685 {
1686     const gl::State &glState = context11->getState();
1687     ProgramD3D *programD3D   = mStateManager.getProgramD3D();
1688 
1689     // Since we use a geometry if-and-only-if we rewrite vertex streams, transform feedback
1690     // won't get the correct output. To work around this, draw with *only* the stream out
1691     // first (no pixel shader) to feed the stream out buffers and then draw again with the
1692     // geometry shader + pixel shader to rasterize the primitives.
1693     mStateManager.setPixelShader(nullptr);
1694 
1695     if (instanceCount > 0)
1696     {
1697         mDeviceContext->DrawInstanced(vertexCount, instanceCount, 0, 0);
1698     }
1699     else
1700     {
1701         mDeviceContext->Draw(vertexCount, 0);
1702     }
1703 
1704     rx::ShaderExecutableD3D *pixelExe = nullptr;
1705     ANGLE_TRY(programD3D->getPixelExecutableForCachedOutputLayout(context11, &pixelExe, nullptr));
1706 
1707     // Skip the draw call if rasterizer discard is enabled (or no fragment shader).
1708     if (!pixelExe || glState.getRasterizerState().rasterizerDiscard)
1709     {
1710         return angle::Result::Continue;
1711     }
1712 
1713     mStateManager.setPixelShader(&GetAs<ShaderExecutable11>(pixelExe)->getPixelShader());
1714 
1715     // Retrieve the geometry shader.
1716     rx::ShaderExecutableD3D *geometryExe = nullptr;
1717     ANGLE_TRY(programD3D->getGeometryExecutableForPrimitiveType(context11, glState, mode,
1718                                                                 &geometryExe, nullptr));
1719 
1720     mStateManager.setGeometryShader(&GetAs<ShaderExecutable11>(geometryExe)->getGeometryShader());
1721 
1722     if (instanceCount > 0)
1723     {
1724         mDeviceContext->DrawInstanced(vertexCount, instanceCount, 0, 0);
1725     }
1726     else
1727     {
1728         mDeviceContext->Draw(vertexCount, 0);
1729     }
1730 
1731     return angle::Result::Continue;
1732 }
1733 
drawArrays(const gl::Context * context,gl::PrimitiveMode mode,GLint firstVertex,GLsizei vertexCount,GLsizei instanceCount,GLuint baseInstance)1734 angle::Result Renderer11::drawArrays(const gl::Context *context,
1735                                      gl::PrimitiveMode mode,
1736                                      GLint firstVertex,
1737                                      GLsizei vertexCount,
1738                                      GLsizei instanceCount,
1739                                      GLuint baseInstance)
1740 {
1741     if (mStateManager.getCullEverything())
1742     {
1743         return angle::Result::Continue;
1744     }
1745 
1746     ProgramD3D *programD3D        = mStateManager.getProgramD3D();
1747     GLsizei adjustedInstanceCount = GetAdjustedInstanceCount(programD3D, instanceCount);
1748 
1749     // Note: vertex indexes can be arbitrarily large.
1750     UINT clampedVertexCount = gl::GetClampedVertexCount<UINT>(vertexCount);
1751 
1752     const auto &glState = context->getState();
1753     if (glState.getCurrentTransformFeedback() && glState.isTransformFeedbackActiveUnpaused())
1754     {
1755         ANGLE_TRY(markTransformFeedbackUsage(context));
1756 
1757         if (programD3D->usesGeometryShader(glState, mode))
1758         {
1759             return drawWithGeometryShaderAndTransformFeedback(
1760                 GetImplAs<Context11>(context), mode, adjustedInstanceCount, clampedVertexCount);
1761         }
1762     }
1763 
1764     switch (mode)
1765     {
1766         case gl::PrimitiveMode::LineLoop:
1767             return drawLineLoop(context, clampedVertexCount, gl::DrawElementsType::InvalidEnum,
1768                                 nullptr, 0, adjustedInstanceCount);
1769         case gl::PrimitiveMode::TriangleFan:
1770             return drawTriangleFan(context, clampedVertexCount, gl::DrawElementsType::InvalidEnum,
1771                                    nullptr, 0, adjustedInstanceCount);
1772         case gl::PrimitiveMode::Points:
1773             if (getFeatures().useInstancedPointSpriteEmulation.enabled)
1774             {
1775                 // This code should not be reachable by multi-view programs.
1776                 ASSERT(programD3D->getState().usesMultiview() == false);
1777 
1778                 // If the shader is writing to gl_PointSize, then pointsprites are being rendered.
1779                 // Emulating instanced point sprites for FL9_3 requires the topology to be
1780                 // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST and DrawIndexedInstanced is called instead.
1781                 if (adjustedInstanceCount == 0)
1782                 {
1783                     mDeviceContext->DrawIndexedInstanced(6, clampedVertexCount, 0, 0, baseInstance);
1784                     return angle::Result::Continue;
1785                 }
1786 
1787                 // If pointsprite emulation is used with glDrawArraysInstanced then we need to take
1788                 // a less efficent code path. Instanced rendering of emulated pointsprites requires
1789                 // a loop to draw each batch of points. An offset into the instanced data buffer is
1790                 // calculated and applied on each iteration to ensure all instances are rendered
1791                 // correctly. Each instance being rendered requires the inputlayout cache to reapply
1792                 // buffers and offsets.
1793                 for (GLsizei i = 0; i < instanceCount; i++)
1794                 {
1795                     ANGLE_TRY(mStateManager.updateVertexOffsetsForPointSpritesEmulation(
1796                         context, firstVertex, i));
1797                     mDeviceContext->DrawIndexedInstanced(6, clampedVertexCount, 0, 0, baseInstance);
1798                 }
1799 
1800                 // This required by updateVertexOffsets... above but is outside of the loop for
1801                 // speed.
1802                 mStateManager.invalidateVertexBuffer();
1803                 return angle::Result::Continue;
1804             }
1805             break;
1806         default:
1807             break;
1808     }
1809 
1810     // "Normal" draw case.
1811     if (adjustedInstanceCount == 0)
1812     {
1813         mDeviceContext->Draw(clampedVertexCount, 0);
1814     }
1815     else
1816     {
1817         mDeviceContext->DrawInstanced(clampedVertexCount, adjustedInstanceCount, 0, baseInstance);
1818     }
1819     return angle::Result::Continue;
1820 }
1821 
drawElements(const gl::Context * context,gl::PrimitiveMode mode,GLint startVertex,GLsizei indexCount,gl::DrawElementsType indexType,const void * indices,GLsizei instanceCount,GLint baseVertex,GLuint baseInstance)1822 angle::Result Renderer11::drawElements(const gl::Context *context,
1823                                        gl::PrimitiveMode mode,
1824                                        GLint startVertex,
1825                                        GLsizei indexCount,
1826                                        gl::DrawElementsType indexType,
1827                                        const void *indices,
1828                                        GLsizei instanceCount,
1829                                        GLint baseVertex,
1830                                        GLuint baseInstance)
1831 {
1832     if (mStateManager.getCullEverything())
1833     {
1834         return angle::Result::Continue;
1835     }
1836 
1837     // Transform feedback is not allowed for DrawElements, this error should have been caught at the
1838     // API validation layer.
1839     const gl::State &glState = context->getState();
1840     ASSERT(!glState.isTransformFeedbackActiveUnpaused());
1841 
1842     // If this draw call is coming from an indirect call, offset by the indirect call's base vertex.
1843     GLint baseVertexAdjusted = baseVertex - startVertex;
1844 
1845     const ProgramD3D *programD3D  = mStateManager.getProgramD3D();
1846     GLsizei adjustedInstanceCount = GetAdjustedInstanceCount(programD3D, instanceCount);
1847 
1848     if (mode == gl::PrimitiveMode::LineLoop)
1849     {
1850         return drawLineLoop(context, indexCount, indexType, indices, baseVertexAdjusted,
1851                             adjustedInstanceCount);
1852     }
1853 
1854     if (mode == gl::PrimitiveMode::TriangleFan)
1855     {
1856         return drawTriangleFan(context, indexCount, indexType, indices, baseVertexAdjusted,
1857                                adjustedInstanceCount);
1858     }
1859 
1860     if (mode != gl::PrimitiveMode::Points || !programD3D->usesInstancedPointSpriteEmulation())
1861     {
1862         if (adjustedInstanceCount == 0)
1863         {
1864             mDeviceContext->DrawIndexed(indexCount, 0, baseVertexAdjusted);
1865         }
1866         else
1867         {
1868             mDeviceContext->DrawIndexedInstanced(indexCount, adjustedInstanceCount, 0,
1869                                                  baseVertexAdjusted, baseInstance);
1870         }
1871         return angle::Result::Continue;
1872     }
1873 
1874     // This code should not be reachable by multi-view programs.
1875     ASSERT(programD3D->getState().usesMultiview() == false);
1876 
1877     // If the shader is writing to gl_PointSize, then pointsprites are being rendered.
1878     // Emulating instanced point sprites for FL9_3 requires the topology to be
1879     // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST and DrawIndexedInstanced is called instead.
1880     //
1881     // The count parameter passed to drawElements represents the total number of instances to be
1882     // rendered. Each instance is referenced by the bound index buffer from the the caller.
1883     //
1884     // Indexed pointsprite emulation replicates data for duplicate entries found in the index
1885     // buffer. This is not an efficent rendering mechanism and is only used on downlevel renderers
1886     // that do not support geometry shaders.
1887     if (instanceCount == 0)
1888     {
1889         mDeviceContext->DrawIndexedInstanced(6, indexCount, 0, baseVertexAdjusted, baseInstance);
1890         return angle::Result::Continue;
1891     }
1892 
1893     // If pointsprite emulation is used with glDrawElementsInstanced then we need to take a less
1894     // efficent code path. Instanced rendering of emulated pointsprites requires a loop to draw each
1895     // batch of points. An offset into the instanced data buffer is calculated and applied on each
1896     // iteration to ensure all instances are rendered correctly.
1897     gl::IndexRange indexRange;
1898     ANGLE_TRY(glState.getVertexArray()->getIndexRange(context, indexType, indexCount, indices,
1899                                                       &indexRange));
1900 
1901     UINT clampedVertexCount = gl::clampCast<UINT>(indexRange.vertexCount());
1902 
1903     // Each instance being rendered requires the inputlayout cache to reapply buffers and offsets.
1904     for (GLsizei i = 0; i < instanceCount; i++)
1905     {
1906         ANGLE_TRY(
1907             mStateManager.updateVertexOffsetsForPointSpritesEmulation(context, startVertex, i));
1908         mDeviceContext->DrawIndexedInstanced(6, clampedVertexCount, 0, baseVertexAdjusted,
1909                                              baseInstance);
1910     }
1911     mStateManager.invalidateVertexBuffer();
1912     return angle::Result::Continue;
1913 }
1914 
drawArraysIndirect(const gl::Context * context,const void * indirect)1915 angle::Result Renderer11::drawArraysIndirect(const gl::Context *context, const void *indirect)
1916 {
1917     if (mStateManager.getCullEverything())
1918     {
1919         return angle::Result::Continue;
1920     }
1921 
1922     const gl::State &glState = context->getState();
1923     ASSERT(!glState.isTransformFeedbackActiveUnpaused());
1924 
1925     gl::Buffer *drawIndirectBuffer = glState.getTargetBuffer(gl::BufferBinding::DrawIndirect);
1926     ASSERT(drawIndirectBuffer);
1927     Buffer11 *storage = GetImplAs<Buffer11>(drawIndirectBuffer);
1928 
1929     uintptr_t offset = reinterpret_cast<uintptr_t>(indirect);
1930 
1931     ID3D11Buffer *buffer = nullptr;
1932     ANGLE_TRY(storage->getBuffer(context, BUFFER_USAGE_INDIRECT, &buffer));
1933     mDeviceContext->DrawInstancedIndirect(buffer, static_cast<unsigned int>(offset));
1934     return angle::Result::Continue;
1935 }
1936 
drawElementsIndirect(const gl::Context * context,const void * indirect)1937 angle::Result Renderer11::drawElementsIndirect(const gl::Context *context, const void *indirect)
1938 {
1939     if (mStateManager.getCullEverything())
1940     {
1941         return angle::Result::Continue;
1942     }
1943 
1944     const gl::State &glState = context->getState();
1945     ASSERT(!glState.isTransformFeedbackActiveUnpaused());
1946 
1947     gl::Buffer *drawIndirectBuffer = glState.getTargetBuffer(gl::BufferBinding::DrawIndirect);
1948     ASSERT(drawIndirectBuffer);
1949     Buffer11 *storage = GetImplAs<Buffer11>(drawIndirectBuffer);
1950     uintptr_t offset  = reinterpret_cast<uintptr_t>(indirect);
1951 
1952     ID3D11Buffer *buffer = nullptr;
1953     ANGLE_TRY(storage->getBuffer(context, BUFFER_USAGE_INDIRECT, &buffer));
1954     mDeviceContext->DrawIndexedInstancedIndirect(buffer, static_cast<unsigned int>(offset));
1955     return angle::Result::Continue;
1956 }
1957 
drawLineLoop(const gl::Context * context,GLuint count,gl::DrawElementsType type,const void * indexPointer,int baseVertex,int instances)1958 angle::Result Renderer11::drawLineLoop(const gl::Context *context,
1959                                        GLuint count,
1960                                        gl::DrawElementsType type,
1961                                        const void *indexPointer,
1962                                        int baseVertex,
1963                                        int instances)
1964 {
1965     const gl::State &glState       = context->getState();
1966     gl::VertexArray *vao           = glState.getVertexArray();
1967     gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer();
1968 
1969     const void *indices = indexPointer;
1970 
1971     // Get the raw indices for an indexed draw
1972     if (type != gl::DrawElementsType::InvalidEnum && elementArrayBuffer)
1973     {
1974         BufferD3D *storage = GetImplAs<BufferD3D>(elementArrayBuffer);
1975         intptr_t offset    = reinterpret_cast<intptr_t>(indices);
1976 
1977         const uint8_t *bufferData = nullptr;
1978         ANGLE_TRY(storage->getData(context, &bufferData));
1979 
1980         indices = bufferData + offset;
1981     }
1982 
1983     if (!mLineLoopIB)
1984     {
1985         mLineLoopIB = new StreamingIndexBufferInterface(this);
1986         ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, INITIAL_INDEX_BUFFER_SIZE,
1987                                                   gl::DrawElementsType::UnsignedInt));
1988     }
1989 
1990     // Checked by Renderer11::applyPrimitiveType
1991     bool indexCheck = static_cast<unsigned int>(count) + 1 >
1992                       (std::numeric_limits<unsigned int>::max() / sizeof(unsigned int));
1993     ANGLE_CHECK(GetImplAs<Context11>(context), !indexCheck,
1994                 "Failed to create a 32-bit looping index buffer for "
1995                 "GL_LINE_LOOP, too many indices required.",
1996                 GL_OUT_OF_MEMORY);
1997 
1998     GetLineLoopIndices(indices, type, static_cast<GLuint>(count),
1999                        glState.isPrimitiveRestartEnabled(), &mScratchIndexDataBuffer);
2000 
2001     unsigned int spaceNeeded =
2002         static_cast<unsigned int>(sizeof(GLuint) * mScratchIndexDataBuffer.size());
2003     ANGLE_TRY(
2004         mLineLoopIB->reserveBufferSpace(context, spaceNeeded, gl::DrawElementsType::UnsignedInt));
2005 
2006     void *mappedMemory = nullptr;
2007     unsigned int offset;
2008     ANGLE_TRY(mLineLoopIB->mapBuffer(context, spaceNeeded, &mappedMemory, &offset));
2009 
2010     // Copy over the converted index data.
2011     memcpy(mappedMemory, &mScratchIndexDataBuffer[0],
2012            sizeof(GLuint) * mScratchIndexDataBuffer.size());
2013 
2014     ANGLE_TRY(mLineLoopIB->unmapBuffer(context));
2015 
2016     IndexBuffer11 *indexBuffer          = GetAs<IndexBuffer11>(mLineLoopIB->getIndexBuffer());
2017     const d3d11::Buffer &d3dIndexBuffer = indexBuffer->getBuffer();
2018     DXGI_FORMAT indexFormat             = indexBuffer->getIndexFormat();
2019 
2020     mStateManager.setIndexBuffer(d3dIndexBuffer.get(), indexFormat, offset);
2021 
2022     UINT indexCount = static_cast<UINT>(mScratchIndexDataBuffer.size());
2023 
2024     if (instances > 0)
2025     {
2026         mDeviceContext->DrawIndexedInstanced(indexCount, instances, 0, baseVertex, 0);
2027     }
2028     else
2029     {
2030         mDeviceContext->DrawIndexed(indexCount, 0, baseVertex);
2031     }
2032 
2033     return angle::Result::Continue;
2034 }
2035 
drawTriangleFan(const gl::Context * context,GLuint count,gl::DrawElementsType type,const void * indices,int baseVertex,int instances)2036 angle::Result Renderer11::drawTriangleFan(const gl::Context *context,
2037                                           GLuint count,
2038                                           gl::DrawElementsType type,
2039                                           const void *indices,
2040                                           int baseVertex,
2041                                           int instances)
2042 {
2043     const gl::State &glState       = context->getState();
2044     gl::VertexArray *vao           = glState.getVertexArray();
2045     gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer();
2046 
2047     const void *indexPointer = indices;
2048 
2049     // Get the raw indices for an indexed draw
2050     if (type != gl::DrawElementsType::InvalidEnum && elementArrayBuffer)
2051     {
2052         BufferD3D *storage = GetImplAs<BufferD3D>(elementArrayBuffer);
2053         intptr_t offset    = reinterpret_cast<intptr_t>(indices);
2054 
2055         const uint8_t *bufferData = nullptr;
2056         ANGLE_TRY(storage->getData(context, &bufferData));
2057 
2058         indexPointer = bufferData + offset;
2059     }
2060 
2061     if (!mTriangleFanIB)
2062     {
2063         mTriangleFanIB = new StreamingIndexBufferInterface(this);
2064         ANGLE_TRY(mTriangleFanIB->reserveBufferSpace(context, INITIAL_INDEX_BUFFER_SIZE,
2065                                                      gl::DrawElementsType::UnsignedInt));
2066     }
2067 
2068     // Checked by Renderer11::applyPrimitiveType
2069     ASSERT(count >= 3);
2070 
2071     const GLuint numTris = count - 2;
2072 
2073     bool indexCheck =
2074         (numTris > std::numeric_limits<unsigned int>::max() / (sizeof(unsigned int) * 3));
2075     ANGLE_CHECK(GetImplAs<Context11>(context), !indexCheck,
2076                 "Failed to create a scratch index buffer for GL_TRIANGLE_FAN, "
2077                 "too many indices required.",
2078                 GL_OUT_OF_MEMORY);
2079 
2080     GetTriFanIndices(indexPointer, type, count, glState.isPrimitiveRestartEnabled(),
2081                      &mScratchIndexDataBuffer);
2082 
2083     const unsigned int spaceNeeded =
2084         static_cast<unsigned int>(mScratchIndexDataBuffer.size() * sizeof(unsigned int));
2085     ANGLE_TRY(mTriangleFanIB->reserveBufferSpace(context, spaceNeeded,
2086                                                  gl::DrawElementsType::UnsignedInt));
2087 
2088     void *mappedMemory = nullptr;
2089     unsigned int offset;
2090     ANGLE_TRY(mTriangleFanIB->mapBuffer(context, spaceNeeded, &mappedMemory, &offset));
2091 
2092     memcpy(mappedMemory, &mScratchIndexDataBuffer[0], spaceNeeded);
2093 
2094     ANGLE_TRY(mTriangleFanIB->unmapBuffer(context));
2095 
2096     IndexBuffer11 *indexBuffer          = GetAs<IndexBuffer11>(mTriangleFanIB->getIndexBuffer());
2097     const d3d11::Buffer &d3dIndexBuffer = indexBuffer->getBuffer();
2098     DXGI_FORMAT indexFormat             = indexBuffer->getIndexFormat();
2099 
2100     mStateManager.setIndexBuffer(d3dIndexBuffer.get(), indexFormat, offset);
2101 
2102     UINT indexCount = static_cast<UINT>(mScratchIndexDataBuffer.size());
2103 
2104     if (instances > 0)
2105     {
2106         mDeviceContext->DrawIndexedInstanced(indexCount, instances, 0, baseVertex, 0);
2107     }
2108     else
2109     {
2110         mDeviceContext->DrawIndexed(indexCount, 0, baseVertex);
2111     }
2112 
2113     return angle::Result::Continue;
2114 }
2115 
releaseDeviceResources()2116 void Renderer11::releaseDeviceResources()
2117 {
2118     mStateManager.deinitialize();
2119     mStateCache.clear();
2120 
2121     SafeDelete(mLineLoopIB);
2122     SafeDelete(mTriangleFanIB);
2123     SafeDelete(mBlit);
2124     SafeDelete(mClear);
2125     SafeDelete(mTrim);
2126     SafeDelete(mPixelTransfer);
2127 
2128     mSyncQuery.reset();
2129 
2130     mCachedResolveTexture.reset();
2131 }
2132 
2133 // set notify to true to broadcast a message to all contexts of the device loss
testDeviceLost()2134 bool Renderer11::testDeviceLost()
2135 {
2136     bool isLost = false;
2137 
2138     if (!mDevice)
2139     {
2140         return true;
2141     }
2142 
2143     // GetRemovedReason is used to test if the device is removed
2144     HRESULT result = mDevice->GetDeviceRemovedReason();
2145     isLost         = d3d11::isDeviceLostError(result);
2146 
2147     if (isLost)
2148     {
2149         ERR() << "The D3D11 device was removed, " << gl::FmtHR(result);
2150     }
2151 
2152     return isLost;
2153 }
2154 
testDeviceResettable()2155 bool Renderer11::testDeviceResettable()
2156 {
2157     // determine if the device is resettable by creating a mock device
2158     PFN_D3D11_CREATE_DEVICE D3D11CreateDevice =
2159         (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
2160 
2161     if (D3D11CreateDevice == nullptr)
2162     {
2163         return false;
2164     }
2165 
2166     ID3D11Device *mockDevice;
2167     D3D_FEATURE_LEVEL mockFeatureLevel;
2168     ID3D11DeviceContext *mockContext;
2169     UINT flags = (mCreateDebugDevice ? D3D11_CREATE_DEVICE_DEBUG : 0);
2170 
2171     ASSERT(mRequestedDriverType != D3D_DRIVER_TYPE_UNKNOWN);
2172     HRESULT result = D3D11CreateDevice(
2173         nullptr, mRequestedDriverType, nullptr, flags, mAvailableFeatureLevels.data(),
2174         static_cast<unsigned int>(mAvailableFeatureLevels.size()), D3D11_SDK_VERSION, &mockDevice,
2175         &mockFeatureLevel, &mockContext);
2176 
2177     if (!mDevice || FAILED(result))
2178     {
2179         return false;
2180     }
2181 
2182     SafeRelease(mockContext);
2183     SafeRelease(mockDevice);
2184 
2185     return true;
2186 }
2187 
release()2188 void Renderer11::release()
2189 {
2190     mScratchMemoryBuffer.clear();
2191 
2192     mAnnotator.release();
2193     gl::UninitializeDebugAnnotations();
2194 
2195     releaseDeviceResources();
2196 
2197     SafeRelease(mDxgiFactory);
2198     SafeRelease(mDxgiAdapter);
2199 
2200     SafeRelease(mDeviceContext3);
2201     SafeRelease(mDeviceContext1);
2202 
2203     if (mDeviceContext)
2204     {
2205         mDeviceContext->ClearState();
2206         mDeviceContext->Flush();
2207         SafeRelease(mDeviceContext);
2208     }
2209 
2210     SafeRelease(mDevice);
2211     SafeRelease(mDebug);
2212 
2213     if (mD3d11Module)
2214     {
2215         FreeLibrary(mD3d11Module);
2216         mD3d11Module = nullptr;
2217     }
2218 
2219     if (mDxgiModule)
2220     {
2221         FreeLibrary(mDxgiModule);
2222         mDxgiModule = nullptr;
2223     }
2224 
2225     if (mDCompModule)
2226     {
2227         FreeLibrary(mDCompModule);
2228         mDCompModule = nullptr;
2229     }
2230 
2231     mDevice12.Reset();
2232     mCommandQueue.Reset();
2233 
2234     if (mD3d12Module)
2235     {
2236         FreeLibrary(mD3d12Module);
2237         mD3d12Module = nullptr;
2238     }
2239 
2240     mCompiler.release();
2241 
2242     mSupportsShareHandles.reset();
2243 }
2244 
resetDevice()2245 bool Renderer11::resetDevice()
2246 {
2247     // recreate everything
2248     release();
2249     egl::Error result = initialize();
2250 
2251     if (result.isError())
2252     {
2253         ERR() << "Could not reinitialize D3D11 device: " << result;
2254         return false;
2255     }
2256 
2257     return true;
2258 }
2259 
getRendererDescription() const2260 std::string Renderer11::getRendererDescription() const
2261 {
2262     std::ostringstream rendererString;
2263 
2264     rendererString << mDescription;
2265     rendererString << " Direct3D11";
2266 
2267     rendererString << " vs_" << getMajorShaderModel() << "_" << getMinorShaderModel()
2268                    << getShaderModelSuffix();
2269     rendererString << " ps_" << getMajorShaderModel() << "_" << getMinorShaderModel()
2270                    << getShaderModelSuffix();
2271 
2272     return rendererString.str();
2273 }
2274 
getAdapterIdentifier() const2275 DeviceIdentifier Renderer11::getAdapterIdentifier() const
2276 {
2277     // Don't use the AdapterLuid here, since that doesn't persist across reboot.
2278     DeviceIdentifier deviceIdentifier = {};
2279     deviceIdentifier.VendorId         = mAdapterDescription.VendorId;
2280     deviceIdentifier.DeviceId         = mAdapterDescription.DeviceId;
2281     deviceIdentifier.SubSysId         = mAdapterDescription.SubSysId;
2282     deviceIdentifier.Revision         = mAdapterDescription.Revision;
2283     deviceIdentifier.FeatureLevel     = static_cast<UINT>(mRenderer11DeviceCaps.featureLevel);
2284 
2285     return deviceIdentifier;
2286 }
2287 
getReservedVertexUniformVectors() const2288 unsigned int Renderer11::getReservedVertexUniformVectors() const
2289 {
2290     // Driver uniforms are stored in a separate constant buffer
2291     return d3d11_gl::GetReservedVertexUniformVectors(mRenderer11DeviceCaps.featureLevel);
2292 }
2293 
getReservedFragmentUniformVectors() const2294 unsigned int Renderer11::getReservedFragmentUniformVectors() const
2295 {
2296     // Driver uniforms are stored in a separate constant buffer
2297     return d3d11_gl::GetReservedFragmentUniformVectors(mRenderer11DeviceCaps.featureLevel);
2298 }
2299 
getReservedShaderUniformBuffers() const2300 gl::ShaderMap<unsigned int> Renderer11::getReservedShaderUniformBuffers() const
2301 {
2302     gl::ShaderMap<unsigned int> shaderReservedUniformBuffers = {};
2303 
2304     // we reserve one buffer for the application uniforms, and one for driver uniforms
2305     shaderReservedUniformBuffers[gl::ShaderType::Vertex]   = 2;
2306     shaderReservedUniformBuffers[gl::ShaderType::Fragment] = 2;
2307 
2308     return shaderReservedUniformBuffers;
2309 }
2310 
getDeviceType() const2311 d3d11::ANGLED3D11DeviceType Renderer11::getDeviceType() const
2312 {
2313     if (mCreatedWithDeviceEXT)
2314     {
2315         return d3d11::GetDeviceType(mDevice);
2316     }
2317 
2318     if ((mRequestedDriverType == D3D_DRIVER_TYPE_SOFTWARE) ||
2319         (mRequestedDriverType == D3D_DRIVER_TYPE_REFERENCE) ||
2320         (mRequestedDriverType == D3D_DRIVER_TYPE_NULL))
2321     {
2322         return d3d11::ANGLE_D3D11_DEVICE_TYPE_SOFTWARE_REF_OR_NULL;
2323     }
2324 
2325     if (mRequestedDriverType == D3D_DRIVER_TYPE_WARP)
2326     {
2327         return d3d11::ANGLE_D3D11_DEVICE_TYPE_WARP;
2328     }
2329 
2330     return d3d11::ANGLE_D3D11_DEVICE_TYPE_HARDWARE;
2331 }
2332 
getShareHandleSupport() const2333 bool Renderer11::getShareHandleSupport() const
2334 {
2335     if (mSupportsShareHandles.valid())
2336     {
2337         return mSupportsShareHandles.value();
2338     }
2339 
2340     // We only currently support share handles with BGRA surfaces, because
2341     // chrome needs BGRA. Once chrome fixes this, we should always support them.
2342     if (!getNativeExtensions().textureFormatBGRA8888)
2343     {
2344         mSupportsShareHandles = false;
2345         return false;
2346     }
2347 
2348     // PIX doesn't seem to support using share handles, so disable them.
2349     if (gl::DebugAnnotationsActive())
2350     {
2351         mSupportsShareHandles = false;
2352         return false;
2353     }
2354 
2355     // Also disable share handles on Feature Level 9_3, since it doesn't support share handles on
2356     // RGBA8 textures/swapchains.
2357     if (mRenderer11DeviceCaps.featureLevel <= D3D_FEATURE_LEVEL_9_3)
2358     {
2359         mSupportsShareHandles = false;
2360         return false;
2361     }
2362 
2363     // Find out which type of D3D11 device the Renderer11 is using
2364     d3d11::ANGLED3D11DeviceType deviceType = getDeviceType();
2365     if (deviceType == d3d11::ANGLE_D3D11_DEVICE_TYPE_UNKNOWN)
2366     {
2367         mSupportsShareHandles = false;
2368         return false;
2369     }
2370 
2371     if (deviceType == d3d11::ANGLE_D3D11_DEVICE_TYPE_SOFTWARE_REF_OR_NULL)
2372     {
2373         // Software/Reference/NULL devices don't support share handles
2374         mSupportsShareHandles = false;
2375         return false;
2376     }
2377 
2378     if (deviceType == d3d11::ANGLE_D3D11_DEVICE_TYPE_WARP)
2379     {
2380 #if !defined(ANGLE_ENABLE_WINDOWS_UWP)
2381         if (!IsWindows8OrGreater())
2382         {
2383             // WARP on Windows 7 doesn't support shared handles
2384             mSupportsShareHandles = false;
2385             return false;
2386         }
2387 #endif  // !defined(ANGLE_ENABLE_WINDOWS_UWP)
2388 
2389         // WARP on Windows 8.0+ supports shared handles when shared with another WARP device
2390         // TODO: allow applications to query for HARDWARE or WARP-specific share handles,
2391         //       to prevent them trying to use a WARP share handle with an a HW device (or
2392         //       vice-versa)
2393         //       e.g. by creating EGL_D3D11_[HARDWARE/WARP]_DEVICE_SHARE_HANDLE_ANGLE
2394         mSupportsShareHandles = true;
2395         return true;
2396     }
2397 
2398     ASSERT(mCreatedWithDeviceEXT || mRequestedDriverType == D3D_DRIVER_TYPE_HARDWARE);
2399     mSupportsShareHandles = true;
2400     return true;
2401 }
2402 
getMajorShaderModel() const2403 int Renderer11::getMajorShaderModel() const
2404 {
2405     switch (mRenderer11DeviceCaps.featureLevel)
2406     {
2407         case D3D_FEATURE_LEVEL_11_1:
2408         case D3D_FEATURE_LEVEL_11_0:
2409             return D3D11_SHADER_MAJOR_VERSION;  // 5
2410         case D3D_FEATURE_LEVEL_10_1:
2411             return D3D10_1_SHADER_MAJOR_VERSION;  // 4
2412         case D3D_FEATURE_LEVEL_10_0:
2413             return D3D10_SHADER_MAJOR_VERSION;  // 4
2414         case D3D_FEATURE_LEVEL_9_3:
2415             return D3D10_SHADER_MAJOR_VERSION;  // 4
2416         default:
2417             UNREACHABLE();
2418             return 0;
2419     }
2420 }
2421 
getMinorShaderModel() const2422 int Renderer11::getMinorShaderModel() const
2423 {
2424     switch (mRenderer11DeviceCaps.featureLevel)
2425     {
2426         case D3D_FEATURE_LEVEL_11_1:
2427         case D3D_FEATURE_LEVEL_11_0:
2428             return D3D11_SHADER_MINOR_VERSION;  // 0
2429         case D3D_FEATURE_LEVEL_10_1:
2430             return D3D10_1_SHADER_MINOR_VERSION;  // 1
2431         case D3D_FEATURE_LEVEL_10_0:
2432             return D3D10_SHADER_MINOR_VERSION;  // 0
2433         case D3D_FEATURE_LEVEL_9_3:
2434             return D3D10_SHADER_MINOR_VERSION;  // 0
2435         default:
2436             UNREACHABLE();
2437             return 0;
2438     }
2439 }
2440 
getShaderModelSuffix() const2441 std::string Renderer11::getShaderModelSuffix() const
2442 {
2443     switch (mRenderer11DeviceCaps.featureLevel)
2444     {
2445         case D3D_FEATURE_LEVEL_11_1:
2446         case D3D_FEATURE_LEVEL_11_0:
2447             return "";
2448         case D3D_FEATURE_LEVEL_10_1:
2449             return "";
2450         case D3D_FEATURE_LEVEL_10_0:
2451             return "";
2452         case D3D_FEATURE_LEVEL_9_3:
2453             return "_level_9_3";
2454         default:
2455             UNREACHABLE();
2456             return "";
2457     }
2458 }
2459 
copyImageInternal(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,RenderTargetD3D * destRenderTarget)2460 angle::Result Renderer11::copyImageInternal(const gl::Context *context,
2461                                             const gl::Framebuffer *framebuffer,
2462                                             const gl::Rectangle &sourceRect,
2463                                             GLenum destFormat,
2464                                             const gl::Offset &destOffset,
2465                                             RenderTargetD3D *destRenderTarget)
2466 {
2467     const gl::FramebufferAttachment *colorAttachment = framebuffer->getReadColorAttachment();
2468     ASSERT(colorAttachment);
2469 
2470     RenderTarget11 *sourceRenderTarget = nullptr;
2471     ANGLE_TRY(colorAttachment->getRenderTarget(context, 0, &sourceRenderTarget));
2472     ASSERT(sourceRenderTarget);
2473 
2474     const d3d11::RenderTargetView &dest =
2475         GetAs<RenderTarget11>(destRenderTarget)->getRenderTargetView();
2476     ASSERT(dest.valid());
2477 
2478     gl::Box sourceArea(sourceRect.x, sourceRect.y, 0, sourceRect.width, sourceRect.height, 1);
2479     gl::Extents sourceSize(sourceRenderTarget->getWidth(), sourceRenderTarget->getHeight(), 1);
2480 
2481     const bool invertSource = UsePresentPathFast(this, colorAttachment);
2482     if (invertSource)
2483     {
2484         sourceArea.y      = sourceSize.height - sourceRect.y;
2485         sourceArea.height = -sourceArea.height;
2486     }
2487 
2488     gl::Box destArea(destOffset.x, destOffset.y, 0, sourceRect.width, sourceRect.height, 1);
2489     gl::Extents destSize(destRenderTarget->getWidth(), destRenderTarget->getHeight(), 1);
2490 
2491     // Use nearest filtering because source and destination are the same size for the direct copy.
2492     // Convert to the unsized format before calling copyTexture.
2493     GLenum sourceFormat = colorAttachment->getFormat().info->format;
2494     if (sourceRenderTarget->getTexture().is2D() && sourceRenderTarget->isMultisampled())
2495     {
2496         TextureHelper11 tex;
2497         ANGLE_TRY(resolveMultisampledTexture(context, sourceRenderTarget,
2498                                              colorAttachment->getDepthSize() > 0,
2499                                              colorAttachment->getStencilSize() > 0, &tex));
2500 
2501         D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
2502         viewDesc.Format                    = sourceRenderTarget->getFormatSet().srvFormat;
2503         viewDesc.ViewDimension             = D3D11_SRV_DIMENSION_TEXTURE2D;
2504         viewDesc.Texture2D.MipLevels       = 1;
2505         viewDesc.Texture2D.MostDetailedMip = 0;
2506 
2507         d3d11::SharedSRV readSRV;
2508         ANGLE_TRY(allocateResource(GetImplAs<Context11>(context), viewDesc, tex.get(), &readSRV));
2509         ASSERT(readSRV.valid());
2510 
2511         ANGLE_TRY(mBlit->copyTexture(context, readSRV, sourceArea, sourceSize, sourceFormat, dest,
2512                                      destArea, destSize, nullptr, gl::GetUnsizedFormat(destFormat),
2513                                      GL_NONE, GL_NEAREST, false, false, false));
2514 
2515         return angle::Result::Continue;
2516     }
2517 
2518     ASSERT(!sourceRenderTarget->isMultisampled());
2519 
2520     const d3d11::SharedSRV &source = sourceRenderTarget->getBlitShaderResourceView(context);
2521     ASSERT(source.valid());
2522 
2523     ANGLE_TRY(mBlit->copyTexture(context, source, sourceArea, sourceSize, sourceFormat, dest,
2524                                  destArea, destSize, nullptr, gl::GetUnsizedFormat(destFormat),
2525                                  GL_NONE, GL_NEAREST, false, false, false));
2526 
2527     return angle::Result::Continue;
2528 }
2529 
copyImage2D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2530 angle::Result Renderer11::copyImage2D(const gl::Context *context,
2531                                       const gl::Framebuffer *framebuffer,
2532                                       const gl::Rectangle &sourceRect,
2533                                       GLenum destFormat,
2534                                       const gl::Offset &destOffset,
2535                                       TextureStorage *storage,
2536                                       GLint level)
2537 {
2538     TextureStorage11_2D *storage11 = GetAs<TextureStorage11_2D>(storage);
2539     ASSERT(storage11);
2540 
2541     gl::ImageIndex index              = gl::ImageIndex::Make2D(level);
2542     RenderTargetD3D *destRenderTarget = nullptr;
2543     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2544                                          &destRenderTarget));
2545     ASSERT(destRenderTarget);
2546 
2547     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2548                                 destRenderTarget));
2549 
2550     storage11->markLevelDirty(level);
2551 
2552     return angle::Result::Continue;
2553 }
2554 
copyImageCube(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,gl::TextureTarget target,GLint level)2555 angle::Result Renderer11::copyImageCube(const gl::Context *context,
2556                                         const gl::Framebuffer *framebuffer,
2557                                         const gl::Rectangle &sourceRect,
2558                                         GLenum destFormat,
2559                                         const gl::Offset &destOffset,
2560                                         TextureStorage *storage,
2561                                         gl::TextureTarget target,
2562                                         GLint level)
2563 {
2564     TextureStorage11_Cube *storage11 = GetAs<TextureStorage11_Cube>(storage);
2565     ASSERT(storage11);
2566 
2567     gl::ImageIndex index              = gl::ImageIndex::MakeCubeMapFace(target, level);
2568     RenderTargetD3D *destRenderTarget = nullptr;
2569     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2570                                          &destRenderTarget));
2571     ASSERT(destRenderTarget);
2572 
2573     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2574                                 destRenderTarget));
2575 
2576     storage11->markLevelDirty(level);
2577 
2578     return angle::Result::Continue;
2579 }
2580 
copyImage3D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2581 angle::Result Renderer11::copyImage3D(const gl::Context *context,
2582                                       const gl::Framebuffer *framebuffer,
2583                                       const gl::Rectangle &sourceRect,
2584                                       GLenum destFormat,
2585                                       const gl::Offset &destOffset,
2586                                       TextureStorage *storage,
2587                                       GLint level)
2588 {
2589     TextureStorage11_3D *storage11 = GetAs<TextureStorage11_3D>(storage);
2590     ASSERT(storage11);
2591 
2592     gl::ImageIndex index              = gl::ImageIndex::Make3D(level, destOffset.z);
2593     RenderTargetD3D *destRenderTarget = nullptr;
2594     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2595                                          &destRenderTarget));
2596     ASSERT(destRenderTarget);
2597 
2598     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2599                                 destRenderTarget));
2600 
2601     storage11->markLevelDirty(level);
2602 
2603     return angle::Result::Continue;
2604 }
2605 
copyImage2DArray(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2606 angle::Result Renderer11::copyImage2DArray(const gl::Context *context,
2607                                            const gl::Framebuffer *framebuffer,
2608                                            const gl::Rectangle &sourceRect,
2609                                            GLenum destFormat,
2610                                            const gl::Offset &destOffset,
2611                                            TextureStorage *storage,
2612                                            GLint level)
2613 {
2614     TextureStorage11_2DArray *storage11 = GetAs<TextureStorage11_2DArray>(storage);
2615     ASSERT(storage11);
2616 
2617     gl::ImageIndex index              = gl::ImageIndex::Make2DArray(level, destOffset.z);
2618     RenderTargetD3D *destRenderTarget = nullptr;
2619     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2620                                          &destRenderTarget));
2621     ASSERT(destRenderTarget);
2622 
2623     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2624                                 destRenderTarget));
2625     storage11->markLevelDirty(level);
2626 
2627     return angle::Result::Continue;
2628 }
2629 
copyTexture(const gl::Context * context,const gl::Texture * source,GLint sourceLevel,gl::TextureTarget srcTarget,const gl::Box & sourceBox,GLenum destFormat,GLenum destType,const gl::Offset & destOffset,TextureStorage * storage,gl::TextureTarget destTarget,GLint destLevel,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha)2630 angle::Result Renderer11::copyTexture(const gl::Context *context,
2631                                       const gl::Texture *source,
2632                                       GLint sourceLevel,
2633                                       gl::TextureTarget srcTarget,
2634                                       const gl::Box &sourceBox,
2635                                       GLenum destFormat,
2636                                       GLenum destType,
2637                                       const gl::Offset &destOffset,
2638                                       TextureStorage *storage,
2639                                       gl::TextureTarget destTarget,
2640                                       GLint destLevel,
2641                                       bool unpackFlipY,
2642                                       bool unpackPremultiplyAlpha,
2643                                       bool unpackUnmultiplyAlpha)
2644 {
2645 
2646     TextureD3D *sourceD3D                = GetImplAs<TextureD3D>(source);
2647     const gl::ImageDesc &sourceImageDesc = source->getTextureState().getImageDesc(
2648         NonCubeTextureTypeToTarget(source->getType()), sourceLevel);
2649 
2650     TextureStorage11 *destStorage11 = GetAs<TextureStorage11>(storage);
2651     ASSERT(destStorage11);
2652 
2653     // Check for fast path where a CopySubresourceRegion can be used.
2654     if (unpackPremultiplyAlpha == unpackUnmultiplyAlpha && !unpackFlipY &&
2655         sourceImageDesc.format.info->sizedInternalFormat ==
2656             destStorage11->getFormatSet().internalFormat)
2657     {
2658         const TextureHelper11 *destResource = nullptr;
2659         ANGLE_TRY(destStorage11->getResource(context, &destResource));
2660 
2661         if (srcTarget == gl::TextureTarget::_2D || srcTarget == gl::TextureTarget::_3D)
2662         {
2663             gl::ImageIndex sourceIndex = gl::ImageIndex::MakeFromTarget(srcTarget, sourceLevel, 1);
2664             const TextureHelper11 *sourceResource = nullptr;
2665             UINT sourceSubresource                = 0;
2666             ANGLE_TRY(GetTextureD3DResourceFromStorageOrImage(context, sourceD3D, sourceIndex,
2667                                                               &sourceResource, &sourceSubresource));
2668 
2669             gl::ImageIndex destIndex = gl::ImageIndex::MakeFromTarget(destTarget, destLevel, 1);
2670 
2671             UINT destSubresource = 0;
2672             ANGLE_TRY(destStorage11->getSubresourceIndex(context, destIndex, &destSubresource));
2673 
2674             D3D11_BOX d3dBox{static_cast<UINT>(sourceBox.x),
2675                              static_cast<UINT>(sourceBox.y),
2676                              static_cast<UINT>(sourceBox.z),
2677                              static_cast<UINT>(sourceBox.x + sourceBox.width),
2678                              static_cast<UINT>(sourceBox.y + sourceBox.height),
2679                              static_cast<UINT>(sourceBox.z + sourceBox.depth)};
2680 
2681             mDeviceContext->CopySubresourceRegion(
2682                 destResource->get(), destSubresource, destOffset.x, destOffset.y, destOffset.z,
2683                 sourceResource->get(), sourceSubresource, &d3dBox);
2684         }
2685         else if (srcTarget == gl::TextureTarget::_2DArray)
2686         {
2687             D3D11_BOX d3dBox{static_cast<UINT>(sourceBox.x),
2688                              static_cast<UINT>(sourceBox.y),
2689                              0,
2690                              static_cast<UINT>(sourceBox.x + sourceBox.width),
2691                              static_cast<UINT>(sourceBox.y + sourceBox.height),
2692                              1u};
2693 
2694             for (int i = 0; i < sourceBox.depth; i++)
2695             {
2696                 gl::ImageIndex sourceIndex =
2697                     gl::ImageIndex::Make2DArray(sourceLevel, i + sourceBox.z);
2698                 const TextureHelper11 *sourceResource = nullptr;
2699                 UINT sourceSubresource                = 0;
2700                 ANGLE_TRY(GetTextureD3DResourceFromStorageOrImage(
2701                     context, sourceD3D, sourceIndex, &sourceResource, &sourceSubresource));
2702 
2703                 gl::ImageIndex dIndex = gl::ImageIndex::Make2DArray(destLevel, i + destOffset.z);
2704                 UINT destSubresource  = 0;
2705                 ANGLE_TRY(destStorage11->getSubresourceIndex(context, dIndex, &destSubresource));
2706 
2707                 mDeviceContext->CopySubresourceRegion(
2708                     destResource->get(), destSubresource, destOffset.x, destOffset.y, 0,
2709                     sourceResource->get(), sourceSubresource, &d3dBox);
2710             }
2711         }
2712         else
2713         {
2714             UNREACHABLE();
2715         }
2716     }
2717     else
2718     {
2719         TextureStorage *sourceStorage = nullptr;
2720         ANGLE_TRY(sourceD3D->getNativeTexture(context, &sourceStorage));
2721 
2722         TextureStorage11 *sourceStorage11 = GetAs<TextureStorage11>(sourceStorage);
2723         ASSERT(sourceStorage11);
2724 
2725         const d3d11::SharedSRV *sourceSRV = nullptr;
2726         ANGLE_TRY(sourceStorage11->getSRVLevels(context, sourceLevel, sourceLevel, &sourceSRV));
2727 
2728         gl::ImageIndex destIndex;
2729         if (destTarget == gl::TextureTarget::_2D || destTarget == gl::TextureTarget::_3D ||
2730             gl::IsCubeMapFaceTarget(destTarget))
2731         {
2732             destIndex = gl::ImageIndex::MakeFromTarget(destTarget, destLevel, 1);
2733         }
2734         else if (destTarget == gl::TextureTarget::_2DArray)
2735         {
2736             destIndex = gl::ImageIndex::Make2DArrayRange(destLevel, 0, sourceImageDesc.size.depth);
2737         }
2738         else
2739         {
2740             UNREACHABLE();
2741         }
2742 
2743         RenderTargetD3D *destRenderTargetD3D = nullptr;
2744         ANGLE_TRY(destStorage11->getRenderTarget(
2745             context, destIndex, destStorage11->getRenderToTextureSamples(), &destRenderTargetD3D));
2746 
2747         RenderTarget11 *destRenderTarget11 = GetAs<RenderTarget11>(destRenderTargetD3D);
2748 
2749         const d3d11::RenderTargetView &destRTV = destRenderTarget11->getRenderTargetView();
2750         ASSERT(destRTV.valid());
2751 
2752         gl::Box sourceArea(sourceBox.x, sourceBox.y, sourceBox.z, sourceBox.width, sourceBox.height,
2753                            sourceBox.depth);
2754 
2755         if (unpackFlipY)
2756         {
2757             sourceArea.y += sourceArea.height;
2758             sourceArea.height = -sourceArea.height;
2759         }
2760 
2761         gl::Box destArea(destOffset.x, destOffset.y, destOffset.z, sourceBox.width,
2762                          sourceBox.height, sourceBox.depth);
2763 
2764         gl::Extents destSize(destRenderTarget11->getWidth(), destRenderTarget11->getHeight(),
2765                              sourceBox.depth);
2766 
2767         // Use nearest filtering because source and destination are the same size for the direct
2768         // copy
2769         GLenum sourceFormat = source->getFormat(srcTarget, sourceLevel).info->format;
2770         ANGLE_TRY(mBlit->copyTexture(context, *sourceSRV, sourceArea, sourceImageDesc.size,
2771                                      sourceFormat, destRTV, destArea, destSize, nullptr, destFormat,
2772                                      destType, GL_NEAREST, false, unpackPremultiplyAlpha,
2773                                      unpackUnmultiplyAlpha));
2774     }
2775 
2776     destStorage11->markLevelDirty(destLevel);
2777 
2778     return angle::Result::Continue;
2779 }
2780 
copyCompressedTexture(const gl::Context * context,const gl::Texture * source,GLint sourceLevel,TextureStorage * storage,GLint destLevel)2781 angle::Result Renderer11::copyCompressedTexture(const gl::Context *context,
2782                                                 const gl::Texture *source,
2783                                                 GLint sourceLevel,
2784                                                 TextureStorage *storage,
2785                                                 GLint destLevel)
2786 {
2787     TextureStorage11_2D *destStorage11 = GetAs<TextureStorage11_2D>(storage);
2788     ASSERT(destStorage11);
2789 
2790     const TextureHelper11 *destResource = nullptr;
2791     ANGLE_TRY(destStorage11->getResource(context, &destResource));
2792 
2793     gl::ImageIndex destIndex = gl::ImageIndex::Make2D(destLevel);
2794     UINT destSubresource     = 0;
2795     ANGLE_TRY(destStorage11->getSubresourceIndex(context, destIndex, &destSubresource));
2796 
2797     TextureD3D *sourceD3D = GetImplAs<TextureD3D>(source);
2798     ASSERT(sourceD3D);
2799 
2800     TextureStorage *sourceStorage = nullptr;
2801     ANGLE_TRY(sourceD3D->getNativeTexture(context, &sourceStorage));
2802 
2803     TextureStorage11_2D *sourceStorage11 = GetAs<TextureStorage11_2D>(sourceStorage);
2804     ASSERT(sourceStorage11);
2805 
2806     const TextureHelper11 *sourceResource = nullptr;
2807     ANGLE_TRY(sourceStorage11->getResource(context, &sourceResource));
2808 
2809     gl::ImageIndex sourceIndex = gl::ImageIndex::Make2D(sourceLevel);
2810     UINT sourceSubresource     = 0;
2811     ANGLE_TRY(sourceStorage11->getSubresourceIndex(context, sourceIndex, &sourceSubresource));
2812 
2813     mDeviceContext->CopySubresourceRegion(destResource->get(), destSubresource, 0, 0, 0,
2814                                           sourceResource->get(), sourceSubresource, nullptr);
2815 
2816     return angle::Result::Continue;
2817 }
2818 
createRenderTarget(const gl::Context * context,int width,int height,GLenum format,GLsizei samples,RenderTargetD3D ** outRT)2819 angle::Result Renderer11::createRenderTarget(const gl::Context *context,
2820                                              int width,
2821                                              int height,
2822                                              GLenum format,
2823                                              GLsizei samples,
2824                                              RenderTargetD3D **outRT)
2825 {
2826     const d3d11::Format &formatInfo = d3d11::Format::Get(format, mRenderer11DeviceCaps);
2827 
2828     const gl::TextureCaps &textureCaps = getNativeTextureCaps().get(format);
2829     GLuint supportedSamples            = textureCaps.getNearestSamples(samples);
2830 
2831     Context11 *context11 = GetImplAs<Context11>(context);
2832 
2833     if (width > 0 && height > 0)
2834     {
2835         // Create texture resource
2836         D3D11_TEXTURE2D_DESC desc;
2837         desc.Width              = width;
2838         desc.Height             = height;
2839         desc.MipLevels          = 1;
2840         desc.ArraySize          = 1;
2841         desc.Format             = formatInfo.texFormat;
2842         desc.SampleDesc.Count   = (supportedSamples == 0) ? 1 : supportedSamples;
2843         desc.SampleDesc.Quality = getSampleDescQuality(supportedSamples);
2844         desc.Usage              = D3D11_USAGE_DEFAULT;
2845         desc.CPUAccessFlags     = 0;
2846         desc.MiscFlags          = 0;
2847 
2848         // If a rendertarget or depthstencil format exists for this texture format,
2849         // we'll flag it to allow binding that way. Shader resource views are a little
2850         // more complicated.
2851         bool bindRTV = false, bindDSV = false, bindSRV = false;
2852         bindRTV = (formatInfo.rtvFormat != DXGI_FORMAT_UNKNOWN);
2853         bindDSV = (formatInfo.dsvFormat != DXGI_FORMAT_UNKNOWN);
2854         bindSRV = (formatInfo.srvFormat != DXGI_FORMAT_UNKNOWN);
2855 
2856         bool isMultisampledDepthStencil = bindDSV && desc.SampleDesc.Count > 1;
2857         if (isMultisampledDepthStencil &&
2858             !mRenderer11DeviceCaps.supportsMultisampledDepthStencilSRVs)
2859         {
2860             bindSRV = false;
2861         }
2862 
2863         desc.BindFlags = (bindRTV ? D3D11_BIND_RENDER_TARGET : 0) |
2864                          (bindDSV ? D3D11_BIND_DEPTH_STENCIL : 0) |
2865                          (bindSRV ? D3D11_BIND_SHADER_RESOURCE : 0);
2866 
2867         // The format must be either an RTV or a DSV
2868         ASSERT(bindRTV != bindDSV);
2869 
2870         TextureHelper11 texture;
2871         ANGLE_TRY(allocateTexture(context11, desc, formatInfo, &texture));
2872         texture.setDebugName("createRenderTarget.Texture");
2873 
2874         d3d11::SharedSRV srv;
2875         d3d11::SharedSRV blitSRV;
2876         if (bindSRV)
2877         {
2878             D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
2879             srvDesc.Format        = formatInfo.srvFormat;
2880             srvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_SRV_DIMENSION_TEXTURE2D
2881                                                             : D3D11_SRV_DIMENSION_TEXTURE2DMS;
2882             srvDesc.Texture2D.MostDetailedMip = 0;
2883             srvDesc.Texture2D.MipLevels       = 1;
2884 
2885             ANGLE_TRY(allocateResource(context11, srvDesc, texture.get(), &srv));
2886             srv.setDebugName("createRenderTarget.SRV");
2887 
2888             if (formatInfo.blitSRVFormat != formatInfo.srvFormat)
2889             {
2890                 D3D11_SHADER_RESOURCE_VIEW_DESC blitSRVDesc;
2891                 blitSRVDesc.Format        = formatInfo.blitSRVFormat;
2892                 blitSRVDesc.ViewDimension = (supportedSamples == 0)
2893                                                 ? D3D11_SRV_DIMENSION_TEXTURE2D
2894                                                 : D3D11_SRV_DIMENSION_TEXTURE2DMS;
2895                 blitSRVDesc.Texture2D.MostDetailedMip = 0;
2896                 blitSRVDesc.Texture2D.MipLevels       = 1;
2897 
2898                 ANGLE_TRY(allocateResource(context11, blitSRVDesc, texture.get(), &blitSRV));
2899                 blitSRV.setDebugName("createRenderTarget.BlitSRV");
2900             }
2901             else
2902             {
2903                 blitSRV = srv.makeCopy();
2904             }
2905         }
2906 
2907         if (bindDSV)
2908         {
2909             D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
2910             dsvDesc.Format        = formatInfo.dsvFormat;
2911             dsvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_DSV_DIMENSION_TEXTURE2D
2912                                                             : D3D11_DSV_DIMENSION_TEXTURE2DMS;
2913             dsvDesc.Texture2D.MipSlice = 0;
2914             dsvDesc.Flags              = 0;
2915 
2916             d3d11::DepthStencilView dsv;
2917             ANGLE_TRY(allocateResource(context11, dsvDesc, texture.get(), &dsv));
2918             dsv.setDebugName("createRenderTarget.DSV");
2919 
2920             *outRT = new TextureRenderTarget11(std::move(dsv), texture, srv, format, formatInfo,
2921                                                width, height, 1, supportedSamples);
2922         }
2923         else if (bindRTV)
2924         {
2925             D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
2926             rtvDesc.Format        = formatInfo.rtvFormat;
2927             rtvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_RTV_DIMENSION_TEXTURE2D
2928                                                             : D3D11_RTV_DIMENSION_TEXTURE2DMS;
2929             rtvDesc.Texture2D.MipSlice = 0;
2930 
2931             d3d11::RenderTargetView rtv;
2932             ANGLE_TRY(allocateResource(context11, rtvDesc, texture.get(), &rtv));
2933             rtv.setDebugName("createRenderTarget.RTV");
2934 
2935             if (formatInfo.dataInitializerFunction != nullptr)
2936             {
2937                 const float clearValues[4] = {0.0f, 0.0f, 0.0f, 1.0f};
2938                 mDeviceContext->ClearRenderTargetView(rtv.get(), clearValues);
2939             }
2940 
2941             *outRT = new TextureRenderTarget11(std::move(rtv), texture, srv, blitSRV, format,
2942                                                formatInfo, width, height, 1, supportedSamples);
2943         }
2944         else
2945         {
2946             UNREACHABLE();
2947         }
2948     }
2949     else
2950     {
2951         *outRT = new TextureRenderTarget11(d3d11::RenderTargetView(), TextureHelper11(),
2952                                            d3d11::SharedSRV(), d3d11::SharedSRV(), format,
2953                                            d3d11::Format::Get(GL_NONE, mRenderer11DeviceCaps),
2954                                            width, height, 1, supportedSamples);
2955     }
2956 
2957     return angle::Result::Continue;
2958 }
2959 
createRenderTargetCopy(const gl::Context * context,RenderTargetD3D * source,RenderTargetD3D ** outRT)2960 angle::Result Renderer11::createRenderTargetCopy(const gl::Context *context,
2961                                                  RenderTargetD3D *source,
2962                                                  RenderTargetD3D **outRT)
2963 {
2964     ASSERT(source != nullptr);
2965 
2966     RenderTargetD3D *newRT = nullptr;
2967     ANGLE_TRY(createRenderTarget(context, source->getWidth(), source->getHeight(),
2968                                  source->getInternalFormat(), source->getSamples(), &newRT));
2969 
2970     RenderTarget11 *source11 = GetAs<RenderTarget11>(source);
2971     RenderTarget11 *dest11   = GetAs<RenderTarget11>(newRT);
2972 
2973     mDeviceContext->CopySubresourceRegion(dest11->getTexture().get(), dest11->getSubresourceIndex(),
2974                                           0, 0, 0, source11->getTexture().get(),
2975                                           source11->getSubresourceIndex(), nullptr);
2976     *outRT = newRT;
2977     return angle::Result::Continue;
2978 }
2979 
loadExecutable(d3d::Context * context,const uint8_t * function,size_t length,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,ShaderExecutableD3D ** outExecutable)2980 angle::Result Renderer11::loadExecutable(d3d::Context *context,
2981                                          const uint8_t *function,
2982                                          size_t length,
2983                                          gl::ShaderType type,
2984                                          const std::vector<D3DVarying> &streamOutVaryings,
2985                                          bool separatedOutputBuffers,
2986                                          ShaderExecutableD3D **outExecutable)
2987 {
2988     ShaderData shaderData(function, length);
2989 
2990     switch (type)
2991     {
2992         case gl::ShaderType::Vertex:
2993         {
2994             d3d11::VertexShader vertexShader;
2995             d3d11::GeometryShader streamOutShader;
2996             ANGLE_TRY(allocateResource(context, shaderData, &vertexShader));
2997 
2998             if (!streamOutVaryings.empty())
2999             {
3000                 std::vector<D3D11_SO_DECLARATION_ENTRY> soDeclaration;
3001                 soDeclaration.reserve(streamOutVaryings.size());
3002 
3003                 for (const auto &streamOutVarying : streamOutVaryings)
3004                 {
3005                     D3D11_SO_DECLARATION_ENTRY entry = {};
3006                     entry.Stream                     = 0;
3007                     entry.SemanticName               = streamOutVarying.semanticName.c_str();
3008                     entry.SemanticIndex              = streamOutVarying.semanticIndex;
3009                     entry.StartComponent             = 0;
3010                     entry.ComponentCount = static_cast<BYTE>(streamOutVarying.componentCount);
3011                     entry.OutputSlot     = static_cast<BYTE>(
3012                         (separatedOutputBuffers ? streamOutVarying.outputSlot : 0));
3013                     soDeclaration.push_back(entry);
3014                 }
3015 
3016                 ANGLE_TRY(allocateResource(context, shaderData, &soDeclaration, &streamOutShader));
3017             }
3018 
3019             *outExecutable = new ShaderExecutable11(function, length, std::move(vertexShader),
3020                                                     std::move(streamOutShader));
3021         }
3022         break;
3023         case gl::ShaderType::Fragment:
3024         {
3025             d3d11::PixelShader pixelShader;
3026             ANGLE_TRY(allocateResource(context, shaderData, &pixelShader));
3027             *outExecutable = new ShaderExecutable11(function, length, std::move(pixelShader));
3028         }
3029         break;
3030         case gl::ShaderType::Geometry:
3031         {
3032             d3d11::GeometryShader geometryShader;
3033             ANGLE_TRY(allocateResource(context, shaderData, &geometryShader));
3034             *outExecutable = new ShaderExecutable11(function, length, std::move(geometryShader));
3035         }
3036         break;
3037         case gl::ShaderType::Compute:
3038         {
3039             d3d11::ComputeShader computeShader;
3040             ANGLE_TRY(allocateResource(context, shaderData, &computeShader));
3041             *outExecutable = new ShaderExecutable11(function, length, std::move(computeShader));
3042         }
3043         break;
3044         default:
3045             ANGLE_HR_UNREACHABLE(context);
3046     }
3047 
3048     return angle::Result::Continue;
3049 }
3050 
compileToExecutable(d3d::Context * context,gl::InfoLog & infoLog,const std::string & shaderHLSL,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,const angle::CompilerWorkaroundsD3D & workarounds,ShaderExecutableD3D ** outExectuable)3051 angle::Result Renderer11::compileToExecutable(d3d::Context *context,
3052                                               gl::InfoLog &infoLog,
3053                                               const std::string &shaderHLSL,
3054                                               gl::ShaderType type,
3055                                               const std::vector<D3DVarying> &streamOutVaryings,
3056                                               bool separatedOutputBuffers,
3057                                               const angle::CompilerWorkaroundsD3D &workarounds,
3058                                               ShaderExecutableD3D **outExectuable)
3059 {
3060     std::stringstream profileStream;
3061 
3062     switch (type)
3063     {
3064         case gl::ShaderType::Vertex:
3065             profileStream << "vs";
3066             break;
3067         case gl::ShaderType::Fragment:
3068             profileStream << "ps";
3069             break;
3070         case gl::ShaderType::Geometry:
3071             profileStream << "gs";
3072             break;
3073         case gl::ShaderType::Compute:
3074             profileStream << "cs";
3075             break;
3076         default:
3077             ANGLE_HR_UNREACHABLE(context);
3078     }
3079 
3080     profileStream << "_" << getMajorShaderModel() << "_" << getMinorShaderModel()
3081                   << getShaderModelSuffix();
3082     std::string profile = profileStream.str();
3083 
3084     UINT flags = D3DCOMPILE_OPTIMIZATION_LEVEL2;
3085 
3086 #if defined(ANGLE_ENABLE_DEBUG_TRACE)
3087 #    ifndef NDEBUG
3088     flags = D3DCOMPILE_SKIP_OPTIMIZATION;
3089 #    endif  // NDEBUG
3090     flags |= D3DCOMPILE_DEBUG;
3091 #endif  // defined(ANGLE_ENABLE_DEBUG_TRACE)
3092 
3093     if (workarounds.enableIEEEStrictness)
3094         flags |= D3DCOMPILE_IEEE_STRICTNESS;
3095 
3096     // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders
3097     // when it would otherwise pass with alternative options.
3098     // Try the default flags first and if compilation fails, try some alternatives.
3099     std::vector<CompileConfig> configs;
3100     configs.push_back(CompileConfig(flags, "default"));
3101     configs.push_back(CompileConfig(flags | D3DCOMPILE_SKIP_VALIDATION, "skip validation"));
3102     configs.push_back(CompileConfig(flags | D3DCOMPILE_SKIP_OPTIMIZATION, "skip optimization"));
3103 
3104     if (getMajorShaderModel() == 4 && getShaderModelSuffix() != "")
3105     {
3106         // Some shaders might cause a "blob content mismatch between level9 and d3d10 shader".
3107         // e.g. dEQP-GLES2.functional.shaders.struct.local.loop_nested_struct_array_*.
3108         // Using the [unroll] directive works around this, as does this D3DCompile flag.
3109         configs.push_back(
3110             CompileConfig(flags | D3DCOMPILE_AVOID_FLOW_CONTROL, "avoid flow control"));
3111     }
3112 
3113     D3D_SHADER_MACRO loopMacros[] = {{"ANGLE_ENABLE_LOOP_FLATTEN", "1"}, {0, 0}};
3114 
3115     // TODO(jmadill): Use ComPtr?
3116     ID3DBlob *binary = nullptr;
3117     std::string debugInfo;
3118     ANGLE_TRY(mCompiler.compileToBinary(context, infoLog, shaderHLSL, profile, configs, loopMacros,
3119                                         &binary, &debugInfo));
3120 
3121     // It's possible that binary is NULL if the compiler failed in all configurations.  Set the
3122     // executable to NULL and return GL_NO_ERROR to signify that there was a link error but the
3123     // internal state is still OK.
3124     if (!binary)
3125     {
3126         *outExectuable = nullptr;
3127         return angle::Result::Continue;
3128     }
3129 
3130     angle::Result error = loadExecutable(
3131         context, static_cast<const uint8_t *>(binary->GetBufferPointer()), binary->GetBufferSize(),
3132         type, streamOutVaryings, separatedOutputBuffers, outExectuable);
3133 
3134     SafeRelease(binary);
3135     if (error == angle::Result::Stop)
3136     {
3137         return error;
3138     }
3139 
3140     if (!debugInfo.empty())
3141     {
3142         (*outExectuable)->appendDebugInfo(debugInfo);
3143     }
3144 
3145     return angle::Result::Continue;
3146 }
3147 
ensureHLSLCompilerInitialized(d3d::Context * context)3148 angle::Result Renderer11::ensureHLSLCompilerInitialized(d3d::Context *context)
3149 {
3150     return mCompiler.ensureInitialized(context);
3151 }
3152 
createUniformStorage(size_t storageSize)3153 UniformStorageD3D *Renderer11::createUniformStorage(size_t storageSize)
3154 {
3155     return new UniformStorage11(storageSize);
3156 }
3157 
createVertexBuffer()3158 VertexBuffer *Renderer11::createVertexBuffer()
3159 {
3160     return new VertexBuffer11(this);
3161 }
3162 
createIndexBuffer()3163 IndexBuffer *Renderer11::createIndexBuffer()
3164 {
3165     return new IndexBuffer11(this);
3166 }
3167 
createStreamProducerD3DTexture(egl::Stream::ConsumerType consumerType,const egl::AttributeMap & attribs)3168 StreamProducerImpl *Renderer11::createStreamProducerD3DTexture(
3169     egl::Stream::ConsumerType consumerType,
3170     const egl::AttributeMap &attribs)
3171 {
3172     return new StreamProducerD3DTexture(this);
3173 }
3174 
supportsFastCopyBufferToTexture(GLenum internalFormat) const3175 bool Renderer11::supportsFastCopyBufferToTexture(GLenum internalFormat) const
3176 {
3177     ASSERT(getNativeExtensions().pixelBufferObjectNV);
3178 
3179     const gl::InternalFormat &internalFormatInfo = gl::GetSizedInternalFormatInfo(internalFormat);
3180     const d3d11::Format &d3d11FormatInfo =
3181         d3d11::Format::Get(internalFormat, mRenderer11DeviceCaps);
3182 
3183     // sRGB formats do not work with D3D11 buffer SRVs
3184     if (internalFormatInfo.colorEncoding == GL_SRGB)
3185     {
3186         return false;
3187     }
3188 
3189     // We cannot support direct copies to non-color-renderable formats
3190     if (d3d11FormatInfo.rtvFormat == DXGI_FORMAT_UNKNOWN)
3191     {
3192         return false;
3193     }
3194 
3195     // We skip all 3-channel formats since sometimes format support is missing
3196     if (internalFormatInfo.componentCount == 3)
3197     {
3198         return false;
3199     }
3200 
3201     // We don't support formats which we can't represent without conversion
3202     if (d3d11FormatInfo.format().glInternalFormat != internalFormat)
3203     {
3204         return false;
3205     }
3206 
3207     // Buffer SRV creation for this format was not working on Windows 10.
3208     if (d3d11FormatInfo.texFormat == DXGI_FORMAT_B5G5R5A1_UNORM)
3209     {
3210         return false;
3211     }
3212 
3213     // This format is not supported as a buffer SRV.
3214     if (d3d11FormatInfo.texFormat == DXGI_FORMAT_A8_UNORM)
3215     {
3216         return false;
3217     }
3218 
3219     return true;
3220 }
3221 
fastCopyBufferToTexture(const gl::Context * context,const gl::PixelUnpackState & unpack,gl::Buffer * unpackBuffer,unsigned int offset,RenderTargetD3D * destRenderTarget,GLenum destinationFormat,GLenum sourcePixelsType,const gl::Box & destArea)3222 angle::Result Renderer11::fastCopyBufferToTexture(const gl::Context *context,
3223                                                   const gl::PixelUnpackState &unpack,
3224                                                   gl::Buffer *unpackBuffer,
3225                                                   unsigned int offset,
3226                                                   RenderTargetD3D *destRenderTarget,
3227                                                   GLenum destinationFormat,
3228                                                   GLenum sourcePixelsType,
3229                                                   const gl::Box &destArea)
3230 {
3231     ASSERT(supportsFastCopyBufferToTexture(destinationFormat));
3232     return mPixelTransfer->copyBufferToTexture(context, unpack, unpackBuffer, offset,
3233                                                destRenderTarget, destinationFormat,
3234                                                sourcePixelsType, destArea);
3235 }
3236 
createImage()3237 ImageD3D *Renderer11::createImage()
3238 {
3239     return new Image11(this);
3240 }
3241 
createExternalImageSibling(const gl::Context * context,EGLenum target,EGLClientBuffer buffer,const egl::AttributeMap & attribs)3242 ExternalImageSiblingImpl *Renderer11::createExternalImageSibling(const gl::Context *context,
3243                                                                  EGLenum target,
3244                                                                  EGLClientBuffer buffer,
3245                                                                  const egl::AttributeMap &attribs)
3246 {
3247     switch (target)
3248     {
3249         case EGL_D3D11_TEXTURE_ANGLE:
3250             return new ExternalImageSiblingImpl11(this, buffer, attribs);
3251 
3252         default:
3253             UNREACHABLE();
3254             return nullptr;
3255     }
3256 }
3257 
generateMipmap(const gl::Context * context,ImageD3D * dest,ImageD3D * src)3258 angle::Result Renderer11::generateMipmap(const gl::Context *context, ImageD3D *dest, ImageD3D *src)
3259 {
3260     Image11 *dest11 = GetAs<Image11>(dest);
3261     Image11 *src11  = GetAs<Image11>(src);
3262     return Image11::GenerateMipmap(context, dest11, src11, mRenderer11DeviceCaps);
3263 }
3264 
generateMipmapUsingD3D(const gl::Context * context,TextureStorage * storage,const gl::TextureState & textureState)3265 angle::Result Renderer11::generateMipmapUsingD3D(const gl::Context *context,
3266                                                  TextureStorage *storage,
3267                                                  const gl::TextureState &textureState)
3268 {
3269     TextureStorage11 *storage11 = GetAs<TextureStorage11>(storage);
3270 
3271     ASSERT(storage11->isRenderTarget());
3272     ASSERT(storage11->supportsNativeMipmapFunction());
3273 
3274     const d3d11::SharedSRV *srv = nullptr;
3275     ANGLE_TRY(storage11->getSRVLevels(context, textureState.getEffectiveBaseLevel(),
3276                                       textureState.getEffectiveMaxLevel(), &srv));
3277 
3278     mDeviceContext->GenerateMips(srv->get());
3279 
3280     return angle::Result::Continue;
3281 }
3282 
copyImage(const gl::Context * context,ImageD3D * dest,ImageD3D * source,const gl::Box & sourceBox,const gl::Offset & destOffset,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha)3283 angle::Result Renderer11::copyImage(const gl::Context *context,
3284                                     ImageD3D *dest,
3285                                     ImageD3D *source,
3286                                     const gl::Box &sourceBox,
3287                                     const gl::Offset &destOffset,
3288                                     bool unpackFlipY,
3289                                     bool unpackPremultiplyAlpha,
3290                                     bool unpackUnmultiplyAlpha)
3291 {
3292     Image11 *dest11 = GetAs<Image11>(dest);
3293     Image11 *src11  = GetAs<Image11>(source);
3294     return Image11::CopyImage(context, dest11, src11, sourceBox, destOffset, unpackFlipY,
3295                               unpackPremultiplyAlpha, unpackUnmultiplyAlpha, mRenderer11DeviceCaps);
3296 }
3297 
createTextureStorage2D(SwapChainD3D * swapChain)3298 TextureStorage *Renderer11::createTextureStorage2D(SwapChainD3D *swapChain)
3299 {
3300     SwapChain11 *swapChain11 = GetAs<SwapChain11>(swapChain);
3301     return new TextureStorage11_2D(this, swapChain11);
3302 }
3303 
createTextureStorageEGLImage(EGLImageD3D * eglImage,RenderTargetD3D * renderTargetD3D)3304 TextureStorage *Renderer11::createTextureStorageEGLImage(EGLImageD3D *eglImage,
3305                                                          RenderTargetD3D *renderTargetD3D)
3306 {
3307     return new TextureStorage11_EGLImage(this, eglImage, GetAs<RenderTarget11>(renderTargetD3D));
3308 }
3309 
createTextureStorageExternal(egl::Stream * stream,const egl::Stream::GLTextureDescription & desc)3310 TextureStorage *Renderer11::createTextureStorageExternal(
3311     egl::Stream *stream,
3312     const egl::Stream::GLTextureDescription &desc)
3313 {
3314     return new TextureStorage11_External(this, stream, desc);
3315 }
3316 
createTextureStorage2D(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,int levels,bool hintLevelZeroOnly)3317 TextureStorage *Renderer11::createTextureStorage2D(GLenum internalformat,
3318                                                    bool renderTarget,
3319                                                    GLsizei width,
3320                                                    GLsizei height,
3321                                                    int levels,
3322                                                    bool hintLevelZeroOnly)
3323 {
3324     return new TextureStorage11_2D(this, internalformat, renderTarget, width, height, levels,
3325                                    hintLevelZeroOnly);
3326 }
3327 
createTextureStorageCube(GLenum internalformat,bool renderTarget,int size,int levels,bool hintLevelZeroOnly)3328 TextureStorage *Renderer11::createTextureStorageCube(GLenum internalformat,
3329                                                      bool renderTarget,
3330                                                      int size,
3331                                                      int levels,
3332                                                      bool hintLevelZeroOnly)
3333 {
3334     return new TextureStorage11_Cube(this, internalformat, renderTarget, size, levels,
3335                                      hintLevelZeroOnly);
3336 }
3337 
createTextureStorage3D(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,GLsizei depth,int levels)3338 TextureStorage *Renderer11::createTextureStorage3D(GLenum internalformat,
3339                                                    bool renderTarget,
3340                                                    GLsizei width,
3341                                                    GLsizei height,
3342                                                    GLsizei depth,
3343                                                    int levels)
3344 {
3345     return new TextureStorage11_3D(this, internalformat, renderTarget, width, height, depth,
3346                                    levels);
3347 }
3348 
createTextureStorage2DArray(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,GLsizei depth,int levels)3349 TextureStorage *Renderer11::createTextureStorage2DArray(GLenum internalformat,
3350                                                         bool renderTarget,
3351                                                         GLsizei width,
3352                                                         GLsizei height,
3353                                                         GLsizei depth,
3354                                                         int levels)
3355 {
3356     return new TextureStorage11_2DArray(this, internalformat, renderTarget, width, height, depth,
3357                                         levels);
3358 }
3359 
createTextureStorage2DMultisample(GLenum internalformat,GLsizei width,GLsizei height,int levels,int samples,bool fixedSampleLocations)3360 TextureStorage *Renderer11::createTextureStorage2DMultisample(GLenum internalformat,
3361                                                               GLsizei width,
3362                                                               GLsizei height,
3363                                                               int levels,
3364                                                               int samples,
3365                                                               bool fixedSampleLocations)
3366 {
3367     return new TextureStorage11_2DMultisample(this, internalformat, width, height, levels, samples,
3368                                               fixedSampleLocations);
3369 }
3370 
createTextureStorage2DMultisampleArray(GLenum internalformat,GLsizei width,GLsizei height,GLsizei depth,int levels,int samples,bool fixedSampleLocations)3371 TextureStorage *Renderer11::createTextureStorage2DMultisampleArray(GLenum internalformat,
3372                                                                    GLsizei width,
3373                                                                    GLsizei height,
3374                                                                    GLsizei depth,
3375                                                                    int levels,
3376                                                                    int samples,
3377                                                                    bool fixedSampleLocations)
3378 {
3379     return new TextureStorage11_2DMultisampleArray(this, internalformat, width, height, depth,
3380                                                    levels, samples, fixedSampleLocations);
3381 }
3382 
readFromAttachment(const gl::Context * context,const gl::FramebufferAttachment & srcAttachment,const gl::Rectangle & sourceArea,GLenum format,GLenum type,GLuint outputPitch,const gl::PixelPackState & pack,uint8_t * pixelsOut)3383 angle::Result Renderer11::readFromAttachment(const gl::Context *context,
3384                                              const gl::FramebufferAttachment &srcAttachment,
3385                                              const gl::Rectangle &sourceArea,
3386                                              GLenum format,
3387                                              GLenum type,
3388                                              GLuint outputPitch,
3389                                              const gl::PixelPackState &pack,
3390                                              uint8_t *pixelsOut)
3391 {
3392     ASSERT(sourceArea.width >= 0);
3393     ASSERT(sourceArea.height >= 0);
3394 
3395     const bool invertTexture = UsePresentPathFast(this, &srcAttachment);
3396 
3397     RenderTarget11 *rt11 = nullptr;
3398     ANGLE_TRY(srcAttachment.getRenderTarget(context, 0, &rt11));
3399     ASSERT(rt11->getTexture().valid());
3400 
3401     const TextureHelper11 &textureHelper = rt11->getTexture();
3402     unsigned int sourceSubResource       = rt11->getSubresourceIndex();
3403 
3404     const gl::Extents &texSize = textureHelper.getExtents();
3405 
3406     gl::Rectangle actualArea = sourceArea;
3407     bool reverseRowOrder     = pack.reverseRowOrder;
3408     if (invertTexture)
3409     {
3410         actualArea.y    = texSize.height - actualArea.y - actualArea.height;
3411         reverseRowOrder = !reverseRowOrder;
3412     }
3413 
3414     // Clamp read region to the defined texture boundaries, preventing out of bounds reads
3415     // and reads of uninitialized data.
3416     gl::Rectangle safeArea;
3417     safeArea.x = gl::clamp(actualArea.x, 0, texSize.width);
3418     safeArea.y = gl::clamp(actualArea.y, 0, texSize.height);
3419     safeArea.width =
3420         gl::clamp(actualArea.width + std::min(actualArea.x, 0), 0, texSize.width - safeArea.x);
3421     safeArea.height =
3422         gl::clamp(actualArea.height + std::min(actualArea.y, 0), 0, texSize.height - safeArea.y);
3423 
3424     ASSERT(safeArea.x >= 0 && safeArea.y >= 0);
3425     ASSERT(safeArea.x + safeArea.width <= texSize.width);
3426     ASSERT(safeArea.y + safeArea.height <= texSize.height);
3427 
3428     if (safeArea.width == 0 || safeArea.height == 0)
3429     {
3430         // no work to do
3431         return angle::Result::Continue;
3432     }
3433 
3434     gl::Extents safeSize(safeArea.width, safeArea.height, 1);
3435     TextureHelper11 stagingHelper;
3436     ANGLE_TRY(createStagingTexture(context, textureHelper.getTextureType(),
3437                                    textureHelper.getFormatSet(), safeSize, StagingAccess::READ,
3438                                    &stagingHelper));
3439     stagingHelper.setDebugName("readFromAttachment::stagingHelper");
3440 
3441     TextureHelper11 resolvedTextureHelper;
3442 
3443     // "srcTexture" usually points to the source texture.
3444     // For 2D multisampled textures, it points to the multisampled resolve texture.
3445     const TextureHelper11 *srcTexture = &textureHelper;
3446 
3447     if (textureHelper.is2D() && textureHelper.getSampleCount() > 1)
3448     {
3449         D3D11_TEXTURE2D_DESC resolveDesc;
3450         resolveDesc.Width              = static_cast<UINT>(texSize.width);
3451         resolveDesc.Height             = static_cast<UINT>(texSize.height);
3452         resolveDesc.MipLevels          = 1;
3453         resolveDesc.ArraySize          = 1;
3454         resolveDesc.Format             = textureHelper.getFormat();
3455         resolveDesc.SampleDesc.Count   = 1;
3456         resolveDesc.SampleDesc.Quality = 0;
3457         resolveDesc.Usage              = D3D11_USAGE_DEFAULT;
3458         resolveDesc.BindFlags          = 0;
3459         resolveDesc.CPUAccessFlags     = 0;
3460         resolveDesc.MiscFlags          = 0;
3461 
3462         ANGLE_TRY(allocateTexture(GetImplAs<Context11>(context), resolveDesc,
3463                                   textureHelper.getFormatSet(), &resolvedTextureHelper));
3464         resolvedTextureHelper.setDebugName("readFromAttachment::resolvedTextureHelper");
3465 
3466         mDeviceContext->ResolveSubresource(resolvedTextureHelper.get(), 0, textureHelper.get(),
3467                                            sourceSubResource, textureHelper.getFormat());
3468 
3469         sourceSubResource = 0;
3470         srcTexture        = &resolvedTextureHelper;
3471     }
3472 
3473     D3D11_BOX srcBox;
3474     srcBox.left   = static_cast<UINT>(safeArea.x);
3475     srcBox.right  = static_cast<UINT>(safeArea.x + safeArea.width);
3476     srcBox.top    = static_cast<UINT>(safeArea.y);
3477     srcBox.bottom = static_cast<UINT>(safeArea.y + safeArea.height);
3478 
3479     // Select the correct layer from a 3D attachment
3480     srcBox.front = 0;
3481     if (textureHelper.is3D())
3482     {
3483         srcBox.front = static_cast<UINT>(srcAttachment.layer());
3484     }
3485     srcBox.back = srcBox.front + 1;
3486 
3487     mDeviceContext->CopySubresourceRegion(stagingHelper.get(), 0, 0, 0, 0, srcTexture->get(),
3488                                           sourceSubResource, &srcBox);
3489 
3490     const angle::Format &angleFormat = GetFormatFromFormatType(format, type);
3491     gl::Buffer *packBuffer = context->getState().getTargetBuffer(gl::BufferBinding::PixelPack);
3492 
3493     PackPixelsParams packParams(safeArea, angleFormat, outputPitch, reverseRowOrder, packBuffer, 0);
3494     return packPixels(context, stagingHelper, packParams, pixelsOut);
3495 }
3496 
packPixels(const gl::Context * context,const TextureHelper11 & textureHelper,const PackPixelsParams & params,uint8_t * pixelsOut)3497 angle::Result Renderer11::packPixels(const gl::Context *context,
3498                                      const TextureHelper11 &textureHelper,
3499                                      const PackPixelsParams &params,
3500                                      uint8_t *pixelsOut)
3501 {
3502     ID3D11Resource *readResource = textureHelper.get();
3503 
3504     D3D11_MAPPED_SUBRESOURCE mapping;
3505     ANGLE_TRY(mapResource(context, readResource, 0, D3D11_MAP_READ, 0, &mapping));
3506 
3507     uint8_t *source = static_cast<uint8_t *>(mapping.pData);
3508     int inputPitch  = static_cast<int>(mapping.RowPitch);
3509 
3510     const auto &formatInfo = textureHelper.getFormatSet();
3511     ASSERT(formatInfo.format().glInternalFormat != GL_NONE);
3512 
3513     PackPixels(params, formatInfo.format(), inputPitch, source, pixelsOut);
3514 
3515     mDeviceContext->Unmap(readResource, 0);
3516 
3517     return angle::Result::Continue;
3518 }
3519 
blitRenderbufferRect(const gl::Context * context,const gl::Rectangle & readRectIn,const gl::Rectangle & drawRectIn,RenderTargetD3D * readRenderTarget,RenderTargetD3D * drawRenderTarget,GLenum filter,const gl::Rectangle * scissor,bool colorBlit,bool depthBlit,bool stencilBlit)3520 angle::Result Renderer11::blitRenderbufferRect(const gl::Context *context,
3521                                                const gl::Rectangle &readRectIn,
3522                                                const gl::Rectangle &drawRectIn,
3523                                                RenderTargetD3D *readRenderTarget,
3524                                                RenderTargetD3D *drawRenderTarget,
3525                                                GLenum filter,
3526                                                const gl::Rectangle *scissor,
3527                                                bool colorBlit,
3528                                                bool depthBlit,
3529                                                bool stencilBlit)
3530 {
3531     // Since blitRenderbufferRect is called for each render buffer that needs to be blitted,
3532     // it should never be the case that both color and depth/stencil need to be blitted at
3533     // at the same time.
3534     ASSERT(colorBlit != (depthBlit || stencilBlit));
3535 
3536     RenderTarget11 *drawRenderTarget11 = GetAs<RenderTarget11>(drawRenderTarget);
3537     ASSERT(drawRenderTarget11);
3538 
3539     const TextureHelper11 &drawTexture = drawRenderTarget11->getTexture();
3540     unsigned int drawSubresource       = drawRenderTarget11->getSubresourceIndex();
3541 
3542     RenderTarget11 *readRenderTarget11 = GetAs<RenderTarget11>(readRenderTarget);
3543     ASSERT(readRenderTarget11);
3544 
3545     const gl::Extents readSize(readRenderTarget->getWidth(), readRenderTarget->getHeight(), 1);
3546     const gl::Extents drawSize(drawRenderTarget->getWidth(), drawRenderTarget->getHeight(), 1);
3547 
3548     // From the spec:
3549     // "The actual region taken from the read framebuffer is limited to the intersection of the
3550     // source buffers being transferred, which may include the color buffer selected by the read
3551     // buffer, the depth buffer, and / or the stencil buffer depending on mask."
3552     // This means negative x and y are out of bounds, and not to be read from. We handle this here
3553     // by internally scaling the read and draw rectangles.
3554 
3555     // Remove reversal from readRect to simplify further operations.
3556     gl::Rectangle readRect = readRectIn;
3557     gl::Rectangle drawRect = drawRectIn;
3558     if (readRect.isReversedX())
3559     {
3560         readRect.x     = readRect.x + readRect.width;
3561         readRect.width = -readRect.width;
3562         drawRect.x     = drawRect.x + drawRect.width;
3563         drawRect.width = -drawRect.width;
3564     }
3565     if (readRect.isReversedY())
3566     {
3567         readRect.y      = readRect.y + readRect.height;
3568         readRect.height = -readRect.height;
3569         drawRect.y      = drawRect.y + drawRect.height;
3570         drawRect.height = -drawRect.height;
3571     }
3572 
3573     gl::Rectangle readBounds(0, 0, readSize.width, readSize.height);
3574     gl::Rectangle inBoundsReadRect;
3575     if (!gl::ClipRectangle(readRect, readBounds, &inBoundsReadRect))
3576     {
3577         return angle::Result::Continue;
3578     }
3579 
3580     {
3581         // Calculate the drawRect that corresponds to inBoundsReadRect.
3582         auto readToDrawX = [&drawRect, &readRect](int readOffset) {
3583             double readToDrawScale =
3584                 static_cast<double>(drawRect.width) / static_cast<double>(readRect.width);
3585             return static_cast<int>(
3586                 round(static_cast<double>(readOffset - readRect.x) * readToDrawScale) + drawRect.x);
3587         };
3588         auto readToDrawY = [&drawRect, &readRect](int readOffset) {
3589             double readToDrawScale =
3590                 static_cast<double>(drawRect.height) / static_cast<double>(readRect.height);
3591             return static_cast<int>(
3592                 round(static_cast<double>(readOffset - readRect.y) * readToDrawScale) + drawRect.y);
3593         };
3594 
3595         gl::Rectangle drawRectMatchingInBoundsReadRect;
3596         drawRectMatchingInBoundsReadRect.x = readToDrawX(inBoundsReadRect.x);
3597         drawRectMatchingInBoundsReadRect.y = readToDrawY(inBoundsReadRect.y);
3598         drawRectMatchingInBoundsReadRect.width =
3599             readToDrawX(inBoundsReadRect.x1()) - drawRectMatchingInBoundsReadRect.x;
3600         drawRectMatchingInBoundsReadRect.height =
3601             readToDrawY(inBoundsReadRect.y1()) - drawRectMatchingInBoundsReadRect.y;
3602         drawRect = drawRectMatchingInBoundsReadRect;
3603         readRect = inBoundsReadRect;
3604     }
3605 
3606     bool scissorNeeded = false;
3607     if (scissor)
3608     {
3609         gl::Rectangle scissoredDrawRect;
3610         if (!gl::ClipRectangle(drawRect, *scissor, &scissoredDrawRect))
3611         {
3612             return angle::Result::Continue;
3613         }
3614         scissorNeeded = scissoredDrawRect != drawRect;
3615     }
3616 
3617     const auto &destFormatInfo =
3618         gl::GetSizedInternalFormatInfo(drawRenderTarget->getInternalFormat());
3619     const auto &srcFormatInfo =
3620         gl::GetSizedInternalFormatInfo(readRenderTarget->getInternalFormat());
3621     const auto &formatSet    = drawRenderTarget11->getFormatSet();
3622     const auto &nativeFormat = formatSet.format();
3623 
3624     // Some blits require masking off emulated texture channels. eg: from RGBA8 to RGB8, we
3625     // emulate RGB8 with RGBA8, so we need to mask off the alpha channel when we copy.
3626 
3627     gl::Color<bool> colorMask;
3628     colorMask.red =
3629         (srcFormatInfo.redBits > 0) && (destFormatInfo.redBits == 0) && (nativeFormat.redBits > 0);
3630     colorMask.green = (srcFormatInfo.greenBits > 0) && (destFormatInfo.greenBits == 0) &&
3631                       (nativeFormat.greenBits > 0);
3632     colorMask.blue = (srcFormatInfo.blueBits > 0) && (destFormatInfo.blueBits == 0) &&
3633                      (nativeFormat.blueBits > 0);
3634     colorMask.alpha = (srcFormatInfo.alphaBits > 0) && (destFormatInfo.alphaBits == 0) &&
3635                       (nativeFormat.alphaBits > 0);
3636 
3637     // We only currently support masking off the alpha channel.
3638     bool colorMaskingNeeded = colorMask.alpha;
3639     ASSERT(!colorMask.red && !colorMask.green && !colorMask.blue);
3640 
3641     bool wholeBufferCopy = !scissorNeeded && !colorMaskingNeeded && readRect.x == 0 &&
3642                            readRect.width == readSize.width && readRect.y == 0 &&
3643                            readRect.height == readSize.height && drawRect.x == 0 &&
3644                            drawRect.width == drawSize.width && drawRect.y == 0 &&
3645                            drawRect.height == drawSize.height;
3646 
3647     bool stretchRequired = readRect.width != drawRect.width || readRect.height != drawRect.height;
3648 
3649     ASSERT(!readRect.isReversedX() && !readRect.isReversedY());
3650     bool reversalRequired = drawRect.isReversedX() || drawRect.isReversedY();
3651 
3652     bool outOfBounds = readRect.x < 0 || readRect.x + readRect.width > readSize.width ||
3653                        readRect.y < 0 || readRect.y + readRect.height > readSize.height ||
3654                        drawRect.x < 0 || drawRect.x + drawRect.width > drawSize.width ||
3655                        drawRect.y < 0 || drawRect.y + drawRect.height > drawSize.height;
3656 
3657     bool partialDSBlit =
3658         (nativeFormat.depthBits > 0 && depthBlit) != (nativeFormat.stencilBits > 0 && stencilBlit);
3659 
3660     const bool canCopySubresource =
3661         drawRenderTarget->getSamples() == readRenderTarget->getSamples() &&
3662         readRenderTarget11->getFormatSet().formatID ==
3663             drawRenderTarget11->getFormatSet().formatID &&
3664         !stretchRequired && !outOfBounds && !reversalRequired && !partialDSBlit &&
3665         !colorMaskingNeeded && (!(depthBlit || stencilBlit) || wholeBufferCopy);
3666 
3667     TextureHelper11 readTexture;
3668     unsigned int readSubresource = 0;
3669     d3d11::SharedSRV readSRV;
3670 
3671     if (readRenderTarget->isMultisampled())
3672     {
3673         ANGLE_TRY(resolveMultisampledTexture(context, readRenderTarget11, depthBlit, stencilBlit,
3674                                              &readTexture));
3675 
3676         if (!stencilBlit && !canCopySubresource)
3677         {
3678             const auto &readFormatSet = readTexture.getFormatSet();
3679 
3680             D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
3681             viewDesc.Format                    = readFormatSet.srvFormat;
3682             viewDesc.ViewDimension             = D3D11_SRV_DIMENSION_TEXTURE2D;
3683             viewDesc.Texture2D.MipLevels       = 1;
3684             viewDesc.Texture2D.MostDetailedMip = 0;
3685 
3686             ANGLE_TRY(allocateResource(GetImplAs<Context11>(context), viewDesc, readTexture.get(),
3687                                        &readSRV));
3688         }
3689     }
3690     else
3691     {
3692         ASSERT(readRenderTarget11);
3693         readTexture     = readRenderTarget11->getTexture();
3694         readSubresource = readRenderTarget11->getSubresourceIndex();
3695 
3696         if (!canCopySubresource)
3697         {
3698             readSRV = readRenderTarget11->getBlitShaderResourceView(context).makeCopy();
3699             if (!readSRV.valid())
3700             {
3701                 ASSERT(depthBlit || stencilBlit);
3702                 readSRV = readRenderTarget11->getShaderResourceView(context).makeCopy();
3703             }
3704             ASSERT(readSRV.valid());
3705         }
3706     }
3707 
3708     if (canCopySubresource)
3709     {
3710         UINT dstX = drawRect.x;
3711         UINT dstY = drawRect.y;
3712 
3713         D3D11_BOX readBox;
3714         readBox.left   = readRect.x;
3715         readBox.right  = readRect.x + readRect.width;
3716         readBox.top    = readRect.y;
3717         readBox.bottom = readRect.y + readRect.height;
3718         readBox.front  = 0;
3719         readBox.back   = 1;
3720 
3721         if (scissorNeeded)
3722         {
3723             // drawRect is guaranteed to have positive width and height because stretchRequired is
3724             // false.
3725             ASSERT(drawRect.width >= 0 || drawRect.height >= 0);
3726 
3727             if (drawRect.x < scissor->x)
3728             {
3729                 dstX = scissor->x;
3730                 readBox.left += (scissor->x - drawRect.x);
3731             }
3732             if (drawRect.y < scissor->y)
3733             {
3734                 dstY = scissor->y;
3735                 readBox.top += (scissor->y - drawRect.y);
3736             }
3737             if (drawRect.x + drawRect.width > scissor->x + scissor->width)
3738             {
3739                 readBox.right -= ((drawRect.x + drawRect.width) - (scissor->x + scissor->width));
3740             }
3741             if (drawRect.y + drawRect.height > scissor->y + scissor->height)
3742             {
3743                 readBox.bottom -= ((drawRect.y + drawRect.height) - (scissor->y + scissor->height));
3744             }
3745         }
3746 
3747         // D3D11 needs depth-stencil CopySubresourceRegions to have a NULL pSrcBox
3748         // We also require complete framebuffer copies for depth-stencil blit.
3749         D3D11_BOX *pSrcBox = wholeBufferCopy ? nullptr : &readBox;
3750 
3751         mDeviceContext->CopySubresourceRegion(drawTexture.get(), drawSubresource, dstX, dstY, 0,
3752                                               readTexture.get(), readSubresource, pSrcBox);
3753     }
3754     else
3755     {
3756         gl::Box readArea(readRect.x, readRect.y, 0, readRect.width, readRect.height, 1);
3757         gl::Box drawArea(drawRect.x, drawRect.y, 0, drawRect.width, drawRect.height, 1);
3758 
3759         if (depthBlit && stencilBlit)
3760         {
3761             ANGLE_TRY(mBlit->copyDepthStencil(context, readTexture, readSubresource, readArea,
3762                                               readSize, drawTexture, drawSubresource, drawArea,
3763                                               drawSize, scissor));
3764         }
3765         else if (depthBlit)
3766         {
3767             const d3d11::DepthStencilView &drawDSV = drawRenderTarget11->getDepthStencilView();
3768             ASSERT(readSRV.valid());
3769             ANGLE_TRY(mBlit->copyDepth(context, readSRV, readArea, readSize, drawDSV, drawArea,
3770                                        drawSize, scissor));
3771         }
3772         else if (stencilBlit)
3773         {
3774             ANGLE_TRY(mBlit->copyStencil(context, readTexture, readSubresource, readArea, readSize,
3775                                          drawTexture, drawSubresource, drawArea, drawSize,
3776                                          scissor));
3777         }
3778         else
3779         {
3780             const d3d11::RenderTargetView &drawRTV = drawRenderTarget11->getRenderTargetView();
3781 
3782             // We don't currently support masking off any other channel than alpha
3783             bool maskOffAlpha = colorMaskingNeeded && colorMask.alpha;
3784             ASSERT(readSRV.valid());
3785             ANGLE_TRY(mBlit->copyTexture(context, readSRV, readArea, readSize, srcFormatInfo.format,
3786                                          drawRTV, drawArea, drawSize, scissor,
3787                                          destFormatInfo.format, GL_NONE, filter, maskOffAlpha,
3788                                          false, false));
3789         }
3790     }
3791 
3792     return angle::Result::Continue;
3793 }
3794 
isES3Capable() const3795 bool Renderer11::isES3Capable() const
3796 {
3797     return (d3d11_gl::GetMaximumClientVersion(mRenderer11DeviceCaps).major > 2);
3798 }
3799 
getRendererClass() const3800 RendererClass Renderer11::getRendererClass() const
3801 {
3802     return RENDERER_D3D11;
3803 }
3804 
onSwap()3805 void Renderer11::onSwap()
3806 {
3807     // Send histogram updates every half hour
3808     const double kHistogramUpdateInterval = 30 * 60;
3809 
3810     auto *platform                   = ANGLEPlatformCurrent();
3811     const double currentTime         = platform->monotonicallyIncreasingTime(platform);
3812     const double timeSinceLastUpdate = currentTime - mLastHistogramUpdateTime;
3813 
3814     if (timeSinceLastUpdate > kHistogramUpdateInterval)
3815     {
3816         updateHistograms();
3817         mLastHistogramUpdateTime = currentTime;
3818     }
3819 }
3820 
updateHistograms()3821 void Renderer11::updateHistograms()
3822 {
3823     // Update the buffer CPU memory histogram
3824     {
3825         size_t sizeSum = 0;
3826         for (const Buffer11 *buffer : mAliveBuffers)
3827         {
3828             sizeSum += buffer->getTotalCPUBufferMemoryBytes();
3829         }
3830         const int kOneMegaByte = 1024 * 1024;
3831         ANGLE_HISTOGRAM_MEMORY_MB("GPU.ANGLE.Buffer11CPUMemoryMB",
3832                                   static_cast<int>(sizeSum) / kOneMegaByte);
3833     }
3834 }
3835 
onBufferCreate(const Buffer11 * created)3836 void Renderer11::onBufferCreate(const Buffer11 *created)
3837 {
3838     mAliveBuffers.insert(created);
3839 }
3840 
onBufferDelete(const Buffer11 * deleted)3841 void Renderer11::onBufferDelete(const Buffer11 *deleted)
3842 {
3843     mAliveBuffers.erase(deleted);
3844 }
3845 
resolveMultisampledTexture(const gl::Context * context,RenderTarget11 * renderTarget,bool depth,bool stencil,TextureHelper11 * textureOut)3846 angle::Result Renderer11::resolveMultisampledTexture(const gl::Context *context,
3847                                                      RenderTarget11 *renderTarget,
3848                                                      bool depth,
3849                                                      bool stencil,
3850                                                      TextureHelper11 *textureOut)
3851 {
3852     if (depth && !stencil)
3853     {
3854         return mBlit->resolveDepth(context, renderTarget, textureOut);
3855     }
3856 
3857     if (stencil)
3858     {
3859         return mBlit->resolveStencil(context, renderTarget, depth, textureOut);
3860     }
3861 
3862     const auto &formatSet = renderTarget->getFormatSet();
3863 
3864     ASSERT(renderTarget->isMultisampled());
3865     const d3d11::SharedSRV &sourceSRV = renderTarget->getShaderResourceView(context);
3866     D3D11_SHADER_RESOURCE_VIEW_DESC sourceSRVDesc;
3867     sourceSRV.get()->GetDesc(&sourceSRVDesc);
3868     ASSERT(sourceSRVDesc.ViewDimension == D3D_SRV_DIMENSION_TEXTURE2DMS ||
3869            sourceSRVDesc.ViewDimension == D3D_SRV_DIMENSION_TEXTURE2DMSARRAY);
3870 
3871     if (!mCachedResolveTexture.valid() ||
3872         mCachedResolveTexture.getExtents().width != renderTarget->getWidth() ||
3873         mCachedResolveTexture.getExtents().height != renderTarget->getHeight() ||
3874         mCachedResolveTexture.getFormat() != formatSet.texFormat)
3875     {
3876         D3D11_TEXTURE2D_DESC resolveDesc;
3877         resolveDesc.Width              = renderTarget->getWidth();
3878         resolveDesc.Height             = renderTarget->getHeight();
3879         resolveDesc.MipLevels          = 1;
3880         resolveDesc.ArraySize          = 1;
3881         resolveDesc.Format             = formatSet.texFormat;
3882         resolveDesc.SampleDesc.Count   = 1;
3883         resolveDesc.SampleDesc.Quality = 0;
3884         resolveDesc.Usage              = D3D11_USAGE_DEFAULT;
3885         resolveDesc.BindFlags          = D3D11_BIND_SHADER_RESOURCE;
3886         resolveDesc.CPUAccessFlags     = 0;
3887         resolveDesc.MiscFlags          = 0;
3888 
3889         ANGLE_TRY(allocateTexture(GetImplAs<Context11>(context), resolveDesc, formatSet,
3890                                   &mCachedResolveTexture));
3891     }
3892 
3893     mDeviceContext->ResolveSubresource(mCachedResolveTexture.get(), 0,
3894                                        renderTarget->getTexture().get(),
3895                                        renderTarget->getSubresourceIndex(), formatSet.texFormat);
3896     *textureOut = mCachedResolveTexture;
3897     return angle::Result::Continue;
3898 }
3899 
getLUID(LUID * adapterLuid) const3900 bool Renderer11::getLUID(LUID *adapterLuid) const
3901 {
3902     adapterLuid->HighPart = 0;
3903     adapterLuid->LowPart  = 0;
3904 
3905     if (!mDxgiAdapter)
3906     {
3907         return false;
3908     }
3909 
3910     DXGI_ADAPTER_DESC adapterDesc;
3911     if (FAILED(mDxgiAdapter->GetDesc(&adapterDesc)))
3912     {
3913         return false;
3914     }
3915 
3916     *adapterLuid = adapterDesc.AdapterLuid;
3917     return true;
3918 }
3919 
getVertexConversionType(angle::FormatID vertexFormatID) const3920 VertexConversionType Renderer11::getVertexConversionType(angle::FormatID vertexFormatID) const
3921 {
3922     return d3d11::GetVertexFormatInfo(vertexFormatID, mRenderer11DeviceCaps.featureLevel)
3923         .conversionType;
3924 }
3925 
getVertexComponentType(angle::FormatID vertexFormatID) const3926 GLenum Renderer11::getVertexComponentType(angle::FormatID vertexFormatID) const
3927 {
3928     const auto &format =
3929         d3d11::GetVertexFormatInfo(vertexFormatID, mRenderer11DeviceCaps.featureLevel);
3930     return d3d11::GetComponentType(format.nativeFormat);
3931 }
3932 
getVertexSpaceRequired(const gl::Context * context,const gl::VertexAttribute & attrib,const gl::VertexBinding & binding,size_t count,GLsizei instances,GLuint baseInstance,unsigned int * bytesRequiredOut) const3933 angle::Result Renderer11::getVertexSpaceRequired(const gl::Context *context,
3934                                                  const gl::VertexAttribute &attrib,
3935                                                  const gl::VertexBinding &binding,
3936                                                  size_t count,
3937                                                  GLsizei instances,
3938                                                  GLuint baseInstance,
3939                                                  unsigned int *bytesRequiredOut) const
3940 {
3941     if (!attrib.enabled)
3942     {
3943         *bytesRequiredOut = 16u;
3944         return angle::Result::Continue;
3945     }
3946 
3947     unsigned int elementCount  = 0;
3948     const unsigned int divisor = binding.getDivisor();
3949     if (instances == 0 || divisor == 0)
3950     {
3951         // This could be a clipped cast.
3952         elementCount = gl::clampCast<unsigned int>(count);
3953     }
3954     else
3955     {
3956         // Round up to divisor, if possible
3957         elementCount =
3958             UnsignedCeilDivide(static_cast<unsigned int>(instances + baseInstance), divisor);
3959     }
3960 
3961     ASSERT(elementCount > 0);
3962 
3963     const D3D_FEATURE_LEVEL featureLevel = mRenderer11DeviceCaps.featureLevel;
3964     const d3d11::VertexFormat &vertexFormatInfo =
3965         d3d11::GetVertexFormatInfo(attrib.format->id, featureLevel);
3966     const d3d11::DXGIFormatSize &dxgiFormatInfo =
3967         d3d11::GetDXGIFormatSizeInfo(vertexFormatInfo.nativeFormat);
3968     unsigned int elementSize = dxgiFormatInfo.pixelBytes;
3969     bool check = (elementSize > std::numeric_limits<unsigned int>::max() / elementCount);
3970     ANGLE_CHECK(GetImplAs<Context11>(context), !check,
3971                 "New vertex buffer size would result in an overflow.", GL_OUT_OF_MEMORY);
3972 
3973     *bytesRequiredOut = elementSize * elementCount;
3974     return angle::Result::Continue;
3975 }
3976 
generateCaps(gl::Caps * outCaps,gl::TextureCapsMap * outTextureCaps,gl::Extensions * outExtensions,gl::Limitations * outLimitations) const3977 void Renderer11::generateCaps(gl::Caps *outCaps,
3978                               gl::TextureCapsMap *outTextureCaps,
3979                               gl::Extensions *outExtensions,
3980                               gl::Limitations *outLimitations) const
3981 {
3982     d3d11_gl::GenerateCaps(mDevice, mDeviceContext, mRenderer11DeviceCaps, getFeatures(),
3983                            mDescription, outCaps, outTextureCaps, outExtensions, outLimitations);
3984 }
3985 
initializeFeatures(angle::FeaturesD3D * features) const3986 void Renderer11::initializeFeatures(angle::FeaturesD3D *features) const
3987 {
3988     if (!mDisplay->getState().featuresAllDisabled)
3989     {
3990         d3d11::InitializeFeatures(mRenderer11DeviceCaps, mAdapterDescription, features);
3991     }
3992     ApplyFeatureOverrides(features, mDisplay->getState());
3993 }
3994 
createEGLDevice()3995 DeviceImpl *Renderer11::createEGLDevice()
3996 {
3997     return new DeviceD3D(EGL_D3D11_DEVICE_ANGLE, mDevice);
3998 }
3999 
createContext(const gl::State & state,gl::ErrorSet * errorSet)4000 ContextImpl *Renderer11::createContext(const gl::State &state, gl::ErrorSet *errorSet)
4001 {
4002     return new Context11(state, errorSet, this);
4003 }
4004 
createDefaultFramebuffer(const gl::FramebufferState & state)4005 FramebufferImpl *Renderer11::createDefaultFramebuffer(const gl::FramebufferState &state)
4006 {
4007     return new Framebuffer11(state, this);
4008 }
4009 
getScratchMemoryBuffer(Context11 * context11,size_t requestedSize,angle::MemoryBuffer ** bufferOut)4010 angle::Result Renderer11::getScratchMemoryBuffer(Context11 *context11,
4011                                                  size_t requestedSize,
4012                                                  angle::MemoryBuffer **bufferOut)
4013 {
4014     ANGLE_CHECK_GL_ALLOC(context11, mScratchMemoryBuffer.get(requestedSize, bufferOut));
4015     return angle::Result::Continue;
4016 }
4017 
getMaxSupportedESVersion() const4018 gl::Version Renderer11::getMaxSupportedESVersion() const
4019 {
4020     return d3d11_gl::GetMaximumClientVersion(mRenderer11DeviceCaps);
4021 }
4022 
getMaxConformantESVersion() const4023 gl::Version Renderer11::getMaxConformantESVersion() const
4024 {
4025     // 3.1 support is in progress.
4026     return std::min(getMaxSupportedESVersion(), gl::Version(3, 0));
4027 }
4028 
getAnnotator()4029 gl::DebugAnnotator *Renderer11::getAnnotator()
4030 {
4031     return &mAnnotator;
4032 }
4033 
dispatchCompute(const gl::Context * context,GLuint numGroupsX,GLuint numGroupsY,GLuint numGroupsZ)4034 angle::Result Renderer11::dispatchCompute(const gl::Context *context,
4035                                           GLuint numGroupsX,
4036                                           GLuint numGroupsY,
4037                                           GLuint numGroupsZ)
4038 {
4039     const gl::State &glState   = context->getState();
4040     const gl::Program *program = glState.getProgram();
4041     if (program->getActiveShaderStorageBlockCount() > 0 ||
4042         program->getActiveAtomicCounterBufferCount() > 0)
4043     {
4044         ANGLE_TRY(markRawBufferUsage(context));
4045     }
4046 
4047     ANGLE_TRY(mStateManager.updateStateForCompute(context, numGroupsX, numGroupsY, numGroupsZ));
4048     mDeviceContext->Dispatch(numGroupsX, numGroupsY, numGroupsZ);
4049 
4050     return angle::Result::Continue;
4051 }
dispatchComputeIndirect(const gl::Context * context,GLintptr indirect)4052 angle::Result Renderer11::dispatchComputeIndirect(const gl::Context *context, GLintptr indirect)
4053 {
4054     const auto &glState        = context->getState();
4055     const gl::Program *program = glState.getProgram();
4056     if (program->getActiveShaderStorageBlockCount() > 0 ||
4057         program->getActiveAtomicCounterBufferCount() > 0)
4058     {
4059         ANGLE_TRY(markRawBufferUsage(context));
4060     }
4061 
4062     auto *dispatchIndirectBuffer = glState.getTargetBuffer(gl::BufferBinding::DispatchIndirect);
4063     ASSERT(dispatchIndirectBuffer);
4064 
4065     Buffer11 *storage         = GetImplAs<Buffer11>(dispatchIndirectBuffer);
4066     const uint8_t *bufferData = nullptr;
4067     // TODO(jie.a.chen@intel.com): num_groups_x,y,z have to be written into the driver constant
4068     // buffer for the built-in variable gl_NumWorkGroups. There is an opportunity for optimization
4069     // to use GPU->GPU copy instead.
4070     // http://anglebug.com/2807
4071     ANGLE_TRY(storage->getData(context, &bufferData));
4072     const GLuint *groups = reinterpret_cast<const GLuint *>(bufferData + indirect);
4073     ANGLE_TRY(mStateManager.updateStateForCompute(context, groups[0], groups[1], groups[2]));
4074 
4075     ID3D11Buffer *buffer = nullptr;
4076     ANGLE_TRY(storage->getBuffer(context, BUFFER_USAGE_INDIRECT, &buffer));
4077 
4078     mDeviceContext->DispatchIndirect(buffer, static_cast<UINT>(indirect));
4079     return angle::Result::Continue;
4080 }
4081 
createStagingTexture(const gl::Context * context,ResourceType textureType,const d3d11::Format & formatSet,const gl::Extents & size,StagingAccess readAndWriteAccess,TextureHelper11 * textureOut)4082 angle::Result Renderer11::createStagingTexture(const gl::Context *context,
4083                                                ResourceType textureType,
4084                                                const d3d11::Format &formatSet,
4085                                                const gl::Extents &size,
4086                                                StagingAccess readAndWriteAccess,
4087                                                TextureHelper11 *textureOut)
4088 {
4089     Context11 *context11 = GetImplAs<Context11>(context);
4090 
4091     if (textureType == ResourceType::Texture2D)
4092     {
4093         D3D11_TEXTURE2D_DESC stagingDesc;
4094         stagingDesc.Width              = size.width;
4095         stagingDesc.Height             = size.height;
4096         stagingDesc.MipLevels          = 1;
4097         stagingDesc.ArraySize          = 1;
4098         stagingDesc.Format             = formatSet.texFormat;
4099         stagingDesc.SampleDesc.Count   = 1;
4100         stagingDesc.SampleDesc.Quality = 0;
4101         stagingDesc.Usage              = D3D11_USAGE_STAGING;
4102         stagingDesc.BindFlags          = 0;
4103         stagingDesc.CPUAccessFlags     = D3D11_CPU_ACCESS_READ;
4104         stagingDesc.MiscFlags          = 0;
4105 
4106         if (readAndWriteAccess == StagingAccess::READ_WRITE)
4107         {
4108             stagingDesc.CPUAccessFlags |= D3D11_CPU_ACCESS_WRITE;
4109         }
4110 
4111         ANGLE_TRY(allocateTexture(context11, stagingDesc, formatSet, textureOut));
4112         return angle::Result::Continue;
4113     }
4114     ASSERT(textureType == ResourceType::Texture3D);
4115 
4116     D3D11_TEXTURE3D_DESC stagingDesc;
4117     stagingDesc.Width          = size.width;
4118     stagingDesc.Height         = size.height;
4119     stagingDesc.Depth          = 1;
4120     stagingDesc.MipLevels      = 1;
4121     stagingDesc.Format         = formatSet.texFormat;
4122     stagingDesc.Usage          = D3D11_USAGE_STAGING;
4123     stagingDesc.BindFlags      = 0;
4124     stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
4125     stagingDesc.MiscFlags      = 0;
4126 
4127     ANGLE_TRY(allocateTexture(context11, stagingDesc, formatSet, textureOut));
4128     return angle::Result::Continue;
4129 }
4130 
allocateTexture(d3d::Context * context,const D3D11_TEXTURE2D_DESC & desc,const d3d11::Format & format,const D3D11_SUBRESOURCE_DATA * initData,TextureHelper11 * textureOut)4131 angle::Result Renderer11::allocateTexture(d3d::Context *context,
4132                                           const D3D11_TEXTURE2D_DESC &desc,
4133                                           const d3d11::Format &format,
4134                                           const D3D11_SUBRESOURCE_DATA *initData,
4135                                           TextureHelper11 *textureOut)
4136 {
4137     d3d11::Texture2D texture;
4138     ANGLE_TRY(mResourceManager11.allocate(context, this, &desc, initData, &texture));
4139     textureOut->init(std::move(texture), desc, format);
4140     return angle::Result::Continue;
4141 }
4142 
allocateTexture(d3d::Context * context,const D3D11_TEXTURE3D_DESC & desc,const d3d11::Format & format,const D3D11_SUBRESOURCE_DATA * initData,TextureHelper11 * textureOut)4143 angle::Result Renderer11::allocateTexture(d3d::Context *context,
4144                                           const D3D11_TEXTURE3D_DESC &desc,
4145                                           const d3d11::Format &format,
4146                                           const D3D11_SUBRESOURCE_DATA *initData,
4147                                           TextureHelper11 *textureOut)
4148 {
4149     d3d11::Texture3D texture;
4150     ANGLE_TRY(mResourceManager11.allocate(context, this, &desc, initData, &texture));
4151     textureOut->init(std::move(texture), desc, format);
4152     return angle::Result::Continue;
4153 }
4154 
getBlendState(const gl::Context * context,const d3d11::BlendStateKey & key,const d3d11::BlendState ** outBlendState)4155 angle::Result Renderer11::getBlendState(const gl::Context *context,
4156                                         const d3d11::BlendStateKey &key,
4157                                         const d3d11::BlendState **outBlendState)
4158 {
4159     return mStateCache.getBlendState(context, this, key, outBlendState);
4160 }
4161 
getRasterizerState(const gl::Context * context,const gl::RasterizerState & rasterState,bool scissorEnabled,ID3D11RasterizerState ** outRasterizerState)4162 angle::Result Renderer11::getRasterizerState(const gl::Context *context,
4163                                              const gl::RasterizerState &rasterState,
4164                                              bool scissorEnabled,
4165                                              ID3D11RasterizerState **outRasterizerState)
4166 {
4167     return mStateCache.getRasterizerState(context, this, rasterState, scissorEnabled,
4168                                           outRasterizerState);
4169 }
4170 
getDepthStencilState(const gl::Context * context,const gl::DepthStencilState & dsState,const d3d11::DepthStencilState ** outDSState)4171 angle::Result Renderer11::getDepthStencilState(const gl::Context *context,
4172                                                const gl::DepthStencilState &dsState,
4173                                                const d3d11::DepthStencilState **outDSState)
4174 {
4175     return mStateCache.getDepthStencilState(context, this, dsState, outDSState);
4176 }
4177 
getSamplerState(const gl::Context * context,const gl::SamplerState & samplerState,ID3D11SamplerState ** outSamplerState)4178 angle::Result Renderer11::getSamplerState(const gl::Context *context,
4179                                           const gl::SamplerState &samplerState,
4180                                           ID3D11SamplerState **outSamplerState)
4181 {
4182     return mStateCache.getSamplerState(context, this, samplerState, outSamplerState);
4183 }
4184 
getSampleDescQuality(GLuint supportedSamples) const4185 UINT Renderer11::getSampleDescQuality(GLuint supportedSamples) const
4186 {
4187     // Per the documentation on
4188     // https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_standard_multisample_quality_levels
4189     // applications can only request the standard multisample pattern on
4190     // feature levels 10_1 and above.
4191     if (supportedSamples > 0 && mDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_1)
4192     {
4193         return D3D11_STANDARD_MULTISAMPLE_PATTERN;
4194     }
4195     return 0;
4196 }
4197 
clearRenderTarget(const gl::Context * context,RenderTargetD3D * renderTarget,const gl::ColorF & clearColorValue,const float clearDepthValue,const unsigned int clearStencilValue)4198 angle::Result Renderer11::clearRenderTarget(const gl::Context *context,
4199                                             RenderTargetD3D *renderTarget,
4200                                             const gl::ColorF &clearColorValue,
4201                                             const float clearDepthValue,
4202                                             const unsigned int clearStencilValue)
4203 {
4204     RenderTarget11 *rt11 = GetAs<RenderTarget11>(renderTarget);
4205 
4206     if (rt11->getFormatSet().dsvFormat != DXGI_FORMAT_UNKNOWN)
4207     {
4208         ASSERT(rt11->getDepthStencilView().valid());
4209 
4210         const auto &format    = rt11->getFormatSet();
4211         const UINT clearFlags = (format.format().depthBits > 0 ? D3D11_CLEAR_DEPTH : 0) |
4212                                 (format.format().stencilBits ? D3D11_CLEAR_STENCIL : 0);
4213         mDeviceContext->ClearDepthStencilView(rt11->getDepthStencilView().get(), clearFlags,
4214                                               clearDepthValue,
4215                                               static_cast<UINT8>(clearStencilValue));
4216         return angle::Result::Continue;
4217     }
4218 
4219     ASSERT(rt11->getRenderTargetView().valid());
4220     ID3D11RenderTargetView *rtv = rt11->getRenderTargetView().get();
4221 
4222     // There are complications with some types of RTV and FL 9_3 with ClearRenderTargetView.
4223     // See https://msdn.microsoft.com/en-us/library/windows/desktop/ff476388(v=vs.85).aspx
4224     ASSERT(mRenderer11DeviceCaps.featureLevel > D3D_FEATURE_LEVEL_9_3 || !IsArrayRTV(rtv));
4225 
4226     const auto &d3d11Format = rt11->getFormatSet();
4227     const auto &glFormat    = gl::GetSizedInternalFormatInfo(renderTarget->getInternalFormat());
4228 
4229     gl::ColorF safeClearColor = clearColorValue;
4230 
4231     if (d3d11Format.format().alphaBits > 0 && glFormat.alphaBits == 0)
4232     {
4233         safeClearColor.alpha = 1.0f;
4234     }
4235 
4236     mDeviceContext->ClearRenderTargetView(rtv, &safeClearColor.red);
4237     return angle::Result::Continue;
4238 }
4239 
canSelectViewInVertexShader() const4240 bool Renderer11::canSelectViewInVertexShader() const
4241 {
4242     return !getFeatures().selectViewInGeometryShader.enabled &&
4243            getRenderer11DeviceCaps().supportsVpRtIndexWriteFromVertexShader;
4244 }
4245 
mapResource(const gl::Context * context,ID3D11Resource * resource,UINT subResource,D3D11_MAP mapType,UINT mapFlags,D3D11_MAPPED_SUBRESOURCE * mappedResource)4246 angle::Result Renderer11::mapResource(const gl::Context *context,
4247                                       ID3D11Resource *resource,
4248                                       UINT subResource,
4249                                       D3D11_MAP mapType,
4250                                       UINT mapFlags,
4251                                       D3D11_MAPPED_SUBRESOURCE *mappedResource)
4252 {
4253     HRESULT hr = mDeviceContext->Map(resource, subResource, mapType, mapFlags, mappedResource);
4254     ANGLE_TRY_HR(GetImplAs<Context11>(context), hr, "Failed to map D3D11 resource.");
4255     return angle::Result::Continue;
4256 }
4257 
markRawBufferUsage(const gl::Context * context)4258 angle::Result Renderer11::markRawBufferUsage(const gl::Context *context)
4259 {
4260     const gl::State &glState   = context->getState();
4261     const gl::Program *program = glState.getProgram();
4262     for (size_t blockIndex = 0; blockIndex < program->getActiveShaderStorageBlockCount();
4263          blockIndex++)
4264     {
4265         GLuint binding = program->getShaderStorageBlockBinding(static_cast<GLuint>(blockIndex));
4266         const auto &shaderStorageBuffer = glState.getIndexedShaderStorageBuffer(binding);
4267         if (shaderStorageBuffer.get() != nullptr)
4268         {
4269             Buffer11 *bufferStorage = GetImplAs<Buffer11>(shaderStorageBuffer.get());
4270             ANGLE_TRY(bufferStorage->markRawBufferUsage(context));
4271         }
4272     }
4273 
4274     for (const auto &atomicCounterBuffer : program->getState().getAtomicCounterBuffers())
4275     {
4276         GLuint binding     = atomicCounterBuffer.binding;
4277         const auto &buffer = glState.getIndexedAtomicCounterBuffer(binding);
4278 
4279         if (buffer.get() != nullptr)
4280         {
4281             Buffer11 *bufferStorage = GetImplAs<Buffer11>(buffer.get());
4282             ANGLE_TRY(bufferStorage->markRawBufferUsage(context));
4283         }
4284     }
4285     return angle::Result::Continue;
4286 }
4287 
markTransformFeedbackUsage(const gl::Context * context)4288 angle::Result Renderer11::markTransformFeedbackUsage(const gl::Context *context)
4289 {
4290     const gl::State &glState                       = context->getState();
4291     const gl::TransformFeedback *transformFeedback = glState.getCurrentTransformFeedback();
4292     for (size_t i = 0; i < transformFeedback->getIndexedBufferCount(); i++)
4293     {
4294         const gl::OffsetBindingPointer<gl::Buffer> &binding =
4295             transformFeedback->getIndexedBuffer(i);
4296         if (binding.get() != nullptr)
4297         {
4298             BufferD3D *bufferD3D = GetImplAs<BufferD3D>(binding.get());
4299             ANGLE_TRY(bufferD3D->markTransformFeedbackUsage(context));
4300         }
4301     }
4302 
4303     return angle::Result::Continue;
4304 }
4305 
getIncompleteTexture(const gl::Context * context,gl::TextureType type,gl::Texture ** textureOut)4306 angle::Result Renderer11::getIncompleteTexture(const gl::Context *context,
4307                                                gl::TextureType type,
4308                                                gl::Texture **textureOut)
4309 {
4310     return GetImplAs<Context11>(context)->getIncompleteTexture(context, type, textureOut);
4311 }
4312 
getVendorString() const4313 std::string Renderer11::getVendorString() const
4314 {
4315     return GetVendorString(mAdapterDescription.VendorId);
4316 }
4317 
getVersionString() const4318 std::string Renderer11::getVersionString() const
4319 {
4320     std::ostringstream versionString;
4321     versionString << "D3D11-";
4322     if (mRenderer11DeviceCaps.driverVersion.valid())
4323     {
4324         versionString << GetDriverVersionString(mRenderer11DeviceCaps.driverVersion.value());
4325     }
4326     return versionString.str();
4327 }
4328 
CreateRenderer11(egl::Display * display)4329 RendererD3D *CreateRenderer11(egl::Display *display)
4330 {
4331     return new Renderer11(display);
4332 }
4333 
4334 }  // namespace rx
4335