예제 #1
0
파일: Texture.cpp 프로젝트: Daivuk/ggj16
    Texture* Texture::createDynamic(const sSize& size)
    {
        ID3D11Texture2D* pTexture = NULL;
        ID3D11ShaderResourceView* pTextureView = NULL;
        auto pRet = new Texture();

        D3D11_TEXTURE2D_DESC desc;
        desc.Width = size.x;
        desc.Height = size.y;
        desc.MipLevels = desc.ArraySize = 1;
        desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        desc.SampleDesc.Count = 1;
        desc.SampleDesc.Quality = 0;
        desc.Usage = D3D11_USAGE_DYNAMIC;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
        desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        desc.MiscFlags = 0;

        auto pDevice = ORenderer->getDevice();
        auto ret = pDevice->CreateTexture2D(&desc, NULL, &pTexture);
        assert(ret == S_OK);
        ret = pDevice->CreateShaderResourceView(pTexture, NULL, &pTextureView);
        assert(ret == S_OK);

        pRet->m_size = size;
        pRet->m_pTextureView = pTextureView;
        pRet->m_pTexture = pTexture;

        return pRet;
    }
	GLRenderResourceManager::GLRenderResourceManager()
	{
		RasterizeDesc rasterDesc;
		DefaultRasterizeState = CreateRasterizeState(&rasterDesc);

		BlendDesc blendDesc;
		DefaultBlentState = CreateBlendState(&blendDesc, 1);

		DepthStencilDesc dsDesc;
		DefaultDepthStencilState = CreateDepthStencilState(&dsDesc, 0);

		SamplerDesc samplerDesc;
		DefaultSamplerState = CreateSamplerState(&samplerDesc);

		unsigned int pixelData[16];
		memset(pixelData, 0xFF, 16 * sizeof(unsigned int));
		BufferInitData data;
		data.Data = pixelData;
		data.RowPitch = 4 * 4;
		data.SlicePitch = 0;
		RenderTexture2D* tex = CreateTexture2D("DefaultTex", NULL, PF_R8G8B8A8_UNORM, 4, 4, false, false, SV_ShaderResource, 1, &data, 0);
		DefaultWhiteTexture2D = CreateSurfaceView(SV_ShaderResource, tex, PF_R8G8B8A8_UNORM);

		RegisterPropertyManager(ShaderPropertyManager::sManagerCamera);
		RegisterPropertyManager(ShaderPropertyManager::sManagerObject);
		RegisterPropertyManager(ShaderPropertyManager::sManagerMaterial);
		RegisterPropertyManager(ShaderPropertyManager::sManagerDirectionLight);
		RegisterPropertyManager(ShaderPropertyManager::sManagerPointLight);
		RegisterPropertyManager(ShaderPropertyManager::sManagerSpotLight);
		RegisterPropertyManager(ShaderPropertyManager::sManagerScene);
		RegisterPropertyManager(ShaderPropertyManager::sManagerShadowMapGen);
		RegisterPropertyManager(ShaderPropertyManager::sManagerGlobal);
	}
예제 #3
0
파일: Texture.cpp 프로젝트: Daivuk/ggj16
    void Texture::createRenderTargetViews(ID3D11Texture2D*& pTexture, ID3D11ShaderResourceView*& pTextureView, ID3D11RenderTargetView*& pRenderTargetView)
    {
        auto pDevice = ORenderer->getDevice();

        D3D11_TEXTURE2D_DESC textureDesc = {0};
        HRESULT result;
        D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
        D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
        memset(&renderTargetViewDesc, 0, sizeof(renderTargetViewDesc));
        memset(&shaderResourceViewDesc, 0, sizeof(shaderResourceViewDesc));

        // Setup the render target texture description.
        textureDesc.Width = m_size.x;
        textureDesc.Height = m_size.y;
        textureDesc.MipLevels = 1;
        textureDesc.ArraySize = 1;
        textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        textureDesc.SampleDesc.Count = 1;
        textureDesc.Usage = D3D11_USAGE_DEFAULT;
        textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        textureDesc.CPUAccessFlags = 0;
        textureDesc.MiscFlags = 0;

        // Create the render target texture.
        result = pDevice->CreateTexture2D(&textureDesc, NULL, &pTexture);
        if (result != S_OK)
        {
            assert(false && "Failed CreateTexture2D");
            return;
        }

        // Setup the description of the render target view.
        renderTargetViewDesc.Format = textureDesc.Format;
        renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
        renderTargetViewDesc.Texture2D.MipSlice = 0;

        // Create the render target view.
        result = pDevice->CreateRenderTargetView(pTexture, &renderTargetViewDesc, &pRenderTargetView);
        if (result != S_OK)
        {
            assert(false && "Failed CreateRenderTargetView");
            return;
        }

        // Setup the description of the shader resource view.
        shaderResourceViewDesc.Format = textureDesc.Format;
        shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
        shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
        shaderResourceViewDesc.Texture2D.MipLevels = 1;

        // Create the shader resource view.
        result = pDevice->CreateShaderResourceView(pTexture, &shaderResourceViewDesc, &pTextureView);
        if (result != S_OK)
        {
            assert(false && "Failed CreateShaderResourceView");
            return;
        }
    }
