• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2016 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 // Context11:
7 //   D3D11-specific functionality associated with a GL Context.
8 //
9 
10 #include "libANGLE/renderer/d3d/d3d11/Context11.h"
11 
12 #include "common/entry_points_enum_autogen.h"
13 #include "common/string_utils.h"
14 #include "libANGLE/Context.h"
15 #include "libANGLE/Context.inl.h"
16 #include "libANGLE/MemoryProgramCache.h"
17 #include "libANGLE/renderer/OverlayImpl.h"
18 #include "libANGLE/renderer/d3d/CompilerD3D.h"
19 #include "libANGLE/renderer/d3d/RenderbufferD3D.h"
20 #include "libANGLE/renderer/d3d/SamplerD3D.h"
21 #include "libANGLE/renderer/d3d/ShaderD3D.h"
22 #include "libANGLE/renderer/d3d/TextureD3D.h"
23 #include "libANGLE/renderer/d3d/d3d11/Buffer11.h"
24 #include "libANGLE/renderer/d3d/d3d11/Fence11.h"
25 #include "libANGLE/renderer/d3d/d3d11/Framebuffer11.h"
26 #include "libANGLE/renderer/d3d/d3d11/IndexBuffer11.h"
27 #include "libANGLE/renderer/d3d/d3d11/Program11.h"
28 #include "libANGLE/renderer/d3d/d3d11/ProgramPipeline11.h"
29 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
30 #include "libANGLE/renderer/d3d/d3d11/StateManager11.h"
31 #include "libANGLE/renderer/d3d/d3d11/TransformFeedback11.h"
32 #include "libANGLE/renderer/d3d/d3d11/VertexArray11.h"
33 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
34 
35 namespace rx
36 {
37 
38 namespace
39 {
DrawCallHasDynamicAttribs(const gl::Context * context)40 ANGLE_INLINE bool DrawCallHasDynamicAttribs(const gl::Context *context)
41 {
42     VertexArray11 *vertexArray11 = GetImplAs<VertexArray11>(context->getState().getVertexArray());
43     return vertexArray11->hasActiveDynamicAttrib(context);
44 }
45 
DrawCallHasStreamingVertexArrays(const gl::Context * context,gl::PrimitiveMode mode)46 bool DrawCallHasStreamingVertexArrays(const gl::Context *context, gl::PrimitiveMode mode)
47 {
48     // Direct drawing doesn't support dynamic attribute storage since it needs the first and count
49     // to translate when applyVertexBuffer. GL_LINE_LOOP and GL_TRIANGLE_FAN are not supported
50     // either since we need to simulate them in D3D.
51     if (DrawCallHasDynamicAttribs(context) || mode == gl::PrimitiveMode::LineLoop ||
52         mode == gl::PrimitiveMode::TriangleFan)
53     {
54         return true;
55     }
56 
57     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(context->getState().getProgram());
58     if (InstancedPointSpritesActive(programD3D, mode))
59     {
60         return true;
61     }
62 
63     return false;
64 }
65 
DrawCallHasStreamingElementArray(const gl::Context * context,gl::DrawElementsType srcType)66 bool DrawCallHasStreamingElementArray(const gl::Context *context, gl::DrawElementsType srcType)
67 {
68     const gl::State &glState       = context->getState();
69     gl::Buffer *elementArrayBuffer = glState.getVertexArray()->getElementArrayBuffer();
70 
71     bool primitiveRestartWorkaround =
72         UsePrimitiveRestartWorkaround(glState.isPrimitiveRestartEnabled(), srcType);
73     const gl::DrawElementsType dstType =
74         (srcType == gl::DrawElementsType::UnsignedInt || primitiveRestartWorkaround)
75             ? gl::DrawElementsType::UnsignedInt
76             : gl::DrawElementsType::UnsignedShort;
77 
78     // Not clear where the offset comes from here.
79     switch (ClassifyIndexStorage(glState, elementArrayBuffer, srcType, dstType, 0))
80     {
81         case IndexStorageType::Dynamic:
82             return true;
83         case IndexStorageType::Direct:
84             return false;
85         case IndexStorageType::Static:
86         {
87             BufferD3D *bufferD3D                     = GetImplAs<BufferD3D>(elementArrayBuffer);
88             StaticIndexBufferInterface *staticBuffer = bufferD3D->getStaticIndexBuffer();
89             return (staticBuffer->getBufferSize() == 0 || staticBuffer->getIndexType() != dstType);
90         }
91         default:
92             UNREACHABLE();
93             return true;
94     }
95 }
96 
97 template <typename IndirectBufferT>
ReadbackIndirectBuffer(const gl::Context * context,const void * indirect,const IndirectBufferT ** bufferPtrOut)98 angle::Result ReadbackIndirectBuffer(const gl::Context *context,
99                                      const void *indirect,
100                                      const IndirectBufferT **bufferPtrOut)
101 {
102     const gl::State &glState       = context->getState();
103     gl::Buffer *drawIndirectBuffer = glState.getTargetBuffer(gl::BufferBinding::DrawIndirect);
104     ASSERT(drawIndirectBuffer);
105     Buffer11 *storage = GetImplAs<Buffer11>(drawIndirectBuffer);
106     uintptr_t offset  = reinterpret_cast<uintptr_t>(indirect);
107 
108     const uint8_t *bufferData = nullptr;
109     ANGLE_TRY(storage->getData(context, &bufferData));
110     ASSERT(bufferData);
111 
112     *bufferPtrOut = reinterpret_cast<const IndirectBufferT *>(bufferData + offset);
113     return angle::Result::Continue;
114 }
115 }  // anonymous namespace
116 
Context11(const gl::State & state,gl::ErrorSet * errorSet,Renderer11 * renderer)117 Context11::Context11(const gl::State &state, gl::ErrorSet *errorSet, Renderer11 *renderer)
118     : ContextD3D(state, errorSet), mRenderer(renderer)
119 {}
120 
~Context11()121 Context11::~Context11() {}
122 
initialize()123 angle::Result Context11::initialize()
124 {
125     return angle::Result::Continue;
126 }
127 
onDestroy(const gl::Context * context)128 void Context11::onDestroy(const gl::Context *context)
129 {
130     mIncompleteTextures.onDestroy(context);
131 }
132 
createCompiler()133 CompilerImpl *Context11::createCompiler()
134 {
135     if (mRenderer->getRenderer11DeviceCaps().featureLevel <= D3D_FEATURE_LEVEL_9_3)
136     {
137         return new CompilerD3D(SH_HLSL_4_0_FL9_3_OUTPUT);
138     }
139     else
140     {
141         return new CompilerD3D(SH_HLSL_4_1_OUTPUT);
142     }
143 }
144 
createShader(const gl::ShaderState & data)145 ShaderImpl *Context11::createShader(const gl::ShaderState &data)
146 {
147     return new ShaderD3D(data, mRenderer->getFeatures(), mRenderer->getNativeExtensions());
148 }
149 
createProgram(const gl::ProgramState & data)150 ProgramImpl *Context11::createProgram(const gl::ProgramState &data)
151 {
152     return new Program11(data, mRenderer);
153 }
154 
createFramebuffer(const gl::FramebufferState & data)155 FramebufferImpl *Context11::createFramebuffer(const gl::FramebufferState &data)
156 {
157     return new Framebuffer11(data, mRenderer);
158 }
159 
createTexture(const gl::TextureState & state)160 TextureImpl *Context11::createTexture(const gl::TextureState &state)
161 {
162     switch (state.getType())
163     {
164         case gl::TextureType::_2D:
165         // GL_TEXTURE_VIDEO_IMAGE_WEBGL maps to native 2D texture on Windows platform
166         case gl::TextureType::VideoImage:
167             return new TextureD3D_2D(state, mRenderer);
168         case gl::TextureType::CubeMap:
169             return new TextureD3D_Cube(state, mRenderer);
170         case gl::TextureType::_3D:
171             return new TextureD3D_3D(state, mRenderer);
172         case gl::TextureType::_2DArray:
173             return new TextureD3D_2DArray(state, mRenderer);
174         case gl::TextureType::External:
175             return new TextureD3D_External(state, mRenderer);
176         case gl::TextureType::_2DMultisample:
177             return new TextureD3D_2DMultisample(state, mRenderer);
178         case gl::TextureType::_2DMultisampleArray:
179             return new TextureD3D_2DMultisampleArray(state, mRenderer);
180         default:
181             UNREACHABLE();
182     }
183 
184     return nullptr;
185 }
186 
createRenderbuffer(const gl::RenderbufferState & state)187 RenderbufferImpl *Context11::createRenderbuffer(const gl::RenderbufferState &state)
188 {
189     return new RenderbufferD3D(state, mRenderer);
190 }
191 
createBuffer(const gl::BufferState & state)192 BufferImpl *Context11::createBuffer(const gl::BufferState &state)
193 {
194     Buffer11 *buffer = new Buffer11(state, mRenderer);
195     mRenderer->onBufferCreate(buffer);
196     return buffer;
197 }
198 
createVertexArray(const gl::VertexArrayState & data)199 VertexArrayImpl *Context11::createVertexArray(const gl::VertexArrayState &data)
200 {
201     return new VertexArray11(data);
202 }
203 
createQuery(gl::QueryType type)204 QueryImpl *Context11::createQuery(gl::QueryType type)
205 {
206     return new Query11(mRenderer, type);
207 }
208 
createFenceNV()209 FenceNVImpl *Context11::createFenceNV()
210 {
211     return new FenceNV11(mRenderer);
212 }
213 
createSync()214 SyncImpl *Context11::createSync()
215 {
216     return new Sync11(mRenderer);
217 }
218 
createTransformFeedback(const gl::TransformFeedbackState & state)219 TransformFeedbackImpl *Context11::createTransformFeedback(const gl::TransformFeedbackState &state)
220 {
221     return new TransformFeedback11(state, mRenderer);
222 }
223 
createSampler(const gl::SamplerState & state)224 SamplerImpl *Context11::createSampler(const gl::SamplerState &state)
225 {
226     return new SamplerD3D(state);
227 }
228 
createProgramPipeline(const gl::ProgramPipelineState & data)229 ProgramPipelineImpl *Context11::createProgramPipeline(const gl::ProgramPipelineState &data)
230 {
231     return new ProgramPipeline11(data);
232 }
233 
createMemoryObject()234 MemoryObjectImpl *Context11::createMemoryObject()
235 {
236     UNREACHABLE();
237     return nullptr;
238 }
239 
createSemaphore()240 SemaphoreImpl *Context11::createSemaphore()
241 {
242     UNREACHABLE();
243     return nullptr;
244 }
245 
createOverlay(const gl::OverlayState & state)246 OverlayImpl *Context11::createOverlay(const gl::OverlayState &state)
247 {
248     // Not implemented.
249     return new OverlayImpl(state);
250 }
251 
flush(const gl::Context * context)252 angle::Result Context11::flush(const gl::Context *context)
253 {
254     return mRenderer->flush(this);
255 }
256 
finish(const gl::Context * context)257 angle::Result Context11::finish(const gl::Context *context)
258 {
259     return mRenderer->finish(this);
260 }
261 
drawArrays(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count)262 angle::Result Context11::drawArrays(const gl::Context *context,
263                                     gl::PrimitiveMode mode,
264                                     GLint first,
265                                     GLsizei count)
266 {
267     ASSERT(count > 0);
268     ANGLE_TRY(mRenderer->getStateManager()->updateState(
269         context, mode, first, count, gl::DrawElementsType::InvalidEnum, nullptr, 0, 0, 0, true));
270     return mRenderer->drawArrays(context, mode, first, count, 0, 0);
271 }
272 
drawArraysInstanced(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count,GLsizei instanceCount)273 angle::Result Context11::drawArraysInstanced(const gl::Context *context,
274                                              gl::PrimitiveMode mode,
275                                              GLint first,
276                                              GLsizei count,
277                                              GLsizei instanceCount)
278 {
279     ASSERT(count > 0);
280     ANGLE_TRY(mRenderer->getStateManager()->updateState(context, mode, first, count,
281                                                         gl::DrawElementsType::InvalidEnum, nullptr,
282                                                         instanceCount, 0, 0, true));
283     return mRenderer->drawArrays(context, mode, first, count, instanceCount, 0);
284 }
285 
drawArraysInstancedBaseInstance(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count,GLsizei instanceCount,GLuint baseInstance)286 angle::Result Context11::drawArraysInstancedBaseInstance(const gl::Context *context,
287                                                          gl::PrimitiveMode mode,
288                                                          GLint first,
289                                                          GLsizei count,
290                                                          GLsizei instanceCount,
291                                                          GLuint baseInstance)
292 {
293     ASSERT(count > 0);
294     ANGLE_TRY(mRenderer->getStateManager()->updateState(context, mode, first, count,
295                                                         gl::DrawElementsType::InvalidEnum, nullptr,
296                                                         instanceCount, 0, baseInstance, true));
297     return mRenderer->drawArrays(context, mode, first, count, instanceCount, baseInstance);
298 }
299 
drawElementsImpl(const gl::Context * context,gl::PrimitiveMode mode,GLsizei indexCount,gl::DrawElementsType indexType,const void * indices,GLsizei instanceCount,GLint baseVertex,GLuint baseInstance,bool promoteDynamic)300 ANGLE_INLINE angle::Result Context11::drawElementsImpl(const gl::Context *context,
301                                                        gl::PrimitiveMode mode,
302                                                        GLsizei indexCount,
303                                                        gl::DrawElementsType indexType,
304                                                        const void *indices,
305                                                        GLsizei instanceCount,
306                                                        GLint baseVertex,
307                                                        GLuint baseInstance,
308                                                        bool promoteDynamic)
309 {
310     ASSERT(indexCount > 0);
311 
312     if (DrawCallHasDynamicAttribs(context))
313     {
314         gl::IndexRange indexRange;
315         ANGLE_TRY(context->getState().getVertexArray()->getIndexRange(
316             context, indexType, indexCount, indices, &indexRange));
317         GLint startVertex;
318         ANGLE_TRY(ComputeStartVertex(GetImplAs<Context11>(context), indexRange, baseVertex,
319                                      &startVertex));
320         ANGLE_TRY(mRenderer->getStateManager()->updateState(
321             context, mode, startVertex, indexCount, indexType, indices, instanceCount, baseVertex,
322             baseInstance, promoteDynamic));
323         return mRenderer->drawElements(context, mode, startVertex, indexCount, indexType, indices,
324                                        instanceCount, baseVertex, baseInstance);
325     }
326     else
327     {
328         ANGLE_TRY(mRenderer->getStateManager()->updateState(context, mode, 0, indexCount, indexType,
329                                                             indices, instanceCount, baseVertex,
330                                                             baseInstance, promoteDynamic));
331         return mRenderer->drawElements(context, mode, 0, indexCount, indexType, indices,
332                                        instanceCount, baseVertex, baseInstance);
333     }
334 }
335 
drawElements(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices)336 angle::Result Context11::drawElements(const gl::Context *context,
337                                       gl::PrimitiveMode mode,
338                                       GLsizei count,
339                                       gl::DrawElementsType type,
340                                       const void *indices)
341 {
342     return drawElementsImpl(context, mode, count, type, indices, 0, 0, 0, true);
343 }
344 
drawElementsBaseVertex(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLint baseVertex)345 angle::Result Context11::drawElementsBaseVertex(const gl::Context *context,
346                                                 gl::PrimitiveMode mode,
347                                                 GLsizei count,
348                                                 gl::DrawElementsType type,
349                                                 const void *indices,
350                                                 GLint baseVertex)
351 {
352     return drawElementsImpl(context, mode, count, type, indices, 0, baseVertex, 0, true);
353 }
354 
drawElementsInstanced(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances)355 angle::Result Context11::drawElementsInstanced(const gl::Context *context,
356                                                gl::PrimitiveMode mode,
357                                                GLsizei count,
358                                                gl::DrawElementsType type,
359                                                const void *indices,
360                                                GLsizei instances)
361 {
362     return drawElementsImpl(context, mode, count, type, indices, instances, 0, 0, true);
363 }
364 
drawElementsInstancedBaseVertex(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances,GLint baseVertex)365 angle::Result Context11::drawElementsInstancedBaseVertex(const gl::Context *context,
366                                                          gl::PrimitiveMode mode,
367                                                          GLsizei count,
368                                                          gl::DrawElementsType type,
369                                                          const void *indices,
370                                                          GLsizei instances,
371                                                          GLint baseVertex)
372 {
373     return drawElementsImpl(context, mode, count, type, indices, instances, baseVertex, 0, true);
374 }
375 
drawElementsInstancedBaseVertexBaseInstance(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances,GLint baseVertex,GLuint baseInstance)376 angle::Result Context11::drawElementsInstancedBaseVertexBaseInstance(const gl::Context *context,
377                                                                      gl::PrimitiveMode mode,
378                                                                      GLsizei count,
379                                                                      gl::DrawElementsType type,
380                                                                      const void *indices,
381                                                                      GLsizei instances,
382                                                                      GLint baseVertex,
383                                                                      GLuint baseInstance)
384 {
385     return drawElementsImpl(context, mode, count, type, indices, instances, baseVertex,
386                             baseInstance, true);
387 }
388 
drawRangeElements(const gl::Context * context,gl::PrimitiveMode mode,GLuint start,GLuint end,GLsizei count,gl::DrawElementsType type,const void * indices)389 angle::Result Context11::drawRangeElements(const gl::Context *context,
390                                            gl::PrimitiveMode mode,
391                                            GLuint start,
392                                            GLuint end,
393                                            GLsizei count,
394                                            gl::DrawElementsType type,
395                                            const void *indices)
396 {
397     return drawElementsImpl(context, mode, count, type, indices, 0, 0, 0, true);
398 }
399 
drawRangeElementsBaseVertex(const gl::Context * context,gl::PrimitiveMode mode,GLuint start,GLuint end,GLsizei count,gl::DrawElementsType type,const void * indices,GLint baseVertex)400 angle::Result Context11::drawRangeElementsBaseVertex(const gl::Context *context,
401                                                      gl::PrimitiveMode mode,
402                                                      GLuint start,
403                                                      GLuint end,
404                                                      GLsizei count,
405                                                      gl::DrawElementsType type,
406                                                      const void *indices,
407                                                      GLint baseVertex)
408 {
409     return drawElementsImpl(context, mode, count, type, indices, 0, baseVertex, 0, true);
410 }
411 
drawArraysIndirect(const gl::Context * context,gl::PrimitiveMode mode,const void * indirect)412 angle::Result Context11::drawArraysIndirect(const gl::Context *context,
413                                             gl::PrimitiveMode mode,
414                                             const void *indirect)
415 {
416     if (DrawCallHasStreamingVertexArrays(context, mode))
417     {
418         const gl::DrawArraysIndirectCommand *cmd = nullptr;
419         ANGLE_TRY(ReadbackIndirectBuffer(context, indirect, &cmd));
420 
421         ANGLE_TRY(mRenderer->getStateManager()->updateState(
422             context, mode, cmd->first, cmd->count, gl::DrawElementsType::InvalidEnum, nullptr,
423             cmd->instanceCount, 0, 0, true));
424         return mRenderer->drawArrays(context, mode, cmd->first, cmd->count, cmd->instanceCount,
425                                      cmd->baseInstance);
426     }
427     else
428     {
429         ANGLE_TRY(mRenderer->getStateManager()->updateState(
430             context, mode, 0, 0, gl::DrawElementsType::InvalidEnum, nullptr, 0, 0, 0, true));
431         return mRenderer->drawArraysIndirect(context, indirect);
432     }
433 }
434 
drawElementsIndirect(const gl::Context * context,gl::PrimitiveMode mode,gl::DrawElementsType type,const void * indirect)435 angle::Result Context11::drawElementsIndirect(const gl::Context *context,
436                                               gl::PrimitiveMode mode,
437                                               gl::DrawElementsType type,
438                                               const void *indirect)
439 {
440     if (DrawCallHasStreamingVertexArrays(context, mode) ||
441         DrawCallHasStreamingElementArray(context, type))
442     {
443         const gl::DrawElementsIndirectCommand *cmd = nullptr;
444         ANGLE_TRY(ReadbackIndirectBuffer(context, indirect, &cmd));
445 
446         const GLuint typeBytes = gl::GetDrawElementsTypeSize(type);
447         const void *indices =
448             reinterpret_cast<const void *>(static_cast<uintptr_t>(cmd->firstIndex * typeBytes));
449 
450         // We must explicitly resolve the index range for the slow-path indirect drawElements to
451         // make sure we are using the correct 'baseVertex'. This parameter does not exist for the
452         // direct drawElements.
453         gl::IndexRange indexRange;
454         ANGLE_TRY(context->getState().getVertexArray()->getIndexRange(context, type, cmd->count,
455                                                                       indices, &indexRange));
456 
457         GLint startVertex;
458         ANGLE_TRY(ComputeStartVertex(GetImplAs<Context11>(context), indexRange, cmd->baseVertex,
459                                      &startVertex));
460 
461         ANGLE_TRY(mRenderer->getStateManager()->updateState(
462             context, mode, startVertex, cmd->count, type, indices, cmd->primCount, cmd->baseVertex,
463             cmd->baseInstance, true));
464         return mRenderer->drawElements(context, mode, static_cast<GLint>(indexRange.start),
465                                        cmd->count, type, indices, cmd->primCount, 0, 0);
466     }
467     else
468     {
469         ANGLE_TRY(mRenderer->getStateManager()->updateState(context, mode, 0, 0, type, nullptr, 0,
470                                                             0, 0, true));
471         return mRenderer->drawElementsIndirect(context, indirect);
472     }
473 }
474 
475 #define DRAW_ARRAYS__                                                                          \
476     {                                                                                          \
477         ANGLE_TRY(mRenderer->getStateManager()->updateState(                                   \
478             context, mode, firsts[drawID], counts[drawID], gl::DrawElementsType::InvalidEnum,  \
479             nullptr, 0, 0, 0, false));                                                         \
480         ANGLE_TRY(mRenderer->drawArrays(context, mode, firsts[drawID], counts[drawID], 0, 0)); \
481     }
482 #define DRAW_ARRAYS_INSTANCED_                                                                \
483     {                                                                                         \
484         ANGLE_TRY(mRenderer->getStateManager()->updateState(                                  \
485             context, mode, firsts[drawID], counts[drawID], gl::DrawElementsType::InvalidEnum, \
486             nullptr, instanceCounts[drawID], 0, 0, false));                                   \
487         ANGLE_TRY(mRenderer->drawArrays(context, mode, firsts[drawID], counts[drawID],        \
488                                         instanceCounts[drawID], 0));                          \
489     }
490 #define DRAW_ARRAYS_INSTANCED_BASE_INSTANCE                                                   \
491     {                                                                                         \
492         ANGLE_TRY(mRenderer->getStateManager()->updateState(                                  \
493             context, mode, firsts[drawID], counts[drawID], gl::DrawElementsType::InvalidEnum, \
494             nullptr, instanceCounts[drawID], 0, baseInstances[drawID], false));               \
495         ANGLE_TRY(mRenderer->drawArrays(context, mode, firsts[drawID], counts[drawID],        \
496                                         instanceCounts[drawID], baseInstances[drawID]));      \
497     }
498 #define DRAW_ELEMENTS__                                                                           \
499     {                                                                                             \
500         ANGLE_TRY(drawElementsImpl(context, mode, counts[drawID], type, indices[drawID], 0, 0, 0, \
501                                    false));                                                       \
502     }
503 #define DRAW_ELEMENTS_INSTANCED_                                                         \
504     {                                                                                    \
505         ANGLE_TRY(drawElementsImpl(context, mode, counts[drawID], type, indices[drawID], \
506                                    instanceCounts[drawID], 0, 0, false));                \
507     }
508 #define DRAW_ELEMENTS_INSTANCED_BASE_VERTEX_BASE_INSTANCE                                \
509     {                                                                                    \
510         ANGLE_TRY(drawElementsImpl(context, mode, counts[drawID], type, indices[drawID], \
511                                    instanceCounts[drawID], baseVertices[drawID],         \
512                                    baseInstances[drawID], false));                       \
513     }
514 
515 #define DRAW_CALL(drawType, instanced, bvbi) DRAW_##drawType##instanced##bvbi
516 
517 #define MULTI_DRAW_BLOCK(drawType, instanced, bvbi, hasDrawID, hasBaseVertex, hasBaseInstance) \
518     for (GLsizei drawID = 0; drawID < drawcount; ++drawID)                                     \
519     {                                                                                          \
520         if (ANGLE_NOOP_DRAW(instanced))                                                        \
521         {                                                                                      \
522             continue;                                                                          \
523         }                                                                                      \
524         ANGLE_SET_DRAW_ID_UNIFORM(hasDrawID)(drawID);                                          \
525         ANGLE_SET_BASE_VERTEX_UNIFORM(hasBaseVertex)(baseVertices[drawID]);                    \
526         ANGLE_SET_BASE_INSTANCE_UNIFORM(hasBaseInstance)(baseInstances[drawID]);               \
527         ASSERT(counts[drawID] > 0);                                                            \
528         DRAW_CALL(drawType, instanced, bvbi);                                                  \
529         ANGLE_MARK_TRANSFORM_FEEDBACK_USAGE(instanced);                                        \
530         gl::MarkShaderStorageUsage(context);                                                   \
531     }
532 
multiDrawArrays(const gl::Context * context,gl::PrimitiveMode mode,const GLint * firsts,const GLsizei * counts,GLsizei drawcount)533 angle::Result Context11::multiDrawArrays(const gl::Context *context,
534                                          gl::PrimitiveMode mode,
535                                          const GLint *firsts,
536                                          const GLsizei *counts,
537                                          GLsizei drawcount)
538 {
539     gl::Program *programObject = context->getState().getLinkedProgram(context);
540     const bool hasDrawID       = programObject && programObject->hasDrawIDUniform();
541     if (hasDrawID)
542     {
543         MULTI_DRAW_BLOCK(ARRAYS, _, _, 1, 0, 0)
544     }
545     else
546     {
547         MULTI_DRAW_BLOCK(ARRAYS, _, _, 0, 0, 0)
548     }
549 
550     return angle::Result::Continue;
551 }
552 
multiDrawArraysInstanced(const gl::Context * context,gl::PrimitiveMode mode,const GLint * firsts,const GLsizei * counts,const GLsizei * instanceCounts,GLsizei drawcount)553 angle::Result Context11::multiDrawArraysInstanced(const gl::Context *context,
554                                                   gl::PrimitiveMode mode,
555                                                   const GLint *firsts,
556                                                   const GLsizei *counts,
557                                                   const GLsizei *instanceCounts,
558                                                   GLsizei drawcount)
559 {
560     gl::Program *programObject = context->getState().getLinkedProgram(context);
561     const bool hasDrawID       = programObject && programObject->hasDrawIDUniform();
562     if (hasDrawID)
563     {
564         MULTI_DRAW_BLOCK(ARRAYS, _INSTANCED, _, 1, 0, 0)
565     }
566     else
567     {
568         MULTI_DRAW_BLOCK(ARRAYS, _INSTANCED, _, 0, 0, 0)
569     }
570 
571     return angle::Result::Continue;
572 }
573 
multiDrawElements(const gl::Context * context,gl::PrimitiveMode mode,const GLsizei * counts,gl::DrawElementsType type,const GLvoid * const * indices,GLsizei drawcount)574 angle::Result Context11::multiDrawElements(const gl::Context *context,
575                                            gl::PrimitiveMode mode,
576                                            const GLsizei *counts,
577                                            gl::DrawElementsType type,
578                                            const GLvoid *const *indices,
579                                            GLsizei drawcount)
580 {
581     gl::Program *programObject = context->getState().getLinkedProgram(context);
582     const bool hasDrawID       = programObject && programObject->hasDrawIDUniform();
583     if (hasDrawID)
584     {
585         MULTI_DRAW_BLOCK(ELEMENTS, _, _, 1, 0, 0)
586     }
587     else
588     {
589         MULTI_DRAW_BLOCK(ELEMENTS, _, _, 0, 0, 0)
590     }
591 
592     return angle::Result::Continue;
593 }
594 
multiDrawElementsInstanced(const gl::Context * context,gl::PrimitiveMode mode,const GLsizei * counts,gl::DrawElementsType type,const GLvoid * const * indices,const GLsizei * instanceCounts,GLsizei drawcount)595 angle::Result Context11::multiDrawElementsInstanced(const gl::Context *context,
596                                                     gl::PrimitiveMode mode,
597                                                     const GLsizei *counts,
598                                                     gl::DrawElementsType type,
599                                                     const GLvoid *const *indices,
600                                                     const GLsizei *instanceCounts,
601                                                     GLsizei drawcount)
602 {
603     gl::Program *programObject = context->getState().getLinkedProgram(context);
604     const bool hasDrawID       = programObject && programObject->hasDrawIDUniform();
605     if (hasDrawID)
606     {
607         MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _, 1, 0, 0)
608     }
609     else
610     {
611         MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _, 0, 0, 0)
612     }
613 
614     return angle::Result::Continue;
615 }
616 
multiDrawArraysInstancedBaseInstance(const gl::Context * context,gl::PrimitiveMode mode,const GLint * firsts,const GLsizei * counts,const GLsizei * instanceCounts,const GLuint * baseInstances,GLsizei drawcount)617 angle::Result Context11::multiDrawArraysInstancedBaseInstance(const gl::Context *context,
618                                                               gl::PrimitiveMode mode,
619                                                               const GLint *firsts,
620                                                               const GLsizei *counts,
621                                                               const GLsizei *instanceCounts,
622                                                               const GLuint *baseInstances,
623                                                               GLsizei drawcount)
624 {
625     gl::Program *programObject = context->getState().getLinkedProgram(context);
626     const bool hasDrawID       = programObject && programObject->hasDrawIDUniform();
627     const bool hasBaseInstance = programObject && programObject->hasBaseInstanceUniform();
628     ResetBaseVertexBaseInstance resetUniforms(programObject, false, hasBaseInstance);
629 
630     if (hasDrawID && hasBaseInstance)
631     {
632         MULTI_DRAW_BLOCK(ARRAYS, _INSTANCED, _BASE_INSTANCE, 1, 0, 1)
633     }
634     else if (hasDrawID)
635     {
636         MULTI_DRAW_BLOCK(ARRAYS, _INSTANCED, _BASE_INSTANCE, 1, 0, 0)
637     }
638     else if (hasBaseInstance)
639     {
640         MULTI_DRAW_BLOCK(ARRAYS, _INSTANCED, _BASE_INSTANCE, 0, 0, 1)
641     }
642     else
643     {
644         MULTI_DRAW_BLOCK(ARRAYS, _INSTANCED, _BASE_INSTANCE, 0, 0, 0)
645     }
646 
647     return angle::Result::Continue;
648 }
649 
multiDrawElementsInstancedBaseVertexBaseInstance(const gl::Context * context,gl::PrimitiveMode mode,const GLsizei * counts,gl::DrawElementsType type,const GLvoid * const * indices,const GLsizei * instanceCounts,const GLint * baseVertices,const GLuint * baseInstances,GLsizei drawcount)650 angle::Result Context11::multiDrawElementsInstancedBaseVertexBaseInstance(
651     const gl::Context *context,
652     gl::PrimitiveMode mode,
653     const GLsizei *counts,
654     gl::DrawElementsType type,
655     const GLvoid *const *indices,
656     const GLsizei *instanceCounts,
657     const GLint *baseVertices,
658     const GLuint *baseInstances,
659     GLsizei drawcount)
660 {
661     gl::Program *programObject = context->getState().getLinkedProgram(context);
662     const bool hasDrawID       = programObject && programObject->hasDrawIDUniform();
663     const bool hasBaseVertex   = programObject && programObject->hasBaseVertexUniform();
664     const bool hasBaseInstance = programObject && programObject->hasBaseInstanceUniform();
665     ResetBaseVertexBaseInstance resetUniforms(programObject, hasBaseVertex, hasBaseInstance);
666 
667     if (hasDrawID)
668     {
669         if (hasBaseVertex)
670         {
671             if (hasBaseInstance)
672             {
673                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 1, 1, 1)
674             }
675             else
676             {
677                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 1, 1, 0)
678             }
679         }
680         else
681         {
682             if (hasBaseInstance)
683             {
684                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 1, 0, 1)
685             }
686             else
687             {
688                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 1, 0, 0)
689             }
690         }
691     }
692     else
693     {
694         if (hasBaseVertex)
695         {
696             if (hasBaseInstance)
697             {
698                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 0, 1, 1)
699             }
700             else
701             {
702                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 0, 1, 0)
703             }
704         }
705         else
706         {
707             if (hasBaseInstance)
708             {
709                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 0, 0, 1)
710             }
711             else
712             {
713                 MULTI_DRAW_BLOCK(ELEMENTS, _INSTANCED, _BASE_VERTEX_BASE_INSTANCE, 0, 0, 0)
714             }
715         }
716     }
717 
718     return angle::Result::Continue;
719 }
720 
getResetStatus()721 gl::GraphicsResetStatus Context11::getResetStatus()
722 {
723     return mRenderer->getResetStatus();
724 }
725 
insertEventMarker(GLsizei length,const char * marker)726 angle::Result Context11::insertEventMarker(GLsizei length, const char *marker)
727 {
728     mRenderer->getAnnotator()->setMarker(marker);
729     return angle::Result::Continue;
730 }
731 
pushGroupMarker(GLsizei length,const char * marker)732 angle::Result Context11::pushGroupMarker(GLsizei length, const char *marker)
733 {
734     mRenderer->getAnnotator()->beginEvent(nullptr, angle::EntryPoint::GLPushGroupMarkerEXT, marker,
735                                           marker);
736     mMarkerStack.push(std::string(marker));
737     return angle::Result::Continue;
738 }
739 
popGroupMarker()740 angle::Result Context11::popGroupMarker()
741 {
742     const char *marker = nullptr;
743     if (!mMarkerStack.empty())
744     {
745         marker = mMarkerStack.top().c_str();
746         mMarkerStack.pop();
747         mRenderer->getAnnotator()->endEvent(nullptr, marker,
748                                             angle::EntryPoint::GLPopGroupMarkerEXT);
749     }
750     return angle::Result::Continue;
751 }
752 
pushDebugGroup(const gl::Context * context,GLenum source,GLuint id,const std::string & message)753 angle::Result Context11::pushDebugGroup(const gl::Context *context,
754                                         GLenum source,
755                                         GLuint id,
756                                         const std::string &message)
757 {
758     // Fall through to the EXT_debug_marker functions
759     return pushGroupMarker(static_cast<GLsizei>(message.size()), message.c_str());
760 }
761 
popDebugGroup(const gl::Context * context)762 angle::Result Context11::popDebugGroup(const gl::Context *context)
763 {
764     // Fall through to the EXT_debug_marker functions
765     return popGroupMarker();
766 }
767 
syncState(const gl::Context * context,const gl::State::DirtyBits & dirtyBits,const gl::State::DirtyBits & bitMask)768 angle::Result Context11::syncState(const gl::Context *context,
769                                    const gl::State::DirtyBits &dirtyBits,
770                                    const gl::State::DirtyBits &bitMask)
771 {
772     mRenderer->getStateManager()->syncState(context, dirtyBits);
773     return angle::Result::Continue;
774 }
775 
getGPUDisjoint()776 GLint Context11::getGPUDisjoint()
777 {
778     return mRenderer->getGPUDisjoint();
779 }
780 
getTimestamp()781 GLint64 Context11::getTimestamp()
782 {
783     return mRenderer->getTimestamp();
784 }
785 
onMakeCurrent(const gl::Context * context)786 angle::Result Context11::onMakeCurrent(const gl::Context *context)
787 {
788     return mRenderer->getStateManager()->onMakeCurrent(context);
789 }
790 
getNativeCaps() const791 gl::Caps Context11::getNativeCaps() const
792 {
793     gl::Caps caps = mRenderer->getNativeCaps();
794 
795     // For pixel shaders, the render targets and unordered access views share the same resource
796     // slots, so the maximum number of fragment shader outputs depends on the current context
797     // version:
798     // - If current context is ES 3.0 and below, we use D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT(8)
799     //   as the value of max draw buffers because UAVs are not used.
800     // - If current context is ES 3.1 and the feature level is 11_0, the RTVs and UAVs share 8
801     //   slots. As ES 3.1 requires at least 1 atomic counter buffer in compute shaders, the value
802     //   of max combined shader output resources is limited to 7, thus only 7 RTV slots can be
803     //   used simultaneously.
804     // - If current context is ES 3.1 and the feature level is 11_1, the RTVs and UAVs share 64
805     //   slots. Currently we allocate 60 slots for combined shader output resources, so we can use
806     //   at most D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT(8) RTVs simultaneously.
807     if (mState.getClientVersion() >= gl::ES_3_1 &&
808         mRenderer->getRenderer11DeviceCaps().featureLevel == D3D_FEATURE_LEVEL_11_0)
809     {
810         caps.maxDrawBuffers      = caps.maxCombinedShaderOutputResources;
811         caps.maxColorAttachments = caps.maxCombinedShaderOutputResources;
812     }
813 
814     return caps;
815 }
816 
getNativeTextureCaps() const817 const gl::TextureCapsMap &Context11::getNativeTextureCaps() const
818 {
819     return mRenderer->getNativeTextureCaps();
820 }
821 
getNativeExtensions() const822 const gl::Extensions &Context11::getNativeExtensions() const
823 {
824     return mRenderer->getNativeExtensions();
825 }
826 
getNativeLimitations() const827 const gl::Limitations &Context11::getNativeLimitations() const
828 {
829     return mRenderer->getNativeLimitations();
830 }
831 
dispatchCompute(const gl::Context * context,GLuint numGroupsX,GLuint numGroupsY,GLuint numGroupsZ)832 angle::Result Context11::dispatchCompute(const gl::Context *context,
833                                          GLuint numGroupsX,
834                                          GLuint numGroupsY,
835                                          GLuint numGroupsZ)
836 {
837     return mRenderer->dispatchCompute(context, numGroupsX, numGroupsY, numGroupsZ);
838 }
839 
dispatchComputeIndirect(const gl::Context * context,GLintptr indirect)840 angle::Result Context11::dispatchComputeIndirect(const gl::Context *context, GLintptr indirect)
841 {
842     return mRenderer->dispatchComputeIndirect(context, indirect);
843 }
844 
triggerDrawCallProgramRecompilation(const gl::Context * context,gl::PrimitiveMode drawMode)845 angle::Result Context11::triggerDrawCallProgramRecompilation(const gl::Context *context,
846                                                              gl::PrimitiveMode drawMode)
847 {
848     const auto &glState    = context->getState();
849     const auto *va11       = GetImplAs<VertexArray11>(glState.getVertexArray());
850     const auto *drawFBO    = glState.getDrawFramebuffer();
851     gl::Program *program   = glState.getProgram();
852     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program);
853 
854     programD3D->updateCachedInputLayout(va11->getCurrentStateSerial(), glState);
855     programD3D->updateCachedOutputLayout(context, drawFBO);
856 
857     bool recompileVS = !programD3D->hasVertexExecutableForCachedInputLayout();
858     bool recompileGS = !programD3D->hasGeometryExecutableForPrimitiveType(glState, drawMode);
859     bool recompilePS = !programD3D->hasPixelExecutableForCachedOutputLayout();
860 
861     if (!recompileVS && !recompileGS && !recompilePS)
862     {
863         return angle::Result::Continue;
864     }
865 
866     // Load the compiler if necessary and recompile the programs.
867     ANGLE_TRY(mRenderer->ensureHLSLCompilerInitialized(this));
868 
869     gl::InfoLog infoLog;
870 
871     if (recompileVS)
872     {
873         ShaderExecutableD3D *vertexExe = nullptr;
874         ANGLE_TRY(programD3D->getVertexExecutableForCachedInputLayout(this, &vertexExe, &infoLog));
875         if (!programD3D->hasVertexExecutableForCachedInputLayout())
876         {
877             ASSERT(infoLog.getLength() > 0);
878             ERR() << "Error compiling dynamic vertex executable: " << infoLog.str();
879             ANGLE_TRY_HR(this, E_FAIL, "Error compiling dynamic vertex executable");
880         }
881     }
882 
883     if (recompileGS)
884     {
885         ShaderExecutableD3D *geometryExe = nullptr;
886         ANGLE_TRY(programD3D->getGeometryExecutableForPrimitiveType(this, glState, drawMode,
887                                                                     &geometryExe, &infoLog));
888         if (!programD3D->hasGeometryExecutableForPrimitiveType(glState, drawMode))
889         {
890             ASSERT(infoLog.getLength() > 0);
891             ERR() << "Error compiling dynamic geometry executable: " << infoLog.str();
892             ANGLE_TRY_HR(this, E_FAIL, "Error compiling dynamic geometry executable");
893         }
894     }
895 
896     if (recompilePS)
897     {
898         ShaderExecutableD3D *pixelExe = nullptr;
899         ANGLE_TRY(programD3D->getPixelExecutableForCachedOutputLayout(this, &pixelExe, &infoLog));
900         if (!programD3D->hasPixelExecutableForCachedOutputLayout())
901         {
902             ASSERT(infoLog.getLength() > 0);
903             ERR() << "Error compiling dynamic pixel executable: " << infoLog.str();
904             ANGLE_TRY_HR(this, E_FAIL, "Error compiling dynamic pixel executable");
905         }
906     }
907 
908     // Refresh the program cache entry.
909     if (mMemoryProgramCache)
910     {
911         ANGLE_TRY(mMemoryProgramCache->updateProgram(context, program));
912     }
913 
914     return angle::Result::Continue;
915 }
916 
triggerDispatchCallProgramRecompilation(const gl::Context * context)917 angle::Result Context11::triggerDispatchCallProgramRecompilation(const gl::Context *context)
918 {
919     const auto &glState    = context->getState();
920     gl::Program *program   = glState.getProgram();
921     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program);
922 
923     programD3D->updateCachedComputeImage2DBindLayout(context);
924 
925     bool recompileCS = !programD3D->hasComputeExecutableForCachedImage2DBindLayout();
926 
927     if (!recompileCS)
928     {
929         return angle::Result::Continue;
930     }
931 
932     // Load the compiler if necessary and recompile the programs.
933     ANGLE_TRY(mRenderer->ensureHLSLCompilerInitialized(this));
934 
935     gl::InfoLog infoLog;
936 
937     ShaderExecutableD3D *computeExe = nullptr;
938     ANGLE_TRY(programD3D->getComputeExecutableForImage2DBindLayout(this, &computeExe, &infoLog));
939     if (!programD3D->hasComputeExecutableForCachedImage2DBindLayout())
940     {
941         ASSERT(infoLog.getLength() > 0);
942         ERR() << "Dynamic recompilation error log: " << infoLog.str();
943         ANGLE_TRY_HR(this, E_FAIL, "Error compiling dynamic compute executable");
944     }
945 
946     // Refresh the program cache entry.
947     if (mMemoryProgramCache)
948     {
949         ANGLE_TRY(mMemoryProgramCache->updateProgram(context, program));
950     }
951 
952     return angle::Result::Continue;
953 }
954 
memoryBarrier(const gl::Context * context,GLbitfield barriers)955 angle::Result Context11::memoryBarrier(const gl::Context *context, GLbitfield barriers)
956 {
957     return angle::Result::Continue;
958 }
959 
memoryBarrierByRegion(const gl::Context * context,GLbitfield barriers)960 angle::Result Context11::memoryBarrierByRegion(const gl::Context *context, GLbitfield barriers)
961 {
962     return angle::Result::Continue;
963 }
964 
getIncompleteTexture(const gl::Context * context,gl::TextureType type,gl::Texture ** textureOut)965 angle::Result Context11::getIncompleteTexture(const gl::Context *context,
966                                               gl::TextureType type,
967                                               gl::Texture **textureOut)
968 {
969     return mIncompleteTextures.getIncompleteTexture(context, type, gl::SamplerFormat::Float, this,
970                                                     textureOut);
971 }
972 
initializeMultisampleTextureToBlack(const gl::Context * context,gl::Texture * glTexture)973 angle::Result Context11::initializeMultisampleTextureToBlack(const gl::Context *context,
974                                                              gl::Texture *glTexture)
975 {
976     ASSERT(glTexture->getType() == gl::TextureType::_2DMultisample);
977     TextureD3D *textureD3D        = GetImplAs<TextureD3D>(glTexture);
978     gl::ImageIndex index          = gl::ImageIndex::Make2DMultisample();
979     RenderTargetD3D *renderTarget = nullptr;
980     GLsizei texSamples            = textureD3D->getRenderToTextureSamples();
981     ANGLE_TRY(textureD3D->getRenderTarget(context, index, texSamples, &renderTarget));
982     return mRenderer->clearRenderTarget(context, renderTarget, gl::ColorF(0.0f, 0.0f, 0.0f, 1.0f),
983                                         1.0f, 0);
984 }
985 
handleResult(HRESULT hr,const char * message,const char * file,const char * function,unsigned int line)986 void Context11::handleResult(HRESULT hr,
987                              const char *message,
988                              const char *file,
989                              const char *function,
990                              unsigned int line)
991 {
992     ASSERT(FAILED(hr));
993 
994     GLenum glErrorCode = DefaultGLErrorCode(hr);
995 
996     std::stringstream errorStream;
997     errorStream << "Internal D3D11 error: " << gl::FmtHR(hr);
998 
999     if (d3d11::isDeviceLostError(hr))
1000     {
1001         HRESULT removalReason = mRenderer->getDevice()->GetDeviceRemovedReason();
1002         errorStream << " (removal reason: " << gl::FmtHR(removalReason) << ")";
1003         mRenderer->notifyDeviceLost();
1004     }
1005 
1006     errorStream << ": " << message;
1007 
1008     mErrors->handleError(glErrorCode, errorStream.str().c_str(), file, function, line);
1009 }
1010 }  // namespace rx
1011