blob: 749b361d298830c0bfda1ed6d00ee6d6fcea8425 [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.com621ce052012-10-31 17:52:29 +000091}
92
daniel@transgaming.com2507f412012-10-31 18:46:48 +000093Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +000094{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000095 releaseDeviceResources();
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000096
97 delete mBlit;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000098
daniel@transgaming.com621ce052012-10-31 17:52:29 +000099 if (mDevice)
100 {
101 // 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 +0000102 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000103 {
104 resetDevice();
105 }
106
107 mDevice->Release();
108 mDevice = NULL;
109 }
110
111 if (mDeviceEx)
112 {
113 mDeviceEx->Release();
114 mDeviceEx = NULL;
115 }
116
117 if (mD3d9)
118 {
119 mD3d9->Release();
120 mD3d9 = NULL;
121 }
122
123 if (mDeviceWindow)
124 {
125 DestroyWindow(mDeviceWindow);
126 mDeviceWindow = NULL;
127 }
128
129 if (mD3d9Ex)
130 {
131 mD3d9Ex->Release();
132 mD3d9Ex = NULL;
133 }
134
135 if (mD3d9Module)
136 {
137 mD3d9Module = NULL;
138 }
139
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000140 if (mD3dCompilerModule)
141 {
142 FreeLibrary(mD3dCompilerModule);
143 mD3dCompilerModule = NULL;
144 }
145
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000146 while (!mMultiSampleSupport.empty())
147 {
148 delete [] mMultiSampleSupport.begin()->second;
149 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
150 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000151}
152
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000153Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
154{
155 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
156 return static_cast<rx::Renderer9*>(renderer);
157}
158
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000159EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000160{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000161 if (mSoftwareDevice)
162 {
163 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
164 }
165 else
166 {
167 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
168 }
169
170 if (mD3d9Module == NULL)
171 {
172 ERR("No D3D9 module found - aborting!\n");
173 return EGL_NOT_INITIALIZED;
174 }
175
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000176 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
177 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
178
179 // Use Direct3D9Ex if available. Among other things, this version is less
180 // inclined to report a lost context, for example when the user switches
181 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
182 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
183 {
184 ASSERT(mD3d9Ex);
185 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
186 ASSERT(mD3d9);
187 }
188 else
189 {
190 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
191 }
192
193 if (!mD3d9)
194 {
195 ERR("Could not create D3D9 device - aborting!\n");
196 return EGL_NOT_INITIALIZED;
197 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000198
199#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
200 // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
201 static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
202
203 for (int i = 0; i < sizeof(d3dCompilerNames) / sizeof(*d3dCompilerNames); ++i)
204 {
205 if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
206 {
207 break;
208 }
209 }
210#else
211 // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
212 mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
213#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
214
215 if (!mD3dCompilerModule)
216 {
217 terminate();
218 return false;
219 }
220
221 mD3DCompileFunc = reinterpret_cast<D3DCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
222 ASSERT(mD3DCompileFunc);
223
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000224 if (mDc != NULL)
225 {
226 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
227 }
228
229 HRESULT result;
230
231 // Give up on getting device caps after about one second.
232 for (int i = 0; i < 10; ++i)
233 {
234 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
235 if (SUCCEEDED(result))
236 {
237 break;
238 }
239 else if (result == D3DERR_NOTAVAILABLE)
240 {
241 Sleep(100); // Give the driver some time to initialize/recover
242 }
243 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
244 {
245 ERR("failed to get device caps (0x%x)\n", result);
246 return EGL_NOT_INITIALIZED;
247 }
248 }
249
250 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
251 {
252 ERR("Renderer does not support PS 2.0. aborting!\n");
253 return EGL_NOT_INITIALIZED;
254 }
255
256 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
257 // This is required by Texture2D::convertToRenderTarget.
258 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
259 {
260 ERR("Renderer does not support stretctrect from textures!\n");
261 return EGL_NOT_INITIALIZED;
262 }
263
264 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
265
266 // ATI cards on XP have problems with non-power-of-two textures.
267 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
268 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
269 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
270 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
271
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000272 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
273 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
274
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000275 mMinSwapInterval = 4;
276 mMaxSwapInterval = 0;
277
278 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
279 {
280 mMinSwapInterval = std::min(mMinSwapInterval, 0);
281 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
282 }
283 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
284 {
285 mMinSwapInterval = std::min(mMinSwapInterval, 1);
286 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
287 }
288 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
289 {
290 mMinSwapInterval = std::min(mMinSwapInterval, 2);
291 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
292 }
293 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
294 {
295 mMinSwapInterval = std::min(mMinSwapInterval, 3);
296 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
297 }
298 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
299 {
300 mMinSwapInterval = std::min(mMinSwapInterval, 4);
301 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
302 }
303
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000304 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000305 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000306 {
307 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000308 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
309 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000310
311 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
312 {
313 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
314 {
315 max = j;
316 }
317 }
318 }
319
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000320 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000321 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000322 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000323 continue;
324
325 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000326 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
327 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000328
329 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
330 {
331 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
332 {
333 max = j;
334 }
335 }
336 }
337
338 mMaxSupportedSamples = max;
339
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000340 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
341 static const TCHAR className[] = TEXT("STATIC");
342
343 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
344
345 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
346 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
347
348 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
349 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
350 {
351 return EGL_BAD_ALLOC;
352 }
353
354 if (FAILED(result))
355 {
356 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
357
358 if (FAILED(result))
359 {
360 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
361 return EGL_BAD_ALLOC;
362 }
363 }
364
365 if (mD3d9Ex)
366 {
367 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
368 ASSERT(SUCCEEDED(result));
369 }
370
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000371 mVertexShaderCache.initialize(mDevice);
372 mPixelShaderCache.initialize(mDevice);
373
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000374 initializeDevice();
375
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +0000376 mBlit = new Blit(this);
377
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000378 return EGL_SUCCESS;
379}
380
381// do any one-time device initialization
382// NOTE: this is also needed after a device lost/reset
383// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000384void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000385{
386 // Permanent non-default states
387 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
388 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
389
390 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
391 {
392 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
393 }
394 else
395 {
396 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
397 }
398
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000399 markAllStateDirty();
400
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000401 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000402
403 if (!mVertexDataManager)
404 {
405 mVertexDataManager = new gl::VertexDataManager(this);
406 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000407}
408
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000409D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000410{
411 D3DPRESENT_PARAMETERS presentParameters = {0};
412
413 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
414 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
415 presentParameters.BackBufferCount = 1;
416 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
417 presentParameters.BackBufferWidth = 1;
418 presentParameters.BackBufferHeight = 1;
419 presentParameters.EnableAutoDepthStencil = FALSE;
420 presentParameters.Flags = 0;
421 presentParameters.hDeviceWindow = mDeviceWindow;
422 presentParameters.MultiSampleQuality = 0;
423 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
424 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
425 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
426 presentParameters.Windowed = TRUE;
427
428 return presentParameters;
429}
430
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000431int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000432{
433 D3DDISPLAYMODE currentDisplayMode;
434 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
435
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000436 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
437 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000438 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
439 int numConfigs = 0;
440
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000441 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000442 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000443 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000444
445 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
446
447 if (SUCCEEDED(result))
448 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000449 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000450 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000451 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000452 HRESULT result = D3D_OK;
453
454 if(depthStencilFormat != D3DFMT_UNKNOWN)
455 {
456 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
457 }
458
459 if (SUCCEEDED(result))
460 {
461 if(depthStencilFormat != D3DFMT_UNKNOWN)
462 {
463 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
464 }
465
466 if (SUCCEEDED(result))
467 {
468 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000469 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
470 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000471 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
472 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
473
474 (*configDescList)[numConfigs++] = newConfig;
475 }
476 }
477 }
478 }
479 }
480
481 return numConfigs;
482}
483
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000484void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000485{
486 delete [] (configDescList);
487}
488
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000489void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000490{
491 if (!mSceneStarted)
492 {
493 long result = mDevice->BeginScene();
494 if (SUCCEEDED(result)) {
495 // This is defensive checking against the device being
496 // lost at unexpected times.
497 mSceneStarted = true;
498 }
499 }
500}
501
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000502void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000503{
504 if (mSceneStarted)
505 {
506 // EndScene can fail if the device was lost, for example due
507 // to a TDR during a draw call.
508 mDevice->EndScene();
509 mSceneStarted = false;
510 }
511}
512
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000513// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000514void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000515{
516 HRESULT result;
517
518 IDirect3DQuery9* query = allocateEventQuery();
519 if (!query)
520 {
521 return;
522 }
523
524 result = query->Issue(D3DISSUE_END);
525 ASSERT(SUCCEEDED(result));
526
527 do
528 {
529 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
530
531 if(block && result == S_FALSE)
532 {
533 // Keep polling, but allow other threads to do something useful first
534 Sleep(0);
535 // explicitly check for device loss
536 // some drivers seem to return S_FALSE even if the device is lost
537 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000538 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000539 {
540 result = D3DERR_DEVICELOST;
541 }
542 }
543 }
544 while(block && result == S_FALSE);
545
546 freeEventQuery(query);
547
548 if (isDeviceLostError(result))
549 {
550 mDisplay->notifyDeviceLost();
551 }
552}
553
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000554SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
555{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000556 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000557}
558
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000559// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000560IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000561{
562 IDirect3DQuery9 *query = NULL;
563
564 if (mEventQueryPool.empty())
565 {
566 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
567 ASSERT(SUCCEEDED(result));
568 }
569 else
570 {
571 query = mEventQueryPool.back();
572 mEventQueryPool.pop_back();
573 }
574
575 return query;
576}
577
578// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000579void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000580{
581 if (mEventQueryPool.size() > 1000)
582 {
583 query->Release();
584 }
585 else
586 {
587 mEventQueryPool.push_back(query);
588 }
589}
590
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000591
592HRESULT Renderer9::compileShaderSource(const char* hlsl, const char* sourceName, const char* profile, DWORD flags, ID3DBlob** binary, ID3DBlob** errorMessage)
593{
594 return mD3DCompileFunc(hlsl, strlen(hlsl), sourceName, NULL, NULL, "main", profile, flags, 0, binary, errorMessage);
595}
596
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000597IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000598{
599 return mVertexShaderCache.create(function, length);
600}
601
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000602IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000603{
604 return mPixelShaderCache.create(function, length);
605}
606
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000607HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
608{
609 D3DPOOL Pool = getBufferPool(Usage);
610 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
611}
612
613HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
614{
615 D3DPOOL Pool = getBufferPool(Usage);
616 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
617}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000618
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000619void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000620{
621 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
622 int d3dSampler = index + d3dSamplerOffset;
623
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000624 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
625 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000626
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000627 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000628 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000629 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000630 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
631 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
632 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
633 if (mSupportsTextureFilterAnisotropy)
634 {
635 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
636 }
637}
638
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000639void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000640{
641 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
642 int d3dSampler = index + d3dSamplerOffset;
643 IDirect3DBaseTexture9 *d3dTexture = NULL;
644
645 if (texture)
646 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000647 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000648 if (texStorage)
649 {
650 d3dTexture = texStorage->getBaseTexture();
651 }
652 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000653 // in the texture class and we're unexpectedly missing the d3d texture
654 ASSERT(d3dTexture != NULL);
655 }
656
657 mDevice->SetTexture(d3dSampler, d3dTexture);
658}
659
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000660void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
661{
662 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
663 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
664
665 if (rasterStateChanged)
666 {
667 // Set the cull mode
668 if (rasterState.cullFace)
669 {
670 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
671 }
672 else
673 {
674 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
675 }
676
677 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
678
679 mCurRasterState = rasterState;
680 }
681
682 if (rasterStateChanged || depthSizeChanged)
683 {
684 if (rasterState.polygonOffsetFill)
685 {
686 if (depthSize > 0)
687 {
688 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
689
690 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
691 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
692 }
693 }
694 else
695 {
696 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
697 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
698 }
699
700 mCurDepthSize = depthSize;
701 }
702
703 mForceSetRasterState = false;
704}
705
706void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
707{
708 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
709 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
710 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
711
712 if (blendStateChanged || blendColorChanged)
713 {
714 if (blendState.blend)
715 {
716 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
717
718 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
719 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
720 {
721 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
722 }
723 else
724 {
725 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
726 gl::unorm<8>(blendColor.alpha),
727 gl::unorm<8>(blendColor.alpha),
728 gl::unorm<8>(blendColor.alpha)));
729 }
730
731 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
732 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
733 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
734
735 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
736 blendState.destBlendRGB != blendState.destBlendAlpha ||
737 blendState.blendEquationRGB != blendState.blendEquationAlpha)
738 {
739 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
740
741 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
742 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
743 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
744 }
745 else
746 {
747 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
748 }
749 }
750 else
751 {
752 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
753 }
754
755 if (blendState.sampleAlphaToCoverage)
756 {
757 FIXME("Sample alpha to coverage is unimplemented.");
758 }
759
760 // Set the color mask
761 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
762 // Apparently some ATI cards have a bug where a draw with a zero color
763 // write mask can cause later draws to have incorrect results. Instead,
764 // set a nonzero color write mask but modify the blend state so that no
765 // drawing is done.
766 // http://code.google.com/p/angleproject/issues/detail?id=169
767
768 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
769 blendState.colorMaskBlue, blendState.colorMaskAlpha);
770 if (colorMask == 0 && !zeroColorMaskAllowed)
771 {
772 // Enable green channel, but set blending so nothing will be drawn.
773 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
774 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
775
776 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
777 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
778 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
779 }
780 else
781 {
782 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
783 }
784
785 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
786
787 mCurBlendState = blendState;
788 mCurBlendColor = blendColor;
789 }
790
791 if (sampleMaskChanged)
792 {
793 // Set the multisample mask
794 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
795 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
796
797 mCurSampleMask = sampleMask;
798 }
799
800 mForceSetBlendState = false;
801}
802
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000803void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
804 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000805{
806 bool depthStencilStateChanged = mForceSetDepthStencilState ||
807 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000808 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
809 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000810 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
811 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
812
813 if (depthStencilStateChanged)
814 {
815 if (depthStencilState.depthTest)
816 {
817 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
818 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
819 }
820 else
821 {
822 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
823 }
824
825 mCurDepthStencilState = depthStencilState;
826 }
827
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000828 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000829 {
830 if (depthStencilState.stencilTest && stencilSize > 0)
831 {
832 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
833 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
834
835 // FIXME: Unsupported by D3D9
836 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
837 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
838 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
839 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000840 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000841 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
842 {
843 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
844 return error(GL_INVALID_OPERATION);
845 }
846
847 // get the maximum size of the stencil ref
848 GLuint maxStencil = (1 << stencilSize) - 1;
849
850 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
851 depthStencilState.stencilWritemask);
852 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
853 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
854
855 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000856 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000857 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
858 depthStencilState.stencilMask);
859
860 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
861 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
862 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
863 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
864 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
865 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
866
867 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
868 depthStencilState.stencilBackWritemask);
869 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
870 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
871
872 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000873 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000874 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
875 depthStencilState.stencilBackMask);
876
877 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
878 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
879 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
880 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
881 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
882 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
883 }
884 else
885 {
886 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
887 }
888
889 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
890
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000891 mCurStencilRef = stencilRef;
892 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000893 mCurFrontFaceCCW = frontFaceCCW;
894 mCurStencilSize = stencilSize;
895 }
896
897 mForceSetDepthStencilState = false;
898}
899
900void Renderer9::setScissorRectangle(const gl::Rectangle& scissor, unsigned int renderTargetWidth,
901 unsigned int renderTargetHeight)
902{
903 bool renderTargetSizedChanged = mForceSetScissor ||
904 renderTargetWidth != mCurRenderTargetWidth ||
905 renderTargetHeight != mCurRenderTargetHeight;
906 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
907
908 if (renderTargetSizedChanged || scissorChanged)
909 {
910 RECT rect;
911 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000912 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000913 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000914 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000915 mDevice->SetScissorRect(&rect);
916
917 mCurScissor = scissor;
918 mCurRenderTargetWidth = renderTargetWidth;
919 mCurRenderTargetHeight = renderTargetHeight;
920 }
921
922 mForceSetScissor = false;
923}
924
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000925bool Renderer9::setViewport(const gl::Rectangle& viewport, float zNear, float zFar,
926 unsigned int renderTargetWidth, unsigned int renderTargetHeight,
927 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
928{
929 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
930 zNear != mCurNear || zFar != mCurFar;
931
932 D3DVIEWPORT9 dxViewport;
933 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(renderTargetWidth));
934 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(renderTargetHeight));
935 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(renderTargetWidth) - static_cast<int>(dxViewport.X));
936 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(renderTargetHeight) - static_cast<int>(dxViewport.Y));
937 dxViewport.MinZ = zNear;
938 dxViewport.MaxZ = zFar;
939
940 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
941 {
942 return false; // Nothing to render
943 }
944
945 if (viewportChanged)
946 {
947 mDevice->SetViewport(&dxViewport);
948
949 mCurViewport = viewport;
950 mCurNear = zNear;
951 mCurFar = zFar;
952 }
953
954 if (currentProgram && (viewportChanged || forceSetUniforms))
955 {
956 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
957 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
958 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
959
960 // These values are used for computing gl_FragCoord in Program::linkVaryings().
961 GLint coord = currentProgram->getDxCoordLocation();
962 GLfloat whxy[4] = { viewport.width * 0.5f,
963 viewport.height * 0.5f,
964 viewport.x + (viewport.width * 0.5f),
965 viewport.y + (viewport.height * 0.5f) };
966 currentProgram->setUniform4fv(coord, 1, whxy);
967
968 GLint depth = currentProgram->getDxDepthLocation();
969 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
970 currentProgram->setUniform2fv(depth, 1, dz);
971
972 GLint depthRange = currentProgram->getDxDepthRangeLocation();
973 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
974 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
975 }
976
977 mForceSetViewport = false;
978 return true;
979}
980
daniel@transgaming.comae39ee22012-11-28 19:42:02 +0000981bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000982{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +0000983 // if there is no color attachment we must synthesize a NULL colorattachment
984 // to keep the D3D runtime happy. This should only be possible if depth texturing.
985 gl::Renderbuffer *renderbufferObject = NULL;
986 if (framebuffer->getColorbufferType() != GL_NONE)
987 {
988 renderbufferObject = framebuffer->getColorbuffer();
989 }
990 else
991 {
992 renderbufferObject = framebuffer->getNullColorbuffer();
993 }
994 if (!renderbufferObject)
995 {
996 ERR("unable to locate renderbuffer for FBO.");
997 return false;
998 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000999
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001000 bool renderTargetChanged = false;
1001 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1002 if (renderTargetSerial != mAppliedRenderTargetSerial)
1003 {
1004 // Apply the render target on the device
1005 IDirect3DSurface9 *renderTargetSurface = NULL;
1006
1007 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1008 if (renderTarget)
1009 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001010 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001011 }
1012
1013 if (!renderTargetSurface)
1014 {
1015 ERR("render target pointer unexpectedly null.");
1016 return false; // Context must be lost
1017 }
1018
1019 mDevice->SetRenderTarget(0, renderTargetSurface);
1020 renderTargetSurface->Release();
1021
1022 mAppliedRenderTargetSerial = renderTargetSerial;
1023 renderTargetChanged = true;
1024 }
1025
1026 gl::Renderbuffer *depthStencil = NULL;
1027 unsigned int depthbufferSerial = 0;
1028 unsigned int stencilbufferSerial = 0;
1029 if (framebuffer->getDepthbufferType() != GL_NONE)
1030 {
1031 depthStencil = framebuffer->getDepthbuffer();
1032 if (!depthStencil)
1033 {
1034 ERR("Depth stencil pointer unexpectedly null.");
1035 return false;
1036 }
1037
1038 depthbufferSerial = depthStencil->getSerial();
1039 }
1040 else if (framebuffer->getStencilbufferType() != GL_NONE)
1041 {
1042 depthStencil = framebuffer->getStencilbuffer();
1043 if (!depthStencil)
1044 {
1045 ERR("Depth stencil pointer unexpectedly null.");
1046 return false;
1047 }
1048
1049 stencilbufferSerial = depthStencil->getSerial();
1050 }
1051
1052 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1053 stencilbufferSerial != mAppliedStencilbufferSerial ||
1054 !mDepthStencilInitialized)
1055 {
1056 // Apply the depth stencil on the device
1057 if (depthStencil)
1058 {
1059 IDirect3DSurface9 *depthStencilSurface = NULL;
1060 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1061
1062 if (depthStencilRenderTarget)
1063 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001064 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001065 }
1066
1067 if (!depthStencilSurface)
1068 {
1069 ERR("depth stencil pointer unexpectedly null.");
1070 return false; // Context must be lost
1071 }
1072
1073 mDevice->SetDepthStencilSurface(depthStencilSurface);
1074 depthStencilSurface->Release();
1075 }
1076 else
1077 {
1078 mDevice->SetDepthStencilSurface(NULL);
1079 }
1080
1081 mAppliedDepthbufferSerial = depthbufferSerial;
1082 mAppliedStencilbufferSerial = stencilbufferSerial;
1083 mDepthStencilInitialized = true;
1084 }
1085
1086 if (renderTargetChanged || !mRenderTargetDescInitialized)
1087 {
1088 mForceSetScissor = true;
1089 mForceSetViewport = true;
1090
1091 mRenderTargetDesc.width = renderbufferObject->getWidth();
1092 mRenderTargetDesc.height = renderbufferObject->getHeight();
1093 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1094 mRenderTargetDescInitialized = true;
1095 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001096
1097 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001098}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001099
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001100GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
1101{
1102 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1103 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1104 if (err != GL_NO_ERROR)
1105 {
1106 return err;
1107 }
1108
1109 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
1110}
1111
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001112void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1113{
1114 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
1115 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
1116
1117 mDevice->SetPixelShader(pixelShader);
1118 mDevice->SetVertexShader(vertexShader);
1119 programBinary->dirtyAllUniforms();
1120}
1121
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001122void Renderer9::clear(GLbitfield mask, const gl::Color &colorClear, float depthClear, int stencilClear,
1123 gl::Framebuffer *frameBuffer)
1124{
1125 mForceSetDepthStencilState = true;
1126
1127 // TODO
1128}
1129
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001130void Renderer9::markAllStateDirty()
1131{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001132 mAppliedRenderTargetSerial = 0;
1133 mAppliedDepthbufferSerial = 0;
1134 mAppliedStencilbufferSerial = 0;
1135 mDepthStencilInitialized = false;
1136 mRenderTargetDescInitialized = false;
1137
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001138 mForceSetDepthStencilState = true;
1139 mForceSetRasterState = true;
1140 mForceSetBlendState = true;
1141 mForceSetScissor = true;
1142 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001143
1144 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001145}
1146
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001147void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001148{
1149 while (!mEventQueryPool.empty())
1150 {
1151 mEventQueryPool.back()->Release();
1152 mEventQueryPool.pop_back();
1153 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001154
1155 mVertexShaderCache.clear();
1156 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001157
1158 delete mVertexDataManager;
1159 mVertexDataManager = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001160}
1161
1162
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001163void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001164{
1165 mDeviceLost = true;
1166}
1167
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001168bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001169{
1170 return mDeviceLost;
1171}
1172
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001173// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001174bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001175{
1176 bool isLost = false;
1177
1178 if (mDeviceEx)
1179 {
1180 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1181 }
1182 else if (mDevice)
1183 {
1184 isLost = FAILED(mDevice->TestCooperativeLevel());
1185 }
1186 else
1187 {
1188 // No device yet, so no reset required
1189 }
1190
1191 if (isLost)
1192 {
1193 // ensure we note the device loss --
1194 // we'll probably get this done again by markDeviceLost
1195 // but best to remember it!
1196 // Note that we don't want to clear the device loss status here
1197 // -- this needs to be done by resetDevice
1198 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001199 if (notify)
1200 {
1201 mDisplay->notifyDeviceLost();
1202 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001203 }
1204
1205 return isLost;
1206}
1207
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001208bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001209{
1210 HRESULT status = D3D_OK;
1211
1212 if (mDeviceEx)
1213 {
1214 status = mDeviceEx->CheckDeviceState(NULL);
1215 }
1216 else if (mDevice)
1217 {
1218 status = mDevice->TestCooperativeLevel();
1219 }
1220
1221 switch (status)
1222 {
1223 case D3DERR_DEVICENOTRESET:
1224 case D3DERR_DEVICEHUNG:
1225 return true;
1226 default:
1227 return false;
1228 }
1229}
1230
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001231bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001232{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001233 releaseDeviceResources();
1234
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001235 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1236
1237 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001238 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001239 int attempts = 3;
1240
1241 while (lost && attempts > 0)
1242 {
1243 if (mDeviceEx)
1244 {
1245 Sleep(500); // Give the graphics driver some CPU time
1246 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1247 }
1248 else
1249 {
1250 result = mDevice->TestCooperativeLevel();
1251 while (result == D3DERR_DEVICELOST)
1252 {
1253 Sleep(100); // Give the graphics driver some CPU time
1254 result = mDevice->TestCooperativeLevel();
1255 }
1256
1257 if (result == D3DERR_DEVICENOTRESET)
1258 {
1259 result = mDevice->Reset(&presentParameters);
1260 }
1261 }
1262
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001263 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001264 attempts --;
1265 }
1266
1267 if (FAILED(result))
1268 {
1269 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1270 return false;
1271 }
1272
1273 // reset device defaults
1274 initializeDevice();
1275 mDeviceLost = false;
1276
1277 return true;
1278}
1279
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001280DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001281{
1282 return mAdapterIdentifier.VendorId;
1283}
1284
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001285const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001286{
1287 return mAdapterIdentifier.Description;
1288}
1289
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001290GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001291{
1292 return mAdapterIdentifier.DeviceIdentifier;
1293}
1294
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001295void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001296{
1297 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1298 {
1299 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1300 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1301
1302 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1303 }
1304}
1305
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001306bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001307{
1308 D3DDISPLAYMODE currentDisplayMode;
1309 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1310
1311 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1312}
1313
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001314bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001315{
1316 D3DDISPLAYMODE currentDisplayMode;
1317 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1318
1319 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1320}
1321
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001322bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001323{
1324 D3DDISPLAYMODE currentDisplayMode;
1325 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1326
1327 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1328}
1329
1330// we use INTZ for depth textures in Direct3D9
1331// we also want NULL texture support to ensure the we can make depth-only FBOs
1332// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001333bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001334{
1335 D3DDISPLAYMODE currentDisplayMode;
1336 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1337
1338 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1339 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1340 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1341 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1342
1343 return intz && null;
1344}
1345
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001346bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001347{
1348 D3DDISPLAYMODE currentDisplayMode;
1349 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1350
1351 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1352 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1353 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1354 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1355
1356 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1357 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1358 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1359 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1360
1361 if (!*filtering && !*renderable)
1362 {
1363 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1364 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1365 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1366 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1367 }
1368 else
1369 {
1370 return true;
1371 }
1372}
1373
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001374bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001375{
1376 D3DDISPLAYMODE currentDisplayMode;
1377 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1378
1379 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1380 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1381 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1382 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1383
1384 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1385 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1386 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1387 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1388
1389 if (!*filtering && !*renderable)
1390 {
1391 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1392 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1393 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1394 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1395 }
1396 else
1397 {
1398 return true;
1399 }
1400}
1401
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001402bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001403{
1404 D3DDISPLAYMODE currentDisplayMode;
1405 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1406
1407 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1408}
1409
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001410bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001411{
1412 D3DDISPLAYMODE currentDisplayMode;
1413 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1414
1415 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1416}
1417
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001418bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001419{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001420 return mSupportsTextureFilterAnisotropy;
1421}
1422
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001423float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001424{
1425 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001426 {
1427 return mDeviceCaps.MaxAnisotropy;
1428 }
1429 return 1.0f;
1430}
1431
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001432bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001433{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001434 IDirect3DQuery9 *query = allocateEventQuery();
1435 if (query)
1436 {
1437 freeEventQuery(query);
1438 return true;
1439 }
1440 else
1441 {
1442 return false;
1443 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001444 return true;
1445}
1446
1447// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1448// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001449bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001450{
1451 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1452 {
1453 return false;
1454 }
1455
1456 D3DDISPLAYMODE currentDisplayMode;
1457 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1458
1459 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1460
1461 return SUCCEEDED(result);
1462}
1463
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001464bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001465{
1466 return mSupportsNonPower2Textures;
1467}
1468
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001469bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001470{
1471 if (!mDevice)
1472 {
1473 return false;
1474 }
1475
1476 IDirect3DQuery9 *query = NULL;
1477 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1478 if (SUCCEEDED(result) && query)
1479 {
1480 query->Release();
1481 return true;
1482 }
1483 else
1484 {
1485 return false;
1486 }
1487}
1488
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001489bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001490{
1491 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1492}
1493
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001494bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001495{
1496 // PIX doesn't seem to support using share handles, so disable them.
1497 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001498 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001499}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001500
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001501bool Renderer9::getShaderModel3Support() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001502{
1503 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1504}
1505
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001506float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001507{
1508 return mDeviceCaps.MaxPointSize;
1509}
1510
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001511int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001512{
1513 return (int)mDeviceCaps.MaxTextureWidth;
1514}
1515
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001516int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001517{
1518 return (int)mDeviceCaps.MaxTextureHeight;
1519}
1520
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001521bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001522{
1523 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1524}
1525
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001526DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001527{
1528 return mDeviceCaps.DeclTypes;
1529}
1530
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001531int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001532{
1533 return mMinSwapInterval;
1534}
1535
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001536int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001537{
1538 return mMaxSwapInterval;
1539}
1540
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001541int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001542{
1543 return mMaxSupportedSamples;
1544}
1545
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001546int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001547{
1548 if (requested == 0)
1549 {
1550 return requested;
1551 }
1552
1553 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
1554 if (itr == mMultiSampleSupport.end())
1555 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00001556 if (format == D3DFMT_UNKNOWN)
1557 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001558 return -1;
1559 }
1560
1561 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
1562 {
1563 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
1564 {
1565 return i;
1566 }
1567 }
1568
1569 return -1;
1570}
1571
daniel@transgaming.coma9571682012-11-28 19:33:08 +00001572D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
1573{
1574 switch (internalformat)
1575 {
1576 case GL_DEPTH_COMPONENT16:
1577 case GL_DEPTH_COMPONENT32_OES:
1578 case GL_DEPTH24_STENCIL8_OES:
1579 return D3DFMT_INTZ;
1580 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
1581 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
1582 return D3DFMT_DXT1;
1583 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
1584 return D3DFMT_DXT3;
1585 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
1586 return D3DFMT_DXT5;
1587 case GL_RGBA32F_EXT:
1588 case GL_RGB32F_EXT:
1589 case GL_ALPHA32F_EXT:
1590 case GL_LUMINANCE32F_EXT:
1591 case GL_LUMINANCE_ALPHA32F_EXT:
1592 return D3DFMT_A32B32G32R32F;
1593 case GL_RGBA16F_EXT:
1594 case GL_RGB16F_EXT:
1595 case GL_ALPHA16F_EXT:
1596 case GL_LUMINANCE16F_EXT:
1597 case GL_LUMINANCE_ALPHA16F_EXT:
1598 return D3DFMT_A16B16G16R16F;
1599 case GL_LUMINANCE8_EXT:
1600 if (getLuminanceTextureSupport())
1601 {
1602 return D3DFMT_L8;
1603 }
1604 break;
1605 case GL_LUMINANCE8_ALPHA8_EXT:
1606 if (getLuminanceAlphaTextureSupport())
1607 {
1608 return D3DFMT_A8L8;
1609 }
1610 break;
1611 case GL_RGB8_OES:
1612 case GL_RGB565:
1613 return D3DFMT_X8R8G8B8;
1614 }
1615
1616 return D3DFMT_A8R8G8B8;
1617}
1618
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001619bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001620{
1621 bool result = false;
1622
1623 if (source && dest)
1624 {
1625 int levels = source->levelCount();
1626 for (int i = 0; i < levels; ++i)
1627 {
1628 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
1629 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
1630
1631 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1632
1633 if (srcSurf) srcSurf->Release();
1634 if (dstSurf) dstSurf->Release();
1635
1636 if (!result)
1637 return false;
1638 }
1639 }
1640
1641 return result;
1642}
1643
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001644bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001645{
1646 bool result = false;
1647
1648 if (source && dest)
1649 {
1650 int levels = source->levelCount();
1651 for (int f = 0; f < 6; f++)
1652 {
1653 for (int i = 0; i < levels; i++)
1654 {
1655 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
1656 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
1657
1658 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1659
1660 if (srcSurf) srcSurf->Release();
1661 if (dstSurf) dstSurf->Release();
1662
1663 if (!result)
1664 return false;
1665 }
1666 }
1667 }
1668
1669 return result;
1670}
1671
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001672D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001673{
1674 if (mD3d9Ex != NULL)
1675 {
1676 return D3DPOOL_DEFAULT;
1677 }
1678 else
1679 {
1680 if (!(usage & D3DUSAGE_DYNAMIC))
1681 {
1682 return D3DPOOL_MANAGED;
1683 }
1684 }
1685
1686 return D3DPOOL_DEFAULT;
1687}
1688
daniel@transgaming.com38380882012-11-28 19:36:39 +00001689bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1690 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001691{
1692 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
1693}
1694
daniel@transgaming.com38380882012-11-28 19:36:39 +00001695bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1696 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001697{
1698 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
1699}
1700
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001701bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
1702 bool blitRenderTarget, bool blitDepthStencil)
1703{
1704 endScene();
1705
1706 if (blitRenderTarget)
1707 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001708 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
1709 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
1710 RenderTarget9 *readRenderTarget = NULL;
1711 RenderTarget9 *drawRenderTarget = NULL;
1712 IDirect3DSurface9* readSurface = NULL;
1713 IDirect3DSurface9* drawSurface = NULL;
1714
1715 if (readBuffer)
1716 {
1717 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
1718 }
1719 if (drawBuffer)
1720 {
1721 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
1722 }
1723
1724 if (readRenderTarget)
1725 {
1726 readSurface = readRenderTarget->getSurface();
1727 }
1728 if (drawRenderTarget)
1729 {
1730 drawSurface = drawRenderTarget->getSurface();
1731 }
1732
1733 if (!readSurface || !drawSurface)
1734 {
1735 ERR("Failed to retrieve the render target.");
1736 return error(GL_OUT_OF_MEMORY, false);
1737 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001738
1739 RECT srcRect, dstRect;
1740 RECT *srcRectPtr = NULL;
1741 RECT *dstRectPtr = NULL;
1742
1743 if (readRect)
1744 {
1745 srcRect.left = readRect->x;
1746 srcRect.right = readRect->x + readRect->width;
1747 srcRect.top = readRect->y;
1748 srcRect.bottom = readRect->y + readRect->height;
1749 srcRectPtr = &srcRect;
1750 }
1751
1752 if (drawRect)
1753 {
1754 dstRect.left = drawRect->x;
1755 dstRect.right = drawRect->x + drawRect->width;
1756 dstRect.top = drawRect->y;
1757 dstRect.bottom = drawRect->y + drawRect->height;
1758 dstRectPtr = &dstRect;
1759 }
1760
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001761 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001762
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001763 readSurface->Release();
1764 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001765
1766 if (FAILED(result))
1767 {
1768 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1769 return false;
1770 }
1771 }
1772
1773 if (blitDepthStencil)
1774 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001775 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
1776 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
1777 RenderTarget9 *readDepthStencil = NULL;
1778 RenderTarget9 *drawDepthStencil = NULL;
1779 IDirect3DSurface9* readSurface = NULL;
1780 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001781
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001782 if (readBuffer)
1783 {
1784 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
1785 }
1786 if (drawBuffer)
1787 {
1788 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
1789 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001790
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001791 if (readDepthStencil)
1792 {
1793 readSurface = readDepthStencil->getSurface();
1794 }
1795 if (drawDepthStencil)
1796 {
1797 drawSurface = drawDepthStencil->getSurface();
1798 }
1799
1800 if (!readSurface || !drawSurface)
1801 {
1802 ERR("Failed to retrieve the render target.");
1803 return error(GL_OUT_OF_MEMORY, false);
1804 }
1805
1806 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
1807
1808 readSurface->Release();
1809 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001810
1811 if (FAILED(result))
1812 {
1813 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1814 return false;
1815 }
1816 }
1817
1818 return true;
1819}
1820
1821void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
1822 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
1823{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001824 RenderTarget9 *renderTarget = NULL;
1825 IDirect3DSurface9 *surface = NULL;
1826 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
1827
1828 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001829 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001830 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
1831 }
1832
1833 if (renderTarget)
1834 {
1835 surface = renderTarget->getSurface();
1836 }
1837
1838 if (!surface)
1839 {
1840 // context must be lost
1841 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001842 }
1843
1844 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001845 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001846
1847 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
1848 {
1849 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001850 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001851 return error(GL_OUT_OF_MEMORY);
1852 }
1853
1854 HRESULT result;
1855 IDirect3DSurface9 *systemSurface = NULL;
1856 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
1857 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
1858 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
1859 if (directToPixels)
1860 {
1861 // Use the pixels ptr as a shared handle to write directly into client's memory
1862 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
1863 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
1864 if (FAILED(result))
1865 {
1866 // Try again without the shared handle
1867 directToPixels = false;
1868 }
1869 }
1870
1871 if (!directToPixels)
1872 {
1873 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
1874 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
1875 if (FAILED(result))
1876 {
1877 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001878 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001879 return error(GL_OUT_OF_MEMORY);
1880 }
1881 }
1882
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001883 result = mDevice->GetRenderTargetData(surface, systemSurface);
1884 surface->Release();
1885 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001886
1887 if (FAILED(result))
1888 {
1889 systemSurface->Release();
1890
1891 // It turns out that D3D will sometimes produce more error
1892 // codes than those documented.
1893 if (gl::checkDeviceLost(result))
1894 return error(GL_OUT_OF_MEMORY);
1895 else
1896 {
1897 UNREACHABLE();
1898 return;
1899 }
1900
1901 }
1902
1903 if (directToPixels)
1904 {
1905 systemSurface->Release();
1906 return;
1907 }
1908
1909 RECT rect;
1910 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
1911 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
1912 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
1913 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
1914
1915 D3DLOCKED_RECT lock;
1916 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
1917
1918 if (FAILED(result))
1919 {
1920 UNREACHABLE();
1921 systemSurface->Release();
1922
1923 return; // No sensible error to generate
1924 }
1925
1926 unsigned char *dest = (unsigned char*)pixels;
1927 unsigned short *dest16 = (unsigned short*)pixels;
1928
1929 unsigned char *source;
1930 int inputPitch;
1931 if (packReverseRowOrder)
1932 {
1933 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
1934 inputPitch = -lock.Pitch;
1935 }
1936 else
1937 {
1938 source = (unsigned char*)lock.pBits;
1939 inputPitch = lock.Pitch;
1940 }
1941
1942 unsigned int fastPixelSize = 0;
1943
1944 if (desc.Format == D3DFMT_A8R8G8B8 &&
1945 format == GL_BGRA_EXT &&
1946 type == GL_UNSIGNED_BYTE)
1947 {
1948 fastPixelSize = 4;
1949 }
1950 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
1951 format == GL_BGRA_EXT &&
1952 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
1953 (desc.Format == D3DFMT_A1R5G5B5 &&
1954 format == GL_BGRA_EXT &&
1955 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
1956 {
1957 fastPixelSize = 2;
1958 }
1959 else if (desc.Format == D3DFMT_A16B16G16R16F &&
1960 format == GL_RGBA &&
1961 type == GL_HALF_FLOAT_OES)
1962 {
1963 fastPixelSize = 8;
1964 }
1965 else if (desc.Format == D3DFMT_A32B32G32R32F &&
1966 format == GL_RGBA &&
1967 type == GL_FLOAT)
1968 {
1969 fastPixelSize = 16;
1970 }
1971
1972 for (int j = 0; j < rect.bottom - rect.top; j++)
1973 {
1974 if (fastPixelSize != 0)
1975 {
1976 // Fast path for formats which require no translation:
1977 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
1978 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
1979 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
1980 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
1981 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
1982 //
1983 // Note that buffers with no alpha go through the slow path below.
1984 memcpy(dest + j * outputPitch,
1985 source + j * inputPitch,
1986 (rect.right - rect.left) * fastPixelSize);
1987 continue;
1988 }
1989
1990 for (int i = 0; i < rect.right - rect.left; i++)
1991 {
1992 float r;
1993 float g;
1994 float b;
1995 float a;
1996
1997 switch (desc.Format)
1998 {
1999 case D3DFMT_R5G6B5:
2000 {
2001 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2002
2003 a = 1.0f;
2004 b = (rgb & 0x001F) * (1.0f / 0x001F);
2005 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2006 r = (rgb & 0xF800) * (1.0f / 0xF800);
2007 }
2008 break;
2009 case D3DFMT_A1R5G5B5:
2010 {
2011 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2012
2013 a = (argb & 0x8000) ? 1.0f : 0.0f;
2014 b = (argb & 0x001F) * (1.0f / 0x001F);
2015 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2016 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2017 }
2018 break;
2019 case D3DFMT_A8R8G8B8:
2020 {
2021 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2022
2023 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2024 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2025 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2026 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2027 }
2028 break;
2029 case D3DFMT_X8R8G8B8:
2030 {
2031 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2032
2033 a = 1.0f;
2034 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2035 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2036 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2037 }
2038 break;
2039 case D3DFMT_A2R10G10B10:
2040 {
2041 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2042
2043 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2044 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2045 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2046 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2047 }
2048 break;
2049 case D3DFMT_A32B32G32R32F:
2050 {
2051 // float formats in D3D are stored rgba, rather than the other way round
2052 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2053 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2054 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2055 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2056 }
2057 break;
2058 case D3DFMT_A16B16G16R16F:
2059 {
2060 // float formats in D3D are stored rgba, rather than the other way round
2061 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2062 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2063 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2064 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2065 }
2066 break;
2067 default:
2068 UNIMPLEMENTED(); // FIXME
2069 UNREACHABLE();
2070 return;
2071 }
2072
2073 switch (format)
2074 {
2075 case GL_RGBA:
2076 switch (type)
2077 {
2078 case GL_UNSIGNED_BYTE:
2079 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2080 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2081 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2082 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2083 break;
2084 default: UNREACHABLE();
2085 }
2086 break;
2087 case GL_BGRA_EXT:
2088 switch (type)
2089 {
2090 case GL_UNSIGNED_BYTE:
2091 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2092 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2093 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2094 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2095 break;
2096 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2097 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2098 // this type is packed as follows:
2099 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2100 // --------------------------------------------------------------------------------
2101 // | 4th | 3rd | 2nd | 1st component |
2102 // --------------------------------------------------------------------------------
2103 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2104 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2105 ((unsigned short)(15 * a + 0.5f) << 12)|
2106 ((unsigned short)(15 * r + 0.5f) << 8) |
2107 ((unsigned short)(15 * g + 0.5f) << 4) |
2108 ((unsigned short)(15 * b + 0.5f) << 0);
2109 break;
2110 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2111 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2112 // this type is packed as follows:
2113 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2114 // --------------------------------------------------------------------------------
2115 // | 4th | 3rd | 2nd | 1st component |
2116 // --------------------------------------------------------------------------------
2117 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2118 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2119 ((unsigned short)( a + 0.5f) << 15) |
2120 ((unsigned short)(31 * r + 0.5f) << 10) |
2121 ((unsigned short)(31 * g + 0.5f) << 5) |
2122 ((unsigned short)(31 * b + 0.5f) << 0);
2123 break;
2124 default: UNREACHABLE();
2125 }
2126 break;
2127 case GL_RGB:
2128 switch (type)
2129 {
2130 case GL_UNSIGNED_SHORT_5_6_5:
2131 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2132 ((unsigned short)(31 * b + 0.5f) << 0) |
2133 ((unsigned short)(63 * g + 0.5f) << 5) |
2134 ((unsigned short)(31 * r + 0.5f) << 11);
2135 break;
2136 case GL_UNSIGNED_BYTE:
2137 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2138 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2139 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2140 break;
2141 default: UNREACHABLE();
2142 }
2143 break;
2144 default: UNREACHABLE();
2145 }
2146 }
2147 }
2148
2149 systemSurface->UnlockRect();
2150
2151 systemSurface->Release();
2152}
2153
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002154RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2155{
2156 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2157 IDirect3DSurface9 *surface = NULL;
2158 if (depth)
2159 {
2160 surface = swapChain9->getDepthStencil();
2161 }
2162 else
2163 {
2164 surface = swapChain9->getRenderTarget();
2165 }
2166
2167 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2168
2169 return renderTarget;
2170}
2171
2172RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2173{
2174 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2175 return renderTarget;
2176}
2177
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002178bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2179{
2180 return mBlit->boxFilter(source, dest);
2181}
2182
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002183D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002184{
2185 if (mD3d9Ex != NULL)
2186 {
2187 return D3DPOOL_DEFAULT;
2188 }
2189 else
2190 {
2191 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2192 {
2193 return D3DPOOL_MANAGED;
2194 }
2195 }
2196
2197 return D3DPOOL_DEFAULT;
2198}
2199
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002200bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2201{
2202 if (source && dest)
2203 {
2204 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2205 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2206
2207 if (fromManaged)
2208 {
2209 D3DSURFACE_DESC desc;
2210 source->GetDesc(&desc);
2211
2212 IDirect3DSurface9 *surf = 0;
2213 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2214
2215 if (SUCCEEDED(result))
2216 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002217 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002218 result = device->UpdateSurface(surf, NULL, dest, NULL);
2219 surf->Release();
2220 }
2221 }
2222 else
2223 {
2224 endScene();
2225 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2226 }
2227
2228 if (FAILED(result))
2229 {
2230 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2231 return false;
2232 }
2233 }
2234
2235 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002236}
2237
2238VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
2239{
2240 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2241 {
2242 mVertexDeclCache[i].vertexDeclaration = NULL;
2243 mVertexDeclCache[i].lruCount = 0;
2244 }
2245
2246 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2247 {
2248 mAppliedVBs[i].serial = 0;
2249 }
2250
2251 mLastSetVDecl = NULL;
2252 mInstancingEnabled = true;
2253}
2254
2255VertexDeclarationCache::~VertexDeclarationCache()
2256{
2257 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2258 {
2259 if (mVertexDeclCache[i].vertexDeclaration)
2260 {
2261 mVertexDeclCache[i].vertexDeclaration->Release();
2262 }
2263 }
2264}
2265
2266GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, gl::TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
2267{
2268 *repeatDraw = 1;
2269
2270 int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
2271 int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
2272
2273 if (instances > 0)
2274 {
2275 // Find an indexed attribute to be mapped to D3D stream 0
2276 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2277 {
2278 if (attributes[i].active)
2279 {
2280 if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
2281 {
2282 if (attributes[i].divisor == 0)
2283 {
2284 indexedAttribute = i;
2285 }
2286 }
2287 else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2288 {
2289 if (attributes[i].divisor != 0)
2290 {
2291 instancedAttribute = i;
2292 }
2293 }
2294 else break; // Found both an indexed and instanced attribute
2295 }
2296 }
2297
2298 if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
2299 {
2300 return GL_INVALID_OPERATION;
2301 }
2302 }
2303
2304 D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
2305 D3DVERTEXELEMENT9 *element = &elements[0];
2306
2307 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2308 {
2309 if (attributes[i].active)
2310 {
2311 int stream = i;
2312
2313 if (instances > 0)
2314 {
2315 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
2316 if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2317 {
2318 *repeatDraw = instances;
2319 }
2320 else
2321 {
2322 if (i == indexedAttribute)
2323 {
2324 stream = 0;
2325 }
2326 else if (i == 0)
2327 {
2328 stream = indexedAttribute;
2329 }
2330
2331 UINT frequency = 1;
2332
2333 if (attributes[i].divisor == 0)
2334 {
2335 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
2336 }
2337 else
2338 {
2339 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
2340 }
2341
2342 device->SetStreamSourceFreq(stream, frequency);
2343 mInstancingEnabled = true;
2344 }
2345 }
2346
2347 if (mAppliedVBs[stream].serial != attributes[i].serial ||
2348 mAppliedVBs[stream].stride != attributes[i].stride ||
2349 mAppliedVBs[stream].offset != attributes[i].offset)
2350 {
2351 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
2352 mAppliedVBs[stream].serial = attributes[i].serial;
2353 mAppliedVBs[stream].stride = attributes[i].stride;
2354 mAppliedVBs[stream].offset = attributes[i].offset;
2355 }
2356
2357 element->Stream = stream;
2358 element->Offset = 0;
2359 element->Type = attributes[i].type;
2360 element->Method = D3DDECLMETHOD_DEFAULT;
2361 element->Usage = D3DDECLUSAGE_TEXCOORD;
2362 element->UsageIndex = programBinary->getSemanticIndex(i);
2363 element++;
2364 }
2365 }
2366
2367 if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2368 {
2369 if (mInstancingEnabled)
2370 {
2371 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2372 {
2373 device->SetStreamSourceFreq(i, 1);
2374 }
2375
2376 mInstancingEnabled = false;
2377 }
2378 }
2379
2380 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
2381 *(element++) = end;
2382
2383 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2384 {
2385 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
2386 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
2387 {
2388 entry->lruCount = ++mMaxLru;
2389 if(entry->vertexDeclaration != mLastSetVDecl)
2390 {
2391 device->SetVertexDeclaration(entry->vertexDeclaration);
2392 mLastSetVDecl = entry->vertexDeclaration;
2393 }
2394
2395 return GL_NO_ERROR;
2396 }
2397 }
2398
2399 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
2400
2401 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2402 {
2403 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
2404 {
2405 lastCache = &mVertexDeclCache[i];
2406 }
2407 }
2408
2409 if (lastCache->vertexDeclaration != NULL)
2410 {
2411 lastCache->vertexDeclaration->Release();
2412 lastCache->vertexDeclaration = NULL;
2413 // mLastSetVDecl is set to the replacement, so we don't have to worry
2414 // about it.
2415 }
2416
2417 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
2418 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
2419 device->SetVertexDeclaration(lastCache->vertexDeclaration);
2420 mLastSetVDecl = lastCache->vertexDeclaration;
2421 lastCache->lruCount = ++mMaxLru;
2422
2423 return GL_NO_ERROR;
2424}
2425
2426void VertexDeclarationCache::markStateDirty()
2427{
2428 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2429 {
2430 mAppliedVBs[i].serial = 0;
2431 }
2432
2433 mLastSetVDecl = NULL;
2434 mInstancingEnabled = true; // Forces it to be disabled when not used
2435}
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002436
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002437}