예제 #4
0
void DX11Engine::createSwapChainRenderTargets(IUnknown** ppRTV, IUnknown** ppRTVsRGB, 
    IUnknown** ppDSV, IUnknown* pNativeDevice, IUnknown* pSwapChainIn, 
    size_t length, const char* debugName) const
{
    auto pSwapChain = reinterpret_cast<IDXGISwapChain*>(pSwapChainIn);
    auto pDevice = reinterpret_cast<ID3D11Device*>(pNativeDevice);
        
    HRESULT hr = S_OK;
    std::unique_ptr<ID3D11Texture2D, COMDeleter> pD3D11Texture;
        
    // rtv
    DXGI_SWAP_CHAIN_DESC desc;
    V(pSwapChain->GetDesc(&desc));
    V(pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), ref(pD3D11Texture)));
    STAR_SET_DEBUG_NAME(pD3D11Texture, length, debugName);

    CD3D11_RENDER_TARGET_VIEW_DESC rtvDesc(D3D11_RTV_DIMENSION_TEXTURE2D);

    rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    ID3D11RenderTargetView* pRTV;
    V(pDevice->CreateRenderTargetView(pD3D11Texture.get(), &rtvDesc, &pRTV));
    *ppRTV = pRTV;
    STAR_SET_DEBUG_NAME(pRTV, length, debugName);

    rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
    V(pDevice->CreateRenderTargetView(pD3D11Texture.get(), &rtvDesc, &pRTV));
    *ppRTVsRGB = pRTV;
    STAR_SET_DEBUG_STRING(pRTV, (debugName + std::string("_sRGB")));
    
    // dsv
    if(ppDSV) {
        D3D11_TEXTURE2D_DESC descTex2D = {
            desc.BufferDesc.Width,
            desc.BufferDesc.Height,
            1, 1, DXGI_FORMAT_D32_FLOAT,{ 1, 0 },
            D3D11_USAGE_DEFAULT, D3D11_BIND_DEPTH_STENCIL,
            0, 0
        };
        
        
        std::unique_ptr<ID3D11Texture2D, COMDeleter> pDST;
        V(pDevice->CreateTexture2D(&descTex2D, nullptr, ref(pDST)));
        STAR_SET_DEBUG_NAME(pDST, length, debugName);

        D3D11_DEPTH_STENCIL_VIEW_DESC descV = {
            DXGI_FORMAT_D32_FLOAT, D3D11_DSV_DIMENSION_TEXTURE2D, 0,{ 0 }
        };
        ID3D11DepthStencilView* pDSV;
        V(pDevice->CreateDepthStencilView(pDST.get(), &descV, &pDSV));
        *ppDSV = pDSV;
        STAR_SET_DEBUG_NAME(pDSV, length, debugName);
    }
}
예제 #5
0
IUnknown* DX11Engine::createTexture2D_SRV(IUnknown* pDeviceIn, const Texture& info, 
    const char* buffer, size_t size, const char* name) const
{
    auto pDevice = reinterpret_cast<ID3D11Device*>(pDeviceIn);

    HRESULT hr;
    D3D11_TEXTURE2D_DESC tex = {
        uint32_t(info.mWidth), uint32_t(info.mHeight),
        uint32_t(info.mMipCount), uint32_t(info.mArraySize), info.mFormat, { 1, 0 },
        D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE,
        0, 0
    };

    if(info.eMiscGenerateMipMaps) {
        tex.MipLevels = 0;
        tex.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
        tex.BindFlags |= D3D11_BIND_RENDER_TARGET;
    }

    uint32_t bpp = getBitsPerPixel(info.mFormat);

    int level = 1;
    if (info.eMiscGenerateMipMaps)
        level = log2i(std::max(info.mWidth, info.mHeight)) + 1;

    boost::container::small_vector<D3D11_SUBRESOURCE_DATA, 12> subres(level);

    int w = info.mWidth;
    int h = info.mHeight;

    for (int i = 0; i != level; ++i) {
        subres[i] = D3D11_SUBRESOURCE_DATA{ buffer, w * bpp / 8, 0 };
        buffer += mipmap_size<1>(w, h, bpp);
        w = next_mip_size(w);
        h = next_mip_size(h);        
    }

    std::unique_ptr<ID3D11Texture2D, COMDeleter> pTex;

    std::unique_ptr<ID3D11ShaderResourceView, COMDeleter> pSRV;
    CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(D3D11_SRV_DIMENSION_TEXTURE2D);

    V(pDevice->CreateTexture2D(&tex, subres.data(), ref(pTex)));
    V(pDevice->CreateShaderResourceView(pTex.get(), &srvDesc, ref(pSRV)));

    STAR_SET_DEBUG_NAME(pSRV, size, name);

    return pSRV.release();
}
예제 #6
0
void D3DTexture2D::Initialize(int width, int height, DXGI_FORMAT format, UINT bind, UINT misc, const D3D11_SUBRESOURCE_DATA* data)
{
	D3D11_TEXTURE2D_DESC desc;

	this->width = width;
	this->height = height;
	
	SetupDefaultDescription(desc, width, height, format, bind, misc);
	// 派生クラスによるオーバーライド
	// この辺、付け焼刃な感じなので後で変える可能性あり
	SetupDescription(desc);

	auto device = core->GetDevice();
	auto hresult = device->CreateTexture2D(&desc, data, &this->texture);

	this->AddResource(HndToRes(texture));

	if (bind & D3D10_BIND_SHADER_RESOURCE) { // ShaderResourceViewの作成
		device->CreateShaderResourceView(texture, nullptr, &srv);

		this->AddResource(HndToRes(srv));
	}
	else {
		srv = nullptr;
	}

	if (bind & D3D10_BIND_RENDER_TARGET) { // RenderTargetViewの作成
		device->CreateRenderTargetView(texture, nullptr, &rtv);

		this->AddResource(HndToRes(rtv));
	}
	else {
		rtv = nullptr;
	}

	if (bind & D3D10_BIND_DEPTH_STENCIL) { // DepthStencilViewの作成
		device->CreateDepthStencilView(texture, nullptr, &dsv);

		this->AddResource(HndToRes(dsv));
	}
	else {
		dsv = nullptr;
	}

}
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
   esContext->userData = malloc(sizeof(UserData));
	
   UserData *userData = esContext->userData;
   GLbyte vShaderStr[] =
      "uniform float u_offset;      \n"
      "attribute vec4 a_position;   \n"
      "attribute vec2 a_texCoord;   \n"
      "varying vec2 v_texCoord;     \n"
      "void main()                  \n"
      "{                            \n"
      "   gl_Position = a_position; \n"
      "   gl_Position.x += u_offset;\n"
      "   v_texCoord = a_texCoord;  \n"
      "}                            \n";
   
   GLbyte fShaderStr[] =  
      "precision mediump float;                            \n"
      "varying vec2 v_texCoord;                            \n"
      "uniform sampler2D s_texture;                        \n"
      "void main()                                         \n"
      "{                                                   \n"
      "  gl_FragColor = texture2D( s_texture, v_texCoord );\n"
      "}                                                   \n";

   // Load the shaders and get a linked program object
   userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );

   // Get the attribute locations
   userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
   userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
   
   // Get the sampler location
   userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );

   // Get the offset location
   userData->offsetLoc = glGetUniformLocation( userData->programObject, "u_offset" );

   // Load the texture
   userData->textureId = CreateTexture2D ();

   glClearColor ( 0.0f, 0.0f, 0.0f, 1.0f );
   return GL_TRUE;
}
예제 #8
0
	void OnStart() override
	{
		auto scene = std::make_shared<asd::Scene>();
		auto layer = std::make_shared<asd::Layer2D>();
		auto obj = std::make_shared<asd::TextureObject2D>();
		scene->AddLayer(layer);
		layer->AddObject(obj);
		asd::Engine::ChangeScene(scene);

		auto g = asd::Engine::GetGraphics();
		auto texture = g->CreateTexture2D(asd::ToAString("Data/Texture/Sample1.png").c_str());
		obj->SetTexture(texture);
		obj->SetScale(asd::Vector2DF(1, 1));

		pe = std::make_shared<asd::PostEffectGaussianBlur>();
		pe->SetIntensity(intensity);
		layer->AddPostEffect(pe);

	}
