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

Revision 761, 43.7 KB checked in by szirmay, 19 years ago (diff)

Added a folder remotely

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