//----------------------------------------------------------------------------- // Name: Init() // Desc: //----------------------------------------------------------------------------- HRESULT CParticleSystem::Init( LPDIRECT3DDEVICE9 pd3dDevice ) { HRESULT hr; // Initialize the particle system if( FAILED( hr = RestoreDeviceObjects( pd3dDevice ) ) ) return hr; // Get max point size D3DCAPS9 d3dCaps; pd3dDevice->GetDeviceCaps( &d3dCaps ); m_fMaxPointSize = d3dCaps.MaxPointSize; // Check and see if we can change the size of point sprites // in hardware by sending D3DFVF_PSIZE with the FVF. if( d3dCaps.FVFCaps & D3DFVFCAPS_PSIZE ) m_bDeviceSupportsPSIZE = true; else m_bDeviceSupportsPSIZE = false; // Load Texture Map for particles if( FAILED( D3DXCreateTextureFromFile( pd3dDevice, m_chTexFile, &m_ptexParticle ) ) ) return E_FAIL; return S_OK; }
int CBgDisp2::CheckMultiTexOk( LPDIRECT3DDEVICE9 pd3ddev ) { HRESULT hr; D3DCAPS9 caps8; hr = pd3ddev->GetDeviceCaps( &caps8 ); if( hr != D3D_OK ){ DbgOut( "bgdisp2 : checkmultitexok : GetDeviceCaps error !!!\n" ); _ASSERT( 0 ); return 1; } WORD maxtexblendnum = (WORD)( caps8.FVFCaps & D3DFVFCAPS_TEXCOORDCOUNTMASK ); DWORD maxstages = caps8.MaxTextureBlendStages; DWORD maxsimu = caps8.MaxSimultaneousTextures; DWORD modu = caps8.TextureOpCaps & D3DTEXOPCAPS_MODULATE; DbgOut( "bgdisp2 : CheckMultiTexOk : caps : maxtexcoord %d, maxstages %d, maxsimu %d, moduleop %d\n", maxtexblendnum, maxstages, maxsimu, modu ); if( (maxtexblendnum >= 2) && (maxstages >= 2) && (maxsimu >= 2) && (modu > 0) ){ multitexok = 1; }else{ multitexok = 0; } DbgOut( "bgdisp2 : multitexok %d\n", multitexok ); return 0; }
IHLSLCodeGenerator::CodeVersion DxStdMtl2::GetPixelShaderSupport(LPDIRECT3DDEVICE9 pd3dDevice, DWORD & instSlots) { D3DCAPS9 Caps; IHLSLCodeGenerator::CodeVersion code; pd3dDevice->GetDeviceCaps(&Caps); UINT major = D3DSHADER_VERSION_MAJOR(Caps.PixelShaderVersion); UINT minor = D3DSHADER_VERSION_MINOR(Caps.PixelShaderVersion); instSlots = 96; if(major < 2 ) code = IHLSLCodeGenerator::PS_1_X; else if(major == 2) { instSlots = Caps.PS20Caps.NumInstructionSlots; if(minor > 0) code = IHLSLCodeGenerator::PS_2_X; else code = IHLSLCodeGenerator::PS_2_0; } else if(major >=3) { instSlots = Caps.MaxPixelShader30InstructionSlots; code = IHLSLCodeGenerator::PS_3_0; } else { code = IHLSLCodeGenerator::PS_1_X; } return code; }
BOOL InitD3D(HWND hwnd) { HRESULT hr; D3DDISPLAYMODE disp_mode; D3DPRESENT_PARAMETERS pp; if (g_bSetupOK) return TRUE; if (g_pD3D) return FALSE; g_pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!g_pD3D) return FALSE; hr = g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &disp_mode); if (FAILED(hr)) { g_pD3D->Release(); g_pD3D = NULL; return FALSE; } ZeroMemory(&pp, sizeof(D3DPRESENT_PARAMETERS)); pp.Windowed = true; pp.SwapEffect = D3DSWAPEFFECT_DISCARD; pp.BackBufferFormat = disp_mode.Format; pp.EnableAutoDepthStencil = TRUE; pp.AutoDepthStencilFormat = D3DFMT_D16; pp.BackBufferCount = 1; BOOL flgSoft = GetPrivateProfileInt("GENERIC","LEVEL",1,".\\TDWGame.ini"); char buff[256]; wsprintf(buff,"%d",flgSoft); WritePrivateProfileString("GENERIC","LEVEL",buff,".\\TDWGame.ini"); hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_HARDWARE_VERTEXPROCESSING,&pp,&g_pD3DDevice); if (FAILED(hr)) { hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&pp,&g_pD3DDevice); if (FAILED(hr)) { hr = g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_REF,hwnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&pp,&g_pD3DDevice); if (FAILED(hr)) { g_pD3D->Release(); g_pD3D = NULL; return FALSE; } } } D3DCAPS9 DX9DCaps; g_pD3DDevice->GetDeviceCaps(&DX9DCaps); g_bSetupOK = TRUE; return TRUE; }
bool CDXGraphicsContext::Initialize(HWND hWnd, HWND hWndStatus, uint32 dwWidth, uint32 dwHeight, BOOL bWindowed ) { HRESULT hr; if( g_GraphicsInfo.hStatusBar ) { SetWindowText(g_GraphicsInfo.hStatusBar,"Initializing DirectX Device, please wait"); } Lock(); // Create the Direct3D object m_pD3D = Direct3DCreate9( D3D_SDK_VERSION ); if( m_pD3D == NULL ) { Unlock(); DisplayD3DErrorMsg( D3DAPPERR_NODIRECT3D, MSGERR_APPMUSTEXIT ); return false; } CGraphicsContext::Initialize(hWnd, hWndStatus, dwWidth, dwHeight, bWindowed ); hr = Create3D( bWindowed ); // Clear/Update a few times to ensure that all of the buffers are cleared if ( m_pd3dDevice ) { Clear(CLEAR_COLOR_AND_DEPTH_BUFFER); m_pd3dDevice->BeginScene(); m_pd3dDevice->EndScene(); UpdateFrame(); } D3DVIEWPORT9 vp = { 0, windowSetting.toolbarHeightToUse, windowSetting.uDisplayWidth, windowSetting.uDisplayHeight, 0, 1 }; gD3DDevWrapper.SetViewport(&vp); Unlock(); g_pD3DDev->GetDeviceCaps(&g_D3DDeviceCaps); if( g_GraphicsInfo.hStatusBar ) { SetWindowText(g_GraphicsInfo.hStatusBar,"DirectX device is ready"); } return hr==S_OK; }
bool InitResourceDX9(void) { LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9(); D3DCAPS9 caps; device->GetDeviceCaps(&caps); if ( caps.PixelShaderVersion < D3DPS_VERSION(3,0) ) { printf("Requires Pixel Shader 3.0\n"); return false; } for ( int i=0; i<TEX_TEXTURES; i++ ) { g_pTextures[i] = NULL; g_pSurfaces[i] = NULL; } if ( !ReInitResourceDX9() ) return false; g_pParticleFX = GutLoadFXShaderDX9("../../shaders/GPUParticle.fx"); if ( NULL==g_pParticleFX ) return false; g_pParticleRenderFX = GutLoadFXShaderDX9("../../shaders/GPUParticle_render.fx"); if ( NULL==g_pParticleRenderFX ) return false; g_pPostFX = GutLoadFXShaderDX9("../../shaders/Posteffect.fx"); if ( NULL==g_pPostFX ) return false; g_pNoiseTexture = GutLoadTexture_DX9("../../textures/noise_512x512.tga"); if ( NULL==g_pNoiseTexture ) return false; g_pParticleTexture = GutLoadTexture_DX9("../../textures/particle.tga"); if ( NULL==g_pParticleTexture ) return false; return true; }
/************************************************************************* method to do work of constructor *************************************************************************/ void DirectX9Renderer::constructor_impl(LPDIRECT3DDEVICE9 device, const Size& display_size) { d_device = device; d_queueing = true; d_currTexture = 0; d_buffer = 0; d_bufferPos = 0; // initialise renderer display area d_display_area.d_left = 0; d_display_area.d_top = 0; d_display_area.setSize(display_size); // Create a vertex buffer if (FAILED(d_device->CreateVertexBuffer( (VERTEXBUFFER_CAPACITY * sizeof(QuadVertex)), D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY, VERTEX_FVF, D3DPOOL_DEFAULT, &d_buffer, 0))) { // Ideally, this would have been a RendererException, but we can't use that until the System object is created // and that requires a Renderer passed to the constructor, so we throw this instead. throw std::exception("Creation of VertexBuffer for Renderer object failed"); } // get the maximum available texture size. D3DCAPS9 devCaps; if (FAILED(device->GetDeviceCaps(&devCaps))) { // release vertex buffer d_buffer->Release(); throw std::exception("Unable to retrieve device capabilities from Direct3DDevice9."); } // set max texture size the the smaller of max width and max height. d_maxTextureSize = ceguimin(devCaps.MaxTextureWidth, devCaps.MaxTextureHeight); d_device->AddRef(); // set ID string d_identifierString = "CEGUI::DirectX81Renderer - Official Direct3D 9 based renderer module for CEGUI"; }
//----------------------------------------------------------------------------// Direct3D9Renderer::Direct3D9Renderer(LPDIRECT3DDEVICE9 device) : d_device(device), d_displaySize(getViewportSize()), d_displayDPI(96, 96), d_defaultTarget(0) { D3DCAPS9 caps; device->GetDeviceCaps(&caps); if (!caps.RasterCaps && D3DPRASTERCAPS_SCISSORTEST) CEGUI_THROW(RendererException( "Hardware does not support D3DPRASTERCAPS_SCISSORTEST. " "Unable to proceed.")); d_maxTextureSize = ceguimin(caps.MaxTextureHeight, caps.MaxTextureWidth); d_supportNonSquareTex = !(caps.TextureCaps & D3DPTEXTURECAPS_SQUAREONLY); d_supportNPOTTex = !(caps.TextureCaps & D3DPTEXTURECAPS_POW2) || (caps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL); d_defaultTarget = new Direct3D9ViewportTarget(*this); }
HRESULT HookIDirect3DDevice9::GetDeviceCaps(LPVOID _this, D3DCAPS9* pCaps) { LOG_API(); return pD3Dev->GetDeviceCaps(pCaps); }
INT CrenderTarget::CreateRenderSurface() { HRESULT hr=-1; DWORD dMip = 1; LPDIRECT3DSURFACE9 pSfC = NULL; LPDIRECT3DSURFACE9 pSfD = NULL; D3DSURFACE_DESC dscC; D3DSURFACE_DESC dscD; D3DCAPS9 m_Caps; m_pDev->GetRenderTarget(0,&pSfC); m_pDev->GetDepthStencilSurface(&pSfD); pSfC->GetDesc(&dscC); pSfD->GetDesc(&dscD); m_pDev->GetDeviceCaps(&m_Caps); pSfC->Release(); pSfD->Release(); if(m_iW<0) m_iW = dscC.Width; if(m_iH<0) m_iH = dscC.Height; m_dC = dscC.Format; m_dD = dscD.Format; if(LCX_TARGET_HDR16 == m_nType) m_dC = D3DFMT_A16B16G16R16F; if(LCX_TARGET_HDR32 == m_nType) m_dC = D3DFMT_A32B32G32R32F; hr = D3DXCreateRenderToSurface(m_pDev , m_iW , m_iH , (D3DFORMAT)m_dC , TRUE , (D3DFORMAT)m_dD , &m_pRts); if(FAILED(hr)) return -1; hr = D3DXCreateTexture(m_pDev , m_iW , m_iH , dMip , D3DUSAGE_RENDERTARGET , (D3DFORMAT)m_dC , D3DPOOL_DEFAULT , &m_pTxP); if(FAILED(hr)) return -1; hr = m_pTxP->GetSurfaceLevel(0, &m_pSfc); if(FAILED(hr)) return -1; // Clear 0x0 m_pDev->ColorFill(m_pSfc, NULL, 0x0); return hr; }
bool InitialiseDirectX() { const D3DFORMAT backBufferFormat = D3DFMT_D16; const D3DFORMAT textureFormat = D3DFMT_A8R8G8B8; if(FAILED(d3d = Direct3DCreate9(D3D_SDK_VERSION))) { ShowMessageBox("Direct3D interface creation has failed"); return false; } // Build present params D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); D3DMULTISAMPLE_TYPE antiAliasingLvl; bool antiAliasing = false; if(SUCCEEDED(d3d->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, textureFormat, true, D3DMULTISAMPLE_2_SAMPLES, nullptr))) { d3dpp.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES; antiAliasingLvl = D3DMULTISAMPLE_2_SAMPLES; antiAliasing = true; } d3dpp.hDeviceWindow = hWnd; d3dpp.Windowed = true; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = textureFormat; d3dpp.BackBufferWidth = WINDOW_WIDTH; d3dpp.BackBufferHeight = WINDOW_HEIGHT; d3dpp.EnableAutoDepthStencil = TRUE; d3dpp.AutoDepthStencilFormat = backBufferFormat; if(FAILED(d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &d3ddev))) { ShowMessageBox("Direct3D interface creation has failed"); return false; } // Create Z-buffer if(FAILED(d3ddev->CreateDepthStencilSurface(WINDOW_WIDTH, WINDOW_HEIGHT, backBufferFormat, antiAliasing ? antiAliasingLvl : D3DMULTISAMPLE_NONE, NULL, TRUE, &backBuffer, NULL))) { ShowMessageBox("Z-buffer creation has failed"); return false; } d3ddev->SetRenderTarget(0,backBuffer); // Set render states d3ddev->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, antiAliasing); // Check shader capabilities D3DCAPS9 caps; d3ddev->GetDeviceCaps(&caps); // Check for vertex shader version 2.0 support. if(caps.VertexShaderVersion < D3DVS_VERSION(2, 0)) { ShowMessageBox("Shader model 2.0 or higher is required"); return false; } return true; }
//----------------------------------------------------------------------------- //Desc: 生成蒙皮网格模型(含有每个顶点的混合权重、索引和一个骨骼组合表) //----------------------------------------------------------------------------- HRESULT DexAllocateHierarchy::GenerateGameSkinMesh(LPDIRECT3DDEVICE9 device, stDexMeshContainerEx *pMeshContainer) { getLog()->BeginLog(); HRESULT hr = S_OK; if (pMeshContainer->pSkinInfo == NULL) return hr; _SafeRelease( pMeshContainer->MeshData.pMesh ); _SafeRelease( pMeshContainer->pBoneCombinationBuf ); D3DCAPS9 d3dCaps; device->GetDeviceCaps( &d3dCaps ); UINT MaxMatrices = 26; pMeshContainer->NumPaletteEntries = min(MaxMatrices, pMeshContainer->pSkinInfo->GetNumBones()); DWORD Flags = D3DXMESHOPT_VERTEXCACHE; if (d3dCaps.VertexShaderVersion >= D3DVS_VERSION(1, 1)) { Flags |= D3DXMESH_MANAGED; } else { getLog()->Log(log_allert, ".X Animation file shader 錯誤!"); } //_SafeRelease(pMeshContainer->MeshData.pMesh); if(1) { DWORD NumMaxFaceInfl; DWORD Flags = D3DXMESHOPT_VERTEXCACHE; LPDIRECT3DINDEXBUFFER9 pIB; hr = pMeshContainer->pOrigMesh->GetIndexBuffer( &pIB ); if( FAILED( hr ) ) return hr; hr = pMeshContainer->pSkinInfo->GetMaxFaceInfluences( pIB, pMeshContainer->pOrigMesh->GetNumFaces(), &NumMaxFaceInfl ); pIB->Release(); if( FAILED( hr ) ) return hr; // 12 entry palette guarantees that any triangle (4 independent influences per vertex of a tri) // can be handled NumMaxFaceInfl = min( NumMaxFaceInfl, 12 ); if( d3dCaps.MaxVertexBlendMatrixIndex + 1 < NumMaxFaceInfl ) { // HW does not support indexed vertex blending. Use SW instead pMeshContainer->NumPaletteEntries = min( 256, pMeshContainer->pSkinInfo->GetNumBones() ); Flags |= D3DXMESH_SYSTEMMEM; } else { // using hardware - determine palette size from caps and number of bones // If normals are present in the vertex data that needs to be blended for lighting, then // the number of matrices is half the number specified by MaxVertexBlendMatrixIndex. pMeshContainer->NumPaletteEntries = min( ( d3dCaps.MaxVertexBlendMatrixIndex + 1 ) / 2, pMeshContainer->pSkinInfo->GetNumBones() ); Flags |= D3DXMESH_MANAGED; } hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh ( pMeshContainer->pOrigMesh, Flags, pMeshContainer->NumPaletteEntries, pMeshContainer->pAdjacency, NULL, NULL, NULL, &pMeshContainer->NumInfl, &pMeshContainer->NumAttributeGroups, &pMeshContainer->pBoneCombinationBuf, &pMeshContainer->MeshData.pMesh ); if( FAILED( hr ) ) return hr; return 1; } //生成蒙皮网格模型 hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh ( pMeshContainer->pOrigMesh, Flags, pMeshContainer->NumPaletteEntries, pMeshContainer->pAdjacency, NULL, NULL, NULL, &pMeshContainer->NumInfl, &pMeshContainer->NumAttributeGroups, &pMeshContainer->pBoneCombinationBuf, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) return hr; // FVF has to match our declarator. Vertex shaders are not as forgiving as FF pipeline DWORD NewFVF = (pMeshContainer->MeshData.pMesh->GetFVF() & D3DFVF_POSITION_MASK) | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_LASTBETA_UBYTE4; if (NewFVF != pMeshContainer->MeshData.pMesh->GetFVF()) { LPD3DXMESH pMesh; hr = pMeshContainer->MeshData.pMesh->CloneMeshFVF(pMeshContainer->MeshData.pMesh->GetOptions(), NewFVF, device, &pMesh); if (!FAILED(hr)) { pMeshContainer->MeshData.pMesh->Release(); pMeshContainer->MeshData.pMesh = pMesh; pMesh = NULL; } } D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE]; LPD3DVERTEXELEMENT9 pDeclCur; hr = pMeshContainer->MeshData.pMesh->GetDeclaration(pDecl); if (FAILED(hr)) return hr; // the vertex shader is expecting to interpret the UBYTE4 as a D3DCOLOR, so update the type // NOTE: this cannot be done with CloneMesh, that would convert the UBYTE4 data to float and then to D3DCOLOR // this is more of a "cast" operation pDeclCur = pDecl; while (pDeclCur->Stream != 0xff) { if ((pDeclCur->Usage == D3DDECLUSAGE_BLENDINDICES) && (pDeclCur->UsageIndex == 0)) pDeclCur->Type = D3DDECLTYPE_D3DCOLOR; pDeclCur++; } hr = pMeshContainer->MeshData.pMesh->UpdateSemantics(pDecl); if (FAILED(hr)) return hr; // allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger if( m_NumBoneMatricesMax < pMeshContainer->pSkinInfo->GetNumBones() ) { m_NumBoneMatricesMax = pMeshContainer->pSkinInfo->GetNumBones(); // Allocate space for blend matrices delete[] m_pBoneMatrices; m_pBoneMatrices = new D3DXMATRIX[m_NumBoneMatricesMax]; if( m_pBoneMatrices == NULL ) { hr = E_OUTOFMEMORY; return hr; } } return hr; }
//----------------------------------------------------------------------------- // Name: create // Desc: Initializes the font //----------------------------------------------------------------------------- bool GUIFont::create(LPDIRECT3DDEVICE9 d3dDevice, const char* fontName, DWORD height, bool bold, bool italic) { // Validate parameters if (!d3dDevice || !fontName || !height) return false; // Make sure the font is clear destroy(); // These variables are used within this method HFONT hFont = NULL; HFONT hFontOld = NULL; HDC hDC = NULL; HBITMAP hbmBitmap = NULL; HGDIOBJ hbmOld = NULL; // Assume that fonts drawn onto the texture do not need scaling unless the texture size // required is larger than the device's maximum myTextScale = 1.0f; // Create a device context for text to draw into hDC = CreateCompatibleDC(NULL); SetMapMode(hDC, MM_TEXT); // Generate the font if (!createGDIFont(hDC, &hFont, fontName, height, bold, italic )) { // Free our context DeleteDC(hDC); // Return failure return false; } // Set this new font up for use (but store the old one so we can restore it later hFontOld = (HFONT)SelectObject(hDC, hFont); // Get this device's ability information D3DCAPS9 d3dCaps; d3dDevice->GetDeviceCaps(&d3dCaps); // Usually the required texture is at least 128x128 pixels. myTexWidth = myTexHeight = 128; // Holds the result of painting the font PaintAlphabetResult par; // Calculate the size of the smallest power-of-two texture which will hold all the // printable characters we need. First, we try making the texture larger until it gets // bigger than the device can support. Then, we scale down the text to fit the largest // texture. do { // If the texture size matches the device's maximum and we've started another // iteration, that means the text is too big. Scale it down. if (myTexWidth == d3dCaps.MaxTextureWidth) myTextScale *= 0.9f; // If this texture is smaller than the device's maximum size, scale it up if (myTexWidth < d3dCaps.MaxTextureWidth) { myTexWidth *= 2; myTexHeight *= 2; } // If the texture is larger than the device can support, scale the text a bit and // make the texture the maximum size. if (myTexWidth > d3dCaps.MaxTextureWidth) { // Calculate the text scaling amount myTextScale = (float)d3dCaps.MaxTextureWidth / (float)myTexWidth; myTexWidth = myTexHeight = d3dCaps.MaxTextureWidth; } // If we are at the maximum sized texture, the text has been scaled so it needs to // be recreated. if (myTexWidth == d3dCaps.MaxTextureWidth) { // Get rid of the new font and put the old font back in DeleteObject(SelectObject(hDC, hFontOld)); // Create the new font if (!createGDIFont(hDC, &hFont, fontName, height, bold, italic)) { // Free information DeleteDC(hDC); // Return failure return false; } // Select the new font hFontOld = (HFONT)SelectObject(hDC, hFont); } } while(PAR_FAILED_NOTENOUGHSPACE == (par = paintAlphabet(hDC, true))); // Check to make sure the function didn't fail if (par != PAR_SUCCEEDED) { // Put the old font back into the device context SelectObject(hDC, hFontOld); // Delete used information DeleteObject(hFont); DeleteDC(hDC); // Erase internal info zero(); // This method failed return false; } // Create the font's texture if (FAILED(d3dDevice->CreateTexture(myTexWidth, myTexHeight, 1, 0, D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, &myTexture, NULL))) { // Put the old font back into the device context SelectObject(hDC, hFontOld); // Delete used information DeleteObject(hFont); DeleteDC(hDC); // Erase internal info zero(); // Return failure return false; } // Prepare to create the bitmap DWORD* bitmapBits; BITMAPINFO bmi; ZeroMemory(&bmi.bmiHeader, sizeof(BITMAPINFOHEADER)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = (int)myTexWidth; bmi.bmiHeader.biHeight = -(int)myTexHeight; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biBitCount = 32; // Create a bitmap for the font hbmBitmap = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, (void**)&bitmapBits, NULL, 0); hbmOld = SelectObject(hDC, hbmBitmap); // Set up the text properties SetTextColor(hDC, RGB(255,255,255)); SetBkColor( hDC, 0x00000000); SetTextAlign(hDC, TA_TOP); // Actually draw the alphabet if (PAR_SUCCEEDED != paintAlphabet(hDC, false)) { // Get rid of created Windows information SelectObject(hDC, hbmOld); SelectObject(hDC, hFontOld); DeleteObject(hbmBitmap); DeleteObject(hFont); DeleteDC(hDC); // Free internal data destroy(); // Return error return false; } // Lock the surface and manually write the alpha values for the pixels D3DLOCKED_RECT d3dlr; if (FAILED(myTexture->LockRect(0, &d3dlr, 0, 0))) { // Get rid of created Windows information SelectObject(hDC, hbmOld); SelectObject(hDC, hFontOld); DeleteObject(hbmBitmap); DeleteObject(hFont); DeleteDC(hDC); // Free internal data destroy(); // Return error return false; } // This data is used to fill in the texture BYTE* destRow; destRow = (BYTE*)d3dlr.pBits; WORD* dest16; BYTE alpha; DWORD x, y; // Write the alpha values for (y = 0; y < myTexHeight; ++y) { dest16 = (WORD*)destRow; for (x = 0; x < myTexWidth; ++x) { // Determine whether or not a pixel was written here alpha = (BYTE)((bitmapBits[myTexWidth * y + x] & 0xFF) >> 4); // Write the alpha value if (alpha > 0) *dest16++ = ((WORD)(alpha << 12) | 0x0FFF); // updated to remove alpha b/c it causes rendering artifacts else *dest16++ = 0x0000; } // Move to the next row destRow += d3dlr.Pitch; } // Unlock the texture myTexture->UnlockRect(0); // Restore states and delete temporary information SelectObject(hDC, hbmOld); SelectObject(hDC, hFontOld); DeleteObject(hbmBitmap); DeleteObject(hFont); DeleteDC(hDC); // Success return true; }
HRESULT KG3DGraphicsEngine::InitDevice(UINT uAdapter, D3DDEVTYPE DeviceType, HWND hwnd) { HRESULT hr = S_OK; DWORD dwBehaviorFlags = 0;//D3DCREATE_MULTITHREADED; D3DPRESENT_PARAMETERS PresentParam; memcpy(&PresentParam, &m_PresentParam, sizeof(D3DPRESENT_PARAMETERS)); _ASSERTE(g_pd3dDevice == NULL); hr = m_pD3D->CreateDevice(uAdapter, DeviceType, hwnd, D3DCREATE_MIXED_VERTEXPROCESSING | dwBehaviorFlags, &PresentParam, &g_pd3dDevice); KG_COM_PROCESS_SUCCESS(hr); memcpy(&PresentParam, &m_PresentParam, sizeof(D3DPRESENT_PARAMETERS)); hr = m_pD3D->CreateDevice(uAdapter, DeviceType, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING | dwBehaviorFlags, &PresentParam, &g_pd3dDevice); KG_COM_PROCESS_SUCCESS(hr); memcpy(&PresentParam, &m_PresentParam, sizeof(D3DPRESENT_PARAMETERS)); hr = m_pD3D->CreateDevice(uAdapter, DeviceType, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING | dwBehaviorFlags, &PresentParam, &g_pd3dDevice); KG_COM_PROCESS_SUCCESS(hr); KGLOG_COM_PROCESS_ERROR(hr); KGLOG_PROCESS_ERROR(g_pd3dDevice); Exit1: memcpy(&m_PresentParam, &PresentParam, sizeof(D3DPRESENT_PARAMETERS)); //检查设备能力 { ZeroMemory(&m_EngineCaps, sizeof(m_EngineCaps)); HRESULT hrTemp = g_pd3dDevice->GetDeviceCaps(&m_EngineCaps.D3DCaps); if (SUCCEEDED(hrTemp)) { for (size_t i = 0; i < _countof(m_EngineCaps.IsShadowTypeAvailable); ++i) { m_EngineCaps.IsShadowTypeAvailable[i] = TRUE; } m_EngineCaps.IsShadowTypeAvailable[EM_MODEL_SHADOW_TYPE_LOW] = (m_EngineCaps.D3DCaps.StencilCaps & D3DSTENCILCAPS_INCR) && (m_EngineCaps.D3DCaps.StencilCaps & D3DSTENCILCAPS_DECR); //其它类型的影子的能力检查还没有写 } else { KGLogPrintf(KGLOG_WARNING, "无法得到设备信息,可能显示不正常"); } } Exit0: if (hr == D3DERR_DEVICELOST) m_bDeviceLost = true; else KGLOG_COM_CHECK_ERROR(hr); return hr; }
virtual const char* open( unsigned buffer_width, unsigned buffer_height, HWND hWnd ) { if ( this->hWnd ) return "Display already open"; this->hWnd = hWnd; lpd3d = Direct3DCreate9( D3D_SDK_VERSION ); if ( ! lpd3d ) return "Creating Direct3D 9 object"; D3DDISPLAYMODE mode; lpd3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, & mode ); ZeroMemory(&dpp, sizeof(dpp)); dpp.Flags = D3DPRESENTFLAG_VIDEO; dpp.SwapEffect = D3DSWAPEFFECT_FLIP; dpp.hDeviceWindow = hWnd; dpp.BackBufferCount = 1; dpp.MultiSampleType = D3DMULTISAMPLE_NONE; dpp.MultiSampleQuality = 0; dpp.EnableAutoDepthStencil = false; dpp.AutoDepthStencilFormat = D3DFMT_UNKNOWN; dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; dpp.Windowed = TRUE; dpp.BackBufferFormat = D3DFMT_UNKNOWN; dpp.BackBufferWidth = 640; dpp.BackBufferHeight = 480; if ( lpd3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, & dpp, & lpdev ) != D3D_OK ) return "Creating Direct3D 9 device object"; lpdev->GetDeviceCaps(&d3dcaps); bool dynamic = !!(d3dcaps.Caps2 & D3DCAPS2_DYNAMICTEXTURES); if(dynamic) { flags.t_usage = D3DUSAGE_DYNAMIC; flags.v_usage = D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC; flags.t_pool = D3DPOOL_DEFAULT; flags.v_pool = D3DPOOL_DEFAULT; flags.lock = D3DLOCK_NOSYSLOCK | D3DLOCK_DISCARD; } else { flags.t_usage = 0; flags.v_usage = D3DUSAGE_WRITEONLY; flags.t_pool = D3DPOOL_MANAGED; flags.v_pool = D3DPOOL_MANAGED; flags.lock = D3DLOCK_NOSYSLOCK | D3DLOCK_DISCARD; } input_width = buffer_width; input_height = buffer_height; surface_width = rounded_power_of_two( buffer_width ); surface_height = rounded_power_of_two( buffer_height ); if ( surface_width > d3dcaps.MaxTextureWidth || surface_height > d3dcaps.MaxTextureHeight ) return "Device texture size limit is too small"; restore_objects(); update_position(); clear(); retry_count = 0; return 0; }
HRESULT InitScene() { HRESULT hr; D3DCAPS9 caps; SetWindowText(hwnd, TITLE); device->GetDeviceCaps(&caps); if( caps.VertexShaderVersion < D3DVS_VERSION(2, 0) || caps.PixelShaderVersion < D3DPS_VERSION(2, 0) ) { MYERROR("This demo requires Shader Model 2.0 capable video card"); return E_FAIL; } palm = new DXObject(device); sandplane = new DXObject(device); waterplane = new DXObject(device); if( !palm->Load("../media/meshes/palm.qm") ) { MYERROR("Could not load palm"); return E_FAIL; } if( !sandplane->CreatePlane(50, 50, 10, 10) ) { MYERROR("Could not create sand plane"); return E_FAIL; } if( !waterplane->CreatePlane(50, 50, 5, 5) ) { MYERROR("Could not create water plane"); return E_FAIL; } waterplane->GenerateTangentFrame(); MYVALID(D3DXLoadMeshFromXA("../media/meshes/sky.X", D3DXMESH_MANAGED, device, NULL, NULL, NULL, NULL, &skymesh)); MYVALID(D3DXCreateCubeTextureFromFileA(device, "../media/textures/sky7.dds", &skytex)); MYVALID(D3DXCreateTextureFromFileA(device, "../media/textures/bark.jpg", &bark)); MYVALID(D3DXCreateTextureFromFileA(device, "../media/textures/leaf.jpg", &leaves)); MYVALID(D3DXCreateTextureFromFileA(device, "../media/textures/sand.jpg", &sand)); MYVALID(D3DXCreateTextureFromFileA(device, "../media/textures/wave2.png", &waves)); MYVALID(DXCreateEffect("../media/shaders/ambient.fx", device, &ambient)); MYVALID(DXCreateEffect("../media/shaders/blinnphong.fx", device, &specular)); MYVALID(DXCreateEffect("../media/shaders/water.fx", device, &water)); MYVALID(DXCreateEffect("../media/shaders/simplebloom.fx", device, &bloom)); MYVALID(DXCreateEffect("../media/shaders/godray.fx", device, &godray)); MYVALID(DXCreateEffect("../media/shaders/sky.fx", device, &skyeffect)); MYVALID(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, &refraction, NULL)); MYVALID(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A16B16G16R16F, D3DPOOL_DEFAULT, &reflection, NULL)); MYVALID(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8, D3DPOOL_DEFAULT, &occluders, NULL)); MYVALID(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8, D3DPOOL_DEFAULT, &blurtex, NULL)); MYVALID(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &sceneldr, NULL)); MYVALID(device->CreateTexture(screenwidth / 2, screenheight / 2, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bloomtex1, NULL)); MYVALID(device->CreateTexture(screenwidth / 2, screenheight / 2, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bloomtex2, NULL)); refraction->GetSurfaceLevel(0, &refractsurf); reflection->GetSurfaceLevel(0, &reflectsurf); occluders->GetSurfaceLevel(0, &occludersurf); blurtex->GetSurfaceLevel(0, &blursurf); sceneldr->GetSurfaceLevel(0, &sceneldrsurf); bloomtex1->GetSurfaceLevel(0, &bloomsurf1); bloomtex2->GetSurfaceLevel(0, &bloomsurf2); D3DVERTEXELEMENT9 elem[] = { { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 16, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; MYVALID(device->CreateVertexDeclaration(elem, &quaddecl)); cameraangle = D3DXVECTOR2(-1.13f * D3DX_PI, 0.55f); return S_OK; }
HRESULT cFont::InitDeviceObjects(LPDIRECT3DDEVICE9 pDevice) { HRESULT hr; this->m_pDevice= pDevice; m_fTextScale = 1.0f; if (dwFontHeight > 40)dwWidth = dwHeight = 1024; else if (dwFontHeight > 20)dwWidth = dwHeight = 512; else dwWidth = dwHeight = 256; D3DCAPS9 d3dCaps; pDevice->GetDeviceCaps(&d3dCaps); if (dwWidth > d3dCaps.MaxTextureWidth) { m_fTextScale = (FLOAT)d3dCaps.MaxTextureWidth / (FLOAT)dwWidth; dwWidth =dwHeight = d3dCaps.MaxTextureWidth; } hr = pDevice->CreateTexture(dwWidth, dwHeight, 1,0, D3DFMT_A4R4G4B4,D3DPOOL_MANAGED, &m_pTexture, 0); if (FAILED(hr))return hr; DWORD* pBitmapBits; BITMAPINFO bmi; ZeroMemory(&bmi.bmiHeader, sizeof(BITMAPINFOHEADER)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = (int)dwWidth; bmi.bmiHeader.biHeight = -(int)dwHeight; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biBitCount = 32; HDC hDC = CreateCompatibleDC(NULL); HBITMAP hbmBitmap = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, (void**)&pBitmapBits, NULL, 0); SetMapMode(hDC, MM_TEXT); INT nHeight = -MulDiv(dwFontHeight, (INT)(GetDeviceCaps(hDC, LOGPIXELSY) * m_fTextScale), 72); DWORD dwBold = (dwFontFlags & D3DFONT_BOLD) ? FW_EXTRABOLD : FW_NORMAL; DWORD dwItalic = (dwFontFlags & D3DFONT_ITALIC) ? TRUE : FALSE; HFONT hFont = CreateFont(nHeight, 0, 0, 0, dwBold, dwItalic, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, strFontName); if (NULL == hFont) return E_FAIL; HGDIOBJ hPrevBitmap = SelectObject(hDC, hbmBitmap); HGDIOBJ hPrevFont = SelectObject(hDC, hFont); SetTextColor(hDC, RGB(255, 255, 255)); SetBkColor(hDC, 0x00000000); SetTextAlign(hDC, TA_TOP); DWORD x = 0; DWORD y = 0; char str[2] = "x"; SIZE size; for (int c = 32; c <= MAX_CHAR_INDEX; c++) { str[0] = c; GetTextExtentPoint32A(hDC, str, 1, &size); if ((DWORD)(x + size.cx + 1) > dwWidth) { x = 0; y += size.cy + 1; } ExtTextOutA(hDC, x + 0, y + 0, ETO_OPAQUE, NULL, str, 1, NULL); m_fTexCoords[c - 32][0] = ((FLOAT)(x + 0)) / dwWidth; m_fTexCoords[c - 32][1] = ((FLOAT)(y + 0)) / dwWidth; m_fTexCoords[c - 32][2] = ((FLOAT)(x + 0 + size.cx)) / dwWidth; m_fTexCoords[c - 32][3] = ((FLOAT)(y + 0 + size.cy)) / dwWidth; x += size.cx + 1; } D3DLOCKED_RECT d3dlr; m_pTexture->LockRect(0, &d3dlr, 0, 0); BYTE* pDstRow = (BYTE*)d3dlr.pBits; WORD* pDst16; BYTE bAlpha; for (y = 0; y < dwHeight; y++) { pDst16 = (WORD*)pDstRow; for (x = 0; x < dwWidth; x++) { bAlpha = (BYTE)((pBitmapBits[dwWidth*y + x] & 0xff) >> 4); if (bAlpha > 0) { *pDst16++ = (bAlpha << 12) | 0x0fff; } else { *pDst16++ = 0x0000; } } pDstRow += d3dlr.Pitch; } m_pTexture->UnlockRect(0); SelectObject(hDC, hPrevBitmap); SelectObject(hDC, hPrevFont); DeleteObject(hbmBitmap); DeleteDC(hDC); DeleteObject(hFont); return S_OK; }