source: GTP/trunk/App/Demos/Illum/Standalone/StochasticIteration [DirectX]/Common/DXUTmisc.h @ 1808

Revision 1808, 38.7 KB checked in by szirmay, 18 years ago (diff)
Line 
1//--------------------------------------------------------------------------------------
2// File: DXUTMisc.h
3//
4// Helper functions for Direct3D programming.
5//
6// Copyright (c) Microsoft Corporation. All rights reserved
7//--------------------------------------------------------------------------------------
8#pragma once
9#ifndef DXUT_MISC_H
10#define DXUT_MISC_H
11
12
13//--------------------------------------------------------------------------------------
14// A growable array
15//--------------------------------------------------------------------------------------
16template< typename TYPE >
17class CGrowableArray
18{
19public:
20    CGrowableArray()  { m_pData = NULL; m_nSize = 0; m_nMaxSize = 0; }
21    CGrowableArray( const CGrowableArray<TYPE>& a ) { for( int i=0; i < a.m_nSize; i++ ) Add( a.m_pData[i] ); }
22    ~CGrowableArray() { RemoveAll(); }
23
24    const TYPE& operator[]( int nIndex ) const { return GetAt( nIndex ); }
25    TYPE& operator[]( int nIndex ) { return GetAt( nIndex ); }
26   
27    CGrowableArray& operator=( const CGrowableArray<TYPE>& a ) { if( this == &a ) return *this; RemoveAll(); for( int i=0; i < a.m_nSize; i++ ) Add( a.m_pData[i] ); return *this; }
28
29    HRESULT SetSize( int nNewMaxSize );
30    HRESULT Add( const TYPE& value );
31    HRESULT Insert( int nIndex, const TYPE& value );
32    HRESULT SetAt( int nIndex, const TYPE& value );
33    TYPE&   GetAt( int nIndex ) { assert( nIndex >= 0 && nIndex < m_nSize ); return m_pData[nIndex]; }
34    int     GetSize() const { return m_nSize; }
35    TYPE*   GetData() { return m_pData; }
36    bool    Contains( const TYPE& value ){ return ( -1 != IndexOf( value ) ); }
37
38    int     IndexOf( const TYPE& value ) { return ( m_nSize > 0 ) ? IndexOf( value, 0, m_nSize ) : -1; }
39    int     IndexOf( const TYPE& value, int iStart ) { return IndexOf( value, iStart, m_nSize - iStart ); }
40    int     IndexOf( const TYPE& value, int nIndex, int nNumElements );
41
42    int     LastIndexOf( const TYPE& value ) { return ( m_nSize > 0 ) ? LastIndexOf( value, m_nSize-1, m_nSize ) : -1; }
43    int     LastIndexOf( const TYPE& value, int nIndex ) { return LastIndexOf( value, nIndex, nIndex+1 ); }
44    int     LastIndexOf( const TYPE& value, int nIndex, int nNumElements );
45
46    HRESULT Remove( int nIndex );
47    void    RemoveAll() { SetSize(0); }
48
49protected:
50    TYPE* m_pData;      // the actual array of data
51    int m_nSize;        // # of elements (upperBound - 1)
52    int m_nMaxSize;     // max allocated
53
54    HRESULT SetSizeInternal( int nNewMaxSize );  // This version doesn't call ctor or dtor.
55};
56
57
58//--------------------------------------------------------------------------------------
59// Performs timer operations
60// Use DXUTGetGlobalTimer() to get the global instance
61//--------------------------------------------------------------------------------------
62class CDXUTTimer
63{
64public:
65    CDXUTTimer();
66
67    void Reset(); // resets the timer
68    void Start(); // starts the timer
69    void Stop();  // stop (or pause) the timer
70    void Advance(); // advance the timer by 0.1 seconds
71    double GetAbsoluteTime(); // get the absolute system time
72    double GetTime(); // get the current time
73    double GetElapsedTime(); // get the time that elapsed between GetElapsedTime() calls
74    bool IsStopped(); // returns true if timer stopped
75
76protected:
77    bool m_bUsingQPF;
78    bool m_bTimerStopped;
79    LONGLONG m_llQPFTicksPerSec;
80
81    LONGLONG m_llStopTime;
82    LONGLONG m_llLastElapsedTime;
83    LONGLONG m_llBaseTime;
84};
85
86CDXUTTimer* DXUTGetGlobalTimer();
87
88
89//-----------------------------------------------------------------------------
90// Resource cache for textures, fonts, meshs, and effects. 
91// Use DXUTGetGlobalResourceCache() to access the global cache
92//-----------------------------------------------------------------------------
93
94enum DXUTCACHE_SOURCELOCATION { DXUTCACHE_LOCATION_FILE, DXUTCACHE_LOCATION_RESOURCE };
95
96struct DXUTCache_Texture
97{
98    DXUTCACHE_SOURCELOCATION Location;
99    WCHAR wszSource[MAX_PATH];
100    HMODULE hSrcModule;
101    UINT Width;
102    UINT Height;
103    UINT Depth;
104    UINT MipLevels;
105    DWORD Usage;
106    D3DFORMAT Format;
107    D3DPOOL Pool;
108    D3DRESOURCETYPE Type;
109    IDirect3DBaseTexture9 *pTexture;
110};
111
112struct DXUTCache_Font : public D3DXFONT_DESC
113{
114    ID3DXFont *pFont;
115};
116
117struct DXUTCache_Effect
118{
119    DXUTCACHE_SOURCELOCATION Location;
120    WCHAR wszSource[MAX_PATH];
121    HMODULE hSrcModule;
122    DWORD dwFlags;
123    ID3DXEffect *pEffect;
124};
125
126
127class CDXUTResourceCache
128{
129public:
130    ~CDXUTResourceCache();
131
132    HRESULT CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, LPDIRECT3DTEXTURE9 *ppTexture );
133    HRESULT CreateTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Width, UINT Height, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DTEXTURE9 *ppTexture );
134    HRESULT CreateTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, LPDIRECT3DTEXTURE9 *ppTexture );
135    HRESULT CreateTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, UINT Width, UINT Height, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DTEXTURE9 *ppTexture );
136    HRESULT CreateCubeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, LPDIRECT3DCUBETEXTURE9 *ppCubeTexture );
137    HRESULT CreateCubeTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Size, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DCUBETEXTURE9 *ppCubeTexture );
138    HRESULT CreateCubeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, LPDIRECT3DCUBETEXTURE9 *ppCubeTexture );
139    HRESULT CreateCubeTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, UINT Size, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DCUBETEXTURE9 *ppCubeTexture );
140    HRESULT CreateVolumeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture );
141    HRESULT CreateVolumeTextureFromFileEx( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, UINT Width, UINT Height, UINT Depth, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DVOLUMETEXTURE9 *ppTexture );
142    HRESULT CreateVolumeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture );
143    HRESULT CreateVolumeTextureFromResourceEx( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, UINT Width, UINT Height, UINT Depth, UINT MipLevels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, DWORD Filter, DWORD MipFilter, D3DCOLOR ColorKey, D3DXIMAGE_INFO *pSrcInfo, PALETTEENTRY *pPalette, LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture );
144    HRESULT CreateFont( LPDIRECT3DDEVICE9 pDevice, UINT Height, UINT Width, UINT Weight, UINT MipLevels, BOOL Italic, DWORD CharSet, DWORD OutputPrecision, DWORD Quality, DWORD PitchAndFamily, LPCTSTR pFacename, LPD3DXFONT *ppFont );
145    HRESULT CreateFontIndirect( LPDIRECT3DDEVICE9 pDevice, CONST D3DXFONT_DESC *pDesc, LPD3DXFONT *ppFont );
146    HRESULT CreateEffectFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, const D3DXMACRO *pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXEFFECTPOOL pPool, LPD3DXEFFECT *ppEffect, LPD3DXBUFFER *ppCompilationErrors );
147    HRESULT CreateEffectFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, LPCTSTR pSrcResource, const D3DXMACRO *pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXEFFECTPOOL pPool, LPD3DXEFFECT *ppEffect, LPD3DXBUFFER *ppCompilationErrors );
148
149public:
150    HRESULT OnCreateDevice( IDirect3DDevice9 *pd3dDevice );
151    HRESULT OnResetDevice( IDirect3DDevice9 *pd3dDevice );
152    HRESULT OnLostDevice();
153    HRESULT OnDestroyDevice();
154
155protected:
156    friend CDXUTResourceCache& DXUTGetGlobalResourceCache();
157    friend HRESULT DXUTInitialize3DEnvironment();
158    friend HRESULT DXUTReset3DEnvironment();
159    friend void DXUTCleanup3DEnvironment( bool bReleaseSettings );
160
161    CDXUTResourceCache() { }
162
163    CGrowableArray< DXUTCache_Texture > m_TextureCache;
164    CGrowableArray< DXUTCache_Effect > m_EffectCache;
165    CGrowableArray< DXUTCache_Font > m_FontCache;
166};
167
168CDXUTResourceCache& DXUTGetGlobalResourceCache();
169
170
171//--------------------------------------------------------------------------------------
172class CD3DArcBall
173{
174public:
175    CD3DArcBall();
176
177    // Functions to change behavior
178    void Reset();
179    void SetTranslationRadius( FLOAT fRadiusTranslation ) { m_fRadiusTranslation = fRadiusTranslation; }
180    void SetWindow( INT nWidth, INT nHeight, FLOAT fRadius = 0.9f ) { m_nWidth = nWidth; m_nHeight = nHeight; m_fRadius = fRadius; m_vCenter = D3DXVECTOR2(m_nWidth/2.0f,m_nHeight/2.0f); }
181    void SetOffset( INT nX, INT nY ) { m_Offset.x = nX; m_Offset.y = nY; }
182
183    // Call these from client and use GetRotationMatrix() to read new rotation matrix
184    void OnBegin( int nX, int nY );  // start the rotation (pass current mouse position)
185    void OnMove( int nX, int nY );   // continue the rotation (pass current mouse position)
186    void OnEnd();                    // end the rotation
187
188    // Or call this to automatically handle left, middle, right buttons
189    LRESULT     HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
190
191    // Functions to get/set state
192    D3DXMATRIX* GetRotationMatrix() { return D3DXMatrixRotationQuaternion(&m_mRotation, &m_qNow); };
193    D3DXMATRIX* GetTranslationMatrix()      { return &m_mTranslation; }
194    D3DXMATRIX* GetTranslationDeltaMatrix() { return &m_mTranslationDelta; }
195    bool        IsBeingDragged()            { return m_bDrag; }
196    D3DXQUATERNION GetQuatNow()             { return m_qNow; }
197    void        SetQuatNow( D3DXQUATERNION q ) { m_qNow = q; }
198
199    static D3DXQUATERNION QuatFromBallPoints( const D3DXVECTOR3 &vFrom, const D3DXVECTOR3 &vTo );
200
201
202protected:
203    D3DXMATRIXA16  m_mRotation;         // Matrix for arc ball's orientation
204    D3DXMATRIXA16  m_mTranslation;      // Matrix for arc ball's position
205    D3DXMATRIXA16  m_mTranslationDelta; // Matrix for arc ball's position
206
207    POINT          m_Offset;   // window offset, or upper-left corner of window
208    INT            m_nWidth;   // arc ball's window width
209    INT            m_nHeight;  // arc ball's window height
210    D3DXVECTOR2    m_vCenter;  // center of arc ball
211    FLOAT          m_fRadius;  // arc ball's radius in screen coords
212    FLOAT          m_fRadiusTranslation; // arc ball's radius for translating the target
213
214    D3DXQUATERNION m_qDown;             // Quaternion before button down
215    D3DXQUATERNION m_qNow;              // Composite quaternion for current drag
216    bool           m_bDrag;             // Whether user is dragging arc ball
217
218    POINT          m_ptLastMouse;      // position of last mouse point
219    D3DXVECTOR3    m_vDownPt;           // starting point of rotation arc
220    D3DXVECTOR3    m_vCurrentPt;        // current point of rotation arc
221
222    D3DXVECTOR3    ScreenToVector( float fScreenPtX, float fScreenPtY );
223};
224
225
226//--------------------------------------------------------------------------------------
227// used by CCamera to map WM_KEYDOWN keys
228//--------------------------------------------------------------------------------------
229enum D3DUtil_CameraKeys
230{
231    CAM_STRAFE_LEFT = 0,
232    CAM_STRAFE_RIGHT,
233    CAM_MOVE_FORWARD,
234    CAM_MOVE_BACKWARD,
235    CAM_MOVE_UP,
236    CAM_MOVE_DOWN,
237    CAM_RESET,
238    CAM_CONTROLDOWN,
239    CAM_MAX_KEYS,
240    CAM_UNKNOWN = 0xFF
241};
242
243#define KEY_WAS_DOWN_MASK 0x80
244#define KEY_IS_DOWN_MASK  0x01
245
246#define MOUSE_LEFT_BUTTON   0x01
247#define MOUSE_MIDDLE_BUTTON 0x02
248#define MOUSE_RIGHT_BUTTON  0x04
249#define MOUSE_WHEEL         0x08
250
251
252//--------------------------------------------------------------------------------------
253// Simple base camera class that moves and rotates.  The base class
254//       records mouse and keyboard input for use by a derived class, and
255//       keeps common state.
256//--------------------------------------------------------------------------------------
257class CBaseCamera
258{
259public:
260    CBaseCamera();
261
262    // Call these from client and use Get*Matrix() to read new matrices
263    virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
264    virtual void    FrameMove( FLOAT fElapsedTime ) = 0;
265
266    // Functions to change camera matrices
267    virtual void Reset();
268    virtual void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt );
269    virtual void SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, FLOAT fFarPlane );
270
271    // Functions to change behavior
272    virtual void SetDragRect( RECT &rc ) { m_rcDrag = rc; }
273    void SetInvertPitch( bool bInvertPitch ) { m_bInvertPitch = bInvertPitch; }
274    void SetDrag( bool bMovementDrag, FLOAT fTotalDragTimeToZero = 0.25f ) { m_bMovementDrag = bMovementDrag; m_fTotalDragTimeToZero = fTotalDragTimeToZero; }
275    void SetEnableYAxisMovement( bool bEnableYAxisMovement ) { m_bEnableYAxisMovement = bEnableYAxisMovement; }
276    void SetEnablePositionMovement( bool bEnablePositionMovement ) { m_bEnablePositionMovement = bEnablePositionMovement; }
277    void SetClipToBoundary( bool bClipToBoundary, D3DXVECTOR3* pvMinBoundary, D3DXVECTOR3* pvMaxBoundary ) { m_bClipToBoundary = bClipToBoundary; if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; if( pvMaxBoundary ) m_vMaxBoundary = *pvMaxBoundary; }
278    void SetScalers( FLOAT fRotationScaler = 0.01f, FLOAT fMoveScaler = 5.0f )  { m_fRotationScaler = fRotationScaler; m_fMoveScaler = fMoveScaler; }
279    void SetNumberOfFramesToSmoothMouseData( int nFrames ) { if( nFrames > 0 ) m_fFramesToSmoothMouseData = (float)nFrames; }
280    void SetResetCursorAfterMove( bool bResetCursorAfterMove ) { m_bResetCursorAfterMove = bResetCursorAfterMove; }
281
282    // Functions to get state
283    const D3DXMATRIX*  GetViewMatrix() const { return &m_mView; }
284    const D3DXMATRIX*  GetProjMatrix() const { return &m_mProj; }
285    const D3DXVECTOR3* GetEyePt() const      { return &m_vEye; }
286    const D3DXVECTOR3* GetLookAtPt() const   { return &m_vLookAt; }
287
288    bool IsBeingDragged() { return (m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown); }
289    bool IsMouseLButtonDown() { return m_bMouseLButtonDown; }
290    bool IsMouseMButtonDown() { return m_bMouseMButtonDown; }
291    bool IsMouseRButtonDown() { return m_bMouseRButtonDown; }
292
293protected:
294    // Functions to map a WM_KEYDOWN key to a D3DUtil_CameraKeys enum
295    virtual D3DUtil_CameraKeys MapKey( UINT nKey );   
296    bool IsKeyDown( BYTE key )  { return( (key & KEY_IS_DOWN_MASK) == KEY_IS_DOWN_MASK ); }
297    bool WasKeyDown( BYTE key ) { return( (key & KEY_WAS_DOWN_MASK) == KEY_WAS_DOWN_MASK ); }
298
299    void ConstrainToBoundary( D3DXVECTOR3* pV );
300    void UpdateMouseDelta( float fElapsedTime );
301    void UpdateVelocity( float fElapsedTime );
302
303    D3DXMATRIX            m_mView;              // View matrix
304    D3DXMATRIX            m_mProj;              // Projection matrix
305
306    BYTE                  m_aKeys[CAM_MAX_KEYS];  // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK
307    POINT                 m_ptLastMousePosition;  // Last absolute position of mouse cursor
308    bool                  m_bMouseLButtonDown;    // True if left button is down
309    bool                  m_bMouseMButtonDown;    // True if middle button is down
310    bool                  m_bMouseRButtonDown;    // True if right button is down
311    int                   m_nCurrentButtonMask;   // mask of which buttons are down
312    int                   m_nMouseWheelDelta;     // Amount of middle wheel scroll (+/-)
313    D3DXVECTOR2           m_vMouseDelta;          // Mouse relative delta smoothed over a few frames
314    float                 m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over
315
316    D3DXVECTOR3           m_vDefaultEye;          // Default camera eye position
317    D3DXVECTOR3           m_vDefaultLookAt;       // Default LookAt position
318    D3DXVECTOR3           m_vEye;                 // Camera eye position
319    D3DXVECTOR3           m_vLookAt;              // LookAt position
320    float                 m_fCameraYawAngle;      // Yaw angle of camera
321    float                 m_fCameraPitchAngle;    // Pitch angle of camera
322
323    RECT                  m_rcDrag;               // Rectangle within which a drag can be initiated.
324    D3DXVECTOR3           m_vVelocity;            // Velocity of camera
325    bool                  m_bMovementDrag;        // If true, then camera movement will slow to a stop otherwise movement is instant
326    D3DXVECTOR3           m_vVelocityDrag;        // Velocity drag force
327    FLOAT                 m_fDragTimer;           // Countdown timer to apply drag
328    FLOAT                 m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0
329    D3DXVECTOR2           m_vRotVelocity;         // Velocity of camera
330
331    float                 m_fFOV;                 // Field of view
332    float                 m_fAspect;              // Aspect ratio
333    float                 m_fNearPlane;           // Near plane
334    float                 m_fFarPlane;            // Far plane
335
336    float                 m_fRotationScaler;      // Scaler for rotation
337    float                 m_fMoveScaler;          // Scaler for movement
338
339    bool                  m_bInvertPitch;         // Invert the pitch axis
340    bool                  m_bEnablePositionMovement; // If true, then the user can translate the camera/model
341    bool                  m_bEnableYAxisMovement; // If true, then camera can move in the y-axis
342
343    bool                  m_bClipToBoundary;      // If true, then the camera will be clipped to the boundary
344    D3DXVECTOR3           m_vMinBoundary;         // Min point in clip boundary
345    D3DXVECTOR3           m_vMaxBoundary;         // Max point in clip boundary
346
347    bool                  m_bResetCursorAfterMove;// If true, the class will reset the cursor position so that the cursor always has space to move
348};
349
350
351//--------------------------------------------------------------------------------------
352// Simple first person camera class that moves and rotates.
353//       It allows yaw and pitch but not roll.  It uses WM_KEYDOWN and
354//       GetCursorPos() to respond to keyboard and mouse input and updates the
355//       view matrix based on input. 
356//--------------------------------------------------------------------------------------
357class CFirstPersonCamera : public CBaseCamera
358{
359public:
360    CFirstPersonCamera();
361
362    // Call these from client and use Get*Matrix() to read new matrices
363    virtual void FrameMove( FLOAT fElapsedTime );
364
365    // Functions to change behavior
366    void SetRotateButtons( bool bLeft, bool bMiddle, bool bRight );
367
368    // Functions to get state
369    D3DXMATRIX*  GetWorldMatrix()            { return &m_mCameraWorld; }
370
371    const D3DXVECTOR3* GetWorldRight() const { return (D3DXVECTOR3*)&m_mCameraWorld._11; }
372    const D3DXVECTOR3* GetWorldUp() const    { return (D3DXVECTOR3*)&m_mCameraWorld._21; }
373    const D3DXVECTOR3* GetWorldAhead() const { return (D3DXVECTOR3*)&m_mCameraWorld._31; }
374    const D3DXVECTOR3* GetEyePt() const      { return (D3DXVECTOR3*)&m_mCameraWorld._41; }
375
376protected:
377    D3DXMATRIX m_mCameraWorld;       // World matrix of the camera (inverse of the view matrix)
378
379    int        m_nActiveButtonMask;  // Mask to determine which button to enable for rotation
380};
381
382
383//--------------------------------------------------------------------------------------
384// Simple model viewing camera class that rotates around the object.
385//--------------------------------------------------------------------------------------
386class CModelViewerCamera : public CBaseCamera
387{
388public:
389    CModelViewerCamera();
390
391    // Call these from client and use Get*Matrix() to read new matrices
392    virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
393    virtual void FrameMove( FLOAT fElapsedTime );
394
395   
396    // Functions to change behavior
397    virtual void SetDragRect( RECT &rc );
398    void Reset();
399    void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt );
400    void SetButtonMasks( int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, int nZoomButtonMask = MOUSE_WHEEL, int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON ) { m_nRotateModelButtonMask = nRotateModelButtonMask, m_nZoomButtonMask = nZoomButtonMask; m_nRotateCameraButtonMask = nRotateCameraButtonMask; }
401    void SetAttachCameraToModel( bool bEnable = false ) { m_bAttachCameraToModel = bEnable; }
402    void SetWindow( int nWidth, int nHeight, float fArcballRadius=0.9f ) { m_WorldArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); m_ViewArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); }
403    void SetRadius( float fDefaultRadius=5.0f, float fMinRadius=1.0f, float fMaxRadius=FLT_MAX  ) { m_fDefaultRadius = m_fRadius = fDefaultRadius; m_fMinRadius = fMinRadius; m_fMaxRadius = fMaxRadius; }
404    void SetModelCenter( D3DXVECTOR3 vModelCenter ) { m_vModelCenter = vModelCenter; }
405    void SetLimitPitch( bool bLimitPitch ) { m_bLimitPitch = bLimitPitch; }
406    void SetViewQuat( D3DXQUATERNION q ) { m_ViewArcBall.SetQuatNow( q ); }
407    void SetWorldQuat( D3DXQUATERNION q ) { m_WorldArcBall.SetQuatNow( q ); }
408
409    // Functions to get state
410    D3DXMATRIX* GetWorldMatrix() { return &m_mWorld; }
411
412protected:
413    CD3DArcBall  m_WorldArcBall;
414    CD3DArcBall  m_ViewArcBall;
415    D3DXVECTOR3  m_vModelCenter;
416    D3DXMATRIX   m_mModelLastRot;        // Last arcball rotation matrix for model
417    D3DXMATRIX   m_mModelRot;            // Rotation matrix of model
418    D3DXMATRIX   m_mWorld;               // World matrix of model
419
420    int          m_nRotateModelButtonMask;
421    int          m_nZoomButtonMask;
422    int          m_nRotateCameraButtonMask;
423
424    bool         m_bAttachCameraToModel;
425    bool         m_bLimitPitch;
426    float        m_fRadius;              // Distance from the camera to model
427    float        m_fDefaultRadius;       // Distance from the camera to model
428    float        m_fMinRadius;           // Min radius
429    float        m_fMaxRadius;           // Max radius
430
431    D3DXMATRIX   m_mCameraRotLast;
432
433};
434
435
436//--------------------------------------------------------------------------------------
437// Manages the intertion point when drawing text
438//--------------------------------------------------------------------------------------
439class CDXUTTextHelper
440{
441public:
442    CDXUTTextHelper( ID3DXFont* pFont, ID3DXSprite* pSprite, int nLineHeight );
443
444    void SetInsertionPos( int x, int y ) { m_pt.x = x; m_pt.y = y; }
445    void SetForegroundColor( D3DXCOLOR clr ) { m_clr = clr; }
446
447    void Begin();
448    HRESULT DrawFormattedTextLine( const WCHAR* strMsg, ... );
449    HRESULT DrawTextLine( const WCHAR* strMsg );
450    HRESULT DrawFormattedTextLine( RECT &rc, DWORD dwFlags, const WCHAR* strMsg, ... );
451    HRESULT DrawTextLine( RECT &rc, DWORD dwFlags, const WCHAR* strMsg );
452    void End();
453
454protected:
455    ID3DXFont*   m_pFont;
456    ID3DXSprite* m_pSprite;
457    D3DXCOLOR    m_clr;
458    POINT        m_pt;
459    int          m_nLineHeight;
460};
461
462
463//--------------------------------------------------------------------------------------
464// Manages a persistent list of lines and draws them using ID3DXLine
465//--------------------------------------------------------------------------------------
466class CDXUTLineManager
467{
468public:
469    CDXUTLineManager();
470    ~CDXUTLineManager();
471
472    HRESULT OnCreatedDevice( IDirect3DDevice9* pd3dDevice );
473    HRESULT OnResetDevice();
474    HRESULT OnRender();
475    HRESULT OnLostDevice();
476    HRESULT OnDeletedDevice();
477
478    HRESULT AddLine( int* pnLineID, D3DXVECTOR2* pVertexList, DWORD dwVertexListCount, D3DCOLOR Color, float fWidth, float fScaleRatio, bool bAntiAlias );
479    HRESULT AddRect( int* pnLineID, RECT rc, D3DCOLOR Color, float fWidth, float fScaleRatio, bool bAntiAlias );
480    HRESULT RemoveLine( int nLineID );
481    HRESULT RemoveAllLines();
482
483protected:
484    struct LINE_NODE
485    {
486        int      nLineID;
487        D3DCOLOR Color;
488        float    fWidth;
489        bool     bAntiAlias;
490        float    fScaleRatio;
491        D3DXVECTOR2* pVertexList;
492        DWORD    dwVertexListCount;
493    };
494
495    CGrowableArray<LINE_NODE*> m_LinesList;
496    IDirect3DDevice9* m_pd3dDevice;
497    ID3DXLine* m_pD3DXLine;
498};
499
500
501//--------------------------------------------------------------------------------------
502// Manages the mesh, direction, mouse events of a directional arrow that
503// rotates around a radius controlled by an arcball
504//--------------------------------------------------------------------------------------
505class CDXUTDirectionWidget
506{
507public:
508    CDXUTDirectionWidget();
509
510    static HRESULT StaticOnCreateDevice( IDirect3DDevice9* pd3dDevice );
511    HRESULT OnResetDevice( const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
512    HRESULT OnRender( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, const D3DXVECTOR3* pEyePt );
513    LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
514    static void StaticOnLostDevice();
515    static void StaticOnDestroyDevice();
516
517    D3DXVECTOR3 GetLightDirection()         { return m_vCurrentDir; };
518    void        SetLightDirection( D3DXVECTOR3 vDir ) { m_vDefaultDir = m_vCurrentDir = vDir; };
519    void        SetButtonMask( int nRotate = MOUSE_RIGHT_BUTTON ) { m_nRotateMask = nRotate; }
520
521    float GetRadius()                 { return m_fRadius; };
522    void  SetRadius( float fRadius )  { m_fRadius = fRadius; };
523
524    bool  IsBeingDragged() { return m_ArcBall.IsBeingDragged(); };
525
526protected:
527    HRESULT UpdateLightDir();
528
529    static IDirect3DDevice9* s_pd3dDevice;
530    static ID3DXEffect* s_pEffect;       
531    static ID3DXMesh*   s_pMesh;   
532
533    float          m_fRadius;
534    int            m_nRotateMask;
535    CD3DArcBall    m_ArcBall;
536    D3DXVECTOR3    m_vDefaultDir;
537    D3DXVECTOR3    m_vCurrentDir;
538    D3DXMATRIX     m_mView;
539    D3DXMATRIXA16  m_mRot;
540    D3DXMATRIXA16  m_mRotSnapshot;
541};
542
543
544//--------------------------------------------------------------------------------------
545// Returns the DirectX SDK path, as stored in the system registry
546//       during the SDK install.
547//--------------------------------------------------------------------------------------
548HRESULT DXUTGetDXSDKMediaPathCch( WCHAR* strDest, int cchDest );
549HRESULT DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, LPCWSTR strFilename );
550
551
552//--------------------------------------------------------------------------------------
553// Returns the string for the given D3DFORMAT.
554//       bWithPrefix determines whether the string should include the "D3DFMT_"
555//--------------------------------------------------------------------------------------
556LPCWSTR DXUTD3DFormatToString( D3DFORMAT format, bool bWithPrefix );
557
558
559//--------------------------------------------------------------------------------------
560// Builds and sets a cursor for the D3D device based on hCursor.
561//--------------------------------------------------------------------------------------
562HRESULT DXUTSetDeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark );
563
564
565//--------------------------------------------------------------------------------------
566// Returns a view matrix for rendering to a face of a cubemap.
567//--------------------------------------------------------------------------------------
568D3DXMATRIX DXUTGetCubeMapViewMatrix( DWORD dwFace );
569
570
571//--------------------------------------------------------------------------------------
572// Debug printing support
573// See dxerr9.h for more debug printing support
574//--------------------------------------------------------------------------------------
575void DXUTOutputDebugStringW( LPCWSTR strMsg, ... );
576void DXUTOutputDebugStringA( LPCSTR strMsg, ... );
577HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, const WCHAR* strMsg, bool bPopMsgBox );
578
579#ifdef UNICODE
580#define DXUTOutputDebugString DXUTOutputDebugStringW
581#else
582#define DXUTOutputDebugString DXUTOutputDebugStringA
583#endif
584
585// These macros are very similar to dxerr9's but it special cases the HRESULT defined
586// by the sample framework pop better message boxes.
587#if defined(DEBUG) | defined(_DEBUG)
588#define DXUT_ERR(str,hr)           DXUTTrace( __FILE__, (DWORD)__LINE__, hr, str, false )
589#define DXUT_ERR_MSGBOX(str,hr)    DXUTTrace( __FILE__, (DWORD)__LINE__, hr, str, true )
590#define DXUTTRACE                  DXUTOutputDebugString
591#else
592#define DXUT_ERR(str,hr)           (hr)
593#define DXUT_ERR_MSGBOX(str,hr)    (hr)
594#define DXUTTRACE                  (__noop)
595#endif
596
597
598//--------------------------------------------------------------------------------------
599// Direct3D9 dynamic linking support -- calls top-level D3D9 APIs with graceful
600// failure if APIs are not present.
601//--------------------------------------------------------------------------------------
602
603IDirect3D9 * WINAPI DXUT_Dynamic_Direct3DCreate9(UINT SDKVersion);
604int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName );
605int WINAPI DXUT_Dynamic_D3DPERF_EndEvent( void );
606void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( D3DCOLOR col, LPCWSTR wszName );
607void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( D3DCOLOR col, LPCWSTR wszName );
608BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame( void );
609void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( DWORD dwOptions );
610DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus( void );
611
612
613//--------------------------------------------------------------------------------------
614// Profiling/instrumentation support
615//--------------------------------------------------------------------------------------
616
617//--------------------------------------------------------------------------------------
618// Some D3DPERF APIs take a color that can be used when displaying user events in
619// performance analysis tools.  The following constants are provided for your
620// convenience, but you can use any colors you like.
621//--------------------------------------------------------------------------------------
622const D3DCOLOR DXUT_PERFEVENTCOLOR  = D3DCOLOR_XRGB(200,100,100);
623const D3DCOLOR DXUT_PERFEVENTCOLOR2 = D3DCOLOR_XRGB(100,200,100);
624const D3DCOLOR DXUT_PERFEVENTCOLOR3 = D3DCOLOR_XRGB(100,100,200);
625
626//--------------------------------------------------------------------------------------
627// The following macros provide a convenient way for your code to call the D3DPERF
628// functions only when PROFILE is defined.  If PROFILE is not defined (as for the final
629// release version of a program), these macros evaluate to nothing, so no detailed event
630// information is embedded in your shipping program.  It is recommended that you create
631// and use three build configurations for your projects:
632//     Debug (nonoptimized code, asserts active, PROFILE defined to assist debugging)
633//     Profile (optimized code, asserts disabled, PROFILE defined to assist optimization)
634//     Release (optimized code, asserts disabled, PROFILE not defined)
635//--------------------------------------------------------------------------------------
636#ifdef PROFILE
637// PROFILE is defined, so these macros call the D3DPERF functions
638#define DXUT_BeginPerfEvent( color, pstrMessage )   DXUT_Dynamic_D3DPERF_BeginEvent( color, pstrMessage )
639#define DXUT_EndPerfEvent()                         DXUT_Dynamic_D3DPERF_EndEvent()
640#define DXUT_SetPerfMarker( color, pstrMessage )    DXUT_Dynamic_D3DPERF_SetMarker( color, pstrMessage )
641#else
642// PROFILE is not defined, so these macros do nothing
643#define DXUT_BeginPerfEvent( color, pstrMessage )   (__noop)
644#define DXUT_EndPerfEvent()                         (__noop)
645#define DXUT_SetPerfMarker( color, pstrMessage )    (__noop)
646#endif
647
648//--------------------------------------------------------------------------------------
649// CDXUTPerfEventGenerator is a helper class that makes it easy to attach begin and end
650// events to a block of code.  Simply define a CDXUTPerfEventGenerator variable anywhere
651// in a block of code, and the class's constructor will call DXUT_BeginPerfEvent when
652// the block of code begins, and the class's destructor will call DXUT_EndPerfEvent when
653// the block ends.
654//--------------------------------------------------------------------------------------
655class CDXUTPerfEventGenerator
656{
657public:
658    CDXUTPerfEventGenerator( D3DCOLOR color, WCHAR* pstrMessage ) { DXUT_BeginPerfEvent( color, pstrMessage ); }
659    ~CDXUTPerfEventGenerator( void ) { DXUT_EndPerfEvent(); }
660};
661
662//--------------------------------------------------------------------------------------
663// Implementation of CGrowableArray
664//--------------------------------------------------------------------------------------
665
666// This version doesn't call ctor or dtor.
667template< typename TYPE >
668HRESULT CGrowableArray<TYPE>::SetSizeInternal( int nNewMaxSize )
669{
670    if( nNewMaxSize < 0 )
671    {
672        assert( false );
673        return E_INVALIDARG;
674    }
675
676    if( nNewMaxSize == 0 )
677    {
678        // Shrink to 0 size & cleanup
679        if( m_pData )
680        {
681            free( m_pData );
682            m_pData = NULL;
683        }
684
685        m_nMaxSize = 0;
686        m_nSize = 0;
687    }
688    else if( m_pData == NULL || nNewMaxSize > m_nMaxSize )
689    {
690        // Grow array
691        int nGrowBy = ( m_nMaxSize == 0 ) ? 16 : m_nMaxSize;
692        nNewMaxSize = max( nNewMaxSize, m_nMaxSize + nGrowBy );
693
694        TYPE* pDataNew = (TYPE*) realloc( m_pData, nNewMaxSize * sizeof(TYPE) );
695        if( pDataNew == NULL )
696            return E_OUTOFMEMORY;
697
698        m_pData = pDataNew;
699        m_nMaxSize = nNewMaxSize;
700    }
701
702    return S_OK;
703}
704
705
706//--------------------------------------------------------------------------------------
707template< typename TYPE >
708HRESULT CGrowableArray<TYPE>::SetSize( int nNewMaxSize )
709{
710    int nOldSize = m_nSize;
711
712    if( nOldSize > nNewMaxSize )
713    {
714        // Removing elements. Call dtor.
715
716        for( int i = nNewMaxSize; i < nOldSize; ++i )
717            m_pData[i].~TYPE();
718    }
719
720    // Adjust buffer.  Note that there's no need to check for error
721    // since if it happens, nOldSize == nNewMaxSize will be true.)
722    HRESULT hr = SetSizeInternal( nNewMaxSize );
723
724    if( nOldSize < nNewMaxSize )
725    {
726        // Adding elements. Call ctor.
727
728        for( int i = nOldSize; i < nNewMaxSize; ++i )
729            ::new (&m_pData[i]) TYPE;
730    }
731
732    return hr;
733}
734
735
736//--------------------------------------------------------------------------------------
737template< typename TYPE >
738HRESULT CGrowableArray<TYPE>::Add( const TYPE& value )
739{
740    HRESULT hr;
741    if( FAILED( hr = SetSizeInternal( m_nSize + 1 ) ) )
742        return hr;
743
744    // Construct the new element
745    ::new (&m_pData[m_nSize]) TYPE;
746
747    // Assign
748    m_pData[m_nSize] = value;
749    ++m_nSize;
750
751    return S_OK;
752}
753
754
755//--------------------------------------------------------------------------------------
756template< typename TYPE >
757HRESULT CGrowableArray<TYPE>::Insert( int nIndex, const TYPE& value )
758{
759    HRESULT hr;
760
761    // Validate index
762    if( nIndex < 0 ||
763        nIndex > m_nSize )
764    {
765        assert( false );
766        return E_INVALIDARG;
767    }
768
769    // Prepare the buffer
770    if( FAILED( hr = SetSizeInternal( m_nSize + 1 ) ) )
771        return hr;
772
773    // Shift the array
774    MoveMemory( &m_pData[nIndex+1], &m_pData[nIndex], sizeof(TYPE) * (m_nSize - nIndex) );
775
776    // Construct the new element
777    ::new (&m_pData[nIndex]) TYPE;
778
779    // Set the value and increase the size
780    m_pData[nIndex] = value;
781    ++m_nSize;
782
783    return S_OK;
784}
785
786
787//--------------------------------------------------------------------------------------
788template< typename TYPE >
789HRESULT CGrowableArray<TYPE>::SetAt( int nIndex, const TYPE& value )
790{
791    // Validate arguments
792    if( nIndex < 0 ||
793        nIndex >= m_nSize )
794    {
795        assert( false );
796        return E_INVALIDARG;
797    }
798
799    m_pData[nIndex] = value;
800    return S_OK;
801}
802
803
804//--------------------------------------------------------------------------------------
805// Searches for the specified value and returns the index of the first occurrence
806// within the section of the data array that extends from iStart and contains the
807// specified number of elements. Returns -1 if value is not found within the given
808// section.
809//--------------------------------------------------------------------------------------
810template< typename TYPE >
811int CGrowableArray<TYPE>::IndexOf( const TYPE& value, int iStart, int nNumElements )
812{
813    // Validate arguments
814    if( iStart < 0 ||
815        iStart >= m_nSize ||
816        nNumElements < 0 ||
817        iStart + nNumElements > m_nSize )
818    {
819        assert( false );
820        return -1;
821    }
822
823    // Search
824    for( int i = iStart; i < (iStart + nNumElements); i++ )
825    {
826        if( value == m_pData[i] )
827            return i;
828    }
829
830    // Not found
831    return -1;
832}
833
834
835//--------------------------------------------------------------------------------------
836// Searches for the specified value and returns the index of the last occurrence
837// within the section of the data array that contains the specified number of elements
838// and ends at iEnd. Returns -1 if value is not found within the given section.
839//--------------------------------------------------------------------------------------
840template< typename TYPE >
841int CGrowableArray<TYPE>::LastIndexOf( const TYPE& value, int iEnd, int nNumElements )
842{
843    // Validate arguments
844    if( iEnd < 0 ||
845        iEnd >= m_nSize ||
846        nNumElements < 0 ||
847        iEnd - nNumElements < 0 )
848    {
849        assert( false );
850        return -1;
851    }
852
853    // Search
854    for( int i = iEnd; i > (iEnd - nNumElements); i-- )
855    {
856        if( value == m_pData[i] )
857            return i;
858    }
859
860    // Not found
861    return -1;
862}
863
864
865
866//--------------------------------------------------------------------------------------
867template< typename TYPE >
868HRESULT CGrowableArray<TYPE>::Remove( int nIndex )
869{
870    if( nIndex < 0 ||
871        nIndex >= m_nSize )
872    {
873        assert( false );
874        return E_INVALIDARG;
875    }
876
877    // Destruct the element to be removed
878    m_pData[nIndex].~TYPE();
879
880    // Compact the array and decrease the size
881    MoveMemory( &m_pData[nIndex], &m_pData[nIndex+1], sizeof(TYPE) * (m_nSize - (nIndex+1)) );
882    --m_nSize;
883
884    return S_OK;
885}
886
887
888#endif
Note: See TracBrowser for help on using the repository browser.