• 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_utils.cpp: Conversion functions and other utility routines
8 // specific to the D3D11 renderer.
9 
10 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
11 
12 #include <algorithm>
13 
14 #include "common/debug.h"
15 #include "libANGLE/Buffer.h"
16 #include "libANGLE/Context.h"
17 #include "libANGLE/Framebuffer.h"
18 #include "libANGLE/Program.h"
19 #include "libANGLE/State.h"
20 #include "libANGLE/VertexArray.h"
21 #include "libANGLE/formatutils.h"
22 #include "libANGLE/renderer/d3d/BufferD3D.h"
23 #include "libANGLE/renderer/d3d/FramebufferD3D.h"
24 #include "libANGLE/renderer/d3d/d3d11/Context11.h"
25 #include "libANGLE/renderer/d3d/d3d11/RenderTarget11.h"
26 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
27 #include "libANGLE/renderer/d3d/d3d11/formatutils11.h"
28 #include "libANGLE/renderer/d3d/d3d11/texture_format_table.h"
29 #include "libANGLE/renderer/driver_utils.h"
30 #include "libANGLE/renderer/dxgi_support_table.h"
31 #include "platform/PlatformMethods.h"
32 #include "platform/autogen/FeaturesD3D_autogen.h"
33 
34 namespace rx
35 {
36 
37 namespace d3d11_gl
38 {
39 namespace
40 {
41 // TODO(xinghua.cao@intel.com): Get a more accurate limit.
42 static D3D_FEATURE_LEVEL kMinimumFeatureLevelForES31 = D3D_FEATURE_LEVEL_11_0;
43 
44 // Helper functor for querying DXGI support. Saves passing the parameters repeatedly.
45 class DXGISupportHelper : angle::NonCopyable
46 {
47   public:
DXGISupportHelper(ID3D11Device * device,D3D_FEATURE_LEVEL featureLevel)48     DXGISupportHelper(ID3D11Device *device, D3D_FEATURE_LEVEL featureLevel)
49         : mDevice(device), mFeatureLevel(featureLevel)
50     {}
51 
query(DXGI_FORMAT dxgiFormat,UINT supportMask)52     bool query(DXGI_FORMAT dxgiFormat, UINT supportMask)
53     {
54         if (dxgiFormat == DXGI_FORMAT_UNKNOWN)
55             return false;
56 
57         auto dxgiSupport = d3d11::GetDXGISupport(dxgiFormat, mFeatureLevel);
58 
59         UINT supportedBits = dxgiSupport.alwaysSupportedFlags;
60 
61         if ((dxgiSupport.optionallySupportedFlags & supportMask) != 0)
62         {
63             UINT formatSupport;
64             if (SUCCEEDED(mDevice->CheckFormatSupport(dxgiFormat, &formatSupport)))
65             {
66                 supportedBits |= (formatSupport & supportMask);
67             }
68             else
69             {
70                 // TODO(jmadill): find out why we fail this call sometimes in FL9_3
71                 // ERR() << "Error checking format support for format 0x" << std::hex << dxgiFormat;
72             }
73         }
74 
75         return ((supportedBits & supportMask) == supportMask);
76     }
77 
78   private:
79     ID3D11Device *mDevice;
80     D3D_FEATURE_LEVEL mFeatureLevel;
81 };
82 
GenerateTextureFormatCaps(gl::Version maxClientVersion,GLenum internalFormat,ID3D11Device * device,const Renderer11DeviceCaps & renderer11DeviceCaps)83 gl::TextureCaps GenerateTextureFormatCaps(gl::Version maxClientVersion,
84                                           GLenum internalFormat,
85                                           ID3D11Device *device,
86                                           const Renderer11DeviceCaps &renderer11DeviceCaps)
87 {
88     gl::TextureCaps textureCaps;
89 
90     DXGISupportHelper support(device, renderer11DeviceCaps.featureLevel);
91     const d3d11::Format &formatInfo = d3d11::Format::Get(internalFormat, renderer11DeviceCaps);
92 
93     const gl::InternalFormat &internalFormatInfo = gl::GetSizedInternalFormatInfo(internalFormat);
94 
95     UINT texSupportMask = D3D11_FORMAT_SUPPORT_TEXTURE2D;
96     if (internalFormatInfo.depthBits == 0 && internalFormatInfo.stencilBits == 0)
97     {
98         texSupportMask |= D3D11_FORMAT_SUPPORT_TEXTURECUBE;
99         if (maxClientVersion.major > 2)
100         {
101             texSupportMask |= D3D11_FORMAT_SUPPORT_TEXTURE3D;
102         }
103     }
104 
105     textureCaps.texturable = support.query(formatInfo.texFormat, texSupportMask);
106     textureCaps.filterable =
107         support.query(formatInfo.srvFormat, D3D11_FORMAT_SUPPORT_SHADER_SAMPLE);
108     textureCaps.textureAttachment =
109         (support.query(formatInfo.rtvFormat, D3D11_FORMAT_SUPPORT_RENDER_TARGET)) ||
110         (support.query(formatInfo.dsvFormat, D3D11_FORMAT_SUPPORT_DEPTH_STENCIL));
111     textureCaps.renderbuffer = textureCaps.textureAttachment;
112     textureCaps.blendable    = textureCaps.renderbuffer;
113 
114     DXGI_FORMAT renderFormat = DXGI_FORMAT_UNKNOWN;
115     if (formatInfo.dsvFormat != DXGI_FORMAT_UNKNOWN)
116     {
117         renderFormat = formatInfo.dsvFormat;
118     }
119     else if (formatInfo.rtvFormat != DXGI_FORMAT_UNKNOWN)
120     {
121         renderFormat = formatInfo.rtvFormat;
122     }
123     if (renderFormat != DXGI_FORMAT_UNKNOWN &&
124         support.query(renderFormat, D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET))
125     {
126         // Assume 1x
127         textureCaps.sampleCounts.insert(1);
128 
129         for (unsigned int sampleCount = 2; sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT;
130              sampleCount *= 2)
131         {
132             UINT qualityCount = 0;
133             if (SUCCEEDED(device->CheckMultisampleQualityLevels(renderFormat, sampleCount,
134                                                                 &qualityCount)))
135             {
136                 // Assume we always support lower sample counts
137                 if (qualityCount == 0)
138                 {
139                     break;
140                 }
141                 textureCaps.sampleCounts.insert(sampleCount);
142             }
143         }
144     }
145 
146     return textureCaps;
147 }
148 
GetNPOTTextureSupport(D3D_FEATURE_LEVEL featureLevel)149 bool GetNPOTTextureSupport(D3D_FEATURE_LEVEL featureLevel)
150 {
151     switch (featureLevel)
152     {
153         case D3D_FEATURE_LEVEL_11_1:
154         case D3D_FEATURE_LEVEL_11_0:
155         case D3D_FEATURE_LEVEL_10_1:
156         case D3D_FEATURE_LEVEL_10_0:
157             return true;
158 
159         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx
160         case D3D_FEATURE_LEVEL_9_3:
161         case D3D_FEATURE_LEVEL_9_2:
162         case D3D_FEATURE_LEVEL_9_1:
163             return false;
164 
165         default:
166             UNREACHABLE();
167             return false;
168     }
169 }
170 
GetMaximumAnisotropy(D3D_FEATURE_LEVEL featureLevel)171 float GetMaximumAnisotropy(D3D_FEATURE_LEVEL featureLevel)
172 {
173     switch (featureLevel)
174     {
175         case D3D_FEATURE_LEVEL_11_1:
176         case D3D_FEATURE_LEVEL_11_0:
177             return D3D11_MAX_MAXANISOTROPY;
178 
179         case D3D_FEATURE_LEVEL_10_1:
180         case D3D_FEATURE_LEVEL_10_0:
181             return D3D10_MAX_MAXANISOTROPY;
182 
183         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx
184         case D3D_FEATURE_LEVEL_9_3:
185         case D3D_FEATURE_LEVEL_9_2:
186             return 16;
187 
188         case D3D_FEATURE_LEVEL_9_1:
189             return D3D_FL9_1_DEFAULT_MAX_ANISOTROPY;
190 
191         default:
192             UNREACHABLE();
193             return 0;
194     }
195 }
196 
GetOcclusionQuerySupport(D3D_FEATURE_LEVEL featureLevel)197 bool GetOcclusionQuerySupport(D3D_FEATURE_LEVEL featureLevel)
198 {
199     switch (featureLevel)
200     {
201         case D3D_FEATURE_LEVEL_11_1:
202         case D3D_FEATURE_LEVEL_11_0:
203         case D3D_FEATURE_LEVEL_10_1:
204         case D3D_FEATURE_LEVEL_10_0:
205             return true;
206 
207         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
208         // ID3D11Device::CreateQuery
209         case D3D_FEATURE_LEVEL_9_3:
210         case D3D_FEATURE_LEVEL_9_2:
211             return true;
212         case D3D_FEATURE_LEVEL_9_1:
213             return false;
214 
215         default:
216             UNREACHABLE();
217             return false;
218     }
219 }
220 
GetEventQuerySupport(D3D_FEATURE_LEVEL featureLevel)221 bool GetEventQuerySupport(D3D_FEATURE_LEVEL featureLevel)
222 {
223     // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
224     // ID3D11Device::CreateQuery
225 
226     switch (featureLevel)
227     {
228         case D3D_FEATURE_LEVEL_11_1:
229         case D3D_FEATURE_LEVEL_11_0:
230         case D3D_FEATURE_LEVEL_10_1:
231         case D3D_FEATURE_LEVEL_10_0:
232         case D3D_FEATURE_LEVEL_9_3:
233         case D3D_FEATURE_LEVEL_9_2:
234         case D3D_FEATURE_LEVEL_9_1:
235             return true;
236 
237         default:
238             UNREACHABLE();
239             return false;
240     }
241 }
242 
GetInstancingSupport(D3D_FEATURE_LEVEL featureLevel)243 bool GetInstancingSupport(D3D_FEATURE_LEVEL featureLevel)
244 {
245     // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
246     // ID3D11Device::CreateInputLayout
247 
248     switch (featureLevel)
249     {
250         case D3D_FEATURE_LEVEL_11_1:
251         case D3D_FEATURE_LEVEL_11_0:
252         case D3D_FEATURE_LEVEL_10_1:
253         case D3D_FEATURE_LEVEL_10_0:
254             return true;
255 
256         // Feature Level 9_3 supports instancing, but slot 0 in the input layout must not be
257         // instanced.
258         // D3D9 has a similar restriction, where stream 0 must not be instanced.
259         // This restriction can be worked around by remapping any non-instanced slot to slot
260         // 0.
261         // This works because HLSL uses shader semantics to match the vertex inputs to the
262         // elements in the input layout, rather than the slots.
263         // Note that we only support instancing via ANGLE_instanced_array on 9_3, since 9_3
264         // doesn't support OpenGL ES 3.0
265         case D3D_FEATURE_LEVEL_9_3:
266             return true;
267 
268         case D3D_FEATURE_LEVEL_9_2:
269         case D3D_FEATURE_LEVEL_9_1:
270             return false;
271 
272         default:
273             UNREACHABLE();
274             return false;
275     }
276 }
277 
GetFramebufferMultisampleSupport(D3D_FEATURE_LEVEL featureLevel)278 bool GetFramebufferMultisampleSupport(D3D_FEATURE_LEVEL featureLevel)
279 {
280     switch (featureLevel)
281     {
282         case D3D_FEATURE_LEVEL_11_1:
283         case D3D_FEATURE_LEVEL_11_0:
284         case D3D_FEATURE_LEVEL_10_1:
285         case D3D_FEATURE_LEVEL_10_0:
286             return true;
287 
288         case D3D_FEATURE_LEVEL_9_3:
289         case D3D_FEATURE_LEVEL_9_2:
290         case D3D_FEATURE_LEVEL_9_1:
291             return false;
292 
293         default:
294             UNREACHABLE();
295             return false;
296     }
297 }
298 
GetFramebufferBlitSupport(D3D_FEATURE_LEVEL featureLevel)299 bool GetFramebufferBlitSupport(D3D_FEATURE_LEVEL featureLevel)
300 {
301     switch (featureLevel)
302     {
303         case D3D_FEATURE_LEVEL_11_1:
304         case D3D_FEATURE_LEVEL_11_0:
305         case D3D_FEATURE_LEVEL_10_1:
306         case D3D_FEATURE_LEVEL_10_0:
307             return true;
308 
309         case D3D_FEATURE_LEVEL_9_3:
310         case D3D_FEATURE_LEVEL_9_2:
311         case D3D_FEATURE_LEVEL_9_1:
312             return false;
313 
314         default:
315             UNREACHABLE();
316             return false;
317     }
318 }
319 
GetDerivativeInstructionSupport(D3D_FEATURE_LEVEL featureLevel)320 bool GetDerivativeInstructionSupport(D3D_FEATURE_LEVEL featureLevel)
321 {
322     // http://msdn.microsoft.com/en-us/library/windows/desktop/bb509588.aspx states that
323     // shader model
324     // ps_2_x is required for the ddx (and other derivative functions).
325 
326     // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx states that
327     // feature level
328     // 9.3 supports shader model ps_2_x.
329 
330     switch (featureLevel)
331     {
332         case D3D_FEATURE_LEVEL_11_1:
333         case D3D_FEATURE_LEVEL_11_0:
334         case D3D_FEATURE_LEVEL_10_1:
335         case D3D_FEATURE_LEVEL_10_0:
336         case D3D_FEATURE_LEVEL_9_3:
337             return true;
338         case D3D_FEATURE_LEVEL_9_2:
339         case D3D_FEATURE_LEVEL_9_1:
340             return false;
341 
342         default:
343             UNREACHABLE();
344             return false;
345     }
346 }
347 
GetShaderTextureLODSupport(D3D_FEATURE_LEVEL featureLevel)348 bool GetShaderTextureLODSupport(D3D_FEATURE_LEVEL featureLevel)
349 {
350     switch (featureLevel)
351     {
352         case D3D_FEATURE_LEVEL_11_1:
353         case D3D_FEATURE_LEVEL_11_0:
354         case D3D_FEATURE_LEVEL_10_1:
355         case D3D_FEATURE_LEVEL_10_0:
356             return true;
357 
358         case D3D_FEATURE_LEVEL_9_3:
359         case D3D_FEATURE_LEVEL_9_2:
360         case D3D_FEATURE_LEVEL_9_1:
361             return false;
362 
363         default:
364             UNREACHABLE();
365             return false;
366     }
367 }
368 
GetMaximumSimultaneousRenderTargets(D3D_FEATURE_LEVEL featureLevel)369 int GetMaximumSimultaneousRenderTargets(D3D_FEATURE_LEVEL featureLevel)
370 {
371     // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
372     // ID3D11Device::CreateInputLayout
373 
374     switch (featureLevel)
375     {
376         case D3D_FEATURE_LEVEL_11_1:
377         case D3D_FEATURE_LEVEL_11_0:
378             return D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT;
379 
380         case D3D_FEATURE_LEVEL_10_1:
381         case D3D_FEATURE_LEVEL_10_0:
382             return D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT;
383 
384         case D3D_FEATURE_LEVEL_9_3:
385             return D3D_FL9_3_SIMULTANEOUS_RENDER_TARGET_COUNT;
386         case D3D_FEATURE_LEVEL_9_2:
387         case D3D_FEATURE_LEVEL_9_1:
388             return D3D_FL9_1_SIMULTANEOUS_RENDER_TARGET_COUNT;
389 
390         default:
391             UNREACHABLE();
392             return 0;
393     }
394 }
395 
GetMaximum2DTextureSize(D3D_FEATURE_LEVEL featureLevel)396 int GetMaximum2DTextureSize(D3D_FEATURE_LEVEL featureLevel)
397 {
398     switch (featureLevel)
399     {
400         case D3D_FEATURE_LEVEL_11_1:
401         case D3D_FEATURE_LEVEL_11_0:
402             return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
403 
404         case D3D_FEATURE_LEVEL_10_1:
405         case D3D_FEATURE_LEVEL_10_0:
406             return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
407 
408         case D3D_FEATURE_LEVEL_9_3:
409             return D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
410         case D3D_FEATURE_LEVEL_9_2:
411         case D3D_FEATURE_LEVEL_9_1:
412             return D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
413 
414         default:
415             UNREACHABLE();
416             return 0;
417     }
418 }
419 
GetMaximumCubeMapTextureSize(D3D_FEATURE_LEVEL featureLevel)420 int GetMaximumCubeMapTextureSize(D3D_FEATURE_LEVEL featureLevel)
421 {
422     switch (featureLevel)
423     {
424         case D3D_FEATURE_LEVEL_11_1:
425         case D3D_FEATURE_LEVEL_11_0:
426             return D3D11_REQ_TEXTURECUBE_DIMENSION;
427 
428         case D3D_FEATURE_LEVEL_10_1:
429         case D3D_FEATURE_LEVEL_10_0:
430             return D3D10_REQ_TEXTURECUBE_DIMENSION;
431 
432         case D3D_FEATURE_LEVEL_9_3:
433             return D3D_FL9_3_REQ_TEXTURECUBE_DIMENSION;
434         case D3D_FEATURE_LEVEL_9_2:
435         case D3D_FEATURE_LEVEL_9_1:
436             return D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
437 
438         default:
439             UNREACHABLE();
440             return 0;
441     }
442 }
443 
GetMaximum2DTextureArraySize(D3D_FEATURE_LEVEL featureLevel)444 int GetMaximum2DTextureArraySize(D3D_FEATURE_LEVEL featureLevel)
445 {
446     switch (featureLevel)
447     {
448         case D3D_FEATURE_LEVEL_11_1:
449         case D3D_FEATURE_LEVEL_11_0:
450             return D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
451 
452         case D3D_FEATURE_LEVEL_10_1:
453         case D3D_FEATURE_LEVEL_10_0:
454             return D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
455 
456         case D3D_FEATURE_LEVEL_9_3:
457         case D3D_FEATURE_LEVEL_9_2:
458         case D3D_FEATURE_LEVEL_9_1:
459             return 0;
460 
461         default:
462             UNREACHABLE();
463             return 0;
464     }
465 }
466 
GetMaximum3DTextureSize(D3D_FEATURE_LEVEL featureLevel)467 int GetMaximum3DTextureSize(D3D_FEATURE_LEVEL featureLevel)
468 {
469     switch (featureLevel)
470     {
471         case D3D_FEATURE_LEVEL_11_1:
472         case D3D_FEATURE_LEVEL_11_0:
473             return D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION;
474 
475         case D3D_FEATURE_LEVEL_10_1:
476         case D3D_FEATURE_LEVEL_10_0:
477             return D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION;
478 
479         case D3D_FEATURE_LEVEL_9_3:
480         case D3D_FEATURE_LEVEL_9_2:
481         case D3D_FEATURE_LEVEL_9_1:
482             return D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION;
483 
484         default:
485             UNREACHABLE();
486             return 0;
487     }
488 }
489 
GetMaximumViewportSize(D3D_FEATURE_LEVEL featureLevel)490 int GetMaximumViewportSize(D3D_FEATURE_LEVEL featureLevel)
491 {
492     switch (featureLevel)
493     {
494         case D3D_FEATURE_LEVEL_11_1:
495         case D3D_FEATURE_LEVEL_11_0:
496             return D3D11_VIEWPORT_BOUNDS_MAX;
497 
498         case D3D_FEATURE_LEVEL_10_1:
499         case D3D_FEATURE_LEVEL_10_0:
500             return D3D10_VIEWPORT_BOUNDS_MAX;
501 
502         // No constants for D3D11 Feature Level 9 viewport size limits, use the maximum
503         // texture sizes
504         case D3D_FEATURE_LEVEL_9_3:
505             return D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
506         case D3D_FEATURE_LEVEL_9_2:
507         case D3D_FEATURE_LEVEL_9_1:
508             return D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
509 
510         default:
511             UNREACHABLE();
512             return 0;
513     }
514 }
515 
GetMaximumDrawIndexedIndexCount(D3D_FEATURE_LEVEL featureLevel)516 int GetMaximumDrawIndexedIndexCount(D3D_FEATURE_LEVEL featureLevel)
517 {
518     // D3D11 allows up to 2^32 elements, but we report max signed int for convenience since
519     // that's what's
520     // returned from glGetInteger
521     static_assert(D3D11_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP == 32,
522                   "Unexpected D3D11 constant value.");
523     static_assert(D3D10_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP == 32,
524                   "Unexpected D3D11 constant value.");
525 
526     switch (featureLevel)
527     {
528         case D3D_FEATURE_LEVEL_11_1:
529         case D3D_FEATURE_LEVEL_11_0:
530         case D3D_FEATURE_LEVEL_10_1:
531         case D3D_FEATURE_LEVEL_10_0:
532             return std::numeric_limits<GLint>::max();
533 
534         case D3D_FEATURE_LEVEL_9_3:
535         case D3D_FEATURE_LEVEL_9_2:
536             return D3D_FL9_2_IA_PRIMITIVE_MAX_COUNT;
537         case D3D_FEATURE_LEVEL_9_1:
538             return D3D_FL9_1_IA_PRIMITIVE_MAX_COUNT;
539 
540         default:
541             UNREACHABLE();
542             return 0;
543     }
544 }
545 
GetMaximumDrawVertexCount(D3D_FEATURE_LEVEL featureLevel)546 int GetMaximumDrawVertexCount(D3D_FEATURE_LEVEL featureLevel)
547 {
548     // D3D11 allows up to 2^32 elements, but we report max signed int for convenience since
549     // that's what's
550     // returned from glGetInteger
551     static_assert(D3D11_REQ_DRAW_VERTEX_COUNT_2_TO_EXP == 32, "Unexpected D3D11 constant value.");
552     static_assert(D3D10_REQ_DRAW_VERTEX_COUNT_2_TO_EXP == 32, "Unexpected D3D11 constant value.");
553 
554     switch (featureLevel)
555     {
556         case D3D_FEATURE_LEVEL_11_1:
557         case D3D_FEATURE_LEVEL_11_0:
558         case D3D_FEATURE_LEVEL_10_1:
559         case D3D_FEATURE_LEVEL_10_0:
560             return std::numeric_limits<GLint>::max();
561 
562         case D3D_FEATURE_LEVEL_9_3:
563         case D3D_FEATURE_LEVEL_9_2:
564             return D3D_FL9_2_IA_PRIMITIVE_MAX_COUNT;
565         case D3D_FEATURE_LEVEL_9_1:
566             return D3D_FL9_1_IA_PRIMITIVE_MAX_COUNT;
567 
568         default:
569             UNREACHABLE();
570             return 0;
571     }
572 }
573 
GetMaximumVertexInputSlots(D3D_FEATURE_LEVEL featureLevel)574 int GetMaximumVertexInputSlots(D3D_FEATURE_LEVEL featureLevel)
575 {
576     switch (featureLevel)
577     {
578         case D3D_FEATURE_LEVEL_11_1:
579         case D3D_FEATURE_LEVEL_11_0:
580             return D3D11_STANDARD_VERTEX_ELEMENT_COUNT;
581 
582         case D3D_FEATURE_LEVEL_10_1:
583             return D3D10_1_STANDARD_VERTEX_ELEMENT_COUNT;
584         case D3D_FEATURE_LEVEL_10_0:
585             return D3D10_STANDARD_VERTEX_ELEMENT_COUNT;
586 
587         // From http://http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx
588         // "Max Input Slots"
589         case D3D_FEATURE_LEVEL_9_3:
590         case D3D_FEATURE_LEVEL_9_2:
591         case D3D_FEATURE_LEVEL_9_1:
592             return 16;
593 
594         default:
595             UNREACHABLE();
596             return 0;
597     }
598 }
599 
GetMaximumVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)600 int GetMaximumVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)
601 {
602     switch (featureLevel)
603     {
604         case D3D_FEATURE_LEVEL_11_1:
605         case D3D_FEATURE_LEVEL_11_0:
606             return D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
607 
608         case D3D_FEATURE_LEVEL_10_1:
609         case D3D_FEATURE_LEVEL_10_0:
610             return D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
611 
612         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
613         // ID3D11DeviceContext::VSSetConstantBuffers
614         case D3D_FEATURE_LEVEL_9_3:
615         case D3D_FEATURE_LEVEL_9_2:
616         case D3D_FEATURE_LEVEL_9_1:
617             return 255 - d3d11_gl::GetReservedVertexUniformVectors(featureLevel);
618 
619         default:
620             UNREACHABLE();
621             return 0;
622     }
623 }
624 
GetMaximumVertexUniformBlocks(D3D_FEATURE_LEVEL featureLevel)625 int GetMaximumVertexUniformBlocks(D3D_FEATURE_LEVEL featureLevel)
626 {
627     switch (featureLevel)
628     {
629         case D3D_FEATURE_LEVEL_11_1:
630         case D3D_FEATURE_LEVEL_11_0:
631             return D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
632                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
633 
634         case D3D_FEATURE_LEVEL_10_1:
635         case D3D_FEATURE_LEVEL_10_0:
636             return D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
637                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
638 
639         // Uniform blocks not supported on D3D11 Feature Level 9
640         case D3D_FEATURE_LEVEL_9_3:
641         case D3D_FEATURE_LEVEL_9_2:
642         case D3D_FEATURE_LEVEL_9_1:
643             return 0;
644 
645         default:
646             UNREACHABLE();
647             return 0;
648     }
649 }
650 
GetReservedVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)651 int GetReservedVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)
652 {
653     // According to The OpenGL ES Shading Language specifications
654     // (Language Version 1.00 section 10.16, Language Version 3.10 section 12.21)
655     // built-in special variables (e.g. gl_FragCoord, or gl_PointCoord)
656     // which are statically used in the shader should be included in the variable packing
657     // algorithm.
658     // Therefore, we should not reserve output vectors for them.
659 
660     switch (featureLevel)
661     {
662         // We must reserve one output vector for dx_Position.
663         // We also reserve one for gl_Position, which we unconditionally output on Feature
664         // Levels 10_0+,
665         // even if it's unused in the shader (e.g. for transform feedback). TODO: This could
666         // be improved.
667         case D3D_FEATURE_LEVEL_11_1:
668         case D3D_FEATURE_LEVEL_11_0:
669         case D3D_FEATURE_LEVEL_10_1:
670         case D3D_FEATURE_LEVEL_10_0:
671             return 2;
672 
673         // Just reserve dx_Position on Feature Level 9, since we don't ever need to output
674         // gl_Position.
675         case D3D_FEATURE_LEVEL_9_3:
676         case D3D_FEATURE_LEVEL_9_2:
677         case D3D_FEATURE_LEVEL_9_1:
678             return 1;
679 
680         default:
681             UNREACHABLE();
682             return 0;
683     }
684 }
685 
GetMaximumVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)686 int GetMaximumVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)
687 {
688     static_assert(gl::IMPLEMENTATION_MAX_VARYING_VECTORS == D3D11_VS_OUTPUT_REGISTER_COUNT,
689                   "Unexpected D3D11 constant value.");
690 
691     switch (featureLevel)
692     {
693         case D3D_FEATURE_LEVEL_11_1:
694         case D3D_FEATURE_LEVEL_11_0:
695             return D3D11_VS_OUTPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
696 
697         case D3D_FEATURE_LEVEL_10_1:
698             return D3D10_1_VS_OUTPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
699         case D3D_FEATURE_LEVEL_10_0:
700             return D3D10_VS_OUTPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
701 
702         // Use Shader Model 2.X limits
703         case D3D_FEATURE_LEVEL_9_3:
704         case D3D_FEATURE_LEVEL_9_2:
705         case D3D_FEATURE_LEVEL_9_1:
706             return 8 - GetReservedVertexOutputVectors(featureLevel);
707 
708         default:
709             UNREACHABLE();
710             return 0;
711     }
712 }
713 
GetMaximumVertexTextureUnits(D3D_FEATURE_LEVEL featureLevel)714 int GetMaximumVertexTextureUnits(D3D_FEATURE_LEVEL featureLevel)
715 {
716     switch (featureLevel)
717     {
718         case D3D_FEATURE_LEVEL_11_1:
719         case D3D_FEATURE_LEVEL_11_0:
720             return D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
721 
722         case D3D_FEATURE_LEVEL_10_1:
723         case D3D_FEATURE_LEVEL_10_0:
724             return D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT;
725 
726         // Vertex textures not supported on D3D11 Feature Level 9 according to
727         // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
728         // ID3D11DeviceContext::VSSetSamplers and ID3D11DeviceContext::VSSetShaderResources
729         case D3D_FEATURE_LEVEL_9_3:
730         case D3D_FEATURE_LEVEL_9_2:
731         case D3D_FEATURE_LEVEL_9_1:
732             return 0;
733 
734         default:
735             UNREACHABLE();
736             return 0;
737     }
738 }
739 
GetMaximumPixelUniformVectors(D3D_FEATURE_LEVEL featureLevel)740 int GetMaximumPixelUniformVectors(D3D_FEATURE_LEVEL featureLevel)
741 {
742     // TODO(geofflang): Remove hard-coded limit once the gl-uniform-arrays test can pass
743     switch (featureLevel)
744     {
745         case D3D_FEATURE_LEVEL_11_1:
746         case D3D_FEATURE_LEVEL_11_0:
747             return 1024;  // D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
748 
749         case D3D_FEATURE_LEVEL_10_1:
750         case D3D_FEATURE_LEVEL_10_0:
751             return 1024;  // D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
752 
753         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
754         // ID3D11DeviceContext::PSSetConstantBuffers
755         case D3D_FEATURE_LEVEL_9_3:
756         case D3D_FEATURE_LEVEL_9_2:
757         case D3D_FEATURE_LEVEL_9_1:
758             return 32 - d3d11_gl::GetReservedFragmentUniformVectors(featureLevel);
759 
760         default:
761             UNREACHABLE();
762             return 0;
763     }
764 }
765 
GetMaximumPixelUniformBlocks(D3D_FEATURE_LEVEL featureLevel)766 int GetMaximumPixelUniformBlocks(D3D_FEATURE_LEVEL featureLevel)
767 {
768     switch (featureLevel)
769     {
770         case D3D_FEATURE_LEVEL_11_1:
771         case D3D_FEATURE_LEVEL_11_0:
772             return D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
773                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
774 
775         case D3D_FEATURE_LEVEL_10_1:
776         case D3D_FEATURE_LEVEL_10_0:
777             return D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
778                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
779 
780         // Uniform blocks not supported on D3D11 Feature Level 9
781         case D3D_FEATURE_LEVEL_9_3:
782         case D3D_FEATURE_LEVEL_9_2:
783         case D3D_FEATURE_LEVEL_9_1:
784             return 0;
785 
786         default:
787             UNREACHABLE();
788             return 0;
789     }
790 }
791 
GetMaximumPixelInputVectors(D3D_FEATURE_LEVEL featureLevel)792 int GetMaximumPixelInputVectors(D3D_FEATURE_LEVEL featureLevel)
793 {
794     switch (featureLevel)
795     {
796         case D3D_FEATURE_LEVEL_11_1:
797         case D3D_FEATURE_LEVEL_11_0:
798             return D3D11_PS_INPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
799 
800         case D3D_FEATURE_LEVEL_10_1:
801         case D3D_FEATURE_LEVEL_10_0:
802             return D3D10_PS_INPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
803 
804         // Use Shader Model 2.X limits
805         case D3D_FEATURE_LEVEL_9_3:
806             return 8 - GetReservedVertexOutputVectors(featureLevel);
807         case D3D_FEATURE_LEVEL_9_2:
808         case D3D_FEATURE_LEVEL_9_1:
809             return 8 - GetReservedVertexOutputVectors(featureLevel);
810 
811         default:
812             UNREACHABLE();
813             return 0;
814     }
815 }
816 
GetMaximumPixelTextureUnits(D3D_FEATURE_LEVEL featureLevel)817 int GetMaximumPixelTextureUnits(D3D_FEATURE_LEVEL featureLevel)
818 {
819     switch (featureLevel)
820     {
821         case D3D_FEATURE_LEVEL_11_1:
822         case D3D_FEATURE_LEVEL_11_0:
823             return D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
824 
825         case D3D_FEATURE_LEVEL_10_1:
826         case D3D_FEATURE_LEVEL_10_0:
827             return D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT;
828 
829         // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
830         // ID3D11DeviceContext::PSSetShaderResources
831         case D3D_FEATURE_LEVEL_9_3:
832         case D3D_FEATURE_LEVEL_9_2:
833         case D3D_FEATURE_LEVEL_9_1:
834             return 16;
835 
836         default:
837             UNREACHABLE();
838             return 0;
839     }
840 }
841 
GetMaxComputeWorkGroupCount(D3D_FEATURE_LEVEL featureLevel)842 std::array<GLint, 3> GetMaxComputeWorkGroupCount(D3D_FEATURE_LEVEL featureLevel)
843 {
844     switch (featureLevel)
845     {
846         case D3D_FEATURE_LEVEL_11_1:
847         case D3D_FEATURE_LEVEL_11_0:
848             return {{D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION,
849                      D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION,
850                      D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION}};
851         default:
852             return {{0, 0, 0}};
853     }
854 }
855 
GetMaxComputeWorkGroupSize(D3D_FEATURE_LEVEL featureLevel)856 std::array<GLint, 3> GetMaxComputeWorkGroupSize(D3D_FEATURE_LEVEL featureLevel)
857 {
858     switch (featureLevel)
859     {
860         case D3D_FEATURE_LEVEL_11_1:
861         case D3D_FEATURE_LEVEL_11_0:
862             return {{D3D11_CS_THREAD_GROUP_MAX_X, D3D11_CS_THREAD_GROUP_MAX_Y,
863                      D3D11_CS_THREAD_GROUP_MAX_Z}};
864         default:
865             return {{0, 0, 0}};
866     }
867 }
868 
GetMaxComputeWorkGroupInvocations(D3D_FEATURE_LEVEL featureLevel)869 int GetMaxComputeWorkGroupInvocations(D3D_FEATURE_LEVEL featureLevel)
870 {
871     switch (featureLevel)
872     {
873         case D3D_FEATURE_LEVEL_11_1:
874         case D3D_FEATURE_LEVEL_11_0:
875             return D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP;
876         default:
877             return 0;
878     }
879 }
880 
GetMaxComputeSharedMemorySize(D3D_FEATURE_LEVEL featureLevel)881 int GetMaxComputeSharedMemorySize(D3D_FEATURE_LEVEL featureLevel)
882 {
883     switch (featureLevel)
884     {
885         // In D3D11 the maximum total size of all variables with the groupshared storage class is
886         // 32kb.
887         // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-syntax
888         case D3D_FEATURE_LEVEL_11_1:
889         case D3D_FEATURE_LEVEL_11_0:
890             return 32768;
891         default:
892             return 0;
893     }
894 }
895 
GetMaximumComputeUniformVectors(D3D_FEATURE_LEVEL featureLevel)896 int GetMaximumComputeUniformVectors(D3D_FEATURE_LEVEL featureLevel)
897 {
898     switch (featureLevel)
899     {
900         case D3D_FEATURE_LEVEL_11_1:
901         case D3D_FEATURE_LEVEL_11_0:
902             return D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
903         default:
904             return 0;
905     }
906 }
907 
GetMaximumComputeUniformBlocks(D3D_FEATURE_LEVEL featureLevel)908 int GetMaximumComputeUniformBlocks(D3D_FEATURE_LEVEL featureLevel)
909 {
910     switch (featureLevel)
911     {
912         case D3D_FEATURE_LEVEL_11_1:
913         case D3D_FEATURE_LEVEL_11_0:
914             return D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
915                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
916         default:
917             return 0;
918     }
919 }
920 
GetMaximumComputeTextureUnits(D3D_FEATURE_LEVEL featureLevel)921 int GetMaximumComputeTextureUnits(D3D_FEATURE_LEVEL featureLevel)
922 {
923     switch (featureLevel)
924     {
925         case D3D_FEATURE_LEVEL_11_1:
926         case D3D_FEATURE_LEVEL_11_0:
927             return D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
928         default:
929             return 0;
930     }
931 }
932 
SetUAVRelatedResourceLimits(D3D_FEATURE_LEVEL featureLevel,gl::Caps * caps)933 void SetUAVRelatedResourceLimits(D3D_FEATURE_LEVEL featureLevel, gl::Caps *caps)
934 {
935     ASSERT(caps);
936 
937     GLuint reservedUAVsForAtomicCounterBuffers = 0u;
938 
939     // For pixel shaders, the render targets and unordered access views share the same resource
940     // slots when being written out.
941     // https://msdn.microsoft.com/en-us/library/windows/desktop/ff476465(v=vs.85).aspx
942     GLuint maxNumRTVsAndUAVs = 0u;
943 
944     switch (featureLevel)
945     {
946         case D3D_FEATURE_LEVEL_11_1:
947             // Currently we allocate 4 UAV slots for atomic counter buffers on feature level 11_1.
948             reservedUAVsForAtomicCounterBuffers = 4u;
949             maxNumRTVsAndUAVs                   = D3D11_1_UAV_SLOT_COUNT;
950             break;
951         case D3D_FEATURE_LEVEL_11_0:
952             // Currently we allocate 1 UAV slot for atomic counter buffers on feature level 11_0.
953             reservedUAVsForAtomicCounterBuffers = 1u;
954             maxNumRTVsAndUAVs                   = D3D11_PS_CS_UAV_REGISTER_COUNT;
955             break;
956         default:
957             return;
958     }
959 
960     // Set limits on atomic counter buffers in fragment shaders and compute shaders.
961     caps->maxCombinedAtomicCounterBuffers = reservedUAVsForAtomicCounterBuffers;
962     caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Compute] =
963         reservedUAVsForAtomicCounterBuffers;
964     caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Fragment] =
965         reservedUAVsForAtomicCounterBuffers;
966     caps->maxAtomicCounterBufferBindings = reservedUAVsForAtomicCounterBuffers;
967 
968     // Setting MAX_COMPUTE_ATOMIC_COUNTERS to a conservative number of 1024 * the number of UAV
969     // reserved for atomic counters. It could theoretically be set to max buffer size / 4 but that
970     // number could cause problems.
971     caps->maxCombinedAtomicCounters = reservedUAVsForAtomicCounterBuffers * 1024;
972     caps->maxShaderAtomicCounters[gl::ShaderType::Compute] = caps->maxCombinedAtomicCounters;
973 
974     // See
975     // https://docs.microsoft.com/en-us/windows/desktop/direct3d11/overviews-direct3d-11-resources-limits
976     // Resource size (in MB) for any of the preceding resources is min(max(128,0.25f * (amount of
977     // dedicated VRAM)), 2048) MB. So we set it to 128MB to keep same with GL backend.
978     caps->maxShaderStorageBlockSize =
979         D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024 * 1024;
980 
981     // Allocate the remaining slots for images and shader storage blocks.
982     // The maximum number of fragment shader outputs depends on the current context version, so we
983     // will not set it here. See comments in Context11::initialize().
984     caps->maxCombinedShaderOutputResources =
985         maxNumRTVsAndUAVs - reservedUAVsForAtomicCounterBuffers;
986 
987     // Set limits on images and shader storage blocks in fragment shaders and compute shaders.
988     caps->maxCombinedShaderStorageBlocks                   = caps->maxCombinedShaderOutputResources;
989     caps->maxShaderStorageBlocks[gl::ShaderType::Compute]  = caps->maxCombinedShaderOutputResources;
990     caps->maxShaderStorageBlocks[gl::ShaderType::Fragment] = caps->maxCombinedShaderOutputResources;
991     caps->maxShaderStorageBufferBindings                   = caps->maxCombinedShaderOutputResources;
992 
993     caps->maxImageUnits                                    = caps->maxCombinedShaderOutputResources;
994     caps->maxCombinedImageUniforms                         = caps->maxCombinedShaderOutputResources;
995     caps->maxShaderImageUniforms[gl::ShaderType::Compute]  = caps->maxCombinedShaderOutputResources;
996     caps->maxShaderImageUniforms[gl::ShaderType::Fragment] = caps->maxCombinedShaderOutputResources;
997 
998     // On feature level 11_1, UAVs are also available in vertex shaders and geometry shaders.
999     if (featureLevel == D3D_FEATURE_LEVEL_11_1)
1000     {
1001         caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Vertex] =
1002             caps->maxCombinedAtomicCounterBuffers;
1003         caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Geometry] =
1004             caps->maxCombinedAtomicCounterBuffers;
1005 
1006         caps->maxShaderImageUniforms[gl::ShaderType::Vertex] =
1007             caps->maxCombinedShaderOutputResources;
1008         caps->maxShaderStorageBlocks[gl::ShaderType::Vertex] =
1009             caps->maxCombinedShaderOutputResources;
1010         caps->maxShaderImageUniforms[gl::ShaderType::Geometry] =
1011             caps->maxCombinedShaderOutputResources;
1012         caps->maxShaderStorageBlocks[gl::ShaderType::Geometry] =
1013             caps->maxCombinedShaderOutputResources;
1014     }
1015 }
1016 
GetMinimumTexelOffset(D3D_FEATURE_LEVEL featureLevel)1017 int GetMinimumTexelOffset(D3D_FEATURE_LEVEL featureLevel)
1018 {
1019     switch (featureLevel)
1020     {
1021         case D3D_FEATURE_LEVEL_11_1:
1022         case D3D_FEATURE_LEVEL_11_0:
1023             return D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE;
1024 
1025         case D3D_FEATURE_LEVEL_10_1:
1026         case D3D_FEATURE_LEVEL_10_0:
1027             return D3D10_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE;
1028 
1029         // Sampling functions with offsets are not available below shader model 4.0.
1030         case D3D_FEATURE_LEVEL_9_3:
1031         case D3D_FEATURE_LEVEL_9_2:
1032         case D3D_FEATURE_LEVEL_9_1:
1033             return 0;
1034 
1035         default:
1036             UNREACHABLE();
1037             return 0;
1038     }
1039 }
1040 
GetMaximumTexelOffset(D3D_FEATURE_LEVEL featureLevel)1041 int GetMaximumTexelOffset(D3D_FEATURE_LEVEL featureLevel)
1042 {
1043     switch (featureLevel)
1044     {
1045         case D3D_FEATURE_LEVEL_11_1:
1046         case D3D_FEATURE_LEVEL_11_0:
1047             return D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE;
1048         case D3D_FEATURE_LEVEL_10_1:
1049         case D3D_FEATURE_LEVEL_10_0:
1050             return D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE;
1051 
1052         // Sampling functions with offsets are not available below shader model 4.0.
1053         case D3D_FEATURE_LEVEL_9_3:
1054         case D3D_FEATURE_LEVEL_9_2:
1055         case D3D_FEATURE_LEVEL_9_1:
1056             return 0;
1057 
1058         default:
1059             UNREACHABLE();
1060             return 0;
1061     }
1062 }
1063 
GetMinimumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)1064 int GetMinimumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)
1065 {
1066     switch (featureLevel)
1067     {
1068         // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/gather4-po--sm5---asm-
1069         case D3D_FEATURE_LEVEL_11_1:
1070         case D3D_FEATURE_LEVEL_11_0:
1071             return -32;
1072 
1073         case D3D_FEATURE_LEVEL_10_1:
1074         case D3D_FEATURE_LEVEL_10_0:
1075         case D3D_FEATURE_LEVEL_9_3:
1076         case D3D_FEATURE_LEVEL_9_2:
1077         case D3D_FEATURE_LEVEL_9_1:
1078             return 0;
1079 
1080         default:
1081             UNREACHABLE();
1082             return 0;
1083     }
1084 }
1085 
GetMaximumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)1086 int GetMaximumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)
1087 {
1088     switch (featureLevel)
1089     {
1090         // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/gather4-po--sm5---asm-
1091         case D3D_FEATURE_LEVEL_11_1:
1092         case D3D_FEATURE_LEVEL_11_0:
1093             return 31;
1094 
1095         case D3D_FEATURE_LEVEL_10_1:
1096         case D3D_FEATURE_LEVEL_10_0:
1097         case D3D_FEATURE_LEVEL_9_3:
1098         case D3D_FEATURE_LEVEL_9_2:
1099         case D3D_FEATURE_LEVEL_9_1:
1100             return 0;
1101 
1102         default:
1103             UNREACHABLE();
1104             return 0;
1105     }
1106 }
1107 
GetMaximumConstantBufferSize(D3D_FEATURE_LEVEL featureLevel)1108 size_t GetMaximumConstantBufferSize(D3D_FEATURE_LEVEL featureLevel)
1109 {
1110     // Returns a size_t despite the limit being a GLuint64 because size_t is the maximum
1111     // size of
1112     // any buffer that could be allocated.
1113 
1114     const size_t bytesPerComponent = 4 * sizeof(float);
1115 
1116     switch (featureLevel)
1117     {
1118         case D3D_FEATURE_LEVEL_11_1:
1119         case D3D_FEATURE_LEVEL_11_0:
1120             return D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * bytesPerComponent;
1121 
1122         case D3D_FEATURE_LEVEL_10_1:
1123         case D3D_FEATURE_LEVEL_10_0:
1124             return D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * bytesPerComponent;
1125 
1126         // Limits from http://msdn.microsoft.com/en-us/library/windows/desktop/ff476501.aspx
1127         // remarks section
1128         case D3D_FEATURE_LEVEL_9_3:
1129         case D3D_FEATURE_LEVEL_9_2:
1130         case D3D_FEATURE_LEVEL_9_1:
1131             return 4096 * bytesPerComponent;
1132 
1133         default:
1134             UNREACHABLE();
1135             return 0;
1136     }
1137 }
1138 
GetMaximumStreamOutputBuffers(D3D_FEATURE_LEVEL featureLevel)1139 int GetMaximumStreamOutputBuffers(D3D_FEATURE_LEVEL featureLevel)
1140 {
1141     switch (featureLevel)
1142     {
1143         case D3D_FEATURE_LEVEL_11_1:
1144         case D3D_FEATURE_LEVEL_11_0:
1145             return D3D11_SO_BUFFER_SLOT_COUNT;
1146 
1147         case D3D_FEATURE_LEVEL_10_1:
1148             return D3D10_1_SO_BUFFER_SLOT_COUNT;
1149         case D3D_FEATURE_LEVEL_10_0:
1150             return D3D10_SO_BUFFER_SLOT_COUNT;
1151 
1152         case D3D_FEATURE_LEVEL_9_3:
1153         case D3D_FEATURE_LEVEL_9_2:
1154         case D3D_FEATURE_LEVEL_9_1:
1155             return 0;
1156 
1157         default:
1158             UNREACHABLE();
1159             return 0;
1160     }
1161 }
1162 
GetMaximumStreamOutputInterleavedComponents(D3D_FEATURE_LEVEL featureLevel)1163 int GetMaximumStreamOutputInterleavedComponents(D3D_FEATURE_LEVEL featureLevel)
1164 {
1165     switch (featureLevel)
1166     {
1167         case D3D_FEATURE_LEVEL_11_1:
1168         case D3D_FEATURE_LEVEL_11_0:
1169 
1170         case D3D_FEATURE_LEVEL_10_1:
1171         case D3D_FEATURE_LEVEL_10_0:
1172             return GetMaximumVertexOutputVectors(featureLevel) * 4;
1173 
1174         case D3D_FEATURE_LEVEL_9_3:
1175         case D3D_FEATURE_LEVEL_9_2:
1176         case D3D_FEATURE_LEVEL_9_1:
1177             return 0;
1178 
1179         default:
1180             UNREACHABLE();
1181             return 0;
1182     }
1183 }
1184 
GetMaximumStreamOutputSeparateComponents(D3D_FEATURE_LEVEL featureLevel)1185 int GetMaximumStreamOutputSeparateComponents(D3D_FEATURE_LEVEL featureLevel)
1186 {
1187     switch (featureLevel)
1188     {
1189         case D3D_FEATURE_LEVEL_11_1:
1190         case D3D_FEATURE_LEVEL_11_0:
1191             return GetMaximumStreamOutputInterleavedComponents(featureLevel) /
1192                    GetMaximumStreamOutputBuffers(featureLevel);
1193 
1194         // D3D 10 and 10.1 only allow one output per output slot if an output slot other
1195         // than zero is used.
1196         case D3D_FEATURE_LEVEL_10_1:
1197         case D3D_FEATURE_LEVEL_10_0:
1198             return 4;
1199 
1200         case D3D_FEATURE_LEVEL_9_3:
1201         case D3D_FEATURE_LEVEL_9_2:
1202         case D3D_FEATURE_LEVEL_9_1:
1203             return 0;
1204 
1205         default:
1206             UNREACHABLE();
1207             return 0;
1208     }
1209 }
1210 
GetMaximumRenderToBufferWindowSize(D3D_FEATURE_LEVEL featureLevel)1211 int GetMaximumRenderToBufferWindowSize(D3D_FEATURE_LEVEL featureLevel)
1212 {
1213     switch (featureLevel)
1214     {
1215         case D3D_FEATURE_LEVEL_11_1:
1216         case D3D_FEATURE_LEVEL_11_0:
1217             return D3D11_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH;
1218         case D3D_FEATURE_LEVEL_10_1:
1219         case D3D_FEATURE_LEVEL_10_0:
1220             return D3D10_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH;
1221 
1222         // REQ_RENDER_TO_BUFFER_WINDOW_WIDTH not supported on D3D11 Feature Level 9,
1223         // use the maximum texture sizes
1224         case D3D_FEATURE_LEVEL_9_3:
1225             return D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
1226         case D3D_FEATURE_LEVEL_9_2:
1227         case D3D_FEATURE_LEVEL_9_1:
1228             return D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
1229 
1230         default:
1231             UNREACHABLE();
1232             return 0;
1233     }
1234 }
1235 
GetIntelDriverVersion(const Optional<LARGE_INTEGER> driverVersion)1236 IntelDriverVersion GetIntelDriverVersion(const Optional<LARGE_INTEGER> driverVersion)
1237 {
1238     if (!driverVersion.valid())
1239         return IntelDriverVersion(0);
1240 
1241     DWORD lowPart = driverVersion.value().LowPart;
1242     return IntelDriverVersion(HIWORD(lowPart) * 10000 + LOWORD(lowPart));
1243 }
1244 
1245 }  // anonymous namespace
1246 
GetReservedVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)1247 unsigned int GetReservedVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)
1248 {
1249     switch (featureLevel)
1250     {
1251         case D3D_FEATURE_LEVEL_11_1:
1252         case D3D_FEATURE_LEVEL_11_0:
1253         case D3D_FEATURE_LEVEL_10_1:
1254         case D3D_FEATURE_LEVEL_10_0:
1255             return 0;
1256 
1257         case D3D_FEATURE_LEVEL_9_3:
1258         case D3D_FEATURE_LEVEL_9_2:
1259         case D3D_FEATURE_LEVEL_9_1:
1260             return 3;  // dx_ViewAdjust, dx_ViewCoords and dx_ViewScale
1261 
1262         default:
1263             UNREACHABLE();
1264             return 0;
1265     }
1266 }
1267 
GetReservedFragmentUniformVectors(D3D_FEATURE_LEVEL featureLevel)1268 unsigned int GetReservedFragmentUniformVectors(D3D_FEATURE_LEVEL featureLevel)
1269 {
1270     switch (featureLevel)
1271     {
1272         case D3D_FEATURE_LEVEL_11_1:
1273         case D3D_FEATURE_LEVEL_11_0:
1274         case D3D_FEATURE_LEVEL_10_1:
1275         case D3D_FEATURE_LEVEL_10_0:
1276             return 0;
1277 
1278         case D3D_FEATURE_LEVEL_9_3:
1279         case D3D_FEATURE_LEVEL_9_2:
1280         case D3D_FEATURE_LEVEL_9_1:
1281             return 4;  // dx_ViewCoords, dx_DepthFront, dx_DepthRange, dx_FragCoordOffset
1282 
1283         default:
1284             UNREACHABLE();
1285             return 0;
1286     }
1287 }
1288 
GetMaximumClientVersion(const Renderer11DeviceCaps & caps)1289 gl::Version GetMaximumClientVersion(const Renderer11DeviceCaps &caps)
1290 {
1291     switch (caps.featureLevel)
1292     {
1293         case D3D_FEATURE_LEVEL_11_1:
1294         case D3D_FEATURE_LEVEL_11_0:
1295             return gl::Version(3, 1);
1296         case D3D_FEATURE_LEVEL_10_1:
1297             return gl::Version(3, 0);
1298 
1299         case D3D_FEATURE_LEVEL_10_0:
1300             if (caps.allowES3OnFL10_0)
1301             {
1302                 return gl::Version(3, 0);
1303             }
1304             else
1305             {
1306                 return gl::Version(2, 0);
1307             }
1308         case D3D_FEATURE_LEVEL_9_3:
1309         case D3D_FEATURE_LEVEL_9_2:
1310         case D3D_FEATURE_LEVEL_9_1:
1311             return gl::Version(2, 0);
1312 
1313         default:
1314             UNREACHABLE();
1315             return gl::Version(0, 0);
1316     }
1317 }
1318 
GetMinimumFeatureLevelForES31()1319 D3D_FEATURE_LEVEL GetMinimumFeatureLevelForES31()
1320 {
1321     return kMinimumFeatureLevelForES31;
1322 }
1323 
GetMaxViewportAndScissorRectanglesPerPipeline(D3D_FEATURE_LEVEL featureLevel)1324 unsigned int GetMaxViewportAndScissorRectanglesPerPipeline(D3D_FEATURE_LEVEL featureLevel)
1325 {
1326     switch (featureLevel)
1327     {
1328         case D3D_FEATURE_LEVEL_11_1:
1329         case D3D_FEATURE_LEVEL_11_0:
1330             return D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
1331         case D3D_FEATURE_LEVEL_10_1:
1332         case D3D_FEATURE_LEVEL_10_0:
1333         case D3D_FEATURE_LEVEL_9_3:
1334         case D3D_FEATURE_LEVEL_9_2:
1335         case D3D_FEATURE_LEVEL_9_1:
1336             return 1;
1337         default:
1338             UNREACHABLE();
1339             return 0;
1340     }
1341 }
1342 
IsMultiviewSupported(D3D_FEATURE_LEVEL featureLevel)1343 bool IsMultiviewSupported(D3D_FEATURE_LEVEL featureLevel)
1344 {
1345     // The multiview extensions can always be supported in D3D11 through geometry shaders.
1346     switch (featureLevel)
1347     {
1348         case D3D_FEATURE_LEVEL_11_1:
1349         case D3D_FEATURE_LEVEL_11_0:
1350             return true;
1351         default:
1352             return false;
1353     }
1354 }
1355 
GetMaxSampleMaskWords(D3D_FEATURE_LEVEL featureLevel)1356 int GetMaxSampleMaskWords(D3D_FEATURE_LEVEL featureLevel)
1357 {
1358     switch (featureLevel)
1359     {
1360         // D3D10+ only allows 1 sample mask.
1361         case D3D_FEATURE_LEVEL_11_1:
1362         case D3D_FEATURE_LEVEL_11_0:
1363         case D3D_FEATURE_LEVEL_10_1:
1364         case D3D_FEATURE_LEVEL_10_0:
1365             return 1;
1366         case D3D_FEATURE_LEVEL_9_3:
1367         case D3D_FEATURE_LEVEL_9_2:
1368         case D3D_FEATURE_LEVEL_9_1:
1369             return 0;
1370         default:
1371             UNREACHABLE();
1372             return 0;
1373     }
1374 }
1375 
HasTextureBufferSupport(ID3D11Device * device,const Renderer11DeviceCaps & renderer11DeviceCaps)1376 bool HasTextureBufferSupport(ID3D11Device *device, const Renderer11DeviceCaps &renderer11DeviceCaps)
1377 {
1378     if (renderer11DeviceCaps.featureLevel < D3D_FEATURE_LEVEL_11_0)
1379         return false;
1380 
1381     if (!renderer11DeviceCaps.supportsTypedUAVLoadAdditionalFormats)
1382         return false;
1383 
1384     // https://docs.microsoft.com/en-us/windows/win32/direct3d12/typed-unordered-access-view-loads
1385     // we don't need to check the typed store. from the spec,
1386     // https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#FormatList
1387     // all the following format support typed stored.
1388     // According to spec,
1389     // https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glBindImageTexture.xhtml the
1390     // required image unit format are GL_RGBA32F, GL_RGBA32UI, GL_RGBA32I, GL_RGBA16F, GL_RGBA16UI,
1391     // GL_RGBA16I, GL_RGBA8, GL_RGBAUI, GL_RGBA8I, GL_RGBA8_SNORM, GL_R32F, GL_R32UI, GL_R32I,
1392     const std::array<DXGI_FORMAT, 2> &optionalFormats = {
1393         DXGI_FORMAT_R32G32B32A32_FLOAT,  // test for GL_RGBA32(UIF), GL_RGBA16(UIF),
1394                                          // GL_RGBA8(UIUnorm)
1395         DXGI_FORMAT_R8G8B8A8_SNORM,      // test for GL_RGBA8_SNORM,
1396     };
1397 
1398     for (DXGI_FORMAT dxgiFormat : optionalFormats)
1399     {
1400         D3D11_FEATURE_DATA_FORMAT_SUPPORT FormatSupport = {dxgiFormat, 0};
1401         if (!SUCCEEDED(device->CheckFeatureSupport(D3D11_FEATURE_FORMAT_SUPPORT, &FormatSupport,
1402                                                    sizeof(FormatSupport))))
1403         {
1404             WARN() << "Error checking typed load support for format 0x" << std::hex << dxgiFormat;
1405             return false;
1406         }
1407         if ((FormatSupport.OutFormatSupport & D3D11_FORMAT_SUPPORT2_UAV_TYPED_LOAD) == 0)
1408             return false;
1409     }
1410     return true;
1411 }
1412 
GenerateCaps(ID3D11Device * device,ID3D11DeviceContext * deviceContext,const Renderer11DeviceCaps & renderer11DeviceCaps,const angle::FeaturesD3D & features,const char * description,gl::Caps * caps,gl::TextureCapsMap * textureCapsMap,gl::Extensions * extensions,gl::Limitations * limitations,ShPixelLocalStorageOptions * plsOptions)1413 void GenerateCaps(ID3D11Device *device,
1414                   ID3D11DeviceContext *deviceContext,
1415                   const Renderer11DeviceCaps &renderer11DeviceCaps,
1416                   const angle::FeaturesD3D &features,
1417                   const char *description,
1418                   gl::Caps *caps,
1419                   gl::TextureCapsMap *textureCapsMap,
1420                   gl::Extensions *extensions,
1421                   gl::Limitations *limitations,
1422                   ShPixelLocalStorageOptions *plsOptions)
1423 {
1424     const D3D_FEATURE_LEVEL featureLevel = renderer11DeviceCaps.featureLevel;
1425     const gl::FormatSet &allFormats      = gl::GetAllSizedInternalFormats();
1426     for (GLenum internalFormat : allFormats)
1427     {
1428         gl::TextureCaps textureCaps =
1429             GenerateTextureFormatCaps(GetMaximumClientVersion(renderer11DeviceCaps), internalFormat,
1430                                       device, renderer11DeviceCaps);
1431         textureCapsMap->insert(internalFormat, textureCaps);
1432     }
1433 
1434     // GL core feature limits
1435     // Reserve MAX_UINT for D3D11's primitive restart.
1436     caps->maxElementIndex  = static_cast<GLint64>(std::numeric_limits<unsigned int>::max() - 1);
1437     caps->max3DTextureSize = GetMaximum3DTextureSize(featureLevel);
1438     caps->max2DTextureSize = GetMaximum2DTextureSize(featureLevel);
1439     caps->maxCubeMapTextureSize = GetMaximumCubeMapTextureSize(featureLevel);
1440     caps->maxArrayTextureLayers = GetMaximum2DTextureArraySize(featureLevel);
1441 
1442     // Unimplemented, set to minimum required
1443     caps->maxLODBias = 2.0f;
1444 
1445     // No specific limits on render target size, maximum 2D texture size is equivalent
1446     caps->maxRenderbufferSize = caps->max2DTextureSize;
1447 
1448     // Maximum draw buffers and color attachments are the same, max color attachments could
1449     // eventually be increased to 16
1450     caps->maxDrawBuffers      = GetMaximumSimultaneousRenderTargets(featureLevel);
1451     caps->maxColorAttachments = GetMaximumSimultaneousRenderTargets(featureLevel);
1452 
1453     // D3D11 has the same limit for viewport width and height
1454     caps->maxViewportWidth  = GetMaximumViewportSize(featureLevel);
1455     caps->maxViewportHeight = caps->maxViewportWidth;
1456 
1457     // Choose a reasonable maximum, enforced in the shader.
1458     caps->minAliasedPointSize = 1.0f;
1459     caps->maxAliasedPointSize = 1024.0f;
1460 
1461     // Wide lines not supported
1462     caps->minAliasedLineWidth = 1.0f;
1463     caps->maxAliasedLineWidth = 1.0f;
1464 
1465     // Primitive count limits
1466     caps->maxElementsIndices  = GetMaximumDrawIndexedIndexCount(featureLevel);
1467     caps->maxElementsVertices = GetMaximumDrawVertexCount(featureLevel);
1468 
1469     // Program and shader binary formats (no supported shader binary formats)
1470     caps->programBinaryFormats.push_back(GL_PROGRAM_BINARY_ANGLE);
1471 
1472     caps->vertexHighpFloat.setIEEEFloat();
1473     caps->vertexMediumpFloat.setIEEEFloat();
1474     caps->vertexLowpFloat.setIEEEFloat();
1475     caps->fragmentHighpFloat.setIEEEFloat();
1476     caps->fragmentMediumpFloat.setIEEEFloat();
1477     caps->fragmentLowpFloat.setIEEEFloat();
1478 
1479     // 32-bit integers are natively supported
1480     caps->vertexHighpInt.setTwosComplementInt(32);
1481     caps->vertexMediumpInt.setTwosComplementInt(32);
1482     caps->vertexLowpInt.setTwosComplementInt(32);
1483     caps->fragmentHighpInt.setTwosComplementInt(32);
1484     caps->fragmentMediumpInt.setTwosComplementInt(32);
1485     caps->fragmentLowpInt.setTwosComplementInt(32);
1486 
1487     // We do not wait for server fence objects internally, so report a max timeout of zero.
1488     caps->maxServerWaitTimeout = 0;
1489 
1490     // Vertex shader limits
1491     caps->maxVertexAttributes     = GetMaximumVertexInputSlots(featureLevel);
1492     caps->maxVertexUniformVectors = GetMaximumVertexUniformVectors(featureLevel);
1493     if (features.skipVSConstantRegisterZero.enabled)
1494     {
1495         caps->maxVertexUniformVectors -= 1;
1496     }
1497     caps->maxShaderUniformComponents[gl::ShaderType::Vertex] = caps->maxVertexUniformVectors * 4;
1498     caps->maxShaderUniformBlocks[gl::ShaderType::Vertex] =
1499         GetMaximumVertexUniformBlocks(featureLevel);
1500     caps->maxVertexOutputComponents = GetMaximumVertexOutputVectors(featureLevel) * 4;
1501     caps->maxShaderTextureImageUnits[gl::ShaderType::Vertex] =
1502         GetMaximumVertexTextureUnits(featureLevel);
1503 
1504     // Vertex Attribute Bindings are emulated on D3D11.
1505     caps->maxVertexAttribBindings = caps->maxVertexAttributes;
1506     // Experimental testing confirmed there is no explicit limit on maximum buffer offset in D3D11.
1507     caps->maxVertexAttribRelativeOffset = std::numeric_limits<GLint>::max();
1508     // Experimental testing confirmed 2048 is the maximum stride that D3D11 can support on all
1509     // platforms.
1510     caps->maxVertexAttribStride = 2048;
1511 
1512     // Fragment shader limits
1513     caps->maxFragmentUniformVectors = GetMaximumPixelUniformVectors(featureLevel);
1514     caps->maxShaderUniformComponents[gl::ShaderType::Fragment] =
1515         caps->maxFragmentUniformVectors * 4;
1516     caps->maxShaderUniformBlocks[gl::ShaderType::Fragment] =
1517         GetMaximumPixelUniformBlocks(featureLevel);
1518     caps->maxFragmentInputComponents = GetMaximumPixelInputVectors(featureLevel) * 4;
1519     caps->maxShaderTextureImageUnits[gl::ShaderType::Fragment] =
1520         GetMaximumPixelTextureUnits(featureLevel);
1521     caps->minProgramTexelOffset = GetMinimumTexelOffset(featureLevel);
1522     caps->maxProgramTexelOffset = GetMaximumTexelOffset(featureLevel);
1523 
1524     // Compute shader limits
1525     caps->maxComputeWorkGroupCount       = GetMaxComputeWorkGroupCount(featureLevel);
1526     caps->maxComputeWorkGroupSize        = GetMaxComputeWorkGroupSize(featureLevel);
1527     caps->maxComputeWorkGroupInvocations = GetMaxComputeWorkGroupInvocations(featureLevel);
1528     caps->maxComputeSharedMemorySize     = GetMaxComputeSharedMemorySize(featureLevel);
1529     caps->maxShaderUniformComponents[gl::ShaderType::Compute] =
1530         GetMaximumComputeUniformVectors(featureLevel) * 4;
1531     caps->maxShaderUniformBlocks[gl::ShaderType::Compute] =
1532         GetMaximumComputeUniformBlocks(featureLevel);
1533     caps->maxShaderTextureImageUnits[gl::ShaderType::Compute] =
1534         GetMaximumComputeTextureUnits(featureLevel);
1535 
1536     SetUAVRelatedResourceLimits(featureLevel, caps);
1537 
1538     // Aggregate shader limits
1539     caps->maxUniformBufferBindings = caps->maxShaderUniformBlocks[gl::ShaderType::Vertex] +
1540                                      caps->maxShaderUniformBlocks[gl::ShaderType::Fragment];
1541     caps->maxUniformBlockSize = static_cast<GLuint64>(GetMaximumConstantBufferSize(featureLevel));
1542 
1543     // TODO(oetuaho): Get a more accurate limit. For now using the minimum requirement for GLES 3.1.
1544     caps->maxUniformLocations = 1024;
1545 
1546     // With DirectX 11.1, constant buffer offset and size must be a multiple of 16 constants of 16
1547     // bytes each.
1548     // https://msdn.microsoft.com/en-us/library/windows/desktop/hh404649%28v=vs.85%29.aspx
1549     // With DirectX 11.0, we emulate UBO offsets using copies of ranges of the UBO however
1550     // we still keep the same alignment as 11.1 for consistency.
1551     caps->uniformBufferOffsetAlignment = 256;
1552 
1553     caps->maxCombinedUniformBlocks = caps->maxShaderUniformBlocks[gl::ShaderType::Vertex] +
1554                                      caps->maxShaderUniformBlocks[gl::ShaderType::Fragment];
1555 
1556     // A shader storage block will be translated to a structure in HLSL. So We reference the HLSL
1557     // structure packing rules
1558     // https://msdn.microsoft.com/en-us/library/windows/desktop/bb509632(v=vs.85).aspx. The
1559     // resulting size of any structure will always be evenly divisible by sizeof(four-component
1560     // vector).
1561     caps->shaderStorageBufferOffsetAlignment = 16;
1562 
1563     for (gl::ShaderType shaderType : gl::AllShaderTypes())
1564     {
1565         caps->maxCombinedShaderUniformComponents[shaderType] =
1566             static_cast<GLint64>(caps->maxShaderUniformBlocks[shaderType]) *
1567                 static_cast<GLint64>(caps->maxUniformBlockSize / 4) +
1568             static_cast<GLint64>(caps->maxShaderUniformComponents[shaderType]);
1569     }
1570 
1571     caps->maxVaryingComponents         = GetMaximumVertexOutputVectors(featureLevel) * 4;
1572     caps->maxVaryingVectors            = GetMaximumVertexOutputVectors(featureLevel);
1573     caps->maxCombinedTextureImageUnits = caps->maxShaderTextureImageUnits[gl::ShaderType::Vertex] +
1574                                          caps->maxShaderTextureImageUnits[gl::ShaderType::Fragment];
1575 
1576     // Transform feedback limits
1577     caps->maxTransformFeedbackInterleavedComponents =
1578         GetMaximumStreamOutputInterleavedComponents(featureLevel);
1579     caps->maxTransformFeedbackSeparateAttributes = GetMaximumStreamOutputBuffers(featureLevel);
1580     caps->maxTransformFeedbackSeparateComponents =
1581         GetMaximumStreamOutputSeparateComponents(featureLevel);
1582 
1583     // Defer the computation of multisample limits to Context::updateCaps() where max*Samples values
1584     // are determined according to available sample counts for each individual format.
1585     caps->maxSamples             = std::numeric_limits<GLint>::max();
1586     caps->maxColorTextureSamples = std::numeric_limits<GLint>::max();
1587     caps->maxDepthTextureSamples = std::numeric_limits<GLint>::max();
1588     caps->maxIntegerSamples      = std::numeric_limits<GLint>::max();
1589 
1590     // Sample mask words limits
1591     caps->maxSampleMaskWords = GetMaxSampleMaskWords(featureLevel);
1592 
1593     // Framebuffer limits
1594     caps->maxFramebufferSamples = std::numeric_limits<GLint>::max();
1595     caps->maxFramebufferWidth   = GetMaximumRenderToBufferWindowSize(featureLevel);
1596     caps->maxFramebufferHeight  = caps->maxFramebufferWidth;
1597 
1598     // Texture gather offset limits
1599     caps->minProgramTextureGatherOffset = GetMinimumTextureGatherOffset(featureLevel);
1600     caps->maxProgramTextureGatherOffset = GetMaximumTextureGatherOffset(featureLevel);
1601 
1602     caps->maxTextureAnisotropy        = GetMaximumAnisotropy(featureLevel);
1603     caps->queryCounterBitsTimeElapsed = 64;
1604 
1605     caps->queryCounterBitsTimestamp = features.enableTimestampQueries.enabled ? 64 : 0;
1606 
1607     caps->maxDualSourceDrawBuffers = 1;
1608 
1609     // GL extension support
1610     extensions->setTextureExtensionSupport(*textureCapsMap);
1611 
1612     // Explicitly disable GL_OES_compressed_ETC1_RGB8_texture because it's emulated and never
1613     // becomes core. WebGL doesn't want to expose it unless there is native support.
1614     extensions->compressedETC1RGB8TextureOES    = false;
1615     extensions->compressedETC1RGB8SubTextureEXT = false;
1616 
1617     extensions->elementIndexUintOES         = true;
1618     extensions->getProgramBinaryOES         = true;
1619     extensions->rgb8Rgba8OES                = true;
1620     extensions->readFormatBgraEXT           = true;
1621     extensions->pixelBufferObjectNV         = true;
1622     extensions->mapbufferOES                = true;
1623     extensions->mapBufferRangeEXT           = true;
1624     extensions->textureNpotOES              = GetNPOTTextureSupport(featureLevel);
1625     extensions->drawBuffersEXT              = GetMaximumSimultaneousRenderTargets(featureLevel) > 1;
1626     extensions->drawBuffersIndexedEXT       = (featureLevel >= D3D_FEATURE_LEVEL_10_1);
1627     extensions->drawBuffersIndexedOES       = extensions->drawBuffersIndexedEXT;
1628     extensions->textureStorageEXT           = true;
1629     extensions->textureFilterAnisotropicEXT = true;
1630     extensions->occlusionQueryBooleanEXT    = GetOcclusionQuerySupport(featureLevel);
1631     extensions->fenceNV                     = GetEventQuerySupport(featureLevel);
1632     extensions->disjointTimerQueryEXT       = true;
1633     extensions->robustnessEXT               = true;
1634     // Direct3D guarantees to return zero for any resource that is accessed out of bounds.
1635     // See https://msdn.microsoft.com/en-us/library/windows/desktop/ff476332(v=vs.85).aspx
1636     // and https://msdn.microsoft.com/en-us/library/windows/desktop/ff476900(v=vs.85).aspx
1637     extensions->robustBufferAccessBehaviorKHR = true;
1638     extensions->blendMinmaxEXT                = true;
1639     // https://docs.microsoft.com/en-us/windows/desktop/direct3ddxgi/format-support-for-direct3d-11-0-feature-level-hardware
1640     extensions->floatBlendEXT               = true;
1641     extensions->framebufferBlitANGLE        = GetFramebufferBlitSupport(featureLevel);
1642     extensions->framebufferBlitNV           = extensions->framebufferBlitANGLE;
1643     extensions->framebufferMultisampleANGLE = GetFramebufferMultisampleSupport(featureLevel);
1644     extensions->instancedArraysANGLE        = GetInstancingSupport(featureLevel);
1645     extensions->instancedArraysEXT          = GetInstancingSupport(featureLevel);
1646     extensions->packReverseRowOrderANGLE    = true;
1647     extensions->standardDerivativesOES      = GetDerivativeInstructionSupport(featureLevel);
1648     extensions->shaderTextureLodEXT         = GetShaderTextureLODSupport(featureLevel);
1649     extensions->fragDepthEXT                = true;
1650     extensions->conservativeDepthEXT        = (featureLevel >= D3D_FEATURE_LEVEL_11_0);
1651     extensions->polygonModeANGLE            = true;
1652     extensions->polygonOffsetClampEXT       = (featureLevel >= D3D_FEATURE_LEVEL_10_0);
1653     extensions->depthClampEXT               = true;
1654     extensions->stencilTexturingANGLE       = (featureLevel >= D3D_FEATURE_LEVEL_10_1);
1655     extensions->multiviewOVR                = IsMultiviewSupported(featureLevel);
1656     extensions->multiview2OVR               = IsMultiviewSupported(featureLevel);
1657     if (extensions->multiviewOVR || extensions->multiview2OVR)
1658     {
1659         caps->maxViews = std::min(static_cast<GLuint>(GetMaximum2DTextureArraySize(featureLevel)),
1660                                   GetMaxViewportAndScissorRectanglesPerPipeline(featureLevel));
1661     }
1662     extensions->textureUsageANGLE = true;  // This could be false since it has no effect in D3D11
1663     extensions->discardFramebufferEXT               = true;
1664     extensions->translatedShaderSourceANGLE         = true;
1665     extensions->fboRenderMipmapOES                  = true;
1666     extensions->debugMarkerEXT                      = true;
1667     extensions->EGLImageOES                         = true;
1668     extensions->EGLImageExternalOES                 = true;
1669     extensions->EGLImageExternalWrapModesEXT        = true;
1670     extensions->EGLImageExternalEssl3OES            = true;
1671     extensions->EGLStreamConsumerExternalNV         = true;
1672     extensions->unpackSubimageEXT                   = true;
1673     extensions->packSubimageNV                      = true;
1674     extensions->lossyEtcDecodeANGLE                 = true;
1675     extensions->syncQueryCHROMIUM                   = GetEventQuerySupport(featureLevel);
1676     extensions->copyTextureCHROMIUM                 = true;
1677     extensions->copyCompressedTextureCHROMIUM       = true;
1678     extensions->textureStorageMultisample2dArrayOES = true;
1679     extensions->textureMirrorClampToEdgeEXT         = true;
1680     extensions->shaderNoperspectiveInterpolationNV  = (featureLevel >= D3D_FEATURE_LEVEL_10_0);
1681     extensions->sampleVariablesOES                  = (featureLevel >= D3D_FEATURE_LEVEL_11_0);
1682     extensions->shaderMultisampleInterpolationOES   = (featureLevel >= D3D_FEATURE_LEVEL_11_0);
1683     if (extensions->shaderMultisampleInterpolationOES)
1684     {
1685         caps->subPixelInterpolationOffsetBits = 4;
1686         caps->minInterpolationOffset          = -0.5f;
1687         caps->maxInterpolationOffset          = +0.4375f;  // +0.5 - (2 ^ -4)
1688     }
1689     extensions->multiviewMultisampleANGLE =
1690         ((extensions->multiviewOVR || extensions->multiview2OVR) &&
1691          extensions->textureStorageMultisample2dArrayOES);
1692     extensions->copyTexture3dANGLE      = true;
1693     extensions->textureBorderClampEXT   = true;
1694     extensions->textureBorderClampOES   = true;
1695     extensions->multiDrawIndirectEXT    = true;
1696     extensions->textureMultisampleANGLE = true;
1697     extensions->provokingVertexANGLE    = true;
1698     extensions->blendFuncExtendedEXT    = true;
1699     // http://anglebug.com/4926
1700     extensions->texture3DOES                             = false;
1701     extensions->baseInstanceEXT                          = true;
1702     extensions->baseVertexBaseInstanceANGLE              = true;
1703     extensions->baseVertexBaseInstanceShaderBuiltinANGLE = true;
1704     extensions->drawElementsBaseVertexOES                = true;
1705     extensions->drawElementsBaseVertexEXT                = true;
1706     if (!strstr(description, "Adreno"))
1707     {
1708         extensions->multisampledRenderToTextureEXT = true;
1709     }
1710     extensions->videoTextureWEBGL = true;
1711 
1712     // D3D11 cannot support reading depth texture as a luminance texture.
1713     // It treats it as a red-channel-only texture.
1714     extensions->depthTextureOES = false;
1715 
1716     // readPixels on depth & stencil not working with D3D11 backend.
1717     extensions->readDepthNV         = false;
1718     extensions->readStencilNV       = false;
1719     extensions->depthBufferFloat2NV = false;
1720 
1721     // GL_EXT_clip_control
1722     extensions->clipControlEXT = (featureLevel >= D3D_FEATURE_LEVEL_9_3);
1723 
1724     // GL_APPLE_clip_distance / GL_EXT_clip_cull_distance / GL_ANGLE_clip_cull_distance
1725     extensions->clipDistanceAPPLE         = true;
1726     extensions->clipCullDistanceEXT       = true;
1727     extensions->clipCullDistanceANGLE     = true;
1728     caps->maxClipDistances                = D3D11_CLIP_OR_CULL_DISTANCE_COUNT;
1729     caps->maxCullDistances                = D3D11_CLIP_OR_CULL_DISTANCE_COUNT;
1730     caps->maxCombinedClipAndCullDistances = D3D11_CLIP_OR_CULL_DISTANCE_COUNT;
1731 
1732     // GL_KHR_parallel_shader_compile
1733     extensions->parallelShaderCompileKHR = true;
1734 
1735     // GL_EXT_texture_buffer
1736     extensions->textureBufferEXT = HasTextureBufferSupport(device, renderer11DeviceCaps);
1737 
1738     // GL_OES_texture_buffer
1739     extensions->textureBufferOES = extensions->textureBufferEXT;
1740 
1741     // ANGLE_shader_pixel_local_storage -- fragment shader UAVs appear in D3D 11.0.
1742     if (featureLevel >= D3D_FEATURE_LEVEL_11_0)
1743     {
1744         extensions->shaderPixelLocalStorageANGLE = true;
1745         plsOptions->type                         = ShPixelLocalStorageType::ImageLoadStore;
1746         if (renderer11DeviceCaps.supportsRasterizerOrderViews)
1747         {
1748             extensions->shaderPixelLocalStorageCoherentANGLE = true;
1749             plsOptions->fragmentSyncType = ShFragmentSynchronizationType::RasterizerOrderViews_D3D;
1750         }
1751         // TODO(anglebug.com/7279): If we add RG* support to pixel local storage, these are *NOT*
1752         // in the set of common formats, so we need to query support for each individualy:
1753         // https://learn.microsoft.com/en-us/windows/win32/direct3d11/typed-unordered-access-view-loads
1754         plsOptions->supportsNativeRGBA8ImageFormats =
1755             renderer11DeviceCaps.supportsUAVLoadStoreCommonFormats;
1756     }
1757 
1758     // D3D11 Feature Level 10_0+ uses SV_IsFrontFace in HLSL to emulate gl_FrontFacing.
1759     // D3D11 Feature Level 9_3 doesn't support SV_IsFrontFace, and has no equivalent, so can't
1760     // support gl_FrontFacing.
1761     limitations->noFrontFacingSupport = (featureLevel <= D3D_FEATURE_LEVEL_9_3);
1762 
1763     // D3D11 Feature Level 9_3 doesn't support alpha-to-coverage
1764     limitations->noSampleAlphaToCoverageSupport = (featureLevel <= D3D_FEATURE_LEVEL_9_3);
1765 
1766     // D3D11 Feature Levels 9_3 and below do not support non-constant loop indexing and require
1767     // additional
1768     // pre-validation of the shader at compile time to produce a better error message.
1769     limitations->shadersRequireIndexedLoopValidation = (featureLevel <= D3D_FEATURE_LEVEL_9_3);
1770 
1771     // D3D11 has no concept of separate masks and refs for front and back faces in the depth stencil
1772     // state.
1773     limitations->noSeparateStencilRefsAndMasks = true;
1774 
1775     // D3D11 cannot support constant color and alpha blend funcs together
1776     limitations->noSimultaneousConstantColorAndAlphaBlendFunc = true;
1777 
1778     // D3D11 does not support multiple transform feedback outputs writing to the same buffer.
1779     limitations->noDoubleBoundTransformFeedbackBuffers = true;
1780 
1781     // D3D11 does not support vertex attribute aliasing
1782     limitations->noVertexAttributeAliasing = true;
1783 
1784     // D3D11 does not support compressed textures where the base mip level is not a multiple of 4
1785     limitations->compressedBaseMipLevelMultipleOfFour = true;
1786 
1787     if (extensions->textureBufferAny())
1788     {
1789         caps->maxTextureBufferSize = 1 << D3D11_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP;
1790         // this maybe touble for RGB32 format.
1791         caps->textureBufferOffsetAlignment = 16;
1792     }
1793 
1794 #ifdef ANGLE_ENABLE_WINDOWS_UWP
1795     // Setting a non-zero divisor on attribute zero doesn't work on certain Windows Phone 8-era
1796     // devices. We should prevent developers from doing this on ALL Windows Store devices. This will
1797     // maintain consistency across all Windows devices. We allow non-zero divisors on attribute zero
1798     // if the Client Version >= 3, since devices affected by this issue don't support ES3+.
1799     limitations->attributeZeroRequiresZeroDivisorInEXT = true;
1800 #endif
1801 }
1802 
1803 }  // namespace d3d11_gl
1804 
1805 namespace gl_d3d11
1806 {
1807 
ConvertBlendFunc(GLenum glBlend,bool isAlpha)1808 D3D11_BLEND ConvertBlendFunc(GLenum glBlend, bool isAlpha)
1809 {
1810     D3D11_BLEND d3dBlend = D3D11_BLEND_ZERO;
1811 
1812     switch (glBlend)
1813     {
1814         case GL_ZERO:
1815             d3dBlend = D3D11_BLEND_ZERO;
1816             break;
1817         case GL_ONE:
1818             d3dBlend = D3D11_BLEND_ONE;
1819             break;
1820         case GL_SRC_COLOR:
1821             d3dBlend = (isAlpha ? D3D11_BLEND_SRC_ALPHA : D3D11_BLEND_SRC_COLOR);
1822             break;
1823         case GL_ONE_MINUS_SRC_COLOR:
1824             d3dBlend = (isAlpha ? D3D11_BLEND_INV_SRC_ALPHA : D3D11_BLEND_INV_SRC_COLOR);
1825             break;
1826         case GL_DST_COLOR:
1827             d3dBlend = (isAlpha ? D3D11_BLEND_DEST_ALPHA : D3D11_BLEND_DEST_COLOR);
1828             break;
1829         case GL_ONE_MINUS_DST_COLOR:
1830             d3dBlend = (isAlpha ? D3D11_BLEND_INV_DEST_ALPHA : D3D11_BLEND_INV_DEST_COLOR);
1831             break;
1832         case GL_SRC_ALPHA:
1833             d3dBlend = D3D11_BLEND_SRC_ALPHA;
1834             break;
1835         case GL_ONE_MINUS_SRC_ALPHA:
1836             d3dBlend = D3D11_BLEND_INV_SRC_ALPHA;
1837             break;
1838         case GL_DST_ALPHA:
1839             d3dBlend = D3D11_BLEND_DEST_ALPHA;
1840             break;
1841         case GL_ONE_MINUS_DST_ALPHA:
1842             d3dBlend = D3D11_BLEND_INV_DEST_ALPHA;
1843             break;
1844         case GL_CONSTANT_COLOR:
1845             d3dBlend = D3D11_BLEND_BLEND_FACTOR;
1846             break;
1847         case GL_ONE_MINUS_CONSTANT_COLOR:
1848             d3dBlend = D3D11_BLEND_INV_BLEND_FACTOR;
1849             break;
1850         case GL_CONSTANT_ALPHA:
1851             d3dBlend = D3D11_BLEND_BLEND_FACTOR;
1852             break;
1853         case GL_ONE_MINUS_CONSTANT_ALPHA:
1854             d3dBlend = D3D11_BLEND_INV_BLEND_FACTOR;
1855             break;
1856         case GL_SRC_ALPHA_SATURATE:
1857             d3dBlend = D3D11_BLEND_SRC_ALPHA_SAT;
1858             break;
1859         case GL_SRC1_COLOR_EXT:
1860             d3dBlend = (isAlpha ? D3D11_BLEND_SRC1_ALPHA : D3D11_BLEND_SRC1_COLOR);
1861             break;
1862         case GL_SRC1_ALPHA_EXT:
1863             d3dBlend = D3D11_BLEND_SRC1_ALPHA;
1864             break;
1865         case GL_ONE_MINUS_SRC1_COLOR_EXT:
1866             d3dBlend = (isAlpha ? D3D11_BLEND_INV_SRC1_ALPHA : D3D11_BLEND_INV_SRC1_COLOR);
1867             break;
1868         case GL_ONE_MINUS_SRC1_ALPHA_EXT:
1869             d3dBlend = D3D11_BLEND_INV_SRC1_ALPHA;
1870             break;
1871         default:
1872             UNREACHABLE();
1873     }
1874 
1875     return d3dBlend;
1876 }
1877 
ConvertBlendOp(GLenum glBlendOp)1878 D3D11_BLEND_OP ConvertBlendOp(GLenum glBlendOp)
1879 {
1880     D3D11_BLEND_OP d3dBlendOp = D3D11_BLEND_OP_ADD;
1881 
1882     switch (glBlendOp)
1883     {
1884         case GL_FUNC_ADD:
1885             d3dBlendOp = D3D11_BLEND_OP_ADD;
1886             break;
1887         case GL_FUNC_SUBTRACT:
1888             d3dBlendOp = D3D11_BLEND_OP_SUBTRACT;
1889             break;
1890         case GL_FUNC_REVERSE_SUBTRACT:
1891             d3dBlendOp = D3D11_BLEND_OP_REV_SUBTRACT;
1892             break;
1893         case GL_MIN:
1894             d3dBlendOp = D3D11_BLEND_OP_MIN;
1895             break;
1896         case GL_MAX:
1897             d3dBlendOp = D3D11_BLEND_OP_MAX;
1898             break;
1899         default:
1900             UNREACHABLE();
1901     }
1902 
1903     return d3dBlendOp;
1904 }
1905 
ConvertColorMask(bool red,bool green,bool blue,bool alpha)1906 UINT8 ConvertColorMask(bool red, bool green, bool blue, bool alpha)
1907 {
1908     UINT8 mask = 0;
1909     if (red)
1910     {
1911         mask |= D3D11_COLOR_WRITE_ENABLE_RED;
1912     }
1913     if (green)
1914     {
1915         mask |= D3D11_COLOR_WRITE_ENABLE_GREEN;
1916     }
1917     if (blue)
1918     {
1919         mask |= D3D11_COLOR_WRITE_ENABLE_BLUE;
1920     }
1921     if (alpha)
1922     {
1923         mask |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
1924     }
1925     return mask;
1926 }
1927 
ConvertCullMode(bool cullEnabled,gl::CullFaceMode cullMode)1928 D3D11_CULL_MODE ConvertCullMode(bool cullEnabled, gl::CullFaceMode cullMode)
1929 {
1930     D3D11_CULL_MODE cull = D3D11_CULL_NONE;
1931 
1932     if (cullEnabled)
1933     {
1934         switch (cullMode)
1935         {
1936             case gl::CullFaceMode::Front:
1937                 cull = D3D11_CULL_FRONT;
1938                 break;
1939             case gl::CullFaceMode::Back:
1940                 cull = D3D11_CULL_BACK;
1941                 break;
1942             case gl::CullFaceMode::FrontAndBack:
1943                 cull = D3D11_CULL_NONE;
1944                 break;
1945             default:
1946                 UNREACHABLE();
1947         }
1948     }
1949     else
1950     {
1951         cull = D3D11_CULL_NONE;
1952     }
1953 
1954     return cull;
1955 }
1956 
ConvertComparison(GLenum comparison)1957 D3D11_COMPARISON_FUNC ConvertComparison(GLenum comparison)
1958 {
1959     D3D11_COMPARISON_FUNC d3dComp = D3D11_COMPARISON_NEVER;
1960     switch (comparison)
1961     {
1962         case GL_NEVER:
1963             d3dComp = D3D11_COMPARISON_NEVER;
1964             break;
1965         case GL_ALWAYS:
1966             d3dComp = D3D11_COMPARISON_ALWAYS;
1967             break;
1968         case GL_LESS:
1969             d3dComp = D3D11_COMPARISON_LESS;
1970             break;
1971         case GL_LEQUAL:
1972             d3dComp = D3D11_COMPARISON_LESS_EQUAL;
1973             break;
1974         case GL_EQUAL:
1975             d3dComp = D3D11_COMPARISON_EQUAL;
1976             break;
1977         case GL_GREATER:
1978             d3dComp = D3D11_COMPARISON_GREATER;
1979             break;
1980         case GL_GEQUAL:
1981             d3dComp = D3D11_COMPARISON_GREATER_EQUAL;
1982             break;
1983         case GL_NOTEQUAL:
1984             d3dComp = D3D11_COMPARISON_NOT_EQUAL;
1985             break;
1986         default:
1987             UNREACHABLE();
1988     }
1989 
1990     return d3dComp;
1991 }
1992 
ConvertDepthMask(bool depthWriteEnabled)1993 D3D11_DEPTH_WRITE_MASK ConvertDepthMask(bool depthWriteEnabled)
1994 {
1995     return depthWriteEnabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
1996 }
1997 
ConvertStencilMask(GLuint stencilmask)1998 UINT8 ConvertStencilMask(GLuint stencilmask)
1999 {
2000     return static_cast<UINT8>(stencilmask);
2001 }
2002 
ConvertStencilOp(GLenum stencilOp)2003 D3D11_STENCIL_OP ConvertStencilOp(GLenum stencilOp)
2004 {
2005     D3D11_STENCIL_OP d3dStencilOp = D3D11_STENCIL_OP_KEEP;
2006 
2007     switch (stencilOp)
2008     {
2009         case GL_ZERO:
2010             d3dStencilOp = D3D11_STENCIL_OP_ZERO;
2011             break;
2012         case GL_KEEP:
2013             d3dStencilOp = D3D11_STENCIL_OP_KEEP;
2014             break;
2015         case GL_REPLACE:
2016             d3dStencilOp = D3D11_STENCIL_OP_REPLACE;
2017             break;
2018         case GL_INCR:
2019             d3dStencilOp = D3D11_STENCIL_OP_INCR_SAT;
2020             break;
2021         case GL_DECR:
2022             d3dStencilOp = D3D11_STENCIL_OP_DECR_SAT;
2023             break;
2024         case GL_INVERT:
2025             d3dStencilOp = D3D11_STENCIL_OP_INVERT;
2026             break;
2027         case GL_INCR_WRAP:
2028             d3dStencilOp = D3D11_STENCIL_OP_INCR;
2029             break;
2030         case GL_DECR_WRAP:
2031             d3dStencilOp = D3D11_STENCIL_OP_DECR;
2032             break;
2033         default:
2034             UNREACHABLE();
2035     }
2036 
2037     return d3dStencilOp;
2038 }
2039 
ConvertFilter(GLenum minFilter,GLenum magFilter,float maxAnisotropy,GLenum comparisonMode)2040 D3D11_FILTER ConvertFilter(GLenum minFilter,
2041                            GLenum magFilter,
2042                            float maxAnisotropy,
2043                            GLenum comparisonMode)
2044 {
2045     bool comparison = comparisonMode != GL_NONE;
2046 
2047     if (maxAnisotropy > 1.0f)
2048     {
2049         return D3D11_ENCODE_ANISOTROPIC_FILTER(static_cast<D3D11_COMPARISON_FUNC>(comparison));
2050     }
2051     else
2052     {
2053         D3D11_FILTER_TYPE dxMin = D3D11_FILTER_TYPE_POINT;
2054         D3D11_FILTER_TYPE dxMip = D3D11_FILTER_TYPE_POINT;
2055         switch (minFilter)
2056         {
2057             case GL_NEAREST:
2058                 dxMin = D3D11_FILTER_TYPE_POINT;
2059                 dxMip = D3D11_FILTER_TYPE_POINT;
2060                 break;
2061             case GL_LINEAR:
2062                 dxMin = D3D11_FILTER_TYPE_LINEAR;
2063                 dxMip = D3D11_FILTER_TYPE_POINT;
2064                 break;
2065             case GL_NEAREST_MIPMAP_NEAREST:
2066                 dxMin = D3D11_FILTER_TYPE_POINT;
2067                 dxMip = D3D11_FILTER_TYPE_POINT;
2068                 break;
2069             case GL_LINEAR_MIPMAP_NEAREST:
2070                 dxMin = D3D11_FILTER_TYPE_LINEAR;
2071                 dxMip = D3D11_FILTER_TYPE_POINT;
2072                 break;
2073             case GL_NEAREST_MIPMAP_LINEAR:
2074                 dxMin = D3D11_FILTER_TYPE_POINT;
2075                 dxMip = D3D11_FILTER_TYPE_LINEAR;
2076                 break;
2077             case GL_LINEAR_MIPMAP_LINEAR:
2078                 dxMin = D3D11_FILTER_TYPE_LINEAR;
2079                 dxMip = D3D11_FILTER_TYPE_LINEAR;
2080                 break;
2081             default:
2082                 UNREACHABLE();
2083         }
2084 
2085         D3D11_FILTER_TYPE dxMag = D3D11_FILTER_TYPE_POINT;
2086         switch (magFilter)
2087         {
2088             case GL_NEAREST:
2089                 dxMag = D3D11_FILTER_TYPE_POINT;
2090                 break;
2091             case GL_LINEAR:
2092                 dxMag = D3D11_FILTER_TYPE_LINEAR;
2093                 break;
2094             default:
2095                 UNREACHABLE();
2096         }
2097 
2098         return D3D11_ENCODE_BASIC_FILTER(dxMin, dxMag, dxMip,
2099                                          static_cast<D3D11_COMPARISON_FUNC>(comparison));
2100     }
2101 }
2102 
ConvertTextureWrap(GLenum wrap)2103 D3D11_TEXTURE_ADDRESS_MODE ConvertTextureWrap(GLenum wrap)
2104 {
2105     switch (wrap)
2106     {
2107         case GL_REPEAT:
2108             return D3D11_TEXTURE_ADDRESS_WRAP;
2109         case GL_MIRRORED_REPEAT:
2110             return D3D11_TEXTURE_ADDRESS_MIRROR;
2111         case GL_CLAMP_TO_EDGE:
2112             return D3D11_TEXTURE_ADDRESS_CLAMP;
2113         case GL_CLAMP_TO_BORDER:
2114             return D3D11_TEXTURE_ADDRESS_BORDER;
2115         case GL_MIRROR_CLAMP_TO_EDGE_EXT:
2116             return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE;
2117         default:
2118             UNREACHABLE();
2119     }
2120 
2121     return D3D11_TEXTURE_ADDRESS_WRAP;
2122 }
2123 
ConvertMaxAnisotropy(float maxAnisotropy,D3D_FEATURE_LEVEL featureLevel)2124 UINT ConvertMaxAnisotropy(float maxAnisotropy, D3D_FEATURE_LEVEL featureLevel)
2125 {
2126     return static_cast<UINT>(std::min(maxAnisotropy, d3d11_gl::GetMaximumAnisotropy(featureLevel)));
2127 }
2128 
ConvertQueryType(gl::QueryType type)2129 D3D11_QUERY ConvertQueryType(gl::QueryType type)
2130 {
2131     switch (type)
2132     {
2133         case gl::QueryType::AnySamples:
2134         case gl::QueryType::AnySamplesConservative:
2135             return D3D11_QUERY_OCCLUSION;
2136         case gl::QueryType::TransformFeedbackPrimitivesWritten:
2137             return D3D11_QUERY_SO_STATISTICS;
2138         case gl::QueryType::TimeElapsed:
2139             // Two internal queries are also created for begin/end timestamps
2140             return D3D11_QUERY_TIMESTAMP_DISJOINT;
2141         case gl::QueryType::Timestamp:
2142             // A disjoint query is also created for timestamp
2143             return D3D11_QUERY_TIMESTAMP_DISJOINT;
2144         case gl::QueryType::CommandsCompleted:
2145             return D3D11_QUERY_EVENT;
2146         default:
2147             UNREACHABLE();
2148             return D3D11_QUERY_EVENT;
2149     }
2150 }
2151 
2152 // Get the D3D11 write mask covering all color channels of a given format
GetColorMask(const gl::InternalFormat & format)2153 UINT8 GetColorMask(const gl::InternalFormat &format)
2154 {
2155     return ConvertColorMask(format.redBits > 0, format.greenBits > 0, format.blueBits > 0,
2156                             format.alphaBits > 0);
2157 }
2158 
2159 }  // namespace gl_d3d11
2160 
2161 namespace d3d11
2162 {
2163 
GetDeviceType(ID3D11Device * device)2164 ANGLED3D11DeviceType GetDeviceType(ID3D11Device *device)
2165 {
2166     // Note that this function returns an ANGLED3D11DeviceType rather than a D3D_DRIVER_TYPE value,
2167     // since it is difficult to tell Software and Reference devices apart
2168 
2169     IDXGIDevice *dxgiDevice     = nullptr;
2170     IDXGIAdapter *dxgiAdapter   = nullptr;
2171     IDXGIAdapter2 *dxgiAdapter2 = nullptr;
2172 
2173     ANGLED3D11DeviceType retDeviceType = ANGLE_D3D11_DEVICE_TYPE_UNKNOWN;
2174 
2175     HRESULT hr = device->QueryInterface(__uuidof(IDXGIDevice), (void **)&dxgiDevice);
2176     if (SUCCEEDED(hr))
2177     {
2178         hr = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&dxgiAdapter);
2179         if (SUCCEEDED(hr))
2180         {
2181             std::wstring adapterString;
2182             HRESULT adapter2hr =
2183                 dxgiAdapter->QueryInterface(__uuidof(dxgiAdapter2), (void **)&dxgiAdapter2);
2184             if (SUCCEEDED(adapter2hr))
2185             {
2186                 // On D3D_FEATURE_LEVEL_9_*, IDXGIAdapter::GetDesc returns "Software Adapter"
2187                 // for the description string. Try to use IDXGIAdapter2::GetDesc2 to get the
2188                 // actual hardware values if possible.
2189                 DXGI_ADAPTER_DESC2 adapterDesc2;
2190                 dxgiAdapter2->GetDesc2(&adapterDesc2);
2191                 adapterString = std::wstring(adapterDesc2.Description);
2192             }
2193             else
2194             {
2195                 DXGI_ADAPTER_DESC adapterDesc;
2196                 dxgiAdapter->GetDesc(&adapterDesc);
2197                 adapterString = std::wstring(adapterDesc.Description);
2198             }
2199 
2200             // Both Reference and Software adapters will be 'Software Adapter'
2201             const bool isSoftwareDevice =
2202                 (adapterString.find(std::wstring(L"Software Adapter")) != std::string::npos);
2203             const bool isNullDevice = (adapterString == L"");
2204             const bool isWARPDevice =
2205                 (adapterString.find(std::wstring(L"Basic Render")) != std::string::npos);
2206 
2207             if (isSoftwareDevice || isNullDevice)
2208             {
2209                 ASSERT(!isWARPDevice);
2210                 retDeviceType = ANGLE_D3D11_DEVICE_TYPE_SOFTWARE_REF_OR_NULL;
2211             }
2212             else if (isWARPDevice)
2213             {
2214                 retDeviceType = ANGLE_D3D11_DEVICE_TYPE_WARP;
2215             }
2216             else
2217             {
2218                 retDeviceType = ANGLE_D3D11_DEVICE_TYPE_HARDWARE;
2219             }
2220         }
2221     }
2222 
2223     SafeRelease(dxgiDevice);
2224     SafeRelease(dxgiAdapter);
2225     SafeRelease(dxgiAdapter2);
2226 
2227     return retDeviceType;
2228 }
2229 
MakeValidSize(bool isImage,DXGI_FORMAT format,GLsizei * requestWidth,GLsizei * requestHeight,int * levelOffset)2230 void MakeValidSize(bool isImage,
2231                    DXGI_FORMAT format,
2232                    GLsizei *requestWidth,
2233                    GLsizei *requestHeight,
2234                    int *levelOffset)
2235 {
2236     const DXGIFormatSize &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(format);
2237     bool validFormat                     = format != DXGI_FORMAT_UNKNOWN;
2238     bool validImage                      = isImage && validFormat;
2239 
2240     int upsampleCount = 0;
2241     // Don't expand the size of full textures that are at least (blockWidth x blockHeight) already.
2242     if (validImage || *requestWidth < static_cast<GLsizei>(dxgiFormatInfo.blockWidth) ||
2243         *requestHeight < static_cast<GLsizei>(dxgiFormatInfo.blockHeight))
2244     {
2245         while (*requestWidth % dxgiFormatInfo.blockWidth != 0 ||
2246                *requestHeight % dxgiFormatInfo.blockHeight != 0)
2247         {
2248             *requestWidth <<= 1;
2249             *requestHeight <<= 1;
2250             upsampleCount++;
2251         }
2252     }
2253     else if (validFormat)
2254     {
2255         if (*requestWidth % dxgiFormatInfo.blockWidth != 0)
2256         {
2257             *requestWidth = roundUp(*requestWidth, static_cast<GLsizei>(dxgiFormatInfo.blockWidth));
2258         }
2259 
2260         if (*requestHeight % dxgiFormatInfo.blockHeight != 0)
2261         {
2262             *requestHeight =
2263                 roundUp(*requestHeight, static_cast<GLsizei>(dxgiFormatInfo.blockHeight));
2264         }
2265     }
2266 
2267     if (levelOffset)
2268     {
2269         *levelOffset = upsampleCount;
2270     }
2271 }
2272 
GenerateInitialTextureData(const gl::Context * context,GLint internalFormat,const Renderer11DeviceCaps & renderer11DeviceCaps,GLuint width,GLuint height,GLuint depth,GLuint mipLevels,gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> * outSubresourceData)2273 angle::Result GenerateInitialTextureData(
2274     const gl::Context *context,
2275     GLint internalFormat,
2276     const Renderer11DeviceCaps &renderer11DeviceCaps,
2277     GLuint width,
2278     GLuint height,
2279     GLuint depth,
2280     GLuint mipLevels,
2281     gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> *outSubresourceData)
2282 {
2283     const d3d11::Format &d3dFormatInfo = d3d11::Format::Get(internalFormat, renderer11DeviceCaps);
2284     ASSERT(d3dFormatInfo.dataInitializerFunction != nullptr);
2285 
2286     const d3d11::DXGIFormatSize &dxgiFormatInfo =
2287         d3d11::GetDXGIFormatSizeInfo(d3dFormatInfo.texFormat);
2288 
2289     using CheckedSize        = angle::CheckedNumeric<size_t>;
2290     CheckedSize rowPitch     = CheckedSize(dxgiFormatInfo.pixelBytes) * CheckedSize(width);
2291     CheckedSize depthPitch   = rowPitch * CheckedSize(height);
2292     CheckedSize maxImageSize = depthPitch * CheckedSize(depth);
2293 
2294     Context11 *context11 = GetImplAs<Context11>(context);
2295     ANGLE_CHECK_GL_ALLOC(context11, maxImageSize.IsValid());
2296 
2297     angle::MemoryBuffer *scratchBuffer = nullptr;
2298     ANGLE_CHECK_GL_ALLOC(context11,
2299                          context->getScratchBuffer(maxImageSize.ValueOrDie(), &scratchBuffer));
2300 
2301     d3dFormatInfo.dataInitializerFunction(width, height, depth, scratchBuffer->data(),
2302                                           rowPitch.ValueOrDie(), depthPitch.ValueOrDie());
2303 
2304     for (unsigned int i = 0; i < mipLevels; i++)
2305     {
2306         unsigned int mipWidth  = std::max(width >> i, 1U);
2307         unsigned int mipHeight = std::max(height >> i, 1U);
2308 
2309         using CheckedUINT         = angle::CheckedNumeric<UINT>;
2310         CheckedUINT mipRowPitch   = CheckedUINT(dxgiFormatInfo.pixelBytes) * CheckedUINT(mipWidth);
2311         CheckedUINT mipDepthPitch = mipRowPitch * CheckedUINT(mipHeight);
2312 
2313         ANGLE_CHECK_GL_ALLOC(context11, mipRowPitch.IsValid() && mipDepthPitch.IsValid());
2314 
2315         outSubresourceData->at(i).pSysMem          = scratchBuffer->data();
2316         outSubresourceData->at(i).SysMemPitch      = mipRowPitch.ValueOrDie();
2317         outSubresourceData->at(i).SysMemSlicePitch = mipDepthPitch.ValueOrDie();
2318     }
2319 
2320     return angle::Result::Continue;
2321 }
2322 
GetPrimitiveRestartIndex()2323 UINT GetPrimitiveRestartIndex()
2324 {
2325     return std::numeric_limits<UINT>::max();
2326 }
2327 
SetPositionTexCoordVertex(PositionTexCoordVertex * vertex,float x,float y,float u,float v)2328 void SetPositionTexCoordVertex(PositionTexCoordVertex *vertex, float x, float y, float u, float v)
2329 {
2330     vertex->x = x;
2331     vertex->y = y;
2332     vertex->u = u;
2333     vertex->v = v;
2334 }
2335 
SetPositionLayerTexCoord3DVertex(PositionLayerTexCoord3DVertex * vertex,float x,float y,unsigned int layer,float u,float v,float s)2336 void SetPositionLayerTexCoord3DVertex(PositionLayerTexCoord3DVertex *vertex,
2337                                       float x,
2338                                       float y,
2339                                       unsigned int layer,
2340                                       float u,
2341                                       float v,
2342                                       float s)
2343 {
2344     vertex->x = x;
2345     vertex->y = y;
2346     vertex->l = layer;
2347     vertex->u = u;
2348     vertex->v = v;
2349     vertex->s = s;
2350 }
2351 
BlendStateKey()2352 BlendStateKey::BlendStateKey()
2353 {
2354     memset(this, 0, sizeof(BlendStateKey));
2355     blendStateExt = gl::BlendStateExt();
2356 }
2357 
BlendStateKey(const BlendStateKey & other)2358 BlendStateKey::BlendStateKey(const BlendStateKey &other)
2359 {
2360     memcpy(this, &other, sizeof(BlendStateKey));
2361 }
2362 
operator ==(const BlendStateKey & a,const BlendStateKey & b)2363 bool operator==(const BlendStateKey &a, const BlendStateKey &b)
2364 {
2365     return memcmp(&a, &b, sizeof(BlendStateKey)) == 0;
2366 }
2367 
operator !=(const BlendStateKey & a,const BlendStateKey & b)2368 bool operator!=(const BlendStateKey &a, const BlendStateKey &b)
2369 {
2370     return !(a == b);
2371 }
2372 
RasterizerStateKey()2373 RasterizerStateKey::RasterizerStateKey()
2374 {
2375     memset(this, 0, sizeof(RasterizerStateKey));
2376 }
2377 
operator ==(const RasterizerStateKey & a,const RasterizerStateKey & b)2378 bool operator==(const RasterizerStateKey &a, const RasterizerStateKey &b)
2379 {
2380     return memcmp(&a, &b, sizeof(RasterizerStateKey)) == 0;
2381 }
2382 
operator !=(const RasterizerStateKey & a,const RasterizerStateKey & b)2383 bool operator!=(const RasterizerStateKey &a, const RasterizerStateKey &b)
2384 {
2385     return !(a == b);
2386 }
2387 
SetDebugName(ID3D11DeviceChild * resource,const char * internalName,const std::string * khrDebugName)2388 HRESULT SetDebugName(ID3D11DeviceChild *resource,
2389                      const char *internalName,
2390                      const std::string *khrDebugName)
2391 {
2392     // Prepend ANGLE to separate names from other components in the same process.
2393     std::string d3dName = "ANGLE";
2394     bool sendNameToD3D  = false;
2395     if (internalName && internalName[0] != '\0')
2396     {
2397         d3dName += std::string("_") + internalName;
2398         sendNameToD3D = true;
2399     }
2400     if (khrDebugName && !khrDebugName->empty())
2401     {
2402         d3dName += std::string("_") + *khrDebugName;
2403         sendNameToD3D = true;
2404     }
2405     // If both internalName and khrDebugName are empty, avoid sending the string to d3d.
2406     if (sendNameToD3D)
2407     {
2408         return resource->SetPrivateData(WKPDID_D3DDebugObjectName,
2409                                         static_cast<UINT>(d3dName.size()), d3dName.c_str());
2410     }
2411     return S_OK;
2412 }
2413 
2414 // Keep this in cpp file where it has visibility of Renderer11.h, otherwise calling
2415 // allocateResource is only compatible with Clang and MSVS, which support calling a
2416 // method on a forward declared class in a template.
2417 template <ResourceType ResourceT>
resolveImpl(d3d::Context * context,Renderer11 * renderer,const GetDescType<ResourceT> & desc,GetInitDataType<ResourceT> * initData,const char * name)2418 angle::Result LazyResource<ResourceT>::resolveImpl(d3d::Context *context,
2419                                                    Renderer11 *renderer,
2420                                                    const GetDescType<ResourceT> &desc,
2421                                                    GetInitDataType<ResourceT> *initData,
2422                                                    const char *name)
2423 {
2424     if (!mResource.valid())
2425     {
2426         ANGLE_TRY(renderer->allocateResource(context, desc, initData, &mResource));
2427         mResource.setInternalName(name);
2428     }
2429     return angle::Result::Continue;
2430 }
2431 
2432 template angle::Result LazyResource<ResourceType::BlendState>::resolveImpl(
2433     d3d::Context *context,
2434     Renderer11 *renderer,
2435     const D3D11_BLEND_DESC &desc,
2436     void *initData,
2437     const char *name);
2438 template angle::Result LazyResource<ResourceType::ComputeShader>::resolveImpl(
2439     d3d::Context *context,
2440     Renderer11 *renderer,
2441     const ShaderData &desc,
2442     void *initData,
2443     const char *name);
2444 template angle::Result LazyResource<ResourceType::GeometryShader>::resolveImpl(
2445     d3d::Context *context,
2446     Renderer11 *renderer,
2447     const ShaderData &desc,
2448     const std::vector<D3D11_SO_DECLARATION_ENTRY> *initData,
2449     const char *name);
2450 template angle::Result LazyResource<ResourceType::InputLayout>::resolveImpl(
2451     d3d::Context *context,
2452     Renderer11 *renderer,
2453     const InputElementArray &desc,
2454     const ShaderData *initData,
2455     const char *name);
2456 template angle::Result LazyResource<ResourceType::PixelShader>::resolveImpl(d3d::Context *context,
2457                                                                             Renderer11 *renderer,
2458                                                                             const ShaderData &desc,
2459                                                                             void *initData,
2460                                                                             const char *name);
2461 template angle::Result LazyResource<ResourceType::VertexShader>::resolveImpl(d3d::Context *context,
2462                                                                              Renderer11 *renderer,
2463                                                                              const ShaderData &desc,
2464                                                                              void *initData,
2465                                                                              const char *name);
2466 
LazyInputLayout(const D3D11_INPUT_ELEMENT_DESC * inputDesc,size_t inputDescLen,const BYTE * byteCode,size_t byteCodeLen,const char * debugName)2467 LazyInputLayout::LazyInputLayout(const D3D11_INPUT_ELEMENT_DESC *inputDesc,
2468                                  size_t inputDescLen,
2469                                  const BYTE *byteCode,
2470                                  size_t byteCodeLen,
2471                                  const char *debugName)
2472     : mInputDesc(inputDesc, inputDescLen), mByteCode(byteCode, byteCodeLen), mDebugName(debugName)
2473 {}
2474 
~LazyInputLayout()2475 LazyInputLayout::~LazyInputLayout() {}
2476 
resolve(d3d::Context * context,Renderer11 * renderer)2477 angle::Result LazyInputLayout::resolve(d3d::Context *context, Renderer11 *renderer)
2478 {
2479     return resolveImpl(context, renderer, mInputDesc, &mByteCode, mDebugName);
2480 }
2481 
LazyBlendState(const D3D11_BLEND_DESC & desc,const char * debugName)2482 LazyBlendState::LazyBlendState(const D3D11_BLEND_DESC &desc, const char *debugName)
2483     : mDesc(desc), mDebugName(debugName)
2484 {}
2485 
resolve(d3d::Context * context,Renderer11 * renderer)2486 angle::Result LazyBlendState::resolve(d3d::Context *context, Renderer11 *renderer)
2487 {
2488     return resolveImpl(context, renderer, mDesc, nullptr, mDebugName);
2489 }
2490 
InitializeFeatures(const Renderer11DeviceCaps & deviceCaps,const DXGI_ADAPTER_DESC & adapterDesc,angle::FeaturesD3D * features)2491 void InitializeFeatures(const Renderer11DeviceCaps &deviceCaps,
2492                         const DXGI_ADAPTER_DESC &adapterDesc,
2493                         angle::FeaturesD3D *features)
2494 {
2495     bool isNvidia          = IsNvidia(adapterDesc.VendorId);
2496     bool isIntel           = IsIntel(adapterDesc.VendorId);
2497     bool isSkylake         = false;
2498     bool isBroadwell       = false;
2499     bool isHaswell         = false;
2500     bool isIvyBridge       = false;
2501     bool isAMD             = IsAMD(adapterDesc.VendorId);
2502     bool isFeatureLevel9_3 = (deviceCaps.featureLevel <= D3D_FEATURE_LEVEL_9_3);
2503 
2504     IntelDriverVersion capsVersion = IntelDriverVersion(0);
2505     if (isIntel)
2506     {
2507         capsVersion = d3d11_gl::GetIntelDriverVersion(deviceCaps.driverVersion);
2508 
2509         isSkylake   = IsSkylake(adapterDesc.DeviceId);
2510         isBroadwell = IsBroadwell(adapterDesc.DeviceId);
2511         isHaswell   = IsHaswell(adapterDesc.DeviceId);
2512         isIvyBridge = IsIvyBridge(adapterDesc.DeviceId);
2513     }
2514 
2515     if (isNvidia)
2516     {
2517         // TODO(jmadill): Narrow problematic driver range.
2518         bool driverVersionValid = deviceCaps.driverVersion.valid();
2519         if (driverVersionValid)
2520         {
2521             WORD part1 = HIWORD(deviceCaps.driverVersion.value().LowPart);
2522             WORD part2 = LOWORD(deviceCaps.driverVersion.value().LowPart);
2523 
2524             // Disable the workaround to fix a second driver bug on newer NVIDIA.
2525             ANGLE_FEATURE_CONDITION(
2526                 features, depthStencilBlitExtraCopy,
2527                 (part1 <= 13u && part2 < 6881) && isNvidia && driverVersionValid);
2528         }
2529         else
2530         {
2531             ANGLE_FEATURE_CONDITION(features, depthStencilBlitExtraCopy,
2532                                     isNvidia && !driverVersionValid);
2533         }
2534     }
2535 
2536     ANGLE_FEATURE_CONDITION(features, mrtPerfWorkaround, true);
2537     ANGLE_FEATURE_CONDITION(features, zeroMaxLodWorkaround, isFeatureLevel9_3);
2538     ANGLE_FEATURE_CONDITION(features, useInstancedPointSpriteEmulation, isFeatureLevel9_3);
2539     ANGLE_FEATURE_CONDITION(features, allowES3OnFL100, false);
2540 
2541     // TODO(jmadill): Disable workaround when we have a fixed compiler DLL.
2542     ANGLE_FEATURE_CONDITION(features, expandIntegerPowExpressions, true);
2543 
2544     ANGLE_FEATURE_CONDITION(features, flushAfterEndingTransformFeedback, isNvidia);
2545     ANGLE_FEATURE_CONDITION(features, getDimensionsIgnoresBaseLevel, isNvidia);
2546     ANGLE_FEATURE_CONDITION(features, skipVSConstantRegisterZero, isNvidia);
2547     ANGLE_FEATURE_CONDITION(features, forceAtomicValueResolution, isNvidia);
2548 
2549     ANGLE_FEATURE_CONDITION(features, preAddTexelFetchOffsets, isIntel);
2550     ANGLE_FEATURE_CONDITION(features, useSystemMemoryForConstantBuffers, isIntel);
2551 
2552     ANGLE_FEATURE_CONDITION(features, callClearTwice,
2553                             isIntel && isSkylake && capsVersion >= IntelDriverVersion(160000) &&
2554                                 capsVersion < IntelDriverVersion(164771));
2555     ANGLE_FEATURE_CONDITION(features, emulateIsnanFloat,
2556                             isIntel && isSkylake && capsVersion >= IntelDriverVersion(160000) &&
2557                                 capsVersion < IntelDriverVersion(164542));
2558     ANGLE_FEATURE_CONDITION(features, rewriteUnaryMinusOperator,
2559                             isIntel && (isBroadwell || isHaswell) &&
2560                                 capsVersion >= IntelDriverVersion(150000) &&
2561                                 capsVersion < IntelDriverVersion(154624));
2562 
2563     ANGLE_FEATURE_CONDITION(features, addMockTextureNoRenderTarget,
2564                             isIntel && capsVersion >= IntelDriverVersion(160000) &&
2565                                 capsVersion < IntelDriverVersion(164815));
2566 
2567     // Haswell/Ivybridge drivers occasionally corrupt (small?) (vertex?) texture data uploads.
2568     ANGLE_FEATURE_CONDITION(features, setDataFasterThanImageUpload,
2569                             !(isIvyBridge || isBroadwell || isHaswell));
2570 
2571     ANGLE_FEATURE_CONDITION(features, disableB5G6R5Support,
2572                             (isIntel && capsVersion >= IntelDriverVersion(150000) &&
2573                              capsVersion < IntelDriverVersion(154539)) ||
2574                                 isAMD);
2575 
2576     // TODO(jmadill): Disable when we have a fixed driver version.
2577     // The tiny stencil texture workaround involves using CopySubresource or UpdateSubresource on a
2578     // depth stencil texture.  This is not allowed until feature level 10.1 but since it is not
2579     // possible to support ES3 on these devices, there is no need for the workaround to begin with
2580     // (anglebug.com/1572).
2581     ANGLE_FEATURE_CONDITION(features, emulateTinyStencilTextures,
2582                             isAMD && !(deviceCaps.featureLevel < D3D_FEATURE_LEVEL_10_1));
2583 
2584     // If the VPAndRTArrayIndexFromAnyShaderFeedingRasterizer feature is not available, we have to
2585     // select the viewport / RT array index in the geometry shader.
2586     ANGLE_FEATURE_CONDITION(features, selectViewInGeometryShader,
2587                             !deviceCaps.supportsVpRtIndexWriteFromVertexShader);
2588 
2589     // NVidia drivers have no trouble clearing textures without showing corruption.
2590     // Intel and AMD drivers that have trouble have been blocklisted by Chromium. In the case of
2591     // Intel, they've been blocklisted to the DX9 runtime.
2592     ANGLE_FEATURE_CONDITION(features, allowClearForRobustResourceInit, true);
2593 
2594     // Allow translating uniform block to StructuredBuffer on Windows 10. This is targeted
2595     // to work around a slow fxc compile performance issue with dynamic uniform indexing.
2596     ANGLE_FEATURE_CONDITION(features, allowTranslateUniformBlockToStructuredBuffer,
2597                             IsWindows10OrLater());
2598 }
2599 
InitializeFrontendFeatures(const DXGI_ADAPTER_DESC & adapterDesc,angle::FrontendFeatures * features)2600 void InitializeFrontendFeatures(const DXGI_ADAPTER_DESC &adapterDesc,
2601                                 angle::FrontendFeatures *features)
2602 {
2603     bool isAMD = IsAMD(adapterDesc.VendorId);
2604 
2605     ANGLE_FEATURE_CONDITION(features, forceDepthAttachmentInitOnClear, isAMD);
2606 }
2607 
InitConstantBufferDesc(D3D11_BUFFER_DESC * constantBufferDescription,size_t byteWidth)2608 void InitConstantBufferDesc(D3D11_BUFFER_DESC *constantBufferDescription, size_t byteWidth)
2609 {
2610     constantBufferDescription->ByteWidth           = static_cast<UINT>(byteWidth);
2611     constantBufferDescription->Usage               = D3D11_USAGE_DYNAMIC;
2612     constantBufferDescription->BindFlags           = D3D11_BIND_CONSTANT_BUFFER;
2613     constantBufferDescription->CPUAccessFlags      = D3D11_CPU_ACCESS_WRITE;
2614     constantBufferDescription->MiscFlags           = 0;
2615     constantBufferDescription->StructureByteStride = 0;
2616 }
2617 
2618 }  // namespace d3d11
2619 
2620 // TextureHelper11 implementation.
TextureHelper11()2621 TextureHelper11::TextureHelper11() : mFormatSet(nullptr), mSampleCount(0) {}
2622 
TextureHelper11(TextureHelper11 && toCopy)2623 TextureHelper11::TextureHelper11(TextureHelper11 &&toCopy) : TextureHelper11()
2624 {
2625     *this = std::move(toCopy);
2626 }
2627 
TextureHelper11(const TextureHelper11 & other)2628 TextureHelper11::TextureHelper11(const TextureHelper11 &other)
2629     : mFormatSet(other.mFormatSet), mExtents(other.mExtents), mSampleCount(other.mSampleCount)
2630 {
2631     mData = other.mData;
2632 }
2633 
~TextureHelper11()2634 TextureHelper11::~TextureHelper11() {}
2635 
getDesc(D3D11_TEXTURE2D_DESC * desc) const2636 void TextureHelper11::getDesc(D3D11_TEXTURE2D_DESC *desc) const
2637 {
2638     static_cast<ID3D11Texture2D *>(mData->object)->GetDesc(desc);
2639 }
2640 
getDesc(D3D11_TEXTURE3D_DESC * desc) const2641 void TextureHelper11::getDesc(D3D11_TEXTURE3D_DESC *desc) const
2642 {
2643     static_cast<ID3D11Texture3D *>(mData->object)->GetDesc(desc);
2644 }
2645 
getDesc(D3D11_BUFFER_DESC * desc) const2646 void TextureHelper11::getDesc(D3D11_BUFFER_DESC *desc) const
2647 {
2648     static_cast<ID3D11Buffer *>(mData->object)->GetDesc(desc);
2649 }
2650 
initDesc(const D3D11_TEXTURE2D_DESC & desc2D)2651 void TextureHelper11::initDesc(const D3D11_TEXTURE2D_DESC &desc2D)
2652 {
2653     mData->resourceType = ResourceType::Texture2D;
2654     mExtents.width      = static_cast<int>(desc2D.Width);
2655     mExtents.height     = static_cast<int>(desc2D.Height);
2656     mExtents.depth      = 1;
2657     mSampleCount        = desc2D.SampleDesc.Count;
2658 }
2659 
initDesc(const D3D11_TEXTURE3D_DESC & desc3D)2660 void TextureHelper11::initDesc(const D3D11_TEXTURE3D_DESC &desc3D)
2661 {
2662     mData->resourceType = ResourceType::Texture3D;
2663     mExtents.width      = static_cast<int>(desc3D.Width);
2664     mExtents.height     = static_cast<int>(desc3D.Height);
2665     mExtents.depth      = static_cast<int>(desc3D.Depth);
2666     mSampleCount        = 1;
2667 }
2668 
initDesc(const D3D11_BUFFER_DESC & descBuffer)2669 void TextureHelper11::initDesc(const D3D11_BUFFER_DESC &descBuffer)
2670 {
2671     mData->resourceType = ResourceType::Buffer;
2672     mExtents.width      = static_cast<int>(descBuffer.ByteWidth);
2673     mExtents.height     = 1;
2674     mExtents.depth      = 1;
2675     mSampleCount        = 1;
2676 }
2677 
operator =(TextureHelper11 && other)2678 TextureHelper11 &TextureHelper11::operator=(TextureHelper11 &&other)
2679 {
2680     std::swap(mData, other.mData);
2681     std::swap(mExtents, other.mExtents);
2682     std::swap(mFormatSet, other.mFormatSet);
2683     std::swap(mSampleCount, other.mSampleCount);
2684     return *this;
2685 }
2686 
operator =(const TextureHelper11 & other)2687 TextureHelper11 &TextureHelper11::operator=(const TextureHelper11 &other)
2688 {
2689     mData        = other.mData;
2690     mExtents     = other.mExtents;
2691     mFormatSet   = other.mFormatSet;
2692     mSampleCount = other.mSampleCount;
2693     return *this;
2694 }
2695 
operator ==(const TextureHelper11 & other) const2696 bool TextureHelper11::operator==(const TextureHelper11 &other) const
2697 {
2698     return mData->object == other.mData->object;
2699 }
2700 
operator !=(const TextureHelper11 & other) const2701 bool TextureHelper11::operator!=(const TextureHelper11 &other) const
2702 {
2703     return mData->object != other.mData->object;
2704 }
2705 
UsePresentPathFast(const Renderer11 * renderer,const gl::FramebufferAttachment * framebufferAttachment)2706 bool UsePresentPathFast(const Renderer11 *renderer,
2707                         const gl::FramebufferAttachment *framebufferAttachment)
2708 {
2709     if (framebufferAttachment == nullptr)
2710     {
2711         return false;
2712     }
2713 
2714     return (framebufferAttachment->type() == GL_FRAMEBUFFER_DEFAULT &&
2715             renderer->presentPathFastEnabled());
2716 }
2717 
UsePrimitiveRestartWorkaround(bool primitiveRestartFixedIndexEnabled,gl::DrawElementsType type)2718 bool UsePrimitiveRestartWorkaround(bool primitiveRestartFixedIndexEnabled,
2719                                    gl::DrawElementsType type)
2720 {
2721     // We should never have to deal with primitive restart workaround issue with GL_UNSIGNED_INT
2722     // indices, since we restrict it via MAX_ELEMENT_INDEX.
2723     return (!primitiveRestartFixedIndexEnabled && type == gl::DrawElementsType::UnsignedShort);
2724 }
2725 
ClassifyIndexStorage(const gl::State & glState,const gl::Buffer * elementArrayBuffer,gl::DrawElementsType elementType,gl::DrawElementsType destElementType,unsigned int offset)2726 IndexStorageType ClassifyIndexStorage(const gl::State &glState,
2727                                       const gl::Buffer *elementArrayBuffer,
2728                                       gl::DrawElementsType elementType,
2729                                       gl::DrawElementsType destElementType,
2730                                       unsigned int offset)
2731 {
2732     // No buffer bound means we are streaming from a client pointer.
2733     if (!elementArrayBuffer || !IsOffsetAligned(elementType, offset))
2734     {
2735         return IndexStorageType::Dynamic;
2736     }
2737 
2738     // The buffer can be used directly if the storage supports it and no translation needed.
2739     BufferD3D *bufferD3D = GetImplAs<BufferD3D>(elementArrayBuffer);
2740     if (bufferD3D->supportsDirectBinding() && destElementType == elementType)
2741     {
2742         return IndexStorageType::Direct;
2743     }
2744 
2745     // Use a static copy when available.
2746     StaticIndexBufferInterface *staticBuffer = bufferD3D->getStaticIndexBuffer();
2747     if (staticBuffer != nullptr)
2748     {
2749         return IndexStorageType::Static;
2750     }
2751 
2752     // Static buffer not available, fall back to streaming.
2753     return IndexStorageType::Dynamic;
2754 }
2755 
SwizzleRequired(const gl::TextureState & textureState)2756 bool SwizzleRequired(const gl::TextureState &textureState)
2757 {
2758     // When sampling stencil, a swizzle is needed to move the stencil channel from G to R.
2759     return textureState.swizzleRequired() || textureState.isStencilMode();
2760 }
2761 
GetEffectiveSwizzle(const gl::TextureState & textureState)2762 gl::SwizzleState GetEffectiveSwizzle(const gl::TextureState &textureState)
2763 {
2764     const gl::SwizzleState &swizzle = textureState.getSwizzleState();
2765     if (textureState.isStencilMode())
2766     {
2767         // Per GL semantics, the stencil value should be in the red channel, while D3D11 formats
2768         // leave stencil in the green channel. So copy the stencil value from green to all
2769         // components requesting red. Green and blue become zero; alpha becomes one.
2770         std::unordered_map<GLenum, GLenum> map = {{GL_RED, GL_GREEN}, {GL_GREEN, GL_ZERO},
2771                                                   {GL_BLUE, GL_ZERO}, {GL_ALPHA, GL_ONE},
2772                                                   {GL_ZERO, GL_ZERO}, {GL_ONE, GL_ONE}};
2773 
2774         return gl::SwizzleState(map[swizzle.swizzleRed], map[swizzle.swizzleGreen],
2775                                 map[swizzle.swizzleBlue], map[swizzle.swizzleAlpha]);
2776     }
2777     return swizzle;
2778 }
2779 
2780 }  // namespace rx
2781