blob: 6a951a491a9e93835cc0a724d7b43d0f919809d9 [file] [log] [blame]
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001//
2// Copyright (c) 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
daniel@transgaming.com1d6aff22012-11-28 19:30:42 +00007// Renderer9.cpp: Implements a back-end specific class for the D3D9 renderer.
daniel@transgaming.com621ce052012-10-31 17:52:29 +00008
daniel@transgaming.com621ce052012-10-31 17:52:29 +00009#include "common/debug.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000010#include "libGLESv2/main.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000011#include "libGLESv2/utilities.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000012#include "libGLESv2/mathutil.h"
daniel@transgaming.com91207b72012-11-28 20:56:43 +000013#include "libGLESv2/Buffer.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000014#include "libGLESv2/Framebuffer.h"
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +000015#include "libGLESv2/Program.h"
16#include "libGLESv2/ProgramBinary.h"
daniel@transgaming.com91207b72012-11-28 20:56:43 +000017#include "libGLESv2/IndexDataManager.h"
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000018#include "libGLESv2/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000019#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000020#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000021#include "libGLESv2/renderer/ShaderExecutable9.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000022#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +000023#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000024#include "libGLESv2/renderer/Image.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000025#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000026#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000027
daniel@transgaming.com3281f972012-10-31 18:38:51 +000028#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000029#include "libEGL/Display.h"
30
daniel@transgaming.com621ce052012-10-31 17:52:29 +000031// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
32#define REF_RAST 0
33
34// The "Debug This Pixel..." feature in PIX often fails when using the
35// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
36// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
37#if !defined(ANGLE_ENABLE_D3D9EX)
38// Enables use of the IDirect3D9Ex interface, when available
39#define ANGLE_ENABLE_D3D9EX 1
40#endif // !defined(ANGLE_ENABLE_D3D9EX)
41
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000042#if !defined(ANGLE_COMPILE_OPTIMIZATION_LEVEL)
43#define ANGLE_COMPILE_OPTIMIZATION_LEVEL D3DCOMPILE_OPTIMIZATION_LEVEL3
44#endif
45
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000046namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000047{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000048static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000049 {
50 D3DFMT_A1R5G5B5,
51 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
52 D3DFMT_A8R8G8B8,
53 D3DFMT_R5G6B5,
54 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
55 D3DFMT_X8R8G8B8
56 };
57
daniel@transgaming.com222ee082012-11-28 19:31:49 +000058static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000059 {
60 D3DFMT_UNKNOWN,
61 // D3DFMT_D16_LOCKABLE,
62 D3DFMT_D32,
63 // D3DFMT_D15S1,
64 D3DFMT_D24S8,
65 D3DFMT_D24X8,
66 // D3DFMT_D24X4S4,
67 D3DFMT_D16,
68 // D3DFMT_D32F_LOCKABLE,
69 // D3DFMT_D24FS8
70 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000072Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000073{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000074 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000075
daniel@transgaming.com7d738a22012-11-28 19:43:08 +000076 mD3dCompilerModule = NULL;
77
daniel@transgaming.com621ce052012-10-31 17:52:29 +000078 mD3d9 = NULL;
79 mD3d9Ex = NULL;
80 mDevice = NULL;
81 mDeviceEx = NULL;
82 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000083 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000084
85 mAdapter = D3DADAPTER_DEFAULT;
86
87 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
88 mDeviceType = D3DDEVTYPE_REF;
89 #else
90 mDeviceType = D3DDEVTYPE_HAL;
91 #endif
92
93 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000094
95 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000096
daniel@transgaming.com91207b72012-11-28 20:56:43 +000097 mAppliedIBSerial = 0;
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000098
99 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000100
101 mVertexDataManager = NULL;
102 mIndexDataManager = NULL;
103 mLineLoopIB = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000104}
105
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000106Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000107{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000108 releaseDeviceResources();
109
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000110 if (mDevice)
111 {
112 // If the device is lost, reset it first to prevent leaving the driver in an unstable state
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000113 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000114 {
115 resetDevice();
116 }
117
118 mDevice->Release();
119 mDevice = NULL;
120 }
121
122 if (mDeviceEx)
123 {
124 mDeviceEx->Release();
125 mDeviceEx = NULL;
126 }
127
128 if (mD3d9)
129 {
130 mD3d9->Release();
131 mD3d9 = NULL;
132 }
133
134 if (mDeviceWindow)
135 {
136 DestroyWindow(mDeviceWindow);
137 mDeviceWindow = NULL;
138 }
139
140 if (mD3d9Ex)
141 {
142 mD3d9Ex->Release();
143 mD3d9Ex = NULL;
144 }
145
146 if (mD3d9Module)
147 {
148 mD3d9Module = NULL;
149 }
150
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000151 if (mD3dCompilerModule)
152 {
153 FreeLibrary(mD3dCompilerModule);
154 mD3dCompilerModule = NULL;
155 }
156
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000157 while (!mMultiSampleSupport.empty())
158 {
159 delete [] mMultiSampleSupport.begin()->second;
160 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
161 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000162}
163
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000164Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
165{
166 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
167 return static_cast<rx::Renderer9*>(renderer);
168}
169
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000170EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000171{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000172 if (mSoftwareDevice)
173 {
174 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
175 }
176 else
177 {
178 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
179 }
180
181 if (mD3d9Module == NULL)
182 {
183 ERR("No D3D9 module found - aborting!\n");
184 return EGL_NOT_INITIALIZED;
185 }
186
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000187 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
188 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
189
190 // Use Direct3D9Ex if available. Among other things, this version is less
191 // inclined to report a lost context, for example when the user switches
192 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
193 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
194 {
195 ASSERT(mD3d9Ex);
196 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
197 ASSERT(mD3d9);
198 }
199 else
200 {
201 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
202 }
203
204 if (!mD3d9)
205 {
206 ERR("Could not create D3D9 device - aborting!\n");
207 return EGL_NOT_INITIALIZED;
208 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000209
210#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
211 // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
212 static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
213
214 for (int i = 0; i < sizeof(d3dCompilerNames) / sizeof(*d3dCompilerNames); ++i)
215 {
216 if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
217 {
218 break;
219 }
220 }
221#else
222 // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
223 mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
224#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
225
226 if (!mD3dCompilerModule)
227 {
228 terminate();
229 return false;
230 }
231
232 mD3DCompileFunc = reinterpret_cast<D3DCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
233 ASSERT(mD3DCompileFunc);
234
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000235 if (mDc != NULL)
236 {
237 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
238 }
239
240 HRESULT result;
241
242 // Give up on getting device caps after about one second.
243 for (int i = 0; i < 10; ++i)
244 {
245 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
246 if (SUCCEEDED(result))
247 {
248 break;
249 }
250 else if (result == D3DERR_NOTAVAILABLE)
251 {
252 Sleep(100); // Give the driver some time to initialize/recover
253 }
254 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
255 {
256 ERR("failed to get device caps (0x%x)\n", result);
257 return EGL_NOT_INITIALIZED;
258 }
259 }
260
261 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
262 {
263 ERR("Renderer does not support PS 2.0. aborting!\n");
264 return EGL_NOT_INITIALIZED;
265 }
266
267 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
268 // This is required by Texture2D::convertToRenderTarget.
269 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
270 {
271 ERR("Renderer does not support stretctrect from textures!\n");
272 return EGL_NOT_INITIALIZED;
273 }
274
275 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
276
277 // ATI cards on XP have problems with non-power-of-two textures.
278 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
279 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
280 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
281 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
282
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000283 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
284 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
285
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000286 mMinSwapInterval = 4;
287 mMaxSwapInterval = 0;
288
289 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
290 {
291 mMinSwapInterval = std::min(mMinSwapInterval, 0);
292 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
293 }
294 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
295 {
296 mMinSwapInterval = std::min(mMinSwapInterval, 1);
297 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
298 }
299 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
300 {
301 mMinSwapInterval = std::min(mMinSwapInterval, 2);
302 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
303 }
304 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
305 {
306 mMinSwapInterval = std::min(mMinSwapInterval, 3);
307 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
308 }
309 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
310 {
311 mMinSwapInterval = std::min(mMinSwapInterval, 4);
312 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
313 }
314
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000315 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000316 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000317 {
318 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000319 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
320 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000321
322 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
323 {
324 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
325 {
326 max = j;
327 }
328 }
329 }
330
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000331 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000332 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000333 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000334 continue;
335
336 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000337 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
338 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000339
340 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
341 {
342 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
343 {
344 max = j;
345 }
346 }
347 }
348
349 mMaxSupportedSamples = max;
350
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000351 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
352 static const TCHAR className[] = TEXT("STATIC");
353
354 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
355
356 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
357 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
358
359 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
360 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
361 {
362 return EGL_BAD_ALLOC;
363 }
364
365 if (FAILED(result))
366 {
367 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
368
369 if (FAILED(result))
370 {
371 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
372 return EGL_BAD_ALLOC;
373 }
374 }
375
376 if (mD3d9Ex)
377 {
378 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
379 ASSERT(SUCCEEDED(result));
380 }
381
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000382 mVertexShaderCache.initialize(mDevice);
383 mPixelShaderCache.initialize(mDevice);
384
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000385 initializeDevice();
386
387 return EGL_SUCCESS;
388}
389
390// do any one-time device initialization
391// NOTE: this is also needed after a device lost/reset
392// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000393void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000394{
395 // Permanent non-default states
396 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
397 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
398
399 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
400 {
401 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
402 }
403 else
404 {
405 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
406 }
407
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000408 markAllStateDirty();
409
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000410 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000411
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000412 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000413 mBlit = new Blit(this);
414 mVertexDataManager = new gl::VertexDataManager(this);
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000415 mIndexDataManager = new gl::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000416}
417
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000418D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000419{
420 D3DPRESENT_PARAMETERS presentParameters = {0};
421
422 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
423 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
424 presentParameters.BackBufferCount = 1;
425 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
426 presentParameters.BackBufferWidth = 1;
427 presentParameters.BackBufferHeight = 1;
428 presentParameters.EnableAutoDepthStencil = FALSE;
429 presentParameters.Flags = 0;
430 presentParameters.hDeviceWindow = mDeviceWindow;
431 presentParameters.MultiSampleQuality = 0;
432 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
433 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
434 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
435 presentParameters.Windowed = TRUE;
436
437 return presentParameters;
438}
439
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000440int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000441{
442 D3DDISPLAYMODE currentDisplayMode;
443 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
444
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000445 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
446 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000447 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
448 int numConfigs = 0;
449
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000450 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000451 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000452 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000453
454 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
455
456 if (SUCCEEDED(result))
457 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000458 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000459 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000460 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000461 HRESULT result = D3D_OK;
462
463 if(depthStencilFormat != D3DFMT_UNKNOWN)
464 {
465 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
466 }
467
468 if (SUCCEEDED(result))
469 {
470 if(depthStencilFormat != D3DFMT_UNKNOWN)
471 {
472 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
473 }
474
475 if (SUCCEEDED(result))
476 {
477 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000478 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
479 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000480 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
481 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
482
483 (*configDescList)[numConfigs++] = newConfig;
484 }
485 }
486 }
487 }
488 }
489
490 return numConfigs;
491}
492
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000493void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000494{
495 delete [] (configDescList);
496}
497
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000498void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000499{
500 if (!mSceneStarted)
501 {
502 long result = mDevice->BeginScene();
503 if (SUCCEEDED(result)) {
504 // This is defensive checking against the device being
505 // lost at unexpected times.
506 mSceneStarted = true;
507 }
508 }
509}
510
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000511void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000512{
513 if (mSceneStarted)
514 {
515 // EndScene can fail if the device was lost, for example due
516 // to a TDR during a draw call.
517 mDevice->EndScene();
518 mSceneStarted = false;
519 }
520}
521
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000522// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000523void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000524{
525 HRESULT result;
526
527 IDirect3DQuery9* query = allocateEventQuery();
528 if (!query)
529 {
530 return;
531 }
532
533 result = query->Issue(D3DISSUE_END);
534 ASSERT(SUCCEEDED(result));
535
536 do
537 {
538 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
539
540 if(block && result == S_FALSE)
541 {
542 // Keep polling, but allow other threads to do something useful first
543 Sleep(0);
544 // explicitly check for device loss
545 // some drivers seem to return S_FALSE even if the device is lost
546 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000547 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000548 {
549 result = D3DERR_DEVICELOST;
550 }
551 }
552 }
553 while(block && result == S_FALSE);
554
555 freeEventQuery(query);
556
557 if (isDeviceLostError(result))
558 {
559 mDisplay->notifyDeviceLost();
560 }
561}
562
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000563SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
564{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000565 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000566}
567
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000568// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000569IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000570{
571 IDirect3DQuery9 *query = NULL;
572
573 if (mEventQueryPool.empty())
574 {
575 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
576 ASSERT(SUCCEEDED(result));
577 }
578 else
579 {
580 query = mEventQueryPool.back();
581 mEventQueryPool.pop_back();
582 }
583
584 return query;
585}
586
587// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000588void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000589{
590 if (mEventQueryPool.size() > 1000)
591 {
592 query->Release();
593 }
594 else
595 {
596 mEventQueryPool.push_back(query);
597 }
598}
599
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000600
601HRESULT Renderer9::compileShaderSource(const char* hlsl, const char* sourceName, const char* profile, DWORD flags, ID3DBlob** binary, ID3DBlob** errorMessage)
602{
603 return mD3DCompileFunc(hlsl, strlen(hlsl), sourceName, NULL, NULL, "main", profile, flags, 0, binary, errorMessage);
604}
605
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000606IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000607{
608 return mVertexShaderCache.create(function, length);
609}
610
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000611IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000612{
613 return mPixelShaderCache.create(function, length);
614}
615
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000616HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
617{
618 D3DPOOL Pool = getBufferPool(Usage);
619 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
620}
621
622HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
623{
624 D3DPOOL Pool = getBufferPool(Usage);
625 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
626}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000627
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000628void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000629{
630 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
631 int d3dSampler = index + d3dSamplerOffset;
632
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000633 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
634 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000635
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000636 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000637 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000638 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000639 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
640 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
641 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
642 if (mSupportsTextureFilterAnisotropy)
643 {
644 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
645 }
646}
647
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000648void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000649{
650 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
651 int d3dSampler = index + d3dSamplerOffset;
652 IDirect3DBaseTexture9 *d3dTexture = NULL;
653
654 if (texture)
655 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000656 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000657 if (texStorage)
658 {
659 d3dTexture = texStorage->getBaseTexture();
660 }
661 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000662 // in the texture class and we're unexpectedly missing the d3d texture
663 ASSERT(d3dTexture != NULL);
664 }
665
666 mDevice->SetTexture(d3dSampler, d3dTexture);
667}
668
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000669void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
670{
671 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
672 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
673
674 if (rasterStateChanged)
675 {
676 // Set the cull mode
677 if (rasterState.cullFace)
678 {
679 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
680 }
681 else
682 {
683 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
684 }
685
686 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
687
688 mCurRasterState = rasterState;
689 }
690
691 if (rasterStateChanged || depthSizeChanged)
692 {
693 if (rasterState.polygonOffsetFill)
694 {
695 if (depthSize > 0)
696 {
697 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
698
699 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
700 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
701 }
702 }
703 else
704 {
705 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
706 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
707 }
708
709 mCurDepthSize = depthSize;
710 }
711
712 mForceSetRasterState = false;
713}
714
715void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
716{
717 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
718 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
719 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
720
721 if (blendStateChanged || blendColorChanged)
722 {
723 if (blendState.blend)
724 {
725 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
726
727 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
728 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
729 {
730 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
731 }
732 else
733 {
734 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
735 gl::unorm<8>(blendColor.alpha),
736 gl::unorm<8>(blendColor.alpha),
737 gl::unorm<8>(blendColor.alpha)));
738 }
739
740 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
741 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
742 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
743
744 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
745 blendState.destBlendRGB != blendState.destBlendAlpha ||
746 blendState.blendEquationRGB != blendState.blendEquationAlpha)
747 {
748 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
749
750 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
751 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
752 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
753 }
754 else
755 {
756 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
757 }
758 }
759 else
760 {
761 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
762 }
763
764 if (blendState.sampleAlphaToCoverage)
765 {
766 FIXME("Sample alpha to coverage is unimplemented.");
767 }
768
769 // Set the color mask
770 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
771 // Apparently some ATI cards have a bug where a draw with a zero color
772 // write mask can cause later draws to have incorrect results. Instead,
773 // set a nonzero color write mask but modify the blend state so that no
774 // drawing is done.
775 // http://code.google.com/p/angleproject/issues/detail?id=169
776
777 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
778 blendState.colorMaskBlue, blendState.colorMaskAlpha);
779 if (colorMask == 0 && !zeroColorMaskAllowed)
780 {
781 // Enable green channel, but set blending so nothing will be drawn.
782 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
783 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
784
785 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
786 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
787 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
788 }
789 else
790 {
791 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
792 }
793
794 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
795
796 mCurBlendState = blendState;
797 mCurBlendColor = blendColor;
798 }
799
800 if (sampleMaskChanged)
801 {
802 // Set the multisample mask
803 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
804 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
805
806 mCurSampleMask = sampleMask;
807 }
808
809 mForceSetBlendState = false;
810}
811
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000812void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
813 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000814{
815 bool depthStencilStateChanged = mForceSetDepthStencilState ||
816 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000817 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
818 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000819 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
820 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
821
822 if (depthStencilStateChanged)
823 {
824 if (depthStencilState.depthTest)
825 {
826 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
827 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
828 }
829 else
830 {
831 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
832 }
833
834 mCurDepthStencilState = depthStencilState;
835 }
836
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000837 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000838 {
839 if (depthStencilState.stencilTest && stencilSize > 0)
840 {
841 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
842 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
843
844 // FIXME: Unsupported by D3D9
845 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
846 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
847 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
848 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000849 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000850 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
851 {
852 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
853 return error(GL_INVALID_OPERATION);
854 }
855
856 // get the maximum size of the stencil ref
857 GLuint maxStencil = (1 << stencilSize) - 1;
858
859 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
860 depthStencilState.stencilWritemask);
861 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
862 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
863
864 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000865 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000866 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
867 depthStencilState.stencilMask);
868
869 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
870 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
871 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
872 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
873 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
874 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
875
876 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
877 depthStencilState.stencilBackWritemask);
878 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
879 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
880
881 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000882 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000883 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
884 depthStencilState.stencilBackMask);
885
886 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
887 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
888 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
889 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
890 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
891 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
892 }
893 else
894 {
895 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
896 }
897
898 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
899
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000900 mCurStencilRef = stencilRef;
901 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000902 mCurFrontFaceCCW = frontFaceCCW;
903 mCurStencilSize = stencilSize;
904 }
905
906 mForceSetDepthStencilState = false;
907}
908
909void Renderer9::setScissorRectangle(const gl::Rectangle& scissor, unsigned int renderTargetWidth,
910 unsigned int renderTargetHeight)
911{
912 bool renderTargetSizedChanged = mForceSetScissor ||
913 renderTargetWidth != mCurRenderTargetWidth ||
914 renderTargetHeight != mCurRenderTargetHeight;
915 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
916
917 if (renderTargetSizedChanged || scissorChanged)
918 {
919 RECT rect;
920 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000921 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000922 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000923 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000924 mDevice->SetScissorRect(&rect);
925
926 mCurScissor = scissor;
927 mCurRenderTargetWidth = renderTargetWidth;
928 mCurRenderTargetHeight = renderTargetHeight;
929 }
930
931 mForceSetScissor = false;
932}
933
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000934bool Renderer9::setViewport(const gl::Rectangle& viewport, float zNear, float zFar,
935 unsigned int renderTargetWidth, unsigned int renderTargetHeight,
936 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
937{
938 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
939 zNear != mCurNear || zFar != mCurFar;
940
941 D3DVIEWPORT9 dxViewport;
942 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(renderTargetWidth));
943 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(renderTargetHeight));
944 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(renderTargetWidth) - static_cast<int>(dxViewport.X));
945 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(renderTargetHeight) - static_cast<int>(dxViewport.Y));
946 dxViewport.MinZ = zNear;
947 dxViewport.MaxZ = zFar;
948
949 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
950 {
951 return false; // Nothing to render
952 }
953
954 if (viewportChanged)
955 {
956 mDevice->SetViewport(&dxViewport);
957
958 mCurViewport = viewport;
959 mCurNear = zNear;
960 mCurFar = zFar;
961 }
962
963 if (currentProgram && (viewportChanged || forceSetUniforms))
964 {
965 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
966 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
967 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
968
969 // These values are used for computing gl_FragCoord in Program::linkVaryings().
970 GLint coord = currentProgram->getDxCoordLocation();
971 GLfloat whxy[4] = { viewport.width * 0.5f,
972 viewport.height * 0.5f,
973 viewport.x + (viewport.width * 0.5f),
974 viewport.y + (viewport.height * 0.5f) };
975 currentProgram->setUniform4fv(coord, 1, whxy);
976
977 GLint depth = currentProgram->getDxDepthLocation();
978 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
979 currentProgram->setUniform2fv(depth, 1, dz);
980
981 GLint depthRange = currentProgram->getDxDepthRangeLocation();
982 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
983 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
984 }
985
986 mForceSetViewport = false;
987 return true;
988}
989
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000990bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
991{
992 switch (mode)
993 {
994 case GL_POINTS:
995 mPrimitiveType = D3DPT_POINTLIST;
996 mPrimitiveCount = count;
997 break;
998 case GL_LINES:
999 mPrimitiveType = D3DPT_LINELIST;
1000 mPrimitiveCount = count / 2;
1001 break;
1002 case GL_LINE_LOOP:
1003 mPrimitiveType = D3DPT_LINESTRIP;
1004 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
1005 break;
1006 case GL_LINE_STRIP:
1007 mPrimitiveType = D3DPT_LINESTRIP;
1008 mPrimitiveCount = count - 1;
1009 break;
1010 case GL_TRIANGLES:
1011 mPrimitiveType = D3DPT_TRIANGLELIST;
1012 mPrimitiveCount = count / 3;
1013 break;
1014 case GL_TRIANGLE_STRIP:
1015 mPrimitiveType = D3DPT_TRIANGLESTRIP;
1016 mPrimitiveCount = count - 2;
1017 break;
1018 case GL_TRIANGLE_FAN:
1019 mPrimitiveType = D3DPT_TRIANGLEFAN;
1020 mPrimitiveCount = count - 2;
1021 break;
1022 default:
1023 return error(GL_INVALID_ENUM, false);
1024 }
1025
1026 return mPrimitiveCount > 0;
1027}
1028
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001029bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001030{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001031 // if there is no color attachment we must synthesize a NULL colorattachment
1032 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1033 gl::Renderbuffer *renderbufferObject = NULL;
1034 if (framebuffer->getColorbufferType() != GL_NONE)
1035 {
1036 renderbufferObject = framebuffer->getColorbuffer();
1037 }
1038 else
1039 {
1040 renderbufferObject = framebuffer->getNullColorbuffer();
1041 }
1042 if (!renderbufferObject)
1043 {
1044 ERR("unable to locate renderbuffer for FBO.");
1045 return false;
1046 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001047
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001048 bool renderTargetChanged = false;
1049 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1050 if (renderTargetSerial != mAppliedRenderTargetSerial)
1051 {
1052 // Apply the render target on the device
1053 IDirect3DSurface9 *renderTargetSurface = NULL;
1054
1055 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1056 if (renderTarget)
1057 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001058 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001059 }
1060
1061 if (!renderTargetSurface)
1062 {
1063 ERR("render target pointer unexpectedly null.");
1064 return false; // Context must be lost
1065 }
1066
1067 mDevice->SetRenderTarget(0, renderTargetSurface);
1068 renderTargetSurface->Release();
1069
1070 mAppliedRenderTargetSerial = renderTargetSerial;
1071 renderTargetChanged = true;
1072 }
1073
1074 gl::Renderbuffer *depthStencil = NULL;
1075 unsigned int depthbufferSerial = 0;
1076 unsigned int stencilbufferSerial = 0;
1077 if (framebuffer->getDepthbufferType() != GL_NONE)
1078 {
1079 depthStencil = framebuffer->getDepthbuffer();
1080 if (!depthStencil)
1081 {
1082 ERR("Depth stencil pointer unexpectedly null.");
1083 return false;
1084 }
1085
1086 depthbufferSerial = depthStencil->getSerial();
1087 }
1088 else if (framebuffer->getStencilbufferType() != GL_NONE)
1089 {
1090 depthStencil = framebuffer->getStencilbuffer();
1091 if (!depthStencil)
1092 {
1093 ERR("Depth stencil pointer unexpectedly null.");
1094 return false;
1095 }
1096
1097 stencilbufferSerial = depthStencil->getSerial();
1098 }
1099
1100 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1101 stencilbufferSerial != mAppliedStencilbufferSerial ||
1102 !mDepthStencilInitialized)
1103 {
1104 // Apply the depth stencil on the device
1105 if (depthStencil)
1106 {
1107 IDirect3DSurface9 *depthStencilSurface = NULL;
1108 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1109
1110 if (depthStencilRenderTarget)
1111 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001112 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001113 }
1114
1115 if (!depthStencilSurface)
1116 {
1117 ERR("depth stencil pointer unexpectedly null.");
1118 return false; // Context must be lost
1119 }
1120
1121 mDevice->SetDepthStencilSurface(depthStencilSurface);
1122 depthStencilSurface->Release();
1123 }
1124 else
1125 {
1126 mDevice->SetDepthStencilSurface(NULL);
1127 }
1128
1129 mAppliedDepthbufferSerial = depthbufferSerial;
1130 mAppliedStencilbufferSerial = stencilbufferSerial;
1131 mDepthStencilInitialized = true;
1132 }
1133
1134 if (renderTargetChanged || !mRenderTargetDescInitialized)
1135 {
1136 mForceSetScissor = true;
1137 mForceSetViewport = true;
1138
1139 mRenderTargetDesc.width = renderbufferObject->getWidth();
1140 mRenderTargetDesc.height = renderbufferObject->getHeight();
1141 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1142 mRenderTargetDescInitialized = true;
1143 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001144
1145 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001146}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001147
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001148GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001149{
1150 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1151 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1152 if (err != GL_NO_ERROR)
1153 {
1154 return err;
1155 }
1156
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001157 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1158}
1159
1160// Applies the indices and element array bindings to the Direct3D 9 device
1161GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, gl::TranslatedIndexData *indexInfo)
1162{
1163 IDirect3DIndexBuffer9 *indexBuffer;
1164 unsigned int serial;
1165 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1166
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001167 if (err == GL_NO_ERROR)
1168 {
1169 if (serial != mAppliedIBSerial)
1170 {
1171 mDevice->SetIndices(indexBuffer);
1172 mAppliedIBSerial = serial;
1173 }
1174 }
1175
1176 return err;
1177}
1178
1179void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1180{
1181 startScene();
1182
1183 if (mode == GL_LINE_LOOP)
1184 {
1185 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1186 }
1187 else if (instances > 0)
1188 {
1189 gl::StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
1190 if (countingIB)
1191 {
1192 if (mAppliedIBSerial != countingIB->getSerial())
1193 {
1194 mDevice->SetIndices(countingIB->getBuffer());
1195 mAppliedIBSerial = countingIB->getSerial();
1196 }
1197
1198 for (int i = 0; i < mRepeatDraw; i++)
1199 {
1200 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1201 }
1202 }
1203 else
1204 {
1205 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1206 return error(GL_OUT_OF_MEMORY);
1207 }
1208 }
1209 else // Regular case
1210 {
1211 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1212 }
1213}
1214
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001215void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const gl::TranslatedIndexData &indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001216{
1217 startScene();
1218
1219 if (mode == GL_LINE_LOOP)
1220 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001221 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001222 }
1223 else
1224 {
1225 for (int i = 0; i < mRepeatDraw; i++)
1226 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001227 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1228 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001229 }
1230 }
1231}
1232
1233void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1234{
1235 // Get the raw indices for an indexed draw
1236 if (type != GL_NONE && elementArrayBuffer)
1237 {
1238 gl::Buffer *indexBuffer = elementArrayBuffer;
1239 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1240 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1241 }
1242
1243 UINT startIndex = 0;
1244 bool succeeded = false;
1245
1246 if (get32BitIndexSupport())
1247 {
1248 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1249
1250 if (!mLineLoopIB)
1251 {
1252 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
1253 }
1254
1255 if (mLineLoopIB)
1256 {
1257 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1258
1259 UINT offset = 0;
1260 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1261 startIndex = offset / 4;
1262
1263 if (data)
1264 {
1265 switch (type)
1266 {
1267 case GL_NONE: // Non-indexed draw
1268 for (int i = 0; i < count; i++)
1269 {
1270 data[i] = i;
1271 }
1272 data[count] = 0;
1273 break;
1274 case GL_UNSIGNED_BYTE:
1275 for (int i = 0; i < count; i++)
1276 {
1277 data[i] = static_cast<const GLubyte*>(indices)[i];
1278 }
1279 data[count] = static_cast<const GLubyte*>(indices)[0];
1280 break;
1281 case GL_UNSIGNED_SHORT:
1282 for (int i = 0; i < count; i++)
1283 {
1284 data[i] = static_cast<const GLushort*>(indices)[i];
1285 }
1286 data[count] = static_cast<const GLushort*>(indices)[0];
1287 break;
1288 case GL_UNSIGNED_INT:
1289 for (int i = 0; i < count; i++)
1290 {
1291 data[i] = static_cast<const GLuint*>(indices)[i];
1292 }
1293 data[count] = static_cast<const GLuint*>(indices)[0];
1294 break;
1295 default: UNREACHABLE();
1296 }
1297
1298 mLineLoopIB->unmap();
1299 succeeded = true;
1300 }
1301 }
1302 }
1303 else
1304 {
1305 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1306
1307 if (!mLineLoopIB)
1308 {
1309 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
1310 }
1311
1312 if (mLineLoopIB)
1313 {
1314 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1315
1316 UINT offset = 0;
1317 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1318 startIndex = offset / 2;
1319
1320 if (data)
1321 {
1322 switch (type)
1323 {
1324 case GL_NONE: // Non-indexed draw
1325 for (int i = 0; i < count; i++)
1326 {
1327 data[i] = i;
1328 }
1329 data[count] = 0;
1330 break;
1331 case GL_UNSIGNED_BYTE:
1332 for (int i = 0; i < count; i++)
1333 {
1334 data[i] = static_cast<const GLubyte*>(indices)[i];
1335 }
1336 data[count] = static_cast<const GLubyte*>(indices)[0];
1337 break;
1338 case GL_UNSIGNED_SHORT:
1339 for (int i = 0; i < count; i++)
1340 {
1341 data[i] = static_cast<const GLushort*>(indices)[i];
1342 }
1343 data[count] = static_cast<const GLushort*>(indices)[0];
1344 break;
1345 case GL_UNSIGNED_INT:
1346 for (int i = 0; i < count; i++)
1347 {
1348 data[i] = static_cast<const GLuint*>(indices)[i];
1349 }
1350 data[count] = static_cast<const GLuint*>(indices)[0];
1351 break;
1352 default: UNREACHABLE();
1353 }
1354
1355 mLineLoopIB->unmap();
1356 succeeded = true;
1357 }
1358 }
1359 }
1360
1361 if (succeeded)
1362 {
1363 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1364 {
1365 mDevice->SetIndices(mLineLoopIB->getBuffer());
1366 mAppliedIBSerial = mLineLoopIB->getSerial();
1367 }
1368
1369 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1370 }
1371 else
1372 {
1373 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1374 return error(GL_OUT_OF_MEMORY);
1375 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001376}
1377
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001378void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1379{
daniel@transgaming.com95892412012-11-28 20:59:09 +00001380 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1381 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
1382
1383 IDirect3DVertexShader9 *vertexShader = NULL;
1384 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
1385
1386 IDirect3DPixelShader9 *pixelShader = NULL;
1387 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001388
1389 mDevice->SetPixelShader(pixelShader);
1390 mDevice->SetVertexShader(vertexShader);
1391 programBinary->dirtyAllUniforms();
1392}
1393
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001394void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001395{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001396 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1397 gl::unorm<8>(clearParams.colorClearValue.red),
1398 gl::unorm<8>(clearParams.colorClearValue.green),
1399 gl::unorm<8>(clearParams.colorClearValue.blue));
1400 float depth = gl::clamp01(clearParams.depthClearValue);
1401 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001402
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001403 unsigned int stencilUnmasked = 0x0;
1404 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1405 {
1406 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1407 stencilUnmasked = (0x1 << stencilSize) - 1;
1408 }
1409
1410 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1411
1412 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1413 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1414 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1415 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1416 clearParams.colorMaskBlue && alphaUnmasked);
1417
1418 if (needMaskedColorClear || needMaskedStencilClear)
1419 {
1420 // State which is altered in all paths from this point to the clear call is saved.
1421 // State which is altered in only some paths will be flagged dirty in the case that
1422 // that path is taken.
1423 HRESULT hr;
1424 if (mMaskedClearSavedState == NULL)
1425 {
1426 hr = mDevice->BeginStateBlock();
1427 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1428
1429 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1430 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1431 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1432 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1433 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1434 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1435 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1436 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1437 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1438 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1439 mDevice->SetPixelShader(NULL);
1440 mDevice->SetVertexShader(NULL);
1441 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1442 mDevice->SetStreamSource(0, NULL, 0, 0);
1443 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1444 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1445 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1446 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1447 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1448 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1449 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1450
1451 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1452 {
1453 mDevice->SetStreamSourceFreq(i, 1);
1454 }
1455
1456 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1457 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1458 }
1459
1460 ASSERT(mMaskedClearSavedState != NULL);
1461
1462 if (mMaskedClearSavedState != NULL)
1463 {
1464 hr = mMaskedClearSavedState->Capture();
1465 ASSERT(SUCCEEDED(hr));
1466 }
1467
1468 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1469 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1470 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1471 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1472 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1473 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1474 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1475 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1476
1477 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1478 {
1479 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1480 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1481 clearParams.colorMaskGreen,
1482 clearParams.colorMaskBlue,
1483 clearParams.colorMaskAlpha));
1484 }
1485 else
1486 {
1487 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1488 }
1489
1490 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1491 {
1492 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1493 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1494 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1495 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1496 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1497 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1498 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1499 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1500 }
1501 else
1502 {
1503 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1504 }
1505
1506 mDevice->SetPixelShader(NULL);
1507 mDevice->SetVertexShader(NULL);
1508 mDevice->SetFVF(D3DFVF_XYZRHW);
1509 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1510 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1511 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1512 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1513 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1514 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1515 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1516
1517 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1518 {
1519 mDevice->SetStreamSourceFreq(i, 1);
1520 }
1521
1522 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1523 quad[0][0] = -0.5f;
1524 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1525 quad[0][2] = 0.0f;
1526 quad[0][3] = 1.0f;
1527
1528 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1529 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1530 quad[1][2] = 0.0f;
1531 quad[1][3] = 1.0f;
1532
1533 quad[2][0] = -0.5f;
1534 quad[2][1] = -0.5f;
1535 quad[2][2] = 0.0f;
1536 quad[2][3] = 1.0f;
1537
1538 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1539 quad[3][1] = -0.5f;
1540 quad[3][2] = 0.0f;
1541 quad[3][3] = 1.0f;
1542
1543 startScene();
1544 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1545
1546 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1547 {
1548 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1549 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1550 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1551 }
1552
1553 if (mMaskedClearSavedState != NULL)
1554 {
1555 mMaskedClearSavedState->Apply();
1556 }
1557 }
1558 else if (clearParams.mask)
1559 {
1560 DWORD dxClearFlags = 0;
1561 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1562 {
1563 dxClearFlags |= D3DCLEAR_TARGET;
1564 }
1565 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1566 {
1567 dxClearFlags |= D3DCLEAR_ZBUFFER;
1568 }
1569 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1570 {
1571 dxClearFlags |= D3DCLEAR_STENCIL;
1572 }
1573
1574 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1575 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001576}
1577
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001578void Renderer9::markAllStateDirty()
1579{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001580 mAppliedRenderTargetSerial = 0;
1581 mAppliedDepthbufferSerial = 0;
1582 mAppliedStencilbufferSerial = 0;
1583 mDepthStencilInitialized = false;
1584 mRenderTargetDescInitialized = false;
1585
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001586 mForceSetDepthStencilState = true;
1587 mForceSetRasterState = true;
1588 mForceSetBlendState = true;
1589 mForceSetScissor = true;
1590 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001591
1592 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001593}
1594
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001595void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001596{
1597 while (!mEventQueryPool.empty())
1598 {
1599 mEventQueryPool.back()->Release();
1600 mEventQueryPool.pop_back();
1601 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001602
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001603 if (mMaskedClearSavedState)
1604 {
1605 mMaskedClearSavedState->Release();
1606 mMaskedClearSavedState = NULL;
1607 }
1608
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001609 mVertexShaderCache.clear();
1610 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001611
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001612 delete mBlit;
1613 mBlit = NULL;
1614
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001615 delete mVertexDataManager;
1616 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001617
1618 delete mIndexDataManager;
1619 mIndexDataManager = NULL;
1620
1621 delete mLineLoopIB;
1622 mLineLoopIB = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001623}
1624
1625
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001626void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001627{
1628 mDeviceLost = true;
1629}
1630
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001631bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001632{
1633 return mDeviceLost;
1634}
1635
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001636// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001637bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001638{
1639 bool isLost = false;
1640
1641 if (mDeviceEx)
1642 {
1643 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1644 }
1645 else if (mDevice)
1646 {
1647 isLost = FAILED(mDevice->TestCooperativeLevel());
1648 }
1649 else
1650 {
1651 // No device yet, so no reset required
1652 }
1653
1654 if (isLost)
1655 {
1656 // ensure we note the device loss --
1657 // we'll probably get this done again by markDeviceLost
1658 // but best to remember it!
1659 // Note that we don't want to clear the device loss status here
1660 // -- this needs to be done by resetDevice
1661 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001662 if (notify)
1663 {
1664 mDisplay->notifyDeviceLost();
1665 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001666 }
1667
1668 return isLost;
1669}
1670
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001671bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001672{
1673 HRESULT status = D3D_OK;
1674
1675 if (mDeviceEx)
1676 {
1677 status = mDeviceEx->CheckDeviceState(NULL);
1678 }
1679 else if (mDevice)
1680 {
1681 status = mDevice->TestCooperativeLevel();
1682 }
1683
1684 switch (status)
1685 {
1686 case D3DERR_DEVICENOTRESET:
1687 case D3DERR_DEVICEHUNG:
1688 return true;
1689 default:
1690 return false;
1691 }
1692}
1693
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001694bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001695{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001696 releaseDeviceResources();
1697
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001698 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1699
1700 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001701 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001702 int attempts = 3;
1703
1704 while (lost && attempts > 0)
1705 {
1706 if (mDeviceEx)
1707 {
1708 Sleep(500); // Give the graphics driver some CPU time
1709 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1710 }
1711 else
1712 {
1713 result = mDevice->TestCooperativeLevel();
1714 while (result == D3DERR_DEVICELOST)
1715 {
1716 Sleep(100); // Give the graphics driver some CPU time
1717 result = mDevice->TestCooperativeLevel();
1718 }
1719
1720 if (result == D3DERR_DEVICENOTRESET)
1721 {
1722 result = mDevice->Reset(&presentParameters);
1723 }
1724 }
1725
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001726 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001727 attempts --;
1728 }
1729
1730 if (FAILED(result))
1731 {
1732 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1733 return false;
1734 }
1735
1736 // reset device defaults
1737 initializeDevice();
1738 mDeviceLost = false;
1739
1740 return true;
1741}
1742
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001743DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001744{
1745 return mAdapterIdentifier.VendorId;
1746}
1747
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001748const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001749{
1750 return mAdapterIdentifier.Description;
1751}
1752
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001753GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001754{
1755 return mAdapterIdentifier.DeviceIdentifier;
1756}
1757
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001758void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001759{
1760 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1761 {
1762 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1763 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1764
1765 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1766 }
1767}
1768
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001769bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001770{
1771 D3DDISPLAYMODE currentDisplayMode;
1772 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1773
1774 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1775}
1776
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001777bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001778{
1779 D3DDISPLAYMODE currentDisplayMode;
1780 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1781
1782 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1783}
1784
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001785bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001786{
1787 D3DDISPLAYMODE currentDisplayMode;
1788 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1789
1790 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1791}
1792
1793// we use INTZ for depth textures in Direct3D9
1794// we also want NULL texture support to ensure the we can make depth-only FBOs
1795// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001796bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001797{
1798 D3DDISPLAYMODE currentDisplayMode;
1799 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1800
1801 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1802 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1803 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1804 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1805
1806 return intz && null;
1807}
1808
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001809bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001810{
1811 D3DDISPLAYMODE currentDisplayMode;
1812 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1813
1814 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1815 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1816 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1817 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1818
1819 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1820 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1821 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1822 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1823
1824 if (!*filtering && !*renderable)
1825 {
1826 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1827 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1828 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1829 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1830 }
1831 else
1832 {
1833 return true;
1834 }
1835}
1836
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001837bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001838{
1839 D3DDISPLAYMODE currentDisplayMode;
1840 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1841
1842 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1843 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1844 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1845 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1846
1847 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1848 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1849 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1850 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1851
1852 if (!*filtering && !*renderable)
1853 {
1854 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1855 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1856 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1857 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1858 }
1859 else
1860 {
1861 return true;
1862 }
1863}
1864
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001865bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001866{
1867 D3DDISPLAYMODE currentDisplayMode;
1868 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1869
1870 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1871}
1872
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001873bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001874{
1875 D3DDISPLAYMODE currentDisplayMode;
1876 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1877
1878 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1879}
1880
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001881bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001882{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001883 return mSupportsTextureFilterAnisotropy;
1884}
1885
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001886float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001887{
1888 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001889 {
1890 return mDeviceCaps.MaxAnisotropy;
1891 }
1892 return 1.0f;
1893}
1894
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001895bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001896{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001897 IDirect3DQuery9 *query = allocateEventQuery();
1898 if (query)
1899 {
1900 freeEventQuery(query);
1901 return true;
1902 }
1903 else
1904 {
1905 return false;
1906 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001907 return true;
1908}
1909
1910// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1911// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001912bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001913{
1914 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1915 {
1916 return false;
1917 }
1918
1919 D3DDISPLAYMODE currentDisplayMode;
1920 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1921
1922 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1923
1924 return SUCCEEDED(result);
1925}
1926
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001927bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001928{
1929 return mSupportsNonPower2Textures;
1930}
1931
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001932bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001933{
1934 if (!mDevice)
1935 {
1936 return false;
1937 }
1938
1939 IDirect3DQuery9 *query = NULL;
1940 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1941 if (SUCCEEDED(result) && query)
1942 {
1943 query->Release();
1944 return true;
1945 }
1946 else
1947 {
1948 return false;
1949 }
1950}
1951
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001952bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001953{
1954 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1955}
1956
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001957bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001958{
1959 // PIX doesn't seem to support using share handles, so disable them.
1960 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001961 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001962}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001963
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001964int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001965{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001966 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001967}
1968
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001969float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001970{
1971 return mDeviceCaps.MaxPointSize;
1972}
1973
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001974int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001975{
1976 return (int)mDeviceCaps.MaxTextureWidth;
1977}
1978
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001979int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001980{
1981 return (int)mDeviceCaps.MaxTextureHeight;
1982}
1983
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001984bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001985{
1986 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1987}
1988
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001989DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001990{
1991 return mDeviceCaps.DeclTypes;
1992}
1993
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001994int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001995{
1996 return mMinSwapInterval;
1997}
1998
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001999int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002000{
2001 return mMaxSwapInterval;
2002}
2003
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002004int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002005{
2006 return mMaxSupportedSamples;
2007}
2008
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002009int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002010{
2011 if (requested == 0)
2012 {
2013 return requested;
2014 }
2015
2016 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2017 if (itr == mMultiSampleSupport.end())
2018 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002019 if (format == D3DFMT_UNKNOWN)
2020 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002021 return -1;
2022 }
2023
2024 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2025 {
2026 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2027 {
2028 return i;
2029 }
2030 }
2031
2032 return -1;
2033}
2034
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002035D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2036{
2037 switch (internalformat)
2038 {
2039 case GL_DEPTH_COMPONENT16:
2040 case GL_DEPTH_COMPONENT32_OES:
2041 case GL_DEPTH24_STENCIL8_OES:
2042 return D3DFMT_INTZ;
2043 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2044 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2045 return D3DFMT_DXT1;
2046 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2047 return D3DFMT_DXT3;
2048 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2049 return D3DFMT_DXT5;
2050 case GL_RGBA32F_EXT:
2051 case GL_RGB32F_EXT:
2052 case GL_ALPHA32F_EXT:
2053 case GL_LUMINANCE32F_EXT:
2054 case GL_LUMINANCE_ALPHA32F_EXT:
2055 return D3DFMT_A32B32G32R32F;
2056 case GL_RGBA16F_EXT:
2057 case GL_RGB16F_EXT:
2058 case GL_ALPHA16F_EXT:
2059 case GL_LUMINANCE16F_EXT:
2060 case GL_LUMINANCE_ALPHA16F_EXT:
2061 return D3DFMT_A16B16G16R16F;
2062 case GL_LUMINANCE8_EXT:
2063 if (getLuminanceTextureSupport())
2064 {
2065 return D3DFMT_L8;
2066 }
2067 break;
2068 case GL_LUMINANCE8_ALPHA8_EXT:
2069 if (getLuminanceAlphaTextureSupport())
2070 {
2071 return D3DFMT_A8L8;
2072 }
2073 break;
2074 case GL_RGB8_OES:
2075 case GL_RGB565:
2076 return D3DFMT_X8R8G8B8;
2077 }
2078
2079 return D3DFMT_A8R8G8B8;
2080}
2081
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002082bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002083{
2084 bool result = false;
2085
2086 if (source && dest)
2087 {
2088 int levels = source->levelCount();
2089 for (int i = 0; i < levels; ++i)
2090 {
2091 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2092 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2093
2094 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2095
2096 if (srcSurf) srcSurf->Release();
2097 if (dstSurf) dstSurf->Release();
2098
2099 if (!result)
2100 return false;
2101 }
2102 }
2103
2104 return result;
2105}
2106
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002107bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002108{
2109 bool result = false;
2110
2111 if (source && dest)
2112 {
2113 int levels = source->levelCount();
2114 for (int f = 0; f < 6; f++)
2115 {
2116 for (int i = 0; i < levels; i++)
2117 {
2118 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2119 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2120
2121 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2122
2123 if (srcSurf) srcSurf->Release();
2124 if (dstSurf) dstSurf->Release();
2125
2126 if (!result)
2127 return false;
2128 }
2129 }
2130 }
2131
2132 return result;
2133}
2134
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002135D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002136{
2137 if (mD3d9Ex != NULL)
2138 {
2139 return D3DPOOL_DEFAULT;
2140 }
2141 else
2142 {
2143 if (!(usage & D3DUSAGE_DYNAMIC))
2144 {
2145 return D3DPOOL_MANAGED;
2146 }
2147 }
2148
2149 return D3DPOOL_DEFAULT;
2150}
2151
daniel@transgaming.com38380882012-11-28 19:36:39 +00002152bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2153 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002154{
2155 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2156}
2157
daniel@transgaming.com38380882012-11-28 19:36:39 +00002158bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2159 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002160{
2161 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2162}
2163
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002164bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2165 bool blitRenderTarget, bool blitDepthStencil)
2166{
2167 endScene();
2168
2169 if (blitRenderTarget)
2170 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002171 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2172 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2173 RenderTarget9 *readRenderTarget = NULL;
2174 RenderTarget9 *drawRenderTarget = NULL;
2175 IDirect3DSurface9* readSurface = NULL;
2176 IDirect3DSurface9* drawSurface = NULL;
2177
2178 if (readBuffer)
2179 {
2180 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2181 }
2182 if (drawBuffer)
2183 {
2184 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2185 }
2186
2187 if (readRenderTarget)
2188 {
2189 readSurface = readRenderTarget->getSurface();
2190 }
2191 if (drawRenderTarget)
2192 {
2193 drawSurface = drawRenderTarget->getSurface();
2194 }
2195
2196 if (!readSurface || !drawSurface)
2197 {
2198 ERR("Failed to retrieve the render target.");
2199 return error(GL_OUT_OF_MEMORY, false);
2200 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002201
2202 RECT srcRect, dstRect;
2203 RECT *srcRectPtr = NULL;
2204 RECT *dstRectPtr = NULL;
2205
2206 if (readRect)
2207 {
2208 srcRect.left = readRect->x;
2209 srcRect.right = readRect->x + readRect->width;
2210 srcRect.top = readRect->y;
2211 srcRect.bottom = readRect->y + readRect->height;
2212 srcRectPtr = &srcRect;
2213 }
2214
2215 if (drawRect)
2216 {
2217 dstRect.left = drawRect->x;
2218 dstRect.right = drawRect->x + drawRect->width;
2219 dstRect.top = drawRect->y;
2220 dstRect.bottom = drawRect->y + drawRect->height;
2221 dstRectPtr = &dstRect;
2222 }
2223
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002224 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002225
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002226 readSurface->Release();
2227 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002228
2229 if (FAILED(result))
2230 {
2231 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2232 return false;
2233 }
2234 }
2235
2236 if (blitDepthStencil)
2237 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002238 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2239 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2240 RenderTarget9 *readDepthStencil = NULL;
2241 RenderTarget9 *drawDepthStencil = NULL;
2242 IDirect3DSurface9* readSurface = NULL;
2243 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002244
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002245 if (readBuffer)
2246 {
2247 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2248 }
2249 if (drawBuffer)
2250 {
2251 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2252 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002253
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002254 if (readDepthStencil)
2255 {
2256 readSurface = readDepthStencil->getSurface();
2257 }
2258 if (drawDepthStencil)
2259 {
2260 drawSurface = drawDepthStencil->getSurface();
2261 }
2262
2263 if (!readSurface || !drawSurface)
2264 {
2265 ERR("Failed to retrieve the render target.");
2266 return error(GL_OUT_OF_MEMORY, false);
2267 }
2268
2269 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2270
2271 readSurface->Release();
2272 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002273
2274 if (FAILED(result))
2275 {
2276 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2277 return false;
2278 }
2279 }
2280
2281 return true;
2282}
2283
2284void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2285 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2286{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002287 RenderTarget9 *renderTarget = NULL;
2288 IDirect3DSurface9 *surface = NULL;
2289 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2290
2291 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002292 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002293 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2294 }
2295
2296 if (renderTarget)
2297 {
2298 surface = renderTarget->getSurface();
2299 }
2300
2301 if (!surface)
2302 {
2303 // context must be lost
2304 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002305 }
2306
2307 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002308 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002309
2310 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2311 {
2312 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002313 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002314 return error(GL_OUT_OF_MEMORY);
2315 }
2316
2317 HRESULT result;
2318 IDirect3DSurface9 *systemSurface = NULL;
2319 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2320 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2321 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2322 if (directToPixels)
2323 {
2324 // Use the pixels ptr as a shared handle to write directly into client's memory
2325 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2326 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2327 if (FAILED(result))
2328 {
2329 // Try again without the shared handle
2330 directToPixels = false;
2331 }
2332 }
2333
2334 if (!directToPixels)
2335 {
2336 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2337 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2338 if (FAILED(result))
2339 {
2340 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002341 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002342 return error(GL_OUT_OF_MEMORY);
2343 }
2344 }
2345
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002346 result = mDevice->GetRenderTargetData(surface, systemSurface);
2347 surface->Release();
2348 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002349
2350 if (FAILED(result))
2351 {
2352 systemSurface->Release();
2353
2354 // It turns out that D3D will sometimes produce more error
2355 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002356 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002357 return error(GL_OUT_OF_MEMORY);
2358 else
2359 {
2360 UNREACHABLE();
2361 return;
2362 }
2363
2364 }
2365
2366 if (directToPixels)
2367 {
2368 systemSurface->Release();
2369 return;
2370 }
2371
2372 RECT rect;
2373 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2374 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2375 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2376 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2377
2378 D3DLOCKED_RECT lock;
2379 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2380
2381 if (FAILED(result))
2382 {
2383 UNREACHABLE();
2384 systemSurface->Release();
2385
2386 return; // No sensible error to generate
2387 }
2388
2389 unsigned char *dest = (unsigned char*)pixels;
2390 unsigned short *dest16 = (unsigned short*)pixels;
2391
2392 unsigned char *source;
2393 int inputPitch;
2394 if (packReverseRowOrder)
2395 {
2396 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2397 inputPitch = -lock.Pitch;
2398 }
2399 else
2400 {
2401 source = (unsigned char*)lock.pBits;
2402 inputPitch = lock.Pitch;
2403 }
2404
2405 unsigned int fastPixelSize = 0;
2406
2407 if (desc.Format == D3DFMT_A8R8G8B8 &&
2408 format == GL_BGRA_EXT &&
2409 type == GL_UNSIGNED_BYTE)
2410 {
2411 fastPixelSize = 4;
2412 }
2413 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2414 format == GL_BGRA_EXT &&
2415 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2416 (desc.Format == D3DFMT_A1R5G5B5 &&
2417 format == GL_BGRA_EXT &&
2418 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2419 {
2420 fastPixelSize = 2;
2421 }
2422 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2423 format == GL_RGBA &&
2424 type == GL_HALF_FLOAT_OES)
2425 {
2426 fastPixelSize = 8;
2427 }
2428 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2429 format == GL_RGBA &&
2430 type == GL_FLOAT)
2431 {
2432 fastPixelSize = 16;
2433 }
2434
2435 for (int j = 0; j < rect.bottom - rect.top; j++)
2436 {
2437 if (fastPixelSize != 0)
2438 {
2439 // Fast path for formats which require no translation:
2440 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2441 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2442 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2443 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2444 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2445 //
2446 // Note that buffers with no alpha go through the slow path below.
2447 memcpy(dest + j * outputPitch,
2448 source + j * inputPitch,
2449 (rect.right - rect.left) * fastPixelSize);
2450 continue;
2451 }
2452
2453 for (int i = 0; i < rect.right - rect.left; i++)
2454 {
2455 float r;
2456 float g;
2457 float b;
2458 float a;
2459
2460 switch (desc.Format)
2461 {
2462 case D3DFMT_R5G6B5:
2463 {
2464 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2465
2466 a = 1.0f;
2467 b = (rgb & 0x001F) * (1.0f / 0x001F);
2468 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2469 r = (rgb & 0xF800) * (1.0f / 0xF800);
2470 }
2471 break;
2472 case D3DFMT_A1R5G5B5:
2473 {
2474 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2475
2476 a = (argb & 0x8000) ? 1.0f : 0.0f;
2477 b = (argb & 0x001F) * (1.0f / 0x001F);
2478 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2479 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2480 }
2481 break;
2482 case D3DFMT_A8R8G8B8:
2483 {
2484 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2485
2486 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2487 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2488 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2489 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2490 }
2491 break;
2492 case D3DFMT_X8R8G8B8:
2493 {
2494 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2495
2496 a = 1.0f;
2497 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2498 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2499 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2500 }
2501 break;
2502 case D3DFMT_A2R10G10B10:
2503 {
2504 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2505
2506 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2507 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2508 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2509 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2510 }
2511 break;
2512 case D3DFMT_A32B32G32R32F:
2513 {
2514 // float formats in D3D are stored rgba, rather than the other way round
2515 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2516 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2517 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2518 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2519 }
2520 break;
2521 case D3DFMT_A16B16G16R16F:
2522 {
2523 // float formats in D3D are stored rgba, rather than the other way round
2524 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2525 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2526 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2527 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2528 }
2529 break;
2530 default:
2531 UNIMPLEMENTED(); // FIXME
2532 UNREACHABLE();
2533 return;
2534 }
2535
2536 switch (format)
2537 {
2538 case GL_RGBA:
2539 switch (type)
2540 {
2541 case GL_UNSIGNED_BYTE:
2542 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2543 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2544 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2545 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2546 break;
2547 default: UNREACHABLE();
2548 }
2549 break;
2550 case GL_BGRA_EXT:
2551 switch (type)
2552 {
2553 case GL_UNSIGNED_BYTE:
2554 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2555 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2556 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2557 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2558 break;
2559 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2560 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2561 // this type is packed as follows:
2562 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2563 // --------------------------------------------------------------------------------
2564 // | 4th | 3rd | 2nd | 1st component |
2565 // --------------------------------------------------------------------------------
2566 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2567 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2568 ((unsigned short)(15 * a + 0.5f) << 12)|
2569 ((unsigned short)(15 * r + 0.5f) << 8) |
2570 ((unsigned short)(15 * g + 0.5f) << 4) |
2571 ((unsigned short)(15 * b + 0.5f) << 0);
2572 break;
2573 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2574 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2575 // this type is packed as follows:
2576 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2577 // --------------------------------------------------------------------------------
2578 // | 4th | 3rd | 2nd | 1st component |
2579 // --------------------------------------------------------------------------------
2580 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2581 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2582 ((unsigned short)( a + 0.5f) << 15) |
2583 ((unsigned short)(31 * r + 0.5f) << 10) |
2584 ((unsigned short)(31 * g + 0.5f) << 5) |
2585 ((unsigned short)(31 * b + 0.5f) << 0);
2586 break;
2587 default: UNREACHABLE();
2588 }
2589 break;
2590 case GL_RGB:
2591 switch (type)
2592 {
2593 case GL_UNSIGNED_SHORT_5_6_5:
2594 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2595 ((unsigned short)(31 * b + 0.5f) << 0) |
2596 ((unsigned short)(63 * g + 0.5f) << 5) |
2597 ((unsigned short)(31 * r + 0.5f) << 11);
2598 break;
2599 case GL_UNSIGNED_BYTE:
2600 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2601 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2602 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2603 break;
2604 default: UNREACHABLE();
2605 }
2606 break;
2607 default: UNREACHABLE();
2608 }
2609 }
2610 }
2611
2612 systemSurface->UnlockRect();
2613
2614 systemSurface->Release();
2615}
2616
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002617RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2618{
2619 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2620 IDirect3DSurface9 *surface = NULL;
2621 if (depth)
2622 {
2623 surface = swapChain9->getDepthStencil();
2624 }
2625 else
2626 {
2627 surface = swapChain9->getRenderTarget();
2628 }
2629
2630 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2631
2632 return renderTarget;
2633}
2634
2635RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2636{
2637 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2638 return renderTarget;
2639}
2640
daniel@transgaming.com55318902012-11-28 20:58:58 +00002641ShaderExecutable *Renderer9::loadExecutable(const DWORD *function, size_t length, GLenum type, void *data)
2642{
2643 ShaderExecutable9 *executable = NULL;
2644 gl::D3DConstantTable *table = reinterpret_cast<gl::D3DConstantTable *>(data);
2645
2646 switch (type)
2647 {
2648 case GL_VERTEX_SHADER:
2649 {
2650 IDirect3DVertexShader9 *vshader = createVertexShader(function, length);
2651 if (vshader)
2652 {
2653 executable = new ShaderExecutable9(vshader, table);
2654 }
2655 }
2656 break;
2657 case GL_FRAGMENT_SHADER:
2658 {
2659 IDirect3DPixelShader9 *pshader = createPixelShader(function, length);
2660 if (pshader)
2661 {
2662 executable = new ShaderExecutable9(pshader, table);
2663 }
2664 }
2665 break;
2666 default:
2667 UNREACHABLE();
2668 break;
2669 }
2670
2671 return executable;
2672}
2673
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002674ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2675{
2676 const char *profile = NULL;
2677
2678 switch (type)
2679 {
2680 case GL_VERTEX_SHADER:
2681 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2682 break;
2683 case GL_FRAGMENT_SHADER:
2684 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2685 break;
2686 default:
2687 UNREACHABLE();
2688 return NULL;
2689 }
2690
2691 gl::D3DConstantTable *constantTable = NULL;
2692 ID3D10Blob *binary = compileToBinary(infoLog, shaderHLSL, profile, &constantTable);
2693 if (!binary)
2694 return NULL;
2695
daniel@transgaming.com55318902012-11-28 20:58:58 +00002696 ShaderExecutable *executable = loadExecutable((DWORD *)binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002697
2698 return executable;
2699}
2700
2701// Compiles the HLSL code of the attached shaders into executable binaries
2702ID3D10Blob *Renderer9::compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, gl::D3DConstantTable **constantTable)
2703{
2704 if (!hlsl)
2705 {
2706 return NULL;
2707 }
2708
2709 HRESULT result = S_OK;
2710 UINT flags = 0;
2711 std::string sourceText;
2712 if (gl::perfActive())
2713 {
2714 flags |= D3DCOMPILE_DEBUG;
2715#ifdef NDEBUG
2716 flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2717#else
2718 flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
2719#endif
2720
2721 std::string sourcePath = getTempPath();
2722 sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl);
2723 writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
2724 }
2725 else
2726 {
2727 flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2728 sourceText = hlsl;
2729 }
2730
2731 // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders when it would otherwise pass with alternative options.
2732 // Try the default flags first and if compilation fails, try some alternatives.
2733 const static UINT extraFlags[] =
2734 {
2735 0,
2736 D3DCOMPILE_AVOID_FLOW_CONTROL,
2737 D3DCOMPILE_PREFER_FLOW_CONTROL
2738 };
2739
2740 const static char * const extraFlagNames[] =
2741 {
2742 "default",
2743 "avoid flow control",
2744 "prefer flow control"
2745 };
2746
2747 for (int i = 0; i < sizeof(extraFlags) / sizeof(UINT); ++i)
2748 {
2749 ID3D10Blob *errorMessage = NULL;
2750 ID3D10Blob *binary = NULL;
2751 result = compileShaderSource(hlsl, gl::g_fakepath, profile, flags | extraFlags[i], &binary, &errorMessage);
2752
2753 if (errorMessage)
2754 {
2755 const char *message = (const char*)errorMessage->GetBufferPointer();
2756
2757 infoLog.appendSanitized(message);
2758 TRACE("\n%s", hlsl);
2759 TRACE("\n%s", message);
2760
2761 errorMessage->Release();
2762 errorMessage = NULL;
2763 }
2764
2765 if (SUCCEEDED(result))
2766 {
2767 gl::D3DConstantTable *table = new gl::D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
2768 if (table->error())
2769 {
2770 delete table;
2771 binary->Release();
2772 return NULL;
2773 }
2774
2775 *constantTable = table;
2776 return binary;
2777 }
2778 else
2779 {
2780 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
2781 {
2782 return error(GL_OUT_OF_MEMORY, (ID3D10Blob*) NULL);
2783 }
2784
2785 infoLog.append("Warning: D3D shader compilation failed with ");
2786 infoLog.append(extraFlagNames[i]);
2787 infoLog.append(" flags.");
2788 if (i + 1 < sizeof(extraFlagNames) / sizeof(char*))
2789 {
2790 infoLog.append(" Retrying with ");
2791 infoLog.append(extraFlagNames[i + 1]);
2792 infoLog.append(".\n");
2793 }
2794 }
2795 }
2796
2797 return NULL;
2798}
2799
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002800bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2801{
2802 return mBlit->boxFilter(source, dest);
2803}
2804
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002805D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002806{
2807 if (mD3d9Ex != NULL)
2808 {
2809 return D3DPOOL_DEFAULT;
2810 }
2811 else
2812 {
2813 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2814 {
2815 return D3DPOOL_MANAGED;
2816 }
2817 }
2818
2819 return D3DPOOL_DEFAULT;
2820}
2821
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002822bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2823{
2824 if (source && dest)
2825 {
2826 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2827 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2828
2829 if (fromManaged)
2830 {
2831 D3DSURFACE_DESC desc;
2832 source->GetDesc(&desc);
2833
2834 IDirect3DSurface9 *surf = 0;
2835 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2836
2837 if (SUCCEEDED(result))
2838 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002839 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002840 result = device->UpdateSurface(surf, NULL, dest, NULL);
2841 surf->Release();
2842 }
2843 }
2844 else
2845 {
2846 endScene();
2847 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2848 }
2849
2850 if (FAILED(result))
2851 {
2852 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2853 return false;
2854 }
2855 }
2856
2857 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002858}
2859
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002860}