void D2DComponent::BeginDraw(Windows::Foundation::Rect updateRect)
{
	Microsoft::WRL::ComPtr<IDXGISurface> surface;
	POINT offset;
	RECT updateRectNative =
	{
		(LONG)updateRect.Left,
		(LONG)updateRect.Top,
		(LONG)updateRect.Right,
		(LONG)updateRect.Bottom
	};

	HRESULT beginDrawHR = _sisNative->BeginDraw(updateRectNative, &surface, &offset);
	if (beginDrawHR == DXGI_ERROR_DEVICE_REMOVED || beginDrawHR == DXGI_ERROR_DEVICE_RESET)
	{
		CreateDeviceResources();
		BeginDraw(updateRect);
	}
	else
	{
		ThrowIfFailed(beginDrawHR);
	}


	Microsoft::WRL::ComPtr<ID2D1Bitmap1> bitmap;
	ThrowIfFailed(_d2dDeviceContext->CreateBitmapFromDxgiSurface(surface.Get(), nullptr, &bitmap));
	_d2dDeviceContext->BeginDraw();
	_d2dDeviceContext->SetTarget(bitmap.Get());
}
Exemple #2
0
void Model::CreatePipelineState()
{
	Microsoft::WRL::ComPtr<ID3DBlob> VertexShader;
	Microsoft::WRL::ComPtr<ID3DBlob> PixelShader;

	LoadAndCompileShader(VertexShader, PixelShader);

	std::array<D3D12_INPUT_ELEMENT_DESC, 2> InputElementDesc
	{ {
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
		{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
	} };

	D3D12_GRAPHICS_PIPELINE_STATE_DESC PipelineStateDesc = {};
	PipelineStateDesc.InputLayout = { InputElementDesc.data(), static_cast<UINT>(InputElementDesc.size()) };
	PipelineStateDesc.pRootSignature = RootSignature.Get();
	PipelineStateDesc.VS = CD3DX12_SHADER_BYTECODE(VertexShader.Get());
	PipelineStateDesc.PS = CD3DX12_SHADER_BYTECODE(PixelShader.Get());
	PipelineStateDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
	PipelineStateDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
	PipelineStateDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
	PipelineStateDesc.SampleMask = UINT_MAX;
	PipelineStateDesc.SampleDesc.Count = 1;
	PipelineStateDesc.NumRenderTargets = 1;
	PipelineStateDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
	PipelineStateDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
	PipelineStateDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;

	Utility::ThrowOnFail(DeviceContext.GetDevice()->CreateGraphicsPipelineState(&PipelineStateDesc, IID_PPV_ARGS(&PipelineState)));
}
Exemple #3
0
void glClear(GLbitfield mask)
{
    if( g_pD3DContext )
    {
        g_pD3DContext->ClearRenderTargetView( g_pD3DRenderTargetView.Get(), g_ClearColor );
        g_pD3DContext->ClearDepthStencilView( g_pD3DDepthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0 );
    }
}
Exemple #4
0
bool Shape::CombineWith(Shape* otherShape, D2D1_COMBINE_MODE mode)
{
	Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
	Microsoft::WRL::ComPtr<ID2D1PathGeometry> path;
	HRESULT hr = Canvas::c_D2DFactory->CreatePathGeometry(path.GetAddressOf());
	if (FAILED(hr)) return false;

	hr = path->Open(sink.GetAddressOf());
	if (FAILED(hr)) return false;

	if (otherShape)
	{
		hr = m_Shape->CombineWithGeometry(
			otherShape->m_Shape.Get(),
			mode,
			otherShape->GetShapeMatrix(),
			sink.Get());
		if (FAILED(hr)) return false;

		sink->Close();

		hr = path.CopyTo(m_Shape.ReleaseAndGetAddressOf());
		if (FAILED(hr)) return false;

		return true;
	}

	static const D2D1_RECT_F rect = { 0.0f, 0.0f, 0.0f, 0.0f };
	Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> emptyShape;
	hr = Canvas::c_D2DFactory->CreateRectangleGeometry(rect, emptyShape.GetAddressOf());
	if (FAILED(hr)) return false;

	hr = emptyShape->CombineWithGeometry(m_Shape.Get(), mode, GetShapeMatrix(), sink.Get());

	sink->Close();

	if (FAILED(hr)) return false;

	hr = path.CopyTo(m_Shape.ReleaseAndGetAddressOf());
	if (FAILED(hr)) return false;

	m_Rotation = 0.0f;
	m_RotationAnchor = D2D1::Point2F();
	m_RotationAnchorDefined = false;
	m_Scale = D2D1::SizeF(1.0f, 1.0f);
	m_ScaleAnchor = D2D1::Point2F();
	m_ScaleAnchorDefined = false;
	m_Skew = D2D1::Point2F();
	m_SkewAnchor = D2D1::Point2F();
	m_SkewAnchorDefined = false;
	m_Offset = D2D1::SizeF(0.0f, 0.0f);

	return true;
}
IFACEMETHODIMP CustomTextRenderer::DrawStrikethrough(
    _In_opt_ void* clientDrawingContext,
    FLOAT baselineOriginX,
    FLOAT baselineOriginY,
    _In_ DWRITE_STRIKETHROUGH const* strikethrough,
    IUnknown* clientDrawingEffect
    )
{
    HRESULT hr;

    D2D1_RECT_F rect = D2D1::RectF(
        0,
        strikethrough->offset,
        strikethrough->width,
        strikethrough->offset + strikethrough->thickness
        );

    Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> rectangleGeometry;
    hr = D2DFactory.Get()->CreateRectangleGeometry(
        &rect,
        &rectangleGeometry
        );

    // Initialize a matrix to translate the origin of the strikethrough
    D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F(
        1.0f, 0.0f,
        0.0f, 1.0f,
        baselineOriginX, baselineOriginY
        );

    Microsoft::WRL::ComPtr<ID2D1TransformedGeometry> transformedGeometry;
    if (SUCCEEDED(hr))
    {
        hr = D2DFactory.Get()->CreateTransformedGeometry(
            rectangleGeometry.Get(),
            &matrix,
            &transformedGeometry
            );
    }

    // Draw the outline of the rectangle
    D2DDeviceContext.Get()->DrawGeometry(
        transformedGeometry.Get(),
        outlineBrush.Get()
        );

    // Fill in the rectangle
    D2DDeviceContext.Get()->FillGeometry(
        transformedGeometry.Get(),
        fillBrush.Get()
        );

    return S_OK;
}
Exemple #6
0
	Microsoft::WRL::ComPtr<ID3D12Resource> Renderer::UploadIndexData(void *data, long dataSize)
	{
		WaitForGpu();

		// Command list allocators can only be reset when the associated 
		// command lists have finished execution on the GPU; apps should use 
		// fences to determine GPU execution progress.
		ThrowIfFailed(_commandAllocators[_frameIndex]->Reset());

		// However, when ExecuteCommandList() is called on a particular command 
		// list, that command list can then be reset at any time and must be before 
		// re-recording.
		ThrowIfFailed(_commandList->Reset(_commandAllocators[_frameIndex].Get(), NULL));

		Microsoft::WRL::ComPtr<ID3D12Resource> indexBuffer;
		Microsoft::WRL::ComPtr<ID3D12Resource> indexBufferUpload;

		ThrowIfFailed(_device->CreateCommittedResource(
			&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
			D3D12_HEAP_FLAG_NONE,
			&CD3DX12_RESOURCE_DESC::Buffer(dataSize),
			D3D12_RESOURCE_STATE_COPY_DEST,
			nullptr,
			IID_PPV_ARGS(&indexBuffer)));

		ThrowIfFailed(_device->CreateCommittedResource(
			&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
			D3D12_HEAP_FLAG_NONE,
			&CD3DX12_RESOURCE_DESC::Buffer(dataSize),
			D3D12_RESOURCE_STATE_GENERIC_READ,
			nullptr,
			IID_PPV_ARGS(&indexBufferUpload)));

		// Copy data to the intermediate upload heap and then schedule a copy 
		// from the upload heap to the vertex buffer.
		UINT8* pIndexDataBegin;
		ThrowIfFailed(indexBufferUpload->Map(0, &CD3DX12_RANGE(0, dataSize), reinterpret_cast<void**>(&pIndexDataBegin)));
		memcpy(pIndexDataBegin, data, dataSize);
		indexBufferUpload->Unmap(0, nullptr);

		_commandList->CopyBufferRegion(indexBuffer.Get(), 0, indexBufferUpload.Get(), 0, dataSize);
		_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(indexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER));

		// Close the command list and execute it to begin the vertex buffer copy into
		// the default heap.
		ThrowIfFailed(_commandList->Close());
		ID3D12CommandList* ppCommandLists[] = { _commandList.Get() };
		_commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);

		WaitForGpu();

		return indexBuffer;
	}
