internal void Init(string name, ref BufferDescription description, IntPtr? initData) { m_description = description; m_elementCount = description.SizeInBytes / Math.Max(1, Description.StructureByteStride); try { m_buffer = new Buffer(MyRender11.Device, initData ?? default(IntPtr), description) { DebugName = name, }; } catch (SharpDXException e) { MyRenderProxy.Log.WriteLine("Error during allocation of a directX buffer!"); LogStuff(e); throw; } try { AfterBufferInit(); } catch (SharpDXException e) { MyRenderProxy.Log.WriteLine("Error during creating a view or an unordered access to a directX buffer!"); LogStuff(e); throw; } IsReleased = false; }
public MeshFactory(SharpDX11Graphics graphics) { this.device = graphics.Device; this.inputAssembler = device.ImmediateContext.InputAssembler; this.demo = graphics.Demo; instanceDataDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }; InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("WORLD", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 64, 1, InputClassification.PerInstanceData, 1) }; inputLayout = new InputLayout(device, graphics.GetEffectPass().Description.Signature, elements); groundColor = ColorToUint(Color.Green); activeColor = ColorToUint(Color.Orange); passiveColor = ColorToUint(Color.OrangeRed); softBodyColor = ColorToUint(Color.LightBlue); }
public Buffer(BufferDescription description) { _description = description; _flags = GetBufferFlagsFromDescription(description); _nativeBuffer = new SharpDX.Direct3D11.Buffer(GraphicManager.Device, description); }
public void Init() { { BuildVertices(); var desc = new BufferDescription(); desc.BindFlags = BindFlags.VertexBuffer; desc.Usage = ResourceUsage.Default; desc.CpuAccessFlags = CpuAccessFlags.None; desc.OptionFlags = ResourceOptionFlags.None; desc.SizeInBytes = Utilities.SizeOf<LineVertex>() * vertices.Length; desc.StructureByteStride = 0; vertexBuffer = Buffer.Create(Device, vertices, desc);//new Buffer(Device, desc); } { var passDesc = new MaterialPassDesc(); passDesc.ManualConstantBuffers = true; passDesc.ShaderFile = InternalResources.SHADER_DEBUG_LINE; passDesc.InputElements = new InputElement[]{ new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 12, 0), }; passDesc.RasteriazerStates.CullMode = CullMode.None; passDesc.DepthStencilStates.DepthWriteMask = DepthWriteMask.Zero; pass = new MaterialPass(Game.Instance.Device, passDesc, "Grid"); matrixBuffer = Material.CreateBuffer<Matrix>(); } }
private void BuildWavesGeometryBuffers() { var vbd = new D3D11.BufferDescription(VertexPN.Stride * _awave.VertexCount, D3D11.ResourceUsage.Dynamic, D3D11.BindFlags.VertexBuffer, D3D11.CpuAccessFlags.Write, D3D11.ResourceOptionFlags.None, 0); _wavesVB = new D3D11.Buffer(Device, vbd); var indices = new List <int>(); var m = _awave.RowCount; var n = _awave.ColumnCount; for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n - 1; j++) { indices.Add(i * n + j); indices.Add(i * n + j + 1); indices.Add((i + 1) * n + j); indices.Add((i + 1) * n + j); indices.Add(i * n + j + 1); indices.Add((i + 1) * n + j + 1); } } var ibd = new D3D11.BufferDescription(sizeof(int) * indices.Count, D3D11.ResourceUsage.Immutable, D3D11.BindFlags.IndexBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); _wavesIB = new D3D11.Buffer(Device, DataStream.Create <int>(indices.ToArray(), false, false), ibd); }
public FilterPixelShader(Device device, int imageWidth, int imageHeight, int constantBufferSize, string pixelShaderBytecodeFilename) { vertexShader = new VertexShader(device, new ShaderBytecode(File.ReadAllBytes("Content/FullScreenQuadVS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes(pixelShaderBytecodeFilename))); var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = false, IsFrontCounterClockwise = true, IsMultisampleEnabled = false, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); if (constantBufferSize > 0) { var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = constantBufferSize, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new Buffer(device, constantBufferDesc); } viewport = new Viewport(0, 0, imageWidth, imageHeight); // TODO: get these dimensions vertexBufferBinding = new VertexBufferBinding(null, 0, 0); }
public PhysicsDebugDraw(DeviceManager manager) { device = manager.Direct3DDevice; inputAssembler = device.ImmediateContext.InputAssembler; lineArray = new PositionColored[0]; using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "VSMain", "vs_5_0")) { vertexShader = new VertexShader(device, bc); InputElement[] elements = new InputElement[] { new InputElement("SV_POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; inputLayout = new InputLayout(device, bc, elements); } vertexBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "PSMain", "ps_5_0")) pixelShader = new PixelShader(device, bc); }
protected override void InitializeInternal() { base.InitializeInternal(); var device = D3DApp11.I.D3DDevice; using (var r = CubeMapSRV.Resource) { r.DebugName = "sky cubemap"; } var sphere = GeometryGenerator.CreateSphere(_skySphereRadius, 30, 30); var vertices = sphere.Vertices.Select(v => v.Position).ToArray(); var vbd = new BufferDescription( VertPos.Stride * vertices.Length, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0 ); _vb = new Buffer(device, DataStream.Create(vertices, false, false), vbd); _indexCount = sphere.Indices.Count; var ibd = new BufferDescription( _indexCount * sizeof(int), ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0 ); _ib = new Buffer(device, DataStream.Create(sphere.Indices.ToArray(), false, false), ibd); }
public Buffer(BufferDescription description, BufferFlags flags) { _description = description; _flags = flags; _nativeBuffer = new SharpDX.Direct3D11.Buffer(GraphicManager.Device, description); }
/// <summary> /// Sets the vertices. /// </summary> /// <param name="vertices">The vertices.</param> /// <exception cref="System.ArgumentNullException">vertices</exception> /// <exception cref="ArgumentNullException">vertices</exception> public void SetVertices(DirectXVertex[] vertices) { if (vertices == null) { throw new ArgumentNullException("vertices"); } Vertices = vertices; if (VertexBuffer != null) { VertexBuffer.Dispose(); VertexBuffer = null; } D3D11.BufferDescription VertexBufferDesc = new D3D11.BufferDescription() { BindFlags = D3D11.BindFlags.VertexBuffer, Usage = D3D11.ResourceUsage.Default, CpuAccessFlags = D3D11.CpuAccessFlags.None, SizeInBytes = Utilities.SizeOf <DirectXVertex>() * Vertices.Length, }; try { VertexBuffer = D3D11.Buffer.Create <DirectXVertex>(Device, Vertices, VertexBufferDesc); VertexBufferBinding = new D3D11.VertexBufferBinding(VertexBuffer, Utilities.SizeOf <DirectXVertex>(), 0); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
public ProjectiveTexturingShader(Device device) { var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso")); vertexShader = new VertexShader(device, shaderByteCode); geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer states var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // constant buffer var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = Constants.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); // user view sampler state var colorSamplerStateDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f), BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f), }; colorSamplerState = new SamplerState(device, colorSamplerStateDesc); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
public LightShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "LightVertexShader", "vs_4_0", ShaderFlags); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "LightPixelShader", "ps_4_0", ShaderFlags); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); Layout = VertexDefinition.PositionTextureNormal.GetInputLayout(device, vertexShaderByteCode); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var lightBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<LightBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantLightBuffer = new Buffer(device, lightBufferDesc); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var cameraBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<CameraBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantCameraBuffer = new Buffer(device, cameraBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription { Filter = Filter.Anisotropic, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 16, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 10 }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); }
public D3D11Buffer(Device device, ulong sizeInBytes, BindFlags bindFlags) { SizeInBytes = sizeInBytes; SharpDX.Direct3D11.BufferDescription bd = new SharpDX.Direct3D11.BufferDescription( (int)sizeInBytes, bindFlags, ResourceUsage.Default); _buffer = new SharpDX.Direct3D11.Buffer(device, bd); }
public D3D11Buffer(Device device, uint sizeInBytes, BufferUsage usage, uint structureByteStride) { SizeInBytes = sizeInBytes; Usage = usage; SharpDX.Direct3D11.BufferDescription bd = new SharpDX.Direct3D11.BufferDescription( (int)sizeInBytes, D3D11Formats.ToD3D11BindFlags(usage), ResourceUsage.Default); if ((usage & BufferUsage.StructuredBufferReadOnly) == BufferUsage.StructuredBufferReadOnly || (usage & BufferUsage.StructuredBufferReadWrite) == BufferUsage.StructuredBufferReadWrite) { bd.OptionFlags = ResourceOptionFlags.BufferStructured; bd.StructureByteStride = (int)structureByteStride; } if ((usage & BufferUsage.IndirectBuffer) == BufferUsage.IndirectBuffer) { bd.OptionFlags = ResourceOptionFlags.DrawIndirectArguments; } if ((usage & BufferUsage.Dynamic) == BufferUsage.Dynamic) { bd.Usage = ResourceUsage.Dynamic; bd.CpuAccessFlags = CpuAccessFlags.Write; } else if ((usage & BufferUsage.Staging) == BufferUsage.Staging) { bd.Usage = ResourceUsage.Staging; bd.CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write; } _buffer = new SharpDX.Direct3D11.Buffer(device, bd); if ((usage & BufferUsage.StructuredBufferReadWrite) == BufferUsage.StructuredBufferReadWrite || (usage & BufferUsage.StructuredBufferReadOnly) == BufferUsage.StructuredBufferReadOnly) { ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription { Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Buffer }; srvDesc.Buffer.ElementCount = (int)(SizeInBytes / structureByteStride); ShaderResourceView = new ShaderResourceView(device, _buffer, srvDesc); } if ((usage & BufferUsage.StructuredBufferReadWrite) == BufferUsage.StructuredBufferReadWrite) { UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription { Dimension = UnorderedAccessViewDimension.Buffer }; uavDesc.Buffer.ElementCount = (int)(SizeInBytes / structureByteStride); uavDesc.Format = SharpDX.DXGI.Format.Unknown; UnorderedAccessView = new UnorderedAccessView(device, _buffer, uavDesc); } }
public void Flush() { if (_pendingVerticesCount == 0) { return; } if (_vertexBuffer == null) { var vertexBufferDesc = new d3d.BufferDescription() { SizeInBytes = MaximumQuadsCount * dx.Utilities.SizeOf <Vertex>(), Usage = d3d.ResourceUsage.Dynamic, BindFlags = d3d.BindFlags.VertexBuffer, CpuAccessFlags = d3d.CpuAccessFlags.Write, OptionFlags = 0, StructureByteStride = 0 }; _vertexBuffer = d3d.Buffer.Create(Device, _dataBuffer, vertexBufferDesc); Context.InputAssembler.SetVertexBuffers(0, new d3d.VertexBufferBinding(_vertexBuffer, dx.Utilities.SizeOf <Vertex>(), 0)); var indexBufferDesc = new d3d.BufferDescription() { SizeInBytes = MaximumQuadsCount * 6 * sizeof(ushort), Usage = d3d.ResourceUsage.Immutable, BindFlags = d3d.BindFlags.IndexBuffer, CpuAccessFlags = d3d.CpuAccessFlags.None, OptionFlags = 0, StructureByteStride = 0 }; uint[] indices = new uint[MaximumQuadsCount * 6]; for (uint i = 0, nx = 0x00000000; i < MaximumQuadsCount * 6; nx += 4) { indices[i++] = nx + 1; indices[i++] = nx + 0; indices[i++] = nx + 2; indices[i++] = nx + 1; indices[i++] = nx + 2; indices[i++] = nx + 3; } _indexBuffer = d3d.Buffer.Create(Device, indices, indexBufferDesc); Context.InputAssembler.SetIndexBuffer(_indexBuffer, dxgi.Format.R32_UInt, 0); } else { var size = _pendingVerticesCount * dx.Utilities.SizeOf <Vertex>(); var dataBox = Context.MapSubresource(_vertexBuffer, 0, d3d.MapMode.WriteDiscard, d3d.MapFlags.None); IntPtr addr = Marshal.UnsafeAddrOfPinnedArrayElement(_dataBuffer, 0); CopyMemory(dataBox.DataPointer, addr, (ulong)size); Context.UnmapSubresource(_vertexBuffer, 0); } Context.DrawIndexed(_pendingVerticesCount / 4 * 6, 0, 0); Context.Flush(); _pendingVerticesCount = 0; }
/// <summary> /// Constructor /// </summary> /// <param name="device">Device</param> /// <param name="size">Buffer size</param> public SharpOutputBuffer(SharpDevice device, int size) { Device = device; BufferDescription desc = new BufferDescription() { SizeInBytes = size, BindFlags = BindFlags.VertexBuffer | BindFlags.StreamOutput, Usage = ResourceUsage.Default, }; _buffer = new Buffer11(Device.Device, desc); }
public static D3D.Buffer CreateConstantBuffer(this D3D.Device device, int sizeInBytes) { var desc = new D3D.BufferDescription((int)System.Math.Ceiling(sizeInBytes / 16f) * 16, D3D.ResourceUsage.Default, D3D.BindFlags.ConstantBuffer, D3D.CpuAccessFlags.None, D3D.ResourceOptionFlags.None, 0); return(new D3D.Buffer(device, desc)); }
public static D3D.Buffer CreateDynamicBuffer(this D3D.Device device, int sizeInBytes, D3D.BindFlags bindFlags) { var desc = new D3D.BufferDescription((int)System.Math.Ceiling(sizeInBytes / 16f) * 16, D3D.ResourceUsage.Dynamic, bindFlags, D3D.CpuAccessFlags.Write, D3D.ResourceOptionFlags.None, 0); return(new D3D.Buffer(device, desc)); }
public MultiMeshContainer(Engine.Serialize.MeshesContainer MC) { if (MC != null) { //Transform = Matrix.Scaling(1); Hardpoints = MC.HardPoints; if (MC.Materials != null && MC.Geometry != null && MC.Geometry.Meshes != null) { BSP = MC.Geometry.BSP; LocalAABBMax = MC.Geometry.AABBMax; LocalAABBMin = MC.Geometry.AABBMin; Meshes = new Serialize.MeshLink[MC.Materials.Length]; Materials = new MaterialContainer[MC.Materials.Length]; for (int i = 0; i < MC.Materials.Length; i++) { Meshes[i] = MC.Geometry.Meshes[i]; Materials[i] = new MaterialContainer(MC.Materials[i]); } VertexsCount = MC.Geometry.VertexCount; BytesPerVertex = MC.Geometry.VertexData.Length / VertexsCount; FaceCount = MC.Geometry.IndexData.Length / 12; using (var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true)) { vertices.WriteRange<byte>(MC.Geometry.VertexData, 0, MC.Geometry.VertexData.Length); vertices.Position = 0; Vertexs = new Buffer(ModelViewer.Program.device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0); } using (var indices = new DataStream(4 * FaceCount * 3, true, true)) { indices.WriteRange<byte>(MC.Geometry.IndexData, 0, MC.Geometry.IndexData.Length); indices.Position = 0; Indices = new Buffer(ModelViewer.Program.device, indices, 4 * FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); } BufferDescription bd = new BufferDescription(); bd.SizeInBytes = Marshal.SizeOf(typeof(ShaderConstants)); bd.Usage = ResourceUsage.Dynamic; bd.BindFlags = BindFlags.ConstantBuffer; bd.CpuAccessFlags = CpuAccessFlags.Write; bd.OptionFlags = ResourceOptionFlags.None; bd.StructureByteStride = 0; constantsBuffer = new Buffer(ModelViewer.Program.device, bd); constants = new ShaderConstants(); } } }
private static void InitDevice() { m_particleBuffer = new MyRWStructuredBuffer(MyGPUEmitters.MAX_PARTICLES, PARTICLE_STRIDE, MyRWStructuredBuffer.UavType.Default, true, "MyGPUParticleRenderer::particleBuffer"); m_deadListBuffer = new MyRWStructuredBuffer(MyGPUEmitters.MAX_PARTICLES, sizeof(uint), MyRWStructuredBuffer.UavType.Append, false, "MyGPUParticleRenderer::deadListBuffer"); m_skippedParticleCountBuffer = new MyRWStructuredBuffer(1, sizeof(uint), MyRWStructuredBuffer.UavType.Counter, true, "MyGPUParticleRenderer::skippedParticleCountBuffer"); // Create a staging buffer that is used to read GPU atomic counter into that can then be mapped for reading // back to the CPU for debugging purposes m_debugCounterBuffers[0] = new MyReadStructuredBuffer(1, sizeof(uint), "MyGPUParticleRenderer::debugCounterBuffers[0]"); m_debugCounterBuffers[1] = new MyReadStructuredBuffer(1, sizeof(uint), "MyGPUParticleRenderer::debugCounterBuffers[1]"); var description = new SharpDX.Direct3D11.BufferDescription(4 * sizeof(uint), SharpDX.Direct3D11.ResourceUsage.Default, SharpDX.Direct3D11.BindFlags.ConstantBuffer, SharpDX.Direct3D11.CpuAccessFlags.None, SharpDX.Direct3D11.ResourceOptionFlags.None, sizeof(uint)); m_activeListConstantBuffer = MyHwBuffers.CreateConstantsBuffer(description, "MyGPUParticleRenderer::activeListConstantBuffer"); m_emitterConstantBuffer = MyHwBuffers.CreateConstantsBuffer(EMITTERCONSTANTBUFFER_SIZE, "MyGPUParticleRenderer::emitterConstantBuffer"); m_emitterStructuredBuffer = MyHwBuffers.CreateStructuredBuffer(MyGPUEmitters.MAX_LIVE_EMITTERS, EMITTERDATA_SIZE, true, null, "MyGPUParticleRenderer::emitterStructuredBuffer"); m_aliveIndexBuffer = new MyRWStructuredBuffer(MyGPUEmitters.MAX_PARTICLES, sizeof(float), MyRWStructuredBuffer.UavType.Counter, true, "MyGPUParticleRenderer::aliveIndexBuffer"); m_indirectDrawArgsBuffer = new MyIndirectArgsBuffer(5, sizeof(uint), "MyGPUParticleRenderer::indirectDrawArgsBuffer"); unsafe { uint[] indices = new uint[MyGPUEmitters.MAX_PARTICLES * 6]; for (uint i = 0, index = 0, vertex = 0; i < MyGPUEmitters.MAX_PARTICLES; i++) { indices[index + 0] = vertex + 0; indices[index + 1] = vertex + 1; indices[index + 2] = vertex + 2; indices[index + 3] = vertex + 2; indices[index + 4] = vertex + 1; indices[index + 5] = vertex + 3; vertex += 4; index += 6; } fixed(uint *ptr = indices) { m_ib = MyHwBuffers.CreateIndexBuffer(MyGPUEmitters.MAX_PARTICLES * 6, SharpDX.DXGI.Format.R32_UInt, SharpDX.Direct3D11.BindFlags.IndexBuffer, SharpDX.Direct3D11.ResourceUsage.Immutable, new IntPtr(ptr), "MyGPUParticleRenderer::indexBuffer"); } } //MyRender11.BlendAlphaPremult }
public model CreateMesh(Device device, aiMesh aiMesh, aiMaterialVector mMaterials, String directory) { var numFaces = (int)aiMesh.mNumFaces; var numVertices = (int)aiMesh.mNumVertices; var aiPositions = aiMesh.mVertices; var aiNormals = aiMesh.mNormals; var aiTextureCoordsAll = aiMesh.mTextureCoords; var aiTextureCoords = (aiTextureCoordsAll != null) ? aiTextureCoordsAll[0] : null; VertexPostitionTexture[] VertexPostitionTextures = new VertexPostitionTexture[aiMesh.mNumVertices]; for (int j = 0; j < aiMesh.mNumVertices; j++) { VertexPostitionTextures[j].position = new Vector3(aiMesh.mVertices[j].x, aiMesh.mVertices[j].y, aiMesh.mVertices[j].z); VertexPostitionTextures[j].textcoord = new Vector2(aiMesh.mTextureCoords[0][j].x, aiMesh.mTextureCoords[0][j].y); } ///being brute =P int SizeInBytes = Marshal.SizeOf(typeof(VertexPostitionTexture)); BufferDescription bd = new BufferDescription(SizeInBytes * (int)aiMesh.mNumVertices, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, SizeInBytes); var vertices = Buffer.Create<VertexPostitionTexture>(device, VertexPostitionTextures, bd); var aiFaces = aiMesh.mFaces; var dxIndices = new uint[numFaces * 3]; for (int i = 0; i < numFaces; ++i) { var aiFace = aiFaces[i]; var aiIndices = aiFace.mIndices; for (int j = 0; j < 3; ++j) { dxIndices[i * 3 + j] = (uint)aiIndices[j]; } } BufferDescription bi = new BufferDescription(sizeof(uint) * numFaces * 3, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, sizeof(uint)); var indices = Buffer.Create<uint>(device, dxIndices, bd); model modelteste = new model(); modelteste.indices = indices; modelteste.numberIndices = numFaces * 3; modelteste.vertex = vertices; modelteste.numberVertices = numVertices; aiString difuse = new aiString(); mMaterials[(int)aiMesh.mMaterialIndex].GetTextureDiffuse0(difuse); modelteste.difuseTextureName = difuse.Data; String fullPath = String.IsNullOrEmpty(directory) ? modelteste.difuseTextureName : Path.Combine(directory, modelteste.difuseTextureName); modelteste.ShaderResourceView = ShaderResourceView.FromFile(device, fullPath); return modelteste; }
/// <summary> /// Function to initialize the buffer data. /// </summary> /// <param name="initialData">The initial data used to populate the buffer.</param> private void Initialize <T>(GorgonNativeBuffer <T> initialData) where T : unmanaged { D3D11.CpuAccessFlags cpuFlags = GetCpuFlags(false, D3D11.BindFlags.IndexBuffer); Log.Print($"{Name} Index Buffer: Creating D3D11 buffer. Size: {SizeInBytes} bytes", LoggingLevel.Simple); GorgonVertexBuffer.ValidateBufferBindings(_info.Usage, 0); D3D11.BindFlags bindFlags = D3D11.BindFlags.IndexBuffer; if ((_info.Binding & VertexIndexBufferBinding.StreamOut) == VertexIndexBufferBinding.StreamOut) { bindFlags |= D3D11.BindFlags.StreamOutput; } if ((_info.Binding & VertexIndexBufferBinding.UnorderedAccess) == VertexIndexBufferBinding.UnorderedAccess) { bindFlags |= D3D11.BindFlags.UnorderedAccess; } var desc = new D3D11.BufferDescription { SizeInBytes = SizeInBytes, Usage = (D3D11.ResourceUsage)_info.Usage, BindFlags = bindFlags, OptionFlags = D3D11.ResourceOptionFlags.None, CpuAccessFlags = cpuFlags, StructureByteStride = 0 }; if ((initialData != null) && (initialData.Length > 0)) { unsafe { D3DResource = Native = new D3D11.Buffer(Graphics.D3DDevice, new IntPtr((void *)initialData), desc) { DebugName = Name }; } } else { D3DResource = Native = new D3D11.Buffer(Graphics.D3DDevice, desc) { DebugName = Name }; } }
/// <summary> /// Initializes a new instance of the <see cref="Buffer" /> class. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="description">The description.</param> /// <param name="bufferFlags">Type of the buffer.</param> /// <param name="viewFormat">The view format.</param> /// <param name="dataPointer">The data pointer.</param> protected Buffer(GraphicsDevice device, BufferDescription description, BufferFlags bufferFlags, PixelFormat viewFormat, IntPtr dataPointer) : base(device) { Description = description; nativeDescription = ConvertToNativeDescription(Description); BufferFlags = bufferFlags; ViewFormat = viewFormat; InitCountAndViewFormat(out this.elementCount, ref ViewFormat); NativeDeviceChild = new SharpDX.Direct3D11.Buffer(device.RootDevice.NativeDevice, dataPointer, nativeDescription); // Staging resource don't have any views if (nativeDescription.Usage != ResourceUsage.Staging) { this.InitializeViews(); } }
/// <summary> /// Initializes a new instance of the <see cref="Buffer" /> class. /// </summary> /// <param name="description">The description.</param> /// <param name="viewFlags">Type of the buffer.</param> /// <param name="viewFormat">The view format.</param> /// <param name="dataPointer">The data pointer.</param> protected Buffer InitializeFromImpl(BufferDescription description, BufferFlags viewFlags, PixelFormat viewFormat, IntPtr dataPointer) { bufferDescription = description; nativeDescription = ConvertToNativeDescription(Description); ViewFlags = viewFlags; InitCountAndViewFormat(out this.elementCount, ref viewFormat); ViewFormat = viewFormat; NativeDeviceChild = new SharpDX.Direct3D11.Buffer(GraphicsDevice.RootDevice.NativeDevice, dataPointer, nativeDescription); // Staging resource don't have any views if (nativeDescription.Usage != ResourceUsage.Staging) this.InitializeViews(); return this; }
private static BufferDescription NewDescription(int bufferSize, int elementSize, BufferFlags bufferFlags, ResourceUsage usage) { var desc = new BufferDescription() { SizeInBytes = bufferSize, StructureByteStride = elementSize, // We keep the element size in the structure byte stride, even if it is not a structured buffer CpuAccessFlags = GetCputAccessFlagsFromUsage(usage), BindFlags = BindFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = usage, }; if ((bufferFlags & BufferFlags.ConstantBuffer) != 0) desc.BindFlags |= BindFlags.ConstantBuffer; if ((bufferFlags & BufferFlags.IndexBuffer) != 0) desc.BindFlags |= BindFlags.IndexBuffer; if ((bufferFlags & BufferFlags.VertexBuffer) != 0) desc.BindFlags |= BindFlags.VertexBuffer; if ((bufferFlags & BufferFlags.RenderTarget) != 0) desc.BindFlags |= BindFlags.RenderTarget; if ((bufferFlags & BufferFlags.ShaderResource) != 0) desc.BindFlags |= BindFlags.ShaderResource; if ((bufferFlags & BufferFlags.UnorderedAccess) != 0) desc.BindFlags |= BindFlags.UnorderedAccess; if ((bufferFlags & BufferFlags.StreamOutput) != 0) desc.BindFlags |= BindFlags.StreamOutput; if ((bufferFlags & BufferFlags.StructuredBuffer) != 0) { desc.OptionFlags |= ResourceOptionFlags.BufferStructured; if (elementSize == 0) throw new ArgumentException("Element size cannot be set to 0 for structured buffer"); } if ((bufferFlags & BufferFlags.RawBuffer) == BufferFlags.RawBuffer) desc.OptionFlags |= ResourceOptionFlags.BufferAllowRawViews; if ((bufferFlags & BufferFlags.ArgumentBuffer) == BufferFlags.ArgumentBuffer) desc.OptionFlags |= ResourceOptionFlags.DrawIndirectArguments; return desc; }
public ColorShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(VertexShaderFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(PixelShaderFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); var inputElements = new InputElement[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = ColorShader.Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<MatrixBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); }
public Buffer createIndexBufferOnDevice(Device _device) { // need to make a statement to check if defined bufferDescription = new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = (int)dataStream.Length, Usage = ResourceUsage.Default, }; dataStream.Position = 0; Buffer indices = new Buffer(_device, dataStream, bufferDescription); dataStream.Close(); return indices; }
private void PlatformConstruct( GraphicsDevice graphicsDevice, uint sizeInBytes, uint elementSizeInBytes, BufferBindFlags flags, ResourceUsage usage, byte[] initialData) { var optionFlags = flags.HasFlag(BufferBindFlags.ShaderResource) ? D3D11.ResourceOptionFlags.BufferStructured : D3D11.ResourceOptionFlags.None; var cpuAccessFlags = usage == ResourceUsage.Dynamic ? D3D11.CpuAccessFlags.Write : D3D11.CpuAccessFlags.None; var d3d11Usage = usage == ResourceUsage.Dynamic ? D3D11.ResourceUsage.Dynamic : D3D11.ResourceUsage.Immutable; var description = new D3D11.BufferDescription { BindFlags = flags.ToBindFlags(), CpuAccessFlags = cpuAccessFlags, OptionFlags = optionFlags, SizeInBytes = (int)sizeInBytes, StructureByteStride = (int)elementSizeInBytes, Usage = d3d11Usage }; if (usage == ResourceUsage.Static) { using (var dataStream = DataStream.Create(initialData, true, false)) { DeviceBuffer = AddDisposable(new D3D11.Buffer( graphicsDevice.Device, dataStream, description)); } } else { DeviceBuffer = AddDisposable(new D3D11.Buffer( graphicsDevice.Device, description)); } }
public void ImmutableTestUShort() { BufferElementCount count = new BufferElementCount(1024); var desc = DescriptorUtils.ImmutableIndexBufferUShort(count); var expected = new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = count * sizeof(ushort), StructureByteStride = sizeof(ushort), Usage = ResourceUsage.Immutable }; Assert.AreEqual(desc, expected); }
public void Init(Form window) { m_Window = window; InitDevice(m_NumSamples); InitShaders(); m_TextureMgr = new SharpDXTextureMgr(this); m_TriMeshMgr = new SharpDXTriMeshMgr(this); var desc = new D3D11.BufferDescription(64, D3D11.ResourceUsage.Default, D3D11.BindFlags.ConstantBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); var o = Matrix4x4.Identity(); m_ShaderParams = D3D11.Buffer.Create(Device, ref o, desc); m_DeviceContext.VertexShader.SetConstantBuffer(0, m_ShaderParams); m_Quad = m_TriMeshMgr.CreateQuad(2.0f, 2.0f); }
public TestSprite(Device device, DVector3 Position) { this.Position = Position; MMesh = ContentManager.LoadMesh("Content/Models/BaseSprite.mesh"); EEEM = ContentManager.LoadEffect("Content/Shaders/BaseSprite"); TexCont = ContentManager.LoadTexture2D("Content/Textures/Particl"); // Подготовка константного буффера BufferDescription bd = new BufferDescription(); bd.SizeInBytes = Marshal.SizeOf(typeof(ShaderConstants)); bd.Usage = ResourceUsage.Dynamic; bd.BindFlags = BindFlags.ConstantBuffer; bd.CpuAccessFlags = CpuAccessFlags.Write; bd.OptionFlags = ResourceOptionFlags.None; bd.StructureByteStride = 0; constantsBuffer = new Buffer(device, bd); constants = new ShaderConstants(); }
public void SetVertexBuffer(Device device, Vector3[] vectors) { BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * vectors.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vectors); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); }
public GSSprite(Device device, DVector3 Position) { //float3 Position //12 //half2 Size //16 //half4 AABBTexCoord //24 //half4 AditiveColor //32 InputElement[] elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R16G16_Float, 12, 0), new InputElement("TEXCOORD", 1, Format.R16G16B16A16_Float, 16, 0), new InputElement("TEXCOORD", 2, Format.R16G16B16A16_Float, 24, 0), }; BytesPerVertex = 32; VertexsCount = 1; var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true); vertices.Write(Conversion.ToVector3(Position)); vertices.Write(new Half2(10, 10)); vertices.Write(new Half4(0, 0, 1, 1)); vertices.Write(new Half4(1, 0, 0, 1)); vertices.Position = 0; Vertexs = new Buffer(device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0); vertices.Dispose(); this.Position = Position; EEEM = ContentManager.LoadEffect("Content/Shaders/GSSprite", elements); TexCont = ContentManager.LoadTexture2D("Content/Textures/Particl"); // Подготовка константного буффера BufferDescription bd = new BufferDescription(); bd.SizeInBytes = Marshal.SizeOf(typeof(ShaderConstants)); bd.Usage = ResourceUsage.Dynamic; bd.BindFlags = BindFlags.ConstantBuffer; bd.CpuAccessFlags = CpuAccessFlags.Write; bd.OptionFlags = ResourceOptionFlags.None; bd.StructureByteStride = 0; constantsBuffer = new Buffer(device, bd); constants = new ShaderConstants(); }
public D3D11Buffer(Device device, uint sizeInBytes, BufferUsage usage, uint structureByteStride, bool rawBuffer) { _device = device; SizeInBytes = sizeInBytes; Usage = usage; _structureByteStride = structureByteStride; _rawBuffer = rawBuffer; SharpDX.Direct3D11.BufferDescription bd = new SharpDX.Direct3D11.BufferDescription( (int)sizeInBytes, D3D11Formats.VdToD3D11BindFlags(usage), ResourceUsage.Default); if ((usage & BufferUsage.StructuredBufferReadOnly) == BufferUsage.StructuredBufferReadOnly || (usage & BufferUsage.StructuredBufferReadWrite) == BufferUsage.StructuredBufferReadWrite) { if (rawBuffer) { bd.OptionFlags = ResourceOptionFlags.BufferAllowRawViews; } else { bd.OptionFlags = ResourceOptionFlags.BufferStructured; bd.StructureByteStride = (int)structureByteStride; } } if ((usage & BufferUsage.IndirectBuffer) == BufferUsage.IndirectBuffer) { bd.OptionFlags = ResourceOptionFlags.DrawIndirectArguments; } if ((usage & BufferUsage.Dynamic) == BufferUsage.Dynamic) { bd.Usage = ResourceUsage.Dynamic; bd.CpuAccessFlags = CpuAccessFlags.Write; } else if ((usage & BufferUsage.Staging) == BufferUsage.Staging) { bd.Usage = ResourceUsage.Staging; bd.CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write; } _buffer = new SharpDX.Direct3D11.Buffer(device, bd); }
private static void InitShaders() { ShaderBytecode vertexShaderByteCode = vertexShaderByteCode = ShaderBytecode.Compile(Properties.Res.vertexShader, "main", "vs_4_0", ShaderFlags.Debug); vertexShader = new VertexShader(device, vertexShaderByteCode); inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); ShaderBytecode pixelShaderByteCode = ShaderBytecode.Compile(Properties.Res.pixelShader, "main", "ps_4_0", ShaderFlags.Debug); pixelShader = new PixelShader(device, pixelShaderByteCode); ShaderBytecode pixelShaderByteCodeSel = ShaderBytecode.Compile(Properties.Res.pixelShaderSel, "main", "ps_4_0", ShaderFlags.Debug); pixelShaderSel = new PixelShader(device, pixelShaderByteCodeSel); context.VertexShader.Set(vertexShader); inputLayout = new InputLayout(device, inputSignature, inputElements); context.InputAssembler.InputLayout = inputLayout; SharpDX.Direct3D11.BufferDescription buffdesc = new SharpDX.Direct3D11.BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <ConstantBufferData>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, buffdesc); RasterizerStateDescription renderStateDesc = new RasterizerStateDescription { CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = 0, FillMode = FillMode.Wireframe, IsAntialiasedLineEnabled = false, IsDepthClipEnabled = true, IsFrontCounterClockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0 }; rasterState = new RasterizerState(device, renderStateDesc); context.Rasterizer.State = rasterState; }
/// <summary> /// Creates an instance of this object. /// </summary> /// <param name="device"></param> /// <param name="capacity"></param> public IndexBuffer ( GraphicsDevice device, int capacity ) { //Log.Message("Creation: Index Buffer"); this.device = device; this.capacity = capacity; BufferDescription desc = new BufferDescription(); desc.BindFlags = BindFlags.IndexBuffer; desc.CpuAccessFlags = CpuAccessFlags.Write; desc.OptionFlags = ResourceOptionFlags.None; desc.SizeInBytes = capacity * sizeof(int); desc.StructureByteStride = 0; desc.Usage = ResourceUsage.Dynamic; lock (device.DeviceContext) { indexBuffer = new D3D11.Buffer( device.Device, desc ); } }
private void BuildBallGeometryBuffers() { var mesh = GeometryGenerator.CreateSphere(10, 30, 30); var vertices = new List <VertexPN>(); foreach (var vertex in mesh.Vertices) { var pos = vertex.Position; vertices.Add(new VertexPN(pos, vertex.Normal, vertex.TexC)); } var vbd = new D3D11.BufferDescription(VertexPN.Stride * vertices.Count, D3D11.ResourceUsage.Immutable, D3D11.BindFlags.VertexBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); _ballVB = new D3D11.Buffer(Device, DataStream.Create <VertexPN>(vertices.ToArray(), false, false), vbd); var ibd = new D3D11.BufferDescription(sizeof(int) * mesh.Indices.Count, D3D11.ResourceUsage.Immutable, D3D11.BindFlags.IndexBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); _ballIB = new D3D11.Buffer(Device, DataStream.Create <Int32>(mesh.Indices.ToArray(), false, false), ibd); _ballIndexCount = mesh.Indices.Count; }
public PhysicsDebugDraw(SharpDX11Graphics graphics) { _device = graphics.Device; _inputAssembler = _device.ImmediateContext.InputAssembler; InputElement[] elements = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, graphics.GetDebugDrawPass().Description.Signature, elements); _vertexBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; _vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); }
/// <summary> /// Creates a new mesh. /// </summary> /// <param name="device">The device to use.</param> /// <param name="name">The name of the mesh.</param> /// <param name="geometry">The list of vertices in the mesh.</param> public Mesh(Device device, String name, List<Vertex> geometry) { using (DataStream vertexStream = new DataStream(Vertex.Size * geometry.Count, false, true)) { foreach (Vertex vertex in geometry) vertex.WriteTo(vertexStream); vertexStream.Position = 0; BufferDescription description = new BufferDescription() { Usage = ResourceUsage.Immutable, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, SizeInBytes = Vertex.Size * geometry.Count, }; vertices = new Buffer(device, vertexStream, description); vertexBuffer = new VertexBufferBinding(vertices, Vertex.Size, 0); } MeshName = name; }
/// <summary> /// Function used to initalize the buffer. /// </summary> /// <param name="initialData">The data to copy into the buffer on creation.</param> private void Initialize(GorgonNativeBuffer <byte> initialData) { if (_info.SizeInBytes < 1) { throw new ArgumentException(string.Format(Resources.GORGFX_ERR_BUFFER_SIZE_TOO_SMALL, 1)); } if ((_info.Usage == ResourceUsage.Immutable) && (initialData == null)) { throw new GorgonException(GorgonResult.CannotCreate, Resources.GORGFX_ERR_BUFFER_IMMUTABLE_REQUIRES_DATA); } D3D11.BufferDescription desc = BuildBufferDesc(_info); // Implicitly allow reading for staging resources. if (_info.Usage == ResourceUsage.Staging) { _info.AllowCpuRead = true; } Log.Print($"{Name} Generic Buffer: Creating D3D11 buffer. Size: {SizeInBytes} bytes", LoggingLevel.Simple); if ((initialData != null) && (initialData.Length > 0)) { unsafe { D3DResource = Native = new D3D11.Buffer(Graphics.D3DDevice, new IntPtr((byte *)initialData), desc) { DebugName = $"{Name}_ID3D11Buffer" }; } } else { D3DResource = Native = new D3D11.Buffer(Graphics.D3DDevice, desc) { DebugName = $"{Name}_ID3D11Buffer" }; } }
public Text(Device device, FontShader shader, int screenWidth, int screenHeight, Font font, Int32 maxLength, Vector4 color) { Font = font; MaxLength = maxLength; Color = color; _shader = shader; _screenHeight = screenHeight; _screenWidth = screenWidth; // The index buffer is static and do not change when the text changes UInt32[] indices = new UInt32[maxLength * 6]; // 6 indices per character for (UInt32 i = 0; i < maxLength; i++) { indices[i * 6] = i * 4; indices[i * 6 + 1] = i * 4 + 1; indices[i * 6 + 2] = i * 4 + 2; indices[i * 6 + 3] = i * 4; indices[i * 6 + 4] = i * 4 + 3; indices[i * 6 + 5] = i * 4 + 1; } IndexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, indices); // The vertex buffer is initialized empty _vertices = new FontShader.Vertex[maxLength * 4]; // 4 vertices per character var vertexBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<FontShader.Vertex>() * maxLength * 4, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the vertex buffer. VertexBuffer = Buffer.Create(device, _vertices, vertexBufferDesc); }
public SimpleText(IContext context, Font font, int maxLength, Color color) { Device device = context.DirectX.Device; Font = font; MaxLength = maxLength; Color = color; _shader = context.Shaders.Get<FontShader>(); _icons = new List<TexturedRectangle>(); // The index buffer is static and do not change when the text changes uint[] indices = new uint[maxLength * 6]; // 6 indices per character for (uint i = 0; i < maxLength; i++) { indices[i * 6] = i * 4; indices[i * 6 + 1] = i * 4 + 1; indices[i * 6 + 2] = i * 4 + 2; indices[i * 6 + 3] = i * 4; indices[i * 6 + 4] = i * 4 + 3; indices[i * 6 + 5] = i * 4 + 1; } _indexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, indices); // The vertex buffer is initialized empty _vertices = new VertexDefinition.PositionTextureColor[maxLength * 4]; // 4 vertices per character var vertexBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<VertexDefinition.PositionTextureColor>() * maxLength * 4, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the vertex buffer. _vertexBuffer = Buffer.Create(device, _vertices, vertexBufferDesc); }
/// <summary> /// Initializes a new instance of the <see cref="Buffer" /> class. /// </summary> /// <param name="description">The description.</param> /// <param name="viewFlags">Type of the buffer.</param> /// <param name="viewFormat">The view format.</param> /// <param name="dataPointer">The data pointer.</param> protected Buffer InitializeFromImpl(BufferDescription description, BufferFlags viewFlags, PixelFormat viewFormat, IntPtr dataPointer) { bufferDescription = description; nativeDescription = ConvertToNativeDescription(Description); ViewFlags = viewFlags; InitCountAndViewFormat(out this.elementCount, ref viewFormat); ViewFormat = viewFormat; NativeDeviceChild = new SharpDX.Direct3D11.Buffer(GraphicsDevice.NativeDevice, dataPointer, nativeDescription); // Staging resource don't have any views if (nativeDescription.Usage != ResourceUsage.Staging) { this.InitializeViews(); } if (GraphicsDevice != null) { GraphicsDevice.RegisterBufferMemoryUsage(SizeInBytes); } return(this); }
/// <summary> /// Function to initialize the buffer data. /// </summary> /// <param name="initialData">The initial data used to populate the buffer.</param> private void Initialize(GorgonNativeBuffer <byte> initialData) { // If the buffer is not aligned to 16 bytes, then pad the size. _info.SizeInBytes = (_info.SizeInBytes + 15) & ~15; TotalConstantCount = _info.SizeInBytes / (sizeof(float) * 4); D3D11.CpuAccessFlags cpuFlags = GetCpuFlags(false, D3D11.BindFlags.ConstantBuffer); Log.Print($"{Name} Constant Buffer: Creating D3D11 buffer. Size: {_info.SizeInBytes} bytes", LoggingLevel.Simple); var desc = new D3D11.BufferDescription { SizeInBytes = _info.SizeInBytes, Usage = (D3D11.ResourceUsage)_info.Usage, BindFlags = D3D11.BindFlags.ConstantBuffer, OptionFlags = D3D11.ResourceOptionFlags.None, CpuAccessFlags = cpuFlags, StructureByteStride = 0 }; if ((initialData != null) && (initialData.Length > 0)) { unsafe { D3DResource = Native = new D3D11.Buffer(Graphics.D3DDevice, new IntPtr((void *)initialData), desc) { DebugName = Name }; } } else { D3DResource = Native = new D3D11.Buffer(Graphics.D3DDevice, desc) { DebugName = Name }; } }
private void BuildLandGeometryBuffers() { GeometryGenerator.MeshData grid = GeometryGenerator.CreateGrid(160.0f, 160.0f, 50, 50); var vertices = new List <VertexPN>(); foreach (var vertex in grid.Vertices) { var pos = vertex.Position; pos.Y = GetHillHeight(pos.X, pos.Z); var normal = GetHillNormal(pos.X, pos.Z); vertices.Add(new VertexPN(pos, normal, vertex.TexC)); } var vbd = new D3D11.BufferDescription(VertexPN.Stride * vertices.Count, D3D11.ResourceUsage.Immutable, D3D11.BindFlags.VertexBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); _groundVB = new D3D11.Buffer(Device, DataStream.Create <VertexPN>(vertices.ToArray(), false, false), vbd); var ibd = new D3D11.BufferDescription(sizeof(int) * grid.Indices.Count, D3D11.ResourceUsage.Immutable, D3D11.BindFlags.IndexBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); _groundIB = new D3D11.Buffer(Device, DataStream.Create <Int32>(grid.Indices.ToArray(), false, false), ibd); _groundIndexCount = grid.Indices.Count; }
private void BuildBuffers() { D3D11.BufferDescription buf_desc = new D3D11.BufferDescription(); buf_desc.BindFlags = D3D11.BindFlags.ShaderResource | D3D11.BindFlags.UnorderedAccess; buf_desc.Usage = D3D11.ResourceUsage.Default; buf_desc.StructureByteStride = WaveSolution.Stride; buf_desc.SizeInBytes = WaveSolution.Stride * VertexCount; buf_desc.OptionFlags = D3D11.ResourceOptionFlags.BufferStructured; buf_desc.CpuAccessFlags = D3D11.CpuAccessFlags.Write | D3D11.CpuAccessFlags.Read; _inputBuf1 = new D3D11.Buffer(Device, buf_desc); _inputBuf2 = new D3D11.Buffer(Device, buf_desc); D3D11.ShaderResourceViewDescription vdesc = new D3D11.ShaderResourceViewDescription(); vdesc.Dimension = D3D.ShaderResourceViewDimension.Buffer; vdesc.Format = DXGI.Format.Unknown; vdesc.Buffer.FirstElement = 0; vdesc.Buffer.ElementCount = VertexCount; _inputBuf1View = new D3D11.ShaderResourceView(Device, _inputBuf1, vdesc); _inputBuf2View = new D3D11.ShaderResourceView(Device, _inputBuf2, vdesc); D3D11.UnorderedAccessViewDescription uavdesc = new D3D11.UnorderedAccessViewDescription(); uavdesc.Format = DXGI.Format.Unknown; uavdesc.Dimension = D3D11.UnorderedAccessViewDimension.Buffer; uavdesc.Buffer.FirstElement = 0; uavdesc.Buffer.ElementCount = VertexCount; _inputBuf1UAV = new D3D11.UnorderedAccessView(Device, _inputBuf1, uavdesc); _inputBuf2UAV = new D3D11.UnorderedAccessView(Device, _inputBuf2, uavdesc); return; }
/*------------------------------------- * NON-PUBLIC METHODS *-----------------------------------*/ private D3D11.Buffer CreateConstantBuffer(Type type) { int size = Marshal.SizeOf(type); if ((size % 16) != 0) { size += 16 - (size % 16); } var bufferDescription = new D3D11.BufferDescription() { BindFlags = D3D11.BindFlags.ConstantBuffer, CpuAccessFlags = D3D11.CpuAccessFlags.Write, SizeInBytes = size, Usage = D3D11.ResourceUsage.Dynamic, }; var data = new byte[size]; var buffer = D3D11.Buffer.Create(Graphics.Device, ref data[0], bufferDescription); return(buffer); }
private static SharpDX.Direct3D11.BufferDescription ConvertToNativeDescription(BufferDescription bufferDescription) { var desc = new SharpDX.Direct3D11.BufferDescription() { SizeInBytes = bufferDescription.SizeInBytes, StructureByteStride = bufferDescription.StructureByteStride, CpuAccessFlags = GetCpuAccessFlagsFromUsage(bufferDescription.Usage), BindFlags = BindFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = (SharpDX.Direct3D11.ResourceUsage)bufferDescription.Usage, }; var bufferFlags = bufferDescription.BufferFlags; if ((bufferFlags & BufferFlags.ConstantBuffer) != 0) { desc.BindFlags |= BindFlags.ConstantBuffer; } if ((bufferFlags & BufferFlags.IndexBuffer) != 0) { desc.BindFlags |= BindFlags.IndexBuffer; } if ((bufferFlags & BufferFlags.VertexBuffer) != 0) { desc.BindFlags |= BindFlags.VertexBuffer; } if ((bufferFlags & BufferFlags.RenderTarget) != 0) { desc.BindFlags |= BindFlags.RenderTarget; } if ((bufferFlags & BufferFlags.ShaderResource) != 0) { desc.BindFlags |= BindFlags.ShaderResource; } if ((bufferFlags & BufferFlags.UnorderedAccess) != 0) { desc.BindFlags |= BindFlags.UnorderedAccess; } if ((bufferFlags & BufferFlags.StructuredBuffer) != 0) { desc.OptionFlags |= ResourceOptionFlags.BufferStructured; if (bufferDescription.StructureByteStride <= 0) { throw new ArgumentException("Element size cannot be less or equal 0 for structured buffer"); } } if ((bufferFlags & BufferFlags.RawBuffer) == BufferFlags.RawBuffer) { desc.OptionFlags |= ResourceOptionFlags.BufferAllowRawViews; } if ((bufferFlags & BufferFlags.ArgumentBuffer) == BufferFlags.ArgumentBuffer) { desc.OptionFlags |= ResourceOptionFlags.DrawIndirectArguments; } if ((bufferFlags & BufferFlags.StreamOutput) != 0) { desc.BindFlags |= BindFlags.StreamOutput; } return(desc); }
internal static StructuredBufferId CreateStructuredBuffer(BufferDescription description, IntPtr? data = null, string debugName = null) { var id = new StructuredBufferId { Index = SBuffers.Allocate() }; MyArrayHelpers.Reserve(ref SBuffersData, id.Index + 1); SBuffers.Data[id.Index] = new MyHwBufferDesc { Description = description, DebugName = debugName }; SBuffersData[id.Index] = new MyStructuredBufferData { }; SbIndices.Add(id); if (!data.HasValue) { InitStructuredBuffer(id); } else { InitStructuredBuffer(id, data.Value); } return id; }
public bool Initialize() { Debug.Assert(!_initialized); #region Shaders string SpriteFX = @"Texture2D SpriteTex; SamplerState samLinear { Filter = MIN_MAG_MIP_LINEAR; AddressU = WRAP; AddressV = WRAP; }; struct VertexIn { float3 PosNdc : POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; struct VertexOut { float4 PosNdc : SV_POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; VertexOut VS(VertexIn vin) { VertexOut vout; vout.PosNdc = float4(vin.PosNdc, 1.0f); vout.Tex = vin.Tex; vout.Color = vin.Color; return vout; }; float4 PS(VertexOut pin) : SV_Target { return pin.Color*SpriteTex.Sample(samLinear, pin.Tex); }; technique11 SpriteTech { pass P0 { SetVertexShader( CompileShader( vs_5_0, VS() ) ); SetHullShader( NULL ); SetDomainShader( NULL ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_5_0, PS() ) ); } };"; #endregion _compiledFX = ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0"); { if (_compiledFX.HasErrors) return false; _effect = new Effect(_device, _compiledFX); { _spriteTech = _effect.GetTechniqueByName("SpriteTech"); _spriteMap = _effect.GetVariableByName("SpriteTex").AsShaderResource(); var pass = _spriteTech.GetPassByIndex(0).Description.Signature; InputElement[] layoutDesc = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, pass, layoutDesc); // Create Vertex Buffer BufferDescription vbd = new BufferDescription { SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _VB = new SharpDX.Direct3D11.Buffer(_device, vbd); // Create and initialise Index Buffer short[] indices = new short[3072]; for (ushort i = 0; i < 512; ++i) { indices[i * 6] = (short)(i * 4); indices[i * 6 + 1] = (short)(i * 4 + 1); indices[i * 6 + 2] = (short)(i * 4 + 2); indices[i * 6 + 3] = (short)(i * 4); indices[i * 6 + 4] = (short)(i * 4 + 2); indices[i * 6 + 5] = (short)(i * 4 + 3); } _indexBuffer = Marshal.AllocHGlobal(indices.Length * Marshal.SizeOf(indices[0])); Marshal.Copy(indices, 0, _indexBuffer, indices.Length); BufferDescription ibd = new BufferDescription { SizeInBytes = 3072 * Marshal.SizeOf(typeof(short)), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _IB = new SharpDX.Direct3D11.Buffer(_device, _indexBuffer, ibd); BlendStateDescription transparentDesc = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; transparentDesc.RenderTarget[0].IsBlendEnabled = true; transparentDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transparentDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transparentDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transparentDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transparentDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBS = new BlendState(_device, transparentDesc); } } _initialized = true; return true; }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<Matrix>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); return true; } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return false; }; }
/// <summary> /// Function to create the resources for the buffer. /// </summary> /// <param name="data">The initial data for the buffer.</param> private void CreateResources(GorgonDataStream data) { var desc = new D3D.BufferDescription { BindFlags = D3D.BindFlags.None, CpuAccessFlags = D3DCPUAccessFlags, OptionFlags = D3D.ResourceOptionFlags.None, SizeInBytes = Settings.SizeInBytes, StructureByteStride = Settings.StructureSize, Usage = D3DUsage }; // If this is a render target buffer, then ensure that we have a default resource. if ((IsRenderTarget) && (Settings.Usage != BufferUsage.Default)) { throw new GorgonException(GorgonResult.CannotCreate, Resources.GORGFX_RENDERTARGET_NEED_DEFAULT); } // Set up the buffer. If we're a staging buffer, then none of this stuff will // work because staging buffers can't be bound to the pipeline, so just skip it. if (Settings.Usage != BufferUsage.Staging) { switch (BufferType) { case BufferType.Constant: desc.BindFlags = D3D.BindFlags.ConstantBuffer; break; case BufferType.Index: desc.BindFlags = D3D.BindFlags.IndexBuffer; break; case BufferType.Vertex: desc.BindFlags = D3D.BindFlags.VertexBuffer; break; case BufferType.Structured: if (!IsRenderTarget) { desc.OptionFlags = D3D.ResourceOptionFlags.BufferStructured; } break; } // Update binding modifiers. if (Settings.AllowShaderViews) { desc.BindFlags |= D3D.BindFlags.ShaderResource; } if (Settings.AllowUnorderedAccessViews) { desc.BindFlags |= D3D.BindFlags.UnorderedAccess; } if (!IsRenderTarget) { if (Settings.AllowIndirectArguments) { desc.OptionFlags = D3D.ResourceOptionFlags.DrawIndirectArguments; } } else { desc.BindFlags |= D3D.BindFlags.RenderTarget; } if (Settings.IsOutput) { desc.BindFlags |= D3D.BindFlags.StreamOutput; } if (Settings.AllowRawViews) { desc.OptionFlags = D3D.ResourceOptionFlags.BufferAllowRawViews; } } // Create and initialize the buffer. if (data != null) { long position = data.Position; using (var dxStream = new DX.DataStream(data.BasePointer, data.Length - position, true, true)) { D3DResource = D3DBuffer = new D3D.Buffer(Graphics.D3DDevice, dxStream, desc); } } else { D3DResource = D3DBuffer = new D3D.Buffer(Graphics.D3DDevice, desc); } }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<MatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 0 }; // Create the texture sampler state. SampleState = new SamplerState(device, samplerDesc); return true; } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return false; }; }
internal Engine_Material(string _shaderFileName, string _imageFileName, bool _includeGeometryShader = false) { #region //Get Instances m_d3d = Engine_Renderer.Instance; #endregion #region //Create InputLayout var inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0, 0), new D3D11.InputElement("TEXCOORD", 0, DXGI.Format.R32G32_Float, D3D11.InputElement.AppendAligned, 0), new D3D11.InputElement("NORMAL", 0, DXGI.Format.R32G32B32_Float, D3D11.InputElement.AppendAligned, 0) }; #endregion #region //Create VertexShader CompilationResult vsResult; using (vsResult = ShaderBytecode.CompileFromFile(_shaderFileName, "VS", "vs_4_0", ShaderFlags.None)) { m_vertexShader = new D3D11.VertexShader(m_d3d.m_device, vsResult.Bytecode.Data); m_inputLayout = new D3D11.InputLayout(m_d3d.m_device, vsResult.Bytecode, inputElements); } #endregion #region //Create PixelShader using (var psResult = ShaderBytecode.CompileFromFile(_shaderFileName, "PS", "ps_4_0", ShaderFlags.None)) m_pixelShader = new D3D11.PixelShader(m_d3d.m_device, psResult.Bytecode.Data); #endregion #region //Create GeometryShader if (_includeGeometryShader) { using (var psResult = ShaderBytecode.CompileFromFile(_shaderFileName, "GS", "gs_4_0", ShaderFlags.None)) m_geometryShader = new D3D11.GeometryShader(m_d3d.m_device, psResult.Bytecode.Data); } #endregion #region //Create ConstantBuffers for Model SPerModelConstantBuffer cbModel = new SPerModelConstantBuffer(); D3D11.BufferDescription bufferDescription = new D3D11.BufferDescription { BindFlags = D3D11.BindFlags.ConstantBuffer, CpuAccessFlags = D3D11.CpuAccessFlags.Write, Usage = D3D11.ResourceUsage.Dynamic, }; m_model = D3D11.Buffer.Create(m_d3d.m_device, D3D11.BindFlags.ConstantBuffer, ref cbModel); #endregion #region //Create Texture and Sampler var texture = Engine_ImgLoader.CreateTexture2DFromBitmap(m_d3d.m_device, Engine_ImgLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), _imageFileName)); m_resourceView = new D3D11.ShaderResourceView(m_d3d.m_device, texture); D3D11.SamplerStateDescription samplerStateDescription = new D3D11.SamplerStateDescription { Filter = D3D11.Filter.Anisotropic, AddressU = D3D11.TextureAddressMode.Clamp, AddressV = D3D11.TextureAddressMode.Clamp, AddressW = D3D11.TextureAddressMode.Clamp, ComparisonFunction = D3D11.Comparison.Always, MaximumAnisotropy = 16, MinimumLod = 0, MaximumLod = float.MaxValue, }; m_sampler = new D3D11.SamplerState(m_d3d.m_device, samplerStateDescription); #endregion }