blob: d2eac1c9db02211debff1ad26773eee36c7fc48c [file] [log] [blame]
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001//
2// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
daniel@transgaming.com1d6aff22012-11-28 19:30:42 +00007// Renderer9.cpp: Implements a back-end specific class for the D3D9 renderer.
daniel@transgaming.com621ce052012-10-31 17:52:29 +00008
daniel@transgaming.com621ce052012-10-31 17:52:29 +00009#include "common/debug.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000010#include "libGLESv2/main.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000011#include "libGLESv2/utilities.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000012#include "libGLESv2/mathutil.h"
daniel@transgaming.com91207b72012-11-28 20:56:43 +000013#include "libGLESv2/Buffer.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000014#include "libGLESv2/Framebuffer.h"
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +000015#include "libGLESv2/Program.h"
16#include "libGLESv2/ProgramBinary.h"
daniel@transgaming.com50aadb02012-11-28 21:06:11 +000017#include "libGLESv2/renderer/IndexDataManager.h"
18#include "libGLESv2/renderer/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000019#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000020#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000021#include "libGLESv2/renderer/ShaderExecutable9.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000022#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +000023#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000024#include "libGLESv2/renderer/Image.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000025#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000026#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000027
daniel@transgaming.com3281f972012-10-31 18:38:51 +000028#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000029#include "libEGL/Display.h"
30
daniel@transgaming.com621ce052012-10-31 17:52:29 +000031// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
32#define REF_RAST 0
33
34// The "Debug This Pixel..." feature in PIX often fails when using the
35// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
36// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
37#if !defined(ANGLE_ENABLE_D3D9EX)
38// Enables use of the IDirect3D9Ex interface, when available
39#define ANGLE_ENABLE_D3D9EX 1
40#endif // !defined(ANGLE_ENABLE_D3D9EX)
41
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000042namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000043{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000044static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000045 {
46 D3DFMT_A1R5G5B5,
47 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
48 D3DFMT_A8R8G8B8,
49 D3DFMT_R5G6B5,
50 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
51 D3DFMT_X8R8G8B8
52 };
53
daniel@transgaming.com222ee082012-11-28 19:31:49 +000054static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000055 {
56 D3DFMT_UNKNOWN,
57 // D3DFMT_D16_LOCKABLE,
58 D3DFMT_D32,
59 // D3DFMT_D15S1,
60 D3DFMT_D24S8,
61 D3DFMT_D24X8,
62 // D3DFMT_D24X4S4,
63 D3DFMT_D16,
64 // D3DFMT_D32F_LOCKABLE,
65 // D3DFMT_D24FS8
66 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000067
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000068Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000069{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000070 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071
72 mD3d9 = NULL;
73 mD3d9Ex = NULL;
74 mDevice = NULL;
75 mDeviceEx = NULL;
76 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000077 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000078
79 mAdapter = D3DADAPTER_DEFAULT;
80
81 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
82 mDeviceType = D3DDEVTYPE_REF;
83 #else
84 mDeviceType = D3DDEVTYPE_HAL;
85 #endif
86
87 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000088
89 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000090
daniel@transgaming.com91207b72012-11-28 20:56:43 +000091 mAppliedIBSerial = 0;
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000092
93 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +000094
95 mVertexDataManager = NULL;
96 mIndexDataManager = NULL;
97 mLineLoopIB = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000098}
99
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000100Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000101{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000102 releaseDeviceResources();
103
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000104 if (mDevice)
105 {
106 // 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 +0000107 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000108 {
109 resetDevice();
110 }
111
112 mDevice->Release();
113 mDevice = NULL;
114 }
115
116 if (mDeviceEx)
117 {
118 mDeviceEx->Release();
119 mDeviceEx = NULL;
120 }
121
122 if (mD3d9)
123 {
124 mD3d9->Release();
125 mD3d9 = NULL;
126 }
127
128 if (mDeviceWindow)
129 {
130 DestroyWindow(mDeviceWindow);
131 mDeviceWindow = NULL;
132 }
133
134 if (mD3d9Ex)
135 {
136 mD3d9Ex->Release();
137 mD3d9Ex = NULL;
138 }
139
140 if (mD3d9Module)
141 {
142 mD3d9Module = NULL;
143 }
144
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000145 while (!mMultiSampleSupport.empty())
146 {
147 delete [] mMultiSampleSupport.begin()->second;
148 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
149 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000150}
151
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000152Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
153{
154 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
155 return static_cast<rx::Renderer9*>(renderer);
156}
157
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000158EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000159{
daniel@transgaming.com25e16af2012-11-28 21:05:57 +0000160 if (!initializeCompiler())
161 {
162 return EGL_NOT_INITIALIZED;
163 }
164
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000165 if (mSoftwareDevice)
166 {
167 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
168 }
169 else
170 {
171 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
172 }
173
174 if (mD3d9Module == NULL)
175 {
176 ERR("No D3D9 module found - aborting!\n");
177 return EGL_NOT_INITIALIZED;
178 }
179
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000180 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
181 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
182
183 // Use Direct3D9Ex if available. Among other things, this version is less
184 // inclined to report a lost context, for example when the user switches
185 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
186 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
187 {
188 ASSERT(mD3d9Ex);
189 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
190 ASSERT(mD3d9);
191 }
192 else
193 {
194 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
195 }
196
197 if (!mD3d9)
198 {
199 ERR("Could not create D3D9 device - aborting!\n");
200 return EGL_NOT_INITIALIZED;
201 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000202
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000203 if (mDc != NULL)
204 {
205 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
206 }
207
208 HRESULT result;
209
210 // Give up on getting device caps after about one second.
211 for (int i = 0; i < 10; ++i)
212 {
213 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
214 if (SUCCEEDED(result))
215 {
216 break;
217 }
218 else if (result == D3DERR_NOTAVAILABLE)
219 {
220 Sleep(100); // Give the driver some time to initialize/recover
221 }
222 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
223 {
224 ERR("failed to get device caps (0x%x)\n", result);
225 return EGL_NOT_INITIALIZED;
226 }
227 }
228
229 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
230 {
231 ERR("Renderer does not support PS 2.0. aborting!\n");
232 return EGL_NOT_INITIALIZED;
233 }
234
235 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
236 // This is required by Texture2D::convertToRenderTarget.
237 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
238 {
239 ERR("Renderer does not support stretctrect from textures!\n");
240 return EGL_NOT_INITIALIZED;
241 }
242
243 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
244
245 // ATI cards on XP have problems with non-power-of-two textures.
246 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
247 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
248 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
249 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
250
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000251 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
252 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
253
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000254 mMinSwapInterval = 4;
255 mMaxSwapInterval = 0;
256
257 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
258 {
259 mMinSwapInterval = std::min(mMinSwapInterval, 0);
260 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
261 }
262 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
263 {
264 mMinSwapInterval = std::min(mMinSwapInterval, 1);
265 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
266 }
267 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
268 {
269 mMinSwapInterval = std::min(mMinSwapInterval, 2);
270 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
271 }
272 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
273 {
274 mMinSwapInterval = std::min(mMinSwapInterval, 3);
275 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
276 }
277 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
278 {
279 mMinSwapInterval = std::min(mMinSwapInterval, 4);
280 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
281 }
282
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000283 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000284 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000285 {
286 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000287 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
288 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000289
290 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
291 {
292 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
293 {
294 max = j;
295 }
296 }
297 }
298
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000299 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000300 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000301 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000302 continue;
303
304 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000305 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
306 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000307
308 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
309 {
310 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
311 {
312 max = j;
313 }
314 }
315 }
316
317 mMaxSupportedSamples = max;
318
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000319 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
320 static const TCHAR className[] = TEXT("STATIC");
321
322 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
323
324 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
325 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
326
327 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
328 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
329 {
330 return EGL_BAD_ALLOC;
331 }
332
333 if (FAILED(result))
334 {
335 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
336
337 if (FAILED(result))
338 {
339 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
340 return EGL_BAD_ALLOC;
341 }
342 }
343
344 if (mD3d9Ex)
345 {
346 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
347 ASSERT(SUCCEEDED(result));
348 }
349
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000350 mVertexShaderCache.initialize(mDevice);
351 mPixelShaderCache.initialize(mDevice);
352
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000353 initializeDevice();
354
355 return EGL_SUCCESS;
356}
357
358// do any one-time device initialization
359// NOTE: this is also needed after a device lost/reset
360// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000361void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000362{
363 // Permanent non-default states
364 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
365 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
366
367 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
368 {
369 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
370 }
371 else
372 {
373 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
374 }
375
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000376 markAllStateDirty();
377
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000378 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000379
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000380 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000381 mBlit = new Blit(this);
daniel@transgaming.com31240482012-11-28 21:06:41 +0000382 mVertexDataManager = new rx::VertexDataManager(this);
383 mIndexDataManager = new rx::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000384}
385
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000386D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000387{
388 D3DPRESENT_PARAMETERS presentParameters = {0};
389
390 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
391 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
392 presentParameters.BackBufferCount = 1;
393 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
394 presentParameters.BackBufferWidth = 1;
395 presentParameters.BackBufferHeight = 1;
396 presentParameters.EnableAutoDepthStencil = FALSE;
397 presentParameters.Flags = 0;
398 presentParameters.hDeviceWindow = mDeviceWindow;
399 presentParameters.MultiSampleQuality = 0;
400 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
401 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
402 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
403 presentParameters.Windowed = TRUE;
404
405 return presentParameters;
406}
407
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000408int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000409{
410 D3DDISPLAYMODE currentDisplayMode;
411 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
412
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000413 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
414 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000415 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
416 int numConfigs = 0;
417
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000418 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000419 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000420 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000421
422 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
423
424 if (SUCCEEDED(result))
425 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000426 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000427 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000428 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000429 HRESULT result = D3D_OK;
430
431 if(depthStencilFormat != D3DFMT_UNKNOWN)
432 {
433 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
434 }
435
436 if (SUCCEEDED(result))
437 {
438 if(depthStencilFormat != D3DFMT_UNKNOWN)
439 {
440 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
441 }
442
443 if (SUCCEEDED(result))
444 {
445 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000446 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
447 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000448 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
449 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
450
451 (*configDescList)[numConfigs++] = newConfig;
452 }
453 }
454 }
455 }
456 }
457
458 return numConfigs;
459}
460
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000461void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000462{
463 delete [] (configDescList);
464}
465
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000466void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000467{
468 if (!mSceneStarted)
469 {
470 long result = mDevice->BeginScene();
471 if (SUCCEEDED(result)) {
472 // This is defensive checking against the device being
473 // lost at unexpected times.
474 mSceneStarted = true;
475 }
476 }
477}
478
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000479void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000480{
481 if (mSceneStarted)
482 {
483 // EndScene can fail if the device was lost, for example due
484 // to a TDR during a draw call.
485 mDevice->EndScene();
486 mSceneStarted = false;
487 }
488}
489
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000490// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000491void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000492{
493 HRESULT result;
494
495 IDirect3DQuery9* query = allocateEventQuery();
496 if (!query)
497 {
498 return;
499 }
500
501 result = query->Issue(D3DISSUE_END);
502 ASSERT(SUCCEEDED(result));
503
504 do
505 {
506 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
507
508 if(block && result == S_FALSE)
509 {
510 // Keep polling, but allow other threads to do something useful first
511 Sleep(0);
512 // explicitly check for device loss
513 // some drivers seem to return S_FALSE even if the device is lost
514 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000515 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000516 {
517 result = D3DERR_DEVICELOST;
518 }
519 }
520 }
521 while(block && result == S_FALSE);
522
523 freeEventQuery(query);
524
525 if (isDeviceLostError(result))
526 {
527 mDisplay->notifyDeviceLost();
528 }
529}
530
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000531SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
532{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000533 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000534}
535
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000536// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000537IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000538{
539 IDirect3DQuery9 *query = NULL;
540
541 if (mEventQueryPool.empty())
542 {
543 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
544 ASSERT(SUCCEEDED(result));
545 }
546 else
547 {
548 query = mEventQueryPool.back();
549 mEventQueryPool.pop_back();
550 }
551
552 return query;
553}
554
555// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000556void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000557{
558 if (mEventQueryPool.size() > 1000)
559 {
560 query->Release();
561 }
562 else
563 {
564 mEventQueryPool.push_back(query);
565 }
566}
567
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000568IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000569{
570 return mVertexShaderCache.create(function, length);
571}
572
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000573IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000574{
575 return mPixelShaderCache.create(function, length);
576}
577
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000578HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
579{
580 D3DPOOL Pool = getBufferPool(Usage);
581 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
582}
583
584HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
585{
586 D3DPOOL Pool = getBufferPool(Usage);
587 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
588}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000589
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000590void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000591{
592 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
593 int d3dSampler = index + d3dSamplerOffset;
594
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000595 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
596 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000597
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000598 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000599 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000600 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000601 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
602 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
603 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
604 if (mSupportsTextureFilterAnisotropy)
605 {
606 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
607 }
608}
609
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000610void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000611{
612 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
613 int d3dSampler = index + d3dSamplerOffset;
614 IDirect3DBaseTexture9 *d3dTexture = NULL;
615
616 if (texture)
617 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000618 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000619 if (texStorage)
620 {
621 d3dTexture = texStorage->getBaseTexture();
622 }
623 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000624 // in the texture class and we're unexpectedly missing the d3d texture
625 ASSERT(d3dTexture != NULL);
626 }
627
628 mDevice->SetTexture(d3dSampler, d3dTexture);
629}
630
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000631void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000632{
633 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000634
635 if (rasterStateChanged)
636 {
637 // Set the cull mode
638 if (rasterState.cullFace)
639 {
640 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
641 }
642 else
643 {
644 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
645 }
646
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000647 if (rasterState.polygonOffsetFill)
648 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000649 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000650 {
651 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
652
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000653 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000654 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
655 }
656 }
657 else
658 {
659 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
660 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
661 }
662
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000663 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000664 }
665
666 mForceSetRasterState = false;
667}
668
669void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
670{
671 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
672 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
673 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
674
675 if (blendStateChanged || blendColorChanged)
676 {
677 if (blendState.blend)
678 {
679 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
680
681 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
682 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
683 {
684 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
685 }
686 else
687 {
688 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
689 gl::unorm<8>(blendColor.alpha),
690 gl::unorm<8>(blendColor.alpha),
691 gl::unorm<8>(blendColor.alpha)));
692 }
693
694 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
695 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
696 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
697
698 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
699 blendState.destBlendRGB != blendState.destBlendAlpha ||
700 blendState.blendEquationRGB != blendState.blendEquationAlpha)
701 {
702 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
703
704 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
705 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
706 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
707 }
708 else
709 {
710 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
711 }
712 }
713 else
714 {
715 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
716 }
717
718 if (blendState.sampleAlphaToCoverage)
719 {
720 FIXME("Sample alpha to coverage is unimplemented.");
721 }
722
723 // Set the color mask
724 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
725 // Apparently some ATI cards have a bug where a draw with a zero color
726 // write mask can cause later draws to have incorrect results. Instead,
727 // set a nonzero color write mask but modify the blend state so that no
728 // drawing is done.
729 // http://code.google.com/p/angleproject/issues/detail?id=169
730
731 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
732 blendState.colorMaskBlue, blendState.colorMaskAlpha);
733 if (colorMask == 0 && !zeroColorMaskAllowed)
734 {
735 // Enable green channel, but set blending so nothing will be drawn.
736 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
737 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
738
739 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
740 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
741 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
742 }
743 else
744 {
745 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
746 }
747
748 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
749
750 mCurBlendState = blendState;
751 mCurBlendColor = blendColor;
752 }
753
754 if (sampleMaskChanged)
755 {
756 // Set the multisample mask
757 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
758 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
759
760 mCurSampleMask = sampleMask;
761 }
762
763 mForceSetBlendState = false;
764}
765
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000766void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000767 int stencilBackRef, bool frontFaceCCW)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000768{
769 bool depthStencilStateChanged = mForceSetDepthStencilState ||
770 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000771 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
772 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000773 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000774
775 if (depthStencilStateChanged)
776 {
777 if (depthStencilState.depthTest)
778 {
779 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
780 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
781 }
782 else
783 {
784 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
785 }
786
787 mCurDepthStencilState = depthStencilState;
788 }
789
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000790 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000791 {
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000792 if (depthStencilState.stencilTest && mCurStencilSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000793 {
794 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
795 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
796
797 // FIXME: Unsupported by D3D9
798 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
799 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
800 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
801 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000802 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000803 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
804 {
805 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
806 return error(GL_INVALID_OPERATION);
807 }
808
809 // get the maximum size of the stencil ref
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000810 unsigned int maxStencil = (1 << mCurStencilSize) - 1;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000811
812 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
813 depthStencilState.stencilWritemask);
814 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
815 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
816
817 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000818 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000819 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
820 depthStencilState.stencilMask);
821
822 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
823 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
824 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
825 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
826 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
827 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
828
829 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
830 depthStencilState.stencilBackWritemask);
831 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
832 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
833
834 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000835 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000836 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
837 depthStencilState.stencilBackMask);
838
839 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
840 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
841 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
842 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
843 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
844 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
845 }
846 else
847 {
848 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
849 }
850
851 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
852
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000853 mCurStencilRef = stencilRef;
854 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000855 mCurFrontFaceCCW = frontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000856 }
857
858 mForceSetDepthStencilState = false;
859}
860
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000861void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000862{
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000863 bool scissorChanged = mForceSetScissor ||
864 memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
865 enabled != mScissorEnabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000866
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000867 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000868 {
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000869 if (enabled)
870 {
871 RECT rect;
872 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
873 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
874 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
875 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
876 mDevice->SetScissorRect(&rect);
877 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000878
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000879 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enabled ? TRUE : FALSE);
880
881 mScissorEnabled = enabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000882 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000883 }
884
885 mForceSetScissor = false;
886}
887
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000888bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, bool ignoreViewport,
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000889 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
890{
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000891 gl::Rectangle actualViewport = viewport;
892 float actualZNear = gl::clamp01(zNear);
893 float actualZFar = gl::clamp01(zFar);
894 if (ignoreViewport)
895 {
896 actualViewport.x = 0;
897 actualViewport.y = 0;
898 actualViewport.width = mRenderTargetDesc.width;
899 actualViewport.height = mRenderTargetDesc.height;
900 actualZNear = 0.0f;
901 actualZFar = 1.0f;
902 }
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000903
904 D3DVIEWPORT9 dxViewport;
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000905 dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
906 dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
907 dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
908 dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
909 dxViewport.MinZ = actualZNear;
910 dxViewport.MaxZ = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000911
912 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
913 {
914 return false; // Nothing to render
915 }
916
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000917 bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
918 actualZNear != mCurNear || actualZFar != mCurFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000919 if (viewportChanged)
920 {
921 mDevice->SetViewport(&dxViewport);
922
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000923 mCurViewport = actualViewport;
924 mCurNear = actualZNear;
925 mCurFar = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000926 }
927
928 if (currentProgram && (viewportChanged || forceSetUniforms))
929 {
930 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
931 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
932 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
933
934 // These values are used for computing gl_FragCoord in Program::linkVaryings().
935 GLint coord = currentProgram->getDxCoordLocation();
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000936 GLfloat whxy[4] = { actualViewport.width * 0.5f,
937 actualViewport.height * 0.5f,
938 actualViewport.x + (actualViewport.width * 0.5f),
939 actualViewport.y + (actualViewport.height * 0.5f) };
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000940 currentProgram->setUniform4fv(coord, 1, whxy);
941
942 GLint depth = currentProgram->getDxDepthLocation();
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000943 GLfloat dz[2] = { (actualZFar - actualZNear) * 0.5f, (actualZNear + actualZFar) * 0.5f };
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000944 currentProgram->setUniform2fv(depth, 1, dz);
945
946 GLint depthRange = currentProgram->getDxDepthRangeLocation();
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000947 GLfloat nearFarDiff[3] = { actualZNear, actualZFar, actualZFar - actualZNear };
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000948 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
949 }
950
951 mForceSetViewport = false;
952 return true;
953}
954
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000955bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
956{
957 switch (mode)
958 {
959 case GL_POINTS:
960 mPrimitiveType = D3DPT_POINTLIST;
961 mPrimitiveCount = count;
962 break;
963 case GL_LINES:
964 mPrimitiveType = D3DPT_LINELIST;
965 mPrimitiveCount = count / 2;
966 break;
967 case GL_LINE_LOOP:
968 mPrimitiveType = D3DPT_LINESTRIP;
969 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
970 break;
971 case GL_LINE_STRIP:
972 mPrimitiveType = D3DPT_LINESTRIP;
973 mPrimitiveCount = count - 1;
974 break;
975 case GL_TRIANGLES:
976 mPrimitiveType = D3DPT_TRIANGLELIST;
977 mPrimitiveCount = count / 3;
978 break;
979 case GL_TRIANGLE_STRIP:
980 mPrimitiveType = D3DPT_TRIANGLESTRIP;
981 mPrimitiveCount = count - 2;
982 break;
983 case GL_TRIANGLE_FAN:
984 mPrimitiveType = D3DPT_TRIANGLEFAN;
985 mPrimitiveCount = count - 2;
986 break;
987 default:
988 return error(GL_INVALID_ENUM, false);
989 }
990
991 return mPrimitiveCount > 0;
992}
993
daniel@transgaming.comae39ee22012-11-28 19:42:02 +0000994bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000995{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +0000996 // if there is no color attachment we must synthesize a NULL colorattachment
997 // to keep the D3D runtime happy. This should only be possible if depth texturing.
998 gl::Renderbuffer *renderbufferObject = NULL;
999 if (framebuffer->getColorbufferType() != GL_NONE)
1000 {
1001 renderbufferObject = framebuffer->getColorbuffer();
1002 }
1003 else
1004 {
1005 renderbufferObject = framebuffer->getNullColorbuffer();
1006 }
1007 if (!renderbufferObject)
1008 {
1009 ERR("unable to locate renderbuffer for FBO.");
1010 return false;
1011 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001012
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001013 bool renderTargetChanged = false;
1014 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1015 if (renderTargetSerial != mAppliedRenderTargetSerial)
1016 {
1017 // Apply the render target on the device
1018 IDirect3DSurface9 *renderTargetSurface = NULL;
1019
1020 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1021 if (renderTarget)
1022 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001023 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001024 }
1025
1026 if (!renderTargetSurface)
1027 {
1028 ERR("render target pointer unexpectedly null.");
1029 return false; // Context must be lost
1030 }
1031
1032 mDevice->SetRenderTarget(0, renderTargetSurface);
1033 renderTargetSurface->Release();
1034
1035 mAppliedRenderTargetSerial = renderTargetSerial;
1036 renderTargetChanged = true;
1037 }
1038
1039 gl::Renderbuffer *depthStencil = NULL;
1040 unsigned int depthbufferSerial = 0;
1041 unsigned int stencilbufferSerial = 0;
1042 if (framebuffer->getDepthbufferType() != GL_NONE)
1043 {
1044 depthStencil = framebuffer->getDepthbuffer();
1045 if (!depthStencil)
1046 {
1047 ERR("Depth stencil pointer unexpectedly null.");
1048 return false;
1049 }
1050
1051 depthbufferSerial = depthStencil->getSerial();
1052 }
1053 else if (framebuffer->getStencilbufferType() != GL_NONE)
1054 {
1055 depthStencil = framebuffer->getStencilbuffer();
1056 if (!depthStencil)
1057 {
1058 ERR("Depth stencil pointer unexpectedly null.");
1059 return false;
1060 }
1061
1062 stencilbufferSerial = depthStencil->getSerial();
1063 }
1064
1065 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1066 stencilbufferSerial != mAppliedStencilbufferSerial ||
1067 !mDepthStencilInitialized)
1068 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001069 unsigned int depthSize = 0;
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001070 unsigned int stencilSize = 0;
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001071
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001072 // Apply the depth stencil on the device
1073 if (depthStencil)
1074 {
1075 IDirect3DSurface9 *depthStencilSurface = NULL;
1076 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1077
1078 if (depthStencilRenderTarget)
1079 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001080 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001081 }
1082
1083 if (!depthStencilSurface)
1084 {
1085 ERR("depth stencil pointer unexpectedly null.");
1086 return false; // Context must be lost
1087 }
1088
1089 mDevice->SetDepthStencilSurface(depthStencilSurface);
1090 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001091
1092 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001093 stencilSize = depthStencil->getStencilSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001094 }
1095 else
1096 {
1097 mDevice->SetDepthStencilSurface(NULL);
1098 }
1099
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001100 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1101 {
1102 mCurDepthSize = depthSize;
1103 mForceSetRasterState = true;
1104 }
1105
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001106 if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
1107 {
1108 mCurStencilSize = stencilSize;
1109 mForceSetDepthStencilState = true;
1110 }
1111
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001112 mAppliedDepthbufferSerial = depthbufferSerial;
1113 mAppliedStencilbufferSerial = stencilbufferSerial;
1114 mDepthStencilInitialized = true;
1115 }
1116
1117 if (renderTargetChanged || !mRenderTargetDescInitialized)
1118 {
1119 mForceSetScissor = true;
1120 mForceSetViewport = true;
1121
1122 mRenderTargetDesc.width = renderbufferObject->getWidth();
1123 mRenderTargetDesc.height = renderbufferObject->getHeight();
1124 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1125 mRenderTargetDescInitialized = true;
1126 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001127
1128 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001129}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001130
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001131GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001132{
daniel@transgaming.com31240482012-11-28 21:06:41 +00001133 TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001134 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1135 if (err != GL_NO_ERROR)
1136 {
1137 return err;
1138 }
1139
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001140 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1141}
1142
1143// Applies the indices and element array bindings to the Direct3D 9 device
daniel@transgaming.com31240482012-11-28 21:06:41 +00001144GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001145{
1146 IDirect3DIndexBuffer9 *indexBuffer;
1147 unsigned int serial;
1148 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1149
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001150 if (err == GL_NO_ERROR)
1151 {
1152 if (serial != mAppliedIBSerial)
1153 {
1154 mDevice->SetIndices(indexBuffer);
1155 mAppliedIBSerial = serial;
1156 }
1157 }
1158
1159 return err;
1160}
1161
1162void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1163{
1164 startScene();
1165
1166 if (mode == GL_LINE_LOOP)
1167 {
1168 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1169 }
1170 else if (instances > 0)
1171 {
daniel@transgaming.com31240482012-11-28 21:06:41 +00001172 StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001173 if (countingIB)
1174 {
1175 if (mAppliedIBSerial != countingIB->getSerial())
1176 {
1177 mDevice->SetIndices(countingIB->getBuffer());
1178 mAppliedIBSerial = countingIB->getSerial();
1179 }
1180
1181 for (int i = 0; i < mRepeatDraw; i++)
1182 {
1183 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1184 }
1185 }
1186 else
1187 {
1188 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1189 return error(GL_OUT_OF_MEMORY);
1190 }
1191 }
1192 else // Regular case
1193 {
1194 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1195 }
1196}
1197
daniel@transgaming.com31240482012-11-28 21:06:41 +00001198void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001199{
1200 startScene();
1201
1202 if (mode == GL_LINE_LOOP)
1203 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001204 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001205 }
1206 else
1207 {
1208 for (int i = 0; i < mRepeatDraw; i++)
1209 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001210 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1211 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001212 }
1213 }
1214}
1215
1216void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1217{
1218 // Get the raw indices for an indexed draw
1219 if (type != GL_NONE && elementArrayBuffer)
1220 {
1221 gl::Buffer *indexBuffer = elementArrayBuffer;
1222 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1223 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1224 }
1225
1226 UINT startIndex = 0;
1227 bool succeeded = false;
1228
1229 if (get32BitIndexSupport())
1230 {
1231 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1232
1233 if (!mLineLoopIB)
1234 {
daniel@transgaming.com31240482012-11-28 21:06:41 +00001235 mLineLoopIB = new StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001236 }
1237
1238 if (mLineLoopIB)
1239 {
1240 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1241
1242 UINT offset = 0;
1243 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1244 startIndex = offset / 4;
1245
1246 if (data)
1247 {
1248 switch (type)
1249 {
1250 case GL_NONE: // Non-indexed draw
1251 for (int i = 0; i < count; i++)
1252 {
1253 data[i] = i;
1254 }
1255 data[count] = 0;
1256 break;
1257 case GL_UNSIGNED_BYTE:
1258 for (int i = 0; i < count; i++)
1259 {
1260 data[i] = static_cast<const GLubyte*>(indices)[i];
1261 }
1262 data[count] = static_cast<const GLubyte*>(indices)[0];
1263 break;
1264 case GL_UNSIGNED_SHORT:
1265 for (int i = 0; i < count; i++)
1266 {
1267 data[i] = static_cast<const GLushort*>(indices)[i];
1268 }
1269 data[count] = static_cast<const GLushort*>(indices)[0];
1270 break;
1271 case GL_UNSIGNED_INT:
1272 for (int i = 0; i < count; i++)
1273 {
1274 data[i] = static_cast<const GLuint*>(indices)[i];
1275 }
1276 data[count] = static_cast<const GLuint*>(indices)[0];
1277 break;
1278 default: UNREACHABLE();
1279 }
1280
1281 mLineLoopIB->unmap();
1282 succeeded = true;
1283 }
1284 }
1285 }
1286 else
1287 {
1288 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1289
1290 if (!mLineLoopIB)
1291 {
daniel@transgaming.com31240482012-11-28 21:06:41 +00001292 mLineLoopIB = new StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001293 }
1294
1295 if (mLineLoopIB)
1296 {
1297 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1298
1299 UINT offset = 0;
1300 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1301 startIndex = offset / 2;
1302
1303 if (data)
1304 {
1305 switch (type)
1306 {
1307 case GL_NONE: // Non-indexed draw
1308 for (int i = 0; i < count; i++)
1309 {
1310 data[i] = i;
1311 }
1312 data[count] = 0;
1313 break;
1314 case GL_UNSIGNED_BYTE:
1315 for (int i = 0; i < count; i++)
1316 {
1317 data[i] = static_cast<const GLubyte*>(indices)[i];
1318 }
1319 data[count] = static_cast<const GLubyte*>(indices)[0];
1320 break;
1321 case GL_UNSIGNED_SHORT:
1322 for (int i = 0; i < count; i++)
1323 {
1324 data[i] = static_cast<const GLushort*>(indices)[i];
1325 }
1326 data[count] = static_cast<const GLushort*>(indices)[0];
1327 break;
1328 case GL_UNSIGNED_INT:
1329 for (int i = 0; i < count; i++)
1330 {
1331 data[i] = static_cast<const GLuint*>(indices)[i];
1332 }
1333 data[count] = static_cast<const GLuint*>(indices)[0];
1334 break;
1335 default: UNREACHABLE();
1336 }
1337
1338 mLineLoopIB->unmap();
1339 succeeded = true;
1340 }
1341 }
1342 }
1343
1344 if (succeeded)
1345 {
1346 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1347 {
1348 mDevice->SetIndices(mLineLoopIB->getBuffer());
1349 mAppliedIBSerial = mLineLoopIB->getSerial();
1350 }
1351
1352 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1353 }
1354 else
1355 {
1356 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1357 return error(GL_OUT_OF_MEMORY);
1358 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001359}
1360
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001361void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1362{
daniel@transgaming.com95892412012-11-28 20:59:09 +00001363 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1364 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
1365
1366 IDirect3DVertexShader9 *vertexShader = NULL;
1367 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
1368
1369 IDirect3DPixelShader9 *pixelShader = NULL;
1370 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001371
1372 mDevice->SetPixelShader(pixelShader);
1373 mDevice->SetVertexShader(vertexShader);
1374 programBinary->dirtyAllUniforms();
1375}
1376
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001377void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001378{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001379 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1380 gl::unorm<8>(clearParams.colorClearValue.red),
1381 gl::unorm<8>(clearParams.colorClearValue.green),
1382 gl::unorm<8>(clearParams.colorClearValue.blue));
1383 float depth = gl::clamp01(clearParams.depthClearValue);
1384 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001385
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001386 unsigned int stencilUnmasked = 0x0;
1387 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1388 {
1389 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1390 stencilUnmasked = (0x1 << stencilSize) - 1;
1391 }
1392
1393 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1394
1395 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1396 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1397 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1398 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1399 clearParams.colorMaskBlue && alphaUnmasked);
1400
1401 if (needMaskedColorClear || needMaskedStencilClear)
1402 {
1403 // State which is altered in all paths from this point to the clear call is saved.
1404 // State which is altered in only some paths will be flagged dirty in the case that
1405 // that path is taken.
1406 HRESULT hr;
1407 if (mMaskedClearSavedState == NULL)
1408 {
1409 hr = mDevice->BeginStateBlock();
1410 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1411
1412 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1413 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1414 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1415 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1416 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1417 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1418 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1419 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1420 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1421 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1422 mDevice->SetPixelShader(NULL);
1423 mDevice->SetVertexShader(NULL);
1424 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1425 mDevice->SetStreamSource(0, NULL, 0, 0);
1426 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1427 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1428 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1429 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1430 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1431 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1432 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1433
1434 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1435 {
1436 mDevice->SetStreamSourceFreq(i, 1);
1437 }
1438
1439 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1440 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1441 }
1442
1443 ASSERT(mMaskedClearSavedState != NULL);
1444
1445 if (mMaskedClearSavedState != NULL)
1446 {
1447 hr = mMaskedClearSavedState->Capture();
1448 ASSERT(SUCCEEDED(hr));
1449 }
1450
1451 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1452 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1453 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1454 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1455 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1456 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1457 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1458 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1459
1460 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1461 {
1462 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1463 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1464 clearParams.colorMaskGreen,
1465 clearParams.colorMaskBlue,
1466 clearParams.colorMaskAlpha));
1467 }
1468 else
1469 {
1470 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1471 }
1472
1473 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1474 {
1475 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1476 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1477 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1478 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1479 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1480 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1481 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1482 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1483 }
1484 else
1485 {
1486 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1487 }
1488
1489 mDevice->SetPixelShader(NULL);
1490 mDevice->SetVertexShader(NULL);
1491 mDevice->SetFVF(D3DFVF_XYZRHW);
1492 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1493 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1494 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1495 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1496 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1497 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1498 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1499
1500 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1501 {
1502 mDevice->SetStreamSourceFreq(i, 1);
1503 }
1504
1505 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1506 quad[0][0] = -0.5f;
1507 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1508 quad[0][2] = 0.0f;
1509 quad[0][3] = 1.0f;
1510
1511 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1512 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1513 quad[1][2] = 0.0f;
1514 quad[1][3] = 1.0f;
1515
1516 quad[2][0] = -0.5f;
1517 quad[2][1] = -0.5f;
1518 quad[2][2] = 0.0f;
1519 quad[2][3] = 1.0f;
1520
1521 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1522 quad[3][1] = -0.5f;
1523 quad[3][2] = 0.0f;
1524 quad[3][3] = 1.0f;
1525
1526 startScene();
1527 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1528
1529 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1530 {
1531 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1532 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1533 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1534 }
1535
1536 if (mMaskedClearSavedState != NULL)
1537 {
1538 mMaskedClearSavedState->Apply();
1539 }
1540 }
1541 else if (clearParams.mask)
1542 {
1543 DWORD dxClearFlags = 0;
1544 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1545 {
1546 dxClearFlags |= D3DCLEAR_TARGET;
1547 }
1548 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1549 {
1550 dxClearFlags |= D3DCLEAR_ZBUFFER;
1551 }
1552 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1553 {
1554 dxClearFlags |= D3DCLEAR_STENCIL;
1555 }
1556
1557 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1558 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001559}
1560
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001561void Renderer9::markAllStateDirty()
1562{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001563 mAppliedRenderTargetSerial = 0;
1564 mAppliedDepthbufferSerial = 0;
1565 mAppliedStencilbufferSerial = 0;
1566 mDepthStencilInitialized = false;
1567 mRenderTargetDescInitialized = false;
1568
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001569 mForceSetDepthStencilState = true;
1570 mForceSetRasterState = true;
1571 mForceSetBlendState = true;
1572 mForceSetScissor = true;
1573 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001574
1575 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001576}
1577
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001578void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001579{
1580 while (!mEventQueryPool.empty())
1581 {
1582 mEventQueryPool.back()->Release();
1583 mEventQueryPool.pop_back();
1584 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001585
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001586 if (mMaskedClearSavedState)
1587 {
1588 mMaskedClearSavedState->Release();
1589 mMaskedClearSavedState = NULL;
1590 }
1591
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001592 mVertexShaderCache.clear();
1593 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001594
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001595 delete mBlit;
1596 mBlit = NULL;
1597
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001598 delete mVertexDataManager;
1599 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001600
1601 delete mIndexDataManager;
1602 mIndexDataManager = NULL;
1603
1604 delete mLineLoopIB;
1605 mLineLoopIB = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001606}
1607
1608
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001609void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001610{
1611 mDeviceLost = true;
1612}
1613
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001614bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001615{
1616 return mDeviceLost;
1617}
1618
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001619// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001620bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001621{
1622 bool isLost = false;
1623
1624 if (mDeviceEx)
1625 {
1626 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1627 }
1628 else if (mDevice)
1629 {
1630 isLost = FAILED(mDevice->TestCooperativeLevel());
1631 }
1632 else
1633 {
1634 // No device yet, so no reset required
1635 }
1636
1637 if (isLost)
1638 {
1639 // ensure we note the device loss --
1640 // we'll probably get this done again by markDeviceLost
1641 // but best to remember it!
1642 // Note that we don't want to clear the device loss status here
1643 // -- this needs to be done by resetDevice
1644 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001645 if (notify)
1646 {
1647 mDisplay->notifyDeviceLost();
1648 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001649 }
1650
1651 return isLost;
1652}
1653
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001654bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001655{
1656 HRESULT status = D3D_OK;
1657
1658 if (mDeviceEx)
1659 {
1660 status = mDeviceEx->CheckDeviceState(NULL);
1661 }
1662 else if (mDevice)
1663 {
1664 status = mDevice->TestCooperativeLevel();
1665 }
1666
1667 switch (status)
1668 {
1669 case D3DERR_DEVICENOTRESET:
1670 case D3DERR_DEVICEHUNG:
1671 return true;
1672 default:
1673 return false;
1674 }
1675}
1676
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001677bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001678{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001679 releaseDeviceResources();
1680
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001681 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1682
1683 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001684 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001685 int attempts = 3;
1686
1687 while (lost && attempts > 0)
1688 {
1689 if (mDeviceEx)
1690 {
1691 Sleep(500); // Give the graphics driver some CPU time
1692 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1693 }
1694 else
1695 {
1696 result = mDevice->TestCooperativeLevel();
1697 while (result == D3DERR_DEVICELOST)
1698 {
1699 Sleep(100); // Give the graphics driver some CPU time
1700 result = mDevice->TestCooperativeLevel();
1701 }
1702
1703 if (result == D3DERR_DEVICENOTRESET)
1704 {
1705 result = mDevice->Reset(&presentParameters);
1706 }
1707 }
1708
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001709 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001710 attempts --;
1711 }
1712
1713 if (FAILED(result))
1714 {
1715 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1716 return false;
1717 }
1718
1719 // reset device defaults
1720 initializeDevice();
1721 mDeviceLost = false;
1722
1723 return true;
1724}
1725
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001726DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001727{
1728 return mAdapterIdentifier.VendorId;
1729}
1730
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001731const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001732{
1733 return mAdapterIdentifier.Description;
1734}
1735
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001736GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001737{
1738 return mAdapterIdentifier.DeviceIdentifier;
1739}
1740
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001741void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001742{
1743 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1744 {
1745 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1746 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1747
1748 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1749 }
1750}
1751
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001752bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001753{
1754 D3DDISPLAYMODE currentDisplayMode;
1755 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1756
1757 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1758}
1759
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001760bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001761{
1762 D3DDISPLAYMODE currentDisplayMode;
1763 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1764
1765 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1766}
1767
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001768bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001769{
1770 D3DDISPLAYMODE currentDisplayMode;
1771 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1772
1773 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1774}
1775
1776// we use INTZ for depth textures in Direct3D9
1777// we also want NULL texture support to ensure the we can make depth-only FBOs
1778// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001779bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001780{
1781 D3DDISPLAYMODE currentDisplayMode;
1782 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1783
1784 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1785 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1786 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1787 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1788
1789 return intz && null;
1790}
1791
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001792bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001793{
1794 D3DDISPLAYMODE currentDisplayMode;
1795 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1796
1797 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1798 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1799 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1800 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1801
1802 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1803 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1804 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1805 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1806
1807 if (!*filtering && !*renderable)
1808 {
1809 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1810 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1811 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1812 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1813 }
1814 else
1815 {
1816 return true;
1817 }
1818}
1819
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001820bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001821{
1822 D3DDISPLAYMODE currentDisplayMode;
1823 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1824
1825 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1826 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1827 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1828 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1829
1830 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1831 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1832 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1833 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1834
1835 if (!*filtering && !*renderable)
1836 {
1837 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1838 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1839 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1840 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1841 }
1842 else
1843 {
1844 return true;
1845 }
1846}
1847
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001848bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001849{
1850 D3DDISPLAYMODE currentDisplayMode;
1851 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1852
1853 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1854}
1855
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001856bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001857{
1858 D3DDISPLAYMODE currentDisplayMode;
1859 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1860
1861 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1862}
1863
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001864bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001865{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001866 return mSupportsTextureFilterAnisotropy;
1867}
1868
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001869float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001870{
1871 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001872 {
1873 return mDeviceCaps.MaxAnisotropy;
1874 }
1875 return 1.0f;
1876}
1877
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001878bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001879{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001880 IDirect3DQuery9 *query = allocateEventQuery();
1881 if (query)
1882 {
1883 freeEventQuery(query);
1884 return true;
1885 }
1886 else
1887 {
1888 return false;
1889 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001890 return true;
1891}
1892
1893// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1894// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001895bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001896{
1897 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1898 {
1899 return false;
1900 }
1901
1902 D3DDISPLAYMODE currentDisplayMode;
1903 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1904
1905 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1906
1907 return SUCCEEDED(result);
1908}
1909
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001910bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001911{
1912 return mSupportsNonPower2Textures;
1913}
1914
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001915bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001916{
1917 if (!mDevice)
1918 {
1919 return false;
1920 }
1921
1922 IDirect3DQuery9 *query = NULL;
1923 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1924 if (SUCCEEDED(result) && query)
1925 {
1926 query->Release();
1927 return true;
1928 }
1929 else
1930 {
1931 return false;
1932 }
1933}
1934
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001935bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001936{
1937 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1938}
1939
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001940bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001941{
1942 // PIX doesn't seem to support using share handles, so disable them.
1943 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001944 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001945}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001946
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001947int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001948{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001949 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001950}
1951
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001952float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001953{
1954 return mDeviceCaps.MaxPointSize;
1955}
1956
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001957int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001958{
1959 return (int)mDeviceCaps.MaxTextureWidth;
1960}
1961
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001962int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001963{
1964 return (int)mDeviceCaps.MaxTextureHeight;
1965}
1966
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001967bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001968{
1969 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1970}
1971
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001972DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001973{
1974 return mDeviceCaps.DeclTypes;
1975}
1976
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001977int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001978{
1979 return mMinSwapInterval;
1980}
1981
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001982int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001983{
1984 return mMaxSwapInterval;
1985}
1986
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001987int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001988{
1989 return mMaxSupportedSamples;
1990}
1991
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001992int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001993{
1994 if (requested == 0)
1995 {
1996 return requested;
1997 }
1998
1999 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2000 if (itr == mMultiSampleSupport.end())
2001 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002002 if (format == D3DFMT_UNKNOWN)
2003 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002004 return -1;
2005 }
2006
2007 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2008 {
2009 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2010 {
2011 return i;
2012 }
2013 }
2014
2015 return -1;
2016}
2017
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002018D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2019{
2020 switch (internalformat)
2021 {
2022 case GL_DEPTH_COMPONENT16:
2023 case GL_DEPTH_COMPONENT32_OES:
2024 case GL_DEPTH24_STENCIL8_OES:
2025 return D3DFMT_INTZ;
2026 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2027 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2028 return D3DFMT_DXT1;
2029 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2030 return D3DFMT_DXT3;
2031 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2032 return D3DFMT_DXT5;
2033 case GL_RGBA32F_EXT:
2034 case GL_RGB32F_EXT:
2035 case GL_ALPHA32F_EXT:
2036 case GL_LUMINANCE32F_EXT:
2037 case GL_LUMINANCE_ALPHA32F_EXT:
2038 return D3DFMT_A32B32G32R32F;
2039 case GL_RGBA16F_EXT:
2040 case GL_RGB16F_EXT:
2041 case GL_ALPHA16F_EXT:
2042 case GL_LUMINANCE16F_EXT:
2043 case GL_LUMINANCE_ALPHA16F_EXT:
2044 return D3DFMT_A16B16G16R16F;
2045 case GL_LUMINANCE8_EXT:
2046 if (getLuminanceTextureSupport())
2047 {
2048 return D3DFMT_L8;
2049 }
2050 break;
2051 case GL_LUMINANCE8_ALPHA8_EXT:
2052 if (getLuminanceAlphaTextureSupport())
2053 {
2054 return D3DFMT_A8L8;
2055 }
2056 break;
2057 case GL_RGB8_OES:
2058 case GL_RGB565:
2059 return D3DFMT_X8R8G8B8;
2060 }
2061
2062 return D3DFMT_A8R8G8B8;
2063}
2064
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002065bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002066{
2067 bool result = false;
2068
2069 if (source && dest)
2070 {
2071 int levels = source->levelCount();
2072 for (int i = 0; i < levels; ++i)
2073 {
2074 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2075 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2076
2077 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2078
2079 if (srcSurf) srcSurf->Release();
2080 if (dstSurf) dstSurf->Release();
2081
2082 if (!result)
2083 return false;
2084 }
2085 }
2086
2087 return result;
2088}
2089
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002090bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002091{
2092 bool result = false;
2093
2094 if (source && dest)
2095 {
2096 int levels = source->levelCount();
2097 for (int f = 0; f < 6; f++)
2098 {
2099 for (int i = 0; i < levels; i++)
2100 {
2101 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2102 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2103
2104 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2105
2106 if (srcSurf) srcSurf->Release();
2107 if (dstSurf) dstSurf->Release();
2108
2109 if (!result)
2110 return false;
2111 }
2112 }
2113 }
2114
2115 return result;
2116}
2117
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002118D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002119{
2120 if (mD3d9Ex != NULL)
2121 {
2122 return D3DPOOL_DEFAULT;
2123 }
2124 else
2125 {
2126 if (!(usage & D3DUSAGE_DYNAMIC))
2127 {
2128 return D3DPOOL_MANAGED;
2129 }
2130 }
2131
2132 return D3DPOOL_DEFAULT;
2133}
2134
daniel@transgaming.com38380882012-11-28 19:36:39 +00002135bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2136 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002137{
2138 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2139}
2140
daniel@transgaming.com38380882012-11-28 19:36:39 +00002141bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2142 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002143{
2144 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2145}
2146
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002147bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2148 bool blitRenderTarget, bool blitDepthStencil)
2149{
2150 endScene();
2151
2152 if (blitRenderTarget)
2153 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002154 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2155 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2156 RenderTarget9 *readRenderTarget = NULL;
2157 RenderTarget9 *drawRenderTarget = NULL;
2158 IDirect3DSurface9* readSurface = NULL;
2159 IDirect3DSurface9* drawSurface = NULL;
2160
2161 if (readBuffer)
2162 {
2163 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2164 }
2165 if (drawBuffer)
2166 {
2167 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2168 }
2169
2170 if (readRenderTarget)
2171 {
2172 readSurface = readRenderTarget->getSurface();
2173 }
2174 if (drawRenderTarget)
2175 {
2176 drawSurface = drawRenderTarget->getSurface();
2177 }
2178
2179 if (!readSurface || !drawSurface)
2180 {
2181 ERR("Failed to retrieve the render target.");
2182 return error(GL_OUT_OF_MEMORY, false);
2183 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002184
2185 RECT srcRect, dstRect;
2186 RECT *srcRectPtr = NULL;
2187 RECT *dstRectPtr = NULL;
2188
2189 if (readRect)
2190 {
2191 srcRect.left = readRect->x;
2192 srcRect.right = readRect->x + readRect->width;
2193 srcRect.top = readRect->y;
2194 srcRect.bottom = readRect->y + readRect->height;
2195 srcRectPtr = &srcRect;
2196 }
2197
2198 if (drawRect)
2199 {
2200 dstRect.left = drawRect->x;
2201 dstRect.right = drawRect->x + drawRect->width;
2202 dstRect.top = drawRect->y;
2203 dstRect.bottom = drawRect->y + drawRect->height;
2204 dstRectPtr = &dstRect;
2205 }
2206
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002207 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002208
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002209 readSurface->Release();
2210 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002211
2212 if (FAILED(result))
2213 {
2214 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2215 return false;
2216 }
2217 }
2218
2219 if (blitDepthStencil)
2220 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002221 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2222 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2223 RenderTarget9 *readDepthStencil = NULL;
2224 RenderTarget9 *drawDepthStencil = NULL;
2225 IDirect3DSurface9* readSurface = NULL;
2226 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002227
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002228 if (readBuffer)
2229 {
2230 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2231 }
2232 if (drawBuffer)
2233 {
2234 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2235 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002236
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002237 if (readDepthStencil)
2238 {
2239 readSurface = readDepthStencil->getSurface();
2240 }
2241 if (drawDepthStencil)
2242 {
2243 drawSurface = drawDepthStencil->getSurface();
2244 }
2245
2246 if (!readSurface || !drawSurface)
2247 {
2248 ERR("Failed to retrieve the render target.");
2249 return error(GL_OUT_OF_MEMORY, false);
2250 }
2251
2252 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2253
2254 readSurface->Release();
2255 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002256
2257 if (FAILED(result))
2258 {
2259 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2260 return false;
2261 }
2262 }
2263
2264 return true;
2265}
2266
2267void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2268 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2269{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002270 RenderTarget9 *renderTarget = NULL;
2271 IDirect3DSurface9 *surface = NULL;
2272 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2273
2274 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002275 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002276 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2277 }
2278
2279 if (renderTarget)
2280 {
2281 surface = renderTarget->getSurface();
2282 }
2283
2284 if (!surface)
2285 {
2286 // context must be lost
2287 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002288 }
2289
2290 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002291 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002292
2293 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2294 {
2295 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002296 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002297 return error(GL_OUT_OF_MEMORY);
2298 }
2299
2300 HRESULT result;
2301 IDirect3DSurface9 *systemSurface = NULL;
2302 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2303 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2304 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2305 if (directToPixels)
2306 {
2307 // Use the pixels ptr as a shared handle to write directly into client's memory
2308 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2309 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2310 if (FAILED(result))
2311 {
2312 // Try again without the shared handle
2313 directToPixels = false;
2314 }
2315 }
2316
2317 if (!directToPixels)
2318 {
2319 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2320 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2321 if (FAILED(result))
2322 {
2323 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002324 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002325 return error(GL_OUT_OF_MEMORY);
2326 }
2327 }
2328
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002329 result = mDevice->GetRenderTargetData(surface, systemSurface);
2330 surface->Release();
2331 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002332
2333 if (FAILED(result))
2334 {
2335 systemSurface->Release();
2336
2337 // It turns out that D3D will sometimes produce more error
2338 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002339 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002340 return error(GL_OUT_OF_MEMORY);
2341 else
2342 {
2343 UNREACHABLE();
2344 return;
2345 }
2346
2347 }
2348
2349 if (directToPixels)
2350 {
2351 systemSurface->Release();
2352 return;
2353 }
2354
2355 RECT rect;
2356 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2357 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2358 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2359 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2360
2361 D3DLOCKED_RECT lock;
2362 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2363
2364 if (FAILED(result))
2365 {
2366 UNREACHABLE();
2367 systemSurface->Release();
2368
2369 return; // No sensible error to generate
2370 }
2371
2372 unsigned char *dest = (unsigned char*)pixels;
2373 unsigned short *dest16 = (unsigned short*)pixels;
2374
2375 unsigned char *source;
2376 int inputPitch;
2377 if (packReverseRowOrder)
2378 {
2379 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2380 inputPitch = -lock.Pitch;
2381 }
2382 else
2383 {
2384 source = (unsigned char*)lock.pBits;
2385 inputPitch = lock.Pitch;
2386 }
2387
2388 unsigned int fastPixelSize = 0;
2389
2390 if (desc.Format == D3DFMT_A8R8G8B8 &&
2391 format == GL_BGRA_EXT &&
2392 type == GL_UNSIGNED_BYTE)
2393 {
2394 fastPixelSize = 4;
2395 }
2396 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2397 format == GL_BGRA_EXT &&
2398 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2399 (desc.Format == D3DFMT_A1R5G5B5 &&
2400 format == GL_BGRA_EXT &&
2401 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2402 {
2403 fastPixelSize = 2;
2404 }
2405 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2406 format == GL_RGBA &&
2407 type == GL_HALF_FLOAT_OES)
2408 {
2409 fastPixelSize = 8;
2410 }
2411 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2412 format == GL_RGBA &&
2413 type == GL_FLOAT)
2414 {
2415 fastPixelSize = 16;
2416 }
2417
2418 for (int j = 0; j < rect.bottom - rect.top; j++)
2419 {
2420 if (fastPixelSize != 0)
2421 {
2422 // Fast path for formats which require no translation:
2423 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2424 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2425 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2426 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2427 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2428 //
2429 // Note that buffers with no alpha go through the slow path below.
2430 memcpy(dest + j * outputPitch,
2431 source + j * inputPitch,
2432 (rect.right - rect.left) * fastPixelSize);
2433 continue;
2434 }
2435
2436 for (int i = 0; i < rect.right - rect.left; i++)
2437 {
2438 float r;
2439 float g;
2440 float b;
2441 float a;
2442
2443 switch (desc.Format)
2444 {
2445 case D3DFMT_R5G6B5:
2446 {
2447 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2448
2449 a = 1.0f;
2450 b = (rgb & 0x001F) * (1.0f / 0x001F);
2451 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2452 r = (rgb & 0xF800) * (1.0f / 0xF800);
2453 }
2454 break;
2455 case D3DFMT_A1R5G5B5:
2456 {
2457 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2458
2459 a = (argb & 0x8000) ? 1.0f : 0.0f;
2460 b = (argb & 0x001F) * (1.0f / 0x001F);
2461 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2462 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2463 }
2464 break;
2465 case D3DFMT_A8R8G8B8:
2466 {
2467 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2468
2469 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2470 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2471 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2472 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2473 }
2474 break;
2475 case D3DFMT_X8R8G8B8:
2476 {
2477 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2478
2479 a = 1.0f;
2480 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2481 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2482 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2483 }
2484 break;
2485 case D3DFMT_A2R10G10B10:
2486 {
2487 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2488
2489 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2490 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2491 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2492 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2493 }
2494 break;
2495 case D3DFMT_A32B32G32R32F:
2496 {
2497 // float formats in D3D are stored rgba, rather than the other way round
2498 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2499 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2500 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2501 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2502 }
2503 break;
2504 case D3DFMT_A16B16G16R16F:
2505 {
2506 // float formats in D3D are stored rgba, rather than the other way round
2507 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2508 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2509 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2510 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2511 }
2512 break;
2513 default:
2514 UNIMPLEMENTED(); // FIXME
2515 UNREACHABLE();
2516 return;
2517 }
2518
2519 switch (format)
2520 {
2521 case GL_RGBA:
2522 switch (type)
2523 {
2524 case GL_UNSIGNED_BYTE:
2525 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2526 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2527 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2528 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2529 break;
2530 default: UNREACHABLE();
2531 }
2532 break;
2533 case GL_BGRA_EXT:
2534 switch (type)
2535 {
2536 case GL_UNSIGNED_BYTE:
2537 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2538 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2539 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2540 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2541 break;
2542 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2543 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2544 // this type is packed as follows:
2545 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2546 // --------------------------------------------------------------------------------
2547 // | 4th | 3rd | 2nd | 1st component |
2548 // --------------------------------------------------------------------------------
2549 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2550 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2551 ((unsigned short)(15 * a + 0.5f) << 12)|
2552 ((unsigned short)(15 * r + 0.5f) << 8) |
2553 ((unsigned short)(15 * g + 0.5f) << 4) |
2554 ((unsigned short)(15 * b + 0.5f) << 0);
2555 break;
2556 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2557 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2558 // this type is packed as follows:
2559 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2560 // --------------------------------------------------------------------------------
2561 // | 4th | 3rd | 2nd | 1st component |
2562 // --------------------------------------------------------------------------------
2563 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2564 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2565 ((unsigned short)( a + 0.5f) << 15) |
2566 ((unsigned short)(31 * r + 0.5f) << 10) |
2567 ((unsigned short)(31 * g + 0.5f) << 5) |
2568 ((unsigned short)(31 * b + 0.5f) << 0);
2569 break;
2570 default: UNREACHABLE();
2571 }
2572 break;
2573 case GL_RGB:
2574 switch (type)
2575 {
2576 case GL_UNSIGNED_SHORT_5_6_5:
2577 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2578 ((unsigned short)(31 * b + 0.5f) << 0) |
2579 ((unsigned short)(63 * g + 0.5f) << 5) |
2580 ((unsigned short)(31 * r + 0.5f) << 11);
2581 break;
2582 case GL_UNSIGNED_BYTE:
2583 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2584 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2585 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2586 break;
2587 default: UNREACHABLE();
2588 }
2589 break;
2590 default: UNREACHABLE();
2591 }
2592 }
2593 }
2594
2595 systemSurface->UnlockRect();
2596
2597 systemSurface->Release();
2598}
2599
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002600RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2601{
2602 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2603 IDirect3DSurface9 *surface = NULL;
2604 if (depth)
2605 {
2606 surface = swapChain9->getDepthStencil();
2607 }
2608 else
2609 {
2610 surface = swapChain9->getRenderTarget();
2611 }
2612
2613 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2614
2615 return renderTarget;
2616}
2617
2618RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2619{
2620 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2621 return renderTarget;
2622}
2623
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002624ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type, void *data)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002625{
2626 ShaderExecutable9 *executable = NULL;
daniel@transgaming.com31240482012-11-28 21:06:41 +00002627 D3DConstantTable *table = reinterpret_cast<D3DConstantTable *>(data);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002628
2629 switch (type)
2630 {
2631 case GL_VERTEX_SHADER:
2632 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002633 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002634 if (vshader)
2635 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002636 executable = new ShaderExecutable9(function, length, vshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002637 }
2638 }
2639 break;
2640 case GL_FRAGMENT_SHADER:
2641 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002642 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002643 if (pshader)
2644 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002645 executable = new ShaderExecutable9(function, length, pshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002646 }
2647 }
2648 break;
2649 default:
2650 UNREACHABLE();
2651 break;
2652 }
2653
2654 return executable;
2655}
2656
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002657ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2658{
2659 const char *profile = NULL;
2660
2661 switch (type)
2662 {
2663 case GL_VERTEX_SHADER:
2664 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2665 break;
2666 case GL_FRAGMENT_SHADER:
2667 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2668 break;
2669 default:
2670 UNREACHABLE();
2671 return NULL;
2672 }
2673
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002674 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002675 if (!binary)
2676 return NULL;
2677
daniel@transgaming.com31240482012-11-28 21:06:41 +00002678 D3DConstantTable *constantTable = new D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
daniel@transgaming.combe281b02012-11-28 21:05:48 +00002679 if (constantTable->error())
2680 {
2681 delete constantTable;
2682 binary->Release();
2683 return NULL;
2684 }
2685
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002686 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002687 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002688
2689 return executable;
2690}
2691
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002692bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2693{
2694 return mBlit->boxFilter(source, dest);
2695}
2696
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002697D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002698{
2699 if (mD3d9Ex != NULL)
2700 {
2701 return D3DPOOL_DEFAULT;
2702 }
2703 else
2704 {
2705 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2706 {
2707 return D3DPOOL_MANAGED;
2708 }
2709 }
2710
2711 return D3DPOOL_DEFAULT;
2712}
2713
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002714bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2715{
2716 if (source && dest)
2717 {
2718 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2719 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2720
2721 if (fromManaged)
2722 {
2723 D3DSURFACE_DESC desc;
2724 source->GetDesc(&desc);
2725
2726 IDirect3DSurface9 *surf = 0;
2727 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2728
2729 if (SUCCEEDED(result))
2730 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002731 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002732 result = device->UpdateSurface(surf, NULL, dest, NULL);
2733 surf->Release();
2734 }
2735 }
2736 else
2737 {
2738 endScene();
2739 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2740 }
2741
2742 if (FAILED(result))
2743 {
2744 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2745 return false;
2746 }
2747 }
2748
2749 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002750}
2751
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002752}