blob: 41ab0ab9ec62a29abd4e1ad9ba9895c6a3a614e1 [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);
382 mVertexDataManager = new gl::VertexDataManager(this);
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000383 mIndexDataManager = new gl::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
647 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
648
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000649 if (rasterState.polygonOffsetFill)
650 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000651 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000652 {
653 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
654
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000655 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000656 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
657 }
658 }
659 else
660 {
661 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
662 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
663 }
664
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000665 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000666 }
667
668 mForceSetRasterState = false;
669}
670
671void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
672{
673 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
674 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
675 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
676
677 if (blendStateChanged || blendColorChanged)
678 {
679 if (blendState.blend)
680 {
681 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
682
683 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
684 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
685 {
686 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
687 }
688 else
689 {
690 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
691 gl::unorm<8>(blendColor.alpha),
692 gl::unorm<8>(blendColor.alpha),
693 gl::unorm<8>(blendColor.alpha)));
694 }
695
696 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
697 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
698 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
699
700 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
701 blendState.destBlendRGB != blendState.destBlendAlpha ||
702 blendState.blendEquationRGB != blendState.blendEquationAlpha)
703 {
704 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
705
706 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
707 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
708 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
709 }
710 else
711 {
712 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
713 }
714 }
715 else
716 {
717 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
718 }
719
720 if (blendState.sampleAlphaToCoverage)
721 {
722 FIXME("Sample alpha to coverage is unimplemented.");
723 }
724
725 // Set the color mask
726 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
727 // Apparently some ATI cards have a bug where a draw with a zero color
728 // write mask can cause later draws to have incorrect results. Instead,
729 // set a nonzero color write mask but modify the blend state so that no
730 // drawing is done.
731 // http://code.google.com/p/angleproject/issues/detail?id=169
732
733 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
734 blendState.colorMaskBlue, blendState.colorMaskAlpha);
735 if (colorMask == 0 && !zeroColorMaskAllowed)
736 {
737 // Enable green channel, but set blending so nothing will be drawn.
738 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
739 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
740
741 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
742 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
743 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
744 }
745 else
746 {
747 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
748 }
749
750 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
751
752 mCurBlendState = blendState;
753 mCurBlendColor = blendColor;
754 }
755
756 if (sampleMaskChanged)
757 {
758 // Set the multisample mask
759 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
760 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
761
762 mCurSampleMask = sampleMask;
763 }
764
765 mForceSetBlendState = false;
766}
767
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000768void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000769 int stencilBackRef, bool frontFaceCCW)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000770{
771 bool depthStencilStateChanged = mForceSetDepthStencilState ||
772 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000773 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
774 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000775 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000776
777 if (depthStencilStateChanged)
778 {
779 if (depthStencilState.depthTest)
780 {
781 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
782 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
783 }
784 else
785 {
786 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
787 }
788
789 mCurDepthStencilState = depthStencilState;
790 }
791
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000792 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000793 {
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000794 if (depthStencilState.stencilTest && mCurStencilSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000795 {
796 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
797 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
798
799 // FIXME: Unsupported by D3D9
800 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
801 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
802 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
803 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000804 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000805 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
806 {
807 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
808 return error(GL_INVALID_OPERATION);
809 }
810
811 // get the maximum size of the stencil ref
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000812 unsigned int maxStencil = (1 << mCurStencilSize) - 1;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000813
814 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
815 depthStencilState.stencilWritemask);
816 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
817 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
818
819 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000820 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000821 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
822 depthStencilState.stencilMask);
823
824 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
825 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
826 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
827 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
828 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
829 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
830
831 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
832 depthStencilState.stencilBackWritemask);
833 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
834 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
835
836 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000837 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000838 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
839 depthStencilState.stencilBackMask);
840
841 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
842 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
843 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
844 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
845 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
846 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
847 }
848 else
849 {
850 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
851 }
852
853 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
854
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000855 mCurStencilRef = stencilRef;
856 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000857 mCurFrontFaceCCW = frontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000858 }
859
860 mForceSetDepthStencilState = false;
861}
862
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000863void Renderer9::setScissorRectangle(const gl::Rectangle &scissor)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000864{
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000865 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
866
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000867 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000868 {
869 RECT rect;
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000870 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
871 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
872 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
873 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000874 mDevice->SetScissorRect(&rect);
875
876 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000877 }
878
879 mForceSetScissor = false;
880}
881
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000882bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, bool ignoreViewport,
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000883 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
884{
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000885 gl::Rectangle actualViewport = viewport;
886 float actualZNear = gl::clamp01(zNear);
887 float actualZFar = gl::clamp01(zFar);
888 if (ignoreViewport)
889 {
890 actualViewport.x = 0;
891 actualViewport.y = 0;
892 actualViewport.width = mRenderTargetDesc.width;
893 actualViewport.height = mRenderTargetDesc.height;
894 actualZNear = 0.0f;
895 actualZFar = 1.0f;
896 }
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000897
898 D3DVIEWPORT9 dxViewport;
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000899 dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
900 dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
901 dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
902 dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
903 dxViewport.MinZ = actualZNear;
904 dxViewport.MaxZ = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000905
906 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
907 {
908 return false; // Nothing to render
909 }
910
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000911 bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
912 actualZNear != mCurNear || actualZFar != mCurFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000913 if (viewportChanged)
914 {
915 mDevice->SetViewport(&dxViewport);
916
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000917 mCurViewport = actualViewport;
918 mCurNear = actualZNear;
919 mCurFar = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000920 }
921
922 if (currentProgram && (viewportChanged || forceSetUniforms))
923 {
924 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
925 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
926 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
927
928 // These values are used for computing gl_FragCoord in Program::linkVaryings().
929 GLint coord = currentProgram->getDxCoordLocation();
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000930 GLfloat whxy[4] = { actualViewport.width * 0.5f,
931 actualViewport.height * 0.5f,
932 actualViewport.x + (actualViewport.width * 0.5f),
933 actualViewport.y + (actualViewport.height * 0.5f) };
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000934 currentProgram->setUniform4fv(coord, 1, whxy);
935
936 GLint depth = currentProgram->getDxDepthLocation();
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000937 GLfloat dz[2] = { (actualZFar - actualZNear) * 0.5f, (actualZNear + actualZFar) * 0.5f };
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000938 currentProgram->setUniform2fv(depth, 1, dz);
939
940 GLint depthRange = currentProgram->getDxDepthRangeLocation();
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000941 GLfloat nearFarDiff[3] = { actualZNear, actualZFar, actualZFar - actualZNear };
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000942 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
943 }
944
945 mForceSetViewport = false;
946 return true;
947}
948
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000949bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
950{
951 switch (mode)
952 {
953 case GL_POINTS:
954 mPrimitiveType = D3DPT_POINTLIST;
955 mPrimitiveCount = count;
956 break;
957 case GL_LINES:
958 mPrimitiveType = D3DPT_LINELIST;
959 mPrimitiveCount = count / 2;
960 break;
961 case GL_LINE_LOOP:
962 mPrimitiveType = D3DPT_LINESTRIP;
963 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
964 break;
965 case GL_LINE_STRIP:
966 mPrimitiveType = D3DPT_LINESTRIP;
967 mPrimitiveCount = count - 1;
968 break;
969 case GL_TRIANGLES:
970 mPrimitiveType = D3DPT_TRIANGLELIST;
971 mPrimitiveCount = count / 3;
972 break;
973 case GL_TRIANGLE_STRIP:
974 mPrimitiveType = D3DPT_TRIANGLESTRIP;
975 mPrimitiveCount = count - 2;
976 break;
977 case GL_TRIANGLE_FAN:
978 mPrimitiveType = D3DPT_TRIANGLEFAN;
979 mPrimitiveCount = count - 2;
980 break;
981 default:
982 return error(GL_INVALID_ENUM, false);
983 }
984
985 return mPrimitiveCount > 0;
986}
987
daniel@transgaming.comae39ee22012-11-28 19:42:02 +0000988bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000989{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +0000990 // if there is no color attachment we must synthesize a NULL colorattachment
991 // to keep the D3D runtime happy. This should only be possible if depth texturing.
992 gl::Renderbuffer *renderbufferObject = NULL;
993 if (framebuffer->getColorbufferType() != GL_NONE)
994 {
995 renderbufferObject = framebuffer->getColorbuffer();
996 }
997 else
998 {
999 renderbufferObject = framebuffer->getNullColorbuffer();
1000 }
1001 if (!renderbufferObject)
1002 {
1003 ERR("unable to locate renderbuffer for FBO.");
1004 return false;
1005 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001006
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001007 bool renderTargetChanged = false;
1008 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1009 if (renderTargetSerial != mAppliedRenderTargetSerial)
1010 {
1011 // Apply the render target on the device
1012 IDirect3DSurface9 *renderTargetSurface = NULL;
1013
1014 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1015 if (renderTarget)
1016 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001017 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001018 }
1019
1020 if (!renderTargetSurface)
1021 {
1022 ERR("render target pointer unexpectedly null.");
1023 return false; // Context must be lost
1024 }
1025
1026 mDevice->SetRenderTarget(0, renderTargetSurface);
1027 renderTargetSurface->Release();
1028
1029 mAppliedRenderTargetSerial = renderTargetSerial;
1030 renderTargetChanged = true;
1031 }
1032
1033 gl::Renderbuffer *depthStencil = NULL;
1034 unsigned int depthbufferSerial = 0;
1035 unsigned int stencilbufferSerial = 0;
1036 if (framebuffer->getDepthbufferType() != GL_NONE)
1037 {
1038 depthStencil = framebuffer->getDepthbuffer();
1039 if (!depthStencil)
1040 {
1041 ERR("Depth stencil pointer unexpectedly null.");
1042 return false;
1043 }
1044
1045 depthbufferSerial = depthStencil->getSerial();
1046 }
1047 else if (framebuffer->getStencilbufferType() != GL_NONE)
1048 {
1049 depthStencil = framebuffer->getStencilbuffer();
1050 if (!depthStencil)
1051 {
1052 ERR("Depth stencil pointer unexpectedly null.");
1053 return false;
1054 }
1055
1056 stencilbufferSerial = depthStencil->getSerial();
1057 }
1058
1059 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1060 stencilbufferSerial != mAppliedStencilbufferSerial ||
1061 !mDepthStencilInitialized)
1062 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001063 unsigned int depthSize = 0;
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001064 unsigned int stencilSize = 0;
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001065
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001066 // Apply the depth stencil on the device
1067 if (depthStencil)
1068 {
1069 IDirect3DSurface9 *depthStencilSurface = NULL;
1070 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1071
1072 if (depthStencilRenderTarget)
1073 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001074 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001075 }
1076
1077 if (!depthStencilSurface)
1078 {
1079 ERR("depth stencil pointer unexpectedly null.");
1080 return false; // Context must be lost
1081 }
1082
1083 mDevice->SetDepthStencilSurface(depthStencilSurface);
1084 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001085
1086 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001087 stencilSize = depthStencil->getStencilSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001088 }
1089 else
1090 {
1091 mDevice->SetDepthStencilSurface(NULL);
1092 }
1093
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001094 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1095 {
1096 mCurDepthSize = depthSize;
1097 mForceSetRasterState = true;
1098 }
1099
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001100 if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
1101 {
1102 mCurStencilSize = stencilSize;
1103 mForceSetDepthStencilState = true;
1104 }
1105
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001106 mAppliedDepthbufferSerial = depthbufferSerial;
1107 mAppliedStencilbufferSerial = stencilbufferSerial;
1108 mDepthStencilInitialized = true;
1109 }
1110
1111 if (renderTargetChanged || !mRenderTargetDescInitialized)
1112 {
1113 mForceSetScissor = true;
1114 mForceSetViewport = true;
1115
1116 mRenderTargetDesc.width = renderbufferObject->getWidth();
1117 mRenderTargetDesc.height = renderbufferObject->getHeight();
1118 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1119 mRenderTargetDescInitialized = true;
1120 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001121
1122 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001123}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001124
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001125GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001126{
1127 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1128 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1129 if (err != GL_NO_ERROR)
1130 {
1131 return err;
1132 }
1133
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001134 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1135}
1136
1137// Applies the indices and element array bindings to the Direct3D 9 device
1138GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, gl::TranslatedIndexData *indexInfo)
1139{
1140 IDirect3DIndexBuffer9 *indexBuffer;
1141 unsigned int serial;
1142 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1143
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001144 if (err == GL_NO_ERROR)
1145 {
1146 if (serial != mAppliedIBSerial)
1147 {
1148 mDevice->SetIndices(indexBuffer);
1149 mAppliedIBSerial = serial;
1150 }
1151 }
1152
1153 return err;
1154}
1155
1156void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1157{
1158 startScene();
1159
1160 if (mode == GL_LINE_LOOP)
1161 {
1162 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1163 }
1164 else if (instances > 0)
1165 {
1166 gl::StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
1167 if (countingIB)
1168 {
1169 if (mAppliedIBSerial != countingIB->getSerial())
1170 {
1171 mDevice->SetIndices(countingIB->getBuffer());
1172 mAppliedIBSerial = countingIB->getSerial();
1173 }
1174
1175 for (int i = 0; i < mRepeatDraw; i++)
1176 {
1177 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1178 }
1179 }
1180 else
1181 {
1182 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1183 return error(GL_OUT_OF_MEMORY);
1184 }
1185 }
1186 else // Regular case
1187 {
1188 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1189 }
1190}
1191
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001192void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const gl::TranslatedIndexData &indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001193{
1194 startScene();
1195
1196 if (mode == GL_LINE_LOOP)
1197 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001198 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001199 }
1200 else
1201 {
1202 for (int i = 0; i < mRepeatDraw; i++)
1203 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001204 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1205 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001206 }
1207 }
1208}
1209
1210void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1211{
1212 // Get the raw indices for an indexed draw
1213 if (type != GL_NONE && elementArrayBuffer)
1214 {
1215 gl::Buffer *indexBuffer = elementArrayBuffer;
1216 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1217 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1218 }
1219
1220 UINT startIndex = 0;
1221 bool succeeded = false;
1222
1223 if (get32BitIndexSupport())
1224 {
1225 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1226
1227 if (!mLineLoopIB)
1228 {
1229 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
1230 }
1231
1232 if (mLineLoopIB)
1233 {
1234 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1235
1236 UINT offset = 0;
1237 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1238 startIndex = offset / 4;
1239
1240 if (data)
1241 {
1242 switch (type)
1243 {
1244 case GL_NONE: // Non-indexed draw
1245 for (int i = 0; i < count; i++)
1246 {
1247 data[i] = i;
1248 }
1249 data[count] = 0;
1250 break;
1251 case GL_UNSIGNED_BYTE:
1252 for (int i = 0; i < count; i++)
1253 {
1254 data[i] = static_cast<const GLubyte*>(indices)[i];
1255 }
1256 data[count] = static_cast<const GLubyte*>(indices)[0];
1257 break;
1258 case GL_UNSIGNED_SHORT:
1259 for (int i = 0; i < count; i++)
1260 {
1261 data[i] = static_cast<const GLushort*>(indices)[i];
1262 }
1263 data[count] = static_cast<const GLushort*>(indices)[0];
1264 break;
1265 case GL_UNSIGNED_INT:
1266 for (int i = 0; i < count; i++)
1267 {
1268 data[i] = static_cast<const GLuint*>(indices)[i];
1269 }
1270 data[count] = static_cast<const GLuint*>(indices)[0];
1271 break;
1272 default: UNREACHABLE();
1273 }
1274
1275 mLineLoopIB->unmap();
1276 succeeded = true;
1277 }
1278 }
1279 }
1280 else
1281 {
1282 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1283
1284 if (!mLineLoopIB)
1285 {
1286 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
1287 }
1288
1289 if (mLineLoopIB)
1290 {
1291 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1292
1293 UINT offset = 0;
1294 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1295 startIndex = offset / 2;
1296
1297 if (data)
1298 {
1299 switch (type)
1300 {
1301 case GL_NONE: // Non-indexed draw
1302 for (int i = 0; i < count; i++)
1303 {
1304 data[i] = i;
1305 }
1306 data[count] = 0;
1307 break;
1308 case GL_UNSIGNED_BYTE:
1309 for (int i = 0; i < count; i++)
1310 {
1311 data[i] = static_cast<const GLubyte*>(indices)[i];
1312 }
1313 data[count] = static_cast<const GLubyte*>(indices)[0];
1314 break;
1315 case GL_UNSIGNED_SHORT:
1316 for (int i = 0; i < count; i++)
1317 {
1318 data[i] = static_cast<const GLushort*>(indices)[i];
1319 }
1320 data[count] = static_cast<const GLushort*>(indices)[0];
1321 break;
1322 case GL_UNSIGNED_INT:
1323 for (int i = 0; i < count; i++)
1324 {
1325 data[i] = static_cast<const GLuint*>(indices)[i];
1326 }
1327 data[count] = static_cast<const GLuint*>(indices)[0];
1328 break;
1329 default: UNREACHABLE();
1330 }
1331
1332 mLineLoopIB->unmap();
1333 succeeded = true;
1334 }
1335 }
1336 }
1337
1338 if (succeeded)
1339 {
1340 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1341 {
1342 mDevice->SetIndices(mLineLoopIB->getBuffer());
1343 mAppliedIBSerial = mLineLoopIB->getSerial();
1344 }
1345
1346 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1347 }
1348 else
1349 {
1350 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1351 return error(GL_OUT_OF_MEMORY);
1352 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001353}
1354
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001355void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1356{
daniel@transgaming.com95892412012-11-28 20:59:09 +00001357 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1358 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
1359
1360 IDirect3DVertexShader9 *vertexShader = NULL;
1361 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
1362
1363 IDirect3DPixelShader9 *pixelShader = NULL;
1364 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001365
1366 mDevice->SetPixelShader(pixelShader);
1367 mDevice->SetVertexShader(vertexShader);
1368 programBinary->dirtyAllUniforms();
1369}
1370
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001371void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001372{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001373 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1374 gl::unorm<8>(clearParams.colorClearValue.red),
1375 gl::unorm<8>(clearParams.colorClearValue.green),
1376 gl::unorm<8>(clearParams.colorClearValue.blue));
1377 float depth = gl::clamp01(clearParams.depthClearValue);
1378 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001379
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001380 unsigned int stencilUnmasked = 0x0;
1381 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1382 {
1383 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1384 stencilUnmasked = (0x1 << stencilSize) - 1;
1385 }
1386
1387 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1388
1389 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1390 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1391 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1392 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1393 clearParams.colorMaskBlue && alphaUnmasked);
1394
1395 if (needMaskedColorClear || needMaskedStencilClear)
1396 {
1397 // State which is altered in all paths from this point to the clear call is saved.
1398 // State which is altered in only some paths will be flagged dirty in the case that
1399 // that path is taken.
1400 HRESULT hr;
1401 if (mMaskedClearSavedState == NULL)
1402 {
1403 hr = mDevice->BeginStateBlock();
1404 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1405
1406 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1407 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1408 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1409 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1410 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1411 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1412 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1413 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1414 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1415 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1416 mDevice->SetPixelShader(NULL);
1417 mDevice->SetVertexShader(NULL);
1418 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1419 mDevice->SetStreamSource(0, NULL, 0, 0);
1420 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1421 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1422 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1423 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1424 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1425 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1426 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1427
1428 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1429 {
1430 mDevice->SetStreamSourceFreq(i, 1);
1431 }
1432
1433 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1434 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1435 }
1436
1437 ASSERT(mMaskedClearSavedState != NULL);
1438
1439 if (mMaskedClearSavedState != NULL)
1440 {
1441 hr = mMaskedClearSavedState->Capture();
1442 ASSERT(SUCCEEDED(hr));
1443 }
1444
1445 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1446 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1447 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1448 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1449 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1450 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1451 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1452 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1453
1454 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1455 {
1456 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1457 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1458 clearParams.colorMaskGreen,
1459 clearParams.colorMaskBlue,
1460 clearParams.colorMaskAlpha));
1461 }
1462 else
1463 {
1464 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1465 }
1466
1467 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1468 {
1469 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1470 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1471 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1472 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1473 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1474 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1475 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1476 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1477 }
1478 else
1479 {
1480 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1481 }
1482
1483 mDevice->SetPixelShader(NULL);
1484 mDevice->SetVertexShader(NULL);
1485 mDevice->SetFVF(D3DFVF_XYZRHW);
1486 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1487 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1488 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1489 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1490 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1491 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1492 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1493
1494 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1495 {
1496 mDevice->SetStreamSourceFreq(i, 1);
1497 }
1498
1499 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1500 quad[0][0] = -0.5f;
1501 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1502 quad[0][2] = 0.0f;
1503 quad[0][3] = 1.0f;
1504
1505 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1506 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1507 quad[1][2] = 0.0f;
1508 quad[1][3] = 1.0f;
1509
1510 quad[2][0] = -0.5f;
1511 quad[2][1] = -0.5f;
1512 quad[2][2] = 0.0f;
1513 quad[2][3] = 1.0f;
1514
1515 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1516 quad[3][1] = -0.5f;
1517 quad[3][2] = 0.0f;
1518 quad[3][3] = 1.0f;
1519
1520 startScene();
1521 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1522
1523 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1524 {
1525 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1526 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1527 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1528 }
1529
1530 if (mMaskedClearSavedState != NULL)
1531 {
1532 mMaskedClearSavedState->Apply();
1533 }
1534 }
1535 else if (clearParams.mask)
1536 {
1537 DWORD dxClearFlags = 0;
1538 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1539 {
1540 dxClearFlags |= D3DCLEAR_TARGET;
1541 }
1542 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1543 {
1544 dxClearFlags |= D3DCLEAR_ZBUFFER;
1545 }
1546 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1547 {
1548 dxClearFlags |= D3DCLEAR_STENCIL;
1549 }
1550
1551 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1552 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001553}
1554
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001555void Renderer9::markAllStateDirty()
1556{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001557 mAppliedRenderTargetSerial = 0;
1558 mAppliedDepthbufferSerial = 0;
1559 mAppliedStencilbufferSerial = 0;
1560 mDepthStencilInitialized = false;
1561 mRenderTargetDescInitialized = false;
1562
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001563 mForceSetDepthStencilState = true;
1564 mForceSetRasterState = true;
1565 mForceSetBlendState = true;
1566 mForceSetScissor = true;
1567 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001568
1569 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001570}
1571
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001572void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001573{
1574 while (!mEventQueryPool.empty())
1575 {
1576 mEventQueryPool.back()->Release();
1577 mEventQueryPool.pop_back();
1578 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001579
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001580 if (mMaskedClearSavedState)
1581 {
1582 mMaskedClearSavedState->Release();
1583 mMaskedClearSavedState = NULL;
1584 }
1585
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001586 mVertexShaderCache.clear();
1587 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001588
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001589 delete mBlit;
1590 mBlit = NULL;
1591
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001592 delete mVertexDataManager;
1593 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001594
1595 delete mIndexDataManager;
1596 mIndexDataManager = NULL;
1597
1598 delete mLineLoopIB;
1599 mLineLoopIB = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001600}
1601
1602
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001603void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001604{
1605 mDeviceLost = true;
1606}
1607
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001608bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001609{
1610 return mDeviceLost;
1611}
1612
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001613// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001614bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001615{
1616 bool isLost = false;
1617
1618 if (mDeviceEx)
1619 {
1620 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1621 }
1622 else if (mDevice)
1623 {
1624 isLost = FAILED(mDevice->TestCooperativeLevel());
1625 }
1626 else
1627 {
1628 // No device yet, so no reset required
1629 }
1630
1631 if (isLost)
1632 {
1633 // ensure we note the device loss --
1634 // we'll probably get this done again by markDeviceLost
1635 // but best to remember it!
1636 // Note that we don't want to clear the device loss status here
1637 // -- this needs to be done by resetDevice
1638 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001639 if (notify)
1640 {
1641 mDisplay->notifyDeviceLost();
1642 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001643 }
1644
1645 return isLost;
1646}
1647
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001648bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001649{
1650 HRESULT status = D3D_OK;
1651
1652 if (mDeviceEx)
1653 {
1654 status = mDeviceEx->CheckDeviceState(NULL);
1655 }
1656 else if (mDevice)
1657 {
1658 status = mDevice->TestCooperativeLevel();
1659 }
1660
1661 switch (status)
1662 {
1663 case D3DERR_DEVICENOTRESET:
1664 case D3DERR_DEVICEHUNG:
1665 return true;
1666 default:
1667 return false;
1668 }
1669}
1670
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001671bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001672{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001673 releaseDeviceResources();
1674
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001675 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1676
1677 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001678 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001679 int attempts = 3;
1680
1681 while (lost && attempts > 0)
1682 {
1683 if (mDeviceEx)
1684 {
1685 Sleep(500); // Give the graphics driver some CPU time
1686 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1687 }
1688 else
1689 {
1690 result = mDevice->TestCooperativeLevel();
1691 while (result == D3DERR_DEVICELOST)
1692 {
1693 Sleep(100); // Give the graphics driver some CPU time
1694 result = mDevice->TestCooperativeLevel();
1695 }
1696
1697 if (result == D3DERR_DEVICENOTRESET)
1698 {
1699 result = mDevice->Reset(&presentParameters);
1700 }
1701 }
1702
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001703 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001704 attempts --;
1705 }
1706
1707 if (FAILED(result))
1708 {
1709 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1710 return false;
1711 }
1712
1713 // reset device defaults
1714 initializeDevice();
1715 mDeviceLost = false;
1716
1717 return true;
1718}
1719
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001720DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001721{
1722 return mAdapterIdentifier.VendorId;
1723}
1724
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001725const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001726{
1727 return mAdapterIdentifier.Description;
1728}
1729
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001730GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001731{
1732 return mAdapterIdentifier.DeviceIdentifier;
1733}
1734
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001735void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001736{
1737 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1738 {
1739 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1740 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1741
1742 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1743 }
1744}
1745
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001746bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001747{
1748 D3DDISPLAYMODE currentDisplayMode;
1749 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1750
1751 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1752}
1753
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001754bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001755{
1756 D3DDISPLAYMODE currentDisplayMode;
1757 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1758
1759 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1760}
1761
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001762bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001763{
1764 D3DDISPLAYMODE currentDisplayMode;
1765 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1766
1767 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1768}
1769
1770// we use INTZ for depth textures in Direct3D9
1771// we also want NULL texture support to ensure the we can make depth-only FBOs
1772// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001773bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001774{
1775 D3DDISPLAYMODE currentDisplayMode;
1776 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1777
1778 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1779 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1780 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1781 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1782
1783 return intz && null;
1784}
1785
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001786bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001787{
1788 D3DDISPLAYMODE currentDisplayMode;
1789 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1790
1791 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1792 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1793 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1794 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1795
1796 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1797 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1798 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1799 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1800
1801 if (!*filtering && !*renderable)
1802 {
1803 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1804 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1805 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1806 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1807 }
1808 else
1809 {
1810 return true;
1811 }
1812}
1813
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001814bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001815{
1816 D3DDISPLAYMODE currentDisplayMode;
1817 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1818
1819 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1820 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1821 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1822 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1823
1824 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1825 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1826 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1827 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1828
1829 if (!*filtering && !*renderable)
1830 {
1831 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1832 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1833 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1834 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1835 }
1836 else
1837 {
1838 return true;
1839 }
1840}
1841
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001842bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001843{
1844 D3DDISPLAYMODE currentDisplayMode;
1845 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1846
1847 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1848}
1849
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001850bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001851{
1852 D3DDISPLAYMODE currentDisplayMode;
1853 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1854
1855 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1856}
1857
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001858bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001859{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001860 return mSupportsTextureFilterAnisotropy;
1861}
1862
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001863float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001864{
1865 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001866 {
1867 return mDeviceCaps.MaxAnisotropy;
1868 }
1869 return 1.0f;
1870}
1871
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001872bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001873{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001874 IDirect3DQuery9 *query = allocateEventQuery();
1875 if (query)
1876 {
1877 freeEventQuery(query);
1878 return true;
1879 }
1880 else
1881 {
1882 return false;
1883 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001884 return true;
1885}
1886
1887// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1888// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001889bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001890{
1891 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1892 {
1893 return false;
1894 }
1895
1896 D3DDISPLAYMODE currentDisplayMode;
1897 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1898
1899 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1900
1901 return SUCCEEDED(result);
1902}
1903
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001904bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001905{
1906 return mSupportsNonPower2Textures;
1907}
1908
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001909bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001910{
1911 if (!mDevice)
1912 {
1913 return false;
1914 }
1915
1916 IDirect3DQuery9 *query = NULL;
1917 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1918 if (SUCCEEDED(result) && query)
1919 {
1920 query->Release();
1921 return true;
1922 }
1923 else
1924 {
1925 return false;
1926 }
1927}
1928
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001929bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001930{
1931 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1932}
1933
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001934bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001935{
1936 // PIX doesn't seem to support using share handles, so disable them.
1937 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001938 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001939}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001940
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001941int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001942{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001943 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001944}
1945
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001946float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001947{
1948 return mDeviceCaps.MaxPointSize;
1949}
1950
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001951int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001952{
1953 return (int)mDeviceCaps.MaxTextureWidth;
1954}
1955
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001956int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001957{
1958 return (int)mDeviceCaps.MaxTextureHeight;
1959}
1960
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001961bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001962{
1963 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1964}
1965
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001966DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001967{
1968 return mDeviceCaps.DeclTypes;
1969}
1970
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001971int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001972{
1973 return mMinSwapInterval;
1974}
1975
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001976int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001977{
1978 return mMaxSwapInterval;
1979}
1980
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001981int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001982{
1983 return mMaxSupportedSamples;
1984}
1985
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001986int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001987{
1988 if (requested == 0)
1989 {
1990 return requested;
1991 }
1992
1993 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
1994 if (itr == mMultiSampleSupport.end())
1995 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00001996 if (format == D3DFMT_UNKNOWN)
1997 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001998 return -1;
1999 }
2000
2001 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2002 {
2003 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2004 {
2005 return i;
2006 }
2007 }
2008
2009 return -1;
2010}
2011
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002012D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2013{
2014 switch (internalformat)
2015 {
2016 case GL_DEPTH_COMPONENT16:
2017 case GL_DEPTH_COMPONENT32_OES:
2018 case GL_DEPTH24_STENCIL8_OES:
2019 return D3DFMT_INTZ;
2020 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2021 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2022 return D3DFMT_DXT1;
2023 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2024 return D3DFMT_DXT3;
2025 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2026 return D3DFMT_DXT5;
2027 case GL_RGBA32F_EXT:
2028 case GL_RGB32F_EXT:
2029 case GL_ALPHA32F_EXT:
2030 case GL_LUMINANCE32F_EXT:
2031 case GL_LUMINANCE_ALPHA32F_EXT:
2032 return D3DFMT_A32B32G32R32F;
2033 case GL_RGBA16F_EXT:
2034 case GL_RGB16F_EXT:
2035 case GL_ALPHA16F_EXT:
2036 case GL_LUMINANCE16F_EXT:
2037 case GL_LUMINANCE_ALPHA16F_EXT:
2038 return D3DFMT_A16B16G16R16F;
2039 case GL_LUMINANCE8_EXT:
2040 if (getLuminanceTextureSupport())
2041 {
2042 return D3DFMT_L8;
2043 }
2044 break;
2045 case GL_LUMINANCE8_ALPHA8_EXT:
2046 if (getLuminanceAlphaTextureSupport())
2047 {
2048 return D3DFMT_A8L8;
2049 }
2050 break;
2051 case GL_RGB8_OES:
2052 case GL_RGB565:
2053 return D3DFMT_X8R8G8B8;
2054 }
2055
2056 return D3DFMT_A8R8G8B8;
2057}
2058
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002059bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002060{
2061 bool result = false;
2062
2063 if (source && dest)
2064 {
2065 int levels = source->levelCount();
2066 for (int i = 0; i < levels; ++i)
2067 {
2068 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2069 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2070
2071 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2072
2073 if (srcSurf) srcSurf->Release();
2074 if (dstSurf) dstSurf->Release();
2075
2076 if (!result)
2077 return false;
2078 }
2079 }
2080
2081 return result;
2082}
2083
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002084bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002085{
2086 bool result = false;
2087
2088 if (source && dest)
2089 {
2090 int levels = source->levelCount();
2091 for (int f = 0; f < 6; f++)
2092 {
2093 for (int i = 0; i < levels; i++)
2094 {
2095 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2096 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2097
2098 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2099
2100 if (srcSurf) srcSurf->Release();
2101 if (dstSurf) dstSurf->Release();
2102
2103 if (!result)
2104 return false;
2105 }
2106 }
2107 }
2108
2109 return result;
2110}
2111
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002112D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002113{
2114 if (mD3d9Ex != NULL)
2115 {
2116 return D3DPOOL_DEFAULT;
2117 }
2118 else
2119 {
2120 if (!(usage & D3DUSAGE_DYNAMIC))
2121 {
2122 return D3DPOOL_MANAGED;
2123 }
2124 }
2125
2126 return D3DPOOL_DEFAULT;
2127}
2128
daniel@transgaming.com38380882012-11-28 19:36:39 +00002129bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2130 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002131{
2132 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
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, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002137{
2138 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2139}
2140
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002141bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2142 bool blitRenderTarget, bool blitDepthStencil)
2143{
2144 endScene();
2145
2146 if (blitRenderTarget)
2147 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002148 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2149 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2150 RenderTarget9 *readRenderTarget = NULL;
2151 RenderTarget9 *drawRenderTarget = NULL;
2152 IDirect3DSurface9* readSurface = NULL;
2153 IDirect3DSurface9* drawSurface = NULL;
2154
2155 if (readBuffer)
2156 {
2157 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2158 }
2159 if (drawBuffer)
2160 {
2161 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2162 }
2163
2164 if (readRenderTarget)
2165 {
2166 readSurface = readRenderTarget->getSurface();
2167 }
2168 if (drawRenderTarget)
2169 {
2170 drawSurface = drawRenderTarget->getSurface();
2171 }
2172
2173 if (!readSurface || !drawSurface)
2174 {
2175 ERR("Failed to retrieve the render target.");
2176 return error(GL_OUT_OF_MEMORY, false);
2177 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002178
2179 RECT srcRect, dstRect;
2180 RECT *srcRectPtr = NULL;
2181 RECT *dstRectPtr = NULL;
2182
2183 if (readRect)
2184 {
2185 srcRect.left = readRect->x;
2186 srcRect.right = readRect->x + readRect->width;
2187 srcRect.top = readRect->y;
2188 srcRect.bottom = readRect->y + readRect->height;
2189 srcRectPtr = &srcRect;
2190 }
2191
2192 if (drawRect)
2193 {
2194 dstRect.left = drawRect->x;
2195 dstRect.right = drawRect->x + drawRect->width;
2196 dstRect.top = drawRect->y;
2197 dstRect.bottom = drawRect->y + drawRect->height;
2198 dstRectPtr = &dstRect;
2199 }
2200
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002201 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002202
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002203 readSurface->Release();
2204 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002205
2206 if (FAILED(result))
2207 {
2208 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2209 return false;
2210 }
2211 }
2212
2213 if (blitDepthStencil)
2214 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002215 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2216 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2217 RenderTarget9 *readDepthStencil = NULL;
2218 RenderTarget9 *drawDepthStencil = NULL;
2219 IDirect3DSurface9* readSurface = NULL;
2220 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002221
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002222 if (readBuffer)
2223 {
2224 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2225 }
2226 if (drawBuffer)
2227 {
2228 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2229 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002230
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002231 if (readDepthStencil)
2232 {
2233 readSurface = readDepthStencil->getSurface();
2234 }
2235 if (drawDepthStencil)
2236 {
2237 drawSurface = drawDepthStencil->getSurface();
2238 }
2239
2240 if (!readSurface || !drawSurface)
2241 {
2242 ERR("Failed to retrieve the render target.");
2243 return error(GL_OUT_OF_MEMORY, false);
2244 }
2245
2246 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2247
2248 readSurface->Release();
2249 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002250
2251 if (FAILED(result))
2252 {
2253 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2254 return false;
2255 }
2256 }
2257
2258 return true;
2259}
2260
2261void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2262 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2263{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002264 RenderTarget9 *renderTarget = NULL;
2265 IDirect3DSurface9 *surface = NULL;
2266 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2267
2268 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002269 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002270 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2271 }
2272
2273 if (renderTarget)
2274 {
2275 surface = renderTarget->getSurface();
2276 }
2277
2278 if (!surface)
2279 {
2280 // context must be lost
2281 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002282 }
2283
2284 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002285 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002286
2287 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2288 {
2289 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002290 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002291 return error(GL_OUT_OF_MEMORY);
2292 }
2293
2294 HRESULT result;
2295 IDirect3DSurface9 *systemSurface = NULL;
2296 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2297 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2298 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2299 if (directToPixels)
2300 {
2301 // Use the pixels ptr as a shared handle to write directly into client's memory
2302 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2303 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2304 if (FAILED(result))
2305 {
2306 // Try again without the shared handle
2307 directToPixels = false;
2308 }
2309 }
2310
2311 if (!directToPixels)
2312 {
2313 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2314 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2315 if (FAILED(result))
2316 {
2317 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002318 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002319 return error(GL_OUT_OF_MEMORY);
2320 }
2321 }
2322
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002323 result = mDevice->GetRenderTargetData(surface, systemSurface);
2324 surface->Release();
2325 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002326
2327 if (FAILED(result))
2328 {
2329 systemSurface->Release();
2330
2331 // It turns out that D3D will sometimes produce more error
2332 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002333 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002334 return error(GL_OUT_OF_MEMORY);
2335 else
2336 {
2337 UNREACHABLE();
2338 return;
2339 }
2340
2341 }
2342
2343 if (directToPixels)
2344 {
2345 systemSurface->Release();
2346 return;
2347 }
2348
2349 RECT rect;
2350 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2351 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2352 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2353 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2354
2355 D3DLOCKED_RECT lock;
2356 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2357
2358 if (FAILED(result))
2359 {
2360 UNREACHABLE();
2361 systemSurface->Release();
2362
2363 return; // No sensible error to generate
2364 }
2365
2366 unsigned char *dest = (unsigned char*)pixels;
2367 unsigned short *dest16 = (unsigned short*)pixels;
2368
2369 unsigned char *source;
2370 int inputPitch;
2371 if (packReverseRowOrder)
2372 {
2373 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2374 inputPitch = -lock.Pitch;
2375 }
2376 else
2377 {
2378 source = (unsigned char*)lock.pBits;
2379 inputPitch = lock.Pitch;
2380 }
2381
2382 unsigned int fastPixelSize = 0;
2383
2384 if (desc.Format == D3DFMT_A8R8G8B8 &&
2385 format == GL_BGRA_EXT &&
2386 type == GL_UNSIGNED_BYTE)
2387 {
2388 fastPixelSize = 4;
2389 }
2390 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2391 format == GL_BGRA_EXT &&
2392 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2393 (desc.Format == D3DFMT_A1R5G5B5 &&
2394 format == GL_BGRA_EXT &&
2395 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2396 {
2397 fastPixelSize = 2;
2398 }
2399 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2400 format == GL_RGBA &&
2401 type == GL_HALF_FLOAT_OES)
2402 {
2403 fastPixelSize = 8;
2404 }
2405 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2406 format == GL_RGBA &&
2407 type == GL_FLOAT)
2408 {
2409 fastPixelSize = 16;
2410 }
2411
2412 for (int j = 0; j < rect.bottom - rect.top; j++)
2413 {
2414 if (fastPixelSize != 0)
2415 {
2416 // Fast path for formats which require no translation:
2417 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2418 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2419 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2420 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2421 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2422 //
2423 // Note that buffers with no alpha go through the slow path below.
2424 memcpy(dest + j * outputPitch,
2425 source + j * inputPitch,
2426 (rect.right - rect.left) * fastPixelSize);
2427 continue;
2428 }
2429
2430 for (int i = 0; i < rect.right - rect.left; i++)
2431 {
2432 float r;
2433 float g;
2434 float b;
2435 float a;
2436
2437 switch (desc.Format)
2438 {
2439 case D3DFMT_R5G6B5:
2440 {
2441 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2442
2443 a = 1.0f;
2444 b = (rgb & 0x001F) * (1.0f / 0x001F);
2445 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2446 r = (rgb & 0xF800) * (1.0f / 0xF800);
2447 }
2448 break;
2449 case D3DFMT_A1R5G5B5:
2450 {
2451 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2452
2453 a = (argb & 0x8000) ? 1.0f : 0.0f;
2454 b = (argb & 0x001F) * (1.0f / 0x001F);
2455 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2456 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2457 }
2458 break;
2459 case D3DFMT_A8R8G8B8:
2460 {
2461 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2462
2463 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2464 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2465 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2466 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2467 }
2468 break;
2469 case D3DFMT_X8R8G8B8:
2470 {
2471 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2472
2473 a = 1.0f;
2474 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2475 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2476 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2477 }
2478 break;
2479 case D3DFMT_A2R10G10B10:
2480 {
2481 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2482
2483 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2484 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2485 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2486 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2487 }
2488 break;
2489 case D3DFMT_A32B32G32R32F:
2490 {
2491 // float formats in D3D are stored rgba, rather than the other way round
2492 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2493 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2494 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2495 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2496 }
2497 break;
2498 case D3DFMT_A16B16G16R16F:
2499 {
2500 // float formats in D3D are stored rgba, rather than the other way round
2501 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2502 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2503 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2504 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2505 }
2506 break;
2507 default:
2508 UNIMPLEMENTED(); // FIXME
2509 UNREACHABLE();
2510 return;
2511 }
2512
2513 switch (format)
2514 {
2515 case GL_RGBA:
2516 switch (type)
2517 {
2518 case GL_UNSIGNED_BYTE:
2519 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2520 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2521 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2522 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2523 break;
2524 default: UNREACHABLE();
2525 }
2526 break;
2527 case GL_BGRA_EXT:
2528 switch (type)
2529 {
2530 case GL_UNSIGNED_BYTE:
2531 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2532 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2533 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2534 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2535 break;
2536 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2537 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2538 // this type is packed as follows:
2539 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2540 // --------------------------------------------------------------------------------
2541 // | 4th | 3rd | 2nd | 1st component |
2542 // --------------------------------------------------------------------------------
2543 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2544 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2545 ((unsigned short)(15 * a + 0.5f) << 12)|
2546 ((unsigned short)(15 * r + 0.5f) << 8) |
2547 ((unsigned short)(15 * g + 0.5f) << 4) |
2548 ((unsigned short)(15 * b + 0.5f) << 0);
2549 break;
2550 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2551 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2552 // this type is packed as follows:
2553 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2554 // --------------------------------------------------------------------------------
2555 // | 4th | 3rd | 2nd | 1st component |
2556 // --------------------------------------------------------------------------------
2557 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2558 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2559 ((unsigned short)( a + 0.5f) << 15) |
2560 ((unsigned short)(31 * r + 0.5f) << 10) |
2561 ((unsigned short)(31 * g + 0.5f) << 5) |
2562 ((unsigned short)(31 * b + 0.5f) << 0);
2563 break;
2564 default: UNREACHABLE();
2565 }
2566 break;
2567 case GL_RGB:
2568 switch (type)
2569 {
2570 case GL_UNSIGNED_SHORT_5_6_5:
2571 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2572 ((unsigned short)(31 * b + 0.5f) << 0) |
2573 ((unsigned short)(63 * g + 0.5f) << 5) |
2574 ((unsigned short)(31 * r + 0.5f) << 11);
2575 break;
2576 case GL_UNSIGNED_BYTE:
2577 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2578 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2579 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2580 break;
2581 default: UNREACHABLE();
2582 }
2583 break;
2584 default: UNREACHABLE();
2585 }
2586 }
2587 }
2588
2589 systemSurface->UnlockRect();
2590
2591 systemSurface->Release();
2592}
2593
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002594RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2595{
2596 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2597 IDirect3DSurface9 *surface = NULL;
2598 if (depth)
2599 {
2600 surface = swapChain9->getDepthStencil();
2601 }
2602 else
2603 {
2604 surface = swapChain9->getRenderTarget();
2605 }
2606
2607 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2608
2609 return renderTarget;
2610}
2611
2612RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2613{
2614 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2615 return renderTarget;
2616}
2617
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002618ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type, void *data)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002619{
2620 ShaderExecutable9 *executable = NULL;
2621 gl::D3DConstantTable *table = reinterpret_cast<gl::D3DConstantTable *>(data);
2622
2623 switch (type)
2624 {
2625 case GL_VERTEX_SHADER:
2626 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002627 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002628 if (vshader)
2629 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002630 executable = new ShaderExecutable9(function, length, vshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002631 }
2632 }
2633 break;
2634 case GL_FRAGMENT_SHADER:
2635 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002636 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002637 if (pshader)
2638 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002639 executable = new ShaderExecutable9(function, length, pshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002640 }
2641 }
2642 break;
2643 default:
2644 UNREACHABLE();
2645 break;
2646 }
2647
2648 return executable;
2649}
2650
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002651ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2652{
2653 const char *profile = NULL;
2654
2655 switch (type)
2656 {
2657 case GL_VERTEX_SHADER:
2658 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2659 break;
2660 case GL_FRAGMENT_SHADER:
2661 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2662 break;
2663 default:
2664 UNREACHABLE();
2665 return NULL;
2666 }
2667
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002668 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002669 if (!binary)
2670 return NULL;
2671
daniel@transgaming.combe281b02012-11-28 21:05:48 +00002672 gl::D3DConstantTable *constantTable = new gl::D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
2673 if (constantTable->error())
2674 {
2675 delete constantTable;
2676 binary->Release();
2677 return NULL;
2678 }
2679
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002680 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002681 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002682
2683 return executable;
2684}
2685
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002686bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2687{
2688 return mBlit->boxFilter(source, dest);
2689}
2690
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002691D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002692{
2693 if (mD3d9Ex != NULL)
2694 {
2695 return D3DPOOL_DEFAULT;
2696 }
2697 else
2698 {
2699 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2700 {
2701 return D3DPOOL_MANAGED;
2702 }
2703 }
2704
2705 return D3DPOOL_DEFAULT;
2706}
2707
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002708bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2709{
2710 if (source && dest)
2711 {
2712 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2713 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2714
2715 if (fromManaged)
2716 {
2717 D3DSURFACE_DESC desc;
2718 source->GetDesc(&desc);
2719
2720 IDirect3DSurface9 *surf = 0;
2721 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2722
2723 if (SUCCEEDED(result))
2724 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002725 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002726 result = device->UpdateSurface(surf, NULL, dest, NULL);
2727 surf->Release();
2728 }
2729 }
2730 else
2731 {
2732 endScene();
2733 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2734 }
2735
2736 if (FAILED(result))
2737 {
2738 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2739 return false;
2740 }
2741 }
2742
2743 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002744}
2745
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002746}