EncodedJSValue JSC_HOST_CALL COMMethodCall::call(ExecState* execState) {
    COMMethodCall* callee = jsCast<COMMethodCall*>(execState->callee());
    if (execState->argumentCount() != callee->_parameterCells.size()) {
        // TODO: error
        CRASH();
    }

    COMInterop* interop = jsCast<GlobalObject*>(execState->lexicalGlobalObject())->interop();

    size_t numberOfABIParameters = callee->_parameterCells.size() + (callee->_isVoid ? 1 : 2);

    HRESULT hr;

    Microsoft::WRL::ComPtr<IUnknown> self;
    hr = interop->wrap(execState->thisValue(), callee->_methodInterface, self.GetAddressOf());

    void** vtable = *reinterpret_cast<void***>(self.Get());
    void* fn = vtable[callee->_methodIndex];

    WTF::Vector<void*> arguments;
    arguments.reserveCapacity(numberOfABIParameters);

    IUnknown* thisValue = self.Get();
    arguments.append(&thisValue);

    for (int i = 0; i < callee->_parameterCells.size(); i++) {
        JSCell* type = callee->_parameterCells[i].get();
        void* buffer = _alloca(std::max(sizeof(ffi_arg), callee->_parameterTypes[i + 1]->size));
        getFFIMethodTable(type)->marshalJSToNative(type, execState, execState->uncheckedArgument(i), buffer);
        arguments.append(buffer);
    }

    void* returnBuffer = nullptr;
    if (!callee->_isVoid) {
        returnBuffer = _alloca(std::max(sizeof(ffi_arg), callee->_parameterTypes[numberOfABIParameters - 1]->size));
        arguments.append(&returnBuffer);
    }

    ffi_call(&callee->_cif, FFI_FN(fn), &hr, arguments.data());

    JSValue jsResult;
    if (!SUCCEEDED(hr)) {
        _com_error error(hr, nullptr);
        jsResult = execState->vm().throwException(execState, createError(execState, error.ErrorMessage()));
    } else if (!callee->_isVoid) {
        JSCell* returnType = callee->_returnType.get();
        jsResult = getFFIMethodTable(returnType)->marshalNativeToJS(returnType, execState, returnBuffer);
    } else {
        jsResult = jsUndefined();
    }

    return JSValue::encode(jsResult);
}
Exemple #8
0
void UpdateDepthState()
{
    if( g_DepthTestEnabled == true && g_DepthMaskEnabled == true )
        g_pD3DContext->OMSetDepthStencilState( g_pD3DDepthStencilState_DepthTestEnabled_DepthWriteEnabled.Get(), 1 );

    else if( g_DepthTestEnabled == false && g_DepthMaskEnabled == true )
        g_pD3DContext->OMSetDepthStencilState( g_pD3DDepthStencilState_DepthTestDisabled_DepthWriteEnabled.Get(), 1 );

    else if( g_DepthTestEnabled == true && g_DepthMaskEnabled == false )
        g_pD3DContext->OMSetDepthStencilState( g_pD3DDepthStencilState_DepthTestEnabled_DepthWriteDisabled.Get(), 1 );

    else if( g_DepthTestEnabled == false && g_DepthMaskEnabled == false )
        g_pD3DContext->OMSetDepthStencilState( g_pD3DDepthStencilState_DepthTestDisabled_DepthWriteDisabled.Get(), 1 );
}
// Callbacks to draw things in world space, left-hand space, and right-hand
// space.
void DrawWorld(
    void* userData //< Passed into AddRenderCallback
    ,
    osvr::renderkit::GraphicsLibrary library //< Graphics library context to use
    ,
    osvr::renderkit::RenderBuffer buffers //< Buffers to use
    ,
    osvr::renderkit::OSVR_ViewportDescription
        viewport //< Viewport we're rendering into
    ,
    OSVR_PoseState pose //< OSVR ModelView matrix set by RenderManager
    ,
    osvr::renderkit::OSVR_ProjectionMatrix
        projection //< Projection matrix set by RenderManager
    ,
    OSVR_TimeValue deadline //< When the frame should be sent to the screen
    ) {
    // Make sure our pointers are filled in correctly.
    if (library.D3D11 == nullptr) {
        std::cerr
            << "DrawWorld: No D3D11 GraphicsLibrary, this should not happen"
            << std::endl;
        return;
    }
    if (buffers.D3D11 == nullptr) {
        std::cerr << "DrawWorld: No D3D11 RenderBuffer, this should not happen"
                  << std::endl;
        return;
    }

    ID3D11DeviceContext* context = library.D3D11->context;
    ID3D11RenderTargetView* renderTargetView = buffers.D3D11->colorBufferView;

    // Set vertex buffer
    UINT stride = sizeof(SimpleVertex);
    UINT offset = 0;
    context->IASetVertexBuffers(0, 1, &g_vertexBuffer, &stride, &offset);

    // Set primitive topology
    context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    // Set depth/stencil state
    context->OMSetDepthStencilState(g_depthStencilState, 1);

    // Draw a triangle using the simple shaders
    context->VSSetShader(vertexShader.Get(), nullptr, 0);
    context->PSSetShader(pixelShader.Get(), nullptr, 0);
    context->Draw(3, 0);
}
Exemple #10
0
	void Draw(const Microsoft::WRL::ComPtr<ID3D11DeviceContext> &pDeviceContext)
	{
		// VBのセット
		ID3D11Buffer* pBufferTbl[] = { m_pVertexBuf.Get() };
		UINT SizeTbl[] = { sizeof(Vertex) };
		UINT OffsetTbl[] = { 0 };
		pDeviceContext->IASetVertexBuffers(0, 1, pBufferTbl, SizeTbl, OffsetTbl);
		// IBのセット
		pDeviceContext->IASetIndexBuffer(m_pIndexBuf.Get(), DXGI_FORMAT_R32_UINT, 0);
		// プリミティブタイプのセット
		pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

		pDeviceContext->DrawIndexed(m_indices // index count
			, 0, 0);
	}
