void CDX10Core::InitRenderAndDepthStencilTargets(int width, int height) { ID3D10Texture2D* pBuffer = NULL; HR( m_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBuffer ) ); // Create a render target view HR( m_pDevice->CreateRenderTargetView( pBuffer, NULL, &m_pRenderTargetView ) ); pBuffer->Release(); // Create DepthStencil target view D3D10_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = width; depthStencilDesc.Height = height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D10_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; HR( m_pDevice->CreateTexture2D( &depthStencilDesc, 0, &pBuffer ) ); HR( m_pDevice->CreateDepthStencilView( pBuffer, 0, &m_pDepthStencilView ) ); pBuffer->Release(); m_pDevice->OMSetRenderTargets( 1, &m_pRenderTargetView, m_pDepthStencilView ); }
void D10State::newTexture(unsigned int w, unsigned int h) { HRESULT hr; ods("D3D10: newTexture %d %d", w, h); if (pTexture) { pTexture->Release(); pTexture = NULL; } if (pSRView) { pSRView->Release(); pSRView = NULL; } D3D10_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = w; desc.Height = h; desc.MipLevels = desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D10_USAGE_DYNAMIC; desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; hr = pDevice->CreateTexture2D(&desc, NULL, &pTexture); if (FAILED(hr)) { pTexture = NULL; ods("D3D10: Failed to create texture."); return; } D3D10_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = desc.Format; srvDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = desc.MipLevels; hr = pDevice->CreateShaderResourceView(pTexture, &srvDesc, &pSRView); if (FAILED(hr)) { pSRView = NULL; pTexture->Release(); pTexture = NULL; ods("D3D10: Failed to create resource view."); return; } }
bool Engine::D3DViewPortSetup( UINT width, UINT height ) { HRESULT hr = S_OK; // Create a render target view ID3D10Texture2D* pBackBuffer; hr = mySwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return false; ID3D10RenderTargetView* tempRenderTarget; hr = my3DDevice->CreateRenderTargetView( pBackBuffer, NULL, &tempRenderTarget ); pBackBuffer->Release(); if( FAILED( hr ) ) return false; myBackBufferRenderTargetView = tempRenderTarget; // Setup the viewport D3D10_VIEWPORT vp; vp.Width = width; vp.Height = height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; my3DDevice->RSSetViewports( 1, &vp ); if( SUCCEEDED( hr ) ) { return true; } else { false; } }
//======================================================================== // Returns default RenderTarget. Member of AbstractRender //======================================================================== RenderTarget *DX10Render::getScreenRenderTarget() { DX10RenderTarget *renderTarget = new DX10RenderTarget(); ID3D10Texture2D *texture; HRESULT hr = swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (void**)&texture); if (FAILED(hr)) { delete renderTarget; return NULL; } hr = device->CreateRenderTargetView(texture, NULL, &renderTarget->renderTargetView); if (FAILED(hr)) { delete renderTarget; return NULL; } texture->Release(); renderTarget->width = resolution.width; renderTarget->height = resolution.height; return renderTarget; }
void CreateRenderTarget() { ID3D10Texture2D* pBackBuffer; g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); pBackBuffer->Release(); }
static bool grabFrameD3D10(IDXGISwapChain *swap) { ID3D10Device *device = 0; ID3D10Texture2D *tex = 0, *captureTex = 0; if (FAILED(swap->GetBuffer(0, IID_ID3D10Texture2D, (void**)&tex))) return false; D3D10_TEXTURE2D_DESC desc; tex->GetDevice(&device); tex->GetDesc(&desc); // re-creating the capture staging texture each frame is definitely not the most efficient // way to handle things, but it frees me of all kind of resource management trouble, so // here goes... desc.MipLevels = 1; desc.ArraySize = 1; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = D3D10_USAGE_STAGING; desc.BindFlags = 0; desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ; desc.MiscFlags = 0; if(FAILED(device->CreateTexture2D(&desc,0,&captureTex))) printLog("video/d3d10: couldn't create staging texture for gpu->cpu download!\n"); else setCaptureResolution(desc.Width,desc.Height); if(device) device->CopySubresourceRegion(captureTex,0,0,0,0,tex,0,0); D3D10_MAPPED_TEXTURE2D mapped; bool grabOk = false; if(captureTex && SUCCEEDED(captureTex->Map(0,D3D10_MAP_READ,0,&mapped))) { switch(desc.Format) { case DXGI_FORMAT_R8G8B8A8_UNORM: blitAndFlipRGBAToCaptureData((unsigned char *) mapped.pData,mapped.RowPitch); grabOk = true; break; default: printLog("video/d3d10: unsupported backbuffer format, can't grab pixels!\n"); break; } captureTex->Unmap(0); } tex->Release(); if(captureTex) captureTex->Release(); if(device) device->Release(); return grabOk; }
static void ImGui_ImplDX10_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D10_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D10_USAGE_DEFAULT; desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D10Texture2D *pTexture = NULL; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); // Create texture view D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc; ZeroMemory(&srv_desc, sizeof(srv_desc)); srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srv_desc.Texture2D.MipLevels = desc.MipLevels; srv_desc.Texture2D.MostDetailedMip = 0; g_pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &g_pFontTextureView); pTexture->Release(); } // Store our identifier io.Fonts->TexID = (ImTextureID)g_pFontTextureView; // Create texture sampler { D3D10_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler); } }
void TextureHandler::addTexture(std::string fileName, std::string textureName) { ID3D10ShaderResourceView * rv; ID3D10Texture2D * GPUTexture; ID3D10Texture2D * CPUTexture; HRESULT hr = D3DX10CreateTextureFromFile(mpDevice, fileName.c_str(), NULL, NULL, (ID3D10Resource**)&GPUTexture, NULL ); if(FAILED(hr)) { DEBUG_MESSAGE("Failed to create GPU texture from file: "<<fileName); return; } D3DX10_IMAGE_LOAD_INFO loadInfo; ZeroMemory(&loadInfo,sizeof(D3DX10_IMAGE_LOAD_INFO)); loadInfo.Width = D3DX10_DEFAULT; loadInfo.Height = D3DX10_DEFAULT; loadInfo.BindFlags = 0; loadInfo.Depth = D3DX10_DEFAULT; loadInfo.Filter = D3DX10_DEFAULT; loadInfo.FirstMipLevel = D3DX10_DEFAULT; loadInfo.Format = DXGI_FORMAT_FROM_FILE; loadInfo.MipFilter = D3DX10_DEFAULT; loadInfo.MiscFlags = D3DX10_DEFAULT; loadInfo.pSrcInfo = 0; loadInfo.Usage = D3D10_USAGE_STAGING; loadInfo.CpuAccessFlags = D3D10_CPU_ACCESS_READ; hr = D3DX10CreateTextureFromFile(mpDevice, fileName.c_str(), &loadInfo, NULL, (ID3D10Resource**)&CPUTexture, NULL ); if(FAILED(hr)) { DEBUG_MESSAGE("Failed to create CPU texture from file: "<<fileName); return; } D3D10_TEXTURE2D_DESC texDesc; GPUTexture->GetDesc(&texDesc); D3D10_SHADER_RESOURCE_VIEW_DESC viewDesc; viewDesc.Format = texDesc.Format; viewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; viewDesc.Texture2D.MipLevels = 1; viewDesc.Texture2D.MostDetailedMip = 0; hr = mpDevice->CreateShaderResourceView(GPUTexture,&viewDesc,&rv); GPUTexture->Release(); if(FAILED(hr)) { DEBUG_MESSAGE("Failed to create GPU resource View. Filename: "<<fileName); return; } mTextures.push_back(myNew Texture(rv,CPUTexture,textureName)); }
bool Render::initDirect3D(HWND& mWnd, int width, int height, int windowed) { // _*_ Create Device and Swap Chain _*_ DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = mWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = windowed; HRESULT hres = D3D10CreateDeviceAndSwapChain(0, D3D10_DRIVER_TYPE_HARDWARE, 0, 0, D3D10_SDK_VERSION, &sd, &g_swap_chain, &g_device); // _*_ Create Render View _*_ ID3D10Texture2D* tBackBuffer; ID3D10Texture2D* tDepthStencilBuffer; D3D10_TEXTURE2D_DESC descDepthStencil; g_swap_chain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&tBackBuffer); g_device->CreateRenderTargetView(tBackBuffer, 0, &g_render_view); tBackBuffer->Release(); // _*_ Create Depth Stencil View _*_ descDepthStencil.Width = width; descDepthStencil.Height = height; descDepthStencil.ArraySize = 1; descDepthStencil.BindFlags = D3D10_BIND_DEPTH_STENCIL; descDepthStencil.CPUAccessFlags = 0; descDepthStencil.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepthStencil.MipLevels = 1; descDepthStencil.MiscFlags = 0; descDepthStencil.SampleDesc.Count = 1; descDepthStencil.SampleDesc.Quality = 0; descDepthStencil.Usage = D3D10_USAGE_DEFAULT; if (FAILED(g_device->CreateTexture2D(&descDepthStencil, 0, &tDepthStencilBuffer))) return false; if (FAILED(g_device->CreateDepthStencilView(tDepthStencilBuffer, 0, &g_depth_stencil_view))) return false; // _*_ Create a Viewport _*_ vp.Width = width; vp.Height = height; vp.MinDepth = 0; vp.MaxDepth = 1; vp.TopLeftX = 0; vp.TopLeftY = 0; g_device->RSSetViewports(1, &vp); return true; }
void GraphicsDevice::CreateRenderTarget() { ID3D10Texture2D *pBackbuffer = nullptr; HR( m_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), reinterpret_cast<void**>(&pBackbuffer)) ); m_pRenderTarget = m_pDefaultRenderTarget = new RenderTarget2D(); m_pRenderTarget->Create(pBackbuffer); pBackbuffer->Release(); }
HRESULT CheckRenderD3D10::ResourceToPPM(ID3D10Device *pDevice, ID3D10Resource *pResource, const char *zFileName) { D3D10_RESOURCE_DIMENSION rType; pResource->GetType(&rType); if (rType != D3D10_RESOURCE_DIMENSION_TEXTURE2D) { printf("SurfaceToPPM: pResource is not a 2D texture! Aborting...\n"); return E_FAIL; } ID3D10Texture2D *pSourceTexture = (ID3D10Texture2D *)pResource; ID3D10Texture2D *pTargetTexture = NULL; D3D10_TEXTURE2D_DESC desc; pSourceTexture->GetDesc(&desc); desc.BindFlags = 0; desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ; desc.Usage = D3D10_USAGE_STAGING; if (FAILED(pDevice->CreateTexture2D(&desc,NULL,&pTargetTexture))) { printf("SurfaceToPPM: Unable to create target Texture resoruce! Aborting... \n"); return E_FAIL; } pDevice->CopyResource(pTargetTexture,pSourceTexture); D3D10_MAPPED_TEXTURE2D mappedTex2D; pTargetTexture->Map(0,D3D10_MAP_READ,0,&mappedTex2D); // Need to convert from dx pitch to pitch=width unsigned char *pPPMData = new unsigned char[desc.Width*desc.Height*4]; for (unsigned int iHeight = 0; iHeight<desc.Height; iHeight++) { memcpy(&(pPPMData[iHeight*desc.Width*4]),(unsigned char *)(mappedTex2D.pData)+iHeight*mappedTex2D.RowPitch,desc.Width*4); } pTargetTexture->Unmap(0); // Prepends the PPM header info and bumps byte data afterwards sdkSavePPM4ub(zFileName, pPPMData, desc.Width, desc.Height); delete [] pPPMData; pTargetTexture->Release(); return S_OK; }
void CreateRenderTarget() { DXGI_SWAP_CHAIN_DESC sd; g_pSwapChain->GetDesc(&sd); // Create the render target ID3D10Texture2D* pBackBuffer; D3D10_RENDER_TARGET_VIEW_DESC render_target_view_desc; ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc)); render_target_view_desc.Format = sd.BufferDesc.Format; render_target_view_desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D; g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView); g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); pBackBuffer->Release(); }
//========================================================================== // Special constructor for screen render target //========================================================================== HRESULT RenderTarget::initScreenRenderTarget() { this->width = D3D10.getScreenX(); this->height = D3D10.getScreenY(); this->count = 1; this->cubeMap = false; ID3D10Texture2D* tex = NULL; HRESULT hr = D3D10.getSwapChain()->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&tex); if(FAILED(hr)) return hr; hr = D3D10.getDevice()->CreateRenderTargetView(tex, NULL, &(this->renderTargetView)); tex->Release(); return hr; }
//----------------------------------------------------------------------------// void Direct3D10Texture::blitToMemory(void* targetData) { if (!d_texture) return; String exception_msg; D3D10_TEXTURE2D_DESC tex_desc; d_texture->GetDesc(&tex_desc); tex_desc.Usage = D3D10_USAGE_STAGING; tex_desc.BindFlags = 0; tex_desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ; ID3D10Texture2D* offscreen; if (SUCCEEDED(d_device.CreateTexture2D(&tex_desc, 0, &offscreen))) { d_device.CopyResource(offscreen, d_texture); D3D10_MAPPED_TEXTURE2D mapped_tex; if (SUCCEEDED(offscreen->Map(0, D3D10_MAP_READ, 0, &mapped_tex))) { blitFromSurface(static_cast<uint32*>(mapped_tex.pData), static_cast<uint32*>(targetData), Sizef(static_cast<float>(tex_desc.Width), static_cast<float>(tex_desc.Height)), mapped_tex.RowPitch); offscreen->Unmap(0); } else exception_msg.assign("ID3D10Texture2D::Map failed."); offscreen->Release(); } else exception_msg.assign( "ID3D10Device::CreateTexture2D failed for 'offscreen'."); if (!exception_msg.empty()) CEGUI_THROW(RendererException(exception_msg)); }
void D3D10System::ResizeView() { LPVOID nullVal = NULL; d3d->OMSetRenderTargets(1, (ID3D10RenderTargetView**)&nullVal, NULL); SafeRelease(swapRenderView); swap->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0); ID3D10Texture2D *backBuffer = NULL; HRESULT err = swap->GetBuffer(0, IID_ID3D10Texture2D, (void**)&backBuffer); if(FAILED(err)) CrashError(TEXT("Unable to get back buffer from swap chain")); err = d3d->CreateRenderTargetView(backBuffer, NULL, &swapRenderView); if(FAILED(err)) CrashError(TEXT("Unable to get render view from back buffer")); backBuffer->Release(); }
bool CRenderDevice::RenderTargetView(HRESULT& hr) { ID3D10Texture2D* pBackBuffer; hr = m_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) { MessageBox( NULL, "NO back bufer", "", NULL ); return false; } hr = m_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &m_pRenderTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) { MessageBox( NULL, "NO m_pRenderTargetView", "", NULL ); return false; } return true; }
HRESULT WINAPI DXGIPresent(IDXGISwapChain * sc, UINT b, UINT c) { DxgiFrameGrabber *dxgiFrameGrabber = DxgiFrameGrabber::getInstance(); Logger *logger = dxgiFrameGrabber->m_logger; DXGI_SWAP_CHAIN_DESC desc; sc->GetDesc(&desc); logger->reportLogDebug(L"d3d10 Buffers count: %u, Output hwnd: %u, %s", desc.BufferCount, desc.OutputWindow, desc.Windowed ? "windowed" : "fullscreen"); if (!desc.Windowed) { if (dxgiDevice == DxgiDeviceUnknown || dxgiDevice == DxgiDeviceD3D10 ) { ID3D10Texture2D *pBackBuffer; HRESULT hr = sc->GetBuffer(0, IID_ID3D10Texture2D, reinterpret_cast<LPVOID*> (&pBackBuffer)); if (hr == S_OK) { if (dxgiDevice == DxgiDeviceUnknown) dxgiDevice = DxgiDeviceD3D10; D3D10Grab(pBackBuffer); pBackBuffer->Release(); } else { if (dxgiDevice != DxgiDeviceUnknown) logger->reportLogError(L"couldn't get d3d10 buffer. returned 0x%x", hr); } } if (dxgiDevice == DxgiDeviceUnknown || dxgiDevice == DxgiDeviceD3D11 ) { ID3D11Texture2D *pBackBuffer; HRESULT hr = sc->GetBuffer(0, IID_ID3D11Texture2D, reinterpret_cast<LPVOID*> (&pBackBuffer)); if(hr == S_OK) { if (dxgiDevice == DxgiDeviceUnknown) dxgiDevice = DxgiDeviceD3D11; D3D11Grab(pBackBuffer); pBackBuffer->Release(); } else { logger->reportLogError(L"couldn't get d3d11 buffer. returned 0x%x", hr); } } } DXGISCPresentFunc originalFunc = reinterpret_cast<DXGISCPresentFunc>(dxgiFrameGrabber->m_dxgiPresentProxyFuncVFTable->getOriginalFunc()); return originalFunc(sc,b,c); }
bool InitializeDirect3dApp(HINSTANCE hInstance) { UINT createDeviceFlags = 0; D3D10_DRIVER_TYPE driverTypes[] = { D3D10_DRIVER_TYPE_HARDWARE, D3D10_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); DXGI_SWAP_CHAIN_DESC scd; scd.BufferDesc.Width = Width; scd.BufferDesc.Height = Height; scd.BufferDesc.RefreshRate.Numerator = 60; scd.BufferDesc.RefreshRate.Denominator = 1; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //no multisampling scd.SampleDesc.Count = 1; scd.SampleDesc.Quality = 0; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.BufferCount = 1; scd.OutputWindow = hwnd; scd.Windowed = true; scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; scd.Flags = 0; D3D10CreateDeviceAndSwapChain(0, D3D10_DRIVER_TYPE_HARDWARE, 0, 0, D3D10_SDK_VERSION, &scd, &SwapChain, &d3dDevice); ID3D10Texture2D* backBuffer; SwapChain->GetBuffer(0, _uuidof(ID3D10Texture2D), reinterpret_cast<void**>(&backBuffer)); d3dDevice->CreateRenderTargetView(backBuffer, 0, &RenderTargetView); backBuffer->Release(); D3D10_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = Width; depthStencilDesc.Height = Height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D10_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; d3dDevice->CreateTexture2D(&depthStencilDesc, NULL, &DepthStencilBuffer); d3dDevice->CreateDepthStencilView(DepthStencilBuffer, NULL, &DepthStencilView); d3dDevice->OMSetRenderTargets(1, &RenderTargetView, DepthStencilView); // Setup the viewport D3D10_VIEWPORT vp; vp.Width = Width; vp.Height = Height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; d3dDevice->RSSetViewports(1, &vp); D3DXMatrixIdentity(&World); D3DXMatrixLookAtLH(&View, &Position, &Target, &Up); return true; }
//----------------------------------------------------------------------------- // Name: InitD3D() // Desc: Initializes Direct3D //----------------------------------------------------------------------------- HRESULT InitD3D(HWND hWnd) { // Set up the structure used to create the device and swapchain DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = g_WindowWidth; sd.BufferDesc.Height = g_WindowHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; // Create device and swapchain HRESULT hr = sFnPtr_D3D10CreateDeviceAndSwapChain( g_pCudaCapableAdapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice); AssertOrQuit(SUCCEEDED(hr)); g_pCudaCapableAdapter->Release(); // Create a render target view of the swapchain ID3D10Texture2D *pBuffer; hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID *)&pBuffer); AssertOrQuit(SUCCEEDED(hr)); hr = g_pd3dDevice->CreateRenderTargetView(pBuffer, NULL, &g_pSwapChainRTV); AssertOrQuit(SUCCEEDED(hr)); pBuffer->Release(); g_pd3dDevice->OMSetRenderTargets(1, &g_pSwapChainRTV, NULL); // Setup the viewport D3D10_VIEWPORT vp; vp.Width = g_WindowWidth; vp.Height = g_WindowHeight; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pd3dDevice->RSSetViewports(1, &vp); // Setup the effect { ID3D10Blob *pCompiledEffect; hr = sFnPtr_D3D10CompileEffectFromMemory( (void *)g_simpleEffectSrc, sizeof(g_simpleEffectSrc), NULL, NULL, // pDefines NULL, // pIncludes 0, // HLSL flags 0, // FXFlags &pCompiledEffect, NULL); AssertOrQuit(SUCCEEDED(hr)); hr = sFnPtr_D3D10CreateEffectFromMemory( pCompiledEffect->GetBufferPointer(), pCompiledEffect->GetBufferSize(), 0, // FXFlags g_pd3dDevice, NULL, &g_pSimpleEffect); pCompiledEffect->Release(); g_pSimpleTechnique = g_pSimpleEffect->GetTechniqueByName("Render"); // g_pmWorldViewProjection = g_pSimpleEffect->GetVariableByName("g_mWorldViewProjection")->AsMatrix(); g_pmWorld = g_pSimpleEffect->GetVariableByName("g_mWorld")->AsMatrix(); g_pmView = g_pSimpleEffect->GetVariableByName("g_mView")->AsMatrix(); g_pmProjection = g_pSimpleEffect->GetVariableByName("g_mProjection")->AsMatrix(); // Define the input layout D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = sizeof(layout)/sizeof(layout[0]); // Create the input layout D3D10_PASS_DESC PassDesc; g_pSimpleTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); hr = g_pd3dDevice->CreateInputLayout(layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pInputLayout); AssertOrQuit(SUCCEEDED(hr)); // Setup Input Layout, apply effect and draw points g_pd3dDevice->IASetInputLayout(g_pInputLayout); g_pSimpleTechnique->GetPassByIndex(0)->Apply(0); g_pd3dDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); } // begin interop cudaD3D10SetDirect3DDevice(g_pd3dDevice); getLastCudaError("cudaD3D10SetDirect3DDevice failed"); return S_OK; }
// Detour function that replaces the IDXGISwapChain::Present() API DllExport HRESULT __stdcall hook_DXGISwapChainPresent( IDXGISwapChain * This, UINT SyncInterval, UINT Flags ) { static int frame_interval; static LARGE_INTEGER initialTv, captureTv, freq; static int capture_initialized = 0; // int i; struct pooldata *data; struct vsource_frame *frame; // DXGI_SWAP_CHAIN_DESC pDESC; HRESULT hr = pDXGISwapChainPresent(This, SyncInterval, Flags); if(resolution_retrieved == 0) { if(DXGI_get_resolution(This) >= 0) { resolution_retrieved = 1; } return hr; } if(vsource_initialized == 0) { ga_error("video source not initialized.\n"); return hr; } This->GetDesc(&pDESC); pDXGI_FORMAT = pDESC.BufferDesc.Format; // extract screen format for sws_scale if(pDESC.BufferDesc.Width != game_width || pDESC.BufferDesc.Height != game_height) { ga_error("game width/height mismatched (%dx%d) != (%dx%d)\n", pDESC.BufferDesc.Width, pDESC.BufferDesc.Height, game_width, game_height); return hr; } // if (enable_server_rate_control && ga_hook_video_rate_control() < 0) return hr; if (dx_version == dx_none) { //bool check_result = FALSE; if (check_dx_device_version(This, IID_ID3D10Device)) { dx_version = dx_10; ga_error("[DXGISwapChain] DirectX 10\n"); } else if (check_dx_device_version(This, IID_ID3D10Device1)) { dx_version = dx_10_1; ga_error("[DXGISwapChain] DirectX 10.1\n"); } else if (check_dx_device_version(This, IID_ID3D11Device)) { dx_version = dx_11; ga_error("[DXGISwapChain] DirectX 11\n"); } } if (capture_initialized == 0) { frame_interval = 1000000/video_fps; // in the unif of us frame_interval++; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&initialTv); capture_initialized = 1; } else { QueryPerformanceCounter(&captureTv); } hr = 0; // d3d10 / d3d10.1 if (dx_version == dx_10 || dx_version == dx_10_1) { void *ppDevice; ID3D10Device *pDevice; //IUnknown *pDevice; if (dx_version == dx_10) { This->GetDevice(IID_ID3D10Device, &ppDevice); pDevice = (ID3D10Device *)ppDevice; } else if (dx_version == dx_10_1) { This->GetDevice(IID_ID3D10Device1, &ppDevice); pDevice = (ID3D10Device1 *)ppDevice; } else { OutputDebugString("Invalid DirectX version in IDXGISwapChain::Present"); return hr; } ID3D10RenderTargetView *pRTV = NULL; ID3D10Resource *pSrcResource = NULL; pDevice->OMGetRenderTargets(1, &pRTV, NULL); pRTV->GetResource(&pSrcResource); ID3D10Texture2D* pSrcBuffer = (ID3D10Texture2D *)pSrcResource; ID3D10Texture2D* pDstBuffer = NULL; D3D10_TEXTURE2D_DESC desc; pSrcBuffer->GetDesc(&desc); desc.BindFlags = 0; desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ; desc.Usage = D3D10_USAGE_STAGING; hr = pDevice->CreateTexture2D(&desc, NULL, &pDstBuffer); if (FAILED(hr)) { OutputDebugString("Failed to create texture2D"); //assert(exp_state == exp_none); } pDevice->CopyResource(pDstBuffer, pSrcBuffer); D3D10_MAPPED_TEXTURE2D mapped_screen; hr = pDstBuffer->Map(0, D3D10_MAP_READ, 0, &mapped_screen); if (FAILED(hr)) { OutputDebugString("Failed to map from DstBuffer"); //assert(exp_state == exp_none); } // copy image do { unsigned char *src, *dst; data = g_pipe[0]->allocate_data(); frame = (struct vsource_frame*) data->ptr; frame->pixelformat = PIX_FMT_BGRA; frame->realwidth = desc.Width; frame->realheight = desc.Height; frame->realstride = desc.Width<<2; frame->realsize = frame->realwidth * frame->realstride; frame->linesize[0] = frame->realstride;//frame->stride; // src = (unsigned char*) mapped_screen.pData; dst = (unsigned char*) frame->imgbuf; for (i = 0; i < encoder_height; i++) { CopyMemory(dst, src, frame->realstride/*frame->stride*/); src += mapped_screen.RowPitch; dst += frame->realstride;//frame->stride; } frame->imgpts = pcdiff_us(captureTv, initialTv, freq)/frame_interval; } while(0); // duplicate from channel 0 to other channels for(i = 1; i < SOURCES; i++) { int j; struct pooldata *dupdata; struct vsource_frame *dupframe; dupdata = g_pipe[i]->allocate_data(); dupframe = (struct vsource_frame*) dupdata->ptr; // vsource_dup_frame(frame, dupframe); // g_pipe[i]->store_data(dupdata); g_pipe[i]->notify_all(); } g_pipe[0]->store_data(data); g_pipe[0]->notify_all(); pDstBuffer->Unmap(0); pDevice->Release(); pSrcResource->Release(); pSrcBuffer->Release(); pRTV->Release(); pDstBuffer->Release(); // d11 } else if (dx_version == dx_11) { void *ppDevice; This->GetDevice(IID_ID3D11Device, &ppDevice); ID3D11Device *pDevice = (ID3D11Device*) ppDevice; This->GetDevice(IID_ID3D11DeviceContext, &ppDevice); ID3D11DeviceContext *pDeviceContext = (ID3D11DeviceContext *) ppDevice; ID3D11RenderTargetView *pRTV = NULL; ID3D11Resource *pSrcResource = NULL; pDeviceContext->OMGetRenderTargets(1, &pRTV, NULL); pRTV->GetResource(&pSrcResource); ID3D11Texture2D *pSrcBuffer = (ID3D11Texture2D *)pSrcResource; ID3D11Texture2D *pDstBuffer = NULL; D3D11_TEXTURE2D_DESC desc; pSrcBuffer->GetDesc(&desc); desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.Usage = D3D11_USAGE_STAGING; hr = pDevice->CreateTexture2D(&desc, NULL, &pDstBuffer); if (FAILED(hr)) { OutputDebugString("Failed to create buffer"); //assert(exp_state == exp_none); } pDeviceContext->CopyResource(pDstBuffer, pSrcBuffer); D3D11_MAPPED_SUBRESOURCE mapped_screen; hr = pDeviceContext->Map(pDstBuffer, 0, D3D11_MAP_READ, 0, &mapped_screen); if (FAILED(hr)) { OutputDebugString("Failed to map from DeviceContext"); //assert(exp_state == exp_none); } // copy image do { unsigned char *src, *dst; data = g_pipe[0]->allocate_data(); frame = (struct vsource_frame*) data->ptr; frame->pixelformat = PIX_FMT_BGRA; frame->realwidth = desc.Width; frame->realheight = desc.Height; frame->realstride = desc.Width<<2; frame->realsize = frame->realwidth * frame->realstride; frame->linesize[0] = frame->realstride;//frame->stride; // src = (unsigned char*) mapped_screen.pData; dst = (unsigned char*) frame->imgbuf; for (i = 0; i < encoder_height; i++) { CopyMemory(dst, src, frame->realstride/*frame->stride*/); src += mapped_screen.RowPitch; dst += frame->realstride;//frame->stride; } frame->imgpts = pcdiff_us(captureTv, initialTv, freq)/frame_interval; } while(0); // duplicate from channel 0 to other channels for(i = 1; i < SOURCES; i++) { int j; struct pooldata *dupdata; struct vsource_frame *dupframe; dupdata = g_pipe[i]->allocate_data(); dupframe = (struct vsource_frame*) dupdata->ptr; // vsource_dup_frame(frame, dupframe); // g_pipe[i]->store_data(dupdata); g_pipe[i]->notify_all(); } g_pipe[0]->store_data(data); g_pipe[0]->notify_all(); pDeviceContext->Unmap(pDstBuffer, 0); pDevice->Release(); pDeviceContext->Release(); pSrcResource->Release(); pSrcBuffer->Release(); pRTV->Release(); pDstBuffer->Release(); } return hr; }
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; // 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; // 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. 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 = D3D10_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D10_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 = 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); // 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 = 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; }
DXMessD3D10Handler::DXMessD3D10Handler(ID3D10Device *dev, IDXGISwapChain *sc, PD3DHookShared shared) { HRESULT hr; int i; pPixelShaderNormal=NULL; pVertexShader=NULL; pVertexLayout=NULL; pSamplerLinear=NULL; pSpriteRasterizer=NULL; pTransparency=NULL; pDepthStencil=NULL; pRenderTargetView=NULL; pDepthStencilView=NULL; pConstantBuffer=NULL; pWireframeRasterizer=NULL; pDisabledDepthStencilState=NULL; pSpriteVB=NULL; pFontVB=NULL; TextureCount=0; textures=NULL; tea=NULL; Valid=FALSE; this->shared=shared; this->dev=dev; this->dev->AddRef(); this->swapchain=sc; this->swapchain->AddRef(); //create the shaders ID3DBlob* pBlob = NULL; ID3DBlob* pErrorBlob = NULL; char shaderfile[MAX_PATH]; sprintf_s(shaderfile,MAX_PATH, "%s%s", shared->CheatEngineDir,"overlay.fx"); //normal pixel shader pBlob = NULL; pErrorBlob = NULL; hr=D3DX10CompileFromFileA( shaderfile, NULL, NULL, "PSNormal", "ps_4_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, NULL, &pBlob, &pErrorBlob, NULL ); if (pErrorBlob) { OutputDebugStringA((LPCSTR)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } if( FAILED( hr ) ) { OutputDebugStringA("pixelshader compilation failed\n"); return; } hr = dev->CreatePixelShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &pPixelShaderNormal ); pBlob->Release(); if( FAILED( hr ) ) { OutputDebugStringA("CreatePixelShader failed\n"); return; } //vertex shader pBlob = NULL; pErrorBlob = NULL; hr=D3DX10CompileFromFileA( shaderfile, NULL, NULL, "VS", "vs_4_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, NULL, &pBlob, &pErrorBlob, NULL ); if (pErrorBlob) { OutputDebugStringA((LPCSTR)pErrorBlob->GetBufferPointer()); pErrorBlob->Release(); } if( FAILED( hr ) ) { OutputDebugStringA("vertexshader compilation failed\n"); return; } hr = dev->CreateVertexShader( pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &pVertexShader ); if( FAILED( hr ) ) { pBlob->Release(); OutputDebugStringA("CreatePixelShader failed\n"); return; } //and create a input layout D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); // Create the input layout hr = dev->CreateInputLayout( layout, numElements, pBlob->GetBufferPointer(), pBlob->GetBufferSize(), &pVertexLayout ); pBlob->Release(); //create rectangular vertex buffer for sprites SpriteVertex spriteVertices[] ={ {XMFLOAT3( 1.0f, 1.0f, 1.0f), XMFLOAT2( 1.0f, 0.0f ) }, {XMFLOAT3( 1.0f, -1.0f, 1.0f), XMFLOAT2( 1.0f, 1.0f )}, {XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT2( 0.0f, 1.0f )}, {XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT2( 0.0f, 1.0f )}, {XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT2( 0.0f, 0.0f )}, {XMFLOAT3( 1.0f, 1.0f, 1.0f), XMFLOAT2( 1.0f, 0.0f )}, }; D3D10_BUFFER_DESC bd2d; ZeroMemory( &bd2d, sizeof(bd2d) ); bd2d.Usage = D3D10_USAGE_DYNAMIC; bd2d.ByteWidth = sizeof( SpriteVertex ) * 6; bd2d.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd2d.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; D3D10_SUBRESOURCE_DATA InitData2d; ZeroMemory( &InitData2d, sizeof(InitData2d) ); InitData2d.pSysMem = spriteVertices; hr = dev->CreateBuffer( &bd2d, &InitData2d, &pSpriteVB ); if( FAILED( hr ) ) { OutputDebugStringA("Vertexbuffer creation failed\n"); return; } D3D10_SAMPLER_DESC sampDesc; ZeroMemory( &sampDesc, sizeof(sampDesc) ); sampDesc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D10_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D10_FLOAT32_MAX; hr = dev->CreateSamplerState( &sampDesc, &pSamplerLinear ); if( FAILED( hr ) ) return; //rasterizer D3D10_RASTERIZER_DESC rasterizerdesc; ZeroMemory(&rasterizerdesc, sizeof(rasterizerdesc)); rasterizerdesc.FillMode = D3D10_FILL_SOLID; rasterizerdesc.CullMode = D3D10_CULL_NONE; rasterizerdesc.FrontCounterClockwise = false; rasterizerdesc.DepthBias = 0; rasterizerdesc.DepthBiasClamp = 0.0f; rasterizerdesc.DepthClipEnable = false; rasterizerdesc.AntialiasedLineEnable = false; rasterizerdesc.MultisampleEnable = false; rasterizerdesc.ScissorEnable = false; rasterizerdesc.SlopeScaledDepthBias = 0.0f; hr=dev->CreateRasterizerState(&rasterizerdesc, &pSpriteRasterizer); if( FAILED( hr ) ) return; rasterizerdesc.FillMode = D3D10_FILL_WIREFRAME; hr=dev->CreateRasterizerState(&rasterizerdesc, &pWireframeRasterizer); if( FAILED( hr ) ) pWireframeRasterizer=NULL; //no biggie D3D10_DEPTH_STENCIL_DESC dsDesc; ZeroMemory(&dsDesc, sizeof(dsDesc)); //everything 0, including DepthEnable hr= dev->CreateDepthStencilState(&dsDesc, &pDisabledDepthStencilState); if( FAILED( hr ) ) pDisabledDepthStencilState=NULL; D3D10_BLEND_DESC blend; ZeroMemory( &blend, sizeof(blend) ); blend.BlendEnable[0] = true; blend.SrcBlend = D3D10_BLEND_SRC_ALPHA ; blend.DestBlend = D3D10_BLEND_INV_SRC_ALPHA; blend.BlendOp = D3D10_BLEND_OP_ADD; blend.SrcBlendAlpha = D3D10_BLEND_SRC_ALPHA; blend.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA; blend.BlendOpAlpha = D3D10_BLEND_OP_ADD; blend.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; blend.AlphaToCoverageEnable=false; for (i=0; i<8; i++) blend.RenderTargetWriteMask[i]=D3D10_COLOR_WRITE_ENABLE_ALL; pTransparency=NULL; hr=dev->CreateBlendState(&blend, &pTransparency); if( FAILED( hr ) ) return; //create a rendertarget ID3D10Texture2D* pBackBuffer = NULL; hr = sc->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return; hr = dev->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) return; DXGI_SWAP_CHAIN_DESC scdesc; ZeroMemory(&scdesc,sizeof(scdesc)); sc->GetDesc(&scdesc); // Create depth stencil texture D3D10_TEXTURE2D_DESC descDepth; ZeroMemory( &descDepth, sizeof(descDepth) ); descDepth.Width = scdesc.BufferDesc.Width; descDepth.Height = scdesc.BufferDesc.Height; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D10_USAGE_DEFAULT; descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = dev->CreateTexture2D( &descDepth, NULL, &pDepthStencil ); if( FAILED( hr ) ) return; // Create the depth stencil view D3D10_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV, sizeof(descDSV) ); descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; hr = dev->CreateDepthStencilView( pDepthStencil, &descDSV, &pDepthStencilView ); if( FAILED( hr ) ) return; //now load the textures tea=(PTextureEntry)((uintptr_t)shared+shared->texturelist); UpdateTextures(); // Create the constant buffer D3D10_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D10_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = dev->CreateBuffer( &bd, NULL, &pConstantBuffer ); if( FAILED( hr ) ) return; //create a vertexbuffer to hold the characters currentMaxCharacterCount=0; SetupFontVertexBuffer(32); //init to 32 chars Valid=TRUE; }
BOOL DXMessD3D10Handler::UpdateTextures() { //call this each time the resolution changes (when the buffer changes) HRESULT hr; ID3D10Resource *test; ID3D10Texture2D *texturex; DXGI_SWAP_CHAIN_DESC desc; int i; int newTextureCount; WaitForSingleObject((HANDLE)(shared->TextureLock), INFINITE); if (shared->textureCount) { ZeroMemory(&desc, sizeof(desc)); hr=swapchain->GetDesc(&desc); if (FAILED(hr)) return hr; newTextureCount=shared->textureCount; if (shared->textureCount > TextureCount) { //update the textures if needed if (textures==NULL) //initial alloc textures=(TextureData10 *)malloc(sizeof(TextureData10)* shared->textureCount); else //realloc textures=(TextureData10 *)realloc(textures, sizeof(TextureData10)* shared->textureCount); //initialize the new entries to NULL for (i=TextureCount; i<shared->textureCount; i++) { textures[i].pTexture=NULL; textures[i].DefinedFontMap=NULL; } } for (i=0; i<newTextureCount; i++) { if (tea[i].AddressOfTexture) { if ((tea[i].hasBeenUpdated) || (textures[i].pTexture==NULL)) { if (textures[i].pTexture) { //already has a texture, so an update. Free the old one first textures[i].pTexture->Release(); textures[i].pTexture=NULL; //should always happen } if (textures[i].DefinedFontMap) { //already has a fontmap. Free the old one free(textures[i].DefinedFontMap); textures[i].DefinedFontMap=NULL; } hr=D3DX10CreateTextureFromMemory(dev, (void *)(tea[i].AddressOfTexture), tea[i].size, NULL, NULL, &test, NULL); if( FAILED( hr ) ) { OutputDebugStringA("Failure creating a texture"); return hr; } hr=test->QueryInterface(__uuidof(ID3D10Texture2D), (void **)(&texturex)); hr=dev->CreateShaderResourceView(test, NULL, &textures[i].pTexture); if( FAILED( hr ) ) return hr; test->Release(); texturex->Release(); if (tea[i].AddressOfFontmap) { int j; float currentOffset=0; textures[i].DefinedFontMap=(PFONTMAP)malloc(sizeof(FONTMAP)); //now parse the fontmap provided by ce and fill in the gaps WORD *cefontmap=(WORD *)(tea[i].AddressOfFontmap); textures[i].DefinedFontMap->charheight=(float)cefontmap[0]; for (j=0; j<96; j++) { textures[i].DefinedFontMap->charinfo[j].offset=currentOffset; textures[i].DefinedFontMap->charinfo[j].charwidth=(float)cefontmap[j+1]; currentOffset+=cefontmap[j+1]; } textures[i].DefinedFontMap->fullwidth=currentOffset; } tea[i].hasBeenUpdated=0; } } else { //It's NULL (cleanup) if (textures[i].pTexture) { textures[i].pTexture->Release(); textures[i].pTexture=NULL; } if (textures[i].DefinedFontMap) { free(textures[i].DefinedFontMap); textures[i].DefinedFontMap=NULL; } } } TextureCount=newTextureCount; } if (shared->texturelistHasUpdate) InterlockedExchange((volatile LONG *)&shared->texturelistHasUpdate,0); SetEvent((HANDLE)(shared->TextureLock)); return TRUE; }
//-------------------------------------------------------------------------------------- // Create Direct3D device and swap chain //-------------------------------------------------------------------------------------- HRESULT InitDevice() { HRESULT hr = S_OK; RECT rc; GetClientRect( g_hWnd, &rc ); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif D3D10_DRIVER_TYPE driverTypes[] = { D3D10_DRIVER_TYPE_HARDWARE, D3D10_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof( driverTypes ) / sizeof( driverTypes[0] ); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { g_driverType = driverTypes[driverTypeIndex]; hr = D3D10CreateDeviceAndSwapChain1( NULL, g_driverType, NULL, createDeviceFlags, D3D10_FEATURE_LEVEL_10_1, D3D10_1_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice ); if( SUCCEEDED( hr ) ) break; } if( FAILED( hr ) ) return hr; // Create a render target view ID3D10Texture2D* pBuffer; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBuffer ); if( FAILED( hr ) ) return hr; hr = g_pd3dDevice->CreateRenderTargetView( pBuffer, NULL, &g_pRenderTargetView ); pBuffer->Release(); if( FAILED( hr ) ) return hr; g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL ); // Setup the viewport D3D10_VIEWPORT vp; vp.Width = width; vp.Height = height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pd3dDevice->RSSetViewports( 1, &vp ); // Create the effect DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3D10_SHADER_DEBUG; #endif hr = D3DX10CreateEffectFromFile( "Tutorial07.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, g_pd3dDevice, NULL, NULL, &g_pEffect, NULL, NULL ); if( FAILED( hr ) ) { MessageBox( NULL, "The FX file cannot be located. Please run this executable from the directory that contains the FX file.", "Error", MB_OK ); return hr; } // Obtain the technique g_pTechnique = g_pEffect->GetTechniqueByName( "Render" ); // Obtain the variables g_pWorldVariable = g_pEffect->GetVariableByName( "World" )->AsMatrix(); g_pViewVariable = g_pEffect->GetVariableByName( "View" )->AsMatrix(); g_pProjectionVariable = g_pEffect->GetVariableByName( "Projection" )->AsMatrix(); g_pMeshColorVariable = g_pEffect->GetVariableByName( "vMeshColor" )->AsVector(); g_pDiffuseVariable = g_pEffect->GetVariableByName( "txDiffuse" )->AsShaderResource(); // Define the input layout D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = sizeof( layout ) / sizeof( layout[0] ); // Create the input layout D3D10_PASS_DESC PassDesc; g_pTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc ); hr = g_pd3dDevice->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout ); if( FAILED( hr ) ) return hr; // Set the input layout g_pd3dDevice->IASetInputLayout( g_pVertexLayout ); // Create vertex buffer SimpleVertex vertices[] = { // top { D3DXVECTOR3( -1.0f, 1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, { D3DXVECTOR3( 1.0f, 1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) }, { D3DXVECTOR3( 1.0f, 1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, { D3DXVECTOR3( -1.0f, 1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) }, { D3DXVECTOR3( 1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, { D3DXVECTOR3( -1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, { D3DXVECTOR3( -1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, { D3DXVECTOR3( -1.0f, 1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, { D3DXVECTOR3( -1.0f, 1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) }, { D3DXVECTOR3( 1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, 1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) }, { D3DXVECTOR3( 1.0f, 1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, { D3DXVECTOR3( -1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, -1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, 1.0f, -1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, { D3DXVECTOR3( -1.0f, 1.0f, -1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) }, { D3DXVECTOR3( -1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, -1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 1.0f ) }, { D3DXVECTOR3( 1.0f, 1.0f, 1.0f ), D3DXVECTOR2( 0.0f, 0.0f ) }, { D3DXVECTOR3( -1.0f, 1.0f, 1.0f ), D3DXVECTOR2( 1.0f, 0.0f ) }, }; D3D10_BUFFER_DESC bd; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof( SimpleVertex ) * 24; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = vertices; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer ); if( FAILED( hr ) ) return hr; // Set vertex buffer UINT stride = sizeof( SimpleVertex ); UINT offset = 0; g_pd3dDevice->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset ); // Create index buffer // Create vertex buffer DWORD indices[] = { 3,1,0, 2,1,3, 6,4,5, 7,4,6, 11,9,8, 10,9,11, 14,12,13, 15,12,14, 19,17,16, 18,17,19, 22,20,21, 23,20,22 }; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof( DWORD ) * 36; bd.BindFlags = D3D10_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; InitData.pSysMem = indices; hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer ); if( FAILED( hr ) ) return hr; // Set index buffer g_pd3dDevice->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 ); // Set primitive topology g_pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); // Load the Texture //hr = D3DX10CreateShaderResourceViewFromFile( g_pd3dDevice, L"seafloor.dds", NULL, NULL, &g_pTextureRV, NULL ); //if( FAILED( hr ) ) // return hr; // Initialize the world matrices D3DXMatrixIdentity( &g_World ); // Initialize the view matrix D3DXVECTOR3 Eye( 0.0f, 1.5f, -2.5f ); D3DXVECTOR3 At( 0.0f, 0.0f, 0.0f ); D3DXVECTOR3 Up( 0.0f, 1.0f, 0.0f ); D3DXMatrixLookAtLH( &g_View, &Eye, &At, &Up ); // Initialize the projection matrix D3DXMatrixPerspectiveFovLH( &g_Projection, ( float )D3DX_PI * 0.25f, width / ( FLOAT )height, 0.1f, 100.0f ); // Update Variables that never change g_pViewVariable->SetMatrix( ( float* )&g_View ); g_pProjectionVariable->SetMatrix( ( float* )&g_Projection ); HANDLE texHandle = NULL; DWORD d3dFormat; ID3D10Texture2D *pTexture = NULL; HWND win = NULL; do { win = FindWindowEx(NULL, win, "Chrome_WidgetWin_0", NULL); } while (GetWindowTextLength(win) == 0); texHandle = DwmaxxGetWindowSharedHandle((HWND)win); if (texHandle == NULL) { MessageBox(NULL, "Unable to get window texture!!!!", "Error", MB_OK); return S_FALSE; } HRESULT hrs = g_pd3dDevice->OpenSharedResource(texHandle, __uuidof(ID3D10Texture2D), (void**)&pTexture); D3D10_TEXTURE2D_DESC desc; pTexture->GetDesc( &desc ); D3D10_SHADER_RESOURCE_VIEW_DESC srvDesc; D3D10_RESOURCE_DIMENSION type; srvDesc.Format = desc.Format; srvDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = desc.MipLevels -1; ID3D10ShaderResourceView *pSRView = NULL; g_pd3dDevice->CreateShaderResourceView( pTexture, &srvDesc, &pSRView ); g_pDiffuseVariable->SetResource( pSRView ); return S_OK; }
D3D10System::D3D10System() { traceIn(D3D10System::D3D10System); HRESULT err; //------------------------------------------------------------------ DXGI_SWAP_CHAIN_DESC swapDesc; zero(&swapDesc, sizeof(swapDesc)); swapDesc.BufferCount = 2; swapDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swapDesc.BufferDesc.Width = App->renderFrameWidth; swapDesc.BufferDesc.Height = App->renderFrameHeight; swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapDesc.Flags = 0; swapDesc.OutputWindow = hwndRenderFrame; swapDesc.SampleDesc.Count = 1; swapDesc.Windowed = TRUE; bDisableCompatibilityMode = AppConfig->GetInt(TEXT("Video"), TEXT("DisableD3DCompatibilityMode"), 1) != 0; UINT createFlags = D3D10_CREATE_DEVICE_BGRA_SUPPORT; if(GlobalConfig->GetInt(TEXT("General"), TEXT("UseDebugD3D"))) createFlags |= D3D10_CREATE_DEVICE_DEBUG; D3D10_FEATURE_LEVEL1 level = bDisableCompatibilityMode ? D3D10_FEATURE_LEVEL_10_1 : D3D10_FEATURE_LEVEL_9_3; //D3D10_CREATE_DEVICE_DEBUG //D3D11_DRIVER_TYPE_REFERENCE, D3D11_DRIVER_TYPE_HARDWARE err = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createFlags, level, D3D10_1_SDK_VERSION, &swapDesc, &swap, &d3d); if(FAILED(err)) { bDisableCompatibilityMode = !bDisableCompatibilityMode; level = bDisableCompatibilityMode ? D3D10_FEATURE_LEVEL_10_1 : D3D10_FEATURE_LEVEL_9_3; err = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createFlags, level, D3D10_1_SDK_VERSION, &swapDesc, &swap, &d3d); } if(FAILED(err)) CrashError(TEXT("Could not create D3D10 device and swap chain. If you get this error, it's likely you probably use a GPU that is old, or that is unsupported.")); //------------------------------------------------------------------ Log(TEXT("Loading up D3D10...")); D3D10_DEPTH_STENCIL_DESC depthDesc; zero(&depthDesc, sizeof(depthDesc)); depthDesc.DepthEnable = FALSE; err = d3d->CreateDepthStencilState(&depthDesc, &depthState); if(FAILED(err)) CrashError(TEXT("Unable to create depth state")); d3d->OMSetDepthStencilState(depthState, 0); //------------------------------------------------------------------ D3D10_RASTERIZER_DESC rasterizerDesc; zero(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.FillMode = D3D10_FILL_SOLID; rasterizerDesc.CullMode = D3D10_CULL_NONE; rasterizerDesc.FrontCounterClockwise = FALSE; rasterizerDesc.DepthClipEnable = TRUE; err = d3d->CreateRasterizerState(&rasterizerDesc, &rasterizerState); if(FAILED(err)) CrashError(TEXT("Unable to create rasterizer state")); d3d->RSSetState(rasterizerState); //------------------------------------------------------------------ ID3D10Texture2D *backBuffer = NULL; err = swap->GetBuffer(0, IID_ID3D10Texture2D, (void**)&backBuffer); if(FAILED(err)) CrashError(TEXT("Unable to get back buffer from swap chain")); err = d3d->CreateRenderTargetView(backBuffer, NULL, &swapRenderView); if(FAILED(err)) CrashError(TEXT("Unable to get render view from back buffer")); backBuffer->Release(); //------------------------------------------------------------------ D3D10_BLEND_DESC disabledBlendDesc; zero(&disabledBlendDesc, sizeof(disabledBlendDesc)); for(int i=0; i<8; i++) { disabledBlendDesc.BlendEnable[i] = TRUE; disabledBlendDesc.RenderTargetWriteMask[i] = D3D10_COLOR_WRITE_ENABLE_ALL; } disabledBlendDesc.BlendOpAlpha = D3D10_BLEND_OP_ADD; disabledBlendDesc.BlendOp = D3D10_BLEND_OP_ADD; disabledBlendDesc.SrcBlendAlpha = D3D10_BLEND_ONE; disabledBlendDesc.DestBlendAlpha = D3D10_BLEND_ZERO; disabledBlendDesc.SrcBlend = D3D10_BLEND_ONE; disabledBlendDesc.DestBlend = D3D10_BLEND_ZERO; err = d3d->CreateBlendState(&disabledBlendDesc, &disabledBlend); if(FAILED(err)) CrashError(TEXT("Unable to create disabled blend state")); this->BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA, 1.0f); bBlendingEnabled = true; traceOut; }
//============================================================================================================= bool CGame10::Initialize() { if( Graphics ) return true; HRESULT hr; HWND hwnd; bool success = false; ID3D10Texture2D* backbuffer; D3D10_VIEWPORT vp; int width = (int)DisplayMode.Width; int height = (int)DisplayMode.Height; success = Application.Initialize(width, height, FullScreen); dassert(false, "CGame10::Initialize(): Could not initialize application", success); hwnd = Application.GetWindowHandle(); SwapChainDesc.BufferDesc = DisplayMode; SwapChainDesc.BufferDesc.Width = width; SwapChainDesc.BufferDesc.Height = height; SwapChainDesc.BufferCount = 1; SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; SwapChainDesc.OutputWindow = hwnd; SwapChainDesc.SampleDesc.Count = 1; SwapChainDesc.SampleDesc.Quality = 0; SwapChainDesc.Windowed = !FullScreen; UINT flags = 0; #ifdef _DEBUG flags |= D3D10_CREATE_DEVICE_DEBUG; #endif hr = D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, flags, D3D10_SDK_VERSION, &SwapChainDesc, &SwapChain, &Graphics); dnassert(false, "CGame10::Initialize(): Could not create device", FAILED(hr)); hr = SwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (void**)&backbuffer); dnassert(false, "CGame10::Initialize(): Could not get backbuffer", FAILED(hr)); hr = Graphics->CreateRenderTargetView(backbuffer, NULL, &RenderTargetView); backbuffer->Release(); dnassert(false, "CGame10::Initialize(): Could not create render target view", FAILED(hr)); // zbuffer if( ZBuffer ) { D3D10_TEXTURE2D_DESC depthdesc; memset(&depthdesc, 0, sizeof(D3D10_TEXTURE2D_DESC)); depthdesc.Width = width; depthdesc.Height = height; depthdesc.MipLevels = 1; depthdesc.ArraySize = 1; depthdesc.Format = DXGI_FORMAT_D32_FLOAT; depthdesc.SampleDesc.Count = 1; depthdesc.SampleDesc.Quality = 0; depthdesc.Usage = D3D10_USAGE_DEFAULT; depthdesc.BindFlags = D3D10_BIND_DEPTH_STENCIL; hr = Graphics->CreateTexture2D(&depthdesc, NULL, &DepthStencil); dnassert(false, "CGame10::Initialize(): Could not create depth buffer", FAILED(hr)); D3D10_DEPTH_STENCIL_VIEW_DESC dsv; memset(&dsv, 0, sizeof(D3D10_DEPTH_STENCIL_VIEW_DESC)); dsv.Format = depthdesc.Format; dsv.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D; dsv.Texture2D.MipSlice = 0; hr = Graphics->CreateDepthStencilView(DepthStencil, &dsv, &DepthStencilView); dnassert(false, "CGame10::Initialize(): Could not create depth stencil view", FAILED(hr)); } Graphics->OMSetRenderTargets(1, &RenderTargetView, DepthStencilView); vp.Width = width; vp.Height = height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; Graphics->RSSetViewports(1, &vp); // ... if( fixedtimestep ) Sync.synchronize.connect(this, &CGame10::Update); return true; }
// Create Direct3D device and swap chain HRESULT DxWidget::InitDevice() { HRESULT hrResult = E_FAIL; HRESULT hrRetCode = E_FAIL; m_driverType = D3D10_DRIVER_TYPE_NULL; UINT createDeviceFlags = 0; D3D10_DRIVER_TYPE driverTypes[] = { D3D10_DRIVER_TYPE_HARDWARE, D3D10_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); ZeroMemory(&m_swapChainDesc, sizeof(m_swapChainDesc)); m_swapChainDesc.BufferCount = 1; m_swapChainDesc.BufferDesc.Width = width(); m_swapChainDesc.BufferDesc.Height = height(); m_swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; m_swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; m_swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; m_swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; m_swapChainDesc.OutputWindow = (HWND)winId(); m_swapChainDesc.SampleDesc.Count = 1; m_swapChainDesc.SampleDesc.Quality = 0; m_swapChainDesc.Windowed = TRUE; for(UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { m_driverType = driverTypes[driverTypeIndex]; hrRetCode = D3D10CreateDeviceAndSwapChain(NULL, m_driverType, NULL, createDeviceFlags, D3D10_SDK_VERSION, &m_swapChainDesc, &m_pSwapChain, &m_pd3dDevice); if(SUCCEEDED(hrRetCode)) break; } KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pSwapChain); KE_PROCESS_ERROR(m_pd3dDevice); // Create a render target view ID3D10Texture2D* pBackBuffer; hrRetCode = m_pSwapChain->GetBuffer(0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBackBuffer); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(pBackBuffer); hrRetCode = m_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pRenderTargetView); m_pd3dDevice->OMSetRenderTargets(1, &m_pRenderTargetView, NULL); // Setup the viewport m_viewPort.Width = width(); m_viewPort.Height = height(); m_viewPort.MinDepth = 0.0f; m_viewPort.MaxDepth = 1.0f; m_viewPort.TopLeftX = 0; m_viewPort.TopLeftY = 0; m_pd3dDevice->RSSetViewports(1, &m_viewPort); // Create the effect DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; hrRetCode = D3DX10CreateEffectFromFile(L"testqt.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, m_pd3dDevice, NULL, NULL, &m_pEffect, NULL, NULL ); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pEffect); // Obtain the technique m_pTechnique = m_pEffect->GetTechniqueByName("Render"); // Define the input layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = sizeof(layout) / sizeof(layout[0]); // Create the input layout D3D10_PASS_DESC PassDesc; m_pTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); hrRetCode = m_pd3dDevice->CreateInputLayout(layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_pVertexLayout); KE_COM_PROCESS_ERROR(hrRetCode); KE_PROCESS_ERROR(m_pVertexLayout); // Set the input layout m_pd3dDevice->IASetInputLayout(m_pVertexLayout); // Set primitive topology m_pd3dDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST); hrResult = S_OK; Exit0: return hrResult; }
D3D10System::D3D10System() { HRESULT err; #ifdef USE_DXGI1_2 REFIID iidVal = OSGetVersion() >= 8 ? __uuidof(IDXGIFactory2) : __uuidof(IDXGIFactory1); #else REFIID iidVal = __uuidof(IDXGIFactory1); #endif UINT adapterID = GlobalConfig->GetInt(TEXT("Video"), TEXT("Adapter"), 0); IDXGIFactory1 *factory; if(FAILED(err = CreateDXGIFactory1(iidVal, (void**)&factory))) CrashError(TEXT("Could not create DXGI factory")); IDXGIAdapter1 *adapter; if(FAILED(err = factory->EnumAdapters1(adapterID, &adapter))) CrashError(TEXT("Could not get DXGI adapter")); //------------------------------------------------------------------ DXGI_SWAP_CHAIN_DESC swapDesc; zero(&swapDesc, sizeof(swapDesc)); swapDesc.BufferCount = 2; swapDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swapDesc.BufferDesc.Width = App->renderFrameWidth; swapDesc.BufferDesc.Height = App->renderFrameHeight; swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapDesc.Flags = 0; swapDesc.OutputWindow = hwndRenderFrame; swapDesc.SampleDesc.Count = 1; swapDesc.Windowed = TRUE; bDisableCompatibilityMode = 1;//AppConfig->GetInt(TEXT("Video"), TEXT("DisableD3DCompatibilityMode"), 1) != 0; UINT createFlags = D3D10_CREATE_DEVICE_BGRA_SUPPORT; if(GlobalConfig->GetInt(TEXT("General"), TEXT("UseDebugD3D"))) createFlags |= D3D10_CREATE_DEVICE_DEBUG; D3D10_FEATURE_LEVEL1 level = bDisableCompatibilityMode ? D3D10_FEATURE_LEVEL_10_1 : D3D10_FEATURE_LEVEL_9_3; //D3D10_CREATE_DEVICE_DEBUG //D3D11_DRIVER_TYPE_REFERENCE, D3D11_DRIVER_TYPE_HARDWARE err = D3D10CreateDeviceAndSwapChain1(adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, createFlags, level, D3D10_1_SDK_VERSION, &swapDesc, &swap, &d3d); if(FAILED(err)) { bDisableCompatibilityMode = !bDisableCompatibilityMode; level = bDisableCompatibilityMode ? D3D10_FEATURE_LEVEL_10_1 : D3D10_FEATURE_LEVEL_9_3; err = D3D10CreateDeviceAndSwapChain1(adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, createFlags, level, D3D10_1_SDK_VERSION, &swapDesc, &swap, &d3d); } if(FAILED(err)) CrashError(TEXT("Could not create D3D10 device and swap chain. This error can happen for one of the following reasons:\r\n\r\n1.) Your GPU is not supported (DirectX 10 support is required - many integrated laptop GPUs do not support DX10)\r\n2.) You're running Windows Vista without the \"Platform Update\"\r\n3.) Your video card drivers are out of date")); adapter->Release(); factory->Release(); //------------------------------------------------------------------ Log(TEXT("Loading up D3D10...")); D3D10_DEPTH_STENCIL_DESC depthDesc; zero(&depthDesc, sizeof(depthDesc)); depthDesc.DepthEnable = FALSE; err = d3d->CreateDepthStencilState(&depthDesc, &depthState); if(FAILED(err)) CrashError(TEXT("Unable to create depth state")); d3d->OMSetDepthStencilState(depthState, 0); //------------------------------------------------------------------ D3D10_RASTERIZER_DESC rasterizerDesc; zero(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.FillMode = D3D10_FILL_SOLID; rasterizerDesc.CullMode = D3D10_CULL_NONE; rasterizerDesc.FrontCounterClockwise = FALSE; rasterizerDesc.DepthClipEnable = TRUE; err = d3d->CreateRasterizerState(&rasterizerDesc, &rasterizerState); if(FAILED(err)) CrashError(TEXT("Unable to create rasterizer state")); d3d->RSSetState(rasterizerState); //------------------------------------------------------------------ rasterizerDesc.ScissorEnable = TRUE; err = d3d->CreateRasterizerState(&rasterizerDesc, &scissorState); if(FAILED(err)) CrashError(TEXT("Unable to create scissor state")); //------------------------------------------------------------------ ID3D10Texture2D *backBuffer = NULL; err = swap->GetBuffer(0, IID_ID3D10Texture2D, (void**)&backBuffer); if(FAILED(err)) CrashError(TEXT("Unable to get back buffer from swap chain")); err = d3d->CreateRenderTargetView(backBuffer, NULL, &swapRenderView); if(FAILED(err)) CrashError(TEXT("Unable to get render view from back buffer")); backBuffer->Release(); //------------------------------------------------------------------ D3D10_BLEND_DESC disabledBlendDesc; zero(&disabledBlendDesc, sizeof(disabledBlendDesc)); for(int i=0; i<8; i++) { disabledBlendDesc.BlendEnable[i] = TRUE; disabledBlendDesc.RenderTargetWriteMask[i] = D3D10_COLOR_WRITE_ENABLE_ALL; } disabledBlendDesc.BlendOpAlpha = D3D10_BLEND_OP_ADD; disabledBlendDesc.BlendOp = D3D10_BLEND_OP_ADD; disabledBlendDesc.SrcBlendAlpha = D3D10_BLEND_ONE; disabledBlendDesc.DestBlendAlpha = D3D10_BLEND_ZERO; disabledBlendDesc.SrcBlend = D3D10_BLEND_ONE; disabledBlendDesc.DestBlend = D3D10_BLEND_ZERO; err = d3d->CreateBlendState(&disabledBlendDesc, &disabledBlend); if(FAILED(err)) CrashError(TEXT("Unable to create disabled blend state")); this->BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA, 1.0f); bBlendingEnabled = true; }
bool initD3DDevice(HWND hWnd) { // Création du device DXGI_SWAP_CHAIN_DESC swapChainDesc; memset(&swapChainDesc, 0, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = SCREEN_WIDTH; swapChainDesc.BufferDesc.Height = SCREEN_HEIGHT; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.RefreshRate.Numerator = REFRESHRATE; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hWnd; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = true; UINT deviceFlags = 0; #ifdef _DEBUG deviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif if(FAILED(D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, D3D10_SDK_VERSION, &swapChainDesc, &g_pSwapChain, &g_pD3DDevice))) return false; // Création de la vue ID3D10Texture2D *pBackBuffer; if(FAILED(g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (void **)&pBackBuffer))) return false; HRESULT res = g_pD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView); pBackBuffer->Release(); if(FAILED(res)) return false; g_pD3DDevice->OMSetRenderTargets(1, &g_pRenderTargetView, NULL); // Initialisation du viewport D3D10_VIEWPORT viewport; viewport.Width = SCREEN_WIDTH; viewport.Height = SCREEN_HEIGHT; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0; viewport.TopLeftY = 0; g_pD3DDevice->RSSetViewports(1, &viewport); // Chargement des shaders DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #ifdef _DEBUG dwShaderFlags |= D3D10_SHADER_DEBUG; #endif if(FAILED(D3DX10CreateEffectFromFile("raytracing.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, g_pD3DDevice, NULL, NULL, &g_pEffect, NULL, NULL))) return false; // Récupération de la technique g_pTechnique = g_pEffect->GetTechniqueByName("Render"); // Création du input layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D10_APPEND_ALIGNED_ELEMENT, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D10_APPEND_ALIGNED_ELEMENT, D3D10_INPUT_PER_VERTEX_DATA, 0}, }; D3D10_PASS_DESC PassDesc; g_pTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); if(FAILED(g_pD3DDevice->CreateInputLayout(layout, 2, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout))) return false; g_pD3DDevice->IASetInputLayout(g_pVertexLayout); // Création du vertex buffer SimpleVertex vertices[] = { {D3DXVECTOR3(-1.0f, -1.0f, 0.5f), D3DXVECTOR2(0.0f, 0.0f)}, {D3DXVECTOR3(-1.0f, 1.0f, 0.5f), D3DXVECTOR2(0.0f, 1.0f)}, {D3DXVECTOR3(1.0f, -1.0f, 0.5f), D3DXVECTOR2(1.0f, 0.0f)}, {D3DXVECTOR3(1.0f, 1.0f, 0.5f), D3DXVECTOR2(1.0f, 1.0f)} }; D3D10_BUFFER_DESC bd; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex)*4; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = vertices; if(FAILED(g_pD3DDevice->CreateBuffer(&bd, &InitData, &g_pVertexBuffer))) return false; UINT stride = sizeof(SimpleVertex); UINT offset = 0; g_pD3DDevice->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset); g_pD3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); return true; }
bool D10State::init() { static HMODREF(GetModuleHandleW(L"D3D10.DLL"), D3D10CreateEffectFromMemory); static HMODREF(GetModuleHandleW(L"D3D10.DLL"), D3D10CreateStateBlock); static HMODREF(GetModuleHandleW(L"D3D10.DLL"), D3D10StateBlockMaskEnableAll); if (pD3D10CreateEffectFromMemory == NULL || pD3D10CreateStateBlock == NULL || pD3D10StateBlockMaskEnableAll == NULL) { ods("D3D10: Could not get handles for all required D3D10 state initialization functions"); return false; } HRESULT hr; D3D10_STATE_BLOCK_MASK StateBlockMask; ZeroMemory(&StateBlockMask, sizeof(StateBlockMask)); hr = pD3D10StateBlockMaskEnableAll(&StateBlockMask); if (FAILED(hr)) { ods("D3D10: D3D10StateBlockMaskEnableAll failed"); return false; } hr = pD3D10CreateStateBlock(pDevice, &StateBlockMask, &pOrigStateBlock); if (FAILED(hr)) { ods("D3D10: D3D10CreateStateBlock for pOrigStateBlock failed"); return false; } hr = pD3D10CreateStateBlock(pDevice, &StateBlockMask, &pMyStateBlock); if (FAILED(hr)) { ods("D3D10: D3D10CreateStateBlock for pMyStateBlock failed"); return false; } hr = pOrigStateBlock->Capture(); if (FAILED(hr)) { ods("D3D10: Failed to store original state block during init"); return false; } ID3D10Texture2D *pBackBuffer = NULL; hr = pSwapChain->GetBuffer(0, __uuidof(*pBackBuffer), (LPVOID*)&pBackBuffer); if (FAILED(hr)) { ods("D3D10: pSwapChain->GetBuffer failure!"); return false; } pDevice->ClearState(); D3D10_TEXTURE2D_DESC backBufferSurfaceDesc; pBackBuffer->GetDesc(&backBufferSurfaceDesc); ZeroMemory(&vp, sizeof(vp)); vp.Width = backBufferSurfaceDesc.Width; vp.Height = backBufferSurfaceDesc.Height; vp.MinDepth = 0; vp.MaxDepth = 1; vp.TopLeftX = 0; vp.TopLeftY = 0; pDevice->RSSetViewports(1, &vp); hr = pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRTV); if (FAILED(hr)) { ods("D3D10: pDevice->CreateRenderTargetView failed!"); return false; } pDevice->OMSetRenderTargets(1, &pRTV, NULL); // Settings for an "over" operation. // https://en.wikipedia.org/w/index.php?title=Alpha_compositing&oldid=580659153#Description D3D10_BLEND_DESC blend; ZeroMemory(&blend, sizeof(blend)); blend.BlendEnable[0] = TRUE; blend.SrcBlend = D3D10_BLEND_ONE; blend.DestBlend = D3D10_BLEND_INV_SRC_ALPHA; blend.BlendOp = D3D10_BLEND_OP_ADD; blend.SrcBlendAlpha = D3D10_BLEND_ONE; blend.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA; blend.BlendOpAlpha = D3D10_BLEND_OP_ADD; blend.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; hr = pDevice->CreateBlendState(&blend, &pBlendState); if (FAILED(hr)) { ods("D3D10: pDevice->CreateBlendState failed!"); return false; } pDevice->OMSetBlendState(pBlendState, NULL, 0xffffffff); hr = pD3D10CreateEffectFromMemory((void *) g_main, sizeof(g_main), 0, pDevice, NULL, &pEffect); if (FAILED(hr)) { ods("D3D10: D3D10CreateEffectFromMemory failed!"); return false; } pTechnique = pEffect->GetTechniqueByName("Render"); if (pTechnique == NULL) { ods("D3D10: Could not get technique for name 'Render'"); return false; } pDiffuseTexture = pEffect->GetVariableByName("txDiffuse")->AsShaderResource(); if (pDiffuseTexture == NULL) { ods("D3D10: Could not get variable by name 'txDiffuse'"); return false; } pTexture = NULL; pSRView = NULL; // Define the input layout D3D10_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = sizeof(layout) / sizeof(layout[0]); // Create the input layout D3D10_PASS_DESC PassDesc; hr = pTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); if (FAILED(hr)) { ods("D3D10: Couldn't get pass description for technique"); return false; } hr = pDevice->CreateInputLayout(layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &pVertexLayout); if (FAILED(hr)) { ods("D3D10: pDevice->CreateInputLayout failure!"); return false; } pDevice->IASetInputLayout(pVertexLayout); D3D10_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D10_USAGE_DYNAMIC; bd.ByteWidth = sizeof(SimpleVertex) * 4; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; bd.MiscFlags = 0; hr = pDevice->CreateBuffer(&bd, NULL, &pVertexBuffer); if (FAILED(hr)) { ods("D3D10: pDevice->CreateBuffer failure!"); return false; } DWORD indices[] = { 0,1,3, 1,2,3, }; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(DWORD) * 6; bd.BindFlags = D3D10_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = indices; hr = pDevice->CreateBuffer(&bd, &InitData, &pIndexBuffer); if (FAILED(hr)) { ods("D3D10: pDevice->CreateBuffer failure!"); return false; } // Set index buffer pDevice->IASetIndexBuffer(pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); // Set primitive topology pDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); hr = pMyStateBlock->Capture(); if (FAILED(hr)) { ods("D3D10: Failed to capture newly created state block"); return false; } hr = pOrigStateBlock->Apply(); if (FAILED(hr)) { ods("D3D10: Failed to restore original state block during init"); return false; } pBackBuffer->Release(); return true; }