• 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 // Renderer9.cpp: Implements a back-end specific class for the D3D9 renderer.
8 
9 #include "libANGLE/renderer/d3d/d3d9/Renderer9.h"
10 
11 #include <EGL/eglext.h>
12 #include <sstream>
13 
14 #include "common/utilities.h"
15 #include "libANGLE/Buffer.h"
16 #include "libANGLE/Context.h"
17 #include "libANGLE/Display.h"
18 #include "libANGLE/Framebuffer.h"
19 #include "libANGLE/FramebufferAttachment.h"
20 #include "libANGLE/Program.h"
21 #include "libANGLE/Renderbuffer.h"
22 #include "libANGLE/State.h"
23 #include "libANGLE/Surface.h"
24 #include "libANGLE/Texture.h"
25 #include "libANGLE/angletypes.h"
26 #include "libANGLE/features.h"
27 #include "libANGLE/formatutils.h"
28 #include "libANGLE/renderer/d3d/CompilerD3D.h"
29 #include "libANGLE/renderer/d3d/DeviceD3D.h"
30 #include "libANGLE/renderer/d3d/DisplayD3D.h"
31 #include "libANGLE/renderer/d3d/FramebufferD3D.h"
32 #include "libANGLE/renderer/d3d/IndexDataManager.h"
33 #include "libANGLE/renderer/d3d/ProgramD3D.h"
34 #include "libANGLE/renderer/d3d/RenderbufferD3D.h"
35 #include "libANGLE/renderer/d3d/ShaderD3D.h"
36 #include "libANGLE/renderer/d3d/SurfaceD3D.h"
37 #include "libANGLE/renderer/d3d/TextureD3D.h"
38 #include "libANGLE/renderer/d3d/d3d9/Blit9.h"
39 #include "libANGLE/renderer/d3d/d3d9/Buffer9.h"
40 #include "libANGLE/renderer/d3d/d3d9/Context9.h"
41 #include "libANGLE/renderer/d3d/d3d9/Fence9.h"
42 #include "libANGLE/renderer/d3d/d3d9/Framebuffer9.h"
43 #include "libANGLE/renderer/d3d/d3d9/Image9.h"
44 #include "libANGLE/renderer/d3d/d3d9/IndexBuffer9.h"
45 #include "libANGLE/renderer/d3d/d3d9/NativeWindow9.h"
46 #include "libANGLE/renderer/d3d/d3d9/Query9.h"
47 #include "libANGLE/renderer/d3d/d3d9/RenderTarget9.h"
48 #include "libANGLE/renderer/d3d/d3d9/ShaderExecutable9.h"
49 #include "libANGLE/renderer/d3d/d3d9/SwapChain9.h"
50 #include "libANGLE/renderer/d3d/d3d9/TextureStorage9.h"
51 #include "libANGLE/renderer/d3d/d3d9/VertexArray9.h"
52 #include "libANGLE/renderer/d3d/d3d9/VertexBuffer9.h"
53 #include "libANGLE/renderer/d3d/d3d9/formatutils9.h"
54 #include "libANGLE/renderer/d3d/d3d9/renderer9_utils.h"
55 #include "libANGLE/renderer/d3d/driver_utils_d3d.h"
56 #include "libANGLE/renderer/driver_utils.h"
57 #include "libANGLE/trace.h"
58 
59 #if !defined(ANGLE_COMPILE_OPTIMIZATION_LEVEL)
60 #    define ANGLE_COMPILE_OPTIMIZATION_LEVEL D3DCOMPILE_OPTIMIZATION_LEVEL3
61 #endif
62 
63 // Enable ANGLE_SUPPORT_SHADER_MODEL_2 if you wish devices with only shader model 2.
64 // Such a device would not be conformant.
65 #ifndef ANGLE_SUPPORT_SHADER_MODEL_2
66 #    define ANGLE_SUPPORT_SHADER_MODEL_2 0
67 #endif
68 
69 namespace rx
70 {
71 
72 namespace
73 {
74 enum
75 {
76     MAX_VERTEX_CONSTANT_VECTORS_D3D9 = 256,
77     MAX_PIXEL_CONSTANT_VECTORS_SM2   = 32,
78     MAX_PIXEL_CONSTANT_VECTORS_SM3   = 224,
79     MAX_VARYING_VECTORS_SM2          = 8,
80     MAX_VARYING_VECTORS_SM3          = 10,
81 
82     MAX_TEXTURE_IMAGE_UNITS_VTF_SM3 = 4
83 };
84 
85 template <typename T>
DrawPoints(IDirect3DDevice9 * device,GLsizei count,const void * indices,int minIndex)86 static void DrawPoints(IDirect3DDevice9 *device, GLsizei count, const void *indices, int minIndex)
87 {
88     for (int i = 0; i < count; i++)
89     {
90         unsigned int indexValue =
91             static_cast<unsigned int>(static_cast<const T *>(indices)[i]) - minIndex;
92         device->DrawPrimitive(D3DPT_POINTLIST, indexValue, 1);
93     }
94 }
95 
96 // A hard limit on buffer size. This works around a problem in the NVIDIA drivers where buffer sizes
97 // close to MAX_UINT would give undefined results. The limit of MAX_UINT/2 should be generous enough
98 // for almost any demanding application.
99 constexpr UINT kMaximumBufferSizeHardLimit = std::numeric_limits<UINT>::max() >> 1;
100 }  // anonymous namespace
101 
Renderer9(egl::Display * display)102 Renderer9::Renderer9(egl::Display *display) : RendererD3D(display), mStateManager(this)
103 {
104     mD3d9Module = nullptr;
105 
106     mD3d9         = nullptr;
107     mD3d9Ex       = nullptr;
108     mDevice       = nullptr;
109     mDeviceEx     = nullptr;
110     mDeviceWindow = nullptr;
111     mBlit         = nullptr;
112 
113     mAdapter = D3DADAPTER_DEFAULT;
114 
115     const egl::AttributeMap &attributes = display->getAttributeMap();
116     EGLint requestedDeviceType          = static_cast<EGLint>(attributes.get(
117         EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE));
118     switch (requestedDeviceType)
119     {
120         case EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE:
121             mDeviceType = D3DDEVTYPE_HAL;
122             break;
123 
124         case EGL_PLATFORM_ANGLE_DEVICE_TYPE_D3D_REFERENCE_ANGLE:
125             mDeviceType = D3DDEVTYPE_REF;
126             break;
127 
128         case EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE:
129             mDeviceType = D3DDEVTYPE_NULLREF;
130             break;
131 
132         default:
133             UNREACHABLE();
134     }
135 
136     mMaskedClearSavedState = nullptr;
137 
138     mVertexDataManager = nullptr;
139     mIndexDataManager  = nullptr;
140     mLineLoopIB        = nullptr;
141     mCountingIB        = nullptr;
142 
143     mMaxNullColorbufferLRU = 0;
144     for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
145     {
146         mNullRenderTargetCache[i].lruCount     = 0;
147         mNullRenderTargetCache[i].width        = 0;
148         mNullRenderTargetCache[i].height       = 0;
149         mNullRenderTargetCache[i].renderTarget = nullptr;
150     }
151 
152     mAppliedVertexShader  = nullptr;
153     mAppliedPixelShader   = nullptr;
154     mAppliedProgramSerial = 0;
155 
156     gl::InitializeDebugAnnotations(&mAnnotator);
157 }
158 
setGlobalDebugAnnotator()159 void Renderer9::setGlobalDebugAnnotator()
160 {
161     gl::InitializeDebugAnnotations(&mAnnotator);
162 }
163 
~Renderer9()164 Renderer9::~Renderer9()
165 {
166     if (mDevice)
167     {
168         // If the device is lost, reset it first to prevent leaving the driver in an unstable state
169         if (testDeviceLost())
170         {
171             resetDevice();
172         }
173     }
174 
175     release();
176 }
177 
release()178 void Renderer9::release()
179 {
180     gl::UninitializeDebugAnnotations();
181 
182     mTranslatedAttribCache.clear();
183 
184     releaseDeviceResources();
185 
186     SafeRelease(mDevice);
187     SafeRelease(mDeviceEx);
188     SafeRelease(mD3d9);
189     SafeRelease(mD3d9Ex);
190 
191     mCompiler.release();
192 
193     if (mDeviceWindow)
194     {
195         DestroyWindow(mDeviceWindow);
196         mDeviceWindow = nullptr;
197     }
198 
199     mD3d9Module = nullptr;
200 }
201 
initialize()202 egl::Error Renderer9::initialize()
203 {
204     ANGLE_TRACE_EVENT0("gpu.angle", "GetModuleHandle_d3d9");
205     mD3d9Module = ::LoadLibrary(TEXT("d3d9.dll"));
206 
207     if (mD3d9Module == nullptr)
208     {
209         return egl::EglNotInitialized(D3D9_INIT_MISSING_DEP) << "No D3D9 module found.";
210     }
211 
212     typedef HRESULT(WINAPI * Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex **);
213     Direct3DCreate9ExFunc Direct3DCreate9ExPtr =
214         reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
215 
216     // Use Direct3D9Ex if available. Among other things, this version is less
217     // inclined to report a lost context, for example when the user switches
218     // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are
219     // available.
220     if (ANGLE_D3D9EX == ANGLE_ENABLED && Direct3DCreate9ExPtr &&
221         SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
222     {
223         ANGLE_TRACE_EVENT0("gpu.angle", "D3d9Ex_QueryInterface");
224         ASSERT(mD3d9Ex);
225         mD3d9Ex->QueryInterface(__uuidof(IDirect3D9), reinterpret_cast<void **>(&mD3d9));
226         ASSERT(mD3d9);
227     }
228     else
229     {
230         ANGLE_TRACE_EVENT0("gpu.angle", "Direct3DCreate9");
231         mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
232     }
233 
234     if (!mD3d9)
235     {
236         return egl::EglNotInitialized(D3D9_INIT_MISSING_DEP) << "Could not create D3D9 device.";
237     }
238 
239     if (mDisplay->getNativeDisplayId() != nullptr)
240     {
241         //  UNIMPLEMENTED();   // FIXME: Determine which adapter index the device context
242         //  corresponds to
243     }
244 
245     HRESULT result;
246 
247     // Give up on getting device caps after about one second.
248     {
249         ANGLE_TRACE_EVENT0("gpu.angle", "GetDeviceCaps");
250         for (int i = 0; i < 10; ++i)
251         {
252             result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
253             if (SUCCEEDED(result))
254             {
255                 break;
256             }
257             else if (result == D3DERR_NOTAVAILABLE)
258             {
259                 Sleep(100);  // Give the driver some time to initialize/recover
260             }
261             else if (FAILED(result))  // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY,
262                                       // D3DERR_INVALIDDEVICE, or another error we can't recover
263                                       // from
264             {
265                 return egl::EglNotInitialized(D3D9_INIT_OTHER_ERROR)
266                        << "Failed to get device caps, " << gl::FmtHR(result);
267             }
268         }
269     }
270 
271 #if ANGLE_SUPPORT_SHADER_MODEL_2
272     size_t minShaderModel = 2;
273 #else
274     size_t minShaderModel = 3;
275 #endif
276 
277     if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(minShaderModel, 0))
278     {
279         return egl::EglNotInitialized(D3D9_INIT_UNSUPPORTED_VERSION)
280                << "Renderer does not support PS " << minShaderModel << ".0, aborting!";
281     }
282 
283     // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture
284     // to a render target texture is not supported. This is required by
285     // Texture2D::ensureRenderTarget.
286     if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
287     {
288         return egl::EglNotInitialized(D3D9_INIT_UNSUPPORTED_STRETCHRECT)
289                << "Renderer does not support StretctRect from textures.";
290     }
291 
292     {
293         ANGLE_TRACE_EVENT0("gpu.angle", "GetAdapterIdentifier");
294         mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
295     }
296 
297     static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
298     static const TCHAR className[]  = TEXT("STATIC");
299 
300     {
301         ANGLE_TRACE_EVENT0("gpu.angle", "CreateWindowEx");
302         mDeviceWindow =
303             CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1,
304                            1, HWND_MESSAGE, nullptr, GetModuleHandle(nullptr), nullptr);
305     }
306 
307     D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
308     DWORD behaviorFlags =
309         D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES | D3DCREATE_MULTITHREADED;
310 
311     {
312         ANGLE_TRACE_EVENT0("gpu.angle", "D3d9_CreateDevice");
313         result = mD3d9->CreateDevice(
314             mAdapter, mDeviceType, mDeviceWindow,
315             behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE,
316             &presentParameters, &mDevice);
317 
318         if (FAILED(result))
319         {
320             ERR() << "CreateDevice1 failed: (" << gl::FmtHR(result) << ")";
321         }
322     }
323     if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
324     {
325         return egl::EglBadAlloc(D3D9_INIT_OUT_OF_MEMORY)
326                << "CreateDevice failed: device lost or out of memory (" << gl::FmtHR(result) << ")";
327     }
328 
329     if (FAILED(result))
330     {
331         ANGLE_TRACE_EVENT0("gpu.angle", "D3d9_CreateDevice2");
332         result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow,
333                                      behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING,
334                                      &presentParameters, &mDevice);
335 
336         if (FAILED(result))
337         {
338             ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY ||
339                    result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
340             return egl::EglBadAlloc(D3D9_INIT_OUT_OF_MEMORY)
341                    << "CreateDevice2 failed: device lost, not available, or of out of memory ("
342                    << gl::FmtHR(result) << ")";
343         }
344     }
345 
346     if (mD3d9Ex)
347     {
348         ANGLE_TRACE_EVENT0("gpu.angle", "mDevice_QueryInterface");
349         result = mDevice->QueryInterface(__uuidof(IDirect3DDevice9Ex), (void **)&mDeviceEx);
350         ASSERT(SUCCEEDED(result));
351     }
352 
353     {
354         ANGLE_TRACE_EVENT0("gpu.angle", "ShaderCache initialize");
355         mVertexShaderCache.initialize(mDevice);
356         mPixelShaderCache.initialize(mDevice);
357     }
358 
359     D3DDISPLAYMODE currentDisplayMode;
360     mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
361 
362     // Check vertex texture support
363     // Only Direct3D 10 ready devices support all the necessary vertex texture formats.
364     // We test this using D3D9 by checking support for the R16F format.
365     mVertexTextureSupport = mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0) &&
366                             SUCCEEDED(mD3d9->CheckDeviceFormat(
367                                 mAdapter, mDeviceType, currentDisplayMode.Format,
368                                 D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F));
369 
370     ANGLE_TRY(initializeDevice());
371 
372     return egl::NoError();
373 }
374 
375 // do any one-time device initialization
376 // NOTE: this is also needed after a device lost/reset
377 // to reset the scene status and ensure the default states are reset.
initializeDevice()378 egl::Error Renderer9::initializeDevice()
379 {
380     // Permanent non-default states
381     mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
382     mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
383 
384     if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
385     {
386         mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD &)mDeviceCaps.MaxPointSize);
387     }
388     else
389     {
390         mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000);  // 1.0f
391     }
392 
393     const gl::Caps &rendererCaps = getNativeCaps();
394 
395     mCurVertexSamplerStates.resize(rendererCaps.maxShaderTextureImageUnits[gl::ShaderType::Vertex]);
396     mCurPixelSamplerStates.resize(
397         rendererCaps.maxShaderTextureImageUnits[gl::ShaderType::Fragment]);
398 
399     mCurVertexTextures.resize(rendererCaps.maxShaderTextureImageUnits[gl::ShaderType::Vertex]);
400     mCurPixelTextures.resize(rendererCaps.maxShaderTextureImageUnits[gl::ShaderType::Fragment]);
401 
402     markAllStateDirty();
403 
404     mSceneStarted = false;
405 
406     ASSERT(!mBlit);
407     mBlit = new Blit9(this);
408 
409     ASSERT(!mVertexDataManager && !mIndexDataManager);
410     mIndexDataManager = new IndexDataManager(this);
411 
412     mTranslatedAttribCache.resize(getNativeCaps().maxVertexAttributes);
413 
414     mStateManager.initialize();
415 
416     return egl::NoError();
417 }
418 
getDefaultPresentParameters()419 D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
420 {
421     D3DPRESENT_PARAMETERS presentParameters = {};
422 
423     // The default swap chain is never actually used. Surface will create a new swap chain with the
424     // proper parameters.
425     presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
426     presentParameters.BackBufferCount        = 1;
427     presentParameters.BackBufferFormat       = D3DFMT_UNKNOWN;
428     presentParameters.BackBufferWidth        = 1;
429     presentParameters.BackBufferHeight       = 1;
430     presentParameters.EnableAutoDepthStencil = FALSE;
431     presentParameters.Flags                  = 0;
432     presentParameters.hDeviceWindow          = mDeviceWindow;
433     presentParameters.MultiSampleQuality     = 0;
434     presentParameters.MultiSampleType        = D3DMULTISAMPLE_NONE;
435     presentParameters.PresentationInterval   = D3DPRESENT_INTERVAL_DEFAULT;
436     presentParameters.SwapEffect             = D3DSWAPEFFECT_DISCARD;
437     presentParameters.Windowed               = TRUE;
438 
439     return presentParameters;
440 }
441 
generateConfigs()442 egl::ConfigSet Renderer9::generateConfigs()
443 {
444     static const GLenum colorBufferFormats[] = {
445         GL_BGR5_A1_ANGLEX,
446         GL_BGRA8_EXT,
447         GL_RGB565,
448 
449     };
450 
451     static const GLenum depthStencilBufferFormats[] = {
452         GL_NONE,
453         GL_DEPTH_COMPONENT32_OES,
454         GL_DEPTH24_STENCIL8_OES,
455         GL_DEPTH_COMPONENT24_OES,
456         GL_DEPTH_COMPONENT16,
457     };
458 
459     const gl::Caps &rendererCaps                  = getNativeCaps();
460     const gl::TextureCapsMap &rendererTextureCaps = getNativeTextureCaps();
461 
462     D3DDISPLAYMODE currentDisplayMode;
463     mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
464 
465     // Determine the min and max swap intervals
466     int minSwapInterval = 4;
467     int maxSwapInterval = 0;
468 
469     if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
470     {
471         minSwapInterval = std::min(minSwapInterval, 0);
472         maxSwapInterval = std::max(maxSwapInterval, 0);
473     }
474     if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
475     {
476         minSwapInterval = std::min(minSwapInterval, 1);
477         maxSwapInterval = std::max(maxSwapInterval, 1);
478     }
479     if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
480     {
481         minSwapInterval = std::min(minSwapInterval, 2);
482         maxSwapInterval = std::max(maxSwapInterval, 2);
483     }
484     if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
485     {
486         minSwapInterval = std::min(minSwapInterval, 3);
487         maxSwapInterval = std::max(maxSwapInterval, 3);
488     }
489     if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
490     {
491         minSwapInterval = std::min(minSwapInterval, 4);
492         maxSwapInterval = std::max(maxSwapInterval, 4);
493     }
494 
495     egl::ConfigSet configs;
496     for (size_t formatIndex = 0; formatIndex < ArraySize(colorBufferFormats); formatIndex++)
497     {
498         GLenum colorBufferInternalFormat = colorBufferFormats[formatIndex];
499         const gl::TextureCaps &colorBufferFormatCaps =
500             rendererTextureCaps.get(colorBufferInternalFormat);
501         if (colorBufferFormatCaps.renderbuffer)
502         {
503             ASSERT(colorBufferFormatCaps.textureAttachment);
504             for (size_t depthStencilIndex = 0;
505                  depthStencilIndex < ArraySize(depthStencilBufferFormats); depthStencilIndex++)
506             {
507                 GLenum depthStencilBufferInternalFormat =
508                     depthStencilBufferFormats[depthStencilIndex];
509                 const gl::TextureCaps &depthStencilBufferFormatCaps =
510                     rendererTextureCaps.get(depthStencilBufferInternalFormat);
511                 if (depthStencilBufferFormatCaps.renderbuffer ||
512                     depthStencilBufferInternalFormat == GL_NONE)
513                 {
514                     ASSERT(depthStencilBufferFormatCaps.textureAttachment ||
515                            depthStencilBufferInternalFormat == GL_NONE);
516                     const gl::InternalFormat &colorBufferFormatInfo =
517                         gl::GetSizedInternalFormatInfo(colorBufferInternalFormat);
518                     const gl::InternalFormat &depthStencilBufferFormatInfo =
519                         gl::GetSizedInternalFormatInfo(depthStencilBufferInternalFormat);
520                     const d3d9::TextureFormat &d3d9ColorBufferFormatInfo =
521                         d3d9::GetTextureFormatInfo(colorBufferInternalFormat);
522 
523                     egl::Config config;
524                     config.renderTargetFormat = colorBufferInternalFormat;
525                     config.depthStencilFormat = depthStencilBufferInternalFormat;
526                     config.bufferSize         = colorBufferFormatInfo.pixelBytes * 8;
527                     config.redSize            = colorBufferFormatInfo.redBits;
528                     config.greenSize          = colorBufferFormatInfo.greenBits;
529                     config.blueSize           = colorBufferFormatInfo.blueBits;
530                     config.luminanceSize      = colorBufferFormatInfo.luminanceBits;
531                     config.alphaSize          = colorBufferFormatInfo.alphaBits;
532                     config.alphaMaskSize      = 0;
533                     config.bindToTextureRGB   = (colorBufferFormatInfo.format == GL_RGB);
534                     config.bindToTextureRGBA  = (colorBufferFormatInfo.format == GL_RGBA ||
535                                                 colorBufferFormatInfo.format == GL_BGRA_EXT);
536                     config.colorBufferType    = EGL_RGB_BUFFER;
537                     // Mark as slow if blits to the back-buffer won't be straight forward
538                     config.configCaveat =
539                         (currentDisplayMode.Format == d3d9ColorBufferFormatInfo.renderFormat)
540                             ? EGL_NONE
541                             : EGL_SLOW_CONFIG;
542                     config.configID          = static_cast<EGLint>(configs.size() + 1);
543                     config.conformant        = EGL_OPENGL_ES2_BIT;
544                     config.depthSize         = depthStencilBufferFormatInfo.depthBits;
545                     config.level             = 0;
546                     config.matchNativePixmap = EGL_NONE;
547                     config.maxPBufferWidth   = rendererCaps.max2DTextureSize;
548                     config.maxPBufferHeight  = rendererCaps.max2DTextureSize;
549                     config.maxPBufferPixels =
550                         rendererCaps.max2DTextureSize * rendererCaps.max2DTextureSize;
551                     config.maxSwapInterval  = maxSwapInterval;
552                     config.minSwapInterval  = minSwapInterval;
553                     config.nativeRenderable = EGL_FALSE;
554                     config.nativeVisualID   = 0;
555                     config.nativeVisualType = EGL_NONE;
556                     config.renderableType   = EGL_OPENGL_ES2_BIT;
557                     config.sampleBuffers    = 0;  // FIXME: enumerate multi-sampling
558                     config.samples          = 0;
559                     config.stencilSize      = depthStencilBufferFormatInfo.stencilBits;
560                     config.surfaceType =
561                         EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
562                     config.transparentType       = EGL_NONE;
563                     config.transparentRedValue   = 0;
564                     config.transparentGreenValue = 0;
565                     config.transparentBlueValue  = 0;
566                     config.colorComponentType    = gl_egl::GLComponentTypeToEGLColorComponentType(
567                         colorBufferFormatInfo.componentType);
568 
569                     configs.add(config);
570                 }
571             }
572         }
573     }
574 
575     ASSERT(configs.size() > 0);
576     return configs;
577 }
578 
generateDisplayExtensions(egl::DisplayExtensions * outExtensions) const579 void Renderer9::generateDisplayExtensions(egl::DisplayExtensions *outExtensions) const
580 {
581     outExtensions->createContextRobustness = true;
582 
583     if (getShareHandleSupport())
584     {
585         outExtensions->d3dShareHandleClientBuffer     = true;
586         outExtensions->surfaceD3DTexture2DShareHandle = true;
587     }
588     outExtensions->d3dTextureClientBuffer = true;
589 
590     outExtensions->querySurfacePointer = true;
591     outExtensions->windowFixedSize     = true;
592     outExtensions->postSubBuffer       = true;
593 
594     outExtensions->image               = true;
595     outExtensions->imageBase           = true;
596     outExtensions->glTexture2DImage    = true;
597     outExtensions->glRenderbufferImage = true;
598 
599     outExtensions->flexibleSurfaceCompatibility = true;
600 
601     // Contexts are virtualized so textures and semaphores can be shared globally
602     outExtensions->displayTextureShareGroup   = true;
603     outExtensions->displaySemaphoreShareGroup = true;
604 
605     // D3D9 can be used without an output surface
606     outExtensions->surfacelessContext = true;
607 
608     outExtensions->robustResourceInitialization = true;
609 }
610 
startScene()611 void Renderer9::startScene()
612 {
613     if (!mSceneStarted)
614     {
615         long result = mDevice->BeginScene();
616         if (SUCCEEDED(result))
617         {
618             // This is defensive checking against the device being
619             // lost at unexpected times.
620             mSceneStarted = true;
621         }
622     }
623 }
624 
endScene()625 void Renderer9::endScene()
626 {
627     if (mSceneStarted)
628     {
629         // EndScene can fail if the device was lost, for example due
630         // to a TDR during a draw call.
631         mDevice->EndScene();
632         mSceneStarted = false;
633     }
634 }
635 
flush(const gl::Context * context)636 angle::Result Renderer9::flush(const gl::Context *context)
637 {
638     IDirect3DQuery9 *query = nullptr;
639     ANGLE_TRY(allocateEventQuery(context, &query));
640 
641     Context9 *context9 = GetImplAs<Context9>(context);
642 
643     HRESULT result = query->Issue(D3DISSUE_END);
644     ANGLE_TRY_HR(context9, result, "Failed to issue event query");
645 
646     // Grab the query data once
647     result = query->GetData(nullptr, 0, D3DGETDATA_FLUSH);
648     freeEventQuery(query);
649     ANGLE_TRY_HR(context9, result, "Failed to get event query data");
650 
651     return angle::Result::Continue;
652 }
653 
finish(const gl::Context * context)654 angle::Result Renderer9::finish(const gl::Context *context)
655 {
656     IDirect3DQuery9 *query = nullptr;
657     ANGLE_TRY(allocateEventQuery(context, &query));
658 
659     Context9 *context9 = GetImplAs<Context9>(context);
660 
661     HRESULT result = query->Issue(D3DISSUE_END);
662     ANGLE_TRY_HR(context9, result, "Failed to issue event query");
663 
664     // Grab the query data once
665     result = query->GetData(nullptr, 0, D3DGETDATA_FLUSH);
666     if (FAILED(result))
667     {
668         freeEventQuery(query);
669     }
670     ANGLE_TRY_HR(context9, result, "Failed to get event query data");
671 
672     // Loop until the query completes
673     unsigned int attempt = 0;
674     while (result == S_FALSE)
675     {
676         // Keep polling, but allow other threads to do something useful first
677         ScheduleYield();
678 
679         result = query->GetData(nullptr, 0, D3DGETDATA_FLUSH);
680         attempt++;
681 
682         if (result == S_FALSE)
683         {
684             // explicitly check for device loss
685             // some drivers seem to return S_FALSE even if the device is lost
686             // instead of D3DERR_DEVICELOST like they should
687             bool checkDeviceLost = (attempt % kPollingD3DDeviceLostCheckFrequency) == 0;
688             if (checkDeviceLost && testDeviceLost())
689             {
690                 result = D3DERR_DEVICELOST;
691             }
692         }
693 
694         if (FAILED(result))
695         {
696             freeEventQuery(query);
697         }
698         ANGLE_TRY_HR(context9, result, "Failed to get event query data");
699     }
700 
701     freeEventQuery(query);
702 
703     return angle::Result::Continue;
704 }
705 
isValidNativeWindow(EGLNativeWindowType window) const706 bool Renderer9::isValidNativeWindow(EGLNativeWindowType window) const
707 {
708     return NativeWindow9::IsValidNativeWindow(window);
709 }
710 
createNativeWindow(EGLNativeWindowType window,const egl::Config *,const egl::AttributeMap &) const711 NativeWindowD3D *Renderer9::createNativeWindow(EGLNativeWindowType window,
712                                                const egl::Config *,
713                                                const egl::AttributeMap &) const
714 {
715     return new NativeWindow9(window);
716 }
717 
createSwapChain(NativeWindowD3D * nativeWindow,HANDLE shareHandle,IUnknown * d3dTexture,GLenum backBufferFormat,GLenum depthBufferFormat,EGLint orientation,EGLint samples)718 SwapChainD3D *Renderer9::createSwapChain(NativeWindowD3D *nativeWindow,
719                                          HANDLE shareHandle,
720                                          IUnknown *d3dTexture,
721                                          GLenum backBufferFormat,
722                                          GLenum depthBufferFormat,
723                                          EGLint orientation,
724                                          EGLint samples)
725 {
726     return new SwapChain9(this, GetAs<NativeWindow9>(nativeWindow), shareHandle, d3dTexture,
727                           backBufferFormat, depthBufferFormat, orientation);
728 }
729 
getD3DTextureInfo(const egl::Config * configuration,IUnknown * d3dTexture,const egl::AttributeMap & attribs,EGLint * width,EGLint * height,GLsizei * samples,gl::Format * glFormat,const angle::Format ** angleFormat,UINT * arraySlice) const730 egl::Error Renderer9::getD3DTextureInfo(const egl::Config *configuration,
731                                         IUnknown *d3dTexture,
732                                         const egl::AttributeMap &attribs,
733                                         EGLint *width,
734                                         EGLint *height,
735                                         GLsizei *samples,
736                                         gl::Format *glFormat,
737                                         const angle::Format **angleFormat,
738                                         UINT *arraySlice) const
739 {
740     IDirect3DTexture9 *texture = nullptr;
741     if (FAILED(d3dTexture->QueryInterface(&texture)))
742     {
743         return egl::EglBadParameter() << "Client buffer is not a IDirect3DTexture9";
744     }
745 
746     IDirect3DDevice9 *textureDevice = nullptr;
747     texture->GetDevice(&textureDevice);
748     if (textureDevice != mDevice)
749     {
750         SafeRelease(texture);
751         return egl::EglBadParameter() << "Texture's device does not match.";
752     }
753     SafeRelease(textureDevice);
754 
755     D3DSURFACE_DESC desc;
756     texture->GetLevelDesc(0, &desc);
757     SafeRelease(texture);
758 
759     if (width)
760     {
761         *width = static_cast<EGLint>(desc.Width);
762     }
763     if (height)
764     {
765         *height = static_cast<EGLint>(desc.Height);
766     }
767 
768     // GetSamplesCount() returns 0 when multisampling isn't used.
769     GLsizei sampleCount = d3d9_gl::GetSamplesCount(desc.MultiSampleType);
770     if ((configuration && configuration->samples > 1) || sampleCount != 0)
771     {
772         return egl::EglBadParameter() << "Multisampling not supported for client buffer texture";
773     }
774     if (samples)
775     {
776         *samples = static_cast<EGLint>(sampleCount);
777     }
778 
779     // From table egl.restrictions in EGL_ANGLE_d3d_texture_client_buffer.
780     switch (desc.Format)
781     {
782         case D3DFMT_R8G8B8:
783         case D3DFMT_A8R8G8B8:
784         case D3DFMT_A16B16G16R16F:
785         case D3DFMT_A32B32G32R32F:
786             break;
787 
788         default:
789             return egl::EglBadParameter()
790                    << "Unknown client buffer texture format: " << desc.Format;
791     }
792 
793     const auto &d3dFormatInfo = d3d9::GetD3DFormatInfo(desc.Format);
794     ASSERT(d3dFormatInfo.info().id != angle::FormatID::NONE);
795 
796     if (glFormat)
797     {
798         *glFormat = gl::Format(d3dFormatInfo.info().glInternalFormat);
799     }
800 
801     if (angleFormat)
802     {
803 
804         *angleFormat = &d3dFormatInfo.info();
805     }
806 
807     if (arraySlice)
808     {
809         *arraySlice = 0;
810     }
811 
812     return egl::NoError();
813 }
814 
validateShareHandle(const egl::Config * config,HANDLE shareHandle,const egl::AttributeMap & attribs) const815 egl::Error Renderer9::validateShareHandle(const egl::Config *config,
816                                           HANDLE shareHandle,
817                                           const egl::AttributeMap &attribs) const
818 {
819     if (shareHandle == nullptr)
820     {
821         return egl::EglBadParameter() << "NULL share handle.";
822     }
823 
824     EGLint width  = attribs.getAsInt(EGL_WIDTH, 0);
825     EGLint height = attribs.getAsInt(EGL_HEIGHT, 0);
826     ASSERT(width != 0 && height != 0);
827 
828     const d3d9::TextureFormat &backBufferd3dFormatInfo =
829         d3d9::GetTextureFormatInfo(config->renderTargetFormat);
830 
831     IDirect3DTexture9 *texture = nullptr;
832     HRESULT result             = mDevice->CreateTexture(width, height, 1, D3DUSAGE_RENDERTARGET,
833                                             backBufferd3dFormatInfo.texFormat, D3DPOOL_DEFAULT,
834                                             &texture, &shareHandle);
835     if (FAILED(result))
836     {
837         return egl::EglBadParameter() << "Failed to open share handle, " << gl::FmtHR(result);
838     }
839 
840     DWORD levelCount = texture->GetLevelCount();
841 
842     D3DSURFACE_DESC desc;
843     texture->GetLevelDesc(0, &desc);
844     SafeRelease(texture);
845 
846     if (levelCount != 1 || desc.Width != static_cast<UINT>(width) ||
847         desc.Height != static_cast<UINT>(height) ||
848         desc.Format != backBufferd3dFormatInfo.texFormat)
849     {
850         return egl::EglBadParameter() << "Invalid texture parameters in share handle texture.";
851     }
852 
853     return egl::NoError();
854 }
855 
createContext(const gl::State & state,gl::ErrorSet * errorSet)856 ContextImpl *Renderer9::createContext(const gl::State &state, gl::ErrorSet *errorSet)
857 {
858     return new Context9(state, errorSet, this);
859 }
860 
getD3DDevice()861 void *Renderer9::getD3DDevice()
862 {
863     return mDevice;
864 }
865 
allocateEventQuery(const gl::Context * context,IDirect3DQuery9 ** outQuery)866 angle::Result Renderer9::allocateEventQuery(const gl::Context *context, IDirect3DQuery9 **outQuery)
867 {
868     if (mEventQueryPool.empty())
869     {
870         HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, outQuery);
871         ANGLE_TRY_HR(GetImplAs<Context9>(context), result, "Failed to allocate event query");
872     }
873     else
874     {
875         *outQuery = mEventQueryPool.back();
876         mEventQueryPool.pop_back();
877     }
878 
879     return angle::Result::Continue;
880 }
881 
freeEventQuery(IDirect3DQuery9 * query)882 void Renderer9::freeEventQuery(IDirect3DQuery9 *query)
883 {
884     if (mEventQueryPool.size() > 1000)
885     {
886         SafeRelease(query);
887     }
888     else
889     {
890         mEventQueryPool.push_back(query);
891     }
892 }
893 
createVertexShader(d3d::Context * context,const DWORD * function,size_t length,IDirect3DVertexShader9 ** outShader)894 angle::Result Renderer9::createVertexShader(d3d::Context *context,
895                                             const DWORD *function,
896                                             size_t length,
897                                             IDirect3DVertexShader9 **outShader)
898 {
899     return mVertexShaderCache.create(context, function, length, outShader);
900 }
901 
createPixelShader(d3d::Context * context,const DWORD * function,size_t length,IDirect3DPixelShader9 ** outShader)902 angle::Result Renderer9::createPixelShader(d3d::Context *context,
903                                            const DWORD *function,
904                                            size_t length,
905                                            IDirect3DPixelShader9 **outShader)
906 {
907     return mPixelShaderCache.create(context, function, length, outShader);
908 }
909 
createVertexBuffer(UINT Length,DWORD Usage,IDirect3DVertexBuffer9 ** ppVertexBuffer)910 HRESULT Renderer9::createVertexBuffer(UINT Length,
911                                       DWORD Usage,
912                                       IDirect3DVertexBuffer9 **ppVertexBuffer)
913 {
914     // Force buffers to be limited to a fixed max size.
915     if (Length > kMaximumBufferSizeHardLimit)
916     {
917         return E_OUTOFMEMORY;
918     }
919 
920     D3DPOOL Pool = getBufferPool(Usage);
921     return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, nullptr);
922 }
923 
createVertexBuffer()924 VertexBuffer *Renderer9::createVertexBuffer()
925 {
926     return new VertexBuffer9(this);
927 }
928 
createIndexBuffer(UINT Length,DWORD Usage,D3DFORMAT Format,IDirect3DIndexBuffer9 ** ppIndexBuffer)929 HRESULT Renderer9::createIndexBuffer(UINT Length,
930                                      DWORD Usage,
931                                      D3DFORMAT Format,
932                                      IDirect3DIndexBuffer9 **ppIndexBuffer)
933 {
934     // Force buffers to be limited to a fixed max size.
935     if (Length > kMaximumBufferSizeHardLimit)
936     {
937         return E_OUTOFMEMORY;
938     }
939 
940     D3DPOOL Pool = getBufferPool(Usage);
941     return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, nullptr);
942 }
943 
createIndexBuffer()944 IndexBuffer *Renderer9::createIndexBuffer()
945 {
946     return new IndexBuffer9(this);
947 }
948 
createStreamProducerD3DTexture(egl::Stream::ConsumerType consumerType,const egl::AttributeMap & attribs)949 StreamProducerImpl *Renderer9::createStreamProducerD3DTexture(
950     egl::Stream::ConsumerType consumerType,
951     const egl::AttributeMap &attribs)
952 {
953     // Streams are not supported under D3D9
954     UNREACHABLE();
955     return nullptr;
956 }
957 
supportsFastCopyBufferToTexture(GLenum internalFormat) const958 bool Renderer9::supportsFastCopyBufferToTexture(GLenum internalFormat) const
959 {
960     // Pixel buffer objects are not supported in D3D9, since D3D9 is ES2-only and PBOs are ES3.
961     return false;
962 }
963 
fastCopyBufferToTexture(const gl::Context * context,const gl::PixelUnpackState & unpack,gl::Buffer * unpackBuffer,unsigned int offset,RenderTargetD3D * destRenderTarget,GLenum destinationFormat,GLenum sourcePixelsType,const gl::Box & destArea)964 angle::Result Renderer9::fastCopyBufferToTexture(const gl::Context *context,
965                                                  const gl::PixelUnpackState &unpack,
966                                                  gl::Buffer *unpackBuffer,
967                                                  unsigned int offset,
968                                                  RenderTargetD3D *destRenderTarget,
969                                                  GLenum destinationFormat,
970                                                  GLenum sourcePixelsType,
971                                                  const gl::Box &destArea)
972 {
973     // Pixel buffer objects are not supported in D3D9, since D3D9 is ES2-only and PBOs are ES3.
974     ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
975     return angle::Result::Stop;
976 }
977 
setSamplerState(const gl::Context * context,gl::ShaderType type,int index,gl::Texture * texture,const gl::SamplerState & samplerState)978 angle::Result Renderer9::setSamplerState(const gl::Context *context,
979                                          gl::ShaderType type,
980                                          int index,
981                                          gl::Texture *texture,
982                                          const gl::SamplerState &samplerState)
983 {
984     CurSamplerState &appliedSampler = (type == gl::ShaderType::Fragment)
985                                           ? mCurPixelSamplerStates[index]
986                                           : mCurVertexSamplerStates[index];
987 
988     // Make sure to add the level offset for our tiny compressed texture workaround
989     TextureD3D *textureD3D = GetImplAs<TextureD3D>(texture);
990 
991     TextureStorage *storage = nullptr;
992     ANGLE_TRY(textureD3D->getNativeTexture(context, &storage));
993 
994     // Storage should exist, texture should be complete
995     ASSERT(storage);
996 
997     DWORD baseLevel = texture->getBaseLevel() + storage->getTopLevel();
998 
999     if (appliedSampler.forceSet || appliedSampler.baseLevel != baseLevel ||
1000         memcmp(&samplerState, &appliedSampler, sizeof(gl::SamplerState)) != 0)
1001     {
1002         int d3dSamplerOffset = (type == gl::ShaderType::Fragment) ? 0 : D3DVERTEXTEXTURESAMPLER0;
1003         int d3dSampler       = index + d3dSamplerOffset;
1004 
1005         mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU,
1006                                  gl_d3d9::ConvertTextureWrap(samplerState.getWrapS()));
1007         mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV,
1008                                  gl_d3d9::ConvertTextureWrap(samplerState.getWrapT()));
1009 
1010         mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER,
1011                                  gl_d3d9::ConvertMagFilter(samplerState.getMagFilter(),
1012                                                            samplerState.getMaxAnisotropy()));
1013 
1014         D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
1015         float lodBias;
1016         gl_d3d9::ConvertMinFilter(samplerState.getMinFilter(), &d3dMinFilter, &d3dMipFilter,
1017                                   &lodBias, samplerState.getMaxAnisotropy(), baseLevel);
1018         mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
1019         mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
1020         mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, baseLevel);
1021         mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPMAPLODBIAS, static_cast<DWORD>(lodBias));
1022         if (getNativeExtensions().textureFilterAnisotropic)
1023         {
1024             DWORD maxAnisotropy = std::min(mDeviceCaps.MaxAnisotropy,
1025                                            static_cast<DWORD>(samplerState.getMaxAnisotropy()));
1026             mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, maxAnisotropy);
1027         }
1028 
1029         ASSERT(texture->getBorderColor().type == angle::ColorGeneric::Type::Float);
1030         mDevice->SetSamplerState(d3dSampler, D3DSAMP_BORDERCOLOR,
1031                                  gl_d3d9::ConvertColor(texture->getBorderColor().colorF));
1032     }
1033 
1034     appliedSampler.forceSet     = false;
1035     appliedSampler.samplerState = samplerState;
1036     appliedSampler.baseLevel    = baseLevel;
1037 
1038     return angle::Result::Continue;
1039 }
1040 
setTexture(const gl::Context * context,gl::ShaderType type,int index,gl::Texture * texture)1041 angle::Result Renderer9::setTexture(const gl::Context *context,
1042                                     gl::ShaderType type,
1043                                     int index,
1044                                     gl::Texture *texture)
1045 {
1046     int d3dSamplerOffset = (type == gl::ShaderType::Fragment) ? 0 : D3DVERTEXTEXTURESAMPLER0;
1047     int d3dSampler       = index + d3dSamplerOffset;
1048     IDirect3DBaseTexture9 *d3dTexture = nullptr;
1049     bool forceSetTexture              = false;
1050 
1051     std::vector<uintptr_t> &appliedTextures =
1052         (type == gl::ShaderType::Fragment) ? mCurPixelTextures : mCurVertexTextures;
1053 
1054     if (texture)
1055     {
1056         TextureD3D *textureImpl = GetImplAs<TextureD3D>(texture);
1057 
1058         TextureStorage *texStorage = nullptr;
1059         ANGLE_TRY(textureImpl->getNativeTexture(context, &texStorage));
1060 
1061         // Texture should be complete and have a storage
1062         ASSERT(texStorage);
1063 
1064         TextureStorage9 *storage9 = GetAs<TextureStorage9>(texStorage);
1065         ANGLE_TRY(storage9->getBaseTexture(context, &d3dTexture));
1066 
1067         // If we get NULL back from getBaseTexture here, something went wrong
1068         // in the texture class and we're unexpectedly missing the d3d texture
1069         ASSERT(d3dTexture != nullptr);
1070 
1071         forceSetTexture = textureImpl->hasDirtyImages();
1072         textureImpl->resetDirty();
1073     }
1074 
1075     if (forceSetTexture || appliedTextures[index] != reinterpret_cast<uintptr_t>(d3dTexture))
1076     {
1077         mDevice->SetTexture(d3dSampler, d3dTexture);
1078     }
1079 
1080     appliedTextures[index] = reinterpret_cast<uintptr_t>(d3dTexture);
1081 
1082     return angle::Result::Continue;
1083 }
1084 
updateState(const gl::Context * context,gl::PrimitiveMode drawMode)1085 angle::Result Renderer9::updateState(const gl::Context *context, gl::PrimitiveMode drawMode)
1086 {
1087     const auto &glState = context->getState();
1088 
1089     // Applies the render target surface, depth stencil surface, viewport rectangle and
1090     // scissor rectangle to the renderer
1091     gl::Framebuffer *framebuffer = glState.getDrawFramebuffer();
1092     ASSERT(framebuffer && !framebuffer->hasAnyDirtyBit());
1093 
1094     Framebuffer9 *framebuffer9 = GetImplAs<Framebuffer9>(framebuffer);
1095 
1096     ANGLE_TRY(applyRenderTarget(context, framebuffer9->getCachedColorRenderTargets()[0],
1097                                 framebuffer9->getCachedDepthStencilRenderTarget()));
1098 
1099     // Setting viewport state
1100     setViewport(glState.getViewport(), glState.getNearPlane(), glState.getFarPlane(), drawMode,
1101                 glState.getRasterizerState().frontFace, false);
1102 
1103     // Setting scissors state
1104     setScissorRectangle(glState.getScissor(), glState.isScissorTestEnabled());
1105 
1106     // Setting blend, depth stencil, and rasterizer states
1107     // Since framebuffer->getSamples will return the original samples which may be different with
1108     // the sample counts that we set in render target view, here we use renderTarget->getSamples to
1109     // get the actual samples.
1110     GLsizei samples                                       = 0;
1111     const gl::FramebufferAttachment *firstColorAttachment = framebuffer->getFirstColorAttachment();
1112     if (firstColorAttachment)
1113     {
1114         ASSERT(firstColorAttachment->isAttached());
1115         RenderTarget9 *renderTarget = nullptr;
1116         ANGLE_TRY(firstColorAttachment->getRenderTarget(context, firstColorAttachment->getSamples(),
1117                                                         &renderTarget));
1118         samples = renderTarget->getSamples();
1119     }
1120     gl::RasterizerState rasterizer = glState.getRasterizerState();
1121     rasterizer.pointDrawMode       = (drawMode == gl::PrimitiveMode::Points);
1122     rasterizer.multiSample         = (samples != 0);
1123 
1124     ANGLE_TRY(setBlendDepthRasterStates(context, drawMode));
1125 
1126     mStateManager.resetDirtyBits();
1127 
1128     return angle::Result::Continue;
1129 }
1130 
setScissorRectangle(const gl::Rectangle & scissor,bool enabled)1131 void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
1132 {
1133     mStateManager.setScissorState(scissor, enabled);
1134 }
1135 
setBlendDepthRasterStates(const gl::Context * context,gl::PrimitiveMode drawMode)1136 angle::Result Renderer9::setBlendDepthRasterStates(const gl::Context *context,
1137                                                    gl::PrimitiveMode drawMode)
1138 {
1139     const auto &glState              = context->getState();
1140     gl::Framebuffer *drawFramebuffer = glState.getDrawFramebuffer();
1141     ASSERT(!drawFramebuffer->hasAnyDirtyBit());
1142     // Since framebuffer->getSamples will return the original samples which may be different with
1143     // the sample counts that we set in render target view, here we use renderTarget->getSamples to
1144     // get the actual samples.
1145     GLsizei samples = 0;
1146     const gl::FramebufferAttachment *firstColorAttachment =
1147         drawFramebuffer->getFirstColorAttachment();
1148     if (firstColorAttachment)
1149     {
1150         ASSERT(firstColorAttachment->isAttached());
1151         RenderTarget9 *renderTarget = nullptr;
1152         ANGLE_TRY(firstColorAttachment->getRenderTarget(context, firstColorAttachment->getSamples(),
1153                                                         &renderTarget));
1154         samples = renderTarget->getSamples();
1155     }
1156     gl::RasterizerState rasterizer = glState.getRasterizerState();
1157     rasterizer.pointDrawMode       = (drawMode == gl::PrimitiveMode::Points);
1158     rasterizer.multiSample         = (samples != 0);
1159 
1160     unsigned int mask = GetBlendSampleMask(glState, samples);
1161     mStateManager.setBlendDepthRasterStates(glState, mask);
1162     return angle::Result::Continue;
1163 }
1164 
setViewport(const gl::Rectangle & viewport,float zNear,float zFar,gl::PrimitiveMode drawMode,GLenum frontFace,bool ignoreViewport)1165 void Renderer9::setViewport(const gl::Rectangle &viewport,
1166                             float zNear,
1167                             float zFar,
1168                             gl::PrimitiveMode drawMode,
1169                             GLenum frontFace,
1170                             bool ignoreViewport)
1171 {
1172     mStateManager.setViewportState(viewport, zNear, zFar, drawMode, frontFace, ignoreViewport);
1173 }
1174 
applyPrimitiveType(gl::PrimitiveMode mode,GLsizei count,bool usesPointSize)1175 bool Renderer9::applyPrimitiveType(gl::PrimitiveMode mode, GLsizei count, bool usesPointSize)
1176 {
1177     switch (mode)
1178     {
1179         case gl::PrimitiveMode::Points:
1180             mPrimitiveType  = D3DPT_POINTLIST;
1181             mPrimitiveCount = count;
1182             break;
1183         case gl::PrimitiveMode::Lines:
1184             mPrimitiveType  = D3DPT_LINELIST;
1185             mPrimitiveCount = count / 2;
1186             break;
1187         case gl::PrimitiveMode::LineLoop:
1188             mPrimitiveType = D3DPT_LINESTRIP;
1189             mPrimitiveCount =
1190                 count - 1;  // D3D doesn't support line loops, so we draw the last line separately
1191             break;
1192         case gl::PrimitiveMode::LineStrip:
1193             mPrimitiveType  = D3DPT_LINESTRIP;
1194             mPrimitiveCount = count - 1;
1195             break;
1196         case gl::PrimitiveMode::Triangles:
1197             mPrimitiveType  = D3DPT_TRIANGLELIST;
1198             mPrimitiveCount = count / 3;
1199             break;
1200         case gl::PrimitiveMode::TriangleStrip:
1201             mPrimitiveType  = D3DPT_TRIANGLESTRIP;
1202             mPrimitiveCount = count - 2;
1203             break;
1204         case gl::PrimitiveMode::TriangleFan:
1205             mPrimitiveType  = D3DPT_TRIANGLEFAN;
1206             mPrimitiveCount = count - 2;
1207             break;
1208         default:
1209             UNREACHABLE();
1210             return false;
1211     }
1212 
1213     return mPrimitiveCount > 0;
1214 }
1215 
getNullColorRenderTarget(const gl::Context * context,const RenderTarget9 * depthRenderTarget,const RenderTarget9 ** outColorRenderTarget)1216 angle::Result Renderer9::getNullColorRenderTarget(const gl::Context *context,
1217                                                   const RenderTarget9 *depthRenderTarget,
1218                                                   const RenderTarget9 **outColorRenderTarget)
1219 {
1220     ASSERT(depthRenderTarget);
1221 
1222     const gl::Extents &size = depthRenderTarget->getExtents();
1223 
1224     // search cached nullcolorbuffers
1225     for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1226     {
1227         if (mNullRenderTargetCache[i].renderTarget != nullptr &&
1228             mNullRenderTargetCache[i].width == size.width &&
1229             mNullRenderTargetCache[i].height == size.height)
1230         {
1231             mNullRenderTargetCache[i].lruCount = ++mMaxNullColorbufferLRU;
1232             *outColorRenderTarget              = mNullRenderTargetCache[i].renderTarget;
1233             return angle::Result::Continue;
1234         }
1235     }
1236 
1237     RenderTargetD3D *nullRenderTarget = nullptr;
1238     ANGLE_TRY(createRenderTarget(context, size.width, size.height, GL_NONE, 0, &nullRenderTarget));
1239 
1240     // add nullbuffer to the cache
1241     NullRenderTargetCacheEntry *oldest = &mNullRenderTargetCache[0];
1242     for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1243     {
1244         if (mNullRenderTargetCache[i].lruCount < oldest->lruCount)
1245         {
1246             oldest = &mNullRenderTargetCache[i];
1247         }
1248     }
1249 
1250     SafeDelete(oldest->renderTarget);
1251     oldest->renderTarget = GetAs<RenderTarget9>(nullRenderTarget);
1252     oldest->lruCount     = ++mMaxNullColorbufferLRU;
1253     oldest->width        = size.width;
1254     oldest->height       = size.height;
1255 
1256     *outColorRenderTarget = oldest->renderTarget;
1257     return angle::Result::Continue;
1258 }
1259 
applyRenderTarget(const gl::Context * context,const RenderTarget9 * colorRenderTargetIn,const RenderTarget9 * depthStencilRenderTarget)1260 angle::Result Renderer9::applyRenderTarget(const gl::Context *context,
1261                                            const RenderTarget9 *colorRenderTargetIn,
1262                                            const RenderTarget9 *depthStencilRenderTarget)
1263 {
1264     // if there is no color attachment we must synthesize a NULL colorattachment
1265     // to keep the D3D runtime happy.  This should only be possible if depth texturing.
1266     const RenderTarget9 *colorRenderTarget = colorRenderTargetIn;
1267     if (colorRenderTarget == nullptr)
1268     {
1269         ANGLE_TRY(getNullColorRenderTarget(context, depthStencilRenderTarget, &colorRenderTarget));
1270     }
1271     ASSERT(colorRenderTarget != nullptr);
1272 
1273     size_t renderTargetWidth     = 0;
1274     size_t renderTargetHeight    = 0;
1275     D3DFORMAT renderTargetFormat = D3DFMT_UNKNOWN;
1276 
1277     bool renderTargetChanged        = false;
1278     unsigned int renderTargetSerial = colorRenderTarget->getSerial();
1279     if (renderTargetSerial != mAppliedRenderTargetSerial)
1280     {
1281         // Apply the render target on the device
1282         IDirect3DSurface9 *renderTargetSurface = colorRenderTarget->getSurface();
1283         ASSERT(renderTargetSurface);
1284 
1285         mDevice->SetRenderTarget(0, renderTargetSurface);
1286         SafeRelease(renderTargetSurface);
1287 
1288         renderTargetWidth  = colorRenderTarget->getWidth();
1289         renderTargetHeight = colorRenderTarget->getHeight();
1290         renderTargetFormat = colorRenderTarget->getD3DFormat();
1291 
1292         mAppliedRenderTargetSerial = renderTargetSerial;
1293         renderTargetChanged        = true;
1294     }
1295 
1296     unsigned int depthStencilSerial = 0;
1297     if (depthStencilRenderTarget != nullptr)
1298     {
1299         depthStencilSerial = depthStencilRenderTarget->getSerial();
1300     }
1301 
1302     if (depthStencilSerial != mAppliedDepthStencilSerial || !mDepthStencilInitialized)
1303     {
1304         unsigned int depthSize   = 0;
1305         unsigned int stencilSize = 0;
1306 
1307         // Apply the depth stencil on the device
1308         if (depthStencilRenderTarget)
1309         {
1310             IDirect3DSurface9 *depthStencilSurface = depthStencilRenderTarget->getSurface();
1311             ASSERT(depthStencilSurface);
1312 
1313             mDevice->SetDepthStencilSurface(depthStencilSurface);
1314             SafeRelease(depthStencilSurface);
1315 
1316             const gl::InternalFormat &format =
1317                 gl::GetSizedInternalFormatInfo(depthStencilRenderTarget->getInternalFormat());
1318 
1319             depthSize   = format.depthBits;
1320             stencilSize = format.stencilBits;
1321         }
1322         else
1323         {
1324             mDevice->SetDepthStencilSurface(nullptr);
1325         }
1326 
1327         mStateManager.updateDepthSizeIfChanged(mDepthStencilInitialized, depthSize);
1328         mStateManager.updateStencilSizeIfChanged(mDepthStencilInitialized, stencilSize);
1329 
1330         mAppliedDepthStencilSerial = depthStencilSerial;
1331         mDepthStencilInitialized   = true;
1332     }
1333 
1334     if (renderTargetChanged || !mRenderTargetDescInitialized)
1335     {
1336         mStateManager.forceSetBlendState();
1337         mStateManager.forceSetScissorState();
1338         mStateManager.setRenderTargetBounds(renderTargetWidth, renderTargetHeight);
1339         mRenderTargetDescInitialized = true;
1340     }
1341 
1342     return angle::Result::Continue;
1343 }
1344 
applyVertexBuffer(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count,GLsizei instances,TranslatedIndexData *)1345 angle::Result Renderer9::applyVertexBuffer(const gl::Context *context,
1346                                            gl::PrimitiveMode mode,
1347                                            GLint first,
1348                                            GLsizei count,
1349                                            GLsizei instances,
1350                                            TranslatedIndexData * /*indexInfo*/)
1351 {
1352     const gl::State &state = context->getState();
1353     ANGLE_TRY(mVertexDataManager->prepareVertexData(context, first, count, &mTranslatedAttribCache,
1354                                                     instances));
1355 
1356     return mVertexDeclarationCache.applyDeclaration(context, mDevice, mTranslatedAttribCache,
1357                                                     state.getProgram(), first, instances,
1358                                                     &mRepeatDraw);
1359 }
1360 
1361 // Applies the indices and element array bindings to the Direct3D 9 device
applyIndexBuffer(const gl::Context * context,const void * indices,GLsizei count,gl::PrimitiveMode mode,gl::DrawElementsType type,TranslatedIndexData * indexInfo)1362 angle::Result Renderer9::applyIndexBuffer(const gl::Context *context,
1363                                           const void *indices,
1364                                           GLsizei count,
1365                                           gl::PrimitiveMode mode,
1366                                           gl::DrawElementsType type,
1367                                           TranslatedIndexData *indexInfo)
1368 {
1369     gl::VertexArray *vao           = context->getState().getVertexArray();
1370     gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer();
1371 
1372     gl::DrawElementsType dstType = gl::DrawElementsType::InvalidEnum;
1373     ANGLE_TRY(GetIndexTranslationDestType(context, count, type, indices, false, &dstType));
1374 
1375     ANGLE_TRY(mIndexDataManager->prepareIndexData(context, type, dstType, count, elementArrayBuffer,
1376                                                   indices, indexInfo));
1377 
1378     // Directly binding the storage buffer is not supported for d3d9
1379     ASSERT(indexInfo->storage == nullptr);
1380 
1381     if (indexInfo->serial != mAppliedIBSerial)
1382     {
1383         IndexBuffer9 *indexBuffer = GetAs<IndexBuffer9>(indexInfo->indexBuffer);
1384 
1385         mDevice->SetIndices(indexBuffer->getBuffer());
1386         mAppliedIBSerial = indexInfo->serial;
1387     }
1388 
1389     return angle::Result::Continue;
1390 }
1391 
drawArraysImpl(const gl::Context * context,gl::PrimitiveMode mode,GLint startVertex,GLsizei count,GLsizei instances)1392 angle::Result Renderer9::drawArraysImpl(const gl::Context *context,
1393                                         gl::PrimitiveMode mode,
1394                                         GLint startVertex,
1395                                         GLsizei count,
1396                                         GLsizei instances)
1397 {
1398     ASSERT(!context->getState().isTransformFeedbackActiveUnpaused());
1399 
1400     startScene();
1401 
1402     if (mode == gl::PrimitiveMode::LineLoop)
1403     {
1404         return drawLineLoop(context, count, gl::DrawElementsType::InvalidEnum, nullptr, 0, nullptr);
1405     }
1406 
1407     if (instances > 0)
1408     {
1409         StaticIndexBufferInterface *countingIB = nullptr;
1410         ANGLE_TRY(getCountingIB(context, count, &countingIB));
1411 
1412         if (mAppliedIBSerial != countingIB->getSerial())
1413         {
1414             IndexBuffer9 *indexBuffer = GetAs<IndexBuffer9>(countingIB->getIndexBuffer());
1415 
1416             mDevice->SetIndices(indexBuffer->getBuffer());
1417             mAppliedIBSerial = countingIB->getSerial();
1418         }
1419 
1420         for (int i = 0; i < mRepeatDraw; i++)
1421         {
1422             mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1423         }
1424 
1425         return angle::Result::Continue;
1426     }
1427 
1428     // Regular case
1429     mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1430     return angle::Result::Continue;
1431 }
1432 
drawElementsImpl(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances)1433 angle::Result Renderer9::drawElementsImpl(const gl::Context *context,
1434                                           gl::PrimitiveMode mode,
1435                                           GLsizei count,
1436                                           gl::DrawElementsType type,
1437                                           const void *indices,
1438                                           GLsizei instances)
1439 {
1440     TranslatedIndexData indexInfo;
1441 
1442     ANGLE_TRY(applyIndexBuffer(context, indices, count, mode, type, &indexInfo));
1443 
1444     gl::IndexRange indexRange;
1445     ANGLE_TRY(context->getState().getVertexArray()->getIndexRange(context, type, count, indices,
1446                                                                   &indexRange));
1447 
1448     size_t vertexCount = indexRange.vertexCount();
1449     ANGLE_TRY(applyVertexBuffer(context, mode, static_cast<GLsizei>(indexRange.start),
1450                                 static_cast<GLsizei>(vertexCount), instances, &indexInfo));
1451 
1452     startScene();
1453 
1454     int minIndex = static_cast<int>(indexRange.start);
1455 
1456     gl::VertexArray *vao           = context->getState().getVertexArray();
1457     gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer();
1458 
1459     if (mode == gl::PrimitiveMode::Points)
1460     {
1461         return drawIndexedPoints(context, count, type, indices, minIndex, elementArrayBuffer);
1462     }
1463 
1464     if (mode == gl::PrimitiveMode::LineLoop)
1465     {
1466         return drawLineLoop(context, count, type, indices, minIndex, elementArrayBuffer);
1467     }
1468 
1469     for (int i = 0; i < mRepeatDraw; i++)
1470     {
1471         mDevice->DrawIndexedPrimitive(mPrimitiveType, -minIndex, minIndex,
1472                                       static_cast<UINT>(vertexCount), indexInfo.startIndex,
1473                                       mPrimitiveCount);
1474     }
1475     return angle::Result::Continue;
1476 }
1477 
drawLineLoop(const gl::Context * context,GLsizei count,gl::DrawElementsType type,const void * indices,int minIndex,gl::Buffer * elementArrayBuffer)1478 angle::Result Renderer9::drawLineLoop(const gl::Context *context,
1479                                       GLsizei count,
1480                                       gl::DrawElementsType type,
1481                                       const void *indices,
1482                                       int minIndex,
1483                                       gl::Buffer *elementArrayBuffer)
1484 {
1485     // Get the raw indices for an indexed draw
1486     if (type != gl::DrawElementsType::InvalidEnum && elementArrayBuffer)
1487     {
1488         BufferD3D *storage        = GetImplAs<BufferD3D>(elementArrayBuffer);
1489         intptr_t offset           = reinterpret_cast<intptr_t>(indices);
1490         const uint8_t *bufferData = nullptr;
1491         ANGLE_TRY(storage->getData(context, &bufferData));
1492         indices = bufferData + offset;
1493     }
1494 
1495     unsigned int startIndex = 0;
1496     Context9 *context9      = GetImplAs<Context9>(context);
1497 
1498     if (getNativeExtensions().elementIndexUintOES)
1499     {
1500         if (!mLineLoopIB)
1501         {
1502             mLineLoopIB = new StreamingIndexBufferInterface(this);
1503             ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, INITIAL_INDEX_BUFFER_SIZE,
1504                                                       gl::DrawElementsType::UnsignedInt));
1505         }
1506 
1507         // Checked by Renderer9::applyPrimitiveType
1508         ASSERT(count >= 0);
1509 
1510         ANGLE_CHECK(context9,
1511                     static_cast<unsigned int>(count) + 1 <=
1512                         (std::numeric_limits<unsigned int>::max() / sizeof(unsigned int)),
1513                     "Failed to create a 32-bit looping index buffer for "
1514                     "GL_LINE_LOOP, too many indices required.",
1515                     GL_OUT_OF_MEMORY);
1516 
1517         const unsigned int spaceNeeded =
1518             (static_cast<unsigned int>(count) + 1) * sizeof(unsigned int);
1519         ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, spaceNeeded,
1520                                                   gl::DrawElementsType::UnsignedInt));
1521 
1522         void *mappedMemory  = nullptr;
1523         unsigned int offset = 0;
1524         ANGLE_TRY(mLineLoopIB->mapBuffer(context, spaceNeeded, &mappedMemory, &offset));
1525 
1526         startIndex         = static_cast<unsigned int>(offset) / 4;
1527         unsigned int *data = static_cast<unsigned int *>(mappedMemory);
1528 
1529         switch (type)
1530         {
1531             case gl::DrawElementsType::InvalidEnum:  // Non-indexed draw
1532                 for (int i = 0; i < count; i++)
1533                 {
1534                     data[i] = i;
1535                 }
1536                 data[count] = 0;
1537                 break;
1538             case gl::DrawElementsType::UnsignedByte:
1539                 for (int i = 0; i < count; i++)
1540                 {
1541                     data[i] = static_cast<const GLubyte *>(indices)[i];
1542                 }
1543                 data[count] = static_cast<const GLubyte *>(indices)[0];
1544                 break;
1545             case gl::DrawElementsType::UnsignedShort:
1546                 for (int i = 0; i < count; i++)
1547                 {
1548                     data[i] = static_cast<const GLushort *>(indices)[i];
1549                 }
1550                 data[count] = static_cast<const GLushort *>(indices)[0];
1551                 break;
1552             case gl::DrawElementsType::UnsignedInt:
1553                 for (int i = 0; i < count; i++)
1554                 {
1555                     data[i] = static_cast<const GLuint *>(indices)[i];
1556                 }
1557                 data[count] = static_cast<const GLuint *>(indices)[0];
1558                 break;
1559             default:
1560                 UNREACHABLE();
1561         }
1562 
1563         ANGLE_TRY(mLineLoopIB->unmapBuffer(context));
1564     }
1565     else
1566     {
1567         if (!mLineLoopIB)
1568         {
1569             mLineLoopIB = new StreamingIndexBufferInterface(this);
1570             ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, INITIAL_INDEX_BUFFER_SIZE,
1571                                                       gl::DrawElementsType::UnsignedShort));
1572         }
1573 
1574         // Checked by Renderer9::applyPrimitiveType
1575         ASSERT(count >= 0);
1576 
1577         ANGLE_CHECK(context9,
1578                     static_cast<unsigned int>(count) + 1 <=
1579                         (std::numeric_limits<unsigned short>::max() / sizeof(unsigned short)),
1580                     "Failed to create a 16-bit looping index buffer for "
1581                     "GL_LINE_LOOP, too many indices required.",
1582                     GL_OUT_OF_MEMORY);
1583 
1584         const unsigned int spaceNeeded =
1585             (static_cast<unsigned int>(count) + 1) * sizeof(unsigned short);
1586         ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, spaceNeeded,
1587                                                   gl::DrawElementsType::UnsignedShort));
1588 
1589         void *mappedMemory = nullptr;
1590         unsigned int offset;
1591         ANGLE_TRY(mLineLoopIB->mapBuffer(context, spaceNeeded, &mappedMemory, &offset));
1592 
1593         startIndex           = static_cast<unsigned int>(offset) / 2;
1594         unsigned short *data = static_cast<unsigned short *>(mappedMemory);
1595 
1596         switch (type)
1597         {
1598             case gl::DrawElementsType::InvalidEnum:  // Non-indexed draw
1599                 for (int i = 0; i < count; i++)
1600                 {
1601                     data[i] = static_cast<unsigned short>(i);
1602                 }
1603                 data[count] = 0;
1604                 break;
1605             case gl::DrawElementsType::UnsignedByte:
1606                 for (int i = 0; i < count; i++)
1607                 {
1608                     data[i] = static_cast<const GLubyte *>(indices)[i];
1609                 }
1610                 data[count] = static_cast<const GLubyte *>(indices)[0];
1611                 break;
1612             case gl::DrawElementsType::UnsignedShort:
1613                 for (int i = 0; i < count; i++)
1614                 {
1615                     data[i] = static_cast<const GLushort *>(indices)[i];
1616                 }
1617                 data[count] = static_cast<const GLushort *>(indices)[0];
1618                 break;
1619             case gl::DrawElementsType::UnsignedInt:
1620                 for (int i = 0; i < count; i++)
1621                 {
1622                     data[i] = static_cast<unsigned short>(static_cast<const GLuint *>(indices)[i]);
1623                 }
1624                 data[count] = static_cast<unsigned short>(static_cast<const GLuint *>(indices)[0]);
1625                 break;
1626             default:
1627                 UNREACHABLE();
1628         }
1629 
1630         ANGLE_TRY(mLineLoopIB->unmapBuffer(context));
1631     }
1632 
1633     if (mAppliedIBSerial != mLineLoopIB->getSerial())
1634     {
1635         IndexBuffer9 *indexBuffer = GetAs<IndexBuffer9>(mLineLoopIB->getIndexBuffer());
1636 
1637         mDevice->SetIndices(indexBuffer->getBuffer());
1638         mAppliedIBSerial = mLineLoopIB->getSerial();
1639     }
1640 
1641     mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1642 
1643     return angle::Result::Continue;
1644 }
1645 
drawIndexedPoints(const gl::Context * context,GLsizei count,gl::DrawElementsType type,const void * indices,int minIndex,gl::Buffer * elementArrayBuffer)1646 angle::Result Renderer9::drawIndexedPoints(const gl::Context *context,
1647                                            GLsizei count,
1648                                            gl::DrawElementsType type,
1649                                            const void *indices,
1650                                            int minIndex,
1651                                            gl::Buffer *elementArrayBuffer)
1652 {
1653     // Drawing index point lists is unsupported in d3d9, fall back to a regular DrawPrimitive call
1654     // for each individual point. This call is not expected to happen often.
1655 
1656     if (elementArrayBuffer)
1657     {
1658         BufferD3D *storage = GetImplAs<BufferD3D>(elementArrayBuffer);
1659         intptr_t offset    = reinterpret_cast<intptr_t>(indices);
1660 
1661         const uint8_t *bufferData = nullptr;
1662         ANGLE_TRY(storage->getData(context, &bufferData));
1663         indices = bufferData + offset;
1664     }
1665 
1666     switch (type)
1667     {
1668         case gl::DrawElementsType::UnsignedByte:
1669             DrawPoints<GLubyte>(mDevice, count, indices, minIndex);
1670             return angle::Result::Continue;
1671         case gl::DrawElementsType::UnsignedShort:
1672             DrawPoints<GLushort>(mDevice, count, indices, minIndex);
1673             return angle::Result::Continue;
1674         case gl::DrawElementsType::UnsignedInt:
1675             DrawPoints<GLuint>(mDevice, count, indices, minIndex);
1676             return angle::Result::Continue;
1677         default:
1678             ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
1679     }
1680 }
1681 
getCountingIB(const gl::Context * context,size_t count,StaticIndexBufferInterface ** outIB)1682 angle::Result Renderer9::getCountingIB(const gl::Context *context,
1683                                        size_t count,
1684                                        StaticIndexBufferInterface **outIB)
1685 {
1686     // Update the counting index buffer if it is not large enough or has not been created yet.
1687     if (count <= 65536)  // 16-bit indices
1688     {
1689         const unsigned int spaceNeeded = static_cast<unsigned int>(count) * sizeof(unsigned short);
1690 
1691         if (!mCountingIB || mCountingIB->getBufferSize() < spaceNeeded)
1692         {
1693             SafeDelete(mCountingIB);
1694             mCountingIB = new StaticIndexBufferInterface(this);
1695             ANGLE_TRY(mCountingIB->reserveBufferSpace(context, spaceNeeded,
1696                                                       gl::DrawElementsType::UnsignedShort));
1697 
1698             void *mappedMemory = nullptr;
1699             ANGLE_TRY(mCountingIB->mapBuffer(context, spaceNeeded, &mappedMemory, nullptr));
1700 
1701             unsigned short *data = static_cast<unsigned short *>(mappedMemory);
1702             for (size_t i = 0; i < count; i++)
1703             {
1704                 data[i] = static_cast<unsigned short>(i);
1705             }
1706 
1707             ANGLE_TRY(mCountingIB->unmapBuffer(context));
1708         }
1709     }
1710     else if (getNativeExtensions().elementIndexUintOES)
1711     {
1712         const unsigned int spaceNeeded = static_cast<unsigned int>(count) * sizeof(unsigned int);
1713 
1714         if (!mCountingIB || mCountingIB->getBufferSize() < spaceNeeded)
1715         {
1716             SafeDelete(mCountingIB);
1717             mCountingIB = new StaticIndexBufferInterface(this);
1718             ANGLE_TRY(mCountingIB->reserveBufferSpace(context, spaceNeeded,
1719                                                       gl::DrawElementsType::UnsignedInt));
1720 
1721             void *mappedMemory = nullptr;
1722             ANGLE_TRY(mCountingIB->mapBuffer(context, spaceNeeded, &mappedMemory, nullptr));
1723 
1724             unsigned int *data = static_cast<unsigned int *>(mappedMemory);
1725             for (unsigned int i = 0; i < count; i++)
1726             {
1727                 data[i] = i;
1728             }
1729 
1730             ANGLE_TRY(mCountingIB->unmapBuffer(context));
1731         }
1732     }
1733     else
1734     {
1735         ANGLE_TRY_HR(GetImplAs<Context9>(context), E_OUTOFMEMORY,
1736                      "Could not create a counting index buffer for glDrawArraysInstanced.");
1737     }
1738 
1739     *outIB = mCountingIB;
1740     return angle::Result::Continue;
1741 }
1742 
applyShaders(const gl::Context * context,gl::PrimitiveMode drawMode)1743 angle::Result Renderer9::applyShaders(const gl::Context *context, gl::PrimitiveMode drawMode)
1744 {
1745     const gl::State &state   = context->getState();
1746     d3d::Context *contextD3D = GetImplAs<ContextD3D>(context);
1747 
1748     // This method is called single-threaded.
1749     ANGLE_TRY(ensureHLSLCompilerInitialized(contextD3D));
1750 
1751     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(state.getProgram());
1752     VertexArray9 *vao      = GetImplAs<VertexArray9>(state.getVertexArray());
1753     programD3D->updateCachedInputLayout(vao->getCurrentStateSerial(), state);
1754 
1755     ShaderExecutableD3D *vertexExe = nullptr;
1756     ANGLE_TRY(programD3D->getVertexExecutableForCachedInputLayout(contextD3D, &vertexExe, nullptr));
1757 
1758     const gl::Framebuffer *drawFramebuffer = state.getDrawFramebuffer();
1759     programD3D->updateCachedOutputLayout(context, drawFramebuffer);
1760 
1761     ShaderExecutableD3D *pixelExe = nullptr;
1762     ANGLE_TRY(programD3D->getPixelExecutableForCachedOutputLayout(contextD3D, &pixelExe, nullptr));
1763 
1764     IDirect3DVertexShader9 *vertexShader =
1765         (vertexExe ? GetAs<ShaderExecutable9>(vertexExe)->getVertexShader() : nullptr);
1766     IDirect3DPixelShader9 *pixelShader =
1767         (pixelExe ? GetAs<ShaderExecutable9>(pixelExe)->getPixelShader() : nullptr);
1768 
1769     if (vertexShader != mAppliedVertexShader)
1770     {
1771         mDevice->SetVertexShader(vertexShader);
1772         mAppliedVertexShader = vertexShader;
1773     }
1774 
1775     if (pixelShader != mAppliedPixelShader)
1776     {
1777         mDevice->SetPixelShader(pixelShader);
1778         mAppliedPixelShader = pixelShader;
1779     }
1780 
1781     // D3D9 has a quirk where creating multiple shaders with the same content
1782     // can return the same shader pointer. Because GL programs store different data
1783     // per-program, checking the program serial guarantees we upload fresh
1784     // uniform data even if our shader pointers are the same.
1785     // https://code.google.com/p/angleproject/issues/detail?id=661
1786     unsigned int programSerial = programD3D->getSerial();
1787     if (programSerial != mAppliedProgramSerial)
1788     {
1789         programD3D->dirtyAllUniforms();
1790         mStateManager.forceSetDXUniformsState();
1791         mAppliedProgramSerial = programSerial;
1792     }
1793 
1794     applyUniforms(programD3D);
1795 
1796     // Driver uniforms
1797     mStateManager.setShaderConstants();
1798 
1799     return angle::Result::Continue;
1800 }
1801 
applyUniforms(ProgramD3D * programD3D)1802 void Renderer9::applyUniforms(ProgramD3D *programD3D)
1803 {
1804     // Skip updates if we're not dirty. Note that D3D9 cannot have compute or geometry.
1805     if (!programD3D->anyShaderUniformsDirty())
1806     {
1807         return;
1808     }
1809 
1810     const auto &uniformArray = programD3D->getD3DUniforms();
1811 
1812     for (const D3DUniform *targetUniform : uniformArray)
1813     {
1814         // Built-in uniforms must be skipped.
1815         if (!targetUniform->isReferencedByShader(gl::ShaderType::Vertex) &&
1816             !targetUniform->isReferencedByShader(gl::ShaderType::Fragment))
1817             continue;
1818 
1819         const GLfloat *f = reinterpret_cast<const GLfloat *>(targetUniform->firstNonNullData());
1820         const GLint *i   = reinterpret_cast<const GLint *>(targetUniform->firstNonNullData());
1821 
1822         switch (targetUniform->typeInfo.type)
1823         {
1824             case GL_SAMPLER_2D:
1825             case GL_SAMPLER_CUBE:
1826             case GL_SAMPLER_EXTERNAL_OES:
1827             case GL_SAMPLER_VIDEO_IMAGE_WEBGL:
1828                 break;
1829             case GL_BOOL:
1830             case GL_BOOL_VEC2:
1831             case GL_BOOL_VEC3:
1832             case GL_BOOL_VEC4:
1833                 applyUniformnbv(targetUniform, i);
1834                 break;
1835             case GL_FLOAT:
1836             case GL_FLOAT_VEC2:
1837             case GL_FLOAT_VEC3:
1838             case GL_FLOAT_VEC4:
1839             case GL_FLOAT_MAT2:
1840             case GL_FLOAT_MAT3:
1841             case GL_FLOAT_MAT4:
1842                 applyUniformnfv(targetUniform, f);
1843                 break;
1844             case GL_INT:
1845             case GL_INT_VEC2:
1846             case GL_INT_VEC3:
1847             case GL_INT_VEC4:
1848                 applyUniformniv(targetUniform, i);
1849                 break;
1850             default:
1851                 UNREACHABLE();
1852         }
1853     }
1854 
1855     programD3D->markUniformsClean();
1856 }
1857 
applyUniformnfv(const D3DUniform * targetUniform,const GLfloat * v)1858 void Renderer9::applyUniformnfv(const D3DUniform *targetUniform, const GLfloat *v)
1859 {
1860     if (targetUniform->isReferencedByShader(gl::ShaderType::Fragment))
1861     {
1862         mDevice->SetPixelShaderConstantF(
1863             targetUniform->mShaderRegisterIndexes[gl::ShaderType::Fragment], v,
1864             targetUniform->registerCount);
1865     }
1866 
1867     if (targetUniform->isReferencedByShader(gl::ShaderType::Vertex))
1868     {
1869         mDevice->SetVertexShaderConstantF(
1870             targetUniform->mShaderRegisterIndexes[gl::ShaderType::Vertex], v,
1871             targetUniform->registerCount);
1872     }
1873 }
1874 
applyUniformniv(const D3DUniform * targetUniform,const GLint * v)1875 void Renderer9::applyUniformniv(const D3DUniform *targetUniform, const GLint *v)
1876 {
1877     ASSERT(targetUniform->registerCount <= MAX_VERTEX_CONSTANT_VECTORS_D3D9);
1878     GLfloat vector[MAX_VERTEX_CONSTANT_VECTORS_D3D9][4];
1879 
1880     for (unsigned int i = 0; i < targetUniform->registerCount; i++)
1881     {
1882         vector[i][0] = (GLfloat)v[4 * i + 0];
1883         vector[i][1] = (GLfloat)v[4 * i + 1];
1884         vector[i][2] = (GLfloat)v[4 * i + 2];
1885         vector[i][3] = (GLfloat)v[4 * i + 3];
1886     }
1887 
1888     applyUniformnfv(targetUniform, (GLfloat *)vector);
1889 }
1890 
applyUniformnbv(const D3DUniform * targetUniform,const GLint * v)1891 void Renderer9::applyUniformnbv(const D3DUniform *targetUniform, const GLint *v)
1892 {
1893     ASSERT(targetUniform->registerCount <= MAX_VERTEX_CONSTANT_VECTORS_D3D9);
1894     GLfloat vector[MAX_VERTEX_CONSTANT_VECTORS_D3D9][4];
1895 
1896     for (unsigned int i = 0; i < targetUniform->registerCount; i++)
1897     {
1898         vector[i][0] = (v[4 * i + 0] == GL_FALSE) ? 0.0f : 1.0f;
1899         vector[i][1] = (v[4 * i + 1] == GL_FALSE) ? 0.0f : 1.0f;
1900         vector[i][2] = (v[4 * i + 2] == GL_FALSE) ? 0.0f : 1.0f;
1901         vector[i][3] = (v[4 * i + 3] == GL_FALSE) ? 0.0f : 1.0f;
1902     }
1903 
1904     applyUniformnfv(targetUniform, (GLfloat *)vector);
1905 }
1906 
clear(const ClearParameters & clearParams,const RenderTarget9 * colorRenderTarget,const RenderTarget9 * depthStencilRenderTarget)1907 void Renderer9::clear(const ClearParameters &clearParams,
1908                       const RenderTarget9 *colorRenderTarget,
1909                       const RenderTarget9 *depthStencilRenderTarget)
1910 {
1911     // Clearing buffers with non-float values is not supported by Renderer9 and ES 2.0
1912     ASSERT(clearParams.colorType == GL_FLOAT);
1913 
1914     // Clearing individual buffers other than buffer zero is not supported by Renderer9 and ES 2.0
1915     bool clearColor = clearParams.clearColor[0];
1916     for (unsigned int i = 0; i < clearParams.clearColor.size(); i++)
1917     {
1918         ASSERT(clearParams.clearColor[i] == clearColor);
1919     }
1920 
1921     float depth   = gl::clamp01(clearParams.depthValue);
1922     DWORD stencil = clearParams.stencilValue & 0x000000FF;
1923 
1924     unsigned int stencilUnmasked = 0x0;
1925     if (clearParams.clearStencil && depthStencilRenderTarget)
1926     {
1927         const gl::InternalFormat &depthStencilFormat =
1928             gl::GetSizedInternalFormatInfo(depthStencilRenderTarget->getInternalFormat());
1929         if (depthStencilFormat.stencilBits > 0)
1930         {
1931             const d3d9::D3DFormat &d3dFormatInfo =
1932                 d3d9::GetD3DFormatInfo(depthStencilRenderTarget->getD3DFormat());
1933             stencilUnmasked = (0x1 << d3dFormatInfo.stencilBits) - 1;
1934         }
1935     }
1936 
1937     const bool needMaskedStencilClear =
1938         clearParams.clearStencil &&
1939         (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1940 
1941     bool needMaskedColorClear = false;
1942     D3DCOLOR color            = D3DCOLOR_ARGB(255, 0, 0, 0);
1943     if (clearColor)
1944     {
1945         ASSERT(colorRenderTarget != nullptr);
1946 
1947         const gl::InternalFormat &formatInfo =
1948             gl::GetSizedInternalFormatInfo(colorRenderTarget->getInternalFormat());
1949         const d3d9::D3DFormat &d3dFormatInfo =
1950             d3d9::GetD3DFormatInfo(colorRenderTarget->getD3DFormat());
1951 
1952         color =
1953             D3DCOLOR_ARGB(gl::unorm<8>((formatInfo.alphaBits == 0 && d3dFormatInfo.alphaBits > 0)
1954                                            ? 1.0f
1955                                            : clearParams.colorF.alpha),
1956                           gl::unorm<8>((formatInfo.redBits == 0 && d3dFormatInfo.redBits > 0)
1957                                            ? 0.0f
1958                                            : clearParams.colorF.red),
1959                           gl::unorm<8>((formatInfo.greenBits == 0 && d3dFormatInfo.greenBits > 0)
1960                                            ? 0.0f
1961                                            : clearParams.colorF.green),
1962                           gl::unorm<8>((formatInfo.blueBits == 0 && d3dFormatInfo.blueBits > 0)
1963                                            ? 0.0f
1964                                            : clearParams.colorF.blue));
1965 
1966         const uint8_t colorMask =
1967             gl::BlendStateExt::ColorMaskStorage::GetValueIndexed(0, clearParams.colorMask);
1968         bool r, g, b, a;
1969         gl::BlendStateExt::UnpackColorMask(colorMask, &r, &g, &b, &a);
1970         if ((formatInfo.redBits > 0 && !r) || (formatInfo.greenBits > 0 && !g) ||
1971             (formatInfo.blueBits > 0 && !b) || (formatInfo.alphaBits > 0 && !a))
1972         {
1973             needMaskedColorClear = true;
1974         }
1975     }
1976 
1977     if (needMaskedColorClear || needMaskedStencilClear)
1978     {
1979         // State which is altered in all paths from this point to the clear call is saved.
1980         // State which is altered in only some paths will be flagged dirty in the case that
1981         //  that path is taken.
1982         HRESULT hr;
1983         if (mMaskedClearSavedState == nullptr)
1984         {
1985             hr = mDevice->BeginStateBlock();
1986             ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1987 
1988             mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1989             mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1990             mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1991             mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1992             mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1993             mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1994             mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1995             mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1996             mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1997             mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1998             mDevice->SetPixelShader(nullptr);
1999             mDevice->SetVertexShader(nullptr);
2000             mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2001             mDevice->SetStreamSource(0, nullptr, 0, 0);
2002             mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2003             mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2004             mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2005             mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2006             mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2007             mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2008             mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2009 
2010             for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2011             {
2012                 mDevice->SetStreamSourceFreq(i, 1);
2013             }
2014 
2015             hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2016             ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2017         }
2018 
2019         ASSERT(mMaskedClearSavedState != nullptr);
2020 
2021         if (mMaskedClearSavedState != nullptr)
2022         {
2023             hr = mMaskedClearSavedState->Capture();
2024             ASSERT(SUCCEEDED(hr));
2025         }
2026 
2027         mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2028         mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2029         mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2030         mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2031         mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2032         mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2033         mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2034         mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2035 
2036         if (clearColor)
2037         {
2038             // clearParams.colorMask follows the same packing scheme as
2039             // D3DCOLORWRITEENABLE_RED/GREEN/BLUE/ALPHA
2040             mDevice->SetRenderState(
2041                 D3DRS_COLORWRITEENABLE,
2042                 gl::BlendStateExt::ColorMaskStorage::GetValueIndexed(0, clearParams.colorMask));
2043         }
2044         else
2045         {
2046             mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2047         }
2048 
2049         if (stencilUnmasked != 0x0 && clearParams.clearStencil)
2050         {
2051             mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2052             mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2053             mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2054             mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2055             mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
2056             mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2057             mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2058             mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2059         }
2060         else
2061         {
2062             mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2063         }
2064 
2065         mDevice->SetPixelShader(nullptr);
2066         mDevice->SetVertexShader(nullptr);
2067         mDevice->SetFVF(D3DFVF_XYZRHW);
2068         mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2069         mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2070         mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2071         mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2072         mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2073         mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2074         mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2075 
2076         for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2077         {
2078             mDevice->SetStreamSourceFreq(i, 1);
2079         }
2080 
2081         int renderTargetWidth  = mStateManager.getRenderTargetWidth();
2082         int renderTargetHeight = mStateManager.getRenderTargetHeight();
2083 
2084         float quad[4][4];  // A quadrilateral covering the target, aligned to match the edges
2085         quad[0][0] = -0.5f;
2086         quad[0][1] = renderTargetHeight - 0.5f;
2087         quad[0][2] = 0.0f;
2088         quad[0][3] = 1.0f;
2089 
2090         quad[1][0] = renderTargetWidth - 0.5f;
2091         quad[1][1] = renderTargetHeight - 0.5f;
2092         quad[1][2] = 0.0f;
2093         quad[1][3] = 1.0f;
2094 
2095         quad[2][0] = -0.5f;
2096         quad[2][1] = -0.5f;
2097         quad[2][2] = 0.0f;
2098         quad[2][3] = 1.0f;
2099 
2100         quad[3][0] = renderTargetWidth - 0.5f;
2101         quad[3][1] = -0.5f;
2102         quad[3][2] = 0.0f;
2103         quad[3][3] = 1.0f;
2104 
2105         startScene();
2106         mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2107 
2108         if (clearParams.clearDepth)
2109         {
2110             mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
2111             mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
2112             mDevice->Clear(0, nullptr, D3DCLEAR_ZBUFFER, color, depth, stencil);
2113         }
2114 
2115         if (mMaskedClearSavedState != nullptr)
2116         {
2117             mMaskedClearSavedState->Apply();
2118         }
2119     }
2120     else if (clearColor || clearParams.clearDepth || clearParams.clearStencil)
2121     {
2122         DWORD dxClearFlags = 0;
2123         if (clearColor)
2124         {
2125             dxClearFlags |= D3DCLEAR_TARGET;
2126         }
2127         if (clearParams.clearDepth)
2128         {
2129             dxClearFlags |= D3DCLEAR_ZBUFFER;
2130         }
2131         if (clearParams.clearStencil)
2132         {
2133             dxClearFlags |= D3DCLEAR_STENCIL;
2134         }
2135 
2136         mDevice->Clear(0, nullptr, dxClearFlags, color, depth, stencil);
2137     }
2138 }
2139 
markAllStateDirty()2140 void Renderer9::markAllStateDirty()
2141 {
2142     mAppliedRenderTargetSerial   = 0;
2143     mAppliedDepthStencilSerial   = 0;
2144     mDepthStencilInitialized     = false;
2145     mRenderTargetDescInitialized = false;
2146 
2147     mStateManager.forceSetRasterState();
2148     mStateManager.forceSetDepthStencilState();
2149     mStateManager.forceSetBlendState();
2150     mStateManager.forceSetScissorState();
2151     mStateManager.forceSetViewportState();
2152 
2153     ASSERT(mCurVertexSamplerStates.size() == mCurVertexTextures.size());
2154     for (unsigned int i = 0; i < mCurVertexTextures.size(); i++)
2155     {
2156         mCurVertexSamplerStates[i].forceSet = true;
2157         mCurVertexTextures[i]               = angle::DirtyPointer;
2158     }
2159 
2160     ASSERT(mCurPixelSamplerStates.size() == mCurPixelTextures.size());
2161     for (unsigned int i = 0; i < mCurPixelSamplerStates.size(); i++)
2162     {
2163         mCurPixelSamplerStates[i].forceSet = true;
2164         mCurPixelTextures[i]               = angle::DirtyPointer;
2165     }
2166 
2167     mAppliedIBSerial      = 0;
2168     mAppliedVertexShader  = nullptr;
2169     mAppliedPixelShader   = nullptr;
2170     mAppliedProgramSerial = 0;
2171     mStateManager.forceSetDXUniformsState();
2172 
2173     mVertexDeclarationCache.markStateDirty();
2174 }
2175 
releaseDeviceResources()2176 void Renderer9::releaseDeviceResources()
2177 {
2178     for (size_t i = 0; i < mEventQueryPool.size(); i++)
2179     {
2180         SafeRelease(mEventQueryPool[i]);
2181     }
2182     mEventQueryPool.clear();
2183 
2184     SafeRelease(mMaskedClearSavedState);
2185 
2186     mVertexShaderCache.clear();
2187     mPixelShaderCache.clear();
2188 
2189     SafeDelete(mBlit);
2190     SafeDelete(mVertexDataManager);
2191     SafeDelete(mIndexDataManager);
2192     SafeDelete(mLineLoopIB);
2193     SafeDelete(mCountingIB);
2194 
2195     for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
2196     {
2197         SafeDelete(mNullRenderTargetCache[i].renderTarget);
2198     }
2199 }
2200 
2201 // set notify to true to broadcast a message to all contexts of the device loss
testDeviceLost()2202 bool Renderer9::testDeviceLost()
2203 {
2204     HRESULT status = getDeviceStatusCode();
2205     return FAILED(status);
2206 }
2207 
getDeviceStatusCode()2208 HRESULT Renderer9::getDeviceStatusCode()
2209 {
2210     HRESULT status = D3D_OK;
2211 
2212     if (mDeviceEx)
2213     {
2214         status = mDeviceEx->CheckDeviceState(nullptr);
2215     }
2216     else if (mDevice)
2217     {
2218         status = mDevice->TestCooperativeLevel();
2219     }
2220 
2221     return status;
2222 }
2223 
testDeviceResettable()2224 bool Renderer9::testDeviceResettable()
2225 {
2226     // On D3D9Ex, DEVICELOST represents a hung device that needs to be restarted
2227     // DEVICEREMOVED indicates the device has been stopped and must be recreated
2228     switch (getDeviceStatusCode())
2229     {
2230         case D3DERR_DEVICENOTRESET:
2231         case D3DERR_DEVICEHUNG:
2232             return true;
2233         case D3DERR_DEVICELOST:
2234             return (mDeviceEx != nullptr);
2235         case D3DERR_DEVICEREMOVED:
2236             ASSERT(mDeviceEx != nullptr);
2237             return isRemovedDeviceResettable();
2238         default:
2239             return false;
2240     }
2241 }
2242 
resetDevice()2243 bool Renderer9::resetDevice()
2244 {
2245     releaseDeviceResources();
2246 
2247     D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
2248 
2249     HRESULT result     = D3D_OK;
2250     bool lost          = testDeviceLost();
2251     bool removedDevice = (getDeviceStatusCode() == D3DERR_DEVICEREMOVED);
2252 
2253     // Device Removed is a feature which is only present with D3D9Ex
2254     ASSERT(mDeviceEx != nullptr || !removedDevice);
2255 
2256     for (int attempts = 3; lost && attempts > 0; attempts--)
2257     {
2258         if (removedDevice)
2259         {
2260             // Device removed, which may trigger on driver reinstallation,
2261             // may cause a longer wait other reset attempts before the
2262             // system is ready to handle creating a new device.
2263             Sleep(800);
2264             lost = !resetRemovedDevice();
2265         }
2266         else if (mDeviceEx)
2267         {
2268             Sleep(500);  // Give the graphics driver some CPU time
2269             result = mDeviceEx->ResetEx(&presentParameters, nullptr);
2270             lost   = testDeviceLost();
2271         }
2272         else
2273         {
2274             result = mDevice->TestCooperativeLevel();
2275             while (result == D3DERR_DEVICELOST)
2276             {
2277                 Sleep(100);  // Give the graphics driver some CPU time
2278                 result = mDevice->TestCooperativeLevel();
2279             }
2280 
2281             if (result == D3DERR_DEVICENOTRESET)
2282             {
2283                 result = mDevice->Reset(&presentParameters);
2284             }
2285             lost = testDeviceLost();
2286         }
2287     }
2288 
2289     if (FAILED(result))
2290     {
2291         ERR() << "Reset/ResetEx failed multiple times, " << gl::FmtHR(result);
2292         return false;
2293     }
2294 
2295     if (removedDevice && lost)
2296     {
2297         ERR() << "Device lost reset failed multiple times";
2298         return false;
2299     }
2300 
2301     // If the device was removed, we already finished re-initialization in resetRemovedDevice
2302     if (!removedDevice)
2303     {
2304         // reset device defaults
2305         if (initializeDevice().isError())
2306         {
2307             return false;
2308         }
2309     }
2310 
2311     return true;
2312 }
2313 
isRemovedDeviceResettable() const2314 bool Renderer9::isRemovedDeviceResettable() const
2315 {
2316     bool success = false;
2317 
2318 #if ANGLE_D3D9EX == ANGLE_ENABLED
2319     IDirect3D9Ex *d3d9Ex = nullptr;
2320     typedef HRESULT(WINAPI * Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex **);
2321     Direct3DCreate9ExFunc Direct3DCreate9ExPtr =
2322         reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
2323 
2324     if (Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &d3d9Ex)))
2325     {
2326         D3DCAPS9 deviceCaps;
2327         HRESULT result = d3d9Ex->GetDeviceCaps(mAdapter, mDeviceType, &deviceCaps);
2328         success        = SUCCEEDED(result);
2329     }
2330 
2331     SafeRelease(d3d9Ex);
2332 #else
2333     UNREACHABLE();
2334 #endif
2335 
2336     return success;
2337 }
2338 
resetRemovedDevice()2339 bool Renderer9::resetRemovedDevice()
2340 {
2341     // From http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx:
2342     // The hardware adapter has been removed. Application must destroy the device, do enumeration of
2343     // adapters and create another Direct3D device. If application continues rendering without
2344     // calling Reset, the rendering calls will succeed. Applies to Direct3D 9Ex only.
2345     release();
2346     return !initialize().isError();
2347 }
2348 
getVendorId() const2349 VendorID Renderer9::getVendorId() const
2350 {
2351     return static_cast<VendorID>(mAdapterIdentifier.VendorId);
2352 }
2353 
getRendererDescription() const2354 std::string Renderer9::getRendererDescription() const
2355 {
2356     std::ostringstream rendererString;
2357 
2358     rendererString << mAdapterIdentifier.Description;
2359     if (getShareHandleSupport())
2360     {
2361         rendererString << " Direct3D9Ex";
2362     }
2363     else
2364     {
2365         rendererString << " Direct3D9";
2366     }
2367 
2368     rendererString << " vs_" << D3DSHADER_VERSION_MAJOR(mDeviceCaps.VertexShaderVersion) << "_"
2369                    << D3DSHADER_VERSION_MINOR(mDeviceCaps.VertexShaderVersion);
2370     rendererString << " ps_" << D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion) << "_"
2371                    << D3DSHADER_VERSION_MINOR(mDeviceCaps.PixelShaderVersion);
2372 
2373     return rendererString.str();
2374 }
2375 
getAdapterIdentifier() const2376 DeviceIdentifier Renderer9::getAdapterIdentifier() const
2377 {
2378     DeviceIdentifier deviceIdentifier = {};
2379     deviceIdentifier.VendorId         = static_cast<UINT>(mAdapterIdentifier.VendorId);
2380     deviceIdentifier.DeviceId         = static_cast<UINT>(mAdapterIdentifier.DeviceId);
2381     deviceIdentifier.SubSysId         = static_cast<UINT>(mAdapterIdentifier.SubSysId);
2382     deviceIdentifier.Revision         = static_cast<UINT>(mAdapterIdentifier.Revision);
2383     deviceIdentifier.FeatureLevel     = 0;
2384 
2385     return deviceIdentifier;
2386 }
2387 
getReservedVertexUniformVectors() const2388 unsigned int Renderer9::getReservedVertexUniformVectors() const
2389 {
2390     return d3d9_gl::GetReservedVertexUniformVectors();
2391 }
2392 
getReservedFragmentUniformVectors() const2393 unsigned int Renderer9::getReservedFragmentUniformVectors() const
2394 {
2395     return d3d9_gl::GetReservedFragmentUniformVectors();
2396 }
2397 
getShareHandleSupport() const2398 bool Renderer9::getShareHandleSupport() const
2399 {
2400     // PIX doesn't seem to support using share handles, so disable them.
2401     return (mD3d9Ex != nullptr) && !gl::DebugAnnotationsActive();
2402 }
2403 
getMajorShaderModel() const2404 int Renderer9::getMajorShaderModel() const
2405 {
2406     return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
2407 }
2408 
getMinorShaderModel() const2409 int Renderer9::getMinorShaderModel() const
2410 {
2411     return D3DSHADER_VERSION_MINOR(mDeviceCaps.PixelShaderVersion);
2412 }
2413 
getShaderModelSuffix() const2414 std::string Renderer9::getShaderModelSuffix() const
2415 {
2416     return "";
2417 }
2418 
getCapsDeclTypes() const2419 DWORD Renderer9::getCapsDeclTypes() const
2420 {
2421     return mDeviceCaps.DeclTypes;
2422 }
2423 
getBufferPool(DWORD usage) const2424 D3DPOOL Renderer9::getBufferPool(DWORD usage) const
2425 {
2426     if (mD3d9Ex != nullptr)
2427     {
2428         return D3DPOOL_DEFAULT;
2429     }
2430     else
2431     {
2432         if (!(usage & D3DUSAGE_DYNAMIC))
2433         {
2434             return D3DPOOL_MANAGED;
2435         }
2436     }
2437 
2438     return D3DPOOL_DEFAULT;
2439 }
2440 
copyImage2D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2441 angle::Result Renderer9::copyImage2D(const gl::Context *context,
2442                                      const gl::Framebuffer *framebuffer,
2443                                      const gl::Rectangle &sourceRect,
2444                                      GLenum destFormat,
2445                                      const gl::Offset &destOffset,
2446                                      TextureStorage *storage,
2447                                      GLint level)
2448 {
2449     RECT rect;
2450     rect.left   = sourceRect.x;
2451     rect.top    = sourceRect.y;
2452     rect.right  = sourceRect.x + sourceRect.width;
2453     rect.bottom = sourceRect.y + sourceRect.height;
2454 
2455     return mBlit->copy2D(context, framebuffer, rect, destFormat, destOffset, storage, level);
2456 }
2457 
copyImageCube(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,gl::TextureTarget target,GLint level)2458 angle::Result Renderer9::copyImageCube(const gl::Context *context,
2459                                        const gl::Framebuffer *framebuffer,
2460                                        const gl::Rectangle &sourceRect,
2461                                        GLenum destFormat,
2462                                        const gl::Offset &destOffset,
2463                                        TextureStorage *storage,
2464                                        gl::TextureTarget target,
2465                                        GLint level)
2466 {
2467     RECT rect;
2468     rect.left   = sourceRect.x;
2469     rect.top    = sourceRect.y;
2470     rect.right  = sourceRect.x + sourceRect.width;
2471     rect.bottom = sourceRect.y + sourceRect.height;
2472 
2473     return mBlit->copyCube(context, framebuffer, rect, destFormat, destOffset, storage, target,
2474                            level);
2475 }
2476 
copyImage3D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2477 angle::Result Renderer9::copyImage3D(const gl::Context *context,
2478                                      const gl::Framebuffer *framebuffer,
2479                                      const gl::Rectangle &sourceRect,
2480                                      GLenum destFormat,
2481                                      const gl::Offset &destOffset,
2482                                      TextureStorage *storage,
2483                                      GLint level)
2484 {
2485     // 3D textures are not available in the D3D9 backend.
2486     ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2487     return angle::Result::Stop;
2488 }
2489 
copyImage2DArray(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2490 angle::Result Renderer9::copyImage2DArray(const gl::Context *context,
2491                                           const gl::Framebuffer *framebuffer,
2492                                           const gl::Rectangle &sourceRect,
2493                                           GLenum destFormat,
2494                                           const gl::Offset &destOffset,
2495                                           TextureStorage *storage,
2496                                           GLint level)
2497 {
2498     // 2D array textures are not available in the D3D9 backend.
2499     ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2500     return angle::Result::Stop;
2501 }
2502 
copyTexture(const gl::Context * context,const gl::Texture * source,GLint sourceLevel,gl::TextureTarget srcTarget,const gl::Box & sourceBox,GLenum destFormat,GLenum destType,const gl::Offset & destOffset,TextureStorage * storage,gl::TextureTarget destTarget,GLint destLevel,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha)2503 angle::Result Renderer9::copyTexture(const gl::Context *context,
2504                                      const gl::Texture *source,
2505                                      GLint sourceLevel,
2506                                      gl::TextureTarget srcTarget,
2507                                      const gl::Box &sourceBox,
2508                                      GLenum destFormat,
2509                                      GLenum destType,
2510                                      const gl::Offset &destOffset,
2511                                      TextureStorage *storage,
2512                                      gl::TextureTarget destTarget,
2513                                      GLint destLevel,
2514                                      bool unpackFlipY,
2515                                      bool unpackPremultiplyAlpha,
2516                                      bool unpackUnmultiplyAlpha)
2517 {
2518     RECT rect;
2519     rect.left   = sourceBox.x;
2520     rect.top    = sourceBox.y;
2521     rect.right  = sourceBox.x + sourceBox.width;
2522     rect.bottom = sourceBox.y + sourceBox.height;
2523 
2524     return mBlit->copyTexture(context, source, sourceLevel, rect, destFormat, destOffset, storage,
2525                               destTarget, destLevel, unpackFlipY, unpackPremultiplyAlpha,
2526                               unpackUnmultiplyAlpha);
2527 }
2528 
copyCompressedTexture(const gl::Context * context,const gl::Texture * source,GLint sourceLevel,TextureStorage * storage,GLint destLevel)2529 angle::Result Renderer9::copyCompressedTexture(const gl::Context *context,
2530                                                const gl::Texture *source,
2531                                                GLint sourceLevel,
2532                                                TextureStorage *storage,
2533                                                GLint destLevel)
2534 {
2535     ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2536     return angle::Result::Stop;
2537 }
2538 
createRenderTarget(const gl::Context * context,int width,int height,GLenum format,GLsizei samples,RenderTargetD3D ** outRT)2539 angle::Result Renderer9::createRenderTarget(const gl::Context *context,
2540                                             int width,
2541                                             int height,
2542                                             GLenum format,
2543                                             GLsizei samples,
2544                                             RenderTargetD3D **outRT)
2545 {
2546     const d3d9::TextureFormat &d3d9FormatInfo = d3d9::GetTextureFormatInfo(format);
2547 
2548     const gl::TextureCaps &textureCaps = getNativeTextureCaps().get(format);
2549     GLuint supportedSamples            = textureCaps.getNearestSamples(samples);
2550 
2551     IDirect3DTexture9 *texture      = nullptr;
2552     IDirect3DSurface9 *renderTarget = nullptr;
2553     if (width > 0 && height > 0)
2554     {
2555         bool requiresInitialization = false;
2556         HRESULT result              = D3DERR_INVALIDCALL;
2557 
2558         const gl::InternalFormat &formatInfo = gl::GetSizedInternalFormatInfo(format);
2559         if (formatInfo.depthBits > 0 || formatInfo.stencilBits > 0)
2560         {
2561             result = mDevice->CreateDepthStencilSurface(
2562                 width, height, d3d9FormatInfo.renderFormat,
2563                 gl_d3d9::GetMultisampleType(supportedSamples), 0, FALSE, &renderTarget, nullptr);
2564         }
2565         else
2566         {
2567             requiresInitialization = (d3d9FormatInfo.dataInitializerFunction != nullptr);
2568             if (supportedSamples > 0)
2569             {
2570                 result = mDevice->CreateRenderTarget(width, height, d3d9FormatInfo.renderFormat,
2571                                                      gl_d3d9::GetMultisampleType(supportedSamples),
2572                                                      0, FALSE, &renderTarget, nullptr);
2573             }
2574             else
2575             {
2576                 result = mDevice->CreateTexture(
2577                     width, height, 1, D3DUSAGE_RENDERTARGET, d3d9FormatInfo.texFormat,
2578                     getTexturePool(D3DUSAGE_RENDERTARGET), &texture, nullptr);
2579                 if (!FAILED(result))
2580                 {
2581                     result = texture->GetSurfaceLevel(0, &renderTarget);
2582                 }
2583             }
2584         }
2585 
2586         ANGLE_TRY_HR(GetImplAs<Context9>(context), result, "Failed to create render target");
2587 
2588         if (requiresInitialization)
2589         {
2590             // This format requires that the data be initialized before the render target can be
2591             // used Unfortunately this requires a Get call on the d3d device but it is far better
2592             // than having to mark the render target as lockable and copy data to the gpu.
2593             IDirect3DSurface9 *prevRenderTarget = nullptr;
2594             mDevice->GetRenderTarget(0, &prevRenderTarget);
2595             mDevice->SetRenderTarget(0, renderTarget);
2596             mDevice->Clear(0, nullptr, D3DCLEAR_TARGET, D3DCOLOR_RGBA(0, 0, 0, 255), 0.0f, 0);
2597             mDevice->SetRenderTarget(0, prevRenderTarget);
2598         }
2599     }
2600 
2601     *outRT = new TextureRenderTarget9(texture, 0, renderTarget, format, width, height, 1,
2602                                       supportedSamples);
2603     return angle::Result::Continue;
2604 }
2605 
createRenderTargetCopy(const gl::Context * context,RenderTargetD3D * source,RenderTargetD3D ** outRT)2606 angle::Result Renderer9::createRenderTargetCopy(const gl::Context *context,
2607                                                 RenderTargetD3D *source,
2608                                                 RenderTargetD3D **outRT)
2609 {
2610     ASSERT(source != nullptr);
2611 
2612     RenderTargetD3D *newRT = nullptr;
2613     ANGLE_TRY(createRenderTarget(context, source->getWidth(), source->getHeight(),
2614                                  source->getInternalFormat(), source->getSamples(), &newRT));
2615 
2616     RenderTarget9 *source9 = GetAs<RenderTarget9>(source);
2617     RenderTarget9 *dest9   = GetAs<RenderTarget9>(newRT);
2618 
2619     HRESULT result = mDevice->StretchRect(source9->getSurface(), nullptr, dest9->getSurface(),
2620                                           nullptr, D3DTEXF_NONE);
2621     ANGLE_TRY_HR(GetImplAs<Context9>(context), result, "Failed to copy render target");
2622 
2623     *outRT = newRT;
2624     return angle::Result::Continue;
2625 }
2626 
loadExecutable(d3d::Context * context,const uint8_t * function,size_t length,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,ShaderExecutableD3D ** outExecutable)2627 angle::Result Renderer9::loadExecutable(d3d::Context *context,
2628                                         const uint8_t *function,
2629                                         size_t length,
2630                                         gl::ShaderType type,
2631                                         const std::vector<D3DVarying> &streamOutVaryings,
2632                                         bool separatedOutputBuffers,
2633                                         ShaderExecutableD3D **outExecutable)
2634 {
2635     // Transform feedback is not supported in ES2 or D3D9
2636     ASSERT(streamOutVaryings.empty());
2637 
2638     switch (type)
2639     {
2640         case gl::ShaderType::Vertex:
2641         {
2642             IDirect3DVertexShader9 *vshader = nullptr;
2643             ANGLE_TRY(createVertexShader(context, (DWORD *)function, length, &vshader));
2644             *outExecutable = new ShaderExecutable9(function, length, vshader);
2645         }
2646         break;
2647         case gl::ShaderType::Fragment:
2648         {
2649             IDirect3DPixelShader9 *pshader = nullptr;
2650             ANGLE_TRY(createPixelShader(context, (DWORD *)function, length, &pshader));
2651             *outExecutable = new ShaderExecutable9(function, length, pshader);
2652         }
2653         break;
2654         default:
2655             ANGLE_HR_UNREACHABLE(context);
2656     }
2657 
2658     return angle::Result::Continue;
2659 }
2660 
compileToExecutable(d3d::Context * context,gl::InfoLog & infoLog,const std::string & shaderHLSL,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,const angle::CompilerWorkaroundsD3D & workarounds,ShaderExecutableD3D ** outExectuable)2661 angle::Result Renderer9::compileToExecutable(d3d::Context *context,
2662                                              gl::InfoLog &infoLog,
2663                                              const std::string &shaderHLSL,
2664                                              gl::ShaderType type,
2665                                              const std::vector<D3DVarying> &streamOutVaryings,
2666                                              bool separatedOutputBuffers,
2667                                              const angle::CompilerWorkaroundsD3D &workarounds,
2668                                              ShaderExecutableD3D **outExectuable)
2669 {
2670     // Transform feedback is not supported in ES2 or D3D9
2671     ASSERT(streamOutVaryings.empty());
2672 
2673     std::stringstream profileStream;
2674 
2675     switch (type)
2676     {
2677         case gl::ShaderType::Vertex:
2678             profileStream << "vs";
2679             break;
2680         case gl::ShaderType::Fragment:
2681             profileStream << "ps";
2682             break;
2683         default:
2684             ANGLE_HR_UNREACHABLE(context);
2685     }
2686 
2687     profileStream << "_" << ((getMajorShaderModel() >= 3) ? 3 : 2);
2688     profileStream << "_"
2689                   << "0";
2690 
2691     std::string profile = profileStream.str();
2692 
2693     UINT flags = ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2694 
2695     if (workarounds.skipOptimization)
2696     {
2697         flags = D3DCOMPILE_SKIP_OPTIMIZATION;
2698     }
2699     else if (workarounds.useMaxOptimization)
2700     {
2701         flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
2702     }
2703 
2704     if (gl::DebugAnnotationsActive())
2705     {
2706 #ifndef NDEBUG
2707         flags = D3DCOMPILE_SKIP_OPTIMIZATION;
2708 #endif
2709 
2710         flags |= D3DCOMPILE_DEBUG;
2711     }
2712 
2713     // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders
2714     // when it would otherwise pass with alternative options. Try the default flags first and if
2715     // compilation fails, try some alternatives.
2716     std::vector<CompileConfig> configs;
2717     configs.push_back(CompileConfig(flags, "default"));
2718     configs.push_back(CompileConfig(flags | D3DCOMPILE_AVOID_FLOW_CONTROL, "avoid flow control"));
2719     configs.push_back(CompileConfig(flags | D3DCOMPILE_PREFER_FLOW_CONTROL, "prefer flow control"));
2720 
2721     ID3DBlob *binary = nullptr;
2722     std::string debugInfo;
2723     angle::Result error = mCompiler.compileToBinary(context, infoLog, shaderHLSL, profile, configs,
2724                                                     nullptr, &binary, &debugInfo);
2725     ANGLE_TRY(error);
2726 
2727     // It's possible that binary is NULL if the compiler failed in all configurations.  Set the
2728     // executable to NULL and return GL_NO_ERROR to signify that there was a link error but the
2729     // internal state is still OK.
2730     if (!binary)
2731     {
2732         *outExectuable = nullptr;
2733         return angle::Result::Continue;
2734     }
2735 
2736     error = loadExecutable(context, reinterpret_cast<const uint8_t *>(binary->GetBufferPointer()),
2737                            binary->GetBufferSize(), type, streamOutVaryings, separatedOutputBuffers,
2738                            outExectuable);
2739 
2740     SafeRelease(binary);
2741     ANGLE_TRY(error);
2742 
2743     if (!debugInfo.empty())
2744     {
2745         (*outExectuable)->appendDebugInfo(debugInfo);
2746     }
2747 
2748     return angle::Result::Continue;
2749 }
2750 
ensureHLSLCompilerInitialized(d3d::Context * context)2751 angle::Result Renderer9::ensureHLSLCompilerInitialized(d3d::Context *context)
2752 {
2753     return mCompiler.ensureInitialized(context);
2754 }
2755 
createUniformStorage(size_t storageSize)2756 UniformStorageD3D *Renderer9::createUniformStorage(size_t storageSize)
2757 {
2758     return new UniformStorageD3D(storageSize);
2759 }
2760 
boxFilter(Context9 * context9,IDirect3DSurface9 * source,IDirect3DSurface9 * dest)2761 angle::Result Renderer9::boxFilter(Context9 *context9,
2762                                    IDirect3DSurface9 *source,
2763                                    IDirect3DSurface9 *dest)
2764 {
2765     return mBlit->boxFilter(context9, source, dest);
2766 }
2767 
getTexturePool(DWORD usage) const2768 D3DPOOL Renderer9::getTexturePool(DWORD usage) const
2769 {
2770     if (mD3d9Ex != nullptr)
2771     {
2772         return D3DPOOL_DEFAULT;
2773     }
2774     else
2775     {
2776         if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2777         {
2778             return D3DPOOL_MANAGED;
2779         }
2780     }
2781 
2782     return D3DPOOL_DEFAULT;
2783 }
2784 
copyToRenderTarget(const gl::Context * context,IDirect3DSurface9 * dest,IDirect3DSurface9 * source,bool fromManaged)2785 angle::Result Renderer9::copyToRenderTarget(const gl::Context *context,
2786                                             IDirect3DSurface9 *dest,
2787                                             IDirect3DSurface9 *source,
2788                                             bool fromManaged)
2789 {
2790     ASSERT(source && dest);
2791 
2792     Context9 *context9 = GetImplAs<Context9>(context);
2793 
2794     HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2795 
2796     if (fromManaged)
2797     {
2798         D3DSURFACE_DESC desc;
2799         source->GetDesc(&desc);
2800 
2801         IDirect3DSurface9 *surf = 0;
2802         result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2803                                                       D3DPOOL_SYSTEMMEM, &surf, nullptr);
2804 
2805         if (SUCCEEDED(result))
2806         {
2807             ANGLE_TRY(Image9::CopyLockableSurfaces(context9, surf, source));
2808             result = mDevice->UpdateSurface(surf, nullptr, dest, nullptr);
2809             SafeRelease(surf);
2810         }
2811     }
2812     else
2813     {
2814         endScene();
2815         result = mDevice->StretchRect(source, nullptr, dest, nullptr, D3DTEXF_NONE);
2816     }
2817 
2818     ANGLE_TRY_HR(context9, result, "Failed to blit internal texture");
2819     return angle::Result::Continue;
2820 }
2821 
getRendererClass() const2822 RendererClass Renderer9::getRendererClass() const
2823 {
2824     return RENDERER_D3D9;
2825 }
2826 
createImage()2827 ImageD3D *Renderer9::createImage()
2828 {
2829     return new Image9(this);
2830 }
2831 
createExternalImageSibling(const gl::Context * context,EGLenum target,EGLClientBuffer buffer,const egl::AttributeMap & attribs)2832 ExternalImageSiblingImpl *Renderer9::createExternalImageSibling(const gl::Context *context,
2833                                                                 EGLenum target,
2834                                                                 EGLClientBuffer buffer,
2835                                                                 const egl::AttributeMap &attribs)
2836 {
2837     UNREACHABLE();
2838     return nullptr;
2839 }
2840 
generateMipmap(const gl::Context * context,ImageD3D * dest,ImageD3D * src)2841 angle::Result Renderer9::generateMipmap(const gl::Context *context, ImageD3D *dest, ImageD3D *src)
2842 {
2843     Image9 *src9 = GetAs<Image9>(src);
2844     Image9 *dst9 = GetAs<Image9>(dest);
2845     return Image9::GenerateMipmap(GetImplAs<Context9>(context), dst9, src9);
2846 }
2847 
generateMipmapUsingD3D(const gl::Context * context,TextureStorage * storage,const gl::TextureState & textureState)2848 angle::Result Renderer9::generateMipmapUsingD3D(const gl::Context *context,
2849                                                 TextureStorage *storage,
2850                                                 const gl::TextureState &textureState)
2851 {
2852     ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2853     return angle::Result::Stop;
2854 }
2855 
copyImage(const gl::Context * context,ImageD3D * dest,ImageD3D * source,const gl::Box & sourceBox,const gl::Offset & destOffset,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha)2856 angle::Result Renderer9::copyImage(const gl::Context *context,
2857                                    ImageD3D *dest,
2858                                    ImageD3D *source,
2859                                    const gl::Box &sourceBox,
2860                                    const gl::Offset &destOffset,
2861                                    bool unpackFlipY,
2862                                    bool unpackPremultiplyAlpha,
2863                                    bool unpackUnmultiplyAlpha)
2864 {
2865     Image9 *dest9 = GetAs<Image9>(dest);
2866     Image9 *src9  = GetAs<Image9>(source);
2867     return Image9::CopyImage(context, dest9, src9, sourceBox.toRect(), destOffset, unpackFlipY,
2868                              unpackPremultiplyAlpha, unpackUnmultiplyAlpha);
2869 }
2870 
createTextureStorage2D(SwapChainD3D * swapChain,const std::string & label)2871 TextureStorage *Renderer9::createTextureStorage2D(SwapChainD3D *swapChain, const std::string &label)
2872 {
2873     SwapChain9 *swapChain9 = GetAs<SwapChain9>(swapChain);
2874     return new TextureStorage9_2D(this, swapChain9, label);
2875 }
2876 
createTextureStorageEGLImage(EGLImageD3D * eglImage,RenderTargetD3D * renderTargetD3D,const std::string & label)2877 TextureStorage *Renderer9::createTextureStorageEGLImage(EGLImageD3D *eglImage,
2878                                                         RenderTargetD3D *renderTargetD3D,
2879                                                         const std::string &label)
2880 {
2881     return new TextureStorage9_EGLImage(this, eglImage, GetAs<RenderTarget9>(renderTargetD3D),
2882                                         label);
2883 }
2884 
createTextureStorageExternal(egl::Stream * stream,const egl::Stream::GLTextureDescription & desc,const std::string & label)2885 TextureStorage *Renderer9::createTextureStorageExternal(
2886     egl::Stream *stream,
2887     const egl::Stream::GLTextureDescription &desc,
2888     const std::string &label)
2889 {
2890     UNIMPLEMENTED();
2891     return nullptr;
2892 }
2893 
createTextureStorage2D(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,int levels,const std::string & label,bool hintLevelZeroOnly)2894 TextureStorage *Renderer9::createTextureStorage2D(GLenum internalformat,
2895                                                   bool renderTarget,
2896                                                   GLsizei width,
2897                                                   GLsizei height,
2898                                                   int levels,
2899                                                   const std::string &label,
2900                                                   bool hintLevelZeroOnly)
2901 {
2902     return new TextureStorage9_2D(this, internalformat, renderTarget, width, height, levels, label);
2903 }
2904 
createTextureStorageCube(GLenum internalformat,bool renderTarget,int size,int levels,bool hintLevelZeroOnly,const std::string & label)2905 TextureStorage *Renderer9::createTextureStorageCube(GLenum internalformat,
2906                                                     bool renderTarget,
2907                                                     int size,
2908                                                     int levels,
2909                                                     bool hintLevelZeroOnly,
2910                                                     const std::string &label)
2911 {
2912     return new TextureStorage9_Cube(this, internalformat, renderTarget, size, levels,
2913                                     hintLevelZeroOnly, label);
2914 }
2915 
createTextureStorage3D(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,GLsizei depth,int levels,const std::string & label)2916 TextureStorage *Renderer9::createTextureStorage3D(GLenum internalformat,
2917                                                   bool renderTarget,
2918                                                   GLsizei width,
2919                                                   GLsizei height,
2920                                                   GLsizei depth,
2921                                                   int levels,
2922                                                   const std::string &label)
2923 {
2924     // 3D textures are not supported by the D3D9 backend.
2925     UNREACHABLE();
2926 
2927     return nullptr;
2928 }
2929 
createTextureStorage2DArray(GLenum internalformat,bool renderTarget,GLsizei width,GLsizei height,GLsizei depth,int levels,const std::string & label)2930 TextureStorage *Renderer9::createTextureStorage2DArray(GLenum internalformat,
2931                                                        bool renderTarget,
2932                                                        GLsizei width,
2933                                                        GLsizei height,
2934                                                        GLsizei depth,
2935                                                        int levels,
2936                                                        const std::string &label)
2937 {
2938     // 2D array textures are not supported by the D3D9 backend.
2939     UNREACHABLE();
2940 
2941     return nullptr;
2942 }
2943 
createTextureStorage2DMultisample(GLenum internalformat,GLsizei width,GLsizei height,int levels,int samples,bool fixedSampleLocations,const std::string & label)2944 TextureStorage *Renderer9::createTextureStorage2DMultisample(GLenum internalformat,
2945                                                              GLsizei width,
2946                                                              GLsizei height,
2947                                                              int levels,
2948                                                              int samples,
2949                                                              bool fixedSampleLocations,
2950                                                              const std::string &label)
2951 {
2952     // 2D multisampled textures are not supported by the D3D9 backend.
2953     UNREACHABLE();
2954 
2955     return nullptr;
2956 }
2957 
createTextureStorage2DMultisampleArray(GLenum internalformat,GLsizei width,GLsizei height,GLsizei depth,int levels,int samples,bool fixedSampleLocations,const std::string & label)2958 TextureStorage *Renderer9::createTextureStorage2DMultisampleArray(GLenum internalformat,
2959                                                                   GLsizei width,
2960                                                                   GLsizei height,
2961                                                                   GLsizei depth,
2962                                                                   int levels,
2963                                                                   int samples,
2964                                                                   bool fixedSampleLocations,
2965                                                                   const std::string &label)
2966 {
2967     // 2D multisampled textures are not supported by the D3D9 backend.
2968     UNREACHABLE();
2969 
2970     return nullptr;
2971 }
2972 
getLUID(LUID * adapterLuid) const2973 bool Renderer9::getLUID(LUID *adapterLuid) const
2974 {
2975     adapterLuid->HighPart = 0;
2976     adapterLuid->LowPart  = 0;
2977 
2978     if (mD3d9Ex)
2979     {
2980         mD3d9Ex->GetAdapterLUID(mAdapter, adapterLuid);
2981         return true;
2982     }
2983 
2984     return false;
2985 }
2986 
getVertexConversionType(angle::FormatID vertexFormatID) const2987 VertexConversionType Renderer9::getVertexConversionType(angle::FormatID vertexFormatID) const
2988 {
2989     return d3d9::GetVertexFormatInfo(getCapsDeclTypes(), vertexFormatID).conversionType;
2990 }
2991 
getVertexComponentType(angle::FormatID vertexFormatID) const2992 GLenum Renderer9::getVertexComponentType(angle::FormatID vertexFormatID) const
2993 {
2994     return d3d9::GetVertexFormatInfo(getCapsDeclTypes(), vertexFormatID).componentType;
2995 }
2996 
getVertexSpaceRequired(const gl::Context * context,const gl::VertexAttribute & attrib,const gl::VertexBinding & binding,size_t count,GLsizei instances,GLuint baseInstance,unsigned int * bytesRequiredOut) const2997 angle::Result Renderer9::getVertexSpaceRequired(const gl::Context *context,
2998                                                 const gl::VertexAttribute &attrib,
2999                                                 const gl::VertexBinding &binding,
3000                                                 size_t count,
3001                                                 GLsizei instances,
3002                                                 GLuint baseInstance,
3003                                                 unsigned int *bytesRequiredOut) const
3004 {
3005     if (!attrib.enabled)
3006     {
3007         *bytesRequiredOut = 16u;
3008         return angle::Result::Continue;
3009     }
3010 
3011     angle::FormatID vertexFormatID = gl::GetVertexFormatID(attrib, gl::VertexAttribType::Float);
3012     const d3d9::VertexFormat &d3d9VertexInfo =
3013         d3d9::GetVertexFormatInfo(getCapsDeclTypes(), vertexFormatID);
3014 
3015     unsigned int elementCount  = 0;
3016     const unsigned int divisor = binding.getDivisor();
3017     if (instances == 0 || divisor == 0)
3018     {
3019         elementCount = static_cast<unsigned int>(count);
3020     }
3021     else
3022     {
3023         // Round up to divisor, if possible
3024         elementCount = UnsignedCeilDivide(static_cast<unsigned int>(instances), divisor);
3025     }
3026 
3027     bool check = (d3d9VertexInfo.outputElementSize >
3028                   std::numeric_limits<unsigned int>::max() / elementCount);
3029     ANGLE_CHECK(GetImplAs<Context9>(context), !check,
3030                 "New vertex buffer size would result in an overflow.", GL_OUT_OF_MEMORY);
3031 
3032     *bytesRequiredOut = static_cast<unsigned int>(d3d9VertexInfo.outputElementSize) * elementCount;
3033     return angle::Result::Continue;
3034 }
3035 
generateCaps(gl::Caps * outCaps,gl::TextureCapsMap * outTextureCaps,gl::Extensions * outExtensions,gl::Limitations * outLimitations) const3036 void Renderer9::generateCaps(gl::Caps *outCaps,
3037                              gl::TextureCapsMap *outTextureCaps,
3038                              gl::Extensions *outExtensions,
3039                              gl::Limitations *outLimitations) const
3040 {
3041     d3d9_gl::GenerateCaps(mD3d9, mDevice, mDeviceType, mAdapter, outCaps, outTextureCaps,
3042                           outExtensions, outLimitations);
3043 }
3044 
initializeFeatures(angle::FeaturesD3D * features) const3045 void Renderer9::initializeFeatures(angle::FeaturesD3D *features) const
3046 {
3047     if (!mDisplay->getState().featuresAllDisabled)
3048     {
3049         d3d9::InitializeFeatures(features);
3050     }
3051     ApplyFeatureOverrides(features, mDisplay->getState());
3052 }
3053 
createEGLDevice()3054 DeviceImpl *Renderer9::createEGLDevice()
3055 {
3056     return new DeviceD3D(EGL_D3D9_DEVICE_ANGLE, mDevice);
3057 }
3058 
CurSamplerState()3059 Renderer9::CurSamplerState::CurSamplerState()
3060     : forceSet(true), baseLevel(std::numeric_limits<size_t>::max()), samplerState()
3061 {}
3062 
genericDrawElements(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances)3063 angle::Result Renderer9::genericDrawElements(const gl::Context *context,
3064                                              gl::PrimitiveMode mode,
3065                                              GLsizei count,
3066                                              gl::DrawElementsType type,
3067                                              const void *indices,
3068                                              GLsizei instances)
3069 {
3070     const gl::State &state = context->getState();
3071     gl::Program *program   = context->getState().getProgram();
3072     ASSERT(program != nullptr);
3073     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program);
3074     bool usesPointSize     = programD3D->usesPointSize();
3075 
3076     programD3D->updateSamplerMapping();
3077 
3078     if (!applyPrimitiveType(mode, count, usesPointSize))
3079     {
3080         return angle::Result::Continue;
3081     }
3082 
3083     ANGLE_TRY(updateState(context, mode));
3084     ANGLE_TRY(applyTextures(context));
3085     ANGLE_TRY(applyShaders(context, mode));
3086 
3087     if (!skipDraw(state, mode))
3088     {
3089         ANGLE_TRY(drawElementsImpl(context, mode, count, type, indices, instances));
3090     }
3091 
3092     return angle::Result::Continue;
3093 }
3094 
genericDrawArrays(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count,GLsizei instances)3095 angle::Result Renderer9::genericDrawArrays(const gl::Context *context,
3096                                            gl::PrimitiveMode mode,
3097                                            GLint first,
3098                                            GLsizei count,
3099                                            GLsizei instances)
3100 {
3101     gl::Program *program = context->getState().getProgram();
3102     ASSERT(program != nullptr);
3103     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program);
3104     bool usesPointSize     = programD3D->usesPointSize();
3105 
3106     programD3D->updateSamplerMapping();
3107 
3108     if (!applyPrimitiveType(mode, count, usesPointSize))
3109     {
3110         return angle::Result::Continue;
3111     }
3112 
3113     ANGLE_TRY(updateState(context, mode));
3114     ANGLE_TRY(applyVertexBuffer(context, mode, first, count, instances, nullptr));
3115     ANGLE_TRY(applyTextures(context));
3116     ANGLE_TRY(applyShaders(context, mode));
3117 
3118     if (!skipDraw(context->getState(), mode))
3119     {
3120         ANGLE_TRY(drawArraysImpl(context, mode, first, count, instances));
3121     }
3122 
3123     return angle::Result::Continue;
3124 }
3125 
createDefaultFramebuffer(const gl::FramebufferState & state)3126 FramebufferImpl *Renderer9::createDefaultFramebuffer(const gl::FramebufferState &state)
3127 {
3128     return new Framebuffer9(state, this);
3129 }
3130 
getMaxSupportedESVersion() const3131 gl::Version Renderer9::getMaxSupportedESVersion() const
3132 {
3133     return gl::Version(2, 0);
3134 }
3135 
getMaxConformantESVersion() const3136 gl::Version Renderer9::getMaxConformantESVersion() const
3137 {
3138     return gl::Version(2, 0);
3139 }
3140 
clearRenderTarget(const gl::Context * context,RenderTargetD3D * renderTarget,const gl::ColorF & clearColorValue,const float clearDepthValue,const unsigned int clearStencilValue)3141 angle::Result Renderer9::clearRenderTarget(const gl::Context *context,
3142                                            RenderTargetD3D *renderTarget,
3143                                            const gl::ColorF &clearColorValue,
3144                                            const float clearDepthValue,
3145                                            const unsigned int clearStencilValue)
3146 {
3147     D3DCOLOR color =
3148         D3DCOLOR_ARGB(gl::unorm<8>(clearColorValue.alpha), gl::unorm<8>(clearColorValue.red),
3149                       gl::unorm<8>(clearColorValue.green), gl::unorm<8>(clearColorValue.blue));
3150     float depth   = clearDepthValue;
3151     DWORD stencil = clearStencilValue & 0x000000FF;
3152 
3153     unsigned int renderTargetSerial        = renderTarget->getSerial();
3154     RenderTarget9 *renderTarget9           = GetAs<RenderTarget9>(renderTarget);
3155     IDirect3DSurface9 *renderTargetSurface = renderTarget9->getSurface();
3156     ASSERT(renderTargetSurface);
3157 
3158     DWORD dxClearFlags = 0;
3159 
3160     const gl::InternalFormat &internalFormatInfo =
3161         gl::GetSizedInternalFormatInfo(renderTarget->getInternalFormat());
3162     if (internalFormatInfo.depthBits > 0 || internalFormatInfo.stencilBits > 0)
3163     {
3164         dxClearFlags = D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL;
3165         if (mAppliedDepthStencilSerial != renderTargetSerial)
3166         {
3167             mDevice->SetDepthStencilSurface(renderTargetSurface);
3168         }
3169     }
3170     else
3171     {
3172         dxClearFlags = D3DCLEAR_TARGET;
3173         if (mAppliedRenderTargetSerial != renderTargetSerial)
3174         {
3175             mDevice->SetRenderTarget(0, renderTargetSurface);
3176         }
3177     }
3178     SafeRelease(renderTargetSurface);
3179 
3180     D3DVIEWPORT9 viewport;
3181     viewport.X      = 0;
3182     viewport.Y      = 0;
3183     viewport.Width  = renderTarget->getWidth();
3184     viewport.Height = renderTarget->getHeight();
3185     mDevice->SetViewport(&viewport);
3186 
3187     mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
3188 
3189     mDevice->Clear(0, nullptr, dxClearFlags, color, depth, stencil);
3190 
3191     markAllStateDirty();
3192 
3193     return angle::Result::Continue;
3194 }
3195 
canSelectViewInVertexShader() const3196 bool Renderer9::canSelectViewInVertexShader() const
3197 {
3198     return false;
3199 }
3200 
3201 // For each Direct3D sampler of either the pixel or vertex stage,
3202 // looks up the corresponding OpenGL texture image unit and texture type,
3203 // and sets the texture and its addressing/filtering state (or NULL when inactive).
3204 // Sampler mapping needs to be up-to-date on the program object before this is called.
applyTextures(const gl::Context * context,gl::ShaderType shaderType)3205 angle::Result Renderer9::applyTextures(const gl::Context *context, gl::ShaderType shaderType)
3206 {
3207     const auto &glState    = context->getState();
3208     const auto &caps       = context->getCaps();
3209     ProgramD3D *programD3D = GetImplAs<ProgramD3D>(glState.getProgram());
3210 
3211     ASSERT(!programD3D->isSamplerMappingDirty());
3212 
3213     // TODO(jmadill): Use the Program's sampler bindings.
3214     const gl::ActiveTexturesCache &activeTextures = glState.getActiveTexturesCache();
3215 
3216     const gl::RangeUI samplerRange = programD3D->getUsedSamplerRange(shaderType);
3217     for (unsigned int samplerIndex = samplerRange.low(); samplerIndex < samplerRange.high();
3218          samplerIndex++)
3219     {
3220         GLint textureUnit = programD3D->getSamplerMapping(shaderType, samplerIndex, caps);
3221         ASSERT(textureUnit != -1);
3222         gl::Texture *texture = activeTextures[textureUnit];
3223 
3224         // A nullptr texture indicates incomplete.
3225         if (texture)
3226         {
3227             gl::Sampler *samplerObject = glState.getSampler(textureUnit);
3228 
3229             const gl::SamplerState &samplerState =
3230                 samplerObject ? samplerObject->getSamplerState() : texture->getSamplerState();
3231 
3232             ANGLE_TRY(setSamplerState(context, shaderType, samplerIndex, texture, samplerState));
3233             ANGLE_TRY(setTexture(context, shaderType, samplerIndex, texture));
3234         }
3235         else
3236         {
3237             gl::TextureType textureType =
3238                 programD3D->getSamplerTextureType(shaderType, samplerIndex);
3239 
3240             // Texture is not sampler complete or it is in use by the framebuffer.  Bind the
3241             // incomplete texture.
3242             gl::Texture *incompleteTexture = nullptr;
3243             ANGLE_TRY(getIncompleteTexture(context, textureType, &incompleteTexture));
3244             ANGLE_TRY(setSamplerState(context, shaderType, samplerIndex, incompleteTexture,
3245                                       incompleteTexture->getSamplerState()));
3246             ANGLE_TRY(setTexture(context, shaderType, samplerIndex, incompleteTexture));
3247         }
3248     }
3249 
3250     // Set all the remaining textures to NULL
3251     int samplerCount = (shaderType == gl::ShaderType::Fragment)
3252                            ? caps.maxShaderTextureImageUnits[gl::ShaderType::Fragment]
3253                            : caps.maxShaderTextureImageUnits[gl::ShaderType::Vertex];
3254 
3255     // TODO(jmadill): faster way?
3256     for (int samplerIndex = samplerRange.high(); samplerIndex < samplerCount; samplerIndex++)
3257     {
3258         ANGLE_TRY(setTexture(context, shaderType, samplerIndex, nullptr));
3259     }
3260 
3261     return angle::Result::Continue;
3262 }
3263 
applyTextures(const gl::Context * context)3264 angle::Result Renderer9::applyTextures(const gl::Context *context)
3265 {
3266     ANGLE_TRY(applyTextures(context, gl::ShaderType::Vertex));
3267     ANGLE_TRY(applyTextures(context, gl::ShaderType::Fragment));
3268     return angle::Result::Continue;
3269 }
3270 
getIncompleteTexture(const gl::Context * context,gl::TextureType type,gl::Texture ** textureOut)3271 angle::Result Renderer9::getIncompleteTexture(const gl::Context *context,
3272                                               gl::TextureType type,
3273                                               gl::Texture **textureOut)
3274 {
3275     return GetImplAs<Context9>(context)->getIncompleteTexture(context, type, textureOut);
3276 }
3277 
ensureVertexDataManagerInitialized(const gl::Context * context)3278 angle::Result Renderer9::ensureVertexDataManagerInitialized(const gl::Context *context)
3279 {
3280     if (!mVertexDataManager)
3281     {
3282         mVertexDataManager = new VertexDataManager(this);
3283         ANGLE_TRY(mVertexDataManager->initialize(context));
3284     }
3285 
3286     return angle::Result::Continue;
3287 }
3288 
getVendorString() const3289 std::string Renderer9::getVendorString() const
3290 {
3291     return GetVendorString(getVendorId());
3292 }
3293 
getVersionString() const3294 std::string Renderer9::getVersionString() const
3295 {
3296     std::ostringstream versionString;
3297     std::string driverName(mAdapterIdentifier.Driver);
3298     if (!driverName.empty())
3299     {
3300         versionString << mAdapterIdentifier.Driver;
3301     }
3302     else
3303     {
3304         versionString << "D3D9 ";
3305     }
3306     versionString << "-";
3307     versionString << GetDriverVersionString(mAdapterIdentifier.DriverVersion);
3308 
3309     return versionString.str();
3310 }
3311 
CreateRenderer9(egl::Display * display)3312 RendererD3D *CreateRenderer9(egl::Display *display)
3313 {
3314     return new Renderer9(display);
3315 }
3316 
3317 }  // namespace rx
3318