Exemple #11
0
	ID3D11DepthStencilView* CreateDepthStencilView(ID3D11Device* pDevice,DWORD dwWidth, DWORD dwHeight)
	{
		HRESULT hr;
		ID3D11DepthStencilView* pDSV = nullptr;
		Microsoft::WRL::ComPtr<ID3D11Texture2D> pDSTexture = nullptr;
		D3D11_TEXTURE2D_DESC DescDepth;
		DescDepth.Width = dwWidth;
		DescDepth.Height = dwHeight;
		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;
		if (FAILED(hr = pDevice->CreateTexture2D(&DescDepth, NULL, &pDSTexture)))
		{
			return nullptr;
		}

		D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
		ZeroMemory(&dsvd, sizeof(dsvd));
		dsvd.Format = DescDepth.Format;
		dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
		dsvd.Texture2D.MipSlice = 0;

		if (FAILED(hr = pDevice->CreateDepthStencilView(
			pDSTexture.Get(), &dsvd, &pDSV)))
		{			
			return nullptr;
		}		
		return pDSV;
	}
Exemple #12
0
void FlowLayoutSink::SetGlyphRun(
    float x,
    float y,
    UINT32 glyphCount,
    const UINT16* glyphIndices,                 // [glyphCount]
    const float* glyphAdvances,                 // [glyphCount]
    const DWRITE_GLYPH_OFFSET* glyphOffsets,    // [glyphCount]
    Microsoft::WRL::ComPtr<IDWriteFontFace> fontFace,
    float fontEmSize,
    UINT8 glyphOrientation,
    bool isReversed,
    bool isSideways
    )
{
    // Append this glyph run to the list.
    m_glyphRuns.resize(m_glyphRuns.size() + 1);
    CustomGlyphRun& glyphRun = m_glyphRuns.back();
    UINT32 glyphStart = static_cast<UINT32>(m_glyphAdvances.size());

    m_glyphIndices.insert (m_glyphIndices.end(),  glyphIndices,  glyphIndices  + glyphCount);
    m_glyphAdvances.insert(m_glyphAdvances.end(), glyphAdvances, glyphAdvances + glyphCount);
    m_glyphOffsets.insert (m_glyphOffsets.end(),  glyphOffsets,  glyphOffsets  + glyphCount);

    glyphRun.x                  = x;
    glyphRun.y                  = y;
    glyphRun.glyphOrientation   = glyphOrientation;
    glyphRun.glyphStart         = glyphStart;
    glyphRun.isSideways         = isSideways;
    glyphRun.isReversed         = isReversed;
    glyphRun.glyphCount         = glyphCount;
    glyphRun.fontEmSize         = fontEmSize;
    glyphRun.fontFace           = fontFace.Get();
}
ID3D12DescriptorHeap* DynamicDescriptorHeap::RequestDescriptorHeap(void)
{
	std::lock_guard<std::mutex> LockGuard(sm_Mutex);

	while (!sm_RetiredDescriptorHeaps.empty() && g_CommandManager.IsFenceComplete(sm_RetiredDescriptorHeaps.front().first))
	{
		sm_AvailableDescriptorHeaps.push(sm_RetiredDescriptorHeaps.front().second);
		sm_RetiredDescriptorHeaps.pop();
	}

	if (!sm_AvailableDescriptorHeaps.empty())
	{
		ID3D12DescriptorHeap* HeapPtr = sm_AvailableDescriptorHeaps.front();
		sm_AvailableDescriptorHeaps.pop();
		return HeapPtr;
	}
	else
	{
		D3D12_DESCRIPTOR_HEAP_DESC HeapDesc = {};
		HeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
		HeapDesc.NumDescriptors = kNumDescriptorsPerHeap;
		HeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
		HeapDesc.NodeMask = 1;
		Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> HeapPtr;
		ASSERT_SUCCEEDED(g_Device->CreateDescriptorHeap(&HeapDesc, MY_IID_PPV_ARGS(&HeapPtr)));
		sm_DescriptorHeapPool.emplace_back(HeapPtr);
		return HeapPtr.Get();
	}
}
Exemple #14
0
void Model::Create()
{
	CreateRootSignature();
	CreatePipelineState();

	Microsoft::WRL::ComPtr<ID3D12CommandAllocator> CommandAllocator;
	Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> CommandList;
	Microsoft::WRL::ComPtr<ID3D12Resource> VertexUploadResource;
	Microsoft::WRL::ComPtr<ID3D12Resource> IndexUploadResource;
	GPUFence Fence;

	Fence.Initialize(DeviceContext.GetDevice());
	Utility::ThrowOnFail(DeviceContext.GetDevice()->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&CommandAllocator)));
	Utility::ThrowOnFail(DeviceContext.GetDevice()->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, CommandAllocator.Get(), nullptr, IID_PPV_ARGS(&CommandList)));
	
	UploadVertices(CommandList, VertexUploadResource);
	UploadIndices(CommandList, IndexUploadResource);

	Utility::ThrowOnFail(CommandList->Close());

	ID3D12CommandList * CommandListPointer = CommandList.Get();
	DeviceContext.GetCommandQueue()->ExecuteCommandLists(1, &CommandListPointer);

	Fence.SetAndWait(DeviceContext.GetCommandQueue());
}
HRESULT Sample2DSceneRenderer::CreateBitmapBrush(PCWSTR uri, ID2D1BitmapBrush **ppBitmapBrush)
{
	Microsoft::WRL::ComPtr<ID2D1Bitmap> ppBitmap;

	auto hr = LoadBitmapFromFile(m_deviceResources.get(), uri, &ppBitmap);
	auto context = m_deviceResources->GetD2DDeviceContext();
	hr = context->CreateBitmapBrush(ppBitmap.Get(), &m_pBitmapBrush);
	return hr;
}
	void PrimitveDrawer::End()
	{

		Microsoft::WRL::ComPtr<ID3D11RasterizerState> pRSState;
		m_pContext->RSGetState(&pRSState);
		m_pContext->RSSetState(m_pStates->CullClockwise());
		m_pDirectXBatch->End();
		m_pContext->RSSetState(pRSState.Get());
	}
