diff options
| author | Vishal More <[email protected]> | 2020-06-11 11:11:17 +0530 |
|---|---|---|
| committer | Vishal More <[email protected]> | 2020-06-11 11:11:17 +0530 |
| commit | bbe353230727568d3c1999af2701d2e150ff232f (patch) | |
| tree | 4b75466fc0f5b8fb70bc020a9da22d2b924d0aab /samples/DX_APIUsage/DXUT/Optional | |
| parent | Documentation Update (diff) | |
| download | gfesdk-bbe353230727568d3c1999af2701d2e150ff232f.tar.xz gfesdk-bbe353230727568d3c1999af2701d2e150ff232f.zip | |
Picking up lastest bug fixes & SHA2 signing1.1.232
[SNG-2803] GFE-SDK : SHA-2 sign task
Diffstat (limited to 'samples/DX_APIUsage/DXUT/Optional')
17 files changed, 4632 insertions, 9784 deletions
diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTLockFreePipe.h b/samples/DX_APIUsage/DXUT/Optional/DXUTLockFreePipe.h index 7dfe14d..b41d34a 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTLockFreePipe.h +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTLockFreePipe.h @@ -2,40 +2,35 @@ // DXUTLockFreePipe.h // // See the "Lockless Programming Considerations for Xbox 360 and Microsoft Windows" -// article in the DirectX SDK for more details. +// article for more details. // -// http://msdn2.microsoft.com/en-us/library/bb310595.aspx +// http://msdn.microsoft.com/en-us/library/ee418650.aspx // -// XNA Developer Connection -// Copyright (C) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once #include <sal.h> +#include <algorithm> + +#pragma pack(push) +#pragma pack(8) +#include <windows.h> +#pragma pack (pop) + +extern "C" + void _ReadWriteBarrier(); +#pragma intrinsic(_ReadWriteBarrier) -#ifdef _XBOX_VER - // Prevent the CPU from rearranging loads - // and stores, sufficiently for read-acquire - // and write-release. - #define DXUTImportBarrier __lwsync - #define DXUTExportBarrier __lwsync -#else - #pragma pack(push) - #pragma pack(8) - #include <windows.h> - #pragma pack (pop) - - extern "C" - void _ReadWriteBarrier(); - #pragma intrinsic(_ReadWriteBarrier) - - // Prevent the compiler from rearranging loads - // and stores, sufficiently for read-acquire - // and write-release. This is sufficient on - // x86 and x64. - #define DXUTImportBarrier _ReadWriteBarrier - #define DXUTExportBarrier _ReadWriteBarrier -#endif +// Prevent the compiler from rearranging loads +// and stores, sufficiently for read-acquire +// and write-release. This is sufficient on +// x86 and x64. +#define DXUTImportBarrier _ReadWriteBarrier +#define DXUTExportBarrier _ReadWriteBarrier // // Pipe class designed for use by at most two threads: one reader, one writer. @@ -63,7 +58,7 @@ public: return m_writeOffset - m_readOffset; } - bool __forceinline Read( void* pvDest, unsigned long cbDest ) + bool __forceinline Read( _Out_writes_(cbDest) void* pvDest, _In_ unsigned long cbDest ) { // Store the read and write offsets into local variables--this is // essentially a snapshot of their values so that they stay constant @@ -118,7 +113,7 @@ public: // then the previous comparison would have failed since that would imply // that there were less than cbDest bytes available to read. // - unsigned long cbTailBytes = min( bytesLeft, c_cbBufferSize - actualReadOffset ); + unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualReadOffset ); memcpy( pbDest, m_pbBuffer + actualReadOffset, cbTailBytes ); bytesLeft -= cbTailBytes; @@ -148,7 +143,7 @@ public: return true; } - bool __forceinline Write( const void* pvSrc, unsigned long cbSrc ) + bool __forceinline Write( _In_reads_(cbSrc) const void* pvSrc, _In_ unsigned long cbSrc ) { // Reading the read offset here has the same caveats as reading // the write offset had in the Read() function above. @@ -179,7 +174,7 @@ public: // See the explanation in the Read() function as to why we don't // explicitly check against the read offset here. - unsigned long cbTailBytes = min( bytesLeft, c_cbBufferSize - actualWriteOffset ); + unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualWriteOffset ); memcpy( m_pbBuffer + actualWriteOffset, pbSrc, cbTailBytes ); bytesLeft -= cbTailBytes; @@ -208,7 +203,7 @@ public: private: // Values derived from the buffer size template parameter // - const static BYTE c_cbBufferSizeLog2 = min( cbBufferSizeLog2, 31 ); + const static BYTE c_cbBufferSizeLog2 = __min( cbBufferSizeLog2, 31 ); const static DWORD c_cbBufferSize = ( 1 << c_cbBufferSizeLog2 ); const static DWORD c_sizeMask = c_cbBufferSize - 1; diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.cpp b/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.cpp index 42e8ea4..f6a1ac7 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.cpp @@ -1,20 +1,28 @@ //-------------------------------------------------------------------------------------- // File: DXUTcamera.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTres.h" -#undef min // use __min instead -#undef max // use __max instead + +using namespace DirectX; + +//====================================================================================== +// CD3DArcBall +//====================================================================================== //-------------------------------------------------------------------------------------- CD3DArcBall::CD3DArcBall() { Reset(); - m_vDownPt = D3DXVECTOR3( 0, 0, 0 ); - m_vCurrentPt = D3DXVECTOR3( 0, 0, 0 ); + + m_vDownPt = XMFLOAT3( 0, 0, 0 ); + m_vCurrentPt = XMFLOAT3( 0, 0, 0 ); m_Offset.x = m_Offset.y = 0; RECT rc; @@ -23,66 +31,26 @@ CD3DArcBall::CD3DArcBall() } - - - //-------------------------------------------------------------------------------------- void CD3DArcBall::Reset() { - D3DXQuaternionIdentity( &m_qDown ); - D3DXQuaternionIdentity( &m_qNow ); - D3DXMatrixIdentity( &m_mRotation ); - D3DXMatrixIdentity( &m_mTranslation ); - D3DXMatrixIdentity( &m_mTranslationDelta ); - m_bDrag = FALSE; - m_fRadiusTranslation = 1.0f; - m_fRadius = 1.0f; -} - + XMVECTOR qid = XMQuaternionIdentity(); + XMStoreFloat4( &m_qDown, qid ); + XMStoreFloat4( &m_qNow, qid ); + XMMATRIX id = XMMatrixIdentity(); + XMStoreFloat4x4( &m_mRotation, id ); + XMStoreFloat4x4( &m_mTranslation, id ); + XMStoreFloat4x4( &m_mTranslationDelta, id ); - -//-------------------------------------------------------------------------------------- -D3DXVECTOR3 CD3DArcBall::ScreenToVector( float fScreenPtX, float fScreenPtY ) -{ - // Scale to screen - FLOAT x = -( fScreenPtX - m_Offset.x - m_nWidth / 2 ) / ( m_fRadius * m_nWidth / 2 ); - FLOAT y = ( fScreenPtY - m_Offset.y - m_nHeight / 2 ) / ( m_fRadius * m_nHeight / 2 ); - - FLOAT z = 0.0f; - FLOAT mag = x * x + y * y; - - if( mag > 1.0f ) - { - FLOAT scale = 1.0f / sqrtf( mag ); - x *= scale; - y *= scale; - } - else - z = sqrtf( 1.0f - mag ); - - // Return vector - return D3DXVECTOR3( x, y, z ); -} - - - - -//-------------------------------------------------------------------------------------- -D3DXQUATERNION CD3DArcBall::QuatFromBallPoints( const D3DXVECTOR3& vFrom, const D3DXVECTOR3& vTo ) -{ - D3DXVECTOR3 vPart; - float fDot = D3DXVec3Dot( &vFrom, &vTo ); - D3DXVec3Cross( &vPart, &vFrom, &vTo ); - - return D3DXQUATERNION( vPart.x, vPart.y, vPart.z, fDot ); + m_bDrag = false; + m_fRadiusTranslation = 1.0f; + m_fRadius = 1.0f; } - - //-------------------------------------------------------------------------------------- -void CD3DArcBall::OnBegin( int nX, int nY ) +void CD3DArcBall::OnBegin( _In_ int nX, _In_ int nY ) { // Only enter the drag state if the click falls // inside the click rectangle. @@ -93,24 +61,27 @@ void CD3DArcBall::OnBegin( int nX, int nY ) { m_bDrag = true; m_qDown = m_qNow; - m_vDownPt = ScreenToVector( ( float )nX, ( float )nY ); + XMVECTOR v = ScreenToVector( float(nX), float(nY) ); + XMStoreFloat3( &m_vDownPt, v ); } } - - //-------------------------------------------------------------------------------------- -void CD3DArcBall::OnMove( int nX, int nY ) +void CD3DArcBall::OnMove( _In_ int nX, _In_ int nY ) { if( m_bDrag ) { - m_vCurrentPt = ScreenToVector( ( float )nX, ( float )nY ); - m_qNow = m_qDown * QuatFromBallPoints( m_vDownPt, m_vCurrentPt ); - } -} + XMVECTOR curr = ScreenToVector( ( float )nX, ( float )nY ); + XMStoreFloat3( &m_vCurrentPt, curr ); + XMVECTOR down = XMLoadFloat3( &m_vDownPt ); + XMVECTOR qdown = XMLoadFloat4( &m_qDown ); + XMVECTOR result = XMQuaternionMultiply( qdown, QuatFromBallPoints( down, curr ) ); + XMStoreFloat4( &m_qNow, result ); + } +} //-------------------------------------------------------------------------------------- @@ -120,11 +91,8 @@ void CD3DArcBall::OnEnd() } - - -//-------------------------------------------------------------------------------------- -// Desc: //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CD3DArcBall::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // Current mouse position @@ -174,20 +142,25 @@ LRESULT CD3DArcBall::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM else if( ( MK_RBUTTON & wParam ) || ( MK_MBUTTON & wParam ) ) { // Normalize based on size of window and bounding sphere radius - FLOAT fDeltaX = ( m_ptLastMouse.x - iMouseX ) * m_fRadiusTranslation / m_nWidth; - FLOAT fDeltaY = ( m_ptLastMouse.y - iMouseY ) * m_fRadiusTranslation / m_nHeight; + float fDeltaX = ( m_ptLastMouse.x - iMouseX ) * m_fRadiusTranslation / m_nWidth; + float fDeltaY = ( m_ptLastMouse.y - iMouseY ) * m_fRadiusTranslation / m_nHeight; + XMMATRIX mTranslationDelta; + XMMATRIX mTranslation = XMLoadFloat4x4( &m_mTranslation ); if( wParam & MK_RBUTTON ) { - D3DXMatrixTranslation( &m_mTranslationDelta, -2 * fDeltaX, 2 * fDeltaY, 0.0f ); - D3DXMatrixMultiply( &m_mTranslation, &m_mTranslation, &m_mTranslationDelta ); + mTranslationDelta = XMMatrixTranslation( -2 * fDeltaX, 2 * fDeltaY, 0.0f ); + mTranslation = XMMatrixMultiply( mTranslation, mTranslationDelta ); } else // wParam & MK_MBUTTON { - D3DXMatrixTranslation( &m_mTranslationDelta, 0.0f, 0.0f, 5 * fDeltaY ); - D3DXMatrixMultiply( &m_mTranslation, &m_mTranslation, &m_mTranslationDelta ); + mTranslationDelta = XMMatrixTranslation( 0.0f, 0.0f, 5 * fDeltaY ); + mTranslation = XMMatrixMultiply( mTranslation, mTranslationDelta ); } + XMStoreFloat4x4( &m_mTranslationDelta, mTranslationDelta ); + XMStoreFloat4x4( &m_mTranslation, mTranslation ); + // Store mouse coordinate m_ptLastMouse.x = iMouseX; m_ptLastMouse.y = iMouseY; @@ -199,99 +172,92 @@ LRESULT CD3DArcBall::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } - +//====================================================================================== +// CBaseCamera +//====================================================================================== //-------------------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------------------- -CBaseCamera::CBaseCamera() +CBaseCamera::CBaseCamera() : + m_cKeysDown(0), + m_nCurrentButtonMask(0), + m_nMouseWheelDelta(0), + m_fFramesToSmoothMouseData(2.0f), + m_fCameraYawAngle(0.0f), + m_fCameraPitchAngle(0.0f), + m_fDragTimer(0.0f), + m_fTotalDragTimeToZero(0.25), + m_fRotationScaler(0.01f), + m_fMoveScaler(5.0f), + m_bMouseLButtonDown(false), + m_bMouseMButtonDown(false), + m_bMouseRButtonDown(false), + m_bMovementDrag(false), + m_bInvertPitch(false), + m_bEnablePositionMovement(true), + m_bEnableYAxisMovement(true), + m_bClipToBoundary(false), + m_bResetCursorAfterMove(false) { - m_cKeysDown = 0; ZeroMemory( m_aKeys, sizeof( BYTE ) * CAM_MAX_KEYS ); ZeroMemory( m_GamePad, sizeof( DXUT_GAMEPAD ) * DXUT_MAX_CONTROLLERS ); - // Set attributes for the view matrix - D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); - D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); - // Setup the view matrix - SetViewParams( &vEyePt, &vLookatPt ); + SetViewParams( g_XMZero, g_XMIdentityR2 ); // Setup the projection matrix - SetProjParams( D3DX_PI / 4, 1.0f, 1.0f, 1000.0f ); + SetProjParams( XM_PI / 4, 1.0f, 1.0f, 1000.0f ); GetCursorPos( &m_ptLastMousePosition ); - m_bMouseLButtonDown = false; - m_bMouseMButtonDown = false; - m_bMouseRButtonDown = false; - m_nCurrentButtonMask = 0; - m_nMouseWheelDelta = 0; - - m_fCameraYawAngle = 0.0f; - m_fCameraPitchAngle = 0.0f; - + SetRect( &m_rcDrag, LONG_MIN, LONG_MIN, LONG_MAX, LONG_MAX ); - m_vVelocity = D3DXVECTOR3( 0, 0, 0 ); - m_bMovementDrag = false; - m_vVelocityDrag = D3DXVECTOR3( 0, 0, 0 ); - m_fDragTimer = 0.0f; - m_fTotalDragTimeToZero = 0.25; - m_vRotVelocity = D3DXVECTOR2( 0, 0 ); - - m_fRotationScaler = 0.01f; - m_fMoveScaler = 5.0f; - - m_bInvertPitch = false; - m_bEnableYAxisMovement = true; - m_bEnablePositionMovement = true; + m_vVelocity = XMFLOAT3( 0, 0, 0 ); + m_vVelocityDrag = XMFLOAT3( 0, 0, 0 ); + m_vRotVelocity = XMFLOAT2( 0, 0 ); - m_vMouseDelta = D3DXVECTOR2( 0, 0 ); - m_fFramesToSmoothMouseData = 2.0f; + m_vMouseDelta = XMFLOAT2( 0, 0 ); - m_bClipToBoundary = false; - m_vMinBoundary = D3DXVECTOR3( -1, -1, -1 ); - m_vMaxBoundary = D3DXVECTOR3( 1, 1, 1 ); - - m_bResetCursorAfterMove = false; + m_vMinBoundary = XMFLOAT3( -1, -1, -1 ); + m_vMaxBoundary = XMFLOAT3( 1, 1, 1 ); } //-------------------------------------------------------------------------------------- // Client can call this to change the position and direction of camera //-------------------------------------------------------------------------------------- -VOID CBaseCamera::SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ) +_Use_decl_annotations_ +void CBaseCamera::SetViewParams( FXMVECTOR vEyePt, FXMVECTOR vLookatPt ) { - if( NULL == pvEyePt || NULL == pvLookatPt ) - return; + XMStoreFloat3( &m_vEye, vEyePt ); + XMStoreFloat3( &m_vDefaultEye, vEyePt ); - m_vDefaultEye = m_vEye = *pvEyePt; - m_vDefaultLookAt = m_vLookAt = *pvLookatPt; + XMStoreFloat3( &m_vLookAt, vLookatPt ); + XMStoreFloat3( &m_vDefaultLookAt , vLookatPt ); // Calc the view matrix - D3DXVECTOR3 vUp( 0,1,0 ); - D3DXMatrixLookAtLH( &m_mView, pvEyePt, pvLookatPt, &vUp ); + XMMATRIX mView = XMMatrixLookAtLH( vEyePt, vLookatPt, g_XMIdentityR1 ); + XMStoreFloat4x4( &m_mView, mView ); - D3DXMATRIX mInvView; - D3DXMatrixInverse( &mInvView, NULL, &m_mView ); + XMMATRIX mInvView = XMMatrixInverse( nullptr, mView ); // The axis basis vectors and camera position are stored inside the // position matrix in the 4 rows of the camera's world matrix. // To figure out the yaw/pitch of the camera, we just need the Z basis vector - D3DXVECTOR3* pZBasis = ( D3DXVECTOR3* )&mInvView._31; + XMFLOAT3 zBasis; + XMStoreFloat3( &zBasis, mInvView.r[2] ); - m_fCameraYawAngle = atan2f( pZBasis->x, pZBasis->z ); - float fLen = sqrtf( pZBasis->z * pZBasis->z + pZBasis->x * pZBasis->x ); - m_fCameraPitchAngle = -atan2f( pZBasis->y, fLen ); + m_fCameraYawAngle = atan2f( zBasis.x, zBasis.z ); + float fLen = sqrtf( zBasis.z * zBasis.z + zBasis.x * zBasis.x ); + m_fCameraPitchAngle = -atan2f( zBasis.y, fLen ); } - - //-------------------------------------------------------------------------------------- // Calculates the projection matrix based on input params //-------------------------------------------------------------------------------------- -VOID CBaseCamera::SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, - FLOAT fFarPlane ) +_Use_decl_annotations_ +void CBaseCamera::SetProjParams( float fFOV, float fAspect, float fNearPlane, float fFarPlane ) { // Set attributes for the projection matrix m_fFOV = fFOV; @@ -299,15 +265,15 @@ VOID CBaseCamera::SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, m_fNearPlane = fNearPlane; m_fFarPlane = fFarPlane; - D3DXMatrixPerspectiveFovLH( &m_mProj, fFOV, fAspect, fNearPlane, fFarPlane ); + XMMATRIX mProj = XMMatrixPerspectiveFovLH( fFOV, fAspect, fNearPlane, fFarPlane ); + XMStoreFloat4x4( &m_mProj, mProj ); } - - //-------------------------------------------------------------------------------------- // Call this from your message proc so this class can handle window messages //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CBaseCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { UNREFERENCED_PARAMETER( hWnd ); @@ -323,6 +289,7 @@ LRESULT CBaseCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM D3DUtil_CameraKeys mappedKey = MapKey( ( UINT )wParam ); if( mappedKey != CAM_UNKNOWN ) { + _Analysis_assume_( mappedKey < CAM_MAX_KEYS ); if( FALSE == IsKeyDown( m_aKeys[mappedKey] ) ) { m_aKeys[ mappedKey ] = KEY_WAS_DOWN_MASK | KEY_IS_DOWN_MASK; @@ -436,13 +403,14 @@ LRESULT CBaseCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM return FALSE; } + //-------------------------------------------------------------------------------------- // Figure out the velocity based on keyboard input & drag if any //-------------------------------------------------------------------------------------- -void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput, - bool bResetCursorAfterMove ) +_Use_decl_annotations_ +void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput ) { - m_vKeyboardDirection = D3DXVECTOR3( 0, 0, 0 ); + m_vKeyboardDirection = XMFLOAT3( 0, 0, 0 ); if( bGetKeyboardInput ) { // Update acceleration vector based on keyboard state @@ -470,8 +438,8 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG if( bGetGamepadInput ) { - m_vGamePadLeftThumb = D3DXVECTOR3( 0, 0, 0 ); - m_vGamePadRightThumb = D3DXVECTOR3( 0, 0, 0 ); + m_vGamePadLeftThumb = XMFLOAT3( 0, 0, 0 ); + m_vGamePadRightThumb = XMFLOAT3( 0, 0, 0 ); // Get controller state for( DWORD iUserIndex = 0; iUserIndex < DXUT_MAX_CONTROLLERS; iUserIndex++ ) @@ -480,7 +448,7 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG // Mark time if the controller is in a non-zero state if( m_GamePad[iUserIndex].wButtons || - m_GamePad[iUserIndex].sThumbLX || m_GamePad[iUserIndex].sThumbLX || + m_GamePad[iUserIndex].sThumbLX || m_GamePad[iUserIndex].sThumbLY || m_GamePad[iUserIndex].sThumbRX || m_GamePad[iUserIndex].sThumbRY || m_GamePad[iUserIndex].bLeftTrigger || m_GamePad[iUserIndex].bRightTrigger ) { @@ -520,13 +488,12 @@ void CBaseCamera::GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bG //-------------------------------------------------------------------------------------- void CBaseCamera::UpdateMouseDelta() { - POINT ptCurMouseDelta; - POINT ptCurMousePos; - // Get current position of mouse + POINT ptCurMousePos; GetCursorPos( &ptCurMousePos ); // Calc how far it's moved since last frame + POINT ptCurMouseDelta; ptCurMouseDelta.x = ptCurMousePos.x - m_ptLastMousePosition.x; ptCurMouseDelta.y = ptCurMousePos.y - m_ptLastMousePosition.y; @@ -559,26 +526,30 @@ void CBaseCamera::UpdateMouseDelta() m_vMouseDelta.x = m_vMouseDelta.x * fPercentOfOld + ptCurMouseDelta.x * fPercentOfNew; m_vMouseDelta.y = m_vMouseDelta.y * fPercentOfOld + ptCurMouseDelta.y * fPercentOfNew; - m_vRotVelocity = m_vMouseDelta * m_fRotationScaler; + m_vRotVelocity.x = m_vMouseDelta.x * m_fRotationScaler; + m_vRotVelocity.y = m_vMouseDelta.y * m_fRotationScaler; } - - //-------------------------------------------------------------------------------------- // Figure out the velocity based on keyboard input & drag if any //-------------------------------------------------------------------------------------- -void CBaseCamera::UpdateVelocity( float fElapsedTime ) +void CBaseCamera::UpdateVelocity( _In_ float fElapsedTime ) { - D3DXMATRIX mRotDelta; - D3DXVECTOR2 vGamePadRightThumb = D3DXVECTOR2( m_vGamePadRightThumb.x, -m_vGamePadRightThumb.z ); - m_vRotVelocity = m_vMouseDelta * m_fRotationScaler + vGamePadRightThumb * 0.02f; + XMVECTOR vGamePadRightThumb = XMVectorSet( m_vGamePadRightThumb.x, -m_vGamePadRightThumb.z, 0, 0 ); + + XMVECTOR vMouseDelta = XMLoadFloat2( &m_vMouseDelta ); + XMVECTOR vRotVelocity = vMouseDelta * m_fRotationScaler + vGamePadRightThumb * 0.02f; - D3DXVECTOR3 vAccel = m_vKeyboardDirection + m_vGamePadLeftThumb; + XMStoreFloat2( &m_vRotVelocity, vRotVelocity ); + + XMVECTOR vKeyboardDirection = XMLoadFloat3( &m_vKeyboardDirection ); + XMVECTOR vGamePadLeftThumb = XMLoadFloat3( &m_vGamePadLeftThumb ); + XMVECTOR vAccel = vKeyboardDirection + vGamePadLeftThumb; // Normalize vector so if moving 2 dirs (left & forward), // the camera doesn't move faster than if moving in 1 dir - D3DXVec3Normalize( &vAccel, &vAccel ); + vAccel = XMVector3Normalize( vAccel ); // Scale the acceleration vector vAccel *= m_fMoveScaler; @@ -586,15 +557,17 @@ void CBaseCamera::UpdateVelocity( float fElapsedTime ) if( m_bMovementDrag ) { // Is there any acceleration this frame? - if( D3DXVec3LengthSq( &vAccel ) > 0 ) + if( XMVectorGetX( XMVector3LengthSq( vAccel ) ) > 0 ) { - // If so, then this means the user has pressed a movement key\ + // If so, then this means the user has pressed a movement key // so change the velocity immediately to acceleration // upon keyboard input. This isn't normal physics // but it will give a quick response to keyboard input - m_vVelocity = vAccel; + XMStoreFloat3( &m_vVelocity, vAccel ); + m_fDragTimer = m_fTotalDragTimeToZero; - m_vVelocityDrag = vAccel / m_fDragTimer; + + XMStoreFloat3( &m_vVelocityDrag, vAccel / m_fDragTimer ); } else { @@ -602,48 +575,34 @@ void CBaseCamera::UpdateVelocity( float fElapsedTime ) if( m_fDragTimer > 0 ) { // Drag until timer is <= 0 - m_vVelocity -= m_vVelocityDrag * fElapsedTime; + XMVECTOR vVelocity = XMLoadFloat3( &m_vVelocity ); + XMVECTOR vVelocityDrag = XMLoadFloat3( &m_vVelocityDrag ); + + vVelocity -= vVelocityDrag * fElapsedTime; + + XMStoreFloat3( &m_vVelocity, vVelocity ); + m_fDragTimer -= fElapsedTime; } else { // Zero velocity - m_vVelocity = D3DXVECTOR3( 0, 0, 0 ); + m_vVelocity = XMFLOAT3( 0, 0, 0 ); } } } else { // No drag, so immediately change the velocity - m_vVelocity = vAccel; + XMStoreFloat3( &m_vVelocity, vAccel ); } } - - -//-------------------------------------------------------------------------------------- -// Clamps pV to lie inside m_vMinBoundary & m_vMaxBoundary -//-------------------------------------------------------------------------------------- -void CBaseCamera::ConstrainToBoundary( D3DXVECTOR3* pV ) -{ - // Constrain vector to a bounding box - pV->x = __max( pV->x, m_vMinBoundary.x ); - pV->y = __max( pV->y, m_vMinBoundary.y ); - pV->z = __max( pV->z, m_vMinBoundary.z ); - - pV->x = __min( pV->x, m_vMaxBoundary.x ); - pV->y = __min( pV->y, m_vMaxBoundary.y ); - pV->z = __min( pV->z, m_vMaxBoundary.z ); -} - - - - //-------------------------------------------------------------------------------------- // Maps a windows virtual key to an enum //-------------------------------------------------------------------------------------- -D3DUtil_CameraKeys CBaseCamera::MapKey( UINT nKey ) +D3DUtil_CameraKeys CBaseCamera::MapKey( _In_ UINT nKey ) { // This could be upgraded to a method that's user-definable but for // simplicity, we'll use a hardcoded mapping. @@ -698,46 +657,49 @@ D3DUtil_CameraKeys CBaseCamera::MapKey( UINT nKey ) } - - //-------------------------------------------------------------------------------------- // Reset the camera's position back to the default //-------------------------------------------------------------------------------------- -VOID CBaseCamera::Reset() +void CBaseCamera::Reset() { - SetViewParams( &m_vDefaultEye, &m_vDefaultLookAt ); -} + XMVECTOR vDefaultEye = XMLoadFloat3( &m_vDefaultEye ); + XMVECTOR vDefaultLookAt = XMLoadFloat3( &m_vDefaultLookAt ); + SetViewParams( vDefaultEye, vDefaultLookAt ); +} +//====================================================================================== +// CFirstPersonCamera +//====================================================================================== -//-------------------------------------------------------------------------------------- -// Constructor -//-------------------------------------------------------------------------------------- -CFirstPersonCamera::CFirstPersonCamera() : m_nActiveButtonMask( 0x07 ) +CFirstPersonCamera::CFirstPersonCamera() : + m_nActiveButtonMask( 0x07 ), + m_bRotateWithoutButtonDown(false) { - m_bRotateWithoutButtonDown = false; } - - //-------------------------------------------------------------------------------------- // Update the view matrix based on user input & elapsed time //-------------------------------------------------------------------------------------- -VOID CFirstPersonCamera::FrameMove( FLOAT fElapsedTime ) +void CFirstPersonCamera::FrameMove( _In_ float fElapsedTime ) { - if( DXUTGetGlobalTimer()->IsStopped() ) { - if (DXUTGetFPS() == 0.0f) fElapsedTime = 0; - else fElapsedTime = 1.0f / DXUTGetFPS(); + if( DXUTGetGlobalTimer()->IsStopped() ) + { + if (DXUTGetFPS() == 0.0f) + fElapsedTime = 0; + else + fElapsedTime = 1.0f / DXUTGetFPS(); } if( IsKeyDown( m_aKeys[CAM_RESET] ) ) + { Reset(); + } // Get keyboard/mouse/gamepad input - GetInput( m_bEnablePositionMovement, ( m_nActiveButtonMask & m_nCurrentButtonMask ) || m_bRotateWithoutButtonDown, - true, m_bResetCursorAfterMove ); + GetInput( m_bEnablePositionMovement, ( m_nActiveButtonMask & m_nCurrentButtonMask ) || m_bRotateWithoutButtonDown, true ); //// Get the mouse movement (if any) if the mouse button are down //if( (m_nActiveButtonMask & m_nCurrentButtonMask) || m_bRotateWithoutButtonDown ) @@ -747,13 +709,14 @@ VOID CFirstPersonCamera::FrameMove( FLOAT fElapsedTime ) UpdateVelocity( fElapsedTime ); // Simple euler method to calculate position delta - D3DXVECTOR3 vPosDelta = m_vVelocity * fElapsedTime; + XMVECTOR vVelocity = XMLoadFloat3( &m_vVelocity ); + XMVECTOR vPosDelta = vVelocity * fElapsedTime; // If rotating the camera - if( ( m_nActiveButtonMask & m_nCurrentButtonMask ) || - m_bRotateWithoutButtonDown || - m_vGamePadRightThumb.x != 0 || - m_vGamePadRightThumb.z != 0 ) + if( ( m_nActiveButtonMask & m_nCurrentButtonMask ) + || m_bRotateWithoutButtonDown + || m_vGamePadRightThumb.x != 0 + || m_vGamePadRightThumb.z != 0 ) { // Update the pitch & yaw angle based on mouse movement float fYawDelta = m_vRotVelocity.x; @@ -767,49 +730,50 @@ VOID CFirstPersonCamera::FrameMove( FLOAT fElapsedTime ) m_fCameraYawAngle += fYawDelta; // Limit pitch to straight up or straight down - m_fCameraPitchAngle = __max( -D3DX_PI / 2.0f, m_fCameraPitchAngle ); - m_fCameraPitchAngle = __min( +D3DX_PI / 2.0f, m_fCameraPitchAngle ); + m_fCameraPitchAngle = std::max( -XM_PI / 2.0f, m_fCameraPitchAngle ); + m_fCameraPitchAngle = std::min( +XM_PI / 2.0f, m_fCameraPitchAngle ); } // Make a rotation matrix based on the camera's yaw & pitch - D3DXMATRIX mCameraRot; - D3DXMatrixRotationYawPitchRoll( &mCameraRot, m_fCameraYawAngle, m_fCameraPitchAngle, 0 ); + XMMATRIX mCameraRot = XMMatrixRotationRollPitchYaw( m_fCameraPitchAngle, m_fCameraYawAngle, 0 ); // Transform vectors based on camera's rotation matrix - D3DXVECTOR3 vWorldUp, vWorldAhead; - D3DXVECTOR3 vLocalUp = D3DXVECTOR3( 0, 1, 0 ); - D3DXVECTOR3 vLocalAhead = D3DXVECTOR3( 0, 0, 1 ); - D3DXVec3TransformCoord( &vWorldUp, &vLocalUp, &mCameraRot ); - D3DXVec3TransformCoord( &vWorldAhead, &vLocalAhead, &mCameraRot ); + XMVECTOR vWorldUp = XMVector3TransformCoord( g_XMIdentityR1, mCameraRot ); + XMVECTOR vWorldAhead = XMVector3TransformCoord( g_XMIdentityR2, mCameraRot ); // Transform the position delta by the camera's rotation - D3DXVECTOR3 vPosDeltaWorld; if( !m_bEnableYAxisMovement ) { // If restricting Y movement, do not include pitch // when transforming position delta vector. - D3DXMatrixRotationYawPitchRoll( &mCameraRot, m_fCameraYawAngle, 0.0f, 0.0f ); + mCameraRot = XMMatrixRotationRollPitchYaw( 0.0f, m_fCameraYawAngle, 0.0f ); } - D3DXVec3TransformCoord( &vPosDeltaWorld, &vPosDelta, &mCameraRot ); + XMVECTOR vPosDeltaWorld = XMVector3TransformCoord( vPosDelta, mCameraRot ); // Move the eye position - m_vEye += vPosDeltaWorld; + XMVECTOR vEye = XMLoadFloat3( &m_vEye ); + vEye += vPosDeltaWorld; if( m_bClipToBoundary ) - ConstrainToBoundary( &m_vEye ); + vEye = ConstrainToBoundary( vEye ); + XMStoreFloat3( &m_vEye, vEye ); - // Update the lookAt position based on the eye position - m_vLookAt = m_vEye + vWorldAhead; + // Update the lookAt position based on the eye position + XMVECTOR vLookAt = vEye + vWorldAhead; + XMStoreFloat3( &m_vLookAt, vLookAt ); // Update the view matrix - D3DXMatrixLookAtLH( &m_mView, &m_vEye, &m_vLookAt, &vWorldUp ); + XMMATRIX mView = XMMatrixLookAtLH( vEye, vLookAt, vWorldUp ); + XMStoreFloat4x4( &m_mView, mView ); - D3DXMatrixInverse( &m_mCameraWorld, NULL, &m_mView ); + XMMATRIX mCameraWorld = XMMatrixInverse( nullptr, mView ); + XMStoreFloat4x4( &m_mCameraWorld, mCameraWorld ); } //-------------------------------------------------------------------------------------- // Enable or disable each of the mouse buttons for rotation drag. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CFirstPersonCamera::SetRotateButtons( bool bLeft, bool bMiddle, bool bRight, bool bRotateWithoutButtonDown ) { m_nActiveButtonMask = ( bLeft ? MOUSE_LEFT_BUTTON : 0 ) | @@ -819,49 +783,48 @@ void CFirstPersonCamera::SetRotateButtons( bool bLeft, bool bMiddle, bool bRight } -//-------------------------------------------------------------------------------------- -// Constructor -//-------------------------------------------------------------------------------------- -CModelViewerCamera::CModelViewerCamera() -{ - D3DXMatrixIdentity( &m_mWorld ); - D3DXMatrixIdentity( &m_mModelRot ); - D3DXMatrixIdentity( &m_mModelLastRot ); - D3DXMatrixIdentity( &m_mCameraRotLast ); - m_vModelCenter = D3DXVECTOR3( 0, 0, 0 ); - m_fRadius = 5.0f; - m_fDefaultRadius = 5.0f; - m_fMinRadius = 1.0f; - m_fMaxRadius = FLT_MAX; - m_bLimitPitch = false; - m_bEnablePositionMovement = false; - m_bAttachCameraToModel = false; - m_nRotateModelButtonMask = MOUSE_LEFT_BUTTON; - m_nZoomButtonMask = MOUSE_WHEEL; - m_nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON; - m_bDragSinceLastUpdate = true; -} +//====================================================================================== +// CModelViewerCamera +//====================================================================================== +CModelViewerCamera::CModelViewerCamera() : + m_nRotateModelButtonMask(MOUSE_LEFT_BUTTON), + m_nZoomButtonMask(MOUSE_WHEEL), + m_nRotateCameraButtonMask(MOUSE_RIGHT_BUTTON), + m_bAttachCameraToModel(false), + m_bLimitPitch(false), + m_bDragSinceLastUpdate(true), + m_fRadius(5.0f), + m_fDefaultRadius(5.0f), + m_fMinRadius(1.0f), + m_fMaxRadius(FLT_MAX) +{ + XMMATRIX id = XMMatrixIdentity(); + XMStoreFloat4x4( &m_mWorld, id ); + XMStoreFloat4x4( &m_mModelRot, id ); + XMStoreFloat4x4( &m_mModelLastRot, id ); + XMStoreFloat4x4( &m_mCameraRotLast, id ); + m_vModelCenter = XMFLOAT3( 0, 0, 0 ); + + m_bEnablePositionMovement = false; +} //-------------------------------------------------------------------------------------- // Update the view matrix & the model's world matrix based // on user input & elapsed time //-------------------------------------------------------------------------------------- -VOID CModelViewerCamera::FrameMove( FLOAT fElapsedTime ) +void CModelViewerCamera::FrameMove( _In_ float fElapsedTime ) { if( IsKeyDown( m_aKeys[CAM_RESET] ) ) Reset(); - if (0 == m_cKeysDown) - { - // Simulate motion for the video - m_WorldArcBall.OnBegin(0, 0); - m_WorldArcBall.OnMove(1, 1); - m_WorldArcBall.OnEnd(); - } + // If no dragged has happend since last time FrameMove is called, + // and no camera key is held down, then no need to handle again. + if( !m_bDragSinceLastUpdate && 0 == m_cKeysDown ) + return; m_bDragSinceLastUpdate = false; @@ -870,100 +833,101 @@ VOID CModelViewerCamera::FrameMove( FLOAT fElapsedTime ) //if( m_nCurrentButtonMask != 0 ) // UpdateMouseDelta( fElapsedTime ); - GetInput( m_bEnablePositionMovement, m_nCurrentButtonMask != 0, true, false ); + GetInput( m_bEnablePositionMovement, m_nCurrentButtonMask != 0, true ); // Get amount of velocity based on the keyboard input and drag (if any) UpdateVelocity( fElapsedTime ); // Simple euler method to calculate position delta - D3DXVECTOR3 vPosDelta = m_vVelocity * fElapsedTime; + XMVECTOR vPosDelta = XMLoadFloat3( &m_vVelocity ) * fElapsedTime; // Change the radius from the camera to the model based on wheel scrolling if( m_nMouseWheelDelta && m_nZoomButtonMask == MOUSE_WHEEL ) m_fRadius -= m_nMouseWheelDelta * m_fRadius * 0.1f / 120.0f; - m_fRadius = __min( m_fMaxRadius, m_fRadius ); - m_fRadius = __max( m_fMinRadius, m_fRadius ); + m_fRadius = std::min( m_fMaxRadius, m_fRadius ); + m_fRadius = std::max( m_fMinRadius, m_fRadius ); m_nMouseWheelDelta = 0; // Get the inverse of the arcball's rotation matrix - D3DXMATRIX mCameraRot; - D3DXMatrixInverse( &mCameraRot, NULL, m_ViewArcBall.GetRotationMatrix() ); + XMMATRIX mCameraRot = XMMatrixInverse( nullptr, m_ViewArcBall.GetRotationMatrix() ); // Transform vectors based on camera's rotation matrix - D3DXVECTOR3 vWorldUp, vWorldAhead; - D3DXVECTOR3 vLocalUp = D3DXVECTOR3( 0, 1, 0 ); - D3DXVECTOR3 vLocalAhead = D3DXVECTOR3( 0, 0, 1 ); - D3DXVec3TransformCoord( &vWorldUp, &vLocalUp, &mCameraRot ); - D3DXVec3TransformCoord( &vWorldAhead, &vLocalAhead, &mCameraRot ); + XMVECTOR vWorldUp = XMVector3TransformCoord( g_XMIdentityR1, mCameraRot ); + XMVECTOR vWorldAhead = XMVector3TransformCoord( g_XMIdentityR2, mCameraRot ); // Transform the position delta by the camera's rotation - D3DXVECTOR3 vPosDeltaWorld; - D3DXVec3TransformCoord( &vPosDeltaWorld, &vPosDelta, &mCameraRot ); + XMVECTOR vPosDeltaWorld = XMVector3TransformCoord( vPosDelta, mCameraRot ); // Move the lookAt position - m_vLookAt += vPosDeltaWorld; + XMVECTOR vLookAt = XMLoadFloat3( &m_vLookAt ); + vLookAt += vPosDeltaWorld; if( m_bClipToBoundary ) - ConstrainToBoundary( &m_vLookAt ); + vLookAt = ConstrainToBoundary( vLookAt ); + XMStoreFloat3( &m_vLookAt, vLookAt ); // Update the eye point based on a radius away from the lookAt position - m_vEye = m_vLookAt - vWorldAhead * m_fRadius; + XMVECTOR vEye = vLookAt - vWorldAhead * m_fRadius; + XMStoreFloat3( &m_vEye, vEye ); // Update the view matrix - D3DXMatrixLookAtLH( &m_mView, &m_vEye, &m_vLookAt, &vWorldUp ); + XMMATRIX mView = XMMatrixLookAtLH( vEye, vLookAt, vWorldUp ); + XMStoreFloat4x4( &m_mView, mView ); - D3DXMATRIX mInvView; - D3DXMatrixInverse( &mInvView, NULL, &m_mView ); - mInvView._41 = mInvView._42 = mInvView._43 = 0; + XMMATRIX mInvView = XMMatrixInverse( nullptr, mView ); + mInvView.r[3] = XMVectorSelect( mInvView.r[3], g_XMZero, g_XMSelect1110 ); - D3DXMATRIX mModelLastRotInv; - D3DXMatrixInverse( &mModelLastRotInv, NULL, &m_mModelLastRot ); + XMMATRIX mModelLastRot = XMLoadFloat4x4( &m_mModelLastRot ); + XMMATRIX mModelLastRotInv = XMMatrixInverse( nullptr, mModelLastRot ); // Accumulate the delta of the arcball's rotation in view space. // Note that per-frame delta rotations could be problematic over long periods of time. - D3DXMATRIX mModelRot; - mModelRot = *m_WorldArcBall.GetRotationMatrix(); - m_mModelRot *= m_mView * mModelLastRotInv * mModelRot * mInvView; + XMMATRIX mModelRot0 = m_WorldArcBall.GetRotationMatrix(); + XMMATRIX mModelRot = XMLoadFloat4x4( &m_mModelRot ); + mModelRot *= mView * mModelLastRotInv * mModelRot0 * mInvView; if( m_ViewArcBall.IsBeingDragged() && m_bAttachCameraToModel && !IsKeyDown( m_aKeys[CAM_CONTROLDOWN] ) ) { // Attach camera to model by inverse of the model rotation - D3DXMATRIX mCameraLastRotInv; - D3DXMatrixInverse( &mCameraLastRotInv, NULL, &m_mCameraRotLast ); - D3DXMATRIX mCameraRotDelta = mCameraLastRotInv * mCameraRot; // local to world matrix - m_mModelRot *= mCameraRotDelta; + XMMATRIX mCameraRotLast = XMLoadFloat4x4( &m_mCameraRotLast ); + XMMATRIX mCameraLastRotInv = XMMatrixInverse( nullptr, mCameraRotLast ); + XMMATRIX mCameraRotDelta = mCameraLastRotInv * mCameraRot; // local to world matrix + mModelRot *= mCameraRotDelta; } - m_mCameraRotLast = mCameraRot; - m_mModelLastRot = mModelRot; + XMStoreFloat4x4( &m_mModelLastRot, mModelRot0 ); + XMStoreFloat4x4( &m_mCameraRotLast, mCameraRot ); // Since we're accumulating delta rotations, we need to orthonormalize // the matrix to prevent eventual matrix skew - D3DXVECTOR3* pXBasis = ( D3DXVECTOR3* )&m_mModelRot._11; - D3DXVECTOR3* pYBasis = ( D3DXVECTOR3* )&m_mModelRot._21; - D3DXVECTOR3* pZBasis = ( D3DXVECTOR3* )&m_mModelRot._31; - D3DXVec3Normalize( pXBasis, pXBasis ); - D3DXVec3Cross( pYBasis, pZBasis, pXBasis ); - D3DXVec3Normalize( pYBasis, pYBasis ); - D3DXVec3Cross( pZBasis, pXBasis, pYBasis ); + XMVECTOR xBasis = XMVector3Normalize( mModelRot.r[0] ); + XMVECTOR yBasis = XMVector3Cross( mModelRot.r[2], xBasis ); + yBasis = XMVector3Normalize( yBasis ); + XMVECTOR zBasis = XMVector3Cross( xBasis, yBasis ); + + mModelRot.r[0] = XMVectorSelect( mModelRot.r[0], xBasis, g_XMSelect1110 ); + mModelRot.r[1] = XMVectorSelect( mModelRot.r[1], yBasis, g_XMSelect1110 ); + mModelRot.r[2] = XMVectorSelect( mModelRot.r[2], zBasis, g_XMSelect1110 ); // Translate the rotation matrix to the same position as the lookAt position - m_mModelRot._41 = m_vLookAt.x; - m_mModelRot._42 = m_vLookAt.y; - m_mModelRot._43 = m_vLookAt.z; + mModelRot.r[3] = XMVectorSelect( mModelRot.r[3], vLookAt, g_XMSelect1110 ); + + XMStoreFloat4x4( &m_mModelRot, mModelRot ); // Translate world matrix so its at the center of the model - D3DXMATRIX mTrans; - D3DXMatrixTranslation( &mTrans, -m_vModelCenter.x, -m_vModelCenter.y, -m_vModelCenter.z ); - m_mWorld = mTrans * m_mModelRot; + XMMATRIX mTrans = XMMatrixTranslation( -m_vModelCenter.x, -m_vModelCenter.y, -m_vModelCenter.z ); + XMMATRIX mWorld = mTrans * mModelRot; + XMStoreFloat4x4( &m_mWorld, mWorld ); } -void CModelViewerCamera::SetDragRect( RECT& rc ) +//-------------------------------------------------------------------------------------- +void CModelViewerCamera::SetDragRect( _In_ const RECT& rc ) { CBaseCamera::SetDragRect( rc ); m_WorldArcBall.SetOffset( rc.left, rc.top ); m_ViewArcBall.SetOffset( rc.left, rc.top ); + SetWindow( rc.right - rc.left, rc.bottom - rc.top ); } @@ -971,14 +935,15 @@ void CModelViewerCamera::SetDragRect( RECT& rc ) //-------------------------------------------------------------------------------------- // Reset the camera's position back to the default //-------------------------------------------------------------------------------------- -VOID CModelViewerCamera::Reset() +void CModelViewerCamera::Reset() { CBaseCamera::Reset(); - D3DXMatrixIdentity( &m_mWorld ); - D3DXMatrixIdentity( &m_mModelRot ); - D3DXMatrixIdentity( &m_mModelLastRot ); - D3DXMatrixIdentity( &m_mCameraRotLast ); + XMMATRIX id = XMMatrixIdentity(); + XMStoreFloat4x4( &m_mWorld, id ); + XMStoreFloat4x4( &m_mModelRot, id ); + XMStoreFloat4x4( &m_mModelLastRot, id ); + XMStoreFloat4x4( &m_mCameraRotLast, id ); m_fRadius = m_fDefaultRadius; m_WorldArcBall.Reset(); @@ -989,32 +954,30 @@ VOID CModelViewerCamera::Reset() //-------------------------------------------------------------------------------------- // Override for setting the view parameters //-------------------------------------------------------------------------------------- -void CModelViewerCamera::SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ) +_Use_decl_annotations_ +void CModelViewerCamera::SetViewParams( FXMVECTOR vEyePt, FXMVECTOR vLookatPt ) { - CBaseCamera::SetViewParams( pvEyePt, pvLookatPt ); + CBaseCamera::SetViewParams( vEyePt, vLookatPt ); // Propogate changes to the member arcball - D3DXQUATERNION quat; - D3DXMATRIXA16 mRotation; - D3DXVECTOR3 vUp( 0,1,0 ); - D3DXMatrixLookAtLH( &mRotation, pvEyePt, pvLookatPt, &vUp ); - D3DXQuaternionRotationMatrix( &quat, &mRotation ); + XMMATRIX mRotation = XMMatrixLookAtLH( vEyePt, vLookatPt, g_XMIdentityR1 ); + XMVECTOR quat = XMQuaternionRotationMatrix( mRotation ); m_ViewArcBall.SetQuatNow( quat ); // Set the radius according to the distance - D3DXVECTOR3 vEyeToPoint; - D3DXVec3Subtract( &vEyeToPoint, pvLookatPt, pvEyePt ); - SetRadius( D3DXVec3Length( &vEyeToPoint ) ); + XMVECTOR vEyeToPoint = XMVectorSubtract( vLookatPt, vEyePt ); + float len = XMVectorGetX( XMVector3Length( vEyeToPoint ) ); + SetRadius( len ); // View information changed. FrameMove should be called. m_bDragSinceLastUpdate = true; } - //-------------------------------------------------------------------------------------- // Call this from your message proc so this class can handle window messages //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CModelViewerCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { CBaseCamera::HandleMessages( hWnd, uMsg, wParam, lParam ); @@ -1099,152 +1062,32 @@ LRESULT CModelViewerCamera::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, } +//====================================================================================== +// CDXUTDirectionWidget +//====================================================================================== -//-------------------------------------------------------------------------------------- -// D3D9 -IDirect3DDevice9* CDXUTDirectionWidget::s_pd3d9Device = NULL; -ID3DXEffect* CDXUTDirectionWidget::s_pD3D9Effect = NULL; -ID3DXMesh* CDXUTDirectionWidget::s_pD3D9Mesh = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hRenderWith1LightNoTexture = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hMaterialDiffuseColor = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hLightDir = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hWorldViewProjection = NULL; -D3DXHANDLE CDXUTDirectionWidget::s_hWorld = NULL; - - -//-------------------------------------------------------------------------------------- -CDXUTDirectionWidget::CDXUTDirectionWidget() +CDXUTDirectionWidget::CDXUTDirectionWidget() : + m_fRadius(1.0f), + m_nRotateMask(MOUSE_RIGHT_BUTTON) { - m_fRadius = 1.0f; - m_vDefaultDir = D3DXVECTOR3( 0, 1, 0 ); + m_vDefaultDir = XMFLOAT3( 0, 1, 0 ); m_vCurrentDir = m_vDefaultDir; - m_nRotateMask = MOUSE_RIGHT_BUTTON; - - D3DXMatrixIdentity( &m_mView ); - D3DXMatrixIdentity( &m_mRot ); - D3DXMatrixIdentity( &m_mRotSnapshot ); -} + XMMATRIX id = XMMatrixIdentity(); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::StaticOnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ) -{ - HRESULT hr; - - s_pd3d9Device = pd3dDevice; - - const char* g_strBuffer = - "float4 g_MaterialDiffuseColor; // Material's diffuse color\r\n" - "float3 g_LightDir; // Light's direction in world space\r\n" - "float4x4 g_mWorld; // World matrix for object\r\n" - "float4x4 g_mWorldViewProjection; // World * View * Projection matrix\r\n" - "\r\n" - "struct VS_OUTPUT\r\n" - "{\r\n" - " float4 Position : POSITION; // vertex position\r\n" - " float4 Diffuse : COLOR0; // vertex diffuse color\r\n" - "};\r\n" - "\r\n" - "VS_OUTPUT RenderWith1LightNoTextureVS( float4 vPos : POSITION,\r\n" - " float3 vNormal : NORMAL )\r\n" - "{\r\n" - " VS_OUTPUT Output;\r\n" - "\r\n" - " // Transform the position from object space to homogeneous projection space\r\n" - " Output.Position = mul(vPos, g_mWorldViewProjection);\r\n" - "\r\n" - " // Transform the normal from object space to world space\r\n" - " float3 vNormalWorldSpace;\r\n" - " vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space)\r\n" - "\r\n" - " // Compute simple directional lighting equation\r\n" - " Output.Diffuse.rgb = g_MaterialDiffuseColor * max(0,dot(vNormalWorldSpace, g_LightDir));\r\n" - " Output.Diffuse.a = 1.0f;\r\n" - "\r\n" - " return Output;\r\n" - "}\r\n" - "\r\n" - "float4 RenderWith1LightNoTexturePS( float4 Diffuse : COLOR0 ) : COLOR0\r\n" - "{\r\n" - " return Diffuse;\r\n" - "}\r\n" - "\r\n" - "technique RenderWith1LightNoTexture\r\n" - "{\r\n" - " pass P0\r\n" - " {\r\n" - " VertexShader = compile vs_2_0 RenderWith1LightNoTextureVS();\r\n" - " PixelShader = compile ps_2_0 RenderWith1LightNoTexturePS();\r\n" - " }\r\n" - "}\r\n" - ""; - - UINT dwBufferSize = ( UINT )strlen( g_strBuffer ) + 1; - - DWORD Flags = D3DXFX_NOT_CLONEABLE; -#ifdef D3DXFX_LARGEADDRESS_HANDLE - Flags |= D3DXFX_LARGEADDRESSAWARE; -#endif - - V_RETURN( D3DXCreateEffect( s_pd3d9Device, g_strBuffer, dwBufferSize, NULL, NULL, Flags, - NULL, &s_pD3D9Effect, NULL ) ); - - // Save technique handles for use when rendering - s_hRenderWith1LightNoTexture = s_pD3D9Effect->GetTechniqueByName( "RenderWith1LightNoTexture" ); - s_hMaterialDiffuseColor = s_pD3D9Effect->GetParameterByName( NULL, "g_MaterialDiffuseColor" ); - s_hLightDir = s_pD3D9Effect->GetParameterByName( NULL, "g_LightDir" ); - s_hWorld = s_pD3D9Effect->GetParameterByName( NULL, "g_mWorld" ); - s_hWorldViewProjection = s_pD3D9Effect->GetParameterByName( NULL, "g_mWorldViewProjection" ); - - // Load the mesh with D3DX and get back a ID3DXMesh*. For this - // sample we'll ignore the X file's embedded materials since we know - // exactly the model we're loading. See the mesh samples such as - // "OptimizedMesh" for a more generic mesh loading example. - V_RETURN( DXUTCreateArrowMeshFromInternalArray( s_pd3d9Device, &s_pD3D9Mesh ) ); - - // Optimize the mesh for this graphics card's vertex cache - // so when rendering the mesh's triangle list the vertices will - // cache hit more often so it won't have to re-execute the vertex shader - // on those vertices so it will improve perf. - DWORD* rgdwAdjacency = new DWORD[s_pD3D9Mesh->GetNumFaces() * 3]; - if( rgdwAdjacency == NULL ) - return E_OUTOFMEMORY; - V( s_pD3D9Mesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) ); - V( s_pD3D9Mesh->OptimizeInplace( D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL ) ); - delete []rgdwAdjacency; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::OnD3D9ResetDevice( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ) -{ - m_ArcBall.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDirectionWidget::StaticOnD3D9LostDevice() -{ - if( s_pD3D9Effect ) - s_pD3D9Effect->OnLostDevice(); -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDirectionWidget::StaticOnD3D9DestroyDevice() -{ - SAFE_RELEASE( s_pD3D9Effect ); - SAFE_RELEASE( s_pD3D9Mesh ); + XMStoreFloat4x4( &m_mView, id ); + XMStoreFloat4x4( &m_mRot, id ); + XMStoreFloat4x4( &m_mRotSnapshot, id ); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CDXUTDirectionWidget::HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + switch( uMsg ) { case WM_LBUTTONDOWN: @@ -1312,221 +1155,70 @@ LRESULT CDXUTDirectionWidget::HandleMessages( HWND hWnd, UINT uMsg, //-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::OnRender9( D3DXCOLOR color, const D3DXMATRIX* pmView, - const D3DXMATRIX* pmProj, const D3DXVECTOR3* pEyePt ) -{ - m_mView = *pmView; - - // Render the light spheres so the user can visually see the light dir - UINT iPass, cPasses; - D3DXMATRIX mRotate; - D3DXMATRIX mScale; - D3DXMATRIX mTrans; - D3DXMATRIXA16 mWorldViewProj; - HRESULT hr; - - V( s_pD3D9Effect->SetTechnique( s_hRenderWith1LightNoTexture ) ); - V( s_pD3D9Effect->SetVector( s_hMaterialDiffuseColor, ( D3DXVECTOR4* )&color ) ); - - D3DXVECTOR3 vEyePt; - D3DXVec3Normalize( &vEyePt, pEyePt ); - V( s_pD3D9Effect->SetValue( s_hLightDir, &vEyePt, sizeof( D3DXVECTOR3 ) ) ); - - // Rotate arrow model to point towards origin - D3DXMATRIX mRotateA, mRotateB; - D3DXVECTOR3 vAt = D3DXVECTOR3( 0, 0, 0 ); - D3DXVECTOR3 vUp = D3DXVECTOR3( 0, 1, 0 ); - D3DXMatrixRotationX( &mRotateB, D3DX_PI ); - D3DXMatrixLookAtLH( &mRotateA, &m_vCurrentDir, &vAt, &vUp ); - D3DXMatrixInverse( &mRotateA, NULL, &mRotateA ); - mRotate = mRotateB * mRotateA; - - D3DXVECTOR3 vL = m_vCurrentDir * m_fRadius * 1.0f; - D3DXMatrixTranslation( &mTrans, vL.x, vL.y, vL.z ); - D3DXMatrixScaling( &mScale, m_fRadius * 0.2f, m_fRadius * 0.2f, m_fRadius * 0.2f ); - - D3DXMATRIX mWorld = mRotate * mScale * mTrans; - mWorldViewProj = mWorld * ( m_mView )*( *pmProj ); - - V( s_pD3D9Effect->SetMatrix( s_hWorldViewProjection, &mWorldViewProj ) ); - V( s_pD3D9Effect->SetMatrix( s_hWorld, &mWorld ) ); - - for( int iSubset = 0; iSubset < 2; iSubset++ ) - { - V( s_pD3D9Effect->Begin( &cPasses, 0 ) ); - for( iPass = 0; iPass < cPasses; iPass++ ) - { - V( s_pD3D9Effect->BeginPass( iPass ) ); - V( s_pD3D9Mesh->DrawSubset( iSubset ) ); - V( s_pD3D9Effect->EndPass() ); - } - V( s_pD3D9Effect->End() ); - } - - return S_OK; -} - -//-------------------------------------------------------------------------------------- HRESULT CDXUTDirectionWidget::UpdateLightDir() { - D3DXMATRIX mInvView; - D3DXMatrixInverse( &mInvView, NULL, &m_mView ); - mInvView._41 = mInvView._42 = mInvView._43 = 0; + XMMATRIX mView = XMLoadFloat4x4( &m_mView ); + + XMMATRIX mInvView = XMMatrixInverse( nullptr, mView ); + mInvView.r[3] = XMVectorSelect( mInvView.r[3], g_XMZero, g_XMSelect1110 ); - D3DXMATRIX mLastRotInv; - D3DXMatrixInverse( &mLastRotInv, NULL, &m_mRotSnapshot ); + XMMATRIX mRotSnapshot = XMLoadFloat4x4( &m_mRotSnapshot ); + XMMATRIX mLastRotInv = XMMatrixInverse( nullptr, mRotSnapshot ); - D3DXMATRIX mRot = *m_ArcBall.GetRotationMatrix(); - m_mRotSnapshot = mRot; + XMMATRIX mRot0 = m_ArcBall.GetRotationMatrix(); + XMStoreFloat4x4( &m_mRotSnapshot, mRot0 ); // Accumulate the delta of the arcball's rotation in view space. // Note that per-frame delta rotations could be problematic over long periods of time. - m_mRot *= m_mView * mLastRotInv * mRot * mInvView; + XMMATRIX mRot = XMLoadFloat4x4( &m_mRot ); + mRot *= mView * mLastRotInv * mRot0 * mInvView; // Since we're accumulating delta rotations, we need to orthonormalize // the matrix to prevent eventual matrix skew - D3DXVECTOR3* pXBasis = ( D3DXVECTOR3* )&m_mRot._11; - D3DXVECTOR3* pYBasis = ( D3DXVECTOR3* )&m_mRot._21; - D3DXVECTOR3* pZBasis = ( D3DXVECTOR3* )&m_mRot._31; - D3DXVec3Normalize( pXBasis, pXBasis ); - D3DXVec3Cross( pYBasis, pZBasis, pXBasis ); - D3DXVec3Normalize( pYBasis, pYBasis ); - D3DXVec3Cross( pZBasis, pXBasis, pYBasis ); + XMVECTOR xBasis = XMVector3Normalize( mRot.r[0] ); + XMVECTOR yBasis = XMVector3Cross( mRot.r[2], xBasis ); + yBasis = XMVector3Normalize( yBasis ); + XMVECTOR zBasis = XMVector3Cross( xBasis, yBasis ); + mRot.r[0] = XMVectorSelect( mRot.r[0], xBasis, g_XMSelect1110 ); + mRot.r[1] = XMVectorSelect( mRot.r[1], yBasis, g_XMSelect1110 ); + mRot.r[2] = XMVectorSelect( mRot.r[2], zBasis, g_XMSelect1110 ); + XMStoreFloat4x4( &m_mRot, mRot ); // Transform the default direction vector by the light's rotation matrix - D3DXVec3TransformNormal( &m_vCurrentDir, &m_vDefaultDir, &m_mRot ); + XMVECTOR vDefaultDir = XMLoadFloat3( &m_vDefaultDir ); + XMVECTOR vCurrentDir = XMVector3TransformNormal( vDefaultDir, mRot ); + XMStoreFloat3( &m_vCurrentDir, vCurrentDir ); return S_OK; } + //-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::StaticOnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) +_Use_decl_annotations_ +HRESULT CDXUTDirectionWidget::OnRender( FXMVECTOR color, CXMMATRIX mView, CXMMATRIX mProj, FXMVECTOR vEyePt ) { - - - //s_pd3d10Device = pd3dDevice; - - //const char* g_strBuffer = - // "float4 g_MaterialDiffuseColor; // Material's diffuse color\r\n" - // "float4 g_LightDir; // Light's direction in world space\r\n" - // "float4x4 g_mWorld; // World matrix for object\r\n" - // "float4x4 g_mWorldViewProjection; // World * View * Projection matrix\r\n" - // "\r\n" - // "struct VS_OUTPUT\r\n" - // "{\r\n" - // " float4 Position : SV_POSITION; // vertex position\r\n" - // " float4 Diffuse : COLOR0; // vertex diffuse color\r\n" - // "};\r\n" - // "\r\n" - // "VS_OUTPUT RenderWith1LightNoTextureVS( float3 vPos : POSITION,\r\n" - // " float3 vNormal : NORMAL )\r\n" - // "{\r\n" - // " VS_OUTPUT Output;\r\n" - // "\r\n" - // " // Transform the position from object space to homogeneous projection space\r\n" - // " Output.Position = mul( float4(vPos,1), g_mWorldViewProjection);\r\n" - // "\r\n" - // " // Transform the normal from object space to world space\r\n" - // " float3 vNormalWorldSpace;\r\n" - // " vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld)); // normal (world space)\r\n" - // "\r\n" - // " // Compute simple directional lighting equation\r\n" - // " Output.Diffuse.rgb = g_MaterialDiffuseColor * max(0,dot(vNormalWorldSpace, g_LightDir));\r\n" - // " Output.Diffuse.a = 1.0f;\r\n" - // "\r\n" - // " return Output;\r\n" - // "}\r\n" - // "\r\n" - // "float4 RenderWith1LightNoTexturePS( VS_OUTPUT Input ) : SV_TARGET\r\n" - // "{\r\n" - // " return Input.Diffuse;\r\n" - // "}\r\n" - // "\r\n" - // "technique10 RenderWith1LightNoTexture\r\n" - // "{\r\n" - // " pass p0\r\n" - // " {\r\n" - // " SetVertexShader( CompileShader( vs_4_0, RenderWith1LightNoTextureVS() ) );\r\n" - // " SetGeometryShader( NULL );\r\n" - // " SetPixelShader( CompileShader( ps_4_0, RenderWith1LightNoTexturePS() ) );\r\n" - // " }\r\n" - // "}\r\n" - // ""; - - //UINT dwBufferSize = ( UINT )strlen( g_strBuffer ) + 1; - - //HRESULT hr = D3DX10CreateEffectFromMemory( g_strBuffer, dwBufferSize, "None", NULL, NULL, "fx_4_0", - // D3D10_SHADER_ENABLE_STRICTNESS, 0, pd3dDevice, NULL, - // NULL, &s_pD3D10Effect, NULL, NULL ); - //if( FAILED( hr ) ) - // return hr; - - //s_pRenderTech = s_pD3D10Effect->GetTechniqueByName( "RenderWith1LightNoTexture" ); - //g_pMaterialDiffuseColor = s_pD3D10Effect->GetVariableByName( "g_MaterialDiffuseColor" )->AsVector(); - //g_pLightDir = s_pD3D10Effect->GetVariableByName( "g_LightDir" )->AsVector(); - //g_pmWorld = s_pD3D10Effect->GetVariableByName( "g_mWorld" )->AsMatrix(); - //g_pmWorldViewProjection = s_pD3D10Effect->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix(); - - //const D3D10_INPUT_ELEMENT_DESC layout[] = - //{ - // { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - // { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - //}; - //D3D10_PASS_DESC PassDesc; - //V_RETURN( s_pRenderTech->GetPassByIndex( 0 )->GetDesc( &PassDesc ) ); - //V_RETURN( pd3dDevice->CreateInputLayout( layout, 2, PassDesc.pIAInputSignature, - // PassDesc.IAInputSignatureSize, &s_pVertexLayout ) ); - + UNREFERENCED_PARAMETER(color); + UNREFERENCED_PARAMETER(mView); + UNREFERENCED_PARAMETER(mProj); + UNREFERENCED_PARAMETER(vEyePt); + // TODO - return S_OK; } + //-------------------------------------------------------------------------------------- -HRESULT CDXUTDirectionWidget::OnRender11( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, - const D3DXVECTOR3* pEyePt ) +_Use_decl_annotations_ +HRESULT CDXUTDirectionWidget::StaticOnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) { - // NO 11 version of D3DX11Mesh YET - // m_mView = *pmView; - - // // Render the light spheres so the user can visually see the light dir - // D3DXMATRIX mRotate; - // D3DXMATRIX mScale; - // D3DXMATRIX mTrans; - // D3DXMATRIXA16 mWorldViewProj; - - // g_pMaterialDiffuseColor->SetFloatVector( ( float* )&color ); - // D3DXVECTOR3 vEyePt; - // D3DXVec3Normalize( &vEyePt, pEyePt ); - // g_pLightDir->SetFloatVector( ( float* )&vEyePt ); - - // // Rotate arrow model to point towards origin - // D3DXMATRIX mRotateA, mRotateB; - // D3DXVECTOR3 vAt = D3DXVECTOR3( 0, 0, 0 ); - // D3DXVECTOR3 vUp = D3DXVECTOR3( 0, 1, 0 ); - // D3DXMatrixRotationX( &mRotateB, D3DX_PI ); - // D3DXMatrixLookAtLH( &mRotateA, &m_vCurrentDir, &vAt, &vUp ); - // D3DXMatrixInverse( &mRotateA, NULL, &mRotateA ); - // mRotate = mRotateB * mRotateA; - - // D3DXVECTOR3 vL = m_vCurrentDir * m_fRadius * 1.0f; - // D3DXMatrixTranslation( &mTrans, vL.x, vL.y, vL.z ); - // D3DXMatrixScaling( &mScale, m_fRadius * 0.2f, m_fRadius * 0.2f, m_fRadius * 0.2f ); - - // D3DXMATRIX mWorld = mRotate * mScale * mTrans; - // mWorldViewProj = mWorld * ( m_mView )*( *pmProj ); - - // g_pmWorldViewProjection->SetMatrix( ( float* )&mWorldViewProj ); - // g_pmWorld->SetMatrix( ( float* )&mWorld ); - - // s_pd3d10Device->IASetInputLayout( s_pVertexLayout ); - - // Add rendering code here - + UNREFERENCED_PARAMETER(pd3dDevice); + UNREFERENCED_PARAMETER(pd3dImmediateContext); + // TODO - return S_OK; } + //-------------------------------------------------------------------------------------- void CDXUTDirectionWidget::StaticOnD3D11DestroyDevice() { -// SAFE_RELEASE( s_pVertexLayout ); -// SAFE_RELEASE( s_pD3D11Effect ); + // TODO - } diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.h b/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.h index c29b104..468e2f5 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.h +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTcamera.h @@ -3,92 +3,105 @@ // // Helper functions for Direct3D programming. // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef CAMERA_H -#define CAMERA_H //-------------------------------------------------------------------------------------- class CD3DArcBall { public: - CD3DArcBall(); + CD3DArcBall(); // Functions to change behavior - void Reset(); - void SetTranslationRadius( FLOAT fRadiusTranslation ) + void Reset(); + void SetTranslationRadius( _In_ float fRadiusTranslation ) { m_fRadiusTranslation = fRadiusTranslation; } - 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 ); - } - void SetOffset( INT nX, INT nY ) + void SetWindow( _In_ INT nWidth, _In_ INT nHeight, _In_ float fRadius = 0.9f ) { - m_Offset.x = nX; m_Offset.y = nY; + m_nWidth = nWidth; + m_nHeight = nHeight; + m_fRadius = fRadius; + m_vCenter.x = float(m_nWidth) / 2.0f; + m_vCenter.y = float(m_nHeight) / 2.0f; } + void SetOffset( _In_ INT nX, _In_ INT nY ) { m_Offset.x = nX; m_Offset.y = nY; } // Call these from client and use GetRotationMatrix() to read new rotation matrix - void OnBegin( int nX, int nY ); // start the rotation (pass current mouse position) - void OnMove( int nX, int nY ); // continue the rotation (pass current mouse position) - void OnEnd(); // end the rotation + void OnBegin( _In_ int nX, _In_ int nY ); // start the rotation (pass current mouse position) + void OnMove( _In_ int nX, _In_ int nY ); // continue the rotation (pass current mouse position) + void OnEnd(); // end the rotation // Or call this to automatically handle left, middle, right buttons - LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); + LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); // Functions to get/set state - const D3DXMATRIX* GetRotationMatrix() - { - return D3DXMatrixRotationQuaternion( &m_mRotation, &m_qNow ); - }; - const D3DXMATRIX* GetTranslationMatrix() const - { - return &m_mTranslation; - } - const D3DXMATRIX* GetTranslationDeltaMatrix() const + DirectX::XMMATRIX GetRotationMatrix() const { - return &m_mTranslationDelta; + using namespace DirectX; + XMVECTOR q = XMLoadFloat4( &m_qNow ); + return DirectX::XMMatrixRotationQuaternion( q ); } - bool IsBeingDragged() const - { - return m_bDrag; - } - D3DXQUATERNION GetQuatNow() const + DirectX::XMMATRIX GetTranslationMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslation ); } + DirectX::XMMATRIX GetTranslationDeltaMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslationDelta ); } + bool IsBeingDragged() const { return m_bDrag; } + DirectX::XMVECTOR GetQuatNow() const { return DirectX::XMLoadFloat4( &m_qNow ); } + void SetQuatNow( _In_ DirectX::FXMVECTOR& q ) { DirectX::XMStoreFloat4( &m_qNow, q ); } + + static DirectX::XMVECTOR QuatFromBallPoints( _In_ DirectX::FXMVECTOR vFrom, _In_ DirectX::FXMVECTOR vTo ) { - return m_qNow; + using namespace DirectX; + + XMVECTOR dot = XMVector3Dot( vFrom, vTo ); + XMVECTOR vPart = XMVector3Cross( vFrom, vTo ); + return XMVectorSelect( dot, vPart, g_XMSelect1110 ); } - void SetQuatNow( D3DXQUATERNION q ) + +protected: + DirectX::XMFLOAT4X4 m_mRotation; // Matrix for arc ball's orientation + DirectX::XMFLOAT4X4 m_mTranslation; // Matrix for arc ball's position + DirectX::XMFLOAT4X4 m_mTranslationDelta;// Matrix for arc ball's position + + POINT m_Offset; // window offset, or upper-left corner of window + INT m_nWidth; // arc ball's window width + INT m_nHeight; // arc ball's window height + DirectX::XMFLOAT2 m_vCenter; // center of arc ball + float m_fRadius; // arc ball's radius in screen coords + float m_fRadiusTranslation; // arc ball's radius for translating the target + + DirectX::XMFLOAT4 m_qDown; // Quaternion before button down + DirectX::XMFLOAT4 m_qNow; // Composite quaternion for current drag + bool m_bDrag; // Whether user is dragging arc ball + + POINT m_ptLastMouse; // position of last mouse point + DirectX::XMFLOAT3 m_vDownPt; // starting point of rotation arc + DirectX::XMFLOAT3 m_vCurrentPt; // current point of rotation arc + + DirectX::XMVECTOR ScreenToVector( _In_ float fScreenPtX, _In_ float fScreenPtY ) { - m_qNow = q; - } + // Scale to screen + float x = -( fScreenPtX - m_Offset.x - m_nWidth / 2 ) / ( m_fRadius * m_nWidth / 2 ); + float y = ( fScreenPtY - m_Offset.y - m_nHeight / 2 ) / ( m_fRadius * m_nHeight / 2 ); - static D3DXQUATERNION WINAPI QuatFromBallPoints( const D3DXVECTOR3& vFrom, const D3DXVECTOR3& vTo ); + float z = 0.0f; + float mag = x * x + y * y; + if( mag > 1.0f ) + { + float scale = 1.0f / sqrtf( mag ); + x *= scale; + y *= scale; + } + else + z = sqrtf( 1.0f - mag ); -protected: - D3DXMATRIXA16 m_mRotation; // Matrix for arc ball's orientation - D3DXMATRIXA16 m_mTranslation; // Matrix for arc ball's position - D3DXMATRIXA16 m_mTranslationDelta; // Matrix for arc ball's position - - POINT m_Offset; // window offset, or upper-left corner of window - INT m_nWidth; // arc ball's window width - INT m_nHeight; // arc ball's window height - D3DXVECTOR2 m_vCenter; // center of arc ball - FLOAT m_fRadius; // arc ball's radius in screen coords - FLOAT m_fRadiusTranslation; // arc ball's radius for translating the target - - D3DXQUATERNION m_qDown; // Quaternion before button down - D3DXQUATERNION m_qNow; // Composite quaternion for current drag - bool m_bDrag; // Whether user is dragging arc ball - - POINT m_ptLastMouse; // position of last mouse point - D3DXVECTOR3 m_vDownPt; // starting point of rotation arc - D3DXVECTOR3 m_vCurrentPt; // current point of rotation arc - - D3DXVECTOR3 ScreenToVector( float fScreenPtX, float fScreenPtY ); + return DirectX::XMVectorSet( x, y, z, 0 ); + } }; @@ -126,170 +139,126 @@ enum D3DUtil_CameraKeys class CBaseCamera { public: - CBaseCamera(); + CBaseCamera(); // Call these from client and use Get*Matrix() to read new matrices - virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual void FrameMove( FLOAT fElapsedTime ) = 0; + virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); + virtual void FrameMove( _In_ float fElapsedTime ) = 0; // Functions to change camera matrices - virtual void Reset(); - virtual void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ); - virtual void SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, FLOAT fFarPlane ); + virtual void Reset(); + virtual void SetViewParams( _In_ DirectX::FXMVECTOR vEyePt, _In_ DirectX::FXMVECTOR vLookatPt ); + virtual void SetProjParams( _In_ float fFOV, _In_ float fAspect, _In_ float fNearPlane, _In_ float fFarPlane ); // Functions to change behavior - virtual void SetDragRect( RECT& rc ) - { - m_rcDrag = rc; - } - void SetInvertPitch( bool bInvertPitch ) + virtual void SetDragRect( _In_ const RECT& rc ) { m_rcDrag = rc; } + void SetInvertPitch( _In_ bool bInvertPitch ) { m_bInvertPitch = bInvertPitch; } + void SetDrag( _In_ bool bMovementDrag, _In_ float fTotalDragTimeToZero = 0.25f ) { - m_bInvertPitch = bInvertPitch; + m_bMovementDrag = bMovementDrag; + m_fTotalDragTimeToZero = fTotalDragTimeToZero; } - void SetDrag( bool bMovementDrag, FLOAT fTotalDragTimeToZero = 0.25f ) + void SetEnableYAxisMovement( _In_ bool bEnableYAxisMovement ) { m_bEnableYAxisMovement = bEnableYAxisMovement; } + void SetEnablePositionMovement( _In_ bool bEnablePositionMovement ) { m_bEnablePositionMovement = bEnablePositionMovement; } + void SetClipToBoundary( _In_ bool bClipToBoundary, _In_opt_ DirectX::XMFLOAT3* pvMinBoundary, _In_opt_ DirectX::XMFLOAT3* pvMaxBoundary ) { - m_bMovementDrag = bMovementDrag; m_fTotalDragTimeToZero = fTotalDragTimeToZero; - } - void SetEnableYAxisMovement( bool bEnableYAxisMovement ) - { - m_bEnableYAxisMovement = bEnableYAxisMovement; - } - void SetEnablePositionMovement( bool bEnablePositionMovement ) - { - m_bEnablePositionMovement = bEnablePositionMovement; - } - void SetClipToBoundary( bool bClipToBoundary, D3DXVECTOR3* pvMinBoundary, - D3DXVECTOR3* pvMaxBoundary ) - { - m_bClipToBoundary = bClipToBoundary; if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; + m_bClipToBoundary = bClipToBoundary; + if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; if( pvMaxBoundary ) m_vMaxBoundary = *pvMaxBoundary; } - void SetScalers( FLOAT fRotationScaler = 0.01f, FLOAT fMoveScaler = 5.0f ) - { - m_fRotationScaler = fRotationScaler; m_fMoveScaler = fMoveScaler; - } - void SetNumberOfFramesToSmoothMouseData( int nFrames ) - { - if( nFrames > 0 ) m_fFramesToSmoothMouseData = ( float )nFrames; - } - void SetResetCursorAfterMove( bool bResetCursorAfterMove ) + void SetScalers( _In_ float fRotationScaler = 0.01f, _In_ float fMoveScaler = 5.0f ) { - m_bResetCursorAfterMove = bResetCursorAfterMove; + m_fRotationScaler = fRotationScaler; + m_fMoveScaler = fMoveScaler; } + void SetNumberOfFramesToSmoothMouseData( _In_ int nFrames ) { if( nFrames > 0 ) m_fFramesToSmoothMouseData = ( float )nFrames; } + void SetResetCursorAfterMove( _In_ bool bResetCursorAfterMove ) { m_bResetCursorAfterMove = bResetCursorAfterMove; } // Functions to get state - const D3DXMATRIX* GetViewMatrix() const - { - return &m_mView; - } - const D3DXMATRIX* GetProjMatrix() const - { - return &m_mProj; - } - const D3DXVECTOR3* GetEyePt() const - { - return &m_vEye; - } - const D3DXVECTOR3* GetLookAtPt() const - { - return &m_vLookAt; - } - float GetNearClip() const - { - return m_fNearPlane; - } - float GetFarClip() const - { - return m_fFarPlane; - } - - bool IsBeingDragged() const - { - return ( m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown ); - } - bool IsMouseLButtonDown() const - { - return m_bMouseLButtonDown; - } - bool IsMouseMButtonDown() const - { - return m_bMouseMButtonDown; - } - bool IsMouseRButtonDown() const - { - return m_bMouseRButtonDown; - } + DirectX::XMMATRIX GetViewMatrix() const { return DirectX::XMLoadFloat4x4( &m_mView ); } + DirectX::XMMATRIX GetProjMatrix() const { return DirectX::XMLoadFloat4x4( &m_mProj ); } + DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( &m_vEye ); } + DirectX::XMVECTOR GetLookAtPt() const { return DirectX::XMLoadFloat3( &m_vLookAt ); } + float GetNearClip() const { return m_fNearPlane; } + float GetFarClip() const { return m_fFarPlane; } + + bool IsBeingDragged() const { return ( m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown ); } + bool IsMouseLButtonDown() const { return m_bMouseLButtonDown; } + bool IsMouseMButtonDown() const { return m_bMouseMButtonDown; } + bool sMouseRButtonDown() const { return m_bMouseRButtonDown; } protected: // Functions to map a WM_KEYDOWN key to a D3DUtil_CameraKeys enum - virtual D3DUtil_CameraKeys MapKey( UINT nKey ); - bool IsKeyDown( BYTE key ) const - { - return( ( key & KEY_IS_DOWN_MASK ) == KEY_IS_DOWN_MASK ); - } - bool WasKeyDown( BYTE key ) const - { - return( ( key & KEY_WAS_DOWN_MASK ) == KEY_WAS_DOWN_MASK ); - } - - void ConstrainToBoundary( D3DXVECTOR3* pV ); - void UpdateMouseDelta(); - void UpdateVelocity( float fElapsedTime ); - void GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput, - bool bResetCursorAfterMove ); - - D3DXMATRIX m_mView; // View matrix - D3DXMATRIX m_mProj; // Projection matrix - - DXUT_GAMEPAD m_GamePad[DXUT_MAX_CONTROLLERS]; // XInput controller state - D3DXVECTOR3 m_vGamePadLeftThumb; - D3DXVECTOR3 m_vGamePadRightThumb; - double m_GamePadLastActive[DXUT_MAX_CONTROLLERS]; - - int m_cKeysDown; // Number of camera keys that are down. - BYTE m_aKeys[CAM_MAX_KEYS]; // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK - D3DXVECTOR3 m_vKeyboardDirection; // Direction vector of keyboard input - POINT m_ptLastMousePosition; // Last absolute position of mouse cursor - bool m_bMouseLButtonDown; // True if left button is down - bool m_bMouseMButtonDown; // True if middle button is down - bool m_bMouseRButtonDown; // True if right button is down - int m_nCurrentButtonMask; // mask of which buttons are down - int m_nMouseWheelDelta; // Amount of middle wheel scroll (+/-) - D3DXVECTOR2 m_vMouseDelta; // Mouse relative delta smoothed over a few frames - float m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over - - D3DXVECTOR3 m_vDefaultEye; // Default camera eye position - D3DXVECTOR3 m_vDefaultLookAt; // Default LookAt position - D3DXVECTOR3 m_vEye; // Camera eye position - D3DXVECTOR3 m_vLookAt; // LookAt position - float m_fCameraYawAngle; // Yaw angle of camera - float m_fCameraPitchAngle; // Pitch angle of camera - - RECT m_rcDrag; // Rectangle within which a drag can be initiated. - D3DXVECTOR3 m_vVelocity; // Velocity of camera - bool m_bMovementDrag; // If true, then camera movement will slow to a stop otherwise movement is instant - D3DXVECTOR3 m_vVelocityDrag; // Velocity drag force - FLOAT m_fDragTimer; // Countdown timer to apply drag - FLOAT m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0 - D3DXVECTOR2 m_vRotVelocity; // Velocity of camera - - float m_fFOV; // Field of view - float m_fAspect; // Aspect ratio - float m_fNearPlane; // Near plane - float m_fFarPlane; // Far plane - - float m_fRotationScaler; // Scaler for rotation - float m_fMoveScaler; // Scaler for movement - - bool m_bInvertPitch; // Invert the pitch axis - bool m_bEnablePositionMovement; // If true, then the user can translate the camera/model - bool m_bEnableYAxisMovement; // If true, then camera can move in the y-axis - - bool m_bClipToBoundary; // If true, then the camera will be clipped to the boundary - D3DXVECTOR3 m_vMinBoundary; // Min point in clip boundary - D3DXVECTOR3 m_vMaxBoundary; // Max point in clip boundary - - bool m_bResetCursorAfterMove;// If true, the class will reset the cursor position so that the cursor always has space to move + virtual D3DUtil_CameraKeys MapKey( _In_ UINT nKey ); + + bool IsKeyDown( _In_ BYTE key ) const { return( ( key & KEY_IS_DOWN_MASK ) == KEY_IS_DOWN_MASK ); } + bool WasKeyDown( _In_ BYTE key ) const { return( ( key & KEY_WAS_DOWN_MASK ) == KEY_WAS_DOWN_MASK ); } + + DirectX::XMVECTOR ConstrainToBoundary( _In_ DirectX::FXMVECTOR v ) + { + using namespace DirectX; + + XMVECTOR vMin = XMLoadFloat3( &m_vMinBoundary ); + XMVECTOR vMax = XMLoadFloat3( &m_vMaxBoundary ); + + // Constrain vector to a bounding box + return XMVectorClamp( v, vMin, vMax ); + } + + void UpdateMouseDelta(); + void UpdateVelocity( _In_ float fElapsedTime ); + void GetInput( _In_ bool bGetKeyboardInput, _In_ bool bGetMouseInput, _In_ bool bGetGamepadInput ); + + DirectX::XMFLOAT4X4 m_mView; // View matrix + DirectX::XMFLOAT4X4 m_mProj; // Projection matrix + + DXUT_GAMEPAD m_GamePad[DXUT_MAX_CONTROLLERS]; // XInput controller state + DirectX::XMFLOAT3 m_vGamePadLeftThumb; + DirectX::XMFLOAT3 m_vGamePadRightThumb; + double m_GamePadLastActive[DXUT_MAX_CONTROLLERS]; + + int m_cKeysDown; // Number of camera keys that are down. + BYTE m_aKeys[CAM_MAX_KEYS]; // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK + DirectX::XMFLOAT3 m_vKeyboardDirection; // Direction vector of keyboard input + POINT m_ptLastMousePosition; // Last absolute position of mouse cursor + int m_nCurrentButtonMask; // mask of which buttons are down + int m_nMouseWheelDelta; // Amount of middle wheel scroll (+/-) + DirectX::XMFLOAT2 m_vMouseDelta; // Mouse relative delta smoothed over a few frames + float m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over + DirectX::XMFLOAT3 m_vDefaultEye; // Default camera eye position + DirectX::XMFLOAT3 m_vDefaultLookAt; // Default LookAt position + DirectX::XMFLOAT3 m_vEye; // Camera eye position + DirectX::XMFLOAT3 m_vLookAt; // LookAt position + float m_fCameraYawAngle; // Yaw angle of camera + float m_fCameraPitchAngle; // Pitch angle of camera + + RECT m_rcDrag; // Rectangle within which a drag can be initiated. + DirectX::XMFLOAT3 m_vVelocity; // Velocity of camera + DirectX::XMFLOAT3 m_vVelocityDrag; // Velocity drag force + float m_fDragTimer; // Countdown timer to apply drag + float m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0 + DirectX::XMFLOAT2 m_vRotVelocity; // Velocity of camera + + float m_fFOV; // Field of view + float m_fAspect; // Aspect ratio + float m_fNearPlane; // Near plane + float m_fFarPlane; // Far plane + + float m_fRotationScaler; // Scaler for rotation + float m_fMoveScaler; // Scaler for movement + + bool m_bMouseLButtonDown; // True if left button is down + bool m_bMouseMButtonDown; // True if middle button is down + bool m_bMouseRButtonDown; // True if right button is down + bool m_bMovementDrag; // If true, then camera movement will slow to a stop otherwise movement is instant + bool m_bInvertPitch; // Invert the pitch axis + bool m_bEnablePositionMovement; // If true, then the user can translate the camera/model + bool m_bEnableYAxisMovement; // If true, then camera can move in the y-axis + bool m_bClipToBoundary; // If true, then the camera will be clipped to the boundary + bool m_bResetCursorAfterMove; // If true, the class will reset the cursor position so that the cursor always has space to move + + DirectX::XMFLOAT3 m_vMinBoundary; // Min point in clip boundary + DirectX::XMFLOAT3 m_vMaxBoundary; // Max point in clip boundary }; @@ -302,41 +271,26 @@ protected: class CFirstPersonCamera : public CBaseCamera { public: - CFirstPersonCamera(); + CFirstPersonCamera(); // Call these from client and use Get*Matrix() to read new matrices - virtual void FrameMove( FLOAT fElapsedTime ); + virtual void FrameMove( _In_ float fElapsedTime ) override; // Functions to change behavior - void SetRotateButtons( bool bLeft, bool bMiddle, bool bRight, bool bRotateWithoutButtonDown = false ); + void SetRotateButtons( _In_ bool bLeft, _In_ bool bMiddle, _In_ bool bRight, _In_ bool bRotateWithoutButtonDown = false ); // Functions to get state - D3DXMATRIX* GetWorldMatrix() - { - return &m_mCameraWorld; - } + DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mCameraWorld ); } - const D3DXVECTOR3* GetWorldRight() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._11; - } - const D3DXVECTOR3* GetWorldUp() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._21; - } - const D3DXVECTOR3* GetWorldAhead() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._31; - } - const D3DXVECTOR3* GetEyePt() const - { - return ( D3DXVECTOR3* )&m_mCameraWorld._41; - } + DirectX::XMVECTOR GetWorldRight() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._11 ) ); } + DirectX::XMVECTOR GetWorldUp() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._21 ) ); } + DirectX::XMVECTOR GetWorldAhead() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._31 ) ); } + DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._41 ) ); } protected: - D3DXMATRIX m_mCameraWorld; // World matrix of the camera (inverse of the view matrix) + DirectX::XMFLOAT4X4 m_mCameraWorld; // World matrix of the camera (inverse of the view matrix) - int m_nActiveButtonMask; // Mask to determine which button to enable for rotation + int m_nActiveButtonMask; // Mask to determine which button to enable for rotation bool m_bRotateWithoutButtonDown; }; @@ -347,71 +301,61 @@ protected: class CModelViewerCamera : public CBaseCamera { public: - CModelViewerCamera(); + CModelViewerCamera(); // Call these from client and use Get*Matrix() to read new matrices - virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual void FrameMove( FLOAT fElapsedTime ); - + virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void FrameMove( _In_ float fElapsedTime ) override; // Functions to change behavior - virtual void SetDragRect( RECT& rc ); - void Reset(); - void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt ); - void SetButtonMasks( int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, int nZoomButtonMask = MOUSE_WHEEL, - int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON ) + virtual void SetDragRect( _In_ const RECT& rc ) override; + virtual void Reset() override; + virtual void SetViewParams( _In_ DirectX::FXMVECTOR pvEyePt, _In_ DirectX::FXMVECTOR pvLookatPt ) override; + void SetButtonMasks( _In_ int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, _In_ int nZoomButtonMask = MOUSE_WHEEL, + _In_ int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON ) { m_nRotateModelButtonMask = nRotateModelButtonMask, m_nZoomButtonMask = nZoomButtonMask; m_nRotateCameraButtonMask = nRotateCameraButtonMask; } - void SetAttachCameraToModel( bool bEnable = false ) - { - m_bAttachCameraToModel = bEnable; - } - void SetWindow( int nWidth, int nHeight, float fArcballRadius=0.9f ) + void SetAttachCameraToModel( _In_ bool bEnable = false ) { m_bAttachCameraToModel = bEnable; } + void SetWindow( _In_ int nWidth, _In_ int nHeight, _In_ float fArcballRadius=0.9f ) { m_WorldArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); m_ViewArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); } - void SetRadius( float fDefaultRadius=5.0f, float fMinRadius=1.0f, float fMaxRadius=FLT_MAX ) + void SetRadius( _In_ float fDefaultRadius=5.0f, _In_ float fMinRadius=1.0f, _In_ float fMaxRadius=FLT_MAX ) { m_fDefaultRadius = m_fRadius = fDefaultRadius; m_fMinRadius = fMinRadius; m_fMaxRadius = fMaxRadius; m_bDragSinceLastUpdate = true; } - void SetModelCenter( D3DXVECTOR3 vModelCenter ) - { - m_vModelCenter = vModelCenter; - } - void SetLimitPitch( bool bLimitPitch ) + void SetModelCenter( _In_ const DirectX::XMFLOAT3& vModelCenter ) { m_vModelCenter = vModelCenter; } + void SetLimitPitch( _In_ bool bLimitPitch ) { m_bLimitPitch = bLimitPitch; } + void SetViewQuat( _In_ DirectX::FXMVECTOR q ) { - m_bLimitPitch = bLimitPitch; - } - void SetViewQuat( D3DXQUATERNION q ) - { - m_ViewArcBall.SetQuatNow( q ); m_bDragSinceLastUpdate = true; + m_ViewArcBall.SetQuatNow( q ); + m_bDragSinceLastUpdate = true; } - void SetWorldQuat( D3DXQUATERNION q ) + void SetWorldQuat( _In_ DirectX::FXMVECTOR q ) { - m_WorldArcBall.SetQuatNow( q ); m_bDragSinceLastUpdate = true; + m_WorldArcBall.SetQuatNow( q ); + m_bDragSinceLastUpdate = true; } // Functions to get state - const D3DXMATRIX* GetWorldMatrix() const - { - return &m_mWorld; - } - void SetWorldMatrix( D3DXMATRIX& mWorld ) + DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mWorld ); } + void SetWorldMatrix( _In_ DirectX::CXMMATRIX mWorld ) { - m_mWorld = mWorld; m_bDragSinceLastUpdate = true; + XMStoreFloat4x4( &m_mWorld, mWorld ); + m_bDragSinceLastUpdate = true; } protected: CD3DArcBall m_WorldArcBall; CD3DArcBall m_ViewArcBall; - D3DXVECTOR3 m_vModelCenter; - D3DXMATRIX m_mModelLastRot; // Last arcball rotation matrix for model - D3DXMATRIX m_mModelRot; // Rotation matrix of model - D3DXMATRIX m_mWorld; // World matrix of model + DirectX::XMFLOAT3 m_vModelCenter; + DirectX::XMFLOAT4X4 m_mModelLastRot; // Last arcball rotation matrix for model + DirectX::XMFLOAT4X4 m_mModelRot; // Rotation matrix of model + DirectX::XMFLOAT4X4 m_mWorld; // World matrix of model int m_nRotateModelButtonMask; int m_nZoomButtonMask; @@ -419,16 +363,16 @@ protected: bool m_bAttachCameraToModel; bool m_bLimitPitch; - float m_fRadius; // Distance from the camera to model - float m_fDefaultRadius; // Distance from the camera to model - float m_fMinRadius; // Min radius - float m_fMaxRadius; // Max radius - bool m_bDragSinceLastUpdate; // True if mouse drag has happened since last time FrameMove is called. - - D3DXMATRIX m_mCameraRotLast; + bool m_bDragSinceLastUpdate; // True if mouse drag has happened since last time FrameMove is called. + float m_fRadius; // Distance from the camera to model + float m_fDefaultRadius; // Distance from the camera to model + float m_fMinRadius; // Min radius + float m_fMaxRadius; // Max radius + DirectX::XMFLOAT4X4 m_mCameraRotLast; }; + //-------------------------------------------------------------------------------------- // Manages the mesh, direction, mouse events of a directional arrow that // rotates around a radius controlled by an arcball @@ -436,82 +380,43 @@ protected: class CDXUTDirectionWidget { public: - CDXUTDirectionWidget(); - - static HRESULT WINAPI StaticOnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnD3D9ResetDevice( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ); - HRESULT OnRender9( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, - const D3DXVECTOR3* pEyePt ); - LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - static void WINAPI StaticOnD3D9LostDevice(); - static void WINAPI StaticOnD3D9DestroyDevice(); - - static HRESULT WINAPI StaticOnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ); - HRESULT OnRender11( D3DXCOLOR color, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj, - const D3DXVECTOR3* pEyePt ); - static void WINAPI StaticOnD3D11DestroyDevice(); - - D3DXVECTOR3 GetLightDirection() + CDXUTDirectionWidget(); + + LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); + + HRESULT OnRender( _In_ DirectX::FXMVECTOR color, _In_ DirectX::CXMMATRIX pmView, _In_ DirectX::CXMMATRIX pmProj, _In_ DirectX::FXMVECTOR vEyePt ); + + DirectX::XMVECTOR GetLightDirection() const { return DirectX::XMLoadFloat3( &m_vCurrentDir ); } + void SetLightDirection( _In_ DirectX::FXMVECTOR vDir ) { - return m_vCurrentDir; - }; - void SetLightDirection( D3DXVECTOR3 vDir ) + DirectX::XMStoreFloat3( &m_vCurrentDir, vDir ); + m_vDefaultDir = m_vCurrentDir; + } + void SetLightDirection( _In_ DirectX::XMFLOAT3 vDir ) { m_vDefaultDir = m_vCurrentDir = vDir; - }; - void SetButtonMask( int nRotate = MOUSE_RIGHT_BUTTON ) - { - m_nRotateMask = nRotate; } + void SetButtonMask( _In_ int nRotate = MOUSE_RIGHT_BUTTON ) { m_nRotateMask = nRotate; } - float GetRadius() - { - return m_fRadius; - }; - void SetRadius( float fRadius ) - { - m_fRadius = fRadius; - }; + float GetRadius() const { return m_fRadius; } + void SetRadius( _In_ float fRadius ) { m_fRadius = fRadius; } - bool IsBeingDragged() - { - return m_ArcBall.IsBeingDragged(); - }; + bool IsBeingDragged() { return m_ArcBall.IsBeingDragged(); } + + static HRESULT WINAPI StaticOnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext ); + static void WINAPI StaticOnD3D11DestroyDevice(); protected: - HRESULT UpdateLightDir(); - - // D3D9 objects - static IDirect3DDevice9* s_pd3d9Device; - static ID3DXEffect* s_pD3D9Effect; - static ID3DXMesh* s_pD3D9Mesh; - static D3DXHANDLE s_hRenderWith1LightNoTexture; - static D3DXHANDLE s_hMaterialDiffuseColor; - static D3DXHANDLE s_hLightDir; - static D3DXHANDLE s_hWorldViewProjection; - static D3DXHANDLE s_hWorld; - - // D3D10 objects - //static ID3D10Device* s_pd3d10Device; - //static ID3D10Effect* s_pD3D10Effect; - //TODO: add some sort of d3d10 mesh object here - //static ID3D10InputLayout* s_pVertexLayout; - //static ID3D10EffectTechnique* s_pRenderTech; - //static ID3D10EffectVectorVariable* g_pMaterialDiffuseColor; - //static ID3D10EffectVectorVariable* g_pLightDir; - //static ID3D10EffectMatrixVariable* g_pmWorld; - //static ID3D10EffectMatrixVariable* g_pmWorldViewProjection; - - D3DXMATRIXA16 m_mRot; - D3DXMATRIXA16 m_mRotSnapshot; + HRESULT UpdateLightDir(); + + // TODO - need support for Direct3D 11 widget + + DirectX::XMFLOAT4X4 m_mRot; + DirectX::XMFLOAT4X4 m_mRotSnapshot; float m_fRadius; int m_nRotateMask; CD3DArcBall m_ArcBall; - D3DXVECTOR3 m_vDefaultDir; - D3DXVECTOR3 m_vCurrentDir; - D3DXMATRIX m_mView; + DirectX::XMFLOAT3 m_vDefaultDir; + DirectX::XMFLOAT3 m_vCurrentDir; + DirectX::XMFLOAT4X4 m_mView; }; - - - -#endif diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTgui.cpp b/samples/DX_APIUsage/DXUT/Optional/DXUTgui.cpp index cb83fff..7a7c17c 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTgui.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTgui.cpp @@ -2,6 +2,9 @@ // File: DXUTgui.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" @@ -10,8 +13,9 @@ #include "SDKMisc.h" -#undef min // use __min instead -#undef max // use __max instead +#include "DDSTextureLoader.h" + +using namespace DirectX; #ifndef WM_XBUTTONDOWN #define WM_XBUTTONDOWN 0x020B // (not always defined) @@ -38,28 +42,14 @@ #define DXUT_MAX_GUI_SPRITES 500 -D3DCOLORVALUE D3DCOLOR_TO_D3DCOLORVALUE( D3DCOLOR c ) +inline XMFLOAT4 D3DCOLOR_TO_D3DCOLORVALUE( DWORD c ) { - D3DCOLORVALUE cv = - { - ( ( c >> 16 ) & 0xFF ) / 255.0f, - ( ( c >> 8 ) & 0xFF ) / 255.0f, - ( c & 0xFF ) / 255.0f, - ( ( c >> 24 ) & 0xFF ) / 255.0f - }; - return cv; + return XMFLOAT4 ( ( ( c >> 16 ) & 0xFF ) / 255.0f, + ( ( c >> 8 ) & 0xFF ) / 255.0f, + ( c & 0xFF ) / 255.0f, + ( ( c >> 24 ) & 0xFF ) / 255.0f ); } -#define UNISCRIBE_DLLNAME L"usp10.dll" - -#define GETPROCADDRESS( Module, APIName, Temp ) \ - Temp = GetProcAddress( Module, #APIName ); \ - if( Temp ) \ - *(FARPROC*)&_##APIName = Temp - -#define PLACEHOLDERPROC( APIName ) \ - _##APIName = Dummy_##APIName - #define IMM32_DLLNAME L"imm32.dll" #define VER_DLLNAME L"version.dll" @@ -164,44 +154,36 @@ const UINT g_uUIEffectFileSize = sizeof( g_strUIEffectFile ); // DXUT_MAX_EDITBOXLENGTH is the maximum string length allowed in edit boxes, -// including the NULL terminator. -// +// including the nul terminator. +// // Uniscribe does not support strings having bigger-than-16-bits length. // This means that the string must be less than 65536 characters long, -// including the NULL terminator. +// including the nul terminator. #define DXUT_MAX_EDITBOXLENGTH 0xFFFF double CDXUTDialog::s_fTimeRefresh = 0.0f; -CDXUTControl* CDXUTDialog::s_pControlFocus = NULL; // The control which has focus -CDXUTControl* CDXUTDialog::s_pControlPressed = NULL; // The control currently pressed +CDXUTControl* CDXUTDialog::s_pControlFocus = nullptr; // The control which has focus +CDXUTControl* CDXUTDialog::s_pControlPressed = nullptr; // The control currently pressed struct DXUT_SCREEN_VERTEX { float x, y, z, h; - D3DCOLOR color; + DWORD color; float tu, tv; - - static DWORD FVF; }; -DWORD DXUT_SCREEN_VERTEX::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1; - struct DXUT_SCREEN_VERTEX_UNTEX { float x, y, z, h; - D3DCOLOR color; - - static DWORD FVF; + DWORD color; }; -DWORD DXUT_SCREEN_VERTEX_UNTEX::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE; - struct DXUT_SCREEN_VERTEX_10 { float x, y, z; - D3DCOLORVALUE color; + XMFLOAT4 color; float tu, tv; }; @@ -216,682 +198,353 @@ inline int RectHeight( RECT& rc ) } -HRESULT InitFont11( ID3D11Device* pd3d11Device, ID3D11InputLayout* pInputLayout ); -void EndFont11(); - -//-------------------------------------------------------------------------------------- -// CDXUTDialog class -//-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -CDXUTDialog::CDXUTDialog() -{ - m_x = 0; - m_y = 0; - m_width = 0; - m_height = 0; - - m_pManager = NULL; - m_bVisible = true; - m_bCaption = false; - m_bMinimized = false; - m_bDrag = false; - m_wszCaption[0] = L'\0'; - m_nCaptionHeight = 18; - - m_colorTopLeft = 0; - m_colorTopRight = 0; - m_colorBottomLeft = 0; - m_colorBottomRight = 0; - - m_pCallbackEvent = NULL; - m_pCallbackEventUserContext = NULL; - - m_fTimeLastRefresh = 0; - - m_pControlMouseOver = NULL; - - m_pNextDialog = this; - m_pPrevDialog = this; - - m_nDefaultControlID = 0xffff; - m_bNonUserEvents = false; - m_bKeyboardInput = false; - m_bMouseInput = true; -} +//====================================================================================== +// Font11 +//====================================================================================== +ID3D11Buffer* g_pFontBuffer11 = nullptr; +UINT g_FontBufferBytes11 = 0; +std::vector<DXUTSpriteVertex> g_FontVertices; +ID3D11ShaderResourceView* g_pFont11 = nullptr; +ID3D11InputLayout* g_pInputLayout11 = nullptr; //-------------------------------------------------------------------------------------- -CDXUTDialog::~CDXUTDialog() +HRESULT InitFont11( _In_ ID3D11Device* pd3d11Device, _In_ ID3D11InputLayout* pInputLayout ) { - int i = 0; - - RemoveAllControls(); - - m_Fonts.RemoveAll(); - m_Textures.RemoveAll(); + HRESULT hr = S_OK; + WCHAR str[MAX_PATH]; + V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"UI\\Font.dds" ) ); - for( i = 0; i < m_DefaultElements.GetSize(); i++ ) - { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - SAFE_DELETE( pElementHolder ); - } + V_RETURN( CreateDDSTextureFromFile( pd3d11Device, str, nullptr, &g_pFont11 ) ); - m_DefaultElements.RemoveAll(); + g_pInputLayout11 = pInputLayout; + return hr; } //-------------------------------------------------------------------------------------- -void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog ) +void EndFont11() { - m_pManager = pManager; - if( bRegisterDialog ) - pManager->RegisterDialog( this ); - - SetTexture( 0, MAKEINTRESOURCE( 0xFFFF ), ( HMODULE )0xFFFF ); - InitDefaultElements(); + SAFE_RELEASE( g_pFontBuffer11 ); + g_FontBufferBytes11 = 0; + SAFE_RELEASE( g_pFont11 ); } //-------------------------------------------------------------------------------------- -void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, LPCWSTR pszControlTextureFilename ) +void BeginText11() { - m_pManager = pManager; - if( bRegisterDialog ) - pManager->RegisterDialog( this ); - SetTexture( 0, pszControlTextureFilename ); - InitDefaultElements(); + g_FontVertices.clear(); } //-------------------------------------------------------------------------------------- -void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, - LPCWSTR szControlTextureResourceName, HMODULE hControlTextureResourceModule ) +_Use_decl_annotations_ +void DrawText11DXUT( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, + LPCWSTR strText, const RECT& rcScreen, XMFLOAT4 vFontColor, + float fBBWidth, float fBBHeight, bool bCenter ) { - m_pManager = pManager; - if( bRegisterDialog ) - pManager->RegisterDialog( this ); - - SetTexture( 0, szControlTextureResourceName, hControlTextureResourceModule ); - InitDefaultElements(); -} + float fCharTexSizeX = 0.010526315f; + //float fGlyphSizeX = 14.0f / fBBWidth; + //float fGlyphSizeY = 32.0f / fBBHeight; + float fGlyphSizeX = 15.0f / fBBWidth; + float fGlyphSizeY = 42.0f / fBBHeight; -//-------------------------------------------------------------------------------------- -void CDXUTDialog::SetCallback( PCALLBACKDXUTGUIEVENT pCallback, void* pUserContext ) -{ - // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility - // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix call CDXUTDialog::Init() first. See comments for details." ); + float fRectLeft = rcScreen.left / fBBWidth; + float fRectTop = 1.0f - rcScreen.top / fBBHeight; - m_pCallbackEvent = pCallback; - m_pCallbackEventUserContext = pUserContext; -} + fRectLeft = fRectLeft * 2.0f - 1.0f; + fRectTop = fRectTop * 2.0f - 1.0f; + int NumChars = (int)wcslen( strText ); + if (bCenter) { + float fRectRight = rcScreen.right / fBBWidth; + fRectRight = fRectRight * 2.0f - 1.0f; + float fRectBottom = 1.0f - rcScreen.bottom / fBBHeight; + fRectBottom = fRectBottom * 2.0f - 1.0f; + float fcenterx = ((fRectRight - fRectLeft) - (float)NumChars*fGlyphSizeX) *0.5f; + float fcentery = ((fRectTop - fRectBottom) - (float)1*fGlyphSizeY) *0.5f; + fRectLeft += fcenterx ; + fRectTop -= fcentery; + } + float fOriginalLeft = fRectLeft; + float fTexTop = 0.0f; + float fTexBottom = 1.0f; -//-------------------------------------------------------------------------------------- -void CDXUTDialog::RemoveControl( int ID ) -{ - for( int i = 0; i < m_Controls.GetSize(); i++ ) + float fDepth = 0.5f; + for( int i=0; i<NumChars; i++ ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - if( pControl->GetID() == ID ) + if( strText[i] == '\n' ) { - // Clean focus first - ClearFocus(); - - // Clear references to this control - if( s_pControlFocus == pControl ) - s_pControlFocus = NULL; - if( s_pControlPressed == pControl ) - s_pControlPressed = NULL; - if( m_pControlMouseOver == pControl ) - m_pControlMouseOver = NULL; - - SAFE_DELETE( pControl ); - m_Controls.Remove( i ); + fRectLeft = fOriginalLeft; + fRectTop -= fGlyphSizeY; - return; + continue; + } + else if( strText[i] < 32 || strText[i] > 126 ) + { + continue; } - } -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialog::RemoveAllControls() -{ - if( s_pControlFocus && s_pControlFocus->m_pDialog == this ) - s_pControlFocus = NULL; - if( s_pControlPressed && s_pControlPressed->m_pDialog == this ) - s_pControlPressed = NULL; - m_pControlMouseOver = NULL; - - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - SAFE_DELETE( pControl ); - } - m_Controls.RemoveAll(); -} + // Add 6 sprite vertices + DXUTSpriteVertex SpriteVertex = {}; + float fRectRight = fRectLeft + fGlyphSizeX; + float fRectBottom = fRectTop - fGlyphSizeY; + float fTexLeft = ( strText[i] - 32 ) * fCharTexSizeX; + float fTexRight = fTexLeft + fCharTexSizeX; + // tri1 + SpriteVertex.vPos = XMFLOAT3( fRectLeft, fRectTop, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexLeft, fTexTop ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); -//-------------------------------------------------------------------------------------- -CDXUTDialogResourceManager::CDXUTDialogResourceManager() -{ - // Begin D3D9-specific - m_pd3d9Device = NULL; - m_pStateBlock = NULL; - m_pSprite = NULL; + SpriteVertex.vPos = XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexRight, fTexTop ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); - // Begin D3D11-specific - // Shaders - m_pVSRenderUI11 = NULL; - m_pPSRenderUI11 = NULL; - m_pPSRenderUIUntex11 = NULL; + SpriteVertex.vPos = XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexLeft, fTexBottom ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); - // States - m_pDepthStencilStateUI11 = NULL; - m_pRasterizerStateUI11 = NULL; - m_pBlendStateUI11 = NULL; - m_pSamplerStateUI11 = NULL; - m_pDepthStencilStateStored11 = NULL; - m_pRasterizerStateStored11 = NULL; - m_pBlendStateStored11 = NULL; - m_pSamplerStateStored11 = NULL; + // tri2 + SpriteVertex.vPos = XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexRight, fTexTop ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); - m_pInputLayout11 = NULL; - m_pVBScreenQuad11 = NULL; - m_pSpriteBuffer11 = NULL; -} + SpriteVertex.vPos = XMFLOAT3( fRectRight, fRectBottom, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexRight, fTexBottom ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); + SpriteVertex.vPos = XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexLeft, fTexBottom ); + SpriteVertex.vColor = vFontColor; + g_FontVertices.push_back( SpriteVertex ); -//-------------------------------------------------------------------------------------- -CDXUTDialogResourceManager::~CDXUTDialogResourceManager() -{ - int i; - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - SAFE_DELETE( pFontNode ); - } - m_FontCache.RemoveAll(); + fRectLeft += fGlyphSizeX; - for( i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - SAFE_DELETE( pTextureNode ); } - m_TextureCache.RemoveAll(); - CUniBuffer::Uninitialize(); + // We have to end text after every line so that rendering order between sprites and fonts is preserved + EndText11( pd3dDevice, pd3d11DeviceContext ); } - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::OnD3D9CreateDevice( LPDIRECT3DDEVICE9 pd3dDevice ) +_Use_decl_annotations_ +void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) { - HRESULT hr = S_OK; - int i = 0; - - m_pd3d9Device = pd3dDevice; - - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - hr = CreateFont9( i ); - if( FAILED( hr ) ) - return hr; - } + if ( g_FontVertices.empty() ) + return; - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + // ensure our buffer size can hold our sprites + UINT FontDataBytes = static_cast<UINT>( g_FontVertices.size() * sizeof( DXUTSpriteVertex ) ); + if( g_FontBufferBytes11 < FontDataBytes ) { - hr = CreateTexture9( i ); - if( FAILED( hr ) ) - return hr; - } - - hr = D3DXCreateSprite( pd3dDevice, &m_pSprite ); - if( FAILED( hr ) ) - return DXUT_ERR( L"D3DXCreateSprite", hr ); - - return S_OK; -} + SAFE_RELEASE( g_pFontBuffer11 ); + g_FontBufferBytes11 = FontDataBytes; + D3D11_BUFFER_DESC BufferDesc; + BufferDesc.ByteWidth = g_FontBufferBytes11; + BufferDesc.Usage = D3D11_USAGE_DYNAMIC; + BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + BufferDesc.MiscFlags = 0; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::OnD3D9ResetDevice() -{ - HRESULT hr = S_OK; + if (FAILED(pd3dDevice->CreateBuffer(&BufferDesc, nullptr, &g_pFontBuffer11))) + { + g_pFontBuffer11 = nullptr; + g_FontBufferBytes11 = 0; + return; + } + DXUT_SetDebugName( g_pFontBuffer11, "DXUT Text11" ); + } - for( int i = 0; i < m_FontCache.GetSize(); i++ ) + // Copy the sprites over + D3D11_BOX destRegion; + destRegion.left = 0; + destRegion.right = FontDataBytes; + destRegion.top = 0; + destRegion.bottom = 1; + destRegion.front = 0; + destRegion.back = 1; + D3D11_MAPPED_SUBRESOURCE MappedResource; + if ( S_OK == pd3d11DeviceContext->Map( g_pFontBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - - if( pFontNode->pFont9 ) - pFontNode->pFont9->OnResetDevice(); + memcpy( MappedResource.pData, (void*)&g_FontVertices[0], FontDataBytes ); + pd3d11DeviceContext->Unmap(g_pFontBuffer11, 0); } - if( m_pSprite ) - m_pSprite->OnResetDevice(); + ID3D11ShaderResourceView* pOldTexture = nullptr; + pd3d11DeviceContext->PSGetShaderResources( 0, 1, &pOldTexture ); + pd3d11DeviceContext->PSSetShaderResources( 0, 1, &g_pFont11 ); - V_RETURN( m_pd3d9Device->CreateStateBlock( D3DSBT_ALL, &m_pStateBlock ) ); + // Draw + UINT Stride = sizeof( DXUTSpriteVertex ); + UINT Offset = 0; + pd3d11DeviceContext->IASetVertexBuffers( 0, 1, &g_pFontBuffer11, &Stride, &Offset ); + pd3d11DeviceContext->IASetInputLayout( g_pInputLayout11 ); + pd3d11DeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); + pd3d11DeviceContext->Draw( static_cast<UINT>( g_FontVertices.size() ), 0 ); - return S_OK; -} + pd3d11DeviceContext->PSSetShaderResources( 0, 1, &pOldTexture ); + SAFE_RELEASE( pOldTexture ); -//-------------------------------------------------------------------------------------- -bool CDXUTDialogResourceManager::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) -{ - return false; + g_FontVertices.clear(); } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D9LostDevice() +//====================================================================================== +// CDXUTDialog class +//====================================================================================== + +CDXUTDialog::CDXUTDialog() : + m_x( 0 ), + m_y( 0 ), + m_width( 0 ), + m_height( 0 ), + m_pManager( nullptr ), + m_bVisible( true ), + m_bCaption( false ), + m_bMinimized( false ), + m_bDrag( false ), + m_nCaptionHeight( 18 ), + m_colorTopLeft( 0 ), + m_colorTopRight( 0 ), + m_colorBottomLeft( 0 ), + m_colorBottomRight( 0 ), + m_pCallbackEvent( nullptr ), + m_pCallbackEventUserContext( nullptr ), + m_fTimeLastRefresh( 0 ), + m_pControlMouseOver( nullptr ), + m_nDefaultControlID( 0xffff ), + m_bNonUserEvents( false ), + m_bKeyboardInput( false ), + m_bMouseInput( true ) { - for( int i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - - if( pFontNode->pFont9 ) - pFontNode->pFont9->OnLostDevice(); - } - - if( m_pSprite ) - m_pSprite->OnLostDevice(); + m_wszCaption[0] = L'\0'; - SAFE_RELEASE( m_pStateBlock ); + m_pNextDialog = this; + m_pPrevDialog = this; } //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D9DestroyDevice() -{ - int i = 0; - - m_pd3d9Device = NULL; - - // Release the resources but don't clear the cache, as these will need to be - // recreated if the device is recreated - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - SAFE_RELEASE( pFontNode->pFont9 ); - } - - for( i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - SAFE_RELEASE( pTextureNode->pTexture9 ); - } - - SAFE_RELEASE( m_pSprite ); -} - - - -HRESULT CDXUTDialogResourceManager::OnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) +CDXUTDialog::~CDXUTDialog() { - m_pd3d11Device = pd3dDevice; - m_pd3d11DeviceContext = pd3d11DeviceContext; - - HRESULT hr = S_OK; - - // Compile Shaders - ID3DBlob* pVSBlob = NULL; - ID3DBlob* pPSBlob = NULL; - ID3DBlob* pPSUntexBlob = NULL; - V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", NULL, NULL, "VS", "vs_4_0_level_9_1", - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pVSBlob, NULL ) ); - V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", NULL, NULL, "PS", "ps_4_0_level_9_1", - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSBlob, NULL ) ); - V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", NULL, NULL, "PSUntex", "ps_4_0_level_9_1", - D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSUntexBlob, NULL ) ); - - // Create Shaders - V_RETURN( pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &m_pVSRenderUI11 ) ); - DXUT_SetDebugName( m_pVSRenderUI11, "CDXUTDialogResourceManager" ); - - V_RETURN( pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &m_pPSRenderUI11 ) ); - DXUT_SetDebugName( m_pPSRenderUI11, "CDXUTDialogResourceManager" ); - - V_RETURN( pd3dDevice->CreatePixelShader( pPSUntexBlob->GetBufferPointer(), pPSUntexBlob->GetBufferSize(), NULL, &m_pPSRenderUIUntex11 ) ); - DXUT_SetDebugName( m_pPSRenderUIUntex11, "CDXUTDialogResourceManager" ); - - // States - D3D11_DEPTH_STENCIL_DESC DSDesc; - ZeroMemory( &DSDesc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); - DSDesc.DepthEnable = FALSE; - DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; - DSDesc.DepthFunc = D3D11_COMPARISON_LESS; - DSDesc.StencilEnable = FALSE; - V_RETURN( pd3dDevice->CreateDepthStencilState( &DSDesc, &m_pDepthStencilStateUI11 ) ); - DXUT_SetDebugName( m_pDepthStencilStateUI11, "CDXUTDialogResourceManager" ); - - D3D11_RASTERIZER_DESC RSDesc; - RSDesc.AntialiasedLineEnable = FALSE; - RSDesc.CullMode = D3D11_CULL_BACK; - RSDesc.DepthBias = 0; - RSDesc.DepthBiasClamp = 0.0f; - RSDesc.DepthClipEnable = TRUE; - RSDesc.FillMode = D3D11_FILL_SOLID; - RSDesc.FrontCounterClockwise = FALSE; - RSDesc.MultisampleEnable = TRUE; - RSDesc.ScissorEnable = FALSE; - RSDesc.SlopeScaledDepthBias = 0.0f; - V_RETURN( pd3dDevice->CreateRasterizerState( &RSDesc, &m_pRasterizerStateUI11 ) ); - DXUT_SetDebugName( m_pRasterizerStateUI11, "CDXUTDialogResourceManager" ); - - D3D11_BLEND_DESC BSDesc; - ZeroMemory( &BSDesc, sizeof( D3D11_BLEND_DESC ) ); - - BSDesc.RenderTarget[0].BlendEnable = TRUE; - BSDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; - BSDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - BSDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - BSDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - BSDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; - BSDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - BSDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; - - V_RETURN( pd3dDevice->CreateBlendState( &BSDesc, &m_pBlendStateUI11 ) ); - DXUT_SetDebugName( m_pBlendStateUI11, "CDXUTDialogResourceManager" ); - - D3D11_SAMPLER_DESC SSDesc; - ZeroMemory( &SSDesc, sizeof( D3D11_SAMPLER_DESC ) ); - SSDesc.Filter = D3D11_FILTER_ANISOTROPIC ; - SSDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; - SSDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; - SSDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; - SSDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; - SSDesc.MaxAnisotropy = 16; - SSDesc.MinLOD = 0; - SSDesc.MaxLOD = D3D11_FLOAT32_MAX; - if ( pd3dDevice->GetFeatureLevel() < D3D_FEATURE_LEVEL_9_3 ) { - SSDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; - SSDesc.MaxAnisotropy = 0; - } - V_RETURN( pd3dDevice->CreateSamplerState( &SSDesc, &m_pSamplerStateUI11 ) ); - DXUT_SetDebugName( m_pSamplerStateUI11, "CDXUTDialogResourceManager" ); + RemoveAllControls(); - // Create the font and texture objects in the cache arrays. - int i = 0; - for( i = 0; i < m_FontCache.GetSize(); i++ ) - { - hr = CreateFont11( i ); - if( FAILED( hr ) ) - return hr; - } + m_Fonts.clear(); + m_Textures.clear(); - for( i = 0; i < m_TextureCache.GetSize(); i++ ) + for( auto it = m_DefaultElements.begin(); it != m_DefaultElements.end(); ++it ) { - hr = CreateTexture11( i ); - if( FAILED( hr ) ) - return hr; + SAFE_DELETE( *it ); } - // Create input layout - const D3D11_INPUT_ELEMENT_DESC layout[] = - { - { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - }; - - V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &m_pInputLayout11 ) ); - DXUT_SetDebugName( m_pInputLayout11, "CDXUTDialogResourceManager" ); - - // Release the blobs - SAFE_RELEASE( pVSBlob ); - SAFE_RELEASE( pPSBlob ); - SAFE_RELEASE( pPSUntexBlob ); - - // Create a vertex buffer quad for rendering later - D3D11_BUFFER_DESC BufDesc; - BufDesc.ByteWidth = sizeof( DXUT_SCREEN_VERTEX_10 ) * 4; - BufDesc.Usage = D3D11_USAGE_DYNAMIC; - BufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - BufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - BufDesc.MiscFlags = 0; - V_RETURN( pd3dDevice->CreateBuffer( &BufDesc, NULL, &m_pVBScreenQuad11 ) ); - DXUT_SetDebugName( m_pVBScreenQuad11, "CDXUTDialogResourceManager" ); - - // Init the D3D11 font - InitFont11( pd3dDevice, m_pInputLayout11 ); - - return S_OK; + m_DefaultElements.clear(); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) +_Use_decl_annotations_ +void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog ) { - HRESULT hr = S_OK; - - m_nBackBufferWidth = pBackBufferSurfaceDesc->Width; - m_nBackBufferHeight = pBackBufferSurfaceDesc->Height; - - return hr; -} - + m_pManager = pManager; + if( bRegisterDialog ) + pManager->RegisterDialog( this ); -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D11ReleasingSwapChain() -{ + SetTexture( 0, MAKEINTRESOURCE( 0xFFFF ), ( HMODULE )0xFFFF ); + InitDefaultElements(); } //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::OnD3D11DestroyDevice() +_Use_decl_annotations_ +void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, LPCWSTR pszControlTextureFilename ) { - int i; - - // Release the resources but don't clear the cache, as these will need to be - // recreated if the device is recreated - - for( i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - SAFE_RELEASE( pTextureNode->pTexResView11 ); - SAFE_RELEASE( pTextureNode->pTexture11 ); - } - - // D3D11 - SAFE_RELEASE( m_pVBScreenQuad11 ); - SAFE_RELEASE( m_pSpriteBuffer11 ); - m_SpriteBufferBytes11 = 0; - SAFE_RELEASE( m_pInputLayout11 ); - - // Shaders - SAFE_RELEASE( m_pVSRenderUI11 ); - SAFE_RELEASE( m_pPSRenderUI11 ); - SAFE_RELEASE( m_pPSRenderUIUntex11 ); - - // States - SAFE_RELEASE( m_pDepthStencilStateUI11 ); - SAFE_RELEASE( m_pRasterizerStateUI11 ); - SAFE_RELEASE( m_pBlendStateUI11 ); - SAFE_RELEASE( m_pSamplerStateUI11 ); - - SAFE_RELEASE( m_pDepthStencilStateStored11 ); - SAFE_RELEASE( m_pRasterizerStateStored11 ); - SAFE_RELEASE( m_pBlendStateStored11 ); - SAFE_RELEASE( m_pSamplerStateStored11 ); - - EndFont11(); + m_pManager = pManager; + if( bRegisterDialog ) + pManager->RegisterDialog( this ); + SetTexture( 0, pszControlTextureFilename ); + InitDefaultElements(); } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::StoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ) -{ - pd3dImmediateContext->OMGetDepthStencilState( &m_pDepthStencilStateStored11, &m_StencilRefStored11 ); - pd3dImmediateContext->RSGetState( &m_pRasterizerStateStored11 ); - pd3dImmediateContext->OMGetBlendState( &m_pBlendStateStored11, m_BlendFactorStored11, &m_SampleMaskStored11 ); - pd3dImmediateContext->PSGetSamplers( 0, 1, &m_pSamplerStateStored11 ); -} //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::RestoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ) +_Use_decl_annotations_ +void CDXUTDialog::Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, + LPCWSTR szControlTextureResourceName, HMODULE hControlTextureResourceModule ) { - pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateStored11, m_StencilRefStored11 ); - pd3dImmediateContext->RSSetState( m_pRasterizerStateStored11 ); - pd3dImmediateContext->OMSetBlendState( m_pBlendStateStored11, m_BlendFactorStored11, m_SampleMaskStored11 ); - pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateStored11 ); + m_pManager = pManager; + if( bRegisterDialog ) + pManager->RegisterDialog( this ); - SAFE_RELEASE( m_pDepthStencilStateStored11 ); - SAFE_RELEASE( m_pRasterizerStateStored11 ); - SAFE_RELEASE( m_pBlendStateStored11 ); - SAFE_RELEASE( m_pSamplerStateStored11 ); + SetTexture( 0, szControlTextureResourceName, hControlTextureResourceModule ); + InitDefaultElements(); } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::ApplyRenderUI11( ID3D11DeviceContext* pd3dImmediateContext ) -{ - // Shaders - pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, NULL, 0 ); - pd3dImmediateContext->HSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->DSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->GSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->PSSetShader( m_pPSRenderUI11, NULL, 0 ); - - // States - pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); - pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); - float BlendFactor[4] = { 0, 0, 0, 0 }; - pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); - pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); -} //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::ApplyRenderUIUntex11( ID3D11DeviceContext* pd3dImmediateContext ) +_Use_decl_annotations_ +void CDXUTDialog::SetCallback( PCALLBACKDXUTGUIEVENT pCallback, void* pUserContext ) { - // Shaders - pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, NULL, 0 ); - pd3dImmediateContext->HSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->DSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->GSSetShader( NULL, NULL, 0 ); - pd3dImmediateContext->PSSetShader( m_pPSRenderUIUntex11, NULL, 0 ); + // If this assert triggers, you need to call CDXUTDialog::Init() first. This change + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // of the application if it wishes to use DXUT's GUI. + assert( m_pManager && L"To fix call CDXUTDialog::Init() first. See comments for details." ); - // States - pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); - pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); - float BlendFactor[4] = { 0, 0, 0, 0 }; - pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); - pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); + m_pCallbackEvent = pCallback; + m_pCallbackEventUserContext = pUserContext; } -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::BeginSprites11( ) -{ - m_SpriteVertices.Reset(); -} //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::EndSprites11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) +void CDXUTDialog::RemoveControl( _In_ int ID ) { - - // ensure our buffer size can hold our sprites - UINT SpriteDataBytes = m_SpriteVertices.GetSize() * sizeof( DXUTSpriteVertex ); - if( m_SpriteBufferBytes11 < SpriteDataBytes ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - SAFE_RELEASE( m_pSpriteBuffer11 ); - m_SpriteBufferBytes11 = SpriteDataBytes; - - D3D11_BUFFER_DESC BufferDesc; - BufferDesc.ByteWidth = m_SpriteBufferBytes11; - BufferDesc.Usage = D3D11_USAGE_DYNAMIC; - BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - BufferDesc.MiscFlags = 0; - - pd3dDevice->CreateBuffer( &BufferDesc, NULL, &m_pSpriteBuffer11 ); - DXUT_SetDebugName( m_pSpriteBuffer11, "CDXUTDialogResourceManager" ); - } - - // Copy the sprites over - D3D11_BOX destRegion; - destRegion.left = 0; - destRegion.right = SpriteDataBytes; - destRegion.top = 0; - destRegion.bottom = 1; - destRegion.front = 0; - destRegion.back = 1; - D3D11_MAPPED_SUBRESOURCE MappedResource; - if ( S_OK == pd3dImmediateContext->Map( m_pSpriteBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) { - CopyMemory( MappedResource.pData, (void*)m_SpriteVertices.GetData(), SpriteDataBytes ); - pd3dImmediateContext->Unmap(m_pSpriteBuffer11, 0); - } - - // Draw - UINT Stride = sizeof( DXUTSpriteVertex ); - UINT Offset = 0; - pd3dImmediateContext->IASetVertexBuffers( 0, 1, &m_pSpriteBuffer11, &Stride, &Offset ); - pd3dImmediateContext->IASetInputLayout( m_pInputLayout11 ); - pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); - pd3dImmediateContext->Draw( m_SpriteVertices.GetSize(), 0 ); - - m_SpriteVertices.Reset(); -} - -//-------------------------------------------------------------------------------------- -bool CDXUTDialogResourceManager::RegisterDialog( CDXUTDialog* pDialog ) -{ - // Check that the dialog isn't already registered. - for( int i = 0; i < m_Dialogs.GetSize(); ++i ) - if( m_Dialogs.GetAt( i ) == pDialog ) - return true; - - // Add to the list. - if( FAILED( m_Dialogs.Add( pDialog ) ) ) - return false; - - // Set up next and prev pointers. - if( m_Dialogs.GetSize() > 1 ) - m_Dialogs[m_Dialogs.GetSize() - 2]->SetNextDialog( pDialog ); - m_Dialogs[m_Dialogs.GetSize() - 1]->SetNextDialog( m_Dialogs[0] ); - - return true; -} - - -//-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::UnregisterDialog( CDXUTDialog* pDialog ) -{ - // Search for the dialog in the list. - for( int i = 0; i < m_Dialogs.GetSize(); ++i ) - if( m_Dialogs.GetAt( i ) == pDialog ) + if( (*it)->GetID() == ID ) { - m_Dialogs.Remove( i ); - if( m_Dialogs.GetSize() > 0 ) - { - int l, r; + // Clean focus first + ClearFocus(); - if( 0 == i ) - l = m_Dialogs.GetSize() - 1; - else - l = i - 1; + // Clear references to this control + if( s_pControlFocus == (*it) ) + s_pControlFocus = nullptr; + if( s_pControlPressed == (*it) ) + s_pControlPressed = nullptr; + if( m_pControlMouseOver == (*it) ) + m_pControlMouseOver = nullptr; - if( m_Dialogs.GetSize() == i ) - r = 0; - else - r = i; + SAFE_DELETE( (*it) ); + m_Controls.erase( it ); - m_Dialogs[l]->SetNextDialog( m_Dialogs[r] ); - } return; } + } } //-------------------------------------------------------------------------------------- -void CDXUTDialogResourceManager::EnableKeyboardInputForAllDialogs() +void CDXUTDialog::RemoveAllControls() { - // Enable keyboard input for all registered dialogs - for( int i = 0; i < m_Dialogs.GetSize(); ++i ) - m_Dialogs[i]->EnableKeyboardInput( true ); + if( s_pControlFocus && s_pControlFocus->m_pDialog == this ) + s_pControlFocus = nullptr; + if( s_pControlPressed && s_pControlPressed->m_pDialog == this ) + s_pControlPressed = nullptr; + m_pControlMouseOver = nullptr; + + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) + { + SAFE_DELETE( *it ); + } + + m_Controls.clear(); } @@ -904,14 +557,13 @@ void CDXUTDialog::Refresh() if( m_pControlMouseOver ) m_pControlMouseOver->OnMouseLeave(); - s_pControlFocus = NULL; - s_pControlPressed = NULL; - m_pControlMouseOver = NULL; + s_pControlFocus = nullptr; + s_pControlPressed = nullptr; + m_pControlMouseOver = nullptr; - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - pControl->Refresh(); + (*it)->Refresh(); } if( m_bKeyboardInput ) @@ -920,150 +572,7 @@ void CDXUTDialog::Refresh() //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::OnRender( float fElapsedTime ) -{ - if( m_pManager->GetD3D9Device() ) - return OnRender9( fElapsedTime ); - else - return OnRender11( fElapsedTime ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::OnRender9( float fElapsedTime ) -{ - // If this assert triggers, you need to call CDXUTDialogResourceManager::On*Device() from inside - // the application's device callbacks. See the SDK samples for an example of how to do this. - assert( m_pManager->GetD3D9Device() && m_pManager->m_pStateBlock && - L"To fix hook up CDXUTDialogResourceManager to device callbacks. See comments for details" ); - - // See if the dialog needs to be refreshed - if( m_fTimeLastRefresh < s_fTimeRefresh ) - { - m_fTimeLastRefresh = DXUTGetTime(); - Refresh(); - } - - // For invisible dialog, out now. - if( !m_bVisible || - ( m_bMinimized && !m_bCaption ) ) - return S_OK; - - IDirect3DDevice9* pd3dDevice = m_pManager->GetD3D9Device(); - - // Set up a state block here and restore it when finished drawing all the controls - m_pManager->m_pStateBlock->Capture(); - - //pd3dDevice->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, TRUE); - //pd3dDevice->SetRenderState( D3DRS_SRGBWRITEENABLE, TRUE ); - - pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); - pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); - pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); - pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_SEPARATEALPHABLENDENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_BLENDOP, D3DBLENDOP_ADD ); - pd3dDevice->SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | - D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED ); - pd3dDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD ); - pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); - pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); - pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_RESULTARG, D3DTA_CURRENT ); - pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); - pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); - - BOOL bBackgroundIsVisible = ( m_colorTopLeft | m_colorTopRight | m_colorBottomRight | m_colorBottomLeft ) & - 0xff000000; - if( !m_bMinimized && bBackgroundIsVisible ) - { - DXUT_SCREEN_VERTEX_UNTEX vertices[4] = - { - ( float )m_x, ( float )m_y, 0.5f, 1.0f, m_colorTopLeft, - ( float )m_x + m_width, ( float )m_y, 0.5f, 1.0f, m_colorTopRight, - ( float )m_x + m_width, ( float )m_y + m_height, 0.5f, 1.0f, m_colorBottomRight, - ( float )m_x, ( float )m_y + m_height, 0.5f, 1.0f, m_colorBottomLeft, - }; - - pd3dDevice->SetVertexShader( NULL ); - pd3dDevice->SetPixelShader( NULL ); - - pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); - - pd3dDevice->SetFVF( DXUT_SCREEN_VERTEX_UNTEX::FVF ); - pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices, sizeof( DXUT_SCREEN_VERTEX_UNTEX ) ); - } - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); - - pd3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); - - DXUTTextureNode* pTextureNode = GetTexture( 0 ); - pd3dDevice->SetTexture( 0, pTextureNode->pTexture9 ); - - m_pManager->m_pSprite->Begin( D3DXSPRITE_DONOTSAVESTATE ); - - // Render the caption if it's enabled. - if( m_bCaption ) - { - // DrawSprite will offset the rect down by - // m_nCaptionHeight, so adjust the rect higher - // here to negate the effect. - RECT rc = - { - 0, -m_nCaptionHeight, m_width, 0 - }; - DrawSprite9( &m_CapElement, &rc ); - rc.left += 5; // Make a left margin - WCHAR wszOutput[256]; - wcscpy_s( wszOutput, 256, m_wszCaption ); - if( m_bMinimized ) - wcscat_s( wszOutput, 256, L" (Minimized)" ); - DrawText9( wszOutput, &m_CapElement, &rc, true ); - } - - // If the dialog is minimized, skip rendering - // its controls. - if( !m_bMinimized ) - { - for( int i = 0; i < m_Controls.GetSize(); i++ ) - { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - // Focused control is drawn last - if( pControl == s_pControlFocus ) - continue; - - pControl->Render( fElapsedTime ); - } - - if( s_pControlFocus != NULL && s_pControlFocus->m_pDialog == this ) - s_pControlFocus->Render( fElapsedTime ); - } - - m_pManager->m_pSprite->End(); - - m_pManager->m_pStateBlock->Apply(); - - return S_OK; -} - - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) +HRESULT CDXUTDialog::OnRender( _In_ float fElapsedTime ) { // If this assert triggers, you need to call CDXUTDialogResourceManager::On*Device() from inside // the application's device callbacks. See the SDK samples for an example of how to do this. @@ -1082,14 +591,13 @@ HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) ( m_bMinimized && !m_bCaption ) ) return S_OK; - ID3D11Device* pd3dDevice = m_pManager->GetD3D11Device(); - ID3D11DeviceContext* pd3dDeviceContext = m_pManager->GetD3D11DeviceContext(); + auto pd3dDevice = m_pManager->GetD3D11Device(); + auto pd3dDeviceContext = m_pManager->GetD3D11DeviceContext(); // Set up a state block here and restore it when finished drawing all the controls m_pManager->StoreD3D11State( pd3dDeviceContext ); - BOOL bBackgroundIsVisible = ( m_colorTopLeft | m_colorTopRight | m_colorBottomRight | m_colorBottomLeft ) & - 0xff000000; + BOOL bBackgroundIsVisible = ( m_colorTopLeft | m_colorTopRight | m_colorBottomRight | m_colorBottomLeft ) & 0xff000000; if( !m_bMinimized && bBackgroundIsVisible ) { // Convert the draw rectangle from screen coordinates to clip space coordinates. @@ -1112,7 +620,7 @@ HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) if( SUCCEEDED( pd3dDeviceContext->Map( m_pManager->m_pVBScreenQuad11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedData ) ) ) { - CopyMemory( MappedData.pData, vertices, sizeof( vertices ) ); + memcpy( MappedData.pData, vertices, sizeof( vertices ) ); pd3dDeviceContext->Unmap( m_pManager->m_pVBScreenQuad11, 0 ); } @@ -1128,7 +636,7 @@ HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) pd3dDeviceContext->Draw( 4, 0 ); } - DXUTTextureNode* pTextureNode = GetTexture( 0 ); + auto pTextureNode = GetTexture( 0 ); pd3dDeviceContext->PSSetShaderResources( 0, 1, &pTextureNode->pTexResView11 ); // Sort depth back to front @@ -1144,31 +652,29 @@ HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) // m_nCaptionHeight, so adjust the rect higher // here to negate the effect. RECT rc = { 0, -m_nCaptionHeight, m_width, 0 }; - DrawSprite11( &m_CapElement, &rc, 0.99f ); + DrawSprite( &m_CapElement, &rc, 0.99f ); rc.left += 5; // Make a left margin WCHAR wszOutput[256]; wcscpy_s( wszOutput, 256, m_wszCaption ); if( m_bMinimized ) wcscat_s( wszOutput, 256, L" (Minimized)" ); - DrawText11( pd3dDevice, pd3dDeviceContext, wszOutput, &m_CapElement, &rc, true ); + DrawText( wszOutput, &m_CapElement, &rc, true ); } // If the dialog is minimized, skip rendering // its controls. if( !m_bMinimized ) { - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - // Focused control is drawn last - if( pControl == s_pControlFocus ) + if( *it == s_pControlFocus ) continue; - pControl->Render( fElapsedTime ); + (*it)->Render( fElapsedTime ); } - if( s_pControlFocus != NULL && s_pControlFocus->m_pDialog == this ) + if( s_pControlFocus && s_pControlFocus->m_pDialog == this ) s_pControlFocus->Render( fElapsedTime ); } @@ -1183,11 +689,13 @@ HRESULT CDXUTDialog::OnRender11( float fElapsedTime ) return S_OK; } + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ VOID CDXUTDialog::SendEvent( UINT nEvent, bool bTriggeredByUser, CDXUTControl* pControl ) { // If no callback has been registered there's nowhere to send the event to - if( m_pCallbackEvent == NULL ) + if( !m_pCallbackEvent ) return; // Discard events triggered programatically if these types of events haven't been @@ -1200,223 +708,97 @@ VOID CDXUTDialog::SendEvent( UINT nEvent, bool bTriggeredByUser, CDXUTControl* p //-------------------------------------------------------------------------------------- -int CDXUTDialogResourceManager::AddFont( LPCWSTR strFaceName, LONG height, LONG weight ) -{ - // See if this font already exists - for( int i = 0; i < m_FontCache.GetSize(); i++ ) - { - DXUTFontNode* pFontNode = m_FontCache.GetAt( i ); - size_t nLen = 0; - nLen = wcsnlen( strFaceName, MAX_PATH); - if( 0 == _wcsnicmp( pFontNode->strFace, strFaceName, nLen ) && - pFontNode->nHeight == height && - pFontNode->nWeight == weight ) - { - return i; - } - } - - // Add a new font and try to create it - DXUTFontNode* pNewFontNode = new DXUTFontNode; - if( pNewFontNode == NULL ) - return -1; - - ZeroMemory( pNewFontNode, sizeof( DXUTFontNode ) ); - wcscpy_s( pNewFontNode->strFace, MAX_PATH, strFaceName ); - pNewFontNode->nHeight = height; - pNewFontNode->nWeight = weight; - m_FontCache.Add( pNewFontNode ); - - int iFont = m_FontCache.GetSize() - 1; - - // If a device is available, try to create immediately - if( m_pd3d9Device ) - CreateFont9( iFont ); - - return iFont; -} - - -//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::SetFont( UINT index, LPCWSTR strFaceName, LONG height, LONG weight ) { // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix call CDXUTDialog::Init() first. See comments for details." ); + assert( m_pManager && L"To fix call CDXUTDialog::Init() first. See comments for details." ); + _Analysis_assume_( m_pManager ); // Make sure the list is at least as large as the index being set - UINT i; - for( i = m_Fonts.GetSize(); i <= index; i++ ) + for( size_t i = m_Fonts.size(); i <= index; i++ ) { - m_Fonts.Add( -1 ); + m_Fonts.push_back( -1 ); } int iFont = m_pManager->AddFont( strFaceName, height, weight ); - m_Fonts.SetAt( index, iFont ); + m_Fonts[ index ] = iFont; return S_OK; } //-------------------------------------------------------------------------------------- -DXUTFontNode* CDXUTDialog::GetFont( UINT index ) -{ - if( NULL == m_pManager ) - return NULL; - return m_pManager->GetFontNode( m_Fonts.GetAt( index ) ); -} - - -//-------------------------------------------------------------------------------------- -int CDXUTDialogResourceManager::AddTexture( LPCWSTR strFilename ) +DXUTFontNode* CDXUTDialog::GetFont( _In_ UINT index ) const { - // See if this texture already exists - for( int i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - size_t nLen = 0; - nLen = wcsnlen( strFilename, MAX_PATH); - if( pTextureNode->bFileSource && // Sources must match - 0 == _wcsnicmp( pTextureNode->strFilename, strFilename, nLen ) ) - { - return i; - } - } - - // Add a new texture and try to create it - DXUTTextureNode* pNewTextureNode = new DXUTTextureNode; - if( pNewTextureNode == NULL ) - return -1; - - ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); - pNewTextureNode->bFileSource = true; - wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strFilename ); - - m_TextureCache.Add( pNewTextureNode ); - - int iTexture = m_TextureCache.GetSize() - 1; - - // If a device is available, try to create immediately - if( m_pd3d9Device ) - CreateTexture9( iTexture ); - - return iTexture; -} - - -//-------------------------------------------------------------------------------------- -int CDXUTDialogResourceManager::AddTexture( LPCWSTR strResourceName, HMODULE hResourceModule ) -{ - // See if this texture already exists - for( int i = 0; i < m_TextureCache.GetSize(); i++ ) - { - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( i ); - if( !pTextureNode->bFileSource && // Sources must match - pTextureNode->hResourceModule == hResourceModule ) // Module handles must match - { - if( IS_INTRESOURCE( strResourceName ) ) - { - // Integer-based ID - if( ( INT_PTR )strResourceName == pTextureNode->nResourceID ) - return i; - } - else - { - // String-based ID - size_t nLen = 0; - nLen = wcsnlen ( strResourceName, MAX_PATH ); - if( 0 == _wcsnicmp( pTextureNode->strFilename, strResourceName, nLen ) ) - return i; - } - } - } - - // Add a new texture and try to create it - DXUTTextureNode* pNewTextureNode = new DXUTTextureNode; - if( pNewTextureNode == NULL ) - return -1; - - ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); - pNewTextureNode->hResourceModule = hResourceModule; - if( IS_INTRESOURCE( strResourceName ) ) - { - pNewTextureNode->nResourceID = ( int )( size_t )strResourceName; - } - else - { - pNewTextureNode->nResourceID = 0; - wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strResourceName ); - } - - m_TextureCache.Add( pNewTextureNode ); - - int iTexture = m_TextureCache.GetSize() - 1; - - // If a device is available, try to create immediately - if( m_pd3d9Device ) - CreateTexture9( iTexture ); - - return iTexture; + if( !m_pManager ) + return nullptr; + return m_pManager->GetFontNode( m_Fonts[ index ] ); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::SetTexture( UINT index, LPCWSTR strFilename ) { // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); + assert( m_pManager && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); + _Analysis_assume_( m_pManager ); // Make sure the list is at least as large as the index being set - for( UINT i = m_Textures.GetSize(); i <= index; i++ ) + for( size_t i = m_Textures.size(); i <= index; i++ ) { - m_Textures.Add( -1 ); + m_Textures.push_back( -1 ); } int iTexture = m_pManager->AddTexture( strFilename ); - m_Textures.SetAt( index, iTexture ); + m_Textures[ index] = iTexture; return S_OK; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::SetTexture( UINT index, LPCWSTR strResourceName, HMODULE hResourceModule ) { // If this assert triggers, you need to call CDXUTDialog::Init() first. This change - // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The - // creation and interfacing with CDXUTDialogResourceManager is now the responsibility + // was made so that the DXUT's GUI could become seperate and optional from DXUT's core. The + // creation and interfacing with CDXUTDialogResourceManager is now the responsibility // of the application if it wishes to use DXUT's GUI. - assert( m_pManager != NULL && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); + assert( m_pManager && L"To fix this, call CDXUTDialog::Init() first. See comments for details." ); + _Analysis_assume_( m_pManager ); // Make sure the list is at least as large as the index being set - for( UINT i = m_Textures.GetSize(); i <= index; i++ ) + for( size_t i = m_Textures.size(); i <= index; i++ ) { - m_Textures.Add( -1 ); + m_Textures.push_back( -1 ); } int iTexture = m_pManager->AddTexture( strResourceName, hResourceModule ); - m_Textures.SetAt( index, iTexture ); + m_Textures[ index ] = iTexture; return S_OK; } //-------------------------------------------------------------------------------------- -DXUTTextureNode* CDXUTDialog::GetTexture( UINT index ) +DXUTTextureNode* CDXUTDialog::GetTexture( _In_ UINT index ) const { - if( NULL == m_pManager ) - return NULL; - return m_pManager->GetTextureNode( m_Textures.GetAt( index ) ); + if( !m_pManager ) + return nullptr; + return m_pManager->GetTextureNode( m_Textures[ index ] ); } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { bool bHandled = false; @@ -1526,6 +908,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) if( s_pControlFocus && s_pControlFocus->m_pDialog == this && s_pControlFocus->GetEnabled() ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { if( s_pControlFocus->HandleKeyboard( uMsg, wParam, lParam ) ) return true; @@ -1538,12 +921,11 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) ( s_pControlFocus->GetType() != DXUT_CONTROL_EDITBOX && s_pControlFocus->GetType() != DXUT_CONTROL_IMEEDITBOX ) ) ) { - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.begin(); it != m_Controls.end(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - if( pControl->GetHotkey() == wParam ) + if( (*it)->GetHotkey() == wParam ) { - pControl->OnHotkey(); + (*it)->OnHotkey(); return true; } } @@ -1560,7 +942,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { case VK_RIGHT: case VK_DOWN: - if( s_pControlFocus != NULL ) + if( s_pControlFocus ) { return OnCycleFocus( true ); } @@ -1568,7 +950,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) case VK_LEFT: case VK_UP: - if( s_pControlFocus != NULL ) + if( s_pControlFocus ) { return OnCycleFocus( false ); } @@ -1602,7 +984,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) case WM_XBUTTONDBLCLK: case WM_MOUSEWHEEL: { - // If not accepting mouse input, return false to indicate the message should still + // If not accepting mouse input, return false to indicate the message should still // be handled by the application (usually to move the camera). if( !m_bMouseInput ) return false; @@ -1629,8 +1011,8 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) } // Not yet handled, see if the mouse is over any controls - CDXUTControl* pControl = GetControlAtPoint( mousePoint ); - if( pControl != NULL && pControl->GetEnabled() ) + auto pControl = GetControlAtPoint( mousePoint ); + if( pControl && pControl->GetEnabled() ) { bHandled = pControl->HandleMouse( uMsg, mousePoint, wParam, lParam ); if( bHandled ) @@ -1645,7 +1027,7 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) s_pControlFocus->m_pDialog == this ) { s_pControlFocus->OnFocusOut(); - s_pControlFocus = NULL; + s_pControlFocus = nullptr; } } @@ -1676,16 +1058,15 @@ bool CDXUTDialog::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) return false; } + //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetControlAtPoint( POINT pt ) +CDXUTControl* CDXUTDialog::GetControlAtPoint( _In_ const POINT& pt ) const { // Search through all child controls for the first one which // contains the mouse point - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl == NULL ) + if( !*it ) { continue; } @@ -1693,21 +1074,21 @@ CDXUTControl* CDXUTDialog::GetControlAtPoint( POINT pt ) // We only return the current control if it is visible // and enabled. Because GetControlAtPoint() is used to do mouse // hittest, it makes sense to perform this filtering. - if( pControl->ContainsPoint( pt ) && pControl->GetEnabled() && pControl->GetVisible() ) + if( (*it)->ContainsPoint( pt ) && (*it)->GetEnabled() && (*it)->GetVisible() ) { - return pControl; + return *it; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -bool CDXUTDialog::GetControlEnabled( int ID ) +bool CDXUTDialog::GetControlEnabled( _In_ int ID ) const { - CDXUTControl* pControl = GetControl( ID ); - if( pControl == NULL ) + auto pControl = GetControl( ID ); + if( !pControl ) return false; return pControl->GetEnabled(); @@ -1716,10 +1097,10 @@ bool CDXUTDialog::GetControlEnabled( int ID ) //-------------------------------------------------------------------------------------- -void CDXUTDialog::SetControlEnabled( int ID, bool bEnabled ) +void CDXUTDialog::SetControlEnabled( _In_ int ID, _In_ bool bEnabled ) { - CDXUTControl* pControl = GetControl( ID ); - if( pControl == NULL ) + auto pControl = GetControl( ID ); + if( !pControl ) return; pControl->SetEnabled( bEnabled ); @@ -1727,18 +1108,19 @@ void CDXUTDialog::SetControlEnabled( int ID, bool bEnabled ) //-------------------------------------------------------------------------------------- -void CDXUTDialog::OnMouseUp( POINT pt ) +void CDXUTDialog::OnMouseUp( _In_ const POINT& pt ) { - s_pControlPressed = NULL; - m_pControlMouseOver = NULL; + UNREFERENCED_PARAMETER(pt); + s_pControlPressed = nullptr; + m_pControlMouseOver = nullptr; } //-------------------------------------------------------------------------------------- -void CDXUTDialog::OnMouseMove( POINT pt ) +void CDXUTDialog::OnMouseMove( _In_ const POINT& pt ) { // Figure out which control the mouse is over now - CDXUTControl* pControl = GetControlAtPoint( pt ); + auto pControl = GetControlAtPoint( pt ); // If the mouse is still over the same control, nothing needs to be done if( pControl == m_pControlMouseOver ) @@ -1750,77 +1132,72 @@ void CDXUTDialog::OnMouseMove( POINT pt ) // Handle mouse entering the new control m_pControlMouseOver = pControl; - if( pControl != NULL ) + if( pControl ) m_pControlMouseOver->OnMouseEnter(); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::SetDefaultElement( UINT nControlType, UINT iElement, CDXUTElement* pElement ) { // If this Element type already exist in the list, simply update the stored Element - for( int i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.begin(); it != m_DefaultElements.end(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - - if( pElementHolder->nControlType == nControlType && - pElementHolder->iElement == iElement ) + if( (*it)->nControlType == nControlType && + (*it)->iElement == iElement ) { - pElementHolder->Element = *pElement; + (*it)->Element = *pElement; return S_OK; } } // Otherwise, add a new entry DXUTElementHolder* pNewHolder; - pNewHolder = new DXUTElementHolder; - if( pNewHolder == NULL ) + pNewHolder = new (std::nothrow) DXUTElementHolder; + if( !pNewHolder ) return E_OUTOFMEMORY; pNewHolder->nControlType = nControlType; pNewHolder->iElement = iElement; pNewHolder->Element = *pElement; - HRESULT hr = m_DefaultElements.Add( pNewHolder ); - if( FAILED( hr ) ) - { - delete pNewHolder; - } - return hr; + m_DefaultElements.push_back( pNewHolder ); + + return S_OK; } //-------------------------------------------------------------------------------------- -CDXUTElement* CDXUTDialog::GetDefaultElement( UINT nControlType, UINT iElement ) +_Use_decl_annotations_ +CDXUTElement* CDXUTDialog::GetDefaultElement( UINT nControlType, UINT iElement ) const { - for( int i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.cbegin(); it != m_DefaultElements.cend(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - - if( pElementHolder->nControlType == nControlType && - pElementHolder->iElement == iElement ) + if( (*it)->nControlType == nControlType && + (*it)->iElement == iElement ) { - return &pElementHolder->Element; + return &(*it)->Element; } } - return NULL; + return nullptr; } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddStatic( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault, CDXUTStatic** ppCreated ) { HRESULT hr = S_OK; - CDXUTStatic* pStatic = new CDXUTStatic( this ); + auto pStatic = new (std::nothrow) CDXUTStatic( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pStatic; - if( pStatic == NULL ) + if( !pStatic ) return E_OUTOFMEMORY; hr = AddControl( pStatic ); @@ -1839,17 +1216,18 @@ HRESULT CDXUTDialog::AddStatic( int ID, LPCWSTR strText, int x, int y, int width //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddButton( int ID, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey, bool bIsDefault, CDXUTButton** ppCreated ) { HRESULT hr = S_OK; - CDXUTButton* pButton = new CDXUTButton( this ); + auto pButton = new (std::nothrow) CDXUTButton( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pButton; - if( pButton == NULL ) + if( !pButton ) return E_OUTOFMEMORY; hr = AddControl( pButton ); @@ -1867,17 +1245,19 @@ HRESULT CDXUTDialog::AddButton( int ID, LPCWSTR strText, int x, int y, int width return S_OK; } +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddButtonCallback(std::function<void()> cb, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey, - bool bIsDefault, CDXUTButton** ppCreated) + bool bIsDefault, CDXUTButton** ppCreated) { HRESULT hr = S_OK; - CDXUTButton* pButton = new CDXUTButton(this); + auto pButton = new (std::nothrow) CDXUTButton(this); - if (ppCreated != NULL) + if (ppCreated) *ppCreated = pButton; - if (pButton == NULL) + if (!pButton) return E_OUTOFMEMORY; hr = AddControl(pButton); @@ -1896,18 +1276,20 @@ HRESULT CDXUTDialog::AddButtonCallback(std::function<void()> cb, LPCWSTR strText return S_OK; } + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddCheckBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bChecked, UINT nHotkey, bool bIsDefault, CDXUTCheckBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTCheckBox* pCheckBox = new CDXUTCheckBox( this ); + auto pCheckBox = new (std::nothrow) CDXUTCheckBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pCheckBox; - if( pCheckBox == NULL ) + if( !pCheckBox ) return E_OUTOFMEMORY; hr = AddControl( pCheckBox ); @@ -1927,19 +1309,19 @@ HRESULT CDXUTDialog::AddCheckBox( int ID, LPCWSTR strText, int x, int y, int wid } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddRadioButton( int ID, UINT nButtonGroup, LPCWSTR strText, int x, int y, int width, int height, bool bChecked, UINT nHotkey, bool bIsDefault, CDXUTRadioButton** ppCreated ) { HRESULT hr = S_OK; - CDXUTRadioButton* pRadioButton = new CDXUTRadioButton( this ); + auto pRadioButton = new (std::nothrow) CDXUTRadioButton( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pRadioButton; - if( pRadioButton == NULL ) + if( !pRadioButton ) return E_OUTOFMEMORY; hr = AddControl( pRadioButton ); @@ -1961,20 +1343,19 @@ HRESULT CDXUTDialog::AddRadioButton( int ID, UINT nButtonGroup, LPCWSTR strText, } - - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddComboBox( int ID, int x, int y, int width, int height, UINT nHotkey, bool bIsDefault, CDXUTComboBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTComboBox* pComboBox = new CDXUTComboBox( this ); + auto pComboBox = new (std::nothrow) CDXUTComboBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pComboBox; - if( pComboBox == NULL ) + if( !pComboBox ) return E_OUTOFMEMORY; hr = AddControl( pComboBox ); @@ -1992,19 +1373,19 @@ HRESULT CDXUTDialog::AddComboBox( int ID, int x, int y, int width, int height, U } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddSlider( int ID, int x, int y, int width, int height, int min, int max, int value, bool bIsDefault, CDXUTSlider** ppCreated ) { HRESULT hr = S_OK; - CDXUTSlider* pSlider = new CDXUTSlider( this ); + auto pSlider = new (std::nothrow) CDXUTSlider( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pSlider; - if( pSlider == NULL ) + if( !pSlider ) return E_OUTOFMEMORY; hr = AddControl( pSlider ); @@ -2024,19 +1405,19 @@ HRESULT CDXUTDialog::AddSlider( int ID, int x, int y, int width, int height, int } - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddEditBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault, CDXUTEditBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTEditBox* pEditBox = new CDXUTEditBox( this ); + auto pEditBox = new (std::nothrow) CDXUTEditBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pEditBox; - if( pEditBox == NULL ) + if( !pEditBox ) return E_OUTOFMEMORY; hr = AddControl( pEditBox ); @@ -2057,15 +1438,16 @@ HRESULT CDXUTDialog::AddEditBox( int ID, LPCWSTR strText, int x, int y, int widt //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTDialog::AddListBox( int ID, int x, int y, int width, int height, DWORD dwStyle, CDXUTListBox** ppCreated ) { HRESULT hr = S_OK; - CDXUTListBox* pListBox = new CDXUTListBox( this ); + auto pListBox = new (std::nothrow) CDXUTListBox( this ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pListBox; - if( pListBox == NULL ) + if( !pListBox ) return E_OUTOFMEMORY; hr = AddControl( pListBox ); @@ -2082,23 +1464,21 @@ HRESULT CDXUTDialog::AddListBox( int ID, int x, int y, int width, int height, DW } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::InitControl( CDXUTControl* pControl ) +HRESULT CDXUTDialog::InitControl( _In_ CDXUTControl* pControl ) { HRESULT hr; - if( pControl == NULL ) + if( !pControl ) return E_INVALIDARG; - pControl->m_Index = m_Controls.GetSize(); + pControl->m_Index = static_cast<UINT>( m_Controls.size() ); // Look for a default Element entries - for( int i = 0; i < m_DefaultElements.GetSize(); i++ ) + for( auto it = m_DefaultElements.begin(); it != m_DefaultElements.end(); ++it ) { - DXUTElementHolder* pElementHolder = m_DefaultElements.GetAt( i ); - if( pElementHolder->nControlType == pControl->GetType() ) - pControl->SetElement( pElementHolder->iElement, &pElementHolder->Element ); + if( (*it)->nControlType == pControl->GetType() ) + pControl->SetElement( (*it)->iElement, &(*it)->Element ); } V_RETURN( pControl->OnInit() ); @@ -2107,9 +1487,8 @@ HRESULT CDXUTDialog::InitControl( CDXUTControl* pControl ) } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::AddControl( CDXUTControl* pControl ) +HRESULT CDXUTDialog::AddControl( _In_ CDXUTControl* pControl ) { HRESULT hr = S_OK; @@ -2118,81 +1497,72 @@ HRESULT CDXUTDialog::AddControl( CDXUTControl* pControl ) return DXTRACE_ERR( L"CDXUTDialog::InitControl", hr ); // Add to the list - hr = m_Controls.Add( pControl ); - if( FAILED( hr ) ) - { - return DXTRACE_ERR( L"CGrowableArray::Add", hr ); - } + m_Controls.push_back( pControl ); return S_OK; } //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetControl( int ID ) +CDXUTControl* CDXUTDialog::GetControl( _In_ int ID ) const { // Try to find the control with the given ID - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl->GetID() == ID ) + if( (*it)->GetID() == ID ) { - return pControl; + return *it; } } // Not found - return NULL; + return nullptr; } - //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetControl( int ID, UINT nControlType ) +CDXUTControl* CDXUTDialog::GetControl( _In_ int ID, _In_ UINT nControlType ) const { // Try to find the control with the given ID - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl->GetID() == ID && pControl->GetType() == nControlType ) + if( (*it)->GetID() == ID && (*it)->GetType() == nControlType ) { - return pControl; + return *it; } } // Not found - return NULL; + return nullptr; } - //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetNextControl( CDXUTControl* pControl ) +CDXUTControl* CDXUTDialog::GetNextControl( _In_ CDXUTControl* pControl ) { int index = pControl->m_Index + 1; - CDXUTDialog* pDialog = pControl->m_pDialog; + auto pDialog = pControl->m_pDialog; // Cycle through dialogs in the loop to find the next control. Note // that if only one control exists in all looped dialogs it will // be the returned 'next' control. - while( index >= ( int )pDialog->m_Controls.GetSize() ) + while( index >= ( int )pDialog->m_Controls.size() ) { pDialog = pDialog->m_pNextDialog; index = 0; } - return pDialog->m_Controls.GetAt( index ); + return pDialog->m_Controls[ index ]; } + //-------------------------------------------------------------------------------------- -CDXUTControl* CDXUTDialog::GetPrevControl( CDXUTControl* pControl ) +CDXUTControl* CDXUTDialog::GetPrevControl( _In_ CDXUTControl* pControl ) { int index = pControl->m_Index - 1; - CDXUTDialog* pDialog = pControl->m_pDialog; + auto pDialog = pControl->m_pDialog; // Cycle through dialogs in the loop to find the next control. Note // that if only one control exists in all looped dialogs it will @@ -2200,27 +1570,25 @@ CDXUTControl* CDXUTDialog::GetPrevControl( CDXUTControl* pControl ) while( index < 0 ) { pDialog = pDialog->m_pPrevDialog; - if( pDialog == NULL ) + if( !pDialog ) pDialog = pControl->m_pDialog; - index = pDialog->m_Controls.GetSize() - 1; + index = int( pDialog->m_Controls.size() ) - 1; } - return pDialog->m_Controls.GetAt( index ); + return pDialog->m_Controls[ index ]; } //-------------------------------------------------------------------------------------- -void CDXUTDialog::ClearRadioButtonGroup( UINT nButtonGroup ) +void CDXUTDialog::ClearRadioButtonGroup( _In_ UINT nButtonGroup ) { // Find all radio buttons with the given group number - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - - if( pControl->GetType() == DXUT_CONTROL_RADIOBUTTON ) + if( (*it)->GetType() == DXUT_CONTROL_RADIOBUTTON ) { - CDXUTRadioButton* pRadioButton = ( CDXUTRadioButton* )pControl; + auto pRadioButton = ( CDXUTRadioButton* )*it; if( pRadioButton->GetButtonGroup() == nButtonGroup ) pRadioButton->SetChecked( false, false ); @@ -2229,22 +1597,19 @@ void CDXUTDialog::ClearRadioButtonGroup( UINT nButtonGroup ) } - //-------------------------------------------------------------------------------------- -void CDXUTDialog::ClearComboBox( int ID ) +void CDXUTDialog::ClearComboBox( _In_ int ID ) { - CDXUTComboBox* pComboBox = GetComboBox( ID ); - if( pComboBox == NULL ) + auto pComboBox = GetComboBox( ID ); + if( !pComboBox ) return; pComboBox->RemoveAllItems(); } - - //-------------------------------------------------------------------------------------- -void CDXUTDialog::RequestFocus( CDXUTControl* pControl ) +void CDXUTDialog::RequestFocus( _In_ CDXUTControl* pControl ) { if( s_pControlFocus == pControl ) return; @@ -2261,156 +1626,22 @@ void CDXUTDialog::RequestFocus( CDXUTControl* pControl ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawRect( RECT* pRect, D3DCOLOR color ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::DrawRect( const RECT* pRect, DWORD color ) { - if( m_pManager->GetD3D9Device() ) - return DrawRect9( pRect, color ); + UNREFERENCED_PARAMETER(pRect); + UNREFERENCED_PARAMETER(color); + // TODO - return E_FAIL; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawRect9( RECT* pRect, D3DCOLOR color ) -{ - RECT rcScreen = *pRect; - OffsetRect( &rcScreen, m_x, m_y ); - - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - - DXUT_SCREEN_VERTEX vertices[4] = - { - ( float )rcScreen.left - 0.5f, ( float )rcScreen.top - 0.5f, 0.5f, 1.0f, color, 0, 0, - ( float )rcScreen.right - 0.5f, ( float )rcScreen.top - 0.5f, 0.5f, 1.0f, color, 0, 0, - ( float )rcScreen.right - 0.5f, ( float )rcScreen.bottom - 0.5f, 0.5f, 1.0f, color, 0, 0, - ( float )rcScreen.left - 0.5f, ( float )rcScreen.bottom - 0.5f, 0.5f, 1.0f, color, 0, 0, - }; - - IDirect3DDevice9* pd3dDevice = m_pManager->GetD3D9Device(); - - // Since we're doing our own drawing here we need to flush the sprites - m_pManager->m_pSprite->Flush(); - IDirect3DVertexDeclaration9* pDecl = NULL; - pd3dDevice->GetVertexDeclaration( &pDecl ); // Preserve the sprite's current vertex decl - pd3dDevice->SetFVF( DXUT_SCREEN_VERTEX::FVF ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 ); - - pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices, sizeof( DXUT_SCREEN_VERTEX ) ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - - // Restore the vertex decl - pd3dDevice->SetVertexDeclaration( pDecl ); - pDecl->Release(); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawPolyLine( POINT* apPoints, UINT nNumPoints, D3DCOLOR color ) -{ - DXUT_SCREEN_VERTEX* vertices = new DXUT_SCREEN_VERTEX[ nNumPoints ]; - if( vertices == NULL ) - return E_OUTOFMEMORY; - - DXUT_SCREEN_VERTEX* pVertex = vertices; - POINT* pt = apPoints; - for( UINT i = 0; i < nNumPoints; i++ ) - { - pVertex->x = m_x + ( float )pt->x; - pVertex->y = m_y + ( float )pt->y; - pVertex->z = 0.5f; - pVertex->h = 1.0f; - pVertex->color = color; - pVertex->tu = 0.0f; - pVertex->tv = 0.0f; - - pVertex++; - pt++; - } - - IDirect3DDevice9* pd3dDevice = m_pManager->GetD3D9Device(); - - // Since we're doing our own drawing here we need to flush the sprites - m_pManager->m_pSprite->Flush(); - IDirect3DVertexDeclaration9* pDecl = NULL; - pd3dDevice->GetVertexDeclaration( &pDecl ); // Preserve the sprite's current vertex decl - pd3dDevice->SetFVF( DXUT_SCREEN_VERTEX::FVF ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG2 ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2 ); - - pd3dDevice->DrawPrimitiveUP( D3DPT_LINESTRIP, nNumPoints - 1, vertices, sizeof( DXUT_SCREEN_VERTEX ) ); - - pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - - // Restore the vertex decl - pd3dDevice->SetVertexDeclaration( pDecl ); - pDecl->Release(); - - SAFE_DELETE_ARRAY( vertices ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawSprite( CDXUTElement* pElement, RECT* prcDest, float fDepth ) -{ - if( m_pManager->GetD3D9Device() ) - return DrawSprite9( pElement, prcDest ); - else - return DrawSprite11( pElement, prcDest, fDepth ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawSprite9( CDXUTElement* pElement, RECT* prcDest ) -{ - // No need to draw fully transparent layers - if( pElement->TextureColor.Current.a == 0 ) - return S_OK; - - RECT rcTexture = pElement->rcTexture; - - RECT rcScreen = *prcDest; - OffsetRect( &rcScreen, m_x, m_y ); - - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - - DXUTTextureNode* pTextureNode = GetTexture( pElement->iTexture ); - if( pTextureNode == NULL ) - return E_FAIL; - - float fScaleX = ( float )RectWidth( rcScreen ) / RectWidth( rcTexture ); - float fScaleY = ( float )RectHeight( rcScreen ) / RectHeight( rcTexture ); - - D3DXMATRIXA16 matTransform; - D3DXMatrixScaling( &matTransform, fScaleX, fScaleY, 1.0f ); - - m_pManager->m_pSprite->SetTransform( &matTransform ); - - D3DXVECTOR3 vPos( ( float )rcScreen.left, ( float )rcScreen.top, 0.0f ); - - vPos.x /= fScaleX; - vPos.y /= fScaleY; - - return m_pManager->m_pSprite->Draw( pTextureNode->pTexture9, &rcTexture, NULL, &vPos, - pElement->TextureColor.Current ); -} - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float fDepth ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::DrawSprite( CDXUTElement* pElement, const RECT* prcDest, float fDepth ) { // No need to draw fully transparent layers - if( pElement->TextureColor.Current.a == 0 ) + if( pElement->TextureColor.Current.w == 0 ) return S_OK; RECT rcTexture = pElement->rcTexture; @@ -2422,8 +1653,8 @@ HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float if( m_bCaption ) OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - DXUTTextureNode* pTextureNode = GetTexture( pElement->iTexture ); - if( pTextureNode == NULL ) + auto pTextureNode = GetTexture( pElement->iTexture ); + if( !pTextureNode ) return E_FAIL; float fBBWidth = ( float )m_pManager->m_nBackBufferWidth; @@ -2440,46 +1671,46 @@ HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float fRectTop = fRectTop * 2.0f - 1.0f; fRectRight = fRectRight * 2.0f - 1.0f; fRectBottom = fRectBottom * 2.0f - 1.0f; - + float fTexLeft = rcTexture.left / fTexWidth; float fTexTop = rcTexture.top / fTexHeight; float fTexRight = rcTexture.right / fTexWidth; float fTexBottom = rcTexture.bottom / fTexHeight; // Add 6 sprite vertices - DXUTSpriteVertex SpriteVertex; + DXUTSpriteVertex SpriteVertex = {}; // tri1 - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexTop ); + SpriteVertex.vPos = XMFLOAT3( fRectLeft, fRectTop, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexLeft, fTexTop ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); + SpriteVertex.vPos = XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexRight, fTexTop ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); + SpriteVertex.vPos = XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexLeft, fTexBottom ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); // tri2 - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); + SpriteVertex.vPos = XMFLOAT3( fRectRight, fRectTop, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexRight, fTexTop ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexBottom ); + SpriteVertex.vPos = XMFLOAT3( fRectRight, fRectBottom, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexRight, fTexBottom ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); + SpriteVertex.vPos = XMFLOAT3( fRectLeft, fRectBottom, fDepth ); + SpriteVertex.vTex = XMFLOAT2( fTexLeft, fTexBottom ); SpriteVertex.vColor = pElement->TextureColor.Current; - m_pManager->m_SpriteVertices.Add( SpriteVertex ); + m_pManager->m_SpriteVertices.push_back( SpriteVertex ); // Why are we drawing the sprite every time? This is very inefficient, but the sprite workaround doesn't have support for sorting now, so we have to // draw a sprite every time to keep the order correct between sprites and text. @@ -2490,298 +1721,28 @@ HRESULT CDXUTDialog::DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::CalcTextRect( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, int nCount ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::CalcTextRect( LPCWSTR strText, CDXUTElement* pElement, const RECT* prcDest, int nCount ) { - HRESULT hr = S_OK; - - DXUTFontNode* pFontNode = GetFont( pElement->iFont ); - if( pFontNode == NULL ) + auto pFontNode = GetFont( pElement->iFont ); + if( !pFontNode ) return E_FAIL; - DWORD dwTextFormat = pElement->dwTextFormat | DT_CALCRECT; - // Since we are only computing the rectangle, we don't need a sprite. - if( pFontNode->pFont9 ) - { - hr = pFontNode->pFont9->DrawText( NULL, strText, nCount, prcDest, dwTextFormat, pElement->FontColor.Current ); - if( FAILED( hr ) ) - return hr; - } - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawText( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow, int nCount, bool bCenter ) -{ - if( m_pManager->GetD3D9Device() ) - return DrawText9( strText, pElement, prcDest, bShadow, nCount ); - else - return DrawText11( m_pManager->GetD3D11Device(), m_pManager->GetD3D11DeviceContext(), strText, pElement, prcDest, bShadow, nCount, bCenter ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawText9( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow, int nCount ) -{ - HRESULT hr = S_OK; - - // No need to draw fully transparent layers - if( pElement->FontColor.Current.a == 0 ) - return S_OK; - - RECT rcScreen = *prcDest; - OffsetRect( &rcScreen, m_x, m_y ); - - // If caption is enabled, offset the Y position by its height. - if( m_bCaption ) - OffsetRect( &rcScreen, 0, m_nCaptionHeight ); - - D3DXMATRIX matTransform; - D3DXMatrixIdentity( &matTransform ); - m_pManager->m_pSprite->SetTransform( &matTransform ); - - DXUTFontNode* pFontNode = GetFont( pElement->iFont ); - - if( bShadow ) - { - RECT rcShadow = rcScreen; - OffsetRect( &rcShadow, 1, 1 ); - hr = pFontNode->pFont9->DrawText( m_pManager->m_pSprite, strText, nCount, &rcShadow, pElement->dwTextFormat, - D3DCOLOR_ARGB( DWORD( pElement->FontColor.Current.a * 255 ), 0, 0, 0 ) ); - if( FAILED( hr ) ) - return hr; - } - - hr = pFontNode->pFont9->DrawText( m_pManager->m_pSprite, strText, nCount, &rcScreen, pElement->dwTextFormat, - pElement->FontColor.Current ); - if( FAILED( hr ) ) - return hr; + UNREFERENCED_PARAMETER(strText); + UNREFERENCED_PARAMETER(prcDest); + UNREFERENCED_PARAMETER(nCount); + // TODO - return S_OK; } -ID3D11Buffer* g_pFontBuffer11 = NULL; -UINT g_FontBufferBytes11 = 0; -CGrowableArray<DXUTSpriteVertex> g_FontVertices; -ID3D11ShaderResourceView* g_pFont11 = NULL; -ID3D11InputLayout* g_pInputLayout11 = NULL; -HRESULT InitFont11( ID3D11Device* pd3d11Device, ID3D11InputLayout* pInputLayout ) -{ - HRESULT hr = S_OK; - WCHAR str[MAX_PATH]; - V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"UI\\Font.dds" ) ); - - if (pd3d11Device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0 ) { - - D3DX11_IMAGE_INFO dii; - D3DX11GetImageInfoFromFile( str, NULL, &dii, NULL ); - - D3DX11_IMAGE_LOAD_INFO dili; - dili.BindFlags = D3DX11_DEFAULT; - dili.CpuAccessFlags = D3DX11_DEFAULT; - dili.Depth = D3DX11_DEFAULT; - dili.Filter = D3DX11_DEFAULT; - dili.FirstMipLevel = 0; - dili.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - dili.Height = D3DX11_DEFAULT; - dili.MipFilter = D3DX11_DEFAULT; - dili.MipLevels = 1; - dili.MiscFlags = D3DX11_DEFAULT; - dili.pSrcInfo = &dii; - dili.Usage = D3D11_USAGE_DEFAULT ; - dili.Width = D3DX11_DEFAULT; - - V_RETURN( D3DX11CreateShaderResourceViewFromFile( pd3d11Device, str, &dili, NULL, &g_pFont11, &hr) ); - } - else - { - V_RETURN( D3DX11CreateShaderResourceViewFromFile( pd3d11Device, str, NULL, NULL, &g_pFont11, &hr) ); - } - -#if defined(PROFILE) || defined(DEBUG) - if (g_pFont11) - { - ID3D11Resource *pRes = NULL; - g_pFont11->GetResource( &pRes ); - DXUT_SetDebugName( pRes, "DXUT Text11" ); - SAFE_RELEASE( pRes ); - } - - DXUT_SetDebugName( g_pFont11, "DXUT Text11" ); -#endif - - g_pInputLayout11 = pInputLayout; - return hr; -} - -void EndFont11() -{ - SAFE_RELEASE( g_pFontBuffer11 ); - g_FontBufferBytes11 = 0; - SAFE_RELEASE( g_pFont11 ); -} - -void BeginText11() -{ - g_FontVertices.Reset(); -} - -void DrawText11DXUT( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, RECT rcScreen, D3DXCOLOR vFontColor, - float fBBWidth, float fBBHeight, bool bCenter ) -{ - float fCharTexSizeX = 0.010526315f; - //float fGlyphSizeX = 14.0f / fBBWidth; - //float fGlyphSizeY = 32.0f / fBBHeight; - float fGlyphSizeX = 15.0f / fBBWidth; - float fGlyphSizeY = 42.0f / fBBHeight; - - - float fRectLeft = rcScreen.left / fBBWidth; - float fRectTop = 1.0f - rcScreen.top / fBBHeight; - - fRectLeft = fRectLeft * 2.0f - 1.0f; - fRectTop = fRectTop * 2.0f - 1.0f; - - int NumChars = (int)wcslen( strText ); - if (bCenter) { - float fRectRight = rcScreen.right / fBBWidth; - fRectRight = fRectRight * 2.0f - 1.0f; - float fRectBottom = 1.0f - rcScreen.bottom / fBBHeight; - fRectBottom = fRectBottom * 2.0f - 1.0f; - float fcenterx = ((fRectRight - fRectLeft) - (float)NumChars*fGlyphSizeX) *0.5f; - float fcentery = ((fRectTop - fRectBottom) - (float)1*fGlyphSizeY) *0.5f; - fRectLeft += fcenterx ; - fRectTop -= fcentery; - } - float fOriginalLeft = fRectLeft; - float fTexTop = 0.0f; - float fTexBottom = 1.0f; - - float fDepth = 0.5f; - for( int i=0; i<NumChars; i++ ) - { - if( strText[i] == '\n' ) - { - fRectLeft = fOriginalLeft; - fRectTop -= fGlyphSizeY; - - continue; - } - else if( strText[i] < 32 || strText[i] > 126 ) - { - continue; - } - - // Add 6 sprite vertices - DXUTSpriteVertex SpriteVertex; - float fRectRight = fRectLeft + fGlyphSizeX; - float fRectBottom = fRectTop - fGlyphSizeY; - float fTexLeft = ( strText[i] - 32 ) * fCharTexSizeX; - float fTexRight = fTexLeft + fCharTexSizeX; - - // tri1 - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexTop ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - - // tri2 - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectTop, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexTop ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - - SpriteVertex.vPos = D3DXVECTOR3( fRectRight, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexRight, fTexBottom ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - - SpriteVertex.vPos = D3DXVECTOR3( fRectLeft, fRectBottom, fDepth ); - SpriteVertex.vTex = D3DXVECTOR2( fTexLeft, fTexBottom ); - SpriteVertex.vColor = vFontColor; - g_FontVertices.Add( SpriteVertex ); - - fRectLeft += fGlyphSizeX; - - } - - // We have to end text after every line so that rendering order between sprites and fonts is preserved - EndText11( pd3dDevice, pd3d11DeviceContext ); -} - -void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) -{ - - // ensure our buffer size can hold our sprites - UINT FontDataBytes = g_FontVertices.GetSize() * sizeof( DXUTSpriteVertex ); - if( g_FontBufferBytes11 < FontDataBytes ) - { - SAFE_RELEASE( g_pFontBuffer11 ); - g_FontBufferBytes11 = FontDataBytes; - - D3D11_BUFFER_DESC BufferDesc; - BufferDesc.ByteWidth = g_FontBufferBytes11; - BufferDesc.Usage = D3D11_USAGE_DYNAMIC; - BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - BufferDesc.MiscFlags = 0; - - pd3dDevice->CreateBuffer( &BufferDesc, NULL, &g_pFontBuffer11 ); - DXUT_SetDebugName( g_pFontBuffer11, "DXUT Text11" ); - } - - // Copy the sprites over - D3D11_BOX destRegion; - destRegion.left = 0; - destRegion.right = FontDataBytes; - destRegion.top = 0; - destRegion.bottom = 1; - destRegion.front = 0; - destRegion.back = 1; - D3D11_MAPPED_SUBRESOURCE MappedResource; - if ( S_OK == pd3d11DeviceContext->Map( g_pFontBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) { - CopyMemory( MappedResource.pData, (void*)g_FontVertices.GetData(), FontDataBytes ); - pd3d11DeviceContext->Unmap(g_pFontBuffer11, 0); - } - - ID3D11ShaderResourceView* pOldTexture = NULL; - pd3d11DeviceContext->PSGetShaderResources( 0, 1, &pOldTexture ); - pd3d11DeviceContext->PSSetShaderResources( 0, 1, &g_pFont11 ); - - // Draw - UINT Stride = sizeof( DXUTSpriteVertex ); - UINT Offset = 0; - pd3d11DeviceContext->IASetVertexBuffers( 0, 1, &g_pFontBuffer11, &Stride, &Offset ); - pd3d11DeviceContext->IASetInputLayout( g_pInputLayout11 ); - pd3d11DeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); - pd3d11DeviceContext->Draw( g_FontVertices.GetSize(), 0 ); - - pd3d11DeviceContext->PSSetShaderResources( 0, 1, &pOldTexture ); - SAFE_RELEASE( pOldTexture ); - - g_FontVertices.Reset(); -} //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialog::DrawText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow, int nCount, bool bCenter ) +_Use_decl_annotations_ +HRESULT CDXUTDialog::DrawText( LPCWSTR strText, CDXUTElement* pElement, const RECT* prcDest, bool bShadow, bool bCenter ) { - //HRESULT hr = S_OK; - // No need to draw fully transparent layers - if( pElement->FontColor.Current.a == 0 ) + if( pElement->FontColor.Current.w == 0 ) return S_OK; RECT rcScreen = *prcDest; @@ -2794,19 +1755,22 @@ HRESULT CDXUTDialog::DrawText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* float fBBWidth = ( float )m_pManager->m_nBackBufferWidth; float fBBHeight = ( float )m_pManager->m_nBackBufferHeight; + auto pd3dDevice = m_pManager->GetD3D11Device(); + auto pd3d11DeviceContext = m_pManager->GetD3D11DeviceContext(); + if( bShadow ) { RECT rcShadow = rcScreen; OffsetRect( &rcShadow, 1, 1 ); - D3DXCOLOR vShadowColor( 0,0,0, 1.0f ); + XMFLOAT4 vShadowColor( 0,0,0, 1.0f ); DrawText11DXUT( pd3dDevice, pd3d11DeviceContext, strText, rcShadow, vShadowColor, fBBWidth, fBBHeight, bCenter ); } - D3DXCOLOR vFontColor( pElement->FontColor.Current.r, pElement->FontColor.Current.g, pElement->FontColor.Current.b, 1.0f ); + XMFLOAT4 vFontColor( pElement->FontColor.Current.x, pElement->FontColor.Current.y, pElement->FontColor.Current.z, 1.0f ); DrawText11DXUT( pd3dDevice, pd3d11DeviceContext, strText, rcScreen, vFontColor, fBBWidth, fBBHeight, bCenter ); @@ -2816,8 +1780,9 @@ HRESULT CDXUTDialog::DrawText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* //-------------------------------------------------------------------------------------- -void CDXUTDialog::SetBackgroundColors( D3DCOLOR colorTopLeft, D3DCOLOR colorTopRight, D3DCOLOR colorBottomLeft, - D3DCOLOR colorBottomRight ) +_Use_decl_annotations_ +void CDXUTDialog::SetBackgroundColors( DWORD colorTopLeft, DWORD colorTopRight, DWORD colorBottomLeft, + DWORD colorBottomRight ) { m_colorTopLeft = colorTopLeft; m_colorTopRight = colorTopRight; @@ -2827,9 +1792,9 @@ void CDXUTDialog::SetBackgroundColors( D3DCOLOR colorTopLeft, D3DCOLOR colorTopR //-------------------------------------------------------------------------------------- -void CDXUTDialog::SetNextDialog( CDXUTDialog* pNextDialog ) +void CDXUTDialog::SetNextDialog( _In_ CDXUTDialog* pNextDialog ) { - if( pNextDialog == NULL ) + if( !pNextDialog ) pNextDialog = this; m_pNextDialog = pNextDialog; @@ -2844,7 +1809,7 @@ void CDXUTDialog::ClearFocus() if( s_pControlFocus ) { s_pControlFocus->OnFocusOut(); - s_pControlFocus = NULL; + s_pControlFocus = nullptr; } ReleaseCapture(); @@ -2855,16 +1820,15 @@ void CDXUTDialog::ClearFocus() void CDXUTDialog::FocusDefaultControl() { // Check for default control in this dialog - for( int i = 0; i < m_Controls.GetSize(); i++ ) + for( auto it = m_Controls.cbegin(); it != m_Controls.cend(); ++it ) { - CDXUTControl* pControl = m_Controls.GetAt( i ); - if( pControl->m_bIsDefault ) + if( (*it)->m_bIsDefault ) { // Remove focus from the current control ClearFocus(); // Give focus to the default control - s_pControlFocus = pControl; + s_pControlFocus = *it; s_pControlFocus->OnFocusIn(); return; } @@ -2873,15 +1837,15 @@ void CDXUTDialog::FocusDefaultControl() //-------------------------------------------------------------------------------------- -bool CDXUTDialog::OnCycleFocus( bool bForward ) +bool CDXUTDialog::OnCycleFocus( _In_ bool bForward ) { - CDXUTControl* pControl = NULL; - CDXUTDialog* pDialog = NULL; // pDialog and pLastDialog are used to track wrapping of + CDXUTControl* pControl = nullptr; + CDXUTDialog* pDialog = nullptr; // pDialog and pLastDialog are used to track wrapping of CDXUTDialog* pLastDialog; // focus from first control to last or vice versa. - if( s_pControlFocus == NULL ) + if( !s_pControlFocus ) { - // If s_pControlFocus is NULL, we focus the first control of first dialog in + // If s_pControlFocus is nullptr, we focus the first control of first dialog in // the case that bForward is true, and focus the last control of last dialog when // bForward is false. // @@ -2889,12 +1853,12 @@ bool CDXUTDialog::OnCycleFocus( bool bForward ) { // Search for the first control from the start of the dialog // array. - for( int d = 0; d < m_pManager->m_Dialogs.GetSize(); ++d ) + for( auto it = m_pManager->m_Dialogs.cbegin(); it != m_pManager->m_Dialogs.cend(); ++it ) { - pDialog = pLastDialog = m_pManager->m_Dialogs.GetAt( d ); - if( pDialog && pDialog->m_Controls.GetSize() > 0 ) + pDialog = pLastDialog = *it; + if( pDialog && !pDialog->m_Controls.empty() ) { - pControl = pDialog->m_Controls.GetAt( 0 ); + pControl = pDialog->m_Controls[ 0 ]; break; } } @@ -2910,12 +1874,12 @@ bool CDXUTDialog::OnCycleFocus( bool bForward ) { // Search for the first control from the end of the dialog // array. - for( int d = m_pManager->m_Dialogs.GetSize() - 1; d >= 0; --d ) + for( auto it = m_pManager->m_Dialogs.crbegin(); it != m_pManager->m_Dialogs.crend(); ++it ) { - pDialog = pLastDialog = m_pManager->m_Dialogs.GetAt( d ); - if( pDialog && pDialog->m_Controls.GetSize() > 0 ) + pDialog = pLastDialog = *it; + if( pDialog && !pDialog->m_Controls.empty() ) { - pControl = pDialog->m_Controls.GetAt( pDialog->m_Controls.GetSize() - 1 ); + pControl = pDialog->m_Controls[ pDialog->m_Controls.size() - 1 ]; break; } } @@ -2939,24 +1903,41 @@ bool CDXUTDialog::OnCycleFocus( bool bForward ) { // Focused control belongs to this dialog. Cycle to the // next/previous control. + assert( pControl != 0 ); + _Analysis_assume_( pControl != 0 ); pLastDialog = s_pControlFocus->m_pDialog; pControl = ( bForward ) ? GetNextControl( s_pControlFocus ) : GetPrevControl( s_pControlFocus ); pDialog = pControl->m_pDialog; } + assert( pControl != 0 ); + _Analysis_assume_( pControl != 0 ); + for( int i = 0; i < 0xffff; i++ ) { // If we just wrapped from last control to first or vice versa, - // set the focused control to NULL. This state, where no control + // set the focused control to nullptr. This state, where no control // has focus, allows the camera to work. - int nLastDialogIndex = m_pManager->m_Dialogs.IndexOf( pLastDialog ); - int nDialogIndex = m_pManager->m_Dialogs.IndexOf( pDialog ); + int nLastDialogIndex = -1; + auto fit = std::find( m_pManager->m_Dialogs.cbegin(), m_pManager->m_Dialogs.cend(), pLastDialog ); + if ( fit != m_pManager->m_Dialogs.cend() ) + { + nLastDialogIndex = int( fit - m_pManager->m_Dialogs.begin() ); + } + + int nDialogIndex = -1; + fit = std::find( m_pManager->m_Dialogs.cbegin(), m_pManager->m_Dialogs.cend(), pDialog ); + if ( fit != m_pManager->m_Dialogs.cend() ) + { + nDialogIndex = int( fit - m_pManager->m_Dialogs.begin() ); + } + if( ( !bForward && nLastDialogIndex < nDialogIndex ) || ( bForward && nDialogIndex < nLastDialogIndex ) ) { if( s_pControlFocus ) s_pControlFocus->OnFocusOut(); - s_pControlFocus = NULL; + s_pControlFocus = nullptr; return true; } @@ -2971,6 +1952,7 @@ bool CDXUTDialog::OnCycleFocus( bool bForward ) if( s_pControlFocus ) s_pControlFocus->OnFocusOut(); s_pControlFocus = pControl; + if( s_pControlFocus ) s_pControlFocus->OnFocusIn(); return true; } @@ -2987,198 +1969,6 @@ bool CDXUTDialog::OnCycleFocus( bool bForward ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateFont9( UINT iFont ) -{ - HRESULT hr = S_OK; - - DXUTFontNode* pFontNode = m_FontCache.GetAt( iFont ); - - SAFE_RELEASE( pFontNode->pFont9 ); - - V_RETURN( D3DXCreateFont( m_pd3d9Device, pFontNode->nHeight, 0, pFontNode->nWeight, 1, FALSE, DEFAULT_CHARSET, - OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, - pFontNode->strFace, &pFontNode->pFont9 ) ); - - return S_OK; -} - - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateFont11( UINT iFont ) -{ - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateTexture9( UINT iTexture ) -{ - HRESULT hr = S_OK; - - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( iTexture ); - - - D3DXIMAGE_INFO info; - - if( !pTextureNode->bFileSource ) - { - if( pTextureNode->nResourceID == 0xFFFF && pTextureNode->hResourceModule == ( HMODULE )0xFFFF ) - { - hr = DXUTCreateGUITextureFromInternalArray9( m_pd3d9Device, &pTextureNode->pTexture9, &info ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"D3DXCreateTextureFromFileInMemoryEx", hr ); - DXUT_SetDebugName( pTextureNode->pTexture9, "DXUT GUI Texture" ); - } - else - { - LPCWSTR pID = pTextureNode->nResourceID ? ( LPCWSTR )( size_t )pTextureNode->nResourceID : - pTextureNode->strFilename; - - // Create texture from resource - hr = D3DXCreateTextureFromResourceEx( m_pd3d9Device, pTextureNode->hResourceModule, pID, D3DX_DEFAULT, - D3DX_DEFAULT, - 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, - &info, NULL, &pTextureNode->pTexture9 ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"D3DXCreateTextureFromResourceEx", hr ); - } - } - else - { - // Make sure there's a texture to create - if( pTextureNode->strFilename[0] == 0 ) - return S_OK; - - // Create texture from file - hr = D3DXCreateTextureFromFileEx( m_pd3d9Device, pTextureNode->strFilename, D3DX_DEFAULT, D3DX_DEFAULT, - 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, - &info, NULL, &pTextureNode->pTexture9 ); - if( FAILED( hr ) ) - { - return DXTRACE_ERR( L"D3DXCreateTextureFromFileEx", hr ); - } - } - - // Store dimensions - pTextureNode->dwWidth = info.Width; - pTextureNode->dwHeight = info.Height; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTDialogResourceManager::CreateTexture11( UINT iTexture ) -{ - HRESULT hr = S_OK; - - DXUTTextureNode* pTextureNode = m_TextureCache.GetAt( iTexture ); - - if( !pTextureNode->bFileSource ) - { - if( pTextureNode->nResourceID == 0xFFFF && pTextureNode->hResourceModule == ( HMODULE )0xFFFF ) - { - hr = DXUTCreateGUITextureFromInternalArray11( m_pd3d11Device, &pTextureNode->pTexture11, NULL ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"D3DX11CreateResourceFromFileInMemory", hr ); - DXUT_SetDebugName( pTextureNode->pTexture11, "DXUT GUI Texture" ); - } - //else - //{ - // LPCWSTR pID = pTextureNode->nResourceID ? ( LPCWSTR )( size_t )pTextureNode->nResourceID : - // pTextureNode->strFilename; - - // D3DX10_IMAGE_INFO SrcInfo; - // D3DX10GetImageInfoFromResource( NULL, pID, NULL, &SrcInfo, NULL ); - - // // Create texture from resource - // ID3D10Resource* pRes; - // D3DX10_IMAGE_LOAD_INFO loadInfo; - // loadInfo.Width = D3DX10_DEFAULT; - // loadInfo.Height = D3DX10_DEFAULT; - // loadInfo.Depth = D3DX10_DEFAULT; - // loadInfo.FirstMipLevel = 0; - // loadInfo.MipLevels = 1; - // loadInfo.Usage = D3D10_USAGE_DEFAULT; - // loadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE; - // loadInfo.CpuAccessFlags = 0; - // loadInfo.MiscFlags = 0; - // loadInfo.Format = MAKE_TYPELESS( SrcInfo.Format ); - // loadInfo.Filter = D3DX10_FILTER_NONE; - // loadInfo.MipFilter = D3DX10_FILTER_NONE; - // loadInfo.pSrcInfo = &SrcInfo; - - // hr = D3DX10CreateTextureFromResource( m_pd3d10Device, pTextureNode->hResourceModule, pID, &loadInfo, - // NULL, &pRes, NULL ); - // if( FAILED( hr ) ) - // return DXTRACE_ERR( L"D3DX10CreateResourceFromResource", hr ); - // hr = pRes->QueryInterface( __uuidof( ID3D10Texture2D ), ( LPVOID* )&pTextureNode->pTexture10 ); - // SAFE_RELEASE( pRes ); - // if( FAILED( hr ) ) - // return hr; - //} - } - else - { - // - //// Make sure there's a texture to create - //if( pTextureNode->strFilename[0] == 0 ) - // return S_OK; - - //D3DX10_IMAGE_INFO SrcInfo; - //D3DX10GetImageInfoFromFile( pTextureNode->strFilename, NULL, &SrcInfo, NULL ); - - //// Create texture from file - //ID3D10Resource* pRes; - //D3DX10_IMAGE_LOAD_INFO loadInfo; - //loadInfo.Width = D3DX10_DEFAULT; - //loadInfo.Height = D3DX10_DEFAULT; - //loadInfo.Depth = D3DX10_DEFAULT; - //loadInfo.FirstMipLevel = 0; - //loadInfo.MipLevels = 1; - //loadInfo.Usage = D3D10_USAGE_DEFAULT; - //loadInfo.BindFlags = D3D10_BIND_SHADER_RESOURCE; - //loadInfo.CpuAccessFlags = 0; - //loadInfo.MiscFlags = 0; - //loadInfo.Format = MAKE_TYPELESS( SrcInfo.Format ); - //loadInfo.Filter = D3DX10_FILTER_NONE; - //loadInfo.MipFilter = D3DX10_FILTER_NONE; - //loadInfo.pSrcInfo = &SrcInfo; - //hr = D3DX10CreateTextureFromFile( m_pd3d10Device, pTextureNode->strFilename, &loadInfo, NULL, &pRes, NULL ); - //if( FAILED( hr ) ) - //{ - // return DXTRACE_ERR( L"D3DX10CreateResourceFromFileEx", hr ); - //} - //hr = pRes->QueryInterface( __uuidof( ID3D10Texture2D ), ( LPVOID* )&pTextureNode->pTexture10 ); - //SAFE_RELEASE( pRes ); - //if( FAILED( hr ) ) - // return hr; - // - } - - // Store dimensions - D3D11_TEXTURE2D_DESC desc; - pTextureNode->pTexture11->GetDesc( &desc ); - pTextureNode->dwWidth = desc.Width; - pTextureNode->dwHeight = desc.Height; - - // Create resource view - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Format = MAKE_SRGB( desc.Format ); - SRVDesc.Texture2D.MipLevels = 1; - SRVDesc.Texture2D.MostDetailedMip = 0; - hr = m_pd3d11Device->CreateShaderResourceView( pTextureNode->pTexture11, &SRVDesc, &pTextureNode->pTexResView11 ); - DXUT_SetDebugName( pTextureNode->pTexResView11, "DXUT GUI Texture" ); - - return hr; -} - - -//-------------------------------------------------------------------------------------- void CDXUTDialog::InitDefaultElements() { SetFont( 0, L"Arial", 14, FW_NORMAL ); @@ -3474,19 +2264,612 @@ void CDXUTDialog::InitDefaultElements() } +//====================================================================================== +// CDXUTDialogResourceManager +//====================================================================================== //-------------------------------------------------------------------------------------- -// CDXUTControl class +CDXUTDialogResourceManager::CDXUTDialogResourceManager() : + m_pVSRenderUI11(nullptr), + m_pPSRenderUI11(nullptr), + m_pPSRenderUIUntex11(nullptr), + m_pDepthStencilStateUI11(nullptr), + m_pRasterizerStateUI11(nullptr), + m_pBlendStateUI11(nullptr), + m_pSamplerStateUI11(nullptr), + m_pDepthStencilStateStored11(nullptr), + m_pRasterizerStateStored11(nullptr), + m_pBlendStateStored11(nullptr), + m_pSamplerStateStored11(nullptr), + m_pInputLayout11(nullptr), + m_pVBScreenQuad11(nullptr), + m_pSpriteBuffer11(nullptr), + m_SpriteBufferBytes11(0) +{ +} + + +//-------------------------------------------------------------------------------------- +CDXUTDialogResourceManager::~CDXUTDialogResourceManager() +{ + for( auto it = m_FontCache.begin(); it != m_FontCache.end(); ++it ) + { + SAFE_DELETE( *it ); + } + m_FontCache.clear(); + + for( auto it = m_TextureCache.begin(); it != m_TextureCache.end(); ++it ) + { + SAFE_DELETE( *it ); + } + m_TextureCache.clear(); +} + + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +bool CDXUTDialogResourceManager::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) +{ + UNREFERENCED_PARAMETER(hWnd); + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + return false; +} + + +_Use_decl_annotations_ +HRESULT CDXUTDialogResourceManager::OnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ) +{ + m_pd3d11Device = pd3dDevice; + m_pd3d11DeviceContext = pd3d11DeviceContext; + + HRESULT hr = S_OK; + + // Compile Shaders + ID3DBlob* pVSBlob = nullptr; + ID3DBlob* pPSBlob = nullptr; + ID3DBlob* pPSUntexBlob = nullptr; + V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", nullptr, nullptr, "VS", "vs_4_0_level_9_1", + D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pVSBlob, nullptr ) ); + V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", nullptr, nullptr, "PS", "ps_4_0_level_9_1", + D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSBlob, nullptr ) ); + V_RETURN( D3DCompile( g_strUIEffectFile, g_uUIEffectFileSize, "none", nullptr, nullptr, "PSUntex", "ps_4_0_level_9_1", + D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY, 0, &pPSUntexBlob, nullptr ) ); + + // Create Shaders + V_RETURN( pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &m_pVSRenderUI11 ) ); + DXUT_SetDebugName( m_pVSRenderUI11, "CDXUTDialogResourceManager" ); + + V_RETURN( pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &m_pPSRenderUI11 ) ); + DXUT_SetDebugName( m_pPSRenderUI11, "CDXUTDialogResourceManager" ); + + V_RETURN( pd3dDevice->CreatePixelShader( pPSUntexBlob->GetBufferPointer(), pPSUntexBlob->GetBufferSize(), nullptr, &m_pPSRenderUIUntex11 ) ); + DXUT_SetDebugName( m_pPSRenderUIUntex11, "CDXUTDialogResourceManager" ); + + // States + D3D11_DEPTH_STENCIL_DESC DSDesc; + ZeroMemory( &DSDesc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); + DSDesc.DepthEnable = FALSE; + DSDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; + DSDesc.DepthFunc = D3D11_COMPARISON_LESS; + DSDesc.StencilEnable = FALSE; + V_RETURN( pd3dDevice->CreateDepthStencilState( &DSDesc, &m_pDepthStencilStateUI11 ) ); + DXUT_SetDebugName( m_pDepthStencilStateUI11, "CDXUTDialogResourceManager" ); + + D3D11_RASTERIZER_DESC RSDesc; + RSDesc.AntialiasedLineEnable = FALSE; + RSDesc.CullMode = D3D11_CULL_BACK; + RSDesc.DepthBias = 0; + RSDesc.DepthBiasClamp = 0.0f; + RSDesc.DepthClipEnable = TRUE; + RSDesc.FillMode = D3D11_FILL_SOLID; + RSDesc.FrontCounterClockwise = FALSE; + RSDesc.MultisampleEnable = TRUE; + RSDesc.ScissorEnable = FALSE; + RSDesc.SlopeScaledDepthBias = 0.0f; + V_RETURN( pd3dDevice->CreateRasterizerState( &RSDesc, &m_pRasterizerStateUI11 ) ); + DXUT_SetDebugName( m_pRasterizerStateUI11, "CDXUTDialogResourceManager" ); + + D3D11_BLEND_DESC BSDesc; + ZeroMemory( &BSDesc, sizeof( D3D11_BLEND_DESC ) ); + + BSDesc.RenderTarget[0].BlendEnable = TRUE; + BSDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; + BSDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + BSDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + BSDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + BSDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; + BSDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + BSDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; + + V_RETURN( pd3dDevice->CreateBlendState( &BSDesc, &m_pBlendStateUI11 ) ); + DXUT_SetDebugName( m_pBlendStateUI11, "CDXUTDialogResourceManager" ); + + D3D11_SAMPLER_DESC SSDesc; + ZeroMemory( &SSDesc, sizeof( D3D11_SAMPLER_DESC ) ); + SSDesc.Filter = D3D11_FILTER_ANISOTROPIC ; + SSDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; + SSDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; + SSDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; + SSDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; + SSDesc.MaxAnisotropy = 16; + SSDesc.MinLOD = 0; + SSDesc.MaxLOD = D3D11_FLOAT32_MAX; + if ( pd3dDevice->GetFeatureLevel() < D3D_FEATURE_LEVEL_9_3 ) + { + SSDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + SSDesc.MaxAnisotropy = 0; + } + V_RETURN( pd3dDevice->CreateSamplerState( &SSDesc, &m_pSamplerStateUI11 ) ); + DXUT_SetDebugName( m_pSamplerStateUI11, "CDXUTDialogResourceManager" ); + + // Create the texture objects in the cache arrays. + for( size_t i = 0; i < m_TextureCache.size(); i++ ) + { + hr = CreateTexture11( static_cast<UINT>( i ) ); + if( FAILED( hr ) ) + return hr; + } + + // Create input layout + const D3D11_INPUT_ELEMENT_DESC layout[] = + { + { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; + + V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &m_pInputLayout11 ) ); + DXUT_SetDebugName( m_pInputLayout11, "CDXUTDialogResourceManager" ); + + // Release the blobs + SAFE_RELEASE( pVSBlob ); + SAFE_RELEASE( pPSBlob ); + SAFE_RELEASE( pPSUntexBlob ); + + // Create a vertex buffer quad for rendering later + D3D11_BUFFER_DESC BufDesc; + BufDesc.ByteWidth = sizeof( DXUT_SCREEN_VERTEX_10 ) * 4; + BufDesc.Usage = D3D11_USAGE_DYNAMIC; + BufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + BufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + BufDesc.MiscFlags = 0; + V_RETURN( pd3dDevice->CreateBuffer( &BufDesc, nullptr, &m_pVBScreenQuad11 ) ); + DXUT_SetDebugName( m_pVBScreenQuad11, "CDXUTDialogResourceManager" ); + + // Init the D3D11 font + InitFont11( pd3dDevice, m_pInputLayout11 ); + + return S_OK; +} + + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTDialogResourceManager::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, + const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) +{ + UNREFERENCED_PARAMETER(pd3dDevice); + + HRESULT hr = S_OK; + + m_nBackBufferWidth = pBackBufferSurfaceDesc->Width; + m_nBackBufferHeight = pBackBufferSurfaceDesc->Height; + + return hr; +} + //-------------------------------------------------------------------------------------- -CDXUTControl::CDXUTControl( CDXUTDialog* pDialog ) +void CDXUTDialogResourceManager::OnD3D11ReleasingSwapChain() +{ +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::OnD3D11DestroyDevice() +{ + // Release the resources but don't clear the cache, as these will need to be + // recreated if the device is recreated + + for( auto it = m_TextureCache.begin(); it != m_TextureCache.end(); ++it ) + { + SAFE_RELEASE( (*it)->pTexResView11 ); + SAFE_RELEASE( (*it)->pTexture11 ); + } + + // D3D11 + SAFE_RELEASE( m_pVBScreenQuad11 ); + SAFE_RELEASE( m_pSpriteBuffer11 ); + m_SpriteBufferBytes11 = 0; + SAFE_RELEASE( m_pInputLayout11 ); + + // Shaders + SAFE_RELEASE( m_pVSRenderUI11 ); + SAFE_RELEASE( m_pPSRenderUI11 ); + SAFE_RELEASE( m_pPSRenderUIUntex11 ); + + // States + SAFE_RELEASE( m_pDepthStencilStateUI11 ); + SAFE_RELEASE( m_pRasterizerStateUI11 ); + SAFE_RELEASE( m_pBlendStateUI11 ); + SAFE_RELEASE( m_pSamplerStateUI11 ); + + SAFE_RELEASE( m_pDepthStencilStateStored11 ); + SAFE_RELEASE( m_pRasterizerStateStored11 ); + SAFE_RELEASE( m_pBlendStateStored11 ); + SAFE_RELEASE( m_pSamplerStateStored11 ); + + EndFont11(); +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::StoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ) +{ + pd3dImmediateContext->OMGetDepthStencilState( &m_pDepthStencilStateStored11, &m_StencilRefStored11 ); + pd3dImmediateContext->RSGetState( &m_pRasterizerStateStored11 ); + pd3dImmediateContext->OMGetBlendState( &m_pBlendStateStored11, m_BlendFactorStored11, &m_SampleMaskStored11 ); + pd3dImmediateContext->PSGetSamplers( 0, 1, &m_pSamplerStateStored11 ); +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::RestoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ) +{ + pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateStored11, m_StencilRefStored11 ); + pd3dImmediateContext->RSSetState( m_pRasterizerStateStored11 ); + pd3dImmediateContext->OMSetBlendState( m_pBlendStateStored11, m_BlendFactorStored11, m_SampleMaskStored11 ); + pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateStored11 ); + + SAFE_RELEASE( m_pDepthStencilStateStored11 ); + SAFE_RELEASE( m_pRasterizerStateStored11 ); + SAFE_RELEASE( m_pBlendStateStored11 ); + SAFE_RELEASE( m_pSamplerStateStored11 ); +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::ApplyRenderUI11( _In_ ID3D11DeviceContext* pd3dImmediateContext ) +{ + // Shaders + pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, nullptr, 0 ); + pd3dImmediateContext->HSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->DSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->GSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->PSSetShader( m_pPSRenderUI11, nullptr, 0 ); + + // States + pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); + pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); + float BlendFactor[4] = { 0, 0, 0, 0 }; + pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); + pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::ApplyRenderUIUntex11( _In_ ID3D11DeviceContext* pd3dImmediateContext ) +{ + // Shaders + pd3dImmediateContext->VSSetShader( m_pVSRenderUI11, nullptr, 0 ); + pd3dImmediateContext->HSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->DSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->GSSetShader( nullptr, nullptr, 0 ); + pd3dImmediateContext->PSSetShader( m_pPSRenderUIUntex11, nullptr, 0 ); + + // States + pd3dImmediateContext->OMSetDepthStencilState( m_pDepthStencilStateUI11, 0 ); + pd3dImmediateContext->RSSetState( m_pRasterizerStateUI11 ); + float BlendFactor[4] = { 0, 0, 0, 0 }; + pd3dImmediateContext->OMSetBlendState( m_pBlendStateUI11, BlendFactor, 0xFFFFFFFF ); + pd3dImmediateContext->PSSetSamplers( 0, 1, &m_pSamplerStateUI11 ); +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::BeginSprites11( ) +{ + m_SpriteVertices.clear(); +} + + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +void CDXUTDialogResourceManager::EndSprites11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ) +{ + + // ensure our buffer size can hold our sprites + UINT SpriteDataBytes = static_cast<UINT>( m_SpriteVertices.size() * sizeof( DXUTSpriteVertex ) ); + if( m_SpriteBufferBytes11 < SpriteDataBytes ) + { + SAFE_RELEASE( m_pSpriteBuffer11 ); + m_SpriteBufferBytes11 = SpriteDataBytes; + + D3D11_BUFFER_DESC BufferDesc; + BufferDesc.ByteWidth = m_SpriteBufferBytes11; + BufferDesc.Usage = D3D11_USAGE_DYNAMIC; + BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + BufferDesc.MiscFlags = 0; + + if ( FAILED(pd3dDevice->CreateBuffer(&BufferDesc, nullptr, &m_pSpriteBuffer11)) ) + { + m_pSpriteBuffer11 = nullptr; + m_SpriteBufferBytes11 = 0; + return; + } + DXUT_SetDebugName( m_pSpriteBuffer11, "CDXUTDialogResourceManager" ); + } + + // Copy the sprites over + D3D11_BOX destRegion; + destRegion.left = 0; + destRegion.right = SpriteDataBytes; + destRegion.top = 0; + destRegion.bottom = 1; + destRegion.front = 0; + destRegion.back = 1; + D3D11_MAPPED_SUBRESOURCE MappedResource; + if ( S_OK == pd3dImmediateContext->Map( m_pSpriteBuffer11, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) ) + { + memcpy( MappedResource.pData, (const void*)&m_SpriteVertices[0], SpriteDataBytes ); + pd3dImmediateContext->Unmap(m_pSpriteBuffer11, 0); + } + + // Draw + UINT Stride = sizeof( DXUTSpriteVertex ); + UINT Offset = 0; + pd3dImmediateContext->IASetVertexBuffers( 0, 1, &m_pSpriteBuffer11, &Stride, &Offset ); + pd3dImmediateContext->IASetInputLayout( m_pInputLayout11 ); + pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); + pd3dImmediateContext->Draw( static_cast<UINT>( m_SpriteVertices.size() ), 0 ); + + m_SpriteVertices.clear(); +} + + +//-------------------------------------------------------------------------------------- +bool CDXUTDialogResourceManager::RegisterDialog( _In_ CDXUTDialog* pDialog ) +{ + // Check that the dialog isn't already registered. + for( auto it = m_Dialogs.cbegin(); it != m_Dialogs.cend(); ++it ) + { + if( *it == pDialog ) + return true; + } + + // Add to the list. + m_Dialogs.push_back( pDialog ); + + // Set up next and prev pointers. + if( m_Dialogs.size() > 1 ) + m_Dialogs[m_Dialogs.size() - 2]->SetNextDialog( pDialog ); + m_Dialogs[m_Dialogs.size() - 1]->SetNextDialog( m_Dialogs[0] ); + + return true; +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::UnregisterDialog( _In_ CDXUTDialog* pDialog ) +{ + // Search for the dialog in the list. + for( size_t i = 0; i < m_Dialogs.size(); ++i ) + { + if( m_Dialogs[ i ] == pDialog ) + { + m_Dialogs.erase( m_Dialogs.begin() + i ); + if( !m_Dialogs.empty() ) + { + int l, r; + + if( 0 == i ) + l = int( m_Dialogs.size() - 1 ); + else + l = int(i) - 1; + + if( m_Dialogs.size() == i ) + r = 0; + else + r = int( i ); + + m_Dialogs[l]->SetNextDialog( m_Dialogs[r] ); + } + return; + } + } +} + + +//-------------------------------------------------------------------------------------- +void CDXUTDialogResourceManager::EnableKeyboardInputForAllDialogs() +{ + // Enable keyboard input for all registered dialogs + for( auto it = m_Dialogs.begin(); it != m_Dialogs.end(); ++it ) + (*it)->EnableKeyboardInput( true ); +} + + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +int CDXUTDialogResourceManager::AddFont( LPCWSTR strFaceName, LONG height, LONG weight ) +{ + // See if this font already exists + for( size_t i = 0; i < m_FontCache.size(); ++i ) + { + auto pFontNode = m_FontCache[ i ]; + size_t nLen = 0; + nLen = wcsnlen( strFaceName, MAX_PATH); + if( 0 == _wcsnicmp( pFontNode->strFace, strFaceName, nLen ) && + pFontNode->nHeight == height && + pFontNode->nWeight == weight ) + { + return static_cast<int>( i ); + } + } + + // Add a new font and try to create it + auto pNewFontNode = new (std::nothrow) DXUTFontNode; + if( !pNewFontNode ) + return -1; + + ZeroMemory( pNewFontNode, sizeof( DXUTFontNode ) ); + wcscpy_s( pNewFontNode->strFace, MAX_PATH, strFaceName ); + pNewFontNode->nHeight = height; + pNewFontNode->nWeight = weight; + m_FontCache.push_back( pNewFontNode ); + + int iFont = (int)m_FontCache.size() - 1; + + // If a device is available, try to create immediately + return iFont; +} + + +//-------------------------------------------------------------------------------------- +int CDXUTDialogResourceManager::AddTexture( _In_z_ LPCWSTR strFilename ) +{ + // See if this texture already exists + for( size_t i = 0; i < m_TextureCache.size(); ++i ) + { + auto pTextureNode = m_TextureCache[ i ]; + size_t nLen = 0; + nLen = wcsnlen( strFilename, MAX_PATH); + if( pTextureNode->bFileSource && // Sources must match + 0 == _wcsnicmp( pTextureNode->strFilename, strFilename, nLen ) ) + { + return static_cast<int>( i ); + } + } + + // Add a new texture and try to create it + auto pNewTextureNode = new (std::nothrow) DXUTTextureNode; + if( !pNewTextureNode ) + return -1; + + ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); + pNewTextureNode->bFileSource = true; + wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strFilename ); + + m_TextureCache.push_back( pNewTextureNode ); + + int iTexture = int( m_TextureCache.size() ) - 1; + + // If a device is available, try to create immediately + + return iTexture; +} + + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +int CDXUTDialogResourceManager::AddTexture( LPCWSTR strResourceName, HMODULE hResourceModule ) +{ + // See if this texture already exists + for( size_t i = 0; i < m_TextureCache.size(); i++ ) + { + auto pTextureNode = m_TextureCache[ i ]; + if( !pTextureNode->bFileSource && // Sources must match + pTextureNode->hResourceModule == hResourceModule ) // Module handles must match + { + if( IS_INTRESOURCE( strResourceName ) ) + { + // Integer-based ID + if( ( INT_PTR )strResourceName == pTextureNode->nResourceID ) + return static_cast<int>( i ); + } + else + { + // String-based ID + size_t nLen = 0; + nLen = wcsnlen ( strResourceName, MAX_PATH ); + if( 0 == _wcsnicmp( pTextureNode->strFilename, strResourceName, nLen ) ) + return static_cast<int>( i ); + } + } + } + + // Add a new texture and try to create it + auto pNewTextureNode = new (std::nothrow) DXUTTextureNode; + if( !pNewTextureNode ) + return -1; + + ZeroMemory( pNewTextureNode, sizeof( DXUTTextureNode ) ); + pNewTextureNode->hResourceModule = hResourceModule; + if( IS_INTRESOURCE( strResourceName ) ) + { + pNewTextureNode->nResourceID = ( int )( size_t )strResourceName; + } + else + { + pNewTextureNode->nResourceID = 0; + wcscpy_s( pNewTextureNode->strFilename, MAX_PATH, strResourceName ); + } + + m_TextureCache.push_back( pNewTextureNode ); + + int iTexture = int( m_TextureCache.size() ) - 1; + + // If a device is available, try to create immediately + + return iTexture; +} + + +//-------------------------------------------------------------------------------------- +HRESULT CDXUTDialogResourceManager::CreateTexture11( _In_ UINT iTexture ) +{ + HRESULT hr = S_OK; + + auto pTextureNode = m_TextureCache[ iTexture ]; + + if( !pTextureNode->bFileSource ) + { + if( pTextureNode->nResourceID == 0xFFFF && pTextureNode->hResourceModule == ( HMODULE )0xFFFF ) + { + hr = DXUTCreateGUITextureFromInternalArray( m_pd3d11Device, &pTextureNode->pTexture11 ); + if( FAILED( hr ) ) + return DXTRACE_ERR( L"DXUTCreateGUITextureFromInternalArray", hr ); + DXUT_SetDebugName( pTextureNode->pTexture11, "DXUT GUI Texture" ); + } + } + + // Store dimensions + D3D11_TEXTURE2D_DESC desc; + pTextureNode->pTexture11->GetDesc( &desc ); + pTextureNode->dwWidth = desc.Width; + pTextureNode->dwHeight = desc.Height; + + // Create resource view + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Format = desc.Format; + SRVDesc.Texture2D.MipLevels = 1; + SRVDesc.Texture2D.MostDetailedMip = 0; + hr = m_pd3d11Device->CreateShaderResourceView( pTextureNode->pTexture11, &SRVDesc, &pTextureNode->pTexResView11 ); + if ( FAILED(hr) ) + return hr; + + DXUT_SetDebugName( pTextureNode->pTexResView11, "DXUT GUI Texture" ); + + return hr; +} + + +//====================================================================================== +// CDXUTControl class +//====================================================================================== + +CDXUTControl::CDXUTControl( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_BUTTON; m_pDialog = pDialog; m_ID = 0; + m_nHotkey = 0; m_Index = 0; - m_pUserData = NULL; + m_pUserData = nullptr; m_bEnabled = true; m_bVisible = true; @@ -3494,7 +2877,7 @@ CDXUTControl::CDXUTControl( CDXUTDialog* pDialog ) m_bHasFocus = false; m_bIsDefault = false; - m_pDialog = NULL; + m_pDialog = nullptr; m_x = 0; m_y = 0; @@ -3505,20 +2888,22 @@ CDXUTControl::CDXUTControl( CDXUTDialog* pDialog ) } +//-------------------------------------------------------------------------------------- CDXUTControl::~CDXUTControl() { - for( int i = 0; i < m_Elements.GetSize(); ++i ) + for( auto it = m_Elements.begin(); it != m_Elements.end(); ++it ) { - delete m_Elements[i]; + auto pElement = *it; + delete pElement; } - m_Elements.RemoveAll(); + m_Elements.clear(); } //-------------------------------------------------------------------------------------- -void CDXUTControl::SetTextColor( D3DCOLOR Color ) +void CDXUTControl::SetTextColor( _In_ DWORD Color ) { - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; if( pElement ) pElement->FontColor.States[DXUT_STATE_NORMAL] = Color; @@ -3526,30 +2911,23 @@ void CDXUTControl::SetTextColor( D3DCOLOR Color ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTControl::SetElement( UINT iElement, CDXUTElement* pElement ) +HRESULT CDXUTControl::SetElement( _In_ UINT iElement, _In_ CDXUTElement* pElement ) { - HRESULT hr = S_OK; - - if( pElement == NULL ) + if( !pElement ) return E_INVALIDARG; // Make certain the array is this large - for( UINT i = m_Elements.GetSize(); i <= iElement; i++ ) + for( size_t i = m_Elements.size(); i <= iElement; i++ ) { - CDXUTElement* pNewElement = new CDXUTElement(); - if( pNewElement == NULL ) + auto pNewElement = new (std::nothrow) CDXUTElement(); + if( !pNewElement ) return E_OUTOFMEMORY; - hr = m_Elements.Add( pNewElement ); - if( FAILED( hr ) ) - { - SAFE_DELETE( pNewElement ); - return hr; - } + m_Elements.push_back( pNewElement ); } // Update the data - CDXUTElement* pCurElement = m_Elements.GetAt( iElement ); + auto pCurElement = m_Elements[ iElement ]; *pCurElement = *pElement; return S_OK; @@ -3562,10 +2940,9 @@ void CDXUTControl::Refresh() m_bMouseOver = false; m_bHasFocus = false; - for( int i = 0; i < m_Elements.GetSize(); i++ ) + for( auto it = m_Elements.begin(); it != m_Elements.end(); ++it ) { - CDXUTElement* pElement = m_Elements.GetAt( i ); - pElement->Refresh(); + (*it)->Refresh(); } } @@ -3577,30 +2954,30 @@ void CDXUTControl::UpdateRects() } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTStatic class -//-------------------------------------------------------------------------------------- +//====================================================================================== //-------------------------------------------------------------------------------------- -CDXUTStatic::CDXUTStatic( CDXUTDialog* pDialog ) +CDXUTStatic::CDXUTStatic( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_STATIC; m_pDialog = pDialog; ZeroMemory( &m_strText, sizeof( m_strText ) ); - for( int i = 0; i < m_Elements.GetSize(); i++ ) + for( auto it = m_Elements.begin(); it != m_Elements.end(); ++it ) { - CDXUTElement* pElement = m_Elements.GetAt( i ); + auto pElement = *it; SAFE_DELETE( pElement ); } - m_Elements.RemoveAll(); + m_Elements.clear(); } //-------------------------------------------------------------------------------------- -void CDXUTStatic::Render( float fElapsedTime ) +void CDXUTStatic::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -3610,20 +2987,20 @@ void CDXUTStatic::Render( float fElapsedTime ) if( m_bEnabled == false ) iState = DXUT_STATE_DISABLED; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; pElement->FontColor.Blend( iState, fElapsedTime ); - m_pDialog->DrawText( m_strText, pElement, &m_rcBoundingBox, false, -1, false); + m_pDialog->DrawText( m_strText, pElement, &m_rcBoundingBox, false, false); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTStatic::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ) +_Use_decl_annotations_ +HRESULT CDXUTStatic::GetTextCopy( LPWSTR strDest, UINT bufferCount ) const { // Validate incoming parameters - if( strDest == NULL || bufferCount == 0 ) + if( !strDest || bufferCount == 0 ) { return E_INVALIDARG; } @@ -3636,9 +3013,9 @@ HRESULT CDXUTStatic::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, //-------------------------------------------------------------------------------------- -HRESULT CDXUTStatic::SetText( LPCWSTR strText ) +HRESULT CDXUTStatic::SetText( _In_z_ LPCWSTR strText ) { - if( strText == NULL ) + if( !strText ) { m_strText[0] = 0; return S_OK; @@ -3649,12 +3026,11 @@ HRESULT CDXUTStatic::SetText( LPCWSTR strText ) } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTButton class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTButton::CDXUTButton( CDXUTDialog* pDialog ) +CDXUTButton::CDXUTButton( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_BUTTON; m_pDialog = pDialog; @@ -3664,8 +3040,12 @@ CDXUTButton::CDXUTButton( CDXUTDialog* pDialog ) } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) + { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3700,8 +3080,12 @@ bool CDXUTButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTButton::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3750,7 +3134,7 @@ bool CDXUTButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam } //-------------------------------------------------------------------------------------- -void CDXUTButton::Render( float fElapsedTime ) +void CDXUTButton::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -3788,7 +3172,7 @@ void CDXUTButton::Render( float fElapsedTime ) } // Background fill layer - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; @@ -3801,27 +3185,26 @@ void CDXUTButton::Render( float fElapsedTime ) pElement->FontColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &rcWindow, DXUT_FAR_BUTTON_DEPTH ); - m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, -1, true ); + m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, true ); // Main button - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); pElement->FontColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &rcWindow, DXUT_NEAR_BUTTON_DEPTH ); - m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, -1, true ); + m_pDialog->DrawText( m_strText, pElement, &rcWindow, false, true ); } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTCheckBox class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTCheckBox::CDXUTCheckBox( CDXUTDialog* pDialog ) +CDXUTCheckBox::CDXUTCheckBox( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_CHECKBOX; m_pDialog = pDialog; @@ -3831,8 +3214,11 @@ CDXUTCheckBox::CDXUTCheckBox( CDXUTDialog* pDialog ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTCheckBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3867,8 +3253,12 @@ bool CDXUTCheckBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTCheckBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTCheckBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -3915,6 +3305,7 @@ bool CDXUTCheckBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTCheckBox::SetCheckedInternal( bool bChecked, bool bFromInput ) { m_bChecked = bChecked; @@ -3924,14 +3315,13 @@ void CDXUTCheckBox::SetCheckedInternal( bool bChecked, bool bFromInput ) //-------------------------------------------------------------------------------------- -BOOL CDXUTCheckBox::ContainsPoint( POINT pt ) +bool CDXUTCheckBox::ContainsPoint( _In_ const POINT& pt ) { return ( PtInRect( &m_rcBoundingBox, pt ) || PtInRect( &m_rcButton, pt ) ); } - //-------------------------------------------------------------------------------------- void CDXUTCheckBox::UpdateRects() { @@ -3945,9 +3335,8 @@ void CDXUTCheckBox::UpdateRects() } - //-------------------------------------------------------------------------------------- -void CDXUTCheckBox::Render( float fElapsedTime ) +void CDXUTCheckBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -3964,7 +3353,7 @@ void CDXUTCheckBox::Render( float fElapsedTime ) else if( m_bHasFocus ) iState = DXUT_STATE_FOCUS; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; @@ -3972,26 +3361,23 @@ void CDXUTCheckBox::Render( float fElapsedTime ) pElement->FontColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcButton, DXUT_NEAR_BUTTON_DEPTH ); - m_pDialog->DrawText( m_strText, pElement, &m_rcText, false, -1, false ); + m_pDialog->DrawText( m_strText, pElement, &m_rcText, false, false ); if( !m_bChecked ) iState = DXUT_STATE_HIDDEN; - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcButton, DXUT_FAR_BUTTON_DEPTH ); } - - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTRadioButton class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTRadioButton::CDXUTRadioButton( CDXUTDialog* pDialog ) +CDXUTRadioButton::CDXUTRadioButton( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_RADIOBUTTON; m_pDialog = pDialog; @@ -4000,8 +3386,11 @@ CDXUTRadioButton::CDXUTRadioButton( CDXUTDialog* pDialog ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTRadioButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4040,8 +3429,12 @@ bool CDXUTRadioButton::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTRadioButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTRadioButton::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4092,6 +3485,7 @@ bool CDXUTRadioButton::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM l } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTRadioButton::SetCheckedInternal( bool bChecked, bool bClearGroup, bool bFromInput ) { if( bChecked && bClearGroup ) @@ -4102,14 +3496,11 @@ void CDXUTRadioButton::SetCheckedInternal( bool bChecked, bool bClearGroup, bool } - - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTComboBox class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTComboBox::CDXUTComboBox( CDXUTDialog* pDialog ) : m_ScrollBar( pDialog ) +CDXUTComboBox::CDXUTComboBox( _In_opt_ CDXUTDialog* pDialog ) : m_ScrollBar( pDialog ) { m_Type = DXUT_CONTROL_COMBOBOX; m_pDialog = pDialog; @@ -4131,14 +3522,14 @@ CDXUTComboBox::~CDXUTComboBox() //-------------------------------------------------------------------------------------- -void CDXUTComboBox::SetTextColor( D3DCOLOR Color ) +void CDXUTComboBox::SetTextColor( _In_ DWORD Color ) { - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; if( pElement ) pElement->FontColor.States[DXUT_STATE_NORMAL] = Color; - pElement = m_Elements.GetAt( 2 ); + pElement = m_Elements[ 2 ]; if( pElement ) pElement->FontColor.States[DXUT_STATE_NORMAL] = Color; @@ -4158,20 +3549,20 @@ void CDXUTComboBox::UpdateRects() m_rcText.right = m_rcButton.left; m_rcDropdown = m_rcText; - OffsetRect( &m_rcDropdown, 0, ( int )( 0.90f * RectHeight( m_rcText ) ) ); + OffsetRect( &m_rcDropdown, 0, static_cast<int>( 0.90f * RectHeight( m_rcText ) ) ); m_rcDropdown.bottom += m_nDropHeight; m_rcDropdown.right -= m_nSBWidth; m_rcDropdownText = m_rcDropdown; - m_rcDropdownText.left += ( int )( 0.1f * RectWidth( m_rcDropdown ) ); - m_rcDropdownText.right -= ( int )( 0.1f * RectWidth( m_rcDropdown ) ); - m_rcDropdownText.top += ( int )( 0.1f * RectHeight( m_rcDropdown ) ); - m_rcDropdownText.bottom -= ( int )( 0.1f * RectHeight( m_rcDropdown ) ); + m_rcDropdownText.left += static_cast<int>(0.1f * RectWidth(m_rcDropdown)); + m_rcDropdownText.right -= static_cast<int>(0.1f * RectWidth(m_rcDropdown)); + m_rcDropdownText.top += static_cast<int>(0.1f * RectHeight(m_rcDropdown)); + m_rcDropdownText.bottom -= static_cast<int>(0.1f * RectHeight(m_rcDropdown)); // Update the scrollbar's rects m_ScrollBar.SetLocation( m_rcDropdown.right, m_rcDropdown.top + 2 ); m_ScrollBar.SetSize( m_nSBWidth, RectHeight( m_rcDropdown ) - 2 ); - DXUTFontNode* pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements.GetAt( 2 )->iFont ); + auto pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements[ 2 ]->iFont ); if( pFontNode && pFontNode->nHeight ) { m_ScrollBar.SetPageSize( RectHeight( m_rcDropdownText ) / pFontNode->nHeight ); @@ -4193,6 +3584,7 @@ void CDXUTComboBox::OnFocusOut() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTComboBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { const DWORD REPEAT_MASK = ( 0x40000000 ); @@ -4279,7 +3671,8 @@ bool CDXUTComboBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTComboBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) return false; @@ -4295,13 +3688,13 @@ bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar if( m_bOpened && PtInRect( &m_rcDropdown, pt ) ) { // Determine which item has been selected - for( int i = 0; i < m_Items.GetSize(); i++ ) + for( size_t i = 0; i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->bVisible && PtInRect( &pItem->rcActive, pt ) ) { - m_iFocused = i; + m_iFocused = static_cast<int>( i ); } } return true; @@ -4340,13 +3733,13 @@ bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar if( m_bOpened && PtInRect( &m_rcDropdown, pt ) ) { // Determine which item has been selected - for( int i = m_ScrollBar.GetTrackPos(); i < m_Items.GetSize(); i++ ) + for( size_t i = m_ScrollBar.GetTrackPos(); i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->bVisible && PtInRect( &pItem->rcActive, pt ) ) { - m_iFocused = m_iSelected = i; + m_iFocused = m_iSelected = static_cast<int>( i ); m_pDialog->SendEvent( EVENT_COMBOBOX_SELECTION_CHANGED, true, this ); m_bOpened = false; @@ -4399,8 +3792,9 @@ bool CDXUTComboBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPar int zDelta = ( short )HIWORD( wParam ) / WHEEL_DELTA; if( m_bOpened ) { - UINT uLines; - SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &uLines, 0 ); + UINT uLines = 0; + if ( !SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &uLines, 0) ) + uLines = 0; m_ScrollBar.Scroll( -zDelta * uLines ); } else @@ -4450,7 +3844,7 @@ void CDXUTComboBox::OnHotkey() m_iSelected++; - if( m_iSelected >= ( int )m_Items.GetSize() ) + if( m_iSelected >= ( int )m_Items.size() ) m_iSelected = 0; m_iFocused = m_iSelected; @@ -4459,17 +3853,18 @@ void CDXUTComboBox::OnHotkey() //-------------------------------------------------------------------------------------- -void CDXUTComboBox::Render( float fElapsedTime ) +void CDXUTComboBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; + DXUT_CONTROL_STATE iState = DXUT_STATE_NORMAL; if( !m_bOpened ) iState = DXUT_STATE_HIDDEN; // Dropdown box - CDXUTElement* pElement = m_Elements.GetAt( 2 ); + auto pElement = m_Elements[ 2 ]; // If we have not initialized the scroll bar page size, // do that now. @@ -4496,20 +3891,19 @@ void CDXUTComboBox::Render( float fElapsedTime ) m_pDialog->DrawSprite( pElement, &m_rcDropdown, DXUT_NEAR_BUTTON_DEPTH ); // Selection outline - CDXUTElement* pSelectionElement = m_Elements.GetAt( 3 ); + auto pSelectionElement = m_Elements[ 3 ]; pSelectionElement->TextureColor.Current = pElement->TextureColor.Current; - pSelectionElement->FontColor.Current = pSelectionElement->FontColor.States[ DXUT_STATE_NORMAL ]; + pSelectionElement->FontColor.SetCurrent( pSelectionElement->FontColor.States[ DXUT_STATE_NORMAL ] ); - DXUTFontNode* pFont = m_pDialog->GetFont( pElement->iFont ); + auto pFont = m_pDialog->GetFont( pElement->iFont ); if( pFont ) { int curY = m_rcDropdownText.top; int nRemainingHeight = RectHeight( m_rcDropdownText ); - //WCHAR strDropdown[4096] = {0}; - for( int i = m_ScrollBar.GetTrackPos(); i < m_Items.GetSize(); i++ ) + for( size_t i = m_ScrollBar.GetTrackPos(); i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; // Make sure there's room left in the dropdown nRemainingHeight -= pFont->nHeight; @@ -4522,10 +3916,6 @@ void CDXUTComboBox::Render( float fElapsedTime ) SetRect( &pItem->rcActive, m_rcDropdownText.left, curY, m_rcDropdownText.right, curY + pFont->nHeight ); curY += pFont->nHeight; - //debug - //int blue = 50 * i; - //m_pDialog->DrawRect( &pItem->rcActive, 0xFFFF0000 | blue ); - pItem->bVisible = true; if( m_bOpened ) @@ -4533,7 +3923,7 @@ void CDXUTComboBox::Render( float fElapsedTime ) if( ( int )i == m_iFocused ) { RECT rc; - SetRect( &rc, m_rcDropdown.left, pItem->rcActive.top - 2, m_rcDropdown.right, + SetRect( &rc, m_rcDropdown.left, pItem->rcActive.top, m_rcDropdown.right, pItem->rcActive.bottom + 2 ); m_pDialog->DrawSprite( pSelectionElement, &rc, DXUT_NEAR_BUTTON_DEPTH ); m_pDialog->DrawText( pItem->strText, pSelectionElement, &pItem->rcActive ); @@ -4575,7 +3965,7 @@ void CDXUTComboBox::Render( float fElapsedTime ) float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; // Button - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -4588,7 +3978,7 @@ void CDXUTComboBox::Render( float fElapsedTime ) iState = DXUT_STATE_PRESSED; // Main text box - pElement = m_Elements.GetAt( 0 ); + pElement = m_Elements[ 0 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -4596,12 +3986,12 @@ void CDXUTComboBox::Render( float fElapsedTime ) m_pDialog->DrawSprite( pElement, &m_rcText, DXUT_NEAR_BUTTON_DEPTH ); - if( m_iSelected >= 0 && m_iSelected < ( int )m_Items.GetSize() ) + if( m_iSelected >= 0 && m_iSelected < ( int )m_Items.size() ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( m_iSelected ); - if( pItem != NULL ) + auto pItem = m_Items[ m_iSelected ]; + if( pItem ) { - m_pDialog->DrawText( pItem->strText, pElement, &m_rcText, false, -1, true ); + m_pDialog->DrawText( pItem->strText, pElement, &m_rcText, false, true ); } } @@ -4609,17 +3999,18 @@ void CDXUTComboBox::Render( float fElapsedTime ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTComboBox::AddItem( const WCHAR* strText, void* pData ) { // Validate parameters - if( strText == NULL ) + if( !strText ) { return E_INVALIDARG; } // Create a new item and set the data - DXUTComboBoxItem* pItem = new DXUTComboBoxItem; - if( pItem == NULL ) + auto pItem = new (std::nothrow) DXUTComboBoxItem; + if( !pItem ) { return DXTRACE_ERR_MSGBOX( L"new", E_OUTOFMEMORY ); } @@ -4628,10 +4019,10 @@ HRESULT CDXUTComboBox::AddItem( const WCHAR* strText, void* pData ) wcscpy_s( pItem->strText, 256, strText ); pItem->pData = pData; - m_Items.Add( pItem ); + m_Items.push_back( pItem ); // Update the scroll bar with new range - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); // If this is the only item in the list, it's selected if( GetNumItems() == 1 ) @@ -4646,53 +4037,53 @@ HRESULT CDXUTComboBox::AddItem( const WCHAR* strText, void* pData ) //-------------------------------------------------------------------------------------- -void CDXUTComboBox::RemoveItem( UINT index ) +void CDXUTComboBox::RemoveItem( _In_ UINT index ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( index ); + auto it = m_Items.begin() + index; + auto pItem = *it; SAFE_DELETE( pItem ); - m_Items.Remove( index ); - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - if( m_iSelected >= m_Items.GetSize() ) - m_iSelected = m_Items.GetSize() - 1; + m_Items.erase( it ); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); + if( m_iSelected >= (int)m_Items.size() ) + m_iSelected = (int)m_Items.size() - 1; } //-------------------------------------------------------------------------------------- void CDXUTComboBox::RemoveAllItems() { - for( int i = 0; i < m_Items.GetSize(); i++ ) + for( auto it = m_Items.begin(); it != m_Items.end(); ++it ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = *it; SAFE_DELETE( pItem ); } - m_Items.RemoveAll(); + m_Items.clear(); m_ScrollBar.SetTrackRange( 0, 1 ); m_iFocused = m_iSelected = -1; } - //-------------------------------------------------------------------------------------- -bool CDXUTComboBox::ContainsItem( const WCHAR* strText, UINT iStart ) +bool CDXUTComboBox::ContainsItem( _In_z_ const WCHAR* strText, _In_ UINT iStart ) { return ( -1 != FindItem( strText, iStart ) ); } //-------------------------------------------------------------------------------------- -int CDXUTComboBox::FindItem( const WCHAR* strText, UINT iStart ) +int CDXUTComboBox::FindItem( _In_z_ const WCHAR* strText, _In_ UINT iStart ) const { - if( strText == NULL ) + if( !strText ) return -1; - for( int i = iStart; i < m_Items.GetSize(); i++ ) + for( size_t i = iStart; i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( 0 == wcscmp( pItem->strText, strText ) ) { - return i; + return static_cast<int>( i ); } } @@ -4701,40 +4092,40 @@ int CDXUTComboBox::FindItem( const WCHAR* strText, UINT iStart ) //-------------------------------------------------------------------------------------- -void* CDXUTComboBox::GetSelectedData() +void* CDXUTComboBox::GetSelectedData() const { if( m_iSelected < 0 ) - return NULL; + return nullptr; - DXUTComboBoxItem* pItem = m_Items.GetAt( m_iSelected ); + auto pItem = m_Items[ m_iSelected ]; return pItem->pData; } //-------------------------------------------------------------------------------------- -DXUTComboBoxItem* CDXUTComboBox::GetSelectedItem() +DXUTComboBoxItem* CDXUTComboBox::GetSelectedItem() const { if( m_iSelected < 0 ) - return NULL; + return nullptr; - return m_Items.GetAt( m_iSelected ); + return m_Items[ m_iSelected ]; } //-------------------------------------------------------------------------------------- -void* CDXUTComboBox::GetItemData( const WCHAR* strText ) +void* CDXUTComboBox::GetItemData( _In_z_ const WCHAR* strText ) const { int index = FindItem( strText ); if( index == -1 ) { - return NULL; + return nullptr; } - DXUTComboBoxItem* pItem = m_Items.GetAt( index ); - if( pItem == NULL ) + auto pItem = m_Items[ index ]; + if( !pItem ) { - DXTRACE_ERR( L"CGrowableArray::GetAt", E_FAIL ); - return NULL; + DXTRACE_ERR( L"CDXUTComboBox::GetItemData", E_FAIL ); + return nullptr; } return pItem->pData; @@ -4742,17 +4133,17 @@ void* CDXUTComboBox::GetItemData( const WCHAR* strText ) //-------------------------------------------------------------------------------------- -void* CDXUTComboBox::GetItemData( int nIndex ) +void* CDXUTComboBox::GetItemData( _In_ int nIndex ) const { - if( nIndex < 0 || nIndex >= m_Items.GetSize() ) - return NULL; + if( nIndex < 0 || nIndex >= (int)m_Items.size() ) + return nullptr; - return m_Items.GetAt( nIndex )->pData; + return m_Items[ nIndex ]->pData; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTComboBox::SetSelectedByIndex( UINT index ) +HRESULT CDXUTComboBox::SetSelectedByIndex( _In_ UINT index ) { if( index >= GetNumItems() ) return E_INVALIDARG; @@ -4766,9 +4157,9 @@ HRESULT CDXUTComboBox::SetSelectedByIndex( UINT index ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTComboBox::SetSelectedByText( const WCHAR* strText ) +HRESULT CDXUTComboBox::SetSelectedByText( _In_z_ const WCHAR* strText ) { - if( strText == NULL ) + if( !strText ) return E_INVALIDARG; int index = FindItem( strText ); @@ -4784,15 +4175,15 @@ HRESULT CDXUTComboBox::SetSelectedByText( const WCHAR* strText ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTComboBox::SetSelectedByData( void* pData ) +HRESULT CDXUTComboBox::SetSelectedByData( _In_ void* pData ) { - for( int i = 0; i < m_Items.GetSize(); i++ ) + for( size_t i = 0; i < m_Items.size(); i++ ) { - DXUTComboBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->pData == pData ) { - m_iFocused = m_iSelected = i; + m_iFocused = m_iSelected = static_cast<int>( i ); m_pDialog->SendEvent( EVENT_COMBOBOX_SELECTION_CHANGED, false, this ); return S_OK; } @@ -4802,9 +4193,11 @@ HRESULT CDXUTComboBox::SetSelectedByData( void* pData ) } +//====================================================================================== +// CDXUTSlider class +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTSlider::CDXUTSlider( CDXUTDialog* pDialog ) +CDXUTSlider::CDXUTSlider( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_SLIDER; m_pDialog = pDialog; @@ -4818,7 +4211,7 @@ CDXUTSlider::CDXUTSlider( CDXUTDialog* pDialog ) //-------------------------------------------------------------------------------------- -BOOL CDXUTSlider::ContainsPoint( POINT pt ) +bool CDXUTSlider::ContainsPoint( _In_ const POINT& pt ) { return ( PtInRect( &m_rcBoundingBox, pt ) || PtInRect( &m_rcButton, pt ) ); @@ -4838,15 +4231,21 @@ void CDXUTSlider::UpdateRects() OffsetRect( &m_rcButton, m_nButtonX, 0 ); } -int CDXUTSlider::ValueFromPos( int x ) + +//-------------------------------------------------------------------------------------- +int CDXUTSlider::ValueFromPos( _In_ int x ) { float fValuePerPixel = ( float )( m_nMax - m_nMin ) / RectWidth( m_rcBoundingBox ); return ( int )( 0.5f + m_nMin + fValuePerPixel * ( x - m_rcBoundingBox.left ) ); } + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTSlider::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4894,8 +4293,11 @@ bool CDXUTSlider::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTSlider::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTSlider::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -4985,7 +4387,7 @@ bool CDXUTSlider::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam //-------------------------------------------------------------------------------------- -void CDXUTSlider::SetRange( int nMin, int nMax ) +void CDXUTSlider::SetRange( _In_ int nMin, _In_ int nMax ) { m_nMin = nMin; m_nMax = nMax; @@ -4995,11 +4397,11 @@ void CDXUTSlider::SetRange( int nMin, int nMax ) //-------------------------------------------------------------------------------------- -void CDXUTSlider::SetValueInternal( int nValue, bool bFromInput ) +void CDXUTSlider::SetValueInternal( _In_ int nValue, _In_ bool bFromInput ) { // Clamp to range - nValue = __max( m_nMin, nValue ); - nValue = __min( m_nMax, nValue ); + nValue = std::max( m_nMin, nValue ); + nValue = std::min( m_nMax, nValue ); if( nValue == m_nValue ) return; @@ -5012,7 +4414,7 @@ void CDXUTSlider::SetValueInternal( int nValue, bool bFromInput ) //-------------------------------------------------------------------------------------- -void CDXUTSlider::Render( float fElapsedTime ) +void CDXUTSlider::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -5051,13 +4453,13 @@ void CDXUTSlider::Render( float fElapsedTime ) float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcBoundingBox, DXUT_FAR_BUTTON_DEPTH ); - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -5065,12 +4467,11 @@ void CDXUTSlider::Render( float fElapsedTime ) } -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTScrollBar class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTScrollBar::CDXUTScrollBar( CDXUTDialog* pDialog ) +CDXUTScrollBar::CDXUTScrollBar( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_SCROLLBAR; m_pDialog = pDialog; @@ -5123,7 +4524,7 @@ void CDXUTScrollBar::UpdateThumbRect() { if( m_nEnd - m_nStart > m_nPageSize ) { - int nThumbHeight = __max( RectHeight( m_rcTrack ) * m_nPageSize / ( m_nEnd - m_nStart ), + int nThumbHeight = std::max( RectHeight( m_rcTrack ) * m_nPageSize / ( m_nEnd - m_nStart ), SCROLLBAR_MINTHUMBSIZE ); int nMaxPosition = m_nEnd - m_nStart - m_nPageSize; m_rcThumb.top = m_rcTrack.top + ( m_nPosition - m_nStart ) * ( RectHeight( m_rcTrack ) - nThumbHeight ) @@ -5144,7 +4545,7 @@ void CDXUTScrollBar::UpdateThumbRect() //-------------------------------------------------------------------------------------- // Scroll() scrolls by nDelta items. A positive value scrolls down, while a negative // value scrolls up. -void CDXUTScrollBar::Scroll( int nDelta ) +void CDXUTScrollBar::Scroll( _In_ int nDelta ) { // Perform scroll m_nPosition += nDelta; @@ -5158,7 +4559,7 @@ void CDXUTScrollBar::Scroll( int nDelta ) //-------------------------------------------------------------------------------------- -void CDXUTScrollBar::ShowItem( int nIndex ) +void CDXUTScrollBar::ShowItem( _In_ int nIndex ) { // Cap the index @@ -5180,15 +4581,23 @@ void CDXUTScrollBar::ShowItem( int nIndex ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTScrollBar::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } //-------------------------------------------------------------------------------------- -bool CDXUTScrollBar::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTScrollBar::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + static int ThumbOffsetY; m_LastMouse = pt; @@ -5298,8 +4707,11 @@ bool CDXUTScrollBar::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPa //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTScrollBar::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + if( WM_CAPTURECHANGED == uMsg ) { // The application just lost mouse capture. We may not have gotten @@ -5313,7 +4725,7 @@ bool CDXUTScrollBar::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTScrollBar::Render( float fElapsedTime ) +void CDXUTScrollBar::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -5383,28 +4795,28 @@ void CDXUTScrollBar::Render( float fElapsedTime ) float fBlendRate = ( iState == DXUT_STATE_PRESSED ) ? 0.0f : 0.8f; // Background track layer - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcTrack, DXUT_FAR_BUTTON_DEPTH ); // Up Arrow - pElement = m_Elements.GetAt( 1 ); + pElement = m_Elements[ 1 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcUpButton, DXUT_NEAR_BUTTON_DEPTH ); // Down Arrow - pElement = m_Elements.GetAt( 2 ); + pElement = m_Elements[ 2 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); m_pDialog->DrawSprite( pElement, &m_rcDownButton, DXUT_NEAR_BUTTON_DEPTH ); // Thumb button - pElement = m_Elements.GetAt( 3 ); + pElement = m_Elements[ 3 ]; // Blend current color pElement->TextureColor.Blend( iState, fElapsedTime, fBlendRate ); @@ -5414,7 +4826,7 @@ void CDXUTScrollBar::Render( float fElapsedTime ) //-------------------------------------------------------------------------------------- -void CDXUTScrollBar::SetTrackRange( int nStart, int nEnd ) +void CDXUTScrollBar::SetTrackRange( _In_ int nStart, _In_ int nEnd ) { m_nStart = nStart; m_nEnd = nEnd; Cap(); @@ -5434,12 +4846,12 @@ void CDXUTScrollBar::Cap() // Clips position at boundaries. Ensures it stays wi m_nPosition = m_nEnd - m_nPageSize + 1; } -//-------------------------------------------------------------------------------------- + +//====================================================================================== // CDXUTListBox class -//-------------------------------------------------------------------------------------- +//====================================================================================== -//-------------------------------------------------------------------------------------- -CDXUTListBox::CDXUTListBox( CDXUTDialog* pDialog ) : m_ScrollBar( pDialog ) +CDXUTListBox::CDXUTListBox( _In_opt_ CDXUTDialog* pDialog ) : m_ScrollBar( pDialog ) { m_Type = DXUT_CONTROL_LISTBOX; m_pDialog = pDialog; @@ -5476,7 +4888,7 @@ void CDXUTListBox::UpdateRects() // Update the scrollbar's rects m_ScrollBar.SetLocation( m_rcBoundingBox.right - m_nSBWidth, m_rcBoundingBox.top ); m_ScrollBar.SetSize( m_nSBWidth, m_height ); - DXUTFontNode* pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements.GetAt( 0 )->iFont ); + auto pFontNode = m_pDialog->GetManager()->GetFontNode( m_Elements[ 0 ]->iFont ); if( pFontNode && pFontNode->nHeight ) { m_ScrollBar.SetPageSize( RectHeight( m_rcText ) / pFontNode->nHeight ); @@ -5489,9 +4901,10 @@ void CDXUTListBox::UpdateRects() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTListBox::AddItem( const WCHAR* wszText, void* pData ) { - DXUTListBoxItem* pNewItem = new DXUTListBoxItem; + auto pNewItem = new (std::nothrow) DXUTListBoxItem; if( !pNewItem ) return E_OUTOFMEMORY; @@ -5500,24 +4913,18 @@ HRESULT CDXUTListBox::AddItem( const WCHAR* wszText, void* pData ) SetRect( &pNewItem->rcActive, 0, 0, 0, 0 ); pNewItem->bSelected = false; - HRESULT hr = m_Items.Add( pNewItem ); - if( FAILED( hr ) ) - { - SAFE_DELETE( pNewItem ); - } - else - { - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - } + m_Items.push_back( pNewItem ); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); - return hr; + return S_OK; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTListBox::InsertItem( int nIndex, const WCHAR* wszText, void* pData ) { - DXUTListBoxItem* pNewItem = new DXUTListBoxItem; + auto pNewItem = new (std::nothrow) DXUTListBoxItem; if( !pNewItem ) return E_OUTOFMEMORY; @@ -5526,56 +4933,50 @@ HRESULT CDXUTListBox::InsertItem( int nIndex, const WCHAR* wszText, void* pData SetRect( &pNewItem->rcActive, 0, 0, 0, 0 ); pNewItem->bSelected = false; - HRESULT hr = m_Items.Insert( nIndex, pNewItem ); - if( SUCCEEDED( hr ) ) - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - else - SAFE_DELETE( pNewItem ); + m_Items[ nIndex ] = pNewItem; + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); - return hr; + return S_OK; } //-------------------------------------------------------------------------------------- -void CDXUTListBox::RemoveItem( int nIndex ) +void CDXUTListBox::RemoveItem( _In_ int nIndex ) { - if( nIndex < 0 || nIndex >= ( int )m_Items.GetSize() ) + if( nIndex < 0 || nIndex >= ( int )m_Items.size() ) return; - DXUTListBoxItem* pItem = m_Items.GetAt( nIndex ); - + auto it = m_Items.begin() + nIndex; + auto pItem = *it; delete pItem; - m_Items.Remove( nIndex ); - m_ScrollBar.SetTrackRange( 0, m_Items.GetSize() ); - if( m_nSelected >= ( int )m_Items.GetSize() ) - m_nSelected = m_Items.GetSize() - 1; + m_Items.erase(it); + m_ScrollBar.SetTrackRange( 0, (int)m_Items.size() ); + if( m_nSelected >= ( int )m_Items.size() ) + m_nSelected = int( m_Items.size() ) - 1; m_pDialog->SendEvent( EVENT_LISTBOX_SELECTION, true, this ); } - - - //-------------------------------------------------------------------------------------- void CDXUTListBox::RemoveAllItems() { - for( int i = 0; i < m_Items.GetSize(); ++i ) + for( auto it = m_Items.begin(); it != m_Items.end(); ++it ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = *it; delete pItem; } - m_Items.RemoveAll(); + m_Items.clear(); m_ScrollBar.SetTrackRange( 0, 1 ); } //-------------------------------------------------------------------------------------- -DXUTListBoxItem* CDXUTListBox::GetItem( int nIndex ) +DXUTListBoxItem* CDXUTListBox::GetItem( _In_ int nIndex ) const { - if( nIndex < 0 || nIndex >= ( int )m_Items.GetSize() ) - return NULL; + if( nIndex < 0 || nIndex >= ( int )m_Items.size() ) + return nullptr; return m_Items[nIndex]; } @@ -5588,7 +4989,7 @@ DXUTListBoxItem* CDXUTListBox::GetItem( int nIndex ) // subsequent searches, the app passes the returned index back to GetSelectedIndex as. // nPreviousSelected. // Returns -1 on error or if no item is selected. -int CDXUTListBox::GetSelectedIndex( int nPreviousSelected ) +int CDXUTListBox::GetSelectedIndex( _In_ int nPreviousSelected ) const { if( nPreviousSelected < -1 ) return -1; @@ -5596,9 +4997,9 @@ int CDXUTListBox::GetSelectedIndex( int nPreviousSelected ) if( m_dwStyle & MULTISELECTION ) { // Multiple selection enabled. Search for the next item with the selected flag. - for( int i = nPreviousSelected + 1; i < ( int )m_Items.GetSize(); ++i ) + for( int i = nPreviousSelected + 1; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; if( pItem->bSelected ) return i; @@ -5615,10 +5016,10 @@ int CDXUTListBox::GetSelectedIndex( int nPreviousSelected ) //-------------------------------------------------------------------------------------- -void CDXUTListBox::SelectItem( int nNewIndex ) +void CDXUTListBox::SelectItem( _In_ int nNewIndex ) { // If no item exists, do nothing. - if( m_Items.GetSize() == 0 ) + if( m_Items.size() == 0 ) return; int nOldSelected = m_nSelected; @@ -5629,8 +5030,8 @@ void CDXUTListBox::SelectItem( int nNewIndex ) // Perform capping if( m_nSelected < 0 ) m_nSelected = 0; - if( m_nSelected >= ( int )m_Items.GetSize() ) - m_nSelected = m_Items.GetSize() - 1; + if( m_nSelected >= ( int )m_Items.size() ) + m_nSelected = int( m_Items.size() ) - 1; if( nOldSelected != m_nSelected ) { @@ -5651,6 +5052,7 @@ void CDXUTListBox::SelectItem( int nNewIndex ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) @@ -5673,7 +5075,7 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) case VK_END: { // If no item exists, do nothing. - if( m_Items.GetSize() == 0 ) + if( m_Items.size() == 0 ) return true; int nOldSelected = m_nSelected; @@ -5692,14 +5094,14 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) case VK_HOME: m_nSelected = 0; break; case VK_END: - m_nSelected = m_Items.GetSize() - 1; break; + m_nSelected = int( m_Items.size() ) - 1; break; } // Perform capping if( m_nSelected < 0 ) m_nSelected = 0; - if( m_nSelected >= ( int )m_Items.GetSize() ) - m_nSelected = m_Items.GetSize() - 1; + if( m_nSelected >= ( int )m_Items.size() ) + m_nSelected = int( m_Items.size() ) - 1; if( nOldSelected != m_nSelected ) { @@ -5708,9 +5110,9 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) // Multiple selection // Clear all selection - for( int i = 0; i < ( int )m_Items.GetSize(); ++i ) + for( int i = 0; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items[i]; + auto pItem = m_Items[i]; pItem->bSelected = false; } @@ -5718,9 +5120,9 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { // Select all items from m_nSelStart to // m_nSelected - int nEnd = __max( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); - for( int n = __min( m_nSelStart, m_nSelected ); n <= nEnd; ++n ) + for( int n = std::min( m_nSelStart, m_nSelected ); n <= nEnd; ++n ) m_Items[n]->bSelected = true; } else @@ -5759,7 +5161,8 @@ bool CDXUTListBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTListBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) return false; @@ -5778,7 +5181,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: // Check for clicks in the text area - if( m_Items.GetSize() > 0 && PtInRect( &m_rcSelection, pt ) ) + if( !m_Items.empty() && PtInRect( &m_rcSelection, pt ) ) { // Compute the index of the clicked item @@ -5791,7 +5194,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Only proceed if the click falls on top of an item. if( nClicked >= m_ScrollBar.GetTrackPos() && - nClicked < ( int )m_Items.GetSize() && + nClicked < ( int )m_Items.size() && nClicked < m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize() ) { SetCapture( DXUTGetHWND() ); @@ -5817,7 +5220,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara { // Determine behavior based on the state of Shift and Ctrl - DXUTListBoxItem* pSelItem = m_Items.GetAt( m_nSelected ); + auto pSelItem = m_Items[ m_nSelected ]; if( ( wParam & ( MK_SHIFT | MK_CONTROL ) ) == MK_CONTROL ) { // Control click. Reverse the selection of this item. @@ -5830,24 +5233,24 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // from last selected item to the current item. // Clear everything else. - int nBegin = __min( m_nSelStart, m_nSelected ); - int nEnd = __max( m_nSelStart, m_nSelected ); + int nBegin = std::min( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); for( int i = 0; i < nBegin; ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = false; } - for( int i = nEnd + 1; i < ( int )m_Items.GetSize(); ++i ) + for( int i = nEnd + 1; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = false; } for( int i = nBegin; i <= nEnd; ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = true; } } @@ -5860,15 +5263,15 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // the same state as m_nSelStart, not including m_nSelected. // Set m_nSelected to selected. - int nBegin = __min( m_nSelStart, m_nSelected ); - int nEnd = __max( m_nSelStart, m_nSelected ); + int nBegin = std::min( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); // The two ends do not need to be set here. - bool bLastSelected = m_Items.GetAt( m_nSelStart )->bSelected; + bool bLastSelected = m_Items[ m_nSelStart ]->bSelected; for( int i = nBegin + 1; i < nEnd; ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = bLastSelected; } @@ -5885,9 +5288,9 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // item. - for( int i = 0; i < ( int )m_Items.GetSize(); ++i ) + for( int i = 0; i < ( int )m_Items.size(); ++i ) { - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; pItem->bSelected = false; } @@ -5911,9 +5314,9 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara { // Set all items between m_nSelStart and m_nSelected to // the same state as m_nSelStart - int nEnd = __max( m_nSelStart, m_nSelected ); + int nEnd = std::max( m_nSelStart, m_nSelected ); - for( int n = __min( m_nSelStart, m_nSelected ) + 1; n < nEnd; ++n ) + for( int n = std::min( m_nSelStart, m_nSelected ) + 1; n < nEnd; ++n ) m_Items[n]->bSelected = m_Items[m_nSelStart]->bSelected; m_Items[m_nSelected]->bSelected = m_Items[m_nSelStart]->bSelected; @@ -5942,7 +5345,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Only proceed if the cursor is on top of an item. if( nItem >= ( int )m_ScrollBar.GetTrackPos() && - nItem < ( int )m_Items.GetSize() && + nItem < ( int )m_Items.size() && nItem < m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize() ) { m_nSelected = nItem; @@ -5959,7 +5362,7 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara { // User drags the mouse below window bottom m_ScrollBar.Scroll( 1 ); - m_nSelected = __min( ( int )m_Items.GetSize(), m_ScrollBar.GetTrackPos() + + m_nSelected = std::min( ( int )m_Items.size(), m_ScrollBar.GetTrackPos() + m_ScrollBar.GetPageSize() ) - 1; m_pDialog->SendEvent( EVENT_LISTBOX_SELECTION, true, this ); } @@ -5968,8 +5371,9 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara case WM_MOUSEWHEEL: { - UINT uLines; - SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &uLines, 0 ); + UINT uLines = 0; + if ( !SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &uLines, 0 ) ) + uLines = 0; int nScrollAmount = int( ( short )HIWORD( wParam ) ) / WHEEL_DELTA * uLines; m_ScrollBar.Scroll( -nScrollAmount ); return true; @@ -5981,8 +5385,11 @@ bool CDXUTListBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTListBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + if( WM_CAPTURECHANGED == uMsg ) { // The application just lost mouse capture. We may not have gotten @@ -5996,23 +5403,23 @@ bool CDXUTListBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTListBox::Render( float fElapsedTime ) +void CDXUTListBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; - CDXUTElement* pElement = m_Elements.GetAt( 0 ); + auto pElement = m_Elements[ 0 ]; pElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); pElement->FontColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); - CDXUTElement* pSelElement = m_Elements.GetAt( 1 ); + auto pSelElement = m_Elements[ 1 ]; pSelElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); pSelElement->FontColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); m_pDialog->DrawSprite( pElement, &m_rcBoundingBox, DXUT_FAR_BUTTON_DEPTH ); // Render the text - if( m_Items.GetSize() > 0 ) + if( !m_Items.empty() ) { // Find out the height of a single line of text RECT rc = m_rcText; @@ -6034,12 +5441,12 @@ void CDXUTListBox::Render( float fElapsedTime ) } rc.right = m_rcText.right; - for( int i = m_ScrollBar.GetTrackPos(); i < ( int )m_Items.GetSize(); ++i ) + for( int i = m_ScrollBar.GetTrackPos(); i < ( int )m_Items.size(); ++i ) { if( rc.bottom > m_rcText.bottom ) break; - DXUTListBoxItem* pItem = m_Items.GetAt( i ); + auto pItem = m_Items[ i ]; // Determine if we need to render this item with the // selected element. @@ -6076,34 +5483,19 @@ void CDXUTListBox::Render( float fElapsedTime ) } -// Static member initialization -HINSTANCE CUniBuffer::s_hDll = NULL; -HRESULT ( WINAPI*CUniBuffer::_ScriptApplyDigitSubstitution )( const SCRIPT_DIGITSUBSTITUTE*, SCRIPT_CONTROL*, - SCRIPT_STATE* ) = Dummy_ScriptApplyDigitSubstitution; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringAnalyse )( HDC, const void*, int, int, int, DWORD, int, SCRIPT_CONTROL*, - SCRIPT_STATE*, const int*, SCRIPT_TABDEF*, const BYTE*, - SCRIPT_STRING_ANALYSIS* ) = Dummy_ScriptStringAnalyse; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringCPtoX )( SCRIPT_STRING_ANALYSIS, int, BOOL, int* ) = Dummy_ScriptStringCPtoX; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringXtoCP )( SCRIPT_STRING_ANALYSIS, int, int*, int* ) = Dummy_ScriptStringXtoCP; -HRESULT ( WINAPI*CUniBuffer::_ScriptStringFree )( SCRIPT_STRING_ANALYSIS* ) = Dummy_ScriptStringFree; -const SCRIPT_LOGATTR* ( WINAPI*CUniBuffer::_ScriptString_pLogAttr )( SCRIPT_STRING_ANALYSIS ) = - Dummy_ScriptString_pLogAttr; -const int* ( WINAPI*CUniBuffer::_ScriptString_pcOutChars )( SCRIPT_STRING_ANALYSIS ) = - Dummy_ScriptString_pcOutChars; -bool CDXUTEditBox::s_bHideCaret; // If true, we don't render the caret. - - - -//-------------------------------------------------------------------------------------- +//====================================================================================== // CDXUTEditBox class -//-------------------------------------------------------------------------------------- +//====================================================================================== + +// Static member initialization +bool CDXUTEditBox::s_bHideCaret; // If true, we don't render the caret. // When scrolling, EDITBOX_SCROLLEXTENT is reciprocal of the amount to scroll. // If EDITBOX_SCROLLEXTENT = 4, then we scroll 1/4 of the control each time. #define EDITBOX_SCROLLEXTENT 4 //-------------------------------------------------------------------------------------- -CDXUTEditBox::CDXUTEditBox( CDXUTDialog* pDialog ) +CDXUTEditBox::CDXUTEditBox( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_EDITBOX; m_pDialog = pDialog; @@ -6137,7 +5529,7 @@ CDXUTEditBox::~CDXUTEditBox() // PlaceCaret: Set the caret to a character position, and adjust the scrolling if // necessary. //-------------------------------------------------------------------------------------- -void CDXUTEditBox::PlaceCaret( int nCP ) +void CDXUTEditBox::PlaceCaret( _In_ int nCP ) { assert( nCP >= 0 && nCP <= m_Buffer.GetTextSize() ); m_nCaret = nCP; @@ -6146,7 +5538,7 @@ void CDXUTEditBox::PlaceCaret( int nCP ) int nX1st, nX, nX2; m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nX1st ); // 1st visible char m_Buffer.CPtoX( nCP, FALSE, &nX ); // LEAD - // If nCP is the NULL terminator, get the leading edge instead of trailing. + // If nCP is the nul terminator, get the leading edge instead of trailing. if( nCP == m_Buffer.GetTextSize() ) nX2 = nX; else @@ -6194,9 +5586,9 @@ void CDXUTEditBox::ClearText() //-------------------------------------------------------------------------------------- -void CDXUTEditBox::SetText( LPCWSTR wszText, bool bSelected ) +void CDXUTEditBox::SetText( _In_z_ LPCWSTR wszText, _In_ bool bSelected ) { - assert( wszText != NULL ); + assert( wszText ); m_Buffer.SetText( wszText ); m_nFirstVisible = 0; @@ -6207,8 +5599,8 @@ void CDXUTEditBox::SetText( LPCWSTR wszText, bool bSelected ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTEditBox::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ) +_Use_decl_annotations_ +HRESULT CDXUTEditBox::GetTextCopy( LPWSTR strDest, UINT bufferCount ) const { assert( strDest ); @@ -6221,8 +5613,8 @@ HRESULT CDXUTEditBox::GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, //-------------------------------------------------------------------------------------- void CDXUTEditBox::DeleteSelectionText() { - int nFirst = __min( m_nCaret, m_nSelStart ); - int nLast = __max( m_nCaret, m_nSelStart ); + int nFirst = std::min( m_nCaret, m_nSelStart ); + int nLast = std::max( m_nCaret, m_nSelStart ); // Update caret and selection PlaceCaret( nFirst ); m_nSelStart = m_nCaret; @@ -6258,23 +5650,27 @@ void CDXUTEditBox::UpdateRects() } +#pragma warning(push) +#pragma warning( disable : 4616 6386 ) void CDXUTEditBox::CopyToClipboard() { // Copy the selection text to the clipboard - if( m_nCaret != m_nSelStart && OpenClipboard( NULL ) ) + if( m_nCaret != m_nSelStart && OpenClipboard( nullptr ) ) { EmptyClipboard(); HGLOBAL hBlock = GlobalAlloc( GMEM_MOVEABLE, sizeof( WCHAR ) * ( m_Buffer.GetTextSize() + 1 ) ); if( hBlock ) { - WCHAR* pwszText = ( WCHAR* )GlobalLock( hBlock ); + auto pwszText = reinterpret_cast<WCHAR*>( GlobalLock( hBlock ) ); if( pwszText ) { - int nFirst = __min( m_nCaret, m_nSelStart ); - int nLast = __max( m_nCaret, m_nSelStart ); + int nFirst = std::min( m_nCaret, m_nSelStart ); + int nLast = std::max( m_nCaret, m_nSelStart ); if( nLast - nFirst > 0 ) - CopyMemory( pwszText, m_Buffer.GetBuffer() + nFirst, ( nLast - nFirst ) * sizeof( WCHAR ) ); + { + memcpy( pwszText, m_Buffer.GetBuffer() + nFirst, ( nLast - nFirst ) * sizeof( WCHAR ) ); + } pwszText[nLast - nFirst] = L'\0'; // Terminate it GlobalUnlock( hBlock ); } @@ -6292,19 +5688,19 @@ void CDXUTEditBox::PasteFromClipboard() { DeleteSelectionText(); - if( OpenClipboard( NULL ) ) + if( OpenClipboard( nullptr ) ) { HANDLE handle = GetClipboardData( CF_UNICODETEXT ); if( handle ) { // Convert the ANSI string to Unicode, then // insert to our buffer. - WCHAR* pwszText = ( WCHAR* )GlobalLock( handle ); + auto pwszText = reinterpret_cast<WCHAR*>( GlobalLock( handle ) ); if( pwszText ) { // Copy all characters up to null. if( m_Buffer.InsertString( m_nCaret, pwszText ) ) - PlaceCaret( m_nCaret + lstrlenW( pwszText ) ); + PlaceCaret( m_nCaret + (int)wcslen( pwszText ) ); m_nSelStart = m_nCaret; GlobalUnlock( handle ); } @@ -6312,11 +5708,15 @@ void CDXUTEditBox::PasteFromClipboard() CloseClipboard(); } } +#pragma warning(pop) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTEditBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -6441,8 +5841,12 @@ bool CDXUTEditBox::HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -bool CDXUTEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTEditBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; @@ -6462,9 +5866,9 @@ bool CDXUTEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Determine the character corresponding to the coordinates. int nCP, nTrail, nX1st; m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nX1st ); // X offset of the 1st visible char - if( SUCCEEDED( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) ) + if( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) { - // Cap at the NULL character. + // Cap at the nul character. if( nTrail && nCP < m_Buffer.GetTextSize() ) PlaceCaret( nCP + 1 ); else @@ -6486,9 +5890,9 @@ bool CDXUTEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lPara // Determine the character corresponding to the coordinates. int nCP, nTrail, nX1st; m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nX1st ); // X offset of the 1st visible char - if( SUCCEEDED( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) ) + if( m_Buffer.XtoCP( pt.x - m_rcText.left + nX1st, &nCP, &nTrail ) ) { - // Cap at the NULL character. + // Cap at the nul character. if( nTrail && nCP < m_Buffer.GetTextSize() ) PlaceCaret( nCP + 1 ); else @@ -6512,14 +5916,17 @@ void CDXUTEditBox::OnFocusIn() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(lParam); + if( !m_bEnabled || !m_bVisible ) return false; switch( uMsg ) { - // Make sure that while editing, the keyup and keydown messages associated with + // Make sure that while editing, the keyup and keydown messages associated with // WM_CHAR messages don't go to any non-focused controls or cameras case WM_KEYUP: case WM_KEYDOWN: @@ -6611,7 +6018,7 @@ bool CDXUTEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) case 16: // Ctrl P case 27: // Ctrl [ case 29: // Ctrl ] - case 28: // Ctrl \ + case 28: // Ctrl backslash break; default: @@ -6652,15 +6059,14 @@ bool CDXUTEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTEditBox::Render( float fElapsedTime ) +void CDXUTEditBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; - HRESULT hr; int nSelStartX = 0, nCaretX = 0; // Left and right X cordinates of the selection region - CDXUTElement* pElement = GetElement( 0 ); + auto pElement = GetElement( 0 ); if( pElement ) { m_Buffer.SetFontNode( m_pDialog->GetFont( pElement->iFont ) ); @@ -6671,7 +6077,7 @@ void CDXUTEditBox::Render( float fElapsedTime ) // Render the control graphics for( int e = 0; e < 9; ++e ) { - pElement = m_Elements.GetAt( e ); + pElement = m_Elements[ e ]; pElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); m_pDialog->DrawSprite( pElement, &m_rcRender[e], DXUT_FAR_BUTTON_DEPTH ); @@ -6686,9 +6092,9 @@ void CDXUTEditBox::Render( float fElapsedTime ) // // Compute the X coordinates of the selection rectangle // - hr = m_Buffer.CPtoX( m_nCaret, FALSE, &nCaretX ); + m_Buffer.CPtoX( m_nCaret, FALSE, &nCaretX ); if( m_nCaret != m_nSelStart ) - hr = m_Buffer.CPtoX( m_nSelStart, FALSE, &nSelStartX ); + m_Buffer.CPtoX( m_nSelStart, FALSE, &nSelStartX ); else nSelStartX = nCaretX; @@ -6709,29 +6115,23 @@ void CDXUTEditBox::Render( float fElapsedTime ) OffsetRect( &rcSelection, m_rcText.left - nXFirst, 0 ); IntersectRect( &rcSelection, &m_rcText, &rcSelection ); - IDirect3DDevice9* pd3dDevice = m_pDialog->GetManager()->GetD3D9Device(); - if( pd3dDevice ) - pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE ); m_pDialog->DrawRect( &rcSelection, m_SelBkColor ); - if( pd3dDevice ) - pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); } // // Render the text // // Element 0 for text - m_Elements.GetAt( 0 )->FontColor.Current = m_TextColor; - m_pDialog->DrawText( m_Buffer.GetBuffer() + m_nFirstVisible, m_Elements.GetAt( 0 ), &m_rcText ); + m_Elements[ 0 ]->FontColor.SetCurrent( m_TextColor ); + m_pDialog->DrawText( m_Buffer.GetBuffer() + m_nFirstVisible, m_Elements[ 0 ], &m_rcText ); // Render the selected text if( m_nCaret != m_nSelStart ) { - int nFirstToRender = __max( m_nFirstVisible, __min( m_nSelStart, m_nCaret ) ); - int nNumChatToRender = __max( m_nSelStart, m_nCaret ) - nFirstToRender; - m_Elements.GetAt( 0 )->FontColor.Current = m_SelTextColor; + int nFirstToRender = std::max( m_nFirstVisible, std::min( m_nSelStart, m_nCaret ) ); + m_Elements[ 0 ]->FontColor.SetCurrent( m_SelTextColor ); m_pDialog->DrawText( m_Buffer.GetBuffer() + nFirstToRender, - m_Elements.GetAt( 0 ), &rcSelection, false, nNumChatToRender ); + m_Elements[ 0 ], &rcSelection, false ); } // @@ -6773,6 +6173,7 @@ void CDXUTEditBox::Render( float fElapsedTime ) #define IN_FLOAT_CHARSET( c ) \ ( (c) == L'-' || (c) == L'.' || ( (c) >= L'0' && (c) <= L'9' ) ) +_Use_decl_annotations_ void CDXUTEditBox::ParseFloatArray( float* pNumbers, int nCount ) { int nWritten = 0; // Number of floats written @@ -6795,9 +6196,9 @@ void CDXUTEditBox::ParseFloatArray( float* pNumbers, int nCount ) ++pEnd; // Copy the token to our buffer - int nTokenLen = __min( sizeof( wszToken ) / sizeof( wszToken[0] ) - 1, int( pEnd - pToken ) ); + int nTokenLen = std::min<int>( sizeof( wszToken ) / sizeof( wszToken[0] ) - 1, int( pEnd - pToken ) ); wcscpy_s( wszToken, nTokenLen, pToken ); - *pNumbers = ( float )wcstod( wszToken, NULL ); + *pNumbers = ( float )wcstod( wszToken, nullptr ); ++nWritten; ++pNumbers; pToken = pEnd; @@ -6805,6 +6206,8 @@ void CDXUTEditBox::ParseFloatArray( float* pNumbers, int nCount ) } +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTEditBox::SetTextFloatArray( const float* pNumbers, int nCount ) { WCHAR wszBuffer[512] = @@ -6813,7 +6216,7 @@ void CDXUTEditBox::SetTextFloatArray( const float* pNumbers, int nCount ) }; WCHAR wszTmp[64]; - if( pNumbers == NULL ) + if( !pNumbers ) return; for( int i = 0; i < nCount; ++i ) @@ -6830,54 +6233,24 @@ void CDXUTEditBox::SetTextFloatArray( const float* pNumbers, int nCount ) } - - //-------------------------------------------------------------------------------------- -void CUniBuffer::Initialize() +void CDXUTEditBox::ResetCaretBlink() { - if( s_hDll ) // Only need to do once - return; - - s_hDll = LoadLibrary( UNISCRIBE_DLLNAME ); - if( s_hDll ) - { - FARPROC Temp; - GETPROCADDRESS( s_hDll, ScriptApplyDigitSubstitution, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringAnalyse, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringCPtoX, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringXtoCP, Temp ); - GETPROCADDRESS( s_hDll, ScriptStringFree, Temp ); - GETPROCADDRESS( s_hDll, ScriptString_pLogAttr, Temp ); - GETPROCADDRESS( s_hDll, ScriptString_pcOutChars, Temp ); - } + m_bCaretOn = true; + m_dfLastBlink = DXUTGetGlobalTimer()->GetAbsoluteTime(); } -//-------------------------------------------------------------------------------------- -void CUniBuffer::Uninitialize() -{ - if( s_hDll ) - { - PLACEHOLDERPROC( ScriptApplyDigitSubstitution ); - PLACEHOLDERPROC( ScriptStringAnalyse ); - PLACEHOLDERPROC( ScriptStringCPtoX ); - PLACEHOLDERPROC( ScriptStringXtoCP ); - PLACEHOLDERPROC( ScriptStringFree ); - PLACEHOLDERPROC( ScriptString_pLogAttr ); - PLACEHOLDERPROC( ScriptString_pcOutChars ); - - FreeLibrary( s_hDll ); - s_hDll = NULL; - } -} - +//====================================================================================== +// CUniBuffer +//====================================================================================== //-------------------------------------------------------------------------------------- -bool CUniBuffer::SetBufferSize( int nNewSize ) +bool CUniBuffer::SetBufferSize( _In_ int nNewSize ) { // If the current size is already the maximum allowed, // we can't possibly allocate more. - if( m_nBufferSize == DXUT_MAX_EDITBOXLENGTH ) + if( m_nBufferSize >= DXUT_MAX_EDITBOXLENGTH ) return false; int nAllocateSize = ( nNewSize == -1 || nNewSize < m_nBufferSize * 2 ) ? ( m_nBufferSize ? m_nBufferSize * @@ -6887,7 +6260,7 @@ bool CUniBuffer::SetBufferSize( int nNewSize ) if( nAllocateSize > DXUT_MAX_EDITBOXLENGTH ) nAllocateSize = DXUT_MAX_EDITBOXLENGTH; - WCHAR* pTempBuffer = new WCHAR[nAllocateSize]; + auto pTempBuffer = new (std::nothrow) WCHAR[nAllocateSize]; if( !pTempBuffer ) return false; @@ -6895,7 +6268,7 @@ bool CUniBuffer::SetBufferSize( int nNewSize ) if( m_pwszBuffer ) { - CopyMemory( pTempBuffer, m_pwszBuffer, m_nBufferSize * sizeof( WCHAR ) ); + memcpy( pTempBuffer, m_pwszBuffer, m_nBufferSize * sizeof( WCHAR ) ); delete[] m_pwszBuffer; } @@ -6911,32 +6284,37 @@ bool CUniBuffer::SetBufferSize( int nNewSize ) HRESULT CUniBuffer::Analyse() { if( m_Analysis ) - _ScriptStringFree( &m_Analysis ); + (void)ScriptStringFree( &m_Analysis ); SCRIPT_CONTROL ScriptControl; // For uniscribe SCRIPT_STATE ScriptState; // For uniscribe ZeroMemory( &ScriptControl, sizeof( ScriptControl ) ); ZeroMemory( &ScriptState, sizeof( ScriptState ) ); - _ScriptApplyDigitSubstitution( NULL, &ScriptControl, &ScriptState ); + +#pragma warning(push) +#pragma warning(disable : 4616 6309 6387 ) + HRESULT hr = ScriptApplyDigitSubstitution( nullptr, &ScriptControl, &ScriptState ); + if ( FAILED(hr) ) + return hr; +#pragma warning(pop) if( !m_pFontNode ) return E_FAIL; - HDC hDC = - ( m_pFontNode->pFont9 ? m_pFontNode->pFont9->GetDC() : NULL ); - HRESULT hr = _ScriptStringAnalyse( hDC, - m_pwszBuffer, - lstrlenW( m_pwszBuffer ) + 1, // NULL is also analyzed. - lstrlenW( m_pwszBuffer ) * 3 / 2 + 16, - -1, - SSA_BREAK | SSA_GLYPHS | SSA_FALLBACK | SSA_LINK, - 0, - &ScriptControl, - &ScriptState, - NULL, - NULL, - NULL, - &m_Analysis ); + HDC hDC = nullptr; + hr = ScriptStringAnalyse( hDC, + m_pwszBuffer, + (int)wcslen( m_pwszBuffer ) + 1, // nul is also analyzed. + (int)wcslen( m_pwszBuffer ) * 3 / 2 + 16, + -1, + SSA_BREAK | SSA_GLYPHS | SSA_FALLBACK | SSA_LINK, + 0, + &ScriptControl, + &ScriptState, + nullptr, + nullptr, + nullptr, + &m_Analysis ); if( SUCCEEDED( hr ) ) m_bAnalyseRequired = false; // Analysis is up-to-date return hr; @@ -6944,15 +6322,13 @@ HRESULT CUniBuffer::Analyse() //-------------------------------------------------------------------------------------- -CUniBuffer::CUniBuffer( int nInitialSize ) +CUniBuffer::CUniBuffer( _In_ int nInitialSize ) { - CUniBuffer::Initialize(); // ensure static vars are properly init'ed first - m_nBufferSize = 0; - m_pwszBuffer = NULL; + m_pwszBuffer = nullptr; m_bAnalyseRequired = true; - m_Analysis = NULL; - m_pFontNode = NULL; + m_Analysis = nullptr; + m_pFontNode = nullptr; if( nInitialSize > 0 ) SetBufferSize( nInitialSize ); @@ -6964,12 +6340,12 @@ CUniBuffer::~CUniBuffer() { delete[] m_pwszBuffer; if( m_Analysis ) - _ScriptStringFree( &m_Analysis ); + (void)ScriptStringFree( &m_Analysis ); } //-------------------------------------------------------------------------------------- -WCHAR& CUniBuffer::operator[]( int n ) // No param checking +WCHAR& CUniBuffer::operator[]( _In_ int n ) // No param checking { // This version of operator[] is called only // if we are asking for write access, so @@ -6991,18 +6367,18 @@ void CUniBuffer::Clear() // Inserts the char at specified index. // If nIndex == -1, insert to the end. //-------------------------------------------------------------------------------------- -bool CUniBuffer::InsertChar( int nIndex, WCHAR wChar ) +bool CUniBuffer::InsertChar( _In_ int nIndex, _In_ WCHAR wChar ) { assert( nIndex >= 0 ); - if( nIndex < 0 || nIndex > lstrlenW( m_pwszBuffer ) ) + if( nIndex < 0 || nIndex > (int)wcslen( m_pwszBuffer ) ) return false; // invalid index // Check for maximum length allowed if( GetTextSize() + 1 >= DXUT_MAX_EDITBOXLENGTH ) return false; - if( lstrlenW( m_pwszBuffer ) + 1 >= m_nBufferSize ) + if( (int)wcslen( m_pwszBuffer ) + 1 >= m_nBufferSize ) { if( !SetBufferSize( -1 ) ) return false; // out of memory @@ -7011,7 +6387,7 @@ bool CUniBuffer::InsertChar( int nIndex, WCHAR wChar ) assert( m_nBufferSize >= 2 ); // Shift the characters after the index, start by copying the null terminator - WCHAR* dest = m_pwszBuffer + lstrlenW( m_pwszBuffer ) + 1; + WCHAR* dest = m_pwszBuffer + wcslen( m_pwszBuffer ) + 1; WCHAR* stop = m_pwszBuffer + nIndex; WCHAR* src = dest - 1; @@ -7032,13 +6408,13 @@ bool CUniBuffer::InsertChar( int nIndex, WCHAR wChar ) // Removes the char at specified index. // If nIndex == -1, remove the last char. //-------------------------------------------------------------------------------------- -bool CUniBuffer::RemoveChar( int nIndex ) +bool CUniBuffer::RemoveChar( _In_ int nIndex ) { - if( !lstrlenW( m_pwszBuffer ) || nIndex < 0 || nIndex >= lstrlenW( m_pwszBuffer ) ) + if( !wcslen( m_pwszBuffer ) || nIndex < 0 || nIndex >= (int)wcslen( m_pwszBuffer ) ) return false; // Invalid index MoveMemory( m_pwszBuffer + nIndex, m_pwszBuffer + nIndex + 1, sizeof( WCHAR ) * - ( lstrlenW( m_pwszBuffer ) - nIndex ) ); + ( wcslen( m_pwszBuffer ) - nIndex ) ); m_bAnalyseRequired = true; return true; } @@ -7049,31 +6425,32 @@ bool CUniBuffer::RemoveChar( int nIndex ) // If nCount == -1, the entire string is inserted. // If nIndex == -1, insert to the end. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CUniBuffer::InsertString( int nIndex, const WCHAR* pStr, int nCount ) { assert( nIndex >= 0 ); if( nIndex < 0 ) return false; - if( nIndex > lstrlenW( m_pwszBuffer ) ) + if( nIndex > (int)wcslen( m_pwszBuffer ) ) return false; // invalid index if( -1 == nCount ) - nCount = lstrlenW( pStr ); + nCount = (int)wcslen( pStr ); // Check for maximum length allowed if( GetTextSize() + nCount >= DXUT_MAX_EDITBOXLENGTH ) return false; - if( lstrlenW( m_pwszBuffer ) + nCount >= m_nBufferSize ) + if( (int)wcslen( m_pwszBuffer ) + nCount >= m_nBufferSize ) { - if( !SetBufferSize( lstrlenW( m_pwszBuffer ) + nCount + 1 ) ) + if( !SetBufferSize( (int)wcslen( m_pwszBuffer ) + nCount + 1 ) ) return false; // out of memory } MoveMemory( m_pwszBuffer + nIndex + nCount, m_pwszBuffer + nIndex, sizeof( WCHAR ) * - ( lstrlenW( m_pwszBuffer ) - nIndex + 1 ) ); - CopyMemory( m_pwszBuffer + nIndex, pStr, nCount * sizeof( WCHAR ) ); + ( wcslen( m_pwszBuffer ) - nIndex + 1 ) ); + memcpy( m_pwszBuffer + nIndex, pStr, nCount * sizeof( WCHAR ) ); m_bAnalyseRequired = true; return true; @@ -7081,11 +6458,11 @@ bool CUniBuffer::InsertString( int nIndex, const WCHAR* pStr, int nCount ) //-------------------------------------------------------------------------------------- -bool CUniBuffer::SetText( LPCWSTR wszText ) +bool CUniBuffer::SetText( _In_z_ LPCWSTR wszText ) { - assert( wszText != NULL ); + assert( wszText ); - int nRequired = int( wcslen( wszText ) + 1 ); + size_t nRequired = wcslen( wszText ) + 1; // Check for maximum length allowed if( nRequired >= DXUT_MAX_EDITBOXLENGTH ) @@ -7107,7 +6484,8 @@ bool CUniBuffer::SetText( LPCWSTR wszText ) //-------------------------------------------------------------------------------------- -HRESULT CUniBuffer::CPtoX( int nCP, BOOL bTrail, int* pX ) +_Use_decl_annotations_ +bool CUniBuffer::CPtoX( int nCP, bool bTrail, int* pX ) { assert( pX ); *pX = 0; // Default @@ -7117,14 +6495,21 @@ HRESULT CUniBuffer::CPtoX( int nCP, BOOL bTrail, int* pX ) hr = Analyse(); if( SUCCEEDED( hr ) ) - hr = _ScriptStringCPtoX( m_Analysis, nCP, bTrail, pX ); + hr = ScriptStringCPtoX( m_Analysis, nCP, bTrail, pX ); - return hr; + if ( FAILED(hr) ) + { + *pX = 0; + return false; + } + + return true; } //-------------------------------------------------------------------------------------- -HRESULT CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) +_Use_decl_annotations_ +bool CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) { assert( pCP && pnTrail ); *pCP = 0; *pnTrail = FALSE; // Default @@ -7133,8 +6518,15 @@ HRESULT CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) if( m_bAnalyseRequired ) hr = Analyse(); - if( SUCCEEDED( hr ) ) - hr = _ScriptStringXtoCP( m_Analysis, nX, pCP, pnTrail ); + if (SUCCEEDED(hr)) + { + hr = ScriptStringXtoCP( m_Analysis, nX, pCP, pnTrail ); + if (FAILED(hr)) + { + *pCP = 0; *pnTrail = FALSE; + return false; + } + } // If the coordinate falls outside the text region, we // can get character positions that don't exist. We must @@ -7143,16 +6535,22 @@ HRESULT CUniBuffer::XtoCP( int nX, int* pCP, int* pnTrail ) { *pCP = 0; *pnTrail = FALSE; } - else if( *pCP > lstrlenW( m_pwszBuffer ) && *pnTrail == FALSE ) + else if( *pCP > (int)wcslen( m_pwszBuffer ) && *pnTrail == FALSE ) { - *pCP = lstrlenW( m_pwszBuffer ); *pnTrail = TRUE; + *pCP = (int)wcslen( m_pwszBuffer ); *pnTrail = TRUE; } - return hr; + if (FAILED(hr)) + { + *pCP = 0; *pnTrail = FALSE; + return false; + } + return true; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CUniBuffer::GetPriorItemPos( int nCP, int* pPrior ) { *pPrior = nCP; // Default is the char itself @@ -7161,13 +6559,13 @@ void CUniBuffer::GetPriorItemPos( int nCP, int* pPrior ) if( FAILED( Analyse() ) ) return; - const SCRIPT_LOGATTR* pLogAttr = _ScriptString_pLogAttr( m_Analysis ); + const SCRIPT_LOGATTR* pLogAttr = ScriptString_pLogAttr( m_Analysis ); if( !pLogAttr ) return; - if( !_ScriptString_pcOutChars( m_Analysis ) ) + if( !ScriptString_pcOutChars( m_Analysis ) ) return; - int nInitial = *_ScriptString_pcOutChars( m_Analysis ); + int nInitial = *ScriptString_pcOutChars( m_Analysis ); if( nCP - 1 < nInitial ) nInitial = nCP - 1; for( int i = nInitial; i > 0; --i ) @@ -7184,6 +6582,7 @@ void CUniBuffer::GetPriorItemPos( int nCP, int* pPrior ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CUniBuffer::GetNextItemPos( int nCP, int* pPrior ) { *pPrior = nCP; // Default is the char itself @@ -7194,18 +6593,18 @@ void CUniBuffer::GetNextItemPos( int nCP, int* pPrior ) if( FAILED( hr ) ) return; - const SCRIPT_LOGATTR* pLogAttr = _ScriptString_pLogAttr( m_Analysis ); + const SCRIPT_LOGATTR* pLogAttr = ScriptString_pLogAttr( m_Analysis ); if( !pLogAttr ) return; - if( !_ScriptString_pcOutChars( m_Analysis ) ) + if( !ScriptString_pcOutChars( m_Analysis ) ) return; - int nInitial = *_ScriptString_pcOutChars( m_Analysis ); + int nInitial = *ScriptString_pcOutChars( m_Analysis ); if( nCP + 1 < nInitial ) nInitial = nCP + 1; int i = nInitial; - int limit = *_ScriptString_pcOutChars( m_Analysis ); + int limit = *ScriptString_pcOutChars( m_Analysis ); while( limit > 0 && i < limit - 1 ) { if( pLogAttr[i].fWordStop ) // Either the fWordStop flag is set @@ -7221,23 +6620,20 @@ void CUniBuffer::GetNextItemPos( int nCP, int* pPrior ) } ++i; - limit = *_ScriptString_pcOutChars( m_Analysis ); + limit = *ScriptString_pcOutChars( m_Analysis ); } // We have reached the end. It's always a word stop, so simply return it. - *pPrior = *_ScriptString_pcOutChars( m_Analysis ) - 1; + *pPrior = *ScriptString_pcOutChars( m_Analysis ) - 1; } -//-------------------------------------------------------------------------------------- -void CDXUTEditBox::ResetCaretBlink() -{ - m_bCaretOn = true; - m_dfLastBlink = DXUTGetGlobalTimer()->GetAbsoluteTime(); -} - +//====================================================================================== +// DXUTBlendColor +//====================================================================================== //-------------------------------------------------------------------------------------- -void DXUTBlendColor::Init( D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOLOR hiddenColor ) +_Use_decl_annotations_ +void DXUTBlendColor::Init( DWORD defaultColor, DWORD disabledColor, DWORD hiddenColor ) { for( int i = 0; i < MAX_CONTROL_STATES; i++ ) { @@ -7246,23 +6642,38 @@ void DXUTBlendColor::Init( D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOL States[ DXUT_STATE_DISABLED ] = disabledColor; States[ DXUT_STATE_HIDDEN ] = hiddenColor; - Current = hiddenColor; + SetCurrent( hiddenColor ); } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void DXUTBlendColor::Blend( UINT iState, float fElapsedTime, float fRate ) { - D3DXCOLOR destColor = States[ iState ]; - D3DXColorLerp( &Current, &Current, &destColor, 1.0f - powf( fRate, 30 * fElapsedTime ) ); + XMFLOAT4 destColor = D3DCOLOR_TO_D3DCOLORVALUE( States[ iState ] ); + XMVECTOR clr1 = XMLoadFloat4( &destColor ); + XMVECTOR clr = XMLoadFloat4( &Current ); + clr = XMVectorLerp( clr, clr1, 1.0f - powf( fRate, 30 * fElapsedTime ) ); + XMStoreFloat4( &Current, clr ); } +//-------------------------------------------------------------------------------------- +void DXUTBlendColor::SetCurrent( DWORD color ) +{ + Current = D3DCOLOR_TO_D3DCOLORVALUE( color ); +} + + +//====================================================================================== +// CDXUTElement +//====================================================================================== //-------------------------------------------------------------------------------------- -void CDXUTElement::SetTexture( UINT iTexture, RECT* prcTexture, D3DCOLOR defaultTextureColor ) +_Use_decl_annotations_ +void CDXUTElement::SetTexture( UINT texture, RECT* prcTexture, DWORD defaultTextureColor ) { - this->iTexture = iTexture; + iTexture = texture; if( prcTexture ) rcTexture = *prcTexture; @@ -7274,10 +6685,11 @@ void CDXUTElement::SetTexture( UINT iTexture, RECT* prcTexture, D3DCOLOR default //-------------------------------------------------------------------------------------- -void CDXUTElement::SetFont( UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextFormat ) +_Use_decl_annotations_ +void CDXUTElement::SetFont( UINT font, DWORD defaultFontColor, DWORD textFormat ) { - this->iFont = iFont; - this->dwTextFormat = dwTextFormat; + iFont = font; + dwTextFormat = textFormat; FontColor.Init( defaultFontColor ); } @@ -7286,8 +6698,6 @@ void CDXUTElement::SetFont( UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextF //-------------------------------------------------------------------------------------- void CDXUTElement::Refresh() { - TextureColor.Current = TextureColor.States[ DXUT_STATE_HIDDEN ]; - FontColor.Current = FontColor.States[ DXUT_STATE_HIDDEN ]; + TextureColor.SetCurrent( TextureColor.States[ DXUT_STATE_HIDDEN ] ); + FontColor.SetCurrent( FontColor.States[ DXUT_STATE_HIDDEN ] ); } - - diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTgui.h b/samples/DX_APIUsage/DXUT/Optional/DXUTgui.h index cae713c..71fcfb4 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTgui.h +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTgui.h @@ -2,17 +2,22 @@ // File: DXUTgui.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_GUI_H -#define DXUT_GUI_H #include <usp10.h> #include <dimm.h> #include <functional> +#ifdef DXUT_AUTOLIB +#pragma comment( lib, "usp10.lib" ) +#endif + //-------------------------------------------------------------------------------------- -// Defines and macros +// Defines and macros //-------------------------------------------------------------------------------------- #define EVENT_BUTTON_CLICKED 0x0101 #define EVENT_COMBOBOX_SELECTION_CHANGED 0x0201 @@ -50,8 +55,8 @@ class CDXUTElement; struct DXUTElementHolder; struct DXUTTextureNode; struct DXUTFontNode; -typedef VOID ( CALLBACK*PCALLBACKDXUTGUIEVENT )( UINT nEvent, int nControlID, CDXUTControl* pControl, - void* pUserContext ); +typedef void ( CALLBACK*PCALLBACKDXUTGUIEVENT )( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl, + _In_opt_ void* pUserContext ); //-------------------------------------------------------------------------------------- @@ -85,12 +90,13 @@ enum DXUT_CONTROL_STATE struct DXUTBlendColor { - void Init( D3DCOLOR defaultColor, D3DCOLOR disabledColor = D3DCOLOR_ARGB( 200, 128, 128, 128 ), - D3DCOLOR hiddenColor = 0 ); - void Blend( UINT iState, float fElapsedTime, float fRate = 0.7f ); + void Init( _In_ DWORD defaultColor, _In_ DWORD disabledColor = D3DCOLOR_ARGB( 200, 128, 128, 128 ), _In_ DWORD hiddenColor = 0 ); + void Blend( _In_ UINT iState, _In_ float fElapsedTime, _In_ float fRate = 0.7f ); + + DWORD States[ MAX_CONTROL_STATES ]; // Modulate colors for all possible control states + DirectX::XMFLOAT4 Current; - D3DCOLOR States[ MAX_CONTROL_STATES ]; // Modulate colors for all possible control states - D3DXCOLOR Current; + void SetCurrent( DWORD color ); }; @@ -100,17 +106,14 @@ struct DXUTBlendColor class CDXUTElement { public: - void SetTexture( UINT iTexture, RECT* prcTexture, D3DCOLOR defaultTextureColor = D3DCOLOR_ARGB( 255, 255, 255, - 255 ) ); - void SetFont( UINT iFont, D3DCOLOR defaultFontColor = D3DCOLOR_ARGB( 255, 255, 255, - 255 ), DWORD dwTextFormat = DT_CENTER | - DT_VCENTER ); + void SetTexture( _In_ UINT texture, _In_ RECT* prcTexture, _In_ DWORD defaultTextureColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ) ); + void SetFont( _In_ UINT font, _In_ DWORD defaultFontColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ), DWORD textFormat = DT_CENTER | DT_VCENTER ); - void Refresh(); + void Refresh(); - UINT iTexture; // Index of the texture for this Element + UINT iTexture; // Index of the texture for this Element UINT iFont; // Index of the font for this Element - DWORD dwTextFormat; // The format argument to DrawText + DWORD dwTextFormat; // The format argument to DrawText RECT rcTexture; // Bounding rect of this element on the composite texture @@ -128,221 +131,164 @@ class CDXUTDialog friend class CDXUTDialogResourceManager; public: - CDXUTDialog(); - ~CDXUTDialog(); + CDXUTDialog(); + ~CDXUTDialog(); // Need to call this now - void Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog = true ); - void Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, - LPCWSTR pszControlTextureFilename ); - void Init( CDXUTDialogResourceManager* pManager, bool bRegisterDialog, - LPCWSTR szControlTextureResourceName, HMODULE hControlTextureResourceModule ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog = true ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog, + _In_z_ LPCWSTR pszControlTextureFilename ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog, + _In_z_ LPCWSTR szControlTextureResourceName, _In_ HMODULE hControlTextureResourceModule ); // Windows message handler - bool MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); + bool MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); // Control creation - HRESULT AddStatic( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault=false, - CDXUTStatic** ppCreated=NULL ); - HRESULT AddButton(int ID, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey = 0, - bool bIsDefault = false, CDXUTButton** ppCreated = NULL); - HRESULT AddButtonCallback(std::function<void()> cb, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey = 0, - bool bIsDefault = false, CDXUTButton** ppCreated = NULL); - HRESULT AddCheckBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bChecked=false, - UINT nHotkey=0, bool bIsDefault=false, CDXUTCheckBox** ppCreated=NULL ); - HRESULT AddRadioButton( int ID, UINT nButtonGroup, LPCWSTR strText, int x, int y, int width, - int height, bool bChecked=false, UINT nHotkey=0, bool bIsDefault=false, - CDXUTRadioButton** ppCreated=NULL ); - HRESULT AddComboBox( int ID, int x, int y, int width, int height, UINT nHotKey=0, bool bIsDefault= - false, CDXUTComboBox** ppCreated=NULL ); - HRESULT AddSlider( int ID, int x, int y, int width, int height, int min=0, int max=100, int value=50, - bool bIsDefault=false, CDXUTSlider** ppCreated=NULL ); + HRESULT AddStatic( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTStatic** ppCreated = nullptr ); + HRESULT AddButton( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotkey=0, + _In_ bool bIsDefault=false, _Out_opt_ CDXUTButton** ppCreated = nullptr ); + HRESULT AddButtonCallback(_In_ std::function<void()> cb, _In_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotkey = 0, + _In_ bool bIsDefault = false, _Out_opt_ CDXUTButton** ppCreated = NULL); + HRESULT AddCheckBox( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bChecked=false, + _In_ UINT nHotkey=0, _In_ bool bIsDefault=false, _Out_opt_ CDXUTCheckBox** ppCreated = nullptr ); + HRESULT AddRadioButton( _In_ int ID, _In_ UINT nButtonGroup, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, + _In_ int height, _In_ bool bChecked=false, _In_ UINT nHotkey=0, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTRadioButton** ppCreated = nullptr ); + HRESULT AddComboBox( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotKey=0, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTComboBox** ppCreated = nullptr ); + HRESULT AddSlider( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ int min=0, _In_ int max=100, _In_ int value=50, + _In_ bool bIsDefault=false, _Out_opt_ CDXUTSlider** ppCreated = nullptr ); // AddIMEEditBox has been renamed into DXUTguiIME.cpp as CDXUTIMEEditBox::CreateIMEEditBox - HRESULT AddEditBox( int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault= - false, CDXUTEditBox** ppCreated=NULL ); - HRESULT AddListBox( int ID, int x, int y, int width, int height, DWORD dwStyle=0, - CDXUTListBox** ppCreated=NULL ); - HRESULT AddControl( CDXUTControl* pControl ); - HRESULT InitControl( CDXUTControl* pControl ); + HRESULT AddEditBox( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bIsDefault=false, + _Out_opt_ CDXUTEditBox** ppCreated = nullptr ); + HRESULT AddListBox( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ DWORD dwStyle=0, + _Out_opt_ CDXUTListBox** ppCreated = nullptr ); + HRESULT AddControl( _In_ CDXUTControl* pControl ); + HRESULT InitControl( _In_ CDXUTControl* pControl ); // Control retrieval - CDXUTStatic* GetStatic( int ID ) + CDXUTStatic* GetStatic( _In_ int ID ) const { - return ( CDXUTStatic* )GetControl( ID, DXUT_CONTROL_STATIC ); + return reinterpret_cast<CDXUTStatic*>( GetControl( ID, DXUT_CONTROL_STATIC ) ); } - CDXUTButton* GetButton( int ID ) + CDXUTButton* GetButton( _In_ int ID ) const { - return ( CDXUTButton* )GetControl( ID, DXUT_CONTROL_BUTTON ); + return reinterpret_cast<CDXUTButton*>( GetControl(ID, DXUT_CONTROL_BUTTON) ); } - CDXUTCheckBox* GetCheckBox( int ID ) + CDXUTCheckBox* GetCheckBox( _In_ int ID ) const { - return ( CDXUTCheckBox* )GetControl( ID, DXUT_CONTROL_CHECKBOX ); + return reinterpret_cast<CDXUTCheckBox*>( GetControl(ID, DXUT_CONTROL_CHECKBOX) ); } - CDXUTRadioButton* GetRadioButton( int ID ) + CDXUTRadioButton* GetRadioButton( _In_ int ID ) const { - return ( CDXUTRadioButton* )GetControl( ID, DXUT_CONTROL_RADIOBUTTON ); + return reinterpret_cast<CDXUTRadioButton*>( GetControl(ID, DXUT_CONTROL_RADIOBUTTON) ); } - CDXUTComboBox* GetComboBox( int ID ) + CDXUTComboBox* GetComboBox( _In_ int ID ) const { - return ( CDXUTComboBox* )GetControl( ID, DXUT_CONTROL_COMBOBOX ); + return reinterpret_cast<CDXUTComboBox*>( GetControl(ID, DXUT_CONTROL_COMBOBOX) ); } - CDXUTSlider* GetSlider( int ID ) + CDXUTSlider* GetSlider( _In_ int ID ) const { - return ( CDXUTSlider* )GetControl( ID, DXUT_CONTROL_SLIDER ); + return reinterpret_cast<CDXUTSlider*>( GetControl(ID, DXUT_CONTROL_SLIDER) ); } - CDXUTEditBox* GetEditBox( int ID ) + CDXUTEditBox* GetEditBox( _In_ int ID ) const { - return ( CDXUTEditBox* )GetControl( ID, DXUT_CONTROL_EDITBOX ); + return reinterpret_cast<CDXUTEditBox*>( GetControl(ID, DXUT_CONTROL_EDITBOX) ); } - CDXUTListBox* GetListBox( int ID ) + CDXUTListBox* GetListBox( _In_ int ID ) const { - return ( CDXUTListBox* )GetControl( ID, DXUT_CONTROL_LISTBOX ); + return reinterpret_cast<CDXUTListBox*>( GetControl(ID, DXUT_CONTROL_LISTBOX) ); } - CDXUTControl* GetControl( int ID ); - CDXUTControl* GetControl( int ID, UINT nControlType ); - CDXUTControl* GetControlAtPoint( POINT pt ); + CDXUTControl* GetControl( _In_ int ID ) const; + CDXUTControl* GetControl( _In_ int ID, _In_ UINT nControlType ) const; + CDXUTControl* GetControlAtPoint( _In_ const POINT& pt ) const; - bool GetControlEnabled( int ID ); - void SetControlEnabled( int ID, bool bEnabled ); + bool GetControlEnabled( _In_ int ID ) const; + void SetControlEnabled( _In_ int ID, _In_ bool bEnabled ); - void ClearRadioButtonGroup( UINT nGroup ); - void ClearComboBox( int ID ); + void ClearRadioButtonGroup( _In_ UINT nGroup ); + void ClearComboBox( _In_ int ID ); // Access the default display Elements used when adding new controls - HRESULT SetDefaultElement( UINT nControlType, UINT iElement, CDXUTElement* pElement ); - CDXUTElement* GetDefaultElement( UINT nControlType, UINT iElement ); + HRESULT SetDefaultElement( _In_ UINT nControlType, _In_ UINT iElement, _In_ CDXUTElement* pElement ); + CDXUTElement* GetDefaultElement( _In_ UINT nControlType, _In_ UINT iElement ) const; // Methods called by controls - void SendEvent( UINT nEvent, bool bTriggeredByUser, CDXUTControl* pControl ); - void RequestFocus( CDXUTControl* pControl ); + void SendEvent( _In_ UINT nEvent, _In_ bool bTriggeredByUser, _In_ CDXUTControl* pControl ); + void RequestFocus( _In_ CDXUTControl* pControl ); // Render helpers - HRESULT DrawRect( RECT* pRect, D3DCOLOR color ); - HRESULT DrawRect9( RECT* pRect, D3DCOLOR color ); - HRESULT DrawPolyLine( POINT* apPoints, UINT nNumPoints, D3DCOLOR color ); - HRESULT DrawSprite( CDXUTElement* pElement, RECT* prcDest, float fDepth ); - HRESULT DrawSprite9( CDXUTElement* pElement, RECT* prcDest ); - HRESULT DrawSprite11( CDXUTElement* pElement, RECT* prcDest, float fDepth ); - HRESULT CalcTextRect( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, int nCount = -1 ); - HRESULT DrawText( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow = false, - int nCount = -1, bool bCenter = false ); - HRESULT DrawText9( LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow = false, - int nCount = -1 ); - HRESULT DrawText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, CDXUTElement* pElement, RECT* prcDest, bool bShadow = false, - int nCount = -1, bool bCenter = false ); + HRESULT DrawRect( _In_ const RECT* pRect, _In_ DWORD color ); + HRESULT DrawSprite( _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ float fDepth ); + HRESULT DrawSprite11( _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ float fDepth ); + HRESULT CalcTextRect( _In_z_ LPCWSTR strText, _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ int nCount = -1 ); + HRESULT DrawText( _In_z_ LPCWSTR strText, _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ bool bShadow = false, + _In_ bool bCenter = false ); // Attributes - bool GetVisible() - { - return m_bVisible; - } - void SetVisible( bool bVisible ) - { - m_bVisible = bVisible; - } - bool GetMinimized() - { - return m_bMinimized; - } - void SetMinimized( bool bMinimized ) - { - m_bMinimized = bMinimized; - } - void SetBackgroundColors( D3DCOLOR colorAllCorners ) - { - SetBackgroundColors( colorAllCorners, colorAllCorners, colorAllCorners, colorAllCorners ); - } - void SetBackgroundColors( D3DCOLOR colorTopLeft, D3DCOLOR colorTopRight, D3DCOLOR colorBottomLeft, - D3DCOLOR colorBottomRight ); - void EnableCaption( bool bEnable ) - { - m_bCaption = bEnable; - } - int GetCaptionHeight() const - { - return m_nCaptionHeight; - } - void SetCaptionHeight( int nHeight ) - { - m_nCaptionHeight = nHeight; - } - void SetCaptionText( const WCHAR* pwszText ) - { - wcscpy_s( m_wszCaption, sizeof( m_wszCaption ) / sizeof( m_wszCaption[0] ), pwszText ); - } - void GetLocation( POINT& Pt ) const + bool GetVisible() const { return m_bVisible; } + void SetVisible( _In_ bool bVisible ) { m_bVisible = bVisible; } + bool GetMinimized() const { return m_bMinimized; } + void SetMinimized( _In_ bool bMinimized ) {m_bMinimized = bMinimized; } + void SetBackgroundColors( _In_ DWORD colorAllCorners ) { SetBackgroundColors( colorAllCorners, colorAllCorners, colorAllCorners, colorAllCorners ); } + void SetBackgroundColors( _In_ DWORD colorTopLeft, _In_ DWORD colorTopRight, _In_ DWORD colorBottomLeft, _In_ DWORD colorBottomRight ); + void EnableCaption( _In_ bool bEnable ) { m_bCaption = bEnable; } + int GetCaptionHeight() const { return m_nCaptionHeight; } + void SetCaptionHeight( _In_ int nHeight ) { m_nCaptionHeight = nHeight; } + void SetCaptionText( _In_ const WCHAR* pwszText ) { wcscpy_s( m_wszCaption, sizeof( m_wszCaption ) / sizeof( m_wszCaption[0] ), pwszText ); } + void GetLocation( _Out_ POINT& Pt ) const { - Pt.x = m_x; Pt.y = m_y; + Pt.x = m_x; + Pt.y = m_y; } - void SetLocation( int x, int y ) + void SetLocation( _In_ int x, _In_ int y ) { - m_x = x; m_y = y; + m_x = x; + m_y = y; } - void SetSize( int width, int height ) + void SetSize( _In_ int width, _In_ int height ) { - m_width = width; m_height = height; - } - int GetWidth() - { - return m_width; - } - int GetHeight() - { - return m_height; + m_width = width; + m_height = height; } + int GetWidth() const { return m_width; } + int GetHeight() const { return m_height; } - static void WINAPI SetRefreshTime( float fTime ) - { - s_fTimeRefresh = fTime; - } + static void WINAPI SetRefreshTime( _In_ float fTime ) { s_fTimeRefresh = fTime; } - static CDXUTControl* WINAPI GetNextControl( CDXUTControl* pControl ); - static CDXUTControl* WINAPI GetPrevControl( CDXUTControl* pControl ); + static CDXUTControl* WINAPI GetNextControl( _In_ CDXUTControl* pControl ); + static CDXUTControl* WINAPI GetPrevControl( _In_ CDXUTControl* pControl ); - void RemoveControl( int ID ); - void RemoveAllControls(); + void RemoveControl( _In_ int ID ); + void RemoveAllControls(); // Sets the callback used to notify the app of control events - void SetCallback( PCALLBACKDXUTGUIEVENT pCallback, void* pUserContext = NULL ); - void EnableNonUserEvents( bool bEnable ) - { - m_bNonUserEvents = bEnable; - } - void EnableKeyboardInput( bool bEnable ) - { - m_bKeyboardInput = bEnable; - } - void EnableMouseInput( bool bEnable ) - { - m_bMouseInput = bEnable; - } - bool IsKeyboardInputEnabled() const - { - return m_bKeyboardInput; - } + void SetCallback( _In_ PCALLBACKDXUTGUIEVENT pCallback, _In_opt_ void* pUserContext = nullptr ); + void EnableNonUserEvents( _In_ bool bEnable ) { m_bNonUserEvents = bEnable; } + void EnableKeyboardInput( _In_ bool bEnable ) { m_bKeyboardInput = bEnable; } + void EnableMouseInput( _In_ bool bEnable ) { m_bMouseInput = bEnable; } + bool IsKeyboardInputEnabled() const { return m_bKeyboardInput; } // Device state notification - void Refresh(); - HRESULT OnRender( float fElapsedTime ); + void Refresh(); + HRESULT OnRender( _In_ float fElapsedTime ); // Shared resource access. Indexed fonts and textures are shared among // all the controls. - HRESULT SetFont( UINT index, LPCWSTR strFaceName, LONG height, LONG weight ); - DXUTFontNode* GetFont( UINT index ); + HRESULT SetFont( _In_ UINT index, _In_z_ LPCWSTR strFaceName, _In_ LONG height, _In_ LONG weight ); + DXUTFontNode* GetFont( _In_ UINT index ) const; - HRESULT SetTexture( UINT index, LPCWSTR strFilename ); - HRESULT SetTexture( UINT index, LPCWSTR strResourceName, HMODULE hResourceModule ); - DXUTTextureNode* GetTexture( UINT index ); + HRESULT SetTexture( _In_ UINT index, _In_z_ LPCWSTR strFilename ); + HRESULT SetTexture( _In_ UINT index, _In_z_ LPCWSTR strResourceName, _In_ HMODULE hResourceModule ); + DXUTTextureNode* GetTexture( _In_ UINT index ) const; - CDXUTDialogResourceManager* GetManager() - { - return m_pManager; - } + CDXUTDialogResourceManager* GetManager() const { return m_pManager; } static void WINAPI ClearFocus(); - void FocusDefaultControl(); + void FocusDefaultControl(); bool m_bNonUserEvents; bool m_bKeyboardInput; @@ -351,24 +297,20 @@ public: private: int m_nDefaultControlID; - HRESULT OnRender9( float fElapsedTime ); - HRESULT OnRender10( float fElapsedTime ); - HRESULT OnRender11( float fElapsedTime ); - static double s_fTimeRefresh; double m_fTimeLastRefresh; // Initialize default Elements - void InitDefaultElements(); + void InitDefaultElements(); // Windows message handlers - void OnMouseMove( POINT pt ); - void OnMouseUp( POINT pt ); + void OnMouseMove( _In_ const POINT& pt ); + void OnMouseUp( _In_ const POINT& pt ); - void SetNextDialog( CDXUTDialog* pNextDialog ); + void SetNextDialog( _In_ CDXUTDialog* pNextDialog ); // Control events - bool OnCycleFocus( bool bForward ); + bool OnCycleFocus( _In_ bool bForward ); static CDXUTControl* s_pControlFocus; // The control which has focus static CDXUTControl* s_pControlPressed; // The control currently pressed @@ -379,7 +321,7 @@ private: bool m_bCaption; bool m_bMinimized; bool m_bDrag; - WCHAR m_wszCaption[256]; + WCHAR m_wszCaption[256]; int m_x; int m_y; @@ -387,20 +329,20 @@ private: int m_height; int m_nCaptionHeight; - D3DCOLOR m_colorTopLeft; - D3DCOLOR m_colorTopRight; - D3DCOLOR m_colorBottomLeft; - D3DCOLOR m_colorBottomRight; + DWORD m_colorTopLeft; + DWORD m_colorTopRight; + DWORD m_colorBottomLeft; + DWORD m_colorBottomRight; CDXUTDialogResourceManager* m_pManager; PCALLBACKDXUTGUIEVENT m_pCallbackEvent; void* m_pCallbackEventUserContext; - CGrowableArray <int> m_Textures; // Index into m_TextureCache; - CGrowableArray <int> m_Fonts; // Index into m_FontCache; + std::vector<int> m_Textures; // Index into m_TextureCache; + std::vector<int> m_Fonts; // Index into m_FontCache; - CGrowableArray <CDXUTControl*> m_Controls; - CGrowableArray <DXUTElementHolder*> m_DefaultElements; + std::vector<CDXUTControl*> m_Controls; + std::vector<DXUTElementHolder*> m_DefaultElements; CDXUTElement m_CapElement; // Element for the caption @@ -420,7 +362,6 @@ struct DXUTTextureNode WCHAR strFilename[MAX_PATH]; DWORD dwWidth; DWORD dwHeight; - IDirect3DTexture9* pTexture9; ID3D11Texture2D* pTexture11; ID3D11ShaderResourceView* pTexResView11; }; @@ -430,80 +371,55 @@ struct DXUTFontNode WCHAR strFace[MAX_PATH]; LONG nHeight; LONG nWeight; - ID3DXFont* pFont9; }; struct DXUTSpriteVertex { - D3DXVECTOR3 vPos; - D3DXCOLOR vColor; - D3DXVECTOR2 vTex; + DirectX::XMFLOAT3 vPos; + DirectX::XMFLOAT4 vColor; + DirectX::XMFLOAT2 vTex; }; + //----------------------------------------------------------------------------- // Manages shared resources of dialogs //----------------------------------------------------------------------------- class CDXUTDialogResourceManager { public: - CDXUTDialogResourceManager(); - ~CDXUTDialogResourceManager(); + CDXUTDialogResourceManager(); + ~CDXUTDialogResourceManager(); - bool MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - - // D3D9 specific - HRESULT OnD3D9CreateDevice( LPDIRECT3DDEVICE9 pd3dDevice ); - HRESULT OnD3D9ResetDevice(); - void OnD3D9LostDevice(); - void OnD3D9DestroyDevice(); - IDirect3DDevice9* GetD3D9Device() - { - return m_pd3d9Device; - } + bool MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); // D3D11 specific - HRESULT OnD3D11CreateDevice( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ); - HRESULT OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); - void OnD3D11ReleasingSwapChain(); - void OnD3D11DestroyDevice(); - void StoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ); - void RestoreD3D11State( ID3D11DeviceContext* pd3dImmediateContext ); - void ApplyRenderUI11( ID3D11DeviceContext* pd3dImmediateContext ); - void ApplyRenderUIUntex11( ID3D11DeviceContext* pd3dImmediateContext ); - void BeginSprites11( ); - void EndSprites11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext ); - ID3D11Device* GetD3D11Device() - { - return m_pd3d11Device; - } - ID3D11DeviceContext* GetD3D11DeviceContext() - { - return m_pd3d11DeviceContext; - } - - DXUTFontNode* GetFontNode( int iIndex ) - { - return m_FontCache.GetAt( iIndex ); - }; - DXUTTextureNode* GetTextureNode( int iIndex ) - { - return m_TextureCache.GetAt( iIndex ); - }; - - int AddFont( LPCWSTR strFaceName, LONG height, LONG weight ); - int AddTexture( LPCWSTR strFilename ); - int AddTexture( LPCWSTR strResourceName, HMODULE hResourceModule ); - - bool RegisterDialog( CDXUTDialog* pDialog ); - void UnregisterDialog( CDXUTDialog* pDialog ); - void EnableKeyboardInputForAllDialogs(); + HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext ); + HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); + void OnD3D11ReleasingSwapChain(); + void OnD3D11DestroyDevice(); + void StoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void RestoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void ApplyRenderUI11( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void ApplyRenderUIUntex11( _In_ ID3D11DeviceContext* pd3dImmediateContext ); + void BeginSprites11( ); + void EndSprites11( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext ); + + ID3D11Device* GetD3D11Device() const { return m_pd3d11Device; } + ID3D11DeviceContext* GetD3D11DeviceContext() const { return m_pd3d11DeviceContext; } + + DXUTFontNode* GetFontNode( _In_ size_t iIndex ) const { return m_FontCache[ iIndex ]; } + DXUTTextureNode* GetTextureNode( _In_ size_t iIndex ) const { return m_TextureCache[ iIndex ]; } + + int AddFont( _In_z_ LPCWSTR strFaceName, _In_ LONG height, _In_ LONG weight ); + int AddTexture( _In_z_ LPCWSTR strFilename ); + int AddTexture( _In_z_ LPCWSTR strResourceName, _In_ HMODULE hResourceModule ); + + bool RegisterDialog( _In_ CDXUTDialog* pDialog ); + void UnregisterDialog( _In_ CDXUTDialog* pDialog ); + void EnableKeyboardInputForAllDialogs(); // Shared between all dialogs - // D3D9 - IDirect3DStateBlock9* m_pStateBlock; - ID3DXSprite* m_pSprite; // Sprite used for drawing - // D3D11 // Shaders ID3D11VertexShader* m_pVSRenderUI11; @@ -531,34 +447,23 @@ public: // Sprite workaround ID3D11Buffer* m_pSpriteBuffer11; UINT m_SpriteBufferBytes11; - CGrowableArray<DXUTSpriteVertex> m_SpriteVertices; + std::vector<DXUTSpriteVertex> m_SpriteVertices; UINT m_nBackBufferWidth; UINT m_nBackBufferHeight; - CGrowableArray <CDXUTDialog*> m_Dialogs; // Dialogs registered + std::vector<CDXUTDialog*> m_Dialogs; // Dialogs registered protected: - // D3D9 specific - IDirect3DDevice9* m_pd3d9Device; - HRESULT CreateFont9( UINT index ); - HRESULT CreateTexture9( UINT index ); - // D3D11 specific ID3D11Device* m_pd3d11Device; ID3D11DeviceContext* m_pd3d11DeviceContext; - HRESULT CreateFont11( UINT index ); - HRESULT CreateTexture11( UINT index ); + HRESULT CreateTexture11( _In_ UINT index ); - CGrowableArray <DXUTTextureNode*> m_TextureCache; // Shared textures - CGrowableArray <DXUTFontNode*> m_FontCache; // Shared fonts + std::vector<DXUTTextureNode*> m_TextureCache; // Shared textures + std::vector<DXUTFontNode*> m_FontCache; // Shared fonts }; -void BeginText11(); -void DrawText11DXUT( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext, - LPCWSTR strText, RECT rcScreen, D3DXCOLOR vFontColor, - float fBBWidth, float fBBHeight, bool bCenter ); -void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceContext ); //----------------------------------------------------------------------------- // Base class for controls @@ -566,126 +471,79 @@ void EndText11( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3d11DeviceConte class CDXUTControl { public: - CDXUTControl( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTControl(); + CDXUTControl( _In_opt_ CDXUTDialog* pDialog = nullptr ); + virtual ~CDXUTControl(); - virtual HRESULT OnInit() - { - return S_OK; - } - virtual void Refresh(); - virtual void Render( float fElapsedTime ) - { - }; + virtual HRESULT OnInit() { return S_OK; } + virtual void Refresh(); + virtual void Render( _In_ float fElapsedTime ) { UNREFERENCED_PARAMETER(fElapsedTime); } // Windows message handler - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) { + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(pt); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); return false; } - virtual bool CanHaveFocus() - { - return false; - } - virtual void OnFocusIn() - { - m_bHasFocus = true; - } - virtual void OnFocusOut() - { - m_bHasFocus = false; - } - virtual void OnMouseEnter() - { - m_bMouseOver = true; - } - virtual void OnMouseLeave() - { - m_bMouseOver = false; - } - virtual void OnHotkey() - { - } + virtual bool CanHaveFocus() { return false; } + virtual void OnFocusIn() { m_bHasFocus = true; } + virtual void OnFocusOut() { m_bHasFocus = false; } + virtual void OnMouseEnter() { m_bMouseOver = true; } + virtual void OnMouseLeave() { m_bMouseOver = false; } + virtual void OnHotkey() { } - virtual BOOL ContainsPoint( POINT pt ) - { - return PtInRect( &m_rcBoundingBox, pt ); - } + virtual bool ContainsPoint( _In_ const POINT& pt ) { return PtInRect( &m_rcBoundingBox, pt ) != 0; } - virtual void SetEnabled( bool bEnabled ) - { - m_bEnabled = bEnabled; - } - virtual bool GetEnabled() - { - return m_bEnabled; - } - virtual void SetVisible( bool bVisible ) - { - m_bVisible = bVisible; - } - virtual bool GetVisible() - { - return m_bVisible; - } + virtual void SetEnabled( _In_ bool bEnabled ) { m_bEnabled = bEnabled; } + virtual bool GetEnabled() const { return m_bEnabled; } + virtual void SetVisible( _In_ bool bVisible ) { m_bVisible = bVisible; } + virtual bool GetVisible() const { return m_bVisible; } - UINT GetType() const - { - return m_Type; - } + UINT GetType() const { return m_Type; } - int GetID() const - { - return m_ID; - } - void SetID( int ID ) - { - m_ID = ID; - } + int GetID() const { return m_ID; } + void SetID( _In_ int ID ) { m_ID = ID; } - void SetLocation( int x, int y ) + void SetLocation( _In_ int x, _In_ int y ) { - m_x = x; m_y = y; UpdateRects(); + m_x = x; + m_y = y; + UpdateRects(); } - void SetSize( int width, int height ) + void SetSize( int width, int height ) { - m_width = width; m_height = height; UpdateRects(); + m_width = width; + m_height = height; + UpdateRects(); } - void SetHotkey( UINT nHotkey ) - { - m_nHotkey = nHotkey; - } - UINT GetHotkey() - { - return m_nHotkey; - } + void SetHotkey( _In_ UINT nHotkey ) { m_nHotkey = nHotkey; } + UINT GetHotkey() const { return m_nHotkey; } - void SetUserData( void* pUserData ) - { - m_pUserData = pUserData; - } - void* GetUserData() const - { - return m_pUserData; - } + void SetUserData( _In_opt_ void* pUserData ) { m_pUserData = pUserData; } + void* GetUserData() const { return m_pUserData; } - virtual void SetTextColor( D3DCOLOR Color ); - CDXUTElement* GetElement( UINT iElement ) - { - return m_Elements.GetAt( iElement ); - } - HRESULT SetElement( UINT iElement, CDXUTElement* pElement ); + virtual void SetTextColor( _In_ DWORD Color ); + CDXUTElement* GetElement( _In_ UINT iElement ) const { return m_Elements[ iElement ]; } + HRESULT SetElement( _In_ UINT iElement, _In_ CDXUTElement* pElement ); bool m_bVisible; // Shown/hidden flag bool m_bMouseOver; // Mouse pointer is above control @@ -700,13 +558,13 @@ public: CDXUTDialog* m_pDialog; // Parent container UINT m_Index; // Index within the control list - CGrowableArray <CDXUTElement*> m_Elements; // All display elements + std::vector<CDXUTElement*> m_Elements; // All display elements protected: - virtual void UpdateRects(); + virtual void UpdateRects(); int m_ID; // ID number - DXUT_CONTROL_TYPE m_Type; // Control type, set once in constructor + DXUT_CONTROL_TYPE m_Type; // Control type, set once in constructor UINT m_nHotkey; // Virtual key code for this control's hotkey void* m_pUserData; // Data associated with this control that is set by user. @@ -734,25 +592,21 @@ struct DXUTElementHolder class CDXUTStatic : public CDXUTControl { public: - CDXUTStatic( CDXUTDialog* pDialog = NULL ); + CDXUTStatic( _In_opt_ CDXUTDialog* pDialog = nullptr ); - virtual void Render( float fElapsedTime ); - virtual BOOL ContainsPoint( POINT pt ) + virtual void Render( _In_ float fElapsedTime ) override; + virtual bool ContainsPoint( _In_ const POINT& pt ) override { + UNREFERENCED_PARAMETER( pt ); return false; } - HRESULT GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ); - LPCWSTR GetText() - { - return m_strText; - } - HRESULT SetText( LPCWSTR strText ); - + HRESULT GetTextCopy( _Out_writes_(bufferCount) LPWSTR strDest, _In_ UINT bufferCount ) const; + LPCWSTR GetText() const { return m_strText; } + HRESULT SetText( _In_z_ LPCWSTR strText ); protected: - WCHAR m_strText[MAX_PATH]; // Window text + WCHAR m_strText[MAX_PATH]; // Window text }; @@ -762,26 +616,26 @@ protected: class CDXUTButton : public CDXUTStatic { public: - CDXUTButton( CDXUTDialog* pDialog = NULL ); + CDXUTButton( _In_opt_ CDXUTDialog* pDialog = nullptr ); - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey() + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override { if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this ); m_pDialog->SendEvent( EVENT_BUTTON_CLICKED, true, this ); } - virtual BOOL ContainsPoint( POINT pt ) + virtual bool ContainsPoint( _In_ const POINT& pt ) override { - return PtInRect( &m_rcBoundingBox, pt ); + return PtInRect( &m_rcBoundingBox, pt ) != 0; } - virtual bool CanHaveFocus() + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual void Render( float fElapsedTime ); + virtual void Render( _In_ float fElapsedTime ) override; protected: bool m_bPressed; @@ -794,32 +648,26 @@ protected: class CDXUTCheckBox : public CDXUTButton { public: - CDXUTCheckBox( CDXUTDialog* pDialog = NULL ); + CDXUTCheckBox( _In_opt_ CDXUTDialog* pDialog = nullptr ); - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey() + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override { if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this ); SetCheckedInternal( !m_bChecked, true ); } - virtual BOOL ContainsPoint( POINT pt ); - virtual void UpdateRects(); + virtual bool ContainsPoint( _In_ const POINT& pt ) override; + virtual void UpdateRects() override; - virtual void Render( float fElapsedTime ); + virtual void Render( _In_ float fElapsedTime ) override; - bool GetChecked() - { - return m_bChecked; - } - void SetChecked( bool bChecked ) - { - SetCheckedInternal( bChecked, false ); - } + bool GetChecked() const { return m_bChecked; } + void SetChecked( _In_ bool bChecked ) { SetCheckedInternal( bChecked, false ); } protected: - virtual void SetCheckedInternal( bool bChecked, bool bFromInput ); + virtual void SetCheckedInternal( _In_ bool bChecked, _In_ bool bFromInput ); bool m_bChecked; RECT m_rcButton; @@ -833,31 +681,22 @@ protected: class CDXUTRadioButton : public CDXUTCheckBox { public: - CDXUTRadioButton( CDXUTDialog* pDialog = NULL ); + CDXUTRadioButton( _In_opt_ CDXUTDialog* pDialog = nullptr ); - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey() + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override { if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this ); SetCheckedInternal( true, true, true ); } - void SetChecked( bool bChecked, bool bClearGroup=true ) - { - SetCheckedInternal( bChecked, bClearGroup, false ); - } - void SetButtonGroup( UINT nButtonGroup ) - { - m_nButtonGroup = nButtonGroup; - } - UINT GetButtonGroup() - { - return m_nButtonGroup; - } + void SetChecked( _In_ bool bChecked, _In_ bool bClearGroup=true ) { SetCheckedInternal( bChecked, bClearGroup, false ); } + void SetButtonGroup( _In_ UINT nButtonGroup ) { m_nButtonGroup = nButtonGroup; } + UINT GetButtonGroup() const { return m_nButtonGroup; } protected: - virtual void SetCheckedInternal( bool bChecked, bool bClearGroup, bool bFromInput ); + virtual void SetCheckedInternal( _In_ bool bChecked, _In_ bool bClearGroup, _In_ bool bFromInput ); UINT m_nButtonGroup; }; @@ -868,36 +707,34 @@ protected: class CDXUTScrollBar : public CDXUTControl { public: - CDXUTScrollBar( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTScrollBar(); + CDXUTScrollBar( _In_opt_ CDXUTDialog* pDialog = nullptr ); + virtual ~CDXUTScrollBar(); - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; - virtual void Render( float fElapsedTime ); - virtual void UpdateRects(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual void UpdateRects() override; - void SetTrackRange( int nStart, int nEnd ); - int GetTrackPos() - { - return m_nPosition; - } - void SetTrackPos( int nPosition ) - { - m_nPosition = nPosition; Cap(); UpdateThumbRect(); - } - int GetPageSize() + void SetTrackRange( _In_ int nStart, _In_ int nEnd ); + int GetTrackPos() const { return m_nPosition; } + void SetTrackPos( _In_ int nPosition ) { - return m_nPageSize; + m_nPosition = nPosition; + Cap(); + UpdateThumbRect(); } - void SetPageSize( int nPageSize ) + int GetPageSize() const { return m_nPageSize; } + void SetPageSize( _In_ int nPageSize ) { - m_nPageSize = nPageSize; Cap(); UpdateThumbRect(); + m_nPageSize = nPageSize; + Cap(); + UpdateThumbRect(); } - void Scroll( int nDelta ); // Scroll by nDelta items (plus or minus) - void ShowItem( int nIndex ); // Ensure that item nIndex is displayed, scroll if necessary + void Scroll( _In_ int nDelta ); // Scroll by nDelta items (plus or minus) + void ShowItem( _In_ int nIndex ); // Ensure that item nIndex is displayed, scroll if necessary protected: // ARROWSTATE indicates the state of the arrow buttons. @@ -949,60 +786,50 @@ struct DXUTListBoxItem class CDXUTListBox : public CDXUTControl { public: - CDXUTListBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTListBox(); + CDXUTListBox( _In_opt_ CDXUTDialog* pDialog = nullptr ); + virtual ~CDXUTListBox(); - virtual HRESULT OnInit() + virtual HRESULT OnInit() override { return m_pDialog->InitControl( &m_ScrollBar ); } - virtual bool CanHaveFocus() + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; - virtual void Render( float fElapsedTime ); - virtual void UpdateRects(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual void UpdateRects() override; - DWORD GetStyle() const + DWORD GetStyle() const { return m_dwStyle; } + size_t GetSize() const { return m_Items.size(); } + void SetStyle( _In_ DWORD dwStyle ) { m_dwStyle = dwStyle; } + int GetScrollBarWidth() const{ return m_nSBWidth; } + void SetScrollBarWidth( _In_ int nWidth ) { - return m_dwStyle; + m_nSBWidth = nWidth; + UpdateRects(); } - int GetSize() const + void SetBorder( _In_ int nBorder, _In_ int nMargin ) { - return m_Items.GetSize(); + m_nBorder = nBorder; + m_nMargin = nMargin; } - void SetStyle( DWORD dwStyle ) - { - m_dwStyle = dwStyle; - } - int GetScrollBarWidth() const - { - return m_nSBWidth; - } - void SetScrollBarWidth( int nWidth ) - { - m_nSBWidth = nWidth; UpdateRects(); - } - void SetBorder( int nBorder, int nMargin ) - { - m_nBorder = nBorder; m_nMargin = nMargin; - } - HRESULT AddItem( const WCHAR* wszText, void* pData ); - HRESULT InsertItem( int nIndex, const WCHAR* wszText, void* pData ); - void RemoveItem( int nIndex ); - void RemoveAllItems(); - - DXUTListBoxItem* GetItem( int nIndex ); - int GetSelectedIndex( int nPreviousSelected = -1 ); - DXUTListBoxItem* GetSelectedItem( int nPreviousSelected = -1 ) + HRESULT AddItem( _In_z_ const WCHAR* wszText, _In_opt_ void* pData ); + HRESULT InsertItem( _In_ int nIndex, _In_z_ const WCHAR* wszText, _In_opt_ void* pData ); + void RemoveItem( _In_ int nIndex ); + void RemoveAllItems(); + + DXUTListBoxItem* GetItem( _In_ int nIndex ) const; + int GetSelectedIndex( _In_ int nPreviousSelected = -1 ) const; + DXUTListBoxItem* GetSelectedItem( _In_ int nPreviousSelected = -1 ) const { return GetItem( GetSelectedIndex( nPreviousSelected ) ); } - void SelectItem( int nNewIndex ); + void SelectItem( _In_ int nNewIndex ); enum STYLE { @@ -1022,7 +849,7 @@ protected: int m_nSelStart; // Index of the item where selection starts (for handling multi-selection) bool m_bDrag; // Whether the user is dragging the mouse to select - CGrowableArray <DXUTListBoxItem*> m_Items; + std::vector<DXUTListBoxItem*> m_Items; }; @@ -1038,71 +865,60 @@ struct DXUTComboBoxItem bool bVisible; }; - class CDXUTComboBox : public CDXUTButton { public: - CDXUTComboBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTComboBox(); + CDXUTComboBox( _In_opt_ CDXUTDialog* pDialog = nullptr ); + virtual ~CDXUTComboBox(); - virtual void SetTextColor( D3DCOLOR Color ); - virtual HRESULT OnInit() + virtual void SetTextColor( _In_ DWORD Color ) override; + virtual HRESULT OnInit() override { return m_pDialog->InitControl( &m_ScrollBar ); } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void OnHotkey(); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void OnHotkey() override; - virtual bool CanHaveFocus() + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual void OnFocusOut(); - virtual void Render( float fElapsedTime ); - - virtual void UpdateRects(); - - HRESULT AddItem( const WCHAR* strText, void* pData ); - void RemoveAllItems(); - void RemoveItem( UINT index ); - bool ContainsItem( const WCHAR* strText, UINT iStart=0 ); - int FindItem( const WCHAR* strText, UINT iStart=0 ); - void* GetItemData( const WCHAR* strText ); - void* GetItemData( int nIndex ); - void SetDropHeight( UINT nHeight ) - { - m_nDropHeight = nHeight; UpdateRects(); - } - int GetScrollBarWidth() const - { - return m_nSBWidth; - } - void SetScrollBarWidth( int nWidth ) - { - m_nSBWidth = nWidth; UpdateRects(); - } + virtual void OnFocusOut() override; + virtual void Render( _In_ float fElapsedTime ) override; - int GetSelectedIndex() const - { - return m_iSelected; - } - void* GetSelectedData(); - DXUTComboBoxItem* GetSelectedItem(); + virtual void UpdateRects() override; - UINT GetNumItems() + HRESULT AddItem( _In_z_ const WCHAR* strText, _In_opt_ void* pData ); + void RemoveAllItems(); + void RemoveItem( _In_ UINT index ); + bool ContainsItem( _In_z_ const WCHAR* strText, _In_ UINT iStart=0 ); + int FindItem( _In_z_ const WCHAR* strText, _In_ UINT iStart=0 ) const; + void* GetItemData( _In_z_ const WCHAR* strText ) const; + void* GetItemData( _In_ int nIndex ) const; + void SetDropHeight( _In_ UINT nHeight ) { - return m_Items.GetSize(); + m_nDropHeight = nHeight; + UpdateRects(); } - DXUTComboBoxItem* GetItem( UINT index ) + int GetScrollBarWidth() const { return m_nSBWidth; } + void SetScrollBarWidth( _In_ int nWidth ) { - return m_Items.GetAt( index ); + m_nSBWidth = nWidth; + UpdateRects(); } - HRESULT SetSelectedByIndex( UINT index ); - HRESULT SetSelectedByText( const WCHAR* strText ); - HRESULT SetSelectedByData( void* pData ); + int GetSelectedIndex() const { return m_iSelected; } + void* GetSelectedData() const; + DXUTComboBoxItem* GetSelectedItem() const; + + UINT GetNumItems() { return static_cast<UINT>( m_Items.size() ); } + DXUTComboBoxItem* GetItem( _In_ UINT index ) { return m_Items[ index ]; } + + HRESULT SetSelectedByIndex( _In_ UINT index ); + HRESULT SetSelectedByText( _In_z_ const WCHAR* strText ); + HRESULT SetSelectedByData( _In_ void* pData ); protected: int m_iSelected; @@ -1118,8 +934,7 @@ protected: RECT m_rcDropdown; RECT m_rcDropdownText; - - CGrowableArray <DXUTComboBoxItem*> m_Items; + std::vector<DXUTComboBoxItem*> m_Items; }; @@ -1129,38 +944,33 @@ protected: class CDXUTSlider : public CDXUTControl { public: - CDXUTSlider( CDXUTDialog* pDialog = NULL ); + CDXUTSlider( _In_opt_ CDXUTDialog* pDialog = nullptr ); - virtual BOOL ContainsPoint( POINT pt ); - virtual bool CanHaveFocus() + virtual bool ContainsPoint( _In_ const POINT& pt ) override; + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; - virtual void UpdateRects(); + virtual void UpdateRects() override; - virtual void Render( float fElapsedTime ); + virtual void Render( _In_ float fElapsedTime ) override; - void SetValue( int nValue ) - { - SetValueInternal( nValue, false ); - } - int GetValue() const - { - return m_nValue; - }; + void SetValue( int nValue ) { SetValueInternal( nValue, false ); } + int GetValue() const { return m_nValue; } - void GetRange( int& nMin, int& nMax ) const + void GetRange( _Out_ int& nMin, _Out_ int& nMax ) const { - nMin = m_nMin; nMax = m_nMax; + nMin = m_nMin; + nMax = m_nMax; } - void SetRange( int nMin, int nMax ); + void SetRange( _In_ int nMin, _In_ int nMax ); protected: - void SetValueInternal( int nValue, bool bFromInput ); - int ValueFromPos( int x ); + void SetValueInternal( _In_ int nValue, _In_ bool bFromInput ); + int ValueFromPos( _In_ int x ); int m_nValue; @@ -1182,53 +992,44 @@ protected: class CUniBuffer { public: - CUniBuffer( int nInitialSize = 1 ); - ~CUniBuffer(); - - static void WINAPI Initialize(); - static void WINAPI Uninitialize(); + CUniBuffer( _In_ int nInitialSize = 1 ); + ~CUniBuffer(); - int GetBufferSize() - { - return m_nBufferSize; - } - bool SetBufferSize( int nSize ); - int GetTextSize() - { - return lstrlenW( m_pwszBuffer ); - } - const WCHAR* GetBuffer() + size_t GetBufferSize() const { return m_nBufferSize; } + bool SetBufferSize( _In_ int nSize ); + int GetTextSize() const { return (int)wcslen( m_pwszBuffer ); } + const WCHAR* GetBuffer() const { return m_pwszBuffer; } - const WCHAR& operator[]( int n ) const + const WCHAR& operator[]( _In_ int n ) const { return m_pwszBuffer[n]; } - WCHAR& operator[]( int n ); - DXUTFontNode* GetFontNode() - { - return m_pFontNode; - } - void SetFontNode( DXUTFontNode* pFontNode ) - { - m_pFontNode = pFontNode; - } - void Clear(); + WCHAR& operator[]( _In_ int n ); + DXUTFontNode* GetFontNode() const { return m_pFontNode; } + void SetFontNode( _In_opt_ DXUTFontNode* pFontNode ) { m_pFontNode = pFontNode; } + void Clear(); + + bool InsertChar( _In_ int nIndex, _In_ WCHAR wChar ); + // Inserts the char at specified index. If nIndex == -1, insert to the end. - bool InsertChar( int nIndex, WCHAR wChar ); // Inserts the char at specified index. If nIndex == -1, insert to the end. - bool RemoveChar( int nIndex ); // Removes the char at specified index. If nIndex == -1, remove the last char. - bool InsertString( int nIndex, const WCHAR* pStr, int nCount = -1 ); // Inserts the first nCount characters of the string pStr at specified index. If nCount == -1, the entire string is inserted. If nIndex == -1, insert to the end. - bool SetText( LPCWSTR wszText ); + bool RemoveChar( _In_ int nIndex ); + // Removes the char at specified index. If nIndex == -1, remove the last char. + + bool InsertString( _In_ int nIndex, _In_z_ const WCHAR* pStr, _In_ int nCount = -1 ); + // Inserts the first nCount characters of the string pStr at specified index. If nCount == -1, the entire string is inserted. If nIndex == -1, insert to the end. + + bool SetText( _In_z_ LPCWSTR wszText ); // Uniscribe - HRESULT CPtoX( int nCP, BOOL bTrail, int* pX ); - HRESULT XtoCP( int nX, int* pCP, int* pnTrail ); - void GetPriorItemPos( int nCP, int* pPrior ); - void GetNextItemPos( int nCP, int* pPrior ); + bool CPtoX( _In_ int nCP, _In_ bool bTrail, _Out_ int* pX ); + bool XtoCP( _In_ int nX, _Out_ int* pCP, _Out_ int* pnTrail ); + void GetPriorItemPos( _In_ int nCP, _Out_ int* pPrior ); + void GetNextItemPos( _In_ int nCP, _Out_ int* pPrior ); private: - HRESULT Analyse(); // Uniscribe -- Analyse() analyses the string in the buffer + HRESULT Analyse(); // Uniscribe -- Analyse() analyses the string in the buffer WCHAR* m_pwszBuffer; // Buffer to hold text int m_nBufferSize; // Size of the buffer allocated, in characters @@ -1237,123 +1038,58 @@ private: DXUTFontNode* m_pFontNode; // Font node for the font that this buffer uses bool m_bAnalyseRequired; // True if the string has changed since last analysis. SCRIPT_STRING_ANALYSIS m_Analysis; // Analysis for the current string - -private: - // Empty implementation of the Uniscribe API - static HRESULT WINAPI Dummy_ScriptApplyDigitSubstitution( const SCRIPT_DIGITSUBSTITUTE*, SCRIPT_CONTROL*, - SCRIPT_STATE* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringAnalyse( HDC, const void*, int, int, int, DWORD, int, SCRIPT_CONTROL*, - SCRIPT_STATE*, const int*, SCRIPT_TABDEF*, const BYTE*, - SCRIPT_STRING_ANALYSIS* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringCPtoX( SCRIPT_STRING_ANALYSIS, int, BOOL, int* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringXtoCP( SCRIPT_STRING_ANALYSIS, int, int*, int* ) - { - return E_NOTIMPL; - } - static HRESULT WINAPI Dummy_ScriptStringFree( SCRIPT_STRING_ANALYSIS* ) - { - return E_NOTIMPL; - } - static const SCRIPT_LOGATTR* WINAPI Dummy_ScriptString_pLogAttr( SCRIPT_STRING_ANALYSIS ) - { - return NULL; - } - static const int* WINAPI Dummy_ScriptString_pcOutChars( SCRIPT_STRING_ANALYSIS ) - { - return NULL; - } - - // Function pointers - static HRESULT( WINAPI* _ScriptApplyDigitSubstitution )( const SCRIPT_DIGITSUBSTITUTE*, - SCRIPT_CONTROL*, SCRIPT_STATE* ); - static HRESULT( WINAPI* _ScriptStringAnalyse )( HDC, const void*, int, int, int, DWORD, int, - SCRIPT_CONTROL*, SCRIPT_STATE*, const int*, - SCRIPT_TABDEF*, const BYTE*, - SCRIPT_STRING_ANALYSIS* ); - static HRESULT( WINAPI* _ScriptStringCPtoX )( SCRIPT_STRING_ANALYSIS, int, BOOL, int* ); - static HRESULT( WINAPI* _ScriptStringXtoCP )( SCRIPT_STRING_ANALYSIS, int, int*, int* ); - static HRESULT( WINAPI* _ScriptStringFree )( SCRIPT_STRING_ANALYSIS* ); - static const SCRIPT_LOGATTR* ( WINAPI*_ScriptString_pLogAttr )( SCRIPT_STRING_ANALYSIS ); - static const int* ( WINAPI*_ScriptString_pcOutChars )( SCRIPT_STRING_ANALYSIS ); - - static HINSTANCE s_hDll; // Uniscribe DLL handle - }; + //----------------------------------------------------------------------------- // EditBox control //----------------------------------------------------------------------------- class CDXUTEditBox : public CDXUTControl { public: - CDXUTEditBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTEditBox(); - - virtual bool HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual void UpdateRects(); - virtual bool CanHaveFocus() + CDXUTEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr ); + virtual ~CDXUTEditBox(); + + virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void UpdateRects() override; + virtual bool CanHaveFocus() override { return ( m_bVisible && m_bEnabled ); } - virtual void Render( float fElapsedTime ); - virtual void OnFocusIn(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual void OnFocusIn() override; - void SetText( LPCWSTR wszText, bool bSelected = false ); - LPCWSTR GetText() - { - return m_Buffer.GetBuffer(); - } - int GetTextLength() - { - return m_Buffer.GetTextSize(); - } // Returns text length in chars excluding NULL. - HRESULT GetTextCopy( __out_ecount(bufferCount) LPWSTR strDest, - UINT bufferCount ); - void ClearText(); - virtual void SetTextColor( D3DCOLOR Color ) - { - m_TextColor = Color; - } // Text color - void SetSelectedTextColor( D3DCOLOR Color ) - { - m_SelTextColor = Color; - } // Selected text color - void SetSelectedBackColor( D3DCOLOR Color ) - { - m_SelBkColor = Color; - } // Selected background color - void SetCaretColor( D3DCOLOR Color ) - { - m_CaretColor = Color; - } // Caret color - void SetBorderWidth( int nBorder ) + void SetText( _In_z_ LPCWSTR wszText, _In_ bool bSelected = false ); + LPCWSTR GetText() const { return m_Buffer.GetBuffer(); } + size_t GetTextLength() const { return m_Buffer.GetTextSize(); } // Returns text length in chars excluding nul. + HRESULT GetTextCopy( _Out_writes_(bufferCount) LPWSTR strDest, _In_ UINT bufferCount ) const; + void ClearText(); + + virtual void SetTextColor( _In_ DWORD Color ) override { m_TextColor = Color; } // Text color + void SetSelectedTextColor( _In_ DWORD Color ) { m_SelTextColor = Color; } // Selected text color + void SetSelectedBackColor( _In_ DWORD Color ) { m_SelBkColor = Color; } // Selected background color + void SetCaretColor( _In_ DWORD Color ) { m_CaretColor = Color; } // Caret color + void SetBorderWidth( _In_ int nBorder ) { - m_nBorder = nBorder; UpdateRects(); + m_nBorder = nBorder; + UpdateRects(); } // Border of the window - void SetSpacing( int nSpacing ) + void SetSpacing( _In_ int nSpacing ) { - m_nSpacing = nSpacing; UpdateRects(); + m_nSpacing = nSpacing; + UpdateRects(); } - void ParseFloatArray( float* pNumbers, int nCount ); - void SetTextFloatArray( const float* pNumbers, int nCount ); + void ParseFloatArray( _In_reads_(nCount) float* pNumbers, _In_ int nCount ); + void SetTextFloatArray( _In_reads_(nCount) const float* pNumbers, _In_ int nCount ); protected: - void PlaceCaret( int nCP ); - void DeleteSelectionText(); - void ResetCaretBlink(); - void CopyToClipboard(); - void PasteFromClipboard(); + void PlaceCaret( _In_ int nCP ); + void DeleteSelectionText(); + void ResetCaretBlink(); + void CopyToClipboard(); + void PasteFromClipboard(); CUniBuffer m_Buffer; // Buffer to hold text int m_nBorder; // Border of the window @@ -1367,10 +1103,10 @@ protected: bool m_bInsertMode; // If true, control is in insert mode. Else, overwrite mode. int m_nSelStart; // Starting position of the selection. The caret marks the end. int m_nFirstVisible;// First visible character in the edit control - D3DCOLOR m_TextColor; // Text color - D3DCOLOR m_SelTextColor; // Selected text color - D3DCOLOR m_SelBkColor; // Selected background color - D3DCOLOR m_CaretColor; // Caret color + DWORD m_TextColor; // Text color + DWORD m_SelTextColor; // Selected text color + DWORD m_SelBkColor; // Selected background color + DWORD m_CaretColor; // Caret color // Mouse-specific bool m_bMouseDrag; // True to indicate drag in progress @@ -1380,6 +1116,9 @@ protected: }; - - -#endif // DXUT_GUI_H +//----------------------------------------------------------------------------- +void BeginText11(); +void DrawText11DXUT( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext, + _In_z_ LPCWSTR strText, _In_ const RECT& rcScreen, _In_ DirectX::XMFLOAT4 vFontColor, + _In_ float fBBWidth, _In_ float fBBHeight, _In_ bool bCenter ); +void EndText11( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext ); diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.cpp b/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.cpp index 4bb0596..8ef717f 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.cpp @@ -2,6 +2,9 @@ // File: DXUTguiIME.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" @@ -10,8 +13,6 @@ #include "DXUTgui.h" #include "DXUTguiIME.h" -#undef min // use __min instead -#undef max // use __max instead #define DXUT_NEAR_BUTTON_DEPTH 0.6f @@ -35,15 +36,16 @@ bool CDXUTIMEEditBox::m_bIMEStaticMsgProcCalled = false; //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTIMEEditBox::CreateIMEEditBox( CDXUTDialog* pDialog, int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault, CDXUTIMEEditBox** ppCreated ) { - CDXUTIMEEditBox* pEditBox = new CDXUTIMEEditBox( pDialog ); + auto pEditBox = new (std::nothrow) CDXUTIMEEditBox( pDialog ); - if( ppCreated != NULL ) + if( ppCreated ) *ppCreated = pEditBox; - if( pEditBox == NULL ) + if( !pEditBox ) return E_OUTOFMEMORY; // Set the ID and position @@ -60,7 +62,7 @@ HRESULT CDXUTIMEEditBox::CreateIMEEditBox( CDXUTDialog* pDialog, int ID, LPCWSTR //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::InitDefaultElements( CDXUTDialog* pDialog ) +void CDXUTIMEEditBox::InitDefaultElements( _In_ CDXUTDialog* pDialog ) { //------------------------------------- // CDXUTIMEEditBox @@ -108,7 +110,7 @@ void CDXUTIMEEditBox::InitDefaultElements( CDXUTDialog* pDialog ) //-------------------------------------------------------------------------------------- -CDXUTIMEEditBox::CDXUTIMEEditBox( CDXUTDialog* pDialog ) +CDXUTIMEEditBox::CDXUTIMEEditBox( _In_opt_ CDXUTDialog* pDialog ) { m_Type = DXUT_CONTROL_IMEEDITBOX; m_pDialog = pDialog; @@ -142,7 +144,7 @@ CDXUTIMEEditBox::~CDXUTIMEEditBox() //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::SendKey( BYTE nVirtKey ) +void CDXUTIMEEditBox::SendKey( _In_ BYTE nVirtKey ) { keybd_event( nVirtKey, 0, 0, 0 ); keybd_event( nVirtKey, 0, KEYEVENTF_KEYUP, 0 ); @@ -193,7 +195,7 @@ void CDXUTIMEEditBox::UpdateRects() //-------------------------------------------------------------------------------------- // Enable/disable the entire IME system. When disabled, the default IME handling // kicks in. -void CDXUTIMEEditBox::EnableImeSystem( bool bEnable ) +void CDXUTIMEEditBox::EnableImeSystem( _In_ bool bEnable ) { ImeUi_EnableIme( bEnable ); } @@ -214,9 +216,9 @@ void CDXUTIMEEditBox::PumpMessage() { MSG msg; - while( PeekMessageW( &msg, NULL, 0, 0, PM_NOREMOVE ) ) + while( PeekMessageW( &msg, nullptr, 0, 0, PM_NOREMOVE ) ) { - if( !GetMessageW( &msg, NULL, 0, 0 ) ) + if( !GetMessageW( &msg, nullptr, 0, 0 ) ) { PostQuitMessage( ( int )msg.wParam ); return; @@ -245,8 +247,11 @@ void CDXUTIMEEditBox::OnFocusOut() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTIMEEditBox::StaticMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { + UNREFERENCED_PARAMETER(hWnd); + UNREFERENCED_PARAMETER(wParam); if( !ImeUi_IsEnabled() ) return false; @@ -295,7 +300,8 @@ bool CDXUTIMEEditBox::StaticMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM //-------------------------------------------------------------------------------------- -bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) +_Use_decl_annotations_ +bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, const POINT& pt, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) return false; @@ -305,7 +311,7 @@ bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lP case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: { - DXUTFontNode* pFont = m_pDialog->GetFont( m_Elements.GetAt( 9 )->iFont ); + auto pFont = m_pDialog->GetFont( m_Elements[ 9 ]->iFont ); // Check if this click is on top of the composition string int nCompStrWidth; @@ -430,7 +436,7 @@ bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lP if( nCharHit >= nEntryStart ) { // Haven't found it. - nEntryStart += lstrlenW( ImeUi_GetCandidate( i ) ) + 1; // plus space separator + nEntryStart += (int)wcslen( ImeUi_GetCandidate( i ) ) + 1; // plus space separator } else { @@ -463,6 +469,7 @@ bool CDXUTIMEEditBox::HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lP //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool CDXUTIMEEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { if( !m_bEnabled || !m_bVisible ) @@ -497,15 +504,16 @@ bool CDXUTIMEEditBox::MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bReading ) +_Use_decl_annotations_ +void CDXUTIMEEditBox::RenderCandidateReadingWindow( bool bReading ) { RECT rc; UINT nNumEntries = bReading ? 4 : MAX_CANDLIST; - D3DCOLOR TextColor, TextBkColor, SelTextColor, SelBkColor; int nX, nXFirst, nXComp; m_Buffer.CPtoX( m_nCaret, FALSE, &nX ); m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nXFirst ); + DWORD TextColor, TextBkColor, SelTextColor, SelBkColor; if( bReading ) { TextColor = m_ReadingColor; @@ -545,9 +553,9 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe if( *( ImeUi_GetCandidate( i ) ) == L'\0' ) break; SetRect( &rc, 0, 0, 0, 0 ); - m_pDialog->CalcTextRect( ImeUi_GetCandidate( i ), m_Elements.GetAt( 1 ), &rc ); - nWidthRequired = __max( nWidthRequired, rc.right - rc.left ); - nSingleLineHeight = __max( nSingleLineHeight, rc.bottom - rc.top ); + m_pDialog->CalcTextRect( ImeUi_GetCandidate( i ), m_Elements[ 1 ], &rc ); + nWidthRequired = std::max<int>( nWidthRequired, rc.right - rc.left ); + nSingleLineHeight = std::max<int>( nSingleLineHeight, rc.bottom - rc.top ); } nHeightRequired = nSingleLineHeight * nNumEntries; } @@ -556,7 +564,7 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe // Horizontal window SetRect( &rc, 0, 0, 0, 0 ); if( bReading ) - m_pDialog->CalcTextRect( s_wszReadingString, m_Elements.GetAt( 1 ), &rc ); + m_pDialog->CalcTextRect( s_wszReadingString, m_Elements[ 1 ], &rc ); else { @@ -570,19 +578,19 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe break; WCHAR wszEntry[32]; - swprintf_s( wszEntry, 32, L"%s ", ImeUi_GetCandidate( i ) ); + swprintf_s( wszEntry, 32, L"%ls ", ImeUi_GetCandidate( i ) ); // If this is the selected entry, mark its char position. if( ImeUi_GetCandidateSelection() == i ) { - s_CandList.nFirstSelected = lstrlen( wszCand ); - s_CandList.nHoriSelectedLen = lstrlen( wszEntry ) - 1; // Minus space + s_CandList.nFirstSelected = (int)wcslen( wszCand ); + s_CandList.nHoriSelectedLen = (int)wcslen( wszEntry ) - 1; // Minus space } wcscat_s( wszCand, 256, wszEntry ); } - wszCand[lstrlen( wszCand ) - 1] = L'\0'; // Remove the last space + wszCand[wcslen( wszCand ) - 1] = L'\0'; // Remove the last space s_CandList.HoriCand.SetText( wszCand ); - m_pDialog->CalcTextRect( s_CandList.HoriCand.GetBuffer(), m_Elements.GetAt( 1 ), &rc ); + m_pDialog->CalcTextRect( s_CandList.HoriCand.GetBuffer(), m_Elements[ 1 ], &rc ); } nWidthRequired = rc.right - rc.left; nSingleLineHeight = nHeightRequired = rc.bottom - rc.top; @@ -670,12 +678,12 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe if( ImeUi_GetCandidateSelection() == i ) { m_pDialog->DrawRect( &rc, SelBkColor ); - m_Elements.GetAt( 1 )->FontColor.Current = SelTextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( SelTextColor ); } else - m_Elements.GetAt( 1 )->FontColor.Current = TextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( TextColor ); - m_pDialog->DrawText( ImeUi_GetCandidate( i ), m_Elements.GetAt( 1 ), &rc ); + m_pDialog->DrawText( ImeUi_GetCandidate( i ), m_Elements[ 1 ], &rc ); rc.top += nSingleLineHeight; } @@ -683,11 +691,11 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe else { // Horizontal candidate window - m_Elements.GetAt( 1 )->FontColor.Current = TextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( TextColor ); if( bReading ) - m_pDialog->DrawText( s_wszReadingString, m_Elements.GetAt( 1 ), &rc ); + m_pDialog->DrawText( s_wszReadingString, m_Elements[ 1 ], &rc ); else - m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer(), m_Elements.GetAt( 1 ), &rc ); + m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer(), m_Elements[ 1 ], &rc ); // Render the selected entry differently if( !bReading ) @@ -699,16 +707,16 @@ void CDXUTIMEEditBox::RenderCandidateReadingWindow( float fElapsedTime, bool bRe rc.right = rc.left + nXRight; rc.left += nXLeft; m_pDialog->DrawRect( &rc, SelBkColor ); - m_Elements.GetAt( 1 )->FontColor.Current = SelTextColor; + m_Elements[ 1 ]->FontColor.SetCurrent( SelTextColor ); m_pDialog->DrawText( s_CandList.HoriCand.GetBuffer() + s_CandList.nFirstSelected, - m_Elements.GetAt( 1 ), &rc, false, s_CandList.nHoriSelectedLen ); + m_Elements[ 1 ], &rc, false ); } } } //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) +void CDXUTIMEEditBox::RenderComposition() { s_CompString.SetText( ImeUi_GetCompositionString() ); @@ -720,7 +728,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) int nX, nXFirst; m_Buffer.CPtoX( m_nCaret, FALSE, &nX ); m_Buffer.CPtoX( m_nFirstVisible, FALSE, &nXFirst ); - CDXUTElement* pElement = m_Elements.GetAt( 1 ); + auto pElement = m_Elements[ 1 ]; // Get the required width RECT rc = @@ -743,10 +751,10 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) s_ptCompString.x = rc.left; s_ptCompString.y = rc.top; - D3DCOLOR TextColor = m_CompColor; + DWORD TextColor = m_CompColor; // Render the window and string. // If the string is too long, we must wrap the line. - pElement->FontColor.Current = TextColor; + pElement->FontColor.SetCurrent( TextColor ); const WCHAR* pwszComp = s_CompString.GetBuffer(); int nCharLeft = s_CompString.GetTextSize(); for(; ; ) @@ -755,7 +763,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) int nLastInLine; int bTrail; s_CompString.XtoCP( m_rcText.right - rc.left, &nLastInLine, &bTrail ); - int nNumCharToDraw = __min( nCharLeft, nLastInLine ); + int nNumCharToDraw = std::min( nCharLeft, nLastInLine ); m_pDialog->CalcTextRect( pwszComp, pElement, &rc, nNumCharToDraw ); // Draw the background @@ -772,7 +780,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) // Not drawing composition string background. We // use the editbox's text color for composition // string text. - TextColor = m_Elements.GetAt( 0 )->FontColor.States[DXUT_STATE_NORMAL]; + TextColor = m_Elements[ 0 ]->FontColor.States[DXUT_STATE_NORMAL]; } } else @@ -782,8 +790,8 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) } // Draw the text - pElement->FontColor.Current = TextColor; - m_pDialog->DrawText( pwszComp, pElement, &rc, false, nNumCharToDraw ); + pElement->FontColor.SetCurrent( TextColor ); + m_pDialog->DrawText( pwszComp, pElement, &rc, false ); // Advance pointer and counter nCharLeft -= nNumCharToDraw; @@ -809,7 +817,7 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) for( pcComp = s_CompString.GetBuffer(), pAttr = ImeUi_GetCompStringAttr(); *pcComp != L'\0'; ++pcComp, ++pAttr ) { - D3DCOLOR bkColor; + DWORD bkColor; // Render a different background for this character int nXLeft, nXRight; @@ -840,12 +848,12 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) // Set up color based on the character attribute if( *pAttr == ATTR_TARGET_CONVERTED ) { - pElement->FontColor.Current = m_CompTargetColor; + pElement->FontColor.SetCurrent( m_CompTargetColor ); bkColor = m_CompTargetBkColor; } else if( *pAttr == ATTR_TARGET_NOTCONVERTED ) { - pElement->FontColor.Current = m_CompTargetNonColor; + pElement->FontColor.SetCurrent( m_CompTargetNonColor ); bkColor = m_CompTargetNonBkColor; } else @@ -884,22 +892,22 @@ void CDXUTIMEEditBox::RenderComposition( float fElapsedTime ) //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::RenderIndicator( float fElapsedTime ) +void CDXUTIMEEditBox::RenderIndicator( _In_ float fElapsedTime ) { - CDXUTElement* pElement = m_Elements.GetAt( 9 ); + auto pElement = m_Elements[ 9 ]; pElement->TextureColor.Blend( DXUT_STATE_NORMAL, fElapsedTime ); m_pDialog->DrawSprite( pElement, &m_rcIndicator, DXUT_NEAR_BUTTON_DEPTH ); RECT rc = m_rcIndicator; InflateRect( &rc, -m_nSpacing, -m_nSpacing ); - pElement->FontColor.Current = m_IndicatorImeColor; + pElement->FontColor.SetCurrent( m_IndicatorImeColor ); RECT rcCalc = { 0, 0, 0, 0 }; // If IME system is off, draw English indicator. - WCHAR* pwszIndicator = ImeUi_IsEnabled() ? ImeUi_GetIndicatior() : L"En"; + const WCHAR* pwszIndicator = ImeUi_IsEnabled() ? ImeUi_GetIndicatior() : L"En"; m_pDialog->CalcTextRect( pwszIndicator, pElement, &rcCalc ); m_pDialog->DrawText( pwszIndicator, pElement, &rc ); @@ -907,7 +915,7 @@ void CDXUTIMEEditBox::RenderIndicator( float fElapsedTime ) //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::Render( float fElapsedTime ) +void CDXUTIMEEditBox::Render( _In_ float fElapsedTime ) { if( m_bVisible == false ) return; @@ -920,7 +928,7 @@ void CDXUTIMEEditBox::Render( float fElapsedTime ) { 0, 0, 0, 0 }; - m_pDialog->CalcTextRect( L"En", m_Elements.GetAt( 9 ), &rc ); + m_pDialog->CalcTextRect( L"En", m_Elements[ 9 ], &rc ); m_nIndicatorWidth = rc.right - rc.left; // Update the rectangles now that we have the indicator's width @@ -930,7 +938,7 @@ void CDXUTIMEEditBox::Render( float fElapsedTime ) // Let the parent render first (edit control) CDXUTEditBox::Render( fElapsedTime ); - CDXUTElement* pElement = GetElement( 1 ); + auto pElement = GetElement( 1 ); if( pElement ) { s_CompString.SetFontNode( m_pDialog->GetFont( pElement->iFont ) ); @@ -951,35 +959,35 @@ void CDXUTIMEEditBox::Render( float fElapsedTime ) // Display the composition string. // This method should also update s_ptCompString // for RenderCandidateReadingWindow. - RenderComposition( fElapsedTime ); + RenderComposition(); // Display the reading/candidate window. RenderCandidateReadingWindow() // uses s_ptCompString to position itself. s_ptCompString must have // been filled in by RenderComposition(). if( ImeUi_IsShowReadingWindow() ) // Reading window - RenderCandidateReadingWindow( fElapsedTime, true ); + RenderCandidateReadingWindow( true ); else if( ImeUi_IsShowCandListWindow() ) // Candidate list window - RenderCandidateReadingWindow( fElapsedTime, false ); + RenderCandidateReadingWindow( false ); } } //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::SetImeEnableFlag( bool bFlag ) +void CDXUTIMEEditBox::SetImeEnableFlag( _In_ bool bFlag ) { s_bImeFlag = bFlag; } //-------------------------------------------------------------------------------------- -void CDXUTIMEEditBox::Initialize( HWND hWnd ) +void CDXUTIMEEditBox::Initialize( _In_ HWND hWnd ) { - ImeUiCallback_DrawRect = NULL; + ImeUiCallback_DrawRect = nullptr; ImeUiCallback_Malloc = malloc; ImeUiCallback_Free = free; - ImeUiCallback_DrawFans = NULL; + ImeUiCallback_DrawFans = nullptr; ImeUi_Initialize( hWnd ); diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.h b/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.h index 0fd177a..4190feb 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.h +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTguiIME.h @@ -2,16 +2,16 @@ // File: DXUTguiIME.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_IME_H -#define DXUT_IME_H #include <usp10.h> #include <dimm.h> #include "ImeUi.h" - //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- @@ -28,37 +28,37 @@ class CDXUTIMEEditBox : public CDXUTEditBox { public: - static HRESULT CreateIMEEditBox( CDXUTDialog* pDialog, int ID, LPCWSTR strText, int x, int y, int width, - int height, bool bIsDefault=false, CDXUTIMEEditBox** ppCreated=NULL ); + static HRESULT CreateIMEEditBox( _In_ CDXUTDialog* pDialog, _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, + _In_ int height, _In_ bool bIsDefault=false, _Outptr_opt_ CDXUTIMEEditBox** ppCreated=nullptr ); - CDXUTIMEEditBox( CDXUTDialog* pDialog = NULL ); - virtual ~CDXUTIMEEditBox(); + CDXUTIMEEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr ); + virtual ~CDXUTIMEEditBox(); - static void InitDefaultElements( CDXUTDialog* pDialog ); + static void InitDefaultElements( _In_ CDXUTDialog* pDialog ); - static void WINAPI Initialize( HWND hWnd ); - static void WINAPI Uninitialize(); + static void WINAPI Initialize( _In_ HWND hWnd ); + static void WINAPI Uninitialize(); static HRESULT WINAPI StaticOnCreateDevice(); - static bool WINAPI StaticMsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); + static bool WINAPI StaticMsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); - static void WINAPI SetImeEnableFlag( bool bFlag ); + static void WINAPI SetImeEnableFlag( _In_ bool bFlag ); - virtual void Render( float fElapsedTime ); - virtual bool MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ); - virtual bool HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ); - virtual void UpdateRects(); - virtual void OnFocusIn(); - virtual void OnFocusOut(); + virtual void Render( _In_ float fElapsedTime ) override; + virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; + virtual void UpdateRects() override; + virtual void OnFocusIn() override; + virtual void OnFocusOut() override; - void PumpMessage(); + void PumpMessage(); - virtual void RenderCandidateReadingWindow( float fElapsedTime, bool bReading ); - virtual void RenderComposition( float fElapsedTime ); - virtual void RenderIndicator( float fElapsedTime ); + virtual void RenderCandidateReadingWindow( _In_ bool bReading ); + virtual void RenderComposition(); + virtual void RenderIndicator( _In_ float fElapsedTime ); protected: - static void WINAPI EnableImeSystem( bool bEnable ); + static void WINAPI EnableImeSystem( _In_ bool bEnable ); static WORD WINAPI GetLanguage() { @@ -68,8 +68,8 @@ protected: { return ImeUi_GetPrimaryLanguage(); } - static void WINAPI SendKey( BYTE nVirtKey ); - static DWORD WINAPI GetImeId( UINT uIndex = 0 ) + static void WINAPI SendKey( _In_ BYTE nVirtKey ); + static DWORD WINAPI GetImeId( _In_ UINT uIndex = 0 ) { return ImeUi_GetImeId( uIndex ); }; @@ -108,24 +108,24 @@ protected: static bool s_bImeFlag; // Is ime enabled // Color of various IME elements - D3DCOLOR m_ReadingColor; // Reading string color - D3DCOLOR m_ReadingWinColor; // Reading window color - D3DCOLOR m_ReadingSelColor; // Selected character in reading string - D3DCOLOR m_ReadingSelBkColor; // Background color for selected char in reading str - D3DCOLOR m_CandidateColor; // Candidate string color - D3DCOLOR m_CandidateWinColor; // Candidate window color - D3DCOLOR m_CandidateSelColor; // Selected candidate string color - D3DCOLOR m_CandidateSelBkColor; // Selected candidate background color - D3DCOLOR m_CompColor; // Composition string color - D3DCOLOR m_CompWinColor; // Composition string window color - D3DCOLOR m_CompCaretColor; // Composition string caret color - D3DCOLOR m_CompTargetColor; // Composition string target converted color - D3DCOLOR m_CompTargetBkColor; // Composition string target converted background - D3DCOLOR m_CompTargetNonColor; // Composition string target non-converted color - D3DCOLOR m_CompTargetNonBkColor;// Composition string target non-converted background - D3DCOLOR m_IndicatorImeColor; // Indicator text color for IME - D3DCOLOR m_IndicatorEngColor; // Indicator text color for English - D3DCOLOR m_IndicatorBkColor; // Indicator text background color + DWORD m_ReadingColor; // Reading string color + DWORD m_ReadingWinColor; // Reading window color + DWORD m_ReadingSelColor; // Selected character in reading string + DWORD m_ReadingSelBkColor; // Background color for selected char in reading str + DWORD m_CandidateColor; // Candidate string color + DWORD m_CandidateWinColor; // Candidate window color + DWORD m_CandidateSelColor; // Selected candidate string color + DWORD m_CandidateSelBkColor; // Selected candidate background color + DWORD m_CompColor; // Composition string color + DWORD m_CompWinColor; // Composition string window color + DWORD m_CompCaretColor; // Composition string caret color + DWORD m_CompTargetColor; // Composition string target converted color + DWORD m_CompTargetBkColor; // Composition string target converted background + DWORD m_CompTargetNonColor; // Composition string target non-converted color + DWORD m_CompTargetNonBkColor;// Composition string target non-converted background + DWORD m_IndicatorImeColor; // Indicator text color for IME + DWORD m_IndicatorEngColor; // Indicator text color for English + DWORD m_IndicatorBkColor; // Indicator text background color // Edit-control-specific data int m_nIndicatorWidth; // Width of the indicator symbol @@ -135,7 +135,3 @@ protected: static bool m_bIMEStaticMsgProcCalled; #endif }; - - - -#endif // DXUT_IME_H diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTres.cpp b/samples/DX_APIUsage/DXUT/Optional/DXUTres.cpp index 080091b..5fb5440 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTres.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTres.cpp @@ -1,11 +1,16 @@ //---------------------------------------------------------------------------- // File: DXUTRes.cpp // -// Copyright (c) Microsoft Corp. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //----------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTres.h" +#include "DDSTextureLoader.h" + static const DWORD g_DXUTGUITextureSrcData[] = { 0x20534444, 0x0000007c, 0x00001007, 0x00000100, 0x00000100, 0x00000000, 0x00000000, 0x00000000, @@ -8283,57 +8288,24 @@ static const DWORD g_DXUTArrowMeshSrcData[] = static const UINT g_DXUTArrowMeshSrcDataSizeInBytes = 2193; -//----------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray9( LPDIRECT3DDEVICE9 pd3dDevice, IDirect3DTexture9** ppTexture, D3DXIMAGE_INFO* pInfo ) -{ - return D3DXCreateTextureFromFileInMemoryEx( pd3dDevice, g_DXUTGUITextureSrcData, g_DXUTGUITextureSrcDataSizeInBytes, - D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, pInfo, NULL, ppTexture ); -} - //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray11(ID3D11Device* pd3dDevice, ID3D11Texture2D** ppTexture, D3DX11_IMAGE_INFO* pInfo) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateGUITextureFromInternalArray(ID3D11Device* pd3dDevice, ID3D11Texture2D** ppTexture) { - HRESULT hr; - - D3DX11_IMAGE_INFO SrcInfo; - if( !pInfo ) - { - D3DX11GetImageInfoFromMemory( g_DXUTGUITextureSrcData, g_DXUTGUITextureSrcDataSizeInBytes, NULL, &SrcInfo, NULL ); - pInfo = &SrcInfo; - } - - ID3D11Resource *pRes; - D3DX11_IMAGE_LOAD_INFO loadInfo; - loadInfo.Width = D3DX11_DEFAULT; - loadInfo.Height = D3DX11_DEFAULT; - loadInfo.Depth = D3DX11_DEFAULT; - loadInfo.FirstMipLevel = 0; - loadInfo.MipLevels = 1; - loadInfo.Usage = D3D11_USAGE_DEFAULT; - loadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE; - loadInfo.CpuAccessFlags = 0; - loadInfo.MiscFlags = 0; - //loadInfo.Format = MAKE_TYPELESS( pInfo->Format ); - loadInfo.Format = MAKE_SRGB( pInfo->Format ); - loadInfo.Filter = D3DX11_FILTER_NONE; - loadInfo.MipFilter = D3DX11_FILTER_NONE; - loadInfo.pSrcInfo = pInfo; + if ( !ppTexture ) + return E_INVALIDARG; - hr = D3DX11CreateTextureFromMemory( pd3dDevice, g_DXUTGUITextureSrcData, g_DXUTGUITextureSrcDataSizeInBytes, &loadInfo, NULL, &pRes, NULL ); - if( FAILED( hr ) ) + ID3D11Resource *pRes = nullptr; + HRESULT hr = DirectX::CreateDDSTextureFromMemory( pd3dDevice, + reinterpret_cast<const uint8_t*>(g_DXUTGUITextureSrcData), g_DXUTGUITextureSrcDataSizeInBytes, + &pRes, nullptr ); + if ( FAILED(hr) ) return hr; + DXUT_SetDebugName( pRes, "DXUT" ); + hr = pRes->QueryInterface( __uuidof( ID3D11Texture2D ), (LPVOID*)ppTexture ); SAFE_RELEASE( pRes ); - return S_OK; + return hr; } - -//----------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateArrowMeshFromInternalArray( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh** ppMesh ) -{ - return D3DXLoadMeshFromXInMemory( g_DXUTArrowMeshSrcData, g_DXUTArrowMeshSrcDataSizeInBytes, - D3DXMESH_MANAGED, pd3dDevice, NULL, NULL, NULL, NULL, ppMesh ); -} - diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTres.h b/samples/DX_APIUsage/DXUT/Optional/DXUTres.h index a3e851f..0216b5c 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTres.h +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTres.h @@ -3,16 +3,11 @@ // // Functions to create DXUT media from arrays in memory // -// Copyright (c) Microsoft Corp. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //----------------------------------------------------------------------------- #pragma once -#ifndef DXUT_RES_H -#define DXUT_RES_H - -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray9( LPDIRECT3DDEVICE9 pd3dDevice, IDirect3DTexture9** ppTexture, - D3DXIMAGE_INFO* pInfo ); -HRESULT WINAPI DXUTCreateGUITextureFromInternalArray11( ID3D11Device* pd3dDevice, ID3D11Texture2D** ppTexture, - D3DX11_IMAGE_INFO* pInfo ); -HRESULT WINAPI DXUTCreateArrowMeshFromInternalArray( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh** ppMesh ); -#endif +HRESULT WINAPI DXUTCreateGUITextureFromInternalArray( _In_ ID3D11Device* pd3dDevice, _Outptr_ ID3D11Texture2D** ppTexture ); diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.cpp b/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.cpp index 6cf495b..483217d 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.cpp @@ -3,24 +3,21 @@ // // Dialog for selection of device settings // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" #include "DXUTsettingsDlg.h" -#undef min // use __min instead -#undef max // use __max instead - //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- -WCHAR* DXUTAPIVersionToString( DXUTDeviceVersion version ); -WCHAR* DXUTPresentIntervalToString( UINT pi ); -WCHAR* DXUTMultisampleTypeToString( D3DMULTISAMPLE_TYPE MultiSampleType ); -WCHAR* DXUTD3DDeviceTypeToString( D3DDEVTYPE devType ); -WCHAR* DXUTD3DX11DeviceTypeToString( D3D_DRIVER_TYPE devType ); -WCHAR* DXUTVertexProcessingTypeToString( DWORD vpt ); +const WCHAR* DXUTPresentIntervalToString( _In_ UINT pi ); +const WCHAR* DXUTDeviceTypeToString( _In_ D3D_DRIVER_TYPE devType ); +const WCHAR* DXUTVertexProcessingTypeToString( _In_ DWORD vpt ); HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL = D3D_FEATURE_LEVEL(0) ); @@ -39,19 +36,24 @@ CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog() //-------------------------------------------------------------------------------------- -CD3DSettingsDlg::CD3DSettingsDlg() +CD3DSettingsDlg::CD3DSettingsDlg() : + m_bActive( false ), + m_pActiveDialog( nullptr ) { - m_pStateBlock = NULL; - m_bActive = false; - m_pActiveDialog = NULL; - m_Levels[0] = D3D_FEATURE_LEVEL_9_1; m_Levels[1] = D3D_FEATURE_LEVEL_9_2; m_Levels[2] = D3D_FEATURE_LEVEL_9_3; m_Levels[3] = D3D_FEATURE_LEVEL_10_0; m_Levels[4] = D3D_FEATURE_LEVEL_10_1; m_Levels[5] = D3D_FEATURE_LEVEL_11_0; - + m_Levels[6] = D3D_FEATURE_LEVEL_11_1; +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + m_Levels[7] = D3D_FEATURE_LEVEL_12_0; + m_Levels[8] = D3D_FEATURE_LEVEL_12_1; +#else + m_Levels[7] = static_cast<D3D_FEATURE_LEVEL>(0xc000); + m_Levels[8] = static_cast<D3D_FEATURE_LEVEL>(0xc100); +#endif } @@ -59,18 +61,18 @@ CD3DSettingsDlg::CD3DSettingsDlg() CD3DSettingsDlg::~CD3DSettingsDlg() { // Release the memory used to hold the D3D11 refresh data in the combo box - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); if( pComboBox ) for( UINT i = 0; i < pComboBox->GetNumItems(); ++i ) { - DXGI_RATIONAL* pRate = reinterpret_cast<DXGI_RATIONAL*>( pComboBox->GetItemData( i ) ); + auto pRate = reinterpret_cast<DXGI_RATIONAL*>( pComboBox->GetItemData( i ) ); delete pRate; } } //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager ) +void CD3DSettingsDlg::Init( _In_ CDXUTDialogResourceManager* pManager ) { assert( pManager ); m_Dialog.Init( pManager, false ); // Don't register this dialog. @@ -80,6 +82,7 @@ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager ) } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager, LPCWSTR szControlTextureFileName ) { assert( pManager ); @@ -91,6 +94,7 @@ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager, LPCWSTR szCont //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CD3DSettingsDlg::Init( CDXUTDialogResourceManager* pManager, LPCWSTR pszControlTextureResourcename, HMODULE hModule ) { @@ -111,89 +115,44 @@ void CD3DSettingsDlg::CreateControls() m_Dialog.SetFont( 1, L"Arial", 28, FW_BOLD ); // Right-justify static controls - CDXUTElement* pElement = m_Dialog.GetDefaultElement( DXUT_CONTROL_STATIC, 0 ); + auto pElement = m_Dialog.GetDefaultElement( DXUT_CONTROL_STATIC, 0 ); if( pElement ) { pElement->dwTextFormat = DT_VCENTER | DT_RIGHT; // Title - CDXUTStatic* pStatic = NULL; + CDXUTStatic* pStatic = nullptr; m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Direct3D Settings", 10, 5, 400, 50, false, &pStatic ); pElement = pStatic->GetElement( 0 ); pElement->iFont = 1; pElement->dwTextFormat = DT_TOP | DT_LEFT; } - // DXUTSETTINGSDLG_API_VERSION - m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"API Version", 10, 35, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_API_VERSION, 200, 35, 300, 23 ); - - //DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL, L"Feature Level", 10, 60, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL, 200, 60, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL, 200, 60, 400, 23 ); m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL )->SetDropHeight( 106 ); - // DXUTSETTINGSDLG_ADAPTER m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Display Adapter", 10, 85, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_ADAPTER, 200, 85, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_ADAPTER, 200, 85, 400, 23 ); // DXUTSETTINGSDLG_DEVICE_TYPE m_Dialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Render Device", 10, 110, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_DEVICE_TYPE, 200, 110, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_DEVICE_TYPE, 200, 110, 400, 23 ); // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN - m_Dialog.AddCheckBox( DXUTSETTINGSDLG_DEVICECLIP, L"Clip to device when window spans across multiple monitors", - 250, 136, 500, 16 ); m_Dialog.AddRadioButton( DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_WINDOWED_GROUP, L"Windowed", 360, 157, 100, 16 ); m_Dialog.AddRadioButton( DXUTSETTINGSDLG_FULLSCREEN, DXUTSETTINGSDLG_WINDOWED_GROUP, L"Full Screen", 220, 157, 100, 16 ); - // DXUTSETTINGSDLG_ADAPTER_FORMAT - m_Dialog.AddStatic( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL, L"Adapter Format", 10, 175, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT, 200, 175, 300, 23 ); - - // DXUTSETTINGSDLG_RESOLUTION - m_Dialog.AddStatic( DXUTSETTINGSDLG_RESOLUTION_LABEL, L"Resolution", 10, 200, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_RESOLUTION, 200, 200, 200, 23 ); - m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION )->SetDropHeight( 106 ); - // DXUTSETTINGSDLG_RES_SHOW_ALL m_Dialog.AddCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL, L"Show All Aspect Ratios", 420, 200, 200, 23, false ); - // DXUTSETTINGSDLG_REFRESH_RATE - m_Dialog.AddStatic( DXUTSETTINGSDLG_REFRESH_RATE_LABEL, L"Refresh Rate", 10, 225, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_REFRESH_RATE, 200, 225, 300, 23 ); - - // DXUTSETTINGSDLG_BACK_BUFFER_FORMAT - m_Dialog.AddStatic( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL, L"Back Buffer Format", 10, 260, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT, 200, 260, 300, 23 ); - - // DXUTSETTINGSDLG_DEPTH_STENCIL - m_Dialog.AddStatic( DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL, L"Depth/Stencil Format", 10, 285, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL, 200, 285, 300, 23 ); - - // DXUTSETTINGSDLG_MULTISAMPLE_TYPE - m_Dialog.AddStatic( DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL, L"Multisample Type", 10, 310, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE, 200, 310, 300, 23 ); - - // DXUTSETTINGSDLG_MULTISAMPLE_QUALITY - m_Dialog.AddStatic( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL, L"Multisample Quality", 10, 335, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY, 200, 335, 300, 23 ); - - // DXUTSETTINGSDLG_VERTEX_PROCESSING - m_Dialog.AddStatic( DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL, L"Vertex Processing", 10, 360, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING, 200, 360, 300, 23 ); - - // DXUTSETTINGSDLG_PRESENT_INTERVAL - m_Dialog.AddStatic( DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL, L"Vertical Sync", 10, 385, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL, 200, 385, 300, 23 ); - // DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL, L"Adapter Output", 10, 175, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, 200, 175, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, 200, 175, 400, 23 ); // DXUTSETTINGSDLG_D3D11_RESOLUTION m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL, L"Resolution", 10, 200, 180, 23 ); @@ -202,23 +161,30 @@ void CD3DSettingsDlg::CreateControls() // DXUTSETTINGSDLG_D3D11_REFRESH_RATE m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL, L"Refresh Rate", 10, 225, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE, 200, 225, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE, 200, 225, 400, 23 ); // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL, L"Back Buffer Format", 10, 260, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT, 200, 260, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT, 200, 260, 400, 23 ); // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL, L"Multisample Count", 10, 285, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT, 200, 285, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT, 200, 285, 400, 23 ); // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL, L"Multisample Quality", 10, 310, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY, 200, 310, 300, 23 ); + m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY, 200, 310, 400, 23 ); // DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL m_Dialog.AddStatic( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL, L"Vertical Sync", 10, 335, 180, 23 ); - m_Dialog.AddComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL, 200, 335, 300, 23 ); + m_Dialog.AddComboBox(DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL, 200, 335, 400, 23); + + auto pPresentIntervalComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL); + if (pPresentIntervalComboBox) + { + pPresentIntervalComboBox->AddItem(L"On", ULongToPtr(1)); + pPresentIntervalComboBox->AddItem(L"Off", ULongToPtr(0)); + } // DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE m_Dialog.AddCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE, L"Create Debug Device", 200, 365, 180, 23 ); @@ -239,17 +205,17 @@ void CD3DSettingsDlg::CreateControls() pElement->dwTextFormat = DT_VCENTER | DT_RIGHT; // Title - CDXUTStatic* pStatic = NULL; - m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Do you want to keep these display settings?", 10, 5, - 640, 50, false, &pStatic ); - pElement = pStatic->GetElement( 0 ); + CDXUTStatic* pStatic = nullptr; + if ( SUCCEEDED(m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC, L"Do you want to keep these display settings?", 10, 5, + 640, 50, false, &pStatic ) ) ) + pElement = pStatic->GetElement( 0 ); pElement->iFont = 1; pElement->dwTextFormat = DT_TOP | DT_LEFT; // Timeout static text control - m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT, L"", 10, 90, 640, 30, - false, &pStatic ); - pElement = pStatic->GetElement( 0 ); + if ( SUCCEEDED(m_RevertModeDialog.AddStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT, L"", 10, 90, 640, 30, + false, &pStatic ) ) ) + pElement = pStatic->GetElement( 0 ); pElement->iFont = 0; pElement->dwTextFormat = DT_TOP | DT_LEFT; } @@ -261,224 +227,180 @@ void CD3DSettingsDlg::CreateControls() //-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ) +// Changes the UI defaults to the current device settings +//-------------------------------------------------------------------------------------- +HRESULT CD3DSettingsDlg::Refresh() { - if( pd3dDevice == NULL ) - return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", E_INVALIDARG ); + g_DeviceSettings = DXUTGetDeviceSettings(); - // Create the fonts/textures - m_Dialog.SetCallback( StaticOnEvent, ( void* )this ); - m_RevertModeDialog.SetCallback( StaticOnEvent, ( void* )this ); + auto pD3DEnum = DXUTGetD3D11Enumeration(); - return S_OK; -} + // Fill the UI with the current settings + AddD3D11DeviceType( g_DeviceSettings.d3d11.DriverType ); + m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, true ); + m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_FULLSCREEN, (g_DeviceSettings.d3d11.DriverType != D3D_DRIVER_TYPE_WARP) ); -//-------------------------------------------------------------------------------------- -// Changes the UI defaults to the current device settings -//-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::Refresh() -{ - HRESULT hr = S_OK; + SetWindowed( FALSE != g_DeviceSettings.d3d11.sd.Windowed ); + auto pOutputInfo = GetCurrentD3D11OutputInfo(); + AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, g_DeviceSettings.d3d11.Output ); + + AddD3D11Resolution( g_DeviceSettings.d3d11.sd.BufferDesc.Width, + g_DeviceSettings.d3d11.sd.BufferDesc.Height ); + AddD3D11RefreshRate( g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate ); + AddD3D11BackBufferFormat( g_DeviceSettings.d3d11.sd.BufferDesc.Format ); + AddD3D11MultisampleCount( g_DeviceSettings.d3d11.sd.SampleDesc.Count ); + AddD3D11MultisampleQuality( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ); + + auto pBestDeviceSettingsCombo = pD3DEnum->GetDeviceSettingsCombo( + g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.sd.BufferDesc.Format, + ( g_DeviceSettings.d3d11.sd.Windowed != 0 ) ); - g_DeviceSettings = DXUTGetDeviceSettings(); + if( !pBestDeviceSettingsCombo ) + return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); - CDXUTComboBox* pAPIComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_API_VERSION ); - pAPIComboBox->RemoveAllItems(); - if( DXUTDoesAppSupportD3D9() ) - { - // Ensure that at least one adapter got enumerated. - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - if( pD3DEnum->GetAdapterInfoList()->GetSize() > 0 ) - AddAPIVersion( DXUT_D3D9_DEVICE ); - } - if( DXUTDoesAppSupportD3D11() && DXUTIsD3D11Available() ) - { - // Ensure that at least one adapter got enumerated. - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - if( pD3DEnum->GetAdapterInfoList()->GetSize() > 0 ) - AddAPIVersion( DXUT_D3D11_DEVICE ); - } + CDXUTComboBox *pFeatureLevelBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); + pFeatureLevelBox->RemoveAllItems(); + + D3D_FEATURE_LEVEL clampFL; + if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + clampFL = DXUTGetD3D11Enumeration()->GetWARPFeaturevel(); + else if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) + clampFL = DXUTGetD3D11Enumeration()->GetREFFeaturevel(); + else + clampFL = pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel; - // If no API has been added, something has gone wrong. Exit the dialog. - if( pAPIComboBox->GetNumItems() == 0 ) + for (int fli = 0; fli < TOTAL_FEATURE_LEVELS; fli++) { - SetActive( false ); - return S_OK; - } + if (m_Levels[fli] >= g_DeviceSettings.MinimumFeatureLevel + && m_Levels[fli] <= clampFL) + { + AddD3D11FeatureLevel( m_Levels[fli] ); + } + } + pFeatureLevelBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DeviceFeatureLevel ) ); + + // Get the adapters list from CD3D11Enumeration object + auto pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - pAPIComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.ver ) ); + if( pAdapterInfoList->empty() ) + return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", DXUTERR_NOCOMPATIBLEDEVICES ); - switch( g_DeviceSettings.ver ) + auto pAdapterCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + pAdapterCombo->RemoveAllItems(); + + // Add adapters + for( auto it = pAdapterInfoList->cbegin(); it != pAdapterInfoList->cend(); ++it ) { - case DXUT_D3D9_DEVICE: - { - // Show all D3D9-specific controls and hide controls for all other D3D versions. - ShowControlSet( DXUT_D3D9_DEVICE ); - - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - - // Fill the UI with the current settings - AddDeviceType( g_DeviceSettings.d3d9.DeviceType ); - SetWindowed( FALSE != g_DeviceSettings.d3d9.pp.Windowed ); - SetDeviceClip( 0 != ( g_DeviceSettings.d3d9.pp.Flags & D3DPRESENTFLAG_DEVICECLIP ) ); - AddAdapterFormat( g_DeviceSettings.d3d9.AdapterFormat ); - AddResolution( g_DeviceSettings.d3d9.pp.BackBufferWidth, g_DeviceSettings.d3d9.pp.BackBufferHeight ); - AddRefreshRate( g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz ); - AddBackBufferFormat( g_DeviceSettings.d3d9.pp.BackBufferFormat ); - AddDepthStencilBufferFormat( g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat ); - AddMultisampleType( g_DeviceSettings.d3d9.pp.MultiSampleType ); - AddMultisampleQuality( g_DeviceSettings.d3d9.pp.MultiSampleQuality ); - - if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_PUREDEVICE ) - AddVertexProcessingType( D3DCREATE_PUREDEVICE ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING ) - AddVertexProcessingType( D3DCREATE_HARDWARE_VERTEXPROCESSING ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING ) - AddVertexProcessingType( D3DCREATE_SOFTWARE_VERTEXPROCESSING ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING ) - AddVertexProcessingType( D3DCREATE_MIXED_VERTEXPROCESSING ); - - CD3D9EnumDeviceSettingsCombo* pBestDeviceSettingsCombo = pD3DEnum->GetDeviceSettingsCombo( - g_DeviceSettings.d3d9.AdapterOrdinal, g_DeviceSettings.d3d9.DeviceType, - g_DeviceSettings.d3d9.AdapterFormat, g_DeviceSettings.d3d9.pp.BackBufferFormat, - ( g_DeviceSettings.d3d9.pp.Windowed != 0 ) ); - if( NULL == pBestDeviceSettingsCombo ) - return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); - - // Get the adapters list from CD3D9Enumeration object - CGrowableArray <CD3D9EnumAdapterInfo*>* pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - - if( pAdapterInfoList->GetSize() == 0 ) - return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", DXUTERR_NOCOMPATIBLEDEVICES ); - - CDXUTComboBox* pAdapterCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterCombo->RemoveAllItems(); - - // Add adapters - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); iAdapter++ ) - { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } + AddAdapter( (*it)->szUniqueDescription, (*it)->AdapterOrdinal ); + } - pAdapterCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.AdapterOrdinal ) ); + pAdapterCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - hr = OnAPIVersionChanged( true ); - if( FAILED( hr ) ) - return hr; + // DXUTSETTINGSDLG_D3D11_RESOLUTION + HRESULT hr = UpdateD3D11Resolutions(); + if ( FAILED(hr) ) + return hr; - //m_Dialog.Refresh(); - CDXUTDialog::SetRefreshTime( ( float )DXUTGetTime() ); - break; - } - case DXUT_D3D11_DEVICE: - { - // Show all D3D11-specific controls and hide controls for all other D3D versions. - ShowControlSet( DXUT_D3D11_DEVICE ); + // DXUTSETTINGSDLG_D3D11_REFRESH_RATE + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + // Windowed mode + bool bWindowed = IsWindowed(); - // Fill the UI with the current settings - AddD3D11DeviceType( g_DeviceSettings.d3d11.DriverType ); - SetWindowed( FALSE != g_DeviceSettings.d3d11.sd.Windowed ); - CD3D11EnumOutputInfo* pOutputInfo = GetCurrentD3D11OutputInfo(); - AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, g_DeviceSettings.d3d11.Output ); - + // Backbuffer Format/Driver Type + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if (pAdapterInfo) + { + auto pBackBufferFormatComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT); + pBackBufferFormatComboBox->RemoveAllItems(); + for (size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++) + { + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[idc]; + if ((pDeviceCombo->Windowed == TRUE) == bWindowed) + { + AddD3D11BackBufferFormat(pDeviceCombo->BackBufferFormat); + } + } - AddD3D11Resolution( g_DeviceSettings.d3d11.sd.BufferDesc.Width, - g_DeviceSettings.d3d11.sd.BufferDesc.Height ); - AddD3D11RefreshRate( g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate ); - AddD3D11BackBufferFormat( g_DeviceSettings.d3d11.sd.BufferDesc.Format ); - AddD3D11MultisampleCount( g_DeviceSettings.d3d11.sd.SampleDesc.Count ); - AddD3D11MultisampleQuality( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ); + pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.sd.BufferDesc.Format) ); - CD3D11EnumDeviceSettingsCombo* pBestDeviceSettingsCombo = pD3DEnum->GetDeviceSettingsCombo( - g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.DriverType, - g_DeviceSettings.d3d11.Output, g_DeviceSettings.d3d11.sd.BufferDesc.Format, - ( g_DeviceSettings.d3d11.sd.Windowed != 0 ) ); + auto pDeviceTypeComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_DEVICE_TYPE); + pDeviceTypeComboBox->RemoveAllItems(); - if( NULL == pBestDeviceSettingsCombo ) - return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); + for (size_t iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.size(); iDeviceInfo++) + { + auto pDeviceInfo = pAdapterInfo->deviceInfoList[iDeviceInfo]; + AddD3D11DeviceType(pDeviceInfo->DeviceType); + } - CDXUTComboBox *pFeatureLevelBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); - pFeatureLevelBox->RemoveAllItems(); - for (int fli = 0; fli < TOTAL_FEATURE_LEVLES; fli++) { - if (m_Levels[fli] >= g_DeviceSettings.MinimumFeatureLevel - && m_Levels[fli] <=pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel) { - AddD3D11FeatureLevel( m_Levels[fli] ); - } - } - pFeatureLevelBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DeviceFeatureLevel ) ); + pDeviceTypeComboBox->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.DriverType) ); + } - - // Get the adapters list from CD3D11Enumeration object - CGrowableArray <CD3D11EnumAdapterInfo*>* pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); + // MSAA settings + auto pDeviceSettingsCombo = GetCurrentD3D11DeviceSettingsCombo(); + if ( pDeviceSettingsCombo ) + { + auto pMultisampleCountCombo = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT); + pMultisampleCountCombo->RemoveAllItems(); - if( pAdapterInfoList->GetSize() == 0 ) - return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", DXUTERR_NOCOMPATIBLEDEVICES ); + for (auto it = pDeviceSettingsCombo->multiSampleCountList.cbegin(); it != pDeviceSettingsCombo->multiSampleCountList.cend(); ++it) + AddD3D11MultisampleCount(*it); - CDXUTComboBox* pAdapterCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterCombo->RemoveAllItems(); + pMultisampleCountCombo->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.sd.SampleDesc.Count) ); - // Add adapters - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); iAdapter++ ) + UINT MaxQuality = 0; + for (size_t iCount = 0; iCount < pDeviceSettingsCombo->multiSampleCountList.size(); iCount++) + { + UINT Count = pDeviceSettingsCombo->multiSampleCountList[iCount]; + if ( Count == g_DeviceSettings.d3d11.sd.SampleDesc.Count ) { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); + MaxQuality = pDeviceSettingsCombo->multiSampleQualityList[iCount]; + break; } + } - pAdapterCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - - hr = OnAPIVersionChanged( true ); - if( FAILED( hr ) ) - return hr; + auto pMultisampleQualityCombo = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY); + pMultisampleQualityCombo->RemoveAllItems(); - //m_Dialog.Refresh(); - CDXUTDialog::SetRefreshTime( ( float )DXUTGetTime() ); - break; + for (UINT iQuality = 0; iQuality < MaxQuality; iQuality++) + { + AddD3D11MultisampleQuality(iQuality); } - } - - return S_OK; -} + pMultisampleQualityCombo->SetSelectedByData(ULongToPtr(g_DeviceSettings.d3d11.sd.SampleDesc.Quality)); + } -//-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D9ResetDevice() -{ - const D3DSURFACE_DESC* pDesc = DXUTGetD3D9BackBufferSurfaceDesc(); - m_Dialog.SetLocation( 0, 0 ); - m_Dialog.SetSize( pDesc->Width, pDesc->Height ); - m_Dialog.SetBackgroundColors( D3DCOLOR_ARGB( 255, 98, 138, 206 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 10, 73, 179 ) ); + // Misc settings + auto pDebugCheckBox = m_Dialog.GetCheckBox(DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE); + if ( pDebugCheckBox ) + { + pDebugCheckBox->SetChecked(0 != (g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG)); + } - m_RevertModeDialog.SetLocation( 0, 0 ); - m_RevertModeDialog.SetSize( pDesc->Width, pDesc->Height ); - m_RevertModeDialog.SetBackgroundColors( D3DCOLOR_ARGB( 255, 98, 138, 206 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 54, 105, 192 ), - D3DCOLOR_ARGB( 255, 10, 73, 179 ) ); + auto pPresentIntervalComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL); + if ( pPresentIntervalComboBox ) + { + pPresentIntervalComboBox->SetSelectedByData(ULongToPtr(g_DeviceSettings.d3d11.SyncInterval) ); + } - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - pd3dDevice->BeginStateBlock(); - pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); - pd3dDevice->EndStateBlock( &m_pStateBlock ); + CDXUTDialog::SetRefreshTime( ( float )DXUTGetTime() ); return S_OK; } + //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::SetSelectedD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) +void CD3DSettingsDlg::SetSelectedD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ) { - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + auto pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); for( UINT i = 0; i < pRefreshRateComboBox->GetNumItems(); ++i ) { - DXGI_RATIONAL* pRate = ( DXGI_RATIONAL* )pRefreshRateComboBox->GetItemData( i ); + auto pRate = reinterpret_cast<DXGI_RATIONAL*>( pRefreshRateComboBox->GetItemData( i ) ); if( pRate && pRate->Numerator == RefreshRate.Numerator && pRate->Denominator == RefreshRate.Denominator ) { @@ -489,38 +411,7 @@ void CD3DSettingsDlg::SetSelectedD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) } //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnRender( float fElapsedTime ) -{ - if( DXUTGetD3D11Device() ) - OnRender11( fElapsedTime ); - else - OnRender9( fElapsedTime ); -} - - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnRender9( float fElapsedTime ) -{ - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - - // Clear the render target and the zbuffer - pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0x00003F3F, 1.0f, 0 ); - - // Render the scene - if( SUCCEEDED( pd3dDevice->BeginScene() ) ) - { - m_pStateBlock->Capture(); - pd3dDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID ); - m_pActiveDialog->OnRender( fElapsedTime ); - m_pStateBlock->Apply(); - pd3dDevice->EndScene(); - } -} - - - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnRender11( float fElapsedTime ) +void CD3DSettingsDlg::OnRender( _In_ float fElapsedTime ) { // Render the scene m_pActiveDialog->OnRender( fElapsedTime ); @@ -528,6 +419,7 @@ void CD3DSettingsDlg::OnRender11( float fElapsedTime ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CD3DSettingsDlg::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { m_pActiveDialog->MsgProc( hWnd, uMsg, wParam, lParam ); @@ -536,27 +428,10 @@ LRESULT CD3DSettingsDlg::MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lP return 0; } - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnD3D9LostDevice() -{ - SAFE_RELEASE( m_pStateBlock ); -} - - -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnD3D9DestroyDevice() -{ -} - - - //-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D11CreateDevice( ID3D11Device* pd3dDevice ) +HRESULT CD3DSettingsDlg::OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice ) { - //HRESULT hr; - - if( pd3dDevice == NULL ) + if( !pd3dDevice ) return DXUT_ERR_MSGBOX( L"CD3DSettingsDlg::OnCreatedDevice", E_INVALIDARG ); // Create the fonts/textures @@ -568,9 +443,11 @@ HRESULT CD3DSettingsDlg::OnD3D11CreateDevice( ID3D11Device* pd3dDevice ) //-------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) +_Use_decl_annotations_ +HRESULT CD3DSettingsDlg::OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ) { + UNREFERENCED_PARAMETER(pd3dDevice); + m_Dialog.SetLocation( 0, 0 ); m_Dialog.SetSize( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); m_Dialog.SetBackgroundColors( D3DCOLOR_ARGB( 255, 98, 138, 206 ), @@ -596,101 +473,13 @@ void CD3DSettingsDlg::OnD3D11DestroyDevice() } -//-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::ShowControlSet( DXUTDeviceVersion ver ) -{ - switch( ver ) - { - case DXUT_D3D9_DEVICE: - - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEVICECLIP )->SetVisible( true ); - - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE )->SetVisible( false ); - - break; - - case DXUT_D3D11_DEVICE: - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_RESOLUTION_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_REFRESH_RATE_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL )->SetVisible( false ); - m_Dialog.GetControl( DXUTSETTINGSDLG_DEVICECLIP )->SetVisible( false ); - - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL )->SetVisible( true ); - m_Dialog.GetControl( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE )->SetVisible( true ); - break; - } -} - //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI CD3DSettingsDlg::StaticOnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserData ) { - CD3DSettingsDlg* pD3DSettings = ( CD3DSettingsDlg* )pUserData; + auto pD3DSettings = reinterpret_cast<CD3DSettingsDlg*>( pUserData ); if( pD3DSettings ) pD3DSettings->OnEvent( nEvent, nControlID, pControl ); } @@ -700,26 +489,34 @@ void WINAPI CD3DSettingsDlg::StaticOnEvent( UINT nEvent, int nControlID, // Desc: Timer callback registered by a call to DXUTSetTimer. It is called each second // until mode change timeout limit. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI CD3DSettingsDlg::StaticOnModeChangeTimer( UINT nIDEvent, void* pUserContext ) { - CD3DSettingsDlg* pD3DSettings = ( CD3DSettingsDlg* )pUserContext; + UNREFERENCED_PARAMETER(nIDEvent); + + auto pD3DSettings = reinterpret_cast<CD3DSettingsDlg*>( pUserContext ); assert( pD3DSettings ); + _Analysis_assume_( pD3DSettings ); assert( pD3DSettings->m_pActiveDialog == &pD3DSettings->m_RevertModeDialog ); assert( pD3DSettings->m_nIDEvent == nIDEvent ); if( 0 == --pD3DSettings->m_nRevertModeTimeout ) { - CDXUTControl* pControl = pD3DSettings->m_RevertModeDialog.GetControl( DXUTSETTINGSDLG_MODE_CHANGE_REVERT ); + auto pControl = pD3DSettings->m_RevertModeDialog.GetControl( DXUTSETTINGSDLG_MODE_CHANGE_REVERT ); assert( pControl ); + _Analysis_assume_( pControl ); pD3DSettings->m_RevertModeDialog.SendEvent( EVENT_BUTTON_CLICKED, false, pControl ); } pD3DSettings->UpdateModeChangeTimeoutText( pD3DSettings->m_nRevertModeTimeout ); } //-------------------------------------------------------------------------------------- -void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, - CDXUTControl* pControl ) +_Use_decl_annotations_ +void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl ) { + UNREFERENCED_PARAMETER(nEvent); + UNREFERENCED_PARAMETER(pControl); + switch( nControlID ) { case DXUTSETTINGSDLG_ADAPTER: @@ -730,42 +527,10 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, OnWindowedFullScreenChanged(); break; case DXUTSETTINGSDLG_FULLSCREEN: OnWindowedFullScreenChanged(); break; - case DXUTSETTINGSDLG_ADAPTER_FORMAT: - OnAdapterFormatChanged(); break; case DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL: - { - if( g_DeviceSettings.ver == DXUT_D3D9_DEVICE ) - { - OnAdapterFormatChanged(); - } - else - { - OnBackBufferFormatChanged(); - } - break; - } + OnBackBufferFormatChanged(); break; case DXUTSETTINGSDLG_D3D11_RESOLUTION: OnD3D11ResolutionChanged(); break; - case DXUTSETTINGSDLG_RESOLUTION: - OnResolutionChanged(); break; - case DXUTSETTINGSDLG_REFRESH_RATE: - OnRefreshRateChanged(); break; - case DXUTSETTINGSDLG_BACK_BUFFER_FORMAT: - OnBackBufferFormatChanged(); break; - case DXUTSETTINGSDLG_DEPTH_STENCIL: - OnDepthStencilBufferFormatChanged(); break; - case DXUTSETTINGSDLG_MULTISAMPLE_TYPE: - OnMultisampleTypeChanged(); break; - case DXUTSETTINGSDLG_MULTISAMPLE_QUALITY: - OnMultisampleQualityChanged(); break; - case DXUTSETTINGSDLG_VERTEX_PROCESSING: - OnVertexProcessingChanged(); break; - case DXUTSETTINGSDLG_PRESENT_INTERVAL: - OnPresentIntervalChanged(); break; - case DXUTSETTINGSDLG_DEVICECLIP: - OnDeviceClipChanged(); break; - case DXUTSETTINGSDLG_API_VERSION: - OnAPIVersionChanged(); break; case DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL: OnFeatureLevelChanged(); break; case DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT: @@ -786,69 +551,34 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, case DXUTSETTINGSDLG_OK: { bool bFullScreenModeChange = false; - DXUTDeviceSettings currentSettings = DXUTGetDeviceSettings(); + auto currentSettings = DXUTGetDeviceSettings(); g_DeviceSettings.MinimumFeatureLevel = currentSettings.MinimumFeatureLevel; - if( g_DeviceSettings.ver == DXUT_D3D9_DEVICE ) + if( g_DeviceSettings.d3d11.sd.Windowed ) { - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = 0; - - RECT rcClient; - if( DXUTIsWindowed() ) - GetClientRect( DXUTGetHWND(), &rcClient ); - else - rcClient = DXUTGetWindowClientRectAtModeChange(); - DWORD dwWindowWidth = rcClient.right - rcClient.left; - DWORD dwWindowHeight = rcClient.bottom - rcClient.top; - - g_DeviceSettings.d3d9.pp.BackBufferWidth = dwWindowWidth; - g_DeviceSettings.d3d9.pp.BackBufferHeight = dwWindowHeight; - } + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator = + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = 0; + + RECT rcClient; + if( DXUTIsWindowed() ) + GetClientRect( DXUTGetHWND(), &rcClient ); else - { - // Check for fullscreen mode change - bFullScreenModeChange = g_DeviceSettings.d3d9.pp.BackBufferWidth != - currentSettings.d3d9.pp.BackBufferWidth || - g_DeviceSettings.d3d9.pp.BackBufferHeight != currentSettings.d3d9.pp.BackBufferHeight || - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz != - currentSettings.d3d9.pp.FullScreen_RefreshRateInHz; - } + rcClient = DXUTGetWindowClientRectAtModeChange(); + DWORD dwWindowWidth = rcClient.right - rcClient.left; + DWORD dwWindowHeight = rcClient.bottom - rcClient.top; - if( g_DeviceSettings.d3d9.pp.MultiSampleType != D3DMULTISAMPLE_NONE ) - { - g_DeviceSettings.d3d9.pp.Flags &= ~D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; - } + g_DeviceSettings.d3d11.sd.BufferDesc.Width = dwWindowWidth; + g_DeviceSettings.d3d11.sd.BufferDesc.Height = dwWindowHeight; } - else // D3D11 + else { - if( g_DeviceSettings.d3d11.sd.Windowed ) - { - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator = - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = 0; - - RECT rcClient; - if( DXUTIsWindowed() ) - GetClientRect( DXUTGetHWND(), &rcClient ); - else - rcClient = DXUTGetWindowClientRectAtModeChange(); - DWORD dwWindowWidth = rcClient.right - rcClient.left; - DWORD dwWindowHeight = rcClient.bottom - rcClient.top; - - g_DeviceSettings.d3d11.sd.BufferDesc.Width = dwWindowWidth; - g_DeviceSettings.d3d11.sd.BufferDesc.Height = dwWindowHeight; - } - else - { - // Check for fullscreen mode change - bFullScreenModeChange = g_DeviceSettings.d3d11.sd.BufferDesc.Width != - currentSettings.d3d11.sd.BufferDesc.Width || - g_DeviceSettings.d3d11.sd.BufferDesc.Height != currentSettings.d3d11.sd.BufferDesc.Height || - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator != - currentSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator || - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator != - currentSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator; - } + // Check for fullscreen mode change + bFullScreenModeChange = g_DeviceSettings.d3d11.sd.BufferDesc.Width != + currentSettings.d3d11.sd.BufferDesc.Width || + g_DeviceSettings.d3d11.sd.BufferDesc.Height != currentSettings.d3d11.sd.BufferDesc.Height || + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator != + currentSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator || + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator != + currentSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator; } if( bFullScreenModeChange ) @@ -857,20 +587,6 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, // settings. These will get set to the user-defined settings once the // user accepts the mode change DXUTDeviceSettings tSettings = g_DeviceSettings; - if( g_DeviceSettings.ver == DXUT_D3D9_DEVICE ) - { - g_DeviceSettings.d3d9.pp.BackBufferWidth = - currentSettings.d3d9.pp.BackBufferWidth; - g_DeviceSettings.d3d9.pp.BackBufferHeight = - currentSettings.d3d9.pp.BackBufferHeight; - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = - currentSettings.d3d9.pp.FullScreen_RefreshRateInHz; - g_DeviceSettings.d3d9.pp.Windowed = - currentSettings.d3d9.pp.Windowed; - } - else - { - g_DeviceSettings.d3d11.sd.BufferDesc.Width = currentSettings.d3d11.sd.BufferDesc.Width; g_DeviceSettings.d3d11.sd.BufferDesc.Height = @@ -880,8 +596,6 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = currentSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator; g_DeviceSettings.d3d11.sd.Windowed = currentSettings.d3d11.sd.Windowed; - - } // apply the user-defined settings DXUTCreateDeviceFromSettings( &tSettings ); @@ -930,324 +644,154 @@ void CD3DSettingsDlg::OnEvent( UINT nEvent, int nControlID, //------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::SetDeviceSettingsFromUI() +CD3D11EnumAdapterInfo* CD3DSettingsDlg::GetCurrentD3D11AdapterInfo() const { - CDXUTComboBox* pComboBox; - CDXUTRadioButton* pRadioButton; - - // DXUTSETTINGSDLG_DEVICE_TYPE - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - g_DeviceSettings.d3d9.DeviceType = ( D3DDEVTYPE )PtrToUlong( pComboBox->GetSelectedData() ); - - // DXUTSETTINGSDLG_WINDOWED - pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); - g_DeviceSettings.d3d9.pp.Windowed = pRadioButton->GetChecked(); - - // DXUTSETTINGSDLG_ADAPTER_FORMAT - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - g_DeviceSettings.d3d9.AdapterFormat = ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); - - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - g_DeviceSettings.d3d9.pp.BackBufferFormat = D3DFMT_UNKNOWN; - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = 0; - } - else - { - // DXUTSETTINGSDLG_BACK_BUFFER_FORMAT - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - g_DeviceSettings.d3d9.pp.BackBufferFormat = ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); - - // DXUTSETTINGSDLG_RESOLUTION - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); - DWORD dwResolution = PtrToUlong( pComboBox->GetSelectedData() ); - g_DeviceSettings.d3d9.pp.BackBufferWidth = HIWORD( dwResolution ); - g_DeviceSettings.d3d9.pp.BackBufferHeight = LOWORD( dwResolution ); - - // DXUTSETTINGSDLG_REFRESH_RATE - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = PtrToUlong( pComboBox->GetSelectedData() ); - } - - // DXUTSETTINGSDLG_DEPTH_STENCIL - pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat = ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -CD3D9EnumAdapterInfo* CD3DSettingsDlg::GetCurrentAdapterInfo() -{ - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - return pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d9.AdapterOrdinal ); -} - - -//------------------------------------------------------------------------------------- -CD3D9EnumDeviceInfo* CD3DSettingsDlg::GetCurrentDeviceInfo() -{ - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - return pD3DEnum->GetDeviceInfo( g_DeviceSettings.d3d9.AdapterOrdinal, - g_DeviceSettings.d3d9.DeviceType ); -} - -//------------------------------------------------------------------------------------- -CD3D11EnumAdapterInfo* CD3DSettingsDlg::GetCurrentD3D11AdapterInfo() -{ - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d11.AdapterOrdinal ); } //------------------------------------------------------------------------------------- -CD3D11EnumDeviceInfo* CD3DSettingsDlg::GetCurrentD3D11DeviceInfo() +CD3D11EnumDeviceInfo* CD3DSettingsDlg::GetCurrentD3D11DeviceInfo() const { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetDeviceInfo( g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.DriverType ); } //------------------------------------------------------------------------------------- -CD3D11EnumOutputInfo* CD3DSettingsDlg::GetCurrentD3D11OutputInfo() +CD3D11EnumOutputInfo* CD3DSettingsDlg::GetCurrentD3D11OutputInfo() const { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetOutputInfo( g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.Output ); } - //------------------------------------------------------------------------------------- -CD3D9EnumDeviceSettingsCombo* CD3DSettingsDlg::GetCurrentDeviceSettingsCombo() +CD3D11EnumDeviceSettingsCombo* CD3DSettingsDlg::GetCurrentD3D11DeviceSettingsCombo() const { - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - return pD3DEnum->GetDeviceSettingsCombo( g_DeviceSettings.d3d9.AdapterOrdinal, - g_DeviceSettings.d3d9.DeviceType, - g_DeviceSettings.d3d9.AdapterFormat, - g_DeviceSettings.d3d9.pp.BackBufferFormat, - ( g_DeviceSettings.d3d9.pp.Windowed == TRUE ) ); -} - -//------------------------------------------------------------------------------------- -CD3D11EnumDeviceSettingsCombo* CD3DSettingsDlg::GetCurrentD3D11DeviceSettingsCombo() -{ - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); + auto pD3DEnum = DXUTGetD3D11Enumeration(); return pD3DEnum->GetDeviceSettingsCombo( g_DeviceSettings.d3d11.AdapterOrdinal, - g_DeviceSettings.d3d11.DriverType, - g_DeviceSettings.d3d11.Output, g_DeviceSettings.d3d11.sd.BufferDesc.Format, ( g_DeviceSettings.d3d11.sd.Windowed == TRUE ) ); } -HRESULT CD3DSettingsDlg::OnD3D11ResolutionChanged () { +HRESULT CD3DSettingsDlg::OnD3D11ResolutionChanged () +{ + if ( g_DeviceSettings.d3d11.sd.Windowed ) + return S_OK; + DWORD dwWidth, dwHeight; GetSelectedD3D11Resolution( &dwWidth, &dwHeight ); - g_DeviceSettings.d3d11.sd.BufferDesc.Width= dwWidth; + g_DeviceSettings.d3d11.sd.BufferDesc.Width = dwWidth; g_DeviceSettings.d3d11.sd.BufferDesc.Height = dwHeight; - + + // DXUTSETTINGSDLG_D3D11_REFRESH_RATE + HRESULT hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; + return S_OK; } -HRESULT CD3DSettingsDlg::OnFeatureLevelChanged () { +HRESULT CD3DSettingsDlg::OnFeatureLevelChanged () +{ HRESULT hr = E_FAIL; - if (g_DeviceSettings.ver == DXUT_D3D11_DEVICE) { - if (g_DeviceSettings.d3d11.DeviceFeatureLevel == GetSelectedFeatureLevel()) return S_OK; - //if( !bRefresh ) - //{ - // Obtain a set of valid D3D10 device settings. - UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; - ZeroMemory( &g_DeviceSettings, sizeof( g_DeviceSettings ) ); - - DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); - g_DeviceSettings.d3d11.CreateFlags = CreateFlags; - g_DeviceSettings.ver = DXUT_D3D11_DEVICE; - //g_DeviceSettings.d3d11.fl = GetSelectedFeatureLevel(); - hr = DXUTSnapDeviceSettingsToEnumDevice(&g_DeviceSettings, true, GetSelectedFeatureLevel()); - - //} - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - CGrowableArray <CD3D11EnumAdapterInfo*>* pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); + if (g_DeviceSettings.d3d11.DeviceFeatureLevel == GetSelectedFeatureLevel()) return S_OK; - CDXUTComboBox* pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterComboBox->RemoveAllItems(); + // Obtain a set of valid D3D11 device settings. + UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; + DXGI_FORMAT BackBufferFormat = g_DeviceSettings.d3d11.sd.BufferDesc.Format; + UINT Count = g_DeviceSettings.d3d11.sd.SampleDesc.Count; + UINT Quality = g_DeviceSettings.d3d11.sd.SampleDesc.Quality; + DXGI_RATIONAL RefreshRate = g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate; + ZeroMemory(&g_DeviceSettings, sizeof(g_DeviceSettings)); - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); ++iAdapter ) - { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } + DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); + g_DeviceSettings.d3d11.CreateFlags = CreateFlags; + hr = DXUTSnapDeviceSettingsToEnumDevice(&g_DeviceSettings, true, GetSelectedFeatureLevel()); + g_DeviceSettings.d3d11.sd.BufferDesc.Format = BackBufferFormat; + g_DeviceSettings.d3d11.sd.SampleDesc.Count = Count; + g_DeviceSettings.d3d11.sd.SampleDesc.Quality = Quality; + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = RefreshRate; - pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); + auto pD3DEnum = DXUTGetD3D11Enumeration(); + auto pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); - pCheckBox->SetChecked( 0 != ( g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG ) ); + // DXUTSETTINGSDLG_ADAPTER + auto pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + pAdapterComboBox->RemoveAllItems(); - hr = OnAdapterChanged(); - if( FAILED( hr ) ) - return hr; + for( auto it = pAdapterInfoList->cbegin(); it != pAdapterInfoList->cend(); ++it ) + { + AddAdapter( (*it)->szUniqueDescription, (*it)->AdapterOrdinal ); } - - return hr; -} -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnAPIVersionChanged( bool bRefresh ) -{ - HRESULT hr; + pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - // Store the API version - g_DeviceSettings.ver = GetSelectedAPIVersion(); + // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT + auto pBackBufferFormatComboBox = m_Dialog.GetComboBox(DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT); + pBackBufferFormatComboBox->RemoveAllItems(); + + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if (!pAdapterInfo) + return E_FAIL; - // Show/hide appropriate dialog controls based on version. - ShowControlSet( g_DeviceSettings.ver ); + bool bWindowed = IsWindowed(); - switch( g_DeviceSettings.ver ) + for (size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++) { - case DXUT_D3D9_DEVICE: + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[idc]; + if ((pDeviceCombo->Windowed == TRUE) == bWindowed) { - if( !bRefresh ) - { - // Obtain a set of valid D3D9 device settings. - UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; - ZeroMemory( &g_DeviceSettings, sizeof( g_DeviceSettings ) ); - // We want a specific API version, so set up match option to preserve it. - DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); - g_DeviceSettings.d3d11.CreateFlags = CreateFlags; - g_DeviceSettings.ver = DXUT_D3D9_DEVICE; - DXUTSnapDeviceSettingsToEnumDevice ( &g_DeviceSettings, true); - } - - CD3D9Enumeration* pD3DEnum = DXUTGetD3D9Enumeration(); - CGrowableArray <CD3D9EnumAdapterInfo*>* pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - - CDXUTComboBox* pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterComboBox->RemoveAllItems(); - - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); ++iAdapter ) - { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } - - pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.AdapterOrdinal ) ); - - hr = OnAdapterChanged(); - if( FAILED( hr ) ) - return hr; - - break; + AddD3D11BackBufferFormat(pDeviceCombo->BackBufferFormat); } + } - case DXUT_D3D11_DEVICE: - { - if( !bRefresh ) - { - // Obtain a set of valid D3D10 device settings. - UINT CreateFlags = g_DeviceSettings.d3d11.CreateFlags; - ZeroMemory( &g_DeviceSettings, sizeof( g_DeviceSettings ) ); - // We want a specific API version, so set up match option to preserve it. - DXUTApplyDefaultDeviceSettings(&g_DeviceSettings); - g_DeviceSettings.d3d11.CreateFlags = CreateFlags; - g_DeviceSettings.ver = DXUT_D3D11_DEVICE; - DXUTSnapDeviceSettingsToEnumDevice(&g_DeviceSettings, true); - - } - - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - CGrowableArray <CD3D11EnumAdapterInfo*>* pAdapterInfoList = pD3DEnum->GetAdapterInfoList(); - - CDXUTComboBox* pAdapterComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); - pAdapterComboBox->RemoveAllItems(); - - for( int iAdapter = 0; iAdapter < pAdapterInfoList->GetSize(); ++iAdapter ) - { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterInfoList->GetAt( iAdapter ); - AddAdapter( pAdapterInfo->szUniqueDescription, pAdapterInfo->AdapterOrdinal ); - } - - pAdapterComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.AdapterOrdinal ) ); - - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); - pCheckBox->SetChecked( 0 != ( g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG ) ); + pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr(g_DeviceSettings.d3d11.sd.BufferDesc.Format) ); - hr = OnAdapterChanged(); - if( FAILED( hr ) ) - return hr; + hr = OnBackBufferFormatChanged(); + if (FAILED(hr)) + return hr; - break; - } - } + auto pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); + pCheckBox->SetChecked( 0 != ( g_DeviceSettings.d3d11.CreateFlags & D3D11_CREATE_DEVICE_DEBUG ) ); - return S_OK; + hr = OnAdapterChanged(); + if( FAILED( hr ) ) + return hr; + + return hr; } //------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::OnAdapterChanged() { - HRESULT hr = S_OK; - - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - // Store the adapter index - g_DeviceSettings.d3d9.AdapterOrdinal = GetSelectedAdapter(); - - // DXUTSETTINGSDLG_DEVICE_TYPE - CDXUTComboBox* pDeviceTypeComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - pDeviceTypeComboBox->RemoveAllItems(); - - CD3D9EnumAdapterInfo* pAdapterInfo = GetCurrentAdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) - { - CD3D9EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); - AddDeviceType( pDeviceInfo->DeviceType ); - } + // Store the adapter index + g_DeviceSettings.d3d11.AdapterOrdinal = GetSelectedAdapter(); - pDeviceTypeComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.DeviceType ) ); - - hr = OnDeviceTypeChanged(); - if( FAILED( hr ) ) - return hr; - - break; - } - - case DXUT_D3D11_DEVICE: - { - // Store the adapter index - g_DeviceSettings.d3d11.AdapterOrdinal = GetSelectedAdapter(); - - // DXUTSETTINGSDLG_DEVICE_TYPE - CDXUTComboBox* pDeviceTypeComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - pDeviceTypeComboBox->RemoveAllItems(); - - CD3D11EnumAdapterInfo* pAdapterInfo = GetCurrentD3D11AdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; + // DXUTSETTINGSDLG_DEVICE_TYPE + auto pDeviceTypeComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + pDeviceTypeComboBox->RemoveAllItems(); - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) - { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); - AddD3D11DeviceType( pDeviceInfo->DeviceType ); - } + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if( !pAdapterInfo ) + return E_FAIL; - pDeviceTypeComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DriverType ) ); + for( size_t iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.size(); iDeviceInfo++ ) + { + auto pDeviceInfo = pAdapterInfo->deviceInfoList[ iDeviceInfo ]; + AddD3D11DeviceType( pDeviceInfo->DeviceType ); + } - hr = OnDeviceTypeChanged(); - if( FAILED( hr ) ) - return hr; + pDeviceTypeComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DriverType ) ); - break; - } - } + HRESULT hr = OnDeviceTypeChanged(); + if( FAILED( hr ) ) + return hr; return S_OK; } @@ -1259,60 +803,64 @@ HRESULT CD3DSettingsDlg::OnDeviceTypeChanged() { HRESULT hr = S_OK; - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - g_DeviceSettings.d3d9.DeviceType = GetSelectedDeviceType(); + g_DeviceSettings.d3d11.DriverType = GetSelectedD3D11DeviceType(); - // Update windowed/full screen radio buttons - bool bHasWindowedDeviceCombo = false; - bool bHasFullScreenDeviceCombo = false; - - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; - - for( int idc = 0; idc < pDeviceInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( idc ); + // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN + m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, true ); + if (g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_FULLSCREEN, false ); + g_DeviceSettings.d3d11.sd.Windowed = TRUE; + } + else + { + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_FULLSCREEN, true ); + } - if( pDeviceSettingsCombo->Windowed ) - bHasWindowedDeviceCombo = true; - else - bHasFullScreenDeviceCombo = true; - } + SetWindowed( g_DeviceSettings.d3d11.sd.Windowed != 0 ); - // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, bHasWindowedDeviceCombo ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_FULLSCREEN, bHasFullScreenDeviceCombo ); + auto pBestDeviceSettingsCombo = DXUTGetD3D11Enumeration()->GetDeviceSettingsCombo( + g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.sd.BufferDesc.Format, + ( g_DeviceSettings.d3d11.sd.Windowed != 0 ) ); - SetWindowed( g_DeviceSettings.d3d9.pp.Windowed && bHasWindowedDeviceCombo ); + if( !pBestDeviceSettingsCombo ) + return DXUT_ERR_MSGBOX( L"GetDeviceSettingsCombo", E_INVALIDARG ); - hr = OnWindowedFullScreenChanged(); - if( FAILED( hr ) ) - return hr; + D3D_FEATURE_LEVEL clampFL; + if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + clampFL = DXUTGetD3D11Enumeration()->GetWARPFeaturevel(); + else if ( g_DeviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) + clampFL = DXUTGetD3D11Enumeration()->GetREFFeaturevel(); + else + clampFL = pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel; - break; - } - case DXUT_D3D11_DEVICE: + if ( g_DeviceSettings.d3d11.DeviceFeatureLevel > clampFL + || clampFL > pBestDeviceSettingsCombo->pDeviceInfo->MaxLevel ) + { + g_DeviceSettings.d3d11.DeviceFeatureLevel = std::min<D3D_FEATURE_LEVEL>( g_DeviceSettings.d3d11.DeviceFeatureLevel, + clampFL ); + + CDXUTComboBox *pFeatureLevelBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); + pFeatureLevelBox->RemoveAllItems(); + for (int fli = 0; fli < TOTAL_FEATURE_LEVELS; fli++) { - g_DeviceSettings.d3d11.DriverType = GetSelectedD3D11DeviceType(); - - // DXUTSETTINGSDLG_WINDOWED, DXUTSETTINGSDLG_FULLSCREEN - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, true ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_FULLSCREEN, true ); - - SetWindowed( g_DeviceSettings.d3d11.sd.Windowed != 0 ); - - hr = OnWindowedFullScreenChanged(); - if( FAILED( hr ) ) - return hr; + if (m_Levels[fli] >= g_DeviceSettings.MinimumFeatureLevel + && m_Levels[fli] <= clampFL) + { + AddD3D11FeatureLevel( m_Levels[fli] ); + } + } + pFeatureLevelBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.DeviceFeatureLevel ) ); - break; - } + hr = OnFeatureLevelChanged(); + if( FAILED( hr ) ) + return hr; } + hr = OnWindowedFullScreenChanged(); + if( FAILED( hr ) ) + return hr; + return S_OK; } @@ -1324,157 +872,43 @@ HRESULT CD3DSettingsDlg::OnWindowedFullScreenChanged() HRESULT hr = S_OK; bool bWindowed = IsWindowed(); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_RESOLUTION_LABEL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_REFRESH_RATE_LABEL, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_ADAPTER_FORMAT, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_RESOLUTION, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_REFRESH_RATE, !bWindowed ); - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_DEVICECLIP, bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_RESOLUTION, !bWindowed ); m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_D3D11_REFRESH_RATE, !bWindowed ); - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - g_DeviceSettings.d3d9.pp.Windowed = bWindowed; - bool bDeviceClip = ( 0x0 != ( g_DeviceSettings.d3d9.pp.Flags & D3DPRESENTFLAG_DEVICECLIP ) ); - - // If windowed, get the appropriate adapter format from Direct3D - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - IDirect3D9* pD3D = DXUTGetD3D9Object(); - if( pD3D == NULL ) - return DXTRACE_ERR( L"DXUTGetD3DObject", E_FAIL ); - - D3DDISPLAYMODE mode; - hr = pD3D->GetAdapterDisplayMode( g_DeviceSettings.d3d9.AdapterOrdinal, &mode ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"GetAdapterDisplayMode", hr ); - - // Default resolution to the fullscreen res that was last used - RECT rc = DXUTGetFullsceenClientRectAtModeChange(); - if( rc.right == 0 || rc.bottom == 0 ) - { - // If nothing last used, then default to the adapter desktop res - g_DeviceSettings.d3d9.pp.BackBufferWidth = mode.Width; - g_DeviceSettings.d3d9.pp.BackBufferHeight = mode.Height; - } - else - { - g_DeviceSettings.d3d9.pp.BackBufferWidth = rc.right; - g_DeviceSettings.d3d9.pp.BackBufferHeight = rc.bottom; - } - - g_DeviceSettings.d3d9.AdapterFormat = mode.Format; - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = mode.RefreshRate; - } - - const D3DFORMAT adapterFormat = g_DeviceSettings.d3d9.AdapterFormat; - const DWORD dwWidth = g_DeviceSettings.d3d9.pp.BackBufferWidth; - const DWORD dwHeight = g_DeviceSettings.d3d9.pp.BackBufferHeight; - const DWORD dwRefreshRate = g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz; - - // DXUTSETTINGSDLG_DEVICECLIP - SetDeviceClip( bDeviceClip ); + g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - // DXUTSETTINGSDLG_ADAPTER_FORMAT - CDXUTComboBox* pAdapterFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - if( pAdapterFormatComboBox == NULL ) - return E_FAIL; - pAdapterFormatComboBox->RemoveAllItems(); + // Get available adapter output + auto pD3DEnum = DXUTGetD3D11Enumeration(); - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; - - if( bWindowed ) - { - AddAdapterFormat( adapterFormat ); - } - else - { - for( int iSettingsCombo = 0; iSettingsCombo < pDeviceInfo->deviceSettingsComboList.GetSize(); - iSettingsCombo++ ) - { - CD3D9EnumDeviceSettingsCombo* pSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( - iSettingsCombo ); - AddAdapterFormat( pSettingsCombo->AdapterFormat ); - } - } - - pAdapterFormatComboBox->SetSelectedByData( ULongToPtr( adapterFormat ) ); - - hr = OnAdapterFormatChanged(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_RESOLUTION - CDXUTComboBox* pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); - - if( bWindowed ) - { - pResolutionComboBox->RemoveAllItems(); - AddResolution( dwWidth, dwHeight ); - } - - pResolutionComboBox->SetSelectedByData( ULongToPtr( MAKELONG( dwWidth, dwHeight ) ) ); - - hr = OnResolutionChanged(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_REFRESH_RATE - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - - if( bWindowed ) - { - pRefreshRateComboBox->RemoveAllItems(); - AddRefreshRate( dwRefreshRate ); - } - - pRefreshRateComboBox->SetSelectedByData( ULongToPtr( dwRefreshRate ) ); - - hr = OnRefreshRateChanged(); - if( FAILED( hr ) ) - return hr; + auto pOutputComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); + pOutputComboBox->RemoveAllItems(); - break; - } - - case DXUT_D3D11_DEVICE: - { - g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - - // Get available adapter output - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - - CDXUTComboBox* pOutputComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); - pOutputComboBox->RemoveAllItems(); + auto pAdapterInfo = pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d11.AdapterOrdinal ); + for( size_t ioutput = 0; ioutput < pAdapterInfo->outputInfoList.size(); ++ioutput ) + { + auto pOutputInfo = pAdapterInfo->outputInfoList[ ioutput ]; + AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, pOutputInfo->Output ); + } - CD3D11EnumAdapterInfo* pAdapterInfo = pD3DEnum->GetAdapterInfo( g_DeviceSettings.d3d11.AdapterOrdinal ); - for( int ioutput = 0; ioutput < pAdapterInfo->outputInfoList.GetSize(); ++ioutput ) - { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( ioutput ); - AddD3D11AdapterOutput( pOutputInfo->Desc.DeviceName, pOutputInfo->Output ); - } + pOutputComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.Output ) ); - pOutputComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.Output ) ); + hr = OnAdapterOutputChanged(); + if( FAILED( hr ) ) + return hr; - hr = OnAdapterOutputChanged(); - if( FAILED( hr ) ) - return hr; + hr = UpdateD3D11Resolutions(); + if (FAILED(hr)) + return hr; - break; - } - } + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; return S_OK; } @@ -1485,235 +919,68 @@ HRESULT CD3DSettingsDlg::OnAdapterOutputChanged() { HRESULT hr; - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D11_DEVICE: - { - bool bWindowed = IsWindowed(); - g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - - // If windowed, get the appropriate adapter format from Direct3D - if( g_DeviceSettings.d3d11.sd.Windowed ) - { - DXGI_MODE_DESC mode; - hr = DXUTGetD3D11AdapterDisplayMode( g_DeviceSettings.d3d11.AdapterOrdinal, - g_DeviceSettings.d3d11.Output, &mode ); - if( FAILED( hr ) ) - return DXTRACE_ERR( L"GetD3D11AdapterDisplayMode", hr ); - - // Default resolution to the fullscreen res that was last used - RECT rc = DXUTGetFullsceenClientRectAtModeChange(); - if( rc.right == 0 || rc.bottom == 0 ) - { - // If nothing last used, then default to the adapter desktop res - g_DeviceSettings.d3d11.sd.BufferDesc.Width = mode.Width; - g_DeviceSettings.d3d11.sd.BufferDesc.Height = mode.Height; - } - else - { - g_DeviceSettings.d3d11.sd.BufferDesc.Width = rc.right; - g_DeviceSettings.d3d11.sd.BufferDesc.Height = rc.bottom; - } - - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = mode.RefreshRate; - } - - const DXGI_RATIONAL RefreshRate = g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate; - - CD3D11EnumAdapterInfo* pAdapterInfo = GetCurrentD3D11AdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - // DXUTSETTINGSDLG_D3D11_RESOLUTION - hr = UpdateD3D11Resolutions(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT - CDXUTComboBox* pBackBufferFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT - ); - pBackBufferFormatComboBox->RemoveAllItems(); - - for( int idc = 0; idc < pAdapterInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = pAdapterInfo->deviceSettingsComboList.GetAt( idc ); - if( ( pDeviceCombo->Windowed == TRUE ) == bWindowed ) - { - AddD3D11BackBufferFormat( pDeviceCombo->BackBufferFormat ); - } - } - - pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.BufferDesc.Format ) ); - - hr = OnBackBufferFormatChanged(); - if( FAILED( hr ) ) - return hr; + bool bWindowed = IsWindowed(); + g_DeviceSettings.d3d11.sd.Windowed = bWindowed; - // DXUTSETTINGSDLG_D3D11_REFRESH_RATE - if( bWindowed ) - { - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); - for( UINT i = 0; i < pRefreshRateComboBox->GetNumItems(); ++i ) - { - DXGI_RATIONAL* pRefreshRate = reinterpret_cast<DXGI_RATIONAL*>( - pRefreshRateComboBox->GetItemData( i ) ); - delete pRefreshRate; - } - pRefreshRateComboBox->RemoveAllItems(); - AddD3D11RefreshRate( RefreshRate ); - } + // If windowed, get the appropriate adapter format from Direct3D + if( g_DeviceSettings.d3d11.sd.Windowed ) + { + DXGI_MODE_DESC mode; + hr = DXUTGetD3D11AdapterDisplayMode( g_DeviceSettings.d3d11.AdapterOrdinal, + g_DeviceSettings.d3d11.Output, &mode ); + if( FAILED( hr ) ) + return DXTRACE_ERR( L"GetD3D11AdapterDisplayMode", hr ); - SetSelectedD3D11RefreshRate( RefreshRate ); - break; + // Default resolution to the fullscreen res that was last used + RECT rc = DXUTGetFullsceenClientRectAtModeChange(); + if( rc.right == 0 || rc.bottom == 0 ) + { + // If nothing last used, then default to the adapter desktop res + g_DeviceSettings.d3d11.sd.BufferDesc.Width = mode.Width; + g_DeviceSettings.d3d11.sd.BufferDesc.Height = mode.Height; } - }; - - hr = OnRefreshRateChanged(); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnAdapterFormatChanged() -{ - HRESULT hr = S_OK; - - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: + else { - // DXUTSETTINGSDLG_ADAPTER_FORMAT - D3DFORMAT adapterFormat = GetSelectedAdapterFormat(); - g_DeviceSettings.d3d9.AdapterFormat = adapterFormat; - - // DXUTSETTINGSDLG_RESOLUTION - CDXUTComboBox* pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); - pResolutionComboBox->RemoveAllItems(); - - CD3D9EnumAdapterInfo* pAdapterInfo = GetCurrentAdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; - - bool bShowAll = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL )->GetChecked(); - - // Get the desktop aspect ratio - D3DDISPLAYMODE dmDesktop; - DXUTGetDesktopResolution( g_DeviceSettings.d3d9.AdapterOrdinal, &dmDesktop.Width, &dmDesktop.Height ); - float fDesktopAspectRatio = dmDesktop.Width / ( float )dmDesktop.Height; - - for( int idm = 0; idm < pAdapterInfo->displayModeList.GetSize(); idm++ ) - { - D3DDISPLAYMODE DisplayMode = pAdapterInfo->displayModeList.GetAt( idm ); - float fAspect = ( float )DisplayMode.Width / ( float )DisplayMode.Height; - - if( DisplayMode.Format == g_DeviceSettings.d3d9.AdapterFormat ) - { - // If "Show All" is not checked, then hide all resolutions - // that don't match the aspect ratio of the desktop resolution - if( bShowAll || ( !bShowAll && fabsf( fDesktopAspectRatio - fAspect ) < 0.05f ) ) - { - AddResolution( DisplayMode.Width, DisplayMode.Height ); - } - } - } - - const DWORD dwCurResolution = MAKELONG( g_DeviceSettings.d3d9.pp.BackBufferWidth, - g_DeviceSettings.d3d9.pp.BackBufferHeight ); - - pResolutionComboBox->SetSelectedByData( ULongToPtr( dwCurResolution ) ); - - hr = OnResolutionChanged(); - if( FAILED( hr ) ) - return hr; - - // DXUTSETTINGSDLG_BACK_BUFFER_FORMAT - CDXUTComboBox* pBackBufferFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - pBackBufferFormatComboBox->RemoveAllItems(); - - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; - - const BOOL bWindowed = IsWindowed(); - bool bHasWindowedBackBuffer = false; - - for( int idc = 0; idc < pDeviceInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceCombo = pDeviceInfo->deviceSettingsComboList.GetAt( idc ); - if( pDeviceCombo->Windowed == bWindowed && - pDeviceCombo->AdapterFormat == g_DeviceSettings.d3d9.AdapterFormat ) - { - AddBackBufferFormat( pDeviceCombo->BackBufferFormat ); - bHasWindowedBackBuffer = true; - } - } - - pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.pp.BackBufferFormat ) ); - - hr = OnBackBufferFormatChanged(); - if( FAILED( hr ) ) - return hr; - - if( !bHasWindowedBackBuffer ) - { - m_Dialog.SetControlEnabled( DXUTSETTINGSDLG_WINDOWED, false ); - - if( g_DeviceSettings.d3d9.pp.Windowed ) - { - SetWindowed( false ); - - hr = OnWindowedFullScreenChanged(); - if( FAILED( hr ) ) - return hr; - } - } - - break; + g_DeviceSettings.d3d11.sd.BufferDesc.Width = rc.right; + g_DeviceSettings.d3d11.sd.BufferDesc.Height = rc.bottom; } - } - - return S_OK; -} - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnResolutionChanged() -{ - HRESULT hr = S_OK; + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Numerator = + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate.Denominator = 0; + } - CD3D9EnumAdapterInfo* pAdapterInfo = GetCurrentAdapterInfo(); - if( pAdapterInfo == NULL ) + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if( !pAdapterInfo ) return E_FAIL; - // Set resolution - DWORD dwWidth, dwHeight; - GetSelectedResolution( &dwWidth, &dwHeight ); - g_DeviceSettings.d3d9.pp.BackBufferWidth = dwWidth; - g_DeviceSettings.d3d9.pp.BackBufferHeight = dwHeight; + // DXUTSETTINGSDLG_D3D11_RESOLUTION + hr = UpdateD3D11Resolutions(); + if( FAILED( hr ) ) + return hr; - DWORD dwRefreshRate = g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz; + // DXUTSETTINGSDLG_D3D11_REFRESH_RATE + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; - // Update the refresh rate list - CDXUTComboBox* pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - pRefreshRateComboBox->RemoveAllItems(); + // DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT + auto pBackBufferFormatComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); + pBackBufferFormatComboBox->RemoveAllItems(); - D3DFORMAT adapterFormat = g_DeviceSettings.d3d9.AdapterFormat; - for( int idm = 0; idm < pAdapterInfo->displayModeList.GetSize(); idm++ ) + for( size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++ ) { - D3DDISPLAYMODE displayMode = pAdapterInfo->displayModeList.GetAt( idm ); - - if( displayMode.Format == adapterFormat && - displayMode.Width == dwWidth && - displayMode.Height == dwHeight ) + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[ idc ]; + if( ( pDeviceCombo->Windowed == TRUE ) == bWindowed ) { - AddRefreshRate( displayMode.RefreshRate ); + AddD3D11BackBufferFormat( pDeviceCombo->BackBufferFormat ); } } - pRefreshRateComboBox->SetSelectedByData( ULongToPtr( dwRefreshRate ) ); + pBackBufferFormatComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.BufferDesc.Format ) ); + + hr = OnBackBufferFormatChanged(); + if( FAILED( hr ) ) + return hr; hr = OnRefreshRateChanged(); if( FAILED( hr ) ) @@ -1723,21 +990,11 @@ HRESULT CD3DSettingsDlg::OnResolutionChanged() } - //------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::OnRefreshRateChanged() { // Set refresh rate - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - g_DeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = GetSelectedRefreshRate(); - break; - - case DXUT_D3D11_DEVICE: - g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = GetSelectedD3D11RefreshRate(); - break; - } + g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate = GetSelectedD3D11RefreshRate(); return S_OK; } @@ -1748,153 +1005,47 @@ HRESULT CD3DSettingsDlg::OnBackBufferFormatChanged() { HRESULT hr = S_OK; - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - { - g_DeviceSettings.d3d9.pp.BackBufferFormat = GetSelectedBackBufferFormat(); - - D3DFORMAT adapterFormat = g_DeviceSettings.d3d9.AdapterFormat; - D3DFORMAT backBufferFormat = g_DeviceSettings.d3d9.pp.BackBufferFormat; + g_DeviceSettings.d3d11.sd.BufferDesc.Format = GetSelectedD3D11BackBufferFormat(); - CD3D9EnumDeviceInfo* pDeviceInfo = GetCurrentDeviceInfo(); - if( pDeviceInfo == NULL ) - return E_FAIL; + DXGI_FORMAT backBufferFormat = g_DeviceSettings.d3d11.sd.BufferDesc.Format; - bool bAllowSoftwareVP, bAllowHardwareVP, bAllowPureHardwareVP, bAllowMixedVP; - DXUTGetD3D9Enumeration()->GetPossibleVertexProcessingList( &bAllowSoftwareVP, &bAllowHardwareVP, - &bAllowPureHardwareVP, &bAllowMixedVP ); + auto pAdapterInfo = GetCurrentD3D11AdapterInfo(); + if( !pAdapterInfo ) + return E_FAIL; - for( int idc = 0; idc < pDeviceInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceCombo = pDeviceInfo->deviceSettingsComboList.GetAt( idc ); + for( size_t idc = 0; idc < pAdapterInfo->deviceSettingsComboList.size(); idc++ ) + { + auto pDeviceCombo = pAdapterInfo->deviceSettingsComboList[ idc ]; - if( pDeviceCombo->Windowed == ( g_DeviceSettings.d3d9.pp.Windowed == TRUE ) && - pDeviceCombo->AdapterFormat == adapterFormat && - pDeviceCombo->BackBufferFormat == backBufferFormat ) - { - CDXUTComboBox* pDepthStencilComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - pDepthStencilComboBox->RemoveAllItems(); - pDepthStencilComboBox->SetEnabled( ( g_DeviceSettings.d3d9.pp.EnableAutoDepthStencil == TRUE ) ); - - if( g_DeviceSettings.d3d9.pp.EnableAutoDepthStencil ) - { - for( int ifmt = 0; ifmt < pDeviceCombo->depthStencilFormatList.GetSize(); ifmt++ ) - { - D3DFORMAT fmt = pDeviceCombo->depthStencilFormatList.GetAt( ifmt ); - - AddDepthStencilBufferFormat( fmt ); - } - - pDepthStencilComboBox->SetSelectedByData( ULongToPtr( - g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat ) ); - } - else - { - if( !pDepthStencilComboBox->ContainsItem( L"(not used)" ) ) - pDepthStencilComboBox->AddItem( L"(not used)", NULL ); - } - - hr = OnDepthStencilBufferFormatChanged(); - if( FAILED( hr ) ) - return hr; - - CDXUTComboBox* pVertexProcessingComboBox = - m_Dialog.GetComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING ); - pVertexProcessingComboBox->RemoveAllItems(); - - // Add valid vertex processing types - if( bAllowSoftwareVP ) - AddVertexProcessingType( D3DCREATE_SOFTWARE_VERTEXPROCESSING ); - - if( bAllowHardwareVP && pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) - AddVertexProcessingType( D3DCREATE_HARDWARE_VERTEXPROCESSING ); - - if( bAllowPureHardwareVP && pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_PUREDEVICE ) - AddVertexProcessingType( D3DCREATE_PUREDEVICE ); - - if( bAllowMixedVP && pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) - AddVertexProcessingType( D3DCREATE_MIXED_VERTEXPROCESSING ); - - if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_PUREDEVICE ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( D3DCREATE_PUREDEVICE ) ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( - D3DCREATE_SOFTWARE_VERTEXPROCESSING ) ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( - D3DCREATE_HARDWARE_VERTEXPROCESSING ) ); - else if( g_DeviceSettings.d3d9.BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING ) - pVertexProcessingComboBox->SetSelectedByData( ULongToPtr( D3DCREATE_MIXED_VERTEXPROCESSING ) ); - - hr = OnVertexProcessingChanged(); - if( FAILED( hr ) ) - return hr; - - CDXUTComboBox* pPresentIntervalComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL ); - pPresentIntervalComboBox->RemoveAllItems(); - pPresentIntervalComboBox->AddItem( L"On", ULongToPtr( D3DPRESENT_INTERVAL_DEFAULT ) ); - pPresentIntervalComboBox->AddItem( L"Off", ULongToPtr( D3DPRESENT_INTERVAL_IMMEDIATE ) ); - - pPresentIntervalComboBox->SetSelectedByData( ULongToPtr( - g_DeviceSettings.d3d9.pp.PresentationInterval ) ); - - hr = OnPresentIntervalChanged(); - if( FAILED( hr ) ) - return hr; - } - } + if( pDeviceCombo->Windowed == ( g_DeviceSettings.d3d11.sd.Windowed == TRUE ) && + pDeviceCombo->BackBufferFormat == backBufferFormat && + pDeviceCombo->DeviceType == g_DeviceSettings.d3d11.DriverType ) + { + auto pMultisampleCountCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); + pMultisampleCountCombo->RemoveAllItems(); - break; - } + for( auto it = pDeviceCombo->multiSampleCountList.cbegin(); it != pDeviceCombo->multiSampleCountList.cend(); ++it ) + AddD3D11MultisampleCount( *it ); + pMultisampleCountCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.SampleDesc.Count ) ); - case DXUT_D3D11_DEVICE: - { - g_DeviceSettings.d3d11.sd.BufferDesc.Format = GetSelectedD3D11BackBufferFormat(); + hr = OnMultisampleTypeChanged(); + if( FAILED( hr ) ) + return hr; - DXGI_FORMAT backBufferFormat = g_DeviceSettings.d3d11.sd.BufferDesc.Format; + auto pPresentIntervalComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); + pPresentIntervalComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.SyncInterval ) ); - CD3D11EnumAdapterInfo* pAdapterInfo = GetCurrentD3D11AdapterInfo(); - if( pAdapterInfo == NULL ) - return E_FAIL; + hr = OnPresentIntervalChanged(); + if( FAILED( hr ) ) + return hr; - for( int idc = 0; idc < pAdapterInfo->deviceSettingsComboList.GetSize(); idc++ ) - { - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = pAdapterInfo->deviceSettingsComboList.GetAt( idc ); + hr = UpdateD3D11Resolutions(); + if( FAILED( hr ) ) + return hr; - if( pDeviceCombo->Windowed == ( g_DeviceSettings.d3d11.sd.Windowed == TRUE ) && - pDeviceCombo->BackBufferFormat == backBufferFormat && - pDeviceCombo->DeviceType == g_DeviceSettings.d3d11.DriverType ) - { - CDXUTComboBox* pMultisampleCountCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT - ); - pMultisampleCountCombo->RemoveAllItems(); - for( int i = 0; i < pDeviceCombo->multiSampleCountList.GetSize(); ++i ) - AddD3D11MultisampleCount( pDeviceCombo->multiSampleCountList.GetAt( i ) ); - pMultisampleCountCombo->SetSelectedByData( ULongToPtr( - g_DeviceSettings.d3d11.sd.SampleDesc.Count ) ); - - hr = OnMultisampleTypeChanged(); - if( FAILED( hr ) ) - return hr; - - CDXUTComboBox* pPresentIntervalComboBox = - m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); - pPresentIntervalComboBox->RemoveAllItems(); - pPresentIntervalComboBox->AddItem( L"On", ULongToPtr( 1 ) ); - pPresentIntervalComboBox->AddItem( L"Off", ULongToPtr( 0 ) ); - - pPresentIntervalComboBox->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.SyncInterval ) ); - - hr = OnPresentIntervalChanged(); - if( FAILED( hr ) ) - return hr; - - hr = UpdateD3D11Resolutions(); - if( FAILED( hr ) ) - return hr; - } - } + hr = UpdateD3D11RefreshRates(); + if ( FAILED(hr) ) + return hr; break; } @@ -1905,136 +1056,42 @@ HRESULT CD3DSettingsDlg::OnBackBufferFormatChanged() //------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnDepthStencilBufferFormatChanged() +HRESULT CD3DSettingsDlg::OnMultisampleTypeChanged() { HRESULT hr = S_OK; - D3DFORMAT depthStencilBufferFormat = GetSelectedDepthStencilBufferFormat(); - - if( g_DeviceSettings.d3d9.pp.EnableAutoDepthStencil ) - g_DeviceSettings.d3d9.pp.AutoDepthStencilFormat = depthStencilBufferFormat; + UINT multisampleCount = GetSelectedD3D11MultisampleCount(); + g_DeviceSettings.d3d11.sd.SampleDesc.Count = multisampleCount; - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = GetCurrentDeviceSettingsCombo(); - if( pDeviceSettingsCombo == NULL ) + auto pDeviceSettingsCombo = GetCurrentD3D11DeviceSettingsCombo(); + if( !pDeviceSettingsCombo ) return E_FAIL; - CDXUTComboBox* pMultisampleTypeCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - pMultisampleTypeCombo->RemoveAllItems(); - - for( int ims = 0; ims < pDeviceSettingsCombo->multiSampleTypeList.GetSize(); ims++ ) + UINT MaxQuality = 0; + for( size_t iCount = 0; iCount < pDeviceSettingsCombo->multiSampleCountList.size(); iCount++ ) { - D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt( ims ); - - bool bConflictFound = false; - for( int iConf = 0; iConf < pDeviceSettingsCombo->DSMSConflictList.GetSize(); iConf++ ) + UINT Count = pDeviceSettingsCombo->multiSampleCountList[ iCount ]; + if( Count == multisampleCount ) { - CD3D9EnumDSMSConflict DSMSConf = pDeviceSettingsCombo->DSMSConflictList.GetAt( iConf ); - if( DSMSConf.DSFormat == depthStencilBufferFormat && - DSMSConf.MSType == msType ) - { - bConflictFound = true; - break; - } + MaxQuality = pDeviceSettingsCombo->multiSampleQualityList[ iCount ]; + break; } - - if( !bConflictFound ) - AddMultisampleType( msType ); } - CDXUTComboBox* pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.pp.MultiSampleType ) ); - - hr = OnMultisampleTypeChanged(); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnMultisampleTypeChanged() -{ - HRESULT hr = S_OK; + // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY + auto pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); + pMultisampleQualityCombo->RemoveAllItems(); - switch( g_DeviceSettings.ver ) + for( UINT iQuality = 0; iQuality < MaxQuality; iQuality++ ) { - case DXUT_D3D9_DEVICE: - { - D3DMULTISAMPLE_TYPE multisampleType = GetSelectedMultisampleType(); - g_DeviceSettings.d3d9.pp.MultiSampleType = multisampleType; - - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = GetCurrentDeviceSettingsCombo(); - if( pDeviceSettingsCombo == NULL ) - return E_FAIL; - - DWORD dwMaxQuality = 0; - for( int iType = 0; iType < pDeviceSettingsCombo->multiSampleTypeList.GetSize(); iType++ ) - { - D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt( iType ); - if( msType == multisampleType ) - { - dwMaxQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt( iType ); - break; - } - } - - // DXUTSETTINGSDLG_MULTISAMPLE_QUALITY - CDXUTComboBox* pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY ); - pMultisampleQualityCombo->RemoveAllItems(); - - for( UINT iQuality = 0; iQuality < dwMaxQuality; iQuality++ ) - { - AddMultisampleQuality( iQuality ); - } - - pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d9.pp.MultiSampleQuality ) ); - - hr = OnMultisampleQualityChanged(); - if( FAILED( hr ) ) - return hr; - - break; - } - case DXUT_D3D11_DEVICE: - { - UINT multisampleCount = GetSelectedD3D11MultisampleCount(); - g_DeviceSettings.d3d11.sd.SampleDesc.Count = multisampleCount; - - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = GetCurrentD3D11DeviceSettingsCombo(); - if( pDeviceSettingsCombo == NULL ) - return E_FAIL; - - UINT MaxQuality = 0; - for( int iCount = 0; iCount < pDeviceSettingsCombo->multiSampleCountList.GetSize(); iCount++ ) - { - UINT Count = pDeviceSettingsCombo->multiSampleCountList.GetAt( iCount ); - if( Count == multisampleCount ) - { - MaxQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt( iCount ); - break; - } - } - - // DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY - CDXUTComboBox* pMultisampleQualityCombo = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY - ); - pMultisampleQualityCombo->RemoveAllItems(); - - for( UINT iQuality = 0; iQuality < MaxQuality; iQuality++ ) - { - AddD3D11MultisampleQuality( iQuality ); - } - - pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ) ); + AddD3D11MultisampleQuality( iQuality ); + } - hr = OnMultisampleQualityChanged(); - if( FAILED( hr ) ) - return hr; + pMultisampleQualityCombo->SetSelectedByData( ULongToPtr( g_DeviceSettings.d3d11.sd.SampleDesc.Quality ) ); - break; - } - } + hr = OnMultisampleQualityChanged(); + if( FAILED( hr ) ) + return hr; return S_OK; } @@ -2043,39 +1100,7 @@ HRESULT CD3DSettingsDlg::OnMultisampleTypeChanged() //------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::OnMultisampleQualityChanged() { - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - g_DeviceSettings.d3d9.pp.MultiSampleQuality = GetSelectedMultisampleQuality(); - break; - - case DXUT_D3D11_DEVICE: g_DeviceSettings.d3d11.sd.SampleDesc.Quality = GetSelectedD3D11MultisampleQuality(); - break; - } - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnVertexProcessingChanged() -{ - DWORD dwBehavior = g_DeviceSettings.d3d9.BehaviorFlags; - - // Clear vertex processing flags - dwBehavior &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; - dwBehavior &= ~D3DCREATE_SOFTWARE_VERTEXPROCESSING; - dwBehavior &= ~D3DCREATE_MIXED_VERTEXPROCESSING; - dwBehavior &= ~D3DCREATE_PUREDEVICE; - - // Determine new flags - DWORD dwNewFlags = GetSelectedVertexProcessingType(); - if( dwNewFlags & D3DCREATE_PUREDEVICE ) - dwNewFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; - - // Make changes - g_DeviceSettings.d3d9.BehaviorFlags = dwBehavior | dwNewFlags; return S_OK; } @@ -2084,16 +1109,7 @@ HRESULT CD3DSettingsDlg::OnVertexProcessingChanged() //------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::OnPresentIntervalChanged() { - switch( g_DeviceSettings.ver ) - { - case DXUT_D3D9_DEVICE: - g_DeviceSettings.d3d9.pp.PresentationInterval = GetSelectedPresentInterval(); - break; - - case DXUT_D3D11_DEVICE: g_DeviceSettings.d3d11.SyncInterval = GetSelectedD3D11PresentInterval(); - break; - } return S_OK; } @@ -2112,41 +1128,11 @@ HRESULT CD3DSettingsDlg::OnDebugDeviceChanged() return S_OK; } -//------------------------------------------------------------------------------------- -HRESULT CD3DSettingsDlg::OnDeviceClipChanged() -{ - if( IsDeviceClip() ) - g_DeviceSettings.d3d9.pp.Flags |= D3DPRESENTFLAG_DEVICECLIP; - else - g_DeviceSettings.d3d9.pp.Flags &= ~D3DPRESENTFLAG_DEVICECLIP; - - return S_OK; -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddAPIVersion( DXUTDeviceVersion version ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_API_VERSION ); - - if( !pComboBox->ContainsItem( DXUTAPIVersionToString( version ) ) ) - pComboBox->AddItem( DXUTAPIVersionToString( version ), ULongToPtr( version ) ); -} - //------------------------------------------------------------------------------------- -DXUTDeviceVersion CD3DSettingsDlg::GetSelectedAPIVersion() +void CD3DSettingsDlg::AddAdapter( _In_z_ const WCHAR* strDescription, _In_ UINT iAdapter ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_API_VERSION ); - - return ( DXUTDeviceVersion )PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddAdapter( const WCHAR* strDescription, UINT iAdapter ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); if( !pComboBox->ContainsItem( strDescription ) ) pComboBox->AddItem( strDescription, ULongToPtr( iAdapter ) ); @@ -2154,75 +1140,46 @@ void CD3DSettingsDlg::AddAdapter( const WCHAR* strDescription, UINT iAdapter ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedAdapter() +UINT CD3DSettingsDlg::GetSelectedAdapter() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER ); return PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddDeviceType( D3DDEVTYPE devType ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - - if( !pComboBox->ContainsItem( DXUTD3DDeviceTypeToString( devType ) ) ) - pComboBox->AddItem( DXUTD3DDeviceTypeToString( devType ), ULongToPtr( devType ) ); -} - - -//------------------------------------------------------------------------------------- -D3DDEVTYPE CD3DSettingsDlg::GetSelectedDeviceType() +void CD3DSettingsDlg::SetWindowed( _In_ bool bWindowed ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - - return ( D3DDEVTYPE )PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::SetWindowed( bool bWindowed ) -{ - CDXUTRadioButton* pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); + auto pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); pRadioButton->SetChecked( bWindowed ); pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_FULLSCREEN ); pRadioButton->SetChecked( !bWindowed ); -} + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL, !bWindowed); -//------------------------------------------------------------------------------------- -bool CD3DSettingsDlg::IsWindowed() -{ - CDXUTRadioButton* pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); - return pRadioButton->GetChecked(); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_RESOLUTION, !bWindowed); + m_Dialog.SetControlEnabled(DXUTSETTINGSDLG_D3D11_REFRESH_RATE, !bWindowed); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddAdapterFormat( D3DFORMAT format ) +bool CD3DSettingsDlg::IsWindowed() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - - if( !pComboBox->ContainsItem( DXUTD3DFormatToString( format, TRUE ) ) ) - pComboBox->AddItem( DXUTD3DFormatToString( format, TRUE ), ULongToPtr( format ) ); -} - - -//------------------------------------------------------------------------------------- -D3DFORMAT CD3DSettingsDlg::GetSelectedAdapterFormat() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_ADAPTER_FORMAT ); - - return ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); + auto pRadioButton = m_Dialog.GetRadioButton( DXUTSETTINGSDLG_WINDOWED ); + return pRadioButton->GetChecked(); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11AdapterOutput( const WCHAR* strName, UINT Output ) +void CD3DSettingsDlg::AddD3D11AdapterOutput( _In_z_ const WCHAR* strName, _In_ UINT Output ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); if( !pComboBox->ContainsItem( strName ) ) pComboBox->AddItem( strName, ULongToPtr( Output ) ); @@ -2230,23 +1187,24 @@ void CD3DSettingsDlg::AddD3D11AdapterOutput( const WCHAR* strName, UINT Output ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedD3D11AdapterOutput() +UINT CD3DSettingsDlg::GetSelectedD3D11AdapterOutput() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT ); return PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddResolution( DWORD dwWidth, DWORD dwHeight ) +_Use_decl_annotations_ +void CD3DSettingsDlg::AddD3D11Resolution( DWORD dwWidth, DWORD dwHeight ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); DWORD dwResolutionData; WCHAR strResolution[50]; dwResolutionData = MAKELONG( dwWidth, dwHeight ); - swprintf_s( strResolution, 50, L"%d by %d", dwWidth, dwHeight ); + swprintf_s( strResolution, 50, L"%u by %u", dwWidth, dwHeight ); if( !pComboBox->ContainsItem( strResolution ) ) pComboBox->AddItem( strResolution, ULongToPtr( dwResolutionData ) ); @@ -2254,9 +1212,10 @@ void CD3DSettingsDlg::AddResolution( DWORD dwWidth, DWORD dwHeight ) //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::GetSelectedResolution( DWORD* pdwWidth, DWORD* pdwHeight ) +_Use_decl_annotations_ +void CD3DSettingsDlg::GetSelectedD3D11Resolution( DWORD* pdwWidth, DWORD* pdwHeight ) const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_RESOLUTION ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); DWORD dwResolution = PtrToUlong( pComboBox->GetSelectedData() ); @@ -2266,33 +1225,9 @@ void CD3DSettingsDlg::GetSelectedResolution( DWORD* pdwWidth, DWORD* pdwHeight ) //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11Resolution( DWORD dwWidth, DWORD dwHeight ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); - - DWORD dwResolutionData; - WCHAR strResolution[50]; - dwResolutionData = MAKELONG( dwWidth, dwHeight ); - swprintf_s( strResolution, 50, L"%d by %d", dwWidth, dwHeight ); - - if( !pComboBox->ContainsItem( strResolution ) ) - pComboBox->AddItem( strResolution, ULongToPtr( dwResolutionData ) ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::GetSelectedD3D11Resolution( DWORD* pdwWidth, DWORD* pdwHeight ) +void CD3DSettingsDlg::AddD3D11FeatureLevel( _In_ D3D_FEATURE_LEVEL fl) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); - - DWORD dwResolution = PtrToUlong( pComboBox->GetSelectedData() ); - - *pdwWidth = LOWORD( dwResolution ); - *pdwHeight = HIWORD( dwResolution ); -} - -void CD3DSettingsDlg::AddD3D11FeatureLevel(D3D_FEATURE_LEVEL fl) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); switch( fl ) { case D3D_FEATURE_LEVEL_9_1: @@ -2331,56 +1266,53 @@ void CD3DSettingsDlg::AddD3D11FeatureLevel(D3D_FEATURE_LEVEL fl) { pComboBox->AddItem( L"D3D_FEATURE_LEVEL_11_0", ULongToPtr( D3D_FEATURE_LEVEL_11_0 ) ); } break; + case D3D_FEATURE_LEVEL_11_1: + { + if( !pComboBox->ContainsItem( L"D3D_FEATURE_LEVEL_11_1" ) ) + pComboBox->AddItem( L"D3D_FEATURE_LEVEL_11_1", ULongToPtr( D3D_FEATURE_LEVEL_11_1 ) ); + } + break; +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + case D3D_FEATURE_LEVEL_12_0: + { + if (!pComboBox->ContainsItem(L"D3D_FEATURE_LEVEL_12_0")) + pComboBox->AddItem(L"D3D_FEATURE_LEVEL_12_0", ULongToPtr(D3D_FEATURE_LEVEL_12_0)); + } + break; + case D3D_FEATURE_LEVEL_12_1: + { + if (!pComboBox->ContainsItem(L"D3D_FEATURE_LEVEL_12_1")) + pComboBox->AddItem(L"D3D_FEATURE_LEVEL_12_1", ULongToPtr(D3D_FEATURE_LEVEL_12_1)); + } + break; +#endif } } -D3D_FEATURE_LEVEL CD3DSettingsDlg::GetSelectedFeatureLevel() { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); - - return (D3D_FEATURE_LEVEL)PtrToUlong( pComboBox->GetSelectedData() ); -} -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddRefreshRate( DWORD dwRate ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); - - WCHAR strRefreshRate[50]; - - if( dwRate == 0 ) - wcscpy_s( strRefreshRate, 50, L"Default Rate" ); - else - swprintf_s( strRefreshRate, 50, L"%d Hz", dwRate ); - - if( !pComboBox->ContainsItem( strRefreshRate ) ) - pComboBox->AddItem( strRefreshRate, ULongToPtr( dwRate ) ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedRefreshRate() +D3D_FEATURE_LEVEL CD3DSettingsDlg::GetSelectedFeatureLevel() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_REFRESH_RATE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL ); - return PtrToUlong( pComboBox->GetSelectedData() ); + return (D3D_FEATURE_LEVEL)PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) +void CD3DSettingsDlg::AddD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); WCHAR strRefreshRate[50]; if( RefreshRate.Numerator == 0 && RefreshRate.Denominator == 0 ) wcscpy_s( strRefreshRate, 50, L"Default Rate" ); else - swprintf_s( strRefreshRate, 50, L"%d Hz", RefreshRate.Numerator / RefreshRate.Denominator ); + swprintf_s( strRefreshRate, 50, L"%u Hz", RefreshRate.Numerator / RefreshRate.Denominator ); if( !pComboBox->ContainsItem( strRefreshRate ) ) { - DXGI_RATIONAL* pNewRate = new DXGI_RATIONAL; + auto pNewRate = new (std::nothrow) DXGI_RATIONAL; if( pNewRate ) { *pNewRate = RefreshRate; @@ -2391,42 +1323,23 @@ void CD3DSettingsDlg::AddD3D11RefreshRate( DXGI_RATIONAL RefreshRate ) //------------------------------------------------------------------------------------- -DXGI_RATIONAL CD3DSettingsDlg::GetSelectedD3D11RefreshRate() +DXGI_RATIONAL CD3DSettingsDlg::GetSelectedD3D11RefreshRate() const { - DXGI_RATIONAL dxgiR; - dxgiR.Numerator = 0; - dxgiR.Denominator = 1; - - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); - + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); return *reinterpret_cast<DXGI_RATIONAL*>( pComboBox->GetSelectedData() ); - } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddBackBufferFormat( D3DFORMAT format ) +void CD3DSettingsDlg::AddD3D11BackBufferFormat( _In_ DXGI_FORMAT format ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - - if( !pComboBox->ContainsItem( DXUTD3DFormatToString( format, TRUE ) ) ) - pComboBox->AddItem( DXUTD3DFormatToString( format, TRUE ), ULongToPtr( format ) ); -} - - -//------------------------------------------------------------------------------------- -D3DFORMAT CD3DSettingsDlg::GetSelectedBackBufferFormat() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_BACK_BUFFER_FORMAT ); - - return ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); -} - + if ( g_DeviceSettings.d3d11.DeviceFeatureLevel < D3D_FEATURE_LEVEL_10_0 ) + { + if ( (format == DXGI_FORMAT_R16G16B16A16_FLOAT) || (format == DXGI_FORMAT_R10G10B10A2_UNORM) ) + return; + } -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11BackBufferFormat( DXGI_FORMAT format ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); if( !pComboBox->ContainsItem( DXUTDXGIFormatToString( format, TRUE ) ) ) pComboBox->AddItem( DXUTDXGIFormatToString( format, TRUE ), ULongToPtr( format ) ); @@ -2434,78 +1347,18 @@ void CD3DSettingsDlg::AddD3D11BackBufferFormat( DXGI_FORMAT format ) //------------------------------------------------------------------------------------- -DXGI_FORMAT CD3DSettingsDlg::GetSelectedD3D11BackBufferFormat() +DXGI_FORMAT CD3DSettingsDlg::GetSelectedD3D11BackBufferFormat() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT ); return ( DXGI_FORMAT )PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddDepthStencilBufferFormat( D3DFORMAT format ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - - if( !pComboBox->ContainsItem( DXUTD3DFormatToString( format, TRUE ) ) ) - pComboBox->AddItem( DXUTD3DFormatToString( format, TRUE ), ULongToPtr( format ) ); -} - - -//------------------------------------------------------------------------------------- -D3DFORMAT CD3DSettingsDlg::GetSelectedDepthStencilBufferFormat() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEPTH_STENCIL ); - - return ( D3DFORMAT )PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddMultisampleType( D3DMULTISAMPLE_TYPE type ) +void CD3DSettingsDlg::AddD3D11MultisampleCount( _In_ UINT Count ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - - if( !pComboBox->ContainsItem( DXUTMultisampleTypeToString( type ) ) ) - pComboBox->AddItem( DXUTMultisampleTypeToString( type ), ULongToPtr( type ) ); -} - - -//------------------------------------------------------------------------------------- -D3DMULTISAMPLE_TYPE CD3DSettingsDlg::GetSelectedMultisampleType() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_TYPE ); - - return ( D3DMULTISAMPLE_TYPE )PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddMultisampleQuality( DWORD dwQuality ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY ); - - WCHAR strQuality[50]; - swprintf_s( strQuality, 50, L"%d", dwQuality ); - - if( !pComboBox->ContainsItem( strQuality ) ) - pComboBox->AddItem( strQuality, ULongToPtr( dwQuality ) ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedMultisampleQuality() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_MULTISAMPLE_QUALITY ); - - return PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11MultisampleCount( UINT Count ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); WCHAR str[50]; swprintf_s( str, 50, L"%u", Count ); @@ -2516,21 +1369,21 @@ void CD3DSettingsDlg::AddD3D11MultisampleCount( UINT Count ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleCount() +UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleCount() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT ); return ( UINT )PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11MultisampleQuality( UINT Quality ) +void CD3DSettingsDlg::AddD3D11MultisampleQuality( _In_ UINT Quality ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); WCHAR strQuality[50]; - swprintf_s( strQuality, 50, L"%d", Quality ); + swprintf_s( strQuality, 50, L"%u", Quality ); if( !pComboBox->ContainsItem( strQuality ) ) pComboBox->AddItem( strQuality, ULongToPtr( Quality ) ); @@ -2538,129 +1391,140 @@ void CD3DSettingsDlg::AddD3D11MultisampleQuality( UINT Quality ) //------------------------------------------------------------------------------------- -UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleQuality() +UINT CD3DSettingsDlg::GetSelectedD3D11MultisampleQuality() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY ); return ( UINT )PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddVertexProcessingType( DWORD dwType ) -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING ); - - if( !pComboBox->ContainsItem( DXUTVertexProcessingTypeToString( dwType ) ) ) - pComboBox->AddItem( DXUTVertexProcessingTypeToString( dwType ), ULongToPtr( dwType ) ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedVertexProcessingType() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_VERTEX_PROCESSING ); - - return PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedPresentInterval() -{ - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL ); - - return PtrToUlong( pComboBox->GetSelectedData() ); -} - - -//------------------------------------------------------------------------------------- -DWORD CD3DSettingsDlg::GetSelectedD3D11PresentInterval() +DWORD CD3DSettingsDlg::GetSelectedD3D11PresentInterval() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL ); return PtrToUlong( pComboBox->GetSelectedData() ); } //------------------------------------------------------------------------------------- -bool CD3DSettingsDlg::GetSelectedDebugDeviceValue() +bool CD3DSettingsDlg::GetSelectedDebugDeviceValue() const { - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); + auto pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE ); return pCheckBox->GetChecked(); } -//------------------------------------------------------------------------------------- -void CD3DSettingsDlg::SetDeviceClip( bool bDeviceClip ) -{ - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_DEVICECLIP ); - pCheckBox->SetChecked( bDeviceClip ); -} - - -//------------------------------------------------------------------------------------- -bool CD3DSettingsDlg::IsDeviceClip() -{ - CDXUTCheckBox* pCheckBox = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_DEVICECLIP ); - return pCheckBox->GetChecked(); -} - //-------------------------------------------------------------------------------------- // Updates the resolution list for D3D11 //-------------------------------------------------------------------------------------- HRESULT CD3DSettingsDlg::UpdateD3D11Resolutions() { - const DWORD dwWidth = g_DeviceSettings.d3d11.sd.BufferDesc.Width; const DWORD dwHeight = g_DeviceSettings.d3d11.sd.BufferDesc.Height; // DXUTSETTINGSDLG_D3D11_RESOLUTION - CDXUTComboBox* pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); + auto pResolutionComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_RESOLUTION ); pResolutionComboBox->RemoveAllItems(); - CD3D11EnumOutputInfo* pOutputInfo = GetCurrentD3D11OutputInfo(); - if( pOutputInfo == NULL ) + auto pOutputInfo = GetCurrentD3D11OutputInfo(); + if( !pOutputInfo ) return E_FAIL; - bool bShowAll = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL )->GetChecked(); + bool bWindowed = IsWindowed(); + if ( !bWindowed ) + { + auto pShowAllCB = m_Dialog.GetCheckBox( DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL ); + bool bShowAll = pShowAllCB->GetChecked(); - // Get the desktop aspect ratio - DXGI_MODE_DESC dmDesktop; - DXUTGetDesktopResolution( g_DeviceSettings.d3d11.AdapterOrdinal, &dmDesktop.Width, &dmDesktop.Height ); - float fDesktopAspectRatio = dmDesktop.Width / ( float )dmDesktop.Height; + // Get the desktop aspect ratio + DXGI_MODE_DESC dmDesktop; + DXUTGetDesktopResolution(g_DeviceSettings.d3d11.AdapterOrdinal, &dmDesktop.Width, &dmDesktop.Height); + float fDesktopAspectRatio = dmDesktop.Width / (float) dmDesktop.Height; - for( int idm = 0; idm < pOutputInfo->displayModeList.GetSize(); idm++ ) - { - DXGI_MODE_DESC DisplayMode = pOutputInfo->displayModeList.GetAt( idm ); - float fAspect = ( float )DisplayMode.Width / ( float )DisplayMode.Height; + if ( !bShowAll && !DXUTIsWindowed() ) + { + float fAspect = (float) dwWidth / (float) dwHeight; + if ( fabsf(fDesktopAspectRatio - fAspect) >= 0.05f ) + { + // Our current fullscren resolution should be listed in the combo box despite the aspect ratio + pShowAllCB->SetChecked(true); + bShowAll = true; + } + } - if( DisplayMode.Format == g_DeviceSettings.d3d11.sd.BufferDesc.Format ) + for (size_t idm = 0; idm < pOutputInfo->displayModeList.size(); idm++) { - // If "Show All" is not checked, then hide all resolutions - // that don't match the aspect ratio of the desktop resolution - if( bShowAll || ( !bShowAll && fabsf( fDesktopAspectRatio - fAspect ) < 0.05f ) ) + auto DisplayMode = pOutputInfo->displayModeList[idm]; + float fAspect = (float) DisplayMode.Width / (float) DisplayMode.Height; + + if (DisplayMode.Format == g_DeviceSettings.d3d11.sd.BufferDesc.Format) { - AddD3D11Resolution( DisplayMode.Width, DisplayMode.Height ); + // If "Show All" is not checked, then hide all resolutions + // that don't match the aspect ratio of the desktop resolution + if (bShowAll || (!bShowAll && fabsf(fDesktopAspectRatio - fAspect) < 0.05f)) + { + AddD3D11Resolution(DisplayMode.Width, DisplayMode.Height); + } } } } + else + { + pResolutionComboBox->RemoveAllItems(); + AddD3D11Resolution( dwWidth, dwHeight ); + } - const DWORD dwCurResolution = MAKELONG( g_DeviceSettings.d3d11.sd.BufferDesc.Width, - g_DeviceSettings.d3d11.sd.BufferDesc.Height ); + pResolutionComboBox->SetSelectedByData(ULongToPtr(MAKELONG(dwWidth, dwHeight))); + OnD3D11ResolutionChanged(); - pResolutionComboBox->SetSelectedByData( ULongToPtr( dwCurResolution ) ); + return S_OK; +} + + +//-------------------------------------------------------------------------------------- +// Updates the refresh list for D3D11 +//-------------------------------------------------------------------------------------- +HRESULT CD3DSettingsDlg::UpdateD3D11RefreshRates() +{ + const DWORD dwWidth = g_DeviceSettings.d3d11.sd.BufferDesc.Width; + const DWORD dwHeight = g_DeviceSettings.d3d11.sd.BufferDesc.Height; + DXGI_FORMAT backBuffer = g_DeviceSettings.d3d11.sd.BufferDesc.Format; + const DXGI_RATIONAL RefreshRate = g_DeviceSettings.d3d11.sd.BufferDesc.RefreshRate; + auto pRefreshRateComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_D3D11_REFRESH_RATE ); + for( UINT i = 0; i < pRefreshRateComboBox->GetNumItems(); ++i ) + { + auto pRefreshRate = reinterpret_cast<DXGI_RATIONAL*>( pRefreshRateComboBox->GetItemData( i ) ); + delete pRefreshRate; + } + pRefreshRateComboBox->RemoveAllItems(); bool bWindowed = IsWindowed(); if( bWindowed ) { - pResolutionComboBox->RemoveAllItems(); - AddD3D11Resolution( dwWidth, dwHeight ); + DXGI_RATIONAL def; + def.Denominator = def.Numerator = 0; + AddD3D11RefreshRate(def); + } + else + { + auto pD3DEnum = DXUTGetD3D11Enumeration(); + if ( !pD3DEnum ) + return E_POINTER; - pResolutionComboBox->SetSelectedByData( ULongToPtr( MAKELONG( dwWidth, dwHeight ) ) ); + auto pOutputInfo = pD3DEnum->GetOutputInfo( g_DeviceSettings.d3d11.AdapterOrdinal, g_DeviceSettings.d3d11.Output ); + if ( !pOutputInfo ) + return E_POINTER; + for( auto it = pOutputInfo->displayModeList.cbegin(); it != pOutputInfo->displayModeList.cend(); ++it ) + { + if ( it->Width == dwWidth && it->Height == dwHeight && it->Format == backBuffer ) + AddD3D11RefreshRate( it->RefreshRate ); + } + SetSelectedD3D11RefreshRate( RefreshRate ); } return S_OK; @@ -2669,25 +1533,25 @@ HRESULT CD3DSettingsDlg::UpdateD3D11Resolutions() // //------------------------------------------------------------------------------------- -void CD3DSettingsDlg::AddD3D11DeviceType( D3D_DRIVER_TYPE devType ) +void CD3DSettingsDlg::AddD3D11DeviceType( _In_ D3D_DRIVER_TYPE devType ) { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); - if( !pComboBox->ContainsItem( DXUTD3DX11DeviceTypeToString( devType ) ) ) - pComboBox->AddItem( DXUTD3DX11DeviceTypeToString( devType ), ULongToPtr( devType ) ); + if( !pComboBox->ContainsItem( DXUTDeviceTypeToString( devType ) ) ) + pComboBox->AddItem( DXUTDeviceTypeToString( devType ), ULongToPtr( devType ) ); } //------------------------------------------------------------------------------------- -D3D_DRIVER_TYPE CD3DSettingsDlg::GetSelectedD3D11DeviceType() +D3D_DRIVER_TYPE CD3DSettingsDlg::GetSelectedD3D11DeviceType() const { - CDXUTComboBox* pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); + auto pComboBox = m_Dialog.GetComboBox( DXUTSETTINGSDLG_DEVICE_TYPE ); return ( D3D_DRIVER_TYPE )PtrToUlong( pComboBox->GetSelectedData() ); } -void CD3DSettingsDlg::UpdateModeChangeTimeoutText( int nSecRemaining ) +void CD3DSettingsDlg::UpdateModeChangeTimeoutText( _In_ int nSecRemaining ) { const WCHAR StrTimeout[] = L"Reverting to previous display settings in %d seconds"; const DWORD CchBuf = sizeof( StrTimeout ) / sizeof( WCHAR ) + 16; @@ -2695,52 +1559,14 @@ void CD3DSettingsDlg::UpdateModeChangeTimeoutText( int nSecRemaining ) swprintf_s( buf, CchBuf, StrTimeout, nSecRemaining ); - CDXUTStatic* pStatic = m_RevertModeDialog.GetStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT ); + auto pStatic = m_RevertModeDialog.GetStatic( DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT ); pStatic->SetText( buf ); } //-------------------------------------------------------------------------------------- -// Returns the string for the given DXUTDeviceVersion. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTAPIVersionToString( DXUTDeviceVersion version ) -{ - switch( version ) - { - case DXUT_D3D9_DEVICE: - return L"Direct3D 9"; - case DXUT_D3D11_DEVICE: - return L"Direct3D 11"; - default: - return L"Unknown version"; - } -} - - -//-------------------------------------------------------------------------------------- -// Returns the string for the given D3DDEVTYPE. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTD3DDeviceTypeToString( D3DDEVTYPE devType ) -{ - switch( devType ) - { - case D3DDEVTYPE_HAL: - return L"D3DDEVTYPE_HAL"; - case D3DDEVTYPE_SW: - return L"D3DDEVTYPE_SW"; - case D3DDEVTYPE_REF: - return L"D3DDEVTYPE_REF"; - default: - return L"Unknown devType"; - } -} - - - - -//-------------------------------------------------------------------------------------- // Returns the string for the given D3D_DRIVER_TYPE. //-------------------------------------------------------------------------------------- -WCHAR* DXUTD3DX11DeviceTypeToString( D3D_DRIVER_TYPE devType ) +const WCHAR* DXUTDeviceTypeToString( _In_ D3D_DRIVER_TYPE devType ) { switch( devType ) { @@ -2758,96 +1584,3 @@ WCHAR* DXUTD3DX11DeviceTypeToString( D3D_DRIVER_TYPE devType ) } -//-------------------------------------------------------------------------------------- -// Returns the string for the given D3DMULTISAMPLE_TYPE. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTMultisampleTypeToString( D3DMULTISAMPLE_TYPE MultiSampleType ) -{ - switch( MultiSampleType ) - { - case D3DMULTISAMPLE_NONE: - return L"D3DMULTISAMPLE_NONE"; - case D3DMULTISAMPLE_NONMASKABLE: - return L"D3DMULTISAMPLE_NONMASKABLE"; - case D3DMULTISAMPLE_2_SAMPLES: - return L"D3DMULTISAMPLE_2_SAMPLES"; - case D3DMULTISAMPLE_3_SAMPLES: - return L"D3DMULTISAMPLE_3_SAMPLES"; - case D3DMULTISAMPLE_4_SAMPLES: - return L"D3DMULTISAMPLE_4_SAMPLES"; - case D3DMULTISAMPLE_5_SAMPLES: - return L"D3DMULTISAMPLE_5_SAMPLES"; - case D3DMULTISAMPLE_6_SAMPLES: - return L"D3DMULTISAMPLE_6_SAMPLES"; - case D3DMULTISAMPLE_7_SAMPLES: - return L"D3DMULTISAMPLE_7_SAMPLES"; - case D3DMULTISAMPLE_8_SAMPLES: - return L"D3DMULTISAMPLE_8_SAMPLES"; - case D3DMULTISAMPLE_9_SAMPLES: - return L"D3DMULTISAMPLE_9_SAMPLES"; - case D3DMULTISAMPLE_10_SAMPLES: - return L"D3DMULTISAMPLE_10_SAMPLES"; - case D3DMULTISAMPLE_11_SAMPLES: - return L"D3DMULTISAMPLE_11_SAMPLES"; - case D3DMULTISAMPLE_12_SAMPLES: - return L"D3DMULTISAMPLE_12_SAMPLES"; - case D3DMULTISAMPLE_13_SAMPLES: - return L"D3DMULTISAMPLE_13_SAMPLES"; - case D3DMULTISAMPLE_14_SAMPLES: - return L"D3DMULTISAMPLE_14_SAMPLES"; - case D3DMULTISAMPLE_15_SAMPLES: - return L"D3DMULTISAMPLE_15_SAMPLES"; - case D3DMULTISAMPLE_16_SAMPLES: - return L"D3DMULTISAMPLE_16_SAMPLES"; - default: - return L"Unknown Multisample Type"; - } -} - - -//-------------------------------------------------------------------------------------- -// Returns the string for the given vertex processing type -//-------------------------------------------------------------------------------------- -WCHAR* DXUTVertexProcessingTypeToString( DWORD vpt ) -{ - switch( vpt ) - { - case D3DCREATE_SOFTWARE_VERTEXPROCESSING: - return L"Software vertex processing"; - case D3DCREATE_MIXED_VERTEXPROCESSING: - return L"Mixed vertex processing"; - case D3DCREATE_HARDWARE_VERTEXPROCESSING: - return L"Hardware vertex processing"; - case D3DCREATE_PUREDEVICE: - return L"Pure hardware vertex processing"; - default: - return L"Unknown vertex processing type"; - } -} - - -//-------------------------------------------------------------------------------------- -// Returns the string for the given present interval. -//-------------------------------------------------------------------------------------- -WCHAR* DXUTPresentIntervalToString( UINT pi ) -{ - switch( pi ) - { - case D3DPRESENT_INTERVAL_IMMEDIATE: - return L"D3DPRESENT_INTERVAL_IMMEDIATE"; - case D3DPRESENT_INTERVAL_DEFAULT: - return L"D3DPRESENT_INTERVAL_DEFAULT"; - case D3DPRESENT_INTERVAL_ONE: - return L"D3DPRESENT_INTERVAL_ONE"; - case D3DPRESENT_INTERVAL_TWO: - return L"D3DPRESENT_INTERVAL_TWO"; - case D3DPRESENT_INTERVAL_THREE: - return L"D3DPRESENT_INTERVAL_THREE"; - case D3DPRESENT_INTERVAL_FOUR: - return L"D3DPRESENT_INTERVAL_FOUR"; - default: - return L"Unknown PresentInterval"; - } -} - - diff --git a/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.h b/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.h index 5d4db4f..fd7f0c8 100644 --- a/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.h +++ b/samples/DX_APIUsage/DXUT/Optional/DXUTsettingsdlg.h @@ -1,16 +1,18 @@ //-------------------------------------------------------------------------------------- -// File: DXUTSettingsDlg.cpp +// File: DXUTSettingsDlg.h // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_SETTINGS_H -#define DXUT_SETTINGS_H //-------------------------------------------------------------------------------------- // Header Includes //-------------------------------------------------------------------------------------- #include "DXUTgui.h" + //-------------------------------------------------------------------------------------- // Control IDs //-------------------------------------------------------------------------------------- @@ -21,27 +23,7 @@ #define DXUTSETTINGSDLG_DEVICE_TYPE 4 #define DXUTSETTINGSDLG_WINDOWED 5 #define DXUTSETTINGSDLG_FULLSCREEN 6 -#define DXUTSETTINGSDLG_ADAPTER_FORMAT 7 -#define DXUTSETTINGSDLG_ADAPTER_FORMAT_LABEL 8 -#define DXUTSETTINGSDLG_RESOLUTION 9 -#define DXUTSETTINGSDLG_RESOLUTION_LABEL 10 -#define DXUTSETTINGSDLG_REFRESH_RATE 11 -#define DXUTSETTINGSDLG_REFRESH_RATE_LABEL 12 -#define DXUTSETTINGSDLG_BACK_BUFFER_FORMAT 13 -#define DXUTSETTINGSDLG_BACK_BUFFER_FORMAT_LABEL 14 -#define DXUTSETTINGSDLG_DEPTH_STENCIL 15 -#define DXUTSETTINGSDLG_DEPTH_STENCIL_LABEL 16 -#define DXUTSETTINGSDLG_MULTISAMPLE_TYPE 17 -#define DXUTSETTINGSDLG_MULTISAMPLE_TYPE_LABEL 18 -#define DXUTSETTINGSDLG_MULTISAMPLE_QUALITY 19 -#define DXUTSETTINGSDLG_MULTISAMPLE_QUALITY_LABEL 20 -#define DXUTSETTINGSDLG_VERTEX_PROCESSING 21 -#define DXUTSETTINGSDLG_VERTEX_PROCESSING_LABEL 22 -#define DXUTSETTINGSDLG_PRESENT_INTERVAL 23 -#define DXUTSETTINGSDLG_PRESENT_INTERVAL_LABEL 24 -#define DXUTSETTINGSDLG_DEVICECLIP 25 #define DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL 26 -#define DXUTSETTINGSDLG_API_VERSION 27 #define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT 28 #define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL 29 #define DXUTSETTINGSDLG_D3D11_RESOLUTION 30 @@ -65,169 +47,109 @@ #define DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT 60 #define DXUTSETTINGSDLG_WINDOWED_GROUP 0x0100 -#define TOTAL_FEATURE_LEVLES 6 +#define TOTAL_FEATURE_LEVELS 9 + //-------------------------------------------------------------------------------------- // Dialog for selection of device settings // Use DXUTGetD3DSettingsDialog() to access global instance -// To control the contents of the dialog, use the CD3D9Enumeration class. +// To control the contents of the dialog, use the CD3D11Enumeration class. //-------------------------------------------------------------------------------------- class CD3DSettingsDlg { public: - CD3DSettingsDlg(); - ~CD3DSettingsDlg(); - - void Init( CDXUTDialogResourceManager* pManager ); - void Init( CDXUTDialogResourceManager* pManager, LPCWSTR szControlTextureFileName ); - void Init( CDXUTDialogResourceManager* pManager, LPCWSTR pszControlTextureResourcename, - HMODULE hModule ); - - HRESULT Refresh(); - void OnRender( float fElapsedTime ); - void OnRender9( float fElapsedTime ); - void OnRender10( float fElapsedTime ); - void OnRender11( float fElapsedTime ); - - HRESULT OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnD3D9ResetDevice(); - void OnD3D9LostDevice(); - void OnD3D9DestroyDevice(); - - HRESULT OnD3D11CreateDevice( ID3D11Device* pd3dDevice ); - HRESULT OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); - void OnD3D11DestroyDevice(); - - CDXUTDialog* GetDialogControl() - { - return &m_Dialog; - } - bool IsActive() - { - return m_bActive; - } - void SetActive( bool bActive ) - { - m_bActive = bActive; if( bActive ) Refresh(); - } - void ShowControlSet( DXUTDeviceVersion ver ); - - LRESULT MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); - -protected: - friend CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); - - void CreateControls(); - HRESULT SetDeviceSettingsFromUI(); - void SetSelectedD3D11RefreshRate( DXGI_RATIONAL RefreshRate ); - HRESULT UpdateD3D11Resolutions(); - - void OnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl ); - static void WINAPI StaticOnEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserData ); - static void WINAPI StaticOnModeChangeTimer( UINT nIDEvent, void* pUserContext ); + CD3DSettingsDlg(); + ~CD3DSettingsDlg(); - CD3D9EnumAdapterInfo* GetCurrentAdapterInfo(); - CD3D9EnumDeviceInfo* GetCurrentDeviceInfo(); - CD3D9EnumDeviceSettingsCombo* GetCurrentDeviceSettingsCombo(); + void Init( _In_ CDXUTDialogResourceManager* pManager ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR szControlTextureFileName ); + void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR pszControlTextureResourcename, + _In_ HMODULE hModule ); - CD3D11EnumAdapterInfo* GetCurrentD3D11AdapterInfo(); - CD3D11EnumDeviceInfo* GetCurrentD3D11DeviceInfo(); - CD3D11EnumOutputInfo* GetCurrentD3D11OutputInfo(); - CD3D11EnumDeviceSettingsCombo* GetCurrentD3D11DeviceSettingsCombo(); + HRESULT Refresh(); + void OnRender( _In_ float fElapsedTime ); - void AddAPIVersion( DXUTDeviceVersion version ); - DXUTDeviceVersion GetSelectedAPIVersion(); + HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice ); + HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice, + _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); + void OnD3D11DestroyDevice(); - void AddAdapter( const WCHAR* strDescription, UINT iAdapter ); - UINT GetSelectedAdapter(); - - void AddDeviceType( D3DDEVTYPE devType ); - D3DDEVTYPE GetSelectedDeviceType(); - - void SetWindowed( bool bWindowed ); - bool IsWindowed(); - - void AddAdapterFormat( D3DFORMAT format ); - D3DFORMAT GetSelectedAdapterFormat(); - - void AddResolution( DWORD dwWidth, DWORD dwHeight ); - void GetSelectedResolution( DWORD* pdwWidth, DWORD* pdwHeight ); + CDXUTDialog* GetDialogControl() { return &m_Dialog; } + bool IsActive() const { return m_bActive; } + void SetActive( _In_ bool bActive ) + { + m_bActive = bActive; + if( bActive ) Refresh(); + } - void AddRefreshRate( DWORD dwRate ); - DWORD GetSelectedRefreshRate(); + LRESULT MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); - void AddBackBufferFormat( D3DFORMAT format ); - D3DFORMAT GetSelectedBackBufferFormat(); +protected: + friend CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); - void AddDepthStencilBufferFormat( D3DFORMAT format ); - D3DFORMAT GetSelectedDepthStencilBufferFormat(); + void CreateControls(); + void SetSelectedD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ); + HRESULT UpdateD3D11Resolutions(); + HRESULT UpdateD3D11RefreshRates(); - void AddMultisampleType( D3DMULTISAMPLE_TYPE type ); - D3DMULTISAMPLE_TYPE GetSelectedMultisampleType(); + void OnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl ); - void AddMultisampleQuality( DWORD dwQuality ); - DWORD GetSelectedMultisampleQuality(); + static void WINAPI StaticOnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl, _In_opt_ void* pUserData ); + static void WINAPI StaticOnModeChangeTimer( _In_ UINT nIDEvent, _In_opt_ void* pUserContext ); - void AddVertexProcessingType( DWORD dwType ); - DWORD GetSelectedVertexProcessingType(); + CD3D11EnumAdapterInfo* GetCurrentD3D11AdapterInfo() const; + CD3D11EnumDeviceInfo* GetCurrentD3D11DeviceInfo() const; + CD3D11EnumOutputInfo* GetCurrentD3D11OutputInfo() const; + CD3D11EnumDeviceSettingsCombo* GetCurrentD3D11DeviceSettingsCombo() const; - DWORD GetSelectedPresentInterval(); + void AddAdapter( _In_z_ const WCHAR* strDescription, _In_ UINT iAdapter ); + UINT GetSelectedAdapter() const; - void SetDeviceClip( bool bDeviceClip ); - bool IsDeviceClip(); + void SetWindowed( _In_ bool bWindowed ); + bool IsWindowed() const; // D3D11 - void AddD3D11DeviceType( D3D_DRIVER_TYPE devType ); - D3D_DRIVER_TYPE GetSelectedD3D11DeviceType(); + void AddD3D11DeviceType( _In_ D3D_DRIVER_TYPE devType ); + D3D_DRIVER_TYPE GetSelectedD3D11DeviceType() const; - void AddD3D11AdapterOutput( const WCHAR* strName, UINT nOutput ); - UINT GetSelectedD3D11AdapterOutput(); + void AddD3D11AdapterOutput( _In_z_ const WCHAR* strName, _In_ UINT nOutput ); + UINT GetSelectedD3D11AdapterOutput() const; - void AddD3D11Resolution( DWORD dwWidth, DWORD dwHeight ); - void GetSelectedD3D11Resolution( DWORD* pdwWidth, DWORD* pdwHeight ); + void AddD3D11Resolution( _In_ DWORD dwWidth, _In_ DWORD dwHeight ); + void GetSelectedD3D11Resolution( _Out_ DWORD* pdwWidth, _Out_ DWORD* pdwHeight ) const; - void AddD3D11FeatureLevel(D3D_FEATURE_LEVEL); - D3D_FEATURE_LEVEL GetSelectedFeatureLevel(); + void AddD3D11FeatureLevel( _In_ D3D_FEATURE_LEVEL fl ); + D3D_FEATURE_LEVEL GetSelectedFeatureLevel() const; - void AddD3D11RefreshRate( DXGI_RATIONAL RefreshRate ); - DXGI_RATIONAL GetSelectedD3D11RefreshRate(); + void AddD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ); + DXGI_RATIONAL GetSelectedD3D11RefreshRate() const; - void AddD3D11BackBufferFormat( DXGI_FORMAT format ); - DXGI_FORMAT GetSelectedD3D11BackBufferFormat(); - - void AddD3D11MultisampleCount( UINT count ); - UINT GetSelectedD3D11MultisampleCount(); - - void AddD3D11MultisampleQuality( UINT Quality ); - UINT GetSelectedD3D11MultisampleQuality(); - - DWORD GetSelectedD3D11PresentInterval(); - bool GetSelectedDebugDeviceValue(); + void AddD3D11BackBufferFormat( _In_ DXGI_FORMAT format ); + DXGI_FORMAT GetSelectedD3D11BackBufferFormat() const; + void AddD3D11MultisampleCount( _In_ UINT count ); + UINT GetSelectedD3D11MultisampleCount() const; + void AddD3D11MultisampleQuality( _In_ UINT Quality ); + UINT GetSelectedD3D11MultisampleQuality() const; + DWORD GetSelectedD3D11PresentInterval() const; + bool GetSelectedDebugDeviceValue() const; + HRESULT OnD3D11ResolutionChanged (); - HRESULT OnAPIVersionChanged( bool bRefresh=false ); HRESULT OnFeatureLevelChanged(); HRESULT OnAdapterChanged(); HRESULT OnDeviceTypeChanged(); HRESULT OnWindowedFullScreenChanged(); HRESULT OnAdapterOutputChanged(); - HRESULT OnAdapterFormatChanged(); - HRESULT OnResolutionChanged(); HRESULT OnRefreshRateChanged(); HRESULT OnBackBufferFormatChanged(); - HRESULT OnDepthStencilBufferFormatChanged(); HRESULT OnMultisampleTypeChanged(); HRESULT OnMultisampleQualityChanged(); - HRESULT OnVertexProcessingChanged(); HRESULT OnPresentIntervalChanged(); HRESULT OnDebugDeviceChanged(); - HRESULT OnDeviceClipChanged(); - void UpdateModeChangeTimeoutText( int nSecRemaining ); + void UpdateModeChangeTimeoutText( _In_ int nSecRemaining ); - IDirect3DStateBlock9* m_pStateBlock; CDXUTDialog* m_pActiveDialog; CDXUTDialog m_Dialog; CDXUTDialog m_RevertModeDialog; @@ -235,14 +157,9 @@ protected: UINT m_nIDEvent; bool m_bActive; - D3D_FEATURE_LEVEL m_Levels[TOTAL_FEATURE_LEVLES]; + D3D_FEATURE_LEVEL m_Levels[TOTAL_FEATURE_LEVELS]; }; CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); - - - -#endif - diff --git a/samples/DX_APIUsage/DXUT/Optional/ImeUi.cpp b/samples/DX_APIUsage/DXUT/Optional/ImeUi.cpp index f7a0cb2..2c6b4ef 100644 --- a/samples/DX_APIUsage/DXUT/Optional/ImeUi.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/ImeUi.cpp @@ -2,19 +2,22 @@ // File: ImeUi.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "dxut.h" #include "ImeUi.h" #include <math.h> #include <msctf.h> #include <malloc.h> -#include <strsafe.h> // Ignore typecast warnings #pragma warning( disable : 4312 ) #pragma warning( disable : 4244 ) #pragma warning( disable : 4311 ) +#pragma prefast( disable : 28159, "GetTickCount() is fine for a blinking cursor" ) #define MAX_CANDIDATE_LENGTH 256 #define COUNTOF(a) ( sizeof( a ) / sizeof( ( a )[0] ) ) @@ -61,7 +64,7 @@ static IMEUI_APPEARANCE gSkinIME = 24, // symbolHeight; 0xa0, // symbolTranslucence; 0, // symbolPlacement; - NULL, // symbolFont; + nullptr, // symbolFont; 0xffffffff, // candColorBase; 0xff000000, // candColorBorder; 0, // candColorText; @@ -121,7 +124,7 @@ FAR* LPINPUTCONTEXT2; class CDisableCicero { public: - CDisableCicero() : m_ptim( NULL ), + CDisableCicero() : m_ptim( nullptr ), m_bComInit( false ) { } @@ -136,12 +139,12 @@ public: return; } HRESULT hr; - hr = CoInitializeEx( NULL, COINIT_APARTMENTTHREADED ); + hr = CoInitializeEx( nullptr, COINIT_APARTMENTTHREADED ); if( SUCCEEDED( hr ) ) { m_bComInit = true; hr = CoCreateInstance( CLSID_TF_ThreadMgr, - NULL, + nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfThreadMgr ), ( void** )&m_ptim ); @@ -152,7 +155,7 @@ public: if( m_ptim ) { m_ptim->Release(); - m_ptim = NULL; + m_ptim = nullptr; } if( m_bComInit ) CoUninitialize(); @@ -161,13 +164,13 @@ public: void DisableCiceroOnThisWnd( HWND hwnd ) { - if( m_ptim == NULL ) + if( !m_ptim ) return; ITfDocumentMgr* pdimPrev; // the dim that is associated previously. - // Associate NULL dim to the window. + // Associate nullptr dim to the window. // When this window gets the focus, Cicero does not work and IMM32 IME // will be activated. - if( SUCCEEDED( m_ptim->AssociateFocus( hwnd, NULL, &pdimPrev ) ) ) + if( SUCCEEDED( m_ptim->AssociateFocus( hwnd, nullptr, &pdimPrev ) ) ) { if( pdimPrev ) pdimPrev->Release(); @@ -255,7 +258,7 @@ static DWORD g_hCompChar; static int g_iCandListIndexBase; static DWORD g_dwImeUiFlags = IMEUI_FLAG_SUPPORT_CARET; static bool g_bUILessMode = false; -static HMODULE g_hImmDll = NULL; +static HMODULE g_hImmDll = nullptr; #define IsNT() (g_osi.dwPlatformId == VER_PLATFORM_WIN32_NT) @@ -289,36 +292,29 @@ static double lastSwirl; static HKL g_hklCurrent = 0; static UINT g_uCodePage = 0; -static LPTSTR g_aszIndicator[] = +static LPCTSTR g_aszIndicator[] = { TEXT( "A" ), -#ifdef UNICODE - L"\x7B80", - L"\x7E41", - L"\xac00", - L"\x3042", -#else - "\xd6\xd0", - "\xa4\xa4", - "\xb0\xa1", - "\x82\xa0", -#endif + L"\x7B80", + L"\x7E41", + L"\xac00", + L"\x3042", }; -static LPTSTR g_pszIndicatior = g_aszIndicator[0]; +static LPCTSTR g_pszIndicatior = g_aszIndicator[0]; -static void GetReadingString( HWND hWnd ); -static DWORD GetImeId( UINT uIndex = 0 ); +static void GetReadingString( _In_ HWND hWnd ); +static DWORD GetImeId( _In_ UINT uIndex = 0 ); static void CheckToggleState(); static void DrawImeIndicator(); static void DrawCandidateList(); -static void DrawCompositionString( bool bDrawCompAttr ); -static void GetReadingWindowOrientation( DWORD dwId ); +static void DrawCompositionString( _In_ bool bDrawCompAttr ); +static void GetReadingWindowOrientation( _In_ DWORD dwId ); static void OnInputLangChangeWorker(); static void OnInputLangChange(); static void SetImeApi(); static void CheckInputLocale(); -static void SetSupportLevel( DWORD dwImeLevel ); -void ImeUi_SetSupportLevel( DWORD dwImeLevel ); +static void SetSupportLevel( _In_ DWORD dwImeLevel ); +void ImeUi_SetSupportLevel( _In_ DWORD dwImeLevel ); // @@ -352,15 +348,15 @@ protected: public ITfCompartmentEventSink { public: - CUIElementSink(); - ~CUIElementSink(); + CUIElementSink(); + virtual ~CUIElementSink(); // IUnknown - STDMETHODIMP QueryInterface( REFIID riid, void** ppvObj ); - STDMETHODIMP_( ULONG ) - AddRef( void ); - STDMETHODIMP_( ULONG ) - Release( void ); + STDMETHODIMP QueryInterface( _In_ REFIID riid, _COM_Outptr_ void** ppvObj ); + STDMETHODIMP_( ULONG ) + AddRef(); + STDMETHODIMP_( ULONG ) + Release(); // ITfUIElementSink // Notifications for Reading Window events. We could process candidate as well, but we'll use IMM for simplicity sake. @@ -370,12 +366,12 @@ protected: // ITfInputProcessorProfileActivationSink // Notification for keyboard input locale change - STDMETHODIMP OnActivated( DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, - REFGUID guidProfile, HKL hkl, DWORD dwFlags ); + STDMETHODIMP OnActivated( DWORD dwProfileType, LANGID langid, _In_ REFCLSID clsid, _In_ REFGUID catid, + _In_ REFGUID guidProfile, HKL hkl, DWORD dwFlags ); // ITfCompartmentEventSink // Notification for open mode (toggle state) change - STDMETHODIMP OnChange( REFGUID rguid ); + STDMETHODIMP OnChange( _In_ REFGUID rguid ); private: LONG _cRef; @@ -386,8 +382,8 @@ protected: static ITfUIElement* GetUIElement( DWORD dwUIElementId ); static BOOL GetCompartments( ITfCompartmentMgr** ppcm, ITfCompartment** ppTfOpenMode, ITfCompartment** ppTfConvMode ); - static BOOL SetupCompartmentSinks( BOOL bResetOnly = FALSE, ITfCompartment* pTfOpenMode = NULL, - ITfCompartment* ppTfConvMode = NULL ); + static BOOL SetupCompartmentSinks( BOOL bResetOnly = FALSE, ITfCompartment* pTfOpenMode = nullptr, + ITfCompartment* ppTfConvMode = nullptr ); static ITfThreadMgrEx* m_tm; static DWORD m_dwUIElementSinkCookie; @@ -414,8 +410,8 @@ DWORD CTsfUiLessMode::m_dwUIElementSinkCookie = TF_INV DWORD CTsfUiLessMode::m_dwAlpnSinkCookie = TF_INVALID_COOKIE; DWORD CTsfUiLessMode::m_dwOpenModeSinkCookie = TF_INVALID_COOKIE; DWORD CTsfUiLessMode::m_dwConvModeSinkCookie = TF_INVALID_COOKIE; -CTsfUiLessMode::CUIElementSink* CTsfUiLessMode::m_TsfSink = NULL; -int CTsfUiLessMode::m_nCandidateRefCount = NULL; +CTsfUiLessMode::CUIElementSink* CTsfUiLessMode::m_TsfSink = nullptr; +int CTsfUiLessMode::m_nCandidateRefCount = 0; static unsigned long _strtoul( LPCSTR psz, LPTSTR*, int ) { @@ -452,282 +448,8 @@ static unsigned long _strtoul( LPCSTR psz, LPTSTR*, int ) return ulRet; } -#ifdef UNICODE -#define GetCharCount(psz) lstrlen(psz) +#define GetCharCount(psz) (int)wcslen(psz) #define GetCharCountFromBytes(psz,iBytes) (iBytes) -static void AW_SendCompString() -{ - int i, iLen; - if ( ImeUiCallback_OnChar ) - { - for ( i = 0; g_szCompositionString[i]; i++ ) - { - ImeUiCallback_OnChar( g_szCompositionString[i] ); - } - return; - } - - BYTE szCompStr[COUNTOF(g_szCompositionString) * 2]; - iLen = WideCharToMultiByte(g_uCodePage, 0, g_szCompositionString, -1, - (LPSTR)szCompStr, COUNTOF(szCompStr), NULL, NULL) - 1; // don't need to send NUL terminator; - for (i = 0; i < iLen; i++) - { - SendKeyMsg(g_hwndCurr, WM_CHAR, szCompStr[i]); - } -} - -// The following AW_Imm* functions are there to support Win95/98 first version. -// They can be deleted if the game doesn't supports them (i.e. games requires Win98 SE or later). -static DWORD AW_GetCandidateList(HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList) -{ - DWORD dwBufLen = ImmGetCandidateListA( himc, dwIndex, NULL, 0 ); - if (dwBufLen) - { - LPCANDIDATELIST pCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(dwBufLen); - if (pCandList) { - dwBufLen = ImmGetCandidateListA( himc, dwIndex, pCandList, dwBufLen ); - if (dwBufLen) { - int i; - int wideBufLen = 0; - for (i = 0; i < (int)pCandList->dwCount; i++) { - wideBufLen += MultiByteToWideChar(g_uCodePage, 0, (LPSTR)pCandList + pCandList->dwOffset[i], -1, NULL, 0) * sizeof(WCHAR); - } - wideBufLen += pCandList->dwOffset[0]; - *ppCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(wideBufLen); - LPCANDIDATELIST pCandListW = *ppCandList; - memcpy(pCandListW, pCandList, pCandList->dwOffset[0]); - LPWSTR pwz = (LPWSTR)((LPSTR)pCandListW + pCandList->dwOffset[0]); - for (i = 0; i < (int)pCandList->dwCount; i++) { - pCandListW->dwOffset[i] = (LPSTR)pwz - (LPSTR)pCandListW; - pwz += MultiByteToWideChar(g_uCodePage, 0, (LPSTR)pCandList + pCandList->dwOffset[i], -1, pwz, 256); - } - dwBufLen = wideBufLen; - } - ImeUiCallback_Free(pCandList); - } - } - return dwBufLen; -} - -static LONG WINAPI AW_ImmGetCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen) -{ - char pszMb[COUNTOF(g_szCompositionString) * 2]; - DWORD dwRet = ImmGetCompositionStringA(himc, dwIndex, pszMb, sizeof(pszMb)); - switch (dwIndex) { - case GCS_RESULTSTR: - case GCS_COMPSTR: - if (dwRet) { - pszMb[dwRet] = 0; - dwRet = (DWORD)MultiByteToWideChar(g_uCodePage, 0, pszMb, -1, (LPWSTR)lpBuf, dwBufLen); - if (dwRet) { - // Note that ImmGetCompositionString() returns number of bytes copied, regardless of the width of character. - dwRet = (dwRet - 1) * sizeof(WCHAR); - } - } - break; - case GCS_CURSORPOS: - dwRet /= 2; - break; - case GCS_COMPATTR: { - char pszMb2[COUNTOF(g_szCompositionString) * 2]; - DWORD dwRet2 = ImmGetCompositionStringA(himc, GCS_COMPSTR, pszMb2, sizeof(pszMb2)); - if (!dwRet2) { - dwRet2 = ImmGetCompositionStringA(himc, GCS_RESULTSTR, pszMb2, sizeof(pszMb2)); - if (!dwRet2) { - return 0; - } - } - char* pOut = (char*)lpBuf; - for (DWORD i = 0; i < dwRet; i++) { - *pOut++ = pszMb[i]; // copy attribute - if (_IsLeadByte(pszMb2[i])) - i++; - } - dwRet = pOut - (char*)lpBuf; - } - break; - } - return dwRet; -} - -#else // !UNICODE -// returns number of characters from number of bytes -static int GetCharCountFromBytes( LPCSTR pszString, int iBytes ) -{ - int iCount = 0; - int i; - for( i = 0; pszString[i] && i < iBytes; i++ ) - { - iCount++; - if( _IsLeadByte(pszString[i]) ) - i++; - } - if( i != iBytes ) - iCount = -iCount; // indicate error - iBytes specifies wrong boundary (i.e. the last byte is leadbyte) - return iCount; -} - -static int GetCharCount( LPTSTR psz ) -{ - int i = 0; - while( *psz ) - { - if( _IsLeadByte(*psz) ) - { - psz++; - } - psz++; - i++; - } - return i; -} - -static DWORD WA_GetCandidateList( HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList ) -{ - DWORD dwBufLen = ImmGetCandidateListW( himc, dwIndex, NULL, 0 ); - if( dwBufLen ) - { - LPCANDIDATELIST pCandList = ( LPCANDIDATELIST )ImeUiCallback_Malloc( dwBufLen ); - if( pCandList ) - { - dwBufLen = ImmGetCandidateListW( himc, dwIndex, pCandList, dwBufLen ); - if( dwBufLen ) - { - int i; - int mbBufLen = 0; - for( i = 0; i < ( int )pCandList->dwCount; i++ ) - { - mbBufLen += WideCharToMultiByte( g_uCodePage, 0, ( LPWSTR )( ( LPSTR )pCandList + - pCandList->dwOffset[i] ), -1, NULL, 0, - NULL, NULL ); - } - mbBufLen += pCandList->dwOffset[0]; - *ppCandList = ( LPCANDIDATELIST )ImeUiCallback_Malloc( mbBufLen ); - LPCANDIDATELIST pCandListA = *ppCandList; - memcpy( pCandListA, pCandList, pCandList->dwOffset[0] ); - LPSTR psz = ( LPSTR )pCandListA + pCandList->dwOffset[0]; - for( i = 0; i < ( int )pCandList->dwCount; i++ ) - { - pCandListA->dwOffset[i] = ( LPSTR )psz - ( LPSTR )pCandListA; - psz += WideCharToMultiByte( g_uCodePage, 0, ( LPWSTR )( ( LPSTR )pCandList + - pCandList->dwOffset[i] ), -1, psz, 256, - NULL, NULL ); - } - dwBufLen = mbBufLen; - } - ImeUiCallback_Free( pCandList ); - } - } - return dwBufLen; -} - -static LONG WINAPI WA_ImmGetCompositionString( HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen ) -{ - WCHAR pwzUc[COUNTOF(g_szCompositionString)]; - DWORD dwRet = ImmGetCompositionStringW( himc, dwIndex, pwzUc, sizeof( pwzUc ) ); - switch( dwIndex ) - { - case GCS_RESULTSTR: - case GCS_COMPSTR: - if( dwRet ) - { - pwzUc[dwRet / sizeof( WCHAR )] = 0; - dwRet = ( DWORD )WideCharToMultiByte( g_uCodePage, 0, pwzUc, -1, ( LPSTR )lpBuf, dwBufLen, NULL, - NULL ); - if( dwRet ) - { - dwRet = dwRet - 1; - } - } - break; - - case GCS_CURSORPOS: - { - WCHAR pwzUc2[COUNTOF(g_szCompositionString)]; - DWORD dwRet2 = ImmGetCompositionStringW( himc, GCS_COMPSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - dwRet2 = ImmGetCompositionStringW( himc, GCS_RESULTSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - return 0; - } - } - dwRet2 /= 2; - //The return value of WideCharToMultiByte() should probably be checked/asserted for success. - //bounds violation (overflow) 'pszMb[iRc]' - const int bufSize = COUNTOF(g_szCompositionString) * 2; - char pszMb[bufSize]; - int iRc = WideCharToMultiByte( g_uCodePage, 0, pwzUc2, dwRet2, pszMb, sizeof( pszMb ), NULL, NULL ); - assert( iRc > 0 ); //WideCharToMultiByte returns 0 if it failed, and it should *never* be negative in the first place - if( iRc >= bufSize ) //if we wrote more bytes than the length of the buffer, we need to terminate it - { - pszMb[ bufSize - 1] = 0; //0 terminate the end of the buffer - } - else - { - pszMb[ iRc ] = 0; - } - char* psz = pszMb; - for( dwRet2 = 0; dwRet2 != dwRet; dwRet2++ ) - { - if( _IsLeadByte( *psz ) ) - psz++; - psz++; - } - dwRet = psz - pszMb; - } - break; - - case GCS_COMPATTR: - { - WCHAR pwzUc2[COUNTOF(g_szCompositionString)]; - DWORD dwRet2 = ImmGetCompositionStringW( himc, GCS_COMPSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - dwRet2 = ImmGetCompositionStringW( himc, GCS_RESULTSTR, pwzUc2, sizeof( pwzUc2 ) ); - if( !dwRet2 ) - { - return 0; - } - } - dwRet2 /= 2; - const int bufSize = COUNTOF(g_szCompositionString) * 2; - char pszMb[bufSize]; - int iRc = WideCharToMultiByte( g_uCodePage, 0, pwzUc2, dwRet2, pszMb, sizeof( pszMb ), NULL, NULL ); - assert( iRc > 0 ); //WideCharToMultiByte returns 0 if it failed, and it should *never* be negative in the first place - if( iRc >= bufSize ) //if we wrote more bytes than the length of the buffer, we need to terminate it - { - pszMb[ bufSize - 1] = 0; //0 terminate the end of the buffer - } - else - { - pszMb[ iRc ] = 0; - } - char* pSrc = ( char* )pwzUc; - char* pOut = ( char* )lpBuf; - for( char* psz = pszMb; *psz; psz++, pSrc++ ) - { - *pOut++ = *pSrc; // copy attribute - if( _IsLeadByte( *psz ) ) - { - *pOut++ = *pSrc; - psz++; - } - // buffer overrun protection, pOut is incremented in the loop, but not part of the - // loop invariant test. To make the code more readable we have a test rather than - // rolling this into the for stmt. - if( ( DWORD )( pOut - ( char* )lpBuf ) >= dwBufLen ) - break; - } - dwRet = pOut - ( char* )lpBuf; - } - break; - } - return dwRet; -} - -#endif // UNICODE static void ComposeCandidateLine( int index, LPCTSTR pszCandidate ) { @@ -746,17 +468,11 @@ static void ComposeCandidateLine( int index, LPCTSTR pszCandidate ) static void SendCompString() { - int i, iLen = lstrlen( g_szCompositionString ); + int i, iLen = (int)wcslen( g_szCompositionString ); if( ImeUiCallback_OnChar ) { LPCWSTR pwz; -#ifdef UNICODE - pwz = g_szCompositionString; -#else - WCHAR szUnicode[COUNTOF( g_szCompositionString ) ]; - pwz = szUnicode; - iLen = MultiByteToWideChar( g_uCodePage, 0, g_szCompositionString, -1, szUnicode, COUNTOF(szUnicode) ) - 1; -#endif + pwz = g_szCompositionString; for( i = 0; i < iLen; i++ ) { ImeUiCallback_OnChar( pwz[i] ); @@ -766,18 +482,14 @@ static void SendCompString() for( i = 0; i < iLen; i++ ) { SendKeyMsg( g_hwndCurr, WM_CHAR, -#ifdef UNICODE - (WPARAM)g_szCompositionString[i] -#else - ( WPARAM )( BYTE )g_szCompositionString[i] -#endif + (WPARAM)g_szCompositionString[i] ); } } static DWORD GetCandidateList( HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList ) { - DWORD dwBufLen = _ImmGetCandidateList( himc, dwIndex, NULL, 0 ); + DWORD dwBufLen = _ImmGetCandidateList( himc, dwIndex, nullptr, 0 ); if( dwBufLen ) { *ppCandList = ( LPCANDIDATELIST )ImeUiCallback_Malloc( dwBufLen ); @@ -833,7 +545,7 @@ static void CancelCompString( HWND hwnd, bool bUseBackSpace = true, int iNewStrL } // initialize composition string data. -static void InitCompStringData( void ) +static void InitCompStringData() { g_IMECursorBytes = 0; g_IMECursorChars = 0; @@ -856,7 +568,7 @@ static void DrawCaret( DWORD x, DWORD y, DWORD height ) // // Draw text in the edit box; // ImeUi_RenderUi(false, true); // paint the rest of IME UI; // -void ImeUi_RenderUI( bool bDrawCompAttr, bool bDrawOtherUi ) +void ImeUi_RenderUI( _In_ bool bDrawCompAttr, _In_ bool bDrawOtherUi ) { if( !g_bInitialized || !g_bImeEnabled || !g_CaretInfo.pFont ) return; @@ -936,7 +648,7 @@ static void DrawImeIndicator() swirl = 0; for( int t1 = 1; t1 < 16; t1++ ) { - float radian = 2.0f * 3.1415926f * ( t1 - 1 + ( bOn * swirl ) ) / 14.0f; + float radian = 2.0f * 3.1415926f * ( t1 - 1 + ( DWORD(bOn) * swirl ) ) / 14.0f; PieData[t1].sx = ( float )( PieData[0].sx + SizeOfPie / 2 * cos( radian ) ); PieData[t1].sy = ( float )( PieData[0].sy + SizeOfPie / 2 * sin( radian ) ); PieData[t1].rhw = 1.0f; @@ -987,9 +699,9 @@ static void DrawImeIndicator() if( gSkinIME.symbolFont ) { #ifdef DS2 - // save the font height here since DS2 shares editbox font and indicator font - DWORD _w, _h; - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h ); + // save the font height here since DS2 shares editbox font and indicator font + DWORD _w, _h; + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h ); #endif //DS2 // GOS deals height in points that is 1/72nd inch and assumes display device is 96dpi. @@ -1008,33 +720,33 @@ static void DrawImeIndicator() gSkinIME.symbolFont->DrawText( cszSymbol ); #ifdef DS2 - // revert the height. - g_CaretInfo.pFont->SetHeight( _h ); - - // Double-check: Confirm match by testing a range of font heights to find best fit - DWORD _h2; - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); - if ( _h2 < _h ) - { - for ( int i=1; _h2<_h && i<10; i++ ) - { - g_CaretInfo.pFont->SetHeight( _h+i ); - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); - } - } - else if ( _h2 > _h ) - { - for ( int i=1; _h2>_h && i<10; i++ ) - { - g_CaretInfo.pFont->SetHeight( _h-i ); - g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); - } - } + // revert the height. + g_CaretInfo.pFont->SetHeight( _h ); + + // Double-check: Confirm match by testing a range of font heights to find best fit + DWORD _h2; + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); + if ( _h2 < _h ) + { + for ( int i=1; _h2<_h && i<10; i++ ) + { + g_CaretInfo.pFont->SetHeight( _h+i ); + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); + } + } + else if ( _h2 > _h ) + { + for ( int i=1; _h2>_h && i<10; i++ ) + { + g_CaretInfo.pFont->SetHeight( _h-i ); + g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 ); + } + } #endif //DS2 } } -static void DrawCompositionString( bool bDrawCompAttr ) +static void DrawCompositionString( _In_ bool bDrawCompAttr ) { // Process timer for caret blink UINT uCurrentTime = GetTickCount(); @@ -1050,7 +762,7 @@ static void DrawCompositionString( bool bDrawCompAttr ) DWORD uDummy; - int len = lstrlen( g_szCompositionString ); + int len = (int)wcslen( g_szCompositionString ); DWORD bgX = g_CaretInfo.caretX; DWORD bgY = g_CaretInfo.caretY; @@ -1089,11 +801,6 @@ static void DrawCompositionString( bool bDrawCompAttr ) TCHAR szChar[3]; szChar[0] = g_szCompositionString[i]; szChar[1] = szChar[2] = 0; -#ifndef UNICODE - cType = 1 + ( ( _IsLeadByte(g_szCompositionString[i]) ) ? 1 : 0 ); - if( cType == 2 && g_szCompositionString[i + 1] ) // in case we have 0 in trailbyte, we don't count it. - szChar[1] = g_szCompositionString[i + 1]; -#endif bgX = bgXnext; TCHAR cSave = g_szCompositionString[i + cType]; g_szCompositionString[i + cType] = 0; @@ -1169,10 +876,6 @@ static void DrawCompositionString( bool bDrawCompAttr ) if( bWrite ) { *pszMlcs++ = g_szCompositionString[i]; -#ifndef UNICODE - if( cType == 2 ) - *pszMlcs++ = g_szCompositionString[i + 1]; -#endif } if( ( DWORD )i == g_IMECursorBytes ) { @@ -1214,7 +917,7 @@ static void DrawCompositionString( bool bDrawCompAttr ) { g_CaretInfo.pFont->SetPosition( x, y ); g_CaretInfo.pFont->DrawText( pszMlcs ); - pszMlcs += lstrlen( pszMlcs ) + 1; + pszMlcs += wcslen( pszMlcs ) + 1; x = g_CaretInfo.margins.left; y += hCompChar; } @@ -1231,6 +934,8 @@ static void DrawCompositionString( bool bDrawCompAttr ) static void DrawCandidateList() { + assert( g_CaretInfo.pFont != nullptr ); + _Analysis_assume_( g_CaretInfo.pFont != nullptr ); DWORD candX = g_dwCandX; DWORD candY = g_dwCandY; DWORD hCompChar = g_hCompChar; @@ -1267,7 +972,7 @@ static void DrawCandidateList() static DWORD uDigitWidth = 0; DWORD uSpaceWidth = 0; static DWORD uDigitWidthList[10]; - static CImeUiFont_Base* pPrevFont = NULL; + static CImeUiFont_Base* pPrevFont = nullptr; // find out the widest width of the digits if( pPrevFont != g_CaretInfo.pFont ) { @@ -1406,13 +1111,9 @@ static void DrawCandidateList() TCHAR szTemp[COUNTOF( g_szReadingString ) ]; if( g_iReadingError >= 0 ) { - StringCchCopy( szTemp, COUNTOF(szTemp), g_szReadingString ); + wcscpy_s( szTemp, COUNTOF(szTemp), g_szReadingString ); LPTSTR psz = szTemp + g_iReadingError; -#ifdef UNICODE - psz++; -#else - psz += ( _IsLeadByte( szTemp[g_iReadingError] ) ) ? 2 : 1; -#endif + psz++; *psz = 0; g_CaretInfo.pFont->GetTextExtent( szTemp, ( DWORD* )&iEnd, ( DWORD* )&iDummy ); TCHAR cSave = szTemp[ g_iReadingError ]; @@ -1477,7 +1178,7 @@ static void DrawCandidateList() int dx = candX + ( seperateLineX - candX - uDigitWidthList[nOneDigit] ) / 2; int dy = candY + largest.cy * i; - + g_CaretInfo.pFont->SetPosition( dx, dy ); g_CaretInfo.pFont->DrawText( szOneDigit ); g_CaretInfo.pFont->SetPosition( seperateLineX + dwMarginX, dy ); @@ -1519,6 +1220,9 @@ static void CloseCandidateList() // ProcessIMEMessages() // Processes IME related messages and acquire information // +#pragma warning(push) +#pragma warning( disable : 4616 6305 ) +_Use_decl_annotations_ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam, bool* trapped ) { HIMC himc; @@ -1559,7 +1263,8 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam TCHAR szCompStr[COUNTOF(g_szCompositionString)]; *trapped = true; - if( NULL == ( himc = _ImmGetContext( hWnd ) ) ) + himc = ImmGetContext( hWnd ); + if( !himc ) { break; } @@ -1571,7 +1276,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam COUNTOF( szCompStr ) ) / sizeof( TCHAR ); szCompStr[lRet] = 0; CancelCompString( g_hwndCurr, false, GetCharCount( szCompStr ) ); - StringCchCopy( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); + wcscpy_s( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); _SendCompString(); InitCompStringData(); } @@ -1590,14 +1295,14 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam // CancelCompString( g_hwndCurr, false, GetCharCount( szCompStr ) ); - StringCchCopy( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); + wcscpy_s( g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr ); lRet = _ImmGetCompositionString( himc, GCS_COMPATTR, g_szCompAttrString, COUNTOF( g_szCompAttrString ) ); g_szCompAttrString[lRet] = 0; // Older CHT IME uses composition string for reading string if( GETLANG() == LANG_CHT && !GetImeId() ) { - int i, chars = lstrlen( g_szCompositionString ) / ( 3 - sizeof( TCHAR ) ); + int i, chars = (int)wcslen( g_szCompositionString ) / ( 3 - sizeof( TCHAR ) ); if( chars ) { g_dwCount = 4; @@ -1609,14 +1314,8 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam g_szCandidate[i][0] = 0; else { -#ifdef UNICODE - g_szCandidate[i][0] = g_szCompositionString[i]; - g_szCandidate[i][1] = 0; -#else - g_szCandidate[i][0] = g_szCompositionString[i * 2]; - g_szCandidate[i][1] = g_szCompositionString[i * 2 + 1]; - g_szCandidate[i][2] = 0; -#endif + g_szCandidate[i][0] = g_szCompositionString[i]; + g_szCandidate[i][1] = 0; } } g_uCandPageSize = MAX_CANDLIST; @@ -1630,7 +1329,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam for( i = 0; i < ( int )g_dwCount; i++ ) { if( g_dwSelection == ( DWORD )i ) - g_iReadingError = lstrlen( g_szReadingString ); + g_iReadingError = (int)wcslen( g_szReadingString ); LPCTSTR pszTmp = g_szCandidate[i]; wcscat_s( g_szReadingString, COUNTOF(g_szReadingString), pszTmp ); } @@ -1641,7 +1340,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } // get caret position in composition string - g_IMECursorBytes = _ImmGetCompositionString( himc, GCS_CURSORPOS, NULL, 0 ); + g_IMECursorBytes = _ImmGetCompositionString( himc, GCS_CURSORPOS, nullptr, 0 ); g_IMECursorChars = GetCharCountFromBytes( g_szCompositionString, g_IMECursorBytes ); if( g_dwIMELevel == 3 ) @@ -1686,7 +1385,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam break; CheckToggleState(); break; - + case IMN_OPENCANDIDATE: case IMN_CHANGECANDIDATE: if( g_bUILessMode ) @@ -1696,9 +1395,10 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam { g_bCandList = true; *trapped = true; - if( NULL == ( himc = _ImmGetContext( hWnd ) ) ) + himc = _ImmGetContext( hWnd ); + if( !himc ) break; - + LPCANDIDATELIST lpCandList; DWORD dwIndex, dwBufLen; @@ -1721,8 +1421,8 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam UINT i; for( i = 0; i < g_dwCount; i++ ) { - UINT uLen = lstrlen( - ( LPTSTR )( ( DWORD )lpCandList + lpCandList->dwOffset[i] ) ) + + UINT uLen = (int)wcslen( + ( LPTSTR )( (UINT_PTR)lpCandList + lpCandList->dwOffset[i] ) ) + ( 3 - sizeof( TCHAR ) ); if( uLen + cChars > maxCandChar ) { @@ -1742,7 +1442,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } else { - g_uCandPageSize = min( lpCandList->dwPageSize, MAX_CANDLIST ); + g_uCandPageSize = std::min<UINT>( lpCandList->dwPageSize, MAX_CANDLIST ); startOfPage = g_bUILessMode ? lpCandList->dwPageStart : ( g_dwSelection / g_uCandPageSize ) * g_uCandPageSize; } @@ -1756,7 +1456,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam i++, j++ ) { ComposeCandidateLine( j, - ( LPTSTR )( ( DWORD )lpCandList + lpCandList->dwOffset[i] ) ); + ( LPTSTR )( (UINT_PTR)lpCandList + lpCandList->dwOffset[i] ) ); } ImeUiCallback_Free( ( HANDLE )lpCandList ); _ImmReleaseContext( hWnd, himc ); @@ -1768,7 +1468,7 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } break; } - + case IMN_CLOSECANDIDATE: if( g_bUILessMode ) { @@ -1859,7 +1559,9 @@ LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam } return 0; } +#pragma warning(pop) +_Use_decl_annotations_ void ImeUi_SetCaretPosition( UINT x, UINT y ) { if( !g_bInitialized ) @@ -1868,6 +1570,7 @@ void ImeUi_SetCaretPosition( UINT x, UINT y ) g_CaretInfo.caretY = y; } +_Use_decl_annotations_ void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const RECT* prc ) { if( !g_bInitialized ) @@ -1885,7 +1588,7 @@ void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const R g_CaretInfo.colorComp = gSkinIME.compColorText; } -void ImeUi_SetState( DWORD dwState ) +void ImeUi_SetState( _In_ DWORD dwState ) { if( !g_bInitialized ) return; @@ -1894,7 +1597,8 @@ void ImeUi_SetState( DWORD dwState ) { ImeUi_EnableIme( true ); } - if( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) ) + himc = _ImmGetContext( g_hwndCurr ); + if( himc ) { if( g_bDisableImeCompletely ) dwState = IMEUI_STATE_OFF; @@ -1951,7 +1655,7 @@ DWORD ImeUi_GetState() return g_dwState; } -void ImeUi_EnableIme( bool bEnable ) +void ImeUi_EnableIme( _In_ bool bEnable ) { if( !g_bInitialized || !g_hwndCurr ) return; @@ -1961,7 +1665,7 @@ void ImeUi_EnableIme( bool bEnable ) if( g_hwndCurr == g_hwndMain ) { HIMC himcDbg; - himcDbg = _ImmAssociateContext( g_hwndCurr, bEnable? g_himcOrg : NULL ); + himcDbg = _ImmAssociateContext( g_hwndCurr, bEnable? g_himcOrg : nullptr ); } g_bImeEnabled = bEnable; if( bEnable ) @@ -1971,12 +1675,12 @@ void ImeUi_EnableIme( bool bEnable ) CTsfUiLessMode::EnableUiUpdates( bEnable ); } -bool ImeUi_IsEnabled( void ) +bool ImeUi_IsEnabled() { return g_bImeEnabled; } -bool ImeUi_Initialize( HWND hwnd, bool bDisable ) +bool ImeUi_Initialize(_In_ HWND hwnd, _In_ bool bDisable ) { if( g_bInitialized ) { @@ -1985,29 +1689,17 @@ bool ImeUi_Initialize( HWND hwnd, bool bDisable ) g_hwndMain = hwnd; g_disableCicero.Initialize(); - g_osi.dwOSVersionInfoSize = sizeof( OSVERSIONINFOA ); - GetVersionExA( &g_osi ); - - bool bUnicodeImm = false; - // IMM in NT or Win98 supports Unicode - if( g_osi.dwPlatformId == VER_PLATFORM_WIN32_NT || - ( g_osi.dwMajorVersion > 4 ) || - ( g_osi.dwMajorVersion == 4 ) && ( g_osi.dwMinorVersion > 0 ) ) - { - bUnicodeImm = true; - } - - g_hImmDll = LoadLibraryA( "imm32.dll" ); + g_hImmDll = LoadLibraryEx( L"imm32.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); g_bDisableImeCompletely = false; if( g_hImmDll ) { - _ImmLockIMC = ( LPINPUTCONTEXT2 ( WINAPI* )( HIMC hIMC ) )GetProcAddress( g_hImmDll, "ImmLockIMC" ); - _ImmUnlockIMC = ( BOOL ( WINAPI* )( HIMC hIMC ) )GetProcAddress( g_hImmDll, "ImmUnlockIMC" ); - _ImmLockIMCC = ( LPVOID ( WINAPI* )( HIMCC hIMCC ) )GetProcAddress( g_hImmDll, "ImmLockIMCC" ); - _ImmUnlockIMCC = ( BOOL ( WINAPI* )( HIMCC hIMCC ) )GetProcAddress( g_hImmDll, "ImmUnlockIMCC" ); - BOOL ( WINAPI* _ImmDisableTextFrameService )( DWORD ) = ( BOOL ( WINAPI* )( DWORD ) )GetProcAddress( g_hImmDll, - "ImmDisableTextFrameService" ); + _ImmLockIMC = reinterpret_cast<LPINPUTCONTEXT2 ( WINAPI* )( HIMC hIMC )>( reinterpret_cast<void*>( GetProcAddress( g_hImmDll, "ImmLockIMC" ) ) ); + _ImmUnlockIMC = reinterpret_cast<BOOL ( WINAPI* )( HIMC hIMC )>( reinterpret_cast<void*>( GetProcAddress( g_hImmDll, "ImmUnlockIMC" ) ) ); + _ImmLockIMCC = reinterpret_cast<LPVOID ( WINAPI* )( HIMCC hIMCC )>( reinterpret_cast<void*>( GetProcAddress( g_hImmDll, "ImmLockIMCC" ) ) ); + _ImmUnlockIMCC = reinterpret_cast<BOOL ( WINAPI* )( HIMCC hIMCC )>( reinterpret_cast<void*>( GetProcAddress( g_hImmDll, "ImmUnlockIMCC" ) ) ); + BOOL ( WINAPI* _ImmDisableTextFrameService )( DWORD ) = reinterpret_cast<BOOL ( WINAPI* )( DWORD )>( reinterpret_cast<void*>( GetProcAddress( g_hImmDll, + "ImmDisableTextFrameService" ) ) ); if( _ImmDisableTextFrameService ) { _ImmDisableTextFrameService( ( DWORD )-1 ); @@ -2018,52 +1710,11 @@ bool ImeUi_Initialize( HWND hwnd, bool bDisable ) g_bDisableImeCompletely = true; return false; } -#ifdef UNICODE - if ( bUnicodeImm ) - { - _ImmGetCompositionString = ImmGetCompositionStringW; - _ImmGetCandidateList = ImmGetCandidateListW; - _GetCandidateList = GetCandidateList; - } - else - { - _ImmGetCandidateList = ImmGetCandidateListA; - _ImmGetCompositionString = AW_ImmGetCompositionString; - _GetCandidateList = AW_GetCandidateList; - } -#else - if( bUnicodeImm ) - { - _ImmGetCompositionString = WA_ImmGetCompositionString; - _ImmGetCandidateList = ImmGetCandidateListA; - _GetCandidateList = WA_GetCandidateList; - } - else - { - _ImmGetCompositionString = ImmGetCompositionStringA; - _ImmGetCandidateList = ImmGetCandidateListA; - _GetCandidateList = GetCandidateList; - } -#endif - - // There are the following combinations of code config, window type, and the method of sending characters. - // Wnd: Unicode, Code: Unicode, Method: SendMessageW (SendMessageW must be supported since RegisterClassW is successful) - // Wnd: non Uni, Code: Unicode, Method: AW_SendCompString (Send characters in multibyte after W->A conversion) - // Wnd: Unicode, Code: non Uni, Method: SendMessageA (System does A->W conversion) - possible, but unlikely to be used. - // Wnd: non Uni, Code: non Uni, Method: SendMessageA -#ifdef UNICODE - if ( !IsWindowUnicode( hwnd ) ) - { - _SendCompString = AW_SendCompString; - } - else -#endif - { - _SendCompString = SendCompString; -#ifdef UNICODE - _SendMessage = SendMessageW; -#endif - } + _ImmGetCompositionString = ImmGetCompositionStringW; + _ImmGetCandidateList = ImmGetCandidateListW; + _GetCandidateList = GetCandidateList; + _SendCompString = SendCompString; + _SendMessage = SendMessageW; // turn init flag on so that subsequent calls to ImeUi functions work. g_bInitialized = true; @@ -2091,19 +1742,6 @@ bool ImeUi_Initialize( HWND hwnd, bool bDisable ) g_uCaretBlinkTime = GetCaretBlinkTime(); -#ifndef UNICODE - // Check if system is SBCS system - CPINFO cpi; - BOOL bRc = GetCPInfo( CP_ACP, &cpi ); - if( bRc ) - { - if( cpi.MaxCharSize == 1 ) - { - g_bDisableImeCompletely = true; // SBCS system. Disable IME. - } - } -#endif - g_CaretInfo.caretX = 0; g_CaretInfo.caretY = 0; g_CaretInfo.pFont = 0; @@ -2142,12 +1780,12 @@ void ImeUi_Uninitialize() { ImmAssociateContext( g_hwndMain, g_himcOrg ); } - g_hwndMain = NULL; - g_himcOrg = NULL; + g_hwndMain = nullptr; + g_himcOrg = nullptr; if( g_hImmDll ) { FreeLibrary( g_hImmDll ); - g_hImmDll = NULL; + g_hImmDll = nullptr; } g_disableCicero.Uninitialize(); g_bInitialized = false; @@ -2172,14 +1810,14 @@ void ImeUi_Uninitialize() // // Use IMEID_VER and IMEID_LANG macro to extract version and language information. // -static DWORD GetImeId( UINT uIndex ) +static DWORD GetImeId( _In_ UINT uIndex ) { static HKL hklPrev = 0; static DWORD dwRet[2] = { 0, 0 }; - + DWORD dwVerSize; DWORD dwVerHandle; LPVOID lpVerBuffer; @@ -2196,7 +1834,7 @@ static DWORD GetImeId( UINT uIndex ) return dwRet[uIndex]; } hklPrev = kl; - DWORD dwLang = ( ( DWORD )kl & 0xffff ); + DWORD dwLang = ( static_cast<DWORD>(reinterpret_cast<UINT_PTR>(kl)) & 0xffff ); if( g_bUILessMode && GETLANG() == LANG_CHT ) { @@ -2211,7 +1849,7 @@ static DWORD GetImeId( UINT uIndex ) { goto error; } - + if( _ImmGetIMEFileNameA( kl, szTmp, sizeof( szTmp ) - 1 ) <= 0 ) { goto error; @@ -2237,7 +1875,7 @@ static DWORD GetImeId( UINT uIndex ) lpVerBuffer = ( LPVOID )ImeUiCallback_Malloc( dwVerSize ); if( lpVerBuffer ) { - if( GetFileVersionInfoA( szTmp, dwVerHandle, dwVerSize, lpVerBuffer ) ) + if( GetFileVersionInfoA( szTmp, 0, dwVerSize, lpVerBuffer ) ) { if( VerQueryValueA( lpVerBuffer, "\\", &lpVerData, &cbVerData ) ) { @@ -2267,10 +1905,9 @@ static DWORD GetImeId( UINT uIndex ) #undef pVerFixedInfo } } + ImeUiCallback_Free( lpVerBuffer ); } - ImeUiCallback_Free( lpVerBuffer ); } - // The flow comes here in the following conditions // - Non Chinese IME input locale // - Older Chinese IME @@ -2280,7 +1917,7 @@ error: return dwRet[uIndex]; } -static void GetReadingString( HWND hWnd ) +static void GetReadingString( _In_ HWND hWnd ) { if( g_bUILessMode ) { @@ -2291,7 +1928,7 @@ static void GetReadingString( HWND hWnd ) { return; } - + HIMC himc; himc = _ImmGetContext( hWnd ); if( !himc ) @@ -2302,13 +1939,13 @@ static void GetReadingString( HWND hWnd ) WCHAR wzBuf[16]; // We believe 16 wchars are big enough to hold reading string after having discussion with CHT IME team. WCHAR* wstr = wzBuf; bool unicode = FALSE; - LPINPUTCONTEXT2 lpIMC = NULL; + LPINPUTCONTEXT2 lpIMC = nullptr; if( _GetReadingString ) { BOOL bVertical; UINT uMaxUiLen; - dwlen = _GetReadingString( himc, 0, NULL, ( PINT )&dwerr, &bVertical, &uMaxUiLen ); + dwlen = _GetReadingString( himc, 0, nullptr, ( PINT )&dwerr, &bVertical, &uMaxUiLen ); if( dwlen ) { if( dwlen > COUNTOF(wzBuf) ) @@ -2324,18 +1961,18 @@ static void GetReadingString( HWND hWnd ) else // IMEs that doesn't implement Reading String API { lpIMC = _ImmLockIMC( himc ); - + // *** hacking code from Michael Yang *** - + LPBYTE p = 0; - + switch( dwId ) { - + case IMEID_CHT_VER42: // New(Phonetic/ChanJie)IME98 : 4.2.x.x // Win98 case IMEID_CHT_VER43: // New(Phonetic/ChanJie)IME98a : 4.3.x.x // WinMe, Win2k case IMEID_CHT_VER44: // New ChanJie IME98b : 4.4.x.x // WinXP - + p = *( LPBYTE* )( ( LPBYTE )_ImmLockIMCC( lpIMC->hPrivate ) + 24 ); if( !p ) break; dwlen = *( DWORD* )( p + 7 * 4 + 32 * 4 ); //m_dwInputReadStrLen @@ -2343,9 +1980,9 @@ static void GetReadingString( HWND hWnd ) wstr = ( WCHAR* )( p + 56 ); unicode = TRUE; break; - + case IMEID_CHT_VER50: // 5.0.x.x // WinME - + p = *( LPBYTE* )( ( LPBYTE )_ImmLockIMCC( lpIMC->hPrivate ) + 3 * 4 ); // PCKeyCtrlManager if( !p ) break; p = *( LPBYTE* )( ( LPBYTE )p + 1 * 4 + 5 * 4 + 4 * 2 ); // = PCReading = &STypingInfo @@ -2380,7 +2017,7 @@ static void GetReadingString( HWND hWnd ) if( !p ) break; dwlen = *( DWORD* )( p + 7 * 4 + 16 * 2 * 4 ); dwerr = *( DWORD* )( p + 8 * 4 + 16 * 2 * 4 ); - dwerr = min( dwerr, dwlen ); + dwerr = std::min( dwerr, dwlen ); wstr = ( WCHAR* )( p + 6 * 4 + 16 * 2 * 1 ); unicode = TRUE; break; @@ -2397,7 +2034,7 @@ static void GetReadingString( HWND hWnd ) unicode = IsNT() ? TRUE : FALSE; } } // switch - + g_szCandidate[0][0] = 0; g_szCandidate[1][0] = 0; g_szCandidate[2][0] = 0; @@ -2414,19 +2051,8 @@ static void GetReadingString( HWND hWnd ) { // select error char g_dwSelection = i; } -#ifdef UNICODE - g_szCandidate[i][0] = wstr[i]; - g_szCandidate[i][1] = 0; -#else - char mbc[3]; - mbc[1] = 0; - mbc[2] = 0; - WideCharToMultiByte( g_uCodePage, 0, wstr + i, 1, mbc, sizeof( mbc ), NULL, NULL ); - - g_szCandidate[i][0] = mbc[0]; - g_szCandidate[i][1] = mbc[1]; - g_szCandidate[i][2] = 0; -#endif + g_szCandidate[i][0] = wstr[i]; + g_szCandidate[i][1] = 0; } g_szCandidate[i][0] = 0; } @@ -2440,23 +2066,12 @@ static void GetReadingString( HWND hWnd ) { g_dwSelection = ( DWORD )j; } -#ifdef UNICODE - MultiByteToWideChar( g_uCodePage, 0, p + i, 1 + ( _IsLeadByte( p[i] ) ? 1 : 0 ), - g_szCandidate[j], 1 ); - if ( _IsLeadByte( p[i] ) ) - { - i++; - } -#else - g_szCandidate[j][0] = p[i]; - g_szCandidate[j][1] = 0; - g_szCandidate[j][2] = 0; - if( _IsLeadByte(p[i]) ) + MultiByteToWideChar( g_uCodePage, 0, p + i, 1 + ( _IsLeadByte( p[i] ) ? 1 : 0 ), + g_szCandidate[j], 1 ); + if ( _IsLeadByte( p[i] ) ) { i++; - g_szCandidate[j][1] = p[i]; } -#endif } g_szCandidate[j][0] = 0; g_dwCount = j; @@ -2477,7 +2092,7 @@ static void GetReadingString( HWND hWnd ) for( UINT i = 0; i < g_dwCount; i++ ) { if( g_dwSelection == ( DWORD )i ) - g_iReadingError = lstrlen( g_szReadingString ); + g_iReadingError = (int)wcslen( g_szReadingString ); LPCTSTR pszTmp = g_szCandidate[i]; wcscat_s( g_szReadingString, COUNTOF(g_szReadingString), pszTmp ); } @@ -2525,7 +2140,7 @@ static struct // - Caller doesn't have to check whether IME is on. // - This function must be called before TranslateMessage() is called. // -bool ImeUi_IgnoreHotKey( const MSG* pmsg ) +bool ImeUi_IgnoreHotKey( _In_ const MSG* pmsg ) { if( !g_bInitialized || !pmsg ) return false; @@ -2567,34 +2182,29 @@ bool ImeUi_IgnoreHotKey( const MSG* pmsg ) return false; } -void ImeUi_FinalizeString( bool bSend ) +void ImeUi_FinalizeString( _In_ bool bSend ) { HIMC himc; static bool bProcessing = false; // to avoid infinite recursion - if( !g_bInitialized || bProcessing || NULL == ( himc = _ImmGetContext( g_hwndCurr ) ) ) + if( !g_bInitialized || bProcessing ) + return; + + himc = _ImmGetContext( g_hwndCurr ); + if ( !himc ) return; bProcessing = true; if( g_dwIMELevel == 2 && bSend ) { // Send composition string to app. - LONG lRet = lstrlen( g_szCompositionString ); + LONG lRet = (int)wcslen( g_szCompositionString ); assert( lRet >= 2 ); // In case of CHT IME, don't send the trailing double byte space, if it exists. -#ifdef UNICODE - if ( GETLANG() == LANG_CHT && (lRet >= 1) - && g_szCompositionString[lRet - 1] == 0x3000 ) - { - lRet--; - } -#else - if( GETLANG() == LANG_CHT && ( lRet >= 2 ) - && ( BYTE )( g_szCompositionString[lRet - 2] ) == 0xa1 - && ( BYTE )( g_szCompositionString[lRet - 1] ) == 0x40 ) + if ( GETLANG() == LANG_CHT && (lRet >= 1) + && g_szCompositionString[lRet - 1] == 0x3000 ) { - lRet -= 2; + lRet--; } -#endif _SendCompString(); } @@ -2604,7 +2214,7 @@ void ImeUi_FinalizeString( bool bSend ) if( g_bUILessMode ) { // For some reason ImmNotifyIME doesn't work on DaYi and Array CHT IMEs. Cancel composition string by setting zero-length string. - ImmSetCompositionString( himc, SCS_SETSTR, TEXT( "" ), sizeof( TCHAR ), TEXT( "" ), sizeof( TCHAR ) ); + ImmSetCompositionString( himc, SCS_SETSTR, const_cast<wchar_t*>(L""), sizeof(wchar_t), const_cast<char*>(""), sizeof(wchar_t) ); } // the following line is necessary as Korean IME doesn't close cand list when comp string is cancelled. _ImmNotifyIME( himc, NI_CLOSECANDIDATE, 0, 0 ); @@ -2627,7 +2237,7 @@ static void SetCompStringColor() gSkinCompStr.colorInputErr = dwTranslucency | gSkinIME.compColorInputErr; } -static void SetSupportLevel( DWORD dwImeLevel ) +static void SetSupportLevel( _In_ DWORD dwImeLevel ) { if( dwImeLevel < 2 || 3 < dwImeLevel ) return; @@ -2641,7 +2251,7 @@ static void SetSupportLevel( DWORD dwImeLevel ) SetCompStringColor(); } -void ImeUi_SetSupportLevel( DWORD dwImeLevel ) +void ImeUi_SetSupportLevel( _In_ DWORD dwImeLevel ) { if( !g_bInitialized ) return; @@ -2649,9 +2259,9 @@ void ImeUi_SetSupportLevel( DWORD dwImeLevel ) SetSupportLevel( dwImeLevel ); } -void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia ) +void ImeUi_SetAppearance( _In_opt_ const IMEUI_APPEARANCE* pia ) { - if( !g_bInitialized || NULL == pia ) + if( !g_bInitialized || !pia ) return; gSkinIME = *pia; gSkinIME.symbolColor &= 0xffffff; // mask translucency @@ -2665,11 +2275,18 @@ void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia ) SetCompStringColor(); } -void ImeUi_GetAppearance( IMEUI_APPEARANCE* pia ) +void ImeUi_GetAppearance( _Out_opt_ IMEUI_APPEARANCE* pia ) { - if( g_bInitialized && pia ) + if ( pia ) { - *pia = gSkinIME; + if ( g_bInitialized ) + { + *pia = gSkinIME; + } + else + { + memset( pia, 0, sizeof(IMEUI_APPEARANCE) ); + } } } @@ -2686,11 +2303,11 @@ static void CheckToggleState() } bool bIme = _ImmIsIME( g_hklCurrent ) != 0 - && ( ( 0xF0000000 & ( DWORD )g_hklCurrent ) == 0xE0000000 ); // Hack to detect IME correctly. When IME is running as TIP, ImmIsIME() returns true for CHT US keyboard. + && ( ( 0xF0000000 & static_cast<DWORD>( reinterpret_cast<UINT_PTR>( g_hklCurrent ) ) ) == 0xE0000000 ); // Hack to detect IME correctly. When IME is running as TIP, ImmIsIME() returns true for CHT US keyboard. g_bChineseIME = ( GETPRIMLANG() == LANG_CHINESE ) && bIme; - HIMC himc; - if( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) ) + HIMC himc = _ImmGetContext( g_hwndCurr ); + if( himc ) { if( g_bChineseIME ) { @@ -2708,7 +2325,7 @@ static void CheckToggleState() g_dwState = IMEUI_STATE_OFF; } -void ImeUi_SetInsertMode( bool bInsert ) +void ImeUi_SetInsertMode( _In_ bool bInsert ) { if( !g_bInitialized ) return; @@ -2720,7 +2337,7 @@ bool ImeUi_GetCaretStatus() return !g_bInitialized || !g_szCompositionString[0]; } -void ImeUi_SetScreenDimension( UINT width, UINT height ) +void ImeUi_SetScreenDimension( _In_ UINT width, _In_ UINT height ) { if( !g_bInitialized ) return; @@ -2732,9 +2349,9 @@ void ImeUi_SetScreenDimension( UINT width, UINT height ) static void _PumpMessage() { MSG msg; - while( PeekMessageA( &msg, NULL, 0, 0, PM_NOREMOVE ) ) + while( PeekMessageA( &msg, nullptr, 0, 0, PM_NOREMOVE ) ) { - if( !GetMessageA( &msg, NULL, 0, 0 ) ) + if( !GetMessageA( &msg, nullptr, 0, 0 ) ) { PostQuitMessage( msg.wParam ); return; @@ -2746,7 +2363,7 @@ static void _PumpMessage() } } -static void GetReadingWindowOrientation( DWORD dwId ) +static void GetReadingWindowOrientation( _In_ DWORD dwId ) { g_bHorizontalReading = ( g_hklCurrent == _CHS_HKL ) || ( g_hklCurrent == _CHT_HKL_NEW_CHANG_JIE ) || ( dwId == 0 ); if( !g_bHorizontalReading && IMEID_LANG( dwId ) == LANG_CHT ) @@ -2754,13 +2371,13 @@ static void GetReadingWindowOrientation( DWORD dwId ) char szRegPath[MAX_PATH]; HKEY hkey; DWORD dwVer = IMEID_VER( dwId ); - StringCchCopyA( szRegPath, COUNTOF(szRegPath), "software\\microsoft\\windows\\currentversion\\" ); + strcpy_s( szRegPath, COUNTOF(szRegPath), "software\\microsoft\\windows\\currentversion\\" ); strcat_s( szRegPath, COUNTOF(szRegPath), ( dwVer >= MAKEIMEVERSION(5, 1) ) ? "MSTCIPH" : "TINTLGNT" ); LONG lRc = RegOpenKeyExA( HKEY_CURRENT_USER, szRegPath, 0, KEY_READ, &hkey ); if( lRc == ERROR_SUCCESS ) { DWORD dwSize = sizeof( DWORD ), dwMapping, dwType; - lRc = RegQueryValueExA( hkey, "keyboard mapping", NULL, &dwType, ( PBYTE )&dwMapping, &dwSize ); + lRc = RegQueryValueExA( hkey, "keyboard mapping", nullptr, &dwType, ( PBYTE )&dwMapping, &dwSize ); if( lRc == ERROR_SUCCESS ) { if( @@ -2780,7 +2397,7 @@ static void GetReadingWindowOrientation( DWORD dwId ) } } -void ImeUi_ToggleLanguageBar( BOOL bRestore ) +void ImeUi_ToggleLanguageBar( _In_ BOOL bRestore ) { static BOOL prevRestore = TRUE; bool bCheck = ( prevRestore == TRUE || bRestore == TRUE ); @@ -2792,17 +2409,17 @@ void ImeUi_ToggleLanguageBar( BOOL bRestore ) if( iShowStatusWindow == -1 ) { iShowStatusWindow = IsNT() && g_osi.dwMajorVersion >= 5 && - ( g_osi.dwMinorVersion > 1 || ( g_osi.dwMinorVersion == 1 && lstrlenA( g_osi.szCSDVersion ) ) ) ? 1 : 0; + ( g_osi.dwMinorVersion > 1 || ( g_osi.dwMinorVersion == 1 && strlen( g_osi.szCSDVersion ) ) ) ? 1 : 0; } HWND hwndImeDef = _ImmGetDefaultIMEWnd( g_hwndCurr ); if( hwndImeDef && bRestore && iShowStatusWindow ) SendMessageA( hwndImeDef, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0 ); HRESULT hr; - hr = CoInitialize( NULL ); + hr = CoInitialize( nullptr ); if( SUCCEEDED( hr ) ) { - ITfLangBarMgr* plbm = NULL; - hr = CoCreateInstance( CLSID_TF_LangBarMgr, NULL, CLSCTX_INPROC_SERVER, __uuidof( ITfLangBarMgr ), + ITfLangBarMgr* plbm = nullptr; + hr = CoCreateInstance( CLSID_TF_LangBarMgr, nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfLangBarMgr ), ( void** )&plbm ); if( SUCCEEDED( hr ) && plbm ) { @@ -2874,8 +2491,8 @@ static void OnInputLangChange() static void SetImeApi() { - _GetReadingString = NULL; - _ShowReadingWindow = NULL; + _GetReadingString = nullptr; + _ShowReadingWindow = nullptr; if( g_bUILessMode ) return; @@ -2883,17 +2500,15 @@ static void SetImeApi() HKL kl = g_hklCurrent; if( _ImmGetIMEFileNameA( kl, szImeFile, sizeof( szImeFile ) - 1 ) <= 0 ) return; - HMODULE hIme = LoadLibraryA( szImeFile ); + HMODULE hIme = LoadLibraryExA( szImeFile, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( !hIme ) return; - _GetReadingString = ( UINT ( WINAPI* )( HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT ) ) - ( GetProcAddress( hIme, "GetReadingString" ) ); - _ShowReadingWindow = ( BOOL ( WINAPI* )( HIMC himc, BOOL ) ) - ( GetProcAddress( hIme, "ShowReadingWindow" ) ); + _GetReadingString = reinterpret_cast<UINT ( WINAPI* )( HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT )>( reinterpret_cast<void*>( GetProcAddress( hIme, "GetReadingString" ) ) ); + _ShowReadingWindow = reinterpret_cast<BOOL ( WINAPI* )( HIMC himc, BOOL )>( reinterpret_cast<void*>( GetProcAddress( hIme, "ShowReadingWindow" ) ) ); if( _ShowReadingWindow ) { - HIMC himc; - if( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) ) + HIMC himc = _ImmGetContext( g_hwndCurr ); + if( himc ) { _ShowReadingWindow( himc, false ); _ImmReleaseContext( g_hwndCurr, himc ); @@ -2944,16 +2559,16 @@ static void CheckInputLocale() g_pszIndicatior = g_aszIndicator[INDICATOR_NON_IME]; } char szCodePage[8]; - int iRc = GetLocaleInfoA( MAKELCID( GETLANG(), SORT_DEFAULT ), LOCALE_IDEFAULTANSICODEPAGE, szCodePage, - COUNTOF( szCodePage ) ); iRc; - g_uCodePage = _strtoul( szCodePage, NULL, 0 ); + (void)GetLocaleInfoA( MAKELCID( GETLANG(), SORT_DEFAULT ), LOCALE_IDEFAULTANSICODEPAGE, szCodePage, + COUNTOF( szCodePage ) ); + g_uCodePage = _strtoul( szCodePage, nullptr, 0 ); for( int i = 0; i < 256; i++ ) { LeadByteTable[i] = ( BYTE )IsDBCSLeadByteEx( g_uCodePage, ( BYTE )i ); } } -void ImeUi_SetWindow( HWND hwnd ) +void ImeUi_SetWindow( _In_ HWND hwnd ) { g_hwndCurr = hwnd; g_disableCicero.DisableCiceroOnThisWnd( hwnd ); @@ -2969,7 +2584,7 @@ DWORD ImeUi_GetFlags() return g_dwImeUiFlags; } -void ImeUi_SetFlags( DWORD dwFlags, bool bSet ) +void ImeUi_SetFlags( _In_ DWORD dwFlags, _In_ bool bSet ) { if( bSet ) { @@ -2997,7 +2612,7 @@ BOOL CTsfUiLessMode::SetupSinks() // ITfThreadMgrEx is available on Vista or later. HRESULT hr; hr = CoCreateInstance( CLSID_TF_ThreadMgr, - NULL, + nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfThreadMgrEx ), ( void** )&m_tm ); @@ -3016,7 +2631,7 @@ BOOL CTsfUiLessMode::SetupSinks() // Setup sinks BOOL bRc = FALSE; - m_TsfSink = new CUIElementSink(); + m_TsfSink = new (std::nothrow) CUIElementSink(); if( m_TsfSink ) { ITfSource* srcTm; @@ -3071,16 +2686,16 @@ CTsfUiLessMode::CUIElementSink::~CUIElementSink() { } -STDAPI CTsfUiLessMode::CUIElementSink::QueryInterface( REFIID riid, void** ppvObj ) +STDAPI CTsfUiLessMode::CUIElementSink::QueryInterface( _In_ REFIID riid, _COM_Outptr_ void** ppvObj ) { - if( ppvObj == NULL ) + if( !ppvObj ) return E_INVALIDARG; - *ppvObj = NULL; + *ppvObj = nullptr; if( IsEqualIID( riid, IID_IUnknown ) ) { - *ppvObj = reinterpret_cast<IUnknown*>( this ); + *ppvObj = static_cast<IUnknown*>( static_cast<ITfUIElementSink*>( this ) ); } else if( IsEqualIID( riid, __uuidof( ITfUIElementSink ) ) ) { @@ -3125,12 +2740,12 @@ CTsfUiLessMode::CUIElementSink::Release() STDAPI CTsfUiLessMode::CUIElementSink::BeginUIElement( DWORD dwUIElementId, BOOL* pbShow ) { - ITfUIElement* pElement = GetUIElement( dwUIElementId ); + auto pElement = GetUIElement( dwUIElementId ); if( !pElement ) return E_INVALIDARG; - ITfReadingInformationUIElement* preading = NULL; - ITfCandidateListUIElement* pcandidate = NULL; + ITfReadingInformationUIElement* preading = nullptr; + ITfCandidateListUIElement* pcandidate = nullptr; *pbShow = FALSE; if( !g_bCandList && SUCCEEDED( pElement->QueryInterface( __uuidof( ITfReadingInformationUIElement ), ( void** )&preading ) ) ) @@ -3152,12 +2767,12 @@ STDAPI CTsfUiLessMode::CUIElementSink::BeginUIElement( DWORD dwUIElementId, BOOL STDAPI CTsfUiLessMode::CUIElementSink::UpdateUIElement( DWORD dwUIElementId ) { - ITfUIElement* pElement = GetUIElement( dwUIElementId ); + auto pElement = GetUIElement( dwUIElementId ); if( !pElement ) return E_INVALIDARG; - ITfReadingInformationUIElement* preading = NULL; - ITfCandidateListUIElement* pcandidate = NULL; + ITfReadingInformationUIElement* preading = nullptr; + ITfCandidateListUIElement* pcandidate = nullptr; if( !g_bCandList && SUCCEEDED( pElement->QueryInterface( __uuidof( ITfReadingInformationUIElement ), ( void** )&preading ) ) ) { @@ -3177,11 +2792,11 @@ STDAPI CTsfUiLessMode::CUIElementSink::UpdateUIElement( DWORD dwUIElementId ) STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement( DWORD dwUIElementId ) { - ITfUIElement* pElement = GetUIElement( dwUIElementId ); + auto pElement = GetUIElement( dwUIElementId ); if( !pElement ) return E_INVALIDARG; - ITfReadingInformationUIElement* preading = NULL; + ITfReadingInformationUIElement* preading = nullptr; if( !g_bCandList && SUCCEEDED( pElement->QueryInterface( __uuidof( ITfReadingInformationUIElement ), ( void** )&preading ) ) ) { @@ -3189,7 +2804,7 @@ STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement( DWORD dwUIElementId ) preading->Release(); } - ITfCandidateListUIElement* pcandidate = NULL; + ITfCandidateListUIElement* pcandidate = nullptr; if( SUCCEEDED( pElement->QueryInterface( __uuidof( ITfCandidateListUIElement ), ( void** )&pcandidate ) ) ) { @@ -3206,27 +2821,31 @@ STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement( DWORD dwUIElementId ) void CTsfUiLessMode::UpdateImeState( BOOL bResetCompartmentEventSink ) { ITfCompartmentMgr* pcm; - ITfCompartment* pTfOpenMode = NULL; - ITfCompartment* pTfConvMode = NULL; + ITfCompartment* pTfOpenMode = nullptr; + ITfCompartment* pTfConvMode = nullptr; if( GetCompartments( &pcm, &pTfOpenMode, &pTfConvMode ) ) { VARIANT valOpenMode; - VARIANT valConvMode; - pTfOpenMode->GetValue( &valOpenMode ); - pTfConvMode->GetValue( &valConvMode ); - if( valOpenMode.vt == VT_I4 ) + if ( SUCCEEDED(pTfOpenMode->GetValue(&valOpenMode)) ) { - if( g_bChineseIME ) - { - g_dwState = valOpenMode.lVal != 0 && valConvMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_ENGLISH; - } - else + VARIANT valConvMode; + if (SUCCEEDED(pTfConvMode->GetValue(&valConvMode))) { - g_dwState = valOpenMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_OFF; + if (valOpenMode.vt == VT_I4) + { + if (g_bChineseIME) + { + g_dwState = valOpenMode.lVal != 0 && valConvMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_ENGLISH; + } + else + { + g_dwState = valOpenMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_OFF; + } + } + VariantClear(&valConvMode); } + VariantClear(&valOpenMode); } - VariantClear( &valOpenMode ); - VariantClear( &valConvMode ); if( bResetCompartmentEventSink ) { @@ -3238,14 +2857,17 @@ void CTsfUiLessMode::UpdateImeState( BOOL bResetCompartmentEventSink ) } } -STDAPI CTsfUiLessMode::CUIElementSink::OnActivated( DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, - REFGUID guidProfile, HKL hkl, DWORD dwFlags ) +STDAPI CTsfUiLessMode::CUIElementSink::OnActivated( DWORD dwProfileType, LANGID langid, _In_ REFCLSID clsid, _In_ REFGUID catid, + _In_ REFGUID guidProfile, HKL hkl, DWORD dwFlags ) { - static GUID TF_PROFILE_DAYI = + UNREFERENCED_PARAMETER(clsid); + UNREFERENCED_PARAMETER(hkl); + + static GUID s_TF_PROFILE_DAYI = { 0x037B2C25, 0x480C, 0x4D7F, 0xB0, 0x27, 0xD6, 0xCA, 0x6B, 0x69, 0x78, 0x8A }; - g_iCandListIndexBase = IsEqualGUID( TF_PROFILE_DAYI, guidProfile ) ? 0 : 1; + g_iCandListIndexBase = IsEqualGUID( s_TF_PROFILE_DAYI, guidProfile ) ? 0 : 1; if( IsEqualIID( catid, GUID_TFCAT_TIP_KEYBOARD ) && ( dwFlags & TF_IPSINK_FLAG_ACTIVE ) ) { g_bChineseIME = ( dwProfileType & TF_PROFILETYPE_INPUTPROCESSOR ) && langid == LANG_CHT; @@ -3260,8 +2882,9 @@ STDAPI CTsfUiLessMode::CUIElementSink::OnActivated( DWORD dwProfileType, LANGID return S_OK; } -STDAPI CTsfUiLessMode::CUIElementSink::OnChange( REFGUID rguid ) +STDAPI CTsfUiLessMode::CUIElementSink::OnChange( _In_ REFGUID rguid ) { + UNREFERENCED_PARAMETER(rguid); UpdateImeState(); return S_OK; } @@ -3283,39 +2906,13 @@ void CTsfUiLessMode::MakeReadingInformationString( ITfReadingInformationUIElemen g_uCandPageSize = MAX_CANDLIST; g_dwSelection = g_iReadingError ? g_iReadingError - 1 : ( DWORD )-1; g_iReadingError--; // g_iReadingError is used only in horizontal window, and has to be -1 if there's no error. -#ifndef UNICODE - if( g_iReadingError > 0 ) - { - // convert g_iReadingError to byte based - LPCSTR pszNext = g_szReadingString; - for( int i = 0; i < g_iReadingError && pszNext && *pszNext; ++i ) - { - pszNext = CharNext( pszNext ); - } - if( pszNext ) // should be non-NULL, but just in case - { - g_iReadingError = pszNext - g_szReadingString; - } - } -#endif BSTR bstr; if( SUCCEEDED( preading->GetString( &bstr ) ) ) { if( bstr ) { -#ifndef UNICODE - char szStr[COUNTOF(g_szReadingString)*2]; - szStr[0] = 0; - int iRc = WideCharToMultiByte( CP_ACP, 0, bstr, -1, szStr, sizeof( szStr ), NULL, NULL ); - if( iRc >= sizeof( szStr ) ) - { - szStr[sizeof( szStr ) - 1] = 0; - } - StringCchCopy( g_szReadingString, COUNTOF(g_szReadingString), szStr ); -#else - StringCchCopy( g_szReadingString, COUNTOF(g_szReadingString), bstr ); -#endif + wcscpy_s( g_szReadingString, COUNTOF(g_szReadingString), bstr ); g_dwCount = cchMax; LPCTSTR pszSource = g_szReadingString; if( fVertical ) @@ -3328,7 +2925,7 @@ void CTsfUiLessMode::MakeReadingInformationString( ITfReadingInformationUIElemen { LPTSTR pszNextSrc = CharNext( pszSource ); SIZE_T size = ( LPSTR )pszNextSrc - ( LPSTR )pszSource; - CopyMemory( pszDest, pszSource, size ); + memcpy( pszDest, pszSource, size ); pszSource = pszNextSrc; pszDest += size; } @@ -3349,7 +2946,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate UINT uIndex = 0; UINT uCount = 0; UINT uCurrentPage = 0; - UINT* IndexList = NULL; + UINT* IndexList = nullptr; UINT uPageCnt = 0; DWORD dwPageStart = 0; DWORD dwPageSize = 0; @@ -3363,7 +2960,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate g_bCandList = true; g_bReadingWindow = false; - pcandidate->GetPageIndex( NULL, 0, &uPageCnt ); + pcandidate->GetPageIndex( nullptr, 0, &uPageCnt ); if( uPageCnt > 0 ) { IndexList = ( UINT* )ImeUiCallback_Malloc( sizeof( UINT ) * uPageCnt ); @@ -3372,12 +2969,12 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate pcandidate->GetPageIndex( IndexList, uPageCnt, &uPageCnt ); dwPageStart = IndexList[uCurrentPage]; dwPageSize = ( uCurrentPage < uPageCnt - 1 ) ? - min( uCount, IndexList[uCurrentPage + 1] ) - dwPageStart: + std::min( uCount, IndexList[uCurrentPage + 1] ) - dwPageStart: uCount - dwPageStart; } } - g_uCandPageSize = min( dwPageSize, MAX_CANDLIST ); + g_uCandPageSize = std::min<UINT>( dwPageSize, MAX_CANDLIST ); g_dwSelection = g_dwSelection - dwPageStart; memset( &g_szCandidate, 0, sizeof( g_szCandidate ) ); @@ -3387,18 +2984,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate { if( bstr ) { -#ifndef UNICODE - char szStr[COUNTOF(g_szCandidate[0])*2]; - szStr[0] = 0; - int iRc = WideCharToMultiByte( CP_ACP, 0, bstr, -1, szStr, sizeof( szStr ), NULL, NULL ); - if( iRc >= sizeof( szStr ) ) - { - szStr[sizeof( szStr ) - 1] = 0; - } - ComposeCandidateLine( j, szStr ); -#else - ComposeCandidateLine( j, bstr ); -#endif + ComposeCandidateLine( j, bstr ); SysFreeString( bstr ); } } @@ -3418,7 +3004,7 @@ void CTsfUiLessMode::MakeCandidateStrings( ITfCandidateListUIElement* pcandidate ITfUIElement* CTsfUiLessMode::GetUIElement( DWORD dwUIElementId ) { ITfUIElementMgr* puiem; - ITfUIElement* pElement = NULL; + ITfUIElement* pElement = nullptr; if( SUCCEEDED( m_tm->QueryInterface( __uuidof( ITfUIElementMgr ), ( void** )&puiem ) ) ) { @@ -3435,7 +3021,7 @@ BOOL CTsfUiLessMode::CurrentInputLocaleIsIme() HRESULT hr; ITfInputProcessorProfiles* pProfiles; - hr = CoCreateInstance( CLSID_TF_InputProcessorProfiles, NULL, CLSCTX_INPROC_SERVER, + hr = CoCreateInstance( CLSID_TF_InputProcessorProfiles, nullptr, CLSCTX_INPROC_SERVER, __uuidof( ITfInputProcessorProfiles ), ( LPVOID* )&pProfiles ); if( SUCCEEDED( hr ) ) { @@ -3461,13 +3047,13 @@ BOOL CTsfUiLessMode::CurrentInputLocaleIsIme() // otherwise the sink can be triggered when a game has multiple instances of IME UI library. void CTsfUiLessMode::EnableUiUpdates( bool bEnable ) { - if( m_tm == NULL || + if( !m_tm || ( bEnable && m_dwUIElementSinkCookie != TF_INVALID_COOKIE ) || ( !bEnable && m_dwUIElementSinkCookie == TF_INVALID_COOKIE ) ) { return; } - ITfSource* srcTm = NULL; + ITfSource* srcTm = nullptr; HRESULT hr = E_FAIL; if( SUCCEEDED( hr = m_tm->QueryInterface( __uuidof( ITfSource ), ( void** )&srcTm ) ) ) { @@ -3490,9 +3076,9 @@ void CTsfUiLessMode::EnableUiUpdates( bool bEnable ) BOOL CTsfUiLessMode::GetCompartments( ITfCompartmentMgr** ppcm, ITfCompartment** ppTfOpenMode, ITfCompartment** ppTfConvMode ) { - ITfCompartmentMgr* pcm = NULL; - ITfCompartment* pTfOpenMode = NULL; - ITfCompartment* pTfConvMode = NULL; + ITfCompartmentMgr* pcm = nullptr; + ITfCompartment* pTfOpenMode = nullptr; + ITfCompartment* pTfConvMode = nullptr; static GUID _GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION = { @@ -3527,7 +3113,7 @@ BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pT ITfCompartment* pTfConvMode ) { bool bLocalCompartments = false; - ITfCompartmentMgr* pcm = NULL; + ITfCompartmentMgr* pcm = nullptr; BOOL bRc = FALSE; HRESULT hr = E_FAIL; @@ -3541,7 +3127,7 @@ BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pT // Invalid parameters or GetCompartments() has failed. return FALSE; } - ITfSource* srcOpenMode = NULL; + ITfSource* srcOpenMode = nullptr; if( SUCCEEDED( hr = pTfOpenMode->QueryInterface( IID_ITfSource, ( void** )&srcOpenMode ) ) ) { // Remove existing sink for open mode @@ -3555,7 +3141,7 @@ BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pT ( ITfCompartmentEventSink* )m_TsfSink, &m_dwOpenModeSinkCookie ) ) ) { - ITfSource* srcConvMode = NULL; + ITfSource* srcConvMode = nullptr; if( SUCCEEDED( hr = pTfConvMode->QueryInterface( IID_ITfSource, ( void** )&srcConvMode ) ) ) { // Remove existing sink for open mode @@ -3591,7 +3177,7 @@ WORD ImeUi_GetPrimaryLanguage() return GETPRIMLANG(); }; -DWORD ImeUi_GetImeId( UINT uIndex ) +DWORD ImeUi_GetImeId( _In_ UINT uIndex ) { return GetImeId( uIndex ); }; @@ -3601,7 +3187,7 @@ WORD ImeUi_GetLanguage() return GETLANG(); }; -PTSTR ImeUi_GetIndicatior() +PCTSTR ImeUi_GetIndicatior() { return g_pszIndicatior; }; @@ -3627,7 +3213,7 @@ bool ImeUi_IsHorizontalReading() return g_bHorizontalReading; }; -TCHAR* ImeUi_GetCandidate( UINT idx ) +TCHAR* ImeUi_GetCandidate( _In_ UINT idx ) { if( idx < MAX_CANDLIST ) return g_szCandidate[idx]; diff --git a/samples/DX_APIUsage/DXUT/Optional/ImeUi.h b/samples/DX_APIUsage/DXUT/Optional/ImeUi.h index deae8f4..d7cbeaa 100644 --- a/samples/DX_APIUsage/DXUT/Optional/ImeUi.h +++ b/samples/DX_APIUsage/DXUT/Optional/ImeUi.h @@ -2,25 +2,25 @@ // File: ImeUi.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- -#ifndef _IMEUI_H_ -#define _IMEUI_H_ -#if _WIN32_WINNT < 0x0400 -#error IMEUI requires _WIN32_WINNT to be 0x0400 or higher. Please add "_WIN32_WINNT=0x0400" to your project's preprocessor setting. -#endif +#pragma once + #include <windows.h> class CImeUiFont_Base { public: - virtual void SetHeight( UINT uHeight ) + virtual void SetHeight( _In_ UINT uHeight ) { - uHeight; + UNREFERENCED_PARAMETER(uHeight); }; // for backward compatibility - virtual void SetColor( DWORD color ) = 0; - virtual void SetPosition( int x, int y ) = 0; - virtual void GetTextExtent( LPCTSTR szText, DWORD* puWidth, DWORD* puHeight ) = 0; - virtual void DrawText( LPCTSTR pszText ) = 0; + virtual void SetColor( _In_ DWORD color ) = 0; + virtual void SetPosition( _In_ int x, _In_ int y ) = 0; + virtual void GetTextExtent( _In_z_ LPCTSTR szText, _Out_ DWORD* puWidth, _Out_ DWORD* puHeight ) = 0; + virtual void DrawText( _In_z_ LPCTSTR pszText ) = 0; }; typedef struct @@ -76,49 +76,47 @@ typedef struct // D3DTLVERTEX compatible // IME Flags #define IMEUI_FLAG_SUPPORT_CARET 0x00000001 -bool ImeUi_Initialize( HWND hwnd, bool bDisable = false ); +bool ImeUi_Initialize( _In_ HWND hwnd, _In_ bool bDisable = false ); void ImeUi_Uninitialize(); -void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia ); -void ImeUi_GetAppearance( IMEUI_APPEARANCE* pia ); -bool ImeUi_IgnoreHotKey( const MSG* pmsg ); -LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam, bool* trapped ); -void ImeUi_SetScreenDimension( UINT width, UINT height ); -void ImeUi_RenderUI( bool bDrawCompAttr = true, bool bDrawOtherUi = true ); -void ImeUi_SetCaretPosition( UINT x, UINT y ); -void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const RECT* prc ); +void ImeUi_SetAppearance( _In_opt_ const IMEUI_APPEARANCE* pia ); +void ImeUi_GetAppearance( _Out_opt_ IMEUI_APPEARANCE* pia ); +bool ImeUi_IgnoreHotKey( _In_ const MSG* pmsg ); +LPARAM ImeUi_ProcessMessage( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _Inout_ LPARAM& lParam, _Out_ bool* trapped ); +void ImeUi_SetScreenDimension( _In_ UINT width, _In_ UINT height ); +void ImeUi_RenderUI( _In_ bool bDrawCompAttr = true, _In_ bool bDrawOtherUi = true ); +void ImeUi_SetCaretPosition( _In_ UINT x, _In_ UINT y ); +void ImeUi_SetCompStringAppearance( _In_ CImeUiFont_Base* pFont, _In_ DWORD color, _In_ const RECT* prc ); bool ImeUi_GetCaretStatus(); -void ImeUi_SetInsertMode( bool bInsert ); -void ImeUi_SetState( DWORD dwState ); +void ImeUi_SetInsertMode( _In_ bool bInsert ); +void ImeUi_SetState( _In_ DWORD dwState ); DWORD ImeUi_GetState(); -void ImeUi_EnableIme( bool bEnable ); -bool ImeUi_IsEnabled( void ); -void ImeUi_FinalizeString( bool bSend = false ); -void ImeUi_ToggleLanguageBar( BOOL bRestore ); +void ImeUi_EnableIme( _In_ bool bEnable ); +bool ImeUi_IsEnabled(); +void ImeUi_FinalizeString( _In_ bool bSend = false ); +void ImeUi_ToggleLanguageBar( _In_ BOOL bRestore ); bool ImeUi_IsSendingKeyMessage(); -void ImeUi_SetWindow( HWND hwnd ); +void ImeUi_SetWindow( _In_ HWND hwnd ); UINT ImeUi_GetInputCodePage(); DWORD ImeUi_GetFlags(); -void ImeUi_SetFlags( DWORD dwFlags, bool bSet ); +void ImeUi_SetFlags( _In_ DWORD dwFlags, _In_ bool bSet ); WORD ImeUi_GetPrimaryLanguage(); -DWORD ImeUi_GetImeId( UINT uIndex ); +DWORD ImeUi_GetImeId( _In_ UINT uIndex ); WORD ImeUi_GetLanguage(); -LPTSTR ImeUi_GetIndicatior(); +LPCTSTR ImeUi_GetIndicatior(); bool ImeUi_IsShowReadingWindow(); bool ImeUi_IsShowCandListWindow(); bool ImeUi_IsVerticalCand(); bool ImeUi_IsHorizontalReading(); -TCHAR* ImeUi_GetCandidate( UINT idx ); +TCHAR* ImeUi_GetCandidate( _In_ UINT idx ); TCHAR* ImeUi_GetCompositionString(); DWORD ImeUi_GetCandidateSelection(); DWORD ImeUi_GetCandidateCount(); BYTE* ImeUi_GetCompStringAttr(); DWORD ImeUi_GetImeCursorChars(); -extern void ( CALLBACK*ImeUiCallback_DrawRect )( int x1, int y1, int x2, int y2, DWORD color ); -extern void* ( __cdecl*ImeUiCallback_Malloc )( size_t bytes ); -extern void ( __cdecl*ImeUiCallback_Free )( void* ptr ); -extern void ( CALLBACK*ImeUiCallback_DrawFans )( const IMEUI_VERTEX* paVertex, UINT uNum ); -extern void ( CALLBACK*ImeUiCallback_OnChar )( WCHAR wc ); - -#endif //_IMEUI_H_ +extern void ( CALLBACK*ImeUiCallback_DrawRect )( _In_ int x1, _In_ int y1, _In_ int x2, _In_ int y2, _In_ DWORD color ); +extern void* ( __cdecl*ImeUiCallback_Malloc )( _In_ size_t bytes ); +extern void ( __cdecl*ImeUiCallback_Free )( _In_ void* ptr ); +extern void ( CALLBACK*ImeUiCallback_DrawFans )( _In_ const IMEUI_VERTEX* paVertex, _In_ UINT uNum ); +extern void ( CALLBACK*ImeUiCallback_OnChar )( _In_ WCHAR wc ); diff --git a/samples/DX_APIUsage/DXUT/Optional/SDKmesh.cpp b/samples/DX_APIUsage/DXUT/Optional/SDKmesh.cpp index 5002d74..207020f 100644 --- a/samples/DX_APIUsage/DXUT/Optional/SDKmesh.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/SDKmesh.cpp @@ -7,12 +7,18 @@ // meets the specific needs of the application. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "SDKMesh.h" #include "SDKMisc.h" +using namespace DirectX; + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pMaterials, UINT numMaterials, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { @@ -22,12 +28,12 @@ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pM { for( UINT m = 0; m < numMaterials; m++ ) { - pMaterials[m].pDiffuseTexture11 = NULL; - pMaterials[m].pNormalTexture11 = NULL; - pMaterials[m].pSpecularTexture11 = NULL; - pMaterials[m].pDiffuseRV11 = NULL; - pMaterials[m].pNormalRV11 = NULL; - pMaterials[m].pSpecularRV11 = NULL; + pMaterials[m].pDiffuseTexture11 = nullptr; + pMaterials[m].pNormalTexture11 = nullptr; + pMaterials[m].pSpecularTexture11 = nullptr; + pMaterials[m].pDiffuseRV11 = nullptr; + pMaterials[m].pNormalRV11 = nullptr; + pMaterials[m].pSpecularRV11 = nullptr; // load textures if( pMaterials[m].DiffuseTexture[0] != 0 ) @@ -54,12 +60,12 @@ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pM { for( UINT m = 0; m < numMaterials; m++ ) { - pMaterials[m].pDiffuseTexture11 = NULL; - pMaterials[m].pNormalTexture11 = NULL; - pMaterials[m].pSpecularTexture11 = NULL; - pMaterials[m].pDiffuseRV11 = NULL; - pMaterials[m].pNormalRV11 = NULL; - pMaterials[m].pSpecularRV11 = NULL; + pMaterials[m].pDiffuseTexture11 = nullptr; + pMaterials[m].pNormalTexture11 = nullptr; + pMaterials[m].pSpecularTexture11 = nullptr; + pMaterials[m].pDiffuseRV11 = nullptr; + pMaterials[m].pNormalRV11 = nullptr; + pMaterials[m].pSpecularRV11 = nullptr; // load textures if( pMaterials[m].DiffuseTexture[0] != 0 ) @@ -92,84 +98,7 @@ void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pM } //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::LoadMaterials( IDirect3DDevice9* pd3dDevice, SDKMESH_MATERIAL* pMaterials, UINT numMaterials, - SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - char strPath[MAX_PATH]; - - if( pLoaderCallbacks && pLoaderCallbacks->pCreateTextureFromFile ) - { - for( UINT m = 0; m < numMaterials; m++ ) - { - pMaterials[m].pDiffuseTexture9 = NULL; - pMaterials[m].pNormalTexture9 = NULL; - pMaterials[m].pSpecularTexture9 = NULL; - - // load textures - if( pMaterials[m].DiffuseTexture[0] != 0 ) - { - pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice, - pMaterials[m].DiffuseTexture, - &pMaterials[m].pDiffuseTexture9, - pLoaderCallbacks->pContext ); - } - if( pMaterials[m].NormalTexture[0] != 0 ) - { - pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice, - pMaterials[m].NormalTexture, &pMaterials[m].pNormalTexture9, - pLoaderCallbacks->pContext ); - } - if( pMaterials[m].SpecularTexture[0] != 0 ) - { - pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice, - pMaterials[m].SpecularTexture, - &pMaterials[m].pSpecularTexture9, - pLoaderCallbacks->pContext ); - } - } - } - else - { - for( UINT m = 0; m < numMaterials; m++ ) - { - pMaterials[m].pDiffuseTexture9 = NULL; - pMaterials[m].pNormalTexture9 = NULL; - pMaterials[m].pSpecularTexture9 = NULL; - pMaterials[m].pDiffuseRV11 = NULL; - pMaterials[m].pNormalRV11 = NULL; - pMaterials[m].pSpecularRV11 = NULL; - - // load textures - if( pMaterials[m].DiffuseTexture[0] != 0 ) - { - sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].DiffuseTexture ); - if( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, - strPath, - &pMaterials[m].pDiffuseTexture9 ) ) ) - pMaterials[m].pDiffuseTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE; - } - if( pMaterials[m].NormalTexture[0] != 0 ) - { - sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].NormalTexture ); - if( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, - strPath, - &pMaterials[m].pNormalTexture9 ) ) ) - pMaterials[m].pNormalTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE; - } - if( pMaterials[m].SpecularTexture[0] != 0 ) - { - sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].SpecularTexture ); - if( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, - strPath, - &pMaterials[m].pSpecularTexture9 ) ) ) - pMaterials[m].pSpecularTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE; - } - - } - } -} - -//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { @@ -193,7 +122,10 @@ HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERT D3D11_SUBRESOURCE_DATA InitData; InitData.pSysMem = pVertices; hr = pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &pHeader->pVB11 ); - DXUT_SetDebugName( pHeader->pVB11, "CDXUTSDKMesh" ); + if (SUCCEEDED(hr)) + { + DXUT_SetDebugName(pHeader->pVB11, "CDXUTSDKMesh"); + } } return hr; @@ -201,6 +133,7 @@ HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERT //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader, void* pIndices, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { @@ -224,101 +157,21 @@ HRESULT CDXUTSDKMesh::CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX D3D11_SUBRESOURCE_DATA InitData; InitData.pSysMem = pIndices; hr = pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &pHeader->pIB11 ); - DXUT_SetDebugName( pHeader->pIB11, "CDXUTSDKMesh" ); - } - - return hr; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::CreateVertexBuffer( IDirect3DDevice9* pd3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* pHeader, - void* pVertices, SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - HRESULT hr = S_OK; - - pHeader->DataOffset = 0; - if( pLoaderCallbacks && pLoaderCallbacks->pCreateVertexBuffer ) - { - pLoaderCallbacks->pCreateVertexBuffer( pd3dDevice, &pHeader->pVB9, ( UINT )pHeader->SizeBytes, - D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, pVertices, - pLoaderCallbacks->pContext ); - } - else - { - hr = pd3dDevice->CreateVertexBuffer( ( UINT )pHeader->SizeBytes, - D3DUSAGE_WRITEONLY, - 0, - D3DPOOL_DEFAULT, - &pHeader->pVB9, - NULL ); - - //lock - if( SUCCEEDED( hr ) ) + if (SUCCEEDED(hr)) { - void* pLockedVerts = NULL; - V_RETURN( pHeader->pVB9->Lock( 0, 0, &pLockedVerts, 0 ) ); - CopyMemory( pLockedVerts, pVertices, ( size_t )pHeader->SizeBytes ); - pHeader->pVB9->Unlock(); + DXUT_SetDebugName(pHeader->pIB11, "CDXUTSDKMesh"); } } return hr; } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::CreateIndexBuffer( IDirect3DDevice9* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader, - void* pIndices, SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - HRESULT hr = S_OK; - - pHeader->DataOffset = 0; - - D3DFORMAT ibFormat = D3DFMT_INDEX16; - switch( pHeader->IndexType ) - { - case IT_16BIT: - ibFormat = D3DFMT_INDEX16; - break; - case IT_32BIT: - ibFormat = D3DFMT_INDEX32; - break; - }; - - if( pLoaderCallbacks && pLoaderCallbacks->pCreateIndexBuffer ) - { - pLoaderCallbacks->pCreateIndexBuffer( pd3dDevice, &pHeader->pIB9, ( UINT )pHeader->SizeBytes, - D3DUSAGE_WRITEONLY, ibFormat, D3DPOOL_DEFAULT, pIndices, - pLoaderCallbacks->pContext ); - } - else - { - hr = pd3dDevice->CreateIndexBuffer( ( UINT )( pHeader->SizeBytes ), - D3DUSAGE_WRITEONLY, - ibFormat, - D3DPOOL_DEFAULT, - &pHeader->pIB9, - NULL ); - - if( SUCCEEDED( hr ) ) - { - void* pLockedIndices = NULL; - V_RETURN( pHeader->pIB9->Lock( 0, 0, &pLockedIndices, 0 ) ); - CopyMemory( pLockedIndices, pIndices, ( size_t )( pHeader->SizeBytes ) ); - pHeader->pIB9->Unlock(); - } - } - - return hr; -} //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, - LPCTSTR szFileName, - bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS11* pLoaderCallbacks11, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 ) + LPCWSTR szFileName, + SDKMESH_CALLBACKS11* pLoaderCallbacks11 ) { HRESULT hr = S_OK; @@ -326,8 +179,8 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, V_RETURN( DXUTFindDXSDKMediaFileCch( m_strPathW, sizeof( m_strPathW ) / sizeof( WCHAR ), szFileName ) ); // Open the file - m_hFile = CreateFile( m_strPathW, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, - NULL ); + m_hFile = CreateFile( m_strPathW, FILE_READ_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, + nullptr ); if( INVALID_HANDLE_VALUE == m_hFile ) return DXUTERR_MEDIANOTFOUND; @@ -338,7 +191,7 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, else *m_strPathW = L'\0'; - WideCharToMultiByte( CP_ACP, 0, m_strPathW, -1, m_strPath, MAX_PATH, NULL, FALSE ); + WideCharToMultiByte( CP_ACP, 0, m_strPathW, -1, m_strPath, MAX_PATH, nullptr, FALSE ); // Get the file size LARGE_INTEGER FileSize; @@ -346,7 +199,7 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, UINT cBytes = FileSize.LowPart; // Allocate memory - m_pStaticMeshData = new BYTE[ cBytes ]; + m_pStaticMeshData = new (std::nothrow) BYTE[ cBytes ]; if( !m_pStaticMeshData ) { CloseHandle( m_hFile ); @@ -355,7 +208,7 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, // Read in the file DWORD dwBytesRead; - if( !ReadFile( m_hFile, m_pStaticMeshData, cBytes, &dwBytesRead, NULL ) ) + if( !ReadFile( m_hFile, m_pStaticMeshData, cBytes, &dwBytesRead, nullptr ) ) hr = E_FAIL; CloseHandle( m_hFile ); @@ -363,13 +216,10 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, if( SUCCEEDED( hr ) ) { hr = CreateFromMemory( pDev11, - pDev9, m_pStaticMeshData, cBytes, - bCreateAdjacencyIndices, false, - pLoaderCallbacks11, - pLoaderCallbacks9 ); + pLoaderCallbacks11 ); if( FAILED( hr ) ) delete []m_pStaticMeshData; } @@ -377,37 +227,39 @@ HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11, return hr; } +_Use_decl_annotations_ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, BYTE* pData, - UINT DataBytes, - bool bCreateAdjacencyIndices, + size_t DataBytes, bool bCopyStatic, - SDKMESH_CALLBACKS11* pLoaderCallbacks11, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 ) + SDKMESH_CALLBACKS11* pLoaderCallbacks11 ) { - HRESULT hr = E_FAIL; - D3DXVECTOR3 lower; - D3DXVECTOR3 upper; + XMFLOAT3 lower; + XMFLOAT3 upper; - m_pDev9 = pDev9; - m_pDev11 = pDev11; + m_pDev11 = pDev11; + + if ( DataBytes < sizeof(SDKMESH_HEADER) ) + return E_FAIL; // Set outstanding resources to zero m_NumOutstandingResources = 0; if( bCopyStatic ) { - SDKMESH_HEADER* pHeader = ( SDKMESH_HEADER* )pData; + auto pHeader = reinterpret_cast<SDKMESH_HEADER*>( pData ); SIZE_T StaticSize = ( SIZE_T )( pHeader->HeaderSize + pHeader->NonBufferDataSize ); - m_pHeapData = new BYTE[ StaticSize ]; + if ( DataBytes < StaticSize ) + return E_FAIL; + + m_pHeapData = new (std::nothrow) BYTE[ StaticSize ]; if( !m_pHeapData ) - return hr; + return E_OUTOFMEMORY; m_pStaticMeshData = m_pHeapData; - CopyMemory( m_pStaticMeshData, pData, StaticSize ); + memcpy( m_pStaticMeshData, pData, StaticSize ); } else { @@ -416,7 +268,8 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, } // Pointer fixup - m_pMeshHeader = ( SDKMESH_HEADER* )m_pStaticMeshData; + m_pMeshHeader = reinterpret_cast<SDKMESH_HEADER*>( m_pStaticMeshData ); + m_pVertexBufferArray = ( SDKMESH_VERTEX_BUFFER_HEADER* )( m_pStaticMeshData + m_pMeshHeader->VertexStreamHeadersOffset ); m_pIndexBufferArray = ( SDKMESH_INDEX_BUFFER_HEADER* )( m_pStaticMeshData + @@ -436,8 +289,7 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, // error condition if( m_pMeshHeader->Version != SDKMESH_FILE_VERSION ) { - hr = E_NOINTERFACE; - goto Error; + return E_NOINTERFACE; } // Setup buffer data pointer @@ -447,31 +299,36 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, UINT64 BufferDataStart = m_pMeshHeader->HeaderSize + m_pMeshHeader->NonBufferDataSize; // Create VBs - m_ppVertices = new BYTE*[m_pMeshHeader->NumVertexBuffers]; + m_ppVertices = new (std::nothrow) BYTE*[m_pMeshHeader->NumVertexBuffers]; + if ( !m_ppVertices ) + { + return E_OUTOFMEMORY; + } for( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) { - BYTE* pVertices = NULL; + BYTE* pVertices = nullptr; pVertices = ( BYTE* )( pBufferData + ( m_pVertexBufferArray[i].DataOffset - BufferDataStart ) ); if( pDev11 ) CreateVertexBuffer( pDev11, &m_pVertexBufferArray[i], pVertices, pLoaderCallbacks11 ); - else if( pDev9 ) - CreateVertexBuffer( pDev9, &m_pVertexBufferArray[i], pVertices, pLoaderCallbacks9 ); m_ppVertices[i] = pVertices; } // Create IBs - m_ppIndices = new BYTE*[m_pMeshHeader->NumIndexBuffers]; + m_ppIndices = new (std::nothrow) BYTE*[m_pMeshHeader->NumIndexBuffers]; + if ( !m_ppIndices ) + { + return E_OUTOFMEMORY; + } + for( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) { - BYTE* pIndices = NULL; + BYTE* pIndices = nullptr; pIndices = ( BYTE* )( pBufferData + ( m_pIndexBufferArray[i].DataOffset - BufferDataStart ) ); if( pDev11 ) CreateIndexBuffer( pDev11, &m_pIndexBufferArray[i], pIndices, pLoaderCallbacks11 ); - else if( pDev9 ) - CreateIndexBuffer( pDev9, &m_pIndexBufferArray[i], pIndices, pLoaderCallbacks9 ); m_ppIndices[i] = pIndices; } @@ -479,23 +336,28 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, // Load Materials if( pDev11 ) LoadMaterials( pDev11, m_pMaterialArray, m_pMeshHeader->NumMaterials, pLoaderCallbacks11 ); - else if( pDev9 ) - LoadMaterials( pDev9, m_pMaterialArray, m_pMeshHeader->NumMaterials, pLoaderCallbacks9 ); // Create a place to store our bind pose frame matrices - m_pBindPoseFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ]; + m_pBindPoseFrameMatrices = new (std::nothrow) XMFLOAT4X4[ m_pMeshHeader->NumFrames ]; if( !m_pBindPoseFrameMatrices ) - goto Error; + { + return E_OUTOFMEMORY; + } // Create a place to store our transformed frame matrices - m_pTransformedFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ]; + m_pTransformedFrameMatrices = new (std::nothrow) XMFLOAT4X4[ m_pMeshHeader->NumFrames ]; if( !m_pTransformedFrameMatrices ) - goto Error; - m_pWorldPoseFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ]; + { + return E_OUTOFMEMORY; + } + + m_pWorldPoseFrameMatrices = new (std::nothrow) XMFLOAT4X4[ m_pMeshHeader->NumFrames ]; if( !m_pWorldPoseFrameMatrices ) - goto Error; + { + return E_OUTOFMEMORY; + } - SDKMESH_SUBSET* pSubset = NULL; + SDKMESH_SUBSET* pSubset = nullptr; D3D11_PRIMITIVE_TOPOLOGY PrimType; // update bounding volume @@ -528,10 +390,10 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, IndexStart *= 2; }*/ - //BYTE* pIndices = NULL; + //BYTE* pIndices = nullptr; //m_ppIndices[i] UINT *ind = ( UINT * )m_ppIndices[currentMesh->IndexBuffer]; - FLOAT *verts = ( FLOAT* )m_ppVertices[currentMesh->VertexBuffers[0]]; + float *verts = ( float* )m_ppVertices[currentMesh->VertexBuffers[0]]; UINT stride = (UINT)m_pVertexBufferArray[currentMesh->VertexBuffers[0]].StrideBytes; assert (stride % 4 == 0); stride /=4; @@ -550,7 +412,7 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, current_ind = ind[vertind]; } tris++; - D3DXVECTOR3 *pt = (D3DXVECTOR3*)&(verts[stride * current_ind]); + XMFLOAT3 *pt = (XMFLOAT3*)&(verts[stride * current_ind]); if (pt->x < lower.x) { lower.x = pt->x; } @@ -575,153 +437,137 @@ HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11, //pd3dDeviceContext->DrawIndexed( IndexCount, IndexStart, VertexStart ); } - D3DXVECTOR3 half = upper - lower; - half *=0.5f; + XMFLOAT3 half( ( upper.x - lower.x ) * 0.5f, + ( upper.y - lower.y ) * 0.5f, + ( upper.z - lower.z ) * 0.5f ); + + currentMesh->BoundingBoxCenter.x = lower.x + half.x; + currentMesh->BoundingBoxCenter.y = lower.y + half.y; + currentMesh->BoundingBoxCenter.z = lower.z + half.z; - currentMesh->BoundingBoxCenter = lower + half; currentMesh->BoundingBoxExtents = half; } // Update - - - hr = S_OK; -Error: - - if( !pLoaderCallbacks9 ) - { - CheckLoadDone(); - } - - return hr; + return S_OK; } + //-------------------------------------------------------------------------------------- // transform bind pose frame using a recursive traversal //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformBindPoseFrame( UINT iFrame, D3DXMATRIX* pParentWorld ) +_Use_decl_annotations_ +void CDXUTSDKMesh::TransformBindPoseFrame( UINT iFrame, CXMMATRIX parentWorld ) { if( !m_pBindPoseFrameMatrices ) return; // Transform ourselves - D3DXMATRIX LocalWorld; - D3DXMatrixMultiply( &LocalWorld, &m_pFrameArray[iFrame].Matrix, pParentWorld ); - m_pBindPoseFrameMatrices[iFrame] = LocalWorld; + XMMATRIX m = XMLoadFloat4x4( &m_pFrameArray[iFrame].Matrix ); + XMMATRIX mLocalWorld = XMMatrixMultiply( m, parentWorld ); + XMStoreFloat4x4( &m_pBindPoseFrameMatrices[iFrame], mLocalWorld ); // Transform our siblings if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME ) - TransformBindPoseFrame( m_pFrameArray[iFrame].SiblingFrame, pParentWorld ); + { + TransformBindPoseFrame( m_pFrameArray[iFrame].SiblingFrame, parentWorld ); + } // Transform our children if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME ) - TransformBindPoseFrame( m_pFrameArray[iFrame].ChildFrame, &LocalWorld ); + { + TransformBindPoseFrame( m_pFrameArray[iFrame].ChildFrame, mLocalWorld ); + } } + //-------------------------------------------------------------------------------------- // transform frame using a recursive traversal //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformFrame( UINT iFrame, D3DXMATRIX* pParentWorld, double fTime ) +_Use_decl_annotations_ +void CDXUTSDKMesh::TransformFrame( UINT iFrame, CXMMATRIX parentWorld, double fTime ) { // Get the tick data - D3DXMATRIX LocalTransform; + XMMATRIX mLocalTransform; + UINT iTick = GetAnimationKeyFromTime( fTime ); if( INVALID_ANIMATION_DATA != m_pFrameArray[iFrame].AnimationDataIndex ) { - SDKANIMATION_FRAME_DATA* pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; - SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[ iTick ]; + auto pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; + auto pData = &pFrameData->pAnimationData[ iTick ]; // turn it into a matrix (Ignore scaling for now) - D3DXVECTOR3 parentPos = pData->Translation; - D3DXMATRIX mTranslate; - D3DXMatrixTranslation( &mTranslate, parentPos.x, parentPos.y, parentPos.z ); - - D3DXQUATERNION quat; - D3DXMATRIX mQuat; - quat.w = pData->Orientation.w; - quat.x = pData->Orientation.x; - quat.y = pData->Orientation.y; - quat.z = pData->Orientation.z; - if( quat.w == 0 && quat.x == 0 && quat.y == 0 && quat.z == 0 ) - D3DXQuaternionIdentity( &quat ); - D3DXQuaternionNormalize( &quat, &quat ); - D3DXMatrixRotationQuaternion( &mQuat, &quat ); - LocalTransform = ( mQuat * mTranslate ); + XMFLOAT3 parentPos = pData->Translation; + XMMATRIX mTranslate = XMMatrixTranslation( parentPos.x, parentPos.y, parentPos.z ); + + XMVECTOR quat = XMVectorSet( pData->Orientation.x, pData->Orientation.y, pData->Orientation.z, pData->Orientation.w ); + if ( XMVector4Equal( quat, g_XMZero ) ) + quat = XMQuaternionIdentity(); + quat = XMQuaternionNormalize( quat ); + XMMATRIX mQuat = XMMatrixRotationQuaternion( quat ); + mLocalTransform = ( mQuat * mTranslate ); } else { - LocalTransform = m_pFrameArray[iFrame].Matrix; + mLocalTransform = XMLoadFloat4x4( &m_pFrameArray[iFrame].Matrix ); } // Transform ourselves - D3DXMATRIX LocalWorld; - D3DXMatrixMultiply( &LocalWorld, &LocalTransform, pParentWorld ); - m_pTransformedFrameMatrices[iFrame] = LocalWorld; - m_pWorldPoseFrameMatrices[iFrame] = LocalWorld; + XMMATRIX mLocalWorld = XMMatrixMultiply( mLocalTransform, parentWorld ); + XMStoreFloat4x4( &m_pTransformedFrameMatrices[iFrame], mLocalWorld ); + XMStoreFloat4x4( &m_pWorldPoseFrameMatrices[iFrame], mLocalWorld ); // Transform our siblings if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME ) - TransformFrame( m_pFrameArray[iFrame].SiblingFrame, pParentWorld, fTime ); + { + TransformFrame( m_pFrameArray[iFrame].SiblingFrame, parentWorld, fTime ); + } // Transform our children if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME ) - TransformFrame( m_pFrameArray[iFrame].ChildFrame, &LocalWorld, fTime ); + { + TransformFrame( m_pFrameArray[iFrame].ChildFrame, mLocalWorld, fTime ); + } } + //-------------------------------------------------------------------------------------- // transform frame assuming that it is an absolute transformation //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::TransformFrameAbsolute( UINT iFrame, double fTime ) { - D3DXMATRIX mTrans1; - D3DXMATRIX mTrans2; - D3DXMATRIX mRot1; - D3DXMATRIX mRot2; - D3DXQUATERNION quat1; - D3DXQUATERNION quat2; - D3DXMATRIX mTo; - D3DXMATRIX mInvTo; - D3DXMATRIX mFrom; - UINT iTick = GetAnimationKeyFromTime( fTime ); if( INVALID_ANIMATION_DATA != m_pFrameArray[iFrame].AnimationDataIndex ) { - SDKANIMATION_FRAME_DATA* pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; - SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[ iTick ]; - SDKANIMATION_DATA* pDataOrig = &pFrameData->pAnimationData[ 0 ]; - - D3DXMatrixTranslation( &mTrans1, -pDataOrig->Translation.x, - -pDataOrig->Translation.y, - -pDataOrig->Translation.z ); - D3DXMatrixTranslation( &mTrans2, pData->Translation.x, - pData->Translation.y, - pData->Translation.z ); - - quat1.x = pDataOrig->Orientation.x; - quat1.y = pDataOrig->Orientation.y; - quat1.z = pDataOrig->Orientation.z; - quat1.w = pDataOrig->Orientation.w; - D3DXQuaternionInverse( &quat1, &quat1 ); - D3DXMatrixRotationQuaternion( &mRot1, &quat1 ); - mInvTo = mTrans1 * mRot1; - - quat2.x = pData->Orientation.x; - quat2.y = pData->Orientation.y; - quat2.z = pData->Orientation.z; - quat2.w = pData->Orientation.w; - D3DXMatrixRotationQuaternion( &mRot2, &quat2 ); - mFrom = mRot2 * mTrans2; - - D3DXMATRIX mOutput = mInvTo * mFrom; - m_pTransformedFrameMatrices[iFrame] = mOutput; + auto pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ]; + auto pData = &pFrameData->pAnimationData[ iTick ]; + auto pDataOrig = &pFrameData->pAnimationData[ 0 ]; + + XMMATRIX mTrans1 = XMMatrixTranslation( -pDataOrig->Translation.x, -pDataOrig->Translation.y, -pDataOrig->Translation.z ); + XMMATRIX mTrans2 = XMMatrixTranslation( pData->Translation.x, pData->Translation.y, pData->Translation.z ); + + XMVECTOR quat1 = XMVectorSet( pDataOrig->Orientation.x, pDataOrig->Orientation.y, pDataOrig->Orientation.z, pDataOrig->Orientation.w ); + quat1 = XMQuaternionInverse( quat1 ); + XMMATRIX mRot1 = XMMatrixRotationQuaternion( quat1 ); + XMMATRIX mInvTo = mTrans1 * mRot1; + + XMVECTOR quat2 = XMVectorSet( pData->Orientation.x, pData->Orientation.y, pData->Orientation.z, pData->Orientation.w ); + XMMATRIX mRot2 = XMMatrixRotationQuaternion( quat2 ); + XMMATRIX mFrom = mRot2 * mTrans2; + + XMMATRIX mOutput = mInvTo * mFrom; + XMStoreFloat4x4( &m_pTransformedFrameMatrices[iFrame], mOutput ); } } #define MAX_D3D11_VERTEX_STREAMS D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT + //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::RenderMesh( UINT iMesh, bool bAdjacent, ID3D11DeviceContext* pd3dDeviceContext, @@ -732,7 +578,7 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, if( 0 < GetOutstandingBufferResources() ) return; - SDKMESH_MESH* pMesh = &m_pMeshArray[iMesh]; + auto pMesh = &m_pMeshArray[iMesh]; UINT Strides[MAX_D3D11_VERTEX_STREAMS]; UINT Offsets[MAX_D3D11_VERTEX_STREAMS]; @@ -754,7 +600,7 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, else pIndexBufferArray = m_pIndexBufferArray; - ID3D11Buffer* pIB = pIndexBufferArray[ pMesh->IndexBuffer ].pIB11; + auto pIB = pIndexBufferArray[ pMesh->IndexBuffer ].pIB11; DXGI_FORMAT ibFormat = DXGI_FORMAT_R16_UINT; switch( pIndexBufferArray[ pMesh->IndexBuffer ].IndexType ) { @@ -769,8 +615,8 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, pd3dDeviceContext->IASetVertexBuffers( 0, pMesh->NumVertexBuffers, pVB, Strides, Offsets ); pd3dDeviceContext->IASetIndexBuffer( pIB, ibFormat, 0 ); - SDKMESH_SUBSET* pSubset = NULL; - SDKMESH_MATERIAL* pMat = NULL; + SDKMESH_SUBSET* pSubset = nullptr; + SDKMESH_MATERIAL* pMat = nullptr; D3D11_PRIMITIVE_TOPOLOGY PrimType; for( UINT subset = 0; subset < pMesh->NumSubsets; subset++ ) @@ -821,6 +667,7 @@ void CDXUTSDKMesh::RenderMesh( UINT iMesh, } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::RenderFrame( UINT iFrame, bool bAdjacent, ID3D11DeviceContext* pd3dDeviceContext, @@ -853,140 +700,22 @@ void CDXUTSDKMesh::RenderFrame( UINT iFrame, } //-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::RenderMesh( UINT iMesh, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ) -{ - if( 0 < GetOutstandingBufferResources() ) - return; - - SDKMESH_MESH* pMesh = &m_pMeshArray[iMesh]; - - // set vb streams - for( UINT i = 0; i < ( UINT )pMesh->NumVertexBuffers; i++ ) - { - pd3dDevice->SetStreamSource( i, - m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].pVB9, - 0, - ( UINT )m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].StrideBytes ); - } - - // Set our index buffer as well - pd3dDevice->SetIndices( m_pIndexBufferArray[ pMesh->IndexBuffer ].pIB9 ); - - // Render the scene with this technique - pEffect->SetTechnique( hTechnique ); - - SDKMESH_SUBSET* pSubset = NULL; - SDKMESH_MATERIAL* pMat = NULL; - D3DPRIMITIVETYPE PrimType; - UINT cPasses = 0; - pEffect->Begin( &cPasses, 0 ); - - for( UINT p = 0; p < cPasses; ++p ) - { - pEffect->BeginPass( p ); - - for( UINT subset = 0; subset < pMesh->NumSubsets; subset++ ) - { - pSubset = &m_pSubsetArray[ pMesh->pSubsets[subset] ]; - - PrimType = GetPrimitiveType9( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType ); - - if( INVALID_MATERIAL != pSubset->MaterialID && m_pMeshHeader->NumMaterials > 0 ) - { - pMat = &m_pMaterialArray[ pSubset->MaterialID ]; - if( htxDiffuse && !IsErrorResource( pMat->pDiffuseTexture9 ) ) - pEffect->SetTexture( htxDiffuse, pMat->pDiffuseTexture9 ); - if( htxNormal && !IsErrorResource( pMat->pNormalTexture9 ) ) - pEffect->SetTexture( htxNormal, pMat->pNormalTexture9 ); - if( htxSpecular && !IsErrorResource( pMat->pSpecularTexture9 ) ) - pEffect->SetTexture( htxSpecular, pMat->pSpecularTexture9 ); - } - - pEffect->CommitChanges(); - - UINT PrimCount = ( UINT )pSubset->IndexCount; - UINT IndexStart = ( UINT )pSubset->IndexStart; - UINT VertexStart = ( UINT )pSubset->VertexStart; - UINT VertexCount = ( UINT )pSubset->VertexCount; - if( D3DPT_TRIANGLELIST == PrimType ) - PrimCount /= 3; - if( D3DPT_LINELIST == PrimType ) - PrimCount /= 2; - if( D3DPT_TRIANGLESTRIP == PrimType ) - PrimCount = ( PrimCount - 3 ) + 1; - if( D3DPT_LINESTRIP == PrimType ) - PrimCount -= 1; - - pd3dDevice->DrawIndexedPrimitive( PrimType, VertexStart, 0, VertexCount, IndexStart, PrimCount ); - } - - pEffect->EndPass(); - } - - pEffect->End(); -} - -//-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::RenderFrame( UINT iFrame, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ) -{ - if( !m_pStaticMeshData || !m_pFrameArray ) - return; - - if( m_pFrameArray[iFrame].Mesh != INVALID_MESH ) - { - RenderMesh( m_pFrameArray[iFrame].Mesh, - pd3dDevice, - pEffect, - hTechnique, - htxDiffuse, - htxNormal, - htxSpecular ); - } - - // Render our children - if( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME ) - RenderFrame( m_pFrameArray[iFrame].ChildFrame, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, - htxSpecular ); - - // Render our siblings - if( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME ) - RenderFrame( m_pFrameArray[iFrame].SiblingFrame, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, - htxSpecular ); -} - - -//-------------------------------------------------------------------------------------- CDXUTSDKMesh::CDXUTSDKMesh() : m_NumOutstandingResources( 0 ), m_bLoading( false ), m_hFile( 0 ), m_hFileMappingObject( 0 ), - m_pMeshHeader( NULL ), - m_pStaticMeshData( NULL ), - m_pHeapData( NULL ), - m_pAdjacencyIndexBufferArray( NULL ), - m_pAnimationData( NULL ), - m_pAnimationHeader( NULL ), - m_ppVertices( NULL ), - m_ppIndices( NULL ), - m_pBindPoseFrameMatrices( NULL ), - m_pTransformedFrameMatrices( NULL ), - m_pWorldPoseFrameMatrices( NULL ), - m_pDev9( NULL ), - m_pDev11( NULL ) + m_pMeshHeader( nullptr ), + m_pStaticMeshData( nullptr ), + m_pHeapData( nullptr ), + m_pAdjacencyIndexBufferArray( nullptr ), + m_pAnimationData( nullptr ), + m_pAnimationHeader( nullptr ), + m_ppVertices( nullptr ), + m_ppIndices( nullptr ), + m_pBindPoseFrameMatrices( nullptr ), + m_pTransformedFrameMatrices( nullptr ), + m_pWorldPoseFrameMatrices( nullptr ), + m_pDev11( nullptr ) { } @@ -998,38 +727,22 @@ CDXUTSDKMesh::~CDXUTSDKMesh() } //-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, LPCTSTR szFileName, bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS11* pLoaderCallbacks ) +_Use_decl_annotations_ +HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, LPCWSTR szFileName, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { - return CreateFromFile( pDev11, NULL, szFileName, bCreateAdjacencyIndices, pLoaderCallbacks, NULL ); + return CreateFromFile( pDev11, szFileName, pLoaderCallbacks ); } //-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( IDirect3DDevice9* pDev9, LPCTSTR szFileName, bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS9* pLoaderCallbacks ) +_Use_decl_annotations_ +HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, BYTE* pData, size_t DataBytes, bool bCopyStatic, SDKMESH_CALLBACKS11* pLoaderCallbacks ) { - return CreateFromFile( NULL, pDev9, szFileName, bCreateAdjacencyIndices, NULL, pLoaderCallbacks ); + return CreateFromMemory( pDev11, pData, DataBytes, bCopyStatic, pLoaderCallbacks ); } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, BYTE* pData, UINT DataBytes, bool bCreateAdjacencyIndices, - bool bCopyStatic, SDKMESH_CALLBACKS11* pLoaderCallbacks ) -{ - return CreateFromMemory( pDev11, NULL, pData, DataBytes, bCreateAdjacencyIndices, bCopyStatic, - pLoaderCallbacks, NULL ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::Create( IDirect3DDevice9* pDev9, BYTE* pData, UINT DataBytes, bool bCreateAdjacencyIndices, - bool bCopyStatic, SDKMESH_CALLBACKS9* pLoaderCallbacks ) -{ - return CreateFromMemory( NULL, pDev9, pData, DataBytes, bCreateAdjacencyIndices, bCopyStatic, NULL, - pLoaderCallbacks ); -} //-------------------------------------------------------------------------------------- -HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName ) +HRESULT CDXUTSDKMesh::LoadAnimation( _In_z_ const WCHAR* szFileName ) { HRESULT hr = E_FAIL; DWORD dwBytesRead = 0; @@ -1040,32 +753,42 @@ HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName ) V_RETURN( DXUTFindDXSDKMediaFileCch( strPath, MAX_PATH, szFileName ) ); // Open the file - HANDLE hFile = CreateFile( strPath, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + HANDLE hFile = CreateFile( strPath, FILE_READ_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_SEQUENTIAL_SCAN, nullptr ); if( INVALID_HANDLE_VALUE == hFile ) return DXUTERR_MEDIANOTFOUND; ///////////////////////// // Header SDKANIMATION_FILE_HEADER fileheader; - if( !ReadFile( hFile, &fileheader, sizeof( SDKANIMATION_FILE_HEADER ), &dwBytesRead, NULL ) ) - goto Error; + if( !ReadFile( hFile, &fileheader, sizeof( SDKANIMATION_FILE_HEADER ), &dwBytesRead, nullptr ) ) + { + CloseHandle(hFile); + return HRESULT_FROM_WIN32(GetLastError()); + } //allocate - m_pAnimationData = new BYTE[ ( size_t )( sizeof( SDKANIMATION_FILE_HEADER ) + fileheader.AnimationDataSize ) ]; + m_pAnimationData = new (std::nothrow) BYTE[ ( size_t )( sizeof( SDKANIMATION_FILE_HEADER ) + fileheader.AnimationDataSize ) ]; if( !m_pAnimationData ) { - hr = E_OUTOFMEMORY; - goto Error; + CloseHandle(hFile); + return E_OUTOFMEMORY; } // read it all in liMove.QuadPart = 0; - if( !SetFilePointerEx( hFile, liMove, NULL, FILE_BEGIN ) ) - goto Error; + if( !SetFilePointerEx( hFile, liMove, nullptr, FILE_BEGIN ) ) + { + CloseHandle(hFile); + return HRESULT_FROM_WIN32(GetLastError()); + } + if( !ReadFile( hFile, m_pAnimationData, ( DWORD )( sizeof( SDKANIMATION_FILE_HEADER ) + - fileheader.AnimationDataSize ), &dwBytesRead, NULL ) ) - goto Error; + fileheader.AnimationDataSize ), &dwBytesRead, nullptr ) ) + { + CloseHandle(hFile); + return HRESULT_FROM_WIN32(GetLastError()); + } // pointer fixup m_pAnimationHeader = ( SDKANIMATION_FILE_HEADER* )m_pAnimationData; @@ -1077,17 +800,14 @@ HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName ) m_pAnimationFrameData[i].pAnimationData = ( SDKANIMATION_DATA* )( m_pAnimationData + m_pAnimationFrameData[i].DataOffset + BaseOffset ); - SDKMESH_FRAME* pFrame = FindFrame( m_pAnimationFrameData[i].FrameName ); + auto pFrame = FindFrame( m_pAnimationFrameData[i].FrameName ); if( pFrame ) { pFrame->AnimationDataIndex = i; } } - hr = S_OK; -Error: - CloseHandle( hFile ); - return hr; + return S_OK; } //-------------------------------------------------------------------------------------- @@ -1102,18 +822,8 @@ void CDXUTSDKMesh::Destroy() { for( UINT64 m = 0; m < m_pMeshHeader->NumMaterials; m++ ) { - if( m_pDev9 ) - { - if( !IsErrorResource( m_pMaterialArray[m].pDiffuseTexture9 ) ) - SAFE_RELEASE( m_pMaterialArray[m].pDiffuseTexture9 ); - if( !IsErrorResource( m_pMaterialArray[m].pNormalTexture9 ) ) - SAFE_RELEASE( m_pMaterialArray[m].pNormalTexture9 ); - if( !IsErrorResource( m_pMaterialArray[m].pSpecularTexture9 ) ) - SAFE_RELEASE( m_pMaterialArray[m].pSpecularTexture9 ); - } - else if( m_pDev11 ) + if( m_pDev11 ) { - //ID3D11Resource* pRes = NULL; if( m_pMaterialArray[m].pDiffuseRV11 && !IsErrorResource( m_pMaterialArray[m].pDiffuseRV11 ) ) { //m_pMaterialArray[m].pDiffuseRV11->GetResource( &pRes ); @@ -1138,17 +848,14 @@ void CDXUTSDKMesh::Destroy() } } } - for( UINT64 i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) { - if( !IsErrorResource( m_pVertexBufferArray[i].pVB9 ) ) - SAFE_RELEASE( m_pVertexBufferArray[i].pVB9 ); + SAFE_RELEASE( m_pVertexBufferArray[i].pVB11 ); } for( UINT64 i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) { - if( !IsErrorResource( m_pIndexBufferArray[i].pIB9 ) ) - SAFE_RELEASE( m_pIndexBufferArray[i].pIB9 ); + SAFE_RELEASE( m_pIndexBufferArray[i].pIB11 ); } } @@ -1162,7 +869,7 @@ void CDXUTSDKMesh::Destroy() SAFE_DELETE_ARRAY( m_pAdjacencyIndexBufferArray ); SAFE_DELETE_ARRAY( m_pHeapData ); - m_pStaticMeshData = NULL; + m_pStaticMeshData = nullptr; SAFE_DELETE_ARRAY( m_pAnimationData ); SAFE_DELETE_ARRAY( m_pBindPoseFrameMatrices ); SAFE_DELETE_ARRAY( m_pTransformedFrameMatrices ); @@ -1171,45 +878,39 @@ void CDXUTSDKMesh::Destroy() SAFE_DELETE_ARRAY( m_ppVertices ); SAFE_DELETE_ARRAY( m_ppIndices ); - m_pMeshHeader = NULL; - m_pVertexBufferArray = NULL; - m_pIndexBufferArray = NULL; - m_pMeshArray = NULL; - m_pSubsetArray = NULL; - m_pFrameArray = NULL; - m_pMaterialArray = NULL; + m_pMeshHeader = nullptr; + m_pVertexBufferArray = nullptr; + m_pIndexBufferArray = nullptr; + m_pMeshArray = nullptr; + m_pSubsetArray = nullptr; + m_pFrameArray = nullptr; + m_pMaterialArray = nullptr; - m_pAnimationHeader = NULL; - m_pAnimationFrameData = NULL; + m_pAnimationHeader = nullptr; + m_pAnimationFrameData = nullptr; } -//-------------------------------------------------------------------------------------- -// transform the bind pose -//-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformBindPose( D3DXMATRIX* pWorld ) -{ - TransformBindPoseFrame( 0, pWorld ); -} //-------------------------------------------------------------------------------------- // transform the mesh frames according to the animation for time fTime //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::TransformMesh( D3DXMATRIX* pWorld, double fTime ) +_Use_decl_annotations_ +void CDXUTSDKMesh::TransformMesh( CXMMATRIX world, double fTime ) { - if( m_pAnimationHeader == NULL || FTT_RELATIVE == m_pAnimationHeader->FrameTransformType ) + if( !m_pAnimationHeader || FTT_RELATIVE == m_pAnimationHeader->FrameTransformType ) { - TransformFrame( 0, pWorld, fTime ); + TransformFrame( 0, world, fTime ); // For each frame, move the transform to the bind pose, then // move it to the final position - D3DXMATRIX mInvBindPose; - D3DXMATRIX mFinal; for( UINT i = 0; i < m_pMeshHeader->NumFrames; i++ ) { - D3DXMatrixInverse( &mInvBindPose, NULL, &m_pBindPoseFrameMatrices[i] ); - mFinal = mInvBindPose * m_pTransformedFrameMatrices[i]; - m_pTransformedFrameMatrices[i] = mFinal; + XMMATRIX m = XMLoadFloat4x4( &m_pBindPoseFrameMatrices[i] ); + XMMATRIX mInvBindPose = XMMatrixInverse( nullptr, m ); + m = XMLoadFloat4x4( &m_pTransformedFrameMatrices[i] ); + XMMATRIX mFinal = mInvBindPose * m; + XMStoreFloat4x4( &m_pTransformedFrameMatrices[i], mFinal ); } } else if( FTT_ABSOLUTE == m_pAnimationHeader->FrameTransformType ) @@ -1221,6 +922,7 @@ void CDXUTSDKMesh::TransformMesh( D3DXMATRIX* pWorld, double fTime ) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::Render( ID3D11DeviceContext* pd3dDeviceContext, UINT iDiffuseSlot, UINT iNormalSlot, @@ -1230,6 +932,7 @@ void CDXUTSDKMesh::Render( ID3D11DeviceContext* pd3dDeviceContext, } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTSDKMesh::RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext, UINT iDiffuseSlot, UINT iNormalSlot, @@ -1240,18 +943,7 @@ void CDXUTSDKMesh::RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext, //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ) -{ - RenderFrame( 0, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, htxSpecular ); -} - -//-------------------------------------------------------------------------------------- -D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( SDKMESH_PRIMITIVE_TYPE PrimType ) +D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( _In_ SDKMESH_PRIMITIVE_TYPE PrimType ) { D3D11_PRIMITIVE_TOPOLOGY retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; @@ -1290,7 +982,7 @@ D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( SDKMESH_PRIMITIVE_TYP } //-------------------------------------------------------------------------------------- -DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( UINT iMesh ) +DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( _In_ UINT iMesh ) const { switch( m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].IndexType ) { @@ -1303,92 +995,40 @@ DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( UINT iMesh ) } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetVB11( UINT iMesh, UINT iVB ) +ID3D11Buffer* CDXUTSDKMesh::GetVB11( _In_ UINT iMesh, _In_ UINT iVB ) const { return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].pVB11; } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetIB11( UINT iMesh ) +ID3D11Buffer* CDXUTSDKMesh::GetIB11( _In_ UINT iMesh ) const { return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB11; } -SDKMESH_INDEX_TYPE CDXUTSDKMesh::GetIndexType( UINT iMesh ) +SDKMESH_INDEX_TYPE CDXUTSDKMesh::GetIndexType( _In_ UINT iMesh ) const { return ( SDKMESH_INDEX_TYPE ) m_pIndexBufferArray[m_pMeshArray[ iMesh ].IndexBuffer].IndexType; } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetAdjIB11( UINT iMesh ) +ID3D11Buffer* CDXUTSDKMesh::GetAdjIB11( _In_ UINT iMesh ) const { return m_pAdjacencyIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB11; } //-------------------------------------------------------------------------------------- -D3DPRIMITIVETYPE CDXUTSDKMesh::GetPrimitiveType9( SDKMESH_PRIMITIVE_TYPE PrimType ) -{ - D3DPRIMITIVETYPE retType = D3DPT_TRIANGLELIST; - - switch( PrimType ) - { - case PT_TRIANGLE_LIST: - retType = D3DPT_TRIANGLELIST; - break; - case PT_TRIANGLE_STRIP: - retType = D3DPT_TRIANGLESTRIP; - break; - case PT_LINE_LIST: - retType = D3DPT_LINELIST; - break; - case PT_LINE_STRIP: - retType = D3DPT_LINESTRIP; - break; - case PT_POINT_LIST: - retType = D3DPT_POINTLIST; - break; - }; - - return retType; -} - -//-------------------------------------------------------------------------------------- -D3DFORMAT CDXUTSDKMesh::GetIBFormat9( UINT iMesh ) -{ - switch( m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].IndexType ) - { - case IT_16BIT: - return D3DFMT_INDEX16; - case IT_32BIT: - return D3DFMT_INDEX32; - }; - return D3DFMT_INDEX16; -} - -//-------------------------------------------------------------------------------------- -IDirect3DVertexBuffer9* CDXUTSDKMesh::GetVB9( UINT iMesh, UINT iVB ) -{ - return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].pVB9; -} - -//-------------------------------------------------------------------------------------- -IDirect3DIndexBuffer9* CDXUTSDKMesh::GetIB9( UINT iMesh ) -{ - return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB9; -} - -//-------------------------------------------------------------------------------------- -char* CDXUTSDKMesh::GetMeshPathA() +const char* CDXUTSDKMesh::GetMeshPathA() const { return m_strPath; } //-------------------------------------------------------------------------------------- -WCHAR* CDXUTSDKMesh::GetMeshPathW() +const WCHAR* CDXUTSDKMesh::GetMeshPathW() const { return m_strPathW; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumMeshes() +UINT CDXUTSDKMesh::GetNumMeshes() const { if( !m_pMeshHeader ) return 0; @@ -1396,7 +1036,7 @@ UINT CDXUTSDKMesh::GetNumMeshes() } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumMaterials() +UINT CDXUTSDKMesh::GetNumMaterials() const { if( !m_pMeshHeader ) return 0; @@ -1404,7 +1044,7 @@ UINT CDXUTSDKMesh::GetNumMaterials() } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumVBs() +UINT CDXUTSDKMesh::GetNumVBs() const { if( !m_pMeshHeader ) return 0; @@ -1412,7 +1052,7 @@ UINT CDXUTSDKMesh::GetNumVBs() } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumIBs() +UINT CDXUTSDKMesh::GetNumIBs() const { if( !m_pMeshHeader ) return 0; @@ -1420,86 +1060,74 @@ UINT CDXUTSDKMesh::GetNumIBs() } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetVB11At( UINT iVB ) +ID3D11Buffer* CDXUTSDKMesh::GetVB11At( _In_ UINT iVB ) const { return m_pVertexBufferArray[ iVB ].pVB11; } //-------------------------------------------------------------------------------------- -ID3D11Buffer* CDXUTSDKMesh::GetIB11At( UINT iIB ) +ID3D11Buffer* CDXUTSDKMesh::GetIB11At( _In_ UINT iIB ) const { return m_pIndexBufferArray[ iIB ].pIB11; } //-------------------------------------------------------------------------------------- -IDirect3DVertexBuffer9* CDXUTSDKMesh::GetVB9At( UINT iVB ) -{ - return m_pVertexBufferArray[ iVB ].pVB9; -} - -//-------------------------------------------------------------------------------------- -IDirect3DIndexBuffer9* CDXUTSDKMesh::GetIB9At( UINT iIB ) -{ - return m_pIndexBufferArray[ iIB ].pIB9; -} - -//-------------------------------------------------------------------------------------- -BYTE* CDXUTSDKMesh::GetRawVerticesAt( UINT iVB ) +BYTE* CDXUTSDKMesh::GetRawVerticesAt( _In_ UINT iVB ) const { return m_ppVertices[iVB]; } //-------------------------------------------------------------------------------------- -BYTE* CDXUTSDKMesh::GetRawIndicesAt( UINT iIB ) +BYTE* CDXUTSDKMesh::GetRawIndicesAt( _In_ UINT iIB ) const { return m_ppIndices[iIB]; } //-------------------------------------------------------------------------------------- -SDKMESH_MATERIAL* CDXUTSDKMesh::GetMaterial( UINT iMaterial ) +SDKMESH_MATERIAL* CDXUTSDKMesh::GetMaterial( _In_ UINT iMaterial ) const { return &m_pMaterialArray[ iMaterial ]; } //-------------------------------------------------------------------------------------- -SDKMESH_MESH* CDXUTSDKMesh::GetMesh( UINT iMesh ) +SDKMESH_MESH* CDXUTSDKMesh::GetMesh( _In_ UINT iMesh ) const { return &m_pMeshArray[ iMesh ]; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumSubsets( UINT iMesh ) +UINT CDXUTSDKMesh::GetNumSubsets( _In_ UINT iMesh ) const { return m_pMeshArray[ iMesh ].NumSubsets; } //-------------------------------------------------------------------------------------- -SDKMESH_SUBSET* CDXUTSDKMesh::GetSubset( UINT iMesh, UINT iSubset ) +SDKMESH_SUBSET* CDXUTSDKMesh::GetSubset( _In_ UINT iMesh, _In_ UINT iSubset ) const { return &m_pSubsetArray[ m_pMeshArray[ iMesh ].pSubsets[iSubset] ]; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetVertexStride( UINT iMesh, UINT iVB ) +UINT CDXUTSDKMesh::GetVertexStride( _In_ UINT iMesh, _In_ UINT iVB ) const { return ( UINT )m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].StrideBytes; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumFrames() +UINT CDXUTSDKMesh::GetNumFrames() const { return m_pMeshHeader->NumFrames; } //-------------------------------------------------------------------------------------- -SDKMESH_FRAME* CDXUTSDKMesh::GetFrame( UINT iFrame ) +SDKMESH_FRAME* CDXUTSDKMesh::GetFrame( _In_ UINT iFrame ) const { assert( iFrame < m_pMeshHeader->NumFrames ); return &m_pFrameArray[ iFrame ]; } //-------------------------------------------------------------------------------------- -SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( char* pszName ) +SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( _In_z_ const char* pszName ) const { for( UINT i = 0; i < m_pMeshHeader->NumFrames; i++ ) { @@ -1508,35 +1136,35 @@ SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( char* pszName ) return &m_pFrameArray[i]; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -UINT64 CDXUTSDKMesh::GetNumVertices( UINT iMesh, UINT iVB ) +UINT64 CDXUTSDKMesh::GetNumVertices( _In_ UINT iMesh, _In_ UINT iVB ) const { return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].NumVertices; } //-------------------------------------------------------------------------------------- -UINT64 CDXUTSDKMesh::GetNumIndices( UINT iMesh ) +UINT64 CDXUTSDKMesh::GetNumIndices( _In_ UINT iMesh ) const { return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].NumIndices; } //-------------------------------------------------------------------------------------- -D3DXVECTOR3 CDXUTSDKMesh::GetMeshBBoxCenter( UINT iMesh ) +XMVECTOR CDXUTSDKMesh::GetMeshBBoxCenter( _In_ UINT iMesh ) const { - return m_pMeshArray[iMesh].BoundingBoxCenter; + return XMLoadFloat3( &m_pMeshArray[iMesh].BoundingBoxCenter ); } //-------------------------------------------------------------------------------------- -D3DXVECTOR3 CDXUTSDKMesh::GetMeshBBoxExtents( UINT iMesh ) +XMVECTOR CDXUTSDKMesh::GetMeshBBoxExtents( _In_ UINT iMesh ) const { - return m_pMeshArray[iMesh].BoundingBoxExtents; + return XMLoadFloat3( &m_pMeshArray[iMesh].BoundingBoxExtents ); } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetOutstandingResources() +UINT CDXUTSDKMesh::GetOutstandingResources() const { UINT outstandingResources = 0; if( !m_pMeshHeader ) @@ -1544,9 +1172,9 @@ UINT CDXUTSDKMesh::GetOutstandingResources() outstandingResources += GetOutstandingBufferResources(); - if( m_pDev11 ) - { - for( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ ) + if( m_pDev11 ) + { + for( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ ) { if( m_pMaterialArray[i].DiffuseTexture[0] != 0 ) { @@ -1566,54 +1194,18 @@ UINT CDXUTSDKMesh::GetOutstandingResources() outstandingResources ++; } } - } - else - { - for( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ ) - { - if( m_pMaterialArray[i].DiffuseTexture[0] != 0 ) - { - if( !m_pMaterialArray[i].pDiffuseTexture9 && !IsErrorResource( m_pMaterialArray[i].pDiffuseTexture9 ) ) - outstandingResources ++; - } - - if( m_pMaterialArray[i].NormalTexture[0] != 0 ) - { - if( !m_pMaterialArray[i].pNormalTexture9 && !IsErrorResource( m_pMaterialArray[i].pNormalTexture9 ) ) - outstandingResources ++; - } - - if( m_pMaterialArray[i].SpecularTexture[0] != 0 ) - { - if( !m_pMaterialArray[i].pSpecularTexture9 && - !IsErrorResource( m_pMaterialArray[i].pSpecularTexture9 ) ) - outstandingResources ++; - } - } } return outstandingResources; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetOutstandingBufferResources() +UINT CDXUTSDKMesh::GetOutstandingBufferResources() const { UINT outstandingResources = 0; if( !m_pMeshHeader ) return 1; - for( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) - { - if( !m_pVertexBufferArray[i].pVB9 && !IsErrorResource( m_pVertexBufferArray[i].pVB9 ) ) - outstandingResources ++; - } - - for( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) - { - if( !m_pIndexBufferArray[i].pIB9 && !IsErrorResource( m_pIndexBufferArray[i].pIB9 ) ) - outstandingResources ++; - } - return outstandingResources; } @@ -1630,7 +1222,7 @@ bool CDXUTSDKMesh::CheckLoadDone() } //-------------------------------------------------------------------------------------- -bool CDXUTSDKMesh::IsLoaded() +bool CDXUTSDKMesh::IsLoaded() const { if( m_pStaticMeshData && !m_bLoading ) { @@ -1641,65 +1233,51 @@ bool CDXUTSDKMesh::IsLoaded() } //-------------------------------------------------------------------------------------- -bool CDXUTSDKMesh::IsLoading() +bool CDXUTSDKMesh::IsLoading() const { return m_bLoading; } //-------------------------------------------------------------------------------------- -void CDXUTSDKMesh::SetLoading( bool bLoading ) +void CDXUTSDKMesh::SetLoading( _In_ bool bLoading ) { m_bLoading = bLoading; } //-------------------------------------------------------------------------------------- -BOOL CDXUTSDKMesh::HadLoadingError() +BOOL CDXUTSDKMesh::HadLoadingError() const { - if( m_pMeshHeader ) - { - for( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ ) - { - if( IsErrorResource( m_pVertexBufferArray[i].pVB9 ) ) - return TRUE; - } - - for( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ ) - { - if( IsErrorResource( m_pIndexBufferArray[i].pIB9 ) ) - return TRUE; - } - } - return FALSE; } //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetNumInfluences( UINT iMesh ) +UINT CDXUTSDKMesh::GetNumInfluences( _In_ UINT iMesh ) const { return m_pMeshArray[iMesh].NumFrameInfluences; } //-------------------------------------------------------------------------------------- -const D3DXMATRIX* CDXUTSDKMesh::GetMeshInfluenceMatrix( UINT iMesh, UINT iInfluence ) +XMMATRIX CDXUTSDKMesh::GetMeshInfluenceMatrix( _In_ UINT iMesh, _In_ UINT iInfluence ) const { UINT iFrame = m_pMeshArray[iMesh].pFrameInfluences[ iInfluence ]; - return &m_pTransformedFrameMatrices[iFrame]; + return XMLoadFloat4x4( &m_pTransformedFrameMatrices[iFrame] ); } -const D3DXMATRIX* CDXUTSDKMesh::GetWorldMatrix( UINT iFrameIndex ) +XMMATRIX CDXUTSDKMesh::GetWorldMatrix( _In_ UINT iFrameIndex ) const { - return &m_pWorldPoseFrameMatrices[iFrameIndex]; + return XMLoadFloat4x4( &m_pWorldPoseFrameMatrices[iFrameIndex] ); } -const D3DXMATRIX* CDXUTSDKMesh::GetInfluenceMatrix( UINT iFrameIndex ) +XMMATRIX CDXUTSDKMesh::GetInfluenceMatrix( _In_ UINT iFrameIndex ) const { - return &m_pTransformedFrameMatrices[iFrameIndex]; + return XMLoadFloat4x4( &m_pTransformedFrameMatrices[iFrameIndex] ); } + //-------------------------------------------------------------------------------------- -UINT CDXUTSDKMesh::GetAnimationKeyFromTime( double fTime ) +UINT CDXUTSDKMesh::GetAnimationKeyFromTime( _In_ double fTime ) const { - if( m_pAnimationHeader == NULL ) + if( !m_pAnimationHeader ) { return 0; } @@ -1712,638 +1290,18 @@ UINT CDXUTSDKMesh::GetAnimationKeyFromTime( double fTime ) return iTick; } -bool CDXUTSDKMesh::GetAnimationProperties( UINT* pNumKeys, FLOAT* pFrameTime ) +_Use_decl_annotations_ +bool CDXUTSDKMesh::GetAnimationProperties( UINT* pNumKeys, float* pFrameTime ) const { - if( m_pAnimationHeader == NULL ) + if( !m_pAnimationHeader ) { + *pNumKeys = 0; + *pFrameTime = 0; return false; } *pNumKeys = m_pAnimationHeader->NumAnimationKeys; - *pFrameTime = 1.0f / (FLOAT)m_pAnimationHeader->AnimationFPS; + *pFrameTime = 1.0f / (float)m_pAnimationHeader->AnimationFPS; return true; } - - -//------------------------------------------------------------------------------------- -// CDXUTXFileMesh implementation. -//------------------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -CDXUTXFileMesh::CDXUTXFileMesh( LPCWSTR strName ) -{ - wcscpy_s( m_strName, 512, strName ); - m_pMesh = NULL; - m_pMaterials = NULL; - m_pTextures = NULL; - m_bUseMaterials = TRUE; - m_pVB = NULL; - m_pIB = NULL; - m_pDecl = NULL; - m_strMaterials = NULL; - m_dwNumMaterials = 0; - m_dwNumVertices = 0; - m_dwNumFaces = 0; - m_dwBytesPerVertex = 0; -} - - - - -//----------------------------------------------------------------------------- -CDXUTXFileMesh::~CDXUTXFileMesh() -{ - Destroy(); -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, LPCWSTR strFilename ) -{ - WCHAR strPath[MAX_PATH]; - LPD3DXBUFFER pAdjacencyBuffer = NULL; - LPD3DXBUFFER pMtrlBuffer = NULL; - HRESULT hr; - - // Cleanup previous mesh if any - Destroy(); - - // Find the path for the file, and convert it to ANSI (for the D3DX API) - DXUTFindDXSDKMediaFileCch( strPath, sizeof( strPath ) / sizeof( WCHAR ), strFilename ); - - // Load the mesh - if( FAILED( hr = D3DXLoadMeshFromX( strPath, D3DXMESH_MANAGED, pd3dDevice, - &pAdjacencyBuffer, &pMtrlBuffer, NULL, - &m_dwNumMaterials, &m_pMesh ) ) ) - { - return hr; - } - - // Optimize the mesh for performance - if( FAILED( hr = m_pMesh->OptimizeInplace( - D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, - ( DWORD* )pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) ) - { - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - return hr; - } - - // Set strPath to the path of the mesh file - WCHAR* pLastBSlash = wcsrchr( strPath, L'\\' ); - if( pLastBSlash ) - *( pLastBSlash + 1 ) = L'\0'; - else - *strPath = L'\0'; - - D3DXMATERIAL* d3dxMtrls = ( D3DXMATERIAL* )pMtrlBuffer->GetBufferPointer(); - hr = CreateMaterials( strPath, pd3dDevice, d3dxMtrls, m_dwNumMaterials ); - - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - - // Extract data from m_pMesh for easy access - D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; - m_dwNumVertices = m_pMesh->GetNumVertices(); - m_dwNumFaces = m_pMesh->GetNumFaces(); - m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex(); - m_pMesh->GetIndexBuffer( &m_pIB ); - m_pMesh->GetVertexBuffer( &m_pVB ); - m_pMesh->GetDeclaration( decl ); - pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl ); - - return hr; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXFILEDATA pFileData ) -{ - LPD3DXBUFFER pMtrlBuffer = NULL; - LPD3DXBUFFER pAdjacencyBuffer = NULL; - HRESULT hr; - - // Cleanup previous mesh if any - Destroy(); - - // Load the mesh from the DXFILEDATA object - if( FAILED( hr = D3DXLoadMeshFromXof( pFileData, D3DXMESH_MANAGED, pd3dDevice, - &pAdjacencyBuffer, &pMtrlBuffer, NULL, - &m_dwNumMaterials, &m_pMesh ) ) ) - { - return hr; - } - - // Optimize the mesh for performance - if( FAILED( hr = m_pMesh->OptimizeInplace( - D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, - ( DWORD* )pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) ) - { - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - return hr; - } - - D3DXMATERIAL* d3dxMtrls = ( D3DXMATERIAL* )pMtrlBuffer->GetBufferPointer(); - hr = CreateMaterials( L"", pd3dDevice, d3dxMtrls, m_dwNumMaterials ); - - SAFE_RELEASE( pAdjacencyBuffer ); - SAFE_RELEASE( pMtrlBuffer ); - - // Extract data from m_pMesh for easy access - D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; - m_dwNumVertices = m_pMesh->GetNumVertices(); - m_dwNumFaces = m_pMesh->GetNumFaces(); - m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex(); - m_pMesh->GetIndexBuffer( &m_pIB ); - m_pMesh->GetVertexBuffer( &m_pVB ); - m_pMesh->GetDeclaration( decl ); - pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl ); - - return hr; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh* pInMesh, - D3DXMATERIAL* pd3dxMaterials, DWORD dwMaterials ) -{ - // Cleanup previous mesh if any - Destroy(); - - // Optimize the mesh for performance - DWORD* rgdwAdjacency = NULL; - rgdwAdjacency = new DWORD[pInMesh->GetNumFaces() * 3]; - if( rgdwAdjacency == NULL ) - return E_OUTOFMEMORY; - pInMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ); - - D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE]; - pInMesh->GetDeclaration( decl ); - - DWORD dwOptions = pInMesh->GetOptions(); - dwOptions &= ~( D3DXMESH_32BIT | D3DXMESH_SYSTEMMEM | D3DXMESH_WRITEONLY ); - dwOptions |= D3DXMESH_MANAGED; - dwOptions |= D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE; - - ID3DXMesh* pTempMesh = NULL; - if( FAILED( pInMesh->Optimize( dwOptions, rgdwAdjacency, NULL, NULL, NULL, &pTempMesh ) ) ) - { - SAFE_DELETE_ARRAY( rgdwAdjacency ); - return E_FAIL; - } - - SAFE_DELETE_ARRAY( rgdwAdjacency ); - SAFE_RELEASE( m_pMesh ); - m_pMesh = pTempMesh; - - HRESULT hr; - hr = CreateMaterials( L"", pd3dDevice, pd3dxMaterials, dwMaterials ); - - // Extract data from m_pMesh for easy access - m_dwNumVertices = m_pMesh->GetNumVertices(); - m_dwNumFaces = m_pMesh->GetNumFaces(); - m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex(); - m_pMesh->GetIndexBuffer( &m_pIB ); - m_pMesh->GetVertexBuffer( &m_pVB ); - m_pMesh->GetDeclaration( decl ); - pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl ); - - return hr; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::CreateMaterials( LPCWSTR strPath, IDirect3DDevice9* pd3dDevice, D3DXMATERIAL* d3dxMtrls, - DWORD dwNumMaterials ) -{ - // Get material info for the mesh - // Get the array of materials out of the buffer - m_dwNumMaterials = dwNumMaterials; - if( d3dxMtrls && m_dwNumMaterials > 0 ) - { - // Allocate memory for the materials and textures - m_pMaterials = new D3DMATERIAL9[m_dwNumMaterials]; - if( m_pMaterials == NULL ) - return E_OUTOFMEMORY; - m_pTextures = new LPDIRECT3DBASETEXTURE9[m_dwNumMaterials]; - if( m_pTextures == NULL ) - return E_OUTOFMEMORY; - m_strMaterials = new CHAR[m_dwNumMaterials][MAX_PATH]; - if( m_strMaterials == NULL ) - return E_OUTOFMEMORY; - - // Copy each material and create its texture - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - // Copy the material - m_pMaterials[i] = d3dxMtrls[i].MatD3D; - m_pTextures[i] = NULL; - - // Create a texture - if( d3dxMtrls[i].pTextureFilename ) - { - strcpy_s( m_strMaterials[i], MAX_PATH, d3dxMtrls[i].pTextureFilename ); - - WCHAR strTexture[MAX_PATH]; - WCHAR strTextureTemp[MAX_PATH]; - D3DXIMAGE_INFO ImgInfo; - - // First attempt to look for texture in the same folder as the input folder. - MultiByteToWideChar( CP_ACP, 0, d3dxMtrls[i].pTextureFilename, -1, strTextureTemp, MAX_PATH ); - strTextureTemp[MAX_PATH - 1] = 0; - - wcscpy_s( strTexture, MAX_PATH, strPath ); - wcscat_s( strTexture, MAX_PATH, strTextureTemp ); - - // Inspect the texture file to determine the texture type. - if( FAILED( D3DXGetImageInfoFromFile( strTexture, &ImgInfo ) ) ) - { - // Search the media folder - if( FAILED( DXUTFindDXSDKMediaFileCch( strTexture, MAX_PATH, strTextureTemp ) ) ) - continue; // Can't find. Skip. - - D3DXGetImageInfoFromFile( strTexture, &ImgInfo ); - } - - // Call the appropriate loader according to the texture type. - switch( ImgInfo.ResourceType ) - { - case D3DRTYPE_TEXTURE: - { - IDirect3DTexture9* pTex; - if( SUCCEEDED( D3DXCreateTextureFromFile( pd3dDevice, strTexture, &pTex ) ) ) - { - // Obtain the base texture interface - pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] ); - // Release the specialized instance - pTex->Release(); - } - break; - } - case D3DRTYPE_CUBETEXTURE: - { - IDirect3DCubeTexture9* pTex; - if( SUCCEEDED( D3DXCreateCubeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) ) - { - // Obtain the base texture interface - pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] ); - // Release the specialized instance - pTex->Release(); - } - break; - } - case D3DRTYPE_VOLUMETEXTURE: - { - IDirect3DVolumeTexture9* pTex; - if( SUCCEEDED( D3DXCreateVolumeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) ) - { - // Obtain the base texture interface - pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] ); - // Release the specialized instance - pTex->Release(); - } - break; - } - } - } - } - } - return S_OK; -} - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::SetFVF( LPDIRECT3DDEVICE9 pd3dDevice, DWORD dwFVF ) -{ - LPD3DXMESH pTempMesh = NULL; - - if( m_pMesh ) - { - if( FAILED( m_pMesh->CloneMeshFVF( m_pMesh->GetOptions(), dwFVF, - pd3dDevice, &pTempMesh ) ) ) - { - SAFE_RELEASE( pTempMesh ); - return E_FAIL; - } - - DWORD dwOldFVF = 0; - dwOldFVF = m_pMesh->GetFVF(); - SAFE_RELEASE( m_pMesh ); - m_pMesh = pTempMesh; - - // Compute normals if they are being requested and - // the old mesh does not have them. - if( !( dwOldFVF & D3DFVF_NORMAL ) && dwFVF & D3DFVF_NORMAL ) - { - D3DXComputeNormals( m_pMesh, NULL ); - } - } - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -// Convert the mesh to the format specified by the given vertex declarations. -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::SetVertexDecl( LPDIRECT3DDEVICE9 pd3dDevice, const D3DVERTEXELEMENT9* pDecl, - bool bAutoComputeNormals, bool bAutoComputeTangents, - bool bSplitVertexForOptimalTangents ) -{ - LPD3DXMESH pTempMesh = NULL; - - if( m_pMesh ) - { - if( FAILED( m_pMesh->CloneMesh( m_pMesh->GetOptions(), pDecl, - pd3dDevice, &pTempMesh ) ) ) - { - SAFE_RELEASE( pTempMesh ); - return E_FAIL; - } - } - - - // Check if the old declaration contains a normal. - bool bHadNormal = false; - bool bHadTangent = false; - D3DVERTEXELEMENT9 aOldDecl[MAX_FVF_DECL_SIZE]; - if( m_pMesh && SUCCEEDED( m_pMesh->GetDeclaration( aOldDecl ) ) ) - { - for( UINT index = 0; index < D3DXGetDeclLength( aOldDecl ); ++index ) - { - if( aOldDecl[index].Usage == D3DDECLUSAGE_NORMAL ) - { - bHadNormal = true; - } - if( aOldDecl[index].Usage == D3DDECLUSAGE_TANGENT ) - { - bHadTangent = true; - } - } - } - - // Check if the new declaration contains a normal. - bool bHaveNormalNow = false; - bool bHaveTangentNow = false; - D3DVERTEXELEMENT9 aNewDecl[MAX_FVF_DECL_SIZE]; - if( pTempMesh && SUCCEEDED( pTempMesh->GetDeclaration( aNewDecl ) ) ) - { - for( UINT index = 0; index < D3DXGetDeclLength( aNewDecl ); ++index ) - { - if( aNewDecl[index].Usage == D3DDECLUSAGE_NORMAL ) - { - bHaveNormalNow = true; - } - if( aNewDecl[index].Usage == D3DDECLUSAGE_TANGENT ) - { - bHaveTangentNow = true; - } - } - } - - SAFE_RELEASE( m_pMesh ); - - if( pTempMesh ) - { - m_pMesh = pTempMesh; - - if( !bHadNormal && bHaveNormalNow && bAutoComputeNormals ) - { - // Compute normals in case the meshes have them - D3DXComputeNormals( m_pMesh, NULL ); - } - - if( bHaveNormalNow && !bHadTangent && bHaveTangentNow && bAutoComputeTangents ) - { - ID3DXMesh* pNewMesh; - HRESULT hr; - - DWORD* rgdwAdjacency = NULL; - rgdwAdjacency = new DWORD[m_pMesh->GetNumFaces() * 3]; - if( rgdwAdjacency == NULL ) - return E_OUTOFMEMORY; - V( m_pMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) ); - - float fPartialEdgeThreshold; - float fSingularPointThreshold; - float fNormalEdgeThreshold; - if( bSplitVertexForOptimalTangents ) - { - fPartialEdgeThreshold = 0.01f; - fSingularPointThreshold = 0.25f; - fNormalEdgeThreshold = 0.01f; - } - else - { - fPartialEdgeThreshold = -1.01f; - fSingularPointThreshold = 0.01f; - fNormalEdgeThreshold = -1.01f; - } - - // Compute tangents, which are required for normal mapping - hr = D3DXComputeTangentFrameEx( m_pMesh, - D3DDECLUSAGE_TEXCOORD, 0, - D3DDECLUSAGE_TANGENT, 0, - D3DX_DEFAULT, 0, - D3DDECLUSAGE_NORMAL, 0, - 0, rgdwAdjacency, - fPartialEdgeThreshold, fSingularPointThreshold, fNormalEdgeThreshold, - &pNewMesh, NULL ); - - SAFE_DELETE_ARRAY( rgdwAdjacency ); - if( FAILED( hr ) ) - return hr; - - SAFE_RELEASE( m_pMesh ); - m_pMesh = pNewMesh; - } - } - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice ) -{ - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::InvalidateDeviceObjects() -{ - SAFE_RELEASE( m_pIB ); - SAFE_RELEASE( m_pVB ); - SAFE_RELEASE( m_pDecl ); - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Destroy() -{ - InvalidateDeviceObjects(); - for( UINT i = 0; i < m_dwNumMaterials; i++ ) - SAFE_RELEASE( m_pTextures[i] ); - SAFE_DELETE_ARRAY( m_pTextures ); - SAFE_DELETE_ARRAY( m_pMaterials ); - SAFE_DELETE_ARRAY( m_strMaterials ); - - SAFE_RELEASE( m_pMesh ); - - m_dwNumMaterials = 0L; - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice, bool bDrawOpaqueSubsets, - bool bDrawAlphaSubsets ) -{ - if( NULL == m_pMesh ) - return E_FAIL; - - // Frist, draw the subsets without alpha - if( bDrawOpaqueSubsets ) - { - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_bUseMaterials ) - { - if( m_pMaterials[i].Diffuse.a < 1.0f ) - continue; - pd3dDevice->SetMaterial( &m_pMaterials[i] ); - pd3dDevice->SetTexture( 0, m_pTextures[i] ); - } - m_pMesh->DrawSubset( i ); - } - } - - // Then, draw the subsets with alpha - if( bDrawAlphaSubsets && m_bUseMaterials ) - { - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_pMaterials[i].Diffuse.a == 1.0f ) - continue; - - // Set the material and texture - pd3dDevice->SetMaterial( &m_pMaterials[i] ); - pd3dDevice->SetTexture( 0, m_pTextures[i] ); - m_pMesh->DrawSubset( i ); - } - } - - return S_OK; -} - - - - -//----------------------------------------------------------------------------- -HRESULT CDXUTXFileMesh::Render( ID3DXEffect* pEffect, - D3DXHANDLE hTexture, - D3DXHANDLE hDiffuse, - D3DXHANDLE hAmbient, - D3DXHANDLE hSpecular, - D3DXHANDLE hEmissive, - D3DXHANDLE hPower, - bool bDrawOpaqueSubsets, - bool bDrawAlphaSubsets ) -{ - if( NULL == m_pMesh ) - return E_FAIL; - - UINT cPasses; - // Frist, draw the subsets without alpha - if( bDrawOpaqueSubsets ) - { - pEffect->Begin( &cPasses, 0 ); - for( UINT p = 0; p < cPasses; ++p ) - { - pEffect->BeginPass( p ); - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_bUseMaterials ) - { - if( m_pMaterials[i].Diffuse.a < 1.0f ) - continue; - if( hTexture ) - pEffect->SetTexture( hTexture, m_pTextures[i] ); - // D3DCOLORVALUE and D3DXVECTOR4 are data-wise identical. - // No conversion is needed. - if( hDiffuse ) - pEffect->SetVector( hDiffuse, ( D3DXVECTOR4* )&m_pMaterials[i].Diffuse ); - if( hAmbient ) - pEffect->SetVector( hAmbient, ( D3DXVECTOR4* )&m_pMaterials[i].Ambient ); - if( hSpecular ) - pEffect->SetVector( hSpecular, ( D3DXVECTOR4* )&m_pMaterials[i].Specular ); - if( hEmissive ) - pEffect->SetVector( hEmissive, ( D3DXVECTOR4* )&m_pMaterials[i].Emissive ); - if( hPower ) - pEffect->SetFloat( hPower, m_pMaterials[i].Power ); - pEffect->CommitChanges(); - } - m_pMesh->DrawSubset( i ); - } - pEffect->EndPass(); - } - pEffect->End(); - } - - // Then, draw the subsets with alpha - if( bDrawAlphaSubsets && m_bUseMaterials ) - { - pEffect->Begin( &cPasses, 0 ); - for( UINT p = 0; p < cPasses; ++p ) - { - pEffect->BeginPass( p ); - for( DWORD i = 0; i < m_dwNumMaterials; i++ ) - { - if( m_bUseMaterials ) - { - if( m_pMaterials[i].Diffuse.a == 1.0f ) - continue; - if( hTexture ) - pEffect->SetTexture( hTexture, m_pTextures[i] ); - // D3DCOLORVALUE and D3DXVECTOR4 are data-wise identical. - // No conversion is needed. - if( hDiffuse ) - pEffect->SetVector( hDiffuse, ( D3DXVECTOR4* )&m_pMaterials[i].Diffuse ); - if( hAmbient ) - pEffect->SetVector( hAmbient, ( D3DXVECTOR4* )&m_pMaterials[i].Ambient ); - if( hSpecular ) - pEffect->SetVector( hSpecular, ( D3DXVECTOR4* )&m_pMaterials[i].Specular ); - if( hEmissive ) - pEffect->SetVector( hEmissive, ( D3DXVECTOR4* )&m_pMaterials[i].Emissive ); - if( hPower ) - pEffect->SetFloat( hPower, m_pMaterials[i].Power ); - pEffect->CommitChanges(); - } - m_pMesh->DrawSubset( i ); - } - pEffect->EndPass(); - } - pEffect->End(); - } - - return S_OK; -} diff --git a/samples/DX_APIUsage/DXUT/Optional/SDKmesh.h b/samples/DX_APIUsage/DXUT/Optional/SDKmesh.h index 2032c52..8fba374 100644 --- a/samples/DX_APIUsage/DXUT/Optional/SDKmesh.h +++ b/samples/DX_APIUsage/DXUT/Optional/SDKmesh.h @@ -8,10 +8,14 @@ // meets the specific needs of the application. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef _SDKMESH_ -#define _SDKMESH_ + +#undef D3DCOLOR_ARGB +#include <d3d9.h> //-------------------------------------------------------------------------------------- // Hard Defines for the various structures @@ -40,7 +44,7 @@ template<typename TYPE> BOOL IsErrorResource( TYPE data ) return FALSE; } //-------------------------------------------------------------------------------------- -// Enumerated Types. These will have mirrors in both D3D9 and D3D11 +// Enumerated Types. //-------------------------------------------------------------------------------------- enum SDKMESH_PRIMITIVE_TYPE { @@ -72,6 +76,8 @@ enum FRAME_TRANSFORM_TYPE //-------------------------------------------------------------------------------------- // Structures. Unions with pointers are forced to 64bit. //-------------------------------------------------------------------------------------- +#pragma pack(push,8) + struct SDKMESH_HEADER { //Basic Info and sizes @@ -107,7 +113,6 @@ struct SDKMESH_VERTEX_BUFFER_HEADER union { UINT64 DataOffset; //(This also forces the union to 64bits) - IDirect3DVertexBuffer9* pVB9; ID3D11Buffer* pVB11; }; }; @@ -120,7 +125,6 @@ struct SDKMESH_INDEX_BUFFER_HEADER union { UINT64 DataOffset; //(This also forces the union to 64bits) - IDirect3DIndexBuffer9* pIB9; ID3D11Buffer* pIB11; }; }; @@ -134,8 +138,8 @@ struct SDKMESH_MESH UINT NumSubsets; UINT NumFrameInfluences; //aka bones - D3DXVECTOR3 BoundingBoxCenter; - D3DXVECTOR3 BoundingBoxExtents; + DirectX::XMFLOAT3 BoundingBoxCenter; + DirectX::XMFLOAT3 BoundingBoxExtents; union { @@ -167,7 +171,7 @@ struct SDKMESH_FRAME UINT ParentFrame; UINT ChildFrame; UINT SiblingFrame; - D3DXMATRIX Matrix; + DirectX::XMFLOAT4X4 Matrix; UINT AnimationDataIndex; //Used to index which set of keyframes transforms this frame }; @@ -183,28 +187,25 @@ struct SDKMESH_MATERIAL char NormalTexture[MAX_TEXTURE_NAME]; char SpecularTexture[MAX_TEXTURE_NAME]; - D3DXVECTOR4 Diffuse; - D3DXVECTOR4 Ambient; - D3DXVECTOR4 Specular; - D3DXVECTOR4 Emissive; - FLOAT Power; + DirectX::XMFLOAT4 Diffuse; + DirectX::XMFLOAT4 Ambient; + DirectX::XMFLOAT4 Specular; + DirectX::XMFLOAT4 Emissive; + float Power; union { UINT64 Force64_1; //Force the union to 64bits - IDirect3DTexture9* pDiffuseTexture9; ID3D11Texture2D* pDiffuseTexture11; }; union { UINT64 Force64_2; //Force the union to 64bits - IDirect3DTexture9* pNormalTexture9; ID3D11Texture2D* pNormalTexture11; }; union { UINT64 Force64_3; //Force the union to 64bits - IDirect3DTexture9* pSpecularTexture9; ID3D11Texture2D* pSpecularTexture11; }; @@ -240,9 +241,9 @@ struct SDKANIMATION_FILE_HEADER struct SDKANIMATION_DATA { - D3DXVECTOR3 Translation; - D3DXVECTOR4 Orientation; - D3DXVECTOR3 Scaling; + DirectX::XMFLOAT3 Translation; + DirectX::XMFLOAT4 Orientation; + DirectX::XMFLOAT3 Scaling; }; struct SDKANIMATION_FRAME_DATA @@ -255,34 +256,31 @@ struct SDKANIMATION_FRAME_DATA }; }; +#pragma pack(pop) + +static_assert( sizeof(D3DVERTEXELEMENT9) == 8, "Direct3D9 Decl structure size incorrect" ); +static_assert( sizeof(SDKMESH_HEADER)== 104, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_VERTEX_BUFFER_HEADER) == 288, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_INDEX_BUFFER_HEADER) == 32, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_MESH) == 224, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_SUBSET) == 144, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_FRAME) == 184, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKMESH_MATERIAL) == 1256, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKANIMATION_FILE_HEADER) == 40, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKANIMATION_DATA) == 40, "SDK Mesh structure size incorrect" ); +static_assert( sizeof(SDKANIMATION_FRAME_DATA) == 112, "SDK Mesh structure size incorrect" ); + #ifndef _CONVERTER_APP_ //-------------------------------------------------------------------------------------- // AsyncLoading callbacks //-------------------------------------------------------------------------------------- -typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE9 )( IDirect3DDevice9* pDev, char* szFileName, - IDirect3DTexture9** ppTexture, void* pContext ); -typedef void ( CALLBACK*LPCREATEVERTEXBUFFER9 )( IDirect3DDevice9* pDev, IDirect3DVertexBuffer9** ppBuffer, - UINT iSizeBytes, DWORD Usage, DWORD FVF, D3DPOOL Pool, void* pData, - void* pContext ); -typedef void ( CALLBACK*LPCREATEINDEXBUFFER9 )( IDirect3DDevice9* pDev, IDirect3DIndexBuffer9** ppBuffer, - UINT iSizeBytes, DWORD Usage, D3DFORMAT ibFormat, D3DPOOL Pool, - void* pData, void* pContext ); -struct SDKMESH_CALLBACKS9 -{ - LPCREATETEXTUREFROMFILE9 pCreateTextureFromFile; - LPCREATEVERTEXBUFFER9 pCreateVertexBuffer; - LPCREATEINDEXBUFFER9 pCreateIndexBuffer; - void* pContext; -}; - - -typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE11 )( ID3D11Device* pDev, char* szFileName, - ID3D11ShaderResourceView** ppRV, void* pContext ); -typedef void ( CALLBACK*LPCREATEVERTEXBUFFER11 )( ID3D11Device* pDev, ID3D11Buffer** ppBuffer, - D3D11_BUFFER_DESC BufferDesc, void* pData, void* pContext ); -typedef void ( CALLBACK*LPCREATEINDEXBUFFER11 )( ID3D11Device* pDev, ID3D11Buffer** ppBuffer, - D3D11_BUFFER_DESC BufferDesc, void* pData, void* pContext ); +typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE11 )( _In_ ID3D11Device* pDev, _In_z_ char* szFileName, + _Outptr_ ID3D11ShaderResourceView** ppRV, _In_opt_ void* pContext ); +typedef void ( CALLBACK*LPCREATEVERTEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer, + _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext ); +typedef void ( CALLBACK*LPCREATEINDEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer, + _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext ); struct SDKMESH_CALLBACKS11 { LPCREATETEXTUREFROMFILE11 pCreateTextureFromFile; @@ -302,8 +300,7 @@ private: //BYTE* m_pBufferData; HANDLE m_hFile; HANDLE m_hFileMappingObject; - CGrowableArray <BYTE*> m_MappedPointers; - IDirect3DDevice9* m_pDev9; + std::vector<BYTE*> m_MappedPointers; ID3D11Device* m_pDev11; ID3D11DeviceContext* m_pDevContext11; @@ -331,259 +328,129 @@ protected: // Adjacency information (not part of the m_pStaticMeshData, so it must be created and destroyed separately ) SDKMESH_INDEX_BUFFER_HEADER* m_pAdjacencyIndexBufferArray; - //Animation (TODO: Add ability to load/track multiple animation sets) + //Animation SDKANIMATION_FILE_HEADER* m_pAnimationHeader; SDKANIMATION_FRAME_DATA* m_pAnimationFrameData; - D3DXMATRIX* m_pBindPoseFrameMatrices; - D3DXMATRIX* m_pTransformedFrameMatrices; - D3DXMATRIX* m_pWorldPoseFrameMatrices; + DirectX::XMFLOAT4X4* m_pBindPoseFrameMatrices; + DirectX::XMFLOAT4X4* m_pTransformedFrameMatrices; + DirectX::XMFLOAT4X4* m_pWorldPoseFrameMatrices; protected: - void LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pMaterials, - UINT NumMaterials, SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - - void LoadMaterials( IDirect3DDevice9* pd3dDevice, SDKMESH_MATERIAL* pMaterials, - UINT NumMaterials, SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - - HRESULT CreateVertexBuffer( ID3D11Device* pd3dDevice, - SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices, - SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - HRESULT CreateVertexBuffer( IDirect3DDevice9* pd3dDevice, - SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices, - SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - - HRESULT CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader, - void* pIndices, SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - HRESULT CreateIndexBuffer( IDirect3DDevice9* pd3dDevice, - SDKMESH_INDEX_BUFFER_HEADER* pHeader, void* pIndices, - SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - - virtual HRESULT CreateFromFile( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, - LPCTSTR szFileName, - bool bCreateAdjacencyIndices, - SDKMESH_CALLBACKS11* pLoaderCallbacks11 = NULL, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 = NULL ); - - virtual HRESULT CreateFromMemory( ID3D11Device* pDev11, - IDirect3DDevice9* pDev9, - BYTE* pData, - UINT DataBytes, - bool bCreateAdjacencyIndices, - bool bCopyStatic, - SDKMESH_CALLBACKS11* pLoaderCallbacks11 = NULL, - SDKMESH_CALLBACKS9* pLoaderCallbacks9 = NULL ); + void LoadMaterials( _In_ ID3D11Device* pd3dDevice, _In_reads_(NumMaterials) SDKMESH_MATERIAL* pMaterials, + _In_ UINT NumMaterials, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + + HRESULT CreateVertexBuffer( _In_ ID3D11Device* pd3dDevice, + _In_ SDKMESH_VERTEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pVertices, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + + HRESULT CreateIndexBuffer( _In_ ID3D11Device* pd3dDevice, + _In_ SDKMESH_INDEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pIndices, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + + virtual HRESULT CreateFromFile( _In_opt_ ID3D11Device* pDev11, + _In_z_ LPCWSTR szFileName, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr ); + + virtual HRESULT CreateFromMemory( _In_opt_ ID3D11Device* pDev11, + _In_reads_(DataBytes) BYTE* pData, + _In_ size_t DataBytes, + _In_ bool bCopyStatic, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr ); //frame manipulation - void TransformBindPoseFrame( UINT iFrame, D3DXMATRIX* pParentWorld ); - void TransformFrame( UINT iFrame, D3DXMATRIX* pParentWorld, double fTime ); - void TransformFrameAbsolute( UINT iFrame, double fTime ); + void TransformBindPoseFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld ); + void TransformFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld, _In_ double fTime ); + void TransformFrameAbsolute( _In_ UINT iFrame, _In_ double fTime ); //Direct3D 11 rendering helpers - void RenderMesh( UINT iMesh, - bool bAdjacent, - ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot, - UINT iNormalSlot, - UINT iSpecularSlot ); - void RenderFrame( UINT iFrame, - bool bAdjacent, - ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot, - UINT iNormalSlot, - UINT iSpecularSlot ); - - - //Direct3D 9 rendering helpers - void RenderMesh( UINT iMesh, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ); - void RenderFrame( UINT iFrame, - LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse, - D3DXHANDLE htxNormal, - D3DXHANDLE htxSpecular ); + void RenderMesh( _In_ UINT iMesh, + _In_ bool bAdjacent, + _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot, + _In_ UINT iNormalSlot, + _In_ UINT iSpecularSlot ); + void RenderFrame( _In_ UINT iFrame, + _In_ bool bAdjacent, + _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot, + _In_ UINT iNormalSlot, + _In_ UINT iSpecularSlot ); public: - CDXUTSDKMesh(); - virtual ~CDXUTSDKMesh(); - - virtual HRESULT Create( ID3D11Device* pDev11, LPCTSTR szFileName, bool bCreateAdjacencyIndices= - false, SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - virtual HRESULT Create( IDirect3DDevice9* pDev9, LPCTSTR szFileName, bool bCreateAdjacencyIndices= - false, SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - virtual HRESULT Create( ID3D11Device* pDev11, BYTE* pData, UINT DataBytes, - bool bCreateAdjacencyIndices=false, bool bCopyStatic=false, - SDKMESH_CALLBACKS11* pLoaderCallbacks=NULL ); - virtual HRESULT Create( IDirect3DDevice9* pDev9, BYTE* pData, UINT DataBytes, - bool bCreateAdjacencyIndices=false, bool bCopyStatic=false, - SDKMESH_CALLBACKS9* pLoaderCallbacks=NULL ); - virtual HRESULT LoadAnimation( WCHAR* szFileName ); - virtual void Destroy(); + CDXUTSDKMesh(); + virtual ~CDXUTSDKMesh(); - //Frame manipulation - void TransformBindPose( D3DXMATRIX* pWorld ); - void TransformMesh( D3DXMATRIX* pWorld, double fTime ); + virtual HRESULT Create( _In_ ID3D11Device* pDev11, _In_z_ LPCWSTR szFileName, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + virtual HRESULT Create( _In_ ID3D11Device* pDev11, BYTE* pData, size_t DataBytes, _In_ bool bCopyStatic=false, + _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); + virtual HRESULT LoadAnimation( _In_z_ const WCHAR* szFileName ); + virtual void Destroy(); + //Frame manipulation + void TransformBindPose( _In_ DirectX::CXMMATRIX world ) { TransformBindPoseFrame( 0, world ); }; + void TransformMesh( _In_ DirectX::CXMMATRIX world, _In_ double fTime ); //Direct3D 11 Rendering - virtual void Render( ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, - UINT iNormalSlot = INVALID_SAMPLER_SLOT, - UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); - virtual void RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext, - UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, - UINT iNormalSlot = INVALID_SAMPLER_SLOT, - UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); - - //Direct3D 9 Rendering - virtual void Render( LPDIRECT3DDEVICE9 pd3dDevice, - LPD3DXEFFECT pEffect, - D3DXHANDLE hTechnique, - D3DXHANDLE htxDiffuse = 0, - D3DXHANDLE htxNormal = 0, - D3DXHANDLE htxSpecular = 0 ); + virtual void Render( _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); + virtual void RenderAdjacent( _In_ ID3D11DeviceContext* pd3dDeviceContext, + _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT, + _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); //Helpers (D3D11 specific) - static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType11( SDKMESH_PRIMITIVE_TYPE PrimType ); - DXGI_FORMAT GetIBFormat11( UINT iMesh ); - ID3D11Buffer* GetVB11( UINT iMesh, UINT iVB ); - ID3D11Buffer* GetIB11( UINT iMesh ); - SDKMESH_INDEX_TYPE GetIndexType( UINT iMesh ); + static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType11( _In_ SDKMESH_PRIMITIVE_TYPE PrimType ); + DXGI_FORMAT GetIBFormat11( _In_ UINT iMesh ) const; + ID3D11Buffer* GetVB11( _In_ UINT iMesh, _In_ UINT iVB ) const; + ID3D11Buffer* GetIB11( _In_ UINT iMesh ) const; + SDKMESH_INDEX_TYPE GetIndexType( _In_ UINT iMesh ) const; - ID3D11Buffer* GetAdjIB11( UINT iMesh ); - - //Helpers (D3D9 specific) - static D3DPRIMITIVETYPE GetPrimitiveType9( SDKMESH_PRIMITIVE_TYPE PrimType ); - D3DFORMAT GetIBFormat9( UINT iMesh ); - IDirect3DVertexBuffer9* GetVB9( UINT iMesh, UINT iVB ); - IDirect3DIndexBuffer9* GetIB9( UINT iMesh ); + ID3D11Buffer* GetAdjIB11( _In_ UINT iMesh ) const; //Helpers (general) - char* GetMeshPathA(); - WCHAR* GetMeshPathW(); - UINT GetNumMeshes(); - UINT GetNumMaterials(); - UINT GetNumVBs(); - UINT GetNumIBs(); - - ID3D11Buffer* GetVB11At( UINT iVB ); - ID3D11Buffer* GetIB11At( UINT iIB ); - - IDirect3DVertexBuffer9* GetVB9At( UINT iVB ); - IDirect3DIndexBuffer9* GetIB9At( UINT iIB ); - - BYTE* GetRawVerticesAt( UINT iVB ); - BYTE* GetRawIndicesAt( UINT iIB ); - SDKMESH_MATERIAL* GetMaterial( UINT iMaterial ); - SDKMESH_MESH* GetMesh( UINT iMesh ); - UINT GetNumSubsets( UINT iMesh ); - SDKMESH_SUBSET* GetSubset( UINT iMesh, UINT iSubset ); - UINT GetVertexStride( UINT iMesh, UINT iVB ); - UINT GetNumFrames(); - SDKMESH_FRAME* GetFrame( UINT iFrame ); - SDKMESH_FRAME* FindFrame( char* pszName ); - UINT64 GetNumVertices( UINT iMesh, UINT iVB ); - UINT64 GetNumIndices( UINT iMesh ); - D3DXVECTOR3 GetMeshBBoxCenter( UINT iMesh ); - D3DXVECTOR3 GetMeshBBoxExtents( UINT iMesh ); - UINT GetOutstandingResources(); - UINT GetOutstandingBufferResources(); - bool CheckLoadDone(); - bool IsLoaded(); - bool IsLoading(); - void SetLoading( bool bLoading ); - BOOL HadLoadingError(); + const char* GetMeshPathA() const; + const WCHAR* GetMeshPathW() const; + UINT GetNumMeshes() const; + UINT GetNumMaterials() const; + UINT GetNumVBs() const; + UINT GetNumIBs() const; + + ID3D11Buffer* GetVB11At( _In_ UINT iVB ) const; + ID3D11Buffer* GetIB11At( _In_ UINT iIB ) const; + + BYTE* GetRawVerticesAt( _In_ UINT iVB ) const; + BYTE* GetRawIndicesAt( _In_ UINT iIB ) const; + + SDKMESH_MATERIAL* GetMaterial( _In_ UINT iMaterial ) const; + SDKMESH_MESH* GetMesh( _In_ UINT iMesh ) const; + UINT GetNumSubsets( _In_ UINT iMesh ) const; + SDKMESH_SUBSET* GetSubset( _In_ UINT iMesh, _In_ UINT iSubset ) const; + UINT GetVertexStride( _In_ UINT iMesh, _In_ UINT iVB ) const; + UINT GetNumFrames() const; + SDKMESH_FRAME* GetFrame( _In_ UINT iFrame ) const; + SDKMESH_FRAME* FindFrame( _In_z_ const char* pszName ) const; + UINT64 GetNumVertices( _In_ UINT iMesh, _In_ UINT iVB ) const; + UINT64 GetNumIndices( _In_ UINT iMesh ) const; + DirectX::XMVECTOR GetMeshBBoxCenter( _In_ UINT iMesh ) const; + DirectX::XMVECTOR GetMeshBBoxExtents( _In_ UINT iMesh ) const; + UINT GetOutstandingResources() const; + UINT GetOutstandingBufferResources() const; + bool CheckLoadDone(); + bool IsLoaded() const; + bool IsLoading() const; + void SetLoading( _In_ bool bLoading ); + BOOL HadLoadingError() const; //Animation - UINT GetNumInfluences( UINT iMesh ); - const D3DXMATRIX* GetMeshInfluenceMatrix( UINT iMesh, UINT iInfluence ); - UINT GetAnimationKeyFromTime( double fTime ); - const D3DXMATRIX* GetWorldMatrix( UINT iFrameIndex ); - const D3DXMATRIX* GetInfluenceMatrix( UINT iFrameIndex ); - bool GetAnimationProperties( UINT* pNumKeys, FLOAT* pFrameTime ); + UINT GetNumInfluences( _In_ UINT iMesh ) const; + DirectX::XMMATRIX GetMeshInfluenceMatrix( _In_ UINT iMesh, _In_ UINT iInfluence ) const; + UINT GetAnimationKeyFromTime( _In_ double fTime ) const; + DirectX::XMMATRIX GetWorldMatrix( _In_ UINT iFrameIndex ) const; + DirectX::XMMATRIX GetInfluenceMatrix( _In_ UINT iFrameIndex ) const; + bool GetAnimationProperties( _Out_ UINT* pNumKeys, _Out_ float* pFrameTime ) const; }; -//----------------------------------------------------------------------------- -// Name: class CDXUTXFileMesh -// Desc: Class for loading and rendering file-based meshes -//----------------------------------------------------------------------------- -class CDXUTXFileMesh -{ -public: - WCHAR m_strName[512]; - LPD3DXMESH m_pMesh; // Managed mesh - - // Cache of data in m_pMesh for easy access - IDirect3DVertexBuffer9* m_pVB; - IDirect3DIndexBuffer9* m_pIB; - IDirect3DVertexDeclaration9* m_pDecl; - DWORD m_dwNumVertices; - DWORD m_dwNumFaces; - DWORD m_dwBytesPerVertex; - - DWORD m_dwNumMaterials; // Materials for the mesh - D3DMATERIAL9* m_pMaterials; - CHAR (*m_strMaterials )[MAX_PATH]; - IDirect3DBaseTexture9** m_pTextures; - bool m_bUseMaterials; - -public: - // Rendering - HRESULT Render( LPDIRECT3DDEVICE9 pd3dDevice, - bool bDrawOpaqueSubsets = true, - bool bDrawAlphaSubsets = true ); - HRESULT Render( ID3DXEffect* pEffect, - D3DXHANDLE hTexture = NULL, - D3DXHANDLE hDiffuse = NULL, - D3DXHANDLE hAmbient = NULL, - D3DXHANDLE hSpecular = NULL, - D3DXHANDLE hEmissive = NULL, - D3DXHANDLE hPower = NULL, - bool bDrawOpaqueSubsets = true, - bool bDrawAlphaSubsets = true ); - - // Mesh access - LPD3DXMESH GetMesh() - { - return m_pMesh; - } - - // Rendering options - void UseMeshMaterials( bool bFlag ) - { - m_bUseMaterials = bFlag; - } - HRESULT SetFVF( LPDIRECT3DDEVICE9 pd3dDevice, DWORD dwFVF ); - HRESULT SetVertexDecl( LPDIRECT3DDEVICE9 pd3dDevice, const D3DVERTEXELEMENT9* pDecl, - bool bAutoComputeNormals = true, bool bAutoComputeTangents = true, - bool bSplitVertexForOptimalTangents = false ); - - // Initializing - HRESULT RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice ); - HRESULT InvalidateDeviceObjects(); - - // Creation/destruction - HRESULT Create( LPDIRECT3DDEVICE9 pd3dDevice, LPCWSTR strFilename ); - HRESULT Create( LPDIRECT3DDEVICE9 pd3dDevice, LPD3DXFILEDATA pFileData ); - HRESULT Create( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh* pInMesh, D3DXMATERIAL* pd3dxMaterials, - DWORD dwMaterials ); - HRESULT CreateMaterials( LPCWSTR strPath, IDirect3DDevice9* pd3dDevice, D3DXMATERIAL* d3dxMtrls, - DWORD dwNumMaterials ); - HRESULT Destroy(); - - CDXUTXFileMesh( LPCWSTR strName = L"CDXUTXMeshFile_Mesh" ); - virtual ~CDXUTXFileMesh(); -}; - - -#endif - #endif diff --git a/samples/DX_APIUsage/DXUT/Optional/SDKmisc.cpp b/samples/DX_APIUsage/DXUT/Optional/SDKmisc.cpp index aec7572..dbfc8f1 100644 --- a/samples/DX_APIUsage/DXUT/Optional/SDKmisc.cpp +++ b/samples/DX_APIUsage/DXUT/Optional/SDKmisc.cpp @@ -3,61 +3,82 @@ // // Various helper functionality that is shared between SDK samples // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "dxut.h" #include "SDKmisc.h" #include "DXUTres.h" -#undef min // use __min instead -#undef max // use __max instead #include "DXUTGui.h" +#include "DDSTextureLoader.h" +#include "WICTextureLoader.h" +#include "ScreenGrab.h" + +using namespace DirectX; + //-------------------------------------------------------------------------------------- // Global/Static Members //-------------------------------------------------------------------------------------- CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache() { // Using an accessor function gives control of the construction order - static CDXUTResourceCache cache; - return cache; + static CDXUTResourceCache* s_cache = nullptr; + if ( !s_cache ) + { +#if defined(DEBUG) || defined(_DEBUG) + int flag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); + _CrtSetDbgFlag( flag & ~_CRTDBG_ALLOC_MEM_DF ); +#endif + s_cache = new CDXUTResourceCache; +#if defined(DEBUG) || defined(_DEBUG) + _CrtSetDbgFlag( flag ); +#endif + } + return *s_cache; } //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- -bool DXUTFindMediaSearchTypicalDirs( __out_ecount(cchSearch) WCHAR* strSearchPath, - __in int cchSearch, - __in LPCWSTR strLeaf, - __in WCHAR* strExePath, - __in WCHAR* strExeName ); -bool DXUTFindMediaSearchParentDirs( __out_ecount(cchSearch) WCHAR* strSearchPath, - __in int cchSearch, - __in WCHAR* strStartAt, - __in WCHAR* strLeafName ); -INT_PTR CALLBACK DisplaySwitchToREFWarningProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ); +bool DXUTFindMediaSearchTypicalDirs( _Out_writes_(cchSearch) WCHAR* strSearchPath, + _In_ int cchSearch, + _In_ LPCWSTR strLeaf, + _In_ const WCHAR* strExePath, + _In_ const WCHAR* strExeName ); +bool DXUTFindMediaSearchParentDirs( _Out_writes_(cchSearch) WCHAR* strSearchPath, + _In_ int cchSearch, + _In_ const WCHAR* strStartAt, + _In_ const WCHAR* strLeafName ); + +INT_PTR CALLBACK DisplaySwitchToREFWarningProc( _In_ HWND hDlg, _In_ UINT message, _In_ WPARAM wParam, _In_ LPARAM lParam ); //-------------------------------------------------------------------------------------- // Shared code for samples to ask user if they want to use a REF device or quit //-------------------------------------------------------------------------------------- -void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) +void WINAPI DXUTDisplaySwitchingToREFWarning() { if( DXUTGetShowMsgBoxOnError() ) { DWORD dwSkipWarning = 0, dwRead = 0, dwWritten = 0; - HANDLE hFile = NULL; + HANDLE hFile = nullptr; // Read previous user settings WCHAR strPath[MAX_PATH]; - SHGetFolderPath( DXUTGetHWND(), CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath ); - wcscat_s( strPath, MAX_PATH, L"\\DXUT\\SkipRefWarning.dat" ); - if( ( hFile = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, - NULL ) ) != INVALID_HANDLE_VALUE ) + if ( SUCCEEDED(SHGetFolderPath(DXUTGetHWND(), CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, strPath)) ) { - ReadFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwRead, NULL ); - CloseHandle( hFile ); + wcscat_s( strPath, MAX_PATH, L"\\DXUT\\SkipRefWarning.dat" ); + if( ( hFile = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, + nullptr ) ) != INVALID_HANDLE_VALUE ) + { + (void)ReadFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwRead, nullptr ); + CloseHandle( hFile ); + } } if( dwSkipWarning == 0 ) @@ -102,10 +123,7 @@ void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) }; LPARAM lParam; - if( ver == DXUT_D3D9_DEVICE ) - lParam = 9; - else - lParam = 11; + lParam = 11; int nResult = ( int )DialogBoxIndirectParam( DXUTGetHINSTANCE(), ( DLGTEMPLATE* )&dtp, DXUTGetHWND(), DisplaySwitchToREFWarningProc, lParam ); @@ -113,15 +131,17 @@ void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) { // Save user settings dwSkipWarning = 1; - SHGetFolderPath( DXUTGetHWND(), CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath ); - wcscat_s( strPath, MAX_PATH, L"\\DXUT" ); - CreateDirectory( strPath, NULL ); - wcscat_s( strPath, MAX_PATH, L"\\SkipRefWarning.dat" ); - if( ( hFile = CreateFile( strPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, - NULL ) ) != INVALID_HANDLE_VALUE ) + if ( SUCCEEDED(SHGetFolderPath(DXUTGetHWND(), CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, strPath)) ) { - WriteFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwWritten, NULL ); - CloseHandle( hFile ); + wcscat_s( strPath, MAX_PATH, L"\\DXUT" ); + CreateDirectory( strPath, nullptr ); + wcscat_s( strPath, MAX_PATH, L"\\SkipRefWarning.dat" ); + if( ( hFile = CreateFile( strPath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, + nullptr ) ) != INVALID_HANDLE_VALUE ) + { + WriteFile( hFile, &dwSkipWarning, sizeof( DWORD ), &dwWritten, nullptr ); + CloseHandle( hFile ); + } } } @@ -136,6 +156,7 @@ void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ) //-------------------------------------------------------------------------------------- // MsgProc for DXUTDisplaySwitchingToREFWarning() dialog box //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ INT_PTR CALLBACK DisplaySwitchToREFWarningProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ) { switch( message ) @@ -146,7 +167,7 @@ INT_PTR CALLBACK DisplaySwitchToREFWarningProc( HWND hDlg, UINT message, WPARAM SendMessage( GetDlgItem( hDlg, 0x100 ), STM_SETIMAGE, IMAGE_ICON, ( LPARAM )LoadIcon( 0, IDI_QUESTION ) ); WCHAR sz[512]; swprintf_s( sz, 512, - L"This program needs to use the Direct3D %lld reference device. This device implements the entire Direct3D %lld feature set, but runs very slowly. Do you wish to continue?", lParam, lParam ); + L"This program needs to use the Direct3D %Iu reference device. This device implements the entire Direct3D %Iu feature set, but runs very slowly. Do you wish to continue?", lParam, lParam ); SetDlgItemText( hDlg, 0x101, sz ); SetDlgItemText( hDlg, IDYES, L"&Yes" ); SetDlgItemText( hDlg, IDNO, L"&No" ); @@ -189,6 +210,7 @@ WCHAR* DXUTMediaSearchPath() } + //-------------------------------------------------------------------------------------- LPCWSTR WINAPI DXUTGetMediaSearchPath() { @@ -197,7 +219,7 @@ LPCWSTR WINAPI DXUTGetMediaSearchPath() //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTSetMediaSearchPath( LPCWSTR strPath ) +HRESULT WINAPI DXUTSetMediaSearchPath( _In_z_ LPCWSTR strPath ) { HRESULT hr; @@ -224,13 +246,14 @@ HRESULT WINAPI DXUTSetMediaSearchPath( LPCWSTR strPath ) // cchDest is the size in WCHARs of strDestPath. Be careful not to // pass in sizeof(strDest) on UNICODE builds. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, LPCWSTR strFilename ) { bool bFound; WCHAR strSearchFor[MAX_PATH]; - if( NULL == strFilename || strFilename[0] == 0 || NULL == strDestPath || cchDest < 10 ) + if( !strFilename || strFilename[0] == 0 || !strDestPath || cchDest < 10 ) return E_INVALIDARG; // Get the exe name, and exe path @@ -242,8 +265,8 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, { 0 }; - WCHAR* strLastSlash = NULL; - GetModuleFileName( NULL, strExePath, MAX_PATH ); + WCHAR* strLastSlash = nullptr; + GetModuleFileName( nullptr, strExePath, MAX_PATH ); strExePath[MAX_PATH - 1] = 0; strLastSlash = wcsrchr( strExePath, TEXT( '\\' ) ); if( strLastSlash ) @@ -275,7 +298,7 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, return S_OK; // Typical directory search again, but also look in a subdir called "\media\" - swprintf_s( strSearchFor, MAX_PATH, L"media\\%s", strFilename ); + swprintf_s( strSearchFor, MAX_PATH, L"media\\%ls", strFilename ); bFound = DXUTFindMediaSearchTypicalDirs( strDestPath, cchDest, strSearchFor, strExePath, strExeName ); if( bFound ) return S_OK; @@ -297,7 +320,7 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, return S_OK; // Search all parent directories starting at .\ and using "media\strFilename" as the leaf name - swprintf_s( strLeafName, MAX_PATH, L"media\\%s", strFilename ); + swprintf_s( strLeafName, MAX_PATH, L"media\\%ls", strFilename ); bFound = DXUTFindMediaSearchParentDirs( strDestPath, cchDest, L".", strLeafName ); if( bFound ) return S_OK; @@ -317,8 +340,9 @@ HRESULT WINAPI DXUTFindDXSDKMediaFileCch( WCHAR* strDestPath, int cchDest, //-------------------------------------------------------------------------------------- // Search a set of typical directories //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWSTR strLeaf, - WCHAR* strExePath, WCHAR* strExeName ) + const WCHAR* strExePath, const WCHAR* strExeName ) { // Typical directories: // .\ @@ -337,42 +361,42 @@ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWST return true; // Search in ..\ - swprintf_s( strSearchPath, cchSearch, L"..\\%s", strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"..\\%ls", strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\..\ - swprintf_s( strSearchPath, cchSearch, L"..\\..\\%s", strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"..\\..\\%ls", strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\..\ - swprintf_s( strSearchPath, cchSearch, L"..\\..\\%s", strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"..\\..\\%ls", strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\ - swprintf_s( strSearchPath, cchSearch, L"%s\\%s", strExePath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\%ls", strExePath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\..\ - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\%s", strExePath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\%ls", strExePath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\..\..\ - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\..\\%s", strExePath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\..\\%ls", strExePath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in "%EXE_DIR%\..\%EXE_NAME%\". This matches the DirectX SDK layout - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\%s\\%s", strExePath, strExeName, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\%ls\\%ls", strExePath, strExeName, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in "%EXE_DIR%\..\..\%EXE_NAME%\". This matches the DirectX SDK layout - swprintf_s( strSearchPath, cchSearch, L"%s\\..\\..\\%s\\%s", strExePath, strExeName, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls\\..\\..\\%ls\\%ls", strExePath, strExeName, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; @@ -380,7 +404,7 @@ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWST WCHAR* s_strSearchPath = DXUTMediaSearchPath(); if( s_strSearchPath[0] != 0 ) { - swprintf_s( strSearchPath, cchSearch, L"%s%s", s_strSearchPath, strLeaf ); + swprintf_s( strSearchPath, cchSearch, L"%ls%ls", s_strSearchPath, strLeaf ); if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; } @@ -389,13 +413,13 @@ bool DXUTFindMediaSearchTypicalDirs( WCHAR* strSearchPath, int cchSearch, LPCWST } - //-------------------------------------------------------------------------------------- // Search parent directories starting at strStartAt, and appending strLeafName // at each parent directory. It stops at the root directory. //-------------------------------------------------------------------------------------- -bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, WCHAR* strStartAt, - WCHAR* strLeafName ) +_Use_decl_annotations_ +bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, const WCHAR* strStartAt, + const WCHAR* strLeafName ) { WCHAR strFullPath[MAX_PATH] = { @@ -409,23 +433,24 @@ bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, WCHAR* { 0 }; - WCHAR* strFilePart = NULL; + WCHAR* strFilePart = nullptr; - GetFullPathName( strStartAt, MAX_PATH, strFullPath, &strFilePart ); - if( strFilePart == NULL ) + if ( !GetFullPathName( strStartAt, MAX_PATH, strFullPath, &strFilePart ) ) return false; - while( strFilePart != NULL && *strFilePart != '\0' ) +#pragma warning( disable : 6102 ) + while( strFilePart && *strFilePart != '\0' ) { - swprintf_s( strFullFileName, MAX_PATH, L"%s\\%s", strFullPath, strLeafName ); + swprintf_s( strFullFileName, MAX_PATH, L"%ls\\%ls", strFullPath, strLeafName ); if( GetFileAttributes( strFullFileName ) != 0xFFFFFFFF ) { wcscpy_s( strSearchPath, cchSearch, strFullFileName ); return true; } - swprintf_s( strSearch, MAX_PATH, L"%s\\..", strFullPath ); - GetFullPathName( strSearch, MAX_PATH, strFullPath, &strFilePart ); + swprintf_s( strSearch, MAX_PATH, L"%ls\\..", strFullPath ); + if ( !GetFullPathName( strSearch, MAX_PATH, strFullPath, &strFilePart ) ) + return false; } return false; @@ -433,1188 +458,483 @@ bool DXUTFindMediaSearchParentDirs( WCHAR* strSearchPath, int cchSearch, WCHAR* //-------------------------------------------------------------------------------------- -// CDXUTResourceCache +// Compiles HLSL shaders //-------------------------------------------------------------------------------------- +#if D3D_COMPILER_VERSION < 46 -//-------------------------------------------------------------------------------------- -CDXUTResourceCache::~CDXUTResourceCache() +namespace { - OnDestroyDevice(); - m_TextureCache.RemoveAll(); - m_EffectCache.RemoveAll(); - m_FontCache.RemoveAll(); -} +struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ) -{ - return CreateTextureFromFileEx( pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, - 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppTexture ); -} +typedef public std::unique_ptr<void, handle_closer> ScopedHandle; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ) -{ - WCHAR szSrcFile[MAX_PATH]; - MultiByteToWideChar( CP_ACP, 0, pSrcFile, -1, szSrcFile, MAX_PATH ); - szSrcFile[MAX_PATH - 1] = 0; +inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; } - return CreateTextureFromFile( pDevice, szSrcFile, ppTexture ); -} - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCTSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) +class CIncludeHandler : public ID3DInclude + // Not as robust as D3D_COMPILE_STANDARD_FILE_INCLUDE, but it works in most cases { - return CreateTextureFromFileEx( pDevice, pContext, pSrcFile, NULL, NULL, ppOutputRV, bSRGB ); -} +private: + static const unsigned int MAX_INCLUDES = 9; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) -{ - WCHAR szSrcFile[MAX_PATH]; - MultiByteToWideChar( CP_ACP, 0, pSrcFile, -1, szSrcFile, MAX_PATH ); - szSrcFile[MAX_PATH - 1] = 0; + struct sInclude + { + HANDLE hFile; + HANDLE hFileMap; + LARGE_INTEGER FileSize; + void *pMapData; + }; - return CreateTextureFromFile( pDevice, pContext, szSrcFile, ppOutputRV, bSRGB ); -} + struct sInclude m_includeFiles[MAX_INCLUDES]; + size_t m_nIncludes; + bool m_reset; + WCHAR m_workingPath[MAX_PATH]; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) +public: + CIncludeHandler() : m_nIncludes(0), m_reset(false) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_TEXTURE ) + if ( !GetCurrentDirectoryW( MAX_PATH, m_workingPath ) ) + *m_workingPath = 0; + + for ( size_t i = 0; i < MAX_INCLUDES; ++i ) { - // A match is found. Obtain the IDirect3DTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DTexture9, ( LPVOID* )ppTexture ); + m_includeFiles[i].hFile = INVALID_HANDLE_VALUE; + m_includeFiles[i].hFileMap = INVALID_HANDLE_VALUE; + m_includeFiles[i].pMapData = nullptr; } } + virtual ~CIncludeHandler() + { + for ( size_t i = 0; i < m_nIncludes; ++i ) + { + UnmapViewOfFile( m_includeFiles[i].pMapData ); -#if defined(PROFILE) || defined(DEBUG) - CHAR strFileA[MAX_PATH]; - WideCharToMultiByte( CP_ACP, 0, pSrcFile, -1, strFileA, MAX_PATH, NULL, FALSE ); - CHAR* pstrName = strrchr( strFileA, '\\' ); - if( pstrName == NULL ) - pstrName = strFileA; - else - pstrName++; -#endif - - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateTextureFromFileEx( pDevice, pSrcFile, Width, Height, MipLevels, Usage, Format, - Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_TEXTURE; - ( *ppTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - DXUT_SetDebugName( *ppTexture, pstrName ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} - - + if ( m_includeFiles[i].hFileMap != INVALID_HANDLE_VALUE) + CloseHandle( m_includeFiles[i].hFileMap ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromFileEx( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, LPCTSTR pSrcFile, - D3DX11_IMAGE_LOAD_INFO* pLoadInfo, ID3DX11ThreadPump* pPump, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) -{ + if ( m_includeFiles[i].hFile != INVALID_HANDLE_VALUE) + CloseHandle( m_includeFiles[i].hFile ); + } - bool is10L9 = DXUTGetDeviceSettings().d3d11.DeviceFeatureLevel < D3D_FEATURE_LEVEL_10_0; - HRESULT hr = S_OK; - D3DX11_IMAGE_LOAD_INFO ZeroInfo; //D3DX11_IMAGE_LOAD_INFO has a default constructor - D3DX11_IMAGE_INFO SrcInfo; + m_nIncludes = 0; - if( !pLoadInfo ) - { - pLoadInfo = &ZeroInfo; + if ( m_reset && *m_workingPath ) + { + SetCurrentDirectoryW( m_workingPath ); + } } - if( !pLoadInfo->pSrcInfo ) + STDMETHOD(Open( D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes ) ) { - D3DX11GetImageInfoFromFile( pSrcFile, NULL, &SrcInfo, NULL ); - pLoadInfo->pSrcInfo = &SrcInfo; + UNREFERENCED_PARAMETER(IncludeType); + UNREFERENCED_PARAMETER(pParentData); - pLoadInfo->Format = pLoadInfo->pSrcInfo->Format; - } + size_t incIndex = m_nIncludes+1; - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) - { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == pLoadInfo->Width && - Entry.Height == pLoadInfo->Height && - Entry.MipLevels == pLoadInfo->MipLevels && - Entry.Usage11 == pLoadInfo->Usage && - Entry.Format == pLoadInfo->Format && - Entry.CpuAccessFlags == pLoadInfo->CpuAccessFlags && - Entry.BindFlags == pLoadInfo->BindFlags && - Entry.MiscFlags == pLoadInfo->MiscFlags ) + // Make sure we have enough room for this include file + if ( incIndex >= MAX_INCLUDES ) + return E_FAIL; + + // try to open the file + m_includeFiles[incIndex].hFile = CreateFileA( pFileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr ); + if( INVALID_HANDLE_VALUE == m_includeFiles[incIndex].hFile ) { - // A match is found. Obtain the IDirect3DTexture9 interface and return that. - return Entry.pSRV11->QueryInterface( __uuidof( ID3D11ShaderResourceView ), ( LPVOID* )ppOutputRV ); + return E_FAIL; } - } -#if defined(PROFILE) || defined(DEBUG) - CHAR strFileA[MAX_PATH]; - WideCharToMultiByte( CP_ACP, 0, pSrcFile, -1, strFileA, MAX_PATH, NULL, FALSE ); - CHAR* pstrName = strrchr( strFileA, '\\' ); - if( pstrName == NULL ) - pstrName = strFileA; - else - pstrName++; -#endif + // Get the file size + GetFileSizeEx( m_includeFiles[incIndex].hFile, &m_includeFiles[incIndex].FileSize ); - //Ready a new entry to the texture cache - //Do this before creating the texture since pLoadInfo may be volatile - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = pLoadInfo->Width; - NewEntry.Height = pLoadInfo->Height; - NewEntry.MipLevels = pLoadInfo->MipLevels; - NewEntry.Usage11 = pLoadInfo->Usage; - // 10L9 can't handle typesless, so we cant make a typesless format - if (is10L9 && bSRGB) { - NewEntry.Format = MAKE_SRGB(pLoadInfo->Format); - }else { - NewEntry.Format = pLoadInfo->Format; - } - NewEntry.CpuAccessFlags = pLoadInfo->CpuAccessFlags; - NewEntry.BindFlags = pLoadInfo->BindFlags; - NewEntry.MiscFlags = pLoadInfo->MiscFlags; + // Use Memory Mapped File I/O for the header data + m_includeFiles[incIndex].hFileMap = CreateFileMappingA( m_includeFiles[incIndex].hFile, nullptr, PAGE_READONLY, m_includeFiles[incIndex].FileSize.HighPart, m_includeFiles[incIndex].FileSize.LowPart, pFileName); + if( !m_includeFiles[incIndex].hFileMap ) + { + if (m_includeFiles[incIndex].hFile != INVALID_HANDLE_VALUE) + CloseHandle( m_includeFiles[incIndex].hFile ); + return E_FAIL; + } - //Create the rexture - ID3D11Texture2D* pRes = NULL; - hr = D3DX11CreateTextureFromFile( pDevice, pSrcFile, pLoadInfo, pPump, ( ID3D11Resource** )&pRes, NULL ); + // Create Map view + *ppData = MapViewOfFile( m_includeFiles[incIndex].hFileMap, FILE_MAP_READ, 0, 0, 0 ); + *pBytes = m_includeFiles[incIndex].FileSize.LowPart; - if( FAILED( hr ) ) - return hr; - D3D11_TEXTURE2D_DESC tex_dsc; - pRes->GetDesc(&tex_dsc); - - - - if (bSRGB ) { - // This is a workaround so that we can load linearly, but sample in SRGB. Right now, we can't load - // as linear since D3DX will try to do conversion on load. Loading as TYPELESS doesn't work either, and - // loading as typed _UNORM doesn't allow us to create an SRGB view. - - // on d3d11 featuer levels this is just a copy, but on 10L9 we must use a cpu side copy with 2 staging resources. - ID3D11Texture2D* unormStaging = NULL; - ID3D11Texture2D* srgbStaging = NULL; - - D3D11_TEXTURE2D_DESC CopyDesc; - pRes->GetDesc( &CopyDesc ); - - pLoadInfo->BindFlags = 0; - pLoadInfo->CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - pLoadInfo->Depth = 0; - pLoadInfo->Filter = D3DX11_FILTER_LINEAR; - pLoadInfo->FirstMipLevel = 0; - pLoadInfo->Format = CopyDesc.Format; - pLoadInfo->Height = CopyDesc.Height; - pLoadInfo->MipFilter = D3DX11_FILTER_LINEAR; - pLoadInfo->MiscFlags = CopyDesc.MiscFlags; - pLoadInfo->Usage = D3D11_USAGE_STAGING; - pLoadInfo->Width = CopyDesc.Width; - - CopyDesc.BindFlags = 0; - CopyDesc.Usage = D3D11_USAGE_STAGING; - CopyDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - CopyDesc.Format = MAKE_SRGB(CopyDesc.Format); - - hr = D3DX11CreateTextureFromFile( pDevice, pSrcFile, pLoadInfo, pPump, ( ID3D11Resource** )&unormStaging, NULL ); - DXUT_SetDebugName( unormStaging, "CDXUTResourceCache" ); - - hr = pDevice->CreateTexture2D(&CopyDesc, NULL, &srgbStaging); - DXUT_SetDebugName( srgbStaging, "CDXUTResourceCache" ); - pContext->CopyResource( srgbStaging, unormStaging ); - ID3D11Texture2D* srgbGPU; - - pRes->GetDesc( &CopyDesc ); - CopyDesc.Format = MAKE_SRGB(CopyDesc.Format); - hr = pDevice->CreateTexture2D(&CopyDesc, NULL, &srgbGPU); - pContext->CopyResource( srgbGPU, srgbStaging ); - - SAFE_RELEASE(pRes); - SAFE_RELEASE(srgbStaging); - SAFE_RELEASE(unormStaging); - pRes = srgbGPU; - } + // Success - Increment the include file count + m_nIncludes = incIndex; - DXUT_SetDebugName( pRes, pstrName ); + return S_OK; + } - D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - if( bSRGB ) - SRVDesc.Format = MAKE_SRGB( ZeroInfo.Format ); - else - SRVDesc.Format = ZeroInfo.Format; - if( pLoadInfo->pSrcInfo->ResourceDimension == D3D11_RESOURCE_DIMENSION_TEXTURE1D ) + STDMETHOD(Close( LPCVOID pData )) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - SRVDesc.Texture1D.MostDetailedMip = 0; - SRVDesc.Texture1D.MipLevels = pLoadInfo->pSrcInfo->MipLevels; + UNREFERENCED_PARAMETER(pData); + // Defer Closure until the container destructor + return S_OK; } - else if( pLoadInfo->pSrcInfo->ResourceDimension == D3D11_RESOURCE_DIMENSION_TEXTURE2D ) + + void SetCWD( LPCWSTR pFileName ) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - SRVDesc.Texture2D.MostDetailedMip = 0; - SRVDesc.Texture2D.MipLevels = pLoadInfo->pSrcInfo->MipLevels; + WCHAR filePath[MAX_PATH]; + wcscpy_s( filePath, MAX_PATH, pFileName ); - if( pLoadInfo->pSrcInfo->MiscFlags & D3D11_RESOURCE_MISC_TEXTURECUBE ) + WCHAR *strLastSlash = wcsrchr( filePath, L'\\' ); + if( strLastSlash ) { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; - SRVDesc.TextureCube.MostDetailedMip = 0; - SRVDesc.TextureCube.MipLevels = pLoadInfo->pSrcInfo->MipLevels; + // Chop the exe name from the exe path + *strLastSlash = 0; + m_reset = true; + SetCurrentDirectoryW( filePath ); } } - else if( pLoadInfo->pSrcInfo->ResourceDimension == D3D11_RESOURCE_DIMENSION_TEXTURE3D ) - { - SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; - SRVDesc.Texture3D.MostDetailedMip = 0; - SRVDesc.Texture3D.MipLevels = pLoadInfo->pSrcInfo->MipLevels; - } - if (bSRGB) { - SRVDesc.Format = MAKE_SRGB(tex_dsc.Format); - }else { - SRVDesc.Format = tex_dsc.Format; - } - SRVDesc.Texture2D.MipLevels = tex_dsc.MipLevels; - SRVDesc.Texture2D.MostDetailedMip = 0; - hr = pDevice->CreateShaderResourceView( pRes, &SRVDesc, ppOutputRV ); - pRes->Release(); - if( FAILED( hr ) ) - return hr; - - DXUT_SetDebugName( *ppOutputRV, pstrName ); +}; - ( *ppOutputRV )->QueryInterface( __uuidof( ID3D11ShaderResourceView ), ( LPVOID* )&NewEntry.pSRV11 ); - - m_TextureCache.Add( NewEntry ); - - return S_OK; -} +}; // namespace +#endif -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, LPDIRECT3DTEXTURE9* ppTexture ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCompileFromFile( LPCWSTR pFileName, + const D3D_SHADER_MACRO* pDefines, + LPCSTR pEntrypoint, LPCSTR pTarget, + UINT Flags1, UINT Flags2, + ID3DBlob** ppCode ) { - return CreateTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, - D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, - D3DX_DEFAULT, 0, NULL, NULL, ppTexture ); -} - + HRESULT hr; + WCHAR str[MAX_PATH]; + V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, pFileName ) ); + +#if defined( DEBUG ) || defined( _DEBUG ) + // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. + // Setting this flag improves the shader debugging experience, but still allows + // the shaders to be optimized and to run exactly the way they will run in + // the release configuration of this program. + Flags1 |= D3DCOMPILE_DEBUG; +#endif -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) - { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_TEXTURE ) - { - // A match is found. Obtain the IDirect3DTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DTexture9, ( LPVOID* )ppTexture ); - } - } + ID3DBlob* pErrorBlob = nullptr; - HRESULT hr; +#if D3D_COMPILER_VERSION >= 46 - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, Width, Height, MipLevels, Usage, - Format, Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); - if( FAILED( hr ) ) - return hr; + hr = D3DCompileFromFile( str, pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE, + pEntrypoint, pTarget, Flags1, Flags2, + ppCode, &pErrorBlob ); - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_TEXTURE; - ( *ppTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} +#else + ScopedHandle hFile( safe_handle( CreateFileW( str, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ) ) ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateCubeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ) -{ - return CreateCubeTextureFromFileEx( pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, 0, - D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppCubeTexture ); -} + if ( !hFile ) + return HRESULT_FROM_WIN32( GetLastError() ); + LARGE_INTEGER FileSize = {}; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) +#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA) + FILE_STANDARD_INFO fileInfo; + if ( !GetFileInformationByHandleEx( hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo) ) ) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == Size && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_CUBETEXTURE ) - { - // A match is found. Obtain the IDirect3DCubeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DCubeTexture9, ( LPVOID* )ppCubeTexture ); - } + return HRESULT_FROM_WIN32( GetLastError() ); } + FileSize = fileInfo.EndOfFile; +#else + GetFileSizeEx( hFile.get(), &FileSize ); +#endif - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateCubeTextureFromFileEx( pDevice, pSrcFile, Size, MipLevels, Usage, Format, Pool, Filter, - MipFilter, ColorKey, pSrcInfo, pPalette, ppCubeTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = Size; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_CUBETEXTURE; - ( *ppCubeTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} + if (!FileSize.LowPart || FileSize.HighPart > 0) + return E_FAIL; + std::unique_ptr<char[]> fxData; + fxData.reset( new (std::nothrow) char[ FileSize.LowPart ] ); + if ( !fxData ) + return E_OUTOFMEMORY; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateCubeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ) -{ - return CreateCubeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, - 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppCubeTexture ); -} + DWORD BytesRead = 0; + if ( !ReadFile( hFile.get(), fxData.get(), FileSize.LowPart, &BytesRead, nullptr ) ) + return HRESULT_FROM_WIN32( GetLastError() ); + if (BytesRead < FileSize.LowPart) + return E_FAIL; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) + char pSrcName[MAX_PATH]; + int result = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, str, -1, pSrcName, MAX_PATH, nullptr, FALSE ); + if ( !result ) + return E_FAIL; + + const CHAR* pstrName = strrchr( pSrcName, '\\' ); + if (!pstrName) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.Width == Size && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_CUBETEXTURE ) - { - // A match is found. Obtain the IDirect3DCubeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DCubeTexture9, ( LPVOID* )ppCubeTexture ); - } + pstrName = pSrcName; } - - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateCubeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, Size, MipLevels, Usage, Format, - Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppCubeTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.Width = Size; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_CUBETEXTURE; - ( *ppCubeTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateVolumeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ) -{ - return CreateVolumeTextureFromFileEx( pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, - 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, - 0, NULL, NULL, ppVolumeTexture ); -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) + else { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.Depth == Depth && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_VOLUMETEXTURE ) - { - // A match is found. Obtain the IDirect3DVolumeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DVolumeTexture9, ( LPVOID* )ppTexture ); - } + pstrName++; } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateVolumeTextureFromFileEx( pDevice, pSrcFile, Width, Height, Depth, MipLevels, Usage, Format, - Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, ppTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.Depth = Depth; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_VOLUMETEXTURE; - ( *ppTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; -} + std::unique_ptr<CIncludeHandler> includes( new (std::nothrow) CIncludeHandler ); + if ( !includes ) + return E_OUTOFMEMORY; + includes->SetCWD( str ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateVolumeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ) -{ - return CreateVolumeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, D3DX_DEFAULT, D3DX_DEFAULT, - D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, - D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppVolumeTexture ); -} + hr = D3DCompile( fxData.get(), BytesRead, pstrName, pDefines, includes.get(), + pEntrypoint, pTarget, Flags1, Flags2, + ppCode, &pErrorBlob ); +#endif -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_TextureCache.GetSize(); ++i ) +#pragma warning( suppress : 6102 ) + if ( pErrorBlob ) { - DXUTCache_Texture& Entry = m_TextureCache[i]; - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.Width == Width && - Entry.Height == Height && - Entry.Depth == Depth && - Entry.MipLevels == MipLevels && - Entry.Usage9 == Usage && - Entry.Format9 == Format && - Entry.Pool9 == Pool && - Entry.Type9 == D3DRTYPE_VOLUMETEXTURE ) - { - // A match is found. Obtain the IDirect3DVolumeTexture9 interface and return that. - return Entry.pTexture9->QueryInterface( IID_IDirect3DVolumeTexture9, ( LPVOID* )ppVolumeTexture ); - } + OutputDebugStringA( reinterpret_cast<const char*>( pErrorBlob->GetBufferPointer() ) ); + pErrorBlob->Release(); } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateVolumeTextureFromResourceEx( pDevice, hSrcModule, pSrcResource, Width, Height, Depth, MipLevels, - Usage, - Format, Pool, Filter, MipFilter, ColorKey, pSrcInfo, pPalette, - ppVolumeTexture ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Texture NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.Width = Width; - NewEntry.Height = Height; - NewEntry.Depth = Depth; - NewEntry.MipLevels = MipLevels; - NewEntry.Usage9 = Usage; - NewEntry.Format9 = Format; - NewEntry.Pool9 = Pool; - NewEntry.Type9 = D3DRTYPE_VOLUMETEXTURE; - ( *ppVolumeTexture )->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&NewEntry.pTexture9 ); - - m_TextureCache.Add( NewEntry ); - return S_OK; + return hr; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::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 ) -{ - D3DXFONT_DESCW Desc; - - Desc.Height = Height; - Desc.Width = Width; - Desc.Weight = Weight; - Desc.MipLevels = MipLevels; - Desc.Italic = Italic; - Desc.CharSet = ( BYTE )CharSet; - Desc.OutputPrecision = ( BYTE )OutputPrecision; - Desc.Quality = ( BYTE )Quality; - Desc.PitchAndFamily = ( BYTE )PitchAndFamily; - wcscpy_s( Desc.FaceName, LF_FACESIZE, pFacename ); - - return CreateFontIndirect( pDevice, &Desc, ppFont ); -} - - +// Texture utilities //-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateFontIndirect( LPDIRECT3DDEVICE9 pDevice, CONST D3DXFONT_DESC *pDesc, LPD3DXFONT *ppFont ) - { - // Search the cache for a matching entry. - for( int i = 0; i < m_FontCache.GetSize(); ++i ) - { - DXUTCache_Font &Entry = m_FontCache[i]; - - if( Entry.Width == pDesc->Width && - Entry.Height == pDesc->Height && - Entry.Weight == pDesc->Weight && - Entry.MipLevels == pDesc->MipLevels && - Entry.Italic == pDesc->Italic && - Entry.CharSet == pDesc->CharSet && - Entry.OutputPrecision == pDesc->OutputPrecision && - Entry.Quality == pDesc->Quality && - Entry.PitchAndFamily == pDesc->PitchAndFamily && - CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE, - Entry.FaceName, -1, - pDesc->FaceName, -1 ) == CSTR_EQUAL ) - { - // A match is found. Increment the reference and return the ID3DXFont object. - Entry.pFont->AddRef(); - *ppFont = Entry.pFont; - return S_OK; - } - } - HRESULT hr; +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateShaderResourceViewFromFile( ID3D11Device* d3dDevice, const wchar_t* szFileName, ID3D11ShaderResourceView** textureView ) +{ + if ( !d3dDevice || !szFileName || !textureView ) + return E_INVALIDARG; - // No matching entry. Load the resource and create a new entry. - hr = D3DXCreateFontIndirect( pDevice, pDesc, ppFont ); - if( FAILED( hr ) ) + WCHAR str[MAX_PATH]; + HRESULT hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ); + if ( FAILED(hr) ) return hr; - DXUTCache_Font NewEntry; - ( D3DXFONT_DESC & )NewEntry = *pDesc; - NewEntry.pFont = *ppFont; - NewEntry.pFont->AddRef(); - - m_FontCache.Add( NewEntry ); - return S_OK; -} - + WCHAR ext[_MAX_EXT]; + _wsplitpath_s( str, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT ); -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateEffectFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - const D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, - LPD3DXEFFECTPOOL pPool, LPD3DXEFFECT* ppEffect, - LPD3DXBUFFER* ppCompilationErrors ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) + if ( _wcsicmp( ext, L".dds" ) == 0 ) { - DXUTCache_Effect& Entry = m_EffectCache[i]; - - if( Entry.Location == DXUTCACHE_LOCATION_FILE && - !lstrcmpW( Entry.wszSource, pSrcFile ) && - Entry.dwFlags == Flags ) - { - // A match is found. Increment the ref coutn and return the ID3DXEffect object. - *ppEffect = Entry.pEffect; - ( *ppEffect )->AddRef(); - return S_OK; - } + hr = DirectX::CreateDDSTextureFromFile( d3dDevice, str, nullptr, textureView ); } - - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. -#ifdef D3DXFX_LARGEADDRESS_HANDLE - Flags |= D3DXFX_LARGEADDRESSAWARE; -#endif - - hr = D3DXCreateEffectFromFile( pDevice, pSrcFile, pDefines, pInclude, Flags, pPool, ppEffect, - ppCompilationErrors ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Effect NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_FILE; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcFile ); - NewEntry.dwFlags = Flags; - NewEntry.pEffect = *ppEffect; - NewEntry.pEffect->AddRef(); - - m_EffectCache.Add( NewEntry ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::CreateEffectFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, const D3DXMACRO* pDefines, - LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXEFFECTPOOL pPool, - LPD3DXEFFECT* ppEffect, LPD3DXBUFFER* ppCompilationErrors ) -{ - // Search the cache for a matching entry. - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) + else { - DXUTCache_Effect& Entry = m_EffectCache[i]; - - if( Entry.Location == DXUTCACHE_LOCATION_RESOURCE && - Entry.hSrcModule == hSrcModule && - !lstrcmpW( Entry.wszSource, pSrcResource ) && - Entry.dwFlags == Flags ) - { - // A match is found. Increment the ref coutn and return the ID3DXEffect object. - *ppEffect = Entry.pEffect; - ( *ppEffect )->AddRef(); - return S_OK; - } + hr = DirectX::CreateWICTextureFromFile( d3dDevice, nullptr, str, nullptr, textureView ); } - HRESULT hr; - - // No matching entry. Load the resource and create a new entry. -#ifdef D3DXFX_LARGEADDRESS_HANDLE - Flags |= D3DXFX_LARGEADDRESSAWARE; -#endif - - hr = D3DXCreateEffectFromResource( pDevice, hSrcModule, pSrcResource, pDefines, pInclude, Flags, - pPool, ppEffect, ppCompilationErrors ); - if( FAILED( hr ) ) - return hr; - - DXUTCache_Effect NewEntry; - NewEntry.Location = DXUTCACHE_LOCATION_RESOURCE; - NewEntry.hSrcModule = hSrcModule; - wcscpy_s( NewEntry.wszSource, MAX_PATH, pSrcResource ); - NewEntry.dwFlags = Flags; - NewEntry.pEffect = *ppEffect; - NewEntry.pEffect->AddRef(); - - m_EffectCache.Add( NewEntry ); - return S_OK; + return hr; } - -//-------------------------------------------------------------------------------------- -// Device event callbacks -//-------------------------------------------------------------------------------------- - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnCreateDevice( IDirect3DDevice9* pd3dDevice ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateTextureFromFile( ID3D11Device* d3dDevice, const wchar_t* szFileName, ID3D11Resource** texture ) { - return S_OK; -} + if ( !d3dDevice || !szFileName || !texture ) + return E_INVALIDARG; + WCHAR str[MAX_PATH]; + HRESULT hr = DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ); + if ( FAILED(hr) ) + return hr; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnResetDevice( IDirect3DDevice9* pd3dDevice ) -{ - // Call OnResetDevice on all effect and font objects - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) - m_EffectCache[i].pEffect->OnResetDevice(); - for( int i = 0; i < m_FontCache.GetSize(); ++i ) - m_FontCache[i].pFont->OnResetDevice(); + WCHAR ext[_MAX_EXT]; + _wsplitpath_s( str, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT ); + if ( _wcsicmp( ext, L".dds" ) == 0 ) + { + hr = DirectX::CreateDDSTextureFromFile( d3dDevice, str, texture, nullptr ); + } + else + { + hr = DirectX::CreateWICTextureFromFile( d3dDevice, nullptr, str, texture, nullptr ); + } - return S_OK; + return hr; } - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnLostDevice() +_Use_decl_annotations_ +HRESULT WINAPI DXUTSaveTextureToFile( ID3D11DeviceContext* pContext, ID3D11Resource* pSource, bool usedds, const wchar_t* szFileName ) { - // Call OnLostDevice on all effect and font objects - for( int i = 0; i < m_EffectCache.GetSize(); ++i ) - m_EffectCache[i].pEffect->OnLostDevice(); - for( int i = 0; i < m_FontCache.GetSize(); ++i ) - m_FontCache[i].pFont->OnLostDevice(); - - // Release all the default pool textures - for( int i = m_TextureCache.GetSize() - 1; i >= 0; --i ) - if( m_TextureCache[i].Pool9 == D3DPOOL_DEFAULT ) - { - SAFE_RELEASE( m_TextureCache[i].pTexture9 ); - m_TextureCache.Remove( i ); // Remove the entry - } - - return S_OK; -} + if ( !pContext || !pSource || !szFileName ) + return E_INVALIDARG; + HRESULT hr; -//-------------------------------------------------------------------------------------- -HRESULT CDXUTResourceCache::OnDestroyDevice() -{ - // Release all resources - for( int i = m_EffectCache.GetSize() - 1; i >= 0; --i ) + if ( usedds ) { - SAFE_RELEASE( m_EffectCache[i].pEffect ); - m_EffectCache.Remove( i ); + hr = DirectX::SaveDDSTextureToFile( pContext, pSource, szFileName ); } - for( int i = m_FontCache.GetSize() - 1; i >= 0; --i ) - { - SAFE_RELEASE( m_FontCache[i].pFont ); - m_FontCache.Remove( i ); - } - for( int i = m_TextureCache.GetSize() - 1; i >= 0; --i ) + else { - SAFE_RELEASE( m_TextureCache[i].pTexture9 ); - SAFE_RELEASE( m_TextureCache[i].pSRV11 ); - m_TextureCache.Remove( i ); + hr = DirectX::SaveWICTextureToFile( pContext, pSource, GUID_ContainerFormatBmp, szFileName ); } - return S_OK; + return hr; } //-------------------------------------------------------------------------------------- // Desc: Returns a view matrix for rendering to a face of a cubemap. //-------------------------------------------------------------------------------------- -D3DXMATRIX WINAPI DXUTGetCubeMapViewMatrix( DWORD dwFace ) +XMMATRIX WINAPI DXUTGetCubeMapViewMatrix( _In_ DWORD dwFace ) { - D3DXVECTOR3 vEyePt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); - D3DXVECTOR3 vLookDir; - D3DXVECTOR3 vUpDir; - - switch( dwFace ) + static const XMVECTORF32 s_vLookDir[] = { - case D3DCUBEMAP_FACE_POSITIVE_X: - vLookDir = D3DXVECTOR3( 1.0f, 0.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - case D3DCUBEMAP_FACE_NEGATIVE_X: - vLookDir = D3DXVECTOR3( -1.0f, 0.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - case D3DCUBEMAP_FACE_POSITIVE_Y: - vLookDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 0.0f, -1.0f ); - break; - case D3DCUBEMAP_FACE_NEGATIVE_Y: - vLookDir = D3DXVECTOR3( 0.0f, -1.0f, 0.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); - break; - case D3DCUBEMAP_FACE_POSITIVE_Z: - vLookDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - case D3DCUBEMAP_FACE_NEGATIVE_Z: - vLookDir = D3DXVECTOR3( 0.0f, 0.0f, -1.0f ); - vUpDir = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); - break; - } + { 1.0f, 0.0f, 0.0f, 0.0f }, + { -1.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, -1.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + }; - // Set the view transform for this cubemap surface - D3DXMATRIXA16 mView; - D3DXMatrixLookAtLH( &mView, &vEyePt, &vLookDir, &vUpDir ); - return mView; -} + static const XMVECTORF32 s_vUpDir[] = + { + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + }; + static_assert( _countof(s_vLookDir) == _countof(s_vUpDir), "arrays mismatch" ); -//-------------------------------------------------------------------------------------- -CDXUTLineManager::CDXUTLineManager() -{ - m_pd3dDevice = NULL; - m_pD3DXLine = NULL; -} - + if ( dwFace >= _countof(s_vLookDir) + || dwFace >= _countof(s_vUpDir) ) + return XMMatrixIdentity(); -//-------------------------------------------------------------------------------------- -CDXUTLineManager::~CDXUTLineManager() -{ - OnDeletedDevice(); + // Set the view transform for this cubemap surface + return XMMatrixLookAtLH( g_XMZero, s_vLookDir[ dwFace ], s_vUpDir[ dwFace ] ); } -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnCreatedDevice( IDirect3DDevice9* pd3dDevice ) -{ - m_pd3dDevice = pd3dDevice; - - HRESULT hr; - hr = D3DXCreateLine( m_pd3dDevice, &m_pD3DXLine ); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - +//====================================================================================== +// CDXUTResourceCache +//====================================================================================== -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnResetDevice() +CDXUTResourceCache::~CDXUTResourceCache() { - if( m_pD3DXLine ) - m_pD3DXLine->OnResetDevice(); - - return S_OK; + OnDestroyDevice(); } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnRender() +_Use_decl_annotations_ +HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCWSTR pSrcFile, + ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) { - HRESULT hr; - if( NULL == m_pD3DXLine ) + if ( !ppOutputRV ) return E_INVALIDARG; - bool bDrawingHasBegun = false; - float fLastWidth = 0.0f; - bool bLastAntiAlias = false; + *ppOutputRV = nullptr; - for( int i = 0; i < m_LinesList.GetSize(); i++ ) + for( auto it = m_TextureCache.cbegin(); it != m_TextureCache.cend(); ++it ) { - LINE_NODE* pLineNode = m_LinesList.GetAt( i ); - if( pLineNode ) + if( !wcscmp( it->wszSource, pSrcFile ) + && it->bSRGB == bSRGB + && it->pSRV11 ) { - if( !bDrawingHasBegun || - fLastWidth != pLineNode->fWidth || - bLastAntiAlias != pLineNode->bAntiAlias ) - { - if( bDrawingHasBegun ) - { - hr = m_pD3DXLine->End(); - if( FAILED( hr ) ) - return hr; - } - - m_pD3DXLine->SetWidth( pLineNode->fWidth ); - m_pD3DXLine->SetAntialias( pLineNode->bAntiAlias ); - - fLastWidth = pLineNode->fWidth; - bLastAntiAlias = pLineNode->bAntiAlias; - - hr = m_pD3DXLine->Begin(); - if( FAILED( hr ) ) - return hr; - bDrawingHasBegun = true; - } - - hr = m_pD3DXLine->Draw( pLineNode->pVertexList, pLineNode->dwVertexListCount, pLineNode->Color ); - if( FAILED( hr ) ) - return hr; + it->pSRV11->AddRef(); + *ppOutputRV = it->pSRV11; + return S_OK; } } - if( bDrawingHasBegun ) - { - hr = m_pD3DXLine->End(); - if( FAILED( hr ) ) - return hr; - } - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnLostDevice() -{ - if( m_pD3DXLine ) - m_pD3DXLine->OnLostDevice(); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::OnDeletedDevice() -{ - RemoveAllLines(); - SAFE_RELEASE( m_pD3DXLine ); + WCHAR ext[_MAX_EXT]; + _wsplitpath_s( pSrcFile, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT ); - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::AddLine( int* pnLineID, D3DXVECTOR2* pVertexList, DWORD dwVertexListCount, D3DCOLOR Color, - float fWidth, float fScaleRatio, bool bAntiAlias ) -{ - if( pVertexList == NULL || dwVertexListCount == 0 ) - return E_INVALIDARG; - - LINE_NODE* pLineNode = new LINE_NODE; - if( pLineNode == NULL ) - return E_OUTOFMEMORY; - ZeroMemory( pLineNode, sizeof( LINE_NODE ) ); - - pLineNode->nLineID = m_LinesList.GetSize(); - pLineNode->Color = Color; - pLineNode->fWidth = fWidth; - pLineNode->bAntiAlias = bAntiAlias; - pLineNode->dwVertexListCount = dwVertexListCount; - - if( pnLineID ) - *pnLineID = pLineNode->nLineID; - - pLineNode->pVertexList = new D3DXVECTOR2[dwVertexListCount]; - if( pLineNode->pVertexList == NULL ) + HRESULT hr; + if ( _wcsicmp( ext, L".dds" ) == 0 ) { - delete pLineNode; - return E_OUTOFMEMORY; + hr = DirectX::CreateDDSTextureFromFileEx( pDevice, pSrcFile, 0, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, bSRGB, + nullptr, ppOutputRV, nullptr ); } - for( DWORD i = 0; i < dwVertexListCount; i++ ) + else { - pLineNode->pVertexList[i] = pVertexList[i] * fScaleRatio; + hr = DirectX::CreateWICTextureFromFileEx( pDevice, pContext, pSrcFile, 0, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, bSRGB, + nullptr, ppOutputRV ); } - m_LinesList.Add( pLineNode ); + if ( FAILED(hr) ) + return hr; + + DXUTCache_Texture entry; + wcscpy_s( entry.wszSource, MAX_PATH, pSrcFile ); + entry.bSRGB = bSRGB; + entry.pSRV11 = *ppOutputRV; + entry.pSRV11->AddRef(); + m_TextureCache.push_back( entry ); return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::AddRect( int* pnLineID, RECT rc, D3DCOLOR Color, float fWidth, float fScaleRatio, - bool bAntiAlias ) +_Use_decl_annotations_ +HRESULT CDXUTResourceCache::CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCSTR pSrcFile, + ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ) { - if( fWidth > 2.0f ) - { - D3DXVECTOR2 vertexList[8]; - - vertexList[0].x = ( float )rc.left; - vertexList[0].y = ( float )rc.top - ( fWidth / 2.0f ); - - vertexList[1].x = ( float )rc.left; - vertexList[1].y = ( float )rc.bottom + ( fWidth / 2.0f ); - - vertexList[2].x = ( float )rc.left; - vertexList[2].y = ( float )rc.bottom - 0.5f; - - vertexList[3].x = ( float )rc.right; - vertexList[3].y = ( float )rc.bottom - 0.5f; - - vertexList[4].x = ( float )rc.right; - vertexList[4].y = ( float )rc.bottom + ( fWidth / 2.0f ); - - vertexList[5].x = ( float )rc.right; - vertexList[5].y = ( float )rc.top - ( fWidth / 2.0f ); - - vertexList[6].x = ( float )rc.right; - vertexList[6].y = ( float )rc.top; - - vertexList[7].x = ( float )rc.left; - vertexList[7].y = ( float )rc.top; - - return AddLine( pnLineID, vertexList, 8, Color, fWidth, fScaleRatio, bAntiAlias ); - } - else - { - D3DXVECTOR2 vertexList[5]; - vertexList[0].x = ( float )rc.left; - vertexList[0].y = ( float )rc.top; - - vertexList[1].x = ( float )rc.left; - vertexList[1].y = ( float )rc.bottom; - - vertexList[2].x = ( float )rc.right; - vertexList[2].y = ( float )rc.bottom; - - vertexList[3].x = ( float )rc.right; - vertexList[3].y = ( float )rc.top; - - vertexList[4].x = ( float )rc.left; - vertexList[4].y = ( float )rc.top; + WCHAR szSrcFile[MAX_PATH]; + MultiByteToWideChar( CP_ACP, 0, pSrcFile, -1, szSrcFile, MAX_PATH ); + szSrcFile[MAX_PATH - 1] = 0; - return AddLine( pnLineID, vertexList, 5, Color, fWidth, fScaleRatio, bAntiAlias ); - } + return CreateTextureFromFile( pDevice, pContext, szSrcFile, ppOutputRV, bSRGB ); } - //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::RemoveLine( int nLineID ) -{ - for( int i = 0; i < m_LinesList.GetSize(); i++ ) - { - LINE_NODE* pLineNode = m_LinesList.GetAt( i ); - if( pLineNode && pLineNode->nLineID == nLineID ) - { - SAFE_DELETE_ARRAY( pLineNode->pVertexList ); - delete pLineNode; - m_LinesList.SetAt( i, NULL ); - } - } - - return S_OK; -} +// Device event callbacks +//-------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------- -HRESULT CDXUTLineManager::RemoveAllLines() +HRESULT CDXUTResourceCache::OnDestroyDevice() { - for( int i = 0; i < m_LinesList.GetSize(); i++ ) + // Release all resources + for( size_t j = 0; j < m_TextureCache.size(); ++j ) { - LINE_NODE* pLineNode = m_LinesList.GetAt( i ); - if( pLineNode ) - { - SAFE_DELETE_ARRAY( pLineNode->pVertexList ); - delete pLineNode; - } + SAFE_RELEASE( m_TextureCache[ j ].pSRV11 ); } - m_LinesList.RemoveAll(); + m_TextureCache.clear(); + m_TextureCache.shrink_to_fit(); return S_OK; } -//-------------------------------------------------------------------------------------- -CDXUTTextHelper::CDXUTTextHelper( ID3DXFont* pFont9, ID3DXSprite* pSprite9, int nLineHeight ) -{ - Init( pFont9, pSprite9, nLineHeight ); -} +//====================================================================================== +// CDXUTTextHelper +//====================================================================================== +_Use_decl_annotations_ CDXUTTextHelper::CDXUTTextHelper( ID3D11Device* pd3d11Device, ID3D11DeviceContext* pd3d11DeviceContext, CDXUTDialogResourceManager* pManager, int nLineHeight ) { - Init( NULL, NULL, nLineHeight ); + Init( nLineHeight ); m_pd3d11Device = pd3d11Device; m_pd3d11DeviceContext = pd3d11DeviceContext; m_pManager = pManager; } + CDXUTTextHelper::~CDXUTTextHelper() { } + //-------------------------------------------------------------------------------------- -void CDXUTTextHelper::Init( ID3DXFont* pFont9, ID3DXSprite* pSprite9, - int nLineHeight ) +void CDXUTTextHelper::Init( _In_ int nLineHeight ) { - m_pFont9 = pFont9; - m_pSprite9 = pSprite9; - m_clr = D3DXCOLOR( 1, 1, 1, 1 ); + m_clr = XMFLOAT4( 1, 1, 1, 1 ); m_pt.x = 0; m_pt.y = 0; m_nLineHeight = nLineHeight; - m_pd3d11Device = NULL; - m_pd3d11DeviceContext = NULL; - m_pManager = NULL; + m_pd3d11Device = nullptr; + m_pd3d11DeviceContext = nullptr; + m_pManager = nullptr; // Create a blend state if a sprite is passed in } //-------------------------------------------------------------------------------------- -HRESULT CDXUTTextHelper::DrawFormattedTextLine( const WCHAR* strMsg, ... ) +HRESULT CDXUTTextHelper::DrawFormattedTextLine( _In_z_ const WCHAR* strMsg, ... ) { WCHAR strBuffer[512]; @@ -1629,19 +949,16 @@ HRESULT CDXUTTextHelper::DrawFormattedTextLine( const WCHAR* strMsg, ... ) //-------------------------------------------------------------------------------------- -HRESULT CDXUTTextHelper::DrawTextLine( const WCHAR* strMsg ) +HRESULT CDXUTTextHelper::DrawTextLine( _In_z_ const WCHAR* strMsg ) { - if( NULL == m_pFont9 && NULL == m_pd3d11DeviceContext ) + if( !m_pd3d11DeviceContext ) return DXUT_ERR_MSGBOX( L"DrawTextLine", E_INVALIDARG ); HRESULT hr = S_OK; RECT rc; SetRect( &rc, m_pt.x, m_pt.y, 0, 0 ); - if( m_pFont9 ) - hr = m_pFont9->DrawText( m_pSprite9, strMsg, -1, &rc, DT_NOCLIP, m_clr ); - else if( m_pd3d11DeviceContext ) - DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, - (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); + DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, + (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); if( FAILED( hr ) ) return DXTRACE_ERR_MSGBOX( L"DrawText", hr ); @@ -1652,7 +969,9 @@ HRESULT CDXUTTextHelper::DrawTextLine( const WCHAR* strMsg ) } -HRESULT CDXUTTextHelper::DrawFormattedTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg, ... ) +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTTextHelper::DrawFormattedTextLine( const RECT& rc, const WCHAR* strMsg, ... ) { WCHAR strBuffer[512]; @@ -1662,21 +981,20 @@ HRESULT CDXUTTextHelper::DrawFormattedTextLine( RECT& rc, DWORD dwFlags, const W strBuffer[511] = L'\0'; va_end( args ); - return DrawTextLine( rc, dwFlags, strBuffer ); + return DrawTextLine( rc, strBuffer ); } -HRESULT CDXUTTextHelper::DrawTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg ) +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT CDXUTTextHelper::DrawTextLine( const RECT& rc, const WCHAR* strMsg ) { - if( NULL == m_pFont9 && NULL == m_pd3d11DeviceContext ) + if( !m_pd3d11DeviceContext ) return DXUT_ERR_MSGBOX( L"DrawTextLine", E_INVALIDARG ); HRESULT hr = S_OK; - if( m_pFont9 ) - hr = m_pFont9->DrawText( m_pSprite9, strMsg, -1, &rc, dwFlags, m_clr ); - else if( m_pd3d11DeviceContext ) - DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, - (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); + DrawText11DXUT( m_pd3d11Device, m_pd3d11DeviceContext, strMsg, rc, m_clr, + (float)m_pManager->m_nBackBufferWidth, (float)m_pManager->m_nBackBufferHeight, false ); if( FAILED( hr ) ) return DXTRACE_ERR_MSGBOX( L"DrawText", hr ); @@ -1690,9 +1008,6 @@ HRESULT CDXUTTextHelper::DrawTextLine( RECT& rc, DWORD dwFlags, const WCHAR* str //-------------------------------------------------------------------------------------- void CDXUTTextHelper::Begin() { - if( m_pSprite9 ) - m_pSprite9->Begin( D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE ); - if( m_pd3d11DeviceContext ) { m_pManager->StoreD3D11State( m_pd3d11DeviceContext ); @@ -1701,11 +1016,11 @@ void CDXUTTextHelper::Begin() } + + +//-------------------------------------------------------------------------------------- void CDXUTTextHelper::End() { - if( m_pSprite9 ) - m_pSprite9->End(); - if( m_pd3d11DeviceContext ) { m_pManager->RestoreD3D11State( m_pd3d11DeviceContext ); diff --git a/samples/DX_APIUsage/DXUT/Optional/SDKmisc.h b/samples/DX_APIUsage/DXUT/Optional/SDKmisc.h index b625b87..a5f8a52 100644 --- a/samples/DX_APIUsage/DXUT/Optional/SDKmisc.h +++ b/samples/DX_APIUsage/DXUT/Optional/SDKmisc.h @@ -3,159 +3,42 @@ // // Various helper functionality that is shared between SDK samples // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef SDKMISC_H -#define SDKMISC_H - //----------------------------------------------------------------------------- // Resource cache for textures, fonts, meshs, and effects. // Use DXUTGetGlobalResourceCache() to access the global cache //----------------------------------------------------------------------------- -enum DXUTCACHE_SOURCELOCATION -{ - DXUTCACHE_LOCATION_FILE, - DXUTCACHE_LOCATION_RESOURCE -}; - struct DXUTCache_Texture { - DXUTCACHE_SOURCELOCATION Location; WCHAR wszSource[MAX_PATH]; - HMODULE hSrcModule; - UINT Width; - UINT Height; - UINT Depth; - UINT MipLevels; - UINT MiscFlags; - union - { - DWORD Usage9; - D3D11_USAGE Usage11; - }; - union - { - D3DFORMAT Format9; - DXGI_FORMAT Format; - }; - union - { - D3DPOOL Pool9; - UINT CpuAccessFlags; - }; - union - { - D3DRESOURCETYPE Type9; - UINT BindFlags; - }; - IDirect3DBaseTexture9* pTexture9; + bool bSRGB; ID3D11ShaderResourceView* pSRV11; - DXUTCache_Texture() - { - pTexture9 = NULL; - pSRV11 = NULL; - } -}; - -struct DXUTCache_Font : public D3DXFONT_DESC -{ - ID3DXFont* pFont; -}; - -struct DXUTCache_Effect -{ - DXUTCACHE_SOURCELOCATION Location; - WCHAR wszSource[MAX_PATH]; - HMODULE hSrcModule; - DWORD dwFlags; - ID3DXEffect* pEffect; + DXUTCache_Texture() : + pSRV11(nullptr) + { + } }; class CDXUTResourceCache { public: - ~CDXUTResourceCache(); - - HRESULT CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCSTR pSrcFile, - LPDIRECT3DTEXTURE9* ppTexture ); - HRESULT CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCTSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB=false ); - HRESULT CreateTextureFromFile( ID3D11Device* pDevice, ID3D11DeviceContext *pContext, LPCSTR pSrcFile, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB=false ); - 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 ); - HRESULT CreateTextureFromFileEx( ID3D11Device* pDevice, ID3D11DeviceContext* pContext, LPCTSTR pSrcFile, - D3DX11_IMAGE_LOAD_INFO* pLoadInfo, ID3DX11ThreadPump* pPump, - ID3D11ShaderResourceView** ppOutputRV, bool bSRGB ); - HRESULT CreateTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, LPDIRECT3DTEXTURE9* ppTexture ); - 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 ); - HRESULT CreateCubeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ); - 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 ); - HRESULT CreateCubeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DCUBETEXTURE9* ppCubeTexture ); - 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 ); - HRESULT CreateVolumeTextureFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ); - 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 ); - HRESULT CreateVolumeTextureFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, - LPDIRECT3DVOLUMETEXTURE9* ppVolumeTexture ); - 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 ); - 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 ); - HRESULT CreateFontIndirect( LPDIRECT3DDEVICE9 pDevice, CONST D3DXFONT_DESC *pDesc, LPD3DXFONT *ppFont ); - HRESULT CreateEffectFromFile( LPDIRECT3DDEVICE9 pDevice, LPCTSTR pSrcFile, - const D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, DWORD Flags, - LPD3DXEFFECTPOOL pPool, LPD3DXEFFECT* ppEffect, - LPD3DXBUFFER* ppCompilationErrors ); - HRESULT CreateEffectFromResource( LPDIRECT3DDEVICE9 pDevice, HMODULE hSrcModule, - LPCTSTR pSrcResource, const D3DXMACRO* pDefines, - LPD3DXINCLUDE pInclude, DWORD Flags, LPD3DXEFFECTPOOL pPool, - LPD3DXEFFECT* ppEffect, LPD3DXBUFFER* ppCompilationErrors ); + ~CDXUTResourceCache(); + HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCWSTR pSrcFile, + _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false ); + HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCSTR pSrcFile, + _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false ); public: - HRESULT OnCreateDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnResetDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnLostDevice(); - HRESULT OnDestroyDevice(); + HRESULT OnDestroyDevice(); protected: friend CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache(); @@ -163,15 +46,11 @@ protected: friend HRESULT WINAPI DXUTReset3DEnvironment(); friend void WINAPI DXUTCleanup3DEnvironment( bool bReleaseSettings ); - CDXUTResourceCache() - { - } + CDXUTResourceCache() { } - CGrowableArray <DXUTCache_Texture> m_TextureCache; - CGrowableArray <DXUTCache_Effect> m_EffectCache; - CGrowableArray <DXUTCache_Font> m_FontCache; + std::vector<DXUTCache_Texture> m_TextureCache; }; - + CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache(); @@ -182,187 +61,70 @@ class CDXUTDialogResourceManager; class CDXUTTextHelper { public: - CDXUTTextHelper( ID3DXFont* pFont9 = NULL, ID3DXSprite* pSprite9 = NULL, - int nLineHeight = 15 ); - CDXUTTextHelper( ID3D11Device* pd3d11Device, ID3D11DeviceContext* pd3dDeviceContext, CDXUTDialogResourceManager* pManager, int nLineHeight ); - ~CDXUTTextHelper(); + CDXUTTextHelper( _In_ ID3D11Device* pd3d11Device, _In_ ID3D11DeviceContext* pd3dDeviceContext, _In_ CDXUTDialogResourceManager* pManager, _In_ int nLineHeight ); + ~CDXUTTextHelper(); - void Init( ID3DXFont* pFont9 = NULL, ID3DXSprite* pSprite9 = NULL, - int nLineHeight = 15 ); + void Init( _In_ int nLineHeight = 15 ); - void SetInsertionPos( int x, int y ) - { - m_pt.x = x; m_pt.y = y; - } - void SetForegroundColor( D3DXCOLOR clr ) + void SetInsertionPos( _In_ int x, _In_ int y ) { - m_clr = clr; + m_pt.x = x; + m_pt.y = y; } + void SetForegroundColor( _In_ DirectX::XMFLOAT4 clr ) { m_clr = clr; } + void SetForegroundColor( _In_ DirectX::FXMVECTOR clr ) { XMStoreFloat4( &m_clr, clr ); } void Begin(); - HRESULT DrawFormattedTextLine( const WCHAR* strMsg, ... ); - HRESULT DrawTextLine( const WCHAR* strMsg ); - HRESULT DrawFormattedTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg, ... ); - HRESULT DrawTextLine( RECT& rc, DWORD dwFlags, const WCHAR* strMsg ); + HRESULT DrawFormattedTextLine( _In_z_ const WCHAR* strMsg, ... ); + HRESULT DrawTextLine( _In_z_ const WCHAR* strMsg ); + HRESULT DrawFormattedTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg, ... ); + HRESULT DrawTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg ); void End(); protected: - ID3DXFont* m_pFont9; - ID3DXSprite* m_pSprite9; - D3DXCOLOR m_clr; + DirectX::XMFLOAT4 m_clr; POINT m_pt; int m_nLineHeight; - // D3D11 font - ID3D11Device* m_pd3d11Device; - ID3D11DeviceContext* m_pd3d11DeviceContext; - CDXUTDialogResourceManager* m_pManager; -}; - - -//-------------------------------------------------------------------------------------- -// Manages a persistent list of lines and draws them using ID3DXLine -//-------------------------------------------------------------------------------------- -class CDXUTLineManager -{ -public: - CDXUTLineManager(); - ~CDXUTLineManager(); - - HRESULT OnCreatedDevice( IDirect3DDevice9* pd3dDevice ); - HRESULT OnResetDevice(); - HRESULT OnRender(); - HRESULT OnLostDevice(); - HRESULT OnDeletedDevice(); - - HRESULT AddLine( int* pnLineID, D3DXVECTOR2* pVertexList, DWORD dwVertexListCount, D3DCOLOR Color, float fWidth, - float fScaleRatio, bool bAntiAlias ); - HRESULT AddRect( int* pnLineID, RECT rc, D3DCOLOR Color, float fWidth, float fScaleRatio, bool bAntiAlias ); - HRESULT RemoveLine( int nLineID ); - HRESULT RemoveAllLines(); - -protected: - struct LINE_NODE - { - int nLineID; - D3DCOLOR Color; - float fWidth; - bool bAntiAlias; - float fScaleRatio; - D3DXVECTOR2* pVertexList; - DWORD dwVertexListCount; - }; - - CGrowableArray <LINE_NODE*> m_LinesList; - IDirect3DDevice9* m_pd3dDevice; - ID3DXLine* m_pD3DXLine; + // D3D11 font + ID3D11Device* m_pd3d11Device; + ID3D11DeviceContext* m_pd3d11DeviceContext; + CDXUTDialogResourceManager* m_pManager; }; //-------------------------------------------------------------------------------------- // Shared code for samples to ask user if they want to use a REF device or quit //-------------------------------------------------------------------------------------- -void WINAPI DXUTDisplaySwitchingToREFWarning( DXUTDeviceVersion ver ); +void WINAPI DXUTDisplaySwitchingToREFWarning(); //-------------------------------------------------------------------------------------- // Tries to finds a media file by searching in common locations //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTFindDXSDKMediaFileCch( __out_ecount(cchDest) WCHAR* strDestPath, - __in int cchDest, - __in LPCWSTR strFilename ); -HRESULT WINAPI DXUTSetMediaSearchPath( LPCWSTR strPath ); +HRESULT WINAPI DXUTFindDXSDKMediaFileCch( _Out_writes_(cchDest) WCHAR* strDestPath, + _In_ int cchDest, + _In_z_ LPCWSTR strFilename ); +HRESULT WINAPI DXUTSetMediaSearchPath( _In_z_ LPCWSTR strPath ); LPCWSTR WINAPI DXUTGetMediaSearchPath(); //-------------------------------------------------------------------------------------- -// Returns a view matrix for rendering to a face of a cubemap. +// Compiles HLSL shaders //-------------------------------------------------------------------------------------- -D3DXMATRIX WINAPI DXUTGetCubeMapViewMatrix( DWORD dwFace ); - +HRESULT WINAPI DXUTCompileFromFile( _In_z_ LPCWSTR pFileName, + _In_reads_opt_(_Inexpressible_(pDefines->Name != NULL)) const D3D_SHADER_MACRO* pDefines, + _In_z_ LPCSTR pEntrypoint, _In_z_ LPCSTR pTarget, + _In_ UINT Flags1, _In_ UINT Flags2, + _Outptr_ ID3DBlob** ppCode ); //-------------------------------------------------------------------------------------- -// Simple helper stack class +// Texture utilities //-------------------------------------------------------------------------------------- -template <class T> class CDXUTStack -{ -private: - UINT m_MemorySize; - UINT m_NumElements; - T* m_pData; - - bool EnsureStackSize( UINT64 iElements ) - { - if( m_MemorySize > iElements ) - return true; - - T* pTemp = new T[ ( size_t )( iElements * 2 + 256 ) ]; - if( !pTemp ) - return false; - - if( m_NumElements ) - { - CopyMemory( pTemp, m_pData, ( size_t )( m_NumElements * sizeof( T ) ) ); - } - - if( m_pData ) delete []m_pData; - m_pData = pTemp; - return true; - } - -public: - CDXUTStack() - { - m_pData = NULL; m_NumElements = 0; m_MemorySize = 0; - } - ~CDXUTStack() - { - if( m_pData ) delete []m_pData; - } - - UINT GetCount() - { - return m_NumElements; - } - T GetAt( UINT i ) - { - return m_pData[i]; - } - T GetTop() - { - if( m_NumElements < 1 ) - return NULL; - - return m_pData[ m_NumElements - 1 ]; - } +HRESULT WINAPI DXUTCreateShaderResourceViewFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11ShaderResourceView** textureView ); +HRESULT WINAPI DXUTCreateTextureFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11Resource** texture ); +HRESULT WINAPI DXUTSaveTextureToFile( _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_ bool usedds, _In_z_ const wchar_t* szFileName ); - T GetRelative( INT i ) - { - INT64 iVal = m_NumElements - 1 + i; - if( iVal < 0 ) - return NULL; - return m_pData[ iVal ]; - } - - bool Push( T pElem ) - { - if( !EnsureStackSize( m_NumElements + 1 ) ) - return false; - - m_pData[m_NumElements] = pElem; - m_NumElements++; - - return true; - } - - T Pop() - { - if( m_NumElements < 1 ) - return NULL; - - m_NumElements --; - return m_pData[m_NumElements]; - } -}; - - -#endif +//-------------------------------------------------------------------------------------- +// Returns a view matrix for rendering to a face of a cubemap. +//-------------------------------------------------------------------------------------- +DirectX::XMMATRIX WINAPI DXUTGetCubeMapViewMatrix( _In_ DWORD dwFace ); |