• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     if (!mDevice)
2137     {
2138         return true;
2139     }
2140 
2141     // GetRemovedReason is used to test if the device is removed
2142     HRESULT result = mDevice->GetDeviceRemovedReason();
2143     bool isLost    = FAILED(result);
2144 
2145     if (isLost)
2146     {
2147         ERR() << "The D3D11 device was removed, " << gl::FmtHR(result);
2148     }
2149 
2150     return isLost;
2151 }
2152 
testDeviceResettable()2153 bool Renderer11::testDeviceResettable()
2154 {
2155     // determine if the device is resettable by creating a mock device
2156     PFN_D3D11_CREATE_DEVICE D3D11CreateDevice =
2157         (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
2158 
2159     if (D3D11CreateDevice == nullptr)
2160     {
2161         return false;
2162     }
2163 
2164     ID3D11Device *mockDevice;
2165     D3D_FEATURE_LEVEL mockFeatureLevel;
2166     ID3D11DeviceContext *mockContext;
2167     UINT flags = (mCreateDebugDevice ? D3D11_CREATE_DEVICE_DEBUG : 0);
2168 
2169     ASSERT(mRequestedDriverType != D3D_DRIVER_TYPE_UNKNOWN);
2170     HRESULT result = D3D11CreateDevice(
2171         nullptr, mRequestedDriverType, nullptr, flags, mAvailableFeatureLevels.data(),
2172         static_cast<unsigned int>(mAvailableFeatureLevels.size()), D3D11_SDK_VERSION, &mockDevice,
2173         &mockFeatureLevel, &mockContext);
2174 
2175     if (!mDevice || FAILED(result))
2176     {
2177         return false;
2178     }
2179 
2180     SafeRelease(mockContext);
2181     SafeRelease(mockDevice);
2182 
2183     return true;
2184 }
2185 
release()2186 void Renderer11::release()
2187 {
2188     mScratchMemoryBuffer.clear();
2189 
2190     mAnnotator.release();
2191     gl::UninitializeDebugAnnotations();
2192 
2193     releaseDeviceResources();
2194 
2195     SafeRelease(mDxgiFactory);
2196     SafeRelease(mDxgiAdapter);
2197 
2198     SafeRelease(mDeviceContext3);
2199     SafeRelease(mDeviceContext1);
2200 
2201     if (mDeviceContext)
2202     {
2203         mDeviceContext->ClearState();
2204         mDeviceContext->Flush();
2205         SafeRelease(mDeviceContext);
2206     }
2207 
2208     SafeRelease(mDevice);
2209     SafeRelease(mDebug);
2210 
2211     if (mD3d11Module)
2212     {
2213         FreeLibrary(mD3d11Module);
2214         mD3d11Module = nullptr;
2215     }
2216 
2217     if (mDxgiModule)
2218     {
2219         FreeLibrary(mDxgiModule);
2220         mDxgiModule = nullptr;
2221     }
2222 
2223     if (mDCompModule)
2224     {
2225         FreeLibrary(mDCompModule);
2226         mDCompModule = nullptr;
2227     }
2228 
2229     mDevice12.Reset();
2230     mCommandQueue.Reset();
2231 
2232     if (mD3d12Module)
2233     {
2234         FreeLibrary(mD3d12Module);
2235         mD3d12Module = nullptr;
2236     }
2237 
2238     mCompiler.release();
2239 
2240     mSupportsShareHandles.reset();
2241 }
2242 
resetDevice()2243 bool Renderer11::resetDevice()
2244 {
2245     // recreate everything
2246     release();
2247     egl::Error result = initialize();
2248 
2249     if (result.isError())
2250     {
2251         ERR() << "Could not reinitialize D3D11 device: " << result;
2252         return false;
2253     }
2254 
2255     return true;
2256 }
2257 
getRendererDescription() const2258 std::string Renderer11::getRendererDescription() const
2259 {
2260     std::ostringstream rendererString;
2261 
2262     rendererString << mDescription;
2263     rendererString << " Direct3D11";
2264 
2265     rendererString << " vs_" << getMajorShaderModel() << "_" << getMinorShaderModel()
2266                    << getShaderModelSuffix();
2267     rendererString << " ps_" << getMajorShaderModel() << "_" << getMinorShaderModel()
2268                    << getShaderModelSuffix();
2269 
2270     return rendererString.str();
2271 }
2272 
getAdapterIdentifier() const2273 DeviceIdentifier Renderer11::getAdapterIdentifier() const
2274 {
2275     // Don't use the AdapterLuid here, since that doesn't persist across reboot.
2276     DeviceIdentifier deviceIdentifier = {};
2277     deviceIdentifier.VendorId         = mAdapterDescription.VendorId;
2278     deviceIdentifier.DeviceId         = mAdapterDescription.DeviceId;
2279     deviceIdentifier.SubSysId         = mAdapterDescription.SubSysId;
2280     deviceIdentifier.Revision         = mAdapterDescription.Revision;
2281     deviceIdentifier.FeatureLevel     = static_cast<UINT>(mRenderer11DeviceCaps.featureLevel);
2282 
2283     return deviceIdentifier;
2284 }
2285 
getReservedVertexUniformVectors() const2286 unsigned int Renderer11::getReservedVertexUniformVectors() const
2287 {
2288     // Driver uniforms are stored in a separate constant buffer
2289     return d3d11_gl::GetReservedVertexUniformVectors(mRenderer11DeviceCaps.featureLevel);
2290 }
2291 
getReservedFragmentUniformVectors() const2292 unsigned int Renderer11::getReservedFragmentUniformVectors() const
2293 {
2294     // Driver uniforms are stored in a separate constant buffer
2295     return d3d11_gl::GetReservedFragmentUniformVectors(mRenderer11DeviceCaps.featureLevel);
2296 }
2297 
getReservedShaderUniformBuffers() const2298 gl::ShaderMap<unsigned int> Renderer11::getReservedShaderUniformBuffers() const
2299 {
2300     gl::ShaderMap<unsigned int> shaderReservedUniformBuffers = {};
2301 
2302     // we reserve one buffer for the application uniforms, and one for driver uniforms
2303     shaderReservedUniformBuffers[gl::ShaderType::Vertex]   = 2;
2304     shaderReservedUniformBuffers[gl::ShaderType::Fragment] = 2;
2305 
2306     return shaderReservedUniformBuffers;
2307 }
2308 
getDeviceType() const2309 d3d11::ANGLED3D11DeviceType Renderer11::getDeviceType() const
2310 {
2311     if (mCreatedWithDeviceEXT)
2312     {
2313         return d3d11::GetDeviceType(mDevice);
2314     }
2315 
2316     if ((mRequestedDriverType == D3D_DRIVER_TYPE_SOFTWARE) ||
2317         (mRequestedDriverType == D3D_DRIVER_TYPE_REFERENCE) ||
2318         (mRequestedDriverType == D3D_DRIVER_TYPE_NULL))
2319     {
2320         return d3d11::ANGLE_D3D11_DEVICE_TYPE_SOFTWARE_REF_OR_NULL;
2321     }
2322 
2323     if (mRequestedDriverType == D3D_DRIVER_TYPE_WARP)
2324     {
2325         return d3d11::ANGLE_D3D11_DEVICE_TYPE_WARP;
2326     }
2327 
2328     return d3d11::ANGLE_D3D11_DEVICE_TYPE_HARDWARE;
2329 }
2330 
getShareHandleSupport() const2331 bool Renderer11::getShareHandleSupport() const
2332 {
2333     if (mSupportsShareHandles.valid())
2334     {
2335         return mSupportsShareHandles.value();
2336     }
2337 
2338     // We only currently support share handles with BGRA surfaces, because
2339     // chrome needs BGRA. Once chrome fixes this, we should always support them.
2340     if (!getNativeExtensions().textureFormatBGRA8888)
2341     {
2342         mSupportsShareHandles = false;
2343         return false;
2344     }
2345 
2346     // PIX doesn't seem to support using share handles, so disable them.
2347     if (gl::DebugAnnotationsActive())
2348     {
2349         mSupportsShareHandles = false;
2350         return false;
2351     }
2352 
2353     // Also disable share handles on Feature Level 9_3, since it doesn't support share handles on
2354     // RGBA8 textures/swapchains.
2355     if (mRenderer11DeviceCaps.featureLevel <= D3D_FEATURE_LEVEL_9_3)
2356     {
2357         mSupportsShareHandles = false;
2358         return false;
2359     }
2360 
2361     // Find out which type of D3D11 device the Renderer11 is using
2362     d3d11::ANGLED3D11DeviceType deviceType = getDeviceType();
2363     if (deviceType == d3d11::ANGLE_D3D11_DEVICE_TYPE_UNKNOWN)
2364     {
2365         mSupportsShareHandles = false;
2366         return false;
2367     }
2368 
2369     if (deviceType == d3d11::ANGLE_D3D11_DEVICE_TYPE_SOFTWARE_REF_OR_NULL)
2370     {
2371         // Software/Reference/NULL devices don't support share handles
2372         mSupportsShareHandles = false;
2373         return false;
2374     }
2375 
2376     if (deviceType == d3d11::ANGLE_D3D11_DEVICE_TYPE_WARP)
2377     {
2378 #if !defined(ANGLE_ENABLE_WINDOWS_UWP)
2379         if (!IsWindows8OrGreater())
2380         {
2381             // WARP on Windows 7 doesn't support shared handles
2382             mSupportsShareHandles = false;
2383             return false;
2384         }
2385 #endif  // !defined(ANGLE_ENABLE_WINDOWS_UWP)
2386 
2387         // WARP on Windows 8.0+ supports shared handles when shared with another WARP device
2388         // TODO: allow applications to query for HARDWARE or WARP-specific share handles,
2389         //       to prevent them trying to use a WARP share handle with an a HW device (or
2390         //       vice-versa)
2391         //       e.g. by creating EGL_D3D11_[HARDWARE/WARP]_DEVICE_SHARE_HANDLE_ANGLE
2392         mSupportsShareHandles = true;
2393         return true;
2394     }
2395 
2396     ASSERT(mCreatedWithDeviceEXT || mRequestedDriverType == D3D_DRIVER_TYPE_HARDWARE);
2397     mSupportsShareHandles = true;
2398     return true;
2399 }
2400 
getMajorShaderModel() const2401 int Renderer11::getMajorShaderModel() const
2402 {
2403     switch (mRenderer11DeviceCaps.featureLevel)
2404     {
2405         case D3D_FEATURE_LEVEL_11_1:
2406         case D3D_FEATURE_LEVEL_11_0:
2407             return D3D11_SHADER_MAJOR_VERSION;  // 5
2408         case D3D_FEATURE_LEVEL_10_1:
2409             return D3D10_1_SHADER_MAJOR_VERSION;  // 4
2410         case D3D_FEATURE_LEVEL_10_0:
2411             return D3D10_SHADER_MAJOR_VERSION;  // 4
2412         case D3D_FEATURE_LEVEL_9_3:
2413             return D3D10_SHADER_MAJOR_VERSION;  // 4
2414         default:
2415             UNREACHABLE();
2416             return 0;
2417     }
2418 }
2419 
getMinorShaderModel() const2420 int Renderer11::getMinorShaderModel() const
2421 {
2422     switch (mRenderer11DeviceCaps.featureLevel)
2423     {
2424         case D3D_FEATURE_LEVEL_11_1:
2425         case D3D_FEATURE_LEVEL_11_0:
2426             return D3D11_SHADER_MINOR_VERSION;  // 0
2427         case D3D_FEATURE_LEVEL_10_1:
2428             return D3D10_1_SHADER_MINOR_VERSION;  // 1
2429         case D3D_FEATURE_LEVEL_10_0:
2430             return D3D10_SHADER_MINOR_VERSION;  // 0
2431         case D3D_FEATURE_LEVEL_9_3:
2432             return D3D10_SHADER_MINOR_VERSION;  // 0
2433         default:
2434             UNREACHABLE();
2435             return 0;
2436     }
2437 }
2438 
getShaderModelSuffix() const2439 std::string Renderer11::getShaderModelSuffix() const
2440 {
2441     switch (mRenderer11DeviceCaps.featureLevel)
2442     {
2443         case D3D_FEATURE_LEVEL_11_1:
2444         case D3D_FEATURE_LEVEL_11_0:
2445             return "";
2446         case D3D_FEATURE_LEVEL_10_1:
2447             return "";
2448         case D3D_FEATURE_LEVEL_10_0:
2449             return "";
2450         case D3D_FEATURE_LEVEL_9_3:
2451             return "_level_9_3";
2452         default:
2453             UNREACHABLE();
2454             return "";
2455     }
2456 }
2457 
copyImageInternal(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,RenderTargetD3D * destRenderTarget)2458 angle::Result Renderer11::copyImageInternal(const gl::Context *context,
2459                                             const gl::Framebuffer *framebuffer,
2460                                             const gl::Rectangle &sourceRect,
2461                                             GLenum destFormat,
2462                                             const gl::Offset &destOffset,
2463                                             RenderTargetD3D *destRenderTarget)
2464 {
2465     const gl::FramebufferAttachment *colorAttachment = framebuffer->getReadColorAttachment();
2466     ASSERT(colorAttachment);
2467 
2468     RenderTarget11 *sourceRenderTarget = nullptr;
2469     ANGLE_TRY(colorAttachment->getRenderTarget(context, 0, &sourceRenderTarget));
2470     ASSERT(sourceRenderTarget);
2471 
2472     const d3d11::RenderTargetView &dest =
2473         GetAs<RenderTarget11>(destRenderTarget)->getRenderTargetView();
2474     ASSERT(dest.valid());
2475 
2476     gl::Box sourceArea(sourceRect.x, sourceRect.y, 0, sourceRect.width, sourceRect.height, 1);
2477     gl::Extents sourceSize(sourceRenderTarget->getWidth(), sourceRenderTarget->getHeight(), 1);
2478 
2479     const bool invertSource = UsePresentPathFast(this, colorAttachment);
2480     if (invertSource)
2481     {
2482         sourceArea.y      = sourceSize.height - sourceRect.y;
2483         sourceArea.height = -sourceArea.height;
2484     }
2485 
2486     gl::Box destArea(destOffset.x, destOffset.y, 0, sourceRect.width, sourceRect.height, 1);
2487     gl::Extents destSize(destRenderTarget->getWidth(), destRenderTarget->getHeight(), 1);
2488 
2489     // Use nearest filtering because source and destination are the same size for the direct copy.
2490     // Convert to the unsized format before calling copyTexture.
2491     GLenum sourceFormat = colorAttachment->getFormat().info->format;
2492     if (sourceRenderTarget->getTexture().is2D() && sourceRenderTarget->isMultisampled())
2493     {
2494         TextureHelper11 tex;
2495         ANGLE_TRY(resolveMultisampledTexture(context, sourceRenderTarget,
2496                                              colorAttachment->getDepthSize() > 0,
2497                                              colorAttachment->getStencilSize() > 0, &tex));
2498 
2499         D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
2500         viewDesc.Format                    = sourceRenderTarget->getFormatSet().srvFormat;
2501         viewDesc.ViewDimension             = D3D11_SRV_DIMENSION_TEXTURE2D;
2502         viewDesc.Texture2D.MipLevels       = 1;
2503         viewDesc.Texture2D.MostDetailedMip = 0;
2504 
2505         d3d11::SharedSRV readSRV;
2506         ANGLE_TRY(allocateResource(GetImplAs<Context11>(context), viewDesc, tex.get(), &readSRV));
2507         ASSERT(readSRV.valid());
2508 
2509         ANGLE_TRY(mBlit->copyTexture(context, readSRV, sourceArea, sourceSize, sourceFormat, dest,
2510                                      destArea, destSize, nullptr, gl::GetUnsizedFormat(destFormat),
2511                                      GL_NONE, GL_NEAREST, false, false, false));
2512 
2513         return angle::Result::Continue;
2514     }
2515 
2516     ASSERT(!sourceRenderTarget->isMultisampled());
2517 
2518     const d3d11::SharedSRV &source = sourceRenderTarget->getBlitShaderResourceView(context);
2519     ASSERT(source.valid());
2520 
2521     ANGLE_TRY(mBlit->copyTexture(context, source, sourceArea, sourceSize, sourceFormat, dest,
2522                                  destArea, destSize, nullptr, gl::GetUnsizedFormat(destFormat),
2523                                  GL_NONE, GL_NEAREST, false, false, false));
2524 
2525     return angle::Result::Continue;
2526 }
2527 
copyImage2D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2528 angle::Result Renderer11::copyImage2D(const gl::Context *context,
2529                                       const gl::Framebuffer *framebuffer,
2530                                       const gl::Rectangle &sourceRect,
2531                                       GLenum destFormat,
2532                                       const gl::Offset &destOffset,
2533                                       TextureStorage *storage,
2534                                       GLint level)
2535 {
2536     TextureStorage11_2D *storage11 = GetAs<TextureStorage11_2D>(storage);
2537     ASSERT(storage11);
2538 
2539     gl::ImageIndex index              = gl::ImageIndex::Make2D(level);
2540     RenderTargetD3D *destRenderTarget = nullptr;
2541     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2542                                          &destRenderTarget));
2543     ASSERT(destRenderTarget);
2544 
2545     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2546                                 destRenderTarget));
2547 
2548     storage11->markLevelDirty(level);
2549 
2550     return angle::Result::Continue;
2551 }
2552 
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)2553 angle::Result Renderer11::copyImageCube(const gl::Context *context,
2554                                         const gl::Framebuffer *framebuffer,
2555                                         const gl::Rectangle &sourceRect,
2556                                         GLenum destFormat,
2557                                         const gl::Offset &destOffset,
2558                                         TextureStorage *storage,
2559                                         gl::TextureTarget target,
2560                                         GLint level)
2561 {
2562     TextureStorage11_Cube *storage11 = GetAs<TextureStorage11_Cube>(storage);
2563     ASSERT(storage11);
2564 
2565     gl::ImageIndex index              = gl::ImageIndex::MakeCubeMapFace(target, level);
2566     RenderTargetD3D *destRenderTarget = nullptr;
2567     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2568                                          &destRenderTarget));
2569     ASSERT(destRenderTarget);
2570 
2571     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2572                                 destRenderTarget));
2573 
2574     storage11->markLevelDirty(level);
2575 
2576     return angle::Result::Continue;
2577 }
2578 
copyImage3D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2579 angle::Result Renderer11::copyImage3D(const gl::Context *context,
2580                                       const gl::Framebuffer *framebuffer,
2581                                       const gl::Rectangle &sourceRect,
2582                                       GLenum destFormat,
2583                                       const gl::Offset &destOffset,
2584                                       TextureStorage *storage,
2585                                       GLint level)
2586 {
2587     TextureStorage11_3D *storage11 = GetAs<TextureStorage11_3D>(storage);
2588     ASSERT(storage11);
2589 
2590     gl::ImageIndex index              = gl::ImageIndex::Make3D(level, destOffset.z);
2591     RenderTargetD3D *destRenderTarget = nullptr;
2592     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2593                                          &destRenderTarget));
2594     ASSERT(destRenderTarget);
2595 
2596     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2597                                 destRenderTarget));
2598 
2599     storage11->markLevelDirty(level);
2600 
2601     return angle::Result::Continue;
2602 }
2603 
copyImage2DArray(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2604 angle::Result Renderer11::copyImage2DArray(const gl::Context *context,
2605                                            const gl::Framebuffer *framebuffer,
2606                                            const gl::Rectangle &sourceRect,
2607                                            GLenum destFormat,
2608                                            const gl::Offset &destOffset,
2609                                            TextureStorage *storage,
2610                                            GLint level)
2611 {
2612     TextureStorage11_2DArray *storage11 = GetAs<TextureStorage11_2DArray>(storage);
2613     ASSERT(storage11);
2614 
2615     gl::ImageIndex index              = gl::ImageIndex::Make2DArray(level, destOffset.z);
2616     RenderTargetD3D *destRenderTarget = nullptr;
2617     ANGLE_TRY(storage11->getRenderTarget(context, index, storage11->getRenderToTextureSamples(),
2618                                          &destRenderTarget));
2619     ASSERT(destRenderTarget);
2620 
2621     ANGLE_TRY(copyImageInternal(context, framebuffer, sourceRect, destFormat, destOffset,
2622                                 destRenderTarget));
2623     storage11->markLevelDirty(level);
2624 
2625     return angle::Result::Continue;
2626 }
2627 
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)2628 angle::Result Renderer11::copyTexture(const gl::Context *context,
2629                                       const gl::Texture *source,
2630                                       GLint sourceLevel,
2631                                       gl::TextureTarget srcTarget,
2632                                       const gl::Box &sourceBox,
2633                                       GLenum destFormat,
2634                                       GLenum destType,
2635                                       const gl::Offset &destOffset,
2636                                       TextureStorage *storage,
2637                                       gl::TextureTarget destTarget,
2638                                       GLint destLevel,
2639                                       bool unpackFlipY,
2640                                       bool unpackPremultiplyAlpha,
2641                                       bool unpackUnmultiplyAlpha)
2642 {
2643 
2644     TextureD3D *sourceD3D                = GetImplAs<TextureD3D>(source);
2645     const gl::ImageDesc &sourceImageDesc = source->getTextureState().getImageDesc(
2646         NonCubeTextureTypeToTarget(source->getType()), sourceLevel);
2647 
2648     TextureStorage11 *destStorage11 = GetAs<TextureStorage11>(storage);
2649     ASSERT(destStorage11);
2650 
2651     // Check for fast path where a CopySubresourceRegion can be used.
2652     if (unpackPremultiplyAlpha == unpackUnmultiplyAlpha && !unpackFlipY &&
2653         sourceImageDesc.format.info->sizedInternalFormat ==
2654             destStorage11->getFormatSet().internalFormat)
2655     {
2656         const TextureHelper11 *destResource = nullptr;
2657         ANGLE_TRY(destStorage11->getResource(context, &destResource));
2658 
2659         if (srcTarget == gl::TextureTarget::_2D || srcTarget == gl::TextureTarget::_3D)
2660         {
2661             gl::ImageIndex sourceIndex = gl::ImageIndex::MakeFromTarget(srcTarget, sourceLevel, 1);
2662             const TextureHelper11 *sourceResource = nullptr;
2663             UINT sourceSubresource                = 0;
2664             ANGLE_TRY(GetTextureD3DResourceFromStorageOrImage(context, sourceD3D, sourceIndex,
2665                                                               &sourceResource, &sourceSubresource));
2666 
2667             gl::ImageIndex destIndex = gl::ImageIndex::MakeFromTarget(destTarget, destLevel, 1);
2668 
2669             UINT destSubresource = 0;
2670             ANGLE_TRY(destStorage11->getSubresourceIndex(context, destIndex, &destSubresource));
2671 
2672             D3D11_BOX d3dBox{static_cast<UINT>(sourceBox.x),
2673                              static_cast<UINT>(sourceBox.y),
2674                              static_cast<UINT>(sourceBox.z),
2675                              static_cast<UINT>(sourceBox.x + sourceBox.width),
2676                              static_cast<UINT>(sourceBox.y + sourceBox.height),
2677                              static_cast<UINT>(sourceBox.z + sourceBox.depth)};
2678 
2679             mDeviceContext->CopySubresourceRegion(
2680                 destResource->get(), destSubresource, destOffset.x, destOffset.y, destOffset.z,
2681                 sourceResource->get(), sourceSubresource, &d3dBox);
2682         }
2683         else if (srcTarget == gl::TextureTarget::_2DArray)
2684         {
2685             D3D11_BOX d3dBox{static_cast<UINT>(sourceBox.x),
2686                              static_cast<UINT>(sourceBox.y),
2687                              0,
2688                              static_cast<UINT>(sourceBox.x + sourceBox.width),
2689                              static_cast<UINT>(sourceBox.y + sourceBox.height),
2690                              1u};
2691 
2692             for (int i = 0; i < sourceBox.depth; i++)
2693             {
2694                 gl::ImageIndex sourceIndex =
2695                     gl::ImageIndex::Make2DArray(sourceLevel, i + sourceBox.z);
2696                 const TextureHelper11 *sourceResource = nullptr;
2697                 UINT sourceSubresource                = 0;
2698                 ANGLE_TRY(GetTextureD3DResourceFromStorageOrImage(
2699                     context, sourceD3D, sourceIndex, &sourceResource, &sourceSubresource));
2700 
2701                 gl::ImageIndex dIndex = gl::ImageIndex::Make2DArray(destLevel, i + destOffset.z);
2702                 UINT destSubresource  = 0;
2703                 ANGLE_TRY(destStorage11->getSubresourceIndex(context, dIndex, &destSubresource));
2704 
2705                 mDeviceContext->CopySubresourceRegion(
2706                     destResource->get(), destSubresource, destOffset.x, destOffset.y, 0,
2707                     sourceResource->get(), sourceSubresource, &d3dBox);
2708             }
2709         }
2710         else
2711         {
2712             UNREACHABLE();
2713         }
2714     }
2715     else
2716     {
2717         TextureStorage *sourceStorage = nullptr;
2718         ANGLE_TRY(sourceD3D->getNativeTexture(context, &sourceStorage));
2719 
2720         TextureStorage11 *sourceStorage11 = GetAs<TextureStorage11>(sourceStorage);
2721         ASSERT(sourceStorage11);
2722 
2723         const d3d11::SharedSRV *sourceSRV = nullptr;
2724         ANGLE_TRY(sourceStorage11->getSRVLevels(context, sourceLevel, sourceLevel, &sourceSRV));
2725 
2726         gl::ImageIndex destIndex;
2727         if (destTarget == gl::TextureTarget::_2D || destTarget == gl::TextureTarget::_3D ||
2728             gl::IsCubeMapFaceTarget(destTarget))
2729         {
2730             destIndex = gl::ImageIndex::MakeFromTarget(destTarget, destLevel, 1);
2731         }
2732         else if (destTarget == gl::TextureTarget::_2DArray)
2733         {
2734             destIndex = gl::ImageIndex::Make2DArrayRange(destLevel, 0, sourceImageDesc.size.depth);
2735         }
2736         else
2737         {
2738             UNREACHABLE();
2739         }
2740 
2741         RenderTargetD3D *destRenderTargetD3D = nullptr;
2742         ANGLE_TRY(destStorage11->getRenderTarget(
2743             context, destIndex, destStorage11->getRenderToTextureSamples(), &destRenderTargetD3D));
2744 
2745         RenderTarget11 *destRenderTarget11 = GetAs<RenderTarget11>(destRenderTargetD3D);
2746 
2747         const d3d11::RenderTargetView &destRTV = destRenderTarget11->getRenderTargetView();
2748         ASSERT(destRTV.valid());
2749 
2750         gl::Box sourceArea(sourceBox.x, sourceBox.y, sourceBox.z, sourceBox.width, sourceBox.height,
2751                            sourceBox.depth);
2752 
2753         if (unpackFlipY)
2754         {
2755             sourceArea.y += sourceArea.height;
2756             sourceArea.height = -sourceArea.height;
2757         }
2758 
2759         gl::Box destArea(destOffset.x, destOffset.y, destOffset.z, sourceBox.width,
2760                          sourceBox.height, sourceBox.depth);
2761 
2762         gl::Extents destSize(destRenderTarget11->getWidth(), destRenderTarget11->getHeight(),
2763                              sourceBox.depth);
2764 
2765         // Use nearest filtering because source and destination are the same size for the direct
2766         // copy
2767         GLenum sourceFormat = source->getFormat(srcTarget, sourceLevel).info->format;
2768         ANGLE_TRY(mBlit->copyTexture(context, *sourceSRV, sourceArea, sourceImageDesc.size,
2769                                      sourceFormat, destRTV, destArea, destSize, nullptr, destFormat,
2770                                      destType, GL_NEAREST, false, unpackPremultiplyAlpha,
2771                                      unpackUnmultiplyAlpha));
2772     }
2773 
2774     destStorage11->markLevelDirty(destLevel);
2775 
2776     return angle::Result::Continue;
2777 }
2778 
copyCompressedTexture(const gl::Context * context,const gl::Texture * source,GLint sourceLevel,TextureStorage * storage,GLint destLevel)2779 angle::Result Renderer11::copyCompressedTexture(const gl::Context *context,
2780                                                 const gl::Texture *source,
2781                                                 GLint sourceLevel,
2782                                                 TextureStorage *storage,
2783                                                 GLint destLevel)
2784 {
2785     TextureStorage11_2D *destStorage11 = GetAs<TextureStorage11_2D>(storage);
2786     ASSERT(destStorage11);
2787 
2788     const TextureHelper11 *destResource = nullptr;
2789     ANGLE_TRY(destStorage11->getResource(context, &destResource));
2790 
2791     gl::ImageIndex destIndex = gl::ImageIndex::Make2D(destLevel);
2792     UINT destSubresource     = 0;
2793     ANGLE_TRY(destStorage11->getSubresourceIndex(context, destIndex, &destSubresource));
2794 
2795     TextureD3D *sourceD3D = GetImplAs<TextureD3D>(source);
2796     ASSERT(sourceD3D);
2797 
2798     TextureStorage *sourceStorage = nullptr;
2799     ANGLE_TRY(sourceD3D->getNativeTexture(context, &sourceStorage));
2800 
2801     TextureStorage11_2D *sourceStorage11 = GetAs<TextureStorage11_2D>(sourceStorage);
2802     ASSERT(sourceStorage11);
2803 
2804     const TextureHelper11 *sourceResource = nullptr;
2805     ANGLE_TRY(sourceStorage11->getResource(context, &sourceResource));
2806 
2807     gl::ImageIndex sourceIndex = gl::ImageIndex::Make2D(sourceLevel);
2808     UINT sourceSubresource     = 0;
2809     ANGLE_TRY(sourceStorage11->getSubresourceIndex(context, sourceIndex, &sourceSubresource));
2810 
2811     mDeviceContext->CopySubresourceRegion(destResource->get(), destSubresource, 0, 0, 0,
2812                                           sourceResource->get(), sourceSubresource, nullptr);
2813 
2814     return angle::Result::Continue;
2815 }
2816 
createRenderTarget(const gl::Context * context,int width,int height,GLenum format,GLsizei samples,RenderTargetD3D ** outRT)2817 angle::Result Renderer11::createRenderTarget(const gl::Context *context,
2818                                              int width,
2819                                              int height,
2820                                              GLenum format,
2821                                              GLsizei samples,
2822                                              RenderTargetD3D **outRT)
2823 {
2824     const d3d11::Format &formatInfo = d3d11::Format::Get(format, mRenderer11DeviceCaps);
2825 
2826     const gl::TextureCaps &textureCaps = getNativeTextureCaps().get(format);
2827     GLuint supportedSamples            = textureCaps.getNearestSamples(samples);
2828 
2829     Context11 *context11 = GetImplAs<Context11>(context);
2830 
2831     if (width > 0 && height > 0)
2832     {
2833         // Create texture resource
2834         D3D11_TEXTURE2D_DESC desc;
2835         desc.Width              = width;
2836         desc.Height             = height;
2837         desc.MipLevels          = 1;
2838         desc.ArraySize          = 1;
2839         desc.Format             = formatInfo.texFormat;
2840         desc.SampleDesc.Count   = (supportedSamples == 0) ? 1 : supportedSamples;
2841         desc.SampleDesc.Quality = getSampleDescQuality(supportedSamples);
2842         desc.Usage              = D3D11_USAGE_DEFAULT;
2843         desc.CPUAccessFlags     = 0;
2844         desc.MiscFlags          = 0;
2845 
2846         // If a rendertarget or depthstencil format exists for this texture format,
2847         // we'll flag it to allow binding that way. Shader resource views are a little
2848         // more complicated.
2849         bool bindRTV = false, bindDSV = false, bindSRV = false;
2850         bindRTV = (formatInfo.rtvFormat != DXGI_FORMAT_UNKNOWN);
2851         bindDSV = (formatInfo.dsvFormat != DXGI_FORMAT_UNKNOWN);
2852         bindSRV = (formatInfo.srvFormat != DXGI_FORMAT_UNKNOWN);
2853 
2854         bool isMultisampledDepthStencil = bindDSV && desc.SampleDesc.Count > 1;
2855         if (isMultisampledDepthStencil &&
2856             !mRenderer11DeviceCaps.supportsMultisampledDepthStencilSRVs)
2857         {
2858             bindSRV = false;
2859         }
2860 
2861         desc.BindFlags = (bindRTV ? D3D11_BIND_RENDER_TARGET : 0) |
2862                          (bindDSV ? D3D11_BIND_DEPTH_STENCIL : 0) |
2863                          (bindSRV ? D3D11_BIND_SHADER_RESOURCE : 0);
2864 
2865         // The format must be either an RTV or a DSV
2866         ASSERT(bindRTV != bindDSV);
2867 
2868         TextureHelper11 texture;
2869         ANGLE_TRY(allocateTexture(context11, desc, formatInfo, &texture));
2870         texture.setDebugName("createRenderTarget.Texture");
2871 
2872         d3d11::SharedSRV srv;
2873         d3d11::SharedSRV blitSRV;
2874         if (bindSRV)
2875         {
2876             D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
2877             srvDesc.Format        = formatInfo.srvFormat;
2878             srvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_SRV_DIMENSION_TEXTURE2D
2879                                                             : D3D11_SRV_DIMENSION_TEXTURE2DMS;
2880             srvDesc.Texture2D.MostDetailedMip = 0;
2881             srvDesc.Texture2D.MipLevels       = 1;
2882 
2883             ANGLE_TRY(allocateResource(context11, srvDesc, texture.get(), &srv));
2884             srv.setDebugName("createRenderTarget.SRV");
2885 
2886             if (formatInfo.blitSRVFormat != formatInfo.srvFormat)
2887             {
2888                 D3D11_SHADER_RESOURCE_VIEW_DESC blitSRVDesc;
2889                 blitSRVDesc.Format        = formatInfo.blitSRVFormat;
2890                 blitSRVDesc.ViewDimension = (supportedSamples == 0)
2891                                                 ? D3D11_SRV_DIMENSION_TEXTURE2D
2892                                                 : D3D11_SRV_DIMENSION_TEXTURE2DMS;
2893                 blitSRVDesc.Texture2D.MostDetailedMip = 0;
2894                 blitSRVDesc.Texture2D.MipLevels       = 1;
2895 
2896                 ANGLE_TRY(allocateResource(context11, blitSRVDesc, texture.get(), &blitSRV));
2897                 blitSRV.setDebugName("createRenderTarget.BlitSRV");
2898             }
2899             else
2900             {
2901                 blitSRV = srv.makeCopy();
2902             }
2903         }
2904 
2905         if (bindDSV)
2906         {
2907             D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
2908             dsvDesc.Format        = formatInfo.dsvFormat;
2909             dsvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_DSV_DIMENSION_TEXTURE2D
2910                                                             : D3D11_DSV_DIMENSION_TEXTURE2DMS;
2911             dsvDesc.Texture2D.MipSlice = 0;
2912             dsvDesc.Flags              = 0;
2913 
2914             d3d11::DepthStencilView dsv;
2915             ANGLE_TRY(allocateResource(context11, dsvDesc, texture.get(), &dsv));
2916             dsv.setDebugName("createRenderTarget.DSV");
2917 
2918             *outRT = new TextureRenderTarget11(std::move(dsv), texture, srv, format, formatInfo,
2919                                                width, height, 1, supportedSamples);
2920         }
2921         else if (bindRTV)
2922         {
2923             D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
2924             rtvDesc.Format        = formatInfo.rtvFormat;
2925             rtvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_RTV_DIMENSION_TEXTURE2D
2926                                                             : D3D11_RTV_DIMENSION_TEXTURE2DMS;
2927             rtvDesc.Texture2D.MipSlice = 0;
2928 
2929             d3d11::RenderTargetView rtv;
2930             ANGLE_TRY(allocateResource(context11, rtvDesc, texture.get(), &rtv));
2931             rtv.setDebugName("createRenderTarget.RTV");
2932 
2933             if (formatInfo.dataInitializerFunction != nullptr)
2934             {
2935                 const float clearValues[4] = {0.0f, 0.0f, 0.0f, 1.0f};
2936                 mDeviceContext->ClearRenderTargetView(rtv.get(), clearValues);
2937             }
2938 
2939             *outRT = new TextureRenderTarget11(std::move(rtv), texture, srv, blitSRV, format,
2940                                                formatInfo, width, height, 1, supportedSamples);
2941         }
2942         else
2943         {
2944             UNREACHABLE();
2945         }
2946     }
2947     else
2948     {
2949         *outRT = new TextureRenderTarget11(d3d11::RenderTargetView(), TextureHelper11(),
2950                                            d3d11::SharedSRV(), d3d11::SharedSRV(), format,
2951                                            d3d11::Format::Get(GL_NONE, mRenderer11DeviceCaps),
2952                                            width, height, 1, supportedSamples);
2953     }
2954 
2955     return angle::Result::Continue;
2956 }
2957 
createRenderTargetCopy(const gl::Context * context,RenderTargetD3D * source,RenderTargetD3D ** outRT)2958 angle::Result Renderer11::createRenderTargetCopy(const gl::Context *context,
2959                                                  RenderTargetD3D *source,
2960                                                  RenderTargetD3D **outRT)
2961 {
2962     ASSERT(source != nullptr);
2963 
2964     RenderTargetD3D *newRT = nullptr;
2965     ANGLE_TRY(createRenderTarget(context, source->getWidth(), source->getHeight(),
2966                                  source->getInternalFormat(), source->getSamples(), &newRT));
2967 
2968     RenderTarget11 *source11 = GetAs<RenderTarget11>(source);
2969     RenderTarget11 *dest11   = GetAs<RenderTarget11>(newRT);
2970 
2971     mDeviceContext->CopySubresourceRegion(dest11->getTexture().get(), dest11->getSubresourceIndex(),
2972                                           0, 0, 0, source11->getTexture().get(),
2973                                           source11->getSubresourceIndex(), nullptr);
2974     *outRT = newRT;
2975     return angle::Result::Continue;
2976 }
2977 
loadExecutable(d3d::Context * context,const uint8_t * function,size_t length,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,ShaderExecutableD3D ** outExecutable)2978 angle::Result Renderer11::loadExecutable(d3d::Context *context,
2979                                          const uint8_t *function,
2980                                          size_t length,
2981                                          gl::ShaderType type,
2982                                          const std::vector<D3DVarying> &streamOutVaryings,
2983                                          bool separatedOutputBuffers,
2984                                          ShaderExecutableD3D **outExecutable)
2985 {
2986     ShaderData shaderData(function, length);
2987 
2988     switch (type)
2989     {
2990         case gl::ShaderType::Vertex:
2991         {
2992             d3d11::VertexShader vertexShader;
2993             d3d11::GeometryShader streamOutShader;
2994             ANGLE_TRY(allocateResource(context, shaderData, &vertexShader));
2995 
2996             if (!streamOutVaryings.empty())
2997             {
2998                 std::vector<D3D11_SO_DECLARATION_ENTRY> soDeclaration;
2999                 soDeclaration.reserve(streamOutVaryings.size());
3000 
3001                 for (const auto &streamOutVarying : streamOutVaryings)
3002                 {
3003                     D3D11_SO_DECLARATION_ENTRY entry = {};
3004                     entry.Stream                     = 0;
3005                     entry.SemanticName               = streamOutVarying.semanticName.c_str();
3006                     entry.SemanticIndex              = streamOutVarying.semanticIndex;
3007                     entry.StartComponent             = 0;
3008                     entry.ComponentCount = static_cast<BYTE>(streamOutVarying.componentCount);
3009                     entry.OutputSlot     = static_cast<BYTE>(
3010                         (separatedOutputBuffers ? streamOutVarying.outputSlot : 0));
3011                     soDeclaration.push_back(entry);
3012                 }
3013 
3014                 ANGLE_TRY(allocateResource(context, shaderData, &soDeclaration, &streamOutShader));
3015             }
3016 
3017             *outExecutable = new ShaderExecutable11(function, length, std::move(vertexShader),
3018                                                     std::move(streamOutShader));
3019         }
3020         break;
3021         case gl::ShaderType::Fragment:
3022         {
3023             d3d11::PixelShader pixelShader;
3024             ANGLE_TRY(allocateResource(context, shaderData, &pixelShader));
3025             *outExecutable = new ShaderExecutable11(function, length, std::move(pixelShader));
3026         }
3027         break;
3028         case gl::ShaderType::Geometry:
3029         {
3030             d3d11::GeometryShader geometryShader;
3031             ANGLE_TRY(allocateResource(context, shaderData, &geometryShader));
3032             *outExecutable = new ShaderExecutable11(function, length, std::move(geometryShader));
3033         }
3034         break;
3035         case gl::ShaderType::Compute:
3036         {
3037             d3d11::ComputeShader computeShader;
3038             ANGLE_TRY(allocateResource(context, shaderData, &computeShader));
3039             *outExecutable = new ShaderExecutable11(function, length, std::move(computeShader));
3040         }
3041         break;
3042         default:
3043             ANGLE_HR_UNREACHABLE(context);
3044     }
3045 
3046     return angle::Result::Continue;
3047 }
3048 
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)3049 angle::Result Renderer11::compileToExecutable(d3d::Context *context,
3050                                               gl::InfoLog &infoLog,
3051                                               const std::string &shaderHLSL,
3052                                               gl::ShaderType type,
3053                                               const std::vector<D3DVarying> &streamOutVaryings,
3054                                               bool separatedOutputBuffers,
3055                                               const angle::CompilerWorkaroundsD3D &workarounds,
3056                                               ShaderExecutableD3D **outExectuable)
3057 {
3058     std::stringstream profileStream;
3059 
3060     switch (type)
3061     {
3062         case gl::ShaderType::Vertex:
3063             profileStream << "vs";
3064             break;
3065         case gl::ShaderType::Fragment:
3066             profileStream << "ps";
3067             break;
3068         case gl::ShaderType::Geometry:
3069             profileStream << "gs";
3070             break;
3071         case gl::ShaderType::Compute:
3072             profileStream << "cs";
3073             break;
3074         default:
3075             ANGLE_HR_UNREACHABLE(context);
3076     }
3077 
3078     profileStream << "_" << getMajorShaderModel() << "_" << getMinorShaderModel()
3079                   << getShaderModelSuffix();
3080     std::string profile = profileStream.str();
3081 
3082     UINT flags = D3DCOMPILE_OPTIMIZATION_LEVEL2;
3083 
3084 #if defined(ANGLE_ENABLE_DEBUG_TRACE)
3085 #    ifndef NDEBUG
3086     flags = D3DCOMPILE_SKIP_OPTIMIZATION;
3087 #    endif  // NDEBUG
3088     flags |= D3DCOMPILE_DEBUG;
3089 #endif  // defined(ANGLE_ENABLE_DEBUG_TRACE)
3090 
3091     if (workarounds.enableIEEEStrictness)
3092         flags |= D3DCOMPILE_IEEE_STRICTNESS;
3093 
3094     // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders
3095     // when it would otherwise pass with alternative options.
3096     // Try the default flags first and if compilation fails, try some alternatives.
3097     std::vector<CompileConfig> configs;
3098     configs.push_back(CompileConfig(flags, "default"));
3099     configs.push_back(CompileConfig(flags | D3DCOMPILE_SKIP_VALIDATION, "skip validation"));
3100     configs.push_back(CompileConfig(flags | D3DCOMPILE_SKIP_OPTIMIZATION, "skip optimization"));
3101 
3102     if (getMajorShaderModel() == 4 && getShaderModelSuffix() != "")
3103     {
3104         // Some shaders might cause a "blob content mismatch between level9 and d3d10 shader".
3105         // e.g. dEQP-GLES2.functional.shaders.struct.local.loop_nested_struct_array_*.
3106         // Using the [unroll] directive works around this, as does this D3DCompile flag.
3107         configs.push_back(
3108             CompileConfig(flags | D3DCOMPILE_AVOID_FLOW_CONTROL, "avoid flow control"));
3109     }
3110 
3111     D3D_SHADER_MACRO loopMacros[] = {{"ANGLE_ENABLE_LOOP_FLATTEN", "1"}, {0, 0}};
3112 
3113     // TODO(jmadill): Use ComPtr?
3114     ID3DBlob *binary = nullptr;
3115     std::string debugInfo;
3116     ANGLE_TRY(mCompiler.compileToBinary(context, infoLog, shaderHLSL, profile, configs, loopMacros,
3117                                         &binary, &debugInfo));
3118 
3119     // It's possible that binary is NULL if the compiler failed in all configurations.  Set the
3120     // executable to NULL and return GL_NO_ERROR to signify that there was a link error but the
3121     // internal state is still OK.
3122     if (!binary)
3123     {
3124         *outExectuable = nullptr;
3125         return angle::Result::Continue;
3126     }
3127 
3128     angle::Result error = loadExecutable(
3129         context, static_cast<const uint8_t *>(binary->GetBufferPointer()), binary->GetBufferSize(),
3130         type, streamOutVaryings, separatedOutputBuffers, outExectuable);
3131 
3132     SafeRelease(binary);
3133     if (error == angle::Result::Stop)
3134     {
3135         return error;
3136     }
3137 
3138     if (!debugInfo.empty())
3139     {
3140         (*outExectuable)->appendDebugInfo(debugInfo);
3141     }
3142 
3143     return angle::Result::Continue;
3144 }
3145 
ensureHLSLCompilerInitialized(d3d::Context * context)3146 angle::Result Renderer11::ensureHLSLCompilerInitialized(d3d::Context *context)
3147 {
3148     return mCompiler.ensureInitialized(context);
3149 }
3150 
createUniformStorage(size_t storageSize)3151 UniformStorageD3D *Renderer11::createUniformStorage(size_t storageSize)
3152 {
3153     return new UniformStorage11(storageSize);
3154 }
3155 
createVertexBuffer()3156 VertexBuffer *Renderer11::createVertexBuffer()
3157 {
3158     return new VertexBuffer11(this);
3159 }
3160 
createIndexBuffer()3161 IndexBuffer *Renderer11::createIndexBuffer()
3162 {
3163     return new IndexBuffer11(this);
3164 }
3165 
createStreamProducerD3DTexture(egl::Stream::ConsumerType consumerType,const egl::AttributeMap & attribs)3166 StreamProducerImpl *Renderer11::createStreamProducerD3DTexture(
3167     egl::Stream::ConsumerType consumerType,
3168     const egl::AttributeMap &attribs)
3169 {
3170     return new StreamProducerD3DTexture(this);
3171 }
3172 
supportsFastCopyBufferToTexture(GLenum internalFormat) const3173 bool Renderer11::supportsFastCopyBufferToTexture(GLenum internalFormat) const
3174 {
3175     ASSERT(getNativeExtensions().pixelBufferObjectNV);
3176 
3177     const gl::InternalFormat &internalFormatInfo = gl::GetSizedInternalFormatInfo(internalFormat);
3178     const d3d11::Format &d3d11FormatInfo =
3179         d3d11::Format::Get(internalFormat, mRenderer11DeviceCaps);
3180 
3181     // sRGB formats do not work with D3D11 buffer SRVs
3182     if (internalFormatInfo.colorEncoding == GL_SRGB)
3183     {
3184         return false;
3185     }
3186 
3187     // We cannot support direct copies to non-color-renderable formats
3188     if (d3d11FormatInfo.rtvFormat == DXGI_FORMAT_UNKNOWN)
3189     {
3190         return false;
3191     }
3192 
3193     // We skip all 3-channel formats since sometimes format support is missing
3194     if (internalFormatInfo.componentCount == 3)
3195     {
3196         return false;
3197     }
3198 
3199     // We don't support formats which we can't represent without conversion
3200     if (d3d11FormatInfo.format().glInternalFormat != internalFormat)
3201     {
3202         return false;
3203     }
3204 
3205     // Buffer SRV creation for this format was not working on Windows 10.
3206     if (d3d11FormatInfo.texFormat == DXGI_FORMAT_B5G5R5A1_UNORM)
3207     {
3208         return false;
3209     }
3210 
3211     // This format is not supported as a buffer SRV.
3212     if (d3d11FormatInfo.texFormat == DXGI_FORMAT_A8_UNORM)
3213     {
3214         return false;
3215     }
3216 
3217     return true;
3218 }
3219 
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)3220 angle::Result Renderer11::fastCopyBufferToTexture(const gl::Context *context,
3221                                                   const gl::PixelUnpackState &unpack,
3222                                                   gl::Buffer *unpackBuffer,
3223                                                   unsigned int offset,
3224                                                   RenderTargetD3D *destRenderTarget,
3225                                                   GLenum destinationFormat,
3226                                                   GLenum sourcePixelsType,
3227                                                   const gl::Box &destArea)
3228 {
3229     ASSERT(supportsFastCopyBufferToTexture(destinationFormat));
3230     return mPixelTransfer->copyBufferToTexture(context, unpack, unpackBuffer, offset,
3231                                                destRenderTarget, destinationFormat,
3232                                                sourcePixelsType, destArea);
3233 }
3234 
createImage()3235 ImageD3D *Renderer11::createImage()
3236 {
3237     return new Image11(this);
3238 }
3239 
createExternalImageSibling(const gl::Context * context,EGLenum target,EGLClientBuffer buffer,const egl::AttributeMap & attribs)3240 ExternalImageSiblingImpl *Renderer11::createExternalImageSibling(const gl::Context *context,
3241                                                                  EGLenum target,
3242                                                                  EGLClientBuffer buffer,
3243                                                                  const egl::AttributeMap &attribs)
3244 {
3245     switch (target)
3246     {
3247         case EGL_D3D11_TEXTURE_ANGLE:
3248             return new ExternalImageSiblingImpl11(this, buffer, attribs);
3249 
3250         default:
3251             UNREACHABLE();
3252             return nullptr;
3253     }
3254 }
3255 
generateMipmap(const gl::Context * context,ImageD3D * dest,ImageD3D * src)3256 angle::Result Renderer11::generateMipmap(const gl::Context *context, ImageD3D *dest, ImageD3D *src)
3257 {
3258     Image11 *dest11 = GetAs<Image11>(dest);
3259     Image11 *src11  = GetAs<Image11>(src);
3260     return Image11::GenerateMipmap(context, dest11, src11, mRenderer11DeviceCaps);
3261 }
3262 
generateMipmapUsingD3D(const gl::Context * context,TextureStorage * storage,const gl::TextureState & textureState)3263 angle::Result Renderer11::generateMipmapUsingD3D(const gl::Context *context,
3264                                                  TextureStorage *storage,
3265                                                  const gl::TextureState &textureState)
3266 {
3267     TextureStorage11 *storage11 = GetAs<TextureStorage11>(storage);
3268 
3269     ASSERT(storage11->isRenderTarget());
3270     ASSERT(storage11->supportsNativeMipmapFunction());
3271 
3272     const d3d11::SharedSRV *srv = nullptr;
3273     ANGLE_TRY(storage11->getSRVLevels(context, textureState.getEffectiveBaseLevel(),
3274                                       textureState.getEffectiveMaxLevel(), &srv));
3275 
3276     mDeviceContext->GenerateMips(srv->get());
3277 
3278     return angle::Result::Continue;
3279 }
3280 
copyImage(const gl::Context * context,ImageD3D * dest,ImageD3D * source,const gl::Box & sourceBox,const gl::Offset & destOffset,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha)3281 angle::Result Renderer11::copyImage(const gl::Context *context,
3282                                     ImageD3D *dest,
3283                                     ImageD3D *source,
3284                                     const gl::Box &sourceBox,
3285                                     const gl::Offset &destOffset,
3286                                     bool unpackFlipY,
3287                                     bool unpackPremultiplyAlpha,
3288                                     bool unpackUnmultiplyAlpha)
3289 {
3290     Image11 *dest11 = GetAs<Image11>(dest);
3291     Image11 *src11  = GetAs<Image11>(source);
3292     return Image11::CopyImage(context, dest11, src11, sourceBox, destOffset, unpackFlipY,
3293                               unpackPremultiplyAlpha, unpackUnmultiplyAlpha, mRenderer11DeviceCaps);
3294 }
3295 
createTextureStorage2D(SwapChainD3D * swapChain,const std::string & label)3296 TextureStorage *Renderer11::createTextureStorage2D(SwapChainD3D *swapChain,
3297                                                    const std::string &label)
3298 {
3299     SwapChain11 *swapChain11 = GetAs<SwapChain11>(swapChain);
3300     return new TextureStorage11_2D(this, swapChain11, label);
3301 }
3302 
createTextureStorageEGLImage(EGLImageD3D * eglImage,RenderTargetD3D * renderTargetD3D,const std::string & label)3303 TextureStorage *Renderer11::createTextureStorageEGLImage(EGLImageD3D *eglImage,
3304                                                          RenderTargetD3D *renderTargetD3D,
3305                                                          const std::string &label)
3306 {
3307     return new TextureStorage11_EGLImage(this, eglImage, GetAs<RenderTarget11>(renderTargetD3D),
3308                                          label);
3309 }
3310 
createTextureStorageExternal(egl::Stream * stream,const egl::Stream::GLTextureDescription & desc,const std::string & label)3311 TextureStorage *Renderer11::createTextureStorageExternal(
3312     egl::Stream *stream,
3313     const egl::Stream::GLTextureDescription &desc,
3314     const std::string &label)
3315 {
3316     return new TextureStorage11_External(this, stream, desc, label);
3317 }
3318 
createTextureStorage2D(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,int levels,const std::string & label,bool hintLevelZeroOnly)3319 TextureStorage *Renderer11::createTextureStorage2D(GLenum internalformat,
3320                                                    bool renderTarget,
3321                                                    GLsizei width,
3322                                                    GLsizei height,
3323                                                    int levels,
3324                                                    const std::string &label,
3325                                                    bool hintLevelZeroOnly)
3326 {
3327     return new TextureStorage11_2D(this, internalformat, renderTarget, width, height, levels, label,
3328                                    hintLevelZeroOnly);
3329 }
3330 
createTextureStorageCube(GLenum internalformat,bool renderTarget,int size,int levels,bool hintLevelZeroOnly,const std::string & label)3331 TextureStorage *Renderer11::createTextureStorageCube(GLenum internalformat,
3332                                                      bool renderTarget,
3333                                                      int size,
3334                                                      int levels,
3335                                                      bool hintLevelZeroOnly,
3336                                                      const std::string &label)
3337 {
3338     return new TextureStorage11_Cube(this, internalformat, renderTarget, size, levels,
3339                                      hintLevelZeroOnly, label);
3340 }
3341 
createTextureStorage3D(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,GLsizei depth,int levels,const std::string & label)3342 TextureStorage *Renderer11::createTextureStorage3D(GLenum internalformat,
3343                                                    bool renderTarget,
3344                                                    GLsizei width,
3345                                                    GLsizei height,
3346                                                    GLsizei depth,
3347                                                    int levels,
3348                                                    const std::string &label)
3349 {
3350     return new TextureStorage11_3D(this, internalformat, renderTarget, width, height, depth, levels,
3351                                    label);
3352 }
3353 
createTextureStorage2DArray(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,GLsizei depth,int levels,const std::string & label)3354 TextureStorage *Renderer11::createTextureStorage2DArray(GLenum internalformat,
3355                                                         bool renderTarget,
3356                                                         GLsizei width,
3357                                                         GLsizei height,
3358                                                         GLsizei depth,
3359                                                         int levels,
3360                                                         const std::string &label)
3361 {
3362     return new TextureStorage11_2DArray(this, internalformat, renderTarget, width, height, depth,
3363                                         levels, label);
3364 }
3365 
createTextureStorage2DMultisample(GLenum internalformat,GLsizei width,GLsizei height,int levels,int samples,bool fixedSampleLocations,const std::string & label)3366 TextureStorage *Renderer11::createTextureStorage2DMultisample(GLenum internalformat,
3367                                                               GLsizei width,
3368                                                               GLsizei height,
3369                                                               int levels,
3370                                                               int samples,
3371                                                               bool fixedSampleLocations,
3372                                                               const std::string &label)
3373 {
3374     return new TextureStorage11_2DMultisample(this, internalformat, width, height, levels, samples,
3375                                               fixedSampleLocations, label);
3376 }
3377 
createTextureStorage2DMultisampleArray(GLenum internalformat,GLsizei width,GLsizei height,GLsizei depth,int levels,int samples,bool fixedSampleLocations,const std::string & label)3378 TextureStorage *Renderer11::createTextureStorage2DMultisampleArray(GLenum internalformat,
3379                                                                    GLsizei width,
3380                                                                    GLsizei height,
3381                                                                    GLsizei depth,
3382                                                                    int levels,
3383                                                                    int samples,
3384                                                                    bool fixedSampleLocations,
3385                                                                    const std::string &label)
3386 {
3387     return new TextureStorage11_2DMultisampleArray(this, internalformat, width, height, depth,
3388                                                    levels, samples, fixedSampleLocations, label);
3389 }
3390 
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)3391 angle::Result Renderer11::readFromAttachment(const gl::Context *context,
3392                                              const gl::FramebufferAttachment &srcAttachment,
3393                                              const gl::Rectangle &sourceArea,
3394                                              GLenum format,
3395                                              GLenum type,
3396                                              GLuint outputPitch,
3397                                              const gl::PixelPackState &pack,
3398                                              uint8_t *pixelsOut)
3399 {
3400     ASSERT(sourceArea.width >= 0);
3401     ASSERT(sourceArea.height >= 0);
3402 
3403     const bool invertTexture = UsePresentPathFast(this, &srcAttachment);
3404 
3405     RenderTarget11 *rt11 = nullptr;
3406     ANGLE_TRY(srcAttachment.getRenderTarget(context, 0, &rt11));
3407     ASSERT(rt11->getTexture().valid());
3408 
3409     const TextureHelper11 &textureHelper = rt11->getTexture();
3410     unsigned int sourceSubResource       = rt11->getSubresourceIndex();
3411 
3412     const gl::Extents &texSize = textureHelper.getExtents();
3413 
3414     gl::Rectangle actualArea = sourceArea;
3415     bool reverseRowOrder     = pack.reverseRowOrder;
3416     if (invertTexture)
3417     {
3418         actualArea.y    = texSize.height - actualArea.y - actualArea.height;
3419         reverseRowOrder = !reverseRowOrder;
3420     }
3421 
3422     // Clamp read region to the defined texture boundaries, preventing out of bounds reads
3423     // and reads of uninitialized data.
3424     gl::Rectangle safeArea;
3425     safeArea.x = gl::clamp(actualArea.x, 0, texSize.width);
3426     safeArea.y = gl::clamp(actualArea.y, 0, texSize.height);
3427     safeArea.width =
3428         gl::clamp(actualArea.width + std::min(actualArea.x, 0), 0, texSize.width - safeArea.x);
3429     safeArea.height =
3430         gl::clamp(actualArea.height + std::min(actualArea.y, 0), 0, texSize.height - safeArea.y);
3431 
3432     ASSERT(safeArea.x >= 0 && safeArea.y >= 0);
3433     ASSERT(safeArea.x + safeArea.width <= texSize.width);
3434     ASSERT(safeArea.y + safeArea.height <= texSize.height);
3435 
3436     if (safeArea.width == 0 || safeArea.height == 0)
3437     {
3438         // no work to do
3439         return angle::Result::Continue;
3440     }
3441 
3442     gl::Extents safeSize(safeArea.width, safeArea.height, 1);
3443     TextureHelper11 stagingHelper;
3444     ANGLE_TRY(createStagingTexture(context, textureHelper.getTextureType(),
3445                                    textureHelper.getFormatSet(), safeSize, StagingAccess::READ,
3446                                    &stagingHelper));
3447     stagingHelper.setDebugName("readFromAttachment::stagingHelper");
3448 
3449     TextureHelper11 resolvedTextureHelper;
3450 
3451     // "srcTexture" usually points to the source texture.
3452     // For 2D multisampled textures, it points to the multisampled resolve texture.
3453     const TextureHelper11 *srcTexture = &textureHelper;
3454 
3455     if (textureHelper.is2D() && textureHelper.getSampleCount() > 1)
3456     {
3457         D3D11_TEXTURE2D_DESC resolveDesc;
3458         resolveDesc.Width              = static_cast<UINT>(texSize.width);
3459         resolveDesc.Height             = static_cast<UINT>(texSize.height);
3460         resolveDesc.MipLevels          = 1;
3461         resolveDesc.ArraySize          = 1;
3462         resolveDesc.Format             = textureHelper.getFormat();
3463         resolveDesc.SampleDesc.Count   = 1;
3464         resolveDesc.SampleDesc.Quality = 0;
3465         resolveDesc.Usage              = D3D11_USAGE_DEFAULT;
3466         resolveDesc.BindFlags          = 0;
3467         resolveDesc.CPUAccessFlags     = 0;
3468         resolveDesc.MiscFlags          = 0;
3469 
3470         ANGLE_TRY(allocateTexture(GetImplAs<Context11>(context), resolveDesc,
3471                                   textureHelper.getFormatSet(), &resolvedTextureHelper));
3472         resolvedTextureHelper.setDebugName("readFromAttachment::resolvedTextureHelper");
3473 
3474         mDeviceContext->ResolveSubresource(resolvedTextureHelper.get(), 0, textureHelper.get(),
3475                                            sourceSubResource, textureHelper.getFormat());
3476 
3477         sourceSubResource = 0;
3478         srcTexture        = &resolvedTextureHelper;
3479     }
3480 
3481     D3D11_BOX srcBox;
3482     srcBox.left   = static_cast<UINT>(safeArea.x);
3483     srcBox.right  = static_cast<UINT>(safeArea.x + safeArea.width);
3484     srcBox.top    = static_cast<UINT>(safeArea.y);
3485     srcBox.bottom = static_cast<UINT>(safeArea.y + safeArea.height);
3486 
3487     // Select the correct layer from a 3D attachment
3488     srcBox.front = 0;
3489     if (textureHelper.is3D())
3490     {
3491         srcBox.front = static_cast<UINT>(srcAttachment.layer());
3492     }
3493     srcBox.back = srcBox.front + 1;
3494 
3495     mDeviceContext->CopySubresourceRegion(stagingHelper.get(), 0, 0, 0, 0, srcTexture->get(),
3496                                           sourceSubResource, &srcBox);
3497 
3498     const angle::Format &angleFormat = GetFormatFromFormatType(format, type);
3499     gl::Buffer *packBuffer = context->getState().getTargetBuffer(gl::BufferBinding::PixelPack);
3500 
3501     PackPixelsParams packParams(safeArea, angleFormat, outputPitch, reverseRowOrder, packBuffer, 0);
3502     return packPixels(context, stagingHelper, packParams, pixelsOut);
3503 }
3504 
packPixels(const gl::Context * context,const TextureHelper11 & textureHelper,const PackPixelsParams & params,uint8_t * pixelsOut)3505 angle::Result Renderer11::packPixels(const gl::Context *context,
3506                                      const TextureHelper11 &textureHelper,
3507                                      const PackPixelsParams &params,
3508                                      uint8_t *pixelsOut)
3509 {
3510     ID3D11Resource *readResource = textureHelper.get();
3511 
3512     D3D11_MAPPED_SUBRESOURCE mapping;
3513     ANGLE_TRY(mapResource(context, readResource, 0, D3D11_MAP_READ, 0, &mapping));
3514 
3515     uint8_t *source = static_cast<uint8_t *>(mapping.pData);
3516     int inputPitch  = static_cast<int>(mapping.RowPitch);
3517 
3518     const auto &formatInfo = textureHelper.getFormatSet();
3519     ASSERT(formatInfo.format().glInternalFormat != GL_NONE);
3520 
3521     PackPixels(params, formatInfo.format(), inputPitch, source, pixelsOut);
3522 
3523     mDeviceContext->Unmap(readResource, 0);
3524 
3525     return angle::Result::Continue;
3526 }
3527 
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)3528 angle::Result Renderer11::blitRenderbufferRect(const gl::Context *context,
3529                                                const gl::Rectangle &readRectIn,
3530                                                const gl::Rectangle &drawRectIn,
3531                                                RenderTargetD3D *readRenderTarget,
3532                                                RenderTargetD3D *drawRenderTarget,
3533                                                GLenum filter,
3534                                                const gl::Rectangle *scissor,
3535                                                bool colorBlit,
3536                                                bool depthBlit,
3537                                                bool stencilBlit)
3538 {
3539     // Since blitRenderbufferRect is called for each render buffer that needs to be blitted,
3540     // it should never be the case that both color and depth/stencil need to be blitted at
3541     // at the same time.
3542     ASSERT(colorBlit != (depthBlit || stencilBlit));
3543 
3544     RenderTarget11 *drawRenderTarget11 = GetAs<RenderTarget11>(drawRenderTarget);
3545     ASSERT(drawRenderTarget11);
3546 
3547     const TextureHelper11 &drawTexture = drawRenderTarget11->getTexture();
3548     unsigned int drawSubresource       = drawRenderTarget11->getSubresourceIndex();
3549 
3550     RenderTarget11 *readRenderTarget11 = GetAs<RenderTarget11>(readRenderTarget);
3551     ASSERT(readRenderTarget11);
3552 
3553     TextureHelper11 readTexture;
3554     unsigned int readSubresource = 0;
3555     d3d11::SharedSRV readSRV;
3556 
3557     if (readRenderTarget->isMultisampled())
3558     {
3559         ANGLE_TRY(resolveMultisampledTexture(context, readRenderTarget11, depthBlit, stencilBlit,
3560                                              &readTexture));
3561 
3562         if (!stencilBlit)
3563         {
3564             const auto &readFormatSet = readTexture.getFormatSet();
3565 
3566             D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
3567             viewDesc.Format                    = readFormatSet.srvFormat;
3568             viewDesc.ViewDimension             = D3D11_SRV_DIMENSION_TEXTURE2D;
3569             viewDesc.Texture2D.MipLevels       = 1;
3570             viewDesc.Texture2D.MostDetailedMip = 0;
3571 
3572             ANGLE_TRY(allocateResource(GetImplAs<Context11>(context), viewDesc, readTexture.get(),
3573                                        &readSRV));
3574         }
3575     }
3576     else
3577     {
3578         ASSERT(readRenderTarget11);
3579         readTexture     = readRenderTarget11->getTexture();
3580         readSubresource = readRenderTarget11->getSubresourceIndex();
3581         readSRV         = readRenderTarget11->getBlitShaderResourceView(context).makeCopy();
3582         if (!readSRV.valid())
3583         {
3584             ASSERT(depthBlit || stencilBlit);
3585             readSRV = readRenderTarget11->getShaderResourceView(context).makeCopy();
3586         }
3587         ASSERT(readSRV.valid());
3588     }
3589 
3590     // Stencil blits don't use shaders.
3591     ASSERT(readSRV.valid() || stencilBlit);
3592 
3593     const gl::Extents readSize(readRenderTarget->getWidth(), readRenderTarget->getHeight(), 1);
3594     const gl::Extents drawSize(drawRenderTarget->getWidth(), drawRenderTarget->getHeight(), 1);
3595 
3596     // From the spec:
3597     // "The actual region taken from the read framebuffer is limited to the intersection of the
3598     // source buffers being transferred, which may include the color buffer selected by the read
3599     // buffer, the depth buffer, and / or the stencil buffer depending on mask."
3600     // This means negative x and y are out of bounds, and not to be read from. We handle this here
3601     // by internally scaling the read and draw rectangles.
3602 
3603     // Remove reversal from readRect to simplify further operations.
3604     gl::Rectangle readRect = readRectIn;
3605     gl::Rectangle drawRect = drawRectIn;
3606     if (readRect.isReversedX())
3607     {
3608         readRect.x     = readRect.x + readRect.width;
3609         readRect.width = -readRect.width;
3610         drawRect.x     = drawRect.x + drawRect.width;
3611         drawRect.width = -drawRect.width;
3612     }
3613     if (readRect.isReversedY())
3614     {
3615         readRect.y      = readRect.y + readRect.height;
3616         readRect.height = -readRect.height;
3617         drawRect.y      = drawRect.y + drawRect.height;
3618         drawRect.height = -drawRect.height;
3619     }
3620 
3621     gl::Rectangle readBounds(0, 0, readSize.width, readSize.height);
3622     gl::Rectangle inBoundsReadRect;
3623     if (!gl::ClipRectangle(readRect, readBounds, &inBoundsReadRect))
3624     {
3625         return angle::Result::Continue;
3626     }
3627 
3628     {
3629         // Calculate the drawRect that corresponds to inBoundsReadRect.
3630         auto readToDrawX = [&drawRect, &readRect](int readOffset) {
3631             double readToDrawScale =
3632                 static_cast<double>(drawRect.width) / static_cast<double>(readRect.width);
3633             return static_cast<int>(
3634                 round(static_cast<double>(readOffset - readRect.x) * readToDrawScale) + drawRect.x);
3635         };
3636         auto readToDrawY = [&drawRect, &readRect](int readOffset) {
3637             double readToDrawScale =
3638                 static_cast<double>(drawRect.height) / static_cast<double>(readRect.height);
3639             return static_cast<int>(
3640                 round(static_cast<double>(readOffset - readRect.y) * readToDrawScale) + drawRect.y);
3641         };
3642 
3643         gl::Rectangle drawRectMatchingInBoundsReadRect;
3644         drawRectMatchingInBoundsReadRect.x = readToDrawX(inBoundsReadRect.x);
3645         drawRectMatchingInBoundsReadRect.y = readToDrawY(inBoundsReadRect.y);
3646         drawRectMatchingInBoundsReadRect.width =
3647             readToDrawX(inBoundsReadRect.x1()) - drawRectMatchingInBoundsReadRect.x;
3648         drawRectMatchingInBoundsReadRect.height =
3649             readToDrawY(inBoundsReadRect.y1()) - drawRectMatchingInBoundsReadRect.y;
3650         drawRect = drawRectMatchingInBoundsReadRect;
3651         readRect = inBoundsReadRect;
3652     }
3653 
3654     bool scissorNeeded = false;
3655     if (scissor)
3656     {
3657         gl::Rectangle scissoredDrawRect;
3658         if (!gl::ClipRectangle(drawRect, *scissor, &scissoredDrawRect))
3659         {
3660             return angle::Result::Continue;
3661         }
3662         scissorNeeded = scissoredDrawRect != drawRect;
3663     }
3664 
3665     const auto &destFormatInfo =
3666         gl::GetSizedInternalFormatInfo(drawRenderTarget->getInternalFormat());
3667     const auto &srcFormatInfo =
3668         gl::GetSizedInternalFormatInfo(readRenderTarget->getInternalFormat());
3669     const auto &formatSet    = drawRenderTarget11->getFormatSet();
3670     const auto &nativeFormat = formatSet.format();
3671 
3672     // Some blits require masking off emulated texture channels. eg: from RGBA8 to RGB8, we
3673     // emulate RGB8 with RGBA8, so we need to mask off the alpha channel when we copy.
3674 
3675     gl::Color<bool> colorMask;
3676     colorMask.red =
3677         (srcFormatInfo.redBits > 0) && (destFormatInfo.redBits == 0) && (nativeFormat.redBits > 0);
3678     colorMask.green = (srcFormatInfo.greenBits > 0) && (destFormatInfo.greenBits == 0) &&
3679                       (nativeFormat.greenBits > 0);
3680     colorMask.blue = (srcFormatInfo.blueBits > 0) && (destFormatInfo.blueBits == 0) &&
3681                      (nativeFormat.blueBits > 0);
3682     colorMask.alpha = (srcFormatInfo.alphaBits > 0) && (destFormatInfo.alphaBits == 0) &&
3683                       (nativeFormat.alphaBits > 0);
3684 
3685     // We only currently support masking off the alpha channel.
3686     bool colorMaskingNeeded = colorMask.alpha;
3687     ASSERT(!colorMask.red && !colorMask.green && !colorMask.blue);
3688 
3689     bool wholeBufferCopy = !scissorNeeded && !colorMaskingNeeded && readRect.x == 0 &&
3690                            readRect.width == readSize.width && readRect.y == 0 &&
3691                            readRect.height == readSize.height && drawRect.x == 0 &&
3692                            drawRect.width == drawSize.width && drawRect.y == 0 &&
3693                            drawRect.height == drawSize.height;
3694 
3695     bool stretchRequired = readRect.width != drawRect.width || readRect.height != drawRect.height;
3696 
3697     ASSERT(!readRect.isReversedX() && !readRect.isReversedY());
3698     bool reversalRequired = drawRect.isReversedX() || drawRect.isReversedY();
3699 
3700     bool outOfBounds = readRect.x < 0 || readRect.x + readRect.width > readSize.width ||
3701                        readRect.y < 0 || readRect.y + readRect.height > readSize.height ||
3702                        drawRect.x < 0 || drawRect.x + drawRect.width > drawSize.width ||
3703                        drawRect.y < 0 || drawRect.y + drawRect.height > drawSize.height;
3704 
3705     bool partialDSBlit =
3706         (nativeFormat.depthBits > 0 && depthBlit) != (nativeFormat.stencilBits > 0 && stencilBlit);
3707 
3708     if (drawRenderTarget->getSamples() == readRenderTarget->getSamples() &&
3709         readRenderTarget11->getFormatSet().formatID ==
3710             drawRenderTarget11->getFormatSet().formatID &&
3711         !stretchRequired && !outOfBounds && !reversalRequired && !partialDSBlit &&
3712         !colorMaskingNeeded && (!(depthBlit || stencilBlit) || wholeBufferCopy))
3713     {
3714         UINT dstX = drawRect.x;
3715         UINT dstY = drawRect.y;
3716 
3717         D3D11_BOX readBox;
3718         readBox.left   = readRect.x;
3719         readBox.right  = readRect.x + readRect.width;
3720         readBox.top    = readRect.y;
3721         readBox.bottom = readRect.y + readRect.height;
3722         readBox.front  = 0;
3723         readBox.back   = 1;
3724 
3725         if (scissorNeeded)
3726         {
3727             // drawRect is guaranteed to have positive width and height because stretchRequired is
3728             // false.
3729             ASSERT(drawRect.width >= 0 || drawRect.height >= 0);
3730 
3731             if (drawRect.x < scissor->x)
3732             {
3733                 dstX = scissor->x;
3734                 readBox.left += (scissor->x - drawRect.x);
3735             }
3736             if (drawRect.y < scissor->y)
3737             {
3738                 dstY = scissor->y;
3739                 readBox.top += (scissor->y - drawRect.y);
3740             }
3741             if (drawRect.x + drawRect.width > scissor->x + scissor->width)
3742             {
3743                 readBox.right -= ((drawRect.x + drawRect.width) - (scissor->x + scissor->width));
3744             }
3745             if (drawRect.y + drawRect.height > scissor->y + scissor->height)
3746             {
3747                 readBox.bottom -= ((drawRect.y + drawRect.height) - (scissor->y + scissor->height));
3748             }
3749         }
3750 
3751         // D3D11 needs depth-stencil CopySubresourceRegions to have a NULL pSrcBox
3752         // We also require complete framebuffer copies for depth-stencil blit.
3753         D3D11_BOX *pSrcBox = wholeBufferCopy ? nullptr : &readBox;
3754 
3755         mDeviceContext->CopySubresourceRegion(drawTexture.get(), drawSubresource, dstX, dstY, 0,
3756                                               readTexture.get(), readSubresource, pSrcBox);
3757     }
3758     else
3759     {
3760         gl::Box readArea(readRect.x, readRect.y, 0, readRect.width, readRect.height, 1);
3761         gl::Box drawArea(drawRect.x, drawRect.y, 0, drawRect.width, drawRect.height, 1);
3762 
3763         if (depthBlit && stencilBlit)
3764         {
3765             ANGLE_TRY(mBlit->copyDepthStencil(context, readTexture, readSubresource, readArea,
3766                                               readSize, drawTexture, drawSubresource, drawArea,
3767                                               drawSize, scissor));
3768         }
3769         else if (depthBlit)
3770         {
3771             const d3d11::DepthStencilView &drawDSV = drawRenderTarget11->getDepthStencilView();
3772             ASSERT(readSRV.valid());
3773             ANGLE_TRY(mBlit->copyDepth(context, readSRV, readArea, readSize, drawDSV, drawArea,
3774                                        drawSize, scissor));
3775         }
3776         else if (stencilBlit)
3777         {
3778             ANGLE_TRY(mBlit->copyStencil(context, readTexture, readSubresource, readArea, readSize,
3779                                          drawTexture, drawSubresource, drawArea, drawSize,
3780                                          scissor));
3781         }
3782         else
3783         {
3784             const d3d11::RenderTargetView &drawRTV = drawRenderTarget11->getRenderTargetView();
3785 
3786             // We don't currently support masking off any other channel than alpha
3787             bool maskOffAlpha = colorMaskingNeeded && colorMask.alpha;
3788             ASSERT(readSRV.valid());
3789             ANGLE_TRY(mBlit->copyTexture(context, readSRV, readArea, readSize, srcFormatInfo.format,
3790                                          drawRTV, drawArea, drawSize, scissor,
3791                                          destFormatInfo.format, GL_NONE, filter, maskOffAlpha,
3792                                          false, false));
3793         }
3794     }
3795 
3796     return angle::Result::Continue;
3797 }
3798 
isES3Capable() const3799 bool Renderer11::isES3Capable() const
3800 {
3801     return (d3d11_gl::GetMaximumClientVersion(mRenderer11DeviceCaps).major > 2);
3802 }
3803 
getRendererClass() const3804 RendererClass Renderer11::getRendererClass() const
3805 {
3806     return RENDERER_D3D11;
3807 }
3808 
onSwap()3809 void Renderer11::onSwap()
3810 {
3811     // Send histogram updates every half hour
3812     const double kHistogramUpdateInterval = 30 * 60;
3813 
3814     auto *platform                   = ANGLEPlatformCurrent();
3815     const double currentTime         = platform->monotonicallyIncreasingTime(platform);
3816     const double timeSinceLastUpdate = currentTime - mLastHistogramUpdateTime;
3817 
3818     if (timeSinceLastUpdate > kHistogramUpdateInterval)
3819     {
3820         updateHistograms();
3821         mLastHistogramUpdateTime = currentTime;
3822     }
3823 }
3824 
updateHistograms()3825 void Renderer11::updateHistograms()
3826 {
3827     // Update the buffer CPU memory histogram
3828     {
3829         size_t sizeSum = 0;
3830         for (const Buffer11 *buffer : mAliveBuffers)
3831         {
3832             sizeSum += buffer->getTotalCPUBufferMemoryBytes();
3833         }
3834         const int kOneMegaByte = 1024 * 1024;
3835         ANGLE_HISTOGRAM_MEMORY_MB("GPU.ANGLE.Buffer11CPUMemoryMB",
3836                                   static_cast<int>(sizeSum) / kOneMegaByte);
3837     }
3838 }
3839 
onBufferCreate(const Buffer11 * created)3840 void Renderer11::onBufferCreate(const Buffer11 *created)
3841 {
3842     mAliveBuffers.insert(created);
3843 }
3844 
onBufferDelete(const Buffer11 * deleted)3845 void Renderer11::onBufferDelete(const Buffer11 *deleted)
3846 {
3847     mAliveBuffers.erase(deleted);
3848 }
3849 
resolveMultisampledTexture(const gl::Context * context,RenderTarget11 * renderTarget,bool depth,bool stencil,TextureHelper11 * textureOut)3850 angle::Result Renderer11::resolveMultisampledTexture(const gl::Context *context,
3851                                                      RenderTarget11 *renderTarget,
3852                                                      bool depth,
3853                                                      bool stencil,
3854                                                      TextureHelper11 *textureOut)
3855 {
3856     if (depth && !stencil)
3857     {
3858         return mBlit->resolveDepth(context, renderTarget, textureOut);
3859     }
3860 
3861     if (stencil)
3862     {
3863         return mBlit->resolveStencil(context, renderTarget, depth, textureOut);
3864     }
3865 
3866     const auto &formatSet = renderTarget->getFormatSet();
3867 
3868     ASSERT(renderTarget->isMultisampled());
3869     const d3d11::SharedSRV &sourceSRV = renderTarget->getShaderResourceView(context);
3870     D3D11_SHADER_RESOURCE_VIEW_DESC sourceSRVDesc;
3871     sourceSRV.get()->GetDesc(&sourceSRVDesc);
3872     ASSERT(sourceSRVDesc.ViewDimension == D3D_SRV_DIMENSION_TEXTURE2DMS ||
3873            sourceSRVDesc.ViewDimension == D3D_SRV_DIMENSION_TEXTURE2DMSARRAY);
3874 
3875     if (!mCachedResolveTexture.valid() ||
3876         mCachedResolveTexture.getExtents().width != renderTarget->getWidth() ||
3877         mCachedResolveTexture.getExtents().height != renderTarget->getHeight() ||
3878         mCachedResolveTexture.getFormat() != formatSet.texFormat)
3879     {
3880         D3D11_TEXTURE2D_DESC resolveDesc;
3881         resolveDesc.Width              = renderTarget->getWidth();
3882         resolveDesc.Height             = renderTarget->getHeight();
3883         resolveDesc.MipLevels          = 1;
3884         resolveDesc.ArraySize          = 1;
3885         resolveDesc.Format             = formatSet.texFormat;
3886         resolveDesc.SampleDesc.Count   = 1;
3887         resolveDesc.SampleDesc.Quality = 0;
3888         resolveDesc.Usage              = D3D11_USAGE_DEFAULT;
3889         resolveDesc.BindFlags          = D3D11_BIND_SHADER_RESOURCE;
3890         resolveDesc.CPUAccessFlags     = 0;
3891         resolveDesc.MiscFlags          = 0;
3892 
3893         ANGLE_TRY(allocateTexture(GetImplAs<Context11>(context), resolveDesc, formatSet,
3894                                   &mCachedResolveTexture));
3895     }
3896 
3897     mDeviceContext->ResolveSubresource(mCachedResolveTexture.get(), 0,
3898                                        renderTarget->getTexture().get(),
3899                                        renderTarget->getSubresourceIndex(), formatSet.texFormat);
3900     *textureOut = mCachedResolveTexture;
3901     return angle::Result::Continue;
3902 }
3903 
getLUID(LUID * adapterLuid) const3904 bool Renderer11::getLUID(LUID *adapterLuid) const
3905 {
3906     adapterLuid->HighPart = 0;
3907     adapterLuid->LowPart  = 0;
3908 
3909     if (!mDxgiAdapter)
3910     {
3911         return false;
3912     }
3913 
3914     DXGI_ADAPTER_DESC adapterDesc;
3915     if (FAILED(mDxgiAdapter->GetDesc(&adapterDesc)))
3916     {
3917         return false;
3918     }
3919 
3920     *adapterLuid = adapterDesc.AdapterLuid;
3921     return true;
3922 }
3923 
getVertexConversionType(angle::FormatID vertexFormatID) const3924 VertexConversionType Renderer11::getVertexConversionType(angle::FormatID vertexFormatID) const
3925 {
3926     return d3d11::GetVertexFormatInfo(vertexFormatID, mRenderer11DeviceCaps.featureLevel)
3927         .conversionType;
3928 }
3929 
getVertexComponentType(angle::FormatID vertexFormatID) const3930 GLenum Renderer11::getVertexComponentType(angle::FormatID vertexFormatID) const
3931 {
3932     const auto &format =
3933         d3d11::GetVertexFormatInfo(vertexFormatID, mRenderer11DeviceCaps.featureLevel);
3934     return d3d11::GetComponentType(format.nativeFormat);
3935 }
3936 
getVertexSpaceRequired(const gl::Context * context,const gl::VertexAttribute & attrib,const gl::VertexBinding & binding,size_t count,GLsizei instances,GLuint baseInstance,unsigned int * bytesRequiredOut) const3937 angle::Result Renderer11::getVertexSpaceRequired(const gl::Context *context,
3938                                                  const gl::VertexAttribute &attrib,
3939                                                  const gl::VertexBinding &binding,
3940                                                  size_t count,
3941                                                  GLsizei instances,
3942                                                  GLuint baseInstance,
3943                                                  unsigned int *bytesRequiredOut) const
3944 {
3945     if (!attrib.enabled)
3946     {
3947         *bytesRequiredOut = 16u;
3948         return angle::Result::Continue;
3949     }
3950 
3951     unsigned int elementCount  = 0;
3952     const unsigned int divisor = binding.getDivisor();
3953     if (instances == 0 || divisor == 0)
3954     {
3955         // This could be a clipped cast.
3956         elementCount = gl::clampCast<unsigned int>(count);
3957     }
3958     else
3959     {
3960         // Round up to divisor, if possible
3961         elementCount =
3962             UnsignedCeilDivide(static_cast<unsigned int>(instances + baseInstance), divisor);
3963     }
3964 
3965     ASSERT(elementCount > 0);
3966 
3967     const D3D_FEATURE_LEVEL featureLevel = mRenderer11DeviceCaps.featureLevel;
3968     const d3d11::VertexFormat &vertexFormatInfo =
3969         d3d11::GetVertexFormatInfo(attrib.format->id, featureLevel);
3970     const d3d11::DXGIFormatSize &dxgiFormatInfo =
3971         d3d11::GetDXGIFormatSizeInfo(vertexFormatInfo.nativeFormat);
3972     unsigned int elementSize = dxgiFormatInfo.pixelBytes;
3973     bool check = (elementSize > std::numeric_limits<unsigned int>::max() / elementCount);
3974     ANGLE_CHECK(GetImplAs<Context11>(context), !check,
3975                 "New vertex buffer size would result in an overflow.", GL_OUT_OF_MEMORY);
3976 
3977     *bytesRequiredOut = elementSize * elementCount;
3978     return angle::Result::Continue;
3979 }
3980 
generateCaps(gl::Caps * outCaps,gl::TextureCapsMap * outTextureCaps,gl::Extensions * outExtensions,gl::Limitations * outLimitations) const3981 void Renderer11::generateCaps(gl::Caps *outCaps,
3982                               gl::TextureCapsMap *outTextureCaps,
3983                               gl::Extensions *outExtensions,
3984                               gl::Limitations *outLimitations) const
3985 {
3986     d3d11_gl::GenerateCaps(mDevice, mDeviceContext, mRenderer11DeviceCaps, getFeatures(),
3987                            mDescription, outCaps, outTextureCaps, outExtensions, outLimitations);
3988 }
3989 
initializeFeatures(angle::FeaturesD3D * features) const3990 void Renderer11::initializeFeatures(angle::FeaturesD3D *features) const
3991 {
3992     if (!mDisplay->getState().featuresAllDisabled)
3993     {
3994         d3d11::InitializeFeatures(mRenderer11DeviceCaps, mAdapterDescription, features);
3995     }
3996     ApplyFeatureOverrides(features, mDisplay->getState());
3997 }
3998 
createEGLDevice()3999 DeviceImpl *Renderer11::createEGLDevice()
4000 {
4001     return new DeviceD3D(EGL_D3D11_DEVICE_ANGLE, mDevice);
4002 }
4003 
createContext(const gl::State & state,gl::ErrorSet * errorSet)4004 ContextImpl *Renderer11::createContext(const gl::State &state, gl::ErrorSet *errorSet)
4005 {
4006     return new Context11(state, errorSet, this);
4007 }
4008 
createDefaultFramebuffer(const gl::FramebufferState & state)4009 FramebufferImpl *Renderer11::createDefaultFramebuffer(const gl::FramebufferState &state)
4010 {
4011     return new Framebuffer11(state, this);
4012 }
4013 
getScratchMemoryBuffer(Context11 * context11,size_t requestedSize,angle::MemoryBuffer ** bufferOut)4014 angle::Result Renderer11::getScratchMemoryBuffer(Context11 *context11,
4015                                                  size_t requestedSize,
4016                                                  angle::MemoryBuffer **bufferOut)
4017 {
4018     ANGLE_CHECK_GL_ALLOC(context11, mScratchMemoryBuffer.get(requestedSize, bufferOut));
4019     return angle::Result::Continue;
4020 }
4021 
getMaxSupportedESVersion() const4022 gl::Version Renderer11::getMaxSupportedESVersion() const
4023 {
4024     return d3d11_gl::GetMaximumClientVersion(mRenderer11DeviceCaps);
4025 }
4026 
getMaxConformantESVersion() const4027 gl::Version Renderer11::getMaxConformantESVersion() const
4028 {
4029     // 3.1 support is in progress.
4030     return std::min(getMaxSupportedESVersion(), gl::Version(3, 0));
4031 }
4032 
getAnnotator()4033 gl::DebugAnnotator *Renderer11::getAnnotator()
4034 {
4035     return &mAnnotator;
4036 }
4037 
dispatchCompute(const gl::Context * context,GLuint numGroupsX,GLuint numGroupsY,GLuint numGroupsZ)4038 angle::Result Renderer11::dispatchCompute(const gl::Context *context,
4039                                           GLuint numGroupsX,
4040                                           GLuint numGroupsY,
4041                                           GLuint numGroupsZ)
4042 {
4043     const gl::State &glState   = context->getState();
4044     const gl::Program *program = glState.getProgram();
4045     if (program->getActiveShaderStorageBlockCount() > 0 ||
4046         program->getActiveAtomicCounterBufferCount() > 0)
4047     {
4048         ANGLE_TRY(markRawBufferUsage(context));
4049     }
4050 
4051     ANGLE_TRY(mStateManager.updateStateForCompute(context, numGroupsX, numGroupsY, numGroupsZ));
4052     mDeviceContext->Dispatch(numGroupsX, numGroupsY, numGroupsZ);
4053 
4054     return angle::Result::Continue;
4055 }
dispatchComputeIndirect(const gl::Context * context,GLintptr indirect)4056 angle::Result Renderer11::dispatchComputeIndirect(const gl::Context *context, GLintptr indirect)
4057 {
4058     const auto &glState        = context->getState();
4059     const gl::Program *program = glState.getProgram();
4060     if (program->getActiveShaderStorageBlockCount() > 0 ||
4061         program->getActiveAtomicCounterBufferCount() > 0)
4062     {
4063         ANGLE_TRY(markRawBufferUsage(context));
4064     }
4065 
4066     auto *dispatchIndirectBuffer = glState.getTargetBuffer(gl::BufferBinding::DispatchIndirect);
4067     ASSERT(dispatchIndirectBuffer);
4068 
4069     Buffer11 *storage         = GetImplAs<Buffer11>(dispatchIndirectBuffer);
4070     const uint8_t *bufferData = nullptr;
4071     // TODO(jie.a.chen@intel.com): num_groups_x,y,z have to be written into the driver constant
4072     // buffer for the built-in variable gl_NumWorkGroups. There is an opportunity for optimization
4073     // to use GPU->GPU copy instead.
4074     // http://anglebug.com/2807
4075     ANGLE_TRY(storage->getData(context, &bufferData));
4076     const GLuint *groups = reinterpret_cast<const GLuint *>(bufferData + indirect);
4077     ANGLE_TRY(mStateManager.updateStateForCompute(context, groups[0], groups[1], groups[2]));
4078 
4079     ID3D11Buffer *buffer = nullptr;
4080     ANGLE_TRY(storage->getBuffer(context, BUFFER_USAGE_INDIRECT, &buffer));
4081 
4082     mDeviceContext->DispatchIndirect(buffer, static_cast<UINT>(indirect));
4083     return angle::Result::Continue;
4084 }
4085 
createStagingTexture(const gl::Context * context,ResourceType textureType,const d3d11::Format & formatSet,const gl::Extents & size,StagingAccess readAndWriteAccess,TextureHelper11 * textureOut)4086 angle::Result Renderer11::createStagingTexture(const gl::Context *context,
4087                                                ResourceType textureType,
4088                                                const d3d11::Format &formatSet,
4089                                                const gl::Extents &size,
4090                                                StagingAccess readAndWriteAccess,
4091                                                TextureHelper11 *textureOut)
4092 {
4093     Context11 *context11 = GetImplAs<Context11>(context);
4094 
4095     if (textureType == ResourceType::Texture2D)
4096     {
4097         D3D11_TEXTURE2D_DESC stagingDesc;
4098         stagingDesc.Width              = size.width;
4099         stagingDesc.Height             = size.height;
4100         stagingDesc.MipLevels          = 1;
4101         stagingDesc.ArraySize          = 1;
4102         stagingDesc.Format             = formatSet.texFormat;
4103         stagingDesc.SampleDesc.Count   = 1;
4104         stagingDesc.SampleDesc.Quality = 0;
4105         stagingDesc.Usage              = D3D11_USAGE_STAGING;
4106         stagingDesc.BindFlags          = 0;
4107         stagingDesc.CPUAccessFlags     = D3D11_CPU_ACCESS_READ;
4108         stagingDesc.MiscFlags          = 0;
4109 
4110         if (readAndWriteAccess == StagingAccess::READ_WRITE)
4111         {
4112             stagingDesc.CPUAccessFlags |= D3D11_CPU_ACCESS_WRITE;
4113         }
4114 
4115         ANGLE_TRY(allocateTexture(context11, stagingDesc, formatSet, textureOut));
4116         return angle::Result::Continue;
4117     }
4118     ASSERT(textureType == ResourceType::Texture3D);
4119 
4120     D3D11_TEXTURE3D_DESC stagingDesc;
4121     stagingDesc.Width          = size.width;
4122     stagingDesc.Height         = size.height;
4123     stagingDesc.Depth          = 1;
4124     stagingDesc.MipLevels      = 1;
4125     stagingDesc.Format         = formatSet.texFormat;
4126     stagingDesc.Usage          = D3D11_USAGE_STAGING;
4127     stagingDesc.BindFlags      = 0;
4128     stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
4129     stagingDesc.MiscFlags      = 0;
4130 
4131     ANGLE_TRY(allocateTexture(context11, stagingDesc, formatSet, textureOut));
4132     return angle::Result::Continue;
4133 }
4134 
allocateTexture(d3d::Context * context,const D3D11_TEXTURE2D_DESC & desc,const d3d11::Format & format,const D3D11_SUBRESOURCE_DATA * initData,TextureHelper11 * textureOut)4135 angle::Result Renderer11::allocateTexture(d3d::Context *context,
4136                                           const D3D11_TEXTURE2D_DESC &desc,
4137                                           const d3d11::Format &format,
4138                                           const D3D11_SUBRESOURCE_DATA *initData,
4139                                           TextureHelper11 *textureOut)
4140 {
4141     d3d11::Texture2D texture;
4142     ANGLE_TRY(mResourceManager11.allocate(context, this, &desc, initData, &texture));
4143     textureOut->init(std::move(texture), desc, format);
4144     return angle::Result::Continue;
4145 }
4146 
allocateTexture(d3d::Context * context,const D3D11_TEXTURE3D_DESC & desc,const d3d11::Format & format,const D3D11_SUBRESOURCE_DATA * initData,TextureHelper11 * textureOut)4147 angle::Result Renderer11::allocateTexture(d3d::Context *context,
4148                                           const D3D11_TEXTURE3D_DESC &desc,
4149                                           const d3d11::Format &format,
4150                                           const D3D11_SUBRESOURCE_DATA *initData,
4151                                           TextureHelper11 *textureOut)
4152 {
4153     d3d11::Texture3D texture;
4154     ANGLE_TRY(mResourceManager11.allocate(context, this, &desc, initData, &texture));
4155     textureOut->init(std::move(texture), desc, format);
4156     return angle::Result::Continue;
4157 }
4158 
getBlendState(const gl::Context * context,const d3d11::BlendStateKey & key,const d3d11::BlendState ** outBlendState)4159 angle::Result Renderer11::getBlendState(const gl::Context *context,
4160                                         const d3d11::BlendStateKey &key,
4161                                         const d3d11::BlendState **outBlendState)
4162 {
4163     return mStateCache.getBlendState(context, this, key, outBlendState);
4164 }
4165 
getRasterizerState(const gl::Context * context,const gl::RasterizerState & rasterState,bool scissorEnabled,ID3D11RasterizerState ** outRasterizerState)4166 angle::Result Renderer11::getRasterizerState(const gl::Context *context,
4167                                              const gl::RasterizerState &rasterState,
4168                                              bool scissorEnabled,
4169                                              ID3D11RasterizerState **outRasterizerState)
4170 {
4171     return mStateCache.getRasterizerState(context, this, rasterState, scissorEnabled,
4172                                           outRasterizerState);
4173 }
4174 
getDepthStencilState(const gl::Context * context,const gl::DepthStencilState & dsState,const d3d11::DepthStencilState ** outDSState)4175 angle::Result Renderer11::getDepthStencilState(const gl::Context *context,
4176                                                const gl::DepthStencilState &dsState,
4177                                                const d3d11::DepthStencilState **outDSState)
4178 {
4179     return mStateCache.getDepthStencilState(context, this, dsState, outDSState);
4180 }
4181 
getSamplerState(const gl::Context * context,const gl::SamplerState & samplerState,ID3D11SamplerState ** outSamplerState)4182 angle::Result Renderer11::getSamplerState(const gl::Context *context,
4183                                           const gl::SamplerState &samplerState,
4184                                           ID3D11SamplerState **outSamplerState)
4185 {
4186     return mStateCache.getSamplerState(context, this, samplerState, outSamplerState);
4187 }
4188 
getSampleDescQuality(GLuint supportedSamples) const4189 UINT Renderer11::getSampleDescQuality(GLuint supportedSamples) const
4190 {
4191     // Per the documentation on
4192     // https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_standard_multisample_quality_levels
4193     // applications can only request the standard multisample pattern on
4194     // feature levels 10_1 and above.
4195     if (supportedSamples > 0 && mDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_1)
4196     {
4197         return D3D11_STANDARD_MULTISAMPLE_PATTERN;
4198     }
4199     return 0;
4200 }
4201 
clearRenderTarget(const gl::Context * context,RenderTargetD3D * renderTarget,const gl::ColorF & clearColorValue,const float clearDepthValue,const unsigned int clearStencilValue)4202 angle::Result Renderer11::clearRenderTarget(const gl::Context *context,
4203                                             RenderTargetD3D *renderTarget,
4204                                             const gl::ColorF &clearColorValue,
4205                                             const float clearDepthValue,
4206                                             const unsigned int clearStencilValue)
4207 {
4208     RenderTarget11 *rt11 = GetAs<RenderTarget11>(renderTarget);
4209 
4210     if (rt11->getFormatSet().dsvFormat != DXGI_FORMAT_UNKNOWN)
4211     {
4212         ASSERT(rt11->getDepthStencilView().valid());
4213 
4214         const auto &format    = rt11->getFormatSet();
4215         const UINT clearFlags = (format.format().depthBits > 0 ? D3D11_CLEAR_DEPTH : 0) |
4216                                 (format.format().stencilBits ? D3D11_CLEAR_STENCIL : 0);
4217         mDeviceContext->ClearDepthStencilView(rt11->getDepthStencilView().get(), clearFlags,
4218                                               clearDepthValue,
4219                                               static_cast<UINT8>(clearStencilValue));
4220         return angle::Result::Continue;
4221     }
4222 
4223     ASSERT(rt11->getRenderTargetView().valid());
4224     ID3D11RenderTargetView *rtv = rt11->getRenderTargetView().get();
4225 
4226     // There are complications with some types of RTV and FL 9_3 with ClearRenderTargetView.
4227     // See https://msdn.microsoft.com/en-us/library/windows/desktop/ff476388(v=vs.85).aspx
4228     ASSERT(mRenderer11DeviceCaps.featureLevel > D3D_FEATURE_LEVEL_9_3 || !IsArrayRTV(rtv));
4229 
4230     const auto &d3d11Format = rt11->getFormatSet();
4231     const auto &glFormat    = gl::GetSizedInternalFormatInfo(renderTarget->getInternalFormat());
4232 
4233     gl::ColorF safeClearColor = clearColorValue;
4234 
4235     if (d3d11Format.format().alphaBits > 0 && glFormat.alphaBits == 0)
4236     {
4237         safeClearColor.alpha = 1.0f;
4238     }
4239 
4240     mDeviceContext->ClearRenderTargetView(rtv, &safeClearColor.red);
4241     return angle::Result::Continue;
4242 }
4243 
canSelectViewInVertexShader() const4244 bool Renderer11::canSelectViewInVertexShader() const
4245 {
4246     return !getFeatures().selectViewInGeometryShader.enabled &&
4247            getRenderer11DeviceCaps().supportsVpRtIndexWriteFromVertexShader;
4248 }
4249 
mapResource(const gl::Context * context,ID3D11Resource * resource,UINT subResource,D3D11_MAP mapType,UINT mapFlags,D3D11_MAPPED_SUBRESOURCE * mappedResource)4250 angle::Result Renderer11::mapResource(const gl::Context *context,
4251                                       ID3D11Resource *resource,
4252                                       UINT subResource,
4253                                       D3D11_MAP mapType,
4254                                       UINT mapFlags,
4255                                       D3D11_MAPPED_SUBRESOURCE *mappedResource)
4256 {
4257     HRESULT hr = mDeviceContext->Map(resource, subResource, mapType, mapFlags, mappedResource);
4258     ANGLE_TRY_HR(GetImplAs<Context11>(context), hr, "Failed to map D3D11 resource.");
4259     return angle::Result::Continue;
4260 }
4261 
markRawBufferUsage(const gl::Context * context)4262 angle::Result Renderer11::markRawBufferUsage(const gl::Context *context)
4263 {
4264     const gl::State &glState   = context->getState();
4265     const gl::Program *program = glState.getProgram();
4266     for (size_t blockIndex = 0; blockIndex < program->getActiveShaderStorageBlockCount();
4267          blockIndex++)
4268     {
4269         GLuint binding = program->getShaderStorageBlockBinding(static_cast<GLuint>(blockIndex));
4270         const auto &shaderStorageBuffer = glState.getIndexedShaderStorageBuffer(binding);
4271         if (shaderStorageBuffer.get() != nullptr)
4272         {
4273             Buffer11 *bufferStorage = GetImplAs<Buffer11>(shaderStorageBuffer.get());
4274             ANGLE_TRY(bufferStorage->markRawBufferUsage(context));
4275         }
4276     }
4277 
4278     for (const auto &atomicCounterBuffer : program->getState().getAtomicCounterBuffers())
4279     {
4280         GLuint binding     = atomicCounterBuffer.binding;
4281         const auto &buffer = glState.getIndexedAtomicCounterBuffer(binding);
4282 
4283         if (buffer.get() != nullptr)
4284         {
4285             Buffer11 *bufferStorage = GetImplAs<Buffer11>(buffer.get());
4286             ANGLE_TRY(bufferStorage->markRawBufferUsage(context));
4287         }
4288     }
4289     return angle::Result::Continue;
4290 }
4291 
markTransformFeedbackUsage(const gl::Context * context)4292 angle::Result Renderer11::markTransformFeedbackUsage(const gl::Context *context)
4293 {
4294     const gl::State &glState                       = context->getState();
4295     const gl::TransformFeedback *transformFeedback = glState.getCurrentTransformFeedback();
4296     for (size_t i = 0; i < transformFeedback->getIndexedBufferCount(); i++)
4297     {
4298         const gl::OffsetBindingPointer<gl::Buffer> &binding =
4299             transformFeedback->getIndexedBuffer(i);
4300         if (binding.get() != nullptr)
4301         {
4302             BufferD3D *bufferD3D = GetImplAs<BufferD3D>(binding.get());
4303             ANGLE_TRY(bufferD3D->markTransformFeedbackUsage(context));
4304         }
4305     }
4306 
4307     return angle::Result::Continue;
4308 }
4309 
getIncompleteTexture(const gl::Context * context,gl::TextureType type,gl::Texture ** textureOut)4310 angle::Result Renderer11::getIncompleteTexture(const gl::Context *context,
4311                                                gl::TextureType type,
4312                                                gl::Texture **textureOut)
4313 {
4314     return GetImplAs<Context11>(context)->getIncompleteTexture(context, type, textureOut);
4315 }
4316 
getVendorString() const4317 std::string Renderer11::getVendorString() const
4318 {
4319     return GetVendorString(mAdapterDescription.VendorId);
4320 }
4321 
getVersionString() const4322 std::string Renderer11::getVersionString() const
4323 {
4324     std::ostringstream versionString;
4325     versionString << "D3D11-";
4326     if (mRenderer11DeviceCaps.driverVersion.valid())
4327     {
4328         versionString << GetDriverVersionString(mRenderer11DeviceCaps.driverVersion.value());
4329     }
4330     return versionString.str();
4331 }
4332 
CreateRenderer11(egl::Display * display)4333 RendererD3D *CreateRenderer11(egl::Display *display)
4334 {
4335     return new Renderer11(display);
4336 }
4337 
4338 }  // namespace rx
4339