Exemple #17
0
void MazeWallObstacle::Render( Microsoft::WRL::ComPtr<ID2D1DeviceContext> & d2dContext ) const
{
	Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> brush;
	DX::ThrowIfFailed(d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &brush));
	D2D1_POINT_2F const pt1 = {(float)m_pt1.m_x, (float)m_pt1.m_y};
	D2D1_POINT_2F const pt2 = {(float)m_pt2.m_x, (float)m_pt2.m_y};

	d2dContext->DrawLine(pt1, pt2, brush.Get());
}
Exemple #18
0
void DXWrapper_InitDeviceAndContext( Microsoft::WRL::ComPtr<ID3D11Device1> pDevice,
                                     Microsoft::WRL::ComPtr<ID3D11DeviceContext1> pContext,
                                     Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pRenderTargetView,
                                     Microsoft::WRL::ComPtr<ID3D11DepthStencilView> pDepthStencilView )
{
    g_pD3DDevice = pDevice;
    g_pD3DContext = pContext;
    g_pD3DRenderTargetView = pRenderTargetView;
    g_pD3DDepthStencilView = pDepthStencilView;

    g_pD3DContext->OMSetRenderTargets( 1, g_pD3DRenderTargetView.GetAddressOf(), g_pD3DDepthStencilView.Get() );

    D3DCreateDepthStencilStates();
    D3DCreateSamplerStates();
    D3DCreateBlendStates();

    float blendfactor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
    g_pD3DContext->OMSetBlendState( g_pD3DBlendStateEnabled.Get(), blendfactor, 0xfff );

    UpdateDepthState();
}
    static inline HRESULT CreateMemoryStream( _Outptr_ IStream** stream )
    {
        Microsoft::WRL::ComPtr<ABI::Windows::Storage::Streams::IRandomAccessStream> abiStream;
        HRESULT hr = Windows::Foundation::ActivateInstance(
            Microsoft::WRL::Wrappers::HStringReference( RuntimeClass_Windows_Storage_Streams_InMemoryRandomAccessStream ).Get(),
            abiStream.GetAddressOf() );

        if (SUCCEEDED(hr))
        {
            hr = CreateStreamOverRandomAccessStream( abiStream.Get(), IID_PPV_ARGS( stream ) );
        }
        return hr;
    }
