//------------------------------------------------------------------------------------------ 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; }
void DG_Perspective(float fovY, float aspect, float zNear, float zFar) { D3DXMATRIX perMatrix; matStack[msIndex]->MultMatrixLocal(D3DXMatrixPerspectiveFovRH( &perMatrix, D3DXToRadian(fovY), aspect, zNear, zFar)); UploadMatrix(); }
//------------------------------------------------------------- // 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 Camera::updateProjection(void) { D3DXMatrixPerspectiveFovRH( &_projection, _fov * D3DX_PI / 180.0f, float( _viewPort.Width ) / float( _viewPort.Height ), _nearClipPlane, _farClipPlane ); }
// Resize And Initialize The Window void DG8Graphics::ResizeWindowDisplay(int x, int y) { D3DXMatrixPerspectiveFovRH(&m_tempmatrix, 45.0f, (float)x/(float)y, 1.0f, 5000.0f); if(m_RenderDevice != NULL){ m_RenderDevice->MultiplyTransform(D3DTS_PROJECTION,&m_tempmatrix); D3DXMatrixIdentity(&m_tempmatrix); m_RenderDevice->MultiplyTransform(D3DTS_VIEW,&m_tempmatrix); } }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- VOID C3DCamera::SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, FLOAT fFarPlane ) { // Set attributes for the projection matrix m_fFOV = fFOV; m_fAspect = fAspect; m_fNearPlane = fNearPlane; m_fFarPlane = fFarPlane; D3DXMatrixPerspectiveFovRH( &m_matProj, fFOV, fAspect, fNearPlane, fFarPlane ); }
void AmjuGLDX9::SetPerspectiveProjection( float fov, float aspectRatio, float nearDist, float farDist) { AMJU_CALL_STACK; // Use RH version for compatibility with gluPerspective() etc D3DXMatrixPerspectiveFovRH( &matProj, D3DXToRadian(fov), aspectRatio, nearDist, farDist); dd->SetTransform(D3DTS_PROJECTION, &matProj); }
//----------------------------------------------------------------------------- // Name: SetProjectionMatrix() // Desc: //----------------------------------------------------------------------------- HRESULT CMyD3DApplication::SetProjectionMatrix() { D3DXMATRIX mat; if (m_pdeHead == NULL) return S_OK; FLOAT fAspect = m_d3dsdBackBuffer.Width / (FLOAT)m_d3dsdBackBuffer.Height; D3DXMatrixPerspectiveFovRH(&mat, 0.25f*3.141592654f, fAspect, m_pdeSelected->fRadius / 64, m_pdeSelected->fRadius * 200); HRESULT hr = m_pd3dDevice->SetTransform( D3DTS_PROJECTION, (D3DMATRIX*)&mat ); if (FAILED(hr)) return hr; // Set Projection Matrix for vertex shader D3DXMatrixTranspose(&mat, &mat); return m_pd3dDevice->SetVertexShaderConstant(2, &mat, 4); }
Matrix3& Matrix3::PerspectiveRH( const Real fov, const Real aspect, const Real zn, const Real zf ) { #ifdef __USE_D3DX__ D3DXMatrixPerspectiveFovRH( (D3DXMATRIX*)this, fov, aspect, zn, zf ); #else Real h = 1.0f / TAN( fov * 0.5f ); Real w = h / aspect; Real Q = zf / ( zn - zf ); Zero(); e[0] = w; e[5] = h; e[10] = Q; e[14] = Q * zn; e[11] = -1.0; #endif return *this; }
//-------------------------------------------------------------------------------------- // 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; }
//Gets current projection matrix D3DXMATRIX* Transformations::projectionMatrix() { D3DXMatrixPerspectiveFovRH(Proj, yAngle, tan(xAngle / 2.0f) / tan(yAngle / 2.0f), clBorder, farBorder); return Proj; }
bool RendererD3D::InitializeRenderer(HWND hWnd, bool fullScreen, unsigned int sampleState) { HRESULT result; // Create the D3D object. if( NULL == ( m_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) return false; ZeroMemory( &m_d3dpp, sizeof(m_d3dpp) ); if(fullScreen){ // Set up the structure used to create the D3DDevice for fullscreen mode D3DDISPLAYMODE dispMode = {0}; // Get the current configuration of the primary monitor result = m_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dispMode); assert(result == D3D_OK); m_d3dpp.Windowed = FALSE; m_d3dpp.BackBufferWidth = SCREEN_WIDTH; m_d3dpp.BackBufferHeight = SCREEN_HEIGHT; if(sampleState==0){ m_d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; } else if(sampleState==2){ m_d3dpp.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES; } else if(sampleState==4){ m_d3dpp.MultiSampleType = D3DMULTISAMPLE_4_SAMPLES; } else { // invalid sample state was passed in, set to none m_d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; } m_d3dpp.FullScreen_RefreshRateInHz = dispMode.RefreshRate; m_d3dpp.BackBufferFormat = dispMode.Format; // Use the current color depth of the monitor m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; m_d3dpp.PresentationInterval = D3DPRESENT_DONOTWAIT; m_d3dpp.EnableAutoDepthStencil = TRUE; m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; } else { // Set up the structure used to create the D3DDevice for windowed mode m_d3dpp.Windowed = TRUE; m_d3dpp.BackBufferWidth = SCREEN_WIDTH; m_d3dpp.BackBufferHeight = SCREEN_HEIGHT; if(sampleState==0){ m_d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; } else if(sampleState==2){ m_d3dpp.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES; } else if(sampleState==4){ m_d3dpp.MultiSampleType = D3DMULTISAMPLE_4_SAMPLES; } else { // invalid sample state was passed in, set to none m_d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; } m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; m_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; m_d3dpp.PresentationInterval = D3DPRESENT_DONOTWAIT; m_d3dpp.EnableAutoDepthStencil = TRUE; m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; } // Create the D3DDevice if( FAILED( m_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &m_d3dpp, &m_pd3dDevice ) ) ) { return false; } // Set up the projection matrix. D3DXMATRIXA16 m_matrixProjection; D3DXMatrixPerspectiveFovRH( &m_matrixProjection, D3DXToRadian( m_fov ), m_d3dpp.BackBufferWidth / (float) m_d3dpp.BackBufferHeight, 1.0f, 4000.f ); m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &m_matrixProjection ); // Turn off D3D lighting result = m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); assert(result == D3D_OK); // Turn on Alpha and setup src/dest blending result = m_pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); assert(result == D3D_OK); result = m_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); assert(result == D3D_OK); result = m_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); assert(result == D3D_OK); // Turn on the z-buffer result = m_pd3dDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); assert(result == D3D_OK); //result = m_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); //assert(result == D3D_OK); // //// Set minification filter, //result = m_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); //assert(result == D3D_OK); // //// Enable mipmapping in general //result = m_pd3dDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); //assert(result == D3D_OK); //result = m_pd3dDevice->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); //assert(result == D3D_OK); // //// Set minification filter, //result = m_pd3dDevice->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); //assert(result == D3D_OK); // //// Enable mipmapping in general //result = m_pd3dDevice->SetSamplerState(1, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); //assert(result == D3D_OK); // Turn off culling so that triangles will still be drawn even when turned away from the camera result = m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); assert(result == D3D_OK); if(sampleState==2 || sampleState==4){ result = m_pd3dDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE); assert(result == D3D_OK); } // Setup font data D3DXCreateFont( m_pd3dDevice, 16, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial", &m_pD3DXFont ); m_pStack = (LPD3DXMATRIXSTACK) new LPD3DXMATRIXSTACK; D3DXCreateMatrixStack( 0, &m_pStack); result= NULL; return true; }
void Viewer::onRender() { static char s[40]; // clear the vertex and face counters m_vertexCount = 0; m_faceCount = 0; // clear all the buffers g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,77), 1.0f, 0 ); // Setup Prespective matrix g_pD3DDevice->BeginScene(); D3DXMATRIX matProj,matWorld,matView, matViewInv; D3DXMatrixPerspectiveFovRH( &matProj, D3DX_PI/4, (float)m_width / (float)m_height, m_scale * 50.0f, m_scale * 1000.0f ); g_pD3DDevice->SetTransform( D3DTS_PROJECTION, &matProj ); D3DXMATRIX Mat1,Mat2; // tmp matrix D3DXMatrixIdentity(&Mat1); D3DXMatrixTranslation(&Mat2,0.0f,0.0f,-m_distance * m_scale); D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); D3DXMatrixRotationX(&Mat2, m_tiltAngle/180.0f*3.14159f); D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); D3DXMatrixRotationZ(&Mat2, m_twistAngle/180.0f*3.14159f); D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); D3DXMatrixTranslation(&Mat2,0.0f,0.0f,-90.0f * m_scale); //I have done à 1/1 translation D3DXMatrixMultiply(&matView,&Mat2,&Mat1); //of the OpenGL version g_pD3DDevice->SetTransform( D3DTS_VIEW, &matView ); D3DXMatrixIdentity(&matWorld); g_pD3DDevice->SetTransform( D3DTS_WORLD, &matWorld ); // setup the light attributes D3DLIGHT9 light; ZeroMemory( &light, sizeof(D3DLIGHT9) ); light.Type = D3DLIGHT_DIRECTIONAL; light.Ambient.r=0.2f;light.Ambient.g=0.2f;light.Ambient.b=0.2f;light.Ambient.a=1.0f; light.Diffuse.r=1.0f;light.Diffuse.g=1.0f;light.Diffuse.b=1.0f;light.Diffuse.a=1.0f; light.Specular.r=0.1f;light.Specular.g=0.1f;light.Specular.b=0.1f;light.Specular.a=1.0f; //light.Direction= D3DXVECTOR3(0.0f,0.70f,0.70f); light.Direction= D3DXVECTOR3(sinf(Tick::getTick()/1000.0f),cosf(Tick::getTick()/1000.0f),-0.5f); float r=light.Direction.x*light.Direction.x +light.Direction.y*light.Direction.y +light.Direction.z*light.Direction.z; light.Direction.x/=r; light.Direction.y/=r; light.Direction.z/=r; g_pD3DDevice->SetLight( 0, &light ); g_pD3DDevice->LightEnable( 0, TRUE ); g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, TRUE ); if(m_bBump) { g_pD3DDevice->SetVertexShaderConstantF(13, (float*)&light.Diffuse, 1 ); g_pD3DDevice->SetVertexShaderConstantF(14, (float*)&light.Specular, 1 ); g_pD3DDevice->SetVertexShaderConstantF(15, (float*)&light.Ambient, 1 ); g_pD3DDevice->SetVertexShaderConstantF(16, (float*)&(-((D3DXVECTOR3)light.Direction)), 1 ); D3DXMatrixTranspose( &Mat1, &matWorld ); g_pD3DDevice->SetVertexShaderConstantF( 0, (float*)&Mat1, 4 ); D3DXMatrixMultiply( &Mat1, &matView, &matProj ); D3DXMatrixMultiply( &Mat1, &matWorld, &Mat1 ); D3DXMatrixTranspose( &Mat1, &Mat1 ); g_pD3DDevice->SetVertexShaderConstantF( 4, (float*)&Mat1, 4 ); float Const[4] = {0.5f,0.5f,0.5f,0.5f}; g_pD3DDevice->SetVertexShaderConstantF( 20,Const, 1 ); } // render the model renderModel(); g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); // render the cursor renderCursor(); RECT FontPosition; FontPosition.top = 0; FontPosition.left = 0; FontPosition.right = m_width; FontPosition.bottom = 100; sprintf(s,"%d fps, press 'b' to toggle bump mapping",m_fps); // // There are changes here between Direct3D SDK 9 and Direct3D SDK 9 summer 2003 update // /* Original SDK m_pFont->Begin(); m_pFont->DrawText(s,-1,&FontPosition,DT_CENTER,0xffffffff); m_pFont->End(); */ ///* Update m_pFont->DrawText(NULL,s,-1,&FontPosition,DT_CENTER,0xffffffff); //*/ g_pD3DDevice->EndScene(); // swap the front- and back-buffer g_pD3DDevice->Present( NULL, NULL, NULL, NULL ); // increase frame counter m_fpsFrames++; }
void ResizeWindowDX10(int width, int height) { GutResetGraphicsDeviceDX10(); float aspect = (float) height / (float) width; D3DXMatrixPerspectiveFovRH(&g_proj_matrix, FastMath::DegreeToRadian(90.0f), aspect, 0.1f, 100.0f); }
bool InitResourceDX10(void) { g_pDevice = GutGetGraphicsDeviceDX10(); ID3D10Blob *pVSCode = NULL; // 載入Vertex Shader g_pVertexShader = GutLoadVertexShaderDX10_HLSL("../../shaders/vertex_color_dx10.hlsl", "VS", "vs_4_0", &pVSCode); if ( NULL==g_pVertexShader ) return false; // 載入Pixel Shader g_pPixelShader = GutLoadPixelShaderDX10_HLSL("../../shaders/vertex_color_dx10.hlsl", "PS", "ps_4_0"); if ( NULL==g_pPixelShader ) return false; // 設定Vertex資料格式 D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 } }; if ( D3D_OK != g_pDevice->CreateInputLayout( layout, sizeof(layout)/sizeof(D3D10_INPUT_ELEMENT_DESC), pVSCode->GetBufferPointer(), pVSCode->GetBufferSize(), &g_pVertexLayout ) ) return false; SAFE_RELEASE(pVSCode); D3D10_BUFFER_DESC cbDesc; // sun vertex buffer cbDesc.ByteWidth = sizeof(Vertex_VC) * g_iNumSphereVertices; cbDesc.Usage = D3D10_USAGE_IMMUTABLE; cbDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; cbDesc.CPUAccessFlags = 0; cbDesc.MiscFlags = 0; // 開啟Vertex Buffer時同時把資料拷貝過去 D3D10_SUBRESOURCE_DATA sbDesc; sbDesc.pSysMem = g_pSunVertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pSunVertexBuffer ) ) return false; // 開啟Vertex Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_pEarthVertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pEarthVertexBuffer ) ) return false; // 開啟Vertex Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_pMoonVertices; // 配置一塊可以存放Vertex的記憶體, 也就是Vertex Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pMoonVertexBuffer ) ) return false; // 設定一塊可以用來放Index的記憶體. cbDesc.ByteWidth = sizeof(unsigned short) * g_iNumSphereIndices; cbDesc.Usage = D3D10_USAGE_IMMUTABLE; cbDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; cbDesc.CPUAccessFlags = 0; cbDesc.MiscFlags = 0; // 開啟Index Buffer時同時把資料拷貝過去 sbDesc.pSysMem = g_pSphereIndices; // 配置一塊可以存放Index的記憶體, 也就是Index Buffer. if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, &sbDesc, &g_pSphereIndexBuffer ) ) return false; // 配置Shader讀取參數的記憶體空間 cbDesc.ByteWidth = sizeof(Matrix4x4); cbDesc.Usage = D3D10_USAGE_DYNAMIC; cbDesc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; cbDesc.MiscFlags = 0; if ( D3D_OK != g_pDevice->CreateBuffer( &cbDesc, NULL, &g_pConstantBuffer ) ) return false; // 計算出一個可以轉換到鏡頭座標系的矩陣 D3DXMatrixPerspectiveFovRH(&g_proj_matrix, FastMath::DegreeToRadian(90.0f), 1.0f, 0.1f, 100.0f); // 開?rasterizer state物件 D3D10_RASTERIZER_DESC rasterizer_state_desc; rasterizer_state_desc.FillMode = D3D10_FILL_SOLID; rasterizer_state_desc.CullMode = D3D10_CULL_BACK; rasterizer_state_desc.FrontCounterClockwise = true; rasterizer_state_desc.DepthBias = 0; rasterizer_state_desc.DepthBiasClamp = 0.0f; rasterizer_state_desc.SlopeScaledDepthBias = 0.0f; rasterizer_state_desc.DepthClipEnable = false; rasterizer_state_desc.ScissorEnable = false; rasterizer_state_desc.MultisampleEnable = false; rasterizer_state_desc.AntialiasedLineEnable = false; if ( D3D_OK != g_pDevice->CreateRasterizerState(&rasterizer_state_desc, &g_pRasterizerState) ) return false; g_pDevice->RSSetState(g_pRasterizerState); return true; }
void Viewer::onRender() { static char s[20]; // clear the vertex and face counters m_vertexCount = 0; m_faceCount = 0; // clear all the buffers g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,77), 1.0f, 0 ); // Setup Prespective matrix g_pD3DDevice->BeginScene(); D3DXMATRIX matProj; D3DXMatrixPerspectiveFovRH( &matProj, D3DX_PI/4, (float) m_width / (float) m_height, m_scale * 50.0f, m_scale * 1000.0f ); g_pD3DDevice->SetTransform( D3DTS_PROJECTION, &matProj ); // setup the light attributes D3DLIGHT9 light; ZeroMemory( &light, sizeof(D3DLIGHT9) ); light.Type = D3DLIGHT_DIRECTIONAL; light.Ambient.r=0.3f;light.Ambient.g=0.3f;light.Ambient.b=0.3f;light.Ambient.a=1.0f; light.Diffuse.r=0.9f;light.Diffuse.g=0.9f;light.Diffuse.b=0.9f;light.Diffuse.a=1.0f; light.Specular.r=0.1f;light.Specular.g=0.1f;light.Specular.b=0.1f;light.Specular.a=1.0f; light.Direction= D3DXVECTOR3(0.0f,0.70f,0.70f); g_pD3DDevice->SetLight( 0, &light ); g_pD3DDevice->LightEnable( 0, TRUE ); g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, TRUE ); D3DXMATRIX Mat1,Mat2; D3DXMatrixIdentity(&Mat1); D3DXMatrixTranslation(&Mat2,0.0f,0.0f,-m_distance * m_scale); D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); D3DXMatrixRotationX(&Mat2, m_tiltAngle/180.0f*3.14159f); D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); D3DXMatrixRotationZ(&Mat2, m_twistAngle/180.0f*3.14159f); D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); D3DXMatrixTranslation(&Mat2,0.0f,0.0f,-90.0f * m_scale); //I have done à 1/1 translation D3DXMatrixMultiply(&Mat1,&Mat2,&Mat1); //of the OpenGL version g_pD3DDevice->SetTransform( D3DTS_VIEW, &Mat1 ); D3DXMatrixIdentity( &Mat1 ); g_pD3DDevice->SetTransform( D3DTS_WORLD, &Mat1 ); // render the model renderModel(); g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); // render the cursor renderCursor(); RECT FontPosition; FontPosition.top = 0; FontPosition.left = 0; FontPosition.right = 100; FontPosition.bottom = 100; sprintf(s,"%d",m_fps); // // There are changes here between Direct3D SDK 9 and Direct3D SDK 9 summer 2003 update // /* Original SDK m_pFont->Begin(); m_pFont->DrawText(s,-1,&FontPosition,DT_CENTER,0xffffffff); m_pFont->End(); */ ///* Update m_pFont->DrawText(NULL,s,-1,&FontPosition,DT_CENTER,0xffffffff); //*/ g_pD3DDevice->EndScene(); // swap the front- and back-buffer g_pD3DDevice->Present( NULL, NULL, NULL, NULL ); // increase frame counter m_fpsFrames++; }
//----------------------------------------------------------------------------- // Name: Render // Desc: //----------------------------------------------------------------------------- HRESULT CMyD3DApplication::Render() { HRESULT hr; if(FAILED(hr = m_pd3dDevice->BeginScene())) return hr; // Draw Environment FLOAT fAspectRatio = (FLOAT)m_d3dsdBackBuffer.Width / (FLOAT)m_d3dsdBackBuffer.Height; D3DXMatrixPerspectiveFovRH(&m_matProjection, D3DXToRadian(60.0f), fAspectRatio, 0.1f, 2000.0f); m_pd3dDevice->SetTransform(D3DTS_PROJECTION, &m_matProjection); if(m_bDrawEnvironment) { D3DXMATRIX mat(m_matView); mat._41 = mat._42 = mat._43 = 0.0f; m_pd3dDevice->SetTransform(D3DTS_VIEW, &mat); m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); m_pd3dDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS); m_Environment.Draw(); m_pd3dDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_DISABLE); } else { m_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0); } m_pd3dDevice->SetTransform(D3DTS_VIEW, &m_matView); // Draw water if(m_bDrawWater) { // Setup matrices if(m_pEffect->IsParameterUsed("mENV")) { D3DXMATRIX matP(m_matPosition); matP._41 = matP._42 = matP._43 = 0.0f; D3DXMATRIX mat; D3DXMatrixScaling(&mat, 1.0f, 1.0f, -1.0f); D3DXMatrixMultiply(&mat, &matP, &mat); // matCube m_pEffect->SetMatrix("mENV", &mat); } // Draw water UINT uPasses; m_pEffect->Begin(&uPasses, 0); for(UINT uPass = 0; uPass < uPasses; uPass++) { m_pEffect->Pass(uPass); m_Water.DrawSurface(); } m_pEffect->End(); } // Show info m_pFont->DrawText( 2, 0, D3DCOLOR_ARGB(255,255,255,0), m_strFrameStats ); m_pFont->DrawText( 2, 20, D3DCOLOR_ARGB(255,255,255,0), m_strDeviceStats ); TCHAR szText[100]; wsprintf( szText, _T("Using Technique %d"), m_iTechnique ); m_pFontSmall->DrawText( 2, 40, D3DCOLOR_ARGB(255,255,100,100), szText ); if( m_bShowHelp ) { m_pFontSmall->DrawText( 2, 60, D3DCOLOR_ARGB(255,100,100,200), _T("Keyboard controls:") ); m_pFontSmall->DrawText( 20, 80, D3DCOLOR_ARGB(255,100,100,200), _T("Add Drop\n") _T("Next Technique\n") _T("Next Tech. (no validate)\n") _T("Prev Technique\n") _T("Prev Tech. (no validate)\n") _T("Move\nTurn\nPitch\nSlide\n") _T("Help\nChange device\nExit") ); m_pFontSmall->DrawText( 210, 80, D3DCOLOR_ARGB(255,100,100,200), _T("D\n") _T("PageDn\nShift-PageDn\n") _T("PageUp\nShift-PageUp\n") _T("W,S\nE,Q\nA,Z\nArrow keys\n") _T("F1\nF2\nEsc") ); } else { m_pFontSmall->DrawText( 2, 60, D3DCOLOR_ARGB(255,100,100,200), _T("Press F1 for help") ); } if(FAILED(hr = m_pd3dDevice->EndScene())) return hr; return S_OK; }
// 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; }
Matrix Matrix::CreatePerspectiveFieldOfView(float fovy, float aspect, float zn, float zf) { D3DXMATRIX mat; D3DXMatrixPerspectiveFovRH(&mat,fovy,aspect,zn,zf); return Matrix( (float*)&mat._11); }
HRESULT DXRender::onResize(unsigned int width, unsigned int height) { if (!isDeviceReady()) return D3DERR_DEVICELOST; LOG(QString_NT("Start resize")); HRESULT hr = S_OK; _presentationParameters.BackBufferWidth = width; _presentationParameters.BackBufferHeight = height; D3DXMatrixPerspectiveFovRH(&proj, CAMERA_FOVY * (PI/180), float(_presentationParameters.BackBufferWidth) / float(_presentationParameters.BackBufferHeight), GLOBAL(nearClippingPlane), GLOBAL(farClippingPlane)); device->SetTransform(D3DTS_PROJECTION, &proj); // update the camera once (important especially on first load where other // code like window2world depend on having a proper view matrix set up); updateCamera(cam->getEye(), cam->getDir(), cam->getUp()); // Set the device to use the device's default buffers. This releases // DirectX's reference to our swap chain device->SetRenderTarget(0, _devBackBuffer); device->SetDepthStencilSurface(_devDepthBuffer); // Release the swap chain SAFE_RELEASE(_swapBackBuffer); SAFE_RELEASE(_swapDepthBuffer); SAFE_RELEASE(_swapChain); // Create the newly sized swap chain hr = device->CreateAdditionalSwapChain(&_presentationParameters, &_swapChain); if (FAILED(hr) || !_swapChain) { LOG(QString_NT("Failed to create additional swap chain: hr = %1").arg(hr)); return hr; } _swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &_swapBackBuffer); // Create the additional depth buffer hr = device->CreateDepthStencilSurface(_presentationParameters.BackBufferWidth, _presentationParameters.BackBufferHeight, D3DFMT_D16, _presentationParameters.MultiSampleType, _presentationParameters.MultiSampleQuality, true, &_swapDepthBuffer, NULL); if (FAILED(hr) || !_swapDepthBuffer) { LOG(QString_NT("Failed to create additional depth buffer: hr = %1").arg(hr)); return hr; } device->SetRenderTarget(0, _swapBackBuffer); device->SetDepthStencilSurface(_swapDepthBuffer); // Update the cached viewport device->GetViewport(&viewport); // Move the origin to the bottom left D3DXMatrixTranslation(&orthoView, -float(viewport.Width) / 2 - 0.5f, -float(viewport.Height) / 2 + 0.5f, 0); // Set up the orthographic projection matrix D3DXMatrixOrthoLH(&orthoProj, viewport.Width, viewport.Height, 0, 1); rndrManager->invalidateRenderer(); LOG(QString_NT("Finish resize")); return hr; }
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