示例#1
0
vpResult vprDepthStencilStateDX11::init()
{
	vprDeviceDX11* dx11Device = static_cast<vprDeviceDX11*>(m_device);
	ID3D11Device* nativeDevice = dx11Device->getNativeDevice();

	D3D11_DEPTH_STENCIL_DESC nativeDesc;
	ZeroMemory(&nativeDesc, sizeof(nativeDesc));

	nativeDesc.DepthEnable = m_desc.m_depthEnable ? TRUE : FALSE;
	nativeDesc.DepthWriteMask = m_desc.m_depthWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
	nativeDesc.DepthFunc = comparisonFuncToDX11[m_desc.m_depthFunc];
	nativeDesc.StencilEnable = m_desc.m_depthEnable ? TRUE : FALSE;
	nativeDesc.StencilReadMask = m_desc.m_stencilReadMask;
	nativeDesc.StencilWriteMask = m_desc.m_stencilWriteMask;

	nativeDesc.FrontFace.StencilFailOp = stencilOpToDX11[m_desc.m_frontFace.m_stencilFailOp];
	nativeDesc.FrontFace.StencilDepthFailOp = stencilOpToDX11[m_desc.m_frontFace.m_stencilDepthFailOp];
	nativeDesc.FrontFace.StencilPassOp = stencilOpToDX11[m_desc.m_frontFace.m_stencilPassOp];
	nativeDesc.FrontFace.StencilFunc = comparisonFuncToDX11[m_desc.m_frontFace.m_stencilFunc];
	
	nativeDesc.BackFace.StencilFailOp = stencilOpToDX11[m_desc.m_backFace.m_stencilFailOp];
	nativeDesc.BackFace.StencilDepthFailOp = stencilOpToDX11[m_desc.m_backFace.m_stencilDepthFailOp];
	nativeDesc.BackFace.StencilPassOp = stencilOpToDX11[m_desc.m_backFace.m_stencilPassOp];
	nativeDesc.BackFace.StencilFunc = comparisonFuncToDX11[m_desc.m_backFace.m_stencilFunc];

	if (FAILED(nativeDevice->CreateDepthStencilState(&nativeDesc, &m_nativeState)))
	{
		return VP_FAILURE;
	}

	return VP_SUCCESS;
}
//-----------------------------------------------------------------------------
void CPUTRenderStateBlockDX11::CreateNativeResources()
{
    // Now, create the DX render state items
    ID3D11Device *pDevice = CPUT_DX11::GetDevice();
    HRESULT hr;
    hr = pDevice->CreateBlendState( &mStateDesc.BlendDesc, &mpBlendState );
    ASSERT( SUCCEEDED(hr), _L("Failed to create blend state.") );

    hr = pDevice->CreateDepthStencilState( &mStateDesc.DepthStencilDesc, &mpDepthStencilState );
    ASSERT( SUCCEEDED(hr), _L("Failed to create depth stencil state.") );

    hr = pDevice->CreateRasterizerState( &mStateDesc.RasterizerDesc, &mpRasterizerState );
    ASSERT( SUCCEEDED(hr), _L("Failed to create rasterizer state.") );

    // TODO: how to map samplers to shaders?
    // Each type can have different samplers assigned (VS, PS, GS, etc.)
    // How does DX treat them?  16 unified?  or 16 each?
    // For now, just read 16 samplers, and set to all stages

    for( UINT ii=0; ii<mNumSamplers; ii++ )
    {
        hr = pDevice->CreateSamplerState( &mStateDesc.SamplerDesc[ii], &mpSamplerState[ii] );
        ASSERT( SUCCEEDED(hr), _L("Failed to create sampler state.") );
    }
} // CPUTRenderStateBlockDX11::CreateDXResources()
示例#3
0
void eve::dx11::DepthStencilStates::Init(eve::dx11::Device* device)
{
	ID3D11Device* d = device->GetDevice();

	D3D11_DEPTH_STENCIL_DESC depthDesc;
	ZeroMemory(&depthDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));

	d->CreateDepthStencilState(&depthDesc, &this->m_pDisabled);

	depthDesc.DepthEnable = TRUE;
	depthDesc.DepthFunc = D3D11_COMPARISON_FUNC::D3D11_COMPARISON_LESS;
	
	d->CreateDepthStencilState(&depthDesc, &this->m_pLessRO);

	depthDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK::D3D11_DEPTH_WRITE_MASK_ALL;

	d->CreateDepthStencilState(&depthDesc, &this->m_pLessRW);
}
示例#4
0
ID3D11DepthStencilState *Clear11::getDepthStencilState(const ClearParameters &clearParams)
{
    ClearDepthStencilInfo dsKey = {0};
    dsKey.clearDepth            = clearParams.clearDepth;
    dsKey.clearStencil          = clearParams.clearStencil;
    dsKey.stencilWriteMask      = clearParams.stencilWriteMask & 0xFF;

    ClearDepthStencilStateMap::const_iterator i = mClearDepthStencilStates.find(dsKey);
    if (i != mClearDepthStencilStates.end())
    {
        return i->second;
    }
    else
    {
        D3D11_DEPTH_STENCIL_DESC dsDesc = {0};
        dsDesc.DepthEnable              = dsKey.clearDepth ? TRUE : FALSE;
        dsDesc.DepthWriteMask =
            dsKey.clearDepth ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
        dsDesc.DepthFunc                    = D3D11_COMPARISON_ALWAYS;
        dsDesc.StencilEnable                = dsKey.clearStencil ? TRUE : FALSE;
        dsDesc.StencilReadMask              = 0;
        dsDesc.StencilWriteMask             = dsKey.stencilWriteMask;
        dsDesc.FrontFace.StencilFailOp      = D3D11_STENCIL_OP_REPLACE;
        dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_REPLACE;
        dsDesc.FrontFace.StencilPassOp      = D3D11_STENCIL_OP_REPLACE;
        dsDesc.FrontFace.StencilFunc        = D3D11_COMPARISON_ALWAYS;
        dsDesc.BackFace.StencilFailOp       = D3D11_STENCIL_OP_REPLACE;
        dsDesc.BackFace.StencilDepthFailOp  = D3D11_STENCIL_OP_REPLACE;
        dsDesc.BackFace.StencilPassOp       = D3D11_STENCIL_OP_REPLACE;
        dsDesc.BackFace.StencilFunc         = D3D11_COMPARISON_ALWAYS;

        ID3D11Device *device             = mRenderer->getDevice();
        ID3D11DepthStencilState *dsState = nullptr;
        HRESULT result                   = device->CreateDepthStencilState(&dsDesc, &dsState);
        if (FAILED(result) || !dsState)
        {
            ERR("Unable to create a ID3D11DepthStencilState, HRESULT: 0x%X.", result);
            return nullptr;
        }

        mClearDepthStencilStates[dsKey] = dsState;

        return dsState;
    }
}
 void PEDepthStencilState::setAPIValues()
 {
     #if APIABSTRACTION_D3D9
     #elif APIABSTRACTION_D3D11
     
     D3D11Renderer *pD3D11Renderer = static_cast<D3D11Renderer *>(m_pContext->getGPUScreen());
     ID3D11Device *pDevice = pD3D11Renderer->m_pD3DDevice;
     ID3D11DeviceContext *pDeviceContext = pD3D11Renderer->m_pD3DContext;
     
     D3D11_DEPTH_STENCIL_DESC dsDesc;
     
     // Depth test parameters
     dsDesc.DepthEnable = m_depthTestEnabled;
     dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
     dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
     
     // Stencil test parameters
     dsDesc.StencilEnable = false;
     //dsDesc.StencilReadMask = 0xFF;
     //dsDesc.StencilWriteMask = 0xFF;
     
     // Stencil operations if pixel is front-facing
     //dsDesc.FrontFace.StencilFailOp = D3D10_STENCIL_OP_KEEP;
     //dsDesc.FrontFace.StencilDepthFailOp = D3D10_STENCIL_OP_INCR;
     //dsDesc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
     //dsDesc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
     
     // Stencil operations if pixel is back-facing
     //dsDesc.BackFace.StencilFailOp = D3D10_STENCIL_OP_KEEP;
     //dsDesc.BackFace.StencilDepthFailOp = D3D10_STENCIL_OP_DECR;
     //dsDesc.BackFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
     //dsDesc.BackFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
     
     // Create depth stencil state
     pDevice->CreateDepthStencilState(&dsDesc, &m_pD3D11DepthStencilStateObject);
     
     #elif PE_API_IS_GL
     
     
     #endif
 }