Exemple #20
0
Microsoft::WRL::ComPtr<ID3D12Resource> d3dUtil::CreateDefaultBuffer(
	ID3D12Device* device,
	ID3D12GraphicsCommandList* cmdList,
	const void* initData,
	UINT64 byteSize,
	Microsoft::WRL::ComPtr<ID3D12Resource>& uploadBuffer)
{
	ComPtr<ID3D12Resource> defaultBuffer;

	// Create the actual default buffer resource.
	ThrowIfFailed(device->CreateCommittedResource(
		&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
		D3D12_HEAP_FLAG_NONE,
		&CD3DX12_RESOURCE_DESC::Buffer(byteSize),
		D3D12_RESOURCE_STATE_COMMON,
		nullptr,
		IID_PPV_ARGS(defaultBuffer.GetAddressOf())));

	// In order to copy CPU memory data into our default buffer, we need to create
	// an intermediate upload heap. 
	ThrowIfFailed(device->CreateCommittedResource(
		&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
		D3D12_HEAP_FLAG_NONE,
		&CD3DX12_RESOURCE_DESC::Buffer(byteSize),
		D3D12_RESOURCE_STATE_GENERIC_READ,
		nullptr,
		IID_PPV_ARGS(uploadBuffer.GetAddressOf())));


	// Describe the data we want to copy into the default buffer.
	D3D12_SUBRESOURCE_DATA subResourceData ={};
	subResourceData.pData = initData;
	subResourceData.RowPitch = byteSize;
	subResourceData.SlicePitch = subResourceData.RowPitch;

	// Schedule to copy the data to the default buffer resource.  At a high level, the helper function UpdateSubresources
	// will copy the CPU memory into the intermediate upload heap.  Then, using ID3D12CommandList::CopySubresourceRegion,
	// the intermediate upload heap data will be copied to mBuffer.
	cmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(defaultBuffer.Get(),
		D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST));
	UpdateSubresources<1>(cmdList, defaultBuffer.Get(), uploadBuffer.Get(), 0, 0, 1, &subResourceData);
	cmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(defaultBuffer.Get(),
		D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_GENERIC_READ));

	// Note: uploadBuffer has to be kept alive after the above function calls because
	// the command list has not been executed yet that performs the actual copy.
	// The caller can Release the uploadBuffer after it knows the copy has been executed.


	return defaultBuffer;
}
void TextInlineFormat_Color::ApplyInlineFormat(ID2D1RenderTarget* target, IDWriteTextLayout* layout)
{
	if (!target || !layout) return;

	Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> solidBrush;
	HRESULT hr = target->CreateSolidColorBrush(ToColorF(m_Color), solidBrush.GetAddressOf());
	if (FAILED(hr)) return;

	for (const auto& range : GetRanges())
	{
		if (range.length <= 0) continue;

		layout->SetDrawingEffect(solidBrush.Get(), range);
	}
}
Exemple #22
0
ID3D12DescriptorHeap* DescriptorAllocator::RequestNewHeap(DeviceManager* deviceManager, D3D12_DESCRIPTOR_HEAP_TYPE Type)
{
	std::lock_guard<std::mutex> LockGuard(s_allocationMutex);

	D3D12_DESCRIPTOR_HEAP_DESC Desc;
	Desc.Type = Type;
	Desc.NumDescriptors = s_numDescriptorsPerHeap;
	Desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
	Desc.NodeMask = 1;

	Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> pHeap;
	assert(S_OK == deviceManager->GetDevice()->CreateDescriptorHeap(&Desc, IID_PPV_ARGS(&pHeap)));
	s_descriptorHeapPool.emplace_back(pHeap);
	return pHeap.Get();
}
Exemple #23
0
STDMETHODIMP TextAnalysis::GenerateResults(
    Microsoft::WRL::ComPtr<IDWriteTextAnalyzer1> textAnalyzer,
    _Out_ std::vector<TextAnalysis::Run>& runs,
    _Out_ std::vector<DWRITE_LINE_BREAKPOINT>& breakpoints
    )
{
    // Analyzes the text using each of the analyzers and returns
    // their results as a series of runs.

    HRESULT hr = S_OK;

    // Initially start out with one result that covers the entire range.
    // This result will be subdivided by the analysis processes.
    m_runs.resize(1);
    LinkedRun& initialRun   = m_runs[0];
    initialRun.nextRunIndex = 0;
    initialRun.textStart    = 0;
    initialRun.textLength   = m_textLength;
    initialRun.bidiLevel    = (m_readingDirection & ReadingDirectionPrimaryProgression) != 0;

    // Allocate enough room to have one breakpoint per code unit.
    m_breakpoints.resize(m_textLength);

    // Call each of the analyzers in sequence, recording their results.
    if (SUCCEEDED(hr = textAnalyzer->AnalyzeLineBreakpoints(this, 0, m_textLength, this))
        &&  SUCCEEDED(hr = AnalyzeBidi(textAnalyzer.Get(), this, 0, m_textLength, this))
        &&  SUCCEEDED(hr = textAnalyzer->AnalyzeScript(this, 0, m_textLength, this))
        &&  SUCCEEDED(hr = textAnalyzer->AnalyzeNumberSubstitution(this, 0, m_textLength, this))
        &&  SUCCEEDED(hr = AnalyzeGlyphOrientation(textAnalyzer, this, 0, m_textLength, this))
        )
    {
        // Exchange our results with the caller's.
        breakpoints.swap(m_breakpoints);

        // Resequence the resulting runs in order before returning to caller.
        size_t totalRuns = m_runs.size();
        runs.resize(totalRuns);

        UINT32 nextRunIndex = 0;
        for (size_t i = 0; i < totalRuns; ++i)
        {
            runs[i]         = m_runs[nextRunIndex];
            nextRunIndex    = m_runs[nextRunIndex].nextRunIndex;
        }
    }

    return hr;
}
Exemple #24
0
void TextureManager::LoadTextures(const std::vector<std::string>& TexturesLocation)
{
  for (std::string TextureLoc : TexturesLocation)
  {
    const std::string &fixed = "..\\examples\\assets\\" + TextureLoc.substr(0, TextureLoc.find_last_of('.')) + ".DDS";
    std::ifstream DDSFile(fixed, std::ifstream::binary);
    irr::video::CImageLoaderDDS DDSPic(DDSFile);
#ifdef GLBUILD
    WrapperResource *res = (WrapperResource*)malloc(sizeof(WrapperResource));
    // TODO : clean it
    GLTexture *tmptexture = new GLTexture(DDSPic.getLoadedImage());
    res->GLValue.Resource = tmptexture->Id;
    res->GLValue.Type = GL_TEXTURE_2D;
#endif

#ifdef DXBUILD
    D3DTexture TextureInRam(DDSPic.getLoadedImage());
    WrapperResource *res = (WrapperResource*)malloc(sizeof(WrapperResource));

    HRESULT hr = Context::getInstance()->dev->CreateCommittedResource(
      &CD3D12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
      D3D12_HEAP_MISC_NONE,
      &CD3D12_RESOURCE_DESC::Tex2D(TextureInRam.getFormat(), (UINT)TextureInRam.getWidth(), (UINT)TextureInRam.getHeight(), 1, (UINT16)TextureInRam.getMipLevelsCount()),
      D3D12_RESOURCE_USAGE_GENERIC_READ,
      nullptr,
      IID_PPV_ARGS(&res->D3DValue.resource)
      );

    Microsoft::WRL::ComPtr<ID3D12CommandAllocator> cmdalloc;
    Context::getInstance()->dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdalloc));
    Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> cmdlist;
    Context::getInstance()->dev->CreateCommandList(1, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdalloc.Get(), nullptr, IID_PPV_ARGS(&cmdlist));

    TextureInRam.CreateUploadCommandToResourceInDefaultHeap(cmdlist.Get(), res->D3DValue.resource);

    cmdlist->Close();
    Context::getInstance()->cmdqueue->ExecuteCommandLists(1, (ID3D12CommandList**)cmdlist.GetAddressOf());
    HANDLE handle = getCPUSyncHandle(Context::getInstance()->cmdqueue.Get());
    res->D3DValue.description.TextureView.SRV = TextureInRam.getResourceViewDesc();

    WaitForSingleObject(handle, INFINITE);
    CloseHandle(handle);
