source: GTP/trunk/App/Demos/Illum/Glow/Common/DXUTmisc.h @ 846

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