尤拉角 EulerAngles 中的旋轉 Directx D3DXMatrixRotationYawPitchRoll
寫在前面:正當很高興地完成了矩陣相關的旋轉後,發現如果涉及到旋轉;矩陣,尤拉角(EulerAngles) ,四元數(Quaternions)這三個概念哪本書上都會提。這次先講下尤拉角。
1.什麼是尤拉角
尤拉角是由三個角組成,這三個角分別是Yaw,Pitch,Roll。很難翻譯這三個單詞,Yaw 表示繞y軸旋轉的角度,Pitch表示繞x軸旋轉的角度,Roll表示繞z軸旋轉的角度。也就是說,任意的旋轉角度都可以通過這三次按照先後順序旋轉得到。矩陣很難讓人具體形象表示,尤拉角就容易多了。注意可能很多地方三個角的先後次序不一樣,我們這裡選擇跟DirectX 中的D3DXMatrixRotationYawPitchRoll函式保持一致,先繞y軸旋轉,在繞x軸旋轉,最後繞z軸旋轉。
感覺Yaw(偏航),Pitch(投擲;傾斜;墜落),Roll(轉動) 介紹飛機旋轉的比較多,竊了三張圖來更象形地表示下:
2.尤拉角中的旋轉
還記得這三個矩陣嗎?繞相關軸旋轉,乘以相關矩陣就行了,也就是說尤拉角最終還是轉換成矩陣相乘,不過是要與三個矩陣相乘。
我們知道可以先把這三個矩陣相乘,這樣可以節約計算量。就是要先計算這三個矩陣相乘,注意矩陣相乘次序是不可更改的,更改了結果就不一樣了。
尤拉角的三個角,可以轉變為矩陣與矩陣的相乘。
3.開始替換D3DXMatrixRotationYawPitchRoll函式
Directx 9.0中有個函式叫D3DXMatrixRotationYawPitchRoll(D3DXMATRIX *pOut
//----------------------------------------------------------------------------- // Name: setupRotate() // Desc: 繞3個角度旋轉 //----------------------------------------------------------------------------- VOID setupRotate(D3DXMATRIXA16 *returnMatrix, float yaw, float pitch, float roll) { float sx = sin(pitch); float sy = sin(yaw); float sz = sin(roll); float cx = cos(pitch); float cy = cos(yaw); float cz = cos(roll); returnMatrix->_11 = cz * cy - sx * sy * sz; returnMatrix->_12 = cy * sz + sx * sy * cz; returnMatrix->_13 = -sy * cx; returnMatrix->_14 = 0.0f; returnMatrix->_21 = -cx * sz; returnMatrix->_22 = cx * cz; returnMatrix->_23 = sx; returnMatrix->_24 = 0.0f; returnMatrix->_31 = sy * cz + sx * cy * sz; returnMatrix->_32 = sy * sz - sx * cy * cz; returnMatrix->_33 = cx * cy; returnMatrix->_34 = 0.0f; returnMatrix->_41 = 0.0f; returnMatrix->_42 = 0.0f; returnMatrix->_43 = 0.0f; returnMatrix->_44 = 1.0f; }
先看下我們使用這個函式的例子效果:跟隨滑鼠移動的水壺,而不是自己在那旋轉個不停。
除了上面的函式之外的核心程式碼(需要對Windows中的訊息處理熟悉):
float g_fSpinX = 0.0f;
float g_fSpinY = 0.0f;
//滑鼠最後位置
static POINT ptLastMousePosit;
//當前滑鼠位置
static POINT ptCurrentMousePosit;
static bool bMousing;
switch( msg )
{
case WM_LBUTTONDOWN: // 當滑鼠左鍵按下時,記錄當前的位置(螢幕座標),並設定按下標誌
{
ptLastMousePosit.x = ptCurrentMousePosit.x = LOWORD (lParam);
ptLastMousePosit.y = ptCurrentMousePosit.y = HIWORD (lParam);
bMousing = true;
}
break;
case WM_LBUTTONUP:
{
bMousing = false;
}
break;
case WM_MOUSEMOVE: // 滑鼠移動時,儲存X/Y軸的移動距離
{
ptCurrentMousePosit.x = LOWORD (lParam);
ptCurrentMousePosit.y = HIWORD (lParam);
if( bMousing )
{
g_fSpinX -= (ptCurrentMousePosit.x - ptLastMousePosit.x);
g_fSpinY -= (ptCurrentMousePosit.y - ptLastMousePosit.y);
}
ptLastMousePosit.x = ptCurrentMousePosit.x;
ptLastMousePosit.y = ptCurrentMousePosit.y;
}
break;
}
//最後兩個值傳到我們寫好的函式中即可
setupRotate(&matWorld,D3DXToRadian(g_fSpinX),D3DXToRadian(g_fSpinY),0.0f);
完整程式碼:如果覺得看起來太累,拉到最底部,下載整個專案來看。
//-----------------------------------------------------------------------------
// File: Lights.cpp
// Copyright (c) Microsoft Corporation & Waitingfy.com. All rights reserved.
//-----------------------------------------------------------------------------
#include <Windows.h>
#include <mmsystem.h>
#include <d3dx9.h>
#include <strsafe.h>
#include <math.h>
#include <assert.h>
//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device
LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices
ID3DXMesh* Objects = 0;//茶壺
float g_fSpinX = 0.0f;
float g_fSpinY = 0.0f;
// A structure for our custom vertex type. We added a normal, and omitted the
// color (which is provided by the material)
struct CUSTOMVERTEX
{
D3DXVECTOR3 position; // The 3D position for the vertex
D3DXVECTOR3 normal; // The surface normal for the vertex
};
// Our custom FVF, which describes our custom vertex structure
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL)
//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
// Create the D3D object.
if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
return E_FAIL;
// Set up the structure used to create the D3DDevice. Since we are now
// using more complex geometry, we will create a device with a zbuffer.
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
// Create the D3DDevice
if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice ) ) )
{
return E_FAIL;
}
// Turn off culling
g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
// Turn on the zbuffer
g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
VOID Cleanup()
{
if( g_pVB != NULL )
g_pVB->Release();
if( g_pd3dDevice != NULL )
g_pd3dDevice->Release();
if( g_pD3D != NULL )
g_pD3D->Release();
if(Objects != NULL){
Objects->Release();
}
}
//-----------------------------------------------------------------------------
// Name: setupRotate()
// Desc: 繞3個角度旋轉
//-----------------------------------------------------------------------------
VOID setupRotate(D3DXMATRIXA16 *returnMatrix, float yaw, float pitch, float roll)
{
float sx = sin(pitch); float sy = sin(yaw); float sz = sin(roll);
float cx = cos(pitch); float cy = cos(yaw); float cz = cos(roll);
returnMatrix->_11 = cz * cy - sx * sy * sz;
returnMatrix->_12 = cy * sz + sx * sy * cz;
returnMatrix->_13 = -sy * cx;
returnMatrix->_14 = 0.0f;
returnMatrix->_21 = -cx * sz;
returnMatrix->_22 = cx * cz;
returnMatrix->_23 = sx;
returnMatrix->_24 = 0.0f;
returnMatrix->_31 = sy * cz + sx * cy * sz;
returnMatrix->_32 = sy * sz - sx * cy * cz;
returnMatrix->_33 = cx * cy;
returnMatrix->_34 = 0.0f;
returnMatrix->_41 = 0.0f;
returnMatrix->_42 = 0.0f;
returnMatrix->_43 = 0.0f;
returnMatrix->_44 = 1.0f;
}
//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
VOID SetupMatrices()
{
// 旋轉
D3DXMATRIXA16 matWorld;
D3DXMatrixIdentity( &matWorld );
//根據x軸和y軸移動距離旋轉
setupRotate(&matWorld,D3DXToRadian(g_fSpinX),D3DXToRadian(g_fSpinY),0.0f);
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );
// 攝像機的位置
D3DXVECTOR3 vEyePt( 0.0f, 3.0f,-5.0f );
D3DXVECTOR3 vLookatPt( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );
D3DXMATRIXA16 matView;
D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );
// 設定視錐體大小
D3DXMATRIXA16 matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f );
g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
}
//-----------------------------------------------------------------------------
// Name: SetupLights()
// Desc: Sets up the Lights and materials for the scene.
//-----------------------------------------------------------------------------
VOID SetupLights()
{
// 初始化一個材料
D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(D3DMATERIAL9) );
mtrl.Diffuse = mtrl.Ambient = D3DXCOLOR(1.0f,1.0f,0.0f,1.0f); //材質有漫射和環境光的設定,都為黃色
g_pd3dDevice->SetMaterial( &mtrl );
// 初始化一個白色的方向光
///*
D3DXVECTOR3 vecDir;
D3DLIGHT9 light;
ZeroMemory( &light, sizeof(D3DLIGHT9) );
light.Type = D3DLIGHT_DIRECTIONAL;//方向光
light.Diffuse = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f);//設定光源的漫射光顏色為白色
light.Direction = D3DXVECTOR3(0.0f,0.0f,1.0f);//光的傳播方向平行z軸
light.Range = 1000.0f;
g_pd3dDevice->SetLight( 0, &light );
g_pd3dDevice->LightEnable( 0, TRUE );
g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );
//*/
// Finally, turn on some ambient light.
g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x00202020 );
}
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
VOID Render()
{
// 背景為藍色
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );
// Begin the scene
if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
{
// 茶壺的材料顏色也定義在這個函式中
SetupLights();
// Setup the world, view, and projection matrices
SetupMatrices();
// Render the vertex buffer contents
g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );
g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
//建立一個茶壺
//Objects = 0;
D3DXMATRIX Worlds;
D3DXCreateTeapot(g_pd3dDevice, &Objects, 0);
Objects->DrawSubset(0);
Objects->Release();
Objects = 0;
// End the scene
g_pd3dDevice->EndScene();
}
// Present the backbuffer contents to the display
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
//Objects->Release();
}
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
static POINT ptLastMousePosit;
static POINT ptCurrentMousePosit;
static bool bMousing;
switch( msg )
{
case WM_DESTROY:
Cleanup();
PostQuitMessage( 0 );
return 0;
case WM_LBUTTONDOWN: // 當滑鼠左鍵按下時,記錄當前的位置(螢幕座標),並設定按下標誌
{
ptLastMousePosit.x = ptCurrentMousePosit.x = LOWORD (lParam);
ptLastMousePosit.y = ptCurrentMousePosit.y = HIWORD (lParam);
bMousing = true;
}
break;
case WM_LBUTTONUP:
{
bMousing = false;
}
break;
case WM_MOUSEMOVE: // 滑鼠移動時,儲存X/Y軸的移動距離
{
ptCurrentMousePosit.x = LOWORD (lParam);
ptCurrentMousePosit.y = HIWORD (lParam);
if( bMousing )
{
g_fSpinX -= (ptCurrentMousePosit.x - ptLastMousePosit.x);
g_fSpinY -= (ptCurrentMousePosit.y - ptLastMousePosit.y);
}
ptLastMousePosit.x = ptCurrentMousePosit.x;
ptLastMousePosit.y = ptCurrentMousePosit.y;
}
break;
}
return DefWindowProc( hWnd, msg, wParam, lParam );
}
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
// Register the window class
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
"D3D Tutorial", NULL };
RegisterClassEx( &wc );
// Create the application's window
HWND hWnd = CreateWindow( "D3D Tutorial", "D3D Tutorial 04: Lights",
WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
GetDesktopWindow(), NULL, wc.hInstance, NULL );
// Initialize Direct3D
if( SUCCEEDED( InitD3D( hWnd ) ) )
{
// Show the window
ShowWindow( hWnd, SW_SHOWDEFAULT );
UpdateWindow( hWnd );
// Enter the message loop
MSG msg;
ZeroMemory( &msg, sizeof(msg) );
while( msg.message!=WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
Render();
}
}
UnregisterClass( "D3D Tutorial", wc.hInstance );
return 0;
}
專案下載:
參考資源:http://hi.baidu.com/_鈊_煩_薏亂/blog/item/bac886c46164c1d438db49e7.html