예제 #9
0
///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
   UserData *userData = esContext->userData;
   char vShaderStr[] =
      "#version 300 es                            \n"
      "uniform float u_offset;                    \n"
      "layout(location = 0) in vec4 a_position;   \n"
      "layout(location = 1) in vec2 a_texCoord;   \n"
      "out vec2 v_texCoord;                       \n"
      "void main()                                \n"
      "{                                          \n"
      "   gl_Position = a_position;               \n"
      "   gl_Position.x += u_offset;              \n"
      "   v_texCoord = a_texCoord;                \n"
      "}                                          \n";

   char fShaderStr[] =
      "#version 300 es                                     \n"
      "precision mediump float;                            \n"
      "in vec2 v_texCoord;                                 \n"
      "layout(location = 0) out vec4 outColor;             \n"
      "uniform sampler2D s_texture;                        \n"
      "void main()                                         \n"
      "{                                                   \n"
      "   outColor = texture( s_texture, v_texCoord );     \n"
      "}                                                   \n";

   // Load the shaders and get a linked program object
   userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );

   // Get the sampler location
   userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );

   // Get the offset location
   userData->offsetLoc = glGetUniformLocation ( userData->programObject, "u_offset" );

   // Load the texture
   userData->textureId = CreateTexture2D ();

   glClearColor ( 1.0f, 1.0f, 1.0f, 0.0f );
   return TRUE;
}
예제 #10
0
	void OnStart() override
	{
		auto scene = std::make_shared<asd::Scene>();
		auto layer = std::make_shared<asd::Layer2D>();
		auto obj= std::make_shared<asd::TextureObject2D>();
		scene->SetHDRMode(true);
		scene->AddLayer(layer);
		layer->AddObject(obj);
		asd::Engine::ChangeScene(scene);

		auto g = asd::Engine::GetGraphics();
		auto texture = g->CreateTexture2D(asd::ToAString("Data/Texture/Sample1.png").c_str());
		obj->SetTexture(texture);
		obj->SetScale(asd::Vector2DF(1, 1));

		auto pe = std::make_shared<asd::PostEffectLightBloom>();
		pe->SetIntensity(5.0f);
		pe->SetThreshold(0.2f);
		pe->SetExposure(3.0f);
		layer->AddPostEffect(pe);
	}
예제 #11
0
	void DepthStencil::Initialize(int width, int height)
	{
		this->format = D24_UNORM_S8_UINT;
		this->width = width;
		this->height = height;
		isValid = false;

		depthStencilView.Release();
		srv.Release();

		CreateTexture2D(width, height, format, USAGE_DEFAULT, BIND_DEPTH_STENCIL);

		auto& graphic = GraphicDevice::Instance();

		auto hr = graphic->device->CreateDepthStencilView(texture2D, 0, &depthStencilView.p);
		if(FAILED(hr)) {
			isValid = false;
			return;
		}
		isValid = true;
	}
