void CCloth::Render(LPDIRECT3DDEVICE9 pd3dDevice, D3DXMATRIX* pWorldM ) { if( m_pTexture ) pd3dDevice->SetTexture(0, m_pTexture ); else pd3dDevice->SetTexture(0, NULL ); pd3dDevice->SetFVF( CUSTOM_VERTEX::FVF ); int square = m_nGridSize; D3DXMATRIX matWorld; D3DXMatrixIdentity( &matWorld ); pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ); for(int i=0; i<m_nGridSize-1; ++i) { for(int j=0; j<m_nGridSize-1; ++j) { CUSTOM_VERTEX v3Pos[6]; v3Pos[0].m_v3Pos = (m_pCurrentBalls[i*m_nGridSize+j].m_v3Pos); v3Pos[1].m_v3Pos = (m_pCurrentBalls[i*m_nGridSize+j+1].m_v3Pos); v3Pos[2].m_v3Pos = (m_pCurrentBalls[(i+1)*m_nGridSize+j].m_v3Pos); v3Pos[3].m_v3Pos = (m_pCurrentBalls[(i+1)*m_nGridSize+j].m_v3Pos); v3Pos[4].m_v3Pos = ( m_pCurrentBalls[i*m_nGridSize+j+1].m_v3Pos ); v3Pos[5].m_v3Pos = ( m_pCurrentBalls[(i+1)*m_nGridSize+j+1].m_v3Pos ); v3Pos[0].m_v3Nor = (m_pCurrentBalls[i*m_nGridSize+j].m_v3Normal); v3Pos[1].m_v3Nor = (m_pCurrentBalls[i*m_nGridSize+j+1].m_v3Normal); v3Pos[2].m_v3Nor = (m_pCurrentBalls[(i+1)*m_nGridSize+j].m_v3Normal); v3Pos[3].m_v3Nor = (m_pCurrentBalls[(i+1)*m_nGridSize+j].m_v3Normal); v3Pos[4].m_v3Nor = ( m_pCurrentBalls[i*m_nGridSize+j+1].m_v3Normal ); v3Pos[5].m_v3Nor = ( m_pCurrentBalls[(i+1)*m_nGridSize+j+1].m_v3Normal ); /* D3DXVec3TransformCoord( &v3Pos[0].m_v3Pos, &v3Pos[0].m_v3Pos, pWorldM ); D3DXVec3TransformCoord( &v3Pos[1].m_v3Pos, &v3Pos[1].m_v3Pos, pWorldM ); D3DXVec3TransformCoord( &v3Pos[2].m_v3Pos, &v3Pos[2].m_v3Pos, pWorldM ); D3DXVec3TransformCoord( &v3Pos[3].m_v3Pos, &v3Pos[3].m_v3Pos, pWorldM ); D3DXVec3TransformCoord( &v3Pos[4].m_v3Pos, &v3Pos[4].m_v3Pos, pWorldM ); D3DXVec3TransformCoord( &v3Pos[5].m_v3Pos, &v3Pos[5].m_v3Pos, pWorldM ); D3DXVec3TransformCoord( &v3Pos[0].m_v3Nor, &v3Pos[0].m_v3Nor, pWorldM ); D3DXVec3TransformCoord( &v3Pos[1].m_v3Nor, &v3Pos[1].m_v3Nor, pWorldM ); D3DXVec3TransformCoord( &v3Pos[2].m_v3Nor, &v3Pos[2].m_v3Nor, pWorldM ); D3DXVec3TransformCoord( &v3Pos[3].m_v3Nor, &v3Pos[3].m_v3Nor, pWorldM ); D3DXVec3TransformCoord( &v3Pos[4].m_v3Nor, &v3Pos[4].m_v3Nor, pWorldM ); D3DXVec3TransformCoord( &v3Pos[5].m_v3Nor, &v3Pos[5].m_v3Nor, pWorldM ); /**/ v3Pos[0].m_dwColor = D3DCOLOR_XRGB( 0, 255, 255 ); v3Pos[1].m_dwColor = D3DCOLOR_XRGB( 0, 255, 255 ); v3Pos[2].m_dwColor = D3DCOLOR_XRGB( 0, 255, 255 ); v3Pos[3].m_dwColor = D3DCOLOR_XRGB( 0, 255, 255 ); v3Pos[4].m_dwColor = D3DCOLOR_XRGB( 0, 255, 255 ); v3Pos[5].m_dwColor = D3DCOLOR_XRGB( 0, 255, 255 ); v3Pos[0].m_v2uv = D3DXVECTOR2( float(j)/(square-1), float(i)/(square-1) ); v3Pos[1].m_v2uv = D3DXVECTOR2( float(j+1)/(square-1),float(i)/(square-1) ); v3Pos[2].m_v2uv = D3DXVECTOR2( float(j)/(square-1), float(i+1)/(square-1) ); v3Pos[3].m_v2uv = D3DXVECTOR2( float(j)/(square-1), float(i+1)/(square-1) ); v3Pos[4].m_v2uv = D3DXVECTOR2( float(j+1)/(square-1), float(i)/(square-1) ); v3Pos[5].m_v2uv = D3DXVECTOR2( float(j+1)/(square-1), float(i+1)/(square-1) ); pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 2, v3Pos, sizeof(CUSTOM_VERTEX) ); } } for(i=0; i<m_nNumSprings; ++i) { //Check the spring has been initialised and the ball numbers are in bounds if( m_pSprings[i].m_nBall1!=-1 && m_pSprings[i].m_nBall2!=-1 && m_pSprings[i].m_nBall1<m_nNumSprings && m_pSprings[i].m_nBall2<m_nNumSprings) { CUSTOM_VERTEX v3Pos[2]; v3Pos[0].m_v3Pos = (m_pCurrentBalls[m_pSprings[i].m_nBall1].m_v3Pos); v3Pos[1].m_v3Pos = (m_pCurrentBalls[m_pSprings[i].m_nBall2].m_v3Pos); pd3dDevice->DrawPrimitiveUP( D3DPT_LINELIST, 1, v3Pos, sizeof(CUSTOM_VERTEX) ); } } }
void Engine::Graphics::render(Drawable object, Camera *cam) { D3DXMATRIX transMat, scaleMat, rotMat, worldMat; D3DXMatrixIdentity(&transMat); D3DXMatrixIdentity(&scaleMat); D3DXMatrixIdentity(&rotMat); D3DXMatrixIdentity(&worldMat); if(!object.get3D()) { D3DXMatrixScaling(&scaleMat, object.getScale().x, object.getScale().y, object.getScale().z); D3DXMatrixTranslation(&transMat, object.getTranslate().x, object.getTranslate().y, object.getTranslate().z); D3DXMatrixRotationYawPitchRoll(&rotMat, D3DXToRadian(object.getRotate().y),D3DXToRadian(object.getRotate().x), D3DXToRadian(object.getRotate().z)); D3DXMatrixMultiply(&scaleMat, &scaleMat, &rotMat); D3DXMatrixMultiply(&worldMat, &scaleMat, &transMat); Engine::DX::instance()->getSprite()->SetTransform(&worldMat); Engine::DX::instance()->getSprite()->Draw( getTexture(object.getHandle()), object.getIsSpriteSheet() ? &object.getRect() : 0, object.getIsSpriteSheet() ? &dVec3(object.getWidth() * 0.5f, object.getHeight() * 0.5f, 0.0f) : &dVec3(getInfo(object.getHandle()).Width *0.5f, getInfo(object.getHandle()).Height *0.5f, 0.0f), 0, object.getColor()); } if(object.get3D()) { //camera.setLookAt(object.getTranslate().x, object.getTranslate().y, object.getTranslate().z); //camera.setProj(800,600); D3DXMATRIX WIT; UINT numPasses = 0; m_Effect->Begin(&numPasses, 0); Mesh *tempMesh = getMesh(object.getHandle()); for(UINT i = 0; i < numPasses; i++) { m_Effect->BeginPass(i); D3DXMatrixScaling(&scaleMat, object.getScale().x, object.getScale().y, object.getScale().z); D3DXMatrixTranslation(&transMat, object.getTranslate().x, object.getTranslate().y, object.getTranslate().z); D3DXMatrixRotationYawPitchRoll(&rotMat, D3DXToRadian(object.getRotate().y),D3DXToRadian(object.getRotate().x), D3DXToRadian(object.getRotate().z)); D3DXMatrixMultiply(&scaleMat, &scaleMat, &rotMat); D3DXMatrixMultiply(&worldMat, &scaleMat, &transMat); D3DXMatrixInverse(&WIT, 0, &worldMat); D3DXMatrixTranspose(&WIT, &WIT); m_Effect->SetMatrix("worldViewProjMat", &(worldMat * cam->getView() * cam->getProjection())); m_Effect->SetMatrix("worldInverseTransposeMat", &WIT); m_Effect->SetMatrix("worldMat", &worldMat); for(DWORD i = 0; i < tempMesh->getNumMaterials(); i++) { m_Effect->SetValue("ambientMaterial", &tempMesh->getMeshMaterial()[i].Ambient, sizeof(D3DXCOLOR)); m_Effect->SetValue("diffuseMaterial", &tempMesh->getMeshMaterial()[i].Diffuse, sizeof(D3DXCOLOR)); m_Effect->SetValue("specularMaterial", &tempMesh->getMeshMaterial()[i].Specular, sizeof(D3DXCOLOR)); m_Effect->SetFloat("specularPower", tempMesh->getMeshMaterial()[i].Power); if(object.getHasTexture()) { m_Effect->SetTexture("tex", tempMesh->getMeshTexture()[i]); m_Effect->SetBool("isTex", true); }else m_Effect->SetBool("isTex", false); m_Effect->CommitChanges(); tempMesh->getMesh()->DrawSubset(i); } m_Effect->EndPass(); //tempMesh = nullptr; } m_Effect->End(); } }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- LRESULT CD3DArcBall::HandleMouseMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { UNREFERENCED_PARAMETER( hWnd ); static int iCurMouseX; // Saved mouse position static int iCurMouseY; static D3DXVECTOR3 s_vDown; // Button down vector // Current mouse position int iMouseX = GET_X_LPARAM(lParam); int iMouseY = GET_Y_LPARAM(lParam); switch( uMsg ) { case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: // Store off the position of the cursor when the button is pressed iCurMouseX = iMouseX; iCurMouseY = iMouseY; return TRUE; case WM_LBUTTONDOWN: // Start drag mode m_bDrag = TRUE; s_vDown = ScreenToVector( iMouseX, iMouseY ); m_qDown = m_qNow; return TRUE; case WM_LBUTTONUP: // End drag mode m_bDrag = FALSE; return TRUE; case WM_MOUSEMOVE: // Drag object if( MK_LBUTTON&wParam ) { if( m_bDrag ) { // recompute m_qNow D3DXVECTOR3 vCur = ScreenToVector( iMouseX, iMouseY ); D3DXQUATERNION qAxisToAxis; D3DXQuaternionAxisToAxis(&qAxisToAxis, &s_vDown, &vCur); m_qNow = m_qDown; m_qNow *= qAxisToAxis; D3DXMatrixRotationQuaternion(&m_matRotationDelta, &qAxisToAxis); } else D3DXMatrixIdentity(&m_matRotationDelta); D3DXMatrixRotationQuaternion(&m_matRotation, &m_qNow); m_bDrag = TRUE; } else if( (MK_RBUTTON&wParam) || (MK_MBUTTON&wParam) ) { // Normalize based on size of window and bounding sphere radius FLOAT fDeltaX = ( iCurMouseX-iMouseX ) * m_fRadiusTranslation / m_iWidth; FLOAT fDeltaY = ( iCurMouseY-iMouseY ) * m_fRadiusTranslation / m_iHeight; if( wParam & MK_RBUTTON ) { D3DXMatrixTranslation( &m_matTranslationDelta, -2*fDeltaX, 2*fDeltaY, 0.0f ); D3DXMatrixMultiply( &m_matTranslation, &m_matTranslation, &m_matTranslationDelta ); } else // wParam & MK_MBUTTON { D3DXMatrixTranslation( &m_matTranslationDelta, 0.0f, 0.0f, 5*fDeltaY ); D3DXMatrixMultiply( &m_matTranslation, &m_matTranslation, &m_matTranslationDelta ); } // Store mouse coordinate iCurMouseX = iMouseX; iCurMouseY = iMouseY; } return TRUE; } return FALSE; }
void EditorLinePrimitive::RecalcTransforms() { //Matrices we need D3DXMATRIX matWorld,matScale,MatRot,MatTemp; //Temporary translation D3DXVECTOR3 Trans; //Copy from the original location, //so we can modify it without hurting anything Trans=Location; //Devide Trans through Scale /*Trans.x/=Scale.x; Trans.y/=Scale.y; Trans.z/=Scale.z;*/ //Apply translation to the WorldMatrix D3DXMatrixTranslation(&matWorld,Trans.x,Trans.y,Trans.z); //Now scale another matrix D3DXMatrixScaling( &matScale, Scale.x, Scale.y, Scale.z ); //Apply rotation D3DXMatrixIdentity(&MatRot); D3DXVECTOR3 DeltaRot = Rotation - RotationMatrixAngles; if(Rotation != D3DXVECTOR3(0,0,0)) { // Calculate matrix with the new angles if(bLocalRotation) { D3DXVECTOR3 Up(0,1,0); D3DXVECTOR3 Front(1,0,0); D3DXVECTOR3 Right; D3DXVec3TransformNormal(&Up, &Up, &RotationMatrix); D3DXVec3TransformNormal(&Front, &Front, &RotationMatrix); D3DXVec3Cross(&Right, &Up, &Front); D3DXMATRIX X; D3DXMatrixRotationAxis(&X, &Front, DeltaRot.x); D3DXMATRIX Y; D3DXMatrixRotationAxis(&Y, &Up, DeltaRot.y); D3DXMATRIX Z; D3DXMatrixRotationAxis(&Z, &Right, DeltaRot.z); RotationMatrix *= X * Y * Z; }else { D3DXMatrixIdentity(&MatRot); D3DXMatrixRotationAxis(&MatTemp, &D3DXVECTOR3(1,0,0), Rotation.x); // Pitch D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp); D3DXMatrixRotationAxis(&MatTemp, &D3DXVECTOR3(0,1,0), Rotation.y); // Yaw D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp); D3DXMatrixRotationAxis(&MatTemp, &D3DXVECTOR3(0,0,1), Rotation.z); // Roll D3DXMatrixMultiply(&RotationMatrix, &MatRot, &MatTemp); //RotationMatrix = X * Y * Z; } RotationMatrixAngles = Rotation; }else if(!bJustUseRotationMatrix) { // Reset matrix to identity (Todo: ROTATION! Ò.ó Y U NO WORK!? (As I want)) D3DXMatrixIdentity(&RotationMatrix); RotationMatrixAngles = D3DXVECTOR3(0,0,0); } WorldMatrix = matScale * RotationMatrix * matWorld; }
Vector3f Camera::screenToWorld(const Vector2f& pos) { mat4 ma1 = m_View * m_Proj; mat4 inv1 = matrix::mat4Inverse(ma1); Vector4f in; in.x = (pos.x - 1024.0f) / 1024.0f; in.y = (768.0f - pos.y) / 768.0f; in.z = 1.0f; in.w = 1.0; // Map to range -1 to 1 in.x = in.x * 2.0 - 1.0; in.y = in.y * 2.0 - 1.0; in.z = in.z * 2.0 - 1.0; Vector4f o4 = inv1 * in; o4 *= 1.0f / o4.w; /* //Vector4f ndc(2 * pos.x / 1024 - 1,2 * (768 - pos.y) / 768 - 1,1, 1); Vector3f ndc(2 * pos.x / 1024 - 1, 2 * (768 - pos.y) / 768 - 1, 1); Vector3f tmp = m * ndc; //tmp *= 1.0f / tmp.w; return Vector3f(tmp.x, tmp.y, tmp.z); */ /* Vector3f v; v.x = (((2.0f * pos.x) / 1024) - 1) / m_Proj._11; v.y = (-2.0f * pos.y / 768 + 1) / m_Proj._22; v.z = 1.0f; //LOG << "v: " << DBG_V3(v); mat4 matInvView = matrix::mat4Inverse(m_View); //Vector4f ndc((2 * (pos.x - 1024)) / 1024 - 1,(2 * (768 - pos.y)) / 768 - 1, 0, 1); Vector3f rayDir = matInvView * v; Vector3f rayOrigin; rayOrigin.x = matInvView._41; rayOrigin.y = matInvView._42; rayOrigin.z = matInvView._43; //LOG << "v: " << DBG_V3(v); return rayDir; */ D3DXMATRIX tm; D3DXMatrixPerspectiveFovLH(&tm, 0.25f*PI, 1024.0f / 768.0f, 0.1f, 1000.0f); mat4 m = m_View;// *m_Proj; mat4 inv = matrix::mat4Inverse(m_Proj); D3DXMATRIX itm; D3DXMatrixInverse(&itm,NULL,&tm); D3DXMATRIX viewMatrix; D3DXMatrixLookAtLH(&viewMatrix, &D3DXVECTOR3(0.0f, 0.0f, -16.0f), //position &D3DXVECTOR3(0.0f, 0.0f, 0.0f), //Look at &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); D3DXMATRIX worldMatrix; D3DXMatrixIdentity(&worldMatrix); D3DXMATRIX m1, m2, m3; D3DXVECTOR3 vvec,outv; D3DXMatrixMultiply(&m1, &worldMatrix, &viewMatrix); D3DXMatrixMultiply(&m2, &m1, &tm); D3DXMatrixInverse(&m3, NULL, &m2); vvec.x = 2.0f * (pos.x - 1024.0f) / 1024.0f - 1.0f; vvec.y = 1.0f - 2.0f * (pos.y - 768.0f) / 768.0f; vvec.z = 1.0f;// (pv->z - pviewport->MinZ) / (pviewport->MaxZ - pviewport->MinZ); D3DXVec3TransformCoord(&outv, &vvec, &m3); //LOG << "screen pos: " << DBG_V2(pos); Vector3f vec; vec.x = (((2.0f * pos.x) / 1024.0f) - 1.0f);// / m_Proj._11; vec.y = -(((2.0f * pos.y) / 768.0f) - 1.0f);// / m_Proj._22; //vec.x = (2.0f * pos.x - 1024.0f) / 1024.0f - 1.0f; //vec.y = 1.0f - (2.0f * pos.y - 768.0f) / 768.0f; vec.z = 1.0f;// (pos.z - 0.1) / (1000 - pviewport->MinZ); Vector3f pout = vec * inv; //D3DXVec3TransformCoord(pout, &vec, &inv); return vec; }
bool MyMesh::Init(IDirect3DDevice9 *d, char *fn) { Device = d; HRESULT hr; ID3DXBuffer* adjBuffer = 0; ID3DXBuffer* mtrlBuffer = 0; D3DXCreateTextureFromFile(Device, "whitetex.dds", &whiteTex); D3DXMATERIAL* mtrls = 0; D3DXLoadMeshFromX(fn, D3DXMESH_MANAGED, Device, &adjBuffer, &mtrlBuffer, 0, &numMtrls, &mesh); // Louis Natanson Lab. Code if (!mesh) { MessageBox(0, "Mesh Load Failed", fn, MB_OK); return false; } if ( (mtrlBuffer != 0) && (numMtrls != 0 ) ) { mtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer(); for (DWORD i = 0; i < numMtrls; i++) { Mtrl m; m.ambient = mtrls[i].MatD3D.Diffuse; m.diffuse = mtrls[i].MatD3D.Diffuse; m.spec = mtrls[i].MatD3D.Specular; m.specPower = mtrls[i].MatD3D.Power; // mtrls[i].MatD3D.Ambient = mtrls[i].MatD3D.Diffuse; // Mtrls.push_back( mtrls[i].MatD3D ); Mtrls.push_back(m); if(mtrls[i].pTextureFilename != 0) { IDirect3DTexture9* tex = 0; hr = D3DXCreateTextureFromFile(Device, mtrls[i].pTextureFilename, &tex); if (hr == S_OK) Textures.push_back(tex); } else Textures.push_back(0); } } mtrlBuffer->Release(); D3DXMatrixIdentity(&worldTransform); D3DXMatrixIdentity(&translationMatrix); D3DXMatrixIdentity(&rotationMatrix); D3DXMatrixIdentity(&scalingMatrix); // calculate the bounding box BYTE* pVertices = NULL; hr = mesh->LockVertexBuffer(D3DLOCK_READONLY, (LPVOID*)&pVertices); if (!FAILED(hr)) { D3DXComputeBoundingBox( (D3DXVECTOR3*)pVertices, mesh->GetNumVertices(), D3DXGetFVFVertexSize(mesh->GetFVF()), &minBounds, &maxBounds); // calculate object bounds for Oriented Bounding Box objectBounds[0] = D3DXVECTOR3( minBounds.x, minBounds.y, minBounds.z ); objectBounds[1] = D3DXVECTOR3( maxBounds.x, minBounds.y, minBounds.z ); objectBounds[2] = D3DXVECTOR3( minBounds.x, maxBounds.y, minBounds.z ); objectBounds[3] = D3DXVECTOR3( maxBounds.x, maxBounds.y, minBounds.z ); objectBounds[4] = D3DXVECTOR3( minBounds.x, minBounds.y, maxBounds.z ); objectBounds[5] = D3DXVECTOR3( maxBounds.x, minBounds.y, maxBounds.z ); objectBounds[6] = D3DXVECTOR3( minBounds.x, maxBounds.y, maxBounds.z ); objectBounds[7] = D3DXVECTOR3( maxBounds.x, maxBounds.y, maxBounds.z ); } mesh->UnlockVertexBuffer(); return true; }
void ColoredCubeApp::drawScene() { D3DApp::drawScene(); // Restore default states, input layout and primitive topology // because mFont->DrawText changes them. Note that we can // restore the default states by passing null. md3dDevice->OMSetDepthStencilState(0, 0); float blendFactors[] = {0.0f, 0.0f, 0.0f, 0.0f}; md3dDevice->OMSetBlendState(0, blendFactors, 0xffffffff); md3dDevice->IASetInputLayout(mVertexLayout); mfxEyePosVar->SetRawValue(&player.getPosition(), 0, sizeof(D3DXVECTOR3)); //set the number of lights to use mfxNumLights->SetInt(numLights); // set the light array lights[0] = flashLightObject.lightSource; //lights[2] = lightObject1.getLight(); if(gamestate == level2) { for(int i = 0; i < ghosts.getNumEnemies(); i++) { lights[2+i] = ghosts.getEnemies()[i].getLight(); } } for(int i = 0; i < numLightObjects; i++) { lights[2+ghosts.getNumEnemies()+i] = lamps[i].getLight(); } lights[numLights-1] = endLight; mfxLightVar->SetRawValue(&lights[0], 0, numLights*sizeof(Light)); // Don't transform texture coordinates, so just use identity transformation. D3DXMATRIX texMtx; D3DXMatrixIdentity(&texMtx); mfxTexMtxVar->SetMatrix((float*)&texMtx); // set the point to the shader technique D3D10_TECHNIQUE_DESC techDesc; mTech->GetDesc(&techDesc); //draw the maze maze.draw(mTech,mView,mProj); //draw the keys if(gamestate == level1) { for(int i = 0; i < totalKeys; i++) { keyObject[i].draw(mView,mProj,mTech); } } //draw the end cube endCube.draw(mView,mProj,mTech); //draw the origin origin.draw(mView, mProj, mTech); for(int i = 0; i < numLightObjects; i++) { lamps[i].draw(mView,mProj,mTech); } for(int i = 0; i < numBatteries; i++) { batteries[i].draw(mView,mProj,mTechColor2); } //flashLightObject.draw(mView,mProj,mTechColor2); //flashLightObject.hitBox.draw(mView,mProj,mTechColor2); //batteryObject.draw(mView,mProj,mTechColor2); //player.draw(mView,mProj,mTechColor2); ghosts.draw(mView,mProj,mTech); /*floor.draw(mView, mProj, mTech); wall1.draw(mView, mProj, mTech); wall2.draw(mView, mProj, mTech); wall3.draw(mView, mProj, mTech); wall4.draw(mView, mProj, mTech);*/ //lightObject1.draw(mView,mProj,mTech); // We specify DT_NOCLIP, so we do not care about width/height of the rect. RECT R = {5, 5, 0, 0}; mFont->DrawText(0, mTimer.c_str(), -1, &R, DT_NOCLIP, BLUE); mSwapChain->Present(0, 0); }
bool D3DClass::Initialize( int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear ) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, i, numerator, denominator, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; ID3D11Texture2D* backBufferPtr; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; float fieldOfView, screenAspect; D3D11_BLEND_DESC blendStateDescription; m_vsync_enabled = vsync; //Store the vsync setting result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); //creating a directx graphics interface factory, sends in the GUID of "IDXGIFactory" and a reference to our factory which is a pointer to an IDXGIFactory, but type casted as a pointer to a void pointer if(FAILED(result)) { return false; } result = factory->EnumAdapters(0, &adapter); //put an adapter for our video card into "adapter" if(FAILED(result)) { return false; } result = adapter->EnumOutputs(0, &adapterOutput); //enumerate the primary adapter output (monitor). if(FAILED(result)) { return false; } result = adapterOutput->GetDisplayModeList( //get the number of modes that fit this display format for the monitor DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL ); if(FAILED(result)) { return false; } displayModeList = new DXGI_MODE_DESC[numModes]; //create an array of DXGI_MODE_DESC with the length of the number of compatible modes available if(!displayModeList) { return false; } result = adapterOutput->GetDisplayModeList( //now actually fill that displayModeList with all those display modes DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList ); if(FAILED(result)) { return false; } //now go through all the display modes and find the one that matches the screen width and height. //when a match is found store the numerator and denominator of the refresh rate for that monitor. for(i = 0; i < numModes; i++) { if(displayModeList[i].Width == (unsigned int)screenWidth) { if(displayModeList[i].Height == (unsigned int)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } result = adapter->GetDesc(&adapterDesc); //get the video card description if(FAILED(result)) { return false; } m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //get the amount of video memory in bytes, devide by 1024 twice to get in megabytes error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); //convert the name of the video card to a character array and store it if(error != 0) { return false; } //we will now release the structures and interfaces used to get the numerator and denominator for the refresh rate and video card information delete[] displayModeList; displayModeList = 0; adapterOutput->Release(); adapterOutput = 0; adapter->Release(); adapter = 0; factory->Release(); factory = 0; //now we will start the directx initialization, starting with the swap chain ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); //initialize swap chain description swapChainDesc.BufferCount = 1; //set the backbuffer count to 1 //set the size of the backbuffer to match the size of the client window swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //set the format of the back buffer to 32bit //backbuffer refresh rate getting set if(m_vsync_enabled) //if vsync is on, set the refresh rate to the system refresh rate { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator= denominator; } else //otherwise, set it to infinite { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator= 1; } swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //set the usage of the back buffer swapChainDesc.OutputWindow = hwnd; //give it our window handle that it shuold render to //turn MSAA off, multisampling anti-aliasing swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; //set fullscreen on or off if(fullscreen) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } //set scan line ordering and scaling to unspecified swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //discard the back buffer contents after presenting swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //don't set the avanced flags swapChainDesc.Flags = 0; featureLevel = D3D_FEATURE_LEVEL_11_0; //set feature level to dx11 result = D3D11CreateDeviceAndSwapChain( //create the swap chain, direct3d devide and direct3d device context NULL, D3D_DRIVER_TYPE_HARDWARE, //D3D_DRIVER_TYPE_REFERENCE, //uncomment this line and comment the above line to use software rendering NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext ); if(FAILED(result)) { return false; } result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); //get the pointer to the back buffer if(FAILED(result)) { return false; } result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); //create the render target view with the back buffer pointer if(FAILED(result)) { return false; } //release the pointer to the back buffer backBufferPtr->Release(); backBufferPtr = 0; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); //initialize the description of the depth buffer //set up the description of the depth buffer depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; result = m_device->CreateTexture2D( //create the texture for the depth buffer using the filled out description &depthBufferDesc, NULL, &m_depthStencilBuffer ); if(FAILED(result)) { return false; } ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); //initialize the description of the stencil state //set up the description of the stencil state depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; //compare what's there and take the lowest value? depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; //stencil operations if pixel is front-facing depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; //stencil operations if pixes is back-facing depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); //create the depth stencil state if(FAILED(result)) { return false; } m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); //we set the depth stencil state ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); //initialize the depth stencil view //set up the depth stencil view description depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; result = m_device->CreateDepthStencilView( //create the depsth stencil view m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView ); if(FAILED(result)) { return false; } m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); //bind the render target view and depth stencil buffer to the output render pipeline //create a raster state to control how the polygons are rendered rasterDesc.AntialiasedLineEnable = false; //rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.CullMode = D3D11_CULL_NONE; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);//create the rasterizer state from the description we just filled out if(FAILED(result)) { return false; } m_deviceContext->RSSetState(m_rasterState);//set the rasterizer state //setup the viewport for rendering m_viewport.Width = (float)screenWidth; m_viewport.Height = (float)screenHeight; m_viewport.MinDepth = 0.0f; m_viewport.MaxDepth = 1.0f; m_viewport.TopLeftX = 0.0f; m_viewport.TopLeftY = 0.0f; m_deviceContext->RSSetViewports(1, &viewport);//create the viewport //setup projection matrix fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; //create the projection matrix D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); D3DXMatrixIdentity(&m_worldMatrix);//initialize the world matrix to the identity matrix D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth);//create a orthographic projection matrix for 2D rendering ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC)); blendStateDescription.RenderTarget[0].BlendEnable = TRUE; blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f; //create the blend state using the description result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState); if(FAILED(result)) { return false; } //modify the description to create an alpha disabled blend state description blendStateDescription.RenderTarget[0].BlendEnable = FALSE; //create the blend state using the description result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState); if(FAILED(result)) { return false; } return true; }
// render text from texture void zz_font_texture_d3d::render_text_impl (const zz_font& font, const zz_font_text& text) { const RECT& rect = text.rect; float u, v; float width, height; u = float(text.tex_rect.left) / this->tex_width; v = float(text.tex_rect.top + line_height) / tex_height; // should be aligned by tex_rect.top width = float(text.rect.right - text.rect.left) / tex_width; height = float(line_height)/ tex_height; assert(line_height <= (text.tex_rect.bottom - text.tex_rect.top)); float top = (float)rect.top; float bottom = (float)top + line_height; HRESULT hr; zz_renderer_d3d * r = static_cast<zz_renderer_d3d*>(znzin->renderer); assert(r); //assert(SUCCEEDED(hr)); D3DXMATRIX saved_view, saved_proj, saved_world; D3DVIEWPORT9 saved_viewport; D3DXMATRIX sprite_tm; // sprite transform // we assume that init_sprite_state() has already been called. if (text.use_sprite) { // save states assert(r->is_a(ZZ_RUNTIME_TYPE(zz_renderer_d3d))); LPD3DXSPRITE sprite = r->get_sprite(); assert(sprite); _device->GetTransform(D3DTS_VIEW, &saved_view); _device->GetTransform(D3DTS_PROJECTION, &saved_proj); _device->GetTransform(D3DTS_WORLD, &saved_world); _device->GetViewport(&saved_viewport); r->get_sprite_transform((float*)&sprite_tm); // save transform r->flush_sprite(); // flushing out previous sprite rendering to avoid rendering disorder } else { // not using sprite D3DXMatrixIdentity(&sprite_tm); // get identity matrix for sprite_tm } r->set_cullmode(zz_render_state::ZZ_CULLMODE_CW); r->invalidate_texture( 0 ); // invalidate 0-th texture to call SetTexture directly. hr = _device->SetTexture( 0, _texture ); assert(SUCCEEDED(hr)); if (text.use_sprite) { FONT_TEXT_VERTEX3_TEXTURE vertices3 [4] = { D3DXVECTOR3((float)rect.left, (float)bottom, .0f), text.color, u, v, D3DXVECTOR3((float)rect.right, (float)bottom, .0f), text.color, u + width, v, D3DXVECTOR3((float)rect.right, (float)top, .0f), text.color, u + width, v - height, D3DXVECTOR3((float)rect.left, (float)top, .0f), text.color, u, v - height, }; const int hm = -1, hp = 1; const int vm = -1, vp = 1; const float adjm = .5f, adjp = -.5f; FONT_TEXT_VERTEX3_TEXTURE vertices3_outline_simple [22] = { D3DXVECTOR3((float)(rect.left+hm)+adjm, (float)(top+vm)+adjm, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hm)+adjm, (float)(bottom+vm)+adjm, .0f ), text.color_outline, u, v, D3DXVECTOR3((float)(rect.right+hm)+adjm, (float)(top+vm)+adjm , .0f ), text.color_outline, u + width, v - height, D3DXVECTOR3((float)(rect.right+hm)+adjm, (float)(bottom+vm)+adjm, .0f ), text.color_outline, u + width, v, D3DXVECTOR3((float)(rect.right+hm)+adjm, (float)(bottom+vm)+adjm, .0f ), text.color_outline, u + width, v, D3DXVECTOR3((float)(rect.left+hp)+adjp, (float)(top+vp)+adjp, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hp)+adjp, (float)(top+vp)+adjp, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hp)+adjp, (float)(bottom+vp)+adjp, .0f ), text.color_outline, u, v, D3DXVECTOR3((float)(rect.right+hp)+adjp, (float)(top+vp)+adjp, .0f ), text.color_outline, u + width, v - height, D3DXVECTOR3((float)(rect.right+hp)+adjp, (float)(bottom+vp)+adjp, .0f ), text.color_outline, u + width, v, D3DXVECTOR3((float)(rect.right+hp)+adjp, (float)(bottom+vp)+adjp, .0f ), text.color_outline, u + width, v, D3DXVECTOR3((float)(rect.left+hm)+adjm, (float)(top+vp)+adjp, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hm)+adjm, (float)(top+vp)+adjp, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hm)+adjm, (float)(bottom+vp)+adjp, .0f ), text.color_outline, u, v, D3DXVECTOR3((float)(rect.right+hm)+adjm, (float)(top+vp)+adjp, .0f ), text.color_outline, u + width, v - height, D3DXVECTOR3((float)(rect.right+hm)+adjm, (float)(bottom+vp)+adjp, .0f ), text.color_outline, u + width, v, D3DXVECTOR3((float)(rect.right+hm)+adjm, (float)(bottom+vp)+adjp, .0f ), text.color_outline, u + width, v, D3DXVECTOR3((float)(rect.left+hp)+adjp, (float)(top+vm)+adjm, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hp)+adjp, (float)(top+vm)+adjm, .0f ), text.color_outline, u, v - height, D3DXVECTOR3((float)(rect.left+hp)+adjp, (float)(bottom+vm)+adjm, .0f ), text.color_outline, u, v, D3DXVECTOR3((float)(rect.right+hp)+adjp, (float)(top+vm)+adjm, .0f ), text.color_outline, u + width, v - height, D3DXVECTOR3((float)(rect.right+hp)+adjp, (float)(bottom+vm)+adjm, .0f ), text.color_outline, u + width, v, }; _device->SetTransform(D3DTS_WORLD, &sprite_tm); hr = _device->SetFVF( FONT_TEXT_VERTEX3_TEXTURE::FVF ); assert(SUCCEEDED(hr)); try { if (font.get_outline_type() == zz_font::OUTLINE_TYPE_SIMPLE) { hr = _device->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 20, vertices3_outline_simple, sizeof(FONT_TEXT_VERTEX3_TEXTURE) ); assert(SUCCEEDED(hr)); } hr = _device->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices3, sizeof(FONT_TEXT_VERTEX3_TEXTURE) ); } catch (...) { // do nothing. maybe device lost state ZZ_LOG("font_texture_d3d: render_tex_impl(). dp exception\n"); } assert(SUCCEEDED(hr)); if (r->get_state()->use_draw_text_rect) { // changing render states { r->set_texture_stage_state( 0, ZZ_TSS_COLOROP, ZZ_TOP_SELECTARG2 ); // DIFFUSE r->set_texture_stage_state( 0, ZZ_TSS_ALPHAOP, ZZ_TOP_DISABLE ); } try { _device->DrawPrimitiveUP( D3DPT_LINESTRIP, 3, vertices3, sizeof(FONT_TEXT_VERTEX3_TEXTURE) ); } catch (...) { ZZ_LOG("font_texture_d3d: render_tex_impl(). dp exception.2\n"); // do nothing. maybe device lost state } } } else { // not using sprite FONT_TEXT_VERTEX4_TEXTURE vertices4 [4] = { D3DXVECTOR4((float)rect.left - .5f, (float)bottom - .5f, .0f, 1.0f), text.color, u, v, D3DXVECTOR4((float)rect.right - .5f, (float)bottom - .5f, .0f, 1.0f), text.color, u + width, v, D3DXVECTOR4((float)rect.right - .5f, (float)top - .5f, .0f, 1.0f), text.color, u + width, v - height, D3DXVECTOR4((float)rect.left - .5f, (float)top - .5f, .0f, 1.0f), text.color, u, v - height, }; const int hm = -1, hp = 1; const int vm = -1, vp = 1; const float adjm = .0f, adjp = -1.0f; FONT_TEXT_VERTEX4_TEXTURE vertices4_outline_simple [22] = { D3DXVECTOR4((float)(rect.left+hm)+adjm, (float)(top+vm)+adjm, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hm)+adjm, (float)(bottom+vm)+adjm, .0f, 1.0f), text.color_outline, u, v, D3DXVECTOR4((float)(rect.right+hm)+adjm, (float)(top+vm)+adjm , .0f, 1.0f), text.color_outline, u + width, v - height, D3DXVECTOR4((float)(rect.right+hm)+adjm, (float)(bottom+vm)+adjm, .0f, 1.0f), text.color_outline, u + width, v, D3DXVECTOR4((float)(rect.right+hm)+adjm, (float)(bottom+vm)+adjm, .0f, 1.0f), text.color_outline, u + width, v, D3DXVECTOR4((float)(rect.left+hp)+adjp, (float)(top+vp)+adjp, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hp)+adjp, (float)(top+vp)+adjp, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hp)+adjp, (float)(bottom+vp)+adjp, .0f, 1.0f), text.color_outline, u, v, D3DXVECTOR4((float)(rect.right+hp)+adjp, (float)(top+vp)+adjp, .0f, 1.0f), text.color_outline, u + width, v - height, D3DXVECTOR4((float)(rect.right+hp)+adjp, (float)(bottom+vp)+adjp, .0f, 1.0f), text.color_outline, u + width, v, D3DXVECTOR4((float)(rect.right+hp)+adjp, (float)(bottom+vp)+adjp, .0f, 1.0f), text.color_outline, u + width, v, D3DXVECTOR4((float)(rect.left+hm)+adjm, (float)(top+vp)+adjp, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hm)+adjm, (float)(top+vp)+adjp, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hm)+adjm, (float)(bottom+vp)+adjp, .0f, 1.0f), text.color_outline, u, v, D3DXVECTOR4((float)(rect.right+hm)+adjm, (float)(top+vp)+adjp, .0f, 1.0f), text.color_outline, u + width, v - height, D3DXVECTOR4((float)(rect.right+hm)+adjm, (float)(bottom+vp)+adjp, .0f, 1.0f), text.color_outline, u + width, v, D3DXVECTOR4((float)(rect.right+hm)+adjm, (float)(bottom+vp)+adjp, .0f, 1.0f), text.color_outline, u + width, v, D3DXVECTOR4((float)(rect.left+hp)+adjp, (float)(top+vm)+adjm, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hp)+adjp, (float)(top+vm)+adjm, .0f, 1.0f), text.color_outline, u, v - height, D3DXVECTOR4((float)(rect.left+hp)+adjp, (float)(bottom+vm)+adjm, .0f, 1.0f), text.color_outline, u, v, D3DXVECTOR4((float)(rect.right+hp)+adjp, (float)(top+vm)+adjm, .0f, 1.0f), text.color_outline, u + width, v - height, D3DXVECTOR4((float)(rect.right+hp)+adjp, (float)(bottom+vm)+adjm, .0f, 1.0f), text.color_outline, u + width, v, }; hr = _device->SetFVF( FONT_TEXT_VERTEX4_TEXTURE::FVF ); assert(SUCCEEDED(hr)); try { if (font.get_outline_type() == zz_font::OUTLINE_TYPE_SIMPLE) { hr = _device->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 20, vertices4_outline_simple, sizeof(FONT_TEXT_VERTEX4_TEXTURE) ); assert(SUCCEEDED(hr)); } hr =_device->DrawPrimitiveUP( D3DPT_TRIANGLEFAN, 2, vertices4, sizeof(FONT_TEXT_VERTEX4_TEXTURE) ); assert(SUCCEEDED(hr)); if (r->get_state()->use_draw_text_rect) { r->set_texture_stage_state(0, ZZ_TSS_COLOROP, ZZ_TOP_SELECTARG2 ); // DIFFUSE r->set_texture_stage_state( 0, ZZ_TSS_ALPHAOP, ZZ_TOP_DISABLE); hr = _device->DrawPrimitiveUP( D3DPT_LINESTRIP, 3, vertices4, sizeof(FONT_TEXT_VERTEX4_TEXTURE) ); assert(SUCCEEDED(hr)); } } catch (...) { // do nothing. maybe device lost state ZZ_LOG("font_texture_d3d: render_tex_impl(). dp exception. 3\n"); } } // restore sprite state if (text.use_sprite) { _device->SetTransform(D3DTS_WORLD, &saved_world); r->set_cullmode(zz_render_state::ZZ_CULLMODE_NONE); r->set_texture_stage_state( 0, ZZ_TSS_COLOROP, ZZ_TOP_MODULATE ); r->set_texture_stage_state( 0, ZZ_TSS_COLORARG1, ZZ_TA_TEXTURE ); r->set_texture_stage_state( 0, ZZ_TSS_COLORARG2, ZZ_TA_DIFFUSE ); r->set_texture_stage_state( 0, ZZ_TSS_ALPHAOP, ZZ_TOP_MODULATE); r->set_texture_stage_state( 0, ZZ_TSS_ALPHAARG1, ZZ_TA_TEXTURE ); r->set_texture_stage_state( 0, ZZ_TSS_ALPHAARG2, ZZ_TA_DIFFUSE ); } }
DisplayObject::DisplayObject() : WorldObject(), m_mesh(NULL) { D3DXMatrixIdentity(&m_world); }
void CTransform::SetUnitTransform() { D3DXMatrixIdentity( &m_kData ); }
/////////////////////////////////////////////////////////////////// // Function: "DrawLine" // // Last Modified: 4/22/2013 // // Input: nX1 The starting x of the line. // nY1 The starting y of the line. // nX2 The ending x of the line. // nY2 The ending y of the line. // dwColor The color to draw the line with (use D3DCOLOR_ARGB() macro). // nWidth The width of the line. // // Return: void // // Purpose: Draws a line of a given color to the screen. /////////////////////////////////////////////////////////////////// void CSGD_Direct3D::DrawLine(int nX1, int nY1, int nX2, int nY2, DWORD dwColor, int nWidth) { // OLD: Use ID3DXLine interface to render line // does not support draw order //D3DXVECTOR2 verts[2]; //verts[0].x = (float)nX1; //verts[0].y = (float)nY1; //verts[1].x = (float)nX2; //verts[1].y = (float)nY2; //m_lpLine->Draw(verts, 2, dwColor); // NEW: Use a 1x1 texture scaled and translated // supports alpha & draw order // no significant FPS change int deltaX = nX2 - nX1; int deltaY = nY2 - nY1; // Line must have a difference in at least one direction if( deltaX == 0 && deltaY == 0 || nWidth <= 0 ) return; // Calculate the length and direction float length = sqrtf( float(deltaX * deltaX + deltaY * deltaY) ); float angle = acos ( deltaX / length ); // abbreviated DotProduct against <1,0> float width = (float)nWidth; float halfWidth = width * 0.5f; //if( length < width ) // length = width; // Indefinite is 0 ... I suppose if( _isnan( angle ) ) angle = 0.0f; else if( deltaY < 0 ) angle = -angle; float cos = cosf( angle ); float sin = sinf( angle ); D3DXMATRIX transform; D3DXMatrixIdentity(&transform); transform.m[0][0] = (FLOAT)(length * cos); // scale & rotate transform.m[0][1] = (FLOAT)(length * sin); transform.m[1][0] = (FLOAT)(width * -sin); transform.m[1][1] = (FLOAT)(width * cos); transform.m[3][0] = (FLOAT)(nX1 + halfWidth * (+sin)); // translate to (x, y) rotated around (0, halfW) transform.m[3][1] = (FLOAT)(nY1 + halfWidth * (- cos)); //transform.m[3][0] = (FLOAT)(nX1); //transform.m[3][1] = (FLOAT)(nY1); // Apply the transform. m_lpSprite->SetTransform(&transform); // Draw the rectangle. m_lpSprite->Draw( m_lpTexture, NULL, NULL, NULL, dwColor ); // Move the world back to identity. D3DXMatrixIdentity(&transform); m_lpSprite->SetTransform(&transform); }
/////////////////////////////////////////////////////////////////// // Function: "DrawHollowRect" // // Last Modified: 3/28/2013 // // Input: rRt The region of the screen to outline. // dwColor The color of the border (use D3DCOLOR_ARGB() macro). // nWidth The width of the rect's border. // // Return: void // // Purpose: Draws the border around a rectangle of a given color to the screen. /////////////////////////////////////////////////////////////////// void CSGD_Direct3D::DrawHollowRect(RECT rRt, DWORD dwColor, int nWidth) { // Use a 1x1 texture scaled and translated // supports alpha & draw order // no significant FPS change D3DXMATRIX transform; D3DXMatrixIdentity(&transform); // Enlarge the rect by 1 pixel to outline a rect rRt.right += 1; rRt.bottom += 1; // Calculate size float width = (float)(rRt.right - rRt.left); float height = (float)(rRt.bottom - rRt.top); float lineWidth = (float)nWidth; float halfWidth = lineWidth * 0.5f; // Top line transform.m[0][0] = (FLOAT)width; transform.m[1][1] = (FLOAT)lineWidth; transform.m[3][0] = (FLOAT)(rRt.left - halfWidth); transform.m[3][1] = (FLOAT)(rRt.top - halfWidth); // Apply the transform. m_lpSprite->SetTransform(&transform); // Draw the rectangle. m_lpSprite->Draw( m_lpTexture, NULL, NULL, NULL, dwColor ); // Left line transform.m[0][0] = (FLOAT)lineWidth; transform.m[1][1] = (FLOAT)height; transform.m[3][0] = (FLOAT)(rRt.left - halfWidth); transform.m[3][1] = (FLOAT)(rRt.top + halfWidth); // Apply the transform. m_lpSprite->SetTransform(&transform); // Draw the rectangle. m_lpSprite->Draw( m_lpTexture, NULL, NULL, NULL, dwColor ); // Bottom line transform.m[0][0] = (FLOAT)width; transform.m[1][1] = (FLOAT)lineWidth; transform.m[3][0] = (FLOAT)(rRt.left + halfWidth); transform.m[3][1] = (FLOAT)(rRt.bottom - halfWidth); // Apply the transform. m_lpSprite->SetTransform(&transform); // Draw the rectangle. m_lpSprite->Draw( m_lpTexture, NULL, NULL, NULL, dwColor ); // Right line transform.m[0][0] = (FLOAT)lineWidth; transform.m[1][1] = (FLOAT)height; transform.m[3][0] = (FLOAT)(rRt.right - halfWidth); transform.m[3][1] = (FLOAT)(rRt.top - halfWidth); // Apply the transform. m_lpSprite->SetTransform(&transform); // Draw the rectangle. m_lpSprite->Draw( m_lpTexture, NULL, NULL, NULL, dwColor ); // Move the world back to identity. D3DXMatrixIdentity(&transform); m_lpSprite->SetTransform(&transform); }
void RenderPick::Draw(float timeDelta) { // Update the view matrix representing the cameras // new position/orientation. D3DXMATRIX V; m_Camera.GetViewMatrix(&V); m_D3DDev->SetTransform(D3DTS_VIEW, &V); // Update: Update Teapot. static float r = 0.0f; static float v = 1.0f; static float angle = 0.0f; D3DXMATRIX World; D3DXMatrixTranslation(&World, cosf(angle) * r, sinf(angle) * r, 10.0f); // transfrom the bounding sphere to match the teapots position in the world. m_BSphere.center = D3DXVECTOR3(cosf(angle) * r, sinf(angle) * r, 10.0f); r += v * timeDelta; // reverse direction if (r >= 8.0f) v = -v; if (r <= 0.0f) v = -v; angle += 1.0f * D3DX_PI * timeDelta; if (angle >= D3DX_PI * 2.0f) angle = 0.0f; // Render m_D3DDev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0xff, 0x40, 0x40, 0x40), 1.0f, 0); m_D3DDev->BeginScene(); // Render basic scene D3DXMATRIX I; D3DXMatrixIdentity(&I); m_D3DDev->SetTransform(D3DTS_WORLD, &I); m_BasicScene->Draw(1.0f); // Render the teapot. m_D3DDev->SetTransform(D3DTS_WORLD, &World); m_D3DDev->SetMaterial(&SGL::YELLOW_MTRL); m_Teapot->DrawSubset(0); // Render the bounding sphere with alpha blending so we can see through it. m_D3DDev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_D3DDev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); m_D3DDev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); D3DMATERIAL9 blue = SGL::BLUE_MTRL; blue.Diffuse.a = 0.25f; // 25% opacity m_D3DDev->SetMaterial(&blue); m_Sphere->DrawSubset(0); m_D3DDev->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); // Draw FPS text RECT rect = {10, 10, m_Width, m_Height}; m_Font->DrawText(NULL, m_FPS.CalcFPSStr(timeDelta), -1, &rect, DT_TOP | DT_LEFT, D3DCOLOR_ARGB(0xff, 0, 0x80, 0)); m_D3DDev->EndScene(); m_D3DDev->Present(NULL, NULL, NULL, NULL); }
bool d3d::DrawBasicScene(IDirect3DDevice9* device, float scale) { static IDirect3DVertexBuffer9* floor = 0; static IDirect3DTexture9* tex = 0; static ID3DXMesh* pillar = 0; HRESULT hr = 0; if( device == 0 ) { if( floor && tex && pillar ) { // they already exist, destroy them d3d::Release<IDirect3DVertexBuffer9*>(floor); d3d::Release<IDirect3DTexture9*>(tex); d3d::Release<ID3DXMesh*>(pillar); } } else if( !floor && !tex && !pillar ) { // they don't exist, create them device->CreateVertexBuffer( 6 * sizeof(d3d::Vertex), 0, d3d::Vertex::FVF, D3DPOOL_MANAGED, &floor, 0); Vertex* v = 0; floor->Lock(0, 0, (void**)&v, 0); v[0] = Vertex(-20.0f, -2.5f, -20.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); v[1] = Vertex(-20.0f, -2.5f, 20.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); v[2] = Vertex( 20.0f, -2.5f, 20.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); v[3] = Vertex(-20.0f, -2.5f, -20.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); v[4] = Vertex( 20.0f, -2.5f, 20.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); v[5] = Vertex( 20.0f, -2.5f, -20.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); floor->Unlock(); D3DXCreateCylinder(device, 0.5f, 0.5f, 5.0f, 20, 20, &pillar, 0); D3DXCreateTextureFromFile( device, "desert.bmp", &tex); } else { // // Pre-Render Setup // device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); D3DXVECTOR3 dir(0.707f, -0.707f, 0.707f); D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col); device->SetLight(0, &light); device->LightEnable(0, true); device->SetRenderState(D3DRS_NORMALIZENORMALS, true); device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Render // D3DXMATRIX T, R, P, S; D3DXMatrixScaling(&S, scale, scale, scale); // used to rotate cylinders to be parallel with world's y-axis D3DXMatrixRotationX(&R, -D3DX_PI * 0.5f); // draw floor D3DXMatrixIdentity(&T); T = T * S; device->SetTransform(D3DTS_WORLD, &T); device->SetMaterial(&d3d::WHITE_MTRL); device->SetTexture(0, tex); device->SetStreamSource(0, floor, 0, sizeof(Vertex)); device->SetFVF(Vertex::FVF); device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2); // draw pillars device->SetMaterial(&d3d::BLUE_MTRL); device->SetTexture(0, 0); for(int i = 0; i < 5; i++) { D3DXMatrixTranslation(&T, -5.0f, 0.0f, -15.0f + (i * 7.5f)); P = R * T * S; device->SetTransform(D3DTS_WORLD, &P); pillar->DrawSubset(0); D3DXMatrixTranslation(&T, 5.0f, 0.0f, -15.0f + (i * 7.5f)); P = R * T * S; device->SetTransform(D3DTS_WORLD, &P); pillar->DrawSubset(0); } } return true; }
void DirectXRender::setTransform2d(int pX, int pY, float pAngleX, float pAngleY, float pAngleZ, float pScaleX, float pScaleY, int pAxisCalX, int pAxisCalY, bool pMirrorX, bool pMirrorY, int pWidth, int pHeight, IND_Matrix *pMatrix) { // ----- World matrix initialization ----- D3DXMATRIX mMatWorld, mMatZ, mMatX, mMatY, mMatTraslation, mMatScale; //Initializes every object transform with pixel to point scale transform _info._device->SetTransform(D3DTS_WORLD, D3DXMatrixIdentity(&mMatWorld)); // ----- Transformation matrix creation ----- // Mirroring (180º rotations) if (pMirrorX || pMirrorY) { //A mirror is a rotation in desired axis (the actual mirror) and a repositioning because rotation //also moves 'out of place' the entity translation-wise if (pMirrorX) { //Rotate in y, to invert texture D3DXMatrixRotationY(&mMatY, D3DXToRadian(180)); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatY); //After rotation around origin, move back texture to correct place D3DXMatrixTranslation(&mMatTraslation, static_cast<float>(pWidth), 0.0f, 0); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatTraslation); } //A mirror is a rotation in desired axis (the actual mirror) and a repositioning because rotation //also moves 'out of place' the entity translation-wise if (pMirrorY) { //Rotate in x, to invert texture D3DXMatrixRotationX(&mMatX, D3DXToRadian(180)); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatX); //After rotation around origin, move back texture to correct place D3DXMatrixTranslation(&mMatTraslation, 0.0f, static_cast<float>(pHeight), 0); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatTraslation); } } // Hotspot - Set hotspot to affect following transforms if (pAxisCalX != 0 || pAxisCalY != 0) { D3DXMatrixTranslation(&mMatTraslation, static_cast<float>( pAxisCalX), static_cast<float>( pAxisCalY), 0); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatTraslation); } // Scaling if (pScaleX != 1.0f || pScaleY != 1.0f) { D3DXMatrixScaling(&mMatScale, pScaleX, pScaleY, 1.0f); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatScale); } // Rotations if (pAngleX != 0.0f) { D3DXMatrixRotationX(&mMatX, D3DXToRadian(pAngleX)); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatX); } if (pAngleY != 0.0f) { D3DXMatrixRotationY(&mMatY, D3DXToRadian(pAngleY)); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatY); } if (pAngleZ != 0.0f) { D3DXMatrixRotationZ(&mMatZ, D3DXToRadian(pAngleZ)); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatZ); } // Translations if (pX != 0 || pY != 0) { D3DXMatrixTranslation(&mMatTraslation, static_cast<float>(pX), static_cast<float>(pY), 0); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mMatTraslation); } // ----- Return World Matrix (in IndieLib format) ----- if (pMatrix) { pMatrix->readFromArray(&mMatWorld.m[0][0]); } // ----- Applies the transformation ----- _info._device->SetTransform(D3DTS_WORLD, &mMatWorld); }
void CEntity::Render() { //_SINGLE(CDevice)->GetDevice()->SetTransform(D3DTS_WORLD, &m_matWorld); m_matWorld = m_matScale * m_matRot * m_matTrans; const D3DXMATRIX* pMatProj = _SINGLE(CCameraManager)->GetCurCam()->GetMatProj(m_eView); const D3DXMATRIX* pMatView = _SINGLE(CCameraManager)->GetCurCam()->GetMatView(m_eView); D3DXMATRIX matWVP = m_matWorld * (*pMatView); CShader* pShader = _SINGLE(CShaderManager)->FindShader(m_eShader); //if(m_eMeshNum == MN_ZOMBIE) //{ // m_vecPass.clear(); // m_vecPass.push_back(3); //} D3DXMATRIX matIden; D3DXMatrixIdentity(&matIden); pShader->SetMatrix("g_matView", pMatView); pShader->SetMatrix("g_matProj", pMatProj); pShader->SetMatrix("g_matWorld", &m_matWorld); pShader->SetMatrix("g_matIden", &matIden); pShader->SetMatrix("g_matWV", &matWVP); matWVP *= (*pMatProj); pShader->SetMatrix("g_matWVP", &matWVP); D3DMATERIAL9 tMaterial; tMaterial.Diffuse.a = 1.f; tMaterial.Diffuse.r = 1.f; tMaterial.Diffuse.g = 1.f; tMaterial.Diffuse.b = 1.f; tMaterial.Ambient = tMaterial.Diffuse; tMaterial.Specular = tMaterial.Diffuse; tMaterial.Power = 1.f; //°¢°¢ÀÇ Æнº¿¡ ´ëÇØ ·»´õ for(unsigned int i = 0; i < m_vecPass.size(); ++i) { m_pMesh->Render(pShader, m_vecPass[i]); } pShader->SetValue("g_mtrlMesh", &tMaterial, sizeof(D3DMATERIAL9)); if(m_bDrawSphere) { DrawSphere(pShader); } /* _SINGLE(CDevice)->GetDevice()->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); pShader->BeginPass(1); m_SphereMesh->DrawSubset(0); pShader->EndPass(); _SINGLE(CDevice)->GetDevice()->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);*/ }
void DirectXRender::setIdentityTransform2d () { // ----- Applies the transformation ----- D3DXMATRIX mMatWorld; //Initializes every object transform with pixel to point scale transform _info._device->SetTransform(D3DTS_WORLD, D3DXMatrixIdentity(&mMatWorld)); }
int CheckBoxPairSystemCollision( sObject* pA, sObject* pB ) { // Check if either box is rotated bool bYesRotated=true; // 20120404 IanM - Need to use rotated collision check if a pivot has been applied if(pA->position.bApplyPivot == false && pB->position.bApplyPivot == false) if(pA->collision.bFixedBoxCheck==true && pB->collision.bFixedBoxCheck==true) bYesRotated=false; // lee - 240306 - u6b4 - any sphere types use fixed box for non-rotating sliding if(pA->collision.eCollisionType==COLLISION_SPHERE || pA->collision.eCollisionType==COLLISION_SPHERE ) { // leefix - 020308 - does not account for rotated elongated boxes (collision error with 90 degree rotated box(10,10,30)) // bYesRotated=false; // so instead, use rotated algorythm but fix sphere to a non-rotated box so rotating does not get it stuck // inside collider (new sphere collision type detection inside code below) } // Use rotated-box check if rotated.. if(bYesRotated==true) { // Multiple checks yield best sliding result (if any) D3DXVECTOR3 box1p = D3DXVECTOR3(pA->position.matWorld._41,pA->position.matWorld._42,pA->position.matWorld._43); int iInitialCollisionResult = CheckAdjustedAagainstB ( box1p, pA, pB ); if(iInitialCollisionResult>0) { // COPIED FROM ADJUSTMENTAGAINSTB FUNCTION (should combine the work) D3DXMATRIX matRotateX, matRotateY, matRotateZ; // Box 1 D3DXVECTOR3 box1s; box1s.x=(pA->collision.vecMax.x-pA->collision.vecMin.x)*0.5f; box1s.y=(pA->collision.vecMax.y-pA->collision.vecMin.y)*0.5f; box1s.z=(pA->collision.vecMax.z-pA->collision.vecMin.z)*0.5f; D3DXVECTOR3 box1offset; box1offset.x=pA->collision.vecMin.x+box1s.x; box1offset.y=pA->collision.vecMin.y+box1s.y; box1offset.z=pA->collision.vecMin.z+box1s.z; box1s.x *= pA->position.vecScale.x; box1s.y *= pA->position.vecScale.y; box1s.z *= pA->position.vecScale.z; D3DXMATRIX matARotation; if ( pA->collision.eCollisionType==COLLISION_SPHERE ) D3DXMatrixIdentity ( &matARotation ); else { // 20120404 IanM - Use common method of calculating the object rotation matrix matARotation = CalcObjectRotationMatrix( pA ); /* if ( pA->position.bFreeFlightRotation ) matARotation = pA->position.matFreeFlightRotate; else { D3DXMatrixRotationX ( &matRotateX, D3DXToRadian ( pA->position.vecRotate.x ) ); // x rotation D3DXMatrixRotationY ( &matRotateY, D3DXToRadian ( pA->position.vecRotate.y ) ); // y rotation D3DXMatrixRotationZ ( &matRotateZ, D3DXToRadian ( pA->position.vecRotate.z ) ); // z rotation matARotation = matRotateX * matRotateY * matRotateZ; } */ } D3DXVec3TransformCoord ( &box1offset, &box1offset, &matARotation ); box1p = pA->position.vecLastPosition;//forslidingcalc, need old A pos box1p+=box1offset; // Box 2 D3DXVECTOR3 box2p = D3DXVECTOR3(pB->position.matWorld._41,pB->position.matWorld._42,pB->position.matWorld._43); D3DXVECTOR3 box2s; box2s.x=(pB->collision.vecMax.x-pB->collision.vecMin.x)*0.5f; box2s.y=(pB->collision.vecMax.y-pB->collision.vecMin.y)*0.5f; box2s.z=(pB->collision.vecMax.z-pB->collision.vecMin.z)*0.5f; D3DXVECTOR3 box2offset; box2offset.x=pB->collision.vecMin.x+box2s.x; box2offset.y=pB->collision.vecMin.y+box2s.y; box2offset.z=pB->collision.vecMin.z+box2s.z; box2s.x *= pB->position.vecScale.x; box2s.y *= pB->position.vecScale.y; box2s.z *= pB->position.vecScale.z; D3DXMATRIX matBRotation; if ( pB->collision.eCollisionType==COLLISION_SPHERE ) D3DXMatrixIdentity ( &matBRotation ); else { // 20120404 IanM - Use common method of calculating the object rotation matrix matBRotation = CalcObjectRotationMatrix( pB ); /* if ( pB->position.bFreeFlightRotation ) matBRotation = pB->position.matFreeFlightRotate; else { D3DXMatrixRotationX ( &matRotateX, D3DXToRadian ( pB->position.vecRotate.x ) ); // x rotation D3DXMatrixRotationY ( &matRotateY, D3DXToRadian ( pB->position.vecRotate.y ) ); // y rotation D3DXMatrixRotationZ ( &matRotateZ, D3DXToRadian ( pB->position.vecRotate.z ) ); // z rotation matBRotation = matRotateX * matRotateY * matRotateZ; } */ } D3DXVec3TransformCoord ( &box2offset, &box2offset, &matBRotation ); box2p+=box2offset; // inverse of box Bs rotation float fDeterminant; D3DXMATRIX matInvBoxBRot; D3DXMatrixInverse ( &matInvBoxBRot, &fDeterminant, &matBRotation ); // rotate Start and End vectors of A using B D3DXVECTOR3 vecAS = pA->position.vecLastPosition; D3DXVECTOR3 vecAE = pA->position.vecPosition; D3DXVECTOR3 vecOldDirection = vecAE - vecAS; D3DXVec3TransformCoord ( &vecAS, &vecAS, &matInvBoxBRot ); D3DXVec3TransformCoord ( &vecAE, &vecAE, &matInvBoxBRot ); // work out closest point in A D3DXVECTOR3 vecCLOSEST; float fDistClosest=9999.0f; D3DXVECTOR3 vecB = pB->position.vecPosition; for ( int iPoint=0; iPoint<4; iPoint++ ) { // center of each side D3DXVECTOR3 vP = D3DXVECTOR3(0,0,0); if ( iPoint==0 ) { vP.x-=box1s.x; vP.z-=box1s.z; } if ( iPoint==1 ) { vP.x-=box1s.x; vP.z+=box1s.z; } if ( iPoint==2 ) { vP.x+=box1s.x; vP.z-=box1s.z; } if ( iPoint==3 ) { vP.x+=box1s.x; vP.z+=box1s.z; } D3DXVec3TransformCoord ( &vP, &vP, &matARotation ); vP+=box1p; // work out distance from start vector float fDx = (float)fabs ( vP.x - vecB.x ); float fDz = (float)fabs ( vP.z - vecB.z ); float fDist = (float)sqrt((fDx*fDx)+(fDz*fDz)); if ( fDist < fDistClosest ) { // record best corner fDistClosest = fDist; vecCLOSEST = vP; } } vecCLOSEST -= box2p; D3DXVec3TransformCoord ( &vecCLOSEST, &vecCLOSEST, &matInvBoxBRot ); // sliding collision for X and Z sides int iSideBest = 0; float fSidePos, fDist; float fDistBest = 99999.0f; fSidePos = 0-box2s.x; fDist = fSidePos - vecCLOSEST.x; if ( fDist>=0.0f ) { fDist = (float)fabs(fDist); if ( fDist<fDistBest ) { iSideBest=0; fDistBest=fDist; } } fSidePos = box2s.x; fDist = vecCLOSEST.x - fSidePos; if ( fDist>=0.0f ) { fDist = (float)fabs(fDist); if ( fDist<fDistBest ) { iSideBest=1; fDistBest=fDist; } } fSidePos = 0-box2s.z; fDist = fSidePos - vecCLOSEST.z; if ( fDist>=0.0f ) { fDist = (float)fabs(fDist); if ( fDist<fDistBest ) { iSideBest=4; fDistBest=fDist; } } fSidePos = box2s.z; fDist = vecCLOSEST.z - fSidePos; if ( fDist>=0.0f ) { fDist = (float)fabs(fDist); if ( fDist<fDistBest ) { iSideBest=5; fDistBest=fDist; } } // bring Start and End vectors onto plane of the side if ( iSideBest==0 ) { vecAS.x = box2p.x-box2s.x; vecAE.x = box2p.x-box2s.x; } if ( iSideBest==1 ) { vecAS.x = box2p.x+box2s.x; vecAE.x = box2p.x+box2s.x; } if ( iSideBest==2 ) { vecAS.y = box2p.y-box2s.y; vecAE.y = box2p.y-box2s.y; } if ( iSideBest==3 ) { vecAS.y = box2p.y+box2s.y; vecAE.y = box2p.y+box2s.y; } if ( iSideBest==4 ) { vecAS.z = box2p.z-box2s.z; vecAE.z = box2p.z-box2s.z; } if ( iSideBest==5 ) { vecAS.z = box2p.z+box2s.z; vecAE.z = box2p.z+box2s.z; } // work out direction based on new start and end D3DXVECTOR3 vecAdjustedDirection = vecAE - vecAS; // orient direction to box Bs rotation for new sliding data D3DXVec3TransformCoord ( &vecAdjustedDirection, &vecAdjustedDirection, &matBRotation ); // if a good collision free slide, use it, else restore to old position box1p = pA->position.vecPosition - (vecOldDirection - vecAdjustedDirection); if ( CheckAdjustedAagainstB ( box1p, pA, pB )==0 ) { // sliding adjustment worked fine gvLatestObjectCollisionResult = vecOldDirection - vecAdjustedDirection; } else { // movement cannot proceed, must restore gvLatestObjectCollisionResult = vecOldDirection; } } return iInitialCollisionResult; } else return CheckUnRotatedBoxes( pA, pB ); }
HRESULT KG3DSFXBillboard::Render(float fCurrentFrame) { HRESULT hRetCode = E_FAIL; CreateVertexBuffer(); if (!m_pVB) return E_FAIL; BOOL bTextureReady = FALSE; if (m_fCurrentFrame != fCurrentFrame) { /* * update the rtx data */ m_vPositionLine.GetData(&m_Translation, fCurrentFrame); m_fRotationTimeLine.GetData(&m_Rotation, fCurrentFrame); m_fWidthTimeLine.GetData(&m_fWidth, fCurrentFrame); m_fHeightTimeLine.GetData(&m_fHeight, fCurrentFrame); m_DiffuseTimeLine.GetData(&m_Color, fCurrentFrame); m_fCurrentFrame = fCurrentFrame; } /* * update to world matrix */ D3DXMatrixTranslation(&m_Matrix, m_Translation.x, m_Translation.y, m_Translation.z); if (m_dwBindTrackIndex != SFX_NOT_BIND_TO_TRACK) { KG3DSFXTrack *pTrack = NULL; D3DXMATRIX matTrack; if (SUCCEEDED(m_pSFX->GetTrack(m_dwBindTrackIndex, &pTrack))) { pTrack->GetTransform(fCurrentFrame, &matTrack); m_Matrix *= matTrack; } } m_matWorld = m_Matrix * (*m_pSFX->GetCurrentWorldMatrix()); /* * crate billboard */ D3DXVECTOR3 vPos = D3DXVECTOR3(m_matWorld._41, m_matWorld._42, m_matWorld._43); KG3DCamera* pCamera = g_cGraphicsTool.GetCamera(); ASSERT(pCamera); float fHScal = m_pSFX->m_Srt.vScanl.y; float fWScal = (m_pSFX->m_Srt.vScanl.x + m_pSFX->m_Srt.vScanl.z) * 0.5f; float HalfWidth = m_fWidth * fWScal * 0.5f; float HalfHeight = m_fHeight * fHScal * 0.5f; D3DXVECTOR3 vRight; D3DXVECTOR3 vUp; switch (m_dwBillBoradType) { case BILLBOARE_TYPE_NORMAL : { vRight = pCamera->GetCameraRight(); vUp = pCamera->GetCameraUp(); } break; case BILLBOARE_TYPE_FREE : { ASSERT(false); } break; case BILLBOARE_TYPE_LOCK_X : { vRight = pCamera->GetCameraRight(); vUp = pCamera->GetCameraFront(); vUp.y = 0.f; D3DXVec3Normalize(&vUp, &vUp); } break; case BILLBOARE_TYPE_LOCK_Y : { vUp = D3DXVECTOR3(0.f, 1.f, 0.f); D3DXVECTOR3 vCameraPos; pCamera->GetPosition(&vCameraPos); D3DXVECTOR3 vLookDirection = vCameraPos - vPos; D3DXVec3Cross(&vRight, &vLookDirection, &vUp); D3DXVec3Normalize(&vRight, &vRight); } break; default : ASSERT(false); break; } if (m_fRotationTimeLine.GetSize() > 1) { D3DXVECTOR3 vAxis; D3DXMATRIX mat; D3DXVec3Cross(&vAxis, &vUp, &vRight); D3DXVec3Normalize(&vAxis, &vAxis); D3DXMatrixRotationAxis(&mat, &vAxis, m_Rotation); D3DXVec3TransformNormal(&vRight, &vRight, &mat); D3DXVec3TransformNormal(&vUp, &vUp, &mat); } VFormat::_Faces_Diffuse_Texture2* pVertex = NULL; hRetCode = m_pVB->Lock(0, 0, (void**)&pVertex, D3DLOCK_DISCARD); if (FAILED(hRetCode)) return hRetCode; pVertex[0].p = vPos - vRight * HalfWidth + vUp * HalfHeight; pVertex[1].p = vPos + vRight * HalfWidth + vUp * HalfHeight; pVertex[2].p = vPos - vRight * HalfWidth - vUp * HalfHeight; pVertex[3].p = vPos + vRight * HalfWidth - vUp * HalfHeight; pVertex[0].diffuse = (D3DCOLOR)m_Color; pVertex[1].diffuse = (D3DCOLOR)m_Color; pVertex[2].diffuse = (D3DCOLOR)m_Color; pVertex[3].diffuse = (D3DCOLOR)m_Color; if (m_pTexture && m_pTexture->GetTexture()) { int nTextureFrameIndex = 0; m_nTextureFrameIndex.GetData(&nTextureFrameIndex, fCurrentFrame); if (nTextureFrameIndex >= (int)(m_dwCuttingNum * m_dwCuttingNum)) nTextureFrameIndex = m_dwCuttingNum * m_dwCuttingNum - 1; D3DXVECTOR2 vUV1 = D3DXVECTOR2(0.f, 0.f); if (m_dwCuttingNum == 1 && m_dwCuttingNum2 == 1) m_vUVTimeLine.GetData(&vUV1, fCurrentFrame); else { vUV1.x = 0; vUV1.y = 0; } float fCellSize1 = 1.0f / (float)m_dwCuttingNum; UINT uY1 = nTextureFrameIndex / m_dwCuttingNum; UINT uX1 = nTextureFrameIndex - uY1 * m_dwCuttingNum; pVertex[0].tu1 = uX1 * fCellSize1 + vUV1.x; pVertex[0].tv1 = uY1 * fCellSize1 + vUV1.y; pVertex[1].tu1 = (uX1 + 1) * fCellSize1 + vUV1.x; pVertex[1].tv1 = uY1 * fCellSize1 + vUV1.y; pVertex[2].tu1 = uX1 * fCellSize1 + vUV1.x; pVertex[2].tv1 = (uY1 + 1) * fCellSize1 + vUV1.y; pVertex[3].tu1 = (uX1 + 1) * fCellSize1 + vUV1.x; pVertex[3].tv1 = (uY1 + 1) * fCellSize1 + vUV1.y; g_pd3dDevice->SetTexture(0, m_pTexture->GetTexture()); if (m_pTexture2 && m_pTexture2->GetTexture()) { int nTexture2FrameIndex = 0; m_nTexture2FrameIndex.GetData(&nTexture2FrameIndex, fCurrentFrame); if (nTexture2FrameIndex >= (int)(m_dwCuttingNum2 * m_dwCuttingNum2)) nTexture2FrameIndex = m_dwCuttingNum2 * m_dwCuttingNum2 - 1; float fCellSize2 = 1.0f / (float)m_dwCuttingNum2; UINT uY2 = nTexture2FrameIndex / m_dwCuttingNum2; UINT uX2 = nTexture2FrameIndex - uY2 * m_dwCuttingNum2; pVertex[0].tu2 = uX2 * fCellSize2; pVertex[0].tv2 = uY2 * fCellSize2; pVertex[1].tu2 = (uX2 + 1) * fCellSize2; pVertex[1].tv2 = uY2 * fCellSize2; pVertex[2].tu2 = uX2 * fCellSize2; pVertex[2].tv2 = (uY2 + 1) * fCellSize2; pVertex[3].tu2 = (uX2 + 1) * fCellSize2; pVertex[3].tv2 = (uY2 + 1) * fCellSize2; } bTextureReady = TRUE; } m_pVB->Unlock(); if (m_pTexture && m_pTexture->GetTexture()) { g_pd3dDevice->SetTexture(0, m_pTexture->GetTexture()); if (m_pTexture2 && m_pTexture2->GetTexture()) g_pd3dDevice->SetTexture(1, m_pTexture2->GetTexture()); else g_pd3dDevice->SetTexture(1, NULL); bTextureReady = TRUE; } else g_pd3dDevice->SetTexture(0, NULL); if(bTextureReady) { D3DXMATRIX matWorldSave; D3DXMATRIX matRender; D3DXMatrixIdentity(&matRender); hRetCode = g_pd3dDevice->GetTransform(D3DTS_WORLD, &matWorldSave); hRetCode = g_pd3dDevice->SetTransform(D3DTS_WORLD, &matRender); hRetCode = g_pd3dDevice->SetStreamSource(0, m_pVB, 0, sizeof(VFormat::_Faces_Diffuse_Texture2)); hRetCode = g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); hRetCode = g_pd3dDevice->SetTransform(D3DTS_WORLD, &matWorldSave); hRetCode = g_pd3dDevice->SetStreamSource(0, 0, 0, 0); } return S_OK; /* HRESULT hResult = E_FAIL; if (m_fCurrentFrame != fCurrentFrame) { m_vPositionLine.GetData(&m_Translation, fCurrentFrame); m_fCurrentFrame = fCurrentFrame; } D3DXMATRIX mat; D3DXQUATERNION q; float fHScal = m_pSFX->m_Srt.vScanl.y; float fWScal = (m_pSFX->m_Srt.vScanl.x + m_pSFX->m_Srt.vScanl.z) * 0.5f; D3DXQuaternionRotationYawPitchRoll(&q, m_Rotation.y, m_Rotation.x, m_Rotation.z); D3DXMatrixTransformation( &mat, &D3DXVECTOR3(0, 0, 0), &D3DXQUATERNION(0, 0, 0, 1), &D3DXVECTOR3(1, 1, 1), &D3DXVECTOR3(0, 0, 0), &q, &m_Translation ); if (m_dwBindTrackIndex != SFX_NOT_BIND_TO_TRACK) { D3DXMATRIX matTrack; KG3DSFXTrack *pTrack = NULL; if (SUCCEEDED(m_pSFX->GetTrack(m_dwBindTrackIndex, &pTrack))) { pTrack->GetTransform(fCurrentFrame, &matTrack); mat *= matTrack; } } m_Matrix = mat; D3DXVECTOR3 vPos(mat._41, mat._42, mat._43); D3DXVec3TransformCoord(&vPos, &vPos, m_pSFX->GetCurrentWorldMatrix()); float fWidth = 1.f; float fHeight = 1.f; m_fWidthTimeLine.GetData(&fWidth, fCurrentFrame); m_fHeightTimeLine.GetData(&fHeight, fCurrentFrame); fWidth *= fWScal;//m_pSFX->GetScaleSize(); fHeight *= fHScal;//m_pSFX->GetScaleSize(); D3DXCOLOR color; m_DiffuseTimeLine.GetData(&color, fCurrentFrame); KG3DCamera* pCamera = g_cGraphicsTool.GetCamera(); ASSERT(pCamera); float HalfWidth = fWidth * 0.5f; float HalfHeight = fHeight * 0.5f; D3DXVECTOR3 vRight; D3DXVECTOR3 vUp; if (m_bRotation && m_fRotationTimeLine.GetSize()) { ASSERT(!m_bLockAxis); vRight = pCamera->GetCameraRight(); vUp = pCamera->GetCameraUp(); D3DXVECTOR3 vAxis = pCamera->GetCameraFront(); D3DXVec3Normalize(&vAxis, &vAxis); D3DXMATRIX mat; float fAngle = 0; m_fRotationTimeLine.GetData(&fAngle, fCurrentFrame); D3DXMatrixRotationAxis(&mat, &vAxis, fAngle); D3DXVec3TransformCoord(&vRight, &vRight, &mat); D3DXVec3TransformCoord(&vUp, &vUp, &mat); } else if (m_bLockAxis) { ASSERT(!m_bRotation); vUp.x = mat._21; vUp.y = mat._22; vUp.z = mat._23; D3DXVECTOR3 vCameraPos; pCamera->GetPosition(&vCameraPos); D3DXVECTOR3 vLookDirection = vCameraPos - vPos; D3DXVec3Cross(&vRight, &vLookDirection, &vUp); } else { vRight = pCamera->GetCameraRight(); vUp = pCamera->GetCameraUp(); } D3DXVec3Normalize(&vRight, &vRight); D3DXVec3Normalize(&vUp, &vUp); VFormat::_Faces_Diffuse_Texture2 vertices[4]; vertices[0].p = vPos - vRight * HalfWidth + vUp * HalfHeight; vertices[1].p = vPos + vRight * HalfWidth + vUp * HalfHeight; vertices[2].p = vPos - vRight * HalfWidth - vUp * HalfHeight; vertices[3].p = vPos + vRight * HalfWidth - vUp * HalfHeight; vertices[0].diffuse = (D3DCOLOR)color; vertices[1].diffuse = (D3DCOLOR)color; vertices[2].diffuse = (D3DCOLOR)color; vertices[3].diffuse = (D3DCOLOR)color; if (m_pTexture && m_pTexture->GetTexture()) { int nTextureFrameIndex = 0; m_nTextureFrameIndex.GetData(&nTextureFrameIndex, fCurrentFrame); if (nTextureFrameIndex >= (int)(m_dwCuttingNum * m_dwCuttingNum)) nTextureFrameIndex = m_dwCuttingNum * m_dwCuttingNum - 1; D3DXVECTOR2 vUV1 = D3DXVECTOR2(0.f, 0.f); if (m_dwCuttingNum == 1 && m_dwCuttingNum2 == 1) m_vUVTimeLine.GetData(&vUV1, fCurrentFrame); else { vUV1.x = 0; vUV1.y = 0; } float fCellSize1 = 1.0f / (float)m_dwCuttingNum; UINT uY1 = nTextureFrameIndex / m_dwCuttingNum; UINT uX1 = nTextureFrameIndex - uY1 * m_dwCuttingNum; vertices[0].tu1 = uX1 * fCellSize1 + vUV1.x; vertices[0].tv1 = uY1 * fCellSize1 + vUV1.y; vertices[1].tu1 = (uX1 + 1) * fCellSize1 + vUV1.x; vertices[1].tv1 = uY1 * fCellSize1 + vUV1.y; vertices[2].tu1 = uX1 * fCellSize1 + vUV1.x; vertices[2].tv1 = (uY1 + 1) * fCellSize1 + vUV1.y; vertices[3].tu1 = (uX1 + 1) * fCellSize1 + vUV1.x; vertices[3].tv1 = (uY1 + 1) * fCellSize1 + vUV1.y; g_pd3dDevice->SetTexture(0, m_pTexture->GetTexture()); if (m_pTexture2 && m_pTexture2->GetTexture()) { int nTexture2FrameIndex = 0; m_nTexture2FrameIndex.GetData(&nTexture2FrameIndex, fCurrentFrame); if (nTexture2FrameIndex >= (int)(m_dwCuttingNum2 * m_dwCuttingNum2)) nTexture2FrameIndex = m_dwCuttingNum2 * m_dwCuttingNum2 - 1; float fCellSize2 = 1.0f / (float)m_dwCuttingNum2; UINT uY2 = nTexture2FrameIndex / m_dwCuttingNum2; UINT uX2 = nTexture2FrameIndex - uY2 * m_dwCuttingNum2; vertices[0].tu2 = uX2 * fCellSize2; vertices[0].tv2 = uY2 * fCellSize2; vertices[1].tu2 = (uX2 + 1) * fCellSize2; vertices[1].tv2 = uY2 * fCellSize2; vertices[2].tu2 = uX2 * fCellSize2; vertices[2].tv2 = (uY2 + 1) * fCellSize2; vertices[3].tu2 = (uX2 + 1) * fCellSize2; vertices[3].tv2 = (uY2 + 1) * fCellSize2; g_pd3dDevice->SetTexture(1, m_pTexture2->GetTexture()); } else { g_pd3dDevice->SetTexture(1, NULL); } } else g_pd3dDevice->SetTexture(0, NULL); g_pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, (void*)vertices, sizeof(VFormat::_Faces_Diffuse_Texture2) ); // update bbox /* m_AABBox.Clear(); m_AABBox.AddPosition(vertices[0].p); m_AABBox.AddPosition(vertices[1].p); m_AABBox.AddPosition(vertices[2].p); m_AABBox.AddPosition(vertices[3].p);*/ // hResult = S_OK; //Exit0: // return hResult; }
// 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" ) ); // Metasequoia モデル変換データ読み込み // fread の引数 path/to/exported_data を、エクスポートしたモデルデータファイルに変更してください。 FILE *fp; unsigned int vertices_count = 0; unsigned int faces_count = 0; float * metasequoiaVertices = NULL; unsigned int * metasequoiaIndices = NULL; if ( ( fp = fopen( "path/to/exported_data", "rb" ) ) == NULL ) { MessageBox( NULL, _T( "失敗: fopen()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } // 頂点数 fread( &vertices_count, sizeof( unsigned int ), 1, fp ); // メモリ確保・読み込み metasequoiaVertices = new float[ 6 * vertices_count ]; fread( metasequoiaVertices, sizeof( float ) * 6, vertices_count, fp ); // 面数 fread( &faces_count, sizeof( unsigned int ), 1, fp ); // メモリ確保・読み込み metasequoiaIndices = new unsigned int[ 3 * faces_count ]; fread( metasequoiaIndices, sizeof( unsigned int ) * 3, faces_count, fp ); // モデル表示用の頂点バッファを生成 D3D11_BUFFER_DESC metasequoiaVertexBufferDesc = { sizeof( float ) * 6 * vertices_count, // ByteWidth D3D11_USAGE_DEFAULT, // Usage D3D11_BIND_VERTEX_BUFFER, // BindFlags 0, // CPUAccessFlags 0, // MiscFlags 0 // StructureByteStride }; D3D11_SUBRESOURCE_DATA metasequoiaVertexResourceData = { metasequoiaVertices }; ID3D11Buffer * pMetasequoiaVertexBuffer = NULL; hr = pDevice->CreateBuffer( &metasequoiaVertexBufferDesc, &metasequoiaVertexResourceData, &pMetasequoiaVertexBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pMetasequoiaVertexBuffer: 0x%p)\n" ), pMetasequoiaVertexBuffer ); // モデル表示用のインデックスバッファを生成 D3D11_BUFFER_DESC metasequoiaIndexBufferDesc = { sizeof( unsigned int ) * 3 * faces_count, // ByteWidth D3D11_USAGE_DEFAULT, // Usage D3D11_BIND_INDEX_BUFFER, // BindFlags 0, // CPUAccessFlags 0, // MiscFlags 0 // StructureByteStride }; D3D11_SUBRESOURCE_DATA metasequoiaIndexResourceData = { metasequoiaIndices }; ID3D11Buffer * pMetasequoiaIndexBuffer = NULL; hr = pDevice->CreateBuffer( &metasequoiaIndexBufferDesc, &metasequoiaIndexResourceData, &pMetasequoiaIndexBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pMetasequoiaIndexBuffer: 0x%p)\n" ), pMetasequoiaIndexBuffer ); // モデル表示用のインデックスバッファをバインド pDeviceContext->IASetIndexBuffer( pMetasequoiaIndexBuffer, DXGI_FORMAT_R32_UINT, 0 ); dtprintf( _T( "ID3D11DeviceContext::IASetIndexBuffer: ok\n" ) ); // 3 軸線の頂点データ float triaxialVertices[ 12 ][ 7 ] = { // Xaxis Yaxis Zaxis 赤 緑 青 Alpha { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }, // x 軸正方向 { 200.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.2f, 0.0f, 0.0f, 1.0f }, // x 軸負方向 { -200.0f, 0.0f, 0.0f, 0.2f, 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f }, // y 軸正方向 { 0.0f, 500.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.0f, 0.2f, 0.0f, 1.0f }, // y 軸負方向 { 0.0f, -500.0f, 0.0f, 0.0f, 0.2f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f }, // z 軸正方向 { 0.0f, 0.0f, 100.0f, 0.0f, 0.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.2f, 1.0f }, // z 軸負方向 { 0.0f, 0.0f, -100.0f, 0.0f, 0.0f, 0.2f, 1.0f } }; // 3 軸線の頂点バッファを生成 D3D11_BUFFER_DESC triaxialVertexBufferDesc = { sizeof( triaxialVertices ), // ByteWidth D3D11_USAGE_DEFAULT, // Usage D3D11_BIND_VERTEX_BUFFER, // BindFlags 0, // CPUAccessFlags 0, // MiscFlags 0 // StructureByteStride }; D3D11_SUBRESOURCE_DATA triaxialVertexResourceData = { triaxialVertices }; ID3D11Buffer * pTriaxialVertexBuffer = NULL; hr = pDevice->CreateBuffer( &triaxialVertexBufferDesc, &triaxialVertexResourceData, &pTriaxialVertexBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pTriaxialVertexBuffer: 0x%p)\n" ), pTriaxialVertexBuffer ); // 頂点シェーダ用の定数バッファを作成 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" ) ); // 3 軸線表示用の頂点シェーダを作成 ID3D11VertexShader * pTriaxialVertexShader = NULL; hr = pDevice->CreateVertexShader( g_vs_perspective, sizeof( g_vs_perspective ), NULL, &pTriaxialVertexShader ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pTriaxialVertexShader: 0x%p)\n" ), pTriaxialVertexShader ); // モデル表示用の頂点シェーダを作成 ID3D11VertexShader * pMetasequoiaVertexShader = NULL; hr = pDevice->CreateVertexShader( g_vs_metasequoiaNormal, sizeof( g_vs_metasequoiaNormal ), NULL, &pMetasequoiaVertexShader ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pMetasequoiaVertexShader: 0x%p)\n" ), pMetasequoiaVertexShader ); // ピクセルシェーダを作成 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( NULL, NULL, 0 ); // 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 ); // 3 軸線表示用の入力レイアウトを作成 D3D11_INPUT_ELEMENT_DESC triaxialVerticesDesc[] = { { "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 * pTriaxialInputLayout = NULL; hr = pDevice->CreateInputLayout( triaxialVerticesDesc, 2, g_vs_perspective, sizeof( g_vs_perspective ), &pTriaxialInputLayout ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pTriaxialInputLayout: 0x%p)\n" ), pTriaxialInputLayout ); // モデル表示用の入力レイアウトを作成 D3D11_INPUT_ELEMENT_DESC metasequoiaVerticesDesc[] = { { "IN_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "IN_NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; ID3D11InputLayout * pMetasequoiaInputLayout = NULL; hr = pDevice->CreateInputLayout( metasequoiaVerticesDesc, 2, g_vs_metasequoiaNormal, sizeof( g_vs_metasequoiaNormal ), &pMetasequoiaInputLayout ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR ); return 0; } dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pMetasequoiaInputLayout: 0x%p)\n" ), pMetasequoiaInputLayout ); // ラスタライザステートを生成 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( 500.0f * 1.414214f * -cosf( theta ), 100.0f, 500.0f * 1.414214f * sinf( theta ) ); const D3DXVECTOR3 at( 0.0f, -50.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.25f, 0.5f, 1.0f }; // RGBA pDeviceContext->ClearRenderTargetView( pRenderTargetView, clear ); // デプス・ステンシルビューをクリア pDeviceContext->ClearDepthStencilView( pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 ); ///// 3 軸線の描画 // 頂点バッファをバインド UINT strides[] = { sizeof( float ) * 7 }; UINT offsets[] = { 0 }; pDeviceContext->IASetVertexBuffers( 0, 1, &pTriaxialVertexBuffer, strides, offsets ); // プリミティブタイプを設定 pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST ); // 頂点シェーダをバインド pDeviceContext->VSSetShader( pTriaxialVertexShader, NULL, 0 ); // 入力レイアウトをバインド pDeviceContext->IASetInputLayout( pTriaxialInputLayout ); // 描画 pDeviceContext->Draw( 12, 0 ); ///// モデルの描画 // 頂点バッファをバインド strides[0] = sizeof( float ) * 6; pDeviceContext->IASetVertexBuffers( 0, 1, &pMetasequoiaVertexBuffer, strides, offsets ); // プリミティブタイプを設定 pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); // 頂点シェーダをバインド pDeviceContext->VSSetShader( pMetasequoiaVertexShader, NULL, 0 ); // 入力レイアウトをバインド pDeviceContext->IASetInputLayout( pMetasequoiaInputLayout ); // 描画 pDeviceContext->DrawIndexed( 3 * faces_count, 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( pMetasequoiaInputLayout ); COM_SAFE_RELEASE( pTriaxialInputLayout ); COM_SAFE_RELEASE( pPixelShader ); COM_SAFE_RELEASE( pMetasequoiaVertexShader ); COM_SAFE_RELEASE( pTriaxialVertexShader ); COM_SAFE_RELEASE( pVSConstantBuffer ); COM_SAFE_RELEASE( pTriaxialVertexBuffer ); COM_SAFE_RELEASE( pMetasequoiaIndexBuffer ); COM_SAFE_RELEASE( pMetasequoiaVertexBuffer ); COM_SAFE_RELEASE( pDepthStencilView ); COM_SAFE_RELEASE( pDepthStencilBuffer ); COM_SAFE_RELEASE( pRenderTargetView ); COM_SAFE_RELEASE( pSwapChain ); COM_SAFE_RELEASE( pDeviceContext ); COM_SAFE_RELEASE( pDevice ); // メモリ解放 delete [] metasequoiaVertices; delete [] metasequoiaIndices; return msg.wParam; }
void Render() { static float radius = 20.0f; float timeDelta = 0.1001; if (::GetAsyncKeyState(VK_LEFT) & 0x8000f) g_teapotPosition.x -= 3.0f * timeDelta; if (::GetAsyncKeyState(VK_RIGHT) & 0x8000f) g_teapotPosition.x += 3.0f * timeDelta; if (::GetAsyncKeyState(VK_UP) & 0x8000f) // radius -= 2.0f * timeDelta; g_teapotPosition.z += 3.0f * timeDelta; if (::GetAsyncKeyState(VK_DOWN) & 0x8000f) // radius += 2.0f * timeDelta; g_teapotPosition.z -= 3.0f * timeDelta; static float angle = (3.0f * D3DX_PI) / 2.0f; if (::GetAsyncKeyState('A') & 0x8000f) angle -= 0.5f * timeDelta; if (::GetAsyncKeyState('D') & 0x8000f) angle += 0.5f * timeDelta; D3DXVECTOR3 position(cosf(angle) * radius, 3.0f, sinf(angle) * radius); D3DXVECTOR3 target(0.0f, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH(&V, &position, &target, &up); g_pDevice->SetTransform(D3DTS_VIEW, &V); g_pDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0xff000000, 1.0f, 0); g_pDevice->BeginScene(); g_pDevice->SetMaterial(&g_materalTeapot); g_pDevice->SetTexture(0, 0); D3DXMATRIX W; D3DXMatrixTranslation(&W, g_teapotPosition.x, g_teapotPosition.y, g_teapotPosition.z); g_pDevice->SetTransform(D3DTS_WORLD, &W); g_pMeshTeapot->DrawSubset(0); D3DXMATRIX I; D3DXMatrixIdentity(&I); g_pDevice->SetTransform(D3DTS_WORLD, &I); g_pDevice->SetStreamSource(0, g_pVertexBuffer, 0, sizeof(Vertex)); g_pDevice->SetFVF(Vertex::FVF); g_pDevice->SetTexture(0, g_pTextureFloor); g_pDevice->SetMaterial(&g_materialFloor); g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2); g_pDevice->SetTexture(0, g_pTextureWall); g_pDevice->SetMaterial(&g_materialWall); g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 6, 4); g_pDevice->SetTexture(0, g_pTextureMirror); g_pDevice->SetMaterial(&g_materialMirror); g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 18, 2); RenderMirror(); g_pDevice->EndScene(); g_pDevice->Present(0, 0, 0, 0); }
CWall::CWall(){ D3DXMatrixIdentity(&m_mLocal); m_width = 0; m_depth = 0; m_pMesh = NULL; }
void RenderMirror() { g_pDevice->SetRenderState(D3DRS_STENCILENABLE, true); g_pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS); g_pDevice->SetRenderState(D3DRS_STENCILREF, 0x1); g_pDevice->SetRenderState(D3DRS_STENCILMASK, 0xffffffff); g_pDevice->SetRenderState(D3DRS_STENCILWRITEMASK, 0xffffffff); g_pDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP); g_pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP); g_pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE); // disable writes to the depth and back buffers g_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, false); g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true); g_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO); g_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); // draw the mirror to the stencil buffer g_pDevice->SetStreamSource(0, g_pVertexBuffer, 0, sizeof(Vertex)); g_pDevice->SetFVF(Vertex::FVF); g_pDevice->SetMaterial(&g_materialMirror); g_pDevice->SetTexture(0, g_pTextureMirror); D3DXMATRIX I; D3DXMatrixIdentity(&I); g_pDevice->SetTransform(D3DTS_WORLD, &I); g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 18, 2); // re-enable depth writes g_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, true); // only draw reflected teapot to the pixels where the mirror // was drawn to. g_pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL); g_pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP); // position reflection D3DXMATRIX W, T, R; D3DXPLANE plane(0.0f, 0.0f, 1.0f, 0.0f); // xy plane D3DXMatrixReflect(&R, &plane); D3DXMatrixTranslation(&T, g_teapotPosition.x, g_teapotPosition.y, g_teapotPosition.z); W = T * R; // clear depth buffer and blend the reflected teapot with the mirror g_pDevice->Clear(0, 0, D3DCLEAR_ZBUFFER, 0, 1.0f, 0); g_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR); g_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO); // Finally, draw the reflected teapot g_pDevice->SetTransform(D3DTS_WORLD, &W); g_pDevice->SetMaterial(&g_materalTeapot); g_pDevice->SetTexture(0, 0); g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); g_pMeshTeapot->DrawSubset(0); // Restore render states. g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pDevice->SetRenderState(D3DRS_STENCILENABLE, false); g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);// }
void cPlayer::Setup(cMainGame* game){ m_pGame = game; LPDIRECT3DTEXTURE9 pTexture = NULL; D3DXCreateTextureFromFile( g_pD3DDevice, "../Resource/Iron_Man_Skin_2.png", &pTexture); D3DXMATRIXA16 matPrevT, matPostT; // 몸통 cPart* pPart = new cPart; pPart->Setup(2, 3, 1, cPart::Cube_Part::PT_body); pPart->SetTexture(pTexture); //pCube->SetPosition(D3DXVECTOR3(0, 0, 0)); m_pRoot = pPart; // 머리 pPart = new cPart; pPart->Setup(2, 2, 2, cPart::Cube_Part::PT_head); pPart->SetTexture(pTexture); D3DXMatrixTranslation(&matPrevT, 0, 2.5f, 0); D3DXMatrixIdentity(&matPostT); pPart->SetTransform(matPrevT, matPostT); m_pRoot->AddChild(pPart); // 팔 pPart = new cPart; pPart->Setup(1, 3, 1, cPart::Cube_Part::PT_arm_left); pPart->SetTexture(pTexture); pPart->SetAngleSpeed(4.0f); //pPart->SetPosition(D3DXVECTOR3(-1.5, 0, 0)); D3DXMatrixTranslation(&matPrevT, 0, -1.0, 0); D3DXMatrixTranslation(&matPostT, -1.5, 1.0, 0); pPart->SetTransform(matPrevT, matPostT); m_pRoot->AddChild(pPart); pPart = new cPart; pPart->Setup(1, 2, 1, cPart::Cube_Part::PT_arm_right); pPart->SetTexture(pTexture); pPart->SetAngleSpeed(-4.0f); D3DXMatrixTranslation(&matPrevT, 0, -0.75, 0); D3DXMatrixTranslation(&matPostT, 1.5, 1.25, 0); pPart->SetTransform(matPrevT, matPostT); m_pRoot->AddChild(pPart); cPart* pPart2 = new cPart; pPart2->Setup(1, 1, 1, cPart::Cube_Part::PT_fist); pPart2->SetTexture(pTexture); pPart2->SetAngleSpeed(-4.0f); D3DXMatrixTranslation(&matPrevT, 0, 0, 0); D3DXMatrixTranslation(&matPostT, 0, -1.5f, 0); pPart2->SetTransform(matPrevT, matPostT); pPart->AddChild(pPart2); m_pFist = pPart2; // 다리 pPart = new cPart; pPart->Setup(1, 3, 1, cPart::Cube_Part::PT_leg_left); pPart->SetTexture(pTexture); pPart->SetAngleSpeed(-4.0f); //pPart->SetPosition(D3DXVECTOR3(-0.5, -3, 0)); D3DXMatrixTranslation(&matPrevT, 0, -1.5f, 0); D3DXMatrixTranslation(&matPostT, -0.5, -1.5f, 0); pPart->SetTransform(matPrevT, matPostT); m_pRoot->AddChild(pPart); pPart = new cPart; pPart->Setup(1, 3, 1, cPart::Cube_Part::PT_leg_right); pPart->SetTexture(pTexture); pPart->SetAngleSpeed(4.0f); D3DXMatrixTranslation(&matPrevT, 0, -1.5f, 0); D3DXMatrixTranslation(&matPostT, 0.5, -1.5f, 0); pPart->SetTransform(matPrevT, matPostT); m_pRoot->AddChild(pPart); SAFE_RELEASE(pTexture); }
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, i, numerator, denominator, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; ID3D10Texture2D* backBufferPtr; D3D10_TEXTURE2D_DESC depthBufferDesc; D3D10_DEPTH_STENCIL_DESC depthStencilDesc; D3D10_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D10_VIEWPORT viewport; float fieldOfView, screenAspect; D3D10_RASTERIZER_DESC rasterDesc; // Store the vsync setting. m_vsync_enabled = vsync; //z 2015-07-28 15:23 Creates a DXGI 1.0 factory that you can use to generate other DXGI objects. // Create a DirectX graphics interface factory. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) { return false; } //z 2015-07-28 15:23 Enumerates the adapters (video cards). // Use the factory to create an adapter for the primary graphics interface (video card). /* When you create a factory, the factory enumerates the set of adapters that are available in the system. Therefore, if you change the adapters in a system, you must destroy and recreate the IDXGIFactory object. The number of adapters in a system changes when you add or remove a display card, or dock or undock a laptop. When the EnumAdapters method succeeds and fills the ppAdapter parameter with the address of the pointer to the adapter interface, EnumAdapters increments the adapter interface's reference count. When you finish using the adapter interface, call the Release method to decrement the reference count before you destroy the pointer. EnumAdapters first returns the adapter with the output on which the desktop primary is displayed. This adapter corresponds with an index of zero. EnumAdapters next returns other adapters with outputs. EnumAdapters finally returns adapters without outputs. */ //z 枚举 adapter 的例子 /* UINT i = 0; IDXGIAdapter * pAdapter; std::vector <IDXGIAdapter*> vAdapters; while(pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND) { vAdapters.push_back(pAdapter); ++i; }*/ result = factory->EnumAdapters(0, &adapter); if(FAILED(result)) { return false; } //z 2015-07-28 15:29 Enumerate adapter (video card) outputs. // Enumerating Outputs. Here is an example of how to use EnumOutputs to enumerate all the outputs on an adapter: /* //z UINT i = 0; IDXGIOutput * pOutput; std::vector<IDXGIOutput*> vOutputs; while(pAdapter->EnumOutputs(i, &pOutput) != DXGI_ERROR_NOT_FOUND) { vOutputs.push_back(pOutput); ++i; } */ // Enumerate the primary adapter output (monitor). result = adapter->EnumOutputs(0, &adapterOutput); if(FAILED(result)) { return false; } //z 2015-07-28 15:31 Gets the display modes that match the requested format and other input options. // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). /* pNumModes [in, out] Type: UINT* Set pDesc to NULL so that pNumModes returns the number of display modes that match the format and the options. Otherwise, pNumModes returns the number of display modes returned in pDesc. As shown, this API is designed to be called twice. First to get the number of modes available, and second to return a description of the modes. //z 2015-07-28 15:34 例子 UINT num = 0; DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT; UINT flags = DXGI_ENUM_MODES_INTERLACED; pOutput->GetDisplayModeList( format, flags, &num, 0); ... DXGI_MODE_DESC * pDescs = new DXGI_MODE_DESC[num]; pOutput->GetDisplayModeList( format, flags, &num, pDescs); */ result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if(FAILED(result)) { return false; } // Create a list to hold all the possible display modes for this monitor/video card combination. displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) { return false; } // Now fill the display mode list structures. result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if(FAILED(result)) { return false; } // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the numerator and denominator of the refresh rate for that monitor. for(i=0; i<numModes; i++) { if(displayModeList[i].Width == (unsigned int)screenWidth) { if(displayModeList[i].Height == (unsigned int)screenHeight) { //z 便利 display mode ,设置 numerator 以及 denominator 。 numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } //z 2015-07-28 15:39 Gets a DXGI 1.0 description of an adapter (or video card). /* Graphics driver model determination — Because DXGI is only available on systems with WDDM drivers, the app must first confirm the driver model by using the following API. //z 调用一次,将结果保存起来。 bool HasWDDMDriver() { LPDIRECT3DCREATE9EX pD3D9Create9Ex = NULL; HMODULE hD3D9 = NULL; hD3D9 = LoadLibrary( L"d3d9.dll" ); if ( NULL == hD3D9 ) { return false; } // // Try to create IDirect3D9Ex interface (also known as a DX9L interface). This interface can only be created if the driver is a WDDM driver. pD3D9Create9Ex = (LPDIRECT3DCREATE9EX) GetProcAddress( hD3D9, "Direct3DCreate9Ex" ); return pD3D9Create9Ex != NULL; } */ // Get the adapter (video card) description. result = adapter->GetDesc(&adapterDesc); if(FAILED(result)) { return false; } // Store the dedicated video card memory in megabytes. //z 记录下内存的数量 m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. //z 记住 adapter 的 description error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if(error != 0) { return false; } // Release the display mode list. delete [] displayModeList; displayModeList = 0; // Release the adapter output. //z 释放与获取的顺序相反 adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; // Initialize the swap chain description. ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Set to a single back buffer. swapChainDesc.BufferCount = 1; // Set the width and height of the back buffer. swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; // Set regular 32-bit surface for the back buffer. swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Set the refresh rate of the back buffer. if(m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // Set the usage of the back buffer. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Set the handle for the window to render to. swapChainDesc.OutputWindow = hwnd; // Turn multisampling off. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // Set to full screen or windowed mode. if(fullscreen) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } // Set the scan line ordering and scaling to unspecified. swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Discard the back buffer contents after presenting. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; //z 2015-07-28 16:02 同时创建 device 以及 swapchain 。 // Create the swap chain and the Direct3D device. result = D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0, D3D10_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device); if(FAILED(result)) { return false; } // Get the pointer to the back buffer. result = m_swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&backBufferPtr); if(FAILED(result)) { return false; } // Create the render target view with the back buffer pointer. //z 由 back buffer pointer 创建 render target view。 result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); if(FAILED(result)) { return false; } // Release pointer to the back buffer as we no longer need it. //z 不需要则 release。 backBufferPtr->Release(); backBufferPtr = 0; // Initialize the description of the depth buffer. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // Set up the description of the depth buffer. depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D10_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; //z 创建一个 texture 2d 。 // Create the texture for the depth buffer using the filled out description. result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if(FAILED(result)) { return false; } // Initialize the description of the stencil state. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // Set up the description of the stencil state. depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D10_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing. depthStencilDesc.FrontFace.StencilFailOp = D3D10_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D10_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilDesc.BackFace.StencilFailOp = D3D10_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D10_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D10_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D10_COMPARISON_ALWAYS; // Create the depth stencil state. result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if(FAILED(result)) { return false; } // Set the depth stencil state on the D3D device. m_device->OMSetDepthStencilState(m_depthStencilState, 1); // Initailze the depth stencil view. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); // Set up the depth stencil view description. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth stencil view. result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if(FAILED(result)) { return false; } // Bind the render target view and depth stencil buffer to the output render pipeline. m_device->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); // Setup the raster description which will determine how and what polygons will be drawn. rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D10_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D10_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; // Create the rasterizer state from the description we just filled out. result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if(FAILED(result)) { return false; } // Now set the rasterizer state. m_device->RSSetState(m_rasterState); // Setup the viewport for rendering. viewport.Width = screenWidth; viewport.Height = screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0; viewport.TopLeftY = 0; // Create the viewport. m_device->RSSetViewports(1, &viewport); // Setup the projection matrix. fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // Create the projection matrix for 3D rendering. D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); // Initialize the world matrix to the identity matrix. D3DXMatrixIdentity(&m_worldMatrix); // Create an orthographic projection matrix for 2D rendering. D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); return true; }
void GraphicsEngine::Render() { this->camera.Update(); //////////////CAMERA CODE////////////////////// // Define camera information. /*D3DXVECTOR3 cameraPos(camera.m_pos.x, camera.m_pos.y, camera.m_pos.z); D3DXVECTOR3 lookAtPos(camera.m_view.x, camera.m_view.y, camera.m_view.z); D3DXVECTOR3 upDir(camera.m_up.x, camera.m_up.y, camera.m_up.z);*/ //A Matrix to hold the world transforms of the objects D3DXMATRIX worldTransform; D3DXMatrixIdentity(&worldTransform); // Build view matrix. /*D3DXMatrixLookAtLH(&g_ViewMatrix, &cameraPos, &lookAtPos, &upDir);*/ g_ViewMatrix = *camera.GetViewMatrix(); // Apply the view (camera). g_D3DDevice->SetTransform(D3DTS_VIEW, &g_ViewMatrix); // Set the projection matrix. D3DXMatrixPerspectiveFovLH(&g_projection, 45.0f, WINDOW_WIDTH/WINDOW_HEIGHT, 0.1f, 1000.0f); g_D3DDevice->SetTransform(D3DTS_PROJECTION, &g_projection); //////////////////////END CAMERA CODE/////////// // Clear the backbuffer. g_D3DDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(40,40,40,100), 1.0f, 0); //Sort the Objects By their z value in view space SortBackToFront(); ////////////////////////////////////////////////////////////////////////////// ///////////////////////////BEGIN SCENE//////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Begin the scene. Start rendering. g_D3DDevice->BeginScene(); //Render Skybox static int time = 0; time += 16; g_D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE); g_D3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); D3DXMatrixIdentity(&worldTransform); unsigned int passes; effectMap["HackMapping"]->GetEffect()->Begin(&passes, 0); effectMap["HackMapping"]->GetEffect()->BeginPass(0); GetWorldMtx(&worldTransform, D3DXVECTOR3(gmMgr->graphics_->camera.GetPos().x,gmMgr->graphics_->camera.GetPos().y, gmMgr->graphics_->camera.GetPos().z), D3DXVECTOR3(1,1,1),D3DXVECTOR3(0,time/10000.0f,0)); effectMap["HackMapping"]->GetEffect()->SetMatrix("g_world", &worldTransform); effectMap["HackMapping"]->GetEffect()->SetMatrix("g_wvp", &(worldTransform * g_ViewMatrix * g_projection)); effectMap["HackMapping"]->GetEffect()->SetTexture("g_texture", this->GetTexture("glow")); effectMap["HackMapping"]->GetEffect()->SetTexture("g_normals", textureMap["default"]); effectMap["HackMapping"]->GetEffect()->SetBool("Lighting", false); effectMap["HackMapping"]->GetEffect()->CommitChanges(); skybox->mesh->DrawSubset(0); effectMap["HackMapping"]->GetEffect()->SetBool("Lighting", true); effectMap["HackMapping"]->GetEffect()->CommitChanges(); effectMap["HackMapping"]->GetEffect()->EndPass(); effectMap["HackMapping"]->GetEffect()->End(); g_D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); g_D3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); //} // Clear the backbuffer. g_D3DDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0,0,0,0), 1.0f, 0); // Texture filter. g_D3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); g_D3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_D3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW ); RenderScene(); g_D3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); RenderScene(); RenderText(); if(m_pBGTexture) { //GraphicsEngine::CreateComponent(FOSSA); g_pSprite->Begin(D3DXSPRITE_ALPHABLEND); D3DXMATRIX mat4Transform; D3DXMATRIX mat4OldTransform; D3DXVECTOR2 vec2Scale; vec2Scale.x = static_cast<float>(WINDOW_WIDTH)/1024.f; vec2Scale.y = static_cast<float>(WINDOW_HEIGHT)/1024.f; D3DXVECTOR3 vec3Position(0.0f, 0.0f, 0.0f); g_pSprite->GetTransform(&mat4OldTransform); D3DXMatrixTransformation2D(&mat4Transform, NULL, 0.0f, &vec2Scale, NULL, 0.0f, NULL); g_pSprite->SetTransform(&mat4Transform); g_pSprite->Draw(m_pBGTexture, NULL, NULL, &vec3Position, m_BGColor); g_pSprite->SetTransform(&mat4OldTransform); g_pSprite->End(); } // End the scene. Stop rendering. g_D3DDevice->EndScene(); ////////////////////////////////////////////////////////////////////////////// ///////////////////////////END SCENE////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Display the scene. g_D3DDevice->Present(NULL, NULL, NULL, NULL); }
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, i, numerator, denominator, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; ID3D11Texture2D* backBufferPtr; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; float fieldOfView, screenAspect; D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc; D3D11_BLEND_DESC blendStateDescription; // Store the vsync setting. m_vsync_enabled = vsync; // Create a DirectX graphics interface factory. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) { return false; } // Use the factory to create an adapter for the primary graphics interface (video card). result = factory->EnumAdapters(0, &adapter); if(FAILED(result)) { return false; } // Enumerate the primary adapter output (monitor). result = adapter->EnumOutputs(0, &adapterOutput); if(FAILED(result)) { return false; } // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if(FAILED(result)) { return false; } // Create a list to hold all the possible display modes for this monitor/video card combination. displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) { return false; } // Now fill the display mode list structures. result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if(FAILED(result)) { return false; } // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the numerator and denominator of the refresh rate for that monitor. for(i=0; i<numModes; i++) { if(displayModeList[i].Width == (unsigned int)screenWidth) { if(displayModeList[i].Height == (unsigned int)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } // Get the adapter (video card) description. result = adapter->GetDesc(&adapterDesc); if(FAILED(result)) { return false; } // Store the dedicated video card memory in megabytes. m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if(error != 0) { return false; } // Release the display mode list. delete [] displayModeList; displayModeList = 0; // Release the adapter output. adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; // Initialize the swap chain description. ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Set to a single back buffer. swapChainDesc.BufferCount = 1; // Set the width and height of the back buffer. swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; // Set regular 32-bit surface for the back buffer. swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Set the refresh rate of the back buffer. if(m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // Set the usage of the back buffer. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Set the handle for the window to render to. swapChainDesc.OutputWindow = hwnd; // Turn multisampling off. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // Set to full screen or windowed mode. if(fullscreen) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } // Set the scan line ordering and scaling to unspecified. swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Discard the back buffer contents after presenting. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; // Set the feature level to DirectX 11. featureLevel = D3D_FEATURE_LEVEL_11_0; // Create the swap chain, Direct3D device, and Direct3D device context. result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if(FAILED(result)) { return false; } // Get the pointer to the back buffer. result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if(FAILED(result)) { return false; } // Create the render target view with the back buffer pointer. result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); if(FAILED(result)) { return false; } // Release pointer to the back buffer as we no longer need it. backBufferPtr->Release(); backBufferPtr = 0; // Initialize the description of the depth buffer. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // Set up the description of the depth buffer. depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; // Create the texture for the depth buffer using the filled out description. result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if(FAILED(result)) { return false; } // Initialize the description of the stencil state. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // Set up the description of the stencil state. depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing. depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the depth stencil state. result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if(FAILED(result)) { return false; } // Set the depth stencil state. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); // Initialize the depth stencil view. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); // Set up the depth stencil view description. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth stencil view. result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if(FAILED(result)) { return false; } // Bind the render target view and depth stencil buffer to the output render pipeline. m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); // Setup the raster description which will determine how and what polygons will be drawn. rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; // Create the rasterizer state from the description we just filled out. result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if(FAILED(result)) { return false; } // Now set the rasterizer state. m_deviceContext->RSSetState(m_rasterState); // Setup the viewport for rendering. viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; // Create the viewport. m_deviceContext->RSSetViewports(1, &viewport); // Setup the projection matrix. fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // Create the projection matrix for 3D rendering. D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); // Initialize the world matrix to the identity matrix. D3DXMatrixIdentity(&m_worldMatrix); // Create an orthographic projection matrix for 2D rendering. D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); // Clear the second depth stencil state before setting the parameters. ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc)); // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. The only difference is // that DepthEnable is set to false, all other parameters are the same as the other depth stencil state. depthDisabledStencilDesc.DepthEnable = false; depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthDisabledStencilDesc.StencilEnable = true; depthDisabledStencilDesc.StencilReadMask = 0xFF; depthDisabledStencilDesc.StencilWriteMask = 0xFF; depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the state using the device. result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState); if(FAILED(result)) { return false; } // Clear the blend state description. ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC)); // Create an alpha enabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = TRUE; blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f; // Create the blend state using the description. result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState); if (FAILED(result)) { return false; } // Modify the description to create an alpha disabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = FALSE; // Create the blend state using the description. result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState); if (FAILED(result)) { return false; } return true; }
bool init(IDirect3DDevice9 * pDevice) { HRESULT hr; //hr = D3DXCreateSphere(pDevice, 1.f, 30, 20, &g_pMeshSphere, nullptr); hr = D3DXCreateTeapot(pDevice, &g_pMeshSphere, nullptr); if (FAILED(hr)) { MessageBox(NULL, _T("创建球网格数据失败"), NULL, MB_OK); return false; } //set matrix// //set view D3DXVECTOR3 pos(-1.f, 0.f, -3.f); D3DXVECTOR3 target(0.f, 0.f, 0.f); D3DXVECTOR3 up(0.f, 1.f, 0.f); D3DXMatrixLookAtLH(&g_matrixView, &pos, &target, &up); g_eyePos = pos; //set projection D3DXMatrixPerspectiveFovLH(&g_matrixProjection, D3DX_PI / 4.f, 1.f,/* 400.f / 400.f */ 1.f, 1000.f); //set world matrix D3DXMATRIX temp; D3DXMatrixIdentity(&g_matrixWorld); D3DXMatrixRotationX(&temp, D3DX_PI / 8.f); g_matrixWorld = temp; D3DXMatrixRotationY(&temp, D3DX_PI / 5.f); g_matrixWorld *= temp; D3DXMatrixRotationZ(&temp, D3DX_PI / 4.f); g_matrixWorld *= temp; D3DXMatrixTranslation(&temp, 0.5f, 0.3f, 2.f); g_matrixWorld *= temp; //set worldViewProj matrix g_matrixWorldViewProj = g_matrixWorld * g_matrixView * g_matrixProjection; /* init light */ memset(&g_light, 0, sizeof(g_light)); g_light.Type = D3DLIGHT_POINT; g_light.Ambient = D3DXCOLOR(1.f, 1.f, 1.f,1.f); g_light.Diffuse = D3DXCOLOR(1.f, 1.f, 1.f, 1.f); g_light.Specular = D3DXCOLOR(1.f, 1.f, 1.f, 1.f); g_light.Position = D3DXVECTOR3(-3.f, -1.f, -1.f); g_light.Range = 10000.f; g_light.Attenuation0 = 1.f; //g_light.Attenuation1 = 1.f; //inint material memset(&g_material, 0, sizeof(g_material)); g_material.Ambient = D3DXCOLOR(0.2f, .2f, .2f, 1.f); g_material.Diffuse = D3DXCOLOR(0.4f, .2f, .7f, 1.f); g_material.Specular = D3DXCOLOR(0.2f, .7f, .2f, 1.f); g_material.Power = 10.f; return true; }
Entity::Entity() :mActive(true), mlayer(Layer::NON_COLLIDER), mColliders(nullptr), mCollideData(), mZorder(0), mStatic(false) { D3DXMatrixIdentity(&mWorld); }