blob: 8bf6d17e8a4e45330d0354c797c2f5758ebf0d9a [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.com2507f412012-10-31 18:46:48 +000014#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000015#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000016#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +000017#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000018#include "libGLESv2/renderer/Image.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000019#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000020
daniel@transgaming.com3281f972012-10-31 18:38:51 +000021#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000022#include "libEGL/Display.h"
23
daniel@transgaming.com621ce052012-10-31 17:52:29 +000024// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
25#define REF_RAST 0
26
27// The "Debug This Pixel..." feature in PIX often fails when using the
28// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
29// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
30#if !defined(ANGLE_ENABLE_D3D9EX)
31// Enables use of the IDirect3D9Ex interface, when available
32#define ANGLE_ENABLE_D3D9EX 1
33#endif // !defined(ANGLE_ENABLE_D3D9EX)
34
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000035namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000036{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000037static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000038 {
39 D3DFMT_A1R5G5B5,
40 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
41 D3DFMT_A8R8G8B8,
42 D3DFMT_R5G6B5,
43 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
44 D3DFMT_X8R8G8B8
45 };
46
daniel@transgaming.com222ee082012-11-28 19:31:49 +000047static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000048 {
49 D3DFMT_UNKNOWN,
50 // D3DFMT_D16_LOCKABLE,
51 D3DFMT_D32,
52 // D3DFMT_D15S1,
53 D3DFMT_D24S8,
54 D3DFMT_D24X8,
55 // D3DFMT_D24X4S4,
56 D3DFMT_D16,
57 // D3DFMT_D32F_LOCKABLE,
58 // D3DFMT_D24FS8
59 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000060
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000061Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000062{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000063 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000064
65 mD3d9 = NULL;
66 mD3d9Ex = NULL;
67 mDevice = NULL;
68 mDeviceEx = NULL;
69 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000070 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071
72 mAdapter = D3DADAPTER_DEFAULT;
73
74 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
75 mDeviceType = D3DDEVTYPE_REF;
76 #else
77 mDeviceType = D3DDEVTYPE_HAL;
78 #endif
79
80 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000081
82 mMaxSupportedSamples = 0;
daniel@transgaming.com8a8b24c2012-11-28 19:36:26 +000083
84 mForceSetDepthStencilState = true;
85 mForceSetRasterState = true;
86 mForceSetBlendState = true;
87 mForceSetScissor = true;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000088}
89
daniel@transgaming.com2507f412012-10-31 18:46:48 +000090Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +000091{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000092 releaseDeviceResources();
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000093
94 delete mBlit;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000095
daniel@transgaming.com621ce052012-10-31 17:52:29 +000096 if (mDevice)
97 {
98 // 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 +000099 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000100 {
101 resetDevice();
102 }
103
104 mDevice->Release();
105 mDevice = NULL;
106 }
107
108 if (mDeviceEx)
109 {
110 mDeviceEx->Release();
111 mDeviceEx = NULL;
112 }
113
114 if (mD3d9)
115 {
116 mD3d9->Release();
117 mD3d9 = NULL;
118 }
119
120 if (mDeviceWindow)
121 {
122 DestroyWindow(mDeviceWindow);
123 mDeviceWindow = NULL;
124 }
125
126 if (mD3d9Ex)
127 {
128 mD3d9Ex->Release();
129 mD3d9Ex = NULL;
130 }
131
132 if (mD3d9Module)
133 {
134 mD3d9Module = NULL;
135 }
136
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000137 while (!mMultiSampleSupport.empty())
138 {
139 delete [] mMultiSampleSupport.begin()->second;
140 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
141 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000142}
143
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000144EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000145{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000146 if (mSoftwareDevice)
147 {
148 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
149 }
150 else
151 {
152 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
153 }
154
155 if (mD3d9Module == NULL)
156 {
157 ERR("No D3D9 module found - aborting!\n");
158 return EGL_NOT_INITIALIZED;
159 }
160
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000161 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
162 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
163
164 // Use Direct3D9Ex if available. Among other things, this version is less
165 // inclined to report a lost context, for example when the user switches
166 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
167 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
168 {
169 ASSERT(mD3d9Ex);
170 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
171 ASSERT(mD3d9);
172 }
173 else
174 {
175 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
176 }
177
178 if (!mD3d9)
179 {
180 ERR("Could not create D3D9 device - aborting!\n");
181 return EGL_NOT_INITIALIZED;
182 }
183 if (mDc != NULL)
184 {
185 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
186 }
187
188 HRESULT result;
189
190 // Give up on getting device caps after about one second.
191 for (int i = 0; i < 10; ++i)
192 {
193 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
194 if (SUCCEEDED(result))
195 {
196 break;
197 }
198 else if (result == D3DERR_NOTAVAILABLE)
199 {
200 Sleep(100); // Give the driver some time to initialize/recover
201 }
202 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
203 {
204 ERR("failed to get device caps (0x%x)\n", result);
205 return EGL_NOT_INITIALIZED;
206 }
207 }
208
209 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
210 {
211 ERR("Renderer does not support PS 2.0. aborting!\n");
212 return EGL_NOT_INITIALIZED;
213 }
214
215 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
216 // This is required by Texture2D::convertToRenderTarget.
217 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
218 {
219 ERR("Renderer does not support stretctrect from textures!\n");
220 return EGL_NOT_INITIALIZED;
221 }
222
223 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
224
225 // ATI cards on XP have problems with non-power-of-two textures.
226 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
227 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
228 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
229 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
230
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000231 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
232 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
233
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000234 mMinSwapInterval = 4;
235 mMaxSwapInterval = 0;
236
237 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
238 {
239 mMinSwapInterval = std::min(mMinSwapInterval, 0);
240 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
241 }
242 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
243 {
244 mMinSwapInterval = std::min(mMinSwapInterval, 1);
245 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
246 }
247 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
248 {
249 mMinSwapInterval = std::min(mMinSwapInterval, 2);
250 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
251 }
252 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
253 {
254 mMinSwapInterval = std::min(mMinSwapInterval, 3);
255 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
256 }
257 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
258 {
259 mMinSwapInterval = std::min(mMinSwapInterval, 4);
260 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
261 }
262
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000263 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000264 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000265 {
266 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000267 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
268 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000269
270 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
271 {
272 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
273 {
274 max = j;
275 }
276 }
277 }
278
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000279 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000280 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000281 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000282 continue;
283
284 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000285 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
286 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000287
288 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
289 {
290 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
291 {
292 max = j;
293 }
294 }
295 }
296
297 mMaxSupportedSamples = max;
298
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000299 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
300 static const TCHAR className[] = TEXT("STATIC");
301
302 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
303
304 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
305 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
306
307 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
308 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
309 {
310 return EGL_BAD_ALLOC;
311 }
312
313 if (FAILED(result))
314 {
315 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
316
317 if (FAILED(result))
318 {
319 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
320 return EGL_BAD_ALLOC;
321 }
322 }
323
324 if (mD3d9Ex)
325 {
326 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
327 ASSERT(SUCCEEDED(result));
328 }
329
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000330 mVertexShaderCache.initialize(mDevice);
331 mPixelShaderCache.initialize(mDevice);
332
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000333 initializeDevice();
334
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +0000335 mBlit = new Blit(this);
336
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000337 return EGL_SUCCESS;
338}
339
340// do any one-time device initialization
341// NOTE: this is also needed after a device lost/reset
342// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000343void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000344{
345 // Permanent non-default states
346 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
347 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
348
349 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
350 {
351 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
352 }
353 else
354 {
355 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
356 }
357
358 mSceneStarted = false;
359}
360
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000361D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000362{
363 D3DPRESENT_PARAMETERS presentParameters = {0};
364
365 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
366 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
367 presentParameters.BackBufferCount = 1;
368 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
369 presentParameters.BackBufferWidth = 1;
370 presentParameters.BackBufferHeight = 1;
371 presentParameters.EnableAutoDepthStencil = FALSE;
372 presentParameters.Flags = 0;
373 presentParameters.hDeviceWindow = mDeviceWindow;
374 presentParameters.MultiSampleQuality = 0;
375 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
376 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
377 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
378 presentParameters.Windowed = TRUE;
379
380 return presentParameters;
381}
382
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000383int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000384{
385 D3DDISPLAYMODE currentDisplayMode;
386 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
387
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000388 int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
389 int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000390 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
391 int numConfigs = 0;
392
393 for (int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
394 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000395 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000396
397 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
398
399 if (SUCCEEDED(result))
400 {
401 for (int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
402 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000403 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000404 HRESULT result = D3D_OK;
405
406 if(depthStencilFormat != D3DFMT_UNKNOWN)
407 {
408 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
409 }
410
411 if (SUCCEEDED(result))
412 {
413 if(depthStencilFormat != D3DFMT_UNKNOWN)
414 {
415 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
416 }
417
418 if (SUCCEEDED(result))
419 {
420 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000421 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
422 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000423 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
424 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
425
426 (*configDescList)[numConfigs++] = newConfig;
427 }
428 }
429 }
430 }
431 }
432
433 return numConfigs;
434}
435
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000436void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000437{
438 delete [] (configDescList);
439}
440
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000441void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000442{
443 if (!mSceneStarted)
444 {
445 long result = mDevice->BeginScene();
446 if (SUCCEEDED(result)) {
447 // This is defensive checking against the device being
448 // lost at unexpected times.
449 mSceneStarted = true;
450 }
451 }
452}
453
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000454void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000455{
456 if (mSceneStarted)
457 {
458 // EndScene can fail if the device was lost, for example due
459 // to a TDR during a draw call.
460 mDevice->EndScene();
461 mSceneStarted = false;
462 }
463}
464
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000465// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000466void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000467{
468 HRESULT result;
469
470 IDirect3DQuery9* query = allocateEventQuery();
471 if (!query)
472 {
473 return;
474 }
475
476 result = query->Issue(D3DISSUE_END);
477 ASSERT(SUCCEEDED(result));
478
479 do
480 {
481 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
482
483 if(block && result == S_FALSE)
484 {
485 // Keep polling, but allow other threads to do something useful first
486 Sleep(0);
487 // explicitly check for device loss
488 // some drivers seem to return S_FALSE even if the device is lost
489 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000490 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000491 {
492 result = D3DERR_DEVICELOST;
493 }
494 }
495 }
496 while(block && result == S_FALSE);
497
498 freeEventQuery(query);
499
500 if (isDeviceLostError(result))
501 {
502 mDisplay->notifyDeviceLost();
503 }
504}
505
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000506SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
507{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000508 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000509}
510
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000511// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000512IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000513{
514 IDirect3DQuery9 *query = NULL;
515
516 if (mEventQueryPool.empty())
517 {
518 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
519 ASSERT(SUCCEEDED(result));
520 }
521 else
522 {
523 query = mEventQueryPool.back();
524 mEventQueryPool.pop_back();
525 }
526
527 return query;
528}
529
530// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000531void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000532{
533 if (mEventQueryPool.size() > 1000)
534 {
535 query->Release();
536 }
537 else
538 {
539 mEventQueryPool.push_back(query);
540 }
541}
542
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000543IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000544{
545 return mVertexShaderCache.create(function, length);
546}
547
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000548IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000549{
550 return mPixelShaderCache.create(function, length);
551}
552
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000553HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
554{
555 D3DPOOL Pool = getBufferPool(Usage);
556 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
557}
558
559HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
560{
561 D3DPOOL Pool = getBufferPool(Usage);
562 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
563}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000564
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000565void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000566{
567 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
568 int d3dSampler = index + d3dSamplerOffset;
569
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000570 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
571 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000572
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000573 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000574 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000575 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000576 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
577 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
578 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
579 if (mSupportsTextureFilterAnisotropy)
580 {
581 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
582 }
583}
584
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000585void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000586{
587 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
588 int d3dSampler = index + d3dSamplerOffset;
589 IDirect3DBaseTexture9 *d3dTexture = NULL;
590
591 if (texture)
592 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000593 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000594 if (texStorage)
595 {
596 d3dTexture = texStorage->getBaseTexture();
597 }
598 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000599 // in the texture class and we're unexpectedly missing the d3d texture
600 ASSERT(d3dTexture != NULL);
601 }
602
603 mDevice->SetTexture(d3dSampler, d3dTexture);
604}
605
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000606void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
607{
608 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
609 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
610
611 if (rasterStateChanged)
612 {
613 // Set the cull mode
614 if (rasterState.cullFace)
615 {
616 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
617 }
618 else
619 {
620 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
621 }
622
623 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
624
625 mCurRasterState = rasterState;
626 }
627
628 if (rasterStateChanged || depthSizeChanged)
629 {
630 if (rasterState.polygonOffsetFill)
631 {
632 if (depthSize > 0)
633 {
634 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
635
636 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
637 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
638 }
639 }
640 else
641 {
642 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
643 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
644 }
645
646 mCurDepthSize = depthSize;
647 }
648
649 mForceSetRasterState = false;
650}
651
652void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
653{
654 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
655 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
656 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
657
658 if (blendStateChanged || blendColorChanged)
659 {
660 if (blendState.blend)
661 {
662 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
663
664 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
665 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
666 {
667 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
668 }
669 else
670 {
671 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
672 gl::unorm<8>(blendColor.alpha),
673 gl::unorm<8>(blendColor.alpha),
674 gl::unorm<8>(blendColor.alpha)));
675 }
676
677 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
678 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
679 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
680
681 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
682 blendState.destBlendRGB != blendState.destBlendAlpha ||
683 blendState.blendEquationRGB != blendState.blendEquationAlpha)
684 {
685 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
686
687 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
688 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
689 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
690 }
691 else
692 {
693 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
694 }
695 }
696 else
697 {
698 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
699 }
700
701 if (blendState.sampleAlphaToCoverage)
702 {
703 FIXME("Sample alpha to coverage is unimplemented.");
704 }
705
706 // Set the color mask
707 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
708 // Apparently some ATI cards have a bug where a draw with a zero color
709 // write mask can cause later draws to have incorrect results. Instead,
710 // set a nonzero color write mask but modify the blend state so that no
711 // drawing is done.
712 // http://code.google.com/p/angleproject/issues/detail?id=169
713
714 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
715 blendState.colorMaskBlue, blendState.colorMaskAlpha);
716 if (colorMask == 0 && !zeroColorMaskAllowed)
717 {
718 // Enable green channel, but set blending so nothing will be drawn.
719 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
720 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
721
722 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
723 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
724 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
725 }
726 else
727 {
728 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
729 }
730
731 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
732
733 mCurBlendState = blendState;
734 mCurBlendColor = blendColor;
735 }
736
737 if (sampleMaskChanged)
738 {
739 // Set the multisample mask
740 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
741 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
742
743 mCurSampleMask = sampleMask;
744 }
745
746 mForceSetBlendState = false;
747}
748
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000749void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
750 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000751{
752 bool depthStencilStateChanged = mForceSetDepthStencilState ||
753 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000754 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
755 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000756 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
757 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
758
759 if (depthStencilStateChanged)
760 {
761 if (depthStencilState.depthTest)
762 {
763 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
764 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
765 }
766 else
767 {
768 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
769 }
770
771 mCurDepthStencilState = depthStencilState;
772 }
773
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000774 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000775 {
776 if (depthStencilState.stencilTest && stencilSize > 0)
777 {
778 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
779 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
780
781 // FIXME: Unsupported by D3D9
782 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
783 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
784 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
785 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000786 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000787 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
788 {
789 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
790 return error(GL_INVALID_OPERATION);
791 }
792
793 // get the maximum size of the stencil ref
794 GLuint maxStencil = (1 << stencilSize) - 1;
795
796 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
797 depthStencilState.stencilWritemask);
798 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
799 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
800
801 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000802 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000803 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
804 depthStencilState.stencilMask);
805
806 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
807 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
808 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
809 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
810 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
811 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
812
813 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
814 depthStencilState.stencilBackWritemask);
815 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
816 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
817
818 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000819 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000820 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
821 depthStencilState.stencilBackMask);
822
823 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
824 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
825 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
826 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
827 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
828 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
829 }
830 else
831 {
832 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
833 }
834
835 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
836
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000837 mCurStencilRef = stencilRef;
838 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000839 mCurFrontFaceCCW = frontFaceCCW;
840 mCurStencilSize = stencilSize;
841 }
842
843 mForceSetDepthStencilState = false;
844}
845
846void Renderer9::setScissorRectangle(const gl::Rectangle& scissor, unsigned int renderTargetWidth,
847 unsigned int renderTargetHeight)
848{
849 bool renderTargetSizedChanged = mForceSetScissor ||
850 renderTargetWidth != mCurRenderTargetWidth ||
851 renderTargetHeight != mCurRenderTargetHeight;
852 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
853
854 if (renderTargetSizedChanged || scissorChanged)
855 {
856 RECT rect;
857 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(renderTargetWidth));
858 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(renderTargetWidth));
859 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(renderTargetWidth));
860 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(renderTargetWidth));
861 mDevice->SetScissorRect(&rect);
862
863 mCurScissor = scissor;
864 mCurRenderTargetWidth = renderTargetWidth;
865 mCurRenderTargetHeight = renderTargetHeight;
866 }
867
868 mForceSetScissor = false;
869}
870
871void Renderer9::applyRenderTarget(gl::Framebuffer *frameBuffer)
872{
873 mForceSetScissor = true;
874
875 // TODO
876}
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000877
daniel@transgaming.comd084c622012-11-28 19:36:05 +0000878void Renderer9::clear(GLbitfield mask, const gl::Color &colorClear, float depthClear, int stencilClear,
879 gl::Framebuffer *frameBuffer)
880{
881 mForceSetDepthStencilState = true;
882
883 // TODO
884}
885
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000886void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000887{
888 while (!mEventQueryPool.empty())
889 {
890 mEventQueryPool.back()->Release();
891 mEventQueryPool.pop_back();
892 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000893
894 mVertexShaderCache.clear();
895 mPixelShaderCache.clear();
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000896}
897
898
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000899void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000900{
901 mDeviceLost = true;
902}
903
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000904bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000905{
906 return mDeviceLost;
907}
908
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000909// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000910bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000911{
912 bool isLost = false;
913
914 if (mDeviceEx)
915 {
916 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
917 }
918 else if (mDevice)
919 {
920 isLost = FAILED(mDevice->TestCooperativeLevel());
921 }
922 else
923 {
924 // No device yet, so no reset required
925 }
926
927 if (isLost)
928 {
929 // ensure we note the device loss --
930 // we'll probably get this done again by markDeviceLost
931 // but best to remember it!
932 // Note that we don't want to clear the device loss status here
933 // -- this needs to be done by resetDevice
934 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000935 if (notify)
936 {
937 mDisplay->notifyDeviceLost();
938 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000939 }
940
941 return isLost;
942}
943
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000944bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000945{
946 HRESULT status = D3D_OK;
947
948 if (mDeviceEx)
949 {
950 status = mDeviceEx->CheckDeviceState(NULL);
951 }
952 else if (mDevice)
953 {
954 status = mDevice->TestCooperativeLevel();
955 }
956
957 switch (status)
958 {
959 case D3DERR_DEVICENOTRESET:
960 case D3DERR_DEVICEHUNG:
961 return true;
962 default:
963 return false;
964 }
965}
966
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000967bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000968{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000969 releaseDeviceResources();
970
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000971 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
972
973 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000974 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000975 int attempts = 3;
976
977 while (lost && attempts > 0)
978 {
979 if (mDeviceEx)
980 {
981 Sleep(500); // Give the graphics driver some CPU time
982 result = mDeviceEx->ResetEx(&presentParameters, NULL);
983 }
984 else
985 {
986 result = mDevice->TestCooperativeLevel();
987 while (result == D3DERR_DEVICELOST)
988 {
989 Sleep(100); // Give the graphics driver some CPU time
990 result = mDevice->TestCooperativeLevel();
991 }
992
993 if (result == D3DERR_DEVICENOTRESET)
994 {
995 result = mDevice->Reset(&presentParameters);
996 }
997 }
998
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000999 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001000 attempts --;
1001 }
1002
1003 if (FAILED(result))
1004 {
1005 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1006 return false;
1007 }
1008
1009 // reset device defaults
1010 initializeDevice();
1011 mDeviceLost = false;
1012
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001013 mForceSetDepthStencilState = true;
1014 mForceSetRasterState = true;
1015 mForceSetBlendState = true;
1016 mForceSetScissor = true;
1017
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001018 return true;
1019}
1020
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001021DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001022{
1023 return mAdapterIdentifier.VendorId;
1024}
1025
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001026const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001027{
1028 return mAdapterIdentifier.Description;
1029}
1030
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001031GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001032{
1033 return mAdapterIdentifier.DeviceIdentifier;
1034}
1035
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001036void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001037{
1038 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1039 {
1040 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1041 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1042
1043 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1044 }
1045}
1046
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001047bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001048{
1049 D3DDISPLAYMODE currentDisplayMode;
1050 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1051
1052 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1053}
1054
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001055bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001056{
1057 D3DDISPLAYMODE currentDisplayMode;
1058 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1059
1060 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1061}
1062
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001063bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001064{
1065 D3DDISPLAYMODE currentDisplayMode;
1066 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1067
1068 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1069}
1070
1071// we use INTZ for depth textures in Direct3D9
1072// we also want NULL texture support to ensure the we can make depth-only FBOs
1073// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001074bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001075{
1076 D3DDISPLAYMODE currentDisplayMode;
1077 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1078
1079 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1080 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1081 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1082 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1083
1084 return intz && null;
1085}
1086
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001087bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001088{
1089 D3DDISPLAYMODE currentDisplayMode;
1090 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1091
1092 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1093 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1094 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1095 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1096
1097 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1098 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1099 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1100 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1101
1102 if (!*filtering && !*renderable)
1103 {
1104 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1105 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1106 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1107 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1108 }
1109 else
1110 {
1111 return true;
1112 }
1113}
1114
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001115bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001116{
1117 D3DDISPLAYMODE currentDisplayMode;
1118 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1119
1120 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1121 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1122 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1123 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1124
1125 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1126 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1127 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1128 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1129
1130 if (!*filtering && !*renderable)
1131 {
1132 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1133 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1134 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1135 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1136 }
1137 else
1138 {
1139 return true;
1140 }
1141}
1142
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001143bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001144{
1145 D3DDISPLAYMODE currentDisplayMode;
1146 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1147
1148 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1149}
1150
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001151bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001152{
1153 D3DDISPLAYMODE currentDisplayMode;
1154 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1155
1156 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1157}
1158
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001159bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001160{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001161 return mSupportsTextureFilterAnisotropy;
1162}
1163
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001164float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001165{
1166 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001167 {
1168 return mDeviceCaps.MaxAnisotropy;
1169 }
1170 return 1.0f;
1171}
1172
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001173bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001174{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001175 IDirect3DQuery9 *query = allocateEventQuery();
1176 if (query)
1177 {
1178 freeEventQuery(query);
1179 return true;
1180 }
1181 else
1182 {
1183 return false;
1184 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001185 return true;
1186}
1187
1188// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1189// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001190bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001191{
1192 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1193 {
1194 return false;
1195 }
1196
1197 D3DDISPLAYMODE currentDisplayMode;
1198 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1199
1200 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1201
1202 return SUCCEEDED(result);
1203}
1204
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001205bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001206{
1207 return mSupportsNonPower2Textures;
1208}
1209
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001210bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001211{
1212 if (!mDevice)
1213 {
1214 return false;
1215 }
1216
1217 IDirect3DQuery9 *query = NULL;
1218 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1219 if (SUCCEEDED(result) && query)
1220 {
1221 query->Release();
1222 return true;
1223 }
1224 else
1225 {
1226 return false;
1227 }
1228}
1229
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001230bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001231{
1232 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1233}
1234
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001235bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001236{
1237 // PIX doesn't seem to support using share handles, so disable them.
1238 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001239 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001240}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001241
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001242bool Renderer9::getShaderModel3Support() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001243{
1244 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1245}
1246
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001247float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001248{
1249 return mDeviceCaps.MaxPointSize;
1250}
1251
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001252int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001253{
1254 return (int)mDeviceCaps.MaxTextureWidth;
1255}
1256
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001257int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001258{
1259 return (int)mDeviceCaps.MaxTextureHeight;
1260}
1261
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001262bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001263{
1264 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1265}
1266
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001267DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001268{
1269 return mDeviceCaps.DeclTypes;
1270}
1271
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001272int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001273{
1274 return mMinSwapInterval;
1275}
1276
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001277int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001278{
1279 return mMaxSwapInterval;
1280}
1281
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001282int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001283{
1284 return mMaxSupportedSamples;
1285}
1286
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001287int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001288{
1289 if (requested == 0)
1290 {
1291 return requested;
1292 }
1293
1294 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
1295 if (itr == mMultiSampleSupport.end())
1296 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00001297 if (format == D3DFMT_UNKNOWN)
1298 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001299 return -1;
1300 }
1301
1302 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
1303 {
1304 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
1305 {
1306 return i;
1307 }
1308 }
1309
1310 return -1;
1311}
1312
daniel@transgaming.coma9571682012-11-28 19:33:08 +00001313D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
1314{
1315 switch (internalformat)
1316 {
1317 case GL_DEPTH_COMPONENT16:
1318 case GL_DEPTH_COMPONENT32_OES:
1319 case GL_DEPTH24_STENCIL8_OES:
1320 return D3DFMT_INTZ;
1321 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
1322 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
1323 return D3DFMT_DXT1;
1324 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
1325 return D3DFMT_DXT3;
1326 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
1327 return D3DFMT_DXT5;
1328 case GL_RGBA32F_EXT:
1329 case GL_RGB32F_EXT:
1330 case GL_ALPHA32F_EXT:
1331 case GL_LUMINANCE32F_EXT:
1332 case GL_LUMINANCE_ALPHA32F_EXT:
1333 return D3DFMT_A32B32G32R32F;
1334 case GL_RGBA16F_EXT:
1335 case GL_RGB16F_EXT:
1336 case GL_ALPHA16F_EXT:
1337 case GL_LUMINANCE16F_EXT:
1338 case GL_LUMINANCE_ALPHA16F_EXT:
1339 return D3DFMT_A16B16G16R16F;
1340 case GL_LUMINANCE8_EXT:
1341 if (getLuminanceTextureSupport())
1342 {
1343 return D3DFMT_L8;
1344 }
1345 break;
1346 case GL_LUMINANCE8_ALPHA8_EXT:
1347 if (getLuminanceAlphaTextureSupport())
1348 {
1349 return D3DFMT_A8L8;
1350 }
1351 break;
1352 case GL_RGB8_OES:
1353 case GL_RGB565:
1354 return D3DFMT_X8R8G8B8;
1355 }
1356
1357 return D3DFMT_A8R8G8B8;
1358}
1359
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001360bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001361{
1362 bool result = false;
1363
1364 if (source && dest)
1365 {
1366 int levels = source->levelCount();
1367 for (int i = 0; i < levels; ++i)
1368 {
1369 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
1370 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
1371
1372 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1373
1374 if (srcSurf) srcSurf->Release();
1375 if (dstSurf) dstSurf->Release();
1376
1377 if (!result)
1378 return false;
1379 }
1380 }
1381
1382 return result;
1383}
1384
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001385bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001386{
1387 bool result = false;
1388
1389 if (source && dest)
1390 {
1391 int levels = source->levelCount();
1392 for (int f = 0; f < 6; f++)
1393 {
1394 for (int i = 0; i < levels; i++)
1395 {
1396 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
1397 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
1398
1399 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1400
1401 if (srcSurf) srcSurf->Release();
1402 if (dstSurf) dstSurf->Release();
1403
1404 if (!result)
1405 return false;
1406 }
1407 }
1408 }
1409
1410 return result;
1411}
1412
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001413D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001414{
1415 if (mD3d9Ex != NULL)
1416 {
1417 return D3DPOOL_DEFAULT;
1418 }
1419 else
1420 {
1421 if (!(usage & D3DUSAGE_DYNAMIC))
1422 {
1423 return D3DPOOL_MANAGED;
1424 }
1425 }
1426
1427 return D3DPOOL_DEFAULT;
1428}
1429
daniel@transgaming.com38380882012-11-28 19:36:39 +00001430bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1431 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001432{
1433 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
1434}
1435
daniel@transgaming.com38380882012-11-28 19:36:39 +00001436bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1437 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001438{
1439 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
1440}
1441
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001442bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
1443 bool blitRenderTarget, bool blitDepthStencil)
1444{
1445 endScene();
1446
1447 if (blitRenderTarget)
1448 {
1449 IDirect3DSurface9* readRenderTarget = readFramebuffer->getRenderTarget();
1450 IDirect3DSurface9* drawRenderTarget = drawFramebuffer->getRenderTarget();
1451
1452 RECT srcRect, dstRect;
1453 RECT *srcRectPtr = NULL;
1454 RECT *dstRectPtr = NULL;
1455
1456 if (readRect)
1457 {
1458 srcRect.left = readRect->x;
1459 srcRect.right = readRect->x + readRect->width;
1460 srcRect.top = readRect->y;
1461 srcRect.bottom = readRect->y + readRect->height;
1462 srcRectPtr = &srcRect;
1463 }
1464
1465 if (drawRect)
1466 {
1467 dstRect.left = drawRect->x;
1468 dstRect.right = drawRect->x + drawRect->width;
1469 dstRect.top = drawRect->y;
1470 dstRect.bottom = drawRect->y + drawRect->height;
1471 dstRectPtr = &dstRect;
1472 }
1473
1474 HRESULT result = mDevice->StretchRect(readRenderTarget, srcRectPtr, drawRenderTarget, dstRectPtr, D3DTEXF_NONE);
1475
1476 readRenderTarget->Release();
1477 drawRenderTarget->Release();
1478
1479 if (FAILED(result))
1480 {
1481 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1482 return false;
1483 }
1484 }
1485
1486 if (blitDepthStencil)
1487 {
1488 IDirect3DSurface9* readDepthStencil = readFramebuffer->getDepthStencil();
1489 IDirect3DSurface9* drawDepthStencil = drawFramebuffer->getDepthStencil();
1490
1491 HRESULT result = mDevice->StretchRect(readDepthStencil, NULL, drawDepthStencil, NULL, D3DTEXF_NONE);
1492
1493 readDepthStencil->Release();
1494 drawDepthStencil->Release();
1495
1496 if (FAILED(result))
1497 {
1498 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1499 return false;
1500 }
1501 }
1502
1503 return true;
1504}
1505
1506void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
1507 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
1508{
1509 IDirect3DSurface9 *renderTarget = framebuffer->getRenderTarget();
1510 if (!renderTarget)
1511 {
1512 return; // Context must be lost, return silently
1513 }
1514
1515 D3DSURFACE_DESC desc;
1516 renderTarget->GetDesc(&desc);
1517
1518 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
1519 {
1520 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
1521 renderTarget->Release();
1522 return error(GL_OUT_OF_MEMORY);
1523 }
1524
1525 HRESULT result;
1526 IDirect3DSurface9 *systemSurface = NULL;
1527 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
1528 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
1529 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
1530 if (directToPixels)
1531 {
1532 // Use the pixels ptr as a shared handle to write directly into client's memory
1533 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
1534 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
1535 if (FAILED(result))
1536 {
1537 // Try again without the shared handle
1538 directToPixels = false;
1539 }
1540 }
1541
1542 if (!directToPixels)
1543 {
1544 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
1545 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
1546 if (FAILED(result))
1547 {
1548 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
1549 renderTarget->Release();
1550 return error(GL_OUT_OF_MEMORY);
1551 }
1552 }
1553
1554 result = mDevice->GetRenderTargetData(renderTarget, systemSurface);
1555 renderTarget->Release();
1556 renderTarget = NULL;
1557
1558 if (FAILED(result))
1559 {
1560 systemSurface->Release();
1561
1562 // It turns out that D3D will sometimes produce more error
1563 // codes than those documented.
1564 if (gl::checkDeviceLost(result))
1565 return error(GL_OUT_OF_MEMORY);
1566 else
1567 {
1568 UNREACHABLE();
1569 return;
1570 }
1571
1572 }
1573
1574 if (directToPixels)
1575 {
1576 systemSurface->Release();
1577 return;
1578 }
1579
1580 RECT rect;
1581 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
1582 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
1583 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
1584 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
1585
1586 D3DLOCKED_RECT lock;
1587 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
1588
1589 if (FAILED(result))
1590 {
1591 UNREACHABLE();
1592 systemSurface->Release();
1593
1594 return; // No sensible error to generate
1595 }
1596
1597 unsigned char *dest = (unsigned char*)pixels;
1598 unsigned short *dest16 = (unsigned short*)pixels;
1599
1600 unsigned char *source;
1601 int inputPitch;
1602 if (packReverseRowOrder)
1603 {
1604 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
1605 inputPitch = -lock.Pitch;
1606 }
1607 else
1608 {
1609 source = (unsigned char*)lock.pBits;
1610 inputPitch = lock.Pitch;
1611 }
1612
1613 unsigned int fastPixelSize = 0;
1614
1615 if (desc.Format == D3DFMT_A8R8G8B8 &&
1616 format == GL_BGRA_EXT &&
1617 type == GL_UNSIGNED_BYTE)
1618 {
1619 fastPixelSize = 4;
1620 }
1621 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
1622 format == GL_BGRA_EXT &&
1623 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
1624 (desc.Format == D3DFMT_A1R5G5B5 &&
1625 format == GL_BGRA_EXT &&
1626 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
1627 {
1628 fastPixelSize = 2;
1629 }
1630 else if (desc.Format == D3DFMT_A16B16G16R16F &&
1631 format == GL_RGBA &&
1632 type == GL_HALF_FLOAT_OES)
1633 {
1634 fastPixelSize = 8;
1635 }
1636 else if (desc.Format == D3DFMT_A32B32G32R32F &&
1637 format == GL_RGBA &&
1638 type == GL_FLOAT)
1639 {
1640 fastPixelSize = 16;
1641 }
1642
1643 for (int j = 0; j < rect.bottom - rect.top; j++)
1644 {
1645 if (fastPixelSize != 0)
1646 {
1647 // Fast path for formats which require no translation:
1648 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
1649 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
1650 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
1651 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
1652 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
1653 //
1654 // Note that buffers with no alpha go through the slow path below.
1655 memcpy(dest + j * outputPitch,
1656 source + j * inputPitch,
1657 (rect.right - rect.left) * fastPixelSize);
1658 continue;
1659 }
1660
1661 for (int i = 0; i < rect.right - rect.left; i++)
1662 {
1663 float r;
1664 float g;
1665 float b;
1666 float a;
1667
1668 switch (desc.Format)
1669 {
1670 case D3DFMT_R5G6B5:
1671 {
1672 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
1673
1674 a = 1.0f;
1675 b = (rgb & 0x001F) * (1.0f / 0x001F);
1676 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
1677 r = (rgb & 0xF800) * (1.0f / 0xF800);
1678 }
1679 break;
1680 case D3DFMT_A1R5G5B5:
1681 {
1682 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
1683
1684 a = (argb & 0x8000) ? 1.0f : 0.0f;
1685 b = (argb & 0x001F) * (1.0f / 0x001F);
1686 g = (argb & 0x03E0) * (1.0f / 0x03E0);
1687 r = (argb & 0x7C00) * (1.0f / 0x7C00);
1688 }
1689 break;
1690 case D3DFMT_A8R8G8B8:
1691 {
1692 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
1693
1694 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
1695 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
1696 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
1697 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
1698 }
1699 break;
1700 case D3DFMT_X8R8G8B8:
1701 {
1702 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
1703
1704 a = 1.0f;
1705 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
1706 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
1707 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
1708 }
1709 break;
1710 case D3DFMT_A2R10G10B10:
1711 {
1712 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
1713
1714 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
1715 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
1716 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
1717 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
1718 }
1719 break;
1720 case D3DFMT_A32B32G32R32F:
1721 {
1722 // float formats in D3D are stored rgba, rather than the other way round
1723 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
1724 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
1725 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
1726 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
1727 }
1728 break;
1729 case D3DFMT_A16B16G16R16F:
1730 {
1731 // float formats in D3D are stored rgba, rather than the other way round
1732 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
1733 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
1734 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
1735 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
1736 }
1737 break;
1738 default:
1739 UNIMPLEMENTED(); // FIXME
1740 UNREACHABLE();
1741 return;
1742 }
1743
1744 switch (format)
1745 {
1746 case GL_RGBA:
1747 switch (type)
1748 {
1749 case GL_UNSIGNED_BYTE:
1750 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
1751 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
1752 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
1753 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
1754 break;
1755 default: UNREACHABLE();
1756 }
1757 break;
1758 case GL_BGRA_EXT:
1759 switch (type)
1760 {
1761 case GL_UNSIGNED_BYTE:
1762 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
1763 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
1764 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
1765 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
1766 break;
1767 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
1768 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
1769 // this type is packed as follows:
1770 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1771 // --------------------------------------------------------------------------------
1772 // | 4th | 3rd | 2nd | 1st component |
1773 // --------------------------------------------------------------------------------
1774 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
1775 dest16[i + j * outputPitch / sizeof(unsigned short)] =
1776 ((unsigned short)(15 * a + 0.5f) << 12)|
1777 ((unsigned short)(15 * r + 0.5f) << 8) |
1778 ((unsigned short)(15 * g + 0.5f) << 4) |
1779 ((unsigned short)(15 * b + 0.5f) << 0);
1780 break;
1781 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
1782 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
1783 // this type is packed as follows:
1784 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1785 // --------------------------------------------------------------------------------
1786 // | 4th | 3rd | 2nd | 1st component |
1787 // --------------------------------------------------------------------------------
1788 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
1789 dest16[i + j * outputPitch / sizeof(unsigned short)] =
1790 ((unsigned short)( a + 0.5f) << 15) |
1791 ((unsigned short)(31 * r + 0.5f) << 10) |
1792 ((unsigned short)(31 * g + 0.5f) << 5) |
1793 ((unsigned short)(31 * b + 0.5f) << 0);
1794 break;
1795 default: UNREACHABLE();
1796 }
1797 break;
1798 case GL_RGB:
1799 switch (type)
1800 {
1801 case GL_UNSIGNED_SHORT_5_6_5:
1802 dest16[i + j * outputPitch / sizeof(unsigned short)] =
1803 ((unsigned short)(31 * b + 0.5f) << 0) |
1804 ((unsigned short)(63 * g + 0.5f) << 5) |
1805 ((unsigned short)(31 * r + 0.5f) << 11);
1806 break;
1807 case GL_UNSIGNED_BYTE:
1808 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
1809 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
1810 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
1811 break;
1812 default: UNREACHABLE();
1813 }
1814 break;
1815 default: UNREACHABLE();
1816 }
1817 }
1818 }
1819
1820 systemSurface->UnlockRect();
1821
1822 systemSurface->Release();
1823}
1824
1825bool Renderer9::setRenderTarget(gl::Renderbuffer *renderbuffer)
1826{
1827 IDirect3DSurface9 *renderTarget = NULL;
1828
1829 if (renderbuffer)
1830 {
1831 renderTarget = renderbuffer->getRenderTarget();
1832 if (!renderTarget)
1833 {
1834 ERR("render target pointer unexpectedly null.");
1835 return false; // Context must be lost
1836 }
1837
1838 mDevice->SetRenderTarget(0, renderTarget);
1839 renderTarget->Release();
1840 }
1841 else
1842 {
1843 mDevice->SetRenderTarget(0, NULL);
1844 }
1845
1846 return true;
1847}
1848
1849bool Renderer9::setDepthStencil(gl::Renderbuffer *renderbuffer)
1850{
1851 IDirect3DSurface9 *depthStencil = NULL;
1852
1853 if (renderbuffer)
1854 {
1855 depthStencil = renderbuffer->getDepthStencil();
1856 if (!depthStencil)
1857 {
1858 ERR("depth stencil pointer unexpectedly null.");
1859 return false; // Context must be lost
1860 }
1861 mDevice->SetDepthStencilSurface(depthStencil);
1862 depthStencil->Release();
1863 }
1864 else
1865 {
1866 mDevice->SetDepthStencilSurface(NULL);
1867 }
1868 return true;
1869}
1870
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001871bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
1872{
1873 return mBlit->boxFilter(source, dest);
1874}
1875
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001876D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001877{
1878 if (mD3d9Ex != NULL)
1879 {
1880 return D3DPOOL_DEFAULT;
1881 }
1882 else
1883 {
1884 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
1885 {
1886 return D3DPOOL_MANAGED;
1887 }
1888 }
1889
1890 return D3DPOOL_DEFAULT;
1891}
1892
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001893bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
1894{
1895 if (source && dest)
1896 {
1897 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
1898 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
1899
1900 if (fromManaged)
1901 {
1902 D3DSURFACE_DESC desc;
1903 source->GetDesc(&desc);
1904
1905 IDirect3DSurface9 *surf = 0;
1906 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
1907
1908 if (SUCCEEDED(result))
1909 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001910 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001911 result = device->UpdateSurface(surf, NULL, dest, NULL);
1912 surf->Release();
1913 }
1914 }
1915 else
1916 {
1917 endScene();
1918 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
1919 }
1920
1921 if (FAILED(result))
1922 {
1923 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
1924 return false;
1925 }
1926 }
1927
1928 return true;
1929}
1930
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001931}