source: GTP/trunk/App/Demos/Illum/StochasticIteration/Stochastic_3.cpp @ 1808

Revision 1808, 17.8 KB checked in by szirmay, 18 years ago (diff)
Line 
1//--------------------------------------------------------------------------------------
2// File: Stochastic_3.cpp
3//
4// Starting point for new Direct3D applications
5//
6// Copyright (c) Microsoft Corporation. All rights reserved.
7//--------------------------------------------------------------------------------------
8#include "dxstdafx.h"
9#include "d3ddefs.h"
10#include "resource.h"
11#include <ctime>
12#include <fstream>
13#include <vector>
14#include "vector4d.h"
15#include "color.h"
16#include "object.h"
17#include "ObjectVector.h"
18#include "RadiosityAlgorithm.h"
19#include "resource.h"
20//#define DEBUG_VS   // Uncomment this line to debug vertex shaders
21//#define DEBUG_PS   // Uncomment this line to debug pixel shaders
22
23
24//--------------------------------------------------------------------------------------
25// Global variables
26//--------------------------------------------------------------------------------------
27//ID3DXFont*              g_pFont = NULL;         // Font for drawing text
28//ID3DXSprite*            g_pTextSprite = NULL;   // Sprite for batching draw text calls
29//ID3DXEffect*            g_pEffect = NULL;       // D3DX effect interface
30//CModelViewerCamera      g_Camera;               // A model viewing camera
31bool                    g_bShowHelp = true;     // If true, it renders the UI control text
32RadiosityAlgorithm*         g_RadiosityAlgorithm;   // holds algorithm instance
33bool                    isFirstRun = true;
34//CDXUTDialog             g_HUD;                  // dialog for standard controls
35//CDXUTDialog             g_SampleUI;             // dialog for sample specific controls
36D3DXVECTOR3 eye;
37D3DXVECTOR3 lookAt;
38
39//--------------------------------------------------------------------------------------
40// UI control IDs
41//--------------------------------------------------------------------------------------
42#define IDC_TOGGLEFULLSCREEN    1
43#define IDC_TOGGLEREF           2
44#define IDC_CHANGEDEVICE        3
45
46
47
48//--------------------------------------------------------------------------------------
49// Forward declarations
50//--------------------------------------------------------------------------------------
51bool    CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed );
52void    CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps );
53HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
54HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
55void    CALLBACK OnFrameMove( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime );
56void    CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime );
57LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing );
58void    CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown  );
59void    CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl );
60void    CALLBACK OnLostDevice();
61void    CALLBACK OnDestroyDevice();
62
63void    InitApp();
64HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh );
65void    RenderText();
66
67
68//--------------------------------------------------------------------------------------
69// Entry point to the program. Initializes everything and goes into a message processing
70// loop. Idle time is used to render the scene.
71//--------------------------------------------------------------------------------------
72INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
73{
74        g_RadiosityAlgorithm=new RadiosityAlgorithm(256,256,9,D3DFMT_G16R16F,D3DFMT_A16B16G16R16F,D3DFMT_A32B32G32R32F,D3DFMT_R32F,D3DFMT_D24S8);
75        // Set the callback functions. These functions allow the sample framework to notify
76    // the application about device changes, user input, and windows messages.  The
77    // callbacks are optional so you need only set callbacks for events you're interested
78    // in. However, if you don't handle the device reset/lost callbacks then the sample
79    // framework won't be able to reset your device since the application must first
80    // release all device resources before resetting.  Likewise, if you don't handle the
81    // device created/destroyed callbacks then the sample framework won't be able to
82    // recreate your device resources.
83    DXUTSetCallbackDeviceCreated( OnCreateDevice );
84    DXUTSetCallbackDeviceReset( OnResetDevice );
85    DXUTSetCallbackDeviceLost( OnLostDevice );
86    DXUTSetCallbackDeviceDestroyed( OnDestroyDevice );
87    DXUTSetCallbackMsgProc( MsgProc );
88    DXUTSetCallbackKeyboard( KeyboardProc );
89    DXUTSetCallbackFrameRender( OnFrameRender );
90    DXUTSetCallbackFrameMove( OnFrameMove );
91
92    // Show the cursor and clip it when in full screen
93    DXUTSetCursorSettings( true, true );
94
95    InitApp();
96
97    // Initialize the sample framework and create the desired Win32 window and Direct3D
98    // device for the application. Calling each of these functions is optional, but they
99    // allow you to set several options which control the behavior of the framework.
100    DXUTInit( true, true, true ); // Parse the command line, handle the default hotkeys, and show msgboxes
101    DXUTCreateWindow( L"Stochastic_3" );
102    DXUTCreateDevice( D3DADAPTER_DEFAULT, true, 800, 600, IsDeviceAcceptable, ModifyDeviceSettings );
103       
104
105       
106       
107    // Pass control to the sample framework for handling the message pump and
108    // dispatching render calls. The sample framework will call your FrameMove
109    // and FrameRender callback when there is idle time between handling window messages.
110    DXUTMainLoop();
111
112    // Perform any application-level cleanup here. Direct3D device resources are released within the
113    // appropriate callback functions and therefore don't require any cleanup code here.
114
115    return DXUTGetExitCode();
116}
117
118
119//--------------------------------------------------------------------------------------
120// Initialize the app
121//--------------------------------------------------------------------------------------
122void InitApp()
123{
124   
125}
126
127
128//--------------------------------------------------------------------------------------
129// Called during device initialization, this code checks the device for some
130// minimum set of capabilities, and rejects those that don't pass by returning false.
131//--------------------------------------------------------------------------------------
132bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat,
133                                  D3DFORMAT BackBufferFormat, bool bWindowed )
134{
135    // Skip backbuffer formats that don't support alpha blending
136    IDirect3D9* pD3D = DXUTGetD3DObject();
137    if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
138                    AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
139                    D3DRTYPE_TEXTURE, BackBufferFormat ) ) )
140        return false;
141
142    return true;
143}
144
145
146//--------------------------------------------------------------------------------------
147// This callback function is called immediately before a device is created to allow the
148// application to modify the device settings. The supplied pDeviceSettings parameter
149// contains the settings that the framework has selected for the new device, and the
150// application can make any desired changes directly to this structure.  Note however that
151// the sample framework will not correct invalid device settings so care must be taken
152// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. 
153//--------------------------------------------------------------------------------------
154void CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps )
155{
156    // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
157    // then switch to SWVP.
158    if( (pCaps->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0 ||
159         pCaps->VertexShaderVersion < D3DVS_VERSION(1,1) )
160    {
161        pDeviceSettings->BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
162    }
163    else
164    {
165        pDeviceSettings->BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING;
166    }
167
168    // This application is designed to work on a pure device by not using
169    // IDirect3D9::Get*() methods, so create a pure device if supported and using HWVP.
170    if ((pCaps->DevCaps & D3DDEVCAPS_PUREDEVICE) != 0 &&
171        (pDeviceSettings->BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) != 0 )
172        pDeviceSettings->BehaviorFlags |= D3DCREATE_PUREDEVICE;
173
174    // Debugging vertex shaders requires either REF or software vertex processing
175    // and debugging pixel shaders requires REF. 
176#ifdef DEBUG_VS
177    if( pDeviceSettings->DeviceType != D3DDEVTYPE_REF )
178    {
179        pDeviceSettings->BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
180        pDeviceSettings->BehaviorFlags &= ~D3DCREATE_PUREDEVICE;
181        pDeviceSettings->BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
182    }
183#endif
184#ifdef DEBUG_PS
185    pDeviceSettings->DeviceType = D3DDEVTYPE_REF;
186#endif
187}
188
189
190//--------------------------------------------------------------------------------------
191// This callback function will be called immediately after the Direct3D device has been
192// created, which will happen during application initialization and windowed/full screen
193// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
194// resources need to be reloaded whenever the device is destroyed. Resources created 
195// here should be released in the OnDestroyDevice callback.
196//--------------------------------------------------------------------------------------
197HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc )
198{
199    HRESULT hr;
200        eye.x=0;
201        eye.y=0.5;
202        eye.z=15.0f;
203        lookAt.x=0;
204        lookAt.y=0.5f;
205        lookAt.z=10.0f;
206    g_RadiosityAlgorithm->initObjects(pd3dDevice);
207        g_RadiosityAlgorithm->doOriginalVisibilityMapPass(true,L"origvismap.hdr");
208    return S_OK;
209}
210
211
212//--------------------------------------------------------------------------------------
213// This function loads the mesh and ensures the mesh has normals; it also optimizes the
214// mesh for the graphics card's vertex cache, which improves performance by organizing
215// the internal triangle list for less cache misses.
216//--------------------------------------------------------------------------------------
217HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh )
218{
219    ID3DXMesh* pMesh = NULL;
220    WCHAR str[MAX_PATH];
221    HRESULT hr;
222
223    // Load the mesh with D3DX and get back a ID3DXMesh*.  For this
224    // sample we'll ignore the X file's embedded materials since we know
225    // exactly the model we're loading.  See the mesh samples such as
226    // "OptimizedMesh" for a more generic mesh loading example.
227    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, strFileName ) );
228
229    V_RETURN( D3DXLoadMeshFromX(str, D3DXMESH_MANAGED, pd3dDevice, NULL, NULL, NULL, NULL, &pMesh) );
230
231    DWORD *rgdwAdjacency = NULL;
232
233    // Make sure there are normals which are required for lighting
234    if( !(pMesh->GetFVF() & D3DFVF_NORMAL) )
235    {
236        ID3DXMesh* pTempMesh;
237        V( pMesh->CloneMeshFVF( pMesh->GetOptions(),
238                                  pMesh->GetFVF() | D3DFVF_NORMAL,
239                                  pd3dDevice, &pTempMesh ) );
240        V( D3DXComputeNormals( pTempMesh, NULL ) );
241
242        SAFE_RELEASE( pMesh );
243        pMesh = pTempMesh;
244    }
245
246    // Optimize the mesh for this graphics card's vertex cache
247    // so when rendering the mesh's triangle list the vertices will
248    // cache hit more often so it won't have to re-execute the vertex shader
249    // on those vertices so it will improve perf.     
250    rgdwAdjacency = new DWORD[pMesh->GetNumFaces() * 3];
251    if( rgdwAdjacency == NULL )
252        return E_OUTOFMEMORY;
253    V( pMesh->ConvertPointRepsToAdjacency(NULL, rgdwAdjacency) );
254    V( pMesh->OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL) );
255    delete []rgdwAdjacency;
256
257    *ppMesh = pMesh;
258
259    return S_OK;
260}
261
262
263//--------------------------------------------------------------------------------------
264// This callback function will be called immediately after the Direct3D device has been
265// reset, which will happen after a lost device scenario. This is the best location to
266// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
267// the device is lost. Resources created here should be released in the OnLostDevice
268// callback.
269//--------------------------------------------------------------------------------------
270HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice,
271                                const D3DSURFACE_DESC* pBackBufferSurfaceDesc )
272{
273    HRESULT hr;
274
275    return S_OK;
276}
277
278
279//--------------------------------------------------------------------------------------
280// This callback function will be called once at the beginning of every frame. This is the
281// best location for your application to handle updates to the scene, but is not
282// intended to contain actual rendering calls, which should instead be placed in the
283// OnFrameRender callback. 
284//--------------------------------------------------------------------------------------
285void CALLBACK OnFrameMove( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime )
286{
287   
288}
289
290
291//--------------------------------------------------------------------------------------
292// This callback function will be called at the end of every frame to perform all the
293// rendering calls for the scene, and it will also be called if the window needs to be
294// repainted. After this function has returned, the sample framework will call
295// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
296//--------------------------------------------------------------------------------------
297void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime )
298{
299    HRESULT hr;
300        int iterationCount=200;
301        if(isFirstRun){
302                hr=g_RadiosityAlgorithm->doEmissionMapPass(false,L"emissionMap.hdr");
303               
304                hr=g_RadiosityAlgorithm->iterate(iterationCount,-1);
305               
306                hr=g_RadiosityAlgorithm->doRadiosityAveragingPass(false,L"finalRadMap.hdr",iterationCount);
307               
308                isFirstRun=false;
309        }
310       
311        LPTSTR buffer=(LPTSTR)new TCHAR[200];
312       
313        wsprintf(buffer,L"picture%i.bmp",iterationCount);
314
315        hr=g_RadiosityAlgorithm->moveCamera(eye.x,eye.y,eye.z,lookAt.x,lookAt.y,lookAt.z);
316        hr=g_RadiosityAlgorithm->doFinalPicturePass(false,buffer);
317       
318}
319
320
321//--------------------------------------------------------------------------------------
322// Render the help and statistics text. This function uses the ID3DXFont interface for
323// efficient text rendering.
324//--------------------------------------------------------------------------------------
325void RenderText()
326{
327   
328}
329
330
331//--------------------------------------------------------------------------------------
332// Before handling window messages, the sample framework passes incoming windows
333// messages to the application through this callback function. If the application sets
334// *pbNoFurtherProcessing to TRUE, then the sample framework will not process this message.
335//--------------------------------------------------------------------------------------
336LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing )
337{
338   
339
340    return 0;
341}
342
343
344//--------------------------------------------------------------------------------------
345// As a convenience, the sample framework inspects the incoming windows messages for
346// keystroke messages and decodes the message parameters to pass relevant keyboard
347// messages to the application.  The framework does not remove the underlying keystroke
348// messages, which are still passed to the application's MsgProc callback.
349//--------------------------------------------------------------------------------------
350void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown )
351{
352    if( bKeyDown )
353    {
354        switch( nChar )
355        {
356            case VK_F1: g_bShowHelp = !g_bShowHelp; break;
357        }
358    }
359}
360
361
362//--------------------------------------------------------------------------------------
363// Handles the GUI events
364//--------------------------------------------------------------------------------------
365void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl )
366{
367   
368}
369
370
371//--------------------------------------------------------------------------------------
372// This callback function will be called immediately after the Direct3D device has
373// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
374// in the OnResetDevice callback should be released here, which generally includes all
375// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
376// information about lost devices.
377//--------------------------------------------------------------------------------------
378void CALLBACK OnLostDevice()
379{
380   
381}
382
383
384//--------------------------------------------------------------------------------------
385// This callback function will be called immediately after the Direct3D device has
386// been destroyed, which generally happens as a result of application termination or
387// windowed/full screen toggles. Resources created in the OnCreateDevice callback
388// should be released here, which generally includes all D3DPOOL_MANAGED resources.
389//--------------------------------------------------------------------------------------
390void CALLBACK OnDestroyDevice()
391{
392        g_RadiosityAlgorithm->deleteObjects();
393        SAFE_DELETE(g_RadiosityAlgorithm);
394}
395
396
397
Note: See TracBrowser for help on using the repository browser.