#endif
    textureSet.emplace(TextureLoc, res);
  }
}
// Initialize the DirectX resources required to run.
void Graphics::Initialize(void)
{
    ASSERT(s_SwapChain1 == nullptr, "Graphics has already been initialized");

    Microsoft::WRL::ComPtr<ID3D12Device> pDevice;

#if _DEBUG
    Microsoft::WRL::ComPtr<ID3D12Debug> debugInterface;
    if (SUCCEEDED(D3D12GetDebugInterface(MY_IID_PPV_ARGS(&debugInterface))))
        debugInterface->EnableDebugLayer();
    else
        Utility::Print("WARNING:  Unable to enable D3D12 debug validation layer\n");
#endif

#ifdef DXIL
    EnableExperimentalShaderModels();
#endif

    // Obtain the DXGI factory
    Microsoft::WRL::ComPtr<IDXGIFactory4> dxgiFactory;
    ASSERT_SUCCEEDED(CreateDXGIFactory2(0, MY_IID_PPV_ARGS(&dxgiFactory)));

    // Create the D3D graphics device
    Microsoft::WRL::ComPtr<IDXGIAdapter1> pAdapter;

    static const bool bUseWarpDriver = false;

    if (!bUseWarpDriver)
    {
        SIZE_T MaxSize = 0;

        for (uint32_t Idx = 0; DXGI_ERROR_NOT_FOUND != dxgiFactory->EnumAdapters1(Idx, &pAdapter); ++Idx)
        {
            DXGI_ADAPTER_DESC1 desc;
            pAdapter->GetDesc1(&desc);
            if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
                continue;

            if (desc.DedicatedVideoMemory > MaxSize && SUCCEEDED(D3D12CreateDevice(pAdapter.Get(), D3D_FEATURE_LEVEL_11_0, MY_IID_PPV_ARGS(&pDevice))))
            {
                pAdapter->GetDesc1(&desc);
                Utility::Printf(L"D3D12-capable hardware found:  %s (%u MB)\n", desc.Description, desc.DedicatedVideoMemory >> 20);
                MaxSize = desc.DedicatedVideoMemory;
            }
        }
void RasterizeShadowRenderer::initialize(
    int imageWidth,
    int imageHeight,
    Microsoft::WRL::ComPtr< ID3D11Device > device,
    Microsoft::WRL::ComPtr< ID3D11DeviceContext > deviceContext )
{
    m_device = device;
    m_deviceContext = deviceContext;

    m_imageWidth = imageWidth;
    m_imageHeight = imageHeight;

    createComputeTargets( imageWidth, imageHeight, *device.Get() );

    loadAndCompileShaders( device );

    m_initialized = true;
}
Exemple #27
0
void CanvasD2D::FillRectangle(Gdiplus::Rect& rect, const Gdiplus::SolidBrush& brush)
{
	if (!m_Target)  // Use GDI+ if D2D render target has not been created.
	{
		m_GdipGraphics->FillRectangle(&brush, rect);
		return;
	}

	Gdiplus::Color color;
	brush.GetColor(&color);

	Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> solidBrush;
	HRESULT hr = m_Target->CreateSolidColorBrush(ToColorF(color), solidBrush.GetAddressOf());
	if (SUCCEEDED(hr))
	{
		m_Target->FillRectangle(ToRectF(rect), solidBrush.Get());
	}
}
void TextInlineFormat_Typography::ApplyInlineFormat(IDWriteTextLayout* layout)
{
	if (!layout) return;

	for (const auto& range : GetRanges())
	{
		if (range.length <= 0) continue;

		Microsoft::WRL::ComPtr<IDWriteTypography> typography;
		HRESULT hr = Canvas::c_DWFactory->CreateTypography(typography.GetAddressOf());
		if (FAILED(hr)) continue;

		DWRITE_FONT_FEATURE feature = { m_Tag, m_Parameter };
		hr = typography->AddFontFeature(feature);
		if (FAILED(hr)) continue;

		layout->SetTypography(typography.Get(), range);
	}
}
Exemple #29
0
void Scene::onKeyUp(UINT8 key)
{
	if (key == 'Z') {

		DXGI_SWAP_CHAIN_DESC desc;
		this->mpSwapChain->GetDesc(&desc);

		Microsoft::WRL::ComPtr<IDXGIOutput> pOutput;
		if (desc.Windowed) {
			//全画面モードに切り替える際はどのディスプレイを対象にするか決めれる
			if (DXGI_ERROR_NOT_FOUND == this->mpAdapter->EnumOutputs(0, pOutput.GetAddressOf())) {
				throw std::runtime_error("アダプターの出力先が見つかりません。");
			}
		}

		auto hr = this->mpSwapChain->SetFullscreenState(desc.Windowed, pOutput.Get());
		if (FAILED(hr)) {
			throw std::runtime_error("フルスリーンモードとウィンドウモードの切り替えに失敗。");
		}
	}
}
void Audio::CreateReverb(IXAudio2* engine, IXAudio2MasteringVoice* masteringVoice, XAUDIO2FX_REVERB_PARAMETERS* parameters, IXAudio2SubmixVoice** newSubmix, bool enableEffect)
{
    XAUDIO2_EFFECT_DESCRIPTOR soundEffectdescriptor;
    XAUDIO2_EFFECT_CHAIN soundEffectChain;
    Microsoft::WRL::ComPtr<IUnknown> soundEffectXAPO;

    DX::ThrowIfFailed(
        XAudio2CreateReverb(&soundEffectXAPO)
        );

    soundEffectdescriptor.InitialState = false;
    soundEffectdescriptor.OutputChannels = 2;
    soundEffectdescriptor.pEffect = soundEffectXAPO.Get();
    soundEffectChain.EffectCount = 1;
    soundEffectChain.pEffectDescriptors = &soundEffectdescriptor;

    DX::ThrowIfFailed(
        engine->CreateSubmixVoice(newSubmix, 2, 48000, 0, 0, nullptr, &soundEffectChain)
        );

    DX::ThrowIfFailed(
        (*newSubmix)->SetEffectParameters(0, parameters, sizeof(m_reverbParametersSmall))
        );

    if (enableEffect)
    {
        DX::ThrowIfFailed(
            (*newSubmix)->EnableEffect(0)
            );
    }

    DX::ThrowIfFailed(
        (*newSubmix)->SetVolume (1.0f)
        );

    float outputMatrix[4] = {0, 0, 0, 0};
    DX::ThrowIfFailed(
        (*newSubmix)->SetOutputMatrix(masteringVoice, 2, 2, outputMatrix)
        );
}