source: GTP/trunk/App/Demos/Illum/MultipleReflections/Common/DXUTmisc.h @ 2242

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