예제 #12
0
void EffectSystemD3D11::UpdateTexture2D(int effectID, const char *name, const char *path)
{
	ASSERT_EFFECT(effectID);
	std::string key(path);
	// 检查是否已创建
	if (mTexture2Ds.find(key) == mTexture2Ds.end())
	{
		CreateTexture2D(key);
	}
	// set resource
	ID3D11ShaderResourceView *resource = mTexture2Ds[key];
	ID3DX11EffectShaderResourceVariable *resourceVariable = mEffects[effectID]->GetVariableByName(name)->AsShaderResource();
	if (resourceVariable->IsValid())
	{
		resourceVariable->SetResource(resource);
	}
	else
	{
		LogSystem::GetInstance().Log("effect shader resource「%s」非法", name);
		return;
	}
}
예제 #13
0
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT GPUCompressBC::Compress( const Image& srcImage, const Image& destImage )
{
    if ( !srcImage.pixels || !destImage.pixels )
        return E_INVALIDARG;

    if ( srcImage.width != destImage.width
         || srcImage.height != destImage.height
         || srcImage.width != m_width
         || srcImage.height != m_height
         || srcImage.format != m_srcformat
         || destImage.format != m_bcformat )
    {
        return E_UNEXPECTED;
    }

    //--- Create input texture --------------------------------------------------------
    auto pDevice = m_device.Get();
    if ( !pDevice )
        return E_POINTER;

    // We need to avoid the hardware doing additional colorspace conversion
    DXGI_FORMAT inputFormat = ( m_srcformat == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB ) ? DXGI_FORMAT_R8G8B8A8_UNORM : m_srcformat;

    ScopedObject<ID3D11Texture2D> sourceTex;
    {
        D3D11_TEXTURE2D_DESC desc;
        memset( &desc, 0, sizeof(desc) );
        desc.Width = static_cast<UINT>( srcImage.width );
        desc.Height = static_cast<UINT>( srcImage.height ); 
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = inputFormat;
        desc.SampleDesc.Count = 1;
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

        D3D11_SUBRESOURCE_DATA initData;
        initData.pSysMem = srcImage.pixels;
        initData.SysMemPitch = static_cast<DWORD>( srcImage.rowPitch );
        initData.SysMemSlicePitch = static_cast<DWORD>( srcImage.slicePitch );

        HRESULT hr = pDevice->CreateTexture2D( &desc, &initData, sourceTex.GetAddressOf() );
        if ( FAILED(hr) )
        {
            return hr;
        }
    }

    ScopedObject<ID3D11ShaderResourceView> sourceSRV;
    {
        D3D11_SHADER_RESOURCE_VIEW_DESC desc;
        memset( &desc, 0, sizeof(desc) );
        desc.Texture2D.MipLevels = 1;
        desc.Format = inputFormat;
        desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;

        HRESULT hr = pDevice->CreateShaderResourceView( sourceTex.Get(), &desc, sourceSRV.ReleaseAndGetAddressOf() );
        if ( FAILED(hr) )
        {
            return hr;
        }
    }

    //--- Compress using DirectCompute ------------------------------------------------
    bool isbc7 = false;
    switch( m_bcformat )
    {
    case DXGI_FORMAT_BC6H_TYPELESS:
    case DXGI_FORMAT_BC6H_UF16:
    case DXGI_FORMAT_BC6H_SF16:
        break;

    case DXGI_FORMAT_BC7_TYPELESS:
    case DXGI_FORMAT_BC7_UNORM:
    case DXGI_FORMAT_BC7_UNORM_SRGB:
        isbc7 = true;
        break;

    default:
        return E_UNEXPECTED;
    }

    const UINT MAX_BLOCK_BATCH = 64;

    auto pContext = m_context.Get();
    if ( !pContext )
        return E_UNEXPECTED;

    size_t xblocks = std::max<size_t>( 1, (m_width + 3) >> 2 );
    size_t yblocks = std::max<size_t>( 1, (m_height + 3) >> 2 );

    UINT num_total_blocks = static_cast<UINT>( xblocks * yblocks );
    UINT num_blocks = num_total_blocks;
    int start_block_id = 0;
    while (num_blocks > 0)
    {
        UINT n = std::min<UINT>( num_blocks, MAX_BLOCK_BATCH );
        UINT uThreadGroupCount = n;

        {
            D3D11_MAPPED_SUBRESOURCE mapped;
            HRESULT hr = pContext->Map( m_constBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
            if ( FAILED(hr) )
                return hr;

            ConstantsBC6HBC7 param;
            param.tex_width = static_cast<UINT>( srcImage.width );
            param.num_block_x = static_cast<UINT>( xblocks );
            param.format = m_bcformat;
            param.mode_id = 0;
            param.start_block_id = start_block_id;
            param.num_total_blocks = num_total_blocks;
            param.alpha_weight = m_alphaWeight;
            memcpy( mapped.pData, &param, sizeof( param ) );

            pContext->Unmap( m_constBuffer.Get(), 0 );
        }

        if ( isbc7 )
        {
            //--- BC7 -----------------------------------------------------------------
            ID3D11ShaderResourceView* pSRVs[] = { sourceSRV.Get(), nullptr };
            RunComputeShader( pContext, m_BC7_tryMode456CS.Get(), pSRVs, 2, m_constBuffer.Get(),
                              m_err1UAV.Get(), std::max<UINT>(uThreadGroupCount / 4, 1) );

            for ( UINT i = 0; i < 3; ++i )
            {
                static const UINT modes[] = { 1, 3, 7 };
                {
                    D3D11_MAPPED_SUBRESOURCE mapped;
                    HRESULT hr = pContext->Map( m_constBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
                    if ( FAILED(hr) )
                    {
                        ResetContext( pContext );
                        return hr;
                    }

                    ConstantsBC6HBC7 param;
                    param.tex_width = static_cast<UINT>( srcImage.width );
                    param.num_block_x = static_cast<UINT>( xblocks );
                    param.format = m_bcformat;
                    param.mode_id = modes[i];
                    param.start_block_id = start_block_id;
                    param.num_total_blocks = num_total_blocks;
                    param.alpha_weight = m_alphaWeight;
                    memcpy( mapped.pData, &param, sizeof( param ) );
                    pContext->Unmap( m_constBuffer.Get(), 0 );
                }

                pSRVs[1] = (i & 1) ? m_err2SRV.Get() : m_err1SRV.Get();
                RunComputeShader( pContext, m_BC7_tryMode137CS.Get(), pSRVs, 2, m_constBuffer.Get(),
                                  (i & 1) ? m_err1UAV.Get() : m_err2UAV.Get(), uThreadGroupCount );
            }               

            for ( UINT i = 0; i < 2; ++i )
            {
                static const UINT modes[] = { 0, 2 };
                {
                    D3D11_MAPPED_SUBRESOURCE mapped;
                    HRESULT hr = pContext->Map( m_constBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
                    if ( FAILED(hr) )
                    {
                        ResetContext( pContext );
                        return hr;
                    }

                    ConstantsBC6HBC7 param;
                    param.tex_width = static_cast<UINT>( srcImage.width );
                    param.num_block_x = static_cast<UINT>( xblocks );
                    param.format = m_bcformat;
                    param.mode_id = modes[i];
                    param.start_block_id = start_block_id;
                    param.num_total_blocks = num_total_blocks;
                    param.alpha_weight = m_alphaWeight;
                    memcpy( mapped.pData, &param, sizeof( param ) );
                    pContext->Unmap( m_constBuffer.Get(), 0 );
                }

                pSRVs[1] = (i & 1) ? m_err1SRV.Get() : m_err2SRV.Get();
                RunComputeShader( pContext, m_BC7_tryMode02CS.Get(), pSRVs, 2, m_constBuffer.Get(),
                                  (i & 1) ? m_err2UAV.Get() : m_err1UAV.Get(), uThreadGroupCount );
            }

            pSRVs[1] = m_err2SRV.Get();
            RunComputeShader( pContext, m_BC7_encodeBlockCS.Get(), pSRVs, 2, m_constBuffer.Get(),
                              m_outputUAV.Get(), std::max<UINT>(uThreadGroupCount / 4, 1) );
        }
        else
        {
            //--- BC6H ----------------------------------------------------------------
            ID3D11ShaderResourceView* pSRVs[] = { sourceSRV.Get(), nullptr };
            RunComputeShader( pContext, m_BC6H_tryModeG10CS.Get(), pSRVs, 2, m_constBuffer.Get(),
                              m_err1UAV.Get(), std::max<UINT>(uThreadGroupCount / 4, 1) );

            for ( UINT i = 0; i < 10; ++i )
            {
                {
                    D3D11_MAPPED_SUBRESOURCE mapped;
                    HRESULT hr = pContext->Map( m_constBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
                    if ( FAILED(hr) )
                    {
                        ResetContext( pContext );
                        return hr;
                    }

                    ConstantsBC6HBC7 param;
                    param.tex_width = static_cast<UINT>( srcImage.width );
                    param.num_block_x = static_cast<UINT>( xblocks );
                    param.format = m_bcformat;
                    param.mode_id = i;
                    param.start_block_id = start_block_id;
                    param.num_total_blocks = num_total_blocks;
                    memcpy( mapped.pData, &param, sizeof( param ) );
                    pContext->Unmap( m_constBuffer.Get(), 0 );
                }

                pSRVs[1] = (i & 1) ? m_err2SRV.Get() : m_err1SRV.Get();
                RunComputeShader( pContext, m_BC6H_tryModeLE10CS.Get(), pSRVs, 2, m_constBuffer.Get(),
                                  (i & 1) ? m_err1UAV.Get() : m_err2UAV.Get(), std::max<UINT>(uThreadGroupCount / 2, 1) );
            }               

            pSRVs[1] = m_err1SRV.Get();
            RunComputeShader( pContext, m_BC6H_encodeBlockCS.Get(), pSRVs, 2, m_constBuffer.Get(),
                              m_outputUAV.Get(), std::max<UINT>(uThreadGroupCount / 2, 1) );
        }

        start_block_id += n;
        num_blocks -= n;
    }

    ResetContext( pContext );

    //--- Copy output texture back to CPU ---------------------------------------------

    pContext->CopyResource( m_outputCPU.Get(), m_output.Get() );

    D3D11_MAPPED_SUBRESOURCE mapped;
    HRESULT hr = pContext->Map( m_outputCPU.Get(), 0, D3D11_MAP_READ, 0, &mapped );
    if ( SUCCEEDED(hr) )
    {
        const uint8_t *pSrc = reinterpret_cast<const uint8_t *>( mapped.pData );
        uint8_t *pDest = destImage.pixels;

        size_t pitch = xblocks * sizeof( BufferBC6HBC7 );

        size_t rows = std::max<size_t>( 1, ( destImage.height + 3 ) >> 2 );

        for( size_t h = 0; h < rows; ++h )
        {
            memcpy( pDest, pSrc, destImage.rowPitch );

            pSrc += pitch;
            pDest += destImage.rowPitch;
        }

        pContext->Unmap( m_outputCPU.Get(), 0 );
    }

    return hr;
}
예제 #14
0
파일: Texture.cpp 프로젝트: Daivuk/ggj16
    Texture* Texture::createFromData(const sSize& size, const unsigned char* in_pData, bool in_generateMipmaps)
    {
        ID3D11Texture2D* pTexture = NULL;
        ID3D11ShaderResourceView* pTextureView = NULL;
        auto pRet = new Texture();

        // Manually generate mip levels
        bool allowMipMaps = true;
        UINT w2 = 1;
        UINT h2 = 1;
        while (w2 < (UINT)size.x) w2 *= 2;
        if (size.x != w2) allowMipMaps = false;
        while (h2 < (UINT)size.y) h2 *= 2;
        if (size.y != h2) allowMipMaps = false;
        unsigned char* pMipMaps = NULL;
        int mipLevels = 1;
        D3D11_SUBRESOURCE_DATA* mipsData = NULL;
        allowMipMaps = allowMipMaps && in_generateMipmaps;
        if (allowMipMaps)
        {
            UINT biggest = std::max<>(w2, h2);
            UINT w2t = w2;
            UINT h2t = h2;
            UINT totalSize = w2t * h2t * 4;
            while (!(w2t == 1 && h2t == 1))
            {
                ++mipLevels;
                w2t /= 2;
                if (w2t < 1) w2t = 1;
                h2t /= 2;
                if (h2t < 1) h2t = 1;
                totalSize += w2t * h2t * 4;
            }
            pMipMaps = new byte[totalSize];
            memcpy(pMipMaps, in_pData, size.x * size.y * 4);

            mipsData = new D3D11_SUBRESOURCE_DATA[mipLevels];

            w2t = w2;
            h2t = h2;
            totalSize = 0;
            int mipTarget = mipLevels;
            mipLevels = 0;
            byte* prev;
            byte* cur;
            while (mipLevels != mipTarget)
            {
                prev = pMipMaps + totalSize;
                mipsData[mipLevels].pSysMem = prev;
                mipsData[mipLevels].SysMemPitch = w2t * 4;
                mipsData[mipLevels].SysMemSlicePitch = 0;
                totalSize += w2t * h2t * 4;
                cur = pMipMaps + totalSize;
                w2t /= 2;
                if (w2t < 1) w2t = 1;
                h2t /= 2;
                if (h2t < 1) h2t = 1;
                ++mipLevels;
                if (mipLevels == mipTarget) break;
                int accum;

                // Generate the mips
                int multX = w2 / w2t;
                int multY = h2 / h2t;
                for (UINT y = 0; y < h2t; ++y)
                {
                    for (UINT x = 0; x < w2t; ++x)
                    {
                        for (UINT k = 0; k < 4; ++k)
                        {
                            accum = 0;
                            accum += prev[(y * multY * w2 + x * multX) * 4 + k];
                            accum += prev[(y * multY * w2 + (x + multX / 2) * multX) * 4 + k];
                            accum += prev[((y + multY / 2) * multY * w2 + x * multX) * 4 + k];
                            accum += prev[((y + multY / 2) * multY * w2 + (x + multX / 2) * multX) * 4 + k];
                            cur[(y * w2t + x) * 4 + k] = accum / 4;
                        }
                    }
                }

                w2 = w2t;
                h2 = h2t;
            }
        }

        D3D11_TEXTURE2D_DESC desc;
        desc.Width = size.x;
        desc.Height = size.y;
        desc.MipLevels = mipLevels;
        desc.ArraySize = 1;
        desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        desc.SampleDesc.Count = 1;
        desc.SampleDesc.Quality = 0;
        desc.Usage = D3D11_USAGE_IMMUTABLE;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
        desc.CPUAccessFlags = 0;
        desc.MiscFlags = 0;

        D3D11_SUBRESOURCE_DATA data;
        data.pSysMem = (pMipMaps) ? pMipMaps : in_pData;
        data.SysMemPitch = size.x * 4;
        data.SysMemSlicePitch = 0;

        auto pDevice = ORenderer->getDevice();
        auto ret = pDevice->CreateTexture2D(&desc, (mipsData) ? mipsData : &data, &pTexture);
        assert(ret == S_OK);
        ret = pDevice->CreateShaderResourceView(pTexture, NULL, &pTextureView);
        assert(ret == S_OK);

        pTexture->Release();
        if (pMipMaps) delete[] pMipMaps;
        if (mipsData) delete[] mipsData;

        pRet->m_size = size;
        pRet->m_pTextureView = pTextureView;

        return pRet;
    }
예제 #15
0
	//--------------------------------------------------------------------------------------
	//	class DefaultRenderTarget : public RenderTarget;
	//	用途: デフォルトのレンダーターゲット
	//	*デフォルトのレンダラー
	//--------------------------------------------------------------------------------------
	//構築
	DefaultRenderTarget::DefaultRenderTarget(const shared_ptr<Stage>& stage) :
		pImpl(new Impl(stage))
	{
		try{
			if (pImpl->m_Stage.expired()){
				throw BaseException(
					L"ステージが無効です",
					L"if (pImpl->m_Stage.expired())",
					L"DefaultRenderTarget::DefaultRenderTarget()"
					);
			}

			auto Dev = App::GetApp()->GetDeviceResources();
			auto pD3D11Device = Dev->GetD3DDevice();
			auto pSwapChain = Dev->GetSwapChain();
			auto pD3D11DeviceContext = Dev->GetD3DDeviceContext();
			auto pD2D11DeviceContext = Dev->GetD2DDeviceContext();


			//レンダリングターゲットビューの作成
			ComPtr<ID3D11Texture2D> pBackBuffer;
			//まずバックバッファのポインタを得る
			ThrowIfFailed(
				pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer),
				L"スワップチェーンからバックバッファの取得に失敗しました。",
				L"pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer)",
				L"DefaultRenderTarget::DefaultRenderTarget()"
				);
			//バックバッファからレンダリングターゲットのビューを作成する
			ThrowIfFailed(
				pD3D11Device->CreateRenderTargetView(pBackBuffer.Get(), nullptr, &pImpl->m_D3D11RenderTargetView),
				L"DX11バックバッファからのレンダリングターゲットビューを作成に失敗しました。",
				L"pD3D11Device->CreateRenderTargetView(pBackBuffer.Get(), nullptr, &m_D3D11RenderTargetView)",
				L"DefaultRenderTarget::DefaultRenderTarget()"
				);

			//深度テクスチャの作成
			D3D11_TEXTURE2D_DESC descDepth;
			ZeroMemory(&descDepth, sizeof(descDepth));
			descDepth.Width = App::GetApp()->GetGameWidth();
			descDepth.Height = App::GetApp()->GetGameHeight();
			descDepth.MipLevels = 1;
			descDepth.ArraySize = 1;
			descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
			descDepth.SampleDesc.Count = 1;
			descDepth.SampleDesc.Quality = 0;
			descDepth.Usage = D3D11_USAGE_DEFAULT;
			descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
			descDepth.CPUAccessFlags = 0;
			descDepth.MiscFlags = 0;

			ThrowIfFailed(
				pD3D11Device->CreateTexture2D(&descDepth, nullptr, &pImpl->m_DepthStencil),
				L"DX11深度テクスチャの作成失敗の作成に失敗しました。",
				L"pD3D11Device->CreateTexture2D(&descDepth, nullptr, &m_DepthStencil)",
				L"DefaultRenderTarget::DefaultRenderTarget()"
				);

			//深度ステンシルビューの作成
			D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
			ZeroMemory(&descDSV, sizeof(descDSV));
			descDSV.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
			descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
			descDSV.Texture2D.MipSlice = 0;

			ThrowIfFailed(
				pD3D11Device->CreateDepthStencilView(pImpl->m_DepthStencil.Get(), &descDSV, &pImpl->m_DepthStencilView),
				L"DX11深度ステンシルビューの作成に失敗しました。",
				L"pD3D11Device->CreateDepthStencilView(m_DepthStencil.Get(), &descDSV, &m_DepthStencilView)",
				L"DefaultRenderTarget::DefaultRenderTarget()"
				);

			ComPtr<IDXGISurface2> dxgiBackBuffer;
			ThrowIfFailed(
				pSwapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer)),
				L"2dデバイスコンテキスト作成に失敗しました。",
				L"m_d2dDevice->CreateDeviceContext()",
				L"DeviceResources::Impl::CreateDeviceResources()"
				);


			ThrowIfFailed(
				pD2D11DeviceContext->CreateBitmapFromDxgiSurface(
				dxgiBackBuffer.Get(),
				nullptr,	//デフォルト設定
				&pImpl->m_d2dTargetBitmap
				),
				L"2dビットマップ作成に失敗しました。",
				L"pD2D11DeviceContext->CreateBitmapFromDxgiSurface()",
				L"DefaultRenderTarget::DefaultRenderTarget()"
				);

			pD2D11DeviceContext->SetTarget(pImpl->m_d2dTargetBitmap.Get());
			//グレースケール テキストのアンチエイリアシング
			pD2D11DeviceContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);

		}
		catch (...){
			throw;
		}
	}
