blob: 039af19b90af0dae1c1e810c8f62cd13b09d24b2 [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"
13#include "libGLESv2/Framebuffer.h"
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +000014#include "libGLESv2/Program.h"
15#include "libGLESv2/ProgramBinary.h"
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000016#include "libGLESv2/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000017#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000018#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000019#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +000020#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000021#include "libGLESv2/renderer/Image.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000022#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000023#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000024
daniel@transgaming.com3281f972012-10-31 18:38:51 +000025#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000026#include "libEGL/Display.h"
27
daniel@transgaming.com621ce052012-10-31 17:52:29 +000028// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
29#define REF_RAST 0
30
31// The "Debug This Pixel..." feature in PIX often fails when using the
32// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
33// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
34#if !defined(ANGLE_ENABLE_D3D9EX)
35// Enables use of the IDirect3D9Ex interface, when available
36#define ANGLE_ENABLE_D3D9EX 1
37#endif // !defined(ANGLE_ENABLE_D3D9EX)
38
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000039namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000040{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000041static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000042 {
43 D3DFMT_A1R5G5B5,
44 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
45 D3DFMT_A8R8G8B8,
46 D3DFMT_R5G6B5,
47 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
48 D3DFMT_X8R8G8B8
49 };
50
daniel@transgaming.com222ee082012-11-28 19:31:49 +000051static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000052 {
53 D3DFMT_UNKNOWN,
54 // D3DFMT_D16_LOCKABLE,
55 D3DFMT_D32,
56 // D3DFMT_D15S1,
57 D3DFMT_D24S8,
58 D3DFMT_D24X8,
59 // D3DFMT_D24X4S4,
60 D3DFMT_D16,
61 // D3DFMT_D32F_LOCKABLE,
62 // D3DFMT_D24FS8
63 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000064
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000065Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000066{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000067 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000068
daniel@transgaming.com7d738a22012-11-28 19:43:08 +000069 mD3dCompilerModule = NULL;
70
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071 mD3d9 = NULL;
72 mD3d9Ex = NULL;
73 mDevice = NULL;
74 mDeviceEx = NULL;
75 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000076 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000077
78 mAdapter = D3DADAPTER_DEFAULT;
79
80 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
81 mDeviceType = D3DDEVTYPE_REF;
82 #else
83 mDeviceType = D3DDEVTYPE_HAL;
84 #endif
85
86 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000087
88 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000089
90 mVertexDataManager = NULL;
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000091
92 mMaskedClearSavedState = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000093}
94
daniel@transgaming.com2507f412012-10-31 18:46:48 +000095Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +000096{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000097 releaseDeviceResources();
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000098
99 delete mBlit;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000100
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000101 if (mDevice)
102 {
103 // 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 +0000104 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000105 {
106 resetDevice();
107 }
108
109 mDevice->Release();
110 mDevice = NULL;
111 }
112
113 if (mDeviceEx)
114 {
115 mDeviceEx->Release();
116 mDeviceEx = NULL;
117 }
118
119 if (mD3d9)
120 {
121 mD3d9->Release();
122 mD3d9 = NULL;
123 }
124
125 if (mDeviceWindow)
126 {
127 DestroyWindow(mDeviceWindow);
128 mDeviceWindow = NULL;
129 }
130
131 if (mD3d9Ex)
132 {
133 mD3d9Ex->Release();
134 mD3d9Ex = NULL;
135 }
136
137 if (mD3d9Module)
138 {
139 mD3d9Module = NULL;
140 }
141
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000142 if (mD3dCompilerModule)
143 {
144 FreeLibrary(mD3dCompilerModule);
145 mD3dCompilerModule = NULL;
146 }
147
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000148 while (!mMultiSampleSupport.empty())
149 {
150 delete [] mMultiSampleSupport.begin()->second;
151 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
152 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000153}
154
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000155Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
156{
157 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
158 return static_cast<rx::Renderer9*>(renderer);
159}
160
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000161EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000162{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000163 if (mSoftwareDevice)
164 {
165 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
166 }
167 else
168 {
169 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
170 }
171
172 if (mD3d9Module == NULL)
173 {
174 ERR("No D3D9 module found - aborting!\n");
175 return EGL_NOT_INITIALIZED;
176 }
177
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000178 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
179 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
180
181 // Use Direct3D9Ex if available. Among other things, this version is less
182 // inclined to report a lost context, for example when the user switches
183 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
184 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
185 {
186 ASSERT(mD3d9Ex);
187 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
188 ASSERT(mD3d9);
189 }
190 else
191 {
192 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
193 }
194
195 if (!mD3d9)
196 {
197 ERR("Could not create D3D9 device - aborting!\n");
198 return EGL_NOT_INITIALIZED;
199 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000200
201#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
202 // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
203 static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
204
205 for (int i = 0; i < sizeof(d3dCompilerNames) / sizeof(*d3dCompilerNames); ++i)
206 {
207 if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
208 {
209 break;
210 }
211 }
212#else
213 // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
214 mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
215#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
216
217 if (!mD3dCompilerModule)
218 {
219 terminate();
220 return false;
221 }
222
223 mD3DCompileFunc = reinterpret_cast<D3DCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
224 ASSERT(mD3DCompileFunc);
225
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000226 if (mDc != NULL)
227 {
228 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
229 }
230
231 HRESULT result;
232
233 // Give up on getting device caps after about one second.
234 for (int i = 0; i < 10; ++i)
235 {
236 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
237 if (SUCCEEDED(result))
238 {
239 break;
240 }
241 else if (result == D3DERR_NOTAVAILABLE)
242 {
243 Sleep(100); // Give the driver some time to initialize/recover
244 }
245 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
246 {
247 ERR("failed to get device caps (0x%x)\n", result);
248 return EGL_NOT_INITIALIZED;
249 }
250 }
251
252 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
253 {
254 ERR("Renderer does not support PS 2.0. aborting!\n");
255 return EGL_NOT_INITIALIZED;
256 }
257
258 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
259 // This is required by Texture2D::convertToRenderTarget.
260 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
261 {
262 ERR("Renderer does not support stretctrect from textures!\n");
263 return EGL_NOT_INITIALIZED;
264 }
265
266 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
267
268 // ATI cards on XP have problems with non-power-of-two textures.
269 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
270 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
271 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
272 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
273
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000274 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
275 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
276
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000277 mMinSwapInterval = 4;
278 mMaxSwapInterval = 0;
279
280 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
281 {
282 mMinSwapInterval = std::min(mMinSwapInterval, 0);
283 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
284 }
285 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
286 {
287 mMinSwapInterval = std::min(mMinSwapInterval, 1);
288 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
289 }
290 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
291 {
292 mMinSwapInterval = std::min(mMinSwapInterval, 2);
293 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
294 }
295 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
296 {
297 mMinSwapInterval = std::min(mMinSwapInterval, 3);
298 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
299 }
300 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
301 {
302 mMinSwapInterval = std::min(mMinSwapInterval, 4);
303 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
304 }
305
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000306 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000307 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000308 {
309 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000310 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
311 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000312
313 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
314 {
315 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
316 {
317 max = j;
318 }
319 }
320 }
321
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000322 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000323 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000324 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000325 continue;
326
327 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000328 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
329 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000330
331 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
332 {
333 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
334 {
335 max = j;
336 }
337 }
338 }
339
340 mMaxSupportedSamples = max;
341
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000342 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
343 static const TCHAR className[] = TEXT("STATIC");
344
345 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
346
347 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
348 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
349
350 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
351 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
352 {
353 return EGL_BAD_ALLOC;
354 }
355
356 if (FAILED(result))
357 {
358 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
359
360 if (FAILED(result))
361 {
362 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
363 return EGL_BAD_ALLOC;
364 }
365 }
366
367 if (mD3d9Ex)
368 {
369 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
370 ASSERT(SUCCEEDED(result));
371 }
372
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000373 mVertexShaderCache.initialize(mDevice);
374 mPixelShaderCache.initialize(mDevice);
375
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000376 initializeDevice();
377
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +0000378 mBlit = new Blit(this);
379
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000380 return EGL_SUCCESS;
381}
382
383// do any one-time device initialization
384// NOTE: this is also needed after a device lost/reset
385// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000386void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000387{
388 // Permanent non-default states
389 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
390 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
391
392 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
393 {
394 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
395 }
396 else
397 {
398 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
399 }
400
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000401 markAllStateDirty();
402
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000403 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000404
405 if (!mVertexDataManager)
406 {
407 mVertexDataManager = new gl::VertexDataManager(this);
408 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000409}
410
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000411D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000412{
413 D3DPRESENT_PARAMETERS presentParameters = {0};
414
415 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
416 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
417 presentParameters.BackBufferCount = 1;
418 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
419 presentParameters.BackBufferWidth = 1;
420 presentParameters.BackBufferHeight = 1;
421 presentParameters.EnableAutoDepthStencil = FALSE;
422 presentParameters.Flags = 0;
423 presentParameters.hDeviceWindow = mDeviceWindow;
424 presentParameters.MultiSampleQuality = 0;
425 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
426 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
427 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
428 presentParameters.Windowed = TRUE;
429
430 return presentParameters;
431}
432
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000433int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000434{
435 D3DDISPLAYMODE currentDisplayMode;
436 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
437
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000438 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
439 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000440 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
441 int numConfigs = 0;
442
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000443 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000444 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000445 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000446
447 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
448
449 if (SUCCEEDED(result))
450 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000451 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000452 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000453 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000454 HRESULT result = D3D_OK;
455
456 if(depthStencilFormat != D3DFMT_UNKNOWN)
457 {
458 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
459 }
460
461 if (SUCCEEDED(result))
462 {
463 if(depthStencilFormat != D3DFMT_UNKNOWN)
464 {
465 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
466 }
467
468 if (SUCCEEDED(result))
469 {
470 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000471 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
472 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000473 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
474 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
475
476 (*configDescList)[numConfigs++] = newConfig;
477 }
478 }
479 }
480 }
481 }
482
483 return numConfigs;
484}
485
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000486void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000487{
488 delete [] (configDescList);
489}
490
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000491void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000492{
493 if (!mSceneStarted)
494 {
495 long result = mDevice->BeginScene();
496 if (SUCCEEDED(result)) {
497 // This is defensive checking against the device being
498 // lost at unexpected times.
499 mSceneStarted = true;
500 }
501 }
502}
503
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000504void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000505{
506 if (mSceneStarted)
507 {
508 // EndScene can fail if the device was lost, for example due
509 // to a TDR during a draw call.
510 mDevice->EndScene();
511 mSceneStarted = false;
512 }
513}
514
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000515// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000516void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000517{
518 HRESULT result;
519
520 IDirect3DQuery9* query = allocateEventQuery();
521 if (!query)
522 {
523 return;
524 }
525
526 result = query->Issue(D3DISSUE_END);
527 ASSERT(SUCCEEDED(result));
528
529 do
530 {
531 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
532
533 if(block && result == S_FALSE)
534 {
535 // Keep polling, but allow other threads to do something useful first
536 Sleep(0);
537 // explicitly check for device loss
538 // some drivers seem to return S_FALSE even if the device is lost
539 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000540 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000541 {
542 result = D3DERR_DEVICELOST;
543 }
544 }
545 }
546 while(block && result == S_FALSE);
547
548 freeEventQuery(query);
549
550 if (isDeviceLostError(result))
551 {
552 mDisplay->notifyDeviceLost();
553 }
554}
555
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000556SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
557{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000558 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000559}
560
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000561// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000562IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000563{
564 IDirect3DQuery9 *query = NULL;
565
566 if (mEventQueryPool.empty())
567 {
568 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
569 ASSERT(SUCCEEDED(result));
570 }
571 else
572 {
573 query = mEventQueryPool.back();
574 mEventQueryPool.pop_back();
575 }
576
577 return query;
578}
579
580// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000581void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000582{
583 if (mEventQueryPool.size() > 1000)
584 {
585 query->Release();
586 }
587 else
588 {
589 mEventQueryPool.push_back(query);
590 }
591}
592
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000593
594HRESULT Renderer9::compileShaderSource(const char* hlsl, const char* sourceName, const char* profile, DWORD flags, ID3DBlob** binary, ID3DBlob** errorMessage)
595{
596 return mD3DCompileFunc(hlsl, strlen(hlsl), sourceName, NULL, NULL, "main", profile, flags, 0, binary, errorMessage);
597}
598
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000599IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000600{
601 return mVertexShaderCache.create(function, length);
602}
603
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000604IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000605{
606 return mPixelShaderCache.create(function, length);
607}
608
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000609HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
610{
611 D3DPOOL Pool = getBufferPool(Usage);
612 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
613}
614
615HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
616{
617 D3DPOOL Pool = getBufferPool(Usage);
618 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
619}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000620
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000621void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000622{
623 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
624 int d3dSampler = index + d3dSamplerOffset;
625
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000626 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
627 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000628
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000629 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000630 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000631 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000632 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
633 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
634 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
635 if (mSupportsTextureFilterAnisotropy)
636 {
637 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
638 }
639}
640
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000641void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000642{
643 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
644 int d3dSampler = index + d3dSamplerOffset;
645 IDirect3DBaseTexture9 *d3dTexture = NULL;
646
647 if (texture)
648 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000649 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000650 if (texStorage)
651 {
652 d3dTexture = texStorage->getBaseTexture();
653 }
654 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000655 // in the texture class and we're unexpectedly missing the d3d texture
656 ASSERT(d3dTexture != NULL);
657 }
658
659 mDevice->SetTexture(d3dSampler, d3dTexture);
660}
661
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000662void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
663{
664 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
665 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
666
667 if (rasterStateChanged)
668 {
669 // Set the cull mode
670 if (rasterState.cullFace)
671 {
672 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
673 }
674 else
675 {
676 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
677 }
678
679 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
680
681 mCurRasterState = rasterState;
682 }
683
684 if (rasterStateChanged || depthSizeChanged)
685 {
686 if (rasterState.polygonOffsetFill)
687 {
688 if (depthSize > 0)
689 {
690 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
691
692 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
693 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
694 }
695 }
696 else
697 {
698 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
699 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
700 }
701
702 mCurDepthSize = depthSize;
703 }
704
705 mForceSetRasterState = false;
706}
707
708void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
709{
710 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
711 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
712 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
713
714 if (blendStateChanged || blendColorChanged)
715 {
716 if (blendState.blend)
717 {
718 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
719
720 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
721 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
722 {
723 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
724 }
725 else
726 {
727 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
728 gl::unorm<8>(blendColor.alpha),
729 gl::unorm<8>(blendColor.alpha),
730 gl::unorm<8>(blendColor.alpha)));
731 }
732
733 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
734 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
735 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
736
737 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
738 blendState.destBlendRGB != blendState.destBlendAlpha ||
739 blendState.blendEquationRGB != blendState.blendEquationAlpha)
740 {
741 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
742
743 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
744 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
745 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
746 }
747 else
748 {
749 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
750 }
751 }
752 else
753 {
754 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
755 }
756
757 if (blendState.sampleAlphaToCoverage)
758 {
759 FIXME("Sample alpha to coverage is unimplemented.");
760 }
761
762 // Set the color mask
763 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
764 // Apparently some ATI cards have a bug where a draw with a zero color
765 // write mask can cause later draws to have incorrect results. Instead,
766 // set a nonzero color write mask but modify the blend state so that no
767 // drawing is done.
768 // http://code.google.com/p/angleproject/issues/detail?id=169
769
770 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
771 blendState.colorMaskBlue, blendState.colorMaskAlpha);
772 if (colorMask == 0 && !zeroColorMaskAllowed)
773 {
774 // Enable green channel, but set blending so nothing will be drawn.
775 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
776 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
777
778 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
779 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
780 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
781 }
782 else
783 {
784 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
785 }
786
787 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
788
789 mCurBlendState = blendState;
790 mCurBlendColor = blendColor;
791 }
792
793 if (sampleMaskChanged)
794 {
795 // Set the multisample mask
796 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
797 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
798
799 mCurSampleMask = sampleMask;
800 }
801
802 mForceSetBlendState = false;
803}
804
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000805void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
806 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000807{
808 bool depthStencilStateChanged = mForceSetDepthStencilState ||
809 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000810 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
811 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000812 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
813 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
814
815 if (depthStencilStateChanged)
816 {
817 if (depthStencilState.depthTest)
818 {
819 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
820 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
821 }
822 else
823 {
824 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
825 }
826
827 mCurDepthStencilState = depthStencilState;
828 }
829
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000830 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000831 {
832 if (depthStencilState.stencilTest && stencilSize > 0)
833 {
834 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
835 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
836
837 // FIXME: Unsupported by D3D9
838 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
839 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
840 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
841 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000842 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000843 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
844 {
845 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
846 return error(GL_INVALID_OPERATION);
847 }
848
849 // get the maximum size of the stencil ref
850 GLuint maxStencil = (1 << stencilSize) - 1;
851
852 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
853 depthStencilState.stencilWritemask);
854 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
855 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
856
857 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000858 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000859 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
860 depthStencilState.stencilMask);
861
862 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
863 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
864 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
865 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
866 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
867 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
868
869 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
870 depthStencilState.stencilBackWritemask);
871 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
872 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
873
874 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000875 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000876 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
877 depthStencilState.stencilBackMask);
878
879 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
880 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
881 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
882 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
883 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
884 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
885 }
886 else
887 {
888 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
889 }
890
891 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
892
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000893 mCurStencilRef = stencilRef;
894 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000895 mCurFrontFaceCCW = frontFaceCCW;
896 mCurStencilSize = stencilSize;
897 }
898
899 mForceSetDepthStencilState = false;
900}
901
902void Renderer9::setScissorRectangle(const gl::Rectangle& scissor, unsigned int renderTargetWidth,
903 unsigned int renderTargetHeight)
904{
905 bool renderTargetSizedChanged = mForceSetScissor ||
906 renderTargetWidth != mCurRenderTargetWidth ||
907 renderTargetHeight != mCurRenderTargetHeight;
908 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
909
910 if (renderTargetSizedChanged || scissorChanged)
911 {
912 RECT rect;
913 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000914 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000915 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000916 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000917 mDevice->SetScissorRect(&rect);
918
919 mCurScissor = scissor;
920 mCurRenderTargetWidth = renderTargetWidth;
921 mCurRenderTargetHeight = renderTargetHeight;
922 }
923
924 mForceSetScissor = false;
925}
926
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000927bool Renderer9::setViewport(const gl::Rectangle& viewport, float zNear, float zFar,
928 unsigned int renderTargetWidth, unsigned int renderTargetHeight,
929 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
930{
931 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
932 zNear != mCurNear || zFar != mCurFar;
933
934 D3DVIEWPORT9 dxViewport;
935 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(renderTargetWidth));
936 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(renderTargetHeight));
937 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(renderTargetWidth) - static_cast<int>(dxViewport.X));
938 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(renderTargetHeight) - static_cast<int>(dxViewport.Y));
939 dxViewport.MinZ = zNear;
940 dxViewport.MaxZ = zFar;
941
942 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
943 {
944 return false; // Nothing to render
945 }
946
947 if (viewportChanged)
948 {
949 mDevice->SetViewport(&dxViewport);
950
951 mCurViewport = viewport;
952 mCurNear = zNear;
953 mCurFar = zFar;
954 }
955
956 if (currentProgram && (viewportChanged || forceSetUniforms))
957 {
958 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
959 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
960 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
961
962 // These values are used for computing gl_FragCoord in Program::linkVaryings().
963 GLint coord = currentProgram->getDxCoordLocation();
964 GLfloat whxy[4] = { viewport.width * 0.5f,
965 viewport.height * 0.5f,
966 viewport.x + (viewport.width * 0.5f),
967 viewport.y + (viewport.height * 0.5f) };
968 currentProgram->setUniform4fv(coord, 1, whxy);
969
970 GLint depth = currentProgram->getDxDepthLocation();
971 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
972 currentProgram->setUniform2fv(depth, 1, dz);
973
974 GLint depthRange = currentProgram->getDxDepthRangeLocation();
975 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
976 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
977 }
978
979 mForceSetViewport = false;
980 return true;
981}
982
daniel@transgaming.comae39ee22012-11-28 19:42:02 +0000983bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000984{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +0000985 // if there is no color attachment we must synthesize a NULL colorattachment
986 // to keep the D3D runtime happy. This should only be possible if depth texturing.
987 gl::Renderbuffer *renderbufferObject = NULL;
988 if (framebuffer->getColorbufferType() != GL_NONE)
989 {
990 renderbufferObject = framebuffer->getColorbuffer();
991 }
992 else
993 {
994 renderbufferObject = framebuffer->getNullColorbuffer();
995 }
996 if (!renderbufferObject)
997 {
998 ERR("unable to locate renderbuffer for FBO.");
999 return false;
1000 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001001
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001002 bool renderTargetChanged = false;
1003 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1004 if (renderTargetSerial != mAppliedRenderTargetSerial)
1005 {
1006 // Apply the render target on the device
1007 IDirect3DSurface9 *renderTargetSurface = NULL;
1008
1009 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1010 if (renderTarget)
1011 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001012 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001013 }
1014
1015 if (!renderTargetSurface)
1016 {
1017 ERR("render target pointer unexpectedly null.");
1018 return false; // Context must be lost
1019 }
1020
1021 mDevice->SetRenderTarget(0, renderTargetSurface);
1022 renderTargetSurface->Release();
1023
1024 mAppliedRenderTargetSerial = renderTargetSerial;
1025 renderTargetChanged = true;
1026 }
1027
1028 gl::Renderbuffer *depthStencil = NULL;
1029 unsigned int depthbufferSerial = 0;
1030 unsigned int stencilbufferSerial = 0;
1031 if (framebuffer->getDepthbufferType() != GL_NONE)
1032 {
1033 depthStencil = framebuffer->getDepthbuffer();
1034 if (!depthStencil)
1035 {
1036 ERR("Depth stencil pointer unexpectedly null.");
1037 return false;
1038 }
1039
1040 depthbufferSerial = depthStencil->getSerial();
1041 }
1042 else if (framebuffer->getStencilbufferType() != GL_NONE)
1043 {
1044 depthStencil = framebuffer->getStencilbuffer();
1045 if (!depthStencil)
1046 {
1047 ERR("Depth stencil pointer unexpectedly null.");
1048 return false;
1049 }
1050
1051 stencilbufferSerial = depthStencil->getSerial();
1052 }
1053
1054 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1055 stencilbufferSerial != mAppliedStencilbufferSerial ||
1056 !mDepthStencilInitialized)
1057 {
1058 // Apply the depth stencil on the device
1059 if (depthStencil)
1060 {
1061 IDirect3DSurface9 *depthStencilSurface = NULL;
1062 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1063
1064 if (depthStencilRenderTarget)
1065 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001066 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001067 }
1068
1069 if (!depthStencilSurface)
1070 {
1071 ERR("depth stencil pointer unexpectedly null.");
1072 return false; // Context must be lost
1073 }
1074
1075 mDevice->SetDepthStencilSurface(depthStencilSurface);
1076 depthStencilSurface->Release();
1077 }
1078 else
1079 {
1080 mDevice->SetDepthStencilSurface(NULL);
1081 }
1082
1083 mAppliedDepthbufferSerial = depthbufferSerial;
1084 mAppliedStencilbufferSerial = stencilbufferSerial;
1085 mDepthStencilInitialized = true;
1086 }
1087
1088 if (renderTargetChanged || !mRenderTargetDescInitialized)
1089 {
1090 mForceSetScissor = true;
1091 mForceSetViewport = true;
1092
1093 mRenderTargetDesc.width = renderbufferObject->getWidth();
1094 mRenderTargetDesc.height = renderbufferObject->getHeight();
1095 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1096 mRenderTargetDescInitialized = true;
1097 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001098
1099 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001100}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001101
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001102GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
1103{
1104 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1105 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1106 if (err != GL_NO_ERROR)
1107 {
1108 return err;
1109 }
1110
1111 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
1112}
1113
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001114void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1115{
1116 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
1117 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
1118
1119 mDevice->SetPixelShader(pixelShader);
1120 mDevice->SetVertexShader(vertexShader);
1121 programBinary->dirtyAllUniforms();
1122}
1123
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001124void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001125{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001126 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1127 gl::unorm<8>(clearParams.colorClearValue.red),
1128 gl::unorm<8>(clearParams.colorClearValue.green),
1129 gl::unorm<8>(clearParams.colorClearValue.blue));
1130 float depth = gl::clamp01(clearParams.depthClearValue);
1131 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001132
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001133 unsigned int stencilUnmasked = 0x0;
1134 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1135 {
1136 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1137 stencilUnmasked = (0x1 << stencilSize) - 1;
1138 }
1139
1140 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1141
1142 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1143 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1144 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1145 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1146 clearParams.colorMaskBlue && alphaUnmasked);
1147
1148 if (needMaskedColorClear || needMaskedStencilClear)
1149 {
1150 // State which is altered in all paths from this point to the clear call is saved.
1151 // State which is altered in only some paths will be flagged dirty in the case that
1152 // that path is taken.
1153 HRESULT hr;
1154 if (mMaskedClearSavedState == NULL)
1155 {
1156 hr = mDevice->BeginStateBlock();
1157 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1158
1159 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1160 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1161 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1162 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1163 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1164 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1165 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1166 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1167 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1168 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1169 mDevice->SetPixelShader(NULL);
1170 mDevice->SetVertexShader(NULL);
1171 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1172 mDevice->SetStreamSource(0, NULL, 0, 0);
1173 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1174 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1175 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1176 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1177 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1178 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1179 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1180
1181 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1182 {
1183 mDevice->SetStreamSourceFreq(i, 1);
1184 }
1185
1186 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1187 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1188 }
1189
1190 ASSERT(mMaskedClearSavedState != NULL);
1191
1192 if (mMaskedClearSavedState != NULL)
1193 {
1194 hr = mMaskedClearSavedState->Capture();
1195 ASSERT(SUCCEEDED(hr));
1196 }
1197
1198 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1199 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1200 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1201 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1202 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1203 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1204 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1205 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1206
1207 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1208 {
1209 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1210 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1211 clearParams.colorMaskGreen,
1212 clearParams.colorMaskBlue,
1213 clearParams.colorMaskAlpha));
1214 }
1215 else
1216 {
1217 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1218 }
1219
1220 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1221 {
1222 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1223 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1224 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1225 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1226 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1227 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1228 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1229 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1230 }
1231 else
1232 {
1233 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1234 }
1235
1236 mDevice->SetPixelShader(NULL);
1237 mDevice->SetVertexShader(NULL);
1238 mDevice->SetFVF(D3DFVF_XYZRHW);
1239 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1240 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1241 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1242 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1243 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1244 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1245 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1246
1247 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1248 {
1249 mDevice->SetStreamSourceFreq(i, 1);
1250 }
1251
1252 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1253 quad[0][0] = -0.5f;
1254 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1255 quad[0][2] = 0.0f;
1256 quad[0][3] = 1.0f;
1257
1258 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1259 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1260 quad[1][2] = 0.0f;
1261 quad[1][3] = 1.0f;
1262
1263 quad[2][0] = -0.5f;
1264 quad[2][1] = -0.5f;
1265 quad[2][2] = 0.0f;
1266 quad[2][3] = 1.0f;
1267
1268 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1269 quad[3][1] = -0.5f;
1270 quad[3][2] = 0.0f;
1271 quad[3][3] = 1.0f;
1272
1273 startScene();
1274 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1275
1276 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1277 {
1278 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1279 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1280 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1281 }
1282
1283 if (mMaskedClearSavedState != NULL)
1284 {
1285 mMaskedClearSavedState->Apply();
1286 }
1287 }
1288 else if (clearParams.mask)
1289 {
1290 DWORD dxClearFlags = 0;
1291 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1292 {
1293 dxClearFlags |= D3DCLEAR_TARGET;
1294 }
1295 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1296 {
1297 dxClearFlags |= D3DCLEAR_ZBUFFER;
1298 }
1299 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1300 {
1301 dxClearFlags |= D3DCLEAR_STENCIL;
1302 }
1303
1304 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1305 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001306}
1307
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001308void Renderer9::markAllStateDirty()
1309{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001310 mAppliedRenderTargetSerial = 0;
1311 mAppliedDepthbufferSerial = 0;
1312 mAppliedStencilbufferSerial = 0;
1313 mDepthStencilInitialized = false;
1314 mRenderTargetDescInitialized = false;
1315
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001316 mForceSetDepthStencilState = true;
1317 mForceSetRasterState = true;
1318 mForceSetBlendState = true;
1319 mForceSetScissor = true;
1320 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001321
1322 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001323}
1324
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001325void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001326{
1327 while (!mEventQueryPool.empty())
1328 {
1329 mEventQueryPool.back()->Release();
1330 mEventQueryPool.pop_back();
1331 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001332
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001333 if (mMaskedClearSavedState)
1334 {
1335 mMaskedClearSavedState->Release();
1336 mMaskedClearSavedState = NULL;
1337 }
1338
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001339 mVertexShaderCache.clear();
1340 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001341
1342 delete mVertexDataManager;
1343 mVertexDataManager = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001344}
1345
1346
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001347void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001348{
1349 mDeviceLost = true;
1350}
1351
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001352bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001353{
1354 return mDeviceLost;
1355}
1356
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001357// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001358bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001359{
1360 bool isLost = false;
1361
1362 if (mDeviceEx)
1363 {
1364 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1365 }
1366 else if (mDevice)
1367 {
1368 isLost = FAILED(mDevice->TestCooperativeLevel());
1369 }
1370 else
1371 {
1372 // No device yet, so no reset required
1373 }
1374
1375 if (isLost)
1376 {
1377 // ensure we note the device loss --
1378 // we'll probably get this done again by markDeviceLost
1379 // but best to remember it!
1380 // Note that we don't want to clear the device loss status here
1381 // -- this needs to be done by resetDevice
1382 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001383 if (notify)
1384 {
1385 mDisplay->notifyDeviceLost();
1386 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001387 }
1388
1389 return isLost;
1390}
1391
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001392bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001393{
1394 HRESULT status = D3D_OK;
1395
1396 if (mDeviceEx)
1397 {
1398 status = mDeviceEx->CheckDeviceState(NULL);
1399 }
1400 else if (mDevice)
1401 {
1402 status = mDevice->TestCooperativeLevel();
1403 }
1404
1405 switch (status)
1406 {
1407 case D3DERR_DEVICENOTRESET:
1408 case D3DERR_DEVICEHUNG:
1409 return true;
1410 default:
1411 return false;
1412 }
1413}
1414
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001415bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001416{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001417 releaseDeviceResources();
1418
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001419 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1420
1421 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001422 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001423 int attempts = 3;
1424
1425 while (lost && attempts > 0)
1426 {
1427 if (mDeviceEx)
1428 {
1429 Sleep(500); // Give the graphics driver some CPU time
1430 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1431 }
1432 else
1433 {
1434 result = mDevice->TestCooperativeLevel();
1435 while (result == D3DERR_DEVICELOST)
1436 {
1437 Sleep(100); // Give the graphics driver some CPU time
1438 result = mDevice->TestCooperativeLevel();
1439 }
1440
1441 if (result == D3DERR_DEVICENOTRESET)
1442 {
1443 result = mDevice->Reset(&presentParameters);
1444 }
1445 }
1446
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001447 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001448 attempts --;
1449 }
1450
1451 if (FAILED(result))
1452 {
1453 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1454 return false;
1455 }
1456
1457 // reset device defaults
1458 initializeDevice();
1459 mDeviceLost = false;
1460
1461 return true;
1462}
1463
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001464DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001465{
1466 return mAdapterIdentifier.VendorId;
1467}
1468
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001469const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001470{
1471 return mAdapterIdentifier.Description;
1472}
1473
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001474GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001475{
1476 return mAdapterIdentifier.DeviceIdentifier;
1477}
1478
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001479void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001480{
1481 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1482 {
1483 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1484 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1485
1486 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1487 }
1488}
1489
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001490bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001491{
1492 D3DDISPLAYMODE currentDisplayMode;
1493 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1494
1495 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1496}
1497
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001498bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001499{
1500 D3DDISPLAYMODE currentDisplayMode;
1501 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1502
1503 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1504}
1505
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001506bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001507{
1508 D3DDISPLAYMODE currentDisplayMode;
1509 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1510
1511 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1512}
1513
1514// we use INTZ for depth textures in Direct3D9
1515// we also want NULL texture support to ensure the we can make depth-only FBOs
1516// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001517bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001518{
1519 D3DDISPLAYMODE currentDisplayMode;
1520 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1521
1522 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1523 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1524 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1525 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1526
1527 return intz && null;
1528}
1529
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001530bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001531{
1532 D3DDISPLAYMODE currentDisplayMode;
1533 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1534
1535 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1536 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1537 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1538 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1539
1540 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1541 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1542 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1543 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1544
1545 if (!*filtering && !*renderable)
1546 {
1547 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1548 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1549 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1550 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1551 }
1552 else
1553 {
1554 return true;
1555 }
1556}
1557
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001558bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001559{
1560 D3DDISPLAYMODE currentDisplayMode;
1561 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1562
1563 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1564 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1565 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1566 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1567
1568 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1569 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1570 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1571 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1572
1573 if (!*filtering && !*renderable)
1574 {
1575 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1576 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1577 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1578 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1579 }
1580 else
1581 {
1582 return true;
1583 }
1584}
1585
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001586bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001587{
1588 D3DDISPLAYMODE currentDisplayMode;
1589 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1590
1591 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1592}
1593
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001594bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001595{
1596 D3DDISPLAYMODE currentDisplayMode;
1597 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1598
1599 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1600}
1601
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001602bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001603{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001604 return mSupportsTextureFilterAnisotropy;
1605}
1606
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001607float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001608{
1609 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001610 {
1611 return mDeviceCaps.MaxAnisotropy;
1612 }
1613 return 1.0f;
1614}
1615
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001616bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001617{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001618 IDirect3DQuery9 *query = allocateEventQuery();
1619 if (query)
1620 {
1621 freeEventQuery(query);
1622 return true;
1623 }
1624 else
1625 {
1626 return false;
1627 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001628 return true;
1629}
1630
1631// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1632// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001633bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001634{
1635 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1636 {
1637 return false;
1638 }
1639
1640 D3DDISPLAYMODE currentDisplayMode;
1641 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1642
1643 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1644
1645 return SUCCEEDED(result);
1646}
1647
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001648bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001649{
1650 return mSupportsNonPower2Textures;
1651}
1652
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001653bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001654{
1655 if (!mDevice)
1656 {
1657 return false;
1658 }
1659
1660 IDirect3DQuery9 *query = NULL;
1661 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1662 if (SUCCEEDED(result) && query)
1663 {
1664 query->Release();
1665 return true;
1666 }
1667 else
1668 {
1669 return false;
1670 }
1671}
1672
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001673bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001674{
1675 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1676}
1677
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001678bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001679{
1680 // PIX doesn't seem to support using share handles, so disable them.
1681 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001682 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001683}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001684
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001685bool Renderer9::getShaderModel3Support() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001686{
1687 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1688}
1689
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001690float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001691{
1692 return mDeviceCaps.MaxPointSize;
1693}
1694
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001695int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001696{
1697 return (int)mDeviceCaps.MaxTextureWidth;
1698}
1699
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001700int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001701{
1702 return (int)mDeviceCaps.MaxTextureHeight;
1703}
1704
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001705bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001706{
1707 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1708}
1709
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001710DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001711{
1712 return mDeviceCaps.DeclTypes;
1713}
1714
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001715int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001716{
1717 return mMinSwapInterval;
1718}
1719
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001720int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001721{
1722 return mMaxSwapInterval;
1723}
1724
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001725int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001726{
1727 return mMaxSupportedSamples;
1728}
1729
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001730int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001731{
1732 if (requested == 0)
1733 {
1734 return requested;
1735 }
1736
1737 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
1738 if (itr == mMultiSampleSupport.end())
1739 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00001740 if (format == D3DFMT_UNKNOWN)
1741 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001742 return -1;
1743 }
1744
1745 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
1746 {
1747 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
1748 {
1749 return i;
1750 }
1751 }
1752
1753 return -1;
1754}
1755
daniel@transgaming.coma9571682012-11-28 19:33:08 +00001756D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
1757{
1758 switch (internalformat)
1759 {
1760 case GL_DEPTH_COMPONENT16:
1761 case GL_DEPTH_COMPONENT32_OES:
1762 case GL_DEPTH24_STENCIL8_OES:
1763 return D3DFMT_INTZ;
1764 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
1765 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
1766 return D3DFMT_DXT1;
1767 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
1768 return D3DFMT_DXT3;
1769 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
1770 return D3DFMT_DXT5;
1771 case GL_RGBA32F_EXT:
1772 case GL_RGB32F_EXT:
1773 case GL_ALPHA32F_EXT:
1774 case GL_LUMINANCE32F_EXT:
1775 case GL_LUMINANCE_ALPHA32F_EXT:
1776 return D3DFMT_A32B32G32R32F;
1777 case GL_RGBA16F_EXT:
1778 case GL_RGB16F_EXT:
1779 case GL_ALPHA16F_EXT:
1780 case GL_LUMINANCE16F_EXT:
1781 case GL_LUMINANCE_ALPHA16F_EXT:
1782 return D3DFMT_A16B16G16R16F;
1783 case GL_LUMINANCE8_EXT:
1784 if (getLuminanceTextureSupport())
1785 {
1786 return D3DFMT_L8;
1787 }
1788 break;
1789 case GL_LUMINANCE8_ALPHA8_EXT:
1790 if (getLuminanceAlphaTextureSupport())
1791 {
1792 return D3DFMT_A8L8;
1793 }
1794 break;
1795 case GL_RGB8_OES:
1796 case GL_RGB565:
1797 return D3DFMT_X8R8G8B8;
1798 }
1799
1800 return D3DFMT_A8R8G8B8;
1801}
1802
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001803bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001804{
1805 bool result = false;
1806
1807 if (source && dest)
1808 {
1809 int levels = source->levelCount();
1810 for (int i = 0; i < levels; ++i)
1811 {
1812 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
1813 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
1814
1815 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1816
1817 if (srcSurf) srcSurf->Release();
1818 if (dstSurf) dstSurf->Release();
1819
1820 if (!result)
1821 return false;
1822 }
1823 }
1824
1825 return result;
1826}
1827
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001828bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001829{
1830 bool result = false;
1831
1832 if (source && dest)
1833 {
1834 int levels = source->levelCount();
1835 for (int f = 0; f < 6; f++)
1836 {
1837 for (int i = 0; i < levels; i++)
1838 {
1839 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
1840 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
1841
1842 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1843
1844 if (srcSurf) srcSurf->Release();
1845 if (dstSurf) dstSurf->Release();
1846
1847 if (!result)
1848 return false;
1849 }
1850 }
1851 }
1852
1853 return result;
1854}
1855
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001856D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001857{
1858 if (mD3d9Ex != NULL)
1859 {
1860 return D3DPOOL_DEFAULT;
1861 }
1862 else
1863 {
1864 if (!(usage & D3DUSAGE_DYNAMIC))
1865 {
1866 return D3DPOOL_MANAGED;
1867 }
1868 }
1869
1870 return D3DPOOL_DEFAULT;
1871}
1872
daniel@transgaming.com38380882012-11-28 19:36:39 +00001873bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1874 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001875{
1876 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
1877}
1878
daniel@transgaming.com38380882012-11-28 19:36:39 +00001879bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1880 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001881{
1882 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
1883}
1884
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001885bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
1886 bool blitRenderTarget, bool blitDepthStencil)
1887{
1888 endScene();
1889
1890 if (blitRenderTarget)
1891 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001892 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
1893 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
1894 RenderTarget9 *readRenderTarget = NULL;
1895 RenderTarget9 *drawRenderTarget = NULL;
1896 IDirect3DSurface9* readSurface = NULL;
1897 IDirect3DSurface9* drawSurface = NULL;
1898
1899 if (readBuffer)
1900 {
1901 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
1902 }
1903 if (drawBuffer)
1904 {
1905 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
1906 }
1907
1908 if (readRenderTarget)
1909 {
1910 readSurface = readRenderTarget->getSurface();
1911 }
1912 if (drawRenderTarget)
1913 {
1914 drawSurface = drawRenderTarget->getSurface();
1915 }
1916
1917 if (!readSurface || !drawSurface)
1918 {
1919 ERR("Failed to retrieve the render target.");
1920 return error(GL_OUT_OF_MEMORY, false);
1921 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001922
1923 RECT srcRect, dstRect;
1924 RECT *srcRectPtr = NULL;
1925 RECT *dstRectPtr = NULL;
1926
1927 if (readRect)
1928 {
1929 srcRect.left = readRect->x;
1930 srcRect.right = readRect->x + readRect->width;
1931 srcRect.top = readRect->y;
1932 srcRect.bottom = readRect->y + readRect->height;
1933 srcRectPtr = &srcRect;
1934 }
1935
1936 if (drawRect)
1937 {
1938 dstRect.left = drawRect->x;
1939 dstRect.right = drawRect->x + drawRect->width;
1940 dstRect.top = drawRect->y;
1941 dstRect.bottom = drawRect->y + drawRect->height;
1942 dstRectPtr = &dstRect;
1943 }
1944
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001945 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001946
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001947 readSurface->Release();
1948 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001949
1950 if (FAILED(result))
1951 {
1952 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1953 return false;
1954 }
1955 }
1956
1957 if (blitDepthStencil)
1958 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001959 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
1960 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
1961 RenderTarget9 *readDepthStencil = NULL;
1962 RenderTarget9 *drawDepthStencil = NULL;
1963 IDirect3DSurface9* readSurface = NULL;
1964 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001965
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001966 if (readBuffer)
1967 {
1968 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
1969 }
1970 if (drawBuffer)
1971 {
1972 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
1973 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001974
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001975 if (readDepthStencil)
1976 {
1977 readSurface = readDepthStencil->getSurface();
1978 }
1979 if (drawDepthStencil)
1980 {
1981 drawSurface = drawDepthStencil->getSurface();
1982 }
1983
1984 if (!readSurface || !drawSurface)
1985 {
1986 ERR("Failed to retrieve the render target.");
1987 return error(GL_OUT_OF_MEMORY, false);
1988 }
1989
1990 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
1991
1992 readSurface->Release();
1993 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001994
1995 if (FAILED(result))
1996 {
1997 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1998 return false;
1999 }
2000 }
2001
2002 return true;
2003}
2004
2005void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2006 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2007{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002008 RenderTarget9 *renderTarget = NULL;
2009 IDirect3DSurface9 *surface = NULL;
2010 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2011
2012 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002013 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002014 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2015 }
2016
2017 if (renderTarget)
2018 {
2019 surface = renderTarget->getSurface();
2020 }
2021
2022 if (!surface)
2023 {
2024 // context must be lost
2025 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002026 }
2027
2028 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002029 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002030
2031 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2032 {
2033 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002034 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002035 return error(GL_OUT_OF_MEMORY);
2036 }
2037
2038 HRESULT result;
2039 IDirect3DSurface9 *systemSurface = NULL;
2040 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2041 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2042 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2043 if (directToPixels)
2044 {
2045 // Use the pixels ptr as a shared handle to write directly into client's memory
2046 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2047 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2048 if (FAILED(result))
2049 {
2050 // Try again without the shared handle
2051 directToPixels = false;
2052 }
2053 }
2054
2055 if (!directToPixels)
2056 {
2057 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2058 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2059 if (FAILED(result))
2060 {
2061 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002062 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002063 return error(GL_OUT_OF_MEMORY);
2064 }
2065 }
2066
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002067 result = mDevice->GetRenderTargetData(surface, systemSurface);
2068 surface->Release();
2069 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002070
2071 if (FAILED(result))
2072 {
2073 systemSurface->Release();
2074
2075 // It turns out that D3D will sometimes produce more error
2076 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002077 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002078 return error(GL_OUT_OF_MEMORY);
2079 else
2080 {
2081 UNREACHABLE();
2082 return;
2083 }
2084
2085 }
2086
2087 if (directToPixels)
2088 {
2089 systemSurface->Release();
2090 return;
2091 }
2092
2093 RECT rect;
2094 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2095 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2096 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2097 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2098
2099 D3DLOCKED_RECT lock;
2100 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2101
2102 if (FAILED(result))
2103 {
2104 UNREACHABLE();
2105 systemSurface->Release();
2106
2107 return; // No sensible error to generate
2108 }
2109
2110 unsigned char *dest = (unsigned char*)pixels;
2111 unsigned short *dest16 = (unsigned short*)pixels;
2112
2113 unsigned char *source;
2114 int inputPitch;
2115 if (packReverseRowOrder)
2116 {
2117 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2118 inputPitch = -lock.Pitch;
2119 }
2120 else
2121 {
2122 source = (unsigned char*)lock.pBits;
2123 inputPitch = lock.Pitch;
2124 }
2125
2126 unsigned int fastPixelSize = 0;
2127
2128 if (desc.Format == D3DFMT_A8R8G8B8 &&
2129 format == GL_BGRA_EXT &&
2130 type == GL_UNSIGNED_BYTE)
2131 {
2132 fastPixelSize = 4;
2133 }
2134 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2135 format == GL_BGRA_EXT &&
2136 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2137 (desc.Format == D3DFMT_A1R5G5B5 &&
2138 format == GL_BGRA_EXT &&
2139 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2140 {
2141 fastPixelSize = 2;
2142 }
2143 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2144 format == GL_RGBA &&
2145 type == GL_HALF_FLOAT_OES)
2146 {
2147 fastPixelSize = 8;
2148 }
2149 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2150 format == GL_RGBA &&
2151 type == GL_FLOAT)
2152 {
2153 fastPixelSize = 16;
2154 }
2155
2156 for (int j = 0; j < rect.bottom - rect.top; j++)
2157 {
2158 if (fastPixelSize != 0)
2159 {
2160 // Fast path for formats which require no translation:
2161 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2162 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2163 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2164 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2165 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2166 //
2167 // Note that buffers with no alpha go through the slow path below.
2168 memcpy(dest + j * outputPitch,
2169 source + j * inputPitch,
2170 (rect.right - rect.left) * fastPixelSize);
2171 continue;
2172 }
2173
2174 for (int i = 0; i < rect.right - rect.left; i++)
2175 {
2176 float r;
2177 float g;
2178 float b;
2179 float a;
2180
2181 switch (desc.Format)
2182 {
2183 case D3DFMT_R5G6B5:
2184 {
2185 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2186
2187 a = 1.0f;
2188 b = (rgb & 0x001F) * (1.0f / 0x001F);
2189 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2190 r = (rgb & 0xF800) * (1.0f / 0xF800);
2191 }
2192 break;
2193 case D3DFMT_A1R5G5B5:
2194 {
2195 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2196
2197 a = (argb & 0x8000) ? 1.0f : 0.0f;
2198 b = (argb & 0x001F) * (1.0f / 0x001F);
2199 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2200 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2201 }
2202 break;
2203 case D3DFMT_A8R8G8B8:
2204 {
2205 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2206
2207 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2208 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2209 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2210 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2211 }
2212 break;
2213 case D3DFMT_X8R8G8B8:
2214 {
2215 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2216
2217 a = 1.0f;
2218 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2219 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2220 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2221 }
2222 break;
2223 case D3DFMT_A2R10G10B10:
2224 {
2225 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2226
2227 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2228 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2229 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2230 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2231 }
2232 break;
2233 case D3DFMT_A32B32G32R32F:
2234 {
2235 // float formats in D3D are stored rgba, rather than the other way round
2236 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2237 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2238 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2239 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2240 }
2241 break;
2242 case D3DFMT_A16B16G16R16F:
2243 {
2244 // float formats in D3D are stored rgba, rather than the other way round
2245 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2246 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2247 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2248 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2249 }
2250 break;
2251 default:
2252 UNIMPLEMENTED(); // FIXME
2253 UNREACHABLE();
2254 return;
2255 }
2256
2257 switch (format)
2258 {
2259 case GL_RGBA:
2260 switch (type)
2261 {
2262 case GL_UNSIGNED_BYTE:
2263 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2264 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2265 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2266 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2267 break;
2268 default: UNREACHABLE();
2269 }
2270 break;
2271 case GL_BGRA_EXT:
2272 switch (type)
2273 {
2274 case GL_UNSIGNED_BYTE:
2275 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2276 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2277 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2278 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2279 break;
2280 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2281 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2282 // this type is packed as follows:
2283 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2284 // --------------------------------------------------------------------------------
2285 // | 4th | 3rd | 2nd | 1st component |
2286 // --------------------------------------------------------------------------------
2287 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2288 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2289 ((unsigned short)(15 * a + 0.5f) << 12)|
2290 ((unsigned short)(15 * r + 0.5f) << 8) |
2291 ((unsigned short)(15 * g + 0.5f) << 4) |
2292 ((unsigned short)(15 * b + 0.5f) << 0);
2293 break;
2294 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2295 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2296 // this type is packed as follows:
2297 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2298 // --------------------------------------------------------------------------------
2299 // | 4th | 3rd | 2nd | 1st component |
2300 // --------------------------------------------------------------------------------
2301 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2302 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2303 ((unsigned short)( a + 0.5f) << 15) |
2304 ((unsigned short)(31 * r + 0.5f) << 10) |
2305 ((unsigned short)(31 * g + 0.5f) << 5) |
2306 ((unsigned short)(31 * b + 0.5f) << 0);
2307 break;
2308 default: UNREACHABLE();
2309 }
2310 break;
2311 case GL_RGB:
2312 switch (type)
2313 {
2314 case GL_UNSIGNED_SHORT_5_6_5:
2315 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2316 ((unsigned short)(31 * b + 0.5f) << 0) |
2317 ((unsigned short)(63 * g + 0.5f) << 5) |
2318 ((unsigned short)(31 * r + 0.5f) << 11);
2319 break;
2320 case GL_UNSIGNED_BYTE:
2321 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2322 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2323 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2324 break;
2325 default: UNREACHABLE();
2326 }
2327 break;
2328 default: UNREACHABLE();
2329 }
2330 }
2331 }
2332
2333 systemSurface->UnlockRect();
2334
2335 systemSurface->Release();
2336}
2337
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002338RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2339{
2340 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2341 IDirect3DSurface9 *surface = NULL;
2342 if (depth)
2343 {
2344 surface = swapChain9->getDepthStencil();
2345 }
2346 else
2347 {
2348 surface = swapChain9->getRenderTarget();
2349 }
2350
2351 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2352
2353 return renderTarget;
2354}
2355
2356RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2357{
2358 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2359 return renderTarget;
2360}
2361
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002362bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2363{
2364 return mBlit->boxFilter(source, dest);
2365}
2366
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002367D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002368{
2369 if (mD3d9Ex != NULL)
2370 {
2371 return D3DPOOL_DEFAULT;
2372 }
2373 else
2374 {
2375 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2376 {
2377 return D3DPOOL_MANAGED;
2378 }
2379 }
2380
2381 return D3DPOOL_DEFAULT;
2382}
2383
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002384bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2385{
2386 if (source && dest)
2387 {
2388 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2389 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2390
2391 if (fromManaged)
2392 {
2393 D3DSURFACE_DESC desc;
2394 source->GetDesc(&desc);
2395
2396 IDirect3DSurface9 *surf = 0;
2397 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2398
2399 if (SUCCEEDED(result))
2400 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002401 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002402 result = device->UpdateSurface(surf, NULL, dest, NULL);
2403 surf->Release();
2404 }
2405 }
2406 else
2407 {
2408 endScene();
2409 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2410 }
2411
2412 if (FAILED(result))
2413 {
2414 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2415 return false;
2416 }
2417 }
2418
2419 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002420}
2421
2422VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
2423{
2424 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2425 {
2426 mVertexDeclCache[i].vertexDeclaration = NULL;
2427 mVertexDeclCache[i].lruCount = 0;
2428 }
2429
2430 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2431 {
2432 mAppliedVBs[i].serial = 0;
2433 }
2434
2435 mLastSetVDecl = NULL;
2436 mInstancingEnabled = true;
2437}
2438
2439VertexDeclarationCache::~VertexDeclarationCache()
2440{
2441 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2442 {
2443 if (mVertexDeclCache[i].vertexDeclaration)
2444 {
2445 mVertexDeclCache[i].vertexDeclaration->Release();
2446 }
2447 }
2448}
2449
2450GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, gl::TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
2451{
2452 *repeatDraw = 1;
2453
2454 int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
2455 int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
2456
2457 if (instances > 0)
2458 {
2459 // Find an indexed attribute to be mapped to D3D stream 0
2460 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2461 {
2462 if (attributes[i].active)
2463 {
2464 if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
2465 {
2466 if (attributes[i].divisor == 0)
2467 {
2468 indexedAttribute = i;
2469 }
2470 }
2471 else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2472 {
2473 if (attributes[i].divisor != 0)
2474 {
2475 instancedAttribute = i;
2476 }
2477 }
2478 else break; // Found both an indexed and instanced attribute
2479 }
2480 }
2481
2482 if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
2483 {
2484 return GL_INVALID_OPERATION;
2485 }
2486 }
2487
2488 D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
2489 D3DVERTEXELEMENT9 *element = &elements[0];
2490
2491 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2492 {
2493 if (attributes[i].active)
2494 {
2495 int stream = i;
2496
2497 if (instances > 0)
2498 {
2499 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
2500 if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2501 {
2502 *repeatDraw = instances;
2503 }
2504 else
2505 {
2506 if (i == indexedAttribute)
2507 {
2508 stream = 0;
2509 }
2510 else if (i == 0)
2511 {
2512 stream = indexedAttribute;
2513 }
2514
2515 UINT frequency = 1;
2516
2517 if (attributes[i].divisor == 0)
2518 {
2519 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
2520 }
2521 else
2522 {
2523 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
2524 }
2525
2526 device->SetStreamSourceFreq(stream, frequency);
2527 mInstancingEnabled = true;
2528 }
2529 }
2530
2531 if (mAppliedVBs[stream].serial != attributes[i].serial ||
2532 mAppliedVBs[stream].stride != attributes[i].stride ||
2533 mAppliedVBs[stream].offset != attributes[i].offset)
2534 {
2535 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
2536 mAppliedVBs[stream].serial = attributes[i].serial;
2537 mAppliedVBs[stream].stride = attributes[i].stride;
2538 mAppliedVBs[stream].offset = attributes[i].offset;
2539 }
2540
2541 element->Stream = stream;
2542 element->Offset = 0;
2543 element->Type = attributes[i].type;
2544 element->Method = D3DDECLMETHOD_DEFAULT;
2545 element->Usage = D3DDECLUSAGE_TEXCOORD;
2546 element->UsageIndex = programBinary->getSemanticIndex(i);
2547 element++;
2548 }
2549 }
2550
2551 if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2552 {
2553 if (mInstancingEnabled)
2554 {
2555 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2556 {
2557 device->SetStreamSourceFreq(i, 1);
2558 }
2559
2560 mInstancingEnabled = false;
2561 }
2562 }
2563
2564 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
2565 *(element++) = end;
2566
2567 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2568 {
2569 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
2570 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
2571 {
2572 entry->lruCount = ++mMaxLru;
2573 if(entry->vertexDeclaration != mLastSetVDecl)
2574 {
2575 device->SetVertexDeclaration(entry->vertexDeclaration);
2576 mLastSetVDecl = entry->vertexDeclaration;
2577 }
2578
2579 return GL_NO_ERROR;
2580 }
2581 }
2582
2583 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
2584
2585 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2586 {
2587 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
2588 {
2589 lastCache = &mVertexDeclCache[i];
2590 }
2591 }
2592
2593 if (lastCache->vertexDeclaration != NULL)
2594 {
2595 lastCache->vertexDeclaration->Release();
2596 lastCache->vertexDeclaration = NULL;
2597 // mLastSetVDecl is set to the replacement, so we don't have to worry
2598 // about it.
2599 }
2600
2601 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
2602 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
2603 device->SetVertexDeclaration(lastCache->vertexDeclaration);
2604 mLastSetVDecl = lastCache->vertexDeclaration;
2605 lastCache->lruCount = ++mMaxLru;
2606
2607 return GL_NO_ERROR;
2608}
2609
2610void VertexDeclarationCache::markStateDirty()
2611{
2612 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2613 {
2614 mAppliedVBs[i].serial = 0;
2615 }
2616
2617 mLastSetVDecl = NULL;
2618 mInstancingEnabled = true; // Forces it to be disabled when not used
2619}
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002620
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002621}