private unsafe IntPtr InternalCreateTexture2D(int width, int height, int format, IntPtr data, int stride, bool isDynamic) { Texture2DDescription t2d = new Texture2DDescription { Width = (uint)width, Height = (uint)height, MipLevels = 1, ArraySize = 1, Format = (uint)format, SampleCount = 1, SampleQuality = 0, Usage = isDynamic ? 2u : 1u, //2:dynamic, 1:immutable BindFlags = 8, //ShaderResource CPUAccessFlags = isDynamic ? 0x10000u : 0, //0x10000u: write only MiscFlags = 0, }; if (data != IntPtr.Zero) { SubresourceData subres = new SubresourceData { pSysMem = data, SysMemPitch = (uint)stride, }; Device.CreateTexture2D(_device, ref t2d, new IntPtr(&subres), out var tex).Check(); return(tex); } else { Device.CreateTexture2D(_device, ref t2d, IntPtr.Zero, out var tex).Check(); return(tex); } }
public static D3DBuffer CreateBuffer <T>(D3DDevice device, T[] vertices) where T : struct { int byteLength = Marshal.SizeOf(typeof(T)) * vertices.Length; IntPtr nativeVertex = Marshal.AllocHGlobal(byteLength); byte[] byteBuffer = new byte[byteLength]; for (int i = 0; i < vertices.Length; i++) { byte[] vertexData = RawSerialize(vertices[i]); Buffer.BlockCopy(vertexData, 0, byteBuffer, vertexData.Length * i, vertexData.Length); } Marshal.Copy(byteBuffer, 0, nativeVertex, byteLength); // build vertex buffer BufferDescription bdv = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)(Marshal.SizeOf(typeof(T)) * vertices.Length), BindingOptions = BindingOptions.VertexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; SubresourceData vertexInit = new SubresourceData() { SystemMemory = nativeVertex }; return(device.CreateBuffer(bdv, vertexInit)); }
void CreateFontsTexture() { var io = ImGui.GetIO(); byte *pixels; int width, height; io.Fonts.GetTexDataAsRGBA32(out pixels, out width, out height); var texDesc = new Texture2DDescription { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = Format.R8G8B8A8_UNorm, SampleDescription = new SampleDescription { Count = 1 }, Usage = Vortice.Direct3D11.Usage.Default, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None }; var subResource = new SubresourceData { DataPointer = (IntPtr)pixels, Pitch = texDesc.Width * 4, SlicePitch = 0 }; var texture = device.CreateTexture2D(texDesc, new[] { subResource }); var resViewDesc = new ShaderResourceViewDescription { Format = Format.R8G8B8A8_UNorm, ViewDimension = ShaderResourceViewDimension.Texture2D, Texture2D = new Texture2DShaderResourceView { MipLevels = texDesc.MipLevels, MostDetailedMip = 0 } }; fontTextureView = device.CreateShaderResourceView(texture, resViewDesc); texture.Release(); io.Fonts.TexID = RegisterTexture(fontTextureView); var samplerDesc = new SamplerDescription { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLODBias = 0f, ComparisonFunction = ComparisonFunction.Always, MinLOD = 0f, MaxLOD = 0f }; fontSampler = device.CreateSamplerState(samplerDesc); }
private void InitVertexBuffer() { IntPtr verticesData = Marshal.AllocCoTaskMem(Marshal.SizeOf(cube.Vertices)); Marshal.StructureToPtr(cube.Vertices, verticesData, true); BufferDescription bufferDesc = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(cube.Vertices), BindingOptions = BindingOptions.VertexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; SubresourceData InitData = new SubresourceData() { SystemMemory = verticesData }; vertexBuffer = device.CreateBuffer(bufferDesc, InitData); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] { vertexBuffer }, new uint[] { stride }, new uint[] { offset }); Marshal.FreeCoTaskMem(verticesData); }
private void InitIndexBuffer() { Cube cube = new Cube(); IntPtr indicesData = Marshal.AllocCoTaskMem(Marshal.SizeOf(cube.Indices)); Marshal.StructureToPtr(cube.Indices, indicesData, true); BufferDescription bufferDesc = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(cube.Indices), BindingOptions = BindingOptions.IndexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; SubresourceData initData = new SubresourceData() { SystemMemory = indicesData }; indexBuffer = device.CreateBuffer(bufferDesc, initData); device.IA.IndexBuffer = new IndexBuffer(indexBuffer, Format.R32UInt, 0); Marshal.FreeCoTaskMem(indicesData); }
public MainPage() { this.InitializeComponent(); m_ctx = new ResourceCreateContext(); m_swapChain = new CompositionSwapChainResources(m_ctx, m_swapChainPanel); var display = DisplayInformation.GetForCurrentView(); display.DpiChanged += new TypedEventHandler <DisplayInformation, object>(OnDpiChanged); m_triangle = makeTriangle(m_ctx); m_compute = makeCompute(m_ctx); m_buffer = m_ctx.CreateByteAddressBuffer(4096, ResourceState.CopyDestination); m_texture = m_ctx.CreateTexture2D(256, 256, 1, GraphicsFormat.R8_UNORM, ResourceState.CopyDestination); var ctx = m_swapChain.CreateGraphicsComputeCommandContext(); { float[] positions = { 0.0f, 0.5f, 0.5f, 1.0f, -0.5f, 0.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.5f, 1.0f }; byte[] b0 = new byte[positions.Length * 4]; Buffer.BlockCopy(positions, 0, b0, 0, b0.Length); float[] colors = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; byte[] b1 = new byte[colors.Length * 4]; Buffer.BlockCopy(colors, 0, b1, 0, b1.Length); ctx.UpdateBuffer(m_buffer, 0, b0); ctx.UpdateBuffer(m_buffer, (uint)b0.Length, b1); } { var subResourceData = new SubresourceData(); subResourceData.Data = GenerateTextureData(); subResourceData.RowPitch = 256; subResourceData.SlicePitch = 256 * 256; SubresourceData[] datas = { subResourceData }; ctx.UploadResource(m_texture, 0, 1, datas); } ctx.TransitionResource(m_texture, ResourceState.CopyDestination, ResourceState.PixelShaderResource | ResourceState.NonPixelShaderResource); ctx.TransitionResource(m_buffer, ResourceState.CopyDestination, ResourceState.NonPixelShaderResource); ctx.SubmitAndWaitToExecute(); }
private void InitializeGeometryBuffers() { PassDescription PassDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayouts, PassDesc.InputAssemblerInputSignature, PassDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.InputLayout = vertexLayout; BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(vertexArray.s_VertexArray); bd.BindingOptions = BindingOptions.VertexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(vertexArray.s_VertexArray)); Marshal.StructureToPtr(vertexArray.s_VertexArray, ptr, true); SubresourceData initData = new SubresourceData { SystemMemory = ptr }; vertexBuffer = device.CreateBuffer(bd, initData); Marshal.FreeHGlobal(ptr); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, // StartSlot new[] { vertexBuffer }, new[] { stride }, new[] { offset }); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(vertexArray.s_FacesIndexArray); bd.BindingOptions = BindingOptions.IndexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; ptr = Marshal.AllocHGlobal(Marshal.SizeOf(vertexArray.s_FacesIndexArray)); Marshal.StructureToPtr(vertexArray.s_FacesIndexArray, ptr, true); initData.SystemMemory = ptr; facesIndexBuffer = device.CreateBuffer(bd, initData); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; }
unsafe static void MemcpySubresource( ulong RowPitch, ulong SlicePitch, Span <byte> dest, SubresourceData pSrc, int RowSizeInBytes, int NumRows, int NumSlices) { for (uint z = 0; z < NumSlices; ++z) { byte * pSrcSlice = (byte *)(pSrc.Data) + (long)SlicePitch * z; Span <byte> pDestSlice = dest.Slice((int)(SlicePitch * z)); for (int y = 0; y < NumRows; ++y) { new Span <byte>(pSrcSlice + ((long)pSrc.RowPitch * y), RowSizeInBytes).CopyTo(pDestSlice.Slice((int)RowPitch * y, RowSizeInBytes)); } } }
/// <summary> /// Init device and required resources /// </summary> private void InitDevice() { // device creation device = D3DDevice.CreateDeviceAndSwapChain(host.Handle); swapChain = device.SwapChain; deviceContext = device.ImmediateContext; SetViews(); // vertex shader & layout // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T vs_4_0 /EVertShader /FoRender.vs using (Stream stream = Application.ResourceAssembly.GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.vs")) { vertexShader = device.CreateVertexShader(stream); deviceContext.VS.Shader = vertexShader; // input layout is for the vert shader InputElementDescription inputElementDescription = new InputElementDescription(); inputElementDescription.SemanticName = "POSITION"; inputElementDescription.SemanticIndex = 0; inputElementDescription.Format = Format.R32G32B32Float; inputElementDescription.InputSlot = 0; inputElementDescription.AlignedByteOffset = 0; inputElementDescription.InputSlotClass = InputClassification.PerVertexData; inputElementDescription.InstanceDataStepRate = 0; stream.Position = 0; InputLayout inputLayout = device.CreateInputLayout( new InputElementDescription[] { inputElementDescription }, stream); deviceContext.IA.InputLayout = inputLayout; } // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T ps_4_0 /EPixShader /FoRender.ps using (Stream stream = Application.ResourceAssembly.GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.ps")) { pixelShader = device.CreatePixelShader(stream); } deviceContext.PS.SetShader(pixelShader, null); // create some geometry to draw (1 triangle) SimpleVertexArray vertex = new SimpleVertexArray(); // put the vertices into a vertex buffer BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Usage = Usage.Default; bufferDescription.ByteWidth = (uint)Marshal.SizeOf(vertex); bufferDescription.BindingOptions = BindingOptions.VertexBuffer; SubresourceData subresourceData = new SubresourceData(); IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); subresourceData.SystemMemory = vertexData; vertexBuffer = device.CreateBuffer(bufferDescription, subresourceData); deviceContext.IA.SetVertexBuffers(0, new D3DBuffer[] { vertexBuffer }, new uint[] { 12 }, new uint[] { 0 }); deviceContext.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; Marshal.FreeCoTaskMem(vertexData); }
void CreateDeviceResources() { uint width = (uint) host.ActualWidth; uint height = (uint) host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); DXGIFactory dxgiFactory = DXGIFactory.CreateFactory(); SwapChainDescription swapDesc = new SwapChainDescription(); swapDesc.BufferDescription.Width = width; swapDesc.BufferDescription.Height = height; swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM; swapDesc.BufferDescription.RefreshRate.Numerator = 60; swapDesc.BufferDescription.RefreshRate.Denominator = 1; swapDesc.SampleDescription.Count = 1; swapDesc.SampleDescription.Quality = 0; swapDesc.BufferUsage = UsageOption.RenderTargetOutput; swapDesc.BufferCount = 1; swapDesc.OutputWindowHandle = host.Handle; swapDesc.Windowed = true; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntialiasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.SetState( rasterizerState ); // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.SetRenderTargets(new RenderTargetView[] {null}); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8_UNORM; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; renderDesc.Texture2D.MipSlice = 0; using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsage.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription; tex2DDescription.ArraySize = 1; tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource; tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified; tex2DDescription.Format = Format.R8G8B8A8_UNORM; tex2DDescription.Height = 4096; tex2DDescription.Width = 512; tex2DDescription.MipLevels = 1; tex2DDescription.MiscFlags = 0; tex2DDescription.SampleDescription.Count = 1; tex2DDescription.SampleDescription.Quality = 0; tex2DDescription.Usage = Usage.Default; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GetDXGISurface()) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix(); viewMatrixVariable = shader.GetVariableByName("View").AsMatrix(); projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix(); diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource(); // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.SetInputLayout( vertexLayout ); IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindFlags = BindFlag.VertexBuffer; bd.CpuAccessFlags = CpuAccessFlag.Unspecified; bd.MiscFlags = ResourceMiscFlag.Undefined; SubresourceData InitData = new SubresourceData() { SysMem = verticesDataPtr }; vertexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] {vertexBuffer}, new uint[] {stride}, new uint[] {offset} ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindFlags = BindFlag.IndexBuffer; bd.CpuAccessFlags = 0; bd.MiscFlags = 0; InitData.SysMem = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float) Math.PI*0.1f, width/(float) height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(Colors.Yellow)), new GradientStop(1.0f, new ColorF(Colors.Black)) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.Gamma_22, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
private void InitIndexBuffer() { IntPtr indicesData = Marshal.AllocCoTaskMem(Marshal.SizeOf(cube.Indices)); Marshal.StructureToPtr(cube.Indices, indicesData, true); BufferDescription bufferDesc = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(cube.Indices), BindingOptions = BindingOptions.IndexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; SubresourceData initData = new SubresourceData() { SystemMemory = indicesData }; indexBuffer = device.CreateBuffer(bufferDesc, initData); device.IA.IndexBuffer = new IndexBuffer(indexBuffer, Format.R32UInt, 0); Marshal.FreeCoTaskMem(indicesData); }
void CreateDeviceResources() { uint width = (uint)host.ActualWidth; uint height = (uint)host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); Factory dxgiFactory = Factory.Create(); SwapChainDescription swapDesc = new SwapChainDescription { BufferDescription = new ModeDescription { Width = width, Height = height, Format = Format.R8G8B8A8UNorm, RefreshRate = new Rational { Numerator = 60, Denominator = 1 } }, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, BufferUsage = UsageOptions.RenderTargetOutput, BufferCount = 1, OutputWindowHandle = host.Handle, Windowed = true }; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntiAliasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.State = rasterizerState; // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null }); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8UNorm; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; Texture2DRenderTargetView renderView = renderDesc.Texture2D; renderView.MipSlice = 0; renderDesc.Texture2D = renderView; using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsages.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription = new Texture2DDescription { ArraySize = 1, BindingOptions = BindingOptions.RenderTarget | BindingOptions.ShaderResource, CpuAccessOptions = CpuAccessOptions.None, Format = Format.R8G8B8A8UNorm, Height = 4096, Width = 512, MipLevels = 1, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, Usage = Usage.Default }; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GraphicsSurface) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix; viewMatrixVariable = shader.GetVariableByName("View").AsMatrix; projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix; diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource; // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.InputLayout = vertexLayout; IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindingOptions = BindingOptions.VertexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; SubresourceData InitData = new SubresourceData { SystemMemory = verticesDataPtr }; vertexBuffer = device.CreateBuffer(bd, InitData); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] { vertexBuffer }, new uint[] { stride }, new uint[] { offset } ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindingOptions = BindingOptions.IndexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; InitData.SystemMemory = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float)Math.PI * 0.1f, width / (float)height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))), new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black))) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.StandardRgb, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle, out swapChain); SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial02.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the technique technique = effect.GetTechniqueByName("Render"); // Define the input layout InputElementDescription[] layout = { new InputElementDescription() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_FLOAT, InputSlot = 0, AlignedByteOffset = 0, InputSlotClass = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; PassDescription passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( layout, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize); device.IA.SetInputLayout(vertexLayout); SimpleVertexArray vertex = new SimpleVertexArray(); BufferDescription bd = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(vertex), BindFlags = BindFlag.VertexBuffer, CpuAccessFlags = 0, MiscFlags = 0 }; IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); SubresourceData InitData = new SubresourceData() { SysMem = vertexData, SysMemPitch = 0, SysMemSlicePitch = 0 }; //D3DBuffer buffer = null; vertexBuffer = device.CreateBuffer(bd, InitData); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(Vector3F)); uint offset = 0; device.IA.SetVertexBuffers(0, new Collection<D3DBuffer>() { vertexBuffer }, new uint[] { stride }, new uint[] { offset }); // Set primitive topology device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); Marshal.FreeCoTaskMem(vertexData); }
protected override void OnShown(EventArgs e) { base.OnShown(e); // device creation device = D3DDevice.CreateDeviceAndSwapChain(Handle); swapChain = device.SwapChain; deviceContext = device.ImmediateContext; SetViews(); // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T vs_4_0 /EVertShader /FoRender.vs using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.vs")) { vertexShader = device.CreateVertexShader(stream); } deviceContext.VS.SetShader(vertexShader, null); // input layout is for the vert shader InputElementDescription inputElementDescription = new InputElementDescription(); inputElementDescription.SemanticName = "POSITION"; inputElementDescription.SemanticIndex = 0; inputElementDescription.Format = Format.R32G32B32Float; inputElementDescription.InputSlot = 0; inputElementDescription.AlignedByteOffset = 0; inputElementDescription.InputSlotClass = InputClassification.PerVertexData; inputElementDescription.InstanceDataStepRate = 0; InputLayout inputLayout; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.vs")) { inputLayout = device.CreateInputLayout(new InputElementDescription[] { inputElementDescription }, stream); } deviceContext.IA.InputLayout = inputLayout; // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T ps_4_0 /EPixShader /FoRender.ps using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.ps")) { pixelShader = device.CreatePixelShader(stream); } deviceContext.PS.SetShader(pixelShader, null); // create some geometry to draw (1 triangle) SimpleVertexArray vertex = new SimpleVertexArray(); // put the vertices into a vertex buffer BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Usage = Usage.Default; bufferDescription.ByteWidth = (uint)Marshal.SizeOf(vertex); bufferDescription.BindingOptions = BindingOptions.VertexBuffer; SubresourceData subresourceData = new SubresourceData(); IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); subresourceData.SystemMemory = vertexData; vertexBuffer = device.CreateBuffer(bufferDescription, subresourceData); deviceContext.IA.SetVertexBuffers(0, new D3DBuffer[] { vertexBuffer }, new uint[] { 12 }, new uint[] { 0 }); deviceContext.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; Marshal.FreeCoTaskMem(vertexData); }
/// <summary> /// Loads a mesh and creates the vertex/index buffers for the part /// </summary> /// <param name="part"></param> /// <param name="meshData"></param> void LoadMesh( ref Part part, string meshData ) { // load vertex data int dataOffset = 0; Match vertexCount = findArrayCount.Match( meshData ); if( !vertexCount.Success ) throw new System.IO.InvalidDataException( "problem reading vertex count" ); List<Vector4F> vertexList = new List<Vector4F>(); int verticies = int.Parse(vertexCount.Groups[1].Value, CultureInfo.InvariantCulture); dataOffset = vertexCount.Index + vertexCount.Length; for( int vertexIndex = 0; vertexIndex < verticies; vertexIndex++ ) { Match vertex = findVector3F.Match( meshData, dataOffset ); if( !vertex.Success ) throw new System.IO.InvalidDataException( "problem reading vertex" ); else dataOffset = vertex.Index + vertex.Length; vertexList.Add( new Vector4F( float.Parse(vertex.Groups[1].Value, CultureInfo.InvariantCulture), float.Parse(vertex.Groups[2].Value, CultureInfo.InvariantCulture), float.Parse(vertex.Groups[3].Value, CultureInfo.InvariantCulture), 1.0f) ); } // load triangle index data Match triangleIndexCount = findArrayCount.Match( meshData, dataOffset ); dataOffset = triangleIndexCount.Index + triangleIndexCount.Length; if( !triangleIndexCount.Success ) throw new System.IO.InvalidDataException( "problem reading index count" ); List<Int32> triangleIndiciesList = new List<Int32>( ); int triangleIndexListCount = int.Parse(triangleIndexCount.Groups[1].Value, CultureInfo.InvariantCulture); dataOffset = triangleIndexCount.Index + triangleIndexCount.Length; for( int triangleIndicyIndex = 0; triangleIndicyIndex < triangleIndexListCount; triangleIndicyIndex++ ) { Match indexEntry = findVertexIndex.Match( meshData, dataOffset ); if( !indexEntry.Success ) throw new System.IO.InvalidDataException( "problem reading vertex index entry" ); else dataOffset = indexEntry.Index + indexEntry.Length; int indexEntryCount = int.Parse(indexEntry.Groups[1].Value, CultureInfo.InvariantCulture); string[ ] vertexIndexes = indexEntry.Groups[ 2 ].Value.Split( new char[ ] { ',' } ); if( indexEntryCount != vertexIndexes.Length ) throw new System.IO.InvalidDataException( "vertex index count does not equal count of indicies found" ); for( int entryIndex = 0; entryIndex <= indexEntryCount - 3; entryIndex++ ) { triangleIndiciesList.Add(int.Parse(vertexIndexes[0], CultureInfo.InvariantCulture)); triangleIndiciesList.Add(int.Parse(vertexIndexes[1 + entryIndex].ToString(), CultureInfo.InvariantCulture)); triangleIndiciesList.Add(int.Parse(vertexIndexes[2 + entryIndex].ToString(), CultureInfo.InvariantCulture)); } } // load mesh colors string vertexColorData = GetTagContent( new Regex( @"MeshVertexColors[\s]+{" ), meshData ); Dictionary<int,Vector4F> colorDictionary = null; if( vertexColorData != "" ) colorDictionary = LoadMeshColors( vertexColorData ); // load mesh normals string meshNormalData = GetTagContent( new Regex( @"MeshNormals[\s]+{" ), meshData ); IndexedMeshNormals meshNormals = null; if( meshNormalData != "" ) { meshNormals = LoadMeshNormals( meshNormalData ); } // load mesh texture coordinates string meshTextureCoordsData = GetTagContent( new Regex( @"MeshTextureCoords[\s]+{" ), meshData ); List<Vector2F> meshTextureCoords = null; if( meshTextureCoordsData != "" ) { meshTextureCoords = LoadMeshTextureCoordinates( meshTextureCoordsData ); } // load mesh material string meshMaterialsData = GetTagContent( new Regex( @"MeshMaterialList[\s]+{" ), meshData ); List<MaterialSpecification> meshMaterials = null; if( meshMaterialsData != "" ) { meshMaterials = LoadMeshMaterialList( meshMaterialsData ); } // copy vertex data to HGLOBAL int byteLength = Marshal.SizeOf( typeof( XMeshVertex ) ) * triangleIndiciesList.Count; IntPtr nativeVertex = Marshal.AllocHGlobal( byteLength ); byte[ ] byteBuffer = new byte[ byteLength ]; XMeshVertex[ ] varray = new XMeshVertex[ triangleIndiciesList.Count ]; for( int n = 0; n < triangleIndiciesList.Count; n++ ) { XMeshVertex vertex = new XMeshVertex( ) { Vertex = vertexList[ triangleIndiciesList[ n ] ], Normal = (meshNormals == null) ? new Vector4F( 0, 0, 0, 1.0f ) : meshNormals.normalVectors[ meshNormals.normalIndexMap[ n ] ], Color = ((colorDictionary == null) ? new Vector4F( 0, 0, 0, 0 ) : colorDictionary[ triangleIndiciesList[ n ] ]), Texture = ((meshTextureCoords == null) ? new Vector2F( 0, 0 ) : meshTextureCoords[ triangleIndiciesList[ n ] ]) }; byte[ ] vertexData = RawSerialize( vertex ); Buffer.BlockCopy( vertexData, 0, byteBuffer, vertexData.Length * n, vertexData.Length ); } Marshal.Copy( byteBuffer, 0, nativeVertex, byteLength ); // build vertex buffer BufferDescription bdv = new BufferDescription( ) { Usage = Usage.Default, ByteWidth = (uint)(Marshal.SizeOf( typeof( XMeshVertex ) ) * triangleIndiciesList.Count), BindFlags = BindFlag.VertexBuffer, CpuAccessFlags = 0, MiscFlags = 0 }; SubresourceData vertexInit = new SubresourceData( ) { SysMem = nativeVertex }; part.vertexBuffer = device.CreateBuffer( bdv, vertexInit ); Debug.Assert( part.vertexBuffer != null ); part.vertexCount = triangleIndiciesList.Count; if( meshMaterials != null ) { // only a single material is currently supported MaterialSpecification m = meshMaterials[ 0 ]; part.material = new Material() { emissiveColor = m.emissiveColor, specularColor = m.specularColor, materialColor = m.materialColor, specularPower = m.specularPower }; string texturePath = ""; if( File.Exists( m.textureFileName ) ) texturePath = m.textureFileName; if( File.Exists( meshDirectory + "\\" + m.textureFileName ) ) texturePath = meshDirectory + "\\" + m.textureFileName; if( File.Exists( meshDirectory + "\\..\\" + m.textureFileName ) ) texturePath = meshDirectory + "\\..\\" + m.textureFileName; if( texturePath.Length == 0 ) { part.material.textureResource = null; } else { part.material.textureResource = D3D10XHelpers.CreateShaderResourceViewFromFile( device, texturePath ); } } Marshal.FreeHGlobal( nativeVertex ); }
/// <summary> /// Loads a mesh and creates the vertex/index buffers for the part /// </summary> /// <param name="part"></param> /// <param name="meshData"></param> void LoadMesh(ref Part part, IXDataObject dataObject) { // load vertex data int dataOffset = 0; Match vertexCount = findArrayCount.Match(dataObject.Body); if(!vertexCount.Success) throw new System.IO.InvalidDataException("problem reading vertex count"); List<Vector4F> vertexList = new List<Vector4F>(); int verticies = int.Parse(vertexCount.Groups[1].Value, CultureInfo.InvariantCulture); dataOffset = vertexCount.Index + vertexCount.Length; for(int vertexIndex = 0; vertexIndex < verticies; vertexIndex++) { Match vertex = findVector3F.Match(dataObject.Body, dataOffset); if(!vertex.Success) throw new System.IO.InvalidDataException("problem reading vertex"); else dataOffset = vertex.Index + vertex.Length; vertexList.Add( new Vector4F( float.Parse(vertex.Groups[1].Value, CultureInfo.InvariantCulture), float.Parse(vertex.Groups[2].Value, CultureInfo.InvariantCulture), float.Parse(vertex.Groups[3].Value, CultureInfo.InvariantCulture), 1.0f)); } // load triangle index data Match triangleIndexCount = findArrayCount.Match(dataObject.Body, dataOffset); dataOffset = triangleIndexCount.Index + triangleIndexCount.Length; if(!triangleIndexCount.Success) throw new System.IO.InvalidDataException("problem reading index count"); List<Int32> triangleIndiciesList = new List<Int32>(); int triangleIndexListCount = int.Parse(triangleIndexCount.Groups[1].Value, CultureInfo.InvariantCulture); dataOffset = triangleIndexCount.Index + triangleIndexCount.Length; for(int triangleIndicyIndex = 0; triangleIndicyIndex < triangleIndexListCount; triangleIndicyIndex++) { Match indexEntry = findVertexIndex.Match(dataObject.Body, dataOffset); if(!indexEntry.Success) throw new System.IO.InvalidDataException("problem reading vertex index entry"); else dataOffset = indexEntry.Index + indexEntry.Length; int indexEntryCount = int.Parse(indexEntry.Groups[1].Value, CultureInfo.InvariantCulture); string[] vertexIndexes = indexEntry.Groups[2].Value.Split(new char[] { ',' }); if(indexEntryCount != vertexIndexes.Length) throw new System.IO.InvalidDataException("vertex index count does not equal count of indicies found"); for(int entryIndex = 0; entryIndex <= indexEntryCount - 3; entryIndex++) { triangleIndiciesList.Add(int.Parse(vertexIndexes[0], CultureInfo.InvariantCulture)); triangleIndiciesList.Add(int.Parse(vertexIndexes[1 + entryIndex].ToString(), CultureInfo.InvariantCulture)); triangleIndiciesList.Add(int.Parse(vertexIndexes[2 + entryIndex].ToString(), CultureInfo.InvariantCulture)); } } // load mesh colors IXDataObject vertexColorData = GetSingleChild(dataObject, "MeshVertexColors"); Dictionary<int, Vector4F> colorDictionary = null; if (vertexColorData != null) colorDictionary = LoadMeshColors(vertexColorData); // load mesh normals IXDataObject meshNormalData = GetSingleChild(dataObject, "MeshNormals"); IndexedMeshNormals meshNormals = null; if(meshNormalData != null) { meshNormals = LoadMeshNormals(meshNormalData); } // load mesh texture coordinates IXDataObject meshTextureCoordsData = GetSingleChild(dataObject, "MeshTextureCoords"); List<Vector2F> meshTextureCoords = null; if(meshTextureCoordsData != null) { meshTextureCoords = LoadMeshTextureCoordinates(meshTextureCoordsData); } // load mesh material IXDataObject meshMaterialsData = GetSingleChild(dataObject, "MeshMaterialList"); List<MaterialSpecification> meshMaterials = null; if(meshMaterialsData != null) { meshMaterials = LoadMeshMaterialList(meshMaterialsData); } // copy vertex data to HGLOBAL int byteLength = Marshal.SizeOf(typeof(XMeshVertex)) * triangleIndiciesList.Count; IntPtr nativeVertex = Marshal.AllocHGlobal(byteLength); byte[] byteBuffer = new byte[byteLength]; XMeshVertex[] varray = new XMeshVertex[triangleIndiciesList.Count]; for(int n = 0; n < triangleIndiciesList.Count; n++) { XMeshVertex vertex = new XMeshVertex() { Vertex = vertexList[triangleIndiciesList[n]], Normal = (meshNormals == null) ? new Vector4F(0, 0, 0, 1.0f) : meshNormals.normalVectors[meshNormals.normalIndexMap[n]], Color = ((colorDictionary == null) ? new Vector4F(0, 0, 0, 0) : colorDictionary[triangleIndiciesList[n]]), Texture = ((meshTextureCoords == null) ? new Vector2F(0, 0) : meshTextureCoords[triangleIndiciesList[n]]) }; byte[] vertexData = RawSerialize(vertex); Buffer.BlockCopy(vertexData, 0, byteBuffer, vertexData.Length * n, vertexData.Length); } Marshal.Copy(byteBuffer, 0, nativeVertex, byteLength); // build vertex buffer BufferDescription bdv = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)(Marshal.SizeOf(typeof(XMeshVertex)) * triangleIndiciesList.Count), BindingOptions = BindingOptions.VertexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; SubresourceData vertexInit = new SubresourceData() { SystemMemory = nativeVertex }; part.vertexBuffer = device.CreateBuffer(bdv, vertexInit); Debug.Assert(part.vertexBuffer != null); part.vertexCount = triangleIndiciesList.Count; if(meshMaterials != null) { // only a single material is currently supported MaterialSpecification m = meshMaterials[0]; part.material = new Material() { emissiveColor = m.emissiveColor, specularColor = m.specularColor, materialColor = m.materialColor, specularPower = m.specularPower }; string texturePath = ""; if(File.Exists(m.textureFileName)) texturePath = m.textureFileName; if(File.Exists(meshDirectory + "\\" + m.textureFileName)) texturePath = meshDirectory + "\\" + m.textureFileName; if(File.Exists(meshDirectory + "\\..\\" + m.textureFileName)) texturePath = meshDirectory + "\\..\\" + m.textureFileName; if(texturePath.Length == 0) { part.material.textureResource = null; } else { part.material.textureResource = D3D10XHelpers.CreateShaderResourceViewFromFile( device, texturePath); } } Marshal.FreeHGlobal(nativeVertex); }
private void InitializeVertexBuffer() { IntPtr verticesData = Marshal.AllocCoTaskMem(Marshal.SizeOf(cube.Vertices)); Marshal.StructureToPtr(cube.Vertices, verticesData, true); BufferDescription bufferDesc = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(cube.Vertices), BindFlags = BindFlag.VertexBuffer, CpuAccessFlags = 0, MiscFlags = 0 }; SubresourceData InitData = new SubresourceData() { SysMem = verticesData }; //D3DBuffer buffer = null; vertexBuffer = device.CreateBuffer(bufferDesc, InitData); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] { vertexBuffer }, new uint[] { stride }, new uint[] { offset }); Marshal.FreeCoTaskMem(verticesData); }
private void InitDevice() { // device creation //device = D3DDevice.CreateDeviceAndSwapChain( // null, // DriverType.Hardware, // null, // CreateDeviceFlag.Default, // new []{FeatureLevel.FeatureLevel_10_1}, // new SwapChainDescription { // BufferCount = 1 // }, // out swapChain); device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle, out swapChain); deviceContext = device.GetImmediateContext(); SetViews(); // Open precompiled vertex shader // This file was compiled using: fxc Render.hlsl /T vs_4_0 /EVertShader /FoRender.vs using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.vs")) { vertexShader = device.CreateVertexShader(stream); } deviceContext.VS.SetShader(vertexShader, null); // input layout is for the vert shader InputElementDescription inputElementDescription = new InputElementDescription(); inputElementDescription.SemanticName = "POSITION"; inputElementDescription.SemanticIndex = 0; inputElementDescription.Format = Format.R32G32B32_FLOAT; inputElementDescription.InputSlot = 0; inputElementDescription.AlignedByteOffset = 0; inputElementDescription.InputSlotClass = InputClassification.PerVertexData; inputElementDescription.InstanceDataStepRate = 0; InputLayout inputLayout; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.vs")) { inputLayout = device.CreateInputLayout(new [] { inputElementDescription }, stream); } deviceContext.IA.SetInputLayout(inputLayout); // Open precompiled pixel shader // This file was compiled using: fxc Render.hlsl /T ps_4_0 /EPixShader /FoRender.ps using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.WindowsAPICodePack.Samples.Direct3D11.Render.ps")) { pixelShader = device.CreatePixelShader(stream); } deviceContext.PS.SetShader(pixelShader, null); // create some geometry to draw (1 triangle) SimpleVertexArray vertex = new SimpleVertexArray(); // put the vertices into a vertex buffer BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Usage = Usage.Default; bufferDescription.ByteWidth = (uint)Marshal.SizeOf(vertex); bufferDescription.BindFlags = BindFlag.VertexBuffer; SubresourceData subresourceData = new SubresourceData(); IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); subresourceData.SysMem = vertexData; vertexBuffer = device.CreateBuffer(bufferDescription, subresourceData); deviceContext.IA.SetVertexBuffers(0, new [] { vertexBuffer }, new uint[] { 12 }, new uint[] { 0 }); deviceContext.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); Marshal.FreeCoTaskMem(vertexData); }
public static FormatTexture CreateTgaTexture( ReadOnlyMemory <byte> tgaData, LoaderFlags loaderFlags = LoaderFlags.None ) { if (tgaData.Length < sizeof(TGAHeader)) { ThrowHelper.ThrowInvalidDataException("Too small"); } ReadOnlySpan <byte> span = tgaData.Span; TGAHeader header = MemoryMarshal.Read <TGAHeader>(span); if (IsCompressed(header.DataTypeCode)) { ThrowHelper.ThrowNotSupportedException("Compressed TGA textures are TODO"); // TODO } int size = header.Height * header.Width * (header.BitsPerPixel / 8); var data = new byte[size]; var buff = data; DXGI_FORMAT format = loaderFlags.HasFlag(LoaderFlags.ForceSrgb) ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM; switch (header.BitsPerPixel) { case 24: RbgToRgba(span.Slice(sizeof(TGAHeader)), buff); break; case 32: ArbgToRgba(span.Slice(sizeof(TGAHeader)), buff); break; case 16: Rgba16ToRgba(span.Slice(sizeof(TGAHeader)), buff); break; default: ThrowHelper.ThrowNotSupportedException("Unsupported format"); break; } var subresources = new SubresourceData[1]; subresources[0] = new SubresourceData(); var desc = new TextureDesc { Width = (uint)header.Width, Height = (uint)header.Height, DepthOrArraySize = 0, // is this right? Format = (DataFormat)format, Dimension = TextureDimension.Tex2D }; return(new FormatTexture( data, desc, 1, loaderFlags, false, subresources, header.BitsPerPixel == 24 ? AlphaMode.Opaque : AlphaMode.Unknown, TexType.Tga )); }
private void InitializeIndexBuffer() { IntPtr indicesData = Marshal.AllocCoTaskMem(Marshal.SizeOf(cube.Indices)); Marshal.StructureToPtr(cube.Indices, indicesData, true); BufferDescription bufferDesc = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(cube.Indices), BindFlags = BindFlag.IndexBuffer, CpuAccessFlags = 0, MiscFlags = 0 }; SubresourceData initData = new SubresourceData() { SysMem = indicesData }; indexBuffer = device.CreateBuffer(bufferDesc, initData); device.IA.SetIndexBuffer(indexBuffer, Format.R32_UINT, 0); Marshal.FreeCoTaskMem(indicesData); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle); swapChain = device.SwapChain; SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial02.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the technique technique = effect.GetTechniqueByName("Render"); // Define the input layout InputElementDescription[] layout = { new InputElementDescription() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32Float, InputSlot = 0, AlignedByteOffset = 0, InputSlotClass = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; PassDescription passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( layout, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize); device.IA.InputLayout = vertexLayout; SimpleVertexArray vertex = new SimpleVertexArray(); BufferDescription bd = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(vertex), BindingOptions = BindingOptions.VertexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); SubresourceData InitData = new SubresourceData() { SystemMemory = vertexData, SystemMemoryPitch = 0, SystemMemorySlicePitch = 0 }; //D3DBuffer buffer = null; vertexBuffer = device.CreateBuffer(bd, InitData); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(Vector3F)); uint offset = 0; device.IA.SetVertexBuffers(0, new Collection <D3DBuffer>() { vertexBuffer }, new uint[] { stride }, new uint[] { offset }); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; Marshal.FreeCoTaskMem(vertexData); }