예제 #16
0
	//--------------------------------------------------------------------------------------
	//	class ShadowMapRenderTarget: public RenderTarget;
	//	用途: シャドウマップのレンダリングターゲット
	//--------------------------------------------------------------------------------------
	//構築と破棄
	ShadowMapRenderTarget::ShadowMapRenderTarget(float ShadowMapDimension) :
		pImpl(new Impl(ShadowMapDimension))
	{
		try{
			//デバイスとコンテキストインターフェイスの取得
			auto Dev = App::GetApp()->GetDeviceResources();
			auto pD3D11Device = Dev->GetD3DDevice();
			auto pSwapChain = Dev->GetSwapChain();
			auto pD3D11DeviceContext = Dev->GetD3DDeviceContext();

			//シャドウマップテクスチャの作成
			D3D11_TEXTURE2D_DESC shadowMapDesc;
			ZeroMemory(&shadowMapDesc, sizeof(D3D11_TEXTURE2D_DESC));
			shadowMapDesc.Width = static_cast<UINT>(pImpl->m_ShadowMapDimension);
			shadowMapDesc.Height = static_cast<UINT>(pImpl->m_ShadowMapDimension);
			shadowMapDesc.MipLevels = 1;
			shadowMapDesc.ArraySize = 1;
			shadowMapDesc.SampleDesc.Count = 1;
			shadowMapDesc.Usage = D3D11_USAGE_DEFAULT;
			shadowMapDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
			shadowMapDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;

			ThrowIfFailed(
				pD3D11Device->CreateTexture2D(&shadowMapDesc, nullptr, &pImpl->m_DepthStencil),
				L"シャドウマップテクスチャの作成に失敗しました。",
				L"pD3D11Device->CreateTexture2D(&shadowMapDesc, nullptr, &m_DepthStencil)",
				L"ShadowMapRenderTarget::ShadowMapRenderTarget()"
				);

			//深度ステンシルビュー作成
			D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
			ZeroMemory(&depthStencilViewDesc, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
			depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
			depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
			depthStencilViewDesc.Texture2D.MipSlice = 0;

			ThrowIfFailed(
				pD3D11Device->CreateDepthStencilView(pImpl->m_DepthStencil.Get(), &depthStencilViewDesc, &pImpl->m_DepthStencilView),
				L"深度ステンシルビューの作成に失敗しました。",
				L"pD3D11Device->CreateDepthStencilView(&m_DepthStencil, &depthStencilViewDesc, &m_DepthStencilView)",
				L"ShadowMapRenderTarget::ShadowMapRenderTarget()"
				);

			//シェーダーリソースビュー作成
			D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
			ZeroMemory(&shaderResourceViewDesc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC));
			shaderResourceViewDesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
			shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
			shaderResourceViewDesc.Texture2D.MipLevels = 1;

			ThrowIfFailed(
				pD3D11Device->CreateShaderResourceView(pImpl->m_DepthStencil.Get(), &shaderResourceViewDesc, &pImpl->m_ShaderResourceView),
				L"シェーダーリソースビューの作成に失敗しました。",
				L"pD3D11Device->CreateShaderResourceView(m_DepthStencil.Get(), &shaderResourceViewDesc, &m_ShaderResourceView)",
				L"ShadowMapRenderTarget::ShadowMapRenderTarget()"
				);


			D3D11_RASTERIZER_DESC shadowRenderStateDesc;
			ZeroMemory(&shadowRenderStateDesc, sizeof(D3D11_RASTERIZER_DESC));
			shadowRenderStateDesc.CullMode = D3D11_CULL_FRONT;
			shadowRenderStateDesc.FillMode = D3D11_FILL_SOLID;
			shadowRenderStateDesc.DepthClipEnable = true;

			ThrowIfFailed(pD3D11Device->CreateRasterizerState(&shadowRenderStateDesc,&pImpl->m_ShadowRenderState),
				L"シャドウマップのラスタライザステートの作成に失敗しました。",
				L"pD3D11Device->CreateRasterizerState(&shadowRenderStateDesc,&pImpl->m_ShadowRenderState)",
				L"ShadowMapRenderTarget::ShadowMapRenderTarget()"
				);


			//ビューポートの作成
			//シャドウレンダリングビューポート
			ZeroMemory(&pImpl->m_ViewPort, sizeof(D3D11_VIEWPORT));
			pImpl->m_ViewPort.Height = pImpl->m_ShadowMapDimension;
			pImpl->m_ViewPort.Width = pImpl->m_ShadowMapDimension;
			pImpl->m_ViewPort.MinDepth = 0.f;
			pImpl->m_ViewPort.MaxDepth = 1.f;
		}
		catch (...){
			throw;
		}
	}