示例#6
0
option<skybox_texture> load_skybox(const wchar_t * filename, ID3D11Device& device)
{

	skybox_texture sky;
	auto result = DirectX::CreateDDSTextureFromFile(&device, filename, nullptr, &sky.resource_view);
	if (result != S_OK) {
		return None<skybox_texture>();
	}

	D3D11_SAMPLER_DESC builder;
	ZeroMemory(&builder, sizeof(builder));
	builder.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	builder.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	builder.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	builder.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	builder.MaxLOD = D3D11_FLOAT32_MAX;
	result = device.CreateSamplerState(&builder, &sky.state);

	// Create a rasterizer state for the sky box
	D3D11_RASTERIZER_DESC rastDesc;
	ZeroMemory(&rastDesc, sizeof(rastDesc));
	rastDesc.FillMode = D3D11_FILL_SOLID;
	rastDesc.CullMode = D3D11_CULL_FRONT;
	rastDesc.DepthClipEnable = true;
	device.CreateRasterizerState(&rastDesc, &sky.rasterizer_state);

	// A depth state for the sky rendering
	D3D11_DEPTH_STENCIL_DESC dsDesc;
	ZeroMemory(&dsDesc, sizeof(dsDesc));
	dsDesc.DepthEnable = true;
	dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
	device.CreateDepthStencilState(&dsDesc, &sky.depth_state);

	if (result != S_OK) {
		return None<skybox_texture>();
	}

	return Some(std::move(sky));
}
gl::Error PixelTransfer11::loadResources()
{
    if (mResourcesLoaded)
    {
        return gl::NoError();
    }

    HRESULT result = S_OK;
    ID3D11Device *device = mRenderer->getDevice();

    D3D11_RASTERIZER_DESC rasterDesc;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.CullMode = D3D11_CULL_NONE;
    rasterDesc.FrontCounterClockwise = FALSE;
    rasterDesc.DepthBias = 0;
    rasterDesc.SlopeScaledDepthBias = 0.0f;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = TRUE;
    rasterDesc.ScissorEnable = FALSE;
    rasterDesc.MultisampleEnable = FALSE;
    rasterDesc.AntialiasedLineEnable = FALSE;

    result = device->CreateRasterizerState(&rasterDesc, &mCopyRasterizerState);
    ASSERT(SUCCEEDED(result));
    if (FAILED(result))
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal pixel transfer rasterizer state, result: 0x%X.", result);
    }

    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_ALWAYS;
    depthStencilDesc.StencilEnable = FALSE;
    depthStencilDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
    depthStencilDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    result = device->CreateDepthStencilState(&depthStencilDesc, &mCopyDepthStencilState);
    ASSERT(SUCCEEDED(result));
    if (FAILED(result))
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal pixel transfer depth stencil state, result: 0x%X.", result);
    }

    D3D11_BUFFER_DESC constantBufferDesc = { 0 };
    constantBufferDesc.ByteWidth = roundUp<UINT>(sizeof(CopyShaderParams), 32u);
    constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    constantBufferDesc.MiscFlags = 0;
    constantBufferDesc.StructureByteStride = 0;

    result = device->CreateBuffer(&constantBufferDesc, NULL, &mParamsConstantBuffer);
    ASSERT(SUCCEEDED(result));
    if (FAILED(result))
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal pixel transfer constant buffer, result: 0x%X.", result);
    }
    d3d11::SetDebugName(mParamsConstantBuffer, "PixelTransfer11 constant buffer");

    // init shaders
    mBufferToTextureVS = d3d11::CompileVS(device, g_VS_BufferToTexture, "BufferToTexture VS");
    if (!mBufferToTextureVS)
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal buffer to texture vertex shader.");
    }

    mBufferToTextureGS = d3d11::CompileGS(device, g_GS_BufferToTexture, "BufferToTexture GS");
    if (!mBufferToTextureGS)
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal buffer to texture geometry shader.");
    }

    ANGLE_TRY(buildShaderMap());

    StructZero(&mParamsData);

    mResourcesLoaded = true;

    return gl::NoError();
}
示例#8
0
// WinMain
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
    HRESULT hr;


    // ウィンドウクラスを登録
    WNDCLASSEX wcex = {
        sizeof( WNDCLASSEX ),			// cbSize
        CS_HREDRAW | CS_VREDRAW,		// style
        WndProc,						// lpfnWndProc
        0,								// cbClsExtra
        0,								// cbWndExtra
        hInstance,						// hInstance
        NULL,							// hIcon
        NULL,							// hCursor
        ( HBRUSH )( COLOR_WINDOW + 1 ),	// hbrBackGround
        NULL,							// lpszMenuName
        g_className,					// lpszClassName
        NULL							// hIconSm
    };
    if ( ! RegisterClassEx( &wcex ) )
    {
        MessageBox( NULL, _T( "失敗: RegisterClassEx()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "RegisterClassEx: ok\n" ) );


    // ウィンドウサイズを計算
    RECT r = { 0, 0, 800, 450 };   // 800x450 (16:9)
    if ( ! AdjustWindowRect( &r, WS_OVERLAPPEDWINDOW, FALSE ) )
    {
        MessageBox( NULL, _T( "失敗: AdjustWindowRect()" ), _T( "エラー" ),  MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "AdjustWindowRect: ok (%d, %d)-(%d, %d)\n" ), r.left, r.top, r.right, r.bottom );


    // ウィンドウ生成
    HWND hWnd;
    hWnd = CreateWindow( g_className,
                         g_windowName,
                         WS_OVERLAPPEDWINDOW,
                         CW_USEDEFAULT,
                         0,
                         r.right - r.left,
                         r.bottom - r.top,
                         NULL,
                         NULL,
                         hInstance,
                         NULL );
    if ( hWnd == NULL )
    {
        MessageBox( NULL, _T( "失敗: CreateWindow()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "CreateWindow: ok\n" ) );


    // ウィンドウ表示
    ShowWindow(hWnd, nCmdShow);
    dtprintf( _T( "ShowWindow: ok\n" ) );



    // スワップチェイン設定
    DXGI_SWAP_CHAIN_DESC scDesc = {
        {
            1280,									// BufferDesc.Width
            720,									// BufferDesc.Height
            {
                60,									// BufferDesc.RefreshRate.Numerator
                1									// BufferDesc.RefreshRate.Denominator
            },
            DXGI_FORMAT_R16G16B16A16_FLOAT,			// BufferDesc.Format
            DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,	// BufferDesc.ScanlineOrdering
            DXGI_MODE_SCALING_CENTERED				// BufferDesc.Scaling
        },
        {
            1,										// SampleDesc.Count
            0										// SampleDesc.Quality
        },
        DXGI_USAGE_RENDER_TARGET_OUTPUT,			// BufferUsage
        1,											// BufferCount
        hWnd,										// OutputWindow
        TRUE,										// Windowed
        DXGI_SWAP_EFFECT_DISCARD,					// SwapEffect
        DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH		// Flags
    };

    // Direct3D11 デバイス・デバイスコンテキスト・スワップチェーンを生成
    ID3D11Device        * pDevice        = NULL;
    ID3D11DeviceContext * pDeviceContext = NULL;
    IDXGISwapChain      * pSwapChain     = NULL;
    D3D_FEATURE_LEVEL     feature;
    hr = D3D11CreateDeviceAndSwapChain( NULL,
                                        D3D_DRIVER_TYPE_HARDWARE,
                                        NULL,
                                        0,
                                        NULL,
                                        0,
                                        D3D11_SDK_VERSION,
                                        &scDesc,
                                        &pSwapChain,
                                        &pDevice,
                                        &feature,
                                        &pDeviceContext );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: D3D11CreateDeviceAndSwapChain()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "D3D11CreateDeviceAndSwapChain: ok (pDevice: 0x%p, pDeviceContext: 0x%p, pSwapChain: 0x%p, feature: 0x%4x)\n" ),
              pDevice,
              pDeviceContext,
              pSwapChain,
              ( int ) feature );


    // バックバッファテクスチャを取得
    ID3D11Texture2D * pBackBuffer = NULL;
    hr = pSwapChain->GetBuffer( 0, __uuidof( pBackBuffer ), reinterpret_cast< void ** >( &pBackBuffer ) );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: IDXGISwapChain::GetBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "IDXGISwapChain::GetBuffer: ok (pBackBuffer: 0x%p)\n" ), pBackBuffer );


    // レンダーターゲットビューを生成
    ID3D11RenderTargetView * pRenderTargetView = NULL;
    hr = pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTargetView );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRenderTargetView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateRenderTargetView: ok (pRenderTargetView: 0x%p)\n" ), pRenderTargetView );


    // デプス・ステンシルバッファとなるテクスチャを生成
    D3D11_TEXTURE2D_DESC depthStencilBufferDesc = {
        1280,						// Width
        720,						// Height
        1,							// MipLevels
        1,							// ArraySize
        DXGI_FORMAT_D32_FLOAT,		// Format
        {
            1,						// SampleDesc.Count
            0						// SampleDesc.Quality
        },
        D3D11_USAGE_DEFAULT,		// Usage
        D3D11_BIND_DEPTH_STENCIL,	// BindFlags
        0,							// CPUAccessFlags
        0							// MiscFlags
    };

    ID3D11Texture2D * pDepthStencilBuffer = NULL;
    hr = pDevice->CreateTexture2D( &depthStencilBufferDesc, NULL, &pDepthStencilBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateTexture2D()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateTexture2D: ok (pDepthStencilBuffer: 0x%p)\n" ), pDepthStencilBuffer );

    // デプス・ステンシルビューを生成
    ID3D11DepthStencilView * pDepthStencilView = NULL;
    hr = pDevice->CreateDepthStencilView( pDepthStencilBuffer, NULL, &pDepthStencilView );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilView()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateDepthStencilView: ok (pDepthStencilView: 0x%p)\n" ), pDepthStencilView );


    // レンダーターゲットビューとデプス・ステンシルビューをバインド
    ID3D11RenderTargetView * pRenderTargetViews[] = { pRenderTargetView };
    pDeviceContext->OMSetRenderTargets( 1, pRenderTargetViews, pDepthStencilView );
    dtprintf( _T( "ID3D11DeviceContext::OMSetRenderTargets: ok\n" ) );

    // バックバッファはもうここでは使わない
    COM_SAFE_RELEASE( pBackBuffer );


    // ビューポートをバインド
    D3D11_VIEWPORT viewport = {
        0.0f,		// TopLeftX
        0.0f,		// TopLeftY
        1280.0f,		// Width
        720.0f,		// Height
        0.0f,		// MinDepth
        1.0f			// MaxDepth
    };
    pDeviceContext->RSSetViewports( 1, &viewport );
    dtprintf( _T( "ID3D11DeviceContext::RSSetViewports: ok\n" ) );


    // 頂点データ
    float vertices[ 8 ][ 7 ] = {
        //    Xaxis  Yaxis  Zaxis  赤     緑     青     Alpha
        { -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  0.0f,  1.0f },   // 手前左上
        {  0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f },   // 手前右上
        {  0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f },   // 手前右下
        { -0.5f, -0.5f,  0.5f,  0.0f,  1.0f,  1.0f,  1.0f },   // 手前左下
        { -0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f },   // 奥左上
        {  0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  1.0f,  1.0f },   // 奥右上
        {  0.5f, -0.5f, -0.5f,  1.0f,  1.0f,  0.0f,  1.0f },   // 奥右下
        { -0.5f, -0.5f, -0.5f,  1.0f,  1.0f,  1.0f,  1.0f }    // 奥左下
    };

    // 頂点バッファを生成
    D3D11_BUFFER_DESC vertexBufferDesc = {
        sizeof( vertices ),			// ByteWidth
        D3D11_USAGE_DEFAULT,		// Usage
        D3D11_BIND_VERTEX_BUFFER,	// BindFlags
        0,							// CPUAccessFlags
        0,							// MiscFlags
        0							// StructureByteStride
    };
    D3D11_SUBRESOURCE_DATA vertexResourceData = { vertices };

    ID3D11Buffer * pVertexBuffer = NULL;
    hr = pDevice->CreateBuffer( &vertexBufferDesc, &vertexResourceData, &pVertexBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVertexBuffer: 0x%p)\n" ), pVertexBuffer );

    // 頂点バッファをバインド
    UINT strides[] = { sizeof( float ) * 7 };
    UINT offsets[] = { 0 };
    pDeviceContext->IASetVertexBuffers( 0, 1, &pVertexBuffer, strides, offsets );
    dtprintf( _T( "ID3D11DeviceContext::IASetVertexBuffers: ok\n" ) );


    // インデックスデータ
    unsigned int indices[] = { 0, 1, 2, 0, 2, 3,    // 手前
                               4, 0, 3, 4, 3, 7,    // 左
                               1, 5, 6, 1, 6, 2,    // 右
                               0, 4, 5, 0, 5, 1,    // 上
                               2, 6, 7, 2, 7, 3,    // 下
                               5, 4, 7, 5, 7, 6
                             };  // 裏

    // インデックスバッファを生成
    D3D11_BUFFER_DESC indexBufferDesc = {
        sizeof( indices ),				// ByteWidth
        D3D11_USAGE_DEFAULT,			// Usage
        D3D11_BIND_INDEX_BUFFER,		// BindFlags
        0,								// CPUAccessFlags
        0,								// MiscFlags
        0								// StructureByteStride
    };
    D3D11_SUBRESOURCE_DATA indexResourceData = { indices };

    ID3D11Buffer * pIndexBuffer = NULL;
    hr = pDevice->CreateBuffer( &indexBufferDesc, &indexResourceData, &pIndexBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pIndexBuffer: 0x%p)\n" ), pIndexBuffer );

    // インデックスバッファをバインド
    pDeviceContext->IASetIndexBuffer( pIndexBuffer, DXGI_FORMAT_R32_UINT, 0 );
    dtprintf( _T( "ID3D11DeviceContext::IASetIndexBuffer: ok\n" ) );


    // プリミティブタイプを設定
    pDeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
    dtprintf( _T( "ID3D11DeviceContext::IASetPrimitiveTopology: ok\n" ) );


    // 頂点シェーダ用の定数バッファを作成
    D3D11_BUFFER_DESC VSConstantBufferDesc = {
        sizeof( D3DXMATRIX ) * 3,		// ByteWidth
        D3D11_USAGE_DYNAMIC,			// Usage
        D3D11_BIND_CONSTANT_BUFFER,		// BindFlags
        D3D11_CPU_ACCESS_WRITE,			// CPUAccessFlags
        0,								// MiscFlags
        0								// StructureByteStride
    };

    ID3D11Buffer * pVSConstantBuffer = NULL;
    hr = pDevice->CreateBuffer( &VSConstantBufferDesc, NULL, &pVSConstantBuffer );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateBuffer()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateBuffer: ok (pVSConstantBuffer: 0x%p)\n" ), pVSConstantBuffer );

    // 定数バッファをバインド
    pDeviceContext->VSSetConstantBuffers( 0, 1, &pVSConstantBuffer );
    dtprintf( _T( "ID3D11DeviceContext::VSSetConstantBuffers: ok\n" ) );


    // 頂点シェーダを作成
    ID3D11VertexShader * pVertexShader = NULL;
    hr = pDevice->CreateVertexShader( g_vs_perspective, sizeof( g_vs_perspective ), NULL, &pVertexShader );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateVertexShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateVertexShader: ok (pVertexShader: 0x%p)\n" ), pVertexShader );

    // ピクセルシェーダを作成
    ID3D11PixelShader * pPixelShader = NULL;
    hr = pDevice->CreatePixelShader( g_ps_constant, sizeof( g_ps_constant ), NULL, &pPixelShader );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreatePixelShader()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreatePixelShader: ok (pPixelShader: 0x%p)\n" ), pPixelShader );

    // シェーダをバインド
    pDeviceContext->VSSetShader( pVertexShader, NULL, 0 );
    dtprintf( _T( "ID3D11DeviceContext::VSSetShader: ok\n" ) );
    pDeviceContext->PSSetShader( pPixelShader, NULL, 0 );
    dtprintf( _T( "ID3D11DeviceContext::PSSetShader: ok\n" ) );
    pDeviceContext->GSSetShader( NULL, NULL, 0 );
    pDeviceContext->HSSetShader( NULL, NULL, 0 );
    pDeviceContext->DSSetShader( NULL, NULL, 0 );


    // 入力エレメント記述子
    D3D11_INPUT_ELEMENT_DESC verticesDesc[] = {
        { "IN_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, 0,               D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "IN_COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    // 入力レイアウトを生成
    ID3D11InputLayout * pInputLayout = NULL;
    hr = pDevice->CreateInputLayout( verticesDesc, 2, g_vs_perspective, sizeof( g_vs_perspective ), &pInputLayout );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateInputLayout()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateInputLayout: ok (pInputLayout: 0x%p)\n" ), pInputLayout );

    // 入力レイアウトをバインド
    pDeviceContext->IASetInputLayout( pInputLayout );
    dtprintf( _T( "ID3D11DeviceContext::IASetInputLayout: ok\n" ) );


    // ラスタライザステートを生成
    D3D11_RASTERIZER_DESC rasterizerStateDesc = {
        D3D11_FILL_SOLID,		// FillMode
//		D3D11_FILL_WIREFRAME,	// FillMode (ワイヤーフレーム表示)
        D3D11_CULL_BACK,		// CullMode
//		D3D11_CULL_NONE,		// CullMode (カリングなし)
        FALSE,					// FrontCounterClockwise
        0,						// DepthBias
        0.0f,					// DepthBiasClamp
        0.0f,					// SlopeScaledDepthBias
        TRUE,					// DepthClipEnable
        FALSE,					// ScissorEnable
        FALSE,					// MultisampleEnable
        FALSE					// AntialiasedLineEnable
    };

    ID3D11RasterizerState * pRasterizerState = NULL;
    hr = pDevice->CreateRasterizerState( &rasterizerStateDesc, &pRasterizerState );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateRasterizerState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateRasterizerState: ok (pRasterizerState: 0x%p)\n" ), pRasterizerState );

    // ラスタライザステートをバインド
    pDeviceContext->RSSetState( pRasterizerState );
    dtprintf( _T( "ID3D11DeviceContext::RSSetState: ok\n" ) );


    // デプス・ステンシルステートを生成
    D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc = {
        TRUE,								// DepthEnable
        D3D11_DEPTH_WRITE_MASK_ALL,			// DepthWriteMask
        D3D11_COMPARISON_LESS,				// DepthFunc
        FALSE,								// StencilEnable
        D3D11_DEFAULT_STENCIL_READ_MASK,	// StencilReadMask
        D3D11_DEFAULT_STENCIL_WRITE_MASK,	// StencilWriteMask
        {
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilFailOp
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilDepthFailOp
            D3D11_STENCIL_OP_KEEP,			// FrontFace.StencilPassOp
            D3D11_COMPARISON_ALWAYS			// FrontFace.StencilFunc
        },
        {
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilFailOp
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilDepthFailOp
            D3D11_STENCIL_OP_KEEP,			// BackFace.StencilPassOp
            D3D11_COMPARISON_ALWAYS			// BackFace.StencilFunc
        }
    };

    ID3D11DepthStencilState * pDepthStencilState = NULL;
    hr = pDevice->CreateDepthStencilState( &depthStencilStateDesc, &pDepthStencilState );
    if ( FAILED( hr ) )
    {
        MessageBox( NULL, _T( "失敗: ID3D11Device::CreateDepthStencilState()" ), _T( "エラー" ), MB_OK | MB_ICONERROR );
        return 0;
    }
    dtprintf( _T( "ID3D11Device::CreateDepthStencilState: ok (pDepthStencilState: 0x%p)\n" ), pDepthStencilState );

    // デプス・ステンシルステートをバインド
    pDeviceContext->OMSetDepthStencilState( pDepthStencilState, 0 );
    dtprintf( _T( "ID3D11DeviceContext::OMSetDepthStencilState: ok\n" ) );



    MSG msg;

    while ( 1 )
    {
        // メッセージを取得
        if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            if ( msg.message == WM_QUIT )
            {
                dtprintf( _T( "PeekMessage: WM_QUIT\n" ) );
                break;
            }
            // メッセージ処理
            DispatchMessage( &msg );
        }
        else
        {
            HRESULT hr;

            static unsigned int count = 0;

            float theta = ( count++ / 200.0f ) * ( 3.141593f / 2.0f );


            // World-View-Projection 行列をそれぞれ生成
            D3DXMATRIX world, view, projection;

            D3DXMatrixIdentity( &world );

            const D3DXVECTOR3 eye( 1.8f * 1.414214f * -cosf( theta ), 1.8f, 1.8f * 1.414214f * sinf( theta ) );
            const D3DXVECTOR3 at( 0.0f, 0.0f, 0.0f );
            const D3DXVECTOR3 up( 0.0f, 1.0f, 0.0f );
            D3DXMatrixLookAtRH( &view, &eye, &at, &up );

            D3DXMatrixPerspectiveFovRH( &projection, 3.141593f / 4.0f, 1280.0f / 720.0f, 1.0f, 10000.0f );


            // 頂点シェーダ用定数バッファへアクセス
            D3D11_MAPPED_SUBRESOURCE mapped;
            hr = pDeviceContext->Map( pVSConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped );
            if ( SUCCEEDED( hr ) )
            {
                D3DXMATRIX * mapped_m = static_cast< D3DXMATRIX * >( mapped.pData );

                mapped_m[0] = world;
                mapped_m[1] = view;
                mapped_m[2] = projection;

                // 後始末
                pDeviceContext->Unmap( pVSConstantBuffer, 0 );
            }


            // レンダーターゲットビューをクリア
            const float clear[ 4 ] = { 0.0f, 0.0f, 0.3f, 1.0f };	// RGBA
            pDeviceContext->ClearRenderTargetView( pRenderTargetView, clear );

            // デプス・ステンシルビューをクリア
            pDeviceContext->ClearDepthStencilView( pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 );


            // 描画
            pDeviceContext->DrawIndexed( 36, 0, 0 );

            pSwapChain->Present( 1, 0 );

            // ちょっとだけ待つ
            Sleep( 5 );
        }
    }



    // シェーダをアンバインド
    pDeviceContext->VSSetShader( NULL, NULL, 0 );
    pDeviceContext->PSSetShader( NULL, NULL, 0 );

    // デバイス・リソース解放
    COM_SAFE_RELEASE( pDepthStencilState );
    COM_SAFE_RELEASE( pRasterizerState );
    COM_SAFE_RELEASE( pInputLayout );
    COM_SAFE_RELEASE( pPixelShader );
    COM_SAFE_RELEASE( pVertexShader );
    COM_SAFE_RELEASE( pVSConstantBuffer );
    COM_SAFE_RELEASE( pIndexBuffer );
    COM_SAFE_RELEASE( pVertexBuffer );
    COM_SAFE_RELEASE( pDepthStencilView );
    COM_SAFE_RELEASE( pDepthStencilBuffer );
    COM_SAFE_RELEASE( pRenderTargetView );
    COM_SAFE_RELEASE( pSwapChain );
    COM_SAFE_RELEASE( pDeviceContext );
    COM_SAFE_RELEASE( pDevice );


    return msg.wParam;
}
示例#9
0
    bool init(ID3D11Device* dev, int argc, char** argv)
    {
        this->dev = dev;

        for(char** p = argv + 1; *p; ++p) {
            if(!strcmp(*p, "-w"))
                wireframe = 1;
            else if(!strcmp(*p, "-b"))
                blue_only = true;
            else if(!strcmp(*p, "-t"))
                triangles = atoi(*++p);
            else if(!strcmp(*p, "-m"))
                impressions = (float)atof(*++p);
            else if(!strcmp(*p, "-p"))
                period = (float)atof(*++p);
            else if(!strcmp(*p, "-s"))
                speed = (float)atof(*++p);
            else {
                fprintf(stderr, "Usage: d3d11gears [-v|-w] [-t TRIANGLES]\n");
                fprintf(stderr, "d3d11gears is an enhanced port of glxgears to Direct3D 11\n");
                fprintf(stderr, "\n");
                //fprintf(stderr, "-v\t\tuse per-vertex diffuse-only lighting (classic glxgears look)\n");
                fprintf(stderr, "-w\t\twireframe mode\n");
                fprintf(stderr, "-t TRIANGLES\ttriangle budget (default is 3200)\n");
                fprintf(stderr, "-m IMPRESSIONS\tmotion blur impressions (default is 1)\n");
                fprintf(stderr, "-p PERIOD\tspeed reversal period (default is infinite)\n");
                fprintf(stderr, "-s SPEED\tgear speed (default is 1.0)\n");
                fprintf(stderr, "-b\tonly show blue gear (for faster motion blur)\n");
                return false;
            }
        }

        ensure(dev->CreatePixelShader(g_ps, sizeof(g_ps), NULL, &ps));
        ensure(dev->CreateVertexShader(g_vs, sizeof(g_vs), NULL, &vs));

        gears[0].color = vec(0.8f, 0.1f, 0.0f, 1.0f);
        gears[1].color = vec(0.0f, 0.8f, 0.2f, 1.0f);
        gears[2].color = vec(0.2f, 0.2f, 1.0f, 1.0f);

        gears[0].mesh = build_gear(dev, triangles / 2, 1.0f, 4.0f, 1.0f, 20, 0.7f);
        gears[1].mesh = build_gear(dev, triangles / 4, 0.5f, 2.0f, 2.0f, 10, 0.7f);
        gears[2].mesh = build_gear(dev, triangles / 4, 1.3f, 2.0f, 0.5f, 10, 0.7f);

        gears[0].x = -3.0f;
        gears[0].y = -2.0f;
        gears[0].wmul = 1.0f;
        gears[0].t0 = 0.0 * M_PI / 180.0f;

        gears[1].x = 3.1f;
        gears[1].y = -2.0f;
        gears[1].wmul = -2.0f;
        gears[1].t0 = -9.0f * (float)M_PI / 180.0f;

        gears[2].x = -3.1f;
        gears[2].y = 4.2f;
        gears[2].wmul = -2.0f;
        gears[2].t0 = -25.0f * (float)M_PI / 180.0f;

        D3D11_BUFFER_DESC bufferd;
        memset(&bufferd, 0, sizeof(bufferd));
        bufferd.ByteWidth = sizeof(cbuf_t);
        bufferd.Usage = D3D11_USAGE_DEFAULT;
        bufferd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        ensure(dev->CreateBuffer(&bufferd, 0, &cb));

        if(impressions > 1)
        {
            D3D11_BLEND_DESC blendd;
            memset(&blendd, 0, sizeof(blendd));
            blendd.RenderTarget[0].BlendEnable = TRUE;
            blendd.RenderTarget[0].BlendOp = blendd.RenderTarget[0].BlendOpAlpha
                                             = D3D11_BLEND_OP_ADD;
            blendd.RenderTarget[0].SrcBlend = blendd.RenderTarget[0].SrcBlendAlpha
                                              = D3D11_BLEND_BLEND_FACTOR;
            blendd.RenderTarget[0].DestBlend = blendd.RenderTarget[0].DestBlendAlpha
                                               = D3D11_BLEND_ONE;
            blendd.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
            ensure(dev->CreateBlendState(&blendd, &blend));

            D3D11_DEPTH_STENCIL_DESC zsad;
            memset(&zsad, 0, sizeof(zsad));
            zsad.DepthEnable = TRUE;
            zsad.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
            zsad.DepthFunc = D3D11_COMPARISON_EQUAL;
            ensure(dev->CreateDepthStencilState(&zsad, &zsa));

            blitter = new d3d11_blitter(dev);
        }

        return true;
    }
bool SetupRendering(osvr::renderkit::GraphicsLibrary library) {
    // Make sure our pointers are filled in correctly.
    if (library.D3D11 == nullptr) {
        std::cerr << "SetupRendering: No D3D11 GraphicsLibrary, this should "
                     "not happen"
                  << std::endl;
        return false;
    }

    ID3D11Device* device = library.D3D11->device;
    ID3D11DeviceContext* context = library.D3D11->context;

    // Setup vertex shader
    auto hr = device->CreateVertexShader(g_triangle_vs, sizeof(g_triangle_vs),
                                         nullptr, vertexShader.GetAddressOf());
    if (FAILED(hr)) {
        return false;
    }

    // Setup pixel shader
    hr = device->CreatePixelShader(g_triangle_ps, sizeof(g_triangle_ps),
                                   nullptr, pixelShader.GetAddressOf());
    if (FAILED(hr)) {
        return false;
    }

    // Set the input layout
    ID3D11InputLayout* vertexLayout;
    D3D11_INPUT_ELEMENT_DESC layout[] = {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
         D3D11_INPUT_PER_VERTEX_DATA, 0},
    };
    hr = device->CreateInputLayout(layout, _countof(layout), g_triangle_vs,
                                   sizeof(g_triangle_vs), &vertexLayout);
    if (SUCCEEDED(hr)) {
        context->IASetInputLayout(vertexLayout);
        vertexLayout->Release();
        vertexLayout = nullptr;
    }

    // Create vertex buffer
    SimpleVertex vertices[3];
    vertices[0].Pos.x = 0.0f;
    vertices[0].Pos.y = 0.5f;
    vertices[0].Pos.z = 0.5f;
    vertices[1].Pos.x = 0.5f;
    vertices[1].Pos.y = -0.5f;
    vertices[1].Pos.z = 0.5f;
    vertices[2].Pos.x = -0.5f;
    vertices[2].Pos.y = -0.5f;
    vertices[2].Pos.z = 0.5f;
    CD3D11_BUFFER_DESC bufferDesc(sizeof(SimpleVertex) * _countof(vertices),
                                  D3D11_BIND_VERTEX_BUFFER);
    D3D11_SUBRESOURCE_DATA subResData = {vertices, 0, 0};
    hr = device->CreateBuffer(&bufferDesc, &subResData, &g_vertexBuffer);

    // Describe how depth and stencil tests should be performed.
    // In particular, that they should not be for this 2D example
    // where we want to render a triangle no matter what.
    D3D11_DEPTH_STENCIL_DESC depthStencilDescription = {};
    depthStencilDescription.DepthEnable = false;
    depthStencilDescription.StencilEnable = false;

    // Create depth stencil state and set it.
    hr = device->CreateDepthStencilState(&depthStencilDescription,
                                         &g_depthStencilState);
    if (FAILED(hr)) {
        std::cerr << "SetupRendering: Could not create depth/stencil state"
                  << std::endl;
        return false;
    }

    return true;
}