blob: 176b0ecf935da3398323ce3362cb2c7474201c2b [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.coma27e05b2012-11-28 19:39:42 +000021#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +000022#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000023#include "libGLESv2/renderer/Image.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000024#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000025#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000026
daniel@transgaming.com3281f972012-10-31 18:38:51 +000027#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000028#include "libEGL/Display.h"
29
daniel@transgaming.com621ce052012-10-31 17:52:29 +000030// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
31#define REF_RAST 0
32
33// The "Debug This Pixel..." feature in PIX often fails when using the
34// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
35// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
36#if !defined(ANGLE_ENABLE_D3D9EX)
37// Enables use of the IDirect3D9Ex interface, when available
38#define ANGLE_ENABLE_D3D9EX 1
39#endif // !defined(ANGLE_ENABLE_D3D9EX)
40
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000041namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000042{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000043static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000044 {
45 D3DFMT_A1R5G5B5,
46 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
47 D3DFMT_A8R8G8B8,
48 D3DFMT_R5G6B5,
49 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
50 D3DFMT_X8R8G8B8
51 };
52
daniel@transgaming.com222ee082012-11-28 19:31:49 +000053static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000054 {
55 D3DFMT_UNKNOWN,
56 // D3DFMT_D16_LOCKABLE,
57 D3DFMT_D32,
58 // D3DFMT_D15S1,
59 D3DFMT_D24S8,
60 D3DFMT_D24X8,
61 // D3DFMT_D24X4S4,
62 D3DFMT_D16,
63 // D3DFMT_D32F_LOCKABLE,
64 // D3DFMT_D24FS8
65 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000066
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000067Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000068{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000069 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000070
daniel@transgaming.com7d738a22012-11-28 19:43:08 +000071 mD3dCompilerModule = NULL;
72
daniel@transgaming.com621ce052012-10-31 17:52:29 +000073 mD3d9 = NULL;
74 mD3d9Ex = NULL;
75 mDevice = NULL;
76 mDeviceEx = NULL;
77 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000078 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000079
80 mAdapter = D3DADAPTER_DEFAULT;
81
82 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
83 mDeviceType = D3DDEVTYPE_REF;
84 #else
85 mDeviceType = D3DDEVTYPE_HAL;
86 #endif
87
88 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000089
90 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000091
daniel@transgaming.com91207b72012-11-28 20:56:43 +000092 mAppliedIBSerial = 0;
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000093
94 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +000095
96 mVertexDataManager = NULL;
97 mIndexDataManager = NULL;
98 mLineLoopIB = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000099}
100
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000101Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000102{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000103 releaseDeviceResources();
104
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000105 if (mDevice)
106 {
107 // 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 +0000108 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000109 {
110 resetDevice();
111 }
112
113 mDevice->Release();
114 mDevice = NULL;
115 }
116
117 if (mDeviceEx)
118 {
119 mDeviceEx->Release();
120 mDeviceEx = NULL;
121 }
122
123 if (mD3d9)
124 {
125 mD3d9->Release();
126 mD3d9 = NULL;
127 }
128
129 if (mDeviceWindow)
130 {
131 DestroyWindow(mDeviceWindow);
132 mDeviceWindow = NULL;
133 }
134
135 if (mD3d9Ex)
136 {
137 mD3d9Ex->Release();
138 mD3d9Ex = NULL;
139 }
140
141 if (mD3d9Module)
142 {
143 mD3d9Module = NULL;
144 }
145
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000146 if (mD3dCompilerModule)
147 {
148 FreeLibrary(mD3dCompilerModule);
149 mD3dCompilerModule = NULL;
150 }
151
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000152 while (!mMultiSampleSupport.empty())
153 {
154 delete [] mMultiSampleSupport.begin()->second;
155 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
156 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000157}
158
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000159Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
160{
161 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
162 return static_cast<rx::Renderer9*>(renderer);
163}
164
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000165EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000166{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000167 if (mSoftwareDevice)
168 {
169 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
170 }
171 else
172 {
173 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
174 }
175
176 if (mD3d9Module == NULL)
177 {
178 ERR("No D3D9 module found - aborting!\n");
179 return EGL_NOT_INITIALIZED;
180 }
181
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000182 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
183 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
184
185 // Use Direct3D9Ex if available. Among other things, this version is less
186 // inclined to report a lost context, for example when the user switches
187 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
188 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
189 {
190 ASSERT(mD3d9Ex);
191 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
192 ASSERT(mD3d9);
193 }
194 else
195 {
196 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
197 }
198
199 if (!mD3d9)
200 {
201 ERR("Could not create D3D9 device - aborting!\n");
202 return EGL_NOT_INITIALIZED;
203 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000204
205#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
206 // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
207 static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
208
209 for (int i = 0; i < sizeof(d3dCompilerNames) / sizeof(*d3dCompilerNames); ++i)
210 {
211 if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
212 {
213 break;
214 }
215 }
216#else
217 // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
218 mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
219#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
220
221 if (!mD3dCompilerModule)
222 {
223 terminate();
224 return false;
225 }
226
227 mD3DCompileFunc = reinterpret_cast<D3DCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
228 ASSERT(mD3DCompileFunc);
229
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000230 if (mDc != NULL)
231 {
232 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
233 }
234
235 HRESULT result;
236
237 // Give up on getting device caps after about one second.
238 for (int i = 0; i < 10; ++i)
239 {
240 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
241 if (SUCCEEDED(result))
242 {
243 break;
244 }
245 else if (result == D3DERR_NOTAVAILABLE)
246 {
247 Sleep(100); // Give the driver some time to initialize/recover
248 }
249 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
250 {
251 ERR("failed to get device caps (0x%x)\n", result);
252 return EGL_NOT_INITIALIZED;
253 }
254 }
255
256 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
257 {
258 ERR("Renderer does not support PS 2.0. aborting!\n");
259 return EGL_NOT_INITIALIZED;
260 }
261
262 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
263 // This is required by Texture2D::convertToRenderTarget.
264 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
265 {
266 ERR("Renderer does not support stretctrect from textures!\n");
267 return EGL_NOT_INITIALIZED;
268 }
269
270 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
271
272 // ATI cards on XP have problems with non-power-of-two textures.
273 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
274 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
275 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
276 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
277
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000278 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
279 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
280
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000281 mMinSwapInterval = 4;
282 mMaxSwapInterval = 0;
283
284 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
285 {
286 mMinSwapInterval = std::min(mMinSwapInterval, 0);
287 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
288 }
289 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
290 {
291 mMinSwapInterval = std::min(mMinSwapInterval, 1);
292 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
293 }
294 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
295 {
296 mMinSwapInterval = std::min(mMinSwapInterval, 2);
297 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
298 }
299 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
300 {
301 mMinSwapInterval = std::min(mMinSwapInterval, 3);
302 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
303 }
304 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
305 {
306 mMinSwapInterval = std::min(mMinSwapInterval, 4);
307 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
308 }
309
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000310 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000311 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000312 {
313 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000314 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
315 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000316
317 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
318 {
319 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
320 {
321 max = j;
322 }
323 }
324 }
325
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000326 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000327 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000328 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000329 continue;
330
331 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000332 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
333 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000334
335 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
336 {
337 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
338 {
339 max = j;
340 }
341 }
342 }
343
344 mMaxSupportedSamples = max;
345
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000346 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
347 static const TCHAR className[] = TEXT("STATIC");
348
349 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
350
351 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
352 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
353
354 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
355 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
356 {
357 return EGL_BAD_ALLOC;
358 }
359
360 if (FAILED(result))
361 {
362 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
363
364 if (FAILED(result))
365 {
366 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
367 return EGL_BAD_ALLOC;
368 }
369 }
370
371 if (mD3d9Ex)
372 {
373 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
374 ASSERT(SUCCEEDED(result));
375 }
376
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000377 mVertexShaderCache.initialize(mDevice);
378 mPixelShaderCache.initialize(mDevice);
379
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000380 initializeDevice();
381
382 return EGL_SUCCESS;
383}
384
385// do any one-time device initialization
386// NOTE: this is also needed after a device lost/reset
387// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000388void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000389{
390 // Permanent non-default states
391 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
392 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
393
394 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
395 {
396 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
397 }
398 else
399 {
400 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
401 }
402
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000403 markAllStateDirty();
404
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000405 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000406
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000407 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000408 mBlit = new Blit(this);
409 mVertexDataManager = new gl::VertexDataManager(this);
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000410 mIndexDataManager = new gl::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000411}
412
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000413D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000414{
415 D3DPRESENT_PARAMETERS presentParameters = {0};
416
417 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
418 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
419 presentParameters.BackBufferCount = 1;
420 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
421 presentParameters.BackBufferWidth = 1;
422 presentParameters.BackBufferHeight = 1;
423 presentParameters.EnableAutoDepthStencil = FALSE;
424 presentParameters.Flags = 0;
425 presentParameters.hDeviceWindow = mDeviceWindow;
426 presentParameters.MultiSampleQuality = 0;
427 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
428 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
429 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
430 presentParameters.Windowed = TRUE;
431
432 return presentParameters;
433}
434
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000435int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000436{
437 D3DDISPLAYMODE currentDisplayMode;
438 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
439
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000440 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
441 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000442 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
443 int numConfigs = 0;
444
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000445 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000446 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000447 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000448
449 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
450
451 if (SUCCEEDED(result))
452 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000453 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000454 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000455 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000456 HRESULT result = D3D_OK;
457
458 if(depthStencilFormat != D3DFMT_UNKNOWN)
459 {
460 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
461 }
462
463 if (SUCCEEDED(result))
464 {
465 if(depthStencilFormat != D3DFMT_UNKNOWN)
466 {
467 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
468 }
469
470 if (SUCCEEDED(result))
471 {
472 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000473 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
474 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000475 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
476 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
477
478 (*configDescList)[numConfigs++] = newConfig;
479 }
480 }
481 }
482 }
483 }
484
485 return numConfigs;
486}
487
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000488void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000489{
490 delete [] (configDescList);
491}
492
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000493void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000494{
495 if (!mSceneStarted)
496 {
497 long result = mDevice->BeginScene();
498 if (SUCCEEDED(result)) {
499 // This is defensive checking against the device being
500 // lost at unexpected times.
501 mSceneStarted = true;
502 }
503 }
504}
505
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000506void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000507{
508 if (mSceneStarted)
509 {
510 // EndScene can fail if the device was lost, for example due
511 // to a TDR during a draw call.
512 mDevice->EndScene();
513 mSceneStarted = false;
514 }
515}
516
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000517// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000518void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000519{
520 HRESULT result;
521
522 IDirect3DQuery9* query = allocateEventQuery();
523 if (!query)
524 {
525 return;
526 }
527
528 result = query->Issue(D3DISSUE_END);
529 ASSERT(SUCCEEDED(result));
530
531 do
532 {
533 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
534
535 if(block && result == S_FALSE)
536 {
537 // Keep polling, but allow other threads to do something useful first
538 Sleep(0);
539 // explicitly check for device loss
540 // some drivers seem to return S_FALSE even if the device is lost
541 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000542 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000543 {
544 result = D3DERR_DEVICELOST;
545 }
546 }
547 }
548 while(block && result == S_FALSE);
549
550 freeEventQuery(query);
551
552 if (isDeviceLostError(result))
553 {
554 mDisplay->notifyDeviceLost();
555 }
556}
557
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000558SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
559{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000560 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000561}
562
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000563// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000564IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000565{
566 IDirect3DQuery9 *query = NULL;
567
568 if (mEventQueryPool.empty())
569 {
570 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
571 ASSERT(SUCCEEDED(result));
572 }
573 else
574 {
575 query = mEventQueryPool.back();
576 mEventQueryPool.pop_back();
577 }
578
579 return query;
580}
581
582// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000583void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000584{
585 if (mEventQueryPool.size() > 1000)
586 {
587 query->Release();
588 }
589 else
590 {
591 mEventQueryPool.push_back(query);
592 }
593}
594
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000595
596HRESULT Renderer9::compileShaderSource(const char* hlsl, const char* sourceName, const char* profile, DWORD flags, ID3DBlob** binary, ID3DBlob** errorMessage)
597{
598 return mD3DCompileFunc(hlsl, strlen(hlsl), sourceName, NULL, NULL, "main", profile, flags, 0, binary, errorMessage);
599}
600
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000601IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000602{
603 return mVertexShaderCache.create(function, length);
604}
605
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000606IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000607{
608 return mPixelShaderCache.create(function, length);
609}
610
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000611HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
612{
613 D3DPOOL Pool = getBufferPool(Usage);
614 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
615}
616
617HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
618{
619 D3DPOOL Pool = getBufferPool(Usage);
620 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
621}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000622
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000623void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000624{
625 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
626 int d3dSampler = index + d3dSamplerOffset;
627
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000628 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
629 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000630
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000631 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000632 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000633 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000634 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
635 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
636 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
637 if (mSupportsTextureFilterAnisotropy)
638 {
639 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
640 }
641}
642
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000643void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000644{
645 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
646 int d3dSampler = index + d3dSamplerOffset;
647 IDirect3DBaseTexture9 *d3dTexture = NULL;
648
649 if (texture)
650 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000651 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000652 if (texStorage)
653 {
654 d3dTexture = texStorage->getBaseTexture();
655 }
656 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000657 // in the texture class and we're unexpectedly missing the d3d texture
658 ASSERT(d3dTexture != NULL);
659 }
660
661 mDevice->SetTexture(d3dSampler, d3dTexture);
662}
663
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000664void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
665{
666 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
667 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
668
669 if (rasterStateChanged)
670 {
671 // Set the cull mode
672 if (rasterState.cullFace)
673 {
674 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
675 }
676 else
677 {
678 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
679 }
680
681 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
682
683 mCurRasterState = rasterState;
684 }
685
686 if (rasterStateChanged || depthSizeChanged)
687 {
688 if (rasterState.polygonOffsetFill)
689 {
690 if (depthSize > 0)
691 {
692 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
693
694 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
695 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
696 }
697 }
698 else
699 {
700 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
701 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
702 }
703
704 mCurDepthSize = depthSize;
705 }
706
707 mForceSetRasterState = false;
708}
709
710void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
711{
712 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
713 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
714 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
715
716 if (blendStateChanged || blendColorChanged)
717 {
718 if (blendState.blend)
719 {
720 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
721
722 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
723 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
724 {
725 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
726 }
727 else
728 {
729 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
730 gl::unorm<8>(blendColor.alpha),
731 gl::unorm<8>(blendColor.alpha),
732 gl::unorm<8>(blendColor.alpha)));
733 }
734
735 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
736 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
737 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
738
739 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
740 blendState.destBlendRGB != blendState.destBlendAlpha ||
741 blendState.blendEquationRGB != blendState.blendEquationAlpha)
742 {
743 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
744
745 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
746 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
747 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
748 }
749 else
750 {
751 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
752 }
753 }
754 else
755 {
756 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
757 }
758
759 if (blendState.sampleAlphaToCoverage)
760 {
761 FIXME("Sample alpha to coverage is unimplemented.");
762 }
763
764 // Set the color mask
765 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
766 // Apparently some ATI cards have a bug where a draw with a zero color
767 // write mask can cause later draws to have incorrect results. Instead,
768 // set a nonzero color write mask but modify the blend state so that no
769 // drawing is done.
770 // http://code.google.com/p/angleproject/issues/detail?id=169
771
772 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
773 blendState.colorMaskBlue, blendState.colorMaskAlpha);
774 if (colorMask == 0 && !zeroColorMaskAllowed)
775 {
776 // Enable green channel, but set blending so nothing will be drawn.
777 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
778 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
779
780 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
781 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
782 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
783 }
784 else
785 {
786 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
787 }
788
789 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
790
791 mCurBlendState = blendState;
792 mCurBlendColor = blendColor;
793 }
794
795 if (sampleMaskChanged)
796 {
797 // Set the multisample mask
798 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
799 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
800
801 mCurSampleMask = sampleMask;
802 }
803
804 mForceSetBlendState = false;
805}
806
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000807void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
808 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000809{
810 bool depthStencilStateChanged = mForceSetDepthStencilState ||
811 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000812 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
813 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000814 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
815 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
816
817 if (depthStencilStateChanged)
818 {
819 if (depthStencilState.depthTest)
820 {
821 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
822 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
823 }
824 else
825 {
826 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
827 }
828
829 mCurDepthStencilState = depthStencilState;
830 }
831
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000832 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000833 {
834 if (depthStencilState.stencilTest && stencilSize > 0)
835 {
836 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
837 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
838
839 // FIXME: Unsupported by D3D9
840 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
841 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
842 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
843 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000844 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000845 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
846 {
847 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
848 return error(GL_INVALID_OPERATION);
849 }
850
851 // get the maximum size of the stencil ref
852 GLuint maxStencil = (1 << stencilSize) - 1;
853
854 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
855 depthStencilState.stencilWritemask);
856 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
857 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
858
859 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000860 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000861 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
862 depthStencilState.stencilMask);
863
864 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
865 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
866 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
867 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
868 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
869 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
870
871 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
872 depthStencilState.stencilBackWritemask);
873 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
874 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
875
876 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000877 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000878 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
879 depthStencilState.stencilBackMask);
880
881 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
882 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
883 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
884 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
885 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
886 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
887 }
888 else
889 {
890 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
891 }
892
893 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
894
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000895 mCurStencilRef = stencilRef;
896 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000897 mCurFrontFaceCCW = frontFaceCCW;
898 mCurStencilSize = stencilSize;
899 }
900
901 mForceSetDepthStencilState = false;
902}
903
904void Renderer9::setScissorRectangle(const gl::Rectangle& scissor, unsigned int renderTargetWidth,
905 unsigned int renderTargetHeight)
906{
907 bool renderTargetSizedChanged = mForceSetScissor ||
908 renderTargetWidth != mCurRenderTargetWidth ||
909 renderTargetHeight != mCurRenderTargetHeight;
910 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
911
912 if (renderTargetSizedChanged || scissorChanged)
913 {
914 RECT rect;
915 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000916 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000917 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000918 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000919 mDevice->SetScissorRect(&rect);
920
921 mCurScissor = scissor;
922 mCurRenderTargetWidth = renderTargetWidth;
923 mCurRenderTargetHeight = renderTargetHeight;
924 }
925
926 mForceSetScissor = false;
927}
928
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000929bool Renderer9::setViewport(const gl::Rectangle& viewport, float zNear, float zFar,
930 unsigned int renderTargetWidth, unsigned int renderTargetHeight,
931 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
932{
933 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
934 zNear != mCurNear || zFar != mCurFar;
935
936 D3DVIEWPORT9 dxViewport;
937 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(renderTargetWidth));
938 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(renderTargetHeight));
939 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(renderTargetWidth) - static_cast<int>(dxViewport.X));
940 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(renderTargetHeight) - static_cast<int>(dxViewport.Y));
941 dxViewport.MinZ = zNear;
942 dxViewport.MaxZ = zFar;
943
944 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
945 {
946 return false; // Nothing to render
947 }
948
949 if (viewportChanged)
950 {
951 mDevice->SetViewport(&dxViewport);
952
953 mCurViewport = viewport;
954 mCurNear = zNear;
955 mCurFar = zFar;
956 }
957
958 if (currentProgram && (viewportChanged || forceSetUniforms))
959 {
960 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
961 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
962 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
963
964 // These values are used for computing gl_FragCoord in Program::linkVaryings().
965 GLint coord = currentProgram->getDxCoordLocation();
966 GLfloat whxy[4] = { viewport.width * 0.5f,
967 viewport.height * 0.5f,
968 viewport.x + (viewport.width * 0.5f),
969 viewport.y + (viewport.height * 0.5f) };
970 currentProgram->setUniform4fv(coord, 1, whxy);
971
972 GLint depth = currentProgram->getDxDepthLocation();
973 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
974 currentProgram->setUniform2fv(depth, 1, dz);
975
976 GLint depthRange = currentProgram->getDxDepthRangeLocation();
977 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
978 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
979 }
980
981 mForceSetViewport = false;
982 return true;
983}
984
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000985bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
986{
987 switch (mode)
988 {
989 case GL_POINTS:
990 mPrimitiveType = D3DPT_POINTLIST;
991 mPrimitiveCount = count;
992 break;
993 case GL_LINES:
994 mPrimitiveType = D3DPT_LINELIST;
995 mPrimitiveCount = count / 2;
996 break;
997 case GL_LINE_LOOP:
998 mPrimitiveType = D3DPT_LINESTRIP;
999 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
1000 break;
1001 case GL_LINE_STRIP:
1002 mPrimitiveType = D3DPT_LINESTRIP;
1003 mPrimitiveCount = count - 1;
1004 break;
1005 case GL_TRIANGLES:
1006 mPrimitiveType = D3DPT_TRIANGLELIST;
1007 mPrimitiveCount = count / 3;
1008 break;
1009 case GL_TRIANGLE_STRIP:
1010 mPrimitiveType = D3DPT_TRIANGLESTRIP;
1011 mPrimitiveCount = count - 2;
1012 break;
1013 case GL_TRIANGLE_FAN:
1014 mPrimitiveType = D3DPT_TRIANGLEFAN;
1015 mPrimitiveCount = count - 2;
1016 break;
1017 default:
1018 return error(GL_INVALID_ENUM, false);
1019 }
1020
1021 return mPrimitiveCount > 0;
1022}
1023
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001024bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001025{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001026 // if there is no color attachment we must synthesize a NULL colorattachment
1027 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1028 gl::Renderbuffer *renderbufferObject = NULL;
1029 if (framebuffer->getColorbufferType() != GL_NONE)
1030 {
1031 renderbufferObject = framebuffer->getColorbuffer();
1032 }
1033 else
1034 {
1035 renderbufferObject = framebuffer->getNullColorbuffer();
1036 }
1037 if (!renderbufferObject)
1038 {
1039 ERR("unable to locate renderbuffer for FBO.");
1040 return false;
1041 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001042
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001043 bool renderTargetChanged = false;
1044 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1045 if (renderTargetSerial != mAppliedRenderTargetSerial)
1046 {
1047 // Apply the render target on the device
1048 IDirect3DSurface9 *renderTargetSurface = NULL;
1049
1050 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1051 if (renderTarget)
1052 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001053 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001054 }
1055
1056 if (!renderTargetSurface)
1057 {
1058 ERR("render target pointer unexpectedly null.");
1059 return false; // Context must be lost
1060 }
1061
1062 mDevice->SetRenderTarget(0, renderTargetSurface);
1063 renderTargetSurface->Release();
1064
1065 mAppliedRenderTargetSerial = renderTargetSerial;
1066 renderTargetChanged = true;
1067 }
1068
1069 gl::Renderbuffer *depthStencil = NULL;
1070 unsigned int depthbufferSerial = 0;
1071 unsigned int stencilbufferSerial = 0;
1072 if (framebuffer->getDepthbufferType() != GL_NONE)
1073 {
1074 depthStencil = framebuffer->getDepthbuffer();
1075 if (!depthStencil)
1076 {
1077 ERR("Depth stencil pointer unexpectedly null.");
1078 return false;
1079 }
1080
1081 depthbufferSerial = depthStencil->getSerial();
1082 }
1083 else if (framebuffer->getStencilbufferType() != GL_NONE)
1084 {
1085 depthStencil = framebuffer->getStencilbuffer();
1086 if (!depthStencil)
1087 {
1088 ERR("Depth stencil pointer unexpectedly null.");
1089 return false;
1090 }
1091
1092 stencilbufferSerial = depthStencil->getSerial();
1093 }
1094
1095 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1096 stencilbufferSerial != mAppliedStencilbufferSerial ||
1097 !mDepthStencilInitialized)
1098 {
1099 // Apply the depth stencil on the device
1100 if (depthStencil)
1101 {
1102 IDirect3DSurface9 *depthStencilSurface = NULL;
1103 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1104
1105 if (depthStencilRenderTarget)
1106 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001107 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001108 }
1109
1110 if (!depthStencilSurface)
1111 {
1112 ERR("depth stencil pointer unexpectedly null.");
1113 return false; // Context must be lost
1114 }
1115
1116 mDevice->SetDepthStencilSurface(depthStencilSurface);
1117 depthStencilSurface->Release();
1118 }
1119 else
1120 {
1121 mDevice->SetDepthStencilSurface(NULL);
1122 }
1123
1124 mAppliedDepthbufferSerial = depthbufferSerial;
1125 mAppliedStencilbufferSerial = stencilbufferSerial;
1126 mDepthStencilInitialized = true;
1127 }
1128
1129 if (renderTargetChanged || !mRenderTargetDescInitialized)
1130 {
1131 mForceSetScissor = true;
1132 mForceSetViewport = true;
1133
1134 mRenderTargetDesc.width = renderbufferObject->getWidth();
1135 mRenderTargetDesc.height = renderbufferObject->getHeight();
1136 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1137 mRenderTargetDescInitialized = true;
1138 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001139
1140 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001141}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001142
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001143GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001144{
1145 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1146 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1147 if (err != GL_NO_ERROR)
1148 {
1149 return err;
1150 }
1151
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001152 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1153}
1154
1155// Applies the indices and element array bindings to the Direct3D 9 device
1156GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, gl::TranslatedIndexData *indexInfo)
1157{
1158 IDirect3DIndexBuffer9 *indexBuffer;
1159 unsigned int serial;
1160 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1161
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001162 if (err == GL_NO_ERROR)
1163 {
1164 if (serial != mAppliedIBSerial)
1165 {
1166 mDevice->SetIndices(indexBuffer);
1167 mAppliedIBSerial = serial;
1168 }
1169 }
1170
1171 return err;
1172}
1173
1174void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1175{
1176 startScene();
1177
1178 if (mode == GL_LINE_LOOP)
1179 {
1180 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1181 }
1182 else if (instances > 0)
1183 {
1184 gl::StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
1185 if (countingIB)
1186 {
1187 if (mAppliedIBSerial != countingIB->getSerial())
1188 {
1189 mDevice->SetIndices(countingIB->getBuffer());
1190 mAppliedIBSerial = countingIB->getSerial();
1191 }
1192
1193 for (int i = 0; i < mRepeatDraw; i++)
1194 {
1195 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1196 }
1197 }
1198 else
1199 {
1200 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1201 return error(GL_OUT_OF_MEMORY);
1202 }
1203 }
1204 else // Regular case
1205 {
1206 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1207 }
1208}
1209
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001210void 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 +00001211{
1212 startScene();
1213
1214 if (mode == GL_LINE_LOOP)
1215 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001216 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001217 }
1218 else
1219 {
1220 for (int i = 0; i < mRepeatDraw; i++)
1221 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001222 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1223 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001224 }
1225 }
1226}
1227
1228void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1229{
1230 // Get the raw indices for an indexed draw
1231 if (type != GL_NONE && elementArrayBuffer)
1232 {
1233 gl::Buffer *indexBuffer = elementArrayBuffer;
1234 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1235 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1236 }
1237
1238 UINT startIndex = 0;
1239 bool succeeded = false;
1240
1241 if (get32BitIndexSupport())
1242 {
1243 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1244
1245 if (!mLineLoopIB)
1246 {
1247 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
1248 }
1249
1250 if (mLineLoopIB)
1251 {
1252 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1253
1254 UINT offset = 0;
1255 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1256 startIndex = offset / 4;
1257
1258 if (data)
1259 {
1260 switch (type)
1261 {
1262 case GL_NONE: // Non-indexed draw
1263 for (int i = 0; i < count; i++)
1264 {
1265 data[i] = i;
1266 }
1267 data[count] = 0;
1268 break;
1269 case GL_UNSIGNED_BYTE:
1270 for (int i = 0; i < count; i++)
1271 {
1272 data[i] = static_cast<const GLubyte*>(indices)[i];
1273 }
1274 data[count] = static_cast<const GLubyte*>(indices)[0];
1275 break;
1276 case GL_UNSIGNED_SHORT:
1277 for (int i = 0; i < count; i++)
1278 {
1279 data[i] = static_cast<const GLushort*>(indices)[i];
1280 }
1281 data[count] = static_cast<const GLushort*>(indices)[0];
1282 break;
1283 case GL_UNSIGNED_INT:
1284 for (int i = 0; i < count; i++)
1285 {
1286 data[i] = static_cast<const GLuint*>(indices)[i];
1287 }
1288 data[count] = static_cast<const GLuint*>(indices)[0];
1289 break;
1290 default: UNREACHABLE();
1291 }
1292
1293 mLineLoopIB->unmap();
1294 succeeded = true;
1295 }
1296 }
1297 }
1298 else
1299 {
1300 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1301
1302 if (!mLineLoopIB)
1303 {
1304 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
1305 }
1306
1307 if (mLineLoopIB)
1308 {
1309 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1310
1311 UINT offset = 0;
1312 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1313 startIndex = offset / 2;
1314
1315 if (data)
1316 {
1317 switch (type)
1318 {
1319 case GL_NONE: // Non-indexed draw
1320 for (int i = 0; i < count; i++)
1321 {
1322 data[i] = i;
1323 }
1324 data[count] = 0;
1325 break;
1326 case GL_UNSIGNED_BYTE:
1327 for (int i = 0; i < count; i++)
1328 {
1329 data[i] = static_cast<const GLubyte*>(indices)[i];
1330 }
1331 data[count] = static_cast<const GLubyte*>(indices)[0];
1332 break;
1333 case GL_UNSIGNED_SHORT:
1334 for (int i = 0; i < count; i++)
1335 {
1336 data[i] = static_cast<const GLushort*>(indices)[i];
1337 }
1338 data[count] = static_cast<const GLushort*>(indices)[0];
1339 break;
1340 case GL_UNSIGNED_INT:
1341 for (int i = 0; i < count; i++)
1342 {
1343 data[i] = static_cast<const GLuint*>(indices)[i];
1344 }
1345 data[count] = static_cast<const GLuint*>(indices)[0];
1346 break;
1347 default: UNREACHABLE();
1348 }
1349
1350 mLineLoopIB->unmap();
1351 succeeded = true;
1352 }
1353 }
1354 }
1355
1356 if (succeeded)
1357 {
1358 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1359 {
1360 mDevice->SetIndices(mLineLoopIB->getBuffer());
1361 mAppliedIBSerial = mLineLoopIB->getSerial();
1362 }
1363
1364 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1365 }
1366 else
1367 {
1368 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1369 return error(GL_OUT_OF_MEMORY);
1370 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001371}
1372
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001373void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1374{
1375 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
1376 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
1377
1378 mDevice->SetPixelShader(pixelShader);
1379 mDevice->SetVertexShader(vertexShader);
1380 programBinary->dirtyAllUniforms();
1381}
1382
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001383void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001384{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001385 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1386 gl::unorm<8>(clearParams.colorClearValue.red),
1387 gl::unorm<8>(clearParams.colorClearValue.green),
1388 gl::unorm<8>(clearParams.colorClearValue.blue));
1389 float depth = gl::clamp01(clearParams.depthClearValue);
1390 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001391
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001392 unsigned int stencilUnmasked = 0x0;
1393 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1394 {
1395 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1396 stencilUnmasked = (0x1 << stencilSize) - 1;
1397 }
1398
1399 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1400
1401 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1402 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1403 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1404 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1405 clearParams.colorMaskBlue && alphaUnmasked);
1406
1407 if (needMaskedColorClear || needMaskedStencilClear)
1408 {
1409 // State which is altered in all paths from this point to the clear call is saved.
1410 // State which is altered in only some paths will be flagged dirty in the case that
1411 // that path is taken.
1412 HRESULT hr;
1413 if (mMaskedClearSavedState == NULL)
1414 {
1415 hr = mDevice->BeginStateBlock();
1416 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1417
1418 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1419 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1420 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1421 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1422 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1423 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1424 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1425 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1426 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1427 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1428 mDevice->SetPixelShader(NULL);
1429 mDevice->SetVertexShader(NULL);
1430 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1431 mDevice->SetStreamSource(0, NULL, 0, 0);
1432 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1433 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1434 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1435 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1436 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1437 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1438 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1439
1440 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1441 {
1442 mDevice->SetStreamSourceFreq(i, 1);
1443 }
1444
1445 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1446 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1447 }
1448
1449 ASSERT(mMaskedClearSavedState != NULL);
1450
1451 if (mMaskedClearSavedState != NULL)
1452 {
1453 hr = mMaskedClearSavedState->Capture();
1454 ASSERT(SUCCEEDED(hr));
1455 }
1456
1457 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1458 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1459 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1460 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1461 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1462 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1463 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1464 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1465
1466 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1467 {
1468 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1469 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1470 clearParams.colorMaskGreen,
1471 clearParams.colorMaskBlue,
1472 clearParams.colorMaskAlpha));
1473 }
1474 else
1475 {
1476 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1477 }
1478
1479 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1480 {
1481 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1482 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1483 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1484 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1485 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1486 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1487 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1488 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1489 }
1490 else
1491 {
1492 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1493 }
1494
1495 mDevice->SetPixelShader(NULL);
1496 mDevice->SetVertexShader(NULL);
1497 mDevice->SetFVF(D3DFVF_XYZRHW);
1498 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1499 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1500 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1501 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1502 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1503 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1504 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1505
1506 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1507 {
1508 mDevice->SetStreamSourceFreq(i, 1);
1509 }
1510
1511 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1512 quad[0][0] = -0.5f;
1513 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1514 quad[0][2] = 0.0f;
1515 quad[0][3] = 1.0f;
1516
1517 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1518 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1519 quad[1][2] = 0.0f;
1520 quad[1][3] = 1.0f;
1521
1522 quad[2][0] = -0.5f;
1523 quad[2][1] = -0.5f;
1524 quad[2][2] = 0.0f;
1525 quad[2][3] = 1.0f;
1526
1527 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1528 quad[3][1] = -0.5f;
1529 quad[3][2] = 0.0f;
1530 quad[3][3] = 1.0f;
1531
1532 startScene();
1533 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1534
1535 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1536 {
1537 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1538 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1539 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1540 }
1541
1542 if (mMaskedClearSavedState != NULL)
1543 {
1544 mMaskedClearSavedState->Apply();
1545 }
1546 }
1547 else if (clearParams.mask)
1548 {
1549 DWORD dxClearFlags = 0;
1550 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1551 {
1552 dxClearFlags |= D3DCLEAR_TARGET;
1553 }
1554 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1555 {
1556 dxClearFlags |= D3DCLEAR_ZBUFFER;
1557 }
1558 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1559 {
1560 dxClearFlags |= D3DCLEAR_STENCIL;
1561 }
1562
1563 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1564 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001565}
1566
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001567void Renderer9::markAllStateDirty()
1568{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001569 mAppliedRenderTargetSerial = 0;
1570 mAppliedDepthbufferSerial = 0;
1571 mAppliedStencilbufferSerial = 0;
1572 mDepthStencilInitialized = false;
1573 mRenderTargetDescInitialized = false;
1574
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001575 mForceSetDepthStencilState = true;
1576 mForceSetRasterState = true;
1577 mForceSetBlendState = true;
1578 mForceSetScissor = true;
1579 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001580
1581 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001582}
1583
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001584void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001585{
1586 while (!mEventQueryPool.empty())
1587 {
1588 mEventQueryPool.back()->Release();
1589 mEventQueryPool.pop_back();
1590 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001591
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001592 if (mMaskedClearSavedState)
1593 {
1594 mMaskedClearSavedState->Release();
1595 mMaskedClearSavedState = NULL;
1596 }
1597
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001598 mVertexShaderCache.clear();
1599 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001600
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001601 delete mBlit;
1602 mBlit = NULL;
1603
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001604 delete mVertexDataManager;
1605 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001606
1607 delete mIndexDataManager;
1608 mIndexDataManager = NULL;
1609
1610 delete mLineLoopIB;
1611 mLineLoopIB = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001612}
1613
1614
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001615void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001616{
1617 mDeviceLost = true;
1618}
1619
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001620bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001621{
1622 return mDeviceLost;
1623}
1624
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001625// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001626bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001627{
1628 bool isLost = false;
1629
1630 if (mDeviceEx)
1631 {
1632 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1633 }
1634 else if (mDevice)
1635 {
1636 isLost = FAILED(mDevice->TestCooperativeLevel());
1637 }
1638 else
1639 {
1640 // No device yet, so no reset required
1641 }
1642
1643 if (isLost)
1644 {
1645 // ensure we note the device loss --
1646 // we'll probably get this done again by markDeviceLost
1647 // but best to remember it!
1648 // Note that we don't want to clear the device loss status here
1649 // -- this needs to be done by resetDevice
1650 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001651 if (notify)
1652 {
1653 mDisplay->notifyDeviceLost();
1654 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001655 }
1656
1657 return isLost;
1658}
1659
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001660bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001661{
1662 HRESULT status = D3D_OK;
1663
1664 if (mDeviceEx)
1665 {
1666 status = mDeviceEx->CheckDeviceState(NULL);
1667 }
1668 else if (mDevice)
1669 {
1670 status = mDevice->TestCooperativeLevel();
1671 }
1672
1673 switch (status)
1674 {
1675 case D3DERR_DEVICENOTRESET:
1676 case D3DERR_DEVICEHUNG:
1677 return true;
1678 default:
1679 return false;
1680 }
1681}
1682
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001683bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001684{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001685 releaseDeviceResources();
1686
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001687 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1688
1689 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001690 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001691 int attempts = 3;
1692
1693 while (lost && attempts > 0)
1694 {
1695 if (mDeviceEx)
1696 {
1697 Sleep(500); // Give the graphics driver some CPU time
1698 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1699 }
1700 else
1701 {
1702 result = mDevice->TestCooperativeLevel();
1703 while (result == D3DERR_DEVICELOST)
1704 {
1705 Sleep(100); // Give the graphics driver some CPU time
1706 result = mDevice->TestCooperativeLevel();
1707 }
1708
1709 if (result == D3DERR_DEVICENOTRESET)
1710 {
1711 result = mDevice->Reset(&presentParameters);
1712 }
1713 }
1714
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001715 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001716 attempts --;
1717 }
1718
1719 if (FAILED(result))
1720 {
1721 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1722 return false;
1723 }
1724
1725 // reset device defaults
1726 initializeDevice();
1727 mDeviceLost = false;
1728
1729 return true;
1730}
1731
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001732DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001733{
1734 return mAdapterIdentifier.VendorId;
1735}
1736
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001737const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001738{
1739 return mAdapterIdentifier.Description;
1740}
1741
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001742GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001743{
1744 return mAdapterIdentifier.DeviceIdentifier;
1745}
1746
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001747void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001748{
1749 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1750 {
1751 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1752 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1753
1754 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1755 }
1756}
1757
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001758bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001759{
1760 D3DDISPLAYMODE currentDisplayMode;
1761 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1762
1763 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1764}
1765
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001766bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001767{
1768 D3DDISPLAYMODE currentDisplayMode;
1769 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1770
1771 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1772}
1773
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001774bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001775{
1776 D3DDISPLAYMODE currentDisplayMode;
1777 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1778
1779 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1780}
1781
1782// we use INTZ for depth textures in Direct3D9
1783// we also want NULL texture support to ensure the we can make depth-only FBOs
1784// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001785bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001786{
1787 D3DDISPLAYMODE currentDisplayMode;
1788 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1789
1790 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1791 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1792 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1793 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1794
1795 return intz && null;
1796}
1797
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001798bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001799{
1800 D3DDISPLAYMODE currentDisplayMode;
1801 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1802
1803 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1804 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1805 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1806 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1807
1808 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1809 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1810 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1811 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1812
1813 if (!*filtering && !*renderable)
1814 {
1815 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1816 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1817 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1818 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1819 }
1820 else
1821 {
1822 return true;
1823 }
1824}
1825
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001826bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001827{
1828 D3DDISPLAYMODE currentDisplayMode;
1829 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1830
1831 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1832 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1833 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1834 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1835
1836 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1837 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1838 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1839 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1840
1841 if (!*filtering && !*renderable)
1842 {
1843 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1844 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1845 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1846 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1847 }
1848 else
1849 {
1850 return true;
1851 }
1852}
1853
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001854bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001855{
1856 D3DDISPLAYMODE currentDisplayMode;
1857 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1858
1859 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1860}
1861
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001862bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001863{
1864 D3DDISPLAYMODE currentDisplayMode;
1865 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1866
1867 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1868}
1869
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001870bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001871{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001872 return mSupportsTextureFilterAnisotropy;
1873}
1874
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001875float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001876{
1877 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001878 {
1879 return mDeviceCaps.MaxAnisotropy;
1880 }
1881 return 1.0f;
1882}
1883
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001884bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001885{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001886 IDirect3DQuery9 *query = allocateEventQuery();
1887 if (query)
1888 {
1889 freeEventQuery(query);
1890 return true;
1891 }
1892 else
1893 {
1894 return false;
1895 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001896 return true;
1897}
1898
1899// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1900// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001901bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001902{
1903 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1904 {
1905 return false;
1906 }
1907
1908 D3DDISPLAYMODE currentDisplayMode;
1909 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1910
1911 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1912
1913 return SUCCEEDED(result);
1914}
1915
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001916bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001917{
1918 return mSupportsNonPower2Textures;
1919}
1920
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001921bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001922{
1923 if (!mDevice)
1924 {
1925 return false;
1926 }
1927
1928 IDirect3DQuery9 *query = NULL;
1929 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1930 if (SUCCEEDED(result) && query)
1931 {
1932 query->Release();
1933 return true;
1934 }
1935 else
1936 {
1937 return false;
1938 }
1939}
1940
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001941bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001942{
1943 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1944}
1945
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001946bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001947{
1948 // PIX doesn't seem to support using share handles, so disable them.
1949 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001950 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001951}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001952
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001953int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001954{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001955 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001956}
1957
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001958float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001959{
1960 return mDeviceCaps.MaxPointSize;
1961}
1962
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001963int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001964{
1965 return (int)mDeviceCaps.MaxTextureWidth;
1966}
1967
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001968int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001969{
1970 return (int)mDeviceCaps.MaxTextureHeight;
1971}
1972
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001973bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001974{
1975 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1976}
1977
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001978DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001979{
1980 return mDeviceCaps.DeclTypes;
1981}
1982
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001983int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001984{
1985 return mMinSwapInterval;
1986}
1987
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001988int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001989{
1990 return mMaxSwapInterval;
1991}
1992
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001993int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001994{
1995 return mMaxSupportedSamples;
1996}
1997
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001998int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001999{
2000 if (requested == 0)
2001 {
2002 return requested;
2003 }
2004
2005 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2006 if (itr == mMultiSampleSupport.end())
2007 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002008 if (format == D3DFMT_UNKNOWN)
2009 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002010 return -1;
2011 }
2012
2013 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2014 {
2015 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2016 {
2017 return i;
2018 }
2019 }
2020
2021 return -1;
2022}
2023
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002024D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2025{
2026 switch (internalformat)
2027 {
2028 case GL_DEPTH_COMPONENT16:
2029 case GL_DEPTH_COMPONENT32_OES:
2030 case GL_DEPTH24_STENCIL8_OES:
2031 return D3DFMT_INTZ;
2032 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2033 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2034 return D3DFMT_DXT1;
2035 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2036 return D3DFMT_DXT3;
2037 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2038 return D3DFMT_DXT5;
2039 case GL_RGBA32F_EXT:
2040 case GL_RGB32F_EXT:
2041 case GL_ALPHA32F_EXT:
2042 case GL_LUMINANCE32F_EXT:
2043 case GL_LUMINANCE_ALPHA32F_EXT:
2044 return D3DFMT_A32B32G32R32F;
2045 case GL_RGBA16F_EXT:
2046 case GL_RGB16F_EXT:
2047 case GL_ALPHA16F_EXT:
2048 case GL_LUMINANCE16F_EXT:
2049 case GL_LUMINANCE_ALPHA16F_EXT:
2050 return D3DFMT_A16B16G16R16F;
2051 case GL_LUMINANCE8_EXT:
2052 if (getLuminanceTextureSupport())
2053 {
2054 return D3DFMT_L8;
2055 }
2056 break;
2057 case GL_LUMINANCE8_ALPHA8_EXT:
2058 if (getLuminanceAlphaTextureSupport())
2059 {
2060 return D3DFMT_A8L8;
2061 }
2062 break;
2063 case GL_RGB8_OES:
2064 case GL_RGB565:
2065 return D3DFMT_X8R8G8B8;
2066 }
2067
2068 return D3DFMT_A8R8G8B8;
2069}
2070
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002071bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002072{
2073 bool result = false;
2074
2075 if (source && dest)
2076 {
2077 int levels = source->levelCount();
2078 for (int i = 0; i < levels; ++i)
2079 {
2080 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2081 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2082
2083 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2084
2085 if (srcSurf) srcSurf->Release();
2086 if (dstSurf) dstSurf->Release();
2087
2088 if (!result)
2089 return false;
2090 }
2091 }
2092
2093 return result;
2094}
2095
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002096bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002097{
2098 bool result = false;
2099
2100 if (source && dest)
2101 {
2102 int levels = source->levelCount();
2103 for (int f = 0; f < 6; f++)
2104 {
2105 for (int i = 0; i < levels; i++)
2106 {
2107 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2108 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2109
2110 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2111
2112 if (srcSurf) srcSurf->Release();
2113 if (dstSurf) dstSurf->Release();
2114
2115 if (!result)
2116 return false;
2117 }
2118 }
2119 }
2120
2121 return result;
2122}
2123
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002124D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002125{
2126 if (mD3d9Ex != NULL)
2127 {
2128 return D3DPOOL_DEFAULT;
2129 }
2130 else
2131 {
2132 if (!(usage & D3DUSAGE_DYNAMIC))
2133 {
2134 return D3DPOOL_MANAGED;
2135 }
2136 }
2137
2138 return D3DPOOL_DEFAULT;
2139}
2140
daniel@transgaming.com38380882012-11-28 19:36:39 +00002141bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2142 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002143{
2144 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2145}
2146
daniel@transgaming.com38380882012-11-28 19:36:39 +00002147bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2148 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002149{
2150 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2151}
2152
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002153bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2154 bool blitRenderTarget, bool blitDepthStencil)
2155{
2156 endScene();
2157
2158 if (blitRenderTarget)
2159 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002160 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2161 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2162 RenderTarget9 *readRenderTarget = NULL;
2163 RenderTarget9 *drawRenderTarget = NULL;
2164 IDirect3DSurface9* readSurface = NULL;
2165 IDirect3DSurface9* drawSurface = NULL;
2166
2167 if (readBuffer)
2168 {
2169 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2170 }
2171 if (drawBuffer)
2172 {
2173 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2174 }
2175
2176 if (readRenderTarget)
2177 {
2178 readSurface = readRenderTarget->getSurface();
2179 }
2180 if (drawRenderTarget)
2181 {
2182 drawSurface = drawRenderTarget->getSurface();
2183 }
2184
2185 if (!readSurface || !drawSurface)
2186 {
2187 ERR("Failed to retrieve the render target.");
2188 return error(GL_OUT_OF_MEMORY, false);
2189 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002190
2191 RECT srcRect, dstRect;
2192 RECT *srcRectPtr = NULL;
2193 RECT *dstRectPtr = NULL;
2194
2195 if (readRect)
2196 {
2197 srcRect.left = readRect->x;
2198 srcRect.right = readRect->x + readRect->width;
2199 srcRect.top = readRect->y;
2200 srcRect.bottom = readRect->y + readRect->height;
2201 srcRectPtr = &srcRect;
2202 }
2203
2204 if (drawRect)
2205 {
2206 dstRect.left = drawRect->x;
2207 dstRect.right = drawRect->x + drawRect->width;
2208 dstRect.top = drawRect->y;
2209 dstRect.bottom = drawRect->y + drawRect->height;
2210 dstRectPtr = &dstRect;
2211 }
2212
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002213 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002214
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002215 readSurface->Release();
2216 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002217
2218 if (FAILED(result))
2219 {
2220 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2221 return false;
2222 }
2223 }
2224
2225 if (blitDepthStencil)
2226 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002227 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2228 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2229 RenderTarget9 *readDepthStencil = NULL;
2230 RenderTarget9 *drawDepthStencil = NULL;
2231 IDirect3DSurface9* readSurface = NULL;
2232 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002233
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002234 if (readBuffer)
2235 {
2236 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2237 }
2238 if (drawBuffer)
2239 {
2240 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2241 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002242
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002243 if (readDepthStencil)
2244 {
2245 readSurface = readDepthStencil->getSurface();
2246 }
2247 if (drawDepthStencil)
2248 {
2249 drawSurface = drawDepthStencil->getSurface();
2250 }
2251
2252 if (!readSurface || !drawSurface)
2253 {
2254 ERR("Failed to retrieve the render target.");
2255 return error(GL_OUT_OF_MEMORY, false);
2256 }
2257
2258 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2259
2260 readSurface->Release();
2261 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002262
2263 if (FAILED(result))
2264 {
2265 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2266 return false;
2267 }
2268 }
2269
2270 return true;
2271}
2272
2273void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2274 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2275{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002276 RenderTarget9 *renderTarget = NULL;
2277 IDirect3DSurface9 *surface = NULL;
2278 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2279
2280 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002281 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002282 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2283 }
2284
2285 if (renderTarget)
2286 {
2287 surface = renderTarget->getSurface();
2288 }
2289
2290 if (!surface)
2291 {
2292 // context must be lost
2293 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002294 }
2295
2296 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002297 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002298
2299 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2300 {
2301 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002302 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002303 return error(GL_OUT_OF_MEMORY);
2304 }
2305
2306 HRESULT result;
2307 IDirect3DSurface9 *systemSurface = NULL;
2308 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2309 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2310 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2311 if (directToPixels)
2312 {
2313 // Use the pixels ptr as a shared handle to write directly into client's memory
2314 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2315 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2316 if (FAILED(result))
2317 {
2318 // Try again without the shared handle
2319 directToPixels = false;
2320 }
2321 }
2322
2323 if (!directToPixels)
2324 {
2325 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2326 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2327 if (FAILED(result))
2328 {
2329 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002330 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002331 return error(GL_OUT_OF_MEMORY);
2332 }
2333 }
2334
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002335 result = mDevice->GetRenderTargetData(surface, systemSurface);
2336 surface->Release();
2337 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002338
2339 if (FAILED(result))
2340 {
2341 systemSurface->Release();
2342
2343 // It turns out that D3D will sometimes produce more error
2344 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002345 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002346 return error(GL_OUT_OF_MEMORY);
2347 else
2348 {
2349 UNREACHABLE();
2350 return;
2351 }
2352
2353 }
2354
2355 if (directToPixels)
2356 {
2357 systemSurface->Release();
2358 return;
2359 }
2360
2361 RECT rect;
2362 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2363 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2364 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2365 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2366
2367 D3DLOCKED_RECT lock;
2368 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2369
2370 if (FAILED(result))
2371 {
2372 UNREACHABLE();
2373 systemSurface->Release();
2374
2375 return; // No sensible error to generate
2376 }
2377
2378 unsigned char *dest = (unsigned char*)pixels;
2379 unsigned short *dest16 = (unsigned short*)pixels;
2380
2381 unsigned char *source;
2382 int inputPitch;
2383 if (packReverseRowOrder)
2384 {
2385 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2386 inputPitch = -lock.Pitch;
2387 }
2388 else
2389 {
2390 source = (unsigned char*)lock.pBits;
2391 inputPitch = lock.Pitch;
2392 }
2393
2394 unsigned int fastPixelSize = 0;
2395
2396 if (desc.Format == D3DFMT_A8R8G8B8 &&
2397 format == GL_BGRA_EXT &&
2398 type == GL_UNSIGNED_BYTE)
2399 {
2400 fastPixelSize = 4;
2401 }
2402 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2403 format == GL_BGRA_EXT &&
2404 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2405 (desc.Format == D3DFMT_A1R5G5B5 &&
2406 format == GL_BGRA_EXT &&
2407 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2408 {
2409 fastPixelSize = 2;
2410 }
2411 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2412 format == GL_RGBA &&
2413 type == GL_HALF_FLOAT_OES)
2414 {
2415 fastPixelSize = 8;
2416 }
2417 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2418 format == GL_RGBA &&
2419 type == GL_FLOAT)
2420 {
2421 fastPixelSize = 16;
2422 }
2423
2424 for (int j = 0; j < rect.bottom - rect.top; j++)
2425 {
2426 if (fastPixelSize != 0)
2427 {
2428 // Fast path for formats which require no translation:
2429 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2430 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2431 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2432 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2433 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2434 //
2435 // Note that buffers with no alpha go through the slow path below.
2436 memcpy(dest + j * outputPitch,
2437 source + j * inputPitch,
2438 (rect.right - rect.left) * fastPixelSize);
2439 continue;
2440 }
2441
2442 for (int i = 0; i < rect.right - rect.left; i++)
2443 {
2444 float r;
2445 float g;
2446 float b;
2447 float a;
2448
2449 switch (desc.Format)
2450 {
2451 case D3DFMT_R5G6B5:
2452 {
2453 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2454
2455 a = 1.0f;
2456 b = (rgb & 0x001F) * (1.0f / 0x001F);
2457 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2458 r = (rgb & 0xF800) * (1.0f / 0xF800);
2459 }
2460 break;
2461 case D3DFMT_A1R5G5B5:
2462 {
2463 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2464
2465 a = (argb & 0x8000) ? 1.0f : 0.0f;
2466 b = (argb & 0x001F) * (1.0f / 0x001F);
2467 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2468 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2469 }
2470 break;
2471 case D3DFMT_A8R8G8B8:
2472 {
2473 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2474
2475 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2476 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2477 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2478 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2479 }
2480 break;
2481 case D3DFMT_X8R8G8B8:
2482 {
2483 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2484
2485 a = 1.0f;
2486 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2487 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2488 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2489 }
2490 break;
2491 case D3DFMT_A2R10G10B10:
2492 {
2493 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2494
2495 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2496 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2497 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2498 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2499 }
2500 break;
2501 case D3DFMT_A32B32G32R32F:
2502 {
2503 // float formats in D3D are stored rgba, rather than the other way round
2504 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2505 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2506 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2507 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2508 }
2509 break;
2510 case D3DFMT_A16B16G16R16F:
2511 {
2512 // float formats in D3D are stored rgba, rather than the other way round
2513 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2514 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2515 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2516 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2517 }
2518 break;
2519 default:
2520 UNIMPLEMENTED(); // FIXME
2521 UNREACHABLE();
2522 return;
2523 }
2524
2525 switch (format)
2526 {
2527 case GL_RGBA:
2528 switch (type)
2529 {
2530 case GL_UNSIGNED_BYTE:
2531 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2532 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2533 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2534 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2535 break;
2536 default: UNREACHABLE();
2537 }
2538 break;
2539 case GL_BGRA_EXT:
2540 switch (type)
2541 {
2542 case GL_UNSIGNED_BYTE:
2543 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2544 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2545 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2546 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2547 break;
2548 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2549 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2550 // this type is packed as follows:
2551 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2552 // --------------------------------------------------------------------------------
2553 // | 4th | 3rd | 2nd | 1st component |
2554 // --------------------------------------------------------------------------------
2555 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2556 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2557 ((unsigned short)(15 * a + 0.5f) << 12)|
2558 ((unsigned short)(15 * r + 0.5f) << 8) |
2559 ((unsigned short)(15 * g + 0.5f) << 4) |
2560 ((unsigned short)(15 * b + 0.5f) << 0);
2561 break;
2562 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2563 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2564 // this type is packed as follows:
2565 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2566 // --------------------------------------------------------------------------------
2567 // | 4th | 3rd | 2nd | 1st component |
2568 // --------------------------------------------------------------------------------
2569 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2570 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2571 ((unsigned short)( a + 0.5f) << 15) |
2572 ((unsigned short)(31 * r + 0.5f) << 10) |
2573 ((unsigned short)(31 * g + 0.5f) << 5) |
2574 ((unsigned short)(31 * b + 0.5f) << 0);
2575 break;
2576 default: UNREACHABLE();
2577 }
2578 break;
2579 case GL_RGB:
2580 switch (type)
2581 {
2582 case GL_UNSIGNED_SHORT_5_6_5:
2583 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2584 ((unsigned short)(31 * b + 0.5f) << 0) |
2585 ((unsigned short)(63 * g + 0.5f) << 5) |
2586 ((unsigned short)(31 * r + 0.5f) << 11);
2587 break;
2588 case GL_UNSIGNED_BYTE:
2589 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2590 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2591 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2592 break;
2593 default: UNREACHABLE();
2594 }
2595 break;
2596 default: UNREACHABLE();
2597 }
2598 }
2599 }
2600
2601 systemSurface->UnlockRect();
2602
2603 systemSurface->Release();
2604}
2605
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002606RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2607{
2608 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2609 IDirect3DSurface9 *surface = NULL;
2610 if (depth)
2611 {
2612 surface = swapChain9->getDepthStencil();
2613 }
2614 else
2615 {
2616 surface = swapChain9->getRenderTarget();
2617 }
2618
2619 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2620
2621 return renderTarget;
2622}
2623
2624RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2625{
2626 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2627 return renderTarget;
2628}
2629
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002630bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2631{
2632 return mBlit->boxFilter(source, dest);
2633}
2634
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002635D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002636{
2637 if (mD3d9Ex != NULL)
2638 {
2639 return D3DPOOL_DEFAULT;
2640 }
2641 else
2642 {
2643 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2644 {
2645 return D3DPOOL_MANAGED;
2646 }
2647 }
2648
2649 return D3DPOOL_DEFAULT;
2650}
2651
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002652bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2653{
2654 if (source && dest)
2655 {
2656 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2657 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2658
2659 if (fromManaged)
2660 {
2661 D3DSURFACE_DESC desc;
2662 source->GetDesc(&desc);
2663
2664 IDirect3DSurface9 *surf = 0;
2665 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2666
2667 if (SUCCEEDED(result))
2668 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002669 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002670 result = device->UpdateSurface(surf, NULL, dest, NULL);
2671 surf->Release();
2672 }
2673 }
2674 else
2675 {
2676 endScene();
2677 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2678 }
2679
2680 if (FAILED(result))
2681 {
2682 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2683 return false;
2684 }
2685 }
2686
2687 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002688}
2689
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002690}