예제 #17
0
void Graphics_LayerRenderer(bool isOpenGLMode)
{
	StartGraphicsTest();
	SetGLEnable(isOpenGLMode);

	asd::Log* log = asd::Log_Imp::Create(u"graphics.html", u"レイヤー");

	auto window = asd::Window_Imp::Create(640, 480, asd::ToAString(u"レイヤー").c_str(), log, false, asd::WindowPositionType::Default, isOpenGLMode ? asd::GraphicsDeviceType::OpenGL : asd::GraphicsDeviceType::DirectX11, asd::ColorSpaceType::LinearSpace, false);
	ASSERT_TRUE(window != nullptr);

	auto synchronizer = std::make_shared<asd::Synchronizer>();
	auto file = asd::File_Imp::Create(synchronizer);
	ASSERT_TRUE(file != nullptr);

	asd::GraphicsOption go;
	go.IsFullScreen = false;
	go.IsReloadingEnabled = false;
	go.ColorSpace = asd::ColorSpaceType::LinearSpace;
	go.GraphicsDevice = isOpenGLMode ? asd::GraphicsDeviceType::OpenGL : asd::GraphicsDeviceType::DirectX11;
	auto graphics = asd::Graphics_Imp::Create(window, isOpenGLMode ? asd::GraphicsDeviceType::OpenGL : asd::GraphicsDeviceType::DirectX11, log, file, go);
	ASSERT_TRUE(graphics != nullptr);

	auto renderer = new asd::LayerRenderer(graphics);
	ASSERT_TRUE(renderer != nullptr);

	auto texture = graphics->CreateTexture2D(asd::ToAString(u"Data/Texture/Sample1.png").c_str());
	ASSERT_TRUE(texture != nullptr);

	int32_t time = 0;
	while (window->DoEvent())
	{
		graphics->Begin();
		graphics->Clear(true, false, asd::Color(0, 0, 0, 255));

		{
			asd::Vector2DF lpos[4];
			lpos[0].X = 0;
			lpos[0].Y = 0;
			lpos[1].X = 600;
			lpos[1].Y = 0;
			lpos[2].X = 640;
			lpos[2].Y = 480;
			lpos[3].X = 0;
			lpos[3].Y = 440;
			renderer->SetWindowSize(asd::Vector2DI(640, 480));
			renderer->SetTexture(texture.get());
			renderer->SetLayerPosition(lpos);
		}

		{
			asd::Vector2DF positions[4];
			asd::Color colors[4];
			asd::Vector2DF uvs[4];

			colors[0] = asd::Color(255, 255, 255, 255);
			colors[1] = asd::Color(255, 255, 255, 255);
			colors[2] = asd::Color(255, 255, 255, 255);

			positions[0].X = 0.0f;
			positions[0].Y = 0.0f;
			positions[1].X = 1.0f;
			positions[1].Y = 0.0f;
			positions[2].X = 1.0f;
			positions[2].Y = 1.0f;


			uvs[0].X = 0;
			uvs[0].Y = 0;
			uvs[1].X = 1;
			uvs[1].Y = 0;
			uvs[2].X = 1;
			uvs[2].Y = 1;

			renderer->AddTriangle(positions, colors, uvs);
		}

		{
			asd::Vector2DF positions[4];
			asd::Color colors[4];
			asd::Vector2DF uvs[4];

			colors[0] = asd::Color(255, 255, 255, 255);
			colors[1] = asd::Color(255, 255, 255, 255);
			colors[2] = asd::Color(255, 255, 255, 255);

			positions[0].X = 0.0f;
			positions[0].Y = 0.0f;
			positions[1].X = 0.5f;
			positions[1].Y = 1.0f;
			positions[2].X = 0.0f;
			positions[2].Y = 0.5f;

			uvs[0].X = 0;
			uvs[0].Y = 0;
			uvs[1].X = 1;
			uvs[1].Y = 1;
			uvs[2].X = 0;
			uvs[2].Y = 1;

			renderer->AddTriangle(positions, colors, uvs);
		}
		

		renderer->DrawCache();
		renderer->ClearCache();

		graphics->Present();

		graphics->End();

		if (time == 10)
		{
			SAVE_SCREEN_SHOT(graphics, 0);
		}

		if (time == 11)
		{
			window->Close();
		}
		time++;
	}

	texture.reset();
	renderer->Release();
	graphics->Release();
	file->Release();
	window->Release();
	delete log;
}
예제 #18
0
void InitApplication(u32 windowWidth, u32 windowHeight, ApplicationFlagsEnum flags, ApplicationPresentProfileEnum profile, i32 adapterIndex) {
	GDisplaySettings.resolution.x = windowWidth;
	GDisplaySettings.resolution.y = windowHeight;

	switch (profile) {
	case APP_PRESENT_THROUGHPUT:
		{
			GDisplaySettings.vsync = 1;
			GDisplaySettings.backbuffers_num = 3;
			GDisplaySettings.max_gpu_buffered_frames = 3;
			GDisplaySettings.wait_to_vblank = false;
		}
		break;
	case APP_PRESENT_UNTHROTTLED:
		{
			GDisplaySettings.vsync = 0;
			GDisplaySettings.backbuffers_num = 3;
			GDisplaySettings.max_gpu_buffered_frames = 3;
			GDisplaySettings.wait_to_vblank = false;
		}
		break;
	case APP_PRESENT_LOWLATENCY:
		{
			GDisplaySettings.vsync = 1;
			GDisplaySettings.backbuffers_num = 3;
			GDisplaySettings.max_gpu_buffered_frames = 2;
			GDisplaySettings.wait_to_vblank = true;
		}
		break;
	case APP_PRESENT_VERYLOWLATENCY:
		{
			GDisplaySettings.vsync = 1;
			GDisplaySettings.backbuffers_num = 2;
			GDisplaySettings.max_gpu_buffered_frames = 1;
			GDisplaySettings.wait_to_vblank = true;
		}
		break;
	default:
		Check(0);

	}

	InitMainThread();
	InitProfiler();
	PROFILE_NAME_THREAD("Main");
	InitScheduler();

	InitSDL(&SDLWindow);

	InitDevice(GDisplaySettings.hwnd, false, flags & APP_FLAG_D3D12_DEBUG, adapterIndex);
	InitRenderingEngines();
	InitResources();

	GGPUMainQueue = CreateQueue(TEXT_("3d_engine"), GPUQueueEnum::Direct);
	GGPUCopyQueue = CreateQueue(TEXT_("copy_engine"), GPUQueueEnum::Copy);

	CreateSwapChain(GetD12Queue(GGPUMainQueue));

	ImGuiIO& io = ImGui::GetIO();
	io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
	io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
	io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
	io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
	io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
	io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
	io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
	io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
	io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
	io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
	io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
	io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
	io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
	io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
	io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
	io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
	io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;

	io.RenderDrawListsFn = Essence::RenderImDrawLists;
	io.ImeWindowHandle = GDisplaySettings.hwnd;

	io.Fonts->AddFontDefault();
	unsigned char* pixels;
	int width, height;
	io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
	io.Fonts->TexID = nullptr;

	D3D12_SUBRESOURCE_DATA imageData;
	imageData.pData = pixels;
	imageData.RowPitch = sizeof(u32) * width;
	imageData.SlicePitch = sizeof(u32) * width * height;

	auto fontsTexture = CreateTexture2D(width, height, DXGI_FORMAT_R8G8B8A8_UNORM, NO_TEXTURE_FLAGS, "font_texture");
	CopyFromCpuToSubresources(GGPUCopyQueue, Slice(fontsTexture), 1, &imageData);
	io.Fonts->TexID = HandleToImGuiTexID(fontsTexture);

	GApplicationInitializeFunction();

	// after issuing init copies waiting for completion
	QueueWait(GGPUMainQueue, GetLastSignaledFence(GGPUCopyQueue));
}
	// TODO create software window
	bool RenderWindowD11_2::Create(const _lParametor& config)
	{
		_lParametor::const_iterator parametor;
		HRESULT hr = S_FALSE;
		auto divace = m_pRSystem->GetD3DDevice();
		auto context = m_pRSystem->GetD3DDeviceContext();

		// Î÷èñòèòü ïðåäûäóùàÿ ðàçìåð îêíà êîíêðåòíîãî êîíòåêñòà.
		ID3D11RenderTargetView* nullViews[] = { nullptr };
		context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
		m_d3dRenderTargetView = nullptr;
		m_d3dDepthStencilView = nullptr;
		context->Flush();

		parametor = config.find("window_name");
		if (parametor != config.end()) {
			mObjectName = parametor->second;
		}

		_32un bit = 0;
		parametor = config.find("display_mode");
		if (parametor != config.end())
		{
			StringConverter::ParseDisplyaMode(parametor->second, m_nWidth, m_nHeight, bit);
		}
		else
		{
			DrawLine("~RenderWindowD11_2: not set display_mode", MT_ERROR);
			return false;
		}

		parametor = config.find("full_screan_mode");
		if (parametor != config.end())
		{
			m_bFullScrean = StringConverter::Parse_bool(parametor->second);
		}
		else
		{
			DrawLine("~RenderWindowD11_2: not set full_screan_mode set in false");
			m_bFullScrean = false;
		}

		parametor = config.find("window_handle");
		if (parametor != config.end())
		{
			m_hWnd = StringConverter::Parse_int(parametor->second);
		}
		else
		{
			DrawLine("~RenderWindowD11_2: not set window_handle", MT_ERROR);
			return false;
		}

		DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 };
		swapChainDesc.Width = m_nWidth;
		swapChainDesc.Height = m_nHeight;
		swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // Ýòî íàèáîëåå ðàñïðîñòðàíåííûé ôîðìàò swap chain.
		swapChainDesc.Stereo = false;
		swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
		swapChainDesc.SampleDesc.Quality = 0;
		swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
		swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
		swapChainDesc.Flags = 0;
		swapChainDesc.Scaling = DXGI_SCALING_NONE;
		swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;

		ComPtr<IDXGIDevice2> dxgiDevice;
		divace->QueryInterface(IID_PPV_ARGS(&dxgiDevice));

		ComPtr<IDXGIAdapter> dxgiAdapter;
		dxgiDevice->GetAdapter(&dxgiAdapter);

		ComPtr<IDXGIFactory2> dxgiFactory;
		dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory));

		hr = dxgiFactory->CreateSwapChainForHwnd(
			divace,			// pDevice [in]
			(HWND)m_hWnd,						// hWnd [in]
			&swapChainDesc,						// pDesc [in]
			nullptr,							// pFullscreenDesc [in, optional]
			nullptr,							// pRestrictToOutput [in, optional]
			&m_swapChain						// ppSwapChain [out]
			);

		if (FAILED(hr)) {
			DrawLine("~RenderWindowD11_2: " + RenderSystemD11_2::GetErrorHR(hr), MT_ERROR);
			return false;
		}

		// Óáåäèòåñü, ÷òî DXGI íå ñòîÿòü â î÷åðåäè áîëüøå, ÷åì îäèí êàäð çà îäèí ðàç. Ýòî è ñîêðàùàåò çàäåðæêè è
		// Ãàðàíòèðóåò, ÷òî ïðèëîæåíèå áóäåò îêàçûâàòü òîëüêî ïîñëå êàæäîãî VSync, ìèíèìèçèðóÿ ïîòðåáëåíèå ýíåðãèè.
		dxgiDevice->SetMaximumFrameLatency(1);

		// Create a render target view of the swap chain back buffer.
		ComPtr<ID3D11Texture2D> backBuffer;
		m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer));

		divace->CreateRenderTargetView(
			backBuffer.Get(),
			nullptr,
			&m_d3dRenderTargetView
			);

		// Create a depth stencil view for use with 3D rendering if needed.
		CD3D11_TEXTURE2D_DESC depthStencilDesc(
			DXGI_FORMAT_D24_UNORM_S8_UINT,
			m_nWidth,
			m_nHeight,
			1, // This depth stencil view has only one texture.
			1, // Use a single mipmap level.
			D3D11_BIND_DEPTH_STENCIL
			);

		ComPtr<ID3D11Texture2D> depthStencil;
		divace->CreateTexture2D(
			&depthStencilDesc,
			nullptr,
			&depthStencil
			);

		CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
		divace->CreateDepthStencilView(
			depthStencil.Get(),
			&depthStencilViewDesc,
			&m_d3dDepthStencilView
			);

		// Set the 3D rendering viewport to target the entire window.
		m_screenViewport = CD3D11_VIEWPORT(
			0.0f,
			0.0f,
			(FLOAT)m_nWidth,
			(FLOAT)m_nHeight
			);

		context->RSSetViewports(1, &m_screenViewport);

		m_bInit = true;

		return true;
	}