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 (static_cast<bool>(ANGLE_D3D9EX) && 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, ¤tDisplayMode);
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, ¤tDisplayMode);
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.getEGLConfigBufferSize();
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->noConfigContext = 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->robustResourceInitializationANGLE = 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 std::this_thread::yield();
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().textureFilterAnisotropicEXT)
1023 {
1024 DWORD maxAnisotropy = std::min(mDeviceCaps.MaxAnisotropy,
1025 static_cast<DWORD>(samplerState.getMaxAnisotropy()));
1026 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, maxAnisotropy);
1027 }
1028
1029 const gl::InternalFormat &info =
1030 gl::GetSizedInternalFormatInfo(textureD3D->getBaseLevelInternalFormat());
1031
1032 mDevice->SetSamplerState(d3dSampler, D3DSAMP_SRGBTEXTURE, info.colorEncoding == GL_SRGB);
1033
1034 if (samplerState.usesBorderColor())
1035 {
1036 angle::ColorGeneric borderColor = texture->getBorderColor();
1037 ASSERT(borderColor.type == angle::ColorGeneric::Type::Float);
1038
1039 // Enforce opaque alpha for opaque formats, excluding DXT1 RGBA as it has no bits info.
1040 if (info.alphaBits == 0 && info.componentCount < 4)
1041 {
1042 borderColor.colorF.alpha = 1.0f;
1043 }
1044
1045 if (info.isLUMA())
1046 {
1047 if (info.luminanceBits == 0)
1048 {
1049 borderColor.colorF.red = 0.0f;
1050 }
1051 // Older Intel drivers use RGBA border color when sampling from D3DFMT_A8L8.
1052 // However, some recent Intel drivers sample alpha from green border channel
1053 // when using this format. Assume the old behavior because newer GPUs should
1054 // use D3D11 anyway.
1055 borderColor.colorF.green = borderColor.colorF.red;
1056 borderColor.colorF.blue = borderColor.colorF.red;
1057 }
1058
1059 D3DCOLOR d3dBorderColor;
1060 if (info.colorEncoding == GL_SRGB && getFeatures().borderColorSrgb.enabled)
1061 {
1062 d3dBorderColor =
1063 D3DCOLOR_RGBA(gl::linearToSRGB(gl::clamp01(borderColor.colorF.red)),
1064 gl::linearToSRGB(gl::clamp01(borderColor.colorF.green)),
1065 gl::linearToSRGB(gl::clamp01(borderColor.colorF.blue)),
1066 gl::unorm<8>(borderColor.colorF.alpha));
1067 }
1068 else
1069 {
1070 d3dBorderColor = gl_d3d9::ConvertColor(borderColor.colorF);
1071 }
1072
1073 mDevice->SetSamplerState(d3dSampler, D3DSAMP_BORDERCOLOR, d3dBorderColor);
1074 }
1075 }
1076
1077 appliedSampler.forceSet = false;
1078 appliedSampler.samplerState = samplerState;
1079 appliedSampler.baseLevel = baseLevel;
1080
1081 return angle::Result::Continue;
1082 }
1083
setTexture(const gl::Context * context,gl::ShaderType type,int index,gl::Texture * texture)1084 angle::Result Renderer9::setTexture(const gl::Context *context,
1085 gl::ShaderType type,
1086 int index,
1087 gl::Texture *texture)
1088 {
1089 int d3dSamplerOffset = (type == gl::ShaderType::Fragment) ? 0 : D3DVERTEXTEXTURESAMPLER0;
1090 int d3dSampler = index + d3dSamplerOffset;
1091 IDirect3DBaseTexture9 *d3dTexture = nullptr;
1092 bool forceSetTexture = false;
1093
1094 std::vector<uintptr_t> &appliedTextures =
1095 (type == gl::ShaderType::Fragment) ? mCurPixelTextures : mCurVertexTextures;
1096
1097 if (texture)
1098 {
1099 TextureD3D *textureImpl = GetImplAs<TextureD3D>(texture);
1100
1101 TextureStorage *texStorage = nullptr;
1102 ANGLE_TRY(textureImpl->getNativeTexture(context, &texStorage));
1103
1104 // Texture should be complete and have a storage
1105 ASSERT(texStorage);
1106
1107 TextureStorage9 *storage9 = GetAs<TextureStorage9>(texStorage);
1108 ANGLE_TRY(storage9->getBaseTexture(context, &d3dTexture));
1109
1110 // If we get NULL back from getBaseTexture here, something went wrong
1111 // in the texture class and we're unexpectedly missing the d3d texture
1112 ASSERT(d3dTexture != nullptr);
1113
1114 forceSetTexture = textureImpl->hasDirtyImages();
1115 textureImpl->resetDirty();
1116 }
1117
1118 if (forceSetTexture || appliedTextures[index] != reinterpret_cast<uintptr_t>(d3dTexture))
1119 {
1120 mDevice->SetTexture(d3dSampler, d3dTexture);
1121 }
1122
1123 appliedTextures[index] = reinterpret_cast<uintptr_t>(d3dTexture);
1124
1125 return angle::Result::Continue;
1126 }
1127
updateState(const gl::Context * context,gl::PrimitiveMode drawMode)1128 angle::Result Renderer9::updateState(const gl::Context *context, gl::PrimitiveMode drawMode)
1129 {
1130 const auto &glState = context->getState();
1131
1132 // Applies the render target surface, depth stencil surface, viewport rectangle and
1133 // scissor rectangle to the renderer
1134 gl::Framebuffer *framebuffer = glState.getDrawFramebuffer();
1135 ASSERT(framebuffer && !framebuffer->hasAnyDirtyBit());
1136
1137 Framebuffer9 *framebuffer9 = GetImplAs<Framebuffer9>(framebuffer);
1138
1139 ANGLE_TRY(applyRenderTarget(context, framebuffer9->getCachedColorRenderTargets()[0],
1140 framebuffer9->getCachedDepthStencilRenderTarget()));
1141
1142 // Setting viewport state
1143 setViewport(glState.getViewport(), glState.getNearPlane(), glState.getFarPlane(), drawMode,
1144 glState.getRasterizerState().frontFace, false);
1145
1146 // Setting scissors state
1147 setScissorRectangle(glState.getScissor(), glState.isScissorTestEnabled());
1148
1149 // Setting blend, depth stencil, and rasterizer states
1150 // Since framebuffer->getSamples will return the original samples which may be different with
1151 // the sample counts that we set in render target view, here we use renderTarget->getSamples to
1152 // get the actual samples.
1153 GLsizei samples = 0;
1154 const gl::FramebufferAttachment *firstColorAttachment = framebuffer->getFirstColorAttachment();
1155 if (firstColorAttachment)
1156 {
1157 ASSERT(firstColorAttachment->isAttached());
1158 RenderTarget9 *renderTarget = nullptr;
1159 ANGLE_TRY(firstColorAttachment->getRenderTarget(context, firstColorAttachment->getSamples(),
1160 &renderTarget));
1161 samples = renderTarget->getSamples();
1162
1163 mDevice->SetRenderState(D3DRS_SRGBWRITEENABLE,
1164 renderTarget->getInternalFormat() == GL_SRGB8_ALPHA8);
1165 }
1166 gl::RasterizerState rasterizer = glState.getRasterizerState();
1167 rasterizer.pointDrawMode = (drawMode == gl::PrimitiveMode::Points);
1168 rasterizer.multiSample = (samples != 0);
1169
1170 ANGLE_TRY(setBlendDepthRasterStates(context, drawMode));
1171
1172 mStateManager.resetDirtyBits();
1173
1174 return angle::Result::Continue;
1175 }
1176
setScissorRectangle(const gl::Rectangle & scissor,bool enabled)1177 void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
1178 {
1179 mStateManager.setScissorState(scissor, enabled);
1180 }
1181
setBlendDepthRasterStates(const gl::Context * context,gl::PrimitiveMode drawMode)1182 angle::Result Renderer9::setBlendDepthRasterStates(const gl::Context *context,
1183 gl::PrimitiveMode drawMode)
1184 {
1185 const auto &glState = context->getState();
1186 gl::Framebuffer *drawFramebuffer = glState.getDrawFramebuffer();
1187 ASSERT(!drawFramebuffer->hasAnyDirtyBit());
1188 // Since framebuffer->getSamples will return the original samples which may be different with
1189 // the sample counts that we set in render target view, here we use renderTarget->getSamples to
1190 // get the actual samples.
1191 GLsizei samples = 0;
1192 const gl::FramebufferAttachment *firstColorAttachment =
1193 drawFramebuffer->getFirstColorAttachment();
1194 if (firstColorAttachment)
1195 {
1196 ASSERT(firstColorAttachment->isAttached());
1197 RenderTarget9 *renderTarget = nullptr;
1198 ANGLE_TRY(firstColorAttachment->getRenderTarget(context, firstColorAttachment->getSamples(),
1199 &renderTarget));
1200 samples = renderTarget->getSamples();
1201 }
1202 gl::RasterizerState rasterizer = glState.getRasterizerState();
1203 rasterizer.pointDrawMode = (drawMode == gl::PrimitiveMode::Points);
1204 rasterizer.multiSample = (samples != 0);
1205
1206 unsigned int mask = GetBlendSampleMask(glState, samples);
1207 mStateManager.setBlendDepthRasterStates(glState, mask);
1208 return angle::Result::Continue;
1209 }
1210
setViewport(const gl::Rectangle & viewport,float zNear,float zFar,gl::PrimitiveMode drawMode,GLenum frontFace,bool ignoreViewport)1211 void Renderer9::setViewport(const gl::Rectangle &viewport,
1212 float zNear,
1213 float zFar,
1214 gl::PrimitiveMode drawMode,
1215 GLenum frontFace,
1216 bool ignoreViewport)
1217 {
1218 mStateManager.setViewportState(viewport, zNear, zFar, drawMode, frontFace, ignoreViewport);
1219 }
1220
applyPrimitiveType(gl::PrimitiveMode mode,GLsizei count,bool usesPointSize)1221 bool Renderer9::applyPrimitiveType(gl::PrimitiveMode mode, GLsizei count, bool usesPointSize)
1222 {
1223 switch (mode)
1224 {
1225 case gl::PrimitiveMode::Points:
1226 mPrimitiveType = D3DPT_POINTLIST;
1227 mPrimitiveCount = count;
1228 break;
1229 case gl::PrimitiveMode::Lines:
1230 mPrimitiveType = D3DPT_LINELIST;
1231 mPrimitiveCount = count / 2;
1232 break;
1233 case gl::PrimitiveMode::LineLoop:
1234 mPrimitiveType = D3DPT_LINESTRIP;
1235 mPrimitiveCount =
1236 count - 1; // D3D doesn't support line loops, so we draw the last line separately
1237 break;
1238 case gl::PrimitiveMode::LineStrip:
1239 mPrimitiveType = D3DPT_LINESTRIP;
1240 mPrimitiveCount = count - 1;
1241 break;
1242 case gl::PrimitiveMode::Triangles:
1243 mPrimitiveType = D3DPT_TRIANGLELIST;
1244 mPrimitiveCount = count / 3;
1245 break;
1246 case gl::PrimitiveMode::TriangleStrip:
1247 mPrimitiveType = D3DPT_TRIANGLESTRIP;
1248 mPrimitiveCount = count - 2;
1249 break;
1250 case gl::PrimitiveMode::TriangleFan:
1251 mPrimitiveType = D3DPT_TRIANGLEFAN;
1252 mPrimitiveCount = count - 2;
1253 break;
1254 default:
1255 UNREACHABLE();
1256 return false;
1257 }
1258
1259 return mPrimitiveCount > 0;
1260 }
1261
getNullColorRenderTarget(const gl::Context * context,const RenderTarget9 * depthRenderTarget,const RenderTarget9 ** outColorRenderTarget)1262 angle::Result Renderer9::getNullColorRenderTarget(const gl::Context *context,
1263 const RenderTarget9 *depthRenderTarget,
1264 const RenderTarget9 **outColorRenderTarget)
1265 {
1266 ASSERT(depthRenderTarget);
1267
1268 const gl::Extents &size = depthRenderTarget->getExtents();
1269
1270 // search cached nullcolorbuffers
1271 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1272 {
1273 if (mNullRenderTargetCache[i].renderTarget != nullptr &&
1274 mNullRenderTargetCache[i].width == size.width &&
1275 mNullRenderTargetCache[i].height == size.height)
1276 {
1277 mNullRenderTargetCache[i].lruCount = ++mMaxNullColorbufferLRU;
1278 *outColorRenderTarget = mNullRenderTargetCache[i].renderTarget;
1279 return angle::Result::Continue;
1280 }
1281 }
1282
1283 RenderTargetD3D *nullRenderTarget = nullptr;
1284 ANGLE_TRY(createRenderTarget(context, size.width, size.height, GL_NONE, 0, &nullRenderTarget));
1285
1286 // add nullbuffer to the cache
1287 NullRenderTargetCacheEntry *oldest = &mNullRenderTargetCache[0];
1288 for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1289 {
1290 if (mNullRenderTargetCache[i].lruCount < oldest->lruCount)
1291 {
1292 oldest = &mNullRenderTargetCache[i];
1293 }
1294 }
1295
1296 SafeDelete(oldest->renderTarget);
1297 oldest->renderTarget = GetAs<RenderTarget9>(nullRenderTarget);
1298 oldest->lruCount = ++mMaxNullColorbufferLRU;
1299 oldest->width = size.width;
1300 oldest->height = size.height;
1301
1302 *outColorRenderTarget = oldest->renderTarget;
1303 return angle::Result::Continue;
1304 }
1305
applyRenderTarget(const gl::Context * context,const RenderTarget9 * colorRenderTargetIn,const RenderTarget9 * depthStencilRenderTarget)1306 angle::Result Renderer9::applyRenderTarget(const gl::Context *context,
1307 const RenderTarget9 *colorRenderTargetIn,
1308 const RenderTarget9 *depthStencilRenderTarget)
1309 {
1310 // if there is no color attachment we must synthesize a NULL colorattachment
1311 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1312 const RenderTarget9 *colorRenderTarget = colorRenderTargetIn;
1313 if (colorRenderTarget == nullptr)
1314 {
1315 ANGLE_TRY(getNullColorRenderTarget(context, depthStencilRenderTarget, &colorRenderTarget));
1316 }
1317 ASSERT(colorRenderTarget != nullptr);
1318
1319 size_t renderTargetWidth = 0;
1320 size_t renderTargetHeight = 0;
1321
1322 bool renderTargetChanged = false;
1323 unsigned int renderTargetSerial = colorRenderTarget->getSerial();
1324 if (renderTargetSerial != mAppliedRenderTargetSerial)
1325 {
1326 // Apply the render target on the device
1327 IDirect3DSurface9 *renderTargetSurface = colorRenderTarget->getSurface();
1328 ASSERT(renderTargetSurface);
1329
1330 mDevice->SetRenderTarget(0, renderTargetSurface);
1331 SafeRelease(renderTargetSurface);
1332
1333 renderTargetWidth = colorRenderTarget->getWidth();
1334 renderTargetHeight = colorRenderTarget->getHeight();
1335
1336 mAppliedRenderTargetSerial = renderTargetSerial;
1337 renderTargetChanged = true;
1338 }
1339
1340 unsigned int depthStencilSerial = 0;
1341 if (depthStencilRenderTarget != nullptr)
1342 {
1343 depthStencilSerial = depthStencilRenderTarget->getSerial();
1344 }
1345
1346 if (depthStencilSerial != mAppliedDepthStencilSerial || !mDepthStencilInitialized)
1347 {
1348 unsigned int depthSize = 0;
1349 unsigned int stencilSize = 0;
1350
1351 // Apply the depth stencil on the device
1352 if (depthStencilRenderTarget)
1353 {
1354 IDirect3DSurface9 *depthStencilSurface = depthStencilRenderTarget->getSurface();
1355 ASSERT(depthStencilSurface);
1356
1357 mDevice->SetDepthStencilSurface(depthStencilSurface);
1358 SafeRelease(depthStencilSurface);
1359
1360 const gl::InternalFormat &format =
1361 gl::GetSizedInternalFormatInfo(depthStencilRenderTarget->getInternalFormat());
1362
1363 depthSize = format.depthBits;
1364 stencilSize = format.stencilBits;
1365 }
1366 else
1367 {
1368 mDevice->SetDepthStencilSurface(nullptr);
1369 }
1370
1371 mStateManager.updateDepthSizeIfChanged(mDepthStencilInitialized, depthSize);
1372 mStateManager.updateStencilSizeIfChanged(mDepthStencilInitialized, stencilSize);
1373
1374 mAppliedDepthStencilSerial = depthStencilSerial;
1375 mDepthStencilInitialized = true;
1376 }
1377
1378 if (renderTargetChanged || !mRenderTargetDescInitialized)
1379 {
1380 mStateManager.forceSetBlendState();
1381 mStateManager.forceSetScissorState();
1382 mStateManager.setRenderTargetBounds(renderTargetWidth, renderTargetHeight);
1383 mRenderTargetDescInitialized = true;
1384 }
1385
1386 return angle::Result::Continue;
1387 }
1388
applyVertexBuffer(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count,GLsizei instances,TranslatedIndexData *)1389 angle::Result Renderer9::applyVertexBuffer(const gl::Context *context,
1390 gl::PrimitiveMode mode,
1391 GLint first,
1392 GLsizei count,
1393 GLsizei instances,
1394 TranslatedIndexData * /*indexInfo*/)
1395 {
1396 const gl::State &state = context->getState();
1397 ANGLE_TRY(mVertexDataManager->prepareVertexData(context, first, count, &mTranslatedAttribCache,
1398 instances));
1399
1400 return mVertexDeclarationCache.applyDeclaration(context, mDevice, mTranslatedAttribCache,
1401 state.getProgram(), first, instances,
1402 &mRepeatDraw);
1403 }
1404
1405 // 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)1406 angle::Result Renderer9::applyIndexBuffer(const gl::Context *context,
1407 const void *indices,
1408 GLsizei count,
1409 gl::PrimitiveMode mode,
1410 gl::DrawElementsType type,
1411 TranslatedIndexData *indexInfo)
1412 {
1413 gl::VertexArray *vao = context->getState().getVertexArray();
1414 gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer();
1415
1416 gl::DrawElementsType dstType = gl::DrawElementsType::InvalidEnum;
1417 ANGLE_TRY(GetIndexTranslationDestType(context, count, type, indices, false, &dstType));
1418
1419 ANGLE_TRY(mIndexDataManager->prepareIndexData(context, type, dstType, count, elementArrayBuffer,
1420 indices, indexInfo));
1421
1422 // Directly binding the storage buffer is not supported for d3d9
1423 ASSERT(indexInfo->storage == nullptr);
1424
1425 if (indexInfo->serial != mAppliedIBSerial)
1426 {
1427 IndexBuffer9 *indexBuffer = GetAs<IndexBuffer9>(indexInfo->indexBuffer);
1428
1429 mDevice->SetIndices(indexBuffer->getBuffer());
1430 mAppliedIBSerial = indexInfo->serial;
1431 }
1432
1433 return angle::Result::Continue;
1434 }
1435
drawArraysImpl(const gl::Context * context,gl::PrimitiveMode mode,GLint startVertex,GLsizei count,GLsizei instances)1436 angle::Result Renderer9::drawArraysImpl(const gl::Context *context,
1437 gl::PrimitiveMode mode,
1438 GLint startVertex,
1439 GLsizei count,
1440 GLsizei instances)
1441 {
1442 ASSERT(!context->getState().isTransformFeedbackActiveUnpaused());
1443
1444 startScene();
1445
1446 if (mode == gl::PrimitiveMode::LineLoop)
1447 {
1448 return drawLineLoop(context, count, gl::DrawElementsType::InvalidEnum, nullptr, 0, nullptr);
1449 }
1450
1451 if (instances > 0)
1452 {
1453 StaticIndexBufferInterface *countingIB = nullptr;
1454 ANGLE_TRY(getCountingIB(context, count, &countingIB));
1455
1456 if (mAppliedIBSerial != countingIB->getSerial())
1457 {
1458 IndexBuffer9 *indexBuffer = GetAs<IndexBuffer9>(countingIB->getIndexBuffer());
1459
1460 mDevice->SetIndices(indexBuffer->getBuffer());
1461 mAppliedIBSerial = countingIB->getSerial();
1462 }
1463
1464 for (int i = 0; i < mRepeatDraw; i++)
1465 {
1466 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1467 }
1468
1469 return angle::Result::Continue;
1470 }
1471
1472 // Regular case
1473 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1474 return angle::Result::Continue;
1475 }
1476
drawElementsImpl(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances)1477 angle::Result Renderer9::drawElementsImpl(const gl::Context *context,
1478 gl::PrimitiveMode mode,
1479 GLsizei count,
1480 gl::DrawElementsType type,
1481 const void *indices,
1482 GLsizei instances)
1483 {
1484 TranslatedIndexData indexInfo;
1485
1486 ANGLE_TRY(applyIndexBuffer(context, indices, count, mode, type, &indexInfo));
1487
1488 gl::IndexRange indexRange;
1489 ANGLE_TRY(context->getState().getVertexArray()->getIndexRange(context, type, count, indices,
1490 &indexRange));
1491
1492 size_t vertexCount = indexRange.vertexCount();
1493 ANGLE_TRY(applyVertexBuffer(context, mode, static_cast<GLsizei>(indexRange.start),
1494 static_cast<GLsizei>(vertexCount), instances, &indexInfo));
1495
1496 startScene();
1497
1498 int minIndex = static_cast<int>(indexRange.start);
1499
1500 gl::VertexArray *vao = context->getState().getVertexArray();
1501 gl::Buffer *elementArrayBuffer = vao->getElementArrayBuffer();
1502
1503 if (mode == gl::PrimitiveMode::Points)
1504 {
1505 return drawIndexedPoints(context, count, type, indices, minIndex, elementArrayBuffer);
1506 }
1507
1508 if (mode == gl::PrimitiveMode::LineLoop)
1509 {
1510 return drawLineLoop(context, count, type, indices, minIndex, elementArrayBuffer);
1511 }
1512
1513 for (int i = 0; i < mRepeatDraw; i++)
1514 {
1515 mDevice->DrawIndexedPrimitive(mPrimitiveType, -minIndex, minIndex,
1516 static_cast<UINT>(vertexCount), indexInfo.startIndex,
1517 mPrimitiveCount);
1518 }
1519 return angle::Result::Continue;
1520 }
1521
drawLineLoop(const gl::Context * context,GLsizei count,gl::DrawElementsType type,const void * indices,int minIndex,gl::Buffer * elementArrayBuffer)1522 angle::Result Renderer9::drawLineLoop(const gl::Context *context,
1523 GLsizei count,
1524 gl::DrawElementsType type,
1525 const void *indices,
1526 int minIndex,
1527 gl::Buffer *elementArrayBuffer)
1528 {
1529 // Get the raw indices for an indexed draw
1530 if (type != gl::DrawElementsType::InvalidEnum && elementArrayBuffer)
1531 {
1532 BufferD3D *storage = GetImplAs<BufferD3D>(elementArrayBuffer);
1533 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1534 const uint8_t *bufferData = nullptr;
1535 ANGLE_TRY(storage->getData(context, &bufferData));
1536 indices = bufferData + offset;
1537 }
1538
1539 unsigned int startIndex = 0;
1540 Context9 *context9 = GetImplAs<Context9>(context);
1541
1542 if (getNativeExtensions().elementIndexUintOES)
1543 {
1544 if (!mLineLoopIB)
1545 {
1546 mLineLoopIB = new StreamingIndexBufferInterface(this);
1547 ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, INITIAL_INDEX_BUFFER_SIZE,
1548 gl::DrawElementsType::UnsignedInt));
1549 }
1550
1551 // Checked by Renderer9::applyPrimitiveType
1552 ASSERT(count >= 0);
1553
1554 ANGLE_CHECK(context9,
1555 static_cast<unsigned int>(count) + 1 <=
1556 (std::numeric_limits<unsigned int>::max() / sizeof(unsigned int)),
1557 "Failed to create a 32-bit looping index buffer for "
1558 "GL_LINE_LOOP, too many indices required.",
1559 GL_OUT_OF_MEMORY);
1560
1561 const unsigned int spaceNeeded =
1562 (static_cast<unsigned int>(count) + 1) * sizeof(unsigned int);
1563 ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, spaceNeeded,
1564 gl::DrawElementsType::UnsignedInt));
1565
1566 void *mappedMemory = nullptr;
1567 unsigned int offset = 0;
1568 ANGLE_TRY(mLineLoopIB->mapBuffer(context, spaceNeeded, &mappedMemory, &offset));
1569
1570 startIndex = static_cast<unsigned int>(offset) / 4;
1571 unsigned int *data = static_cast<unsigned int *>(mappedMemory);
1572
1573 switch (type)
1574 {
1575 case gl::DrawElementsType::InvalidEnum: // Non-indexed draw
1576 for (int i = 0; i < count; i++)
1577 {
1578 data[i] = i;
1579 }
1580 data[count] = 0;
1581 break;
1582 case gl::DrawElementsType::UnsignedByte:
1583 for (int i = 0; i < count; i++)
1584 {
1585 data[i] = static_cast<const GLubyte *>(indices)[i];
1586 }
1587 data[count] = static_cast<const GLubyte *>(indices)[0];
1588 break;
1589 case gl::DrawElementsType::UnsignedShort:
1590 for (int i = 0; i < count; i++)
1591 {
1592 data[i] = static_cast<const GLushort *>(indices)[i];
1593 }
1594 data[count] = static_cast<const GLushort *>(indices)[0];
1595 break;
1596 case gl::DrawElementsType::UnsignedInt:
1597 for (int i = 0; i < count; i++)
1598 {
1599 data[i] = static_cast<const GLuint *>(indices)[i];
1600 }
1601 data[count] = static_cast<const GLuint *>(indices)[0];
1602 break;
1603 default:
1604 UNREACHABLE();
1605 }
1606
1607 ANGLE_TRY(mLineLoopIB->unmapBuffer(context));
1608 }
1609 else
1610 {
1611 if (!mLineLoopIB)
1612 {
1613 mLineLoopIB = new StreamingIndexBufferInterface(this);
1614 ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, INITIAL_INDEX_BUFFER_SIZE,
1615 gl::DrawElementsType::UnsignedShort));
1616 }
1617
1618 // Checked by Renderer9::applyPrimitiveType
1619 ASSERT(count >= 0);
1620
1621 ANGLE_CHECK(context9,
1622 static_cast<unsigned int>(count) + 1 <=
1623 (std::numeric_limits<unsigned short>::max() / sizeof(unsigned short)),
1624 "Failed to create a 16-bit looping index buffer for "
1625 "GL_LINE_LOOP, too many indices required.",
1626 GL_OUT_OF_MEMORY);
1627
1628 const unsigned int spaceNeeded =
1629 (static_cast<unsigned int>(count) + 1) * sizeof(unsigned short);
1630 ANGLE_TRY(mLineLoopIB->reserveBufferSpace(context, spaceNeeded,
1631 gl::DrawElementsType::UnsignedShort));
1632
1633 void *mappedMemory = nullptr;
1634 unsigned int offset;
1635 ANGLE_TRY(mLineLoopIB->mapBuffer(context, spaceNeeded, &mappedMemory, &offset));
1636
1637 startIndex = static_cast<unsigned int>(offset) / 2;
1638 unsigned short *data = static_cast<unsigned short *>(mappedMemory);
1639
1640 switch (type)
1641 {
1642 case gl::DrawElementsType::InvalidEnum: // Non-indexed draw
1643 for (int i = 0; i < count; i++)
1644 {
1645 data[i] = static_cast<unsigned short>(i);
1646 }
1647 data[count] = 0;
1648 break;
1649 case gl::DrawElementsType::UnsignedByte:
1650 for (int i = 0; i < count; i++)
1651 {
1652 data[i] = static_cast<const GLubyte *>(indices)[i];
1653 }
1654 data[count] = static_cast<const GLubyte *>(indices)[0];
1655 break;
1656 case gl::DrawElementsType::UnsignedShort:
1657 for (int i = 0; i < count; i++)
1658 {
1659 data[i] = static_cast<const GLushort *>(indices)[i];
1660 }
1661 data[count] = static_cast<const GLushort *>(indices)[0];
1662 break;
1663 case gl::DrawElementsType::UnsignedInt:
1664 for (int i = 0; i < count; i++)
1665 {
1666 data[i] = static_cast<unsigned short>(static_cast<const GLuint *>(indices)[i]);
1667 }
1668 data[count] = static_cast<unsigned short>(static_cast<const GLuint *>(indices)[0]);
1669 break;
1670 default:
1671 UNREACHABLE();
1672 }
1673
1674 ANGLE_TRY(mLineLoopIB->unmapBuffer(context));
1675 }
1676
1677 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1678 {
1679 IndexBuffer9 *indexBuffer = GetAs<IndexBuffer9>(mLineLoopIB->getIndexBuffer());
1680
1681 mDevice->SetIndices(indexBuffer->getBuffer());
1682 mAppliedIBSerial = mLineLoopIB->getSerial();
1683 }
1684
1685 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1686
1687 return angle::Result::Continue;
1688 }
1689
drawIndexedPoints(const gl::Context * context,GLsizei count,gl::DrawElementsType type,const void * indices,int minIndex,gl::Buffer * elementArrayBuffer)1690 angle::Result Renderer9::drawIndexedPoints(const gl::Context *context,
1691 GLsizei count,
1692 gl::DrawElementsType type,
1693 const void *indices,
1694 int minIndex,
1695 gl::Buffer *elementArrayBuffer)
1696 {
1697 // Drawing index point lists is unsupported in d3d9, fall back to a regular DrawPrimitive call
1698 // for each individual point. This call is not expected to happen often.
1699
1700 if (elementArrayBuffer)
1701 {
1702 BufferD3D *storage = GetImplAs<BufferD3D>(elementArrayBuffer);
1703 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1704
1705 const uint8_t *bufferData = nullptr;
1706 ANGLE_TRY(storage->getData(context, &bufferData));
1707 indices = bufferData + offset;
1708 }
1709
1710 switch (type)
1711 {
1712 case gl::DrawElementsType::UnsignedByte:
1713 DrawPoints<GLubyte>(mDevice, count, indices, minIndex);
1714 return angle::Result::Continue;
1715 case gl::DrawElementsType::UnsignedShort:
1716 DrawPoints<GLushort>(mDevice, count, indices, minIndex);
1717 return angle::Result::Continue;
1718 case gl::DrawElementsType::UnsignedInt:
1719 DrawPoints<GLuint>(mDevice, count, indices, minIndex);
1720 return angle::Result::Continue;
1721 default:
1722 ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
1723 }
1724 }
1725
getCountingIB(const gl::Context * context,size_t count,StaticIndexBufferInterface ** outIB)1726 angle::Result Renderer9::getCountingIB(const gl::Context *context,
1727 size_t count,
1728 StaticIndexBufferInterface **outIB)
1729 {
1730 // Update the counting index buffer if it is not large enough or has not been created yet.
1731 if (count <= 65536) // 16-bit indices
1732 {
1733 const unsigned int spaceNeeded = static_cast<unsigned int>(count) * sizeof(unsigned short);
1734
1735 if (!mCountingIB || mCountingIB->getBufferSize() < spaceNeeded)
1736 {
1737 SafeDelete(mCountingIB);
1738 mCountingIB = new StaticIndexBufferInterface(this);
1739 ANGLE_TRY(mCountingIB->reserveBufferSpace(context, spaceNeeded,
1740 gl::DrawElementsType::UnsignedShort));
1741
1742 void *mappedMemory = nullptr;
1743 ANGLE_TRY(mCountingIB->mapBuffer(context, spaceNeeded, &mappedMemory, nullptr));
1744
1745 unsigned short *data = static_cast<unsigned short *>(mappedMemory);
1746 for (size_t i = 0; i < count; i++)
1747 {
1748 data[i] = static_cast<unsigned short>(i);
1749 }
1750
1751 ANGLE_TRY(mCountingIB->unmapBuffer(context));
1752 }
1753 }
1754 else if (getNativeExtensions().elementIndexUintOES)
1755 {
1756 const unsigned int spaceNeeded = static_cast<unsigned int>(count) * sizeof(unsigned int);
1757
1758 if (!mCountingIB || mCountingIB->getBufferSize() < spaceNeeded)
1759 {
1760 SafeDelete(mCountingIB);
1761 mCountingIB = new StaticIndexBufferInterface(this);
1762 ANGLE_TRY(mCountingIB->reserveBufferSpace(context, spaceNeeded,
1763 gl::DrawElementsType::UnsignedInt));
1764
1765 void *mappedMemory = nullptr;
1766 ANGLE_TRY(mCountingIB->mapBuffer(context, spaceNeeded, &mappedMemory, nullptr));
1767
1768 unsigned int *data = static_cast<unsigned int *>(mappedMemory);
1769 for (unsigned int i = 0; i < count; i++)
1770 {
1771 data[i] = i;
1772 }
1773
1774 ANGLE_TRY(mCountingIB->unmapBuffer(context));
1775 }
1776 }
1777 else
1778 {
1779 ANGLE_TRY_HR(GetImplAs<Context9>(context), E_OUTOFMEMORY,
1780 "Could not create a counting index buffer for glDrawArraysInstanced.");
1781 }
1782
1783 *outIB = mCountingIB;
1784 return angle::Result::Continue;
1785 }
1786
applyShaders(const gl::Context * context,gl::PrimitiveMode drawMode)1787 angle::Result Renderer9::applyShaders(const gl::Context *context, gl::PrimitiveMode drawMode)
1788 {
1789 const gl::State &state = context->getState();
1790 d3d::Context *contextD3D = GetImplAs<ContextD3D>(context);
1791
1792 // This method is called single-threaded.
1793 ANGLE_TRY(ensureHLSLCompilerInitialized(contextD3D));
1794
1795 ProgramD3D *programD3D = GetImplAs<ProgramD3D>(state.getProgram());
1796 VertexArray9 *vao = GetImplAs<VertexArray9>(state.getVertexArray());
1797 programD3D->updateCachedInputLayout(vao->getCurrentStateSerial(), state);
1798
1799 ShaderExecutableD3D *vertexExe = nullptr;
1800 ANGLE_TRY(programD3D->getVertexExecutableForCachedInputLayout(contextD3D, &vertexExe, nullptr));
1801
1802 const gl::Framebuffer *drawFramebuffer = state.getDrawFramebuffer();
1803 programD3D->updateCachedOutputLayout(context, drawFramebuffer);
1804
1805 ShaderExecutableD3D *pixelExe = nullptr;
1806 ANGLE_TRY(programD3D->getPixelExecutableForCachedOutputLayout(contextD3D, &pixelExe, nullptr));
1807
1808 IDirect3DVertexShader9 *vertexShader =
1809 (vertexExe ? GetAs<ShaderExecutable9>(vertexExe)->getVertexShader() : nullptr);
1810 IDirect3DPixelShader9 *pixelShader =
1811 (pixelExe ? GetAs<ShaderExecutable9>(pixelExe)->getPixelShader() : nullptr);
1812
1813 if (vertexShader != mAppliedVertexShader)
1814 {
1815 mDevice->SetVertexShader(vertexShader);
1816 mAppliedVertexShader = vertexShader;
1817 }
1818
1819 if (pixelShader != mAppliedPixelShader)
1820 {
1821 mDevice->SetPixelShader(pixelShader);
1822 mAppliedPixelShader = pixelShader;
1823 }
1824
1825 // D3D9 has a quirk where creating multiple shaders with the same content
1826 // can return the same shader pointer. Because GL programs store different data
1827 // per-program, checking the program serial guarantees we upload fresh
1828 // uniform data even if our shader pointers are the same.
1829 // https://code.google.com/p/angleproject/issues/detail?id=661
1830 unsigned int programSerial = programD3D->getSerial();
1831 if (programSerial != mAppliedProgramSerial)
1832 {
1833 programD3D->dirtyAllUniforms();
1834 mStateManager.forceSetDXUniformsState();
1835 mAppliedProgramSerial = programSerial;
1836 }
1837
1838 applyUniforms(programD3D);
1839
1840 // Driver uniforms
1841 mStateManager.setShaderConstants();
1842
1843 return angle::Result::Continue;
1844 }
1845
applyUniforms(ProgramD3D * programD3D)1846 void Renderer9::applyUniforms(ProgramD3D *programD3D)
1847 {
1848 // Skip updates if we're not dirty. Note that D3D9 cannot have compute or geometry.
1849 if (!programD3D->anyShaderUniformsDirty())
1850 {
1851 return;
1852 }
1853
1854 const auto &uniformArray = programD3D->getD3DUniforms();
1855
1856 for (const D3DUniform *targetUniform : uniformArray)
1857 {
1858 // Built-in uniforms must be skipped.
1859 if (!targetUniform->isReferencedByShader(gl::ShaderType::Vertex) &&
1860 !targetUniform->isReferencedByShader(gl::ShaderType::Fragment))
1861 continue;
1862
1863 const GLfloat *f = reinterpret_cast<const GLfloat *>(targetUniform->firstNonNullData());
1864 const GLint *i = reinterpret_cast<const GLint *>(targetUniform->firstNonNullData());
1865
1866 switch (targetUniform->typeInfo.type)
1867 {
1868 case GL_SAMPLER_2D:
1869 case GL_SAMPLER_CUBE:
1870 case GL_SAMPLER_EXTERNAL_OES:
1871 case GL_SAMPLER_VIDEO_IMAGE_WEBGL:
1872 break;
1873 case GL_BOOL:
1874 case GL_BOOL_VEC2:
1875 case GL_BOOL_VEC3:
1876 case GL_BOOL_VEC4:
1877 applyUniformnbv(targetUniform, i);
1878 break;
1879 case GL_FLOAT:
1880 case GL_FLOAT_VEC2:
1881 case GL_FLOAT_VEC3:
1882 case GL_FLOAT_VEC4:
1883 case GL_FLOAT_MAT2:
1884 case GL_FLOAT_MAT3:
1885 case GL_FLOAT_MAT4:
1886 applyUniformnfv(targetUniform, f);
1887 break;
1888 case GL_INT:
1889 case GL_INT_VEC2:
1890 case GL_INT_VEC3:
1891 case GL_INT_VEC4:
1892 applyUniformniv(targetUniform, i);
1893 break;
1894 default:
1895 UNREACHABLE();
1896 }
1897 }
1898
1899 programD3D->markUniformsClean();
1900 }
1901
applyUniformnfv(const D3DUniform * targetUniform,const GLfloat * v)1902 void Renderer9::applyUniformnfv(const D3DUniform *targetUniform, const GLfloat *v)
1903 {
1904 if (targetUniform->isReferencedByShader(gl::ShaderType::Fragment))
1905 {
1906 mDevice->SetPixelShaderConstantF(
1907 targetUniform->mShaderRegisterIndexes[gl::ShaderType::Fragment], v,
1908 targetUniform->registerCount);
1909 }
1910
1911 if (targetUniform->isReferencedByShader(gl::ShaderType::Vertex))
1912 {
1913 mDevice->SetVertexShaderConstantF(
1914 targetUniform->mShaderRegisterIndexes[gl::ShaderType::Vertex], v,
1915 targetUniform->registerCount);
1916 }
1917 }
1918
applyUniformniv(const D3DUniform * targetUniform,const GLint * v)1919 void Renderer9::applyUniformniv(const D3DUniform *targetUniform, const GLint *v)
1920 {
1921 ASSERT(targetUniform->registerCount <= MAX_VERTEX_CONSTANT_VECTORS_D3D9);
1922 GLfloat vector[MAX_VERTEX_CONSTANT_VECTORS_D3D9][4];
1923
1924 for (unsigned int i = 0; i < targetUniform->registerCount; i++)
1925 {
1926 vector[i][0] = (GLfloat)v[4 * i + 0];
1927 vector[i][1] = (GLfloat)v[4 * i + 1];
1928 vector[i][2] = (GLfloat)v[4 * i + 2];
1929 vector[i][3] = (GLfloat)v[4 * i + 3];
1930 }
1931
1932 applyUniformnfv(targetUniform, (GLfloat *)vector);
1933 }
1934
applyUniformnbv(const D3DUniform * targetUniform,const GLint * v)1935 void Renderer9::applyUniformnbv(const D3DUniform *targetUniform, const GLint *v)
1936 {
1937 ASSERT(targetUniform->registerCount <= MAX_VERTEX_CONSTANT_VECTORS_D3D9);
1938 GLfloat vector[MAX_VERTEX_CONSTANT_VECTORS_D3D9][4];
1939
1940 for (unsigned int i = 0; i < targetUniform->registerCount; i++)
1941 {
1942 vector[i][0] = (v[4 * i + 0] == GL_FALSE) ? 0.0f : 1.0f;
1943 vector[i][1] = (v[4 * i + 1] == GL_FALSE) ? 0.0f : 1.0f;
1944 vector[i][2] = (v[4 * i + 2] == GL_FALSE) ? 0.0f : 1.0f;
1945 vector[i][3] = (v[4 * i + 3] == GL_FALSE) ? 0.0f : 1.0f;
1946 }
1947
1948 applyUniformnfv(targetUniform, (GLfloat *)vector);
1949 }
1950
clear(const ClearParameters & clearParams,const RenderTarget9 * colorRenderTarget,const RenderTarget9 * depthStencilRenderTarget)1951 void Renderer9::clear(const ClearParameters &clearParams,
1952 const RenderTarget9 *colorRenderTarget,
1953 const RenderTarget9 *depthStencilRenderTarget)
1954 {
1955 // Clearing buffers with non-float values is not supported by Renderer9 and ES 2.0
1956 ASSERT(clearParams.colorType == GL_FLOAT);
1957
1958 // Clearing individual buffers other than buffer zero is not supported by Renderer9 and ES 2.0
1959 bool clearColor = clearParams.clearColor[0];
1960 for (unsigned int i = 0; i < clearParams.clearColor.size(); i++)
1961 {
1962 ASSERT(clearParams.clearColor[i] == clearColor);
1963 }
1964
1965 float depth = gl::clamp01(clearParams.depthValue);
1966 DWORD stencil = clearParams.stencilValue & 0x000000FF;
1967
1968 unsigned int stencilUnmasked = 0x0;
1969 if (clearParams.clearStencil && depthStencilRenderTarget)
1970 {
1971 const gl::InternalFormat &depthStencilFormat =
1972 gl::GetSizedInternalFormatInfo(depthStencilRenderTarget->getInternalFormat());
1973 if (depthStencilFormat.stencilBits > 0)
1974 {
1975 const d3d9::D3DFormat &d3dFormatInfo =
1976 d3d9::GetD3DFormatInfo(depthStencilRenderTarget->getD3DFormat());
1977 stencilUnmasked = (0x1 << d3dFormatInfo.stencilBits) - 1;
1978 }
1979 }
1980
1981 const bool needMaskedStencilClear =
1982 clearParams.clearStencil &&
1983 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1984
1985 bool needMaskedColorClear = false;
1986 D3DCOLOR color = D3DCOLOR_ARGB(255, 0, 0, 0);
1987 if (clearColor)
1988 {
1989 ASSERT(colorRenderTarget != nullptr);
1990
1991 const gl::InternalFormat &formatInfo =
1992 gl::GetSizedInternalFormatInfo(colorRenderTarget->getInternalFormat());
1993 const d3d9::D3DFormat &d3dFormatInfo =
1994 d3d9::GetD3DFormatInfo(colorRenderTarget->getD3DFormat());
1995
1996 color =
1997 D3DCOLOR_ARGB(gl::unorm<8>((formatInfo.alphaBits == 0 && d3dFormatInfo.alphaBits > 0)
1998 ? 1.0f
1999 : clearParams.colorF.alpha),
2000 gl::unorm<8>((formatInfo.redBits == 0 && d3dFormatInfo.redBits > 0)
2001 ? 0.0f
2002 : clearParams.colorF.red),
2003 gl::unorm<8>((formatInfo.greenBits == 0 && d3dFormatInfo.greenBits > 0)
2004 ? 0.0f
2005 : clearParams.colorF.green),
2006 gl::unorm<8>((formatInfo.blueBits == 0 && d3dFormatInfo.blueBits > 0)
2007 ? 0.0f
2008 : clearParams.colorF.blue));
2009
2010 const uint8_t colorMask =
2011 gl::BlendStateExt::ColorMaskStorage::GetValueIndexed(0, clearParams.colorMask);
2012 bool r, g, b, a;
2013 gl::BlendStateExt::UnpackColorMask(colorMask, &r, &g, &b, &a);
2014 if ((formatInfo.redBits > 0 && !r) || (formatInfo.greenBits > 0 && !g) ||
2015 (formatInfo.blueBits > 0 && !b) || (formatInfo.alphaBits > 0 && !a))
2016 {
2017 needMaskedColorClear = true;
2018 }
2019 }
2020
2021 if (needMaskedColorClear || needMaskedStencilClear)
2022 {
2023 // State which is altered in all paths from this point to the clear call is saved.
2024 // State which is altered in only some paths will be flagged dirty in the case that
2025 // that path is taken.
2026 HRESULT hr;
2027 if (mMaskedClearSavedState == nullptr)
2028 {
2029 hr = mDevice->BeginStateBlock();
2030 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2031
2032 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2033 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2034 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2035 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2036 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2037 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2038 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2039 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2040 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2041 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2042 mDevice->SetPixelShader(nullptr);
2043 mDevice->SetVertexShader(nullptr);
2044 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2045 mDevice->SetStreamSource(0, nullptr, 0, 0);
2046 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2047 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2048 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2049 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2050 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2051 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2052 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2053
2054 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2055 {
2056 mDevice->SetStreamSourceFreq(i, 1);
2057 }
2058
2059 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2060 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2061 }
2062
2063 ASSERT(mMaskedClearSavedState != nullptr);
2064
2065 if (mMaskedClearSavedState != nullptr)
2066 {
2067 hr = mMaskedClearSavedState->Capture();
2068 ASSERT(SUCCEEDED(hr));
2069 }
2070
2071 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2072 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2073 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2074 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2075 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2076 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2077 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2078 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2079
2080 if (clearColor)
2081 {
2082 // clearParams.colorMask follows the same packing scheme as
2083 // D3DCOLORWRITEENABLE_RED/GREEN/BLUE/ALPHA
2084 mDevice->SetRenderState(
2085 D3DRS_COLORWRITEENABLE,
2086 gl::BlendStateExt::ColorMaskStorage::GetValueIndexed(0, clearParams.colorMask));
2087 }
2088 else
2089 {
2090 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2091 }
2092
2093 if (stencilUnmasked != 0x0 && clearParams.clearStencil)
2094 {
2095 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2096 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2097 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2098 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2099 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
2100 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2101 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2102 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2103 }
2104 else
2105 {
2106 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2107 }
2108
2109 mDevice->SetPixelShader(nullptr);
2110 mDevice->SetVertexShader(nullptr);
2111 mDevice->SetFVF(D3DFVF_XYZRHW);
2112 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2113 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2114 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2115 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2116 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2117 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2118 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2119
2120 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2121 {
2122 mDevice->SetStreamSourceFreq(i, 1);
2123 }
2124
2125 int renderTargetWidth = mStateManager.getRenderTargetWidth();
2126 int renderTargetHeight = mStateManager.getRenderTargetHeight();
2127
2128 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
2129 quad[0][0] = -0.5f;
2130 quad[0][1] = renderTargetHeight - 0.5f;
2131 quad[0][2] = 0.0f;
2132 quad[0][3] = 1.0f;
2133
2134 quad[1][0] = renderTargetWidth - 0.5f;
2135 quad[1][1] = renderTargetHeight - 0.5f;
2136 quad[1][2] = 0.0f;
2137 quad[1][3] = 1.0f;
2138
2139 quad[2][0] = -0.5f;
2140 quad[2][1] = -0.5f;
2141 quad[2][2] = 0.0f;
2142 quad[2][3] = 1.0f;
2143
2144 quad[3][0] = renderTargetWidth - 0.5f;
2145 quad[3][1] = -0.5f;
2146 quad[3][2] = 0.0f;
2147 quad[3][3] = 1.0f;
2148
2149 startScene();
2150 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2151
2152 if (clearParams.clearDepth)
2153 {
2154 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
2155 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
2156 mDevice->Clear(0, nullptr, D3DCLEAR_ZBUFFER, color, depth, stencil);
2157 }
2158
2159 if (mMaskedClearSavedState != nullptr)
2160 {
2161 mMaskedClearSavedState->Apply();
2162 }
2163 }
2164 else if (clearColor || clearParams.clearDepth || clearParams.clearStencil)
2165 {
2166 DWORD dxClearFlags = 0;
2167 if (clearColor)
2168 {
2169 dxClearFlags |= D3DCLEAR_TARGET;
2170 }
2171 if (clearParams.clearDepth)
2172 {
2173 dxClearFlags |= D3DCLEAR_ZBUFFER;
2174 }
2175 if (clearParams.clearStencil)
2176 {
2177 dxClearFlags |= D3DCLEAR_STENCIL;
2178 }
2179
2180 mDevice->Clear(0, nullptr, dxClearFlags, color, depth, stencil);
2181 }
2182 }
2183
markAllStateDirty()2184 void Renderer9::markAllStateDirty()
2185 {
2186 mAppliedRenderTargetSerial = 0;
2187 mAppliedDepthStencilSerial = 0;
2188 mDepthStencilInitialized = false;
2189 mRenderTargetDescInitialized = false;
2190
2191 mStateManager.forceSetRasterState();
2192 mStateManager.forceSetDepthStencilState();
2193 mStateManager.forceSetBlendState();
2194 mStateManager.forceSetScissorState();
2195 mStateManager.forceSetViewportState();
2196
2197 ASSERT(mCurVertexSamplerStates.size() == mCurVertexTextures.size());
2198 for (unsigned int i = 0; i < mCurVertexTextures.size(); i++)
2199 {
2200 mCurVertexSamplerStates[i].forceSet = true;
2201 mCurVertexTextures[i] = angle::DirtyPointer;
2202 }
2203
2204 ASSERT(mCurPixelSamplerStates.size() == mCurPixelTextures.size());
2205 for (unsigned int i = 0; i < mCurPixelSamplerStates.size(); i++)
2206 {
2207 mCurPixelSamplerStates[i].forceSet = true;
2208 mCurPixelTextures[i] = angle::DirtyPointer;
2209 }
2210
2211 mAppliedIBSerial = 0;
2212 mAppliedVertexShader = nullptr;
2213 mAppliedPixelShader = nullptr;
2214 mAppliedProgramSerial = 0;
2215 mStateManager.forceSetDXUniformsState();
2216
2217 mVertexDeclarationCache.markStateDirty();
2218 }
2219
releaseDeviceResources()2220 void Renderer9::releaseDeviceResources()
2221 {
2222 for (size_t i = 0; i < mEventQueryPool.size(); i++)
2223 {
2224 SafeRelease(mEventQueryPool[i]);
2225 }
2226 mEventQueryPool.clear();
2227
2228 SafeRelease(mMaskedClearSavedState);
2229
2230 mVertexShaderCache.clear();
2231 mPixelShaderCache.clear();
2232
2233 SafeDelete(mBlit);
2234 SafeDelete(mVertexDataManager);
2235 SafeDelete(mIndexDataManager);
2236 SafeDelete(mLineLoopIB);
2237 SafeDelete(mCountingIB);
2238
2239 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
2240 {
2241 SafeDelete(mNullRenderTargetCache[i].renderTarget);
2242 }
2243 }
2244
2245 // set notify to true to broadcast a message to all contexts of the device loss
testDeviceLost()2246 bool Renderer9::testDeviceLost()
2247 {
2248 HRESULT status = getDeviceStatusCode();
2249 return FAILED(status);
2250 }
2251
getDeviceStatusCode()2252 HRESULT Renderer9::getDeviceStatusCode()
2253 {
2254 HRESULT status = D3D_OK;
2255
2256 if (mDeviceEx)
2257 {
2258 status = mDeviceEx->CheckDeviceState(nullptr);
2259 }
2260 else if (mDevice)
2261 {
2262 status = mDevice->TestCooperativeLevel();
2263 }
2264
2265 return status;
2266 }
2267
testDeviceResettable()2268 bool Renderer9::testDeviceResettable()
2269 {
2270 // On D3D9Ex, DEVICELOST represents a hung device that needs to be restarted
2271 // DEVICEREMOVED indicates the device has been stopped and must be recreated
2272 switch (getDeviceStatusCode())
2273 {
2274 case D3DERR_DEVICENOTRESET:
2275 case D3DERR_DEVICEHUNG:
2276 return true;
2277 case D3DERR_DEVICELOST:
2278 return (mDeviceEx != nullptr);
2279 case D3DERR_DEVICEREMOVED:
2280 ASSERT(mDeviceEx != nullptr);
2281 return isRemovedDeviceResettable();
2282 default:
2283 return false;
2284 }
2285 }
2286
resetDevice()2287 bool Renderer9::resetDevice()
2288 {
2289 releaseDeviceResources();
2290
2291 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
2292
2293 HRESULT result = D3D_OK;
2294 bool lost = testDeviceLost();
2295 bool removedDevice = (getDeviceStatusCode() == D3DERR_DEVICEREMOVED);
2296
2297 // Device Removed is a feature which is only present with D3D9Ex
2298 ASSERT(mDeviceEx != nullptr || !removedDevice);
2299
2300 for (int attempts = 3; lost && attempts > 0; attempts--)
2301 {
2302 if (removedDevice)
2303 {
2304 // Device removed, which may trigger on driver reinstallation,
2305 // may cause a longer wait other reset attempts before the
2306 // system is ready to handle creating a new device.
2307 Sleep(800);
2308 lost = !resetRemovedDevice();
2309 }
2310 else if (mDeviceEx)
2311 {
2312 Sleep(500); // Give the graphics driver some CPU time
2313 result = mDeviceEx->ResetEx(&presentParameters, nullptr);
2314 lost = testDeviceLost();
2315 }
2316 else
2317 {
2318 result = mDevice->TestCooperativeLevel();
2319 while (result == D3DERR_DEVICELOST)
2320 {
2321 Sleep(100); // Give the graphics driver some CPU time
2322 result = mDevice->TestCooperativeLevel();
2323 }
2324
2325 if (result == D3DERR_DEVICENOTRESET)
2326 {
2327 result = mDevice->Reset(&presentParameters);
2328 }
2329 lost = testDeviceLost();
2330 }
2331 }
2332
2333 if (FAILED(result))
2334 {
2335 ERR() << "Reset/ResetEx failed multiple times, " << gl::FmtHR(result);
2336 return false;
2337 }
2338
2339 if (removedDevice && lost)
2340 {
2341 ERR() << "Device lost reset failed multiple times";
2342 return false;
2343 }
2344
2345 // If the device was removed, we already finished re-initialization in resetRemovedDevice
2346 if (!removedDevice)
2347 {
2348 // reset device defaults
2349 if (initializeDevice().isError())
2350 {
2351 return false;
2352 }
2353 }
2354
2355 return true;
2356 }
2357
isRemovedDeviceResettable() const2358 bool Renderer9::isRemovedDeviceResettable() const
2359 {
2360 bool success = false;
2361
2362 #if ANGLE_D3D9EX
2363 IDirect3D9Ex *d3d9Ex = nullptr;
2364 typedef HRESULT(WINAPI * Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex **);
2365 Direct3DCreate9ExFunc Direct3DCreate9ExPtr =
2366 reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
2367
2368 if (Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &d3d9Ex)))
2369 {
2370 D3DCAPS9 deviceCaps;
2371 HRESULT result = d3d9Ex->GetDeviceCaps(mAdapter, mDeviceType, &deviceCaps);
2372 success = SUCCEEDED(result);
2373 }
2374
2375 SafeRelease(d3d9Ex);
2376 #else
2377 UNREACHABLE();
2378 #endif
2379
2380 return success;
2381 }
2382
resetRemovedDevice()2383 bool Renderer9::resetRemovedDevice()
2384 {
2385 // From http://msdn.microsoft.com/en-us/library/windows/desktop/bb172554(v=vs.85).aspx:
2386 // The hardware adapter has been removed. Application must destroy the device, do enumeration of
2387 // adapters and create another Direct3D device. If application continues rendering without
2388 // calling Reset, the rendering calls will succeed. Applies to Direct3D 9Ex only.
2389 release();
2390 return !initialize().isError();
2391 }
2392
getVendorId() const2393 VendorID Renderer9::getVendorId() const
2394 {
2395 return static_cast<VendorID>(mAdapterIdentifier.VendorId);
2396 }
2397
getRendererDescription() const2398 std::string Renderer9::getRendererDescription() const
2399 {
2400 std::ostringstream rendererString;
2401
2402 rendererString << mAdapterIdentifier.Description;
2403 if (getShareHandleSupport())
2404 {
2405 rendererString << " Direct3D9Ex";
2406 }
2407 else
2408 {
2409 rendererString << " Direct3D9";
2410 }
2411
2412 rendererString << " vs_" << D3DSHADER_VERSION_MAJOR(mDeviceCaps.VertexShaderVersion) << "_"
2413 << D3DSHADER_VERSION_MINOR(mDeviceCaps.VertexShaderVersion);
2414 rendererString << " ps_" << D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion) << "_"
2415 << D3DSHADER_VERSION_MINOR(mDeviceCaps.PixelShaderVersion);
2416
2417 return rendererString.str();
2418 }
2419
getAdapterIdentifier() const2420 DeviceIdentifier Renderer9::getAdapterIdentifier() const
2421 {
2422 DeviceIdentifier deviceIdentifier = {};
2423 deviceIdentifier.VendorId = static_cast<UINT>(mAdapterIdentifier.VendorId);
2424 deviceIdentifier.DeviceId = static_cast<UINT>(mAdapterIdentifier.DeviceId);
2425 deviceIdentifier.SubSysId = static_cast<UINT>(mAdapterIdentifier.SubSysId);
2426 deviceIdentifier.Revision = static_cast<UINT>(mAdapterIdentifier.Revision);
2427 deviceIdentifier.FeatureLevel = 0;
2428
2429 return deviceIdentifier;
2430 }
2431
getReservedVertexUniformVectors() const2432 unsigned int Renderer9::getReservedVertexUniformVectors() const
2433 {
2434 return d3d9_gl::GetReservedVertexUniformVectors();
2435 }
2436
getReservedFragmentUniformVectors() const2437 unsigned int Renderer9::getReservedFragmentUniformVectors() const
2438 {
2439 return d3d9_gl::GetReservedFragmentUniformVectors();
2440 }
2441
getShareHandleSupport() const2442 bool Renderer9::getShareHandleSupport() const
2443 {
2444 // PIX doesn't seem to support using share handles, so disable them.
2445 return (mD3d9Ex != nullptr) && !gl::DebugAnnotationsActive(/*context=*/nullptr);
2446 }
2447
getMajorShaderModel() const2448 int Renderer9::getMajorShaderModel() const
2449 {
2450 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
2451 }
2452
getMinorShaderModel() const2453 int Renderer9::getMinorShaderModel() const
2454 {
2455 return D3DSHADER_VERSION_MINOR(mDeviceCaps.PixelShaderVersion);
2456 }
2457
getShaderModelSuffix() const2458 std::string Renderer9::getShaderModelSuffix() const
2459 {
2460 return "";
2461 }
2462
getCapsDeclTypes() const2463 DWORD Renderer9::getCapsDeclTypes() const
2464 {
2465 return mDeviceCaps.DeclTypes;
2466 }
2467
getBufferPool(DWORD usage) const2468 D3DPOOL Renderer9::getBufferPool(DWORD usage) const
2469 {
2470 if (mD3d9Ex != nullptr)
2471 {
2472 return D3DPOOL_DEFAULT;
2473 }
2474 else
2475 {
2476 if (!(usage & D3DUSAGE_DYNAMIC))
2477 {
2478 return D3DPOOL_MANAGED;
2479 }
2480 }
2481
2482 return D3DPOOL_DEFAULT;
2483 }
2484
copyImage2D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2485 angle::Result Renderer9::copyImage2D(const gl::Context *context,
2486 const gl::Framebuffer *framebuffer,
2487 const gl::Rectangle &sourceRect,
2488 GLenum destFormat,
2489 const gl::Offset &destOffset,
2490 TextureStorage *storage,
2491 GLint level)
2492 {
2493 RECT rect;
2494 rect.left = sourceRect.x;
2495 rect.top = sourceRect.y;
2496 rect.right = sourceRect.x + sourceRect.width;
2497 rect.bottom = sourceRect.y + sourceRect.height;
2498
2499 return mBlit->copy2D(context, framebuffer, rect, destFormat, destOffset, storage, level);
2500 }
2501
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)2502 angle::Result Renderer9::copyImageCube(const gl::Context *context,
2503 const gl::Framebuffer *framebuffer,
2504 const gl::Rectangle &sourceRect,
2505 GLenum destFormat,
2506 const gl::Offset &destOffset,
2507 TextureStorage *storage,
2508 gl::TextureTarget target,
2509 GLint level)
2510 {
2511 RECT rect;
2512 rect.left = sourceRect.x;
2513 rect.top = sourceRect.y;
2514 rect.right = sourceRect.x + sourceRect.width;
2515 rect.bottom = sourceRect.y + sourceRect.height;
2516
2517 return mBlit->copyCube(context, framebuffer, rect, destFormat, destOffset, storage, target,
2518 level);
2519 }
2520
copyImage3D(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2521 angle::Result Renderer9::copyImage3D(const gl::Context *context,
2522 const gl::Framebuffer *framebuffer,
2523 const gl::Rectangle &sourceRect,
2524 GLenum destFormat,
2525 const gl::Offset &destOffset,
2526 TextureStorage *storage,
2527 GLint level)
2528 {
2529 // 3D textures are not available in the D3D9 backend.
2530 ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2531 return angle::Result::Stop;
2532 }
2533
copyImage2DArray(const gl::Context * context,const gl::Framebuffer * framebuffer,const gl::Rectangle & sourceRect,GLenum destFormat,const gl::Offset & destOffset,TextureStorage * storage,GLint level)2534 angle::Result Renderer9::copyImage2DArray(const gl::Context *context,
2535 const gl::Framebuffer *framebuffer,
2536 const gl::Rectangle &sourceRect,
2537 GLenum destFormat,
2538 const gl::Offset &destOffset,
2539 TextureStorage *storage,
2540 GLint level)
2541 {
2542 // 2D array textures are not available in the D3D9 backend.
2543 ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2544 return angle::Result::Stop;
2545 }
2546
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)2547 angle::Result Renderer9::copyTexture(const gl::Context *context,
2548 const gl::Texture *source,
2549 GLint sourceLevel,
2550 gl::TextureTarget srcTarget,
2551 const gl::Box &sourceBox,
2552 GLenum destFormat,
2553 GLenum destType,
2554 const gl::Offset &destOffset,
2555 TextureStorage *storage,
2556 gl::TextureTarget destTarget,
2557 GLint destLevel,
2558 bool unpackFlipY,
2559 bool unpackPremultiplyAlpha,
2560 bool unpackUnmultiplyAlpha)
2561 {
2562 RECT rect;
2563 rect.left = sourceBox.x;
2564 rect.top = sourceBox.y;
2565 rect.right = sourceBox.x + sourceBox.width;
2566 rect.bottom = sourceBox.y + sourceBox.height;
2567
2568 return mBlit->copyTexture(context, source, sourceLevel, rect, destFormat, destOffset, storage,
2569 destTarget, destLevel, unpackFlipY, unpackPremultiplyAlpha,
2570 unpackUnmultiplyAlpha);
2571 }
2572
copyCompressedTexture(const gl::Context * context,const gl::Texture * source,GLint sourceLevel,TextureStorage * storage,GLint destLevel)2573 angle::Result Renderer9::copyCompressedTexture(const gl::Context *context,
2574 const gl::Texture *source,
2575 GLint sourceLevel,
2576 TextureStorage *storage,
2577 GLint destLevel)
2578 {
2579 ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2580 return angle::Result::Stop;
2581 }
2582
createRenderTarget(const gl::Context * context,int width,int height,GLenum format,GLsizei samples,RenderTargetD3D ** outRT)2583 angle::Result Renderer9::createRenderTarget(const gl::Context *context,
2584 int width,
2585 int height,
2586 GLenum format,
2587 GLsizei samples,
2588 RenderTargetD3D **outRT)
2589 {
2590 const d3d9::TextureFormat &d3d9FormatInfo = d3d9::GetTextureFormatInfo(format);
2591
2592 const gl::TextureCaps &textureCaps = getNativeTextureCaps().get(format);
2593 GLuint supportedSamples = textureCaps.getNearestSamples(samples);
2594
2595 IDirect3DTexture9 *texture = nullptr;
2596 IDirect3DSurface9 *renderTarget = nullptr;
2597 if (width > 0 && height > 0)
2598 {
2599 bool requiresInitialization = false;
2600 HRESULT result = D3DERR_INVALIDCALL;
2601
2602 const gl::InternalFormat &formatInfo = gl::GetSizedInternalFormatInfo(format);
2603 if (formatInfo.depthBits > 0 || formatInfo.stencilBits > 0)
2604 {
2605 result = mDevice->CreateDepthStencilSurface(
2606 width, height, d3d9FormatInfo.renderFormat,
2607 gl_d3d9::GetMultisampleType(supportedSamples), 0, FALSE, &renderTarget, nullptr);
2608 }
2609 else
2610 {
2611 requiresInitialization = (d3d9FormatInfo.dataInitializerFunction != nullptr);
2612 if (supportedSamples > 0)
2613 {
2614 result = mDevice->CreateRenderTarget(width, height, d3d9FormatInfo.renderFormat,
2615 gl_d3d9::GetMultisampleType(supportedSamples),
2616 0, FALSE, &renderTarget, nullptr);
2617 }
2618 else
2619 {
2620 result = mDevice->CreateTexture(
2621 width, height, 1, D3DUSAGE_RENDERTARGET, d3d9FormatInfo.texFormat,
2622 getTexturePool(D3DUSAGE_RENDERTARGET), &texture, nullptr);
2623 if (!FAILED(result))
2624 {
2625 result = texture->GetSurfaceLevel(0, &renderTarget);
2626 }
2627 }
2628 }
2629
2630 ANGLE_TRY_HR(GetImplAs<Context9>(context), result, "Failed to create render target");
2631
2632 if (requiresInitialization)
2633 {
2634 // This format requires that the data be initialized before the render target can be
2635 // used Unfortunately this requires a Get call on the d3d device but it is far better
2636 // than having to mark the render target as lockable and copy data to the gpu.
2637 IDirect3DSurface9 *prevRenderTarget = nullptr;
2638 mDevice->GetRenderTarget(0, &prevRenderTarget);
2639 mDevice->SetRenderTarget(0, renderTarget);
2640 mDevice->Clear(0, nullptr, D3DCLEAR_TARGET, D3DCOLOR_RGBA(0, 0, 0, 255), 0.0f, 0);
2641 mDevice->SetRenderTarget(0, prevRenderTarget);
2642 }
2643 }
2644
2645 *outRT = new TextureRenderTarget9(texture, 0, renderTarget, format, width, height, 1,
2646 supportedSamples);
2647 return angle::Result::Continue;
2648 }
2649
createRenderTargetCopy(const gl::Context * context,RenderTargetD3D * source,RenderTargetD3D ** outRT)2650 angle::Result Renderer9::createRenderTargetCopy(const gl::Context *context,
2651 RenderTargetD3D *source,
2652 RenderTargetD3D **outRT)
2653 {
2654 ASSERT(source != nullptr);
2655
2656 RenderTargetD3D *newRT = nullptr;
2657 ANGLE_TRY(createRenderTarget(context, source->getWidth(), source->getHeight(),
2658 source->getInternalFormat(), source->getSamples(), &newRT));
2659
2660 RenderTarget9 *source9 = GetAs<RenderTarget9>(source);
2661 RenderTarget9 *dest9 = GetAs<RenderTarget9>(newRT);
2662
2663 HRESULT result = mDevice->StretchRect(source9->getSurface(), nullptr, dest9->getSurface(),
2664 nullptr, D3DTEXF_NONE);
2665 ANGLE_TRY_HR(GetImplAs<Context9>(context), result, "Failed to copy render target");
2666
2667 *outRT = newRT;
2668 return angle::Result::Continue;
2669 }
2670
loadExecutable(d3d::Context * context,const uint8_t * function,size_t length,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,ShaderExecutableD3D ** outExecutable)2671 angle::Result Renderer9::loadExecutable(d3d::Context *context,
2672 const uint8_t *function,
2673 size_t length,
2674 gl::ShaderType type,
2675 const std::vector<D3DVarying> &streamOutVaryings,
2676 bool separatedOutputBuffers,
2677 ShaderExecutableD3D **outExecutable)
2678 {
2679 // Transform feedback is not supported in ES2 or D3D9
2680 ASSERT(streamOutVaryings.empty());
2681
2682 switch (type)
2683 {
2684 case gl::ShaderType::Vertex:
2685 {
2686 IDirect3DVertexShader9 *vshader = nullptr;
2687 ANGLE_TRY(createVertexShader(context, (DWORD *)function, length, &vshader));
2688 *outExecutable = new ShaderExecutable9(function, length, vshader);
2689 }
2690 break;
2691 case gl::ShaderType::Fragment:
2692 {
2693 IDirect3DPixelShader9 *pshader = nullptr;
2694 ANGLE_TRY(createPixelShader(context, (DWORD *)function, length, &pshader));
2695 *outExecutable = new ShaderExecutable9(function, length, pshader);
2696 }
2697 break;
2698 default:
2699 ANGLE_HR_UNREACHABLE(context);
2700 }
2701
2702 return angle::Result::Continue;
2703 }
2704
compileToExecutable(d3d::Context * context,gl::InfoLog & infoLog,const std::string & shaderHLSL,gl::ShaderType type,const std::vector<D3DVarying> & streamOutVaryings,bool separatedOutputBuffers,const CompilerWorkaroundsD3D & workarounds,ShaderExecutableD3D ** outExectuable)2705 angle::Result Renderer9::compileToExecutable(d3d::Context *context,
2706 gl::InfoLog &infoLog,
2707 const std::string &shaderHLSL,
2708 gl::ShaderType type,
2709 const std::vector<D3DVarying> &streamOutVaryings,
2710 bool separatedOutputBuffers,
2711 const CompilerWorkaroundsD3D &workarounds,
2712 ShaderExecutableD3D **outExectuable)
2713 {
2714 // Transform feedback is not supported in ES2 or D3D9
2715 ASSERT(streamOutVaryings.empty());
2716
2717 std::stringstream profileStream;
2718
2719 switch (type)
2720 {
2721 case gl::ShaderType::Vertex:
2722 profileStream << "vs";
2723 break;
2724 case gl::ShaderType::Fragment:
2725 profileStream << "ps";
2726 break;
2727 default:
2728 ANGLE_HR_UNREACHABLE(context);
2729 }
2730
2731 profileStream << "_" << ((getMajorShaderModel() >= 3) ? 3 : 2);
2732 profileStream << "_"
2733 << "0";
2734
2735 std::string profile = profileStream.str();
2736
2737 UINT flags = ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2738
2739 if (workarounds.skipOptimization)
2740 {
2741 flags = D3DCOMPILE_SKIP_OPTIMIZATION;
2742 }
2743 else if (workarounds.useMaxOptimization)
2744 {
2745 flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
2746 }
2747
2748 if (gl::DebugAnnotationsActive(/*context=*/nullptr))
2749 {
2750 #ifndef NDEBUG
2751 flags = D3DCOMPILE_SKIP_OPTIMIZATION;
2752 #endif
2753
2754 flags |= D3DCOMPILE_DEBUG;
2755 }
2756
2757 // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders
2758 // when it would otherwise pass with alternative options. Try the default flags first and if
2759 // compilation fails, try some alternatives.
2760 std::vector<CompileConfig> configs;
2761 configs.push_back(CompileConfig(flags, "default"));
2762 configs.push_back(CompileConfig(flags | D3DCOMPILE_AVOID_FLOW_CONTROL, "avoid flow control"));
2763 configs.push_back(CompileConfig(flags | D3DCOMPILE_PREFER_FLOW_CONTROL, "prefer flow control"));
2764
2765 ID3DBlob *binary = nullptr;
2766 std::string debugInfo;
2767 angle::Result error = mCompiler.compileToBinary(context, infoLog, shaderHLSL, profile, configs,
2768 nullptr, &binary, &debugInfo);
2769 ANGLE_TRY(error);
2770
2771 // It's possible that binary is NULL if the compiler failed in all configurations. Set the
2772 // executable to NULL and return GL_NO_ERROR to signify that there was a link error but the
2773 // internal state is still OK.
2774 if (!binary)
2775 {
2776 *outExectuable = nullptr;
2777 return angle::Result::Continue;
2778 }
2779
2780 error = loadExecutable(context, reinterpret_cast<const uint8_t *>(binary->GetBufferPointer()),
2781 binary->GetBufferSize(), type, streamOutVaryings, separatedOutputBuffers,
2782 outExectuable);
2783
2784 SafeRelease(binary);
2785 ANGLE_TRY(error);
2786
2787 if (!debugInfo.empty())
2788 {
2789 (*outExectuable)->appendDebugInfo(debugInfo);
2790 }
2791
2792 return angle::Result::Continue;
2793 }
2794
ensureHLSLCompilerInitialized(d3d::Context * context)2795 angle::Result Renderer9::ensureHLSLCompilerInitialized(d3d::Context *context)
2796 {
2797 return mCompiler.ensureInitialized(context);
2798 }
2799
createUniformStorage(size_t storageSize)2800 UniformStorageD3D *Renderer9::createUniformStorage(size_t storageSize)
2801 {
2802 return new UniformStorageD3D(storageSize);
2803 }
2804
boxFilter(Context9 * context9,IDirect3DSurface9 * source,IDirect3DSurface9 * dest)2805 angle::Result Renderer9::boxFilter(Context9 *context9,
2806 IDirect3DSurface9 *source,
2807 IDirect3DSurface9 *dest)
2808 {
2809 return mBlit->boxFilter(context9, source, dest);
2810 }
2811
getTexturePool(DWORD usage) const2812 D3DPOOL Renderer9::getTexturePool(DWORD usage) const
2813 {
2814 if (mD3d9Ex != nullptr)
2815 {
2816 return D3DPOOL_DEFAULT;
2817 }
2818 else
2819 {
2820 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2821 {
2822 return D3DPOOL_MANAGED;
2823 }
2824 }
2825
2826 return D3DPOOL_DEFAULT;
2827 }
2828
copyToRenderTarget(const gl::Context * context,IDirect3DSurface9 * dest,IDirect3DSurface9 * source,bool fromManaged)2829 angle::Result Renderer9::copyToRenderTarget(const gl::Context *context,
2830 IDirect3DSurface9 *dest,
2831 IDirect3DSurface9 *source,
2832 bool fromManaged)
2833 {
2834 ASSERT(source && dest);
2835
2836 Context9 *context9 = GetImplAs<Context9>(context);
2837
2838 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2839
2840 if (fromManaged)
2841 {
2842 D3DSURFACE_DESC desc;
2843 source->GetDesc(&desc);
2844
2845 IDirect3DSurface9 *surf = 0;
2846 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2847 D3DPOOL_SYSTEMMEM, &surf, nullptr);
2848
2849 if (SUCCEEDED(result))
2850 {
2851 ANGLE_TRY(Image9::CopyLockableSurfaces(context9, surf, source));
2852 result = mDevice->UpdateSurface(surf, nullptr, dest, nullptr);
2853 SafeRelease(surf);
2854 }
2855 }
2856 else
2857 {
2858 endScene();
2859 result = mDevice->StretchRect(source, nullptr, dest, nullptr, D3DTEXF_NONE);
2860 }
2861
2862 ANGLE_TRY_HR(context9, result, "Failed to blit internal texture");
2863 return angle::Result::Continue;
2864 }
2865
getRendererClass() const2866 RendererClass Renderer9::getRendererClass() const
2867 {
2868 return RENDERER_D3D9;
2869 }
2870
createImage()2871 ImageD3D *Renderer9::createImage()
2872 {
2873 return new Image9(this);
2874 }
2875
createExternalImageSibling(const gl::Context * context,EGLenum target,EGLClientBuffer buffer,const egl::AttributeMap & attribs)2876 ExternalImageSiblingImpl *Renderer9::createExternalImageSibling(const gl::Context *context,
2877 EGLenum target,
2878 EGLClientBuffer buffer,
2879 const egl::AttributeMap &attribs)
2880 {
2881 UNREACHABLE();
2882 return nullptr;
2883 }
2884
generateMipmap(const gl::Context * context,ImageD3D * dest,ImageD3D * src)2885 angle::Result Renderer9::generateMipmap(const gl::Context *context, ImageD3D *dest, ImageD3D *src)
2886 {
2887 Image9 *src9 = GetAs<Image9>(src);
2888 Image9 *dst9 = GetAs<Image9>(dest);
2889 return Image9::GenerateMipmap(GetImplAs<Context9>(context), dst9, src9);
2890 }
2891
generateMipmapUsingD3D(const gl::Context * context,TextureStorage * storage,const gl::TextureState & textureState)2892 angle::Result Renderer9::generateMipmapUsingD3D(const gl::Context *context,
2893 TextureStorage *storage,
2894 const gl::TextureState &textureState)
2895 {
2896 ANGLE_HR_UNREACHABLE(GetImplAs<Context9>(context));
2897 return angle::Result::Stop;
2898 }
2899
copyImage(const gl::Context * context,ImageD3D * dest,ImageD3D * source,const gl::Box & sourceBox,const gl::Offset & destOffset,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha)2900 angle::Result Renderer9::copyImage(const gl::Context *context,
2901 ImageD3D *dest,
2902 ImageD3D *source,
2903 const gl::Box &sourceBox,
2904 const gl::Offset &destOffset,
2905 bool unpackFlipY,
2906 bool unpackPremultiplyAlpha,
2907 bool unpackUnmultiplyAlpha)
2908 {
2909 Image9 *dest9 = GetAs<Image9>(dest);
2910 Image9 *src9 = GetAs<Image9>(source);
2911 return Image9::CopyImage(context, dest9, src9, sourceBox.toRect(), destOffset, unpackFlipY,
2912 unpackPremultiplyAlpha, unpackUnmultiplyAlpha);
2913 }
2914
createTextureStorage2D(SwapChainD3D * swapChain,const std::string & label)2915 TextureStorage *Renderer9::createTextureStorage2D(SwapChainD3D *swapChain, const std::string &label)
2916 {
2917 SwapChain9 *swapChain9 = GetAs<SwapChain9>(swapChain);
2918 return new TextureStorage9_2D(this, swapChain9, label);
2919 }
2920
createTextureStorageEGLImage(EGLImageD3D * eglImage,RenderTargetD3D * renderTargetD3D,const std::string & label)2921 TextureStorage *Renderer9::createTextureStorageEGLImage(EGLImageD3D *eglImage,
2922 RenderTargetD3D *renderTargetD3D,
2923 const std::string &label)
2924 {
2925 return new TextureStorage9_EGLImage(this, eglImage, GetAs<RenderTarget9>(renderTargetD3D),
2926 label);
2927 }
2928
createTextureStorageBuffer(const gl::OffsetBindingPointer<gl::Buffer> & buffer,GLenum internalFormat,const std::string & label)2929 TextureStorage *Renderer9::createTextureStorageBuffer(
2930 const gl::OffsetBindingPointer<gl::Buffer> &buffer,
2931 GLenum internalFormat,
2932 const std::string &label)
2933 {
2934 UNREACHABLE();
2935 return nullptr;
2936 }
2937
createTextureStorageExternal(egl::Stream * stream,const egl::Stream::GLTextureDescription & desc,const std::string & label)2938 TextureStorage *Renderer9::createTextureStorageExternal(
2939 egl::Stream *stream,
2940 const egl::Stream::GLTextureDescription &desc,
2941 const std::string &label)
2942 {
2943 UNIMPLEMENTED();
2944 return nullptr;
2945 }
2946
createTextureStorage2D(GLenum internalformat,BindFlags bindFlags,GLsizei width,GLsizei height,int levels,const std::string & label,bool hintLevelZeroOnly)2947 TextureStorage *Renderer9::createTextureStorage2D(GLenum internalformat,
2948 BindFlags bindFlags,
2949 GLsizei width,
2950 GLsizei height,
2951 int levels,
2952 const std::string &label,
2953 bool hintLevelZeroOnly)
2954 {
2955 return new TextureStorage9_2D(this, internalformat, bindFlags.renderTarget, width, height,
2956 levels, label);
2957 }
2958
createTextureStorageCube(GLenum internalformat,BindFlags bindFlags,int size,int levels,bool hintLevelZeroOnly,const std::string & label)2959 TextureStorage *Renderer9::createTextureStorageCube(GLenum internalformat,
2960 BindFlags bindFlags,
2961 int size,
2962 int levels,
2963 bool hintLevelZeroOnly,
2964 const std::string &label)
2965 {
2966 return new TextureStorage9_Cube(this, internalformat, bindFlags.renderTarget, size, levels,
2967 hintLevelZeroOnly, label);
2968 }
2969
createTextureStorage3D(GLenum internalformat,BindFlags bindFlags,GLsizei width,GLsizei height,GLsizei depth,int levels,const std::string & label)2970 TextureStorage *Renderer9::createTextureStorage3D(GLenum internalformat,
2971 BindFlags bindFlags,
2972 GLsizei width,
2973 GLsizei height,
2974 GLsizei depth,
2975 int levels,
2976 const std::string &label)
2977 {
2978 // 3D textures are not supported by the D3D9 backend.
2979 UNREACHABLE();
2980
2981 return nullptr;
2982 }
2983
createTextureStorage2DArray(GLenum internalformat,BindFlags bindFlags,GLsizei width,GLsizei height,GLsizei depth,int levels,const std::string & label)2984 TextureStorage *Renderer9::createTextureStorage2DArray(GLenum internalformat,
2985 BindFlags bindFlags,
2986 GLsizei width,
2987 GLsizei height,
2988 GLsizei depth,
2989 int levels,
2990 const std::string &label)
2991 {
2992 // 2D array textures are not supported by the D3D9 backend.
2993 UNREACHABLE();
2994
2995 return nullptr;
2996 }
2997
createTextureStorage2DMultisample(GLenum internalformat,GLsizei width,GLsizei height,int levels,int samples,bool fixedSampleLocations,const std::string & label)2998 TextureStorage *Renderer9::createTextureStorage2DMultisample(GLenum internalformat,
2999 GLsizei width,
3000 GLsizei height,
3001 int levels,
3002 int samples,
3003 bool fixedSampleLocations,
3004 const std::string &label)
3005 {
3006 // 2D multisampled textures are not supported by the D3D9 backend.
3007 UNREACHABLE();
3008
3009 return nullptr;
3010 }
3011
createTextureStorage2DMultisampleArray(GLenum internalformat,GLsizei width,GLsizei height,GLsizei depth,int levels,int samples,bool fixedSampleLocations,const std::string & label)3012 TextureStorage *Renderer9::createTextureStorage2DMultisampleArray(GLenum internalformat,
3013 GLsizei width,
3014 GLsizei height,
3015 GLsizei depth,
3016 int levels,
3017 int samples,
3018 bool fixedSampleLocations,
3019 const std::string &label)
3020 {
3021 // 2D multisampled textures are not supported by the D3D9 backend.
3022 UNREACHABLE();
3023
3024 return nullptr;
3025 }
3026
getLUID(LUID * adapterLuid) const3027 bool Renderer9::getLUID(LUID *adapterLuid) const
3028 {
3029 adapterLuid->HighPart = 0;
3030 adapterLuid->LowPart = 0;
3031
3032 if (mD3d9Ex)
3033 {
3034 mD3d9Ex->GetAdapterLUID(mAdapter, adapterLuid);
3035 return true;
3036 }
3037
3038 return false;
3039 }
3040
getVertexConversionType(angle::FormatID vertexFormatID) const3041 VertexConversionType Renderer9::getVertexConversionType(angle::FormatID vertexFormatID) const
3042 {
3043 return d3d9::GetVertexFormatInfo(getCapsDeclTypes(), vertexFormatID).conversionType;
3044 }
3045
getVertexComponentType(angle::FormatID vertexFormatID) const3046 GLenum Renderer9::getVertexComponentType(angle::FormatID vertexFormatID) const
3047 {
3048 return d3d9::GetVertexFormatInfo(getCapsDeclTypes(), vertexFormatID).componentType;
3049 }
3050
getVertexSpaceRequired(const gl::Context * context,const gl::VertexAttribute & attrib,const gl::VertexBinding & binding,size_t count,GLsizei instances,GLuint baseInstance,unsigned int * bytesRequiredOut) const3051 angle::Result Renderer9::getVertexSpaceRequired(const gl::Context *context,
3052 const gl::VertexAttribute &attrib,
3053 const gl::VertexBinding &binding,
3054 size_t count,
3055 GLsizei instances,
3056 GLuint baseInstance,
3057 unsigned int *bytesRequiredOut) const
3058 {
3059 if (!attrib.enabled)
3060 {
3061 *bytesRequiredOut = 16u;
3062 return angle::Result::Continue;
3063 }
3064
3065 angle::FormatID vertexFormatID = gl::GetVertexFormatID(attrib, gl::VertexAttribType::Float);
3066 const d3d9::VertexFormat &d3d9VertexInfo =
3067 d3d9::GetVertexFormatInfo(getCapsDeclTypes(), vertexFormatID);
3068
3069 unsigned int elementCount = 0;
3070 const unsigned int divisor = binding.getDivisor();
3071 if (instances == 0 || divisor == 0)
3072 {
3073 elementCount = static_cast<unsigned int>(count);
3074 }
3075 else
3076 {
3077 // Round up to divisor, if possible
3078 elementCount = UnsignedCeilDivide(static_cast<unsigned int>(instances), divisor);
3079 }
3080
3081 bool check = (d3d9VertexInfo.outputElementSize >
3082 std::numeric_limits<unsigned int>::max() / elementCount);
3083 ANGLE_CHECK(GetImplAs<Context9>(context), !check,
3084 "New vertex buffer size would result in an overflow.", GL_OUT_OF_MEMORY);
3085
3086 *bytesRequiredOut = static_cast<unsigned int>(d3d9VertexInfo.outputElementSize) * elementCount;
3087 return angle::Result::Continue;
3088 }
3089
generateCaps(gl::Caps * outCaps,gl::TextureCapsMap * outTextureCaps,gl::Extensions * outExtensions,gl::Limitations * outLimitations,ShPixelLocalStorageOptions * outPLSOptions) const3090 void Renderer9::generateCaps(gl::Caps *outCaps,
3091 gl::TextureCapsMap *outTextureCaps,
3092 gl::Extensions *outExtensions,
3093 gl::Limitations *outLimitations,
3094 ShPixelLocalStorageOptions *outPLSOptions) const
3095 {
3096 d3d9_gl::GenerateCaps(mD3d9, mDevice, mDeviceType, mAdapter, outCaps, outTextureCaps,
3097 outExtensions, outLimitations);
3098 }
3099
initializeFeatures(angle::FeaturesD3D * features) const3100 void Renderer9::initializeFeatures(angle::FeaturesD3D *features) const
3101 {
3102 if (!mDisplay->getState().featuresAllDisabled)
3103 {
3104 d3d9::InitializeFeatures(features, mAdapterIdentifier.VendorId);
3105 }
3106 ApplyFeatureOverrides(features, mDisplay->getState());
3107 }
3108
initializeFrontendFeatures(angle::FrontendFeatures * features) const3109 void Renderer9::initializeFrontendFeatures(angle::FrontendFeatures *features) const {}
3110
createEGLDevice()3111 DeviceImpl *Renderer9::createEGLDevice()
3112 {
3113 return new DeviceD3D(EGL_D3D9_DEVICE_ANGLE, mDevice);
3114 }
3115
CurSamplerState()3116 Renderer9::CurSamplerState::CurSamplerState()
3117 : forceSet(true), baseLevel(std::numeric_limits<size_t>::max()), samplerState()
3118 {}
3119
genericDrawElements(const gl::Context * context,gl::PrimitiveMode mode,GLsizei count,gl::DrawElementsType type,const void * indices,GLsizei instances)3120 angle::Result Renderer9::genericDrawElements(const gl::Context *context,
3121 gl::PrimitiveMode mode,
3122 GLsizei count,
3123 gl::DrawElementsType type,
3124 const void *indices,
3125 GLsizei instances)
3126 {
3127 const gl::State &state = context->getState();
3128 gl::Program *program = context->getState().getProgram();
3129 ASSERT(program != nullptr);
3130 ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program);
3131 bool usesPointSize = programD3D->usesPointSize();
3132
3133 programD3D->updateSamplerMapping();
3134
3135 if (!applyPrimitiveType(mode, count, usesPointSize))
3136 {
3137 return angle::Result::Continue;
3138 }
3139
3140 ANGLE_TRY(updateState(context, mode));
3141 ANGLE_TRY(applyTextures(context));
3142 ANGLE_TRY(applyShaders(context, mode));
3143
3144 if (!skipDraw(state, mode))
3145 {
3146 ANGLE_TRY(drawElementsImpl(context, mode, count, type, indices, instances));
3147 }
3148
3149 return angle::Result::Continue;
3150 }
3151
genericDrawArrays(const gl::Context * context,gl::PrimitiveMode mode,GLint first,GLsizei count,GLsizei instances)3152 angle::Result Renderer9::genericDrawArrays(const gl::Context *context,
3153 gl::PrimitiveMode mode,
3154 GLint first,
3155 GLsizei count,
3156 GLsizei instances)
3157 {
3158 gl::Program *program = context->getState().getProgram();
3159 ASSERT(program != nullptr);
3160 ProgramD3D *programD3D = GetImplAs<ProgramD3D>(program);
3161 bool usesPointSize = programD3D->usesPointSize();
3162
3163 programD3D->updateSamplerMapping();
3164
3165 if (!applyPrimitiveType(mode, count, usesPointSize))
3166 {
3167 return angle::Result::Continue;
3168 }
3169
3170 ANGLE_TRY(updateState(context, mode));
3171 ANGLE_TRY(applyVertexBuffer(context, mode, first, count, instances, nullptr));
3172 ANGLE_TRY(applyTextures(context));
3173 ANGLE_TRY(applyShaders(context, mode));
3174
3175 if (!skipDraw(context->getState(), mode))
3176 {
3177 ANGLE_TRY(drawArraysImpl(context, mode, first, count, instances));
3178 }
3179
3180 return angle::Result::Continue;
3181 }
3182
createDefaultFramebuffer(const gl::FramebufferState & state)3183 FramebufferImpl *Renderer9::createDefaultFramebuffer(const gl::FramebufferState &state)
3184 {
3185 return new Framebuffer9(state, this);
3186 }
3187
getMaxSupportedESVersion() const3188 gl::Version Renderer9::getMaxSupportedESVersion() const
3189 {
3190 return gl::Version(2, 0);
3191 }
3192
getMaxConformantESVersion() const3193 gl::Version Renderer9::getMaxConformantESVersion() const
3194 {
3195 return gl::Version(2, 0);
3196 }
3197
clearRenderTarget(const gl::Context * context,RenderTargetD3D * renderTarget,const gl::ColorF & clearColorValue,const float clearDepthValue,const unsigned int clearStencilValue)3198 angle::Result Renderer9::clearRenderTarget(const gl::Context *context,
3199 RenderTargetD3D *renderTarget,
3200 const gl::ColorF &clearColorValue,
3201 const float clearDepthValue,
3202 const unsigned int clearStencilValue)
3203 {
3204 D3DCOLOR color =
3205 D3DCOLOR_ARGB(gl::unorm<8>(clearColorValue.alpha), gl::unorm<8>(clearColorValue.red),
3206 gl::unorm<8>(clearColorValue.green), gl::unorm<8>(clearColorValue.blue));
3207 float depth = clearDepthValue;
3208 DWORD stencil = clearStencilValue & 0x000000FF;
3209
3210 unsigned int renderTargetSerial = renderTarget->getSerial();
3211 RenderTarget9 *renderTarget9 = GetAs<RenderTarget9>(renderTarget);
3212 IDirect3DSurface9 *renderTargetSurface = renderTarget9->getSurface();
3213 ASSERT(renderTargetSurface);
3214
3215 DWORD dxClearFlags = 0;
3216
3217 const gl::InternalFormat &internalFormatInfo =
3218 gl::GetSizedInternalFormatInfo(renderTarget->getInternalFormat());
3219 if (internalFormatInfo.depthBits > 0 || internalFormatInfo.stencilBits > 0)
3220 {
3221 dxClearFlags = D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL;
3222 if (mAppliedDepthStencilSerial != renderTargetSerial)
3223 {
3224 mDevice->SetDepthStencilSurface(renderTargetSurface);
3225 }
3226 }
3227 else
3228 {
3229 dxClearFlags = D3DCLEAR_TARGET;
3230 if (mAppliedRenderTargetSerial != renderTargetSerial)
3231 {
3232 mDevice->SetRenderTarget(0, renderTargetSurface);
3233 }
3234 }
3235 SafeRelease(renderTargetSurface);
3236
3237 D3DVIEWPORT9 viewport;
3238 viewport.X = 0;
3239 viewport.Y = 0;
3240 viewport.Width = renderTarget->getWidth();
3241 viewport.Height = renderTarget->getHeight();
3242 mDevice->SetViewport(&viewport);
3243
3244 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
3245
3246 mDevice->Clear(0, nullptr, dxClearFlags, color, depth, stencil);
3247
3248 markAllStateDirty();
3249
3250 return angle::Result::Continue;
3251 }
3252
canSelectViewInVertexShader() const3253 bool Renderer9::canSelectViewInVertexShader() const
3254 {
3255 return false;
3256 }
3257
3258 // For each Direct3D sampler of either the pixel or vertex stage,
3259 // looks up the corresponding OpenGL texture image unit and texture type,
3260 // and sets the texture and its addressing/filtering state (or NULL when inactive).
3261 // Sampler mapping needs to be up-to-date on the program object before this is called.
applyTextures(const gl::Context * context,gl::ShaderType shaderType)3262 angle::Result Renderer9::applyTextures(const gl::Context *context, gl::ShaderType shaderType)
3263 {
3264 const auto &glState = context->getState();
3265 const auto &caps = context->getCaps();
3266 ProgramD3D *programD3D = GetImplAs<ProgramD3D>(glState.getProgram());
3267
3268 ASSERT(!programD3D->isSamplerMappingDirty());
3269
3270 // TODO(jmadill): Use the Program's sampler bindings.
3271 const gl::ActiveTexturesCache &activeTextures = glState.getActiveTexturesCache();
3272
3273 const gl::RangeUI samplerRange = programD3D->getUsedSamplerRange(shaderType);
3274 for (unsigned int samplerIndex = samplerRange.low(); samplerIndex < samplerRange.high();
3275 samplerIndex++)
3276 {
3277 GLint textureUnit = programD3D->getSamplerMapping(shaderType, samplerIndex, caps);
3278 ASSERT(textureUnit != -1);
3279 gl::Texture *texture = activeTextures[textureUnit];
3280
3281 // A nullptr texture indicates incomplete.
3282 if (texture)
3283 {
3284 gl::Sampler *samplerObject = glState.getSampler(textureUnit);
3285
3286 const gl::SamplerState &samplerState =
3287 samplerObject ? samplerObject->getSamplerState() : texture->getSamplerState();
3288
3289 ANGLE_TRY(setSamplerState(context, shaderType, samplerIndex, texture, samplerState));
3290 ANGLE_TRY(setTexture(context, shaderType, samplerIndex, texture));
3291 }
3292 else
3293 {
3294 gl::TextureType textureType =
3295 programD3D->getSamplerTextureType(shaderType, samplerIndex);
3296
3297 // Texture is not sampler complete or it is in use by the framebuffer. Bind the
3298 // incomplete texture.
3299 gl::Texture *incompleteTexture = nullptr;
3300 ANGLE_TRY(getIncompleteTexture(context, textureType, &incompleteTexture));
3301 ANGLE_TRY(setSamplerState(context, shaderType, samplerIndex, incompleteTexture,
3302 incompleteTexture->getSamplerState()));
3303 ANGLE_TRY(setTexture(context, shaderType, samplerIndex, incompleteTexture));
3304 }
3305 }
3306
3307 // Set all the remaining textures to NULL
3308 int samplerCount = (shaderType == gl::ShaderType::Fragment)
3309 ? caps.maxShaderTextureImageUnits[gl::ShaderType::Fragment]
3310 : caps.maxShaderTextureImageUnits[gl::ShaderType::Vertex];
3311
3312 // TODO(jmadill): faster way?
3313 for (int samplerIndex = samplerRange.high(); samplerIndex < samplerCount; samplerIndex++)
3314 {
3315 ANGLE_TRY(setTexture(context, shaderType, samplerIndex, nullptr));
3316 }
3317
3318 return angle::Result::Continue;
3319 }
3320
applyTextures(const gl::Context * context)3321 angle::Result Renderer9::applyTextures(const gl::Context *context)
3322 {
3323 ANGLE_TRY(applyTextures(context, gl::ShaderType::Vertex));
3324 ANGLE_TRY(applyTextures(context, gl::ShaderType::Fragment));
3325 return angle::Result::Continue;
3326 }
3327
getIncompleteTexture(const gl::Context * context,gl::TextureType type,gl::Texture ** textureOut)3328 angle::Result Renderer9::getIncompleteTexture(const gl::Context *context,
3329 gl::TextureType type,
3330 gl::Texture **textureOut)
3331 {
3332 return GetImplAs<Context9>(context)->getIncompleteTexture(context, type, textureOut);
3333 }
3334
ensureVertexDataManagerInitialized(const gl::Context * context)3335 angle::Result Renderer9::ensureVertexDataManagerInitialized(const gl::Context *context)
3336 {
3337 if (!mVertexDataManager)
3338 {
3339 mVertexDataManager = new VertexDataManager(this);
3340 ANGLE_TRY(mVertexDataManager->initialize(context));
3341 }
3342
3343 return angle::Result::Continue;
3344 }
3345
getVendorString() const3346 std::string Renderer9::getVendorString() const
3347 {
3348 return GetVendorString(getVendorId());
3349 }
3350
getVersionString(bool includeFullVersion) const3351 std::string Renderer9::getVersionString(bool includeFullVersion) const
3352 {
3353 std::ostringstream versionString;
3354 std::string driverName(mAdapterIdentifier.Driver);
3355 if (!driverName.empty())
3356 {
3357 versionString << mAdapterIdentifier.Driver;
3358 }
3359 else
3360 {
3361 versionString << "D3D9";
3362 }
3363
3364 if (includeFullVersion)
3365 {
3366 versionString << " -";
3367 versionString << GetDriverVersionString(mAdapterIdentifier.DriverVersion);
3368 }
3369
3370 return versionString.str();
3371 }
3372
CreateRenderer9(egl::Display * display)3373 RendererD3D *CreateRenderer9(egl::Display *display)
3374 {
3375 return new Renderer9(display);
3376 }
3377
3378 } // namespace rx
3379