///////////////////////////////////// // Name: // Purpose: // Output: // Return: ///////////////////////////////////// PUBLIC void CameraSetScene(hCAMERA cam) { D3DXMatrixLookAtRH( &cam->mtxCamera, &cam->vEye, &cam->vTarget, &cam->vUp ); g_p3DDevice->SetTransform(D3DTS_VIEW, &cam->mtxCamera); //update proj. mtx D3DXMATRIX projMtx; g_p3DDevice->GetTransform(D3DTS_PROJECTION, &projMtx); g_projMtx = cam->mtxCamera*projMtx; //update the billboard to face this camera TextureBillboardPrepare(); //calculate the frustrum planes FrustrumCalculate(); //set the eye pt. g_eyePt = cam->vEye; }
void D3DOverdrawWindow:: SetupView(int iViewpoint) { Vector3 e(0, 0, 1), u; if (m_pViewpoint && iViewpoint >= 0 && iViewpoint < (int) m_nViewpointCount) { e = m_pViewpoint[iViewpoint]; } if (e[1]*e[1] < e[0]*e[0]) { u = Normalize(Vector3(-e[2], 0, e[0])); } else { u = Normalize(Vector3(0, e[2], -e[1])); } D3DXVECTOR3 eye(e[0], e[1], e[2]); D3DXVECTOR3 at(0, 0, 0); D3DXVECTOR3 up(u[0], u[1], u[2]); D3DXMatrixLookAtRH(&m_mViewing, &eye, &at, &up); }
Matrix4x4& Matrix3::LookAtRH( const Vector3& eye, const Vector3& at, const Vector3& up ) { #ifdef __USE_D3DX__ D3DXMatrixLookAtRH( (D3DXMATRIX*)this, (D3DXVECTOR3*)&eye, (D3DXVECTOR3*)&at, (D3DXVECTOR3*)&up ); #else Vector3 zaxis = eye - at; zaxis.Normalize(); Vector3 xaxis = Vector3::Cross( up, zaxis ); xaxis.Normalize(); Vector3 yaxis = Vector3::Cross( zaxis, xaxis ); e[0] = xaxis.x; e[4] = xaxis.y; e[8] = xaxis.z; e[1] = yaxis.x; e[5] = yaxis.y; e[9] = yaxis.z; e[2] = zaxis.x; e[6] = zaxis.y; e[10] = zaxis.z; e[12] = Vector3::Dot( xaxis, eye ); e[13] = Vector3::Dot( yaxis, eye ); e[14] = Vector3::Dot( zaxis, eye ); e[3] = e[7] = e[11] = 0.0f; e[15] = 1.0f; #endif return *this;}
//------------------------------------------------------------------------------------------ HRESULT CGraphicDevice::SetCameraInfo( const SCameraInfo& i_cameraInfo ) { HRESULT hr; // 新しいカメラ情報を保持 m_cameraInfo = i_cameraInfo; /// 新しいカメラ情報でビュー,射影行列を計算 /// D3DXMATRIX mView, mProj; // ビュー行列を計算 D3DXMatrixLookAtRH( &mView , &m_cameraInfo.vEyePos , &m_cameraInfo.vInterestPos , &m_cameraInfo.vUpDir ); // 射影行列を計算 D3DXMatrixPerspectiveFovRH( &mProj , m_cameraInfo.fFov , ((float)m_nWidth) / m_nHeight , m_cameraInfo.fNear , m_cameraInfo.fFar ); // 各行列を設定 V_RETURN( SetTransform(TransformType_View, mView) ); V_RETURN( SetTransform(TransformType_Projection, mProj) ); return S_OK; }
//------------------------------------------------------------- // Name: RestoreDeviceObjects() // Desc: 화면크기가 변했을때 호출됨 // 확보한 메모리는 InvalidateDeviceObjects()에서 해제 //------------------------------------------------------------- HRESULT CMyD3DApplication::RestoreDeviceObjects() { // 정점과 색정보 CUSTOMVERTEX vertices[] = { // x, y, z, {-0.5f, +0.5f, 0}, {+0.5f, +0.5f, 0}, {-0.5f, -0.5f, 0}, {+0.5f, -0.5f, 0}, }; // 정점버퍼 생성 if( FAILED( m_pd3dDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX), // 정점버퍼 크기 0, D3DFVF_CUSTOMVERTEX, // 사용법, 정점포맷 D3DPOOL_DEFAULT, // 메모리 클래스 &m_pVB, NULL ))) // 정점버퍼 리소스 return E_FAIL; // 정점버퍼에 정보 저장 VOID* pVertices; if(FAILED( m_pVB->Lock(0, sizeof(vertices), (void**)&pVertices, 0))) return E_FAIL; memcpy( pVertices, vertices, sizeof(vertices) ); m_pVB->Unlock(); // 단축매크로 #define RS m_pd3dDevice->SetRenderState #define TSS m_pd3dDevice->SetTextureStageState #define SAMP m_pd3dDevice->SetSamplerState // 렌더링 상태설정 RS( D3DRS_DITHERENABLE, FALSE ); RS( D3DRS_SPECULARENABLE, FALSE ); RS( D3DRS_ZENABLE, TRUE ); RS( D3DRS_AMBIENT, 0x000F0F0F ); TSS( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 ); TSS( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE ); // 폰트 m_pFont->RestoreDeviceObjects(); // 뷰행렬 설정 D3DXVECTOR3 vEye = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); D3DXVECTOR3 vAt = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); D3DXVECTOR3 vUp = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); D3DXMatrixLookAtRH( &m_matView, &vEye, &vAt, &vUp ); // 투영행렬 설정 FLOAT fAspectRatio = (FLOAT)m_d3dsdBackBuffer.Width / (FLOAT)m_d3dsdBackBuffer.Height; D3DXMatrixPerspectiveFovRH( &m_matProj, D3DXToRadian(60.0f), fAspectRatio, 0.1f, 100.0f ); return S_OK; }
// Called before we begin drawing anything to the back buffer. This function // sets us up by calling beginscene, from there we can render whatever we want // then finish up by calling PostRender(). bool RendererD3D::PreRender(unsigned int fovState) { if(fovState==0){ lerp(m_fov,0.1f,m_fov,45.0f); } else if(fovState==1){ lerp(m_fov,0.1f,m_fov,80.0f); } else { lerp(m_fov,0.1f,m_fov,120.0f); } // Just making some forward declarations so the LookAt function is easier to read Camera& camera = Camera::GetInstance(); Vector position = camera.GetPosition(); Vector view = camera.GetCamEye(); Vector upVector = camera.GetUpVector(); double timeSeconds = GetTickCount() / 1000.0; // Clear the backbuffer to the clear color m_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(70,130,180), 1.0f, 0 ); // Set the camera position D3DXMATRIXA16 matrix; D3DXVECTOR3 eyeLocation; // Create and set the view matrix eyeLocation.x = position.x; eyeLocation.y = position.y; eyeLocation.z = position.z; D3DXVECTOR3 lookAt( view.x, view.y, view.z ); // Camera's up vector D3DXVECTOR3 up( upVector.x,upVector.y, upVector.z ); D3DXMatrixLookAtRH( &matrix, &eyeLocation, &lookAt, &up ); m_pd3dDevice->SetTransform( D3DTS_VIEW, &matrix ); // Store the view matrix m_viewMatrix = matrix; D3DXMATRIXA16 matrixProjection; D3DXMatrixPerspectiveFovRH( &matrixProjection, D3DXToRadian( m_fov ), SCREEN_WIDTH / (float) SCREEN_HEIGHT, 1.0f, 4000.f ); m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matrixProjection ); // Store the projection matrix m_projectionMatrix = matrixProjection; m_viewFrustum.UpdateViewFrustum(); if( SUCCEEDED( m_pd3dDevice->BeginScene() ) ){ return true; } else { return false; } }
void OmniMapD3D::LoadAndPush_ProjectiveTexturing_Matricies() { D3DXMATRIX matView; D3DXVECTOR3 camPos( ProjectorPosition.pos.x, ProjectorPosition.pos.y, ProjectorPosition.pos.z ); // Camera position D3DXVECTOR3 camLookat( ProjectorPosition.lookAtpos.x, ProjectorPosition.lookAtpos.y, ProjectorPosition.lookAtpos.z ); // Look-at point D3DXVECTOR3 camUp( ProjectorPosition.headsUp.x, ProjectorPosition.headsUp.y, ProjectorPosition.headsUp.z ); // Up vector D3DXMatrixOrthoRH(&worldViewProjection, 2.0, 2.0, 0.0, 1.0f); D3DXMatrixLookAtRH( &worldView, &camPos, &camLookat, &camUp); }
//Gets current view matrix D3DXMATRIX* Transformations::viewMatrix() { /*D3DXMATRIX* M = new D3DXMATRIX(cxAxis.x, cxAxis.y, cxAxis.z, 0.0f, cyAxis.x, cyAxis.y, cyAxis.z, 0.0f, czAxis.x, czAxis.y, czAxis.z, 0.0f, cPosition.x, cPosition.y, cPosition.z, 1.0f); D3DXMATRIX* N = new D3DXMATRIX(); D3DXMatrixInverse(N, NULL, M);*/ D3DXMatrixLookAtRH(View,&cPosition,&lookat,&up); return View; }
HRESULT World::frameRender(IDirect3DDevice9* pd3dDevice, double dTime, float fElapsedTime) { EpCamera& camera = GetG().m_camera; HRESULT hr = S_OK; ////////////////////////////////////////////////////////////////////////// // Perspective Rendering Phase pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE ); // TODO - Lighting D3DXMATRIX v, p, w; D3DXVECTOR3 eye(0, 0, -50), at(0, 0, 0), up(0, 1, 0); D3DXMatrixPerspectiveFovLH(&p, ArnToRadian(45.0), 1.0f, 0.0f, 1000.0f); D3DXMatrixLookAtRH(&v, &eye, &at, &up); D3DXMatrixIdentity(&w); pd3dDevice->SetTransform(D3DTS_VIEW, camera.GetViewMatrix()); pd3dDevice->SetTransform(D3DTS_PROJECTION, camera.GetProjMatrix()); ////////////////////////////////////////////////////////////////////////// // Aran lib rendering routine (CW) pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); //pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); pd3dDevice->SetFVF(ArnVertex::FVF); D3DPERF_BeginEvent(0, L"World render"); GetG().m_videoMan->renderMeshesOnly(m_modelSg->getSceneRoot()); D3DPERF_EndEvent(); ////////////////////////////////////////////////////////////////////////// // EP rendering routine (CCW) UnitSet::iterator it = m_unitSet.begin(); for ( ; it != m_unitSet.end(); ++it ) { if ( !(*it)->getRemoveFlag() ) { if ( (*it)->getType() != UT_UNITBASE ) { // Locally created instance. Almost by script file. (*it)->frameRender( pd3dDevice, dTime, fElapsedTime ); } else { // Remotely created instance by RakNet ReplicaManager. pd3dDevice->SetTransform( D3DTS_WORLD, (D3DMATRIX*)&((*it)->getLocalXformRaw()) ); pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); g_bst[BST_TEAPOT]->DrawSubset( 0 ); } } } DialogList::iterator itDialog = m_scriptedDialog.begin(); for ( ; itDialog != m_scriptedDialog.end(); ++itDialog ) { (*itDialog)->frameRender(pd3dDevice, dTime, fElapsedTime); } WorldStateManager& wsm = WorldStateManager::getSingleton(); wsm.getCurState()->frameRender(pd3dDevice, dTime, fElapsedTime); return hr; }
// renderShadowLayer - Calculates projection for, and renders, one shadow layer void DistantLand::renderShadowLayer(int layer, float radius) { DECLARE_MWBRIDGE D3DXVECTOR3 lookAt, nearPos; D3DXVECTOR3 up(0, 0, 1); D3DXMATRIX *view = &smView[layer], *proj = &smProj[layer], *viewproj = &smViewproj[layer]; // Select light vector, sunPos during daytime, sunVec during night D3DXVECTOR4 lightVec = (sunPos.z > 0) ? -sunPos : sunVec; // Centre of projection is ahead of the player // Not as far in z direction as player is likely looking at the ground plane rather than below lookAt.x = eyePos.x + radius * eyeVec.x; lookAt.y = eyePos.y + radius * eyeVec.y; lookAt.z = eyePos.z + 0.5 * radius * eyeVec.z; // Quantize projection centre to reduce texture swimming lookAt.x = 16.0 * floor(lookAt.x / 16.0); lookAt.y = 16.0 * floor(lookAt.y / 16.0); lookAt.z = 16.0 * floor(lookAt.z / 16.0); // Create shadow frustum centred on lookAt, looking along lightVec const float zrange = 8192.0; nearPos.x = lookAt.x - zrange * lightVec.x; nearPos.y = lookAt.y - zrange * lightVec.y; nearPos.z = lookAt.z - zrange * lightVec.z; D3DXMatrixLookAtRH(view, &nearPos, &lookAt, &up); D3DXMatrixOrthoRH(proj, 2 * radius, (1 + fabs(lightVec.z)) * radius, 0, 2.0 * zrange); *viewproj = (*view) * (*proj); // Texel quantization produces hideous temporal aliasing //viewproj->_41 = floor(viewproj->_41 * 512.0) / 512.0; //viewproj->_42 = floor(viewproj->_42 * 512.0) / 512.0; effect->SetMatrixArray(ehShadowViewproj, viewproj, 1); effectShadow->CommitChanges(); // Cull ViewFrustum range_frustum(viewproj); VisibleSet visible_set; currentWorldSpace->NearStatics->GetVisibleMeshesCoarse(range_frustum, visible_set); currentWorldSpace->FarStatics->GetVisibleMeshesCoarse(range_frustum, visible_set); currentWorldSpace->VeryFarStatics->GetVisibleMeshesCoarse(range_frustum, visible_set); // Render land and statics if(mwBridge->IsExterior()) renderDistantLand(effectShadow, view, proj); device->SetVertexDeclaration(StaticDecl); visible_set.Render(device, effectShadow, effect, &ehTex0, &ehHasAlpha, &ehWorld, SIZEOFSTATICVERT); }
void DXRender::updateCamera(const Vec3 & camPos, const Vec3 & camTgt, const Vec3 & camUp) { this->camPos = (const D3DXVECTOR3 &)camPos; this->camTgt = (const D3DXVECTOR3 &)(camTgt + camPos); this->camUp = (const D3DXVECTOR3 &)camUp; D3DXMatrixLookAtRH(&view, (const D3DXVECTOR3 *)&camPos, (const D3DXVECTOR3 *)&(camTgt + camPos), (const D3DXVECTOR3 *)&camUp); device->SetTransform(D3DTS_VIEW, &view); D3DXMatrixMultiply(&viewProj, &view, &proj); D3DXMatrixInverse(&viewProjInv, NULL, &viewProj); }
void AmjuGLDX9::LookAt(float eyeX, float eyeY, float eyeZ, float x, float y, float z, float upX, float upY, float upZ) { AMJU_CALL_STACK; D3DXVECTOR3 vEyePt(eyeX, eyeY, eyeZ); D3DXVECTOR3 vLookatPt(x, y, z); D3DXVECTOR3 vUpVec(upX, upY, upZ); D3DXMATRIX matLookAt; D3DXMatrixLookAtRH( &matLookAt, &vEyePt, &vLookatPt, &vUpVec ); g_matrixStack->LoadIdentity(); g_matrixStack->LoadMatrix( &matLookAt ); }
void renderFrame(void) { d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 162, 232), 1.0f, 0); // use 0, 162, 232 for nice blue color d3ddev->BeginScene(); // begins the 3D scene // SET UP THE PIPELINE D3DXMATRIX matTranslate; Vector2 mousePos = worldCoord(mouseX, mouseY); D3DXMatrixTranslation(&matTranslate, mousePos.x, mousePos.y, 0); D3DXMATRIX matView; // the view transform matrix D3DXMatrixLookAtRH(&matView, &D3DXVECTOR3(0.0f, 0.0f, 5.0f), // the camera position &D3DXVECTOR3(0.0f, 0.0f, 0.0f), // the look-at position &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); // the up direction d3ddev->SetTransform(D3DTS_VIEW, &(matView)); // set the view transform to matView D3DXMATRIX matProjection; // the projection transform matrix D3DXMatrixOrthoRH(&matProjection, viewWidth, // the horizontal view volume viewWidth * currentRatio, // the vertical view volume 0.25f, // the near view-plane 15.0f); // the far view-plane d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection); // set the projection d3ddev->SetTexture(0, tx); // select the vertex buffer to display d3ddev->SetStreamSource(0, vb, 0, sizeof(CUSTOMVERTEX)); // copy the vertex buffer to the back buffer d3ddev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); RECT rect; SetRect(&rect, 0, 0, wndWidth, wndHeight); font->DrawTextA(NULL, "Everward", 8, &rect, DT_CENTER | DT_VCENTER, 0xffffff00); d3ddev->EndScene(); // ends the 3D scene d3ddev->Present(NULL, NULL, NULL, NULL); // displays the created frame on the screen }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- VOID C3DCamera::SetViewParams( D3DXVECTOR3 &vEyePt, D3DXVECTOR3& vLookatPt, D3DXVECTOR3& vUpVec ) { // Set attributes for the view matrix m_vEyePt = vEyePt; m_vLookatPt = vLookatPt; m_vUpVec = vUpVec; D3DXVec3Normalize( &m_vView, &(m_vLookatPt - m_vEyePt) ); D3DXVec3Cross( &m_vCross, &m_vView, &m_vUpVec ); D3DXMatrixLookAtRH( &m_matView, &m_vEyePt, &m_vLookatPt, &m_vUpVec ); D3DXMatrixInverse( &m_matBillboard, NULL, &m_matView ); m_matBillboard._41 = 0.0f; m_matBillboard._42 = 0.0f; m_matBillboard._43 = 0.0f; }
//-------------------------------------------------------------------------------------- // Render the scene using the D3D9 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; // Clear the render target and the zbuffer V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB( 0, 45, 50, 170 ), 1.0f, 0 ) ); // set active device SCEMAN->SetActiveDevice( pd3dDevice ); D3DXMATRIX mtxTemp_Projection; D3DXMATRIX mtxTemp_View; D3DXMatrixPerspectiveFovRH( &mtxTemp_Projection, 60.f, 1.f, 1.f, 1000.f ); D3DXMatrixLookAtRH( &mtxTemp_View, &D3DXVECTOR3( 20.f, 20.f, 20.f ), &D3DXVECTOR3( 0.f, 0.f, 0.f ), &D3DXVECTOR3( 0.f, 1.f, 0.f ) ); SCEMAN->SetProjectionMatrix( &mtxTemp_Projection ); SCEMAN->SetViewMatrix( &mtxTemp_View ); // call update SCEMAN->Update( (float) fElapsedTime ); // update auto-params SHAMAN->UpdateAutoShaderParameters( (float) fElapsedTime ); // Render the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" ); // These events are to help PIX identify what the code is doing SCEMAN->Render(); DXUT_EndPerfEvent(); V( pd3dDevice->EndScene() ); } }
//----------------------------------------------------------------------------// void Direct3D10RenderTarget::updateMatrix() const { const float fov = 0.523598776f; const float w = d_area.getWidth(); const float h = d_area.getHeight(); const float aspect = w / h; const float midx = w * 0.5f; const float midy = h * 0.5f; d_viewDistance = midx / (aspect * 0.267949192431123f); D3DXVECTOR3 eye(midx, midy, -d_viewDistance); D3DXVECTOR3 at(midx, midy, 1); D3DXVECTOR3 up(0, -1, 0); D3DXMATRIX tmp; D3DXMatrixMultiply(&d_matrix, D3DXMatrixLookAtRH(&d_matrix, &eye, &at, &up), D3DXMatrixPerspectiveFovRH(&tmp, fov, aspect, d_viewDistance * 0.5f, d_viewDistance * 2.0f)); d_matrixValid = false; }
// WinMain int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { HRESULT hr; // ウィンドウクラスを登録 WNDCLASSEX wcex = { sizeof( WNDCLASSEX ), // cbSize CS_HREDRAW | CS_VREDRAW, // style WndProc, // lpfnWndProc 0, // cbClsExtra 0, // cbWndExtra hInstance, // hInstance NULL, // hIcon NULL, // hCursor ( HBRUSH )( COLOR_WINDOW + 1 ), // hbrBackGround NULL, // lpszMenuName g_className, // lpszClassName NULL // hIconSm }; if ( ! RegisterClassEx( &wcex ) ) { MessageBox( NULL, _T( "失敗: RegisterClassEx()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "RegisterClassEx: ok\n" ) ); // ウィンドウサイズを計算 RECT r = { 0, 0, 800, 450 }; // 800x450 (16:9) if ( ! AdjustWindowRect( &r, WS_OVERLAPPEDWINDOW, FALSE ) ) { MessageBox( NULL, _T( "失敗: AdjustWindowRect()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "AdjustWindowRect: ok (%d, %d)-(%d, %d)\n" ), r.left, r.top, r.right, r.bottom ); // ウィンドウ生成 HWND hWnd; hWnd = CreateWindow( g_className, g_windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, r.right - r.left, r.bottom - r.top, NULL, NULL, hInstance, NULL ); if ( hWnd == NULL ) { MessageBox( NULL, _T( "失敗: CreateWindow()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "CreateWindow: ok\n" ) ); // ウィンドウ表示 ShowWindow(hWnd, nCmdShow); dtprintf( _T( "ShowWindow: ok\n" ) ); // スワップチェイン設定 DXGI_SWAP_CHAIN_DESC scDesc = { { 1280, // BufferDesc.Width 720, // BufferDesc.Height { 60, // BufferDesc.RefreshRate.Numerator 1 // BufferDesc.RefreshRate.Denominator }, DXGI_FORMAT_R16G16B16A16_FLOAT, // BufferDesc.Format DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED, // BufferDesc.ScanlineOrdering DXGI_MODE_SCALING_CENTERED // BufferDesc.Scaling }, { 1, // SampleDesc.Count 0 // SampleDesc.Quality }, DXGI_USAGE_RENDER_TARGET_OUTPUT, // BufferUsage 1, // BufferCount hWnd, // OutputWindow TRUE, // Windowed DXGI_SWAP_EFFECT_DISCARD, // SwapEffect DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH // Flags }; // Direct3D11 デバイス・デバイスコンテキスト・スワップチェーンを生成 ID3D11Device * pDevice = NULL; ID3D11DeviceContext * pDeviceContext = NULL; IDXGISwapChain * pSwapChain = NULL; D3D_FEATURE_LEVEL feature; hr = D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, NULL, 0, D3D11_SDK_VERSION, &scDesc, &pSwapChain, &pDevice, &feature, &pDeviceContext ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: D3D11CreateDeviceAndSwapChain()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "D3D11CreateDeviceAndSwapChain: ok (pDevice: 0x%p, pDeviceContext: 0x%p, pSwapChain: 0x%p, feature: 0x%4x)\n" ), pDevice, pDeviceContext, pSwapChain, ( int ) feature ); // バックバッファテクスチャを取得 ID3D11Texture2D * pBackBuffer = NULL; hr = pSwapChain->GetBuffer( 0, __uuidof( pBackBuffer ), reinterpret_cast< void ** >( &pBackBuffer ) ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: IDXGISwapChain::GetBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "IDXGISwapChain::GetBuffer: ok (pBackBuffer: 0x%p)\n" ), pBackBuffer ); // レンダーターゲットビューを生成 ID3D11RenderTargetView * pRenderTargetView = NULL; hr = pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTargetView ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRenderTargetView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateRenderTargetView: ok (pRenderTargetView: 0x%p)\n" ), pRenderTargetView ); // デプス・ステンシルバッファとなるテクスチャを生成 D3D11_TEXTURE2D_DESC depthStencilBufferDesc = { 1280, // Width 720, // Height 1, // MipLevels 1, // ArraySize DXGI_FORMAT_D32_FLOAT, // Format { 1, // SampleDesc.Count 0 // SampleDesc.Quality }, D3D11_USAGE_DEFAULT, // Usage D3D11_BIND_DEPTH_STENCIL, // BindFlags 0, // CPUAccessFlags 0 // MiscFlags }; ID3D11Texture2D * pDepthStencilBuffer = NULL; hr = pDevice->CreateTexture2D( &depthStencilBufferDesc, NULL, &pDepthStencilBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateTexture2D()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateTexture2D: ok (pDepthStencilBuffer: 0x%p)\n" ), pDepthStencilBuffer ); // デプス・ステンシルビューを生成 ID3D11DepthStencilView * pDepthStencilView = NULL; hr = pDevice->CreateDepthStencilView( pDepthStencilBuffer, NULL, &pDepthStencilView ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateDepthStencilView: ok (pDepthStencilView: 0x%p)\n" ), pDepthStencilView ); // レンダーターゲットビューとデプス・ステンシルビューをバインド ID3D11RenderTargetView * pRenderTargetViews[] = { pRenderTargetView }; pDeviceContext->OMSetRenderTargets( 1, pRenderTargetViews, pDepthStencilView ); dtprintf( _T( "ID3D11DeviceContext::OMSetRenderTargets: ok\n" ) ); // バックバッファはもうここでは使わない COM_SAFE_RELEASE( pBackBuffer ); // ビューポートをバインド D3D11_VIEWPORT viewport = { 0.0f, // TopLeftX 0.0f, // TopLeftY 1280.0f, // Width 720.0f, // Height 0.0f, // MinDepth 1.0f // MaxDepth }; pDeviceContext->RSSetViewports( 1, &viewport ); dtprintf( _T( "ID3D11DeviceContext::RSSetViewports: ok\n" ) ); // 頂点データ float vertices[ 8 ][ 7 ] = { // Xaxis Yaxis Zaxis 赤 緑 青 Alpha { -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f }, // 手前左上 { 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f }, // 手前右上 { 0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f }, // 手前右下 { -0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f }, // 手前左下 { -0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f }, // 奥左上 { 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 1.0f, 1.0f }, // 奥右上 { 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f }, // 奥右下 { -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f } // 奥左下 }; // 頂点バッファを生成 D3D11_BUFFER_DESC vertexBufferDesc = { sizeof( vertices ), // ByteWidth D3D11_USAGE_DEFAULT, // Usage D3D11_BIND_VERTEX_BUFFER, // BindFlags 0, // CPUAccessFlags 0, // MiscFlags 0 // StructureByteStride }; D3D11_SUBRESOURCE_DATA vertexResourceData = { vertices }; ID3D11Buffer * pVertexBuffer = NULL; hr = pDevice->CreateBuffer( &vertexBufferDesc, &vertexResourceData, &pVertexBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVertexBuffer: 0x%p)\n" ), pVertexBuffer ); // 頂点バッファをバインド UINT strides[] = { sizeof( float ) * 7 }; UINT offsets[] = { 0 }; pDeviceContext->IASetVertexBuffers( 0, 1, &pVertexBuffer, strides, offsets ); dtprintf( _T( "ID3D11DeviceContext::IASetVertexBuffers: ok\n" ) ); // インデックスデータ unsigned int indices[] = { 0, 1, 2, 0, 2, 3, // 手前 4, 0, 3, 4, 3, 7, // 左 1, 5, 6, 1, 6, 2, // 右 0, 4, 5, 0, 5, 1, // 上 2, 6, 7, 2, 7, 3, // 下 5, 4, 7, 5, 7, 6 }; // 裏 // インデックスバッファを生成 D3D11_BUFFER_DESC indexBufferDesc = { sizeof( indices ), // ByteWidth D3D11_USAGE_DEFAULT, // Usage D3D11_BIND_INDEX_BUFFER, // BindFlags 0, // CPUAccessFlags 0, // MiscFlags 0 // StructureByteStride }; D3D11_SUBRESOURCE_DATA indexResourceData = { indices }; ID3D11Buffer * pIndexBuffer = NULL; hr = pDevice->CreateBuffer( &indexBufferDesc, &indexResourceData, &pIndexBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pIndexBuffer: 0x%p)\n" ), pIndexBuffer ); // インデックスバッファをバインド pDeviceContext->IASetIndexBuffer( pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 ); dtprintf( _T( "ID3D11DeviceContext::IASetIndexBuffer: ok\n" ) ); // プリミティブタイプを設定 pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); dtprintf( _T( "ID3D11DeviceContext::IASetPrimitiveTopology: ok\n" ) ); // 頂点シェーダ用の定数バッファを作成 D3D11_BUFFER_DESC VSConstantBufferDesc = { sizeof( D3DXMATRIX ) * 3, // ByteWidth D3D11_USAGE_DYNAMIC, // Usage D3D11_BIND_CONSTANT_BUFFER, // BindFlags D3D11_CPU_ACCESS_WRITE, // CPUAccessFlags 0, // MiscFlags 0 // StructureByteStride }; ID3D11Buffer * pVSConstantBuffer = NULL; hr = pDevice->CreateBuffer( &VSConstantBufferDesc, NULL, &pVSConstantBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVSConstantBuffer: 0x%p)\n" ), pVSConstantBuffer ); // 定数バッファをバインド pDeviceContext->VSSetConstantBuffers( 0, 1, &pVSConstantBuffer ); dtprintf( _T( "ID3D11DeviceContext::VSSetConstantBuffers: ok\n" ) ); // 頂点シェーダを作成 ID3D11VertexShader * pVertexShader = NULL; hr = pDevice->CreateVertexShader( g_vs_perspective, sizeof( g_vs_perspective ), NULL, &pVertexShader ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pVertexShader: 0x%p)\n" ), pVertexShader ); // ピクセルシェーダを作成 ID3D11PixelShader * pPixelShader = NULL; hr = pDevice->CreatePixelShader( g_ps_constant, sizeof( g_ps_constant ), NULL, &pPixelShader ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreatePixelShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreatePixelShader: ok (pPixelShader: 0x%p)\n" ), pPixelShader ); // シェーダをバインド pDeviceContext->VSSetShader( pVertexShader, NULL, 0 ); dtprintf( _T( "ID3D11DeviceContext::VSSetShader: ok\n" ) ); pDeviceContext->PSSetShader( pPixelShader, NULL, 0 ); dtprintf( _T( "ID3D11DeviceContext::PSSetShader: ok\n" ) ); pDeviceContext->GSSetShader( NULL, NULL, 0 ); pDeviceContext->HSSetShader( NULL, NULL, 0 ); pDeviceContext->DSSetShader( NULL, NULL, 0 ); // 入力エレメント記述子 D3D11_INPUT_ELEMENT_DESC verticesDesc[] = { { "IN_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "IN_COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; // 入力レイアウトを生成 ID3D11InputLayout * pInputLayout = NULL; hr = pDevice->CreateInputLayout( verticesDesc, 2, g_vs_perspective, sizeof( g_vs_perspective ), &pInputLayout ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pInputLayout: 0x%p)\n" ), pInputLayout ); // 入力レイアウトをバインド pDeviceContext->IASetInputLayout( pInputLayout ); dtprintf( _T( "ID3D11DeviceContext::IASetInputLayout: ok\n" ) ); // ラスタライザステートを生成 D3D11_RASTERIZER_DESC rasterizerStateDesc = { D3D11_FILL_SOLID, // FillMode // D3D11_FILL_WIREFRAME, // FillMode (ワイヤーフレーム表示) D3D11_CULL_BACK, // CullMode // D3D11_CULL_NONE, // CullMode (カリングなし) FALSE, // FrontCounterClockwise 0, // DepthBias 0.0f, // DepthBiasClamp 0.0f, // SlopeScaledDepthBias TRUE, // DepthClipEnable FALSE, // ScissorEnable FALSE, // MultisampleEnable FALSE // AntialiasedLineEnable }; ID3D11RasterizerState * pRasterizerState = NULL; hr = pDevice->CreateRasterizerState( &rasterizerStateDesc, &pRasterizerState ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRasterizerState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateRasterizerState: ok (pRasterizerState: 0x%p)\n" ), pRasterizerState ); // ラスタライザステートをバインド pDeviceContext->RSSetState( pRasterizerState ); dtprintf( _T( "ID3D11DeviceContext::RSSetState: ok\n" ) ); // デプス・ステンシルステートを生成 D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc = { TRUE, // DepthEnable D3D11_DEPTH_WRITE_MASK_ALL, // DepthWriteMask D3D11_COMPARISON_LESS, // DepthFunc FALSE, // StencilEnable D3D11_DEFAULT_STENCIL_READ_MASK, // StencilReadMask D3D11_DEFAULT_STENCIL_WRITE_MASK, // StencilWriteMask { D3D11_STENCIL_OP_KEEP, // FrontFace.StencilFailOp D3D11_STENCIL_OP_KEEP, // FrontFace.StencilDepthFailOp D3D11_STENCIL_OP_KEEP, // FrontFace.StencilPassOp D3D11_COMPARISON_ALWAYS // FrontFace.StencilFunc }, { D3D11_STENCIL_OP_KEEP, // BackFace.StencilFailOp D3D11_STENCIL_OP_KEEP, // BackFace.StencilDepthFailOp D3D11_STENCIL_OP_KEEP, // BackFace.StencilPassOp D3D11_COMPARISON_ALWAYS // BackFace.StencilFunc } }; ID3D11DepthStencilState * pDepthStencilState = NULL; hr = pDevice->CreateDepthStencilState( &depthStencilStateDesc, &pDepthStencilState ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateDepthStencilState: ok (pDepthStencilState: 0x%p)\n" ), pDepthStencilState ); // デプス・ステンシルステートをバインド pDeviceContext->OMSetDepthStencilState( pDepthStencilState, 0 ); dtprintf( _T( "ID3D11DeviceContext::OMSetDepthStencilState: ok\n" ) ); MSG msg; while ( 1 ) { // メッセージを取得 if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if ( msg.message == WM_QUIT ) { dtprintf( _T( "PeekMessage: WM_QUIT\n" ) ); break; } // メッセージ処理 DispatchMessage( &msg ); } else { HRESULT hr; static unsigned int count = 0; float theta = ( count++ / 200.0f ) * ( 3.141593f / 2.0f ); // World-View-Projection 行列をそれぞれ生成 D3DXMATRIX world, view, projection; D3DXMatrixIdentity( &world ); const D3DXVECTOR3 eye( 1.8f * 1.414214f * -cosf( theta ), 1.8f, 1.8f * 1.414214f * sinf( theta ) ); const D3DXVECTOR3 at( 0.0f, 0.0f, 0.0f ); const D3DXVECTOR3 up( 0.0f, 1.0f, 0.0f ); D3DXMatrixLookAtRH( &view, &eye, &at, &up ); D3DXMatrixPerspectiveFovRH( &projection, 3.141593f / 4.0f, 1280.0f / 720.0f, 1.0f, 10000.0f ); // 頂点シェーダ用定数バッファへアクセス D3D11_MAPPED_SUBRESOURCE mapped; hr = pDeviceContext->Map( pVSConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped ); if ( SUCCEEDED( hr ) ) { D3DXMATRIX * mapped_m = static_cast< D3DXMATRIX * >( mapped.pData ); mapped_m[0] = world; mapped_m[1] = view; mapped_m[2] = projection; // 後始末 pDeviceContext->Unmap( pVSConstantBuffer, 0 ); } // レンダーターゲットビューをクリア const float clear[ 4 ] = { 0.0f, 0.0f, 0.3f, 1.0f }; // RGBA pDeviceContext->ClearRenderTargetView( pRenderTargetView, clear ); // デプス・ステンシルビューをクリア pDeviceContext->ClearDepthStencilView( pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 ); // 描画 pDeviceContext->DrawIndexed( 36, 0, 0 ); pSwapChain->Present( 1, 0 ); // ちょっとだけ待つ Sleep( 5 ); } } // シェーダをアンバインド pDeviceContext->VSSetShader( NULL, NULL, 0 ); pDeviceContext->PSSetShader( NULL, NULL, 0 ); // デバイス・リソース解放 COM_SAFE_RELEASE( pDepthStencilState ); COM_SAFE_RELEASE( pRasterizerState ); COM_SAFE_RELEASE( pInputLayout ); COM_SAFE_RELEASE( pPixelShader ); COM_SAFE_RELEASE( pVertexShader ); COM_SAFE_RELEASE( pVSConstantBuffer ); COM_SAFE_RELEASE( pIndexBuffer ); COM_SAFE_RELEASE( pVertexBuffer ); COM_SAFE_RELEASE( pDepthStencilView ); COM_SAFE_RELEASE( pDepthStencilBuffer ); COM_SAFE_RELEASE( pRenderTargetView ); COM_SAFE_RELEASE( pSwapChain ); COM_SAFE_RELEASE( pDeviceContext ); COM_SAFE_RELEASE( pDevice ); return msg.wParam; }
void RenderFrameDX10(void) { Vector4 vClearColor(0.0f, 0.0f, 0.0f, 0.0f); UINT stride = sizeof(Vertex_VC); UINT offset = 0; // 取得呼叫GutCreateGraphicsDeviceDX10時所產生的D3D10物件 ID3D10RenderTargetView *pRenderTargetView = GutGetDX10RenderTargetView(); //frame buffer ID3D10DepthStencilView *pDepthStencilView = GutGetDX10DepthStencilView(); //depth/stencil buffer IDXGISwapChain *pSwapChain = GutGetDX10SwapChain(); // front/back buffer // 清除顏色 g_pDevice->ClearRenderTargetView(pRenderTargetView, (float *)&vClearColor); // 清除Depth/Stencil buffer g_pDevice->ClearDepthStencilView(pDepthStencilView, D3D10_CLEAR_DEPTH | D3D10_CLEAR_STENCIL, 1.0f, 0); // 設定vertex shader g_pDevice->VSSetShader(g_pVertexShader); // 設定pixel shader g_pDevice->PSSetShader(g_pPixelShader); // 設定vertex shader讀取參數的記憶體位罝 g_pDevice->VSSetConstantBuffers(0, 1, &g_pConstantBuffer); // 設定vertex資料格式 g_pDevice->IASetInputLayout(g_pVertexLayout); // 設定index buffer g_pDevice->IASetIndexBuffer(g_pSphereIndexBuffer, DXGI_FORMAT_R16_UINT, 0); // 設定三角形頂點索引值資料排列是triangle strip g_pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // 計算出一個可以轉換到鏡頭座標系的矩陣 D3DXMATRIX temp_matrix; D3DXMATRIX view_matrix, view_proj_matrix, world_view_proj_matrix; D3DXMatrixLookAtRH(&view_matrix, (D3DXVECTOR3 *)&g_eye, (D3DXVECTOR3 *)&g_lookat, (D3DXVECTOR3 *)&g_up); D3DXMatrixMultiply(&view_proj_matrix, &view_matrix, &g_proj_matrix); // 太陽, 帶入滑鼠的旋轉控制 D3DXMATRIX sun_matrix, sun_ry, sun_rx; D3DXMatrixRotationX(&sun_rx, g_fRotate_X); D3DXMatrixRotationY(&sun_ry, g_fRotate_Y); D3DXMatrixMultiply(&sun_matrix, &sun_ry, &sun_rx); D3DXMatrixMultiply(&world_view_proj_matrix, &sun_matrix, &view_proj_matrix); // 設定shader參數 D3DXMATRIX *pConstData; g_pConstantBuffer->Map( D3D10_MAP_WRITE_DISCARD, NULL, (void **) &pConstData ); *pConstData = world_view_proj_matrix; g_pConstantBuffer->Unmap(); // g_pDevice->IASetVertexBuffers(0, 1, &g_pSunVertexBuffer, &stride, &offset); g_pDevice->DrawIndexed(g_iNumSphereIndices, 0, 0); // 水星 float mercury_rotate_y = 2.0f * MATH_PI * (g_simulation_days / days_a_year_mercury); D3DXMATRIX mercury_matrix, mercury_translate, mercury_rotate; D3DXMatrixRotationY(&mercury_rotate, mercury_rotate_y); D3DXMatrixTranslation(&mercury_translate, mercury_to_sun_distance, 0.0f, 0.0f); D3DXMatrixMultiply(&temp_matrix, &mercury_translate, &mercury_rotate); D3DXMatrixMultiply(&mercury_matrix, &temp_matrix, &sun_matrix); D3DXMatrixMultiply(&world_view_proj_matrix, &mercury_matrix, &view_proj_matrix); // 設定shader參數 g_pConstantBuffer->Map( D3D10_MAP_WRITE_DISCARD, NULL, (void **) &pConstData ); *pConstData = world_view_proj_matrix; g_pConstantBuffer->Unmap(); g_pDevice->IASetVertexBuffers(0, 1, &g_pMoonVertexBuffer, &stride, &offset); g_pDevice->DrawIndexed(g_iNumSphereIndices, 0, 0); // 金星 float venus_rotate_y = 2.0f * MATH_PI * (g_simulation_days / days_a_year_venus); D3DXMATRIX venus_matrix, venus_rotate, venus_translate; D3DXMatrixRotationY(&venus_rotate, venus_rotate_y); D3DXMatrixTranslation(&venus_translate, venus_to_sun_distance, 0.0f, 0.0f); D3DXMatrixMultiply(&temp_matrix, &venus_translate, &venus_rotate); D3DXMatrixMultiply(&venus_matrix, &temp_matrix, &sun_matrix); D3DXMatrixMultiply(&world_view_proj_matrix, &venus_matrix, &view_proj_matrix); // 設定shader參數 g_pConstantBuffer->Map( D3D10_MAP_WRITE_DISCARD, NULL, (void **) &pConstData ); *pConstData = world_view_proj_matrix; g_pConstantBuffer->Unmap(); g_pDevice->IASetVertexBuffers(0, 1, &g_pMoonVertexBuffer, &stride, &offset); g_pDevice->DrawIndexed(g_iNumSphereIndices, 0, 0); // 地球 float earth_rotate_y = 2.0f * MATH_PI * (g_simulation_days / days_a_year); D3DXMATRIX earth_matrix, earth_rotate, earth_translate; D3DXMatrixRotationY(&earth_rotate, earth_rotate_y); D3DXMatrixTranslation(&earth_translate, earth_to_sun_distance, 0.0f, 0.0f); D3DXMatrixMultiply(&temp_matrix, &earth_translate, &earth_rotate); D3DXMatrixMultiply(&earth_matrix, &temp_matrix, &sun_matrix); D3DXMatrixMultiply(&world_view_proj_matrix, &earth_matrix, &view_proj_matrix); // 設定shader參數 g_pConstantBuffer->Map( D3D10_MAP_WRITE_DISCARD, NULL, (void **) &pConstData ); *pConstData = world_view_proj_matrix; g_pConstantBuffer->Unmap(); g_pDevice->IASetVertexBuffers(0, 1, &g_pEarthVertexBuffer, &stride, &offset); g_pDevice->DrawIndexed(g_iNumSphereIndices, 0, 0); // 月亮 float moon_rotate_y = 2.0f * MATH_PI * (g_simulation_days / days_a_month); D3DXMATRIX moon_matrix, moon_rotate, moon_translate; D3DXMatrixRotationY(&moon_rotate, moon_rotate_y); D3DXMatrixTranslation(&moon_translate, moon_to_earth_distance, 0.0f, 0.0f); D3DXMatrixMultiply(&temp_matrix, &moon_translate, &moon_rotate); D3DXMatrixMultiply(&moon_matrix, &temp_matrix, &earth_matrix); D3DXMatrixMultiply(&world_view_proj_matrix, &moon_matrix, &view_proj_matrix); // 設定shader參數 g_pConstantBuffer->Map( D3D10_MAP_WRITE_DISCARD, NULL, (void **) &pConstData ); *pConstData = world_view_proj_matrix; g_pConstantBuffer->Unmap(); g_pDevice->IASetVertexBuffers(0, 1, &g_pMoonVertexBuffer, &stride, &offset); g_pDevice->DrawIndexed(g_iNumSphereIndices, 0, 0); // 等待硬體掃結束, 然後才更新畫面 pSwapChain->Present(1, 0); }
bool CMapOutdoor::BeginRenderCharacterShadowToTexture() { D3DXMATRIX matLightView, matLightProj; CCamera* pCurrentCamera = CCameraManager::Instance().GetCurrentCamera(); if (!pCurrentCamera) return false; if (recreate) { CreateCharacterShadowTexture(); recreate = false; } D3DXVECTOR3 v3Target = pCurrentCamera->GetTarget(); D3DXVECTOR3 v3Eye(v3Target.x - 1.732f * 1250.0f, v3Target.y - 1250.0f, v3Target.z + 2.0f * 1.732f * 1250.0f); D3DXMatrixLookAtRH(&matLightView, &v3Eye, &v3Target, &D3DXVECTOR3(0.0f, 0.0f, 1.0f)); D3DXMatrixOrthoRH(&matLightProj, 2550.0f, 2550.0f, 1.0f, 15000.0f); STATEMANAGER.SaveTransform(D3DTS_VIEW, &matLightView); STATEMANAGER.SaveTransform(D3DTS_PROJECTION, &matLightProj); dwLightEnable = STATEMANAGER.GetRenderState(D3DRS_LIGHTING); STATEMANAGER.SetRenderState(D3DRS_LIGHTING, FALSE); STATEMANAGER.SaveRenderState(D3DRS_TEXTUREFACTOR, 0xFF808080); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR); STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE); STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); bool bSuccess = true; // Backup Device Context if (FAILED(ms_lpd3dDevice->GetRenderTarget(&m_lpBackupRenderTargetSurface))) { TraceError("CMapOutdoor::BeginRenderCharacterShadowToTexture : Unable to Save Window Render Target\n"); bSuccess = false; } if (FAILED(ms_lpd3dDevice->GetDepthStencilSurface(&m_lpBackupDepthSurface))) { TraceError("CMapOutdoor::BeginRenderCharacterShadowToTexture : Unable to Save Window Depth Surface\n"); bSuccess = false; } if (FAILED(ms_lpd3dDevice->SetRenderTarget(m_lpCharacterShadowMapRenderTargetSurface, m_lpCharacterShadowMapDepthSurface))) { TraceError("CMapOutdoor::BeginRenderCharacterShadowToTexture : Unable to Set Shadow Map Render Target\n"); bSuccess = false; } if (FAILED(ms_lpd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0xFF, 0xFF, 0xFF), 1.0f, 0))) { TraceError("CMapOutdoor::BeginRenderCharacterShadowToTexture : Unable to Clear Render Target"); bSuccess = false; } if (FAILED(ms_lpd3dDevice->GetViewport(&m_BackupViewport))) { TraceError("CMapOutdoor::BeginRenderCharacterShadowToTexture : Unable to Save Window Viewport\n"); bSuccess = false; } if (FAILED(ms_lpd3dDevice->SetViewport(&m_ShadowMapViewport))) { TraceError("CMapOutdoor::BeginRenderCharacterShadowToTexture : Unable to Set Shadow Map viewport\n"); bSuccess = false; } return bSuccess; }
void DrawMap(void) { char buff[512]; /*------------------------------------------------------------------------------ //Begin Input Ctrl & View Matrix Setup ------------------------------------------------------------------------------*/ static float angle = 0.0f; static float view = -240.0f; //view = -view; D3DXMATRIX matWorld; D3DXMATRIX matWorld2; D3DXMatrixTranslation(&matWorld2,0.0f,0.0f,angle/1500.0f); //D3DXMatrixRotationX(&matWorld, DEGtoRAD(angle/1.0069)); //DXMatrixRotationY(&matWorld, DEGtoRAD(angle)); D3DXMatrixRotationYawPitchRoll(&matWorld,DEGtoRAD(angle/20.0f),DEGtoRAD(angle/15.0f),DEGtoRAD(angle/10.0f)); matWorld*=matWorld2; angle += 1.0f; //g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); D3DXMATRIX matView; static float mawari = 0.0f; float delta; delta = 0.02f; if( GetKeyState(VK_CONTROL)&0x8000 ){ delta = 0.1f; }; if( GetKeyState(VK_RIGHT) & 0x8000 ) mawari-=delta; if( GetKeyState(VK_LEFT) & 0x8000 ) mawari+=delta; static D3DXVECTOR3 pos(0.0f, 0.0f, 0.0f); delta = 2.0f; if( GetKeyState(VK_CONTROL)&0x8000 ){ delta = 5.0f; }; if( GetKeyState(VK_UP) & 0x8000 ){ pos.x+=cos(mawari)*delta; pos.z+=sin(mawari)*delta; } if( GetKeyState(VK_DOWN) & 0x8000 ){ pos.x+=cos(mawari+3.1415926f)*delta; pos.z+=sin(mawari+3.1415926f)*delta; } if( GetKeyState(VK_PRIOR) & 0x8000 ){ pos.y+=delta; } if( GetKeyState(VK_NEXT) & 0x8000 ){ pos.y-=delta; } if( GetKeyState(VK_HOME) & 0x8000 ){ mawari=pos.x=pos.y=pos.z=0.0f; } D3DXVECTOR3 pnt(pos.x+cos(mawari), pos.y+0.0f, pos.z+sin(mawari)); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtRH(&matView, &pos, &pnt, &up); g_pD3DDevice->SetTransform(D3DTS_VIEW, &matView); D3DXMATRIX matProj; D3DXMatrixPerspectiveFovRH(&matProj, DEGtoRAD(45.0f), 4.0f / 3.0f, 1.0f, 500.0f); g_pD3DDevice->SetTransform(D3DTS_PROJECTION, &matProj); if( GetAsyncKeyState(VK_RETURN) & 0x1 ){ AutoMakeMMB=TRUE;} /*------------------------------------------------------------------------------ //End Input Ctrl & View Matrix Setup ------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------ //Begin RenderState ------------------------------------------------------------------------------*/ //g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW/*/D3DCULL_NONE*/ ); g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW/*/D3DCULL_NONE*/ ); g_pD3DDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); //g_pD3DDevice->SetLight(0,&light); //g_pD3DDevice->LightEnable(0,TRUE); g_pD3DDevice->SetRenderState(D3DRS_LIGHTING,FALSE); //g_pD3DDevice->SetRenderState(D3DRS_AMBIENT, 0xF0F0F0F0); g_pD3DDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD ); g_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); g_pD3DDevice->SetRenderState( D3DRS_STENCILENABLE, TRUE ); g_pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE , TRUE ); g_pD3DDevice->SetRenderState( D3DRS_ALPHAREF , 0x80 ); g_pD3DDevice->SetRenderState( D3DRS_ALPHAFUNC , D3DCMP_GREATER ); //g_pD3DDevice->SetRenderState(D3DRS_EDGEANTIALIAS,TRUE); /*------------------------------------------------------------------------------ //End RenderState ------------------------------------------------------------------------------*/ //地图是在TheDesertWorld.cpp里画的 //g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,128), 1.0f, 0L ); if( flgFirst ) logprintf("MZB:%d",noj); pory = 0; for( int i=0; i< noj; i++ ) { //if(i>=50) break; D3DXMATRIX matWorld; D3DXMATRIX matWorld2; D3DXMATRIX matWorld3; D3DXMATRIX matWorld4; D3DXMATRIX matWorldR4; D3DXMATRIX matWorldR5; D3DXMATRIX matWorldR6; ZeroMemory(&matWorld,sizeof(D3DXMATRIX)); D3DXMatrixScaling(&matWorld3,oj[i].fScaleX,oj[i].fScaleY,oj[i].fScaleZ); D3DXMatrixTranslation(&matWorld,oj[i].fTransX,oj[i].fTransY,oj[i].fTransZ); D3DXMatrixRotationX(&matWorldR4,oj[i].fRotX); D3DXMatrixRotationY(&matWorldR5,oj[i].fRotY); D3DXMatrixRotationZ(&matWorldR6,oj[i].fRotZ); matWorld2 = matWorldR4 * matWorldR5 * matWorldR6; matWorld=((matWorld3*matWorld2)/**matWorld4*/)*matWorld; g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); if( oj[i].fScaleX*oj[i].fScaleY*oj[i].fScaleZ < 0.0f ) { g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW ); } else { g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); } if(0) { float pp[]={-20,0,0,20,0,0, 0,-20,0,0,20,0, 0,0,-20,0,0,20}; //float pp[]={-10,0,0,10,0,0, 0,-10,0,0,10,0, 0,0,-10,0,0,10}; g_pD3DDevice->SetFVF(D3DFVF_XYZ); g_pD3DDevice->DrawPrimitiveUP(D3DPT_LINELIST,3,pp,12); } //Draw MzbLists Hint { RECT rc={5,91,600,128}; //自动输出 i = haha; //这个会打乱文件名和文件内容的正确配对吗? if (AutoMakeMMB == TRUE) {haha+=1;}; if (haha == (noj -1)) {haha = 0;AutoMakeMMB == false;}; sprintf(buff,"-----MZBList:%d/%d",i,noj); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(0,0,255)); } for( int j=0; j< NumMMB; j++ ) { if( memcmp(MMBlist[j]+16,oj[i].id,16) ) continue; //Draw Mmb Hint { RECT rc={5,134,600,160}; sprintf(buff,"------- Draw MMB:%s",sstr(oj[i].id,16)); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(0,0,255)); } /*------------------------------------------------------------------------------ //Begin MapObj Files Output ------------------------------------------------------------------------------*/ char opname[16]; //要输出的文件名 CopyMemory(opname,MMBlist[j]+16,16); ChangeSpaceToNull(opname); lstrcat(opname,".MapObj"); if (DoesFileExist(opname)) { logprintf("发现有文件重复将自动复盖,这些文件是%s",opname);} HANDLE hFile = CreateFile(opname,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL ); //ReadFile(hFile,pdat,dwSize,&dmy,NULL); if( hFile!=INVALID_HANDLE_VALUE && hFile!=NULL ) { DWORD dmy; //SetFilePointer(hFile,0,NULL,FILE_END); LPSTR ReadLocate = MMBlist[j+1]-16; int size = (int)(((*(DWORD*)&ReadLocate[4])>>3)&0x007ffff0); WriteFile(hFile,&ReadLocate[0],size,&dmy,NULL); CloseHandle(hFile); } /*------------------------------------------------------------------------------ //End MapObj Files Output ------------------------------------------------------------------------------*/ DrawMMB(MMBlist[j]); //信息输出1 { RECT rc={5,5,600,64}; sprintf(buff,"正在绘制Index数=%d\nLookAt:X=%02.2f Y=%02.2f Z=%02.2f",pory,pos.x,pos.y,pos.z); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(196,196,0)); } //信息输出2 { RECT rc={5,48,600,96}; sprintf(buff,"%sMZB=%d MMB=%d\n当前第%d个MMB",oj?"总共":"第",noj,NumMMB,j); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(196,196,0)); } break; }//End For MumMMB break; }//End For Noj
BOOL gldInitialiseMesa_DX( DGL_ctx *lpCtx) { GLD_driver_dx8 *gld = NULL; int MaxTextureSize, TextureLevels; BOOL bSoftwareTnL; if (lpCtx == NULL) return FALSE; gld = lpCtx->glPriv; if (gld == NULL) return FALSE; if (glb.bMultitexture) { lpCtx->glCtx->Const.MaxTextureUnits = gld->d3dCaps8.MaxSimultaneousTextures; // Only support MAX_TEXTURE_UNITS texture units. // ** If this is altered then the FVF formats must be reviewed **. if (lpCtx->glCtx->Const.MaxTextureUnits > GLD_MAX_TEXTURE_UNITS_DX8) lpCtx->glCtx->Const.MaxTextureUnits = GLD_MAX_TEXTURE_UNITS_DX8; } else { // Multitexture override lpCtx->glCtx->Const.MaxTextureUnits = 1; } // max texture size MaxTextureSize = min(gld->d3dCaps8.MaxTextureHeight, gld->d3dCaps8.MaxTextureWidth); if (MaxTextureSize == 0) MaxTextureSize = 256; // Sanity check // // HACK!! if (MaxTextureSize > 1024) MaxTextureSize = 1024; // HACK - CLAMP TO 1024 // HACK!! // // Got to set MAX_TEXTURE_SIZE as max levels. // Who thought this stupid idea up? ;) TextureLevels = 0; // Calculate power-of-two. while (MaxTextureSize) { TextureLevels++; MaxTextureSize >>= 1; } lpCtx->glCtx->Const.MaxTextureLevels = (TextureLevels) ? TextureLevels : 8; lpCtx->glCtx->Const.MaxDrawBuffers = 1; IDirect3DDevice8_SetRenderState(gld->pDev, D3DRS_LIGHTING, FALSE); IDirect3DDevice8_SetRenderState(gld->pDev, D3DRS_CULLMODE, D3DCULL_NONE); IDirect3DDevice8_SetRenderState(gld->pDev, D3DRS_DITHERENABLE, TRUE); IDirect3DDevice8_SetRenderState(gld->pDev, D3DRS_SHADEMODE, D3DSHADE_GOURAUD); IDirect3DDevice8_SetRenderState(gld->pDev, D3DRS_ZENABLE, (lpCtx->lpPF->dwDriverData!=D3DFMT_UNKNOWN) ? D3DZB_TRUE : D3DZB_FALSE); // Set the view matrix { D3DXMATRIX vm; #if 1 D3DXMatrixIdentity(&vm); #else D3DXVECTOR3 Eye(0.0f, 0.0f, 0.0f); D3DXVECTOR3 At(0.0f, 0.0f, -1.0f); D3DXVECTOR3 Up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtRH(&vm, &Eye, &At, &Up); vm._31 = -vm._31; vm._32 = -vm._32; vm._33 = -vm._33; vm._34 = -vm._34; #endif IDirect3DDevice8_SetTransform(gld->pDev, D3DTS_VIEW, &vm); } if (gld->bHasHWTnL) { if (glb.dwTnL == GLDS_TNL_DEFAULT) bSoftwareTnL = FALSE; // HW TnL else { bSoftwareTnL = ((glb.dwTnL == GLDS_TNL_MESA) || (glb.dwTnL == GLDS_TNL_D3DSW)) ? TRUE : FALSE; } } else { // No HW TnL, so no choice possible bSoftwareTnL = TRUE; } IDirect3DDevice8_SetRenderState(gld->pDev, D3DRS_SOFTWAREVERTEXPROCESSING, bSoftwareTnL); // Dump this in a Release build as well, now. //#ifdef _DEBUG ddlogPrintf(DDLOG_INFO, "HW TnL: %s", gld->bHasHWTnL ? (bSoftwareTnL ? "Disabled" : "Enabled") : "Unavailable"); //#endif gldEnableExtensions_DX8(lpCtx->glCtx); gldInstallPipeline_DX8(lpCtx->glCtx); gldSetupDriverPointers_DX8(lpCtx->glCtx); // Signal a complete state update lpCtx->glCtx->Driver.UpdateState(lpCtx->glCtx, _NEW_ALL); // Start a scene IDirect3DDevice8_BeginScene(gld->pDev); lpCtx->bSceneStarted = TRUE; return TRUE; }