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); }
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)); }
/// <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); }
/// <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, 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 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); }
/// <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); }