void HackerContext::FrameAnalysisClearRT(ID3D11RenderTargetView *target) { FLOAT colour[4] = {0,0,0,0}; ID3D11Resource *resource = NULL; // FIXME: Do this before each draw call instead of when render targets // are assigned to fix assigned render targets not being cleared, and // work better with frame analysis triggers if (!(G->cur_analyse_options & FrameAnalysisOptions::CLEAR_RT)) return; // Use the address of the resource rather than the view to determine if // we have seen it before so we don't clear a render target that is // simply used as several different types of views: target->GetResource(&resource); if (!resource) return; resource->Release(); // Don't need the object, only the address if (G->frame_analysis_seen_rts.count(resource)) return; G->frame_analysis_seen_rts.insert(resource); mOrigContext->ClearRenderTargetView(target, colour); }
Vector2f CTextureManager::GetTextureSize( ID3D11ShaderResourceView* aResourceView, bool aNormalize) const { ID3D11Resource* resource = nullptr; aResourceView->GetResource(&resource); if (!resource) { return Vector2f(0, 0); } ID3D11Texture2D* txt = reinterpret_cast<ID3D11Texture2D*>( resource ); D3D11_TEXTURE2D_DESC desc; txt->GetDesc( &desc ); Vector2f size(static_cast<float>(desc.Width), static_cast<float>(desc.Height)); resource->Release(); Vector2<float> windowSize; windowSize.x = static_cast<float>(CEngine::GetInstance()->GetWindowSize().y); windowSize.y = static_cast<float>(CEngine::GetInstance()->GetWindowSize().y); if (aNormalize) { return size / windowSize; } return size; }
void screenshot(const string& name) { #ifndef WINSTORE_SUPPORT CreateDirectoryA("screenshots", 0); time_t t = std::time(nullptr); struct tm time_info; localtime_s(&time_info, &t); stringstream ss(""); if (name.length() <= 0) ss << "screenshots/sc_" << std::put_time(&time_info, "%d-%m-%Y %H-%M-%S") << ".png"; else ss << name; wstringstream wss(L""); wss << ss.str().c_str(); ID3D11Resource* res = nullptr; wiRenderer::renderTargetView->GetResource(&res); HRESULT h = SaveWICTextureToFile(wiRenderer::immediateContext, res, GUID_ContainerFormatPng, wss.str().c_str()); if (FAILED(h)) wiBackLog::post("Screenshot failed"); else { ss << " Saved successfully!"; wiBackLog::post(ss.str().c_str()); } res->Release(); #endif }
void HackerContext::FrameAnalysisClearUAV(ID3D11UnorderedAccessView *uav) { UINT values[4] = {0,0,0,0}; ID3D11Resource *resource = NULL; // FIXME: Do this before each draw/dispatch call instead of when UAVs // are assigned to fix assigned render targets not being cleared, and // work better with frame analysis triggers if (!(G->cur_analyse_options & FrameAnalysisOptions::CLEAR_RT)) return; // Use the address of the resource rather than the view to determine if // we have seen it before so we don't clear a render target that is // simply used as several different types of views: uav->GetResource(&resource); if (!resource) return; resource->Release(); // Don't need the object, only the address if (G->frame_analysis_seen_rts.count(resource)) return; G->frame_analysis_seen_rts.insert(resource); mOrigContext->ClearUnorderedAccessViewUint(uav, values); }
void MyD3DAssets::loadPSTexture(int textureIndex) { ID3D11ShaderResourceView *view = nullptr; context->base->PSGetShaderResources(textureIndex, 1, &view); if (view == nullptr) { PSTexture.free(); } else { ID3D11Resource *textureResource = nullptr; view->GetResource(&textureResource); ID3D11Texture2D* texture = nullptr; HRESULT hr = textureResource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&texture)); if (texture == nullptr || FAILED(hr)) { PSTexture.free(); g_logger->logErrorFile << "textureResource->QueryInterface failed" << endl; } else { readTexture(texture, PSTexture); texture->Release(); } textureResource->Release(); view->Release(); } }
void initAll(ID3D11Device& device, ID3D11DeviceContext& context, ShaderResources& shaderResources) { assert(shaderResources.mDiffuseMapSRV == nullptr); assert(shaderResources.mCSResultsSRV == nullptr); assert(shaderResources.mCSResultsUAV == nullptr); ID3D11Resource* texture = nullptr; // // Diffuse Map // HRESULT result = CreateDDSTextureFromFile(&device, L"Resources/Textures/brick.dds", &texture, &shaderResources.mDiffuseMapSRV); DxErrorChecker(result); texture->Release(); // // Create compute shader texture // D3D11_TEXTURE2D_DESC groupResultsTexDesc; groupResultsTexDesc.Width = 512; groupResultsTexDesc.Height = 512; groupResultsTexDesc.MipLevels = 1; groupResultsTexDesc.ArraySize = 1; groupResultsTexDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; groupResultsTexDesc.SampleDesc.Count = 1; groupResultsTexDesc.SampleDesc.Quality = 0; groupResultsTexDesc.Usage = D3D11_USAGE_DEFAULT; groupResultsTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; groupResultsTexDesc.CPUAccessFlags = 0; groupResultsTexDesc.MiscFlags = 0; ID3D11Texture2D* groupResultsTex = nullptr; assert(Globals::gDirect3DData.mDevice); result = device.CreateTexture2D(&groupResultsTexDesc, 0, &groupResultsTex); DxErrorChecker(result); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; result = device.CreateTexture2D(&groupResultsTexDesc, 0, &groupResultsTex); result = device.CreateShaderResourceView(groupResultsTex, &srvDesc, &shaderResources.mCSResultsSRV); D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; uavDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = 0; result = device.CreateUnorderedAccessView(groupResultsTex, &uavDesc, &shaderResources.mCSResultsUAV); // Views save a reference to the texture so we can release our reference. groupResultsTex->Release(); }
void LoadSkybox(ID3D11Device* d3dDevice, LPCWSTR fileName) { ID3D11Resource* resource = 0; HRESULT hr; hr = D3DX11CreateTextureFromFile(d3dDevice, fileName, 0, 0, &resource, 0); assert(SUCCEEDED(hr)); d3dDevice->CreateShaderResourceView(resource, 0, &gSkyboxSRV); resource->Release(); }
//------------------------------------------------------------------------------- void D3D11RenderSystem::CopyFrameBufferToTexture( D3D11Texture* pTexture ) { ID3D11Resource* pSrcTex = nullptr; m_pRenderTargetView->GetResource(&pSrcTex); m_pDeviceContext->CopyResource(pTexture->GetInternalTex(), pSrcTex); pSrcTex->Release(); pTexture->CreateSRV(); }
int32 CGameObject::Initialize() { ApplyShader(); D3D11_BLEND_DESC blendDesc = {}; blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; theDevice->CreateBlendState( &blendDesc, &m_alphaBlendState ); theContext->OMSetBlendState( m_alphaBlendState, blendFactor, 0xFFFFFFFF ); D3D11_SAMPLER_DESC samplerDesc = {}; samplerDesc.AddressU = samplerDesc.AddressV = samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; // samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC; // samplerDesc.MaxAnisotropy = 4; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; HR( theDevice->CreateSamplerState( &samplerDesc, &m_pTextureSampler ) ); ID3D11Resource* pcolorTex = 00; m_material.GetDiffuse()->GetResource( &pcolorTex ); D3D11_TEXTURE2D_DESC colorTexDesc = {}; (reinterpret_cast<ID3D11Texture2D*>(pcolorTex))->GetDesc( &colorTexDesc ); pcolorTex->Release(); BuildBuffers(); D3D11_SAMPLER_DESC colorMapDesc = {}; colorMapDesc.AddressU = colorMapDesc.AddressV = colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; // colorMapDesc.Filter = D3D11_FILTER_ANISOTROPIC; // colorMapDesc.MaxAnisotropy = 4; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; HR( theDevice->CreateSamplerState( &colorMapDesc, &m_pTextureSampler ) ); m_pFXWorld = m_effect->GetVariableByName( "gWorld" )->AsMatrix(); m_pFXTexture = m_effect->GetVariableByName( "gTexture" )->AsShaderResource(); m_pFXTextureSampler = m_effect->GetVariableByName( "gTextureSampler" )->AsSampler(); return 0; }
bool xD11BaseTexture::saveToFile(const wchar_t* fileName) { D3DX11_IMAGE_FILE_FORMAT fFormat = xD11ConstLexer::GetDX11ImageFileFormat(fileName); if((int)fFormat == -1) return false; ID3D11Resource* pResource = this->GetD11Resource(); if(pResource == NULL) return false; HRESULT hr = D3DX11SaveTextureToFileW(m_pD11RenderApi->d11DeviceContext() , pResource , fFormat , fileName); pResource->Release(); return SUCCEEDED(hr); }
void FD3D12CommandContext::CheckIfSRVIsResolved(FD3D12ShaderResourceView* SRV) { // MSFT: Seb: TODO: Make this work on 12 #if CHECK_SRV_TRANSITIONS if (GRHIThread || !SRV) { return; } static const auto CheckSRVCVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.CheckSRVTransitions")); if (!CheckSRVCVar->GetValueOnRenderThread()) { return; } ID3D11Resource* SRVResource = nullptr; SRV->GetResource(&SRVResource); int32 MipLevel; int32 NumMips; int32 ArraySlice; int32 NumSlices; GetMipAndSliceInfoFromSRV(SRV, MipLevel, NumMips, ArraySlice, NumSlices); //d3d uses -1 to mean 'all mips' int32 LastMip = MipLevel + NumMips - 1; int32 LastSlice = ArraySlice + NumSlices - 1; TArray<FUnresolvedRTInfo> RTInfoArray; UnresolvedTargets.MultiFind(SRVResource, RTInfoArray); for (int32 InfoIndex = 0; InfoIndex < RTInfoArray.Num(); ++InfoIndex) { const FUnresolvedRTInfo& RTInfo = RTInfoArray[InfoIndex]; int32 RTLastMip = RTInfo.MipLevel + RTInfo.NumMips - 1; ensureMsgf((MipLevel == -1 || NumMips == -1) || (LastMip < RTInfo.MipLevel || MipLevel > RTLastMip), TEXT("SRV is set to read mips in range %i to %i. Target %s is unresolved for mip %i"), MipLevel, LastMip, *RTInfo.ResourceName.ToString(), RTInfo.MipLevel); ensureMsgf(NumMips != -1, TEXT("SRV is set to read all mips. Target %s is unresolved for mip %i"), *RTInfo.ResourceName.ToString(), RTInfo.MipLevel); int32 RTLastSlice = RTInfo.ArraySlice + RTInfo.ArraySize - 1; ensureMsgf((ArraySlice == -1 || LastSlice == -1) || (LastSlice < RTInfo.ArraySlice || ArraySlice > RTLastSlice), TEXT("SRV is set to read slices in range %i to %i. Target %s is unresolved for mip %i"), ArraySlice, LastSlice, *RTInfo.ResourceName.ToString(), RTInfo.ArraySlice); ensureMsgf(ArraySlice == -1 || NumSlices != -1, TEXT("SRV is set to read all slices. Target %s is unresolved for slice %i")); } SRVResource->Release(); #endif }
//----------------------------------------------------------------------------- CPUTTexture *CPUTTextureDX11::CreateTexture( const cString &name, const cString &absolutePathAndFilename, bool loadAsSRGB ) { // TODO: Delegate to derived class. We don't currently have CPUTTextureDX11 ID3D11ShaderResourceView *pShaderResourceView = NULL; ID3D11Resource *pTexture = NULL; ID3D11Device *pD3dDevice= CPUT_DX11::GetDevice(); CPUTResult result = CreateNativeTexture( pD3dDevice, absolutePathAndFilename, &pShaderResourceView, &pTexture, loadAsSRGB ); ASSERT( CPUTSUCCESS(result), _L("Error loading texture: '")+absolutePathAndFilename ); CPUTTextureDX11 *pNewTexture = new CPUTTextureDX11(); pNewTexture->mName = name; pNewTexture->SetTextureAndShaderResourceView( pTexture, pShaderResourceView ); pTexture->Release(); pShaderResourceView->Release(); CPUTAssetLibrary::GetAssetLibrary()->AddTexture( absolutePathAndFilename, pNewTexture); return pNewTexture; }
//----------------------------------------------------------------------------// void Direct3D11Texture::initialiseShaderResourceView() { if (!d_texture) return; D3D11_TEXTURE2D_DESC tex_desc; d_texture->GetDesc(&tex_desc); ID3D11Resource* resource = 0; d_texture->QueryInterface(__uuidof(ID3D11Resource), reinterpret_cast<LPVOID*>(&resource)); D3D11_SHADER_RESOURCE_VIEW_DESC srvd; srvd.Format = tex_desc.Format; srvd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvd.Texture2D.MostDetailedMip = 0; srvd.Texture2D.MipLevels = tex_desc.MipLevels; d_device.d_device->CreateShaderResourceView(resource, &srvd, &d_resourceView); resource->Release(); }
void HackerContext::DumpUAVs(bool compute) { UINT i; NvAPI_Status nvret; ID3D11UnorderedAccessView *uavs[D3D11_PS_CS_UAV_REGISTER_COUNT]; ID3D11Resource *resource; wchar_t filename[MAX_PATH]; HRESULT hr; if (analyse_options & FrameAnalysisOptions::STEREO) { // Enable reverse stereo blit for all resources we are about to dump: nvret = NvAPI_Stereo_ReverseStereoBlitControl(mHackerDevice->mStereoHandle, true); if (nvret != NVAPI_OK) { LogInfo("DumpStereoResource failed to enable reverse stereo blit\n"); // Continue anyway, we should still be able to dump in 2D... } } mOrigContext->CSGetUnorderedAccessViews(0, D3D11_PS_CS_UAV_REGISTER_COUNT, uavs); for (i = 0; i < D3D11_PS_CS_UAV_REGISTER_COUNT; ++i) { if (!uavs[i]) continue; uavs[i]->GetResource(&resource); if (!resource) { uavs[i]->Release(); continue; } hr = FrameAnalysisFilename(filename, MAX_PATH, compute, true, false, i); if (SUCCEEDED(hr)) DumpResource(resource, filename); resource->Release(); uavs[i]->Release(); } if (analyse_options & FrameAnalysisOptions::STEREO) NvAPI_Stereo_ReverseStereoBlitControl(mHackerDevice->mStereoHandle, false); }
void ResourcesManager::initAll(ID3D11Device* device, ID3D11DeviceContext* context) { assert(device); assert(context); ID3D11Resource* texture = nullptr; // Create grass texture shader resource view HRESULT result = CreateDDSTextureFromFile(device, L"Resources/Textures/sand.dds", &texture, &mSandSRV); DxErrorChecker(result); // Create sky cube map shader resource view result = CreateDDSTextureFromFile(device, L"Resources/Textures/desertcube1024.dds", &texture, &mSkyCubeMapSRV); DxErrorChecker(result); // Create sphere diffuse map texture result = CreateDDSTextureFromFile(device, L"Resources/Textures/stone.dds", &texture, &mSphereDiffuseMapSRV); DxErrorChecker(result); texture->Release(); }
//-- SetRenderTarget ---------------------------------------------------------- // //----------------------------------------------------------------------------- void Renderer::SetRenderTarget(TextureDX* texture) { if (texture == NULL || texture->GetRenderTarget() == NULL) return; ID3D11Texture2D* pTexture = texture->GetTexture(); D3D11_TEXTURE2D_DESC txDesc, dtxDesc; pTexture->GetDesc(&txDesc); ID3D11Resource* pResource = NULL; ID3D11Texture2D* pDepthTexture = NULL; g_depthView->GetResource(&pResource); pResource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pDepthTexture)); pDepthTexture->GetDesc(&dtxDesc); pDepthTexture->Release(); pResource->Release(); // depth view dimension must be equals render target dimension if (txDesc.Width != dtxDesc.Width || txDesc.Height != dtxDesc.Height) { SAFE_RELEASE( g_depthView ); CD3D11_TEXTURE2D_DESC depthBufferDesc(DXGI_FORMAT_D24_UNORM_S8_UINT, txDesc.Width, txDesc.Height, 1, 1, D3D11_BIND_DEPTH_STENCIL); m_pD3D11Device->CreateTexture2D(&depthBufferDesc, NULL, &pDepthTexture); CD3D11_DEPTH_STENCIL_VIEW_DESC viewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); m_pD3D11Device->CreateDepthStencilView(pDepthTexture, &viewDesc, &g_depthView); pDepthTexture->Release(); } else m_pD3D11Contex->ClearDepthStencilView(g_depthView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0, 0); ID3D11RenderTargetView* rtView = texture->GetRenderTarget(); // change view port to render target dimension like dx9 does CD3D11_VIEWPORT vp(pTexture, rtView); m_pD3D11Contex->RSSetViewports(1, &vp); m_pD3D11Contex->OMSetRenderTargets(1, &rtView, g_depthView); } // SetRenderTarget
void ResourcesManager::initAll(ID3D11Device* device, ID3D11DeviceContext* context) { assert(device); assert(context); ID3D11Resource* texture = nullptr; // Create diffuse and normal maps HRESULT result = CreateDDSTextureFromFile(device, L"Resources/Textures/wood1.dds", &texture, &mFloorDiffuseMapSRV); DxErrorChecker(result); result = CreateDDSTextureFromFile(device, L"Resources/Textures/wood1Normal.dds", &texture, &mFloorNormalMapSRV); DxErrorChecker(result); result = CreateDDSTextureFromFile(device, L"Resources/Textures/brick.dds", &texture, &mCylinderDiffuseMapSRV); DxErrorChecker(result); result = CreateDDSTextureFromFile(device, L"Resources/Textures/brickNormal.dds", &texture, &mCylinderNormalMapSRV); DxErrorChecker(result); texture->Release(); }
ID3D11VideoProcessorInputView* CProcessorHD::GetInputView(ID3D11View* view) { ID3D11VideoProcessorInputView* inputView = nullptr; if (m_context) // we have own context so the view will be processor input view { inputView = reinterpret_cast<ID3D11VideoProcessorInputView*>(view); inputView->AddRef(); // it will be released in Render method return inputView; } // the view came from decoder ID3D11VideoDecoderOutputView* decoderView = reinterpret_cast<ID3D11VideoDecoderOutputView*>(view); if (!decoderView) { CLog::Log(LOGERROR, __FUNCTION__" - cannot get view."); return nullptr; } ID3D11Resource* resource = nullptr; D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC vdovd; decoderView->GetDesc(&vdovd); decoderView->GetResource(&resource); D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC vpivd = { 0 }; vpivd.FourCC = 0; // if zero, the driver uses the DXGI format; must be 0 on level 9.x vpivd.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D; vpivd.Texture2D.ArraySlice = vdovd.Texture2D.ArraySlice; vpivd.Texture2D.MipSlice = 0; if (FAILED(m_pVideoDevice->CreateVideoProcessorInputView(resource, m_pEnumerator, &vpivd, &inputView))) { CLog::Log(LOGERROR, __FUNCTION__" - cannot create processor view."); } resource->Release(); return inputView; }
ID3D11VideoProcessorInputView* CProcessorHD::GetInputView(CRenderBuffer* view) const { ID3D11VideoProcessorInputView* inputView = nullptr; D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC vpivd = { 0, D3D11_VPIV_DIMENSION_TEXTURE2D,{ 0, 0 } }; if (view->format == BUFFER_FMT_D3D11_BYPASS) { // the view cames from decoder ID3D11VideoDecoderOutputView* decoderView = reinterpret_cast<ID3D11VideoDecoderOutputView*>(view->GetHWView()); if (!decoderView) { CLog::Log(LOGERROR, "%s: cannot get decoder view.", __FUNCTION__); return nullptr; } ID3D11Resource* resource = nullptr; D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC vdovd; decoderView->GetDesc(&vdovd); decoderView->GetResource(&resource); vpivd.Texture2D.ArraySlice = vdovd.Texture2D.ArraySlice; if (FAILED(m_pVideoDevice->CreateVideoProcessorInputView(resource, m_pEnumerator, &vpivd, &inputView))) CLog::Log(LOGERROR, "%s: cannot create processor input view.", __FUNCTION__); resource->Release(); } else if (view->format == BUFFER_FMT_D3D11_NV12 || view->format == BUFFER_FMT_D3D11_P010 || view->format == BUFFER_FMT_D3D11_P016) { if (FAILED(m_pVideoDevice->CreateVideoProcessorInputView(view->GetResource(), m_pEnumerator, &vpivd, &inputView))) CLog::Log(LOGERROR, "%s: cannot create processor input view.", __FUNCTION__); } return inputView; }
bool PerlinFire::LoadTexture2D(ID3D11Device * pd3dDevice, LPCWSTR fileName, ID3D11Texture2D ** tex, ID3D11ShaderResourceView ** texRV) { HRESULT hr; ID3D11Resource * pRes = NULL; D3DX11CreateTextureFromFile( pd3dDevice, fileName, NULL, NULL, &pRes, &hr ); pRes->QueryInterface( __uuidof(ID3D11Texture2D), (LPVOID*) tex); D3D11_TEXTURE2D_DESC desc; (*tex)->GetDesc(& desc); D3D11_SHADER_RESOURCE_VIEW_DESC descSRV; ZeroMemory( &descSRV, sizeof(descSRV) ); descSRV.Format = desc.Format; descSRV.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; descSRV.Texture2D.MipLevels = desc.MipLevels; pd3dDevice->CreateShaderResourceView( *tex, &descSRV, texRV ); pRes->Release(); return true; }
ID3D11VideoProcessorInputView* CProcessorHD::GetInputView(ID3D11View* view) { ID3D11VideoProcessorInputView* inputView = nullptr; if (m_eViewType == PROCESSOR_VIEW_TYPE_PROCESSOR) { inputView = reinterpret_cast<ID3D11VideoProcessorInputView*>(view); inputView->AddRef(); // it will be released later } else if (m_eViewType == PROCESSOR_VIEW_TYPE_DECODER) { // the view cames from decoder ID3D11VideoDecoderOutputView* decoderView = reinterpret_cast<ID3D11VideoDecoderOutputView*>(view); if (!decoderView) { CLog::Log(LOGERROR, "%s - cannot get view.", __FUNCTION__); return nullptr; } ID3D11Resource* resource = nullptr; D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC vdovd; decoderView->GetDesc(&vdovd); decoderView->GetResource(&resource); D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC vpivd = { { 0 } }; vpivd.FourCC = 0; vpivd.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D; vpivd.Texture2D.ArraySlice = vdovd.Texture2D.ArraySlice; vpivd.Texture2D.MipSlice = 0; if (FAILED(m_pVideoDevice->CreateVideoProcessorInputView(resource, m_pEnumerator, &vpivd, &inputView))) CLog::Log(LOGERROR, "%s - cannot create processor view.", __FUNCTION__); resource->Release(); } return inputView; }
// ---------------------------------------------------------------------------------------------- Texture* TextureLib::LoadEmbeddedTexture(ID3D11Device* device, const wchar_t* name) { assert(s_Inst != NULL); Imple* pImple = s_Inst->m_pImple; typedef std::pair<std::wstring, Texture*> NameTexPair; const wchar_t* resType = L"Texture"; HRESULT hr = E_FAIL; Texture* tex = NULL; ID3D11Resource* dxresource = NULL; ID3D11ShaderResourceView* dxTexView = NULL; uint32_t resSize = 0; uint8_t* data = (uint8_t*)ResUtil::LoadResource(resType, name, &resSize); hr = CreateWICTextureFromMemory(device, NULL, data, resSize, &dxresource, &dxTexView); free(data); if (!Logger::IsFailureLog(hr, L"Error loading %s\n", name)) { D3D11_RESOURCE_DIMENSION resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; dxresource->GetType(&resDim); assert(resDim == D3D11_RESOURCE_DIMENSION_TEXTURE2D); ID3D11Texture2D* dxTex = NULL; hr = dxresource->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&dxTex); dxresource->Release(); assert(dxTex); tex = new Texture(dxTex, dxTexView); auto insertResult = pImple->m_textures.insert(NameTexPair(name, tex)); assert(insertResult.second); } return tex; }
void TextureLib::InitInstance(ID3D11Device* device) { s_Inst = new TextureLib(); Imple* pImple = s_Inst->m_pImple; // color format ABGR pImple->m_defaultTextures[TextureType::DIFFUSE] = CreateCheckerboardTexture2D(device, 128, 128, 0xFF404040, 0xFF808080); pImple->m_defaultTextures[TextureType::Cubemap] = CreateCheckerboardTexture2D(device, 128, 128, 0xff000040, 0xff000080, true); pImple->m_defaultTextures[TextureType::NORMAL] = CreateSolidTexture2D(device, 8, 8, 0xFFFF8080); pImple->m_defaultTextures[TextureType::LIGHT] = CreateSolidTexture2D(device, 8, 8, 0xFFFFFFFF); pImple->m_defaultTextures[TextureType::SPEC] = CreateSolidTexture2D(device, 8, 8, 0xFF000000); pImple->m_defaultTextures[TextureType::BlankMask] = CreateSolidTexture2D(device, 4, 4, 0x00); pImple->m_defaultTextures[TextureType::FullMask] = CreateSolidTexture2D(device, 4, 4, 0xFFFFFFFF); pImple->m_whiteTexture = CreateSolidTexture2D(device, 8, 8, 0xFFFFFFFF); typedef std::pair<std::wstring, Texture*> NameTexPair; uint32_t resCount = ResUtil::ResourceCount(); for(uint32_t i = 0; i < resCount; i++) { const wchar_t* resName = ResUtil::GetResourceName(i); const std::wstring ext = FileUtils::GetExtensionLower(resName); HRESULT hr = E_FAIL; Texture* tex = NULL; ID3D11Resource* dxresource = NULL; ID3D11ShaderResourceView* dxTexView = NULL; uint32_t resSize = 0; if(ext == L".dds") { uint8_t* data = ResUtil::LoadResource(resName,&resSize); if(resSize == 0) continue; hr = CreateDDSTextureFromMemory( device, data, resSize, &dxresource, &dxTexView); free(data); } else if(ext == L".png" || ext == L".bmp" || ext == L".jpeg") { uint8_t* data = ResUtil::LoadResource(resName,&resSize); if(resSize == 0) continue; hr = CreateWICTextureFromMemory( device, NULL, data, resSize, &dxresource, &dxTexView); free(data); } if (Logger::IsFailureLog(hr, L"Error loading %s\n", resName)) { continue; } D3D11_RESOURCE_DIMENSION resType = D3D11_RESOURCE_DIMENSION_UNKNOWN; dxresource->GetType( &resType ); assert( resType == D3D11_RESOURCE_DIMENSION_TEXTURE2D); ID3D11Texture2D* dxTex = NULL; hr = dxresource->QueryInterface( __uuidof(ID3D11Texture2D), (void**) &dxTex ); dxresource->Release(); assert(dxTex); tex = new Texture(dxTex,dxTexView); auto insertResult = pImple->m_textures.insert(NameTexPair(resName,tex)); assert(insertResult.second); } }
// 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; }
void DoD3D11Capture(IDXGISwapChain *swap) { ID3D11Device *device = NULL; HRESULT chi; if(SUCCEEDED(chi = swap->GetDevice(__uuidof(ID3D11Device), (void**)&device))) { if(!lpCurrentDevice) { lpCurrentDevice = device; /*FARPROC curRelease = GetVTable(device, (8/4)); if(curRelease != newD3D11Release) { oldD3D11Release = curRelease; newD3D11Release = (FARPROC)DeviceReleaseHook; SetVTable(device, (8/4), newD3D11Release); }*/ } ID3D11DeviceContext *context; device->GetImmediateContext(&context); if(bCapturing && bStopRequested) { ClearD3D11Data(); bCapturing = false; bStopRequested = false; } if(!bCapturing && WaitForSingleObject(hSignalRestart, 0) == WAIT_OBJECT_0) { hwndOBS = FindWindow(OBS_WINDOW_CLASS, NULL); if(hwndOBS) bCapturing = true; } if(!bHasTextures && bCapturing) { if(dxgiFormat && hwndOBS) { BOOL bSuccess = DoD3D11Hook(device); if(bSuccess) { d3d11CaptureInfo.mapID = InitializeSharedMemoryGPUCapture(&texData); if(!d3d11CaptureInfo.mapID) { RUNONCE logOutput << "SwapPresentHook: creation of shared memory failed" << endl; bSuccess = false; } } if(bSuccess) { bHasTextures = true; d3d11CaptureInfo.captureType = CAPTURETYPE_SHAREDTEX; d3d11CaptureInfo.bFlip = FALSE; texData->texHandle = (DWORD)sharedHandle; memcpy(infoMem, &d3d11CaptureInfo, sizeof(CaptureInfo)); SetEvent(hSignalReady); logOutput << "DoD3D11Hook: success" << endl; } else { ClearD3D11Data(); } } } if(bHasTextures) { LONGLONG timeVal = OSGetTimeMicroseconds(); //check keep alive state, dumb but effective if(bCapturing) { if((timeVal-keepAliveTime) > 3000000) { HANDLE hKeepAlive = OpenEvent(EVENT_ALL_ACCESS, FALSE, strKeepAlive.c_str()); if (hKeepAlive) { CloseHandle(hKeepAlive); } else { ClearD3D11Data(); bCapturing = false; } keepAliveTime = timeVal; } } LONGLONG frameTime; if(bCapturing) { if(texData) { if(frameTime = texData->frameTime) { LONGLONG timeElapsed = timeVal-lastTime; if(timeElapsed >= frameTime) { if(!IsWindow(hwndOBS)) { hwndOBS = NULL; bStopRequested = true; } if(WaitForSingleObject(hSignalEnd, 0) == WAIT_OBJECT_0) bStopRequested = true; lastTime += frameTime; if(timeElapsed > frameTime*2) lastTime = timeVal; DWORD nextCapture = curCapture == 0 ? 1 : 0; ID3D11Resource *backBuffer = NULL; if(SUCCEEDED(swap->GetBuffer(0, IID_ID3D11Resource, (void**)&backBuffer))) { if(bIsMultisampled) context->ResolveSubresource(copyTextureGame, 0, backBuffer, 0, dxgiFormat); else context->CopyResource(copyTextureGame, backBuffer); backBuffer->Release(); } curCapture = nextCapture; } } } } else ClearD3D11Data(); } device->Release(); context->Release(); } }
HRESULT STDMETHODCALLTYPE SwapPresentHook(UINT syncInterval, UINT flags) { IDXGISwapChain *swap = (IDXGISwapChain*)this; if(lpCurrentSwap == NULL && !bTargetAcquired) { lpCurrentSwap = swap; SetupD3D11(swap); bTargetAcquired = true; } if(lpCurrentSwap == swap) { ID3D11Device *device = NULL; HRESULT chi; if(SUCCEEDED(chi = swap->GetDevice(__uuidof(ID3D11Device), (void**)&device))) { if(!lpCurrentDevice) { lpCurrentDevice = device; oldD3D11Release = GetVTable(device, (8/4)); newD3D11Release = ConvertClassProcToFarproc((CLASSPROC)&D3D11Override::DeviceReleaseHook); SetVTable(device, (8/4), newD3D11Release); } ID3D11DeviceContext *context; device->GetImmediateContext(&context); if(!bHasTextures && bCapturing) { if(dxgiFormat) { if(!hwndReceiver) hwndReceiver = FindWindow(RECEIVER_WINDOWCLASS, NULL); if(hwndReceiver) { D3D11_TEXTURE2D_DESC texDesc; ZeroMemory(&texDesc, sizeof(texDesc)); texDesc.Width = d3d11CaptureInfo.cx; texDesc.Height = d3d11CaptureInfo.cy; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.Format = dxgiFormat; texDesc.SampleDesc.Count = 1; texDesc.Usage = D3D11_USAGE_STAGING; texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; bool bSuccess = true; UINT pitch; for(UINT i=0; i<2; i++) { HRESULT ching; if(FAILED(ching = device->CreateTexture2D(&texDesc, NULL, &d3d11Textures[i]))) { bSuccess = false; break; } if(i == 0) { ID3D11Resource *resource; if(FAILED(d3d11Textures[i]->QueryInterface(__uuidof(ID3D11Resource), (void**)&resource))) { bSuccess = false; break; } D3D11_MAPPED_SUBRESOURCE map; if(FAILED(context->Map(resource, 0, D3D11_MAP_READ, 0, &map))) { bSuccess = false; break; } pitch = map.RowPitch; context->Unmap(resource, 0); resource->Release(); } } if(bSuccess) { d3d11CaptureInfo.mapID = InitializeSharedMemory(pitch*d3d11CaptureInfo.cy, &d3d11CaptureInfo.mapSize, ©Data, textureBuffers); if(!d3d11CaptureInfo.mapID) bSuccess = false; } if(bSuccess) { bHasTextures = true; d3d11CaptureInfo.captureType = CAPTURETYPE_MEMORY; d3d11CaptureInfo.hwndSender = hwndSender; d3d11CaptureInfo.pitch = pitch; d3d11CaptureInfo.bFlip = FALSE; PostMessage(hwndReceiver, RECEIVER_NEWCAPTURE, 0, (LPARAM)&d3d11CaptureInfo); } else { for(UINT i=0; i<2; i++) { SafeRelease(d3d11Textures[i]); if(textureBuffers[i]) { free(textureBuffers[i]); textureBuffers[i] = NULL; } } } } } } if(bHasTextures) { if(bCapturing) { DWORD nextCapture = curCapture == 0 ? 1 : 0; ID3D11Texture2D *texture = d3d11Textures[curCapture]; ID3D11Resource *backBuffer = NULL; if(SUCCEEDED(swap->GetBuffer(0, IID_ID3D11Resource, (void**)&backBuffer))) { if(bIsMultisampled) context->ResolveSubresource(texture, 0, backBuffer, 0, dxgiFormat); else context->CopyResource(texture, backBuffer); backBuffer->Release(); ID3D11Texture2D *lastTexture = d3d11Textures[nextCapture]; ID3D11Resource *resource; if(SUCCEEDED(lastTexture->QueryInterface(__uuidof(ID3D11Resource), (void**)&resource))) { D3D11_MAPPED_SUBRESOURCE map; if(SUCCEEDED(context->Map(resource, 0, D3D11_MAP_READ, 0, &map))) { LPBYTE *pTextureBuffer = NULL; int lastRendered = -1; //under no circumstances do we -ever- allow a stall if(WaitForSingleObject(textureMutexes[curCapture], 0) == WAIT_OBJECT_0) lastRendered = (int)curCapture; else if(WaitForSingleObject(textureMutexes[nextCapture], 0) == WAIT_OBJECT_0) lastRendered = (int)nextCapture; if(lastRendered != -1) { SSECopy(textureBuffers[lastRendered], map.pData, map.RowPitch*d3d11CaptureInfo.cy); ReleaseMutex(textureMutexes[lastRendered]); } context->Unmap(resource, 0); copyData->lastRendered = (UINT)lastRendered; } resource->Release(); } } curCapture = nextCapture; } else ClearD3D11Data(); } device->Release(); context->Release(); } } gi11swapPresent.Unhook(); HRESULT hRes = swap->Present(syncInterval, flags); gi11swapPresent.Rehook(); return hRes; }
HRESULT STDMETHODCALLTYPE D3D11SwapPresentHook(IDXGISwapChain *swap, UINT syncInterval, UINT flags) { if(lpCurrentSwap == NULL && !bTargetAcquired) { lpCurrentSwap = swap; SetupD3D11(swap); bTargetAcquired = true; } if(lpCurrentSwap == swap) { ID3D11Device *device = NULL; HRESULT chi; if(SUCCEEDED(chi = swap->GetDevice(__uuidof(ID3D11Device), (void**)&device))) { if(!lpCurrentDevice) { lpCurrentDevice = device; /*FARPROC curRelease = GetVTable(device, (8/4)); if(curRelease != newD3D11Release) { oldD3D11Release = curRelease; newD3D11Release = (FARPROC)DeviceReleaseHook; SetVTable(device, (8/4), newD3D11Release); }*/ } ID3D11DeviceContext *context; device->GetImmediateContext(&context); if(bCapturing && bStopRequested) { ClearD3D11Data(); bStopRequested = false; } if(!bHasTextures && bCapturing) { if(dxgiFormat) { if(!hwndReceiver) hwndReceiver = FindWindow(RECEIVER_WINDOWCLASS, NULL); if(hwndReceiver) { BOOL bSuccess = DoD3D11Hook(device); if(bSuccess) { d3d11CaptureInfo.mapID = InitializeSharedMemoryGPUCapture(&texData); if(!d3d11CaptureInfo.mapID) { RUNONCE logOutput << "SwapPresentHook: creation of shared memory failed" << endl; bSuccess = false; } } if(bSuccess) bSuccess = IsWindow(hwndReceiver); if(bSuccess) { bHasTextures = true; d3d11CaptureInfo.captureType = CAPTURETYPE_SHAREDTEX; d3d11CaptureInfo.hwndSender = hwndSender; d3d11CaptureInfo.bFlip = FALSE; texData->texHandles[0] = sharedHandles[0]; texData->texHandles[1] = sharedHandles[1]; PostMessage(hwndReceiver, RECEIVER_NEWCAPTURE, 0, (LPARAM)&d3d11CaptureInfo); logOutput << "DoD3D11Hook: success"; } else { ClearD3D11Data(); } } } } if(bHasTextures) { LONGLONG frameTime; if(bCapturing) { if(texData) { if(frameTime = texData->frameTime) { LONGLONG timeVal = OSGetTimeMicroseconds(); LONGLONG timeElapsed = timeVal-lastTime; if(timeElapsed >= frameTime) { lastTime += frameTime; if(timeElapsed > frameTime*2) lastTime = timeVal; DWORD nextCapture = curCapture == 0 ? 1 : 0; ID3D11Resource *backBuffer = NULL; if(SUCCEEDED(swap->GetBuffer(0, IID_ID3D11Resource, (void**)&backBuffer))) { if(bIsMultisampled) context->ResolveSubresource(copyTextureGame, 0, backBuffer, 0, dxgiFormat); else context->CopyResource(copyTextureGame, backBuffer); ID3D10Texture2D *outputTexture = NULL; int lastRendered = -1; if(keyedMutexes[curCapture]->AcquireSync(0, 0) == WAIT_OBJECT_0) lastRendered = (int)curCapture; else if(keyedMutexes[nextCapture]->AcquireSync(0, 0) == WAIT_OBJECT_0) lastRendered = (int)nextCapture; if(lastRendered != -1) { shareDevice->CopyResource(sharedTextures[lastRendered], copyTextureIntermediary); keyedMutexes[lastRendered]->ReleaseSync(0); } texData->lastRendered = lastRendered; backBuffer->Release(); } curCapture = nextCapture; } } } } else ClearD3D11Data(); } device->Release(); context->Release(); } } gi11swapPresent.Unhook(); HRESULT hRes = swap->Present(syncInterval, flags); gi11swapPresent.Rehook(); return hRes; }
void TextureLib::InitInstance(ID3D11Device* device) { s_Inst = new TextureLib(); Imple* pImple = s_Inst->m_pImple; pImple->m_defaultTextures[TextureType::DIFFUSE] = CreateCheckerboardTexture2D(device, 128, 128, 0xFF404040, 0xFF808080, false,true); pImple->m_defaultTextures[TextureType::DIFFUSE]->SetTextureType(TextureType::DIFFUSE); pImple->m_defaultTextures[TextureType::Cubemap] = CreateCheckerboardTexture2D(device, 128, 128, 0xff000040, 0xff000080, true); pImple->m_defaultTextures[TextureType::Cubemap]->SetTextureType(TextureType::Cubemap); pImple->m_defaultTextures[TextureType::NORMAL] = CreateSolidTexture2D(device, 8, 8, 0xFFFF8080); pImple->m_defaultTextures[TextureType::NORMAL]->SetTextureType(TextureType::NORMAL); pImple->m_defaultTextures[TextureType::LIGHT] = CreateSolidTexture2D(device, 8, 8, 0xFFFFFFFF); pImple->m_defaultTextures[TextureType::LIGHT]->SetTextureType(TextureType::LIGHT); pImple->m_defaultTextures[TextureType::SPEC] = CreateSolidTexture2D(device, 8, 8, 0xFF000000); pImple->m_defaultTextures[TextureType::SPEC]->SetTextureType(TextureType::SPEC); pImple->m_defaultTextures[TextureType::BlankMask] = CreateSolidTexture2D(device, 4, 4, 0x00); pImple->m_defaultTextures[TextureType::BlankMask]->SetTextureType(TextureType::BlankMask); pImple->m_defaultTextures[TextureType::FullMask] = CreateSolidTexture2D(device, 4, 4, 0xFFFFFFFF); pImple->m_defaultTextures[TextureType::FullMask]->SetTextureType(TextureType::FullMask); pImple->m_whiteTexture = CreateSolidTexture2D(device, 8, 8, 0xFFFFFFFF); typedef std::pair<std::wstring, Texture*> NameTexPair; const wchar_t* resName = L"Light.png"; const wchar_t* resType = L"Texture"; HRESULT hr = E_FAIL; Texture* tex = NULL; ID3D11Resource* dxresource = NULL; ID3D11ShaderResourceView* dxTexView = NULL; uint32_t resSize = 0; uint8_t* data = (uint8_t*)ResUtil::LoadResource(resType, resName,&resSize); hr = CreateWICTextureFromMemory( device, NULL, data, resSize, &dxresource, &dxTexView); free(data); if (!Logger::IsFailureLog(hr, L"Error loading %s\n", resName)) { D3D11_RESOURCE_DIMENSION resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; dxresource->GetType( &resDim ); assert( resDim == D3D11_RESOURCE_DIMENSION_TEXTURE2D); ID3D11Texture2D* dxTex = NULL; hr = dxresource->QueryInterface( __uuidof(ID3D11Texture2D), (void**) &dxTex ); dxresource->Release(); assert(dxTex); tex = new Texture(dxTex,dxTexView); auto insertResult = pImple->m_textures.insert(NameTexPair(resName,tex)); assert(insertResult.second); } }
bool SplashScreen::LoadContent( ) { ID3DBlob* vsBuffer = 0; // compile the vertex shader from fx file bool compileResult = game_->CompileD3DShader( "TextureMap_Sprites.fx", "VS_Main", "vs_4_0", &vsBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling the vertex shader!" ); return false; } HRESULT d3dResult; // create the vertex shader d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), 0, &solidColorVS_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the vertex shader!" ); if( vsBuffer ) vsBuffer->Release( ); return false; } D3D11_INPUT_ELEMENT_DESC solidColorLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout ); // create the input layout d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements, vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ ); vsBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating the input layout!" ); return false; } ID3DBlob* psBuffer = 0; // compile the pixel shader from fx file compileResult = game_->CompileD3DShader( "TextureMap_Sprites.fx", "PS_Main", "ps_4_0", &psBuffer ); if( compileResult == false ) { DXTRACE_MSG( "Error compiling pixel shader!" ); return false; } // create the pixel shader d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ), psBuffer->GetBufferSize( ), 0, &solidColorPS_ ); psBuffer->Release( ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Error creating pixel shader!" ); return false; } // load the texture image d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_, "Assets/Images/Menu.png", 0, 0, &colorMap_, 0 ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to load the texture image!" ); return false; } D3D11_SAMPLER_DESC colorMapDesc; ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) ); colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX; // create the sampler state d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorMapSampler_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create color map sampler state!" ); return false; } ID3D11Resource* colorTex; colorMap_->GetResource( &colorTex ); D3D11_TEXTURE2D_DESC colorTexDesc; ( ( ID3D11Texture2D* )colorTex )->GetDesc( &colorTexDesc ); colorTex->Release( ); float halfWidth = ( float )colorTexDesc.Width / 2.0f; float halfHeight = ( float )colorTexDesc.Height / 2.0f; D3D11_BUFFER_DESC vertexDesc; ZeroMemory( &vertexDesc, sizeof( vertexDesc ) ); vertexDesc.Usage = D3D11_USAGE_DYNAMIC; vertexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof( VertexPos ) * 4; // create the vertex buffer d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, 0, &vertexBuffer_ ); if( FAILED( d3dResult ) ) { DXTRACE_MSG( "Failed to create vertex buffer!" ); return false; } D3D11_BUFFER_DESC constDesc; ZeroMemory( &constDesc, sizeof( constDesc ) ); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = sizeof( XMMATRIX ); constDesc.Usage = D3D11_USAGE_DEFAULT; // create the constant buffer d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &mvpCB_ ); if( FAILED( d3dResult ) ) { return false; } // load the sprite sheet with sprite names and coordinates spriteSheet_ = new SpriteSheet( game_, 3, 6, ( float )colorTexDesc.Width, ( float )colorTexDesc.Height ); spriteWidth_ = spriteSheet_->GetSheetWidth( ) / spriteSheet_->GetHorizontalSprites( ); spriteHeight_ = spriteSheet_->GetSheetHeight( ) / spriteSheet_->GetVerticalSprites( ); // add coordinates to animations vector<XMFLOAT2> menu; menu.push_back( XMFLOAT2( 0.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "menu" , menu, -1 ); vector<XMFLOAT2> menu_play; menu_play.push_back( XMFLOAT2( 1.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "menu_play" , menu_play, -1 ); vector<XMFLOAT2> menu_instructions; menu_instructions.push_back( XMFLOAT2( 0.0f, 1.0f ) ); spriteSheet_->AddAnimationToMap( "menu_instructions" , menu_instructions, -1 ); vector<XMFLOAT2> menu_credits; menu_credits.push_back( XMFLOAT2( 1.0f, 1.0f ) ); spriteSheet_->AddAnimationToMap( "menu_credits" , menu_credits, -1 ); vector<XMFLOAT2> menu_exit; menu_exit.push_back( XMFLOAT2( 0.0f, 2.0f ) ); spriteSheet_->AddAnimationToMap( "menu_exit" , menu_exit, -1 ); vector<XMFLOAT2> instructions; instructions.push_back( XMFLOAT2( 1.0f, 2.0f ) ); spriteSheet_->AddAnimationToMap( "instructions" , instructions, -1 ); vector<XMFLOAT2> instructions_back; instructions_back.push_back( XMFLOAT2( 0.0f, 3.0f ) ); spriteSheet_->AddAnimationToMap( "instructions_back" , instructions_back, -1 ); vector<XMFLOAT2> credits; credits.push_back( XMFLOAT2( 1.0f, 3.0f ) ); spriteSheet_->AddAnimationToMap( "credits" , credits, -1 ); vector<XMFLOAT2> credits_back; credits_back.push_back( XMFLOAT2( 0.0f, 4.0f ) ); spriteSheet_->AddAnimationToMap( "credits_back" , credits_back, -1 ); vector<XMFLOAT2> game_over; game_over.push_back( XMFLOAT2( 1.0f, 4.0f ) ); spriteSheet_->AddAnimationToMap( "game_over" , game_over, -1 ); vector<XMFLOAT2> game_over_replay; game_over_replay.push_back( XMFLOAT2( 0.0f, 5.0f ) ); spriteSheet_->AddAnimationToMap( "game_over_replay" , game_over_replay, -1 ); vector<XMFLOAT2> game_over_menu; game_over_menu.push_back( XMFLOAT2( 1.0f, 5.0f ) ); spriteSheet_->AddAnimationToMap( "game_over_menu" , game_over_menu, -1 ); vector<XMFLOAT2> victory; victory.push_back( XMFLOAT2( 2.0f, 0.0f ) ); spriteSheet_->AddAnimationToMap( "victory" , victory, -1 ); vector<XMFLOAT2> victory_replay; victory_replay.push_back( XMFLOAT2( 2.0f, 1.0f ) ); spriteSheet_->AddAnimationToMap( "victory_replay" , victory_replay, -1 ); vector<XMFLOAT2> victory_back; victory_back.push_back( XMFLOAT2( 2.0f, 2.0f ) ); spriteSheet_->AddAnimationToMap( "victory_back" , victory_back, -1 ); // create sprite menu sprite_ = spriteSheet_->CreateSprite( collisionTemplate_, spriteWidth_, spriteHeight_, 0.0f, XMFLOAT2( game_->GetScreenWidth( ) / 2, game_->GetScreenHeight( ) / 2 ) ); sprite_.SetCurrentAnimation( "menu" ); // load button positions on splash screen play_ = XMFLOAT4( 500.0f, 595.0f, game_->GetScreenHeight( ) - 391.0f, game_->GetScreenHeight( ) - 330.0f ); instructions_ = XMFLOAT4( 500.0f, 762.0f, game_->GetScreenHeight( ) - 451.0f, game_->GetScreenHeight( ) - 390.0f ); credits_ = XMFLOAT4( 500.0f, 652.0f, game_->GetScreenHeight( ) - 511.0f, game_->GetScreenHeight( ) - 450.0f ); exit_ = XMFLOAT4( 500.0f, 586.0f, game_->GetScreenHeight( ) - 571.0f, game_->GetScreenHeight( ) - 510.0f ); replay_ = XMFLOAT4( 84.0f, 235.0f, game_->GetScreenHeight( ) - 577.0f, game_->GetScreenHeight( ) - 506.0f ); menu_ = XMFLOAT4( 611.0f, 721.0f, game_->GetScreenHeight( ) - 570.0f, game_->GetScreenHeight( ) - 509.0f ); back_ = XMFLOAT4( 616.0f, 722.0f, game_->GetScreenHeight( ) - 560.0f, game_->GetScreenHeight( ) - 499.0f ); // load mouse cursor if( !mouseCursor_->LoadContent( ) ) return false; // load score if( !score_->LoadContent( ) ) return false; Initialize( ); return true; }
void Display::renderPrevious() { //Currently a mess but it works! Memory::releaseDynamic(prevStateSRV_); ID3D11Texture2D* t; ID3D11Texture2D* t2; D3D11_TEXTURE2D_DESC texDesc; texDesc.ArraySize = 1; texDesc.BindFlags = 0; texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // must be same as backbuffer texDesc.Width = Core::getViewport().width; // must be same as backbuffer texDesc.Height = Core::getViewport().height; // must be same as backbuffer texDesc.MipLevels = 1; texDesc.MiscFlags = 0; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_STAGING; D3D11_TEXTURE2D_DESC texDesc2; texDesc2.ArraySize = 1; texDesc2.BindFlags = D3D11_BIND_SHADER_RESOURCE; texDesc2.CPUAccessFlags = 0; texDesc2.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // must be same as backbuffer texDesc2.Width = Core::getViewport().width; // must be same as backbuffer texDesc2.Height = Core::getViewport().height; // must be same as backbuffer texDesc2.MipLevels = 1; texDesc2.MiscFlags = 0; texDesc2.SampleDesc.Count = 1; texDesc2.SampleDesc.Quality = 0; texDesc2.Usage = D3D11_USAGE_DEFAULT; device_->CreateTexture2D(&texDesc, 0, &t); device_->CreateTexture2D(&texDesc2, 0, &t2); context_->OMSetRenderTargets(0, nullptr, nullptr); ID3D11Resource *backbufferRes; mainRTV_->GetResource(&backbufferRes); context_->CopyResource(t, backbufferRes); backbufferRes->Release(); D3D11_MAPPED_SUBRESOURCE map; context_->Map(t, 0, D3D11_MAP_READ_WRITE, 0, &map); const int width = Core::getViewport().width; const int height = Core::getViewport().height; for (int y = 0; y < height; ++y) { unsigned char* ptr = (unsigned char*)map.pData + (unsigned int)y * map.RowPitch + 3; for (int x = 0; x < width; ++x) { *ptr = 0xFF; ptr += 4; } } context_->Unmap(t, 0); context_->CopyResource(t2, t); //D3DX11SaveTextureToFile(context_, t2, D3DX11_IFF_PNG, "backbuffer.png"); //debug output D3D11_TEXTURE2D_DESC desc; t2->GetDesc(&desc); D3D11_SHADER_RESOURCE_VIEW_DESC SRDesc; SRDesc.Format = desc.Format; SRDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRDesc.Texture2D.MostDetailedMip = 0; SRDesc.Texture2D.MipLevels = desc.MipLevels; device_->CreateShaderResourceView(t2,&SRDesc , &prevStateSRV_); //device_->CreateShaderResourceView(getTexture("test")->getTexture(),&SRDesc , &prevStateSRV_); t->Release(